/*
 @license
 Shaka Player
 Copyright 2016 Google LLC
 SPDX-License-Identifier: Apache-2.0
*/
(function(){var innerGlobal=typeof window!="undefined"?window:global;var exportTo={};(function(window,global,module){/*

 Copyright The Closure Library Authors.
 SPDX-License-Identifier: Apache-2.0
*/
var COMPILED=!0,goog=goog||{};goog.global=this||self;goog.exportPath_=function(a,b,c,d){a=a.split(".");d=d||goog.global;a[0]in d||typeof d.execScript=="undefined"||d.execScript("var "+a[0]);for(var e;a.length&&(e=a.shift());)if(a.length||b===void 0)d=d[e]&&d[e]!==Object.prototype[e]?d[e]:d[e]={};else if(!c&&goog.isObject(b)&&goog.isObject(d[e]))for(var f in b)b.hasOwnProperty(f)&&(d[e][f]=b[f]);else d[e]=b};
goog.define=function(a,b){if(!COMPILED){var c=goog.global.CLOSURE_UNCOMPILED_DEFINES,d=goog.global.CLOSURE_DEFINES;c&&c.nodeType===void 0&&Object.prototype.hasOwnProperty.call(c,a)?b=c[a]:d&&d.nodeType===void 0&&Object.prototype.hasOwnProperty.call(d,a)&&(b=d[a])}return b};goog.FEATURESET_YEAR=2012;goog.DEBUG=!0;goog.LOCALE="en";goog.TRUSTED_SITE=!0;goog.DISALLOW_TEST_ONLY_CODE=COMPILED&&!goog.DEBUG;goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING=!1;
goog.provide=function(a){if(goog.isInModuleLoader_())throw Error("goog.provide cannot be used within a module.");if(!COMPILED&&goog.isProvided_(a))throw Error('Namespace "'+a+'" already declared.');goog.constructNamespace_(a)};goog.constructNamespace_=function(a,b,c){if(!COMPILED){delete goog.implicitNamespaces_[a];for(var d=a;(d=d.substring(0,d.lastIndexOf(".")))&&!goog.getObjectByName(d);)goog.implicitNamespaces_[d]=!0}goog.exportPath_(a,b,c)};goog.NONCE_PATTERN_=/^[\w+/_-]+[=]{0,2}$/;
goog.getScriptNonce_=function(a){a=(a||goog.global).document;return(a=a.querySelector&&a.querySelector("script[nonce]"))&&(a=a.nonce||a.getAttribute("nonce"))&&goog.NONCE_PATTERN_.test(a)?a:""};goog.VALID_MODULE_RE_=/^[a-zA-Z_$][a-zA-Z0-9._$]*$/;
goog.module=function(a){if(typeof a!=="string"||!a||a.search(goog.VALID_MODULE_RE_)==-1)throw Error("Invalid module identifier");if(!goog.isInGoogModuleLoader_())throw Error("Module "+a+" has been loaded incorrectly. Note, modules cannot be loaded as normal scripts. They require some kind of pre-processing step. You're likely trying to load a module via a script tag or as a part of a concatenated bundle without rewriting the module. For more info see: https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.");if(goog.moduleLoaderState_.moduleName)throw Error("goog.module may only be called once per module.");
goog.moduleLoaderState_.moduleName=a;if(!COMPILED){if(goog.isProvided_(a))throw Error('Namespace "'+a+'" already declared.');delete goog.implicitNamespaces_[a]}};goog.module.get=function(a){return goog.module.getInternal_(a)};goog.module.getInternal_=function(a){if(!COMPILED){if(a in goog.loadedModules_)return goog.loadedModules_[a].exports;if(!goog.implicitNamespaces_[a])return a=goog.getObjectByName(a),a!=null?a:null}return null};goog.ModuleType={ES6:"es6",GOOG:"goog"};goog.moduleLoaderState_=null;
goog.isInModuleLoader_=function(){return goog.isInGoogModuleLoader_()||goog.isInEs6ModuleLoader_()};goog.isInGoogModuleLoader_=function(){return!!goog.moduleLoaderState_&&goog.moduleLoaderState_.type==goog.ModuleType.GOOG};goog.isInEs6ModuleLoader_=function(){if(goog.moduleLoaderState_&&goog.moduleLoaderState_.type==goog.ModuleType.ES6)return!0;var a=goog.global.$jscomp;return a?typeof a.getCurrentModulePath!="function"?!1:!!a.getCurrentModulePath():!1};
goog.module.declareLegacyNamespace=function(){if(!COMPILED&&!goog.isInGoogModuleLoader_())throw Error("goog.module.declareLegacyNamespace must be called from within a goog.module");if(!COMPILED&&!goog.moduleLoaderState_.moduleName)throw Error("goog.module must be called prior to goog.module.declareLegacyNamespace.");goog.moduleLoaderState_.declareLegacyNamespace=!0};
goog.declareModuleId=function(a){if(!COMPILED){if(!goog.isInEs6ModuleLoader_())throw Error("goog.declareModuleId may only be called from within an ES6 module");if(goog.moduleLoaderState_&&goog.moduleLoaderState_.moduleName)throw Error("goog.declareModuleId may only be called once per module.");if(a in goog.loadedModules_)throw Error('Module with namespace "'+a+'" already exists.');}if(goog.moduleLoaderState_)goog.moduleLoaderState_.moduleName=a;else{var b=goog.global.$jscomp;if(!b||typeof b.getCurrentModulePath!=
"function")throw Error('Module with namespace "'+a+'" has been loaded incorrectly.');b=b.require(b.getCurrentModulePath());goog.loadedModules_[a]={exports:b,type:goog.ModuleType.ES6,moduleId:a}}};goog.setTestOnly=function(a){if(goog.DISALLOW_TEST_ONLY_CODE)throw a=a||"",Error("Importing test-only code into non-debug environment"+(a?": "+a:"."));};goog.forwardDeclare=function(a){};
COMPILED||(goog.isProvided_=function(a){return a in goog.loadedModules_||!goog.implicitNamespaces_[a]&&goog.getObjectByName(a)!=null},goog.implicitNamespaces_={"goog.module":!0});goog.getObjectByName=function(a,b){a=a.split(".");b=b||goog.global;for(var c=0;c<a.length;c++)if(b=b[a[c]],b==null)return null;return b};goog.addDependency=function(a,b,c,d){!COMPILED&&goog.DEPENDENCIES_ENABLED&&goog.debugLoader_.addDependency(a,b,c,d)};goog.ENABLE_DEBUG_LOADER=!1;
goog.logToConsole_=function(a){goog.global.console&&goog.global.console.error(a)};goog.require=function(a){if(!COMPILED){goog.ENABLE_DEBUG_LOADER&&goog.debugLoader_.requested(a);if(goog.isProvided_(a)){if(goog.isInModuleLoader_())return goog.module.getInternal_(a)}else if(goog.ENABLE_DEBUG_LOADER){var b=goog.moduleLoaderState_;goog.moduleLoaderState_=null;try{goog.debugLoader_.load_(a)}finally{goog.moduleLoaderState_=b}}return null}};goog.requireType=function(a){return{}};goog.basePath="";
goog.abstractMethod=function(){throw Error("unimplemented abstract method");};goog.addSingletonGetter=function(a){a.instance_=void 0;a.getInstance=function(){if(a.instance_)return a.instance_;goog.DEBUG&&(goog.instantiatedSingletons_[goog.instantiatedSingletons_.length]=a);return a.instance_=new a}};goog.instantiatedSingletons_=[];goog.LOAD_MODULE_USING_EVAL=!0;goog.SEAL_MODULE_EXPORTS=goog.DEBUG;goog.loadedModules_={};goog.DEPENDENCIES_ENABLED=!COMPILED&&goog.ENABLE_DEBUG_LOADER;goog.TRANSPILE="detect";
goog.ASSUME_ES_MODULES_TRANSPILED=!1;goog.TRUSTED_TYPES_POLICY_NAME="goog";goog.hasBadLetScoping=null;
goog.loadModule=function(a){var b=goog.moduleLoaderState_;try{goog.moduleLoaderState_={moduleName:"",declareLegacyNamespace:!1,type:goog.ModuleType.GOOG};var c={},d=c;if(typeof a==="function")d=a.call(void 0,d);else if(typeof a==="string")d=goog.loadModuleFromSource_.call(void 0,d,a);else throw Error("Invalid module definition");var e=goog.moduleLoaderState_.moduleName;if(typeof e==="string"&&e)goog.moduleLoaderState_.declareLegacyNamespace?goog.constructNamespace_(e,d,c!==d):goog.SEAL_MODULE_EXPORTS&&
Object.seal&&typeof d=="object"&&d!=null&&Object.seal(d),goog.loadedModules_[e]={exports:d,type:goog.ModuleType.GOOG,moduleId:goog.moduleLoaderState_.moduleName};else throw Error('Invalid module name "'+e+'"');}finally{goog.moduleLoaderState_=b}};goog.loadModuleFromSource_=function(a){eval(goog.CLOSURE_EVAL_PREFILTER_.createScript(arguments[1]));return a};
goog.normalizePath_=function(a){a=a.split("/");for(var b=0;b<a.length;)a[b]=="."?a.splice(b,1):b&&a[b]==".."&&a[b-1]&&a[b-1]!=".."?a.splice(--b,2):b++;return a.join("/")};goog.loadFileSync_=function(a){if(goog.global.CLOSURE_LOAD_FILE_SYNC)return goog.global.CLOSURE_LOAD_FILE_SYNC(a);try{var b=new goog.global.XMLHttpRequest;b.open("get",a,!1);b.send();return b.status==0||b.status==200?b.responseText:null}catch(c){return null}};
goog.typeOf=function(a){var b=typeof a;return b!="object"?b:a?Array.isArray(a)?"array":b:"null"};goog.isArrayLike=function(a){var b=goog.typeOf(a);return b=="array"||b=="object"&&typeof a.length=="number"};goog.isDateLike=function(a){return goog.isObject(a)&&typeof a.getFullYear=="function"};goog.isObject=function(a){var b=typeof a;return b=="object"&&a!=null||b=="function"};
goog.getUid=function(a){return Object.prototype.hasOwnProperty.call(a,goog.UID_PROPERTY_)&&a[goog.UID_PROPERTY_]||(a[goog.UID_PROPERTY_]=++goog.uidCounter_)};goog.hasUid=function(a){return!!a[goog.UID_PROPERTY_]};goog.removeUid=function(a){a!==null&&"removeAttribute"in a&&a.removeAttribute(goog.UID_PROPERTY_);try{delete a[goog.UID_PROPERTY_]}catch(b){}};goog.UID_PROPERTY_="closure_uid_"+(Math.random()*1E9>>>0);goog.uidCounter_=0;
goog.cloneObject=function(a){var b=goog.typeOf(a);if(b=="object"||b=="array"){if(typeof a.clone==="function")return a.clone();if(typeof Map!=="undefined"&&a instanceof Map)return new Map(a);if(typeof Set!=="undefined"&&a instanceof Set)return new Set(a);b=b=="array"?[]:{};for(var c in a)b[c]=goog.cloneObject(a[c]);return b}return a};goog.bindNative_=function(a,b,c){return a.call.apply(a.bind,arguments)};
goog.bindJs_=function(a,b,c){if(!a)throw Error();if(arguments.length>2){var d=Array.prototype.slice.call(arguments,2);return function(){var e=Array.prototype.slice.call(arguments);Array.prototype.unshift.apply(e,d);return a.apply(b,e)}}return function(){return a.apply(b,arguments)}};goog.bind=function(a,b,c){Function.prototype.bind&&Function.prototype.bind.toString().indexOf("native code")!=-1?goog.bind=goog.bindNative_:goog.bind=goog.bindJs_;return goog.bind.apply(null,arguments)};
goog.partial=function(a,b){var c=Array.prototype.slice.call(arguments,1);return function(){var d=c.slice();d.push.apply(d,arguments);return a.apply(this,d)}};goog.now=function(){return Date.now()};goog.globalEval=function(a){(0,eval)(a)};
goog.getCssName=function(a,b){if(String(a).charAt(0)==".")throw Error('className passed in goog.getCssName must not start with ".". You passed: '+a);var c=function(e){return goog.cssNameMapping_[e]||e},d=function(e){e=e.split("-");for(var f=[],g=0;g<e.length;g++)f.push(c(e[g]));return f.join("-")};d=goog.cssNameMapping_?goog.cssNameMappingStyle_=="BY_WHOLE"?c:d:function(e){return e};a=b?a+"-"+d(b):d(a);return goog.global.CLOSURE_CSS_NAME_MAP_FN?goog.global.CLOSURE_CSS_NAME_MAP_FN(a):a};
goog.setCssNameMapping=function(a,b){goog.cssNameMapping_=a;goog.cssNameMappingStyle_=b};!COMPILED&&goog.global.CLOSURE_CSS_NAME_MAPPING&&(goog.cssNameMapping_=goog.global.CLOSURE_CSS_NAME_MAPPING);goog.GetMsgOptions=function(){};
goog.getMsg=function(a,b,c){c&&c.html&&(a=a.replace(/</g,"&lt;"));c&&c.unescapeHtmlEntities&&(a=a.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&amp;/g,"&"));b&&(a=a.replace(/\{\$([^}]+)}/g,function(d,e){return b!=null&&e in b?b[e]:d}));return a};goog.getMsgWithFallback=function(a,b){return a};goog.exportSymbol=function(a,b,c){goog.exportPath_(a,b,!0,c)};goog.exportProperty=function(a,b,c){a[b]=c};
goog.inherits=function(a,b){function c(){}c.prototype=b.prototype;a.superClass_=b.prototype;a.prototype=new c;a.prototype.constructor=a;a.base=function(d,e,f){for(var g=Array(arguments.length-2),h=2;h<arguments.length;h++)g[h-2]=arguments[h];return b.prototype[e].apply(d,g)}};goog.scope=function(a){if(goog.isInModuleLoader_())throw Error("goog.scope is not supported within a module.");a.call(goog.global)};COMPILED||(goog.global.COMPILED=COMPILED);
goog.defineClass=function(a,b){var c=b.constructor,d=b.statics;c&&c!=Object.prototype.constructor||(c=function(){throw Error("cannot instantiate an interface (no constructor defined).");});c=goog.defineClass.createSealingConstructor_(c,a);a&&goog.inherits(c,a);delete b.constructor;delete b.statics;goog.defineClass.applyProperties_(c.prototype,b);d!=null&&(d instanceof Function?d(c):goog.defineClass.applyProperties_(c,d));return c};goog.defineClass.SEAL_CLASS_INSTANCES=goog.DEBUG;
goog.defineClass.createSealingConstructor_=function(a,b){return goog.defineClass.SEAL_CLASS_INSTANCES?function(){var c=a.apply(this,arguments)||this;c[goog.UID_PROPERTY_]=c[goog.UID_PROPERTY_];return c}:a};goog.defineClass.OBJECT_PROTOTYPE_FIELDS_="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");
goog.defineClass.applyProperties_=function(a,b){for(var c in b)Object.prototype.hasOwnProperty.call(b,c)&&(a[c]=b[c]);for(var d=0;d<goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length;d++)c=goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[d],Object.prototype.hasOwnProperty.call(b,c)&&(a[c]=b[c])};goog.identity_=function(a){return a};
goog.createTrustedTypesPolicy=function(a){var b=null,c=goog.global.trustedTypes;if(!c||!c.createPolicy)return b;try{b=c.createPolicy(a,{createHTML:goog.identity_,createScript:goog.identity_,createScriptURL:goog.identity_})}catch(d){goog.logToConsole_(d.message)}return b};
!COMPILED&&goog.DEPENDENCIES_ENABLED&&(goog.isEdge_=function(){return!!(goog.global.navigator&&goog.global.navigator.userAgent?goog.global.navigator.userAgent:"").match(/Edge\/(\d+)(\.\d)*/i)},goog.inHtmlDocument_=function(){var a=goog.global.document;return a!=null&&"write"in a},goog.isDocumentLoading_=function(){var a=goog.global.document;return a.attachEvent?a.readyState!="complete":a.readyState=="loading"},goog.findBasePath_=function(){if(goog.global.CLOSURE_BASE_PATH!=void 0&&typeof goog.global.CLOSURE_BASE_PATH===
"string")goog.basePath=goog.global.CLOSURE_BASE_PATH;else if(goog.inHtmlDocument_()){var a=goog.global.document,b=a.currentScript;a=b?[b]:a.getElementsByTagName("SCRIPT");for(b=a.length-1;b>=0;--b){var c=a[b].src,d=c.lastIndexOf("?");d=d==-1?c.length:d;if(c.slice(d-7,d)=="base.js"){goog.basePath=c.slice(0,d-7);break}}}},goog.findBasePath_(),goog.protectScriptTag_=function(a){return a.replace(/<\/(SCRIPT)/ig,"\\x3c/$1")},goog.DebugLoader_=function(){this.dependencies_={};this.idToPath_={};this.written_=
{};this.loadingDeps_=[];this.depsToLoad_=[];this.paused_=!1;this.factory_=new goog.DependencyFactory;this.deferredCallbacks_={};this.deferredQueue_=[]},goog.DebugLoader_.prototype.bootstrap=function(a,b){function c(){d&&(goog.global.setTimeout(d,0),d=null)}var d=b;if(a.length){b=[];for(var e=0;e<a.length;e++){var f=this.getPathFromDeps_(a[e]);if(!f)throw Error("Unregonized namespace: "+a[e]);b.push(this.dependencies_[f])}f=goog.require;var g=0;for(e=0;e<a.length;e++)f(a[e]),b[e].onLoad(function(){++g==
a.length&&c()})}else c()},goog.DebugLoader_.prototype.loadClosureDeps=function(){this.depsToLoad_.push(this.factory_.createDependency(goog.normalizePath_(goog.basePath+"deps.js"),"deps.js",[],[],{}));this.loadDeps_()},goog.DebugLoader_.prototype.requested=function(a,b){(a=this.getPathFromDeps_(a))&&(b||this.areDepsLoaded_(this.dependencies_[a].requires))&&(b=this.deferredCallbacks_[a])&&(delete this.deferredCallbacks_[a],b())},goog.DebugLoader_.prototype.setDependencyFactory=function(a){this.factory_=
a},goog.DebugLoader_.prototype.load_=function(a){if(this.getPathFromDeps_(a)){var b=this,c=[],d=function(e){var f=b.getPathFromDeps_(e);if(!f)throw Error("Bad dependency path or symbol: "+e);if(!b.written_[f]){b.written_[f]=!0;e=b.dependencies_[f];for(f=0;f<e.requires.length;f++)goog.isProvided_(e.requires[f])||d(e.requires[f]);c.push(e)}};d(a);a=!!this.depsToLoad_.length;this.depsToLoad_=this.depsToLoad_.concat(c);this.paused_||a||this.loadDeps_()}else goog.logToConsole_("goog.require could not find: "+
a)},goog.DebugLoader_.prototype.loadDeps_=function(){for(var a=this,b=this.paused_;this.depsToLoad_.length&&!b;)(function(){var c=!1,d=a.depsToLoad_.shift(),e=!1;a.loading_(d);var f={pause:function(){if(c)throw Error("Cannot call pause after the call to load.");b=!0},resume:function(){c?a.resume_():b=!1},loaded:function(){if(e)throw Error("Double call to loaded.");e=!0;a.loaded_(d)},pending:function(){for(var g=[],h=0;h<a.loadingDeps_.length;h++)g.push(a.loadingDeps_[h]);return g},setModuleState:function(g){goog.moduleLoaderState_=
{type:g,moduleName:"",declareLegacyNamespace:!1}},registerEs6ModuleExports:function(g,h,k){k&&(goog.loadedModules_[k]={exports:h,type:goog.ModuleType.ES6,moduleId:k||""})},registerGoogModuleExports:function(g,h){goog.loadedModules_[g]={exports:h,type:goog.ModuleType.GOOG,moduleId:g}},clearModuleState:function(){goog.moduleLoaderState_=null},defer:function(g){if(c)throw Error("Cannot register with defer after the call to load.");a.defer_(d,g)},areDepsLoaded:function(){return a.areDepsLoaded_(d.requires)}};
try{d.load(f)}finally{c=!0}})();b&&this.pause_()},goog.DebugLoader_.prototype.pause_=function(){this.paused_=!0},goog.DebugLoader_.prototype.resume_=function(){this.paused_&&(this.paused_=!1,this.loadDeps_())},goog.DebugLoader_.prototype.loading_=function(a){this.loadingDeps_.push(a)},goog.DebugLoader_.prototype.loaded_=function(a){for(var b=0;b<this.loadingDeps_.length;b++)if(this.loadingDeps_[b]==a){this.loadingDeps_.splice(b,1);break}for(b=0;b<this.deferredQueue_.length;b++)if(this.deferredQueue_[b]==
a.path){this.deferredQueue_.splice(b,1);break}if(this.loadingDeps_.length==this.deferredQueue_.length&&!this.depsToLoad_.length)for(;this.deferredQueue_.length;)this.requested(this.deferredQueue_.shift(),!0);a.loaded()},goog.DebugLoader_.prototype.areDepsLoaded_=function(a){for(var b=0;b<a.length;b++){var c=this.getPathFromDeps_(a[b]);if(!c||!(c in this.deferredCallbacks_||goog.isProvided_(a[b])))return!1}return!0},goog.DebugLoader_.prototype.getPathFromDeps_=function(a){return a in this.idToPath_?
this.idToPath_[a]:a in this.dependencies_?a:null},goog.DebugLoader_.prototype.defer_=function(a,b){this.deferredCallbacks_[a.path]=b;this.deferredQueue_.push(a.path)},goog.LoadController=function(){},goog.LoadController.prototype.pause=function(){},goog.LoadController.prototype.resume=function(){},goog.LoadController.prototype.loaded=function(){},goog.LoadController.prototype.pending=function(){},goog.LoadController.prototype.registerEs6ModuleExports=function(a,b,c){},goog.LoadController.prototype.setModuleState=
function(a){},goog.LoadController.prototype.clearModuleState=function(){},goog.LoadController.prototype.defer=function(a){},goog.LoadController.prototype.areDepsLoaded=function(){},goog.Dependency=function(a,b,c,d,e){this.path=a;this.relativePath=b;this.provides=c;this.requires=d;this.loadFlags=e;this.loaded_=!1;this.loadCallbacks_=[]},goog.Dependency.prototype.getPathName=function(){var a=this.path,b=a.indexOf("://");b>=0&&(a=a.substring(b+3),b=a.indexOf("/"),b>=0&&(a=a.substring(b+1)));return a},
goog.Dependency.prototype.onLoad=function(a){this.loaded_?a():this.loadCallbacks_.push(a)},goog.Dependency.prototype.loaded=function(){this.loaded_=!0;var a=this.loadCallbacks_;this.loadCallbacks_=[];for(var b=0;b<a.length;b++)a[b]()},goog.Dependency.defer_=!1,goog.Dependency.callbackMap_={},goog.Dependency.registerCallback_=function(a){var b=Math.random().toString(32);goog.Dependency.callbackMap_[b]=a;return b},goog.Dependency.unregisterCallback_=function(a){delete goog.Dependency.callbackMap_[a]},
goog.Dependency.callback_=function(a,b){if(a in goog.Dependency.callbackMap_){for(var c=goog.Dependency.callbackMap_[a],d=[],e=1;e<arguments.length;e++)d.push(arguments[e]);c.apply(void 0,d)}else throw Error("Callback key "+a+" does not exist (was base.js loaded more than once?).");},goog.Dependency.prototype.load=function(a){if(goog.global.CLOSURE_IMPORT_SCRIPT)goog.global.CLOSURE_IMPORT_SCRIPT(this.path)?a.loaded():a.pause();else if(goog.inHtmlDocument_()){var b=goog.global.document;if(b.readyState==
"complete"&&!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING){if(/\bdeps.js$/.test(this.path)){a.loaded();return}throw Error('Cannot write "'+this.path+'" after document load');}var c=goog.getScriptNonce_();if(!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING&&goog.isDocumentLoading_()){var d=function(h){h.readyState&&h.readyState!="complete"?h.onload=d:(goog.Dependency.unregisterCallback_(e),a.loaded())};var e=goog.Dependency.registerCallback_(d);c=c?' nonce="'+c+'"':"";var f='<script src="'+this.path+'"'+
c+(goog.Dependency.defer_?" defer":"")+' id="script-'+e+'">\x3c/script>';f+="<script"+c+">";f=goog.Dependency.defer_?f+("document.getElementById('script-"+e+"').onload = function() {\n  goog.Dependency.callback_('"+e+"', this);\n};\n"):f+("goog.Dependency.callback_('"+e+"', document.getElementById('script-"+e+"'));");f+="\x3c/script>";b.write(goog.TRUSTED_TYPES_POLICY_?goog.TRUSTED_TYPES_POLICY_.createHTML(f):f)}else{var g=b.createElement("script");g.defer=goog.Dependency.defer_;g.async=!1;c&&(g.nonce=
c);g.onload=function(){g.onload=null;a.loaded()};g.src=goog.TRUSTED_TYPES_POLICY_?goog.TRUSTED_TYPES_POLICY_.createScriptURL(this.path):this.path;b.head.appendChild(g)}}else goog.logToConsole_("Cannot use default debug loader outside of HTML documents."),this.relativePath=="deps.js"?(goog.logToConsole_("Consider setting CLOSURE_IMPORT_SCRIPT before loading base.js, or setting CLOSURE_NO_DEPS to true."),a.loaded()):a.pause()},goog.Es6ModuleDependency=function(a,b,c,d,e){goog.Dependency.call(this,a,
b,c,d,e)},goog.inherits(goog.Es6ModuleDependency,goog.Dependency),goog.Es6ModuleDependency.prototype.load=function(a){function b(l,m){var n="",q=goog.getScriptNonce_();q&&(n=' nonce="'+q+'"');l=m?'<script type="module" crossorigin'+n+">"+m+"\x3c/script>":'<script type="module" crossorigin src="'+l+'"'+n+">\x3c/script>";d.write(goog.TRUSTED_TYPES_POLICY_?goog.TRUSTED_TYPES_POLICY_.createHTML(l):l)}function c(l,m){var n=d.createElement("script");n.defer=!0;n.async=!1;n.type="module";n.setAttribute("crossorigin",
!0);var q=goog.getScriptNonce_();q&&(n.nonce=q);m?n.text=goog.TRUSTED_TYPES_POLICY_?goog.TRUSTED_TYPES_POLICY_.createScript(m):m:n.src=goog.TRUSTED_TYPES_POLICY_?goog.TRUSTED_TYPES_POLICY_.createScriptURL(l):l;d.head.appendChild(n)}if(goog.global.CLOSURE_IMPORT_SCRIPT)goog.global.CLOSURE_IMPORT_SCRIPT(this.path)?a.loaded():a.pause();else if(goog.inHtmlDocument_()){var d=goog.global.document,e=this;if(goog.isDocumentLoading_()){var f=b;goog.Dependency.defer_=!0}else f=c;var g=goog.Dependency.registerCallback_(function(){goog.Dependency.unregisterCallback_(g);
a.setModuleState(goog.ModuleType.ES6)});f(void 0,'goog.Dependency.callback_("'+g+'")');f(this.path,void 0);var h=goog.Dependency.registerCallback_(function(l){goog.Dependency.unregisterCallback_(h);a.registerEs6ModuleExports(e.path,l,goog.moduleLoaderState_.moduleName)});f(void 0,'import * as m from "'+this.path+'"; goog.Dependency.callback_("'+h+'", m)');var k=goog.Dependency.registerCallback_(function(){goog.Dependency.unregisterCallback_(k);a.clearModuleState();a.loaded()});f(void 0,'goog.Dependency.callback_("'+
k+'")')}else goog.logToConsole_("Cannot use default debug loader outside of HTML documents."),a.pause()},goog.TransformedDependency=function(a,b,c,d,e){goog.Dependency.call(this,a,b,c,d,e);this.contents_=null;this.lazyFetch_=!goog.inHtmlDocument_()||!("noModule"in goog.global.document.createElement("script"))},goog.inherits(goog.TransformedDependency,goog.Dependency),goog.TransformedDependency.prototype.load=function(a){function b(){e.contents_=goog.loadFileSync_(e.path);e.contents_&&(e.contents_=
e.transform(e.contents_),e.contents_&&(e.contents_+="\n//# sourceURL="+e.path))}function c(){e.lazyFetch_&&b();if(e.contents_){f&&a.setModuleState(goog.ModuleType.ES6);try{var l=e.contents_;e.contents_=null;goog.globalEval(goog.CLOSURE_EVAL_PREFILTER_.createScript(l));if(f)var m=goog.moduleLoaderState_.moduleName}finally{f&&a.clearModuleState()}f&&goog.global.$jscomp.require.ensure([e.getPathName()],function(){a.registerEs6ModuleExports(e.path,goog.global.$jscomp.require(e.getPathName()),m)});a.loaded()}}
function d(){var l=goog.global.document,m=goog.Dependency.registerCallback_(function(){goog.Dependency.unregisterCallback_(m);c()}),n=goog.getScriptNonce_();n="<script"+(n?' nonce="'+n+'"':"")+">"+goog.protectScriptTag_('goog.Dependency.callback_("'+m+'");')+"\x3c/script>";l.write(goog.TRUSTED_TYPES_POLICY_?goog.TRUSTED_TYPES_POLICY_.createHTML(n):n)}var e=this;if(goog.global.CLOSURE_IMPORT_SCRIPT)b(),this.contents_&&goog.global.CLOSURE_IMPORT_SCRIPT("",this.contents_)?(this.contents_=null,a.loaded()):
a.pause();else{var f=this.loadFlags.module==goog.ModuleType.ES6;this.lazyFetch_||b();var g=a.pending().length>1;if(goog.Dependency.defer_&&(g||goog.isDocumentLoading_()))a.defer(function(){c()});else{var h=goog.global.document;g=goog.inHtmlDocument_()&&("ActiveXObject"in goog.global||goog.isEdge_());if(f&&goog.inHtmlDocument_()&&goog.isDocumentLoading_()&&!g){goog.Dependency.defer_=!0;a.pause();var k=h.onreadystatechange;h.onreadystatechange=function(){h.readyState=="interactive"&&(h.onreadystatechange=
k,c(),a.resume());typeof k==="function"&&k.apply(void 0,arguments)}}else goog.inHtmlDocument_()&&goog.isDocumentLoading_()?d():c()}}},goog.TransformedDependency.prototype.transform=function(a){},goog.PreTranspiledEs6ModuleDependency=function(a,b,c,d,e){goog.TransformedDependency.call(this,a,b,c,d,e)},goog.inherits(goog.PreTranspiledEs6ModuleDependency,goog.TransformedDependency),goog.PreTranspiledEs6ModuleDependency.prototype.transform=function(a){return a},goog.GoogModuleDependency=function(a,b,
c,d,e){goog.TransformedDependency.call(this,a,b,c,d,e)},goog.inherits(goog.GoogModuleDependency,goog.TransformedDependency),goog.GoogModuleDependency.prototype.transform=function(a){return goog.LOAD_MODULE_USING_EVAL&&goog.global.JSON!==void 0?"goog.loadModule("+goog.global.JSON.stringify(a+"\n//# sourceURL="+this.path+"\n")+");":'goog.loadModule(function(exports) {"use strict";'+a+"\n;return exports});\n//# sourceURL="+this.path+"\n"},goog.DebugLoader_.prototype.addDependency=function(a,b,c,d){b=
b||[];a=a.replace(/\\/g,"/");var e=goog.normalizePath_(goog.basePath+a);d&&typeof d!=="boolean"||(d=d?{module:goog.ModuleType.GOOG}:{});c=this.factory_.createDependency(e,a,b,c,d);this.dependencies_[e]=c;for(c=0;c<b.length;c++)this.idToPath_[b[c]]=e;this.idToPath_[a]=e},goog.DependencyFactory=function(){},goog.DependencyFactory.prototype.createDependency=function(a,b,c,d,e){return e.module==goog.ModuleType.GOOG?new goog.GoogModuleDependency(a,b,c,d,e):e.module==goog.ModuleType.ES6?goog.ASSUME_ES_MODULES_TRANSPILED?
new goog.PreTranspiledEs6ModuleDependency(a,b,c,d,e):new goog.Es6ModuleDependency(a,b,c,d,e):new goog.Dependency(a,b,c,d,e)},goog.debugLoader_=new goog.DebugLoader_,goog.loadClosureDeps=function(){goog.debugLoader_.loadClosureDeps()},goog.setDependencyFactory=function(a){goog.debugLoader_.setDependencyFactory(a)},goog.TRUSTED_TYPES_POLICY_=goog.TRUSTED_TYPES_POLICY_NAME?goog.createTrustedTypesPolicy(goog.TRUSTED_TYPES_POLICY_NAME+"#base"):null,goog.global.CLOSURE_NO_DEPS||goog.debugLoader_.loadClosureDeps(),
goog.bootstrap=function(a,b){goog.debugLoader_.bootstrap(a,b)});if(!COMPILED){var isChrome87=!1;try{isChrome87=eval(goog.global.trustedTypes.emptyScript)!==goog.global.trustedTypes.emptyScript}catch(a){}goog.CLOSURE_EVAL_PREFILTER_=goog.global.trustedTypes&&isChrome87&&goog.createTrustedTypesPolicy("goog#base#devonly#eval")||{createScript:goog.identity_}};/*
 @license
 Shaka Player
 Copyright 2016 Google LLC
 SPDX-License-Identifier: Apache-2.0
*/
goog.asserts=class{static assert(a,b){}};goog.asserts.ENABLE_ASSERTS=!0;goog.asserts.ENABLE_ASSERTS&&console.assert&&console.assert.bind&&(goog.asserts.assert=console.assert.bind(console));var shaka={abr:{}};
shaka.abr.Ewma=class{constructor(a){goog.asserts.assert(a>0,"expected halfLife to be positive");this.logHalf_=Math.log(.5);this.alpha_=Math.exp(this.logHalf_/a);this.totalWeight_=this.estimate_=0}updateAlpha(a){goog.asserts.assert(a>0,"expected halfLife to be positive");this.alpha_=Math.exp(this.logHalf_/a)}sample(a,b){const c=Math.pow(this.alpha_,a);b=b*(1-c)+c*this.estimate_;isNaN(b)||(this.estimate_=b,this.totalWeight_+=a)}getEstimate(){return this.estimate_/(1-Math.pow(this.alpha_,this.totalWeight_))}};shaka.abr.EwmaBandwidthEstimator=class{constructor(){this.fast_=new shaka.abr.Ewma(2);this.slow_=new shaka.abr.Ewma(5);this.bytesSampled_=0;this.minTotalBytes_=128E3;this.minBytes_=16E3}configure(a){this.minTotalBytes_=a.minTotalBytes;this.minBytes_=a.minBytes;this.fast_.updateAlpha(a.fastHalfLife);this.slow_.updateAlpha(a.slowHalfLife)}sample(a,b){if(!(b<this.minBytes_)){var c=8E3*b/a;a/=1E3;this.bytesSampled_+=b;this.fast_.sample(a,c);this.slow_.sample(a,c)}}getBandwidthEstimate(a){return this.bytesSampled_<
this.minTotalBytes_?a:Math.min(this.fast_.getEstimate(),this.slow_.getEstimate())}hasGoodEstimate(){return this.bytesSampled_>=this.minTotalBytes_}};shaka.log=class{static alwaysError(...a){}static alwaysWarn(...a){}static warnOnce(a,...b){shaka.log.oneTimeWarningIssued_.has(a)||(shaka.log.oneTimeWarningIssued_.add(a),shaka.log.alwaysWarn(...b))}static error(...a){}static warning(...a){}static info(...a){}static debug(...a){}static v1(...a){}static v2(...a){}};shaka.log.Level={NONE:0,ERROR:1,WARNING:2,INFO:3,DEBUG:4,V1:5,V2:6};shaka.log.MAX_LOG_LEVEL=4;shaka.log.oneTimeWarningIssued_=new Set;
window.console&&(shaka.log.logMap_=(new Map).set(shaka.log.Level.ERROR,(...a)=>console.error(...a)).set(shaka.log.Level.WARNING,(...a)=>console.warn(...a)).set(shaka.log.Level.INFO,(...a)=>console.info(...a)).set(shaka.log.Level.DEBUG,(...a)=>console.log(...a)).set(shaka.log.Level.V1,(...a)=>console.debug(...a)).set(shaka.log.Level.V2,(...a)=>console.debug(...a)),shaka.log.alwaysWarn=(...a)=>console.warn(...a),shaka.log.alwaysError=(...a)=>console.error(...a),goog.DEBUG?(goog.exportSymbol("shaka.log",
shaka.log),shaka.log.setLevel=a=>{const b=c=>c<=a?(goog.asserts.assert(shaka.log.logMap_.has(c),"Unexpected log level"),shaka.log.logMap_.get(c)):()=>{};shaka.log.currentLevel=a;shaka.log.error=b(shaka.log.Level.ERROR);shaka.log.warning=b(shaka.log.Level.WARNING);shaka.log.info=b(shaka.log.Level.INFO);shaka.log.debug=b(shaka.log.Level.DEBUG);shaka.log.v1=b(shaka.log.Level.V1);shaka.log.v2=b(shaka.log.Level.V2)},shaka.log.setLevel(shaka.log.MAX_LOG_LEVEL)):(shaka.log.MAX_LOG_LEVEL>=shaka.log.Level.ERROR&&
(shaka.log.error=shaka.log.logMap_.get(shaka.log.Level.ERROR)),shaka.log.MAX_LOG_LEVEL>=shaka.log.Level.WARNING&&(shaka.log.warning=shaka.log.logMap_.get(shaka.log.Level.WARNING)),shaka.log.MAX_LOG_LEVEL>=shaka.log.Level.INFO&&(shaka.log.info=shaka.log.logMap_.get(shaka.log.Level.INFO)),shaka.log.MAX_LOG_LEVEL>=shaka.log.Level.DEBUG&&(shaka.log.debug=shaka.log.logMap_.get(shaka.log.Level.DEBUG)),shaka.log.MAX_LOG_LEVEL>=shaka.log.Level.V1&&(shaka.log.v1=shaka.log.logMap_.get(shaka.log.Level.V1)),
shaka.log.MAX_LOG_LEVEL>=shaka.log.Level.V2&&(shaka.log.v2=shaka.log.logMap_.get(shaka.log.Level.V2))));shaka.util={};
shaka.util.ArrayUtils=class{static defaultEquals(a,b){return typeof a==="number"&&typeof b==="number"&&isNaN(a)&&isNaN(b)?!0:a===b}static remove(a,b){b=a.indexOf(b);b>-1&&a.splice(b,1)}static count(a,b){let c=0;for(const d of a)c+=b(d)?1:0;return c}static hasSameElements(a,b,c){c||(c=shaka.util.ArrayUtils.defaultEquals);if(a.length!=b.length)return!1;b=b.slice();for(const d of a){a=b.findIndex(e=>c(d,e));if(a==-1)return!1;b[a]=b[b.length-1];b.pop()}return b.length==0}static partition(a,b){const c=
[],d=[];for(const e of a)b(e)?c.push(e):d.push(e);return[c,d]}static binarySearch(a,b){let c=0,d=a.length;for(;c<d;){const e=c+d>>>1;b(a[e])?c=e+1:d=e}return c}static equal(a,b,c){if(a===b)return!0;if(!a||!b)return a==b;c||(c=shaka.util.ArrayUtils.defaultEquals);if(a.length!=b.length)return!1;for(let d=0;d<a.length;d++)if(!c(a[d],b[d]))return!1;return!0}};shaka.util.IReleasable=class{release(){}};shaka.util.MultiMap=class{constructor(){this.map_=new Map}push(a,b){this.map_.has(a)?this.map_.get(a).push(b):this.map_.set(a,[b])}get(a){return this.map_.has(a)?this.map_.get(a).slice():null}getAll(){const a=[];for(const b of this.map_.values())a.push(...b);return a}remove(a,b){if(this.map_.has(a)){var c=this.map_.get(a).filter(d=>d!=b);this.map_.set(a,c);c.length||this.map_.delete(a)}}clear(){this.map_.clear()}forEach(a){this.map_.forEach((b,c)=>{a(c,b)})}size(){return this.map_.size}keys(){return Array.from(this.map_.keys())}};shaka.util.EventManager=class{constructor(){this.bindingMap_=new shaka.util.MultiMap}release(){this.removeAll();this.bindingMap_=null}listen(a,b,c,d){this.bindingMap_&&(a=new shaka.util.EventManager.Binding_(a,b,c,d),this.bindingMap_.push(b,a))}listenOnce(a,b,c,d){const e=f=>{this.unlisten(a,b,e);c(f)};this.listen(a,b,e,d)}unlisten(a,b,c){if(this.bindingMap_){var d=this.bindingMap_.get(b)||[];for(const e of d)e.target!=a||c!=e.listener&&c||(e.unlisten(),this.bindingMap_.remove(b,e))}}removeAll(){if(this.bindingMap_){var a=
this.bindingMap_.getAll();for(const b of a)b.unlisten();this.bindingMap_.clear()}}};goog.exportSymbol("shaka.util.EventManager",shaka.util.EventManager);goog.exportProperty(shaka.util.EventManager.prototype,"removeAll",shaka.util.EventManager.prototype.removeAll);goog.exportProperty(shaka.util.EventManager.prototype,"unlisten",shaka.util.EventManager.prototype.unlisten);goog.exportProperty(shaka.util.EventManager.prototype,"listenOnce",shaka.util.EventManager.prototype.listenOnce);
goog.exportProperty(shaka.util.EventManager.prototype,"listen",shaka.util.EventManager.prototype.listen);goog.exportProperty(shaka.util.EventManager.prototype,"release",shaka.util.EventManager.prototype.release);
shaka.util.EventManager.Binding_=class{constructor(a,b,c,d){this.target=a;this.type=b;this.listener=c;this.options=shaka.util.EventManager.Binding_.convertOptions_(a,d);this.target.addEventListener(b,c,this.options)}unlisten(){goog.asserts.assert(this.target,"Missing target");this.target.removeEventListener(this.type,this.listener,this.options);this.listener=this.target=null;this.options=!1}static convertOptions_(a,b){if(b==void 0)return!1;if(typeof b=="boolean")return b;const c=new Set(["passive",
"capture"]),d=Object.keys(b).filter(e=>!c.has(e));goog.asserts.assert(d.length==0,"Unsupported flag(s) to addEventListener: "+d.join(","));return shaka.util.EventManager.Binding_.doesSupportObject_(a)?b:b.capture||!1}static doesSupportObject_(a){let b=shaka.util.EventManager.Binding_.supportsObject_;if(b==void 0){b=!1;try{const d={};var c={get:()=>{b=!0;return!1}};Object.defineProperty(d,"passive",c);Object.defineProperty(d,"capture",c);c=()=>{};a.addEventListener("test",c,d);a.removeEventListener("test",
c,d)}catch(d){b=!1}shaka.util.EventManager.Binding_.supportsObject_=b}return b||!1}};shaka.util.EventManager.Binding_.supportsObject_=void 0;shaka.config={};shaka.config.AutoShowText={NEVER:0,ALWAYS:1,IF_PREFERRED_TEXT_LANGUAGE:2,IF_SUBTITLES_MAY_BE_NEEDED:3};goog.exportSymbol("shaka.config.AutoShowText",shaka.config.AutoShowText);shaka.util.Lazy=class{constructor(a){this.gen_=a;this.value_=void 0}value(){this.value_===void 0&&(this.value_=this.gen_(),goog.asserts.assert(this.value_!==void 0,"Unable to create lazy value"));return this.value_}reset(){this.value_=void 0}};shaka.device={};
shaka.device.DeviceFactory=class{static registerDeviceFactory(a){goog.asserts.assert(!shaka.device.DeviceFactory.factory_,"Device Factory should NOT be defined");shaka.device.DeviceFactory.factory_=a}static registerDefaultDeviceFactory(a){goog.asserts.assert(!shaka.device.DeviceFactory.defaultFactory_,"Default device Factory should NOT be defined");shaka.device.DeviceFactory.defaultFactory_=a}static getDevice(){goog.asserts.assert(shaka.device.DeviceFactory.factory_||shaka.device.DeviceFactory.defaultFactory_,"Device Factory should be defined");
return shaka.device.DeviceFactory.device_.value()}};shaka.device.DeviceFactory.factory_=null;shaka.device.DeviceFactory.defaultFactory_=null;shaka.device.DeviceFactory.device_=new shaka.util.Lazy(()=>{let a=void 0;shaka.device.DeviceFactory.factory_&&(a=shaka.device.DeviceFactory.factory_());!a&&shaka.device.DeviceFactory.defaultFactory_&&(a=shaka.device.DeviceFactory.defaultFactory_());a&&shaka.log.info(a.toString());return a});shaka.device.IDevice=class{supportsMediaSource(){}supportsMediaType(a){}supportsMediaCapabilities(){}getVersion(){}getDeviceName(){}getDeviceType(){}getBrowserEngine(){}requiresEncryptionInfoInAllInitSegments(a,b){}requiresClearAndEncryptedInitSegments(){}insertEncryptionDataBeforeClear(){}requiresTfhdFix(a){}requiresEC3InitSegments(){}supportsSequenceMode(){}supportsSmoothCodecSwitching(){}seekDelay(){}detectMaxHardwareResolution(){}supportsServerCertificate(){}adjustConfig(a){}shouldOverrideDolbyVisionCodecs(){}shouldAvoidUseTextDecoderEncoder(){}supportsOfflineStorage(){}rejectCodecs(){}getHdrLevel(a){}supportsAirPlay(){}misreportAC3UsingDrm(){}returnLittleEndianUsingPlayReady(){}supportsEncryptionSchemePolyfill(){}misreportsSupportForPersistentLicenses(){}supportStandardVP9Checking(){}createMediaKeysWhenCheckingSupport(){}disableHEVCSupport(){}supportsCbcsWithoutEncryptionSchemeSupport(){}supportsContainerChangeType(){}needWaitForEncryptedEvent(a){}};
shaka.device.IDevice.DeviceType={DESKTOP:"DESKTOP",MOBILE:"MOBILE",TV:"TV",VR:"VR",APPLE_VR:"APPLE_VR",CONSOLE:"CONSOLE",CAST:"CAST"};shaka.device.IDevice.BrowserEngine={CHROMIUM:"CHROMIUM",EDGE:"EDGE",GECKO:"GECKO",WEBKIT:"WEBKIT",UNKNOWN:"UNKNOWN"};shaka.deprecate={};shaka.deprecate.Version=class{constructor(a,b){this.major_=a;this.minor_=b}major(){return this.major_}minor(){return this.minor_}compareTo(a){const b=this.minor_-a.minor_;return this.major_-a.major_||b}toString(){return"v"+this.major_+"."+this.minor_}static parse(a){a=a.substring(1).split(".",2);return new shaka.deprecate.Version(Number(a[0]),Number(a[1]))}};shaka.deprecate.Enforcer=class{constructor(a,b,c){this.libraryVersion_=a;this.onPending_=b;this.onExpired_=c}enforce(a,b,c){(a.compareTo(this.libraryVersion_)>0?this.onPending_:this.onExpired_)(this.libraryVersion_,a,b,c)}};shaka.Deprecate=class{static init(a){goog.asserts.assert(shaka.Deprecate.enforcer_==null,"Deprecate.init should only be called once.");shaka.Deprecate.enforcer_=new shaka.deprecate.Enforcer(shaka.deprecate.Version.parse(a),shaka.Deprecate.onPending_,shaka.Deprecate.onExpired_)}static deprecateFeature(a,b,c){const d=shaka.Deprecate.enforcer_;goog.asserts.assert(d,"Missing deprecation enforcer. Was |init| called?");a=new shaka.deprecate.Version(a,0);d.enforce(a,b,c)}static onPending_(a,b,c,d){shaka.log.alwaysWarn([c,
"has been deprecated and will be removed in",b,". We are currently at version",a,". Additional information:",d].join(" "))}static onExpired_(a,b,c,d){a=[c,"has been deprecated and has been removed in",b,". We are now at version",a,". Additional information:",d].join(" ");shaka.log.alwaysError(a);goog.asserts.assert(!1,a)}};shaka.Deprecate.enforcer_=null;/*
 @license
 Copyright 2006 The Closure Library Authors
 SPDX-License-Identifier: Apache-2.0
*/
goog.uri={};goog.uri.utils={};goog.uri.utils.splitRe_=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^/?#]*)@)?([^/#?]*?)(?::([0-9]+))?(?=[/#?]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#(.*))?$");goog.uri.utils.ComponentIndex={SCHEME:1,USER_INFO:2,DOMAIN:3,PORT:4,PATH:5,QUERY_DATA:6,FRAGMENT:7};goog.uri.utils.split=function(a){return a.match(goog.uri.utils.splitRe_)};goog.Uri=function(a){var b;a instanceof goog.Uri?(this.setScheme(a.getScheme()),this.setUserInfo(a.getUserInfo()),this.setDomain(a.getDomain()),this.setPort(a.getPort()),this.setPath(a.getPath()),this.setQueryData(a.getQueryData().clone()),this.setFragment(a.getFragment())):a&&(b=goog.uri.utils.split(String(a)))?(this.setScheme(b[goog.uri.utils.ComponentIndex.SCHEME]||"",!0),this.setUserInfo(b[goog.uri.utils.ComponentIndex.USER_INFO]||"",!0),this.setDomain(b[goog.uri.utils.ComponentIndex.DOMAIN]||
"",!0),this.setPort(b[goog.uri.utils.ComponentIndex.PORT]),this.setPath(b[goog.uri.utils.ComponentIndex.PATH]||"",!0),this.setQueryData(b[goog.uri.utils.ComponentIndex.QUERY_DATA]||"",!0),this.setFragment(b[goog.uri.utils.ComponentIndex.FRAGMENT]||"",!0)):this.queryData_=new goog.Uri.QueryData(null,null)};goog.Uri.prototype.scheme_="";goog.Uri.prototype.userInfo_="";goog.Uri.prototype.domain_="";goog.Uri.prototype.port_=null;goog.Uri.prototype.path_="";goog.Uri.prototype.fragment_="";
goog.Uri.prototype.toString=function(){var a=[],b=this.getScheme();b&&a.push(goog.Uri.encodeSpecialChars_(b,goog.Uri.reDisallowedInSchemeOrUserInfo_,!0),":");if(b=this.getDomain()){a.push("//");var c=this.getUserInfo();c&&a.push(goog.Uri.encodeSpecialChars_(c,goog.Uri.reDisallowedInSchemeOrUserInfo_,!0),"@");a.push(goog.Uri.removeDoubleEncoding_(encodeURIComponent(b)));b=this.getPort();b!=null&&a.push(":",String(b))}if(b=this.getPath())this.hasDomain()&&b.charAt(0)!="/"&&a.push("/"),a.push(goog.Uri.encodeSpecialChars_(b,
b.charAt(0)=="/"?goog.Uri.reDisallowedInAbsolutePath_:goog.Uri.reDisallowedInRelativePath_,!0));(b=this.getEncodedQuery())&&a.push("?",b);(b=this.getFragment())&&a.push("#",goog.Uri.encodeSpecialChars_(b,goog.Uri.reDisallowedInFragment_));return a.join("")};
goog.Uri.prototype.resolve=function(a){var b=this.clone();b.scheme_==="data"&&(b=new goog.Uri);var c=a.hasScheme();c?b.setScheme(a.getScheme()):c=a.hasUserInfo();c?b.setUserInfo(a.getUserInfo()):c=a.hasDomain();c?b.setDomain(a.getDomain()):c=a.hasPort();var d=a.getPath();if(c)b.setPort(a.getPort());else if(c=a.hasPath()){if(d.charAt(0)!="/")if(this.hasDomain()&&!this.hasPath())d="/"+d;else{var e=b.getPath().lastIndexOf("/");e!=-1&&(d=b.getPath().substr(0,e+1)+d)}d=goog.Uri.removeDotSegments(d)}c?
b.setPath(d):c=a.hasQuery();c?b.setQueryData(a.getQueryData().clone()):c=a.hasFragment();c&&b.setFragment(a.getFragment());return b};goog.Uri.prototype.clone=function(){return new goog.Uri(this)};goog.Uri.prototype.getScheme=function(){return this.scheme_};goog.Uri.prototype.setScheme=function(a,b){if(this.scheme_=b?goog.Uri.decodeOrEmpty_(a,!0):a)this.scheme_=this.scheme_.replace(/:$/,"");return this};goog.Uri.prototype.hasScheme=function(){return!!this.scheme_};goog.Uri.prototype.getUserInfo=function(){return this.userInfo_};
goog.Uri.prototype.setUserInfo=function(a,b){this.userInfo_=b?goog.Uri.decodeOrEmpty_(a):a;return this};goog.Uri.prototype.hasUserInfo=function(){return!!this.userInfo_};goog.Uri.prototype.getDomain=function(){return this.domain_};goog.Uri.prototype.setDomain=function(a,b){this.domain_=b?goog.Uri.decodeOrEmpty_(a,!0):a;return this};goog.Uri.prototype.hasDomain=function(){return!!this.domain_};goog.Uri.prototype.getPort=function(){return this.port_};
goog.Uri.prototype.setPort=function(a){if(a){a=Number(a);if(isNaN(a)||a<0)throw Error("Bad port number "+a);this.port_=a}else this.port_=null;return this};goog.Uri.prototype.hasPort=function(){return this.port_!=null};goog.Uri.prototype.getPath=function(){return this.path_};goog.Uri.prototype.setPath=function(a,b){this.path_=b?goog.Uri.decodeOrEmpty_(a,!0):a;return this};goog.Uri.prototype.hasPath=function(){return!!this.path_};
goog.Uri.prototype.hasQuery=function(){return this.queryData_.toString()!==""};goog.Uri.prototype.setQueryData=function(a,b){a instanceof goog.Uri.QueryData?this.queryData_=a:(b||(a=goog.Uri.encodeSpecialChars_(a,goog.Uri.reDisallowedInQuery_)),this.queryData_=new goog.Uri.QueryData(a,null));return this};goog.Uri.prototype.getEncodedQuery=function(){return this.queryData_.toString()};goog.Uri.prototype.getDecodedQuery=function(){return this.queryData_.toDecodedString()};
goog.Uri.prototype.getQueryData=function(){return this.queryData_};goog.Uri.prototype.getFragment=function(){return this.fragment_};goog.Uri.prototype.setFragment=function(a,b){this.fragment_=b?goog.Uri.decodeOrEmpty_(a):a;return this};goog.Uri.prototype.hasFragment=function(){return!!this.fragment_};
goog.Uri.removeDotSegments=function(a){if(a==".."||a==".")return"";if(a.indexOf("./")==-1&&a.indexOf("/.")==-1)return a;var b=a.lastIndexOf("/",0)==0;a=a.split("/");for(var c=[],d=0;d<a.length;){var e=a[d++];e=="."?b&&d==a.length&&c.push(""):e==".."?((c.length>1||c.length==1&&c[0]!="")&&c.pop(),b&&d==a.length&&c.push("")):(c.push(e),b=!0)}return c.join("/")};goog.Uri.decodeOrEmpty_=function(a,b){return a?b?decodeURI(a):decodeURIComponent(a):""};
goog.Uri.encodeSpecialChars_=function(a,b,c){return a!=null?(a=encodeURI(a).replace(b,goog.Uri.encodeChar_),c&&(a=goog.Uri.removeDoubleEncoding_(a)),a):null};goog.Uri.encodeChar_=function(a){a=a.charCodeAt(0);return"%"+(a>>4&15).toString(16)+(a&15).toString(16)};goog.Uri.removeDoubleEncoding_=function(a){return a.replace(/%25([0-9a-fA-F]{2})/g,"%$1")};goog.Uri.reDisallowedInSchemeOrUserInfo_=/[#\/\?@]/g;goog.Uri.reDisallowedInRelativePath_=/[#\?:]/g;goog.Uri.reDisallowedInAbsolutePath_=/[#\?]/g;
goog.Uri.reDisallowedInQuery_=/[#\?@]/g;goog.Uri.reDisallowedInFragment_=/#/g;goog.Uri.QueryData=function(a,b){this.encodedQuery_=a||null};goog.Uri.QueryData.prototype.ensureKeyMapInitialized_=function(){if(!this.keyMap_&&(this.keyMap_=new Map,this.count_=0,this.encodedQuery_))for(var a=this.encodedQuery_.split("&"),b=0;b<a.length;b++){var c=a[b].indexOf("="),d=null;if(c>=0){var e=a[b].substring(0,c);d=a[b].substring(c+1)}else e=a[b];e=decodeURIComponent(e);d=d||"";this.add(e,decodeURIComponent(d))}};
goog.Uri.QueryData.prototype.keyMap_=null;goog.Uri.QueryData.prototype.count_=null;goog.Uri.QueryData.prototype.getCount=function(){this.ensureKeyMapInitialized_();return this.count_};goog.Uri.QueryData.prototype.add=function(a,b){this.ensureKeyMapInitialized_();this.encodedQuery_=null;var c=this.keyMap_.has(a)?this.keyMap_.get(a):null;c||this.keyMap_.set(a,c=[]);c.push(b);goog.asserts.assert(this.count_!=null,"Should not be null.");this.count_++;return this};
goog.Uri.QueryData.prototype.set=function(a,b){this.ensureKeyMapInitialized_();this.encodedQuery_=null;this.keyMap_.has(a)?this.keyMap_.set(a,[b]):this.add(a,b);return this};goog.Uri.QueryData.prototype.get=function(a){this.ensureKeyMapInitialized_();return this.keyMap_.get(a)||[]};
goog.Uri.QueryData.prototype.toString=function(){if(this.encodedQuery_)return this.encodedQuery_;if(!this.keyMap_||!this.keyMap_.size)return"";var a=[];for(const f of this.keyMap_.keys())for(var b=encodeURIComponent(f),c=this.keyMap_.get(f),d=0;d<c.length;d++){var e=b;c[d]!==""&&(e+="="+encodeURIComponent(c[d]));a.push(e)}return this.encodedQuery_=a.join("&")};goog.Uri.QueryData.prototype.toDecodedString=function(){return goog.Uri.decodeOrEmpty_(this.toString())};
goog.Uri.QueryData.prototype.clone=function(){var a=new goog.Uri.QueryData;a.encodedQuery_=this.encodedQuery_;if(this.keyMap_){var b=new Map;for(const [c,d]of this.keyMap_)b.set(c,d.concat());a.keyMap_=b;a.count_=this.count_}return a};shaka.util.BufferUtils=class{static equal(a,b){var c=shaka.util.BufferUtils;if(!a&&!b)return!0;if(!a||!b||a.byteLength!=b.byteLength)return!1;if(c.unsafeGetArrayBuffer_(a)==c.unsafeGetArrayBuffer_(b)&&(a.byteOffset||0)==(b.byteOffset||0))return!0;c=shaka.util.BufferUtils.toUint8(a);b=shaka.util.BufferUtils.toUint8(b);for(let d=0;d<a.byteLength;d++)if(c[d]!=b[d])return!1;return!0}static unsafeGetArrayBuffer_(a){return ArrayBuffer.isView(a)?a.buffer:a}static toArrayBuffer(a){return ArrayBuffer.isView(a)?
a.byteOffset==0&&a.byteLength==a.buffer.byteLength?a.buffer:(new Uint8Array(a)).buffer:a}static toUint8(a,b=0,c=Infinity){return shaka.util.BufferUtils.view_(a,b,c,Uint8Array)}static toUint16(a,b=0,c=Infinity){return shaka.util.BufferUtils.view_(a,b,c,Uint16Array)}static toDataView(a,b=0,c=Infinity){return shaka.util.BufferUtils.view_(a,b,c,DataView)}static view_(a,b,c,d){const e=shaka.util.BufferUtils.unsafeGetArrayBuffer_(a);let f=1;"BYTES_PER_ELEMENT"in d&&(f=d.BYTES_PER_ELEMENT);const g=((a.byteOffset||
0)+a.byteLength)/f;a=Math.floor(Math.max(0,Math.min(((a.byteOffset||0)+b)/f,g)));return new d(e,a,Math.floor(Math.min(a+Math.max(c,0),g))-a)}};goog.exportSymbol("shaka.util.BufferUtils",shaka.util.BufferUtils);goog.exportProperty(shaka.util.BufferUtils,"toDataView",shaka.util.BufferUtils.toDataView);goog.exportProperty(shaka.util.BufferUtils,"toUint16",shaka.util.BufferUtils.toUint16);goog.exportProperty(shaka.util.BufferUtils,"toUint8",shaka.util.BufferUtils.toUint8);
goog.exportProperty(shaka.util.BufferUtils,"toArrayBuffer",shaka.util.BufferUtils.toArrayBuffer);goog.exportProperty(shaka.util.BufferUtils,"equal",shaka.util.BufferUtils.equal);shaka.drm={};
shaka.drm.DrmUtils=class{static isBrowserSupported(){return!!window.MediaKeys&&!!window.navigator&&!!window.navigator.requestMediaKeySystemAccess&&!!window.MediaKeySystemAccess&&!!window.MediaKeySystemAccess.prototype.getConfiguration}static areDrmCompatible(a,b){if(a===b||!a.length||!b.length)return!0;for(const c of a){if(shaka.drm.DrmUtils.isClearKeyWihRawKey(c))return!0;for(const d of b)if(c.keySystem===d.keySystem||shaka.drm.DrmUtils.isClearKeyWihRawKey(d))return!0}return!1}static getCommonDrmInfos(a,b){if(!a.length)return b;
if(!b.length)return a;const c=[];for(const e of a)for(const f of b)if(e.keySystem==f.keySystem){a=new Map;var d=(e.initData||[]).concat(f.initData||[]);for(const g of d)a.set(g.keyId,g);a=Array.from(a.values());d=e.keyIds&&f.keyIds?new Set([...e.keyIds,...f.keyIds]):e.keyIds||f.keyIds;c.push({keySystem:e.keySystem,licenseServerUri:e.licenseServerUri||f.licenseServerUri,distinctiveIdentifierRequired:e.distinctiveIdentifierRequired||f.distinctiveIdentifierRequired,persistentStateRequired:e.persistentStateRequired||
f.persistentStateRequired,videoRobustness:e.videoRobustness||f.videoRobustness,audioRobustness:e.audioRobustness||f.audioRobustness,serverCertificate:e.serverCertificate||f.serverCertificate,serverCertificateUri:e.serverCertificateUri||f.serverCertificateUri,initData:a,keyIds:d});break}else shaka.drm.DrmUtils.isClearKeyWihRawKey(e)?c.push(e):shaka.drm.DrmUtils.isClearKeyWihRawKey(f)&&c.push(f);return c}static keySystem(a){return a?a.keySystem:""}static isClearKeySystem(a){return a==="org.w3.clearkey"}static isWidevineKeySystem(a){return a?
!!a.match(/^com\.widevine\.alpha/):!1}static isPlayReadyKeySystem(a){return a?!!a.match(/^com\.(microsoft|chromecast)\.playready/):!1}static isFairPlayKeySystem(a){return a?!!a.match(/^com\.apple\.fps/):!1}static isWisePlayKeySystem(a){return a==="com.huawei.wiseplay"}static isClearKeyWihRawKey(a){return(a=a.licenseServerUri)?a.startsWith("data:application/json;base64,"):!1}static generateKeySystemCacheKey_(a,b,c,d){d=[...(new Set(d))].sort().join("#");return`${a}#${b}#${c}#${d}`}static hasMediaKeySystemAccess(a,
b,c,d){const e=shaka.drm.DrmUtils;a=e.generateKeySystemCacheKey_(a,b,c,d);return e.memoizedMediaKeySystemAccessRequests_.has(a)}static getMediaKeySystemAccess(a,b,c,d){const e=shaka.drm.DrmUtils;a=e.generateKeySystemCacheKey_(a,b,c,d);return e.memoizedMediaKeySystemAccessRequests_.get(a)||null}static setMediaKeySystemAccess(a,b,c,d,e){const f=shaka.drm.DrmUtils;a=f.generateKeySystemCacheKey_(a,b,c,d);f.memoizedMediaKeySystemAccessRequests_.set(a,e)}static clearMediaKeySystemAccessMap(){shaka.drm.DrmUtils.memoizedMediaKeySystemAccessRequests_.clear()}static isMediaKeysPolyfilled(a){return a===
window.shakaMediaKeysPolyfill}};shaka.drm.DrmUtils.DUMMY_KEY_ID=new shaka.util.Lazy(()=>shaka.util.BufferUtils.toArrayBuffer(new Uint8Array([0])));shaka.drm.DrmUtils.memoizedMediaKeySystemAccessRequests_=new Map;shaka.util.Error=class{constructor(a,b,c,...d){this.severity=a;this.category=b;this.code=c;this.data=d;this.handled=!1;a="Shaka Error "+this.code;if(goog.DEBUG){b=a="UNKNOWN";for(const e in shaka.util.Error.Category)shaka.util.Error.Category[e]==this.category&&(a=e);for(const e in shaka.util.Error.Code)shaka.util.Error.Code[e]==this.code&&(b=e);a="Shaka Error "+a+"."+b+" ("+this.data.toString()+")"}this.message=a;if(shaka.util.Error.createStack)try{throw Error(this.message||"Shaka Error");}catch(e){this.stack=
e.stack}}toString(){return"shaka.util.Error "+JSON.stringify(this,null,"  ")}};goog.exportSymbol("shaka.util.Error",shaka.util.Error);shaka.util.Error.createStack=!0;shaka.util.Error.Severity={RECOVERABLE:1,CRITICAL:2};goog.exportProperty(shaka.util.Error,"Severity",shaka.util.Error.Severity);shaka.util.Error.Category={NETWORK:1,TEXT:2,MEDIA:3,MANIFEST:4,STREAMING:5,DRM:6,PLAYER:7,CAST:8,STORAGE:9,ADS:10};goog.exportProperty(shaka.util.Error,"Category",shaka.util.Error.Category);
shaka.util.Error.Code={UNSUPPORTED_SCHEME:1E3,BAD_HTTP_STATUS:1001,HTTP_ERROR:1002,TIMEOUT:1003,MALFORMED_DATA_URI:1004,REQUEST_FILTER_ERROR:1006,RESPONSE_FILTER_ERROR:1007,MALFORMED_TEST_URI:1008,UNEXPECTED_TEST_REQUEST:1009,ATTEMPTS_EXHAUSTED:1010,SEGMENT_MISSING:1011,INVALID_TEXT_HEADER:2E3,INVALID_TEXT_CUE:2001,UNABLE_TO_DETECT_ENCODING:2003,BAD_ENCODING:2004,INVALID_XML:2005,INVALID_MP4_TTML:2007,INVALID_MP4_VTT:2008,UNABLE_TO_EXTRACT_CUE_START_TIME:2009,INVALID_MP4_CEA:2010,TEXT_COULD_NOT_GUESS_MIME_TYPE:2011,
CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS:2012,TEXT_ONLY_WEBVTT_SRC_EQUALS:2013,MISSING_TEXT_PLUGIN:2014,UNSUPPORTED_EXTERNAL_THUMBNAILS_URI:2017,BUFFER_READ_OUT_OF_BOUNDS:3E3,JS_INTEGER_OVERFLOW:3001,EBML_OVERFLOW:3002,EBML_BAD_FLOATING_POINT_SIZE:3003,MP4_SIDX_WRONG_BOX_TYPE:3004,MP4_SIDX_INVALID_TIMESCALE:3005,MP4_SIDX_TYPE_NOT_SUPPORTED:3006,WEBM_CUES_ELEMENT_MISSING:3007,WEBM_EBML_HEADER_ELEMENT_MISSING:3008,WEBM_SEGMENT_ELEMENT_MISSING:3009,WEBM_INFO_ELEMENT_MISSING:3010,WEBM_DURATION_ELEMENT_MISSING:3011,
WEBM_CUE_TRACK_POSITIONS_ELEMENT_MISSING:3012,WEBM_CUE_TIME_ELEMENT_MISSING:3013,MEDIA_SOURCE_OPERATION_FAILED:3014,MEDIA_SOURCE_OPERATION_THREW:3015,VIDEO_ERROR:3016,QUOTA_EXCEEDED_ERROR:3017,TRANSMUXING_FAILED:3018,CONTENT_TRANSFORMATION_FAILED:3019,MSS_MISSING_DATA_FOR_TRANSMUXING:3020,MSS_TRANSMUXING_FAILED:3022,TRANSMUXING_NO_VIDEO_DATA:3023,STREAMING_NOT_ALLOWED:3024,UNABLE_TO_GUESS_MANIFEST_TYPE:4E3,DASH_INVALID_XML:4001,DASH_NO_SEGMENT_INFO:4002,DASH_EMPTY_ADAPTATION_SET:4003,DASH_EMPTY_PERIOD:4004,
DASH_WEBM_MISSING_INIT:4005,DASH_UNSUPPORTED_CONTAINER:4006,DASH_PSSH_BAD_ENCODING:4007,DASH_NO_COMMON_KEY_SYSTEM:4008,DASH_MULTIPLE_KEY_IDS_NOT_SUPPORTED:4009,DASH_CONFLICTING_KEY_IDS:4010,RESTRICTIONS_CANNOT_BE_MET:4012,HLS_PLAYLIST_HEADER_MISSING:4015,INVALID_HLS_TAG:4016,HLS_INVALID_PLAYLIST_HIERARCHY:4017,DASH_DUPLICATE_REPRESENTATION_ID:4018,HLS_MULTIPLE_MEDIA_INIT_SECTIONS_FOUND:4020,HLS_REQUIRED_ATTRIBUTE_MISSING:4023,HLS_REQUIRED_TAG_MISSING:4024,HLS_COULD_NOT_GUESS_CODECS:4025,HLS_KEYFORMATS_NOT_SUPPORTED:4026,
DASH_UNSUPPORTED_XLINK_ACTUATE:4027,DASH_XLINK_DEPTH_LIMIT:4028,CONTENT_UNSUPPORTED_BY_BROWSER:4032,CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM:4033,NO_VARIANTS:4036,PERIOD_FLATTENING_FAILED:4037,INCONSISTENT_DRM_ACROSS_PERIODS:4038,HLS_VARIABLE_NOT_FOUND:4039,HLS_MSE_ENCRYPTED_MP2T_NOT_SUPPORTED:4040,HLS_MSE_ENCRYPTED_LEGACY_APPLE_MEDIA_KEYS_NOT_SUPPORTED:4041,NO_WEB_CRYPTO_API:4042,CANNOT_ADD_EXTERNAL_THUMBNAILS_TO_LIVE_STREAM:4045,MSS_INVALID_XML:4046,MSS_LIVE_CONTENT_NOT_SUPPORTED:4047,AES_128_INVALID_IV_LENGTH:4048,
AES_128_INVALID_KEY_LENGTH:4049,DASH_CONFLICTING_AES_128:4050,DASH_UNSUPPORTED_AES_128:4051,DASH_INVALID_PATCH:4052,HLS_EMPTY_MEDIA_PLAYLIST:4053,DASH_MSE_ENCRYPTED_LEGACY_APPLE_MEDIA_KEYS_NOT_SUPPORTED:4054,CANNOT_ADD_EXTERNAL_CHAPTERS_TO_LIVE_STREAM:4055,STREAMING_ENGINE_STARTUP_INVALID_STATE:5006,NO_RECOGNIZED_KEY_SYSTEMS:6E3,REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE:6001,FAILED_TO_CREATE_CDM:6002,FAILED_TO_ATTACH_TO_VIDEO:6003,INVALID_SERVER_CERTIFICATE:6004,FAILED_TO_CREATE_SESSION:6005,FAILED_TO_GENERATE_LICENSE_REQUEST:6006,
LICENSE_REQUEST_FAILED:6007,LICENSE_RESPONSE_REJECTED:6008,ENCRYPTED_CONTENT_WITHOUT_DRM_INFO:6010,NO_LICENSE_SERVER_GIVEN:6012,OFFLINE_SESSION_REMOVED:6013,EXPIRED:6014,SERVER_CERTIFICATE_REQUIRED:6015,INIT_DATA_TRANSFORM_ERROR:6016,SERVER_CERTIFICATE_REQUEST_FAILED:6017,MIN_HDCP_VERSION_NOT_MATCH:6018,ERROR_CHECKING_HDCP_VERSION:6019,MISSING_EME_SUPPORT:6020,LOAD_INTERRUPTED:7E3,OPERATION_ABORTED:7001,NO_VIDEO_ELEMENT:7002,OBJECT_DESTROYED:7003,CONTENT_NOT_LOADED:7004,SRC_EQUALS_PRELOAD_NOT_SUPPORTED:7005,
PRELOAD_DESTROYED:7006,QUEUE_INDEX_OUT_OF_BOUNDS:7007,CAST_API_UNAVAILABLE:8E3,NO_CAST_RECEIVERS:8001,ALREADY_CASTING:8002,UNEXPECTED_CAST_ERROR:8003,CAST_CANCELED_BY_USER:8004,CAST_CONNECTION_TIMED_OUT:8005,CAST_RECEIVER_APP_UNAVAILABLE:8006,STORAGE_NOT_SUPPORTED:9E3,INDEXED_DB_ERROR:9001,DEPRECATED_OPERATION_ABORTED:9002,REQUESTED_ITEM_NOT_FOUND:9003,MALFORMED_OFFLINE_URI:9004,CANNOT_STORE_LIVE_OFFLINE:9005,NO_INIT_DATA_FOR_OFFLINE:9007,LOCAL_PLAYER_INSTANCE_REQUIRED:9008,NEW_KEY_OPERATION_NOT_SUPPORTED:9011,
KEY_NOT_FOUND:9012,MISSING_STORAGE_CELL:9013,STORAGE_LIMIT_REACHED:9014,DOWNLOAD_SIZE_CALLBACK_ERROR:9015,MODIFY_OPERATION_NOT_SUPPORTED:9016,INDEXED_DB_INIT_TIMED_OUT:9017,CS_IMA_SDK_MISSING:1E4,CS_AD_MANAGER_NOT_INITIALIZED:10001,SS_IMA_SDK_MISSING:10002,SS_AD_MANAGER_NOT_INITIALIZED:10003,CURRENT_DAI_REQUEST_NOT_FINISHED:10004,MT_AD_MANAGER_NOT_INITIALIZED:10005,INTERSTITIAL_AD_MANAGER_NOT_INITIALIZED:10006,VAST_INVALID_XML:10007};goog.exportProperty(shaka.util.Error,"Code",shaka.util.Error.Code);shaka.util.StringUtils=class{static fromUTF8(a){if(!a)return"";a=shaka.util.BufferUtils.toUint8(a);a[0]==239&&a[1]==187&&a[2]==191&&(a=a.subarray(3));if(window.TextDecoder&&!shaka.device.DeviceFactory.getDevice().shouldAvoidUseTextDecoderEncoder())return a=(new TextDecoder).decode(a),a.includes("\ufffd")&&shaka.log.alwaysError('Decoded string contains an "unknown character" codepoint.  That probably means the UTF8 encoding was incorrect!'),a;let b="";for(let d=0;d<a.length;++d){var c=65533;(a[d]&
128)==0?c=a[d]:a.length>=d+2&&(a[d]&224)==192&&(a[d+1]&192)==128?(c=(a[d]&31)<<6|a[d+1]&63,d+=1):a.length>=d+3&&(a[d]&240)==224&&(a[d+1]&192)==128&&(a[d+2]&192)==128?(c=(a[d]&15)<<12|(a[d+1]&63)<<6|a[d+2]&63,d+=2):a.length>=d+4&&(a[d]&241)==240&&(a[d+1]&192)==128&&(a[d+2]&192)==128&&(a[d+3]&192)==128&&(c=(a[d]&7)<<18|(a[d+1]&63)<<12|(a[d+2]&63)<<6|a[d+3]&63,d+=3);if(c<=65535)b+=String.fromCharCode(c);else{c-=65536;const e=c&1023;b+=String.fromCharCode(55296+(c>>10));b+=String.fromCharCode(56320+e)}}return b}static fromUTF16(a,
b,c){if(!a)return"";if(!c&&a.byteLength%2!=0)throw shaka.log.error("Data has an incorrect length, must be even."),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.BAD_ENCODING);c=Math.floor(a.byteLength/2);const d=new Uint16Array(c);a=shaka.util.BufferUtils.toDataView(a);for(let e=0;e<c;e++)d[e]=a.getUint16(e*2,b);return shaka.util.StringUtils.fromCharCode(d)}static fromBytesAutoDetect(a){const b=shaka.util.StringUtils;if(!a)return"";const c=
shaka.util.BufferUtils.toUint8(a);if(c[0]==239&&c[1]==187&&c[2]==191)return b.fromUTF8(c);if(c[0]==254&&c[1]==255)return b.fromUTF16(c.subarray(2),!1);if(c[0]==255&&c[1]==254)return b.fromUTF16(c.subarray(2),!0);const d=e=>c.byteLength<=e||c[e]>=9&&c[e]<=126;shaka.log.debug("Unable to find byte-order-mark, making an educated guess.");if(c[0]==0&&c[2]==0)return b.fromUTF16(a,!1);if(c[1]==0&&c[3]==0)return b.fromUTF16(a,!0);if(d(0)&&d(1)&&d(2)&&d(3))return b.fromUTF8(a);throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.TEXT,shaka.util.Error.Code.UNABLE_TO_DETECT_ENCODING);}static toUTF8(a){if(window.TextEncoder&&!shaka.device.DeviceFactory.getDevice().shouldAvoidUseTextDecoderEncoder()){var b=new TextEncoder;return shaka.util.BufferUtils.toArrayBuffer(b.encode(a))}a=encodeURIComponent(a);a=unescape(a);b=new Uint8Array(a.length);for(let c=0;c<a.length;c++)b[c]=a[c].charCodeAt(0);return shaka.util.BufferUtils.toArrayBuffer(b)}static toUTF16(a,b){const c=new ArrayBuffer(a.length*2),d=new DataView(c);
for(let e=0;e<a.length;++e){const f=a.charCodeAt(e);d.setUint16(e*2,f,b)}return c}static fromCharCode(a){return shaka.util.StringUtils.fromCharCodeImpl_.value()(a)}static resetFromCharCode(){shaka.util.StringUtils.fromCharCodeImpl_.reset()}static htmlUnescape(a){const b={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&apos;":"'","&nbsp;":"\u00a0","&lrm;":"\u200e","&rlm;":"\u200f"},c=/&(?:amp|lt|gt|quot|apos|nbsp|lrm|rlm|#[xX]?[0-9a-fA-F]+);/g,d=RegExp(c.source);return a&&d.test(a)?a.replace(c,e=>
e[1]=="#"?(e=e[2]=="x"||e[2]=="X"?parseInt(e.substring(3),16):parseInt(e.substring(2),10),e>=0&&e<=1114111?String.fromCodePoint(e):""):b[e]||"'"):a||""}};goog.exportSymbol("shaka.util.StringUtils",shaka.util.StringUtils);goog.exportProperty(shaka.util.StringUtils,"resetFromCharCode",shaka.util.StringUtils.resetFromCharCode);goog.exportProperty(shaka.util.StringUtils,"toUTF16",shaka.util.StringUtils.toUTF16);goog.exportProperty(shaka.util.StringUtils,"toUTF8",shaka.util.StringUtils.toUTF8);
goog.exportProperty(shaka.util.StringUtils,"fromBytesAutoDetect",shaka.util.StringUtils.fromBytesAutoDetect);goog.exportProperty(shaka.util.StringUtils,"fromUTF16",shaka.util.StringUtils.fromUTF16);goog.exportProperty(shaka.util.StringUtils,"fromUTF8",shaka.util.StringUtils.fromUTF8);
shaka.util.StringUtils.fromCharCodeImpl_=new shaka.util.Lazy(()=>{const a=b=>{try{const c=new Uint8Array(b),d=String.fromCharCode.apply(null,c);goog.asserts.assert(d,"Should get value");return d.length>0}catch(c){return!1}};for(let b=65536;b>0;b/=2)if(a(b))return c=>{let d="";for(let e=0;e<c.length;e+=b){const f=c.subarray(e,e+b);d+=String.fromCharCode.apply(null,f)}return d};goog.asserts.assert(!1,"Unable to create a fromCharCode method");return null});shaka.util.Uint8ArrayUtils=class{static toStandardBase64(a){a=shaka.util.BufferUtils.toUint8(a);return Uint8Array.prototype.toBase64?a.toBase64({alphabet:"base64",omitPadding:!1}):(a=shaka.util.StringUtils.fromCharCode(a),btoa(a))}static toBase64(a,b){b=b==void 0?!0:b;return Uint8Array.prototype.toBase64?shaka.util.BufferUtils.toUint8(a).toBase64({alphabet:"base64url",omitPadding:!b}):(a=shaka.util.Uint8ArrayUtils.toStandardBase64(a).replace(/\+/g,"-").replace(/\//g,"_"),b?a:a.replace(/[=]*$/,""))}static fromBase64(a){if(!("fromBase64"in
Uint8Array)){a=window.atob(a.replace(/-/g,"+").replace(/_/g,"/"));var b=new Uint8Array(a.length);for(let c=0;c<a.length;++c)b[c]=a.charCodeAt(c);return b}a=a.replace(/\s+/g,"");b=/[-_]/.test(a);return Uint8Array.fromBase64(a,{alphabet:b?"base64url":"base64"})}static fromHex(a){if(!("fromHex"in Uint8Array)){const b=a.length/2,c=new Uint8Array(b);for(let d=0;d<b;d++)c[d]=window.parseInt(a.substr(d*2,2),16);return c}return Uint8Array.fromHex(a)}static toHex(a){a=shaka.util.BufferUtils.toUint8(a);if(!Uint8Array.prototype.toHex){let b=
"";for(let c of a)c=c.toString(16),c.length==1&&(c="0"+c),b+=c;return b}return a.toHex()}static concat(...a){return shaka.util.Uint8ArrayUtils.concatRange(a,0,a.length)}static concatRange(a,b=0,c=a.length){const d=shaka.util.BufferUtils;var e=0;for(var f=b;f<c;++f)e+=a[f].byteLength;e=new Uint8Array(e);for(f=0;b<c;++b){const g=a[b];ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT===1?e.set(g,f):e.set(d.toUint8(g),f);f+=g.byteLength}return e}};goog.exportSymbol("shaka.util.Uint8ArrayUtils",shaka.util.Uint8ArrayUtils);
goog.exportProperty(shaka.util.Uint8ArrayUtils,"concat",shaka.util.Uint8ArrayUtils.concat);goog.exportProperty(shaka.util.Uint8ArrayUtils,"toHex",shaka.util.Uint8ArrayUtils.toHex);goog.exportProperty(shaka.util.Uint8ArrayUtils,"fromHex",shaka.util.Uint8ArrayUtils.fromHex);goog.exportProperty(shaka.util.Uint8ArrayUtils,"fromBase64",shaka.util.Uint8ArrayUtils.fromBase64);goog.exportProperty(shaka.util.Uint8ArrayUtils,"toBase64",shaka.util.Uint8ArrayUtils.toBase64);
goog.exportProperty(shaka.util.Uint8ArrayUtils,"toStandardBase64",shaka.util.Uint8ArrayUtils.toStandardBase64);shaka.util.ManifestParserUtils=class{static resolveUris(a,b,c=""){if(b.length==0)return a;if(a.length==1&&b.length==1){var d=new goog.Uri(a[0]),e=new goog.Uri(b[0]);d=d.resolve(e);c&&d.setQueryData(c);return[d.toString()]}b=b.map(g=>new goog.Uri(g));const f=[];for(d of a){a=new goog.Uri(d);for(e of b){const g=a.resolve(e);c&&g.setQueryData(c);f.push(g.toString())}}return f}static createDrmInfo(a,b,c,d,e){b={keySystem:a,encryptionScheme:b,licenseServerUri:"",distinctiveIdentifierRequired:!1,persistentStateRequired:!1,
audioRobustness:"",videoRobustness:"",serverCertificate:null,serverCertificateUri:"",sessionType:"",initData:c||[],keyIds:new Set,mediaTypes:e};d&&(b.keySystemUris=new Set([d]));!c&&shaka.drm.DrmUtils.isFairPlayKeySystem(a)&&b.initData.push({initDataType:"sinf",initData:new Uint8Array(0),keyId:null});return b}static createDrmInfoFromClearKeys(a,b="cenc"){var c=shaka.util.StringUtils;const d=shaka.util.Uint8ArrayUtils,e=[],f=[],g=[];a.forEach((k,l)=>{let m=l;m.length!=22&&(m=d.toBase64(d.fromHex(l),
!1));let n=k;n.length!=22&&(n=d.toBase64(d.fromHex(k),!1));k={kty:"oct",kid:m,k:n};e.push(k);f.push(k.kid);g.push(l)});a=JSON.stringify({keys:e});const h=JSON.stringify({kids:f});c=[{initData:shaka.util.BufferUtils.toUint8(c.toUTF8(h)),initDataType:"keyids"}];return{keySystem:"org.w3.clearkey",encryptionScheme:b,licenseServerUri:"data:application/json;base64,"+window.btoa(a),distinctiveIdentifierRequired:!1,persistentStateRequired:!1,audioRobustness:"",videoRobustness:"",serverCertificate:null,serverCertificateUri:"",
sessionType:"",initData:c,keyIds:new Set(g)}}static guessCodecs(a,b){if(b.length==1)return b[0];a=shaka.util.ManifestParserUtils.guessCodecsSafe(a,b);if(a!=null)return a;throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_COULD_NOT_GUESS_CODECS,b);}static guessCodecsSafe(a,b){const c=shaka.util.ManifestParserUtils.CODEC_REGEXPS_BY_CONTENT_TYPE_.get(a);for(const d of c)for(const e of b)if(d.test(e.trim()))return e.trim();return a==
shaka.util.ManifestParserUtils.ContentType.TEXT?"":null}static guessAllCodecsSafe(a,b){const c=[];a=shaka.util.ManifestParserUtils.CODEC_REGEXPS_BY_CONTENT_TYPE_.get(a);for(const d of a)for(const e of b)d.test(e.trim())&&c.push(e.trim());return c}};shaka.util.ManifestParserUtils.ContentType={VIDEO:"video",AUDIO:"audio",TEXT:"text",IMAGE:"image",APPLICATION:"application"};shaka.util.ManifestParserUtils.TextStreamKind={SUBTITLE:"subtitle",CLOSED_CAPTION:"caption"};
shaka.util.ManifestParserUtils.GAP_OVERLAP_TOLERANCE_SECONDS=1/15;shaka.util.ManifestParserUtils.VIDEO_CODEC_REGEXPS=[/^avc/,/^hev/,/^hvc/,/^vvc/,/^vvi/,/^vp0?[89]/,/^av01/,/^mp2v/,/^dvh/,/^dva/,/^dav/];shaka.util.ManifestParserUtils.AUDIO_CODEC_REGEXPS=[/^vorbis$/,/^Opus$/,/^opus$/,/^fLaC$/,/^flac$/,/^mp4a/,/^[ae]c-3$/,/^ac-4/,/^dts[cehx]?$/,/^iamf/,/^mhm[12]/,/^ac3$/,/^eac3$/,/^apac$/];shaka.util.ManifestParserUtils.TEXT_CODEC_REGEXPS=[/^vtt$/,/^wvtt/,/^stpp/];
shaka.util.ManifestParserUtils.CODEC_REGEXPS_BY_CONTENT_TYPE_=(new Map).set("audio",shaka.util.ManifestParserUtils.AUDIO_CODEC_REGEXPS).set("video",shaka.util.ManifestParserUtils.VIDEO_CODEC_REGEXPS).set("text",shaka.util.ManifestParserUtils.TEXT_CODEC_REGEXPS);shaka.lcevc={};
shaka.lcevc.Dec=class{constructor(a,b,c,d){this.dec_=null;this.media_=a;this.canvas_=b;this.decConfig_=c;this.isDualTrack_=d;this.toBeDeprecated_=!1;this.create_()}appendBuffer(a,b,c){c.type!==shaka.util.ManifestParserUtils.ContentType.VIDEO||this.isDualTrack_&&!c.baseOriginalId||this.dec_&&this.dec_.appendBuffer(a,"video",c.id,-b,!this.isDualTrack_)}removeBuffer(a,b,c){a===shaka.util.ManifestParserUtils.ContentType.VIDEO&&this.dec_&&this.dec_.flushBuffer(b,c)}hideCanvas(){this.dec_&&this.canvas_.classList.add("shaka-hidden")}create_(){this.isSupported_()&&
!this.dec_&&this.lcevcLib_.SupportObject.webGLSupport(this.canvas_)&&(this.canvas_.classList.remove("shaka-hidden"),this.dec_=this.toBeDeprecated_?new this.lcevcLib_.LcevcDil(this.media_,this.canvas_,this.decConfig_):new this.lcevcLib_.LCEVCdec(this.media_,this.canvas_,this.decConfig_))}release(){this.dec_&&(this.dec_.close(),this.dec_=null)}isSupported_(){typeof libDPIModule==="undefined"&&shaka.log.alwaysWarn("Could not find LCEVC Library dependencies on this page");if(typeof LCEVCdec!=="undefined")this.lcevcLib_=
LCEVCdec;else if(typeof LcevcDil!=="undefined")this.lcevcLib_=LcevcDil,this.toBeDeprecated_=!0,shaka.Deprecate.deprecateFeature(5,"LcevcDil","lcevc_dil.js is deprecated, please use lcevc_dec.js instead");else return shaka.log.alwaysWarn("Could not find LCEVC Library on this page"),!1;if(typeof this.lcevcLib_.SupportObject==="undefined")return shaka.log.alwaysWarn("Could not find LCEVC Library on this page"),!1;this.lcevcLib_.SupportObject.SupportStatus||shaka.log.alwaysWarn(this.lcevcLib_.SupportObject.SupportError);
return typeof this.lcevcLib_!=="undefined"&&typeof libDPIModule!=="undefined"&&this.canvas_ instanceof HTMLCanvasElement&&this.lcevcLib_.SupportObject.SupportStatus}updateVariant(a,b){if(a=a.video){a.dependencyStream&&(a=a.dependencyStream);var c=shaka.lcevc.Dec.ContainerFormat.MPEG2_TS,d=shaka.lcevc.Dec.StreamingFormat.OTHER;switch(a.mimeType){case "video/webm":c=shaka.lcevc.Dec.ContainerFormat.WEBM;break;case "video/mp4":c=shaka.lcevc.Dec.ContainerFormat.MP4}switch(b){case "DASH":d=shaka.lcevc.Dec.StreamingFormat.DASH;
break;case "HLS":d=shaka.lcevc.Dec.StreamingFormat.HLS}this.dec_&&(this.dec_.setLevelSwitching(a.id,!0),this.dec_.setContainerFormat(c),this.toBeDeprecated_||this.dec_.setStreamingFormat(d))}}static isStreamSupported(a){return a&&typeof LCEVCdec!=="undefined"?a.codecs=="lvc1":!1}};goog.exportSymbol("shaka.lcevc.Dec",shaka.lcevc.Dec);goog.exportProperty(shaka.lcevc.Dec.prototype,"release",shaka.lcevc.Dec.prototype.release);shaka.lcevc.Dec.ContainerFormat={MPEG2_TS:0,WEBM:1,MP4:2};
shaka.lcevc.Dec.StreamingFormat={HLS:0,DASH:1,OTHER:-1};shaka.media={};
shaka.media.ManifestParser=class{static registerParserByExtension(a,b){shaka.Deprecate.deprecateFeature(5,"ManifestParser.registerParserByExtension","Please use an ManifestParser with registerParserByMime function.")}static registerParserByMime(a,b){shaka.media.ManifestParser.parsersByMime.set(a,b)}static unregisterParserByMime(a){shaka.media.ManifestParser.parsersByMime.delete(a)}static probeSupport(){const a=shaka.media.ManifestParser,b={},c=shaka.device.DeviceFactory.getDevice();if(c.supportsMediaSource())for(var d of a.parsersByMime.keys())b[d]=
!0;d=["application/dash+xml","application/x-mpegurl","application/vnd.apple.mpegurl","audio/x-mpegurl","application/vnd.ms-sstr+xml"];for(const e of d)c.supportsMediaSource()?b[e]=a.parsersByMime.has(e):b[e]=c.supportsMediaType(e);return b}static getFactory(a,b){var c=shaka.media.ManifestParser;if(b){if(c=c.parsersByMime.get(b))return c;shaka.log.warning("Could not determine manifest type using MIME type ",b)}throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,
shaka.util.Error.Code.UNABLE_TO_GUESS_MANIFEST_TYPE,a,b);}static isSupported(a){return shaka.device.DeviceFactory.getDevice().supportsMediaSource()?shaka.media.ManifestParser.parsersByMime.has(a):!1}};goog.exportSymbol("shaka.media.ManifestParser",shaka.media.ManifestParser);goog.exportProperty(shaka.media.ManifestParser,"unregisterParserByMime",shaka.media.ManifestParser.unregisterParserByMime);goog.exportProperty(shaka.media.ManifestParser,"registerParserByMime",shaka.media.ManifestParser.registerParserByMime);
goog.exportProperty(shaka.media.ManifestParser,"registerParserByExtension",shaka.media.ManifestParser.registerParserByExtension);shaka.media.ManifestParser.HLS="HLS";shaka.media.ManifestParser.DASH="DASH";shaka.media.ManifestParser.MSS="MSS";shaka.media.ManifestParser.UNKNOWN="UNKNOWN";shaka.media.ManifestParser.AccessibilityPurpose={VISUALLY_IMPAIRED:"visually impaired",HARD_OF_HEARING:"hard of hearing",SPOKEN_SUBTITLES:"spoken subtitles"};
goog.exportProperty(shaka.media.ManifestParser,"AccessibilityPurpose",shaka.media.ManifestParser.AccessibilityPurpose);shaka.media.ManifestParser.parsersByMime=new Map;shaka.cea={};shaka.cea.DummyCaptionDecoder=class{extract(a,b){}decode(){return[]}clear(){}getStreams(){return[]}};shaka.cea.DummyCeaParser=class{init(a){}parse(a){return[]}};shaka.media.ClosedCaptionParser=class{constructor(a){this.decoderCache_=new Map;this.currentContinuityTimeline_=0;this.ceaParser_=new shaka.cea.DummyCeaParser;if(a=shaka.media.ClosedCaptionParser.findParser(a.toLowerCase()))this.ceaParser_=a();this.ceaDecoder_=new shaka.cea.DummyCaptionDecoder;if(a=shaka.media.ClosedCaptionParser.findDecoder())this.ceaDecoder_=a(),this.decoderCache_.set(this.currentContinuityTimeline_,this.ceaDecoder_)}init(a,b=!1,c=-1){shaka.log.debug("Passing new init segment to CEA parser");
c!=-1&&this.currentContinuityTimeline_!=c?this.updateDecoder_(c):b||this.reset();this.ceaParser_.init(a);c!=-1&&(this.currentContinuityTimeline_=c)}parseFrom(a){a=this.ceaParser_.parse(a);for(const b of a)a=shaka.util.BufferUtils.toUint8(b.packet),a.length>0&&this.ceaDecoder_.extract(a,b.pts);return this.ceaDecoder_.decode()}updateDecoder_(a){var b=this.decoderCache_.get(a);this.decoderCache_.set(this.currentContinuityTimeline_,this.ceaDecoder_);if(b)this.ceaDecoder_=b;else{if(b=shaka.media.ClosedCaptionParser.findDecoder())this.ceaDecoder_=
b();this.decoderCache_.set(a,this.ceaDecoder_)}}reset(){this.ceaDecoder_.clear()}remove(a=[]){a=new Set(a);for(const b of this.decoderCache_.keys())if(!a.has(b)){let c=this.decoderCache_.get(b);c&&c.clear();this.decoderCache_.delete(b)}}getStreams(){return this.ceaDecoder_.getStreams()}static registerParser(a,b){shaka.media.ClosedCaptionParser.parserMap_.set(a,b)}static unregisterParser(a){shaka.media.ClosedCaptionParser.parserMap_.delete(a)}static findParser(a){return shaka.media.ClosedCaptionParser.parserMap_.get(a)}static registerDecoder(a){shaka.media.ClosedCaptionParser.decoderFactory_=
a}static unregisterDecoder(){shaka.media.ClosedCaptionParser.decoderFactory_=null}static findDecoder(){return shaka.media.ClosedCaptionParser.decoderFactory_}};goog.exportSymbol("shaka.media.ClosedCaptionParser",shaka.media.ClosedCaptionParser);goog.exportProperty(shaka.media.ClosedCaptionParser,"findDecoder",shaka.media.ClosedCaptionParser.findDecoder);goog.exportProperty(shaka.media.ClosedCaptionParser,"unregisterDecoder",shaka.media.ClosedCaptionParser.unregisterDecoder);
goog.exportProperty(shaka.media.ClosedCaptionParser,"registerDecoder",shaka.media.ClosedCaptionParser.registerDecoder);goog.exportProperty(shaka.media.ClosedCaptionParser,"findParser",shaka.media.ClosedCaptionParser.findParser);goog.exportProperty(shaka.media.ClosedCaptionParser,"unregisterParser",shaka.media.ClosedCaptionParser.unregisterParser);goog.exportProperty(shaka.media.ClosedCaptionParser,"registerParser",shaka.media.ClosedCaptionParser.registerParser);
shaka.media.ClosedCaptionParser.parserMap_=new Map;shaka.media.ClosedCaptionParser.decoderFactory_=null;shaka.text={};shaka.text.CueRegion=class{constructor(){const a=shaka.text.CueRegion;this.id="";this.regionAnchorY=this.regionAnchorX=this.viewportAnchorY=this.viewportAnchorX=0;this.height=this.width=100;this.viewportAnchorUnits=this.widthUnits=this.heightUnits=a.units.PERCENTAGE;this.scroll=a.scrollMode.NONE}};goog.exportSymbol("shaka.text.CueRegion",shaka.text.CueRegion);shaka.text.CueRegion.units={PX:0,PERCENTAGE:1,LINES:2};goog.exportProperty(shaka.text.CueRegion,"units",shaka.text.CueRegion.units);
shaka.text.CueRegion.scrollMode={NONE:"",UP:"up"};goog.exportProperty(shaka.text.CueRegion,"scrollMode",shaka.text.CueRegion.scrollMode);shaka.util.TextParser=class{constructor(a){this.data_=a||"";this.position_=0}atEnd(){return this.position_==this.data_.length}readLine(){return this.readRegexReturnCapture_(/(.*?)(\n|$)/gm,1)}readWord(){return this.readRegexReturnCapture_(/[^ \t\n]*/gm,0)}skipWhitespace(){this.readRegex(/[ \t]+/gm)}readRegex(a){a=this.indexOf_(a);if(this.atEnd()||a==null||a.position!=this.position_)return null;this.position_+=a.length;return a.results}readRegexReturnCapture_(a,b){return this.atEnd()?null:(a=this.readRegex(a))?
a[b]:null}indexOf_(a){goog.asserts.assert(a.global,"global flag should be set");a.lastIndex=this.position_;a=a.exec(this.data_);return a==null?null:{position:a.index,length:a[0].length,results:a}}parseTime(){const a=this.readRegex(shaka.util.TextParser.timeFormat_);if(a==null)return null;const b=Number(a[2]),c=Number(a[3]);return b>59||c>59?null:(Number(a[6])||0)/1E3+c+b*60+(Number(a[1])||0)*3600}static parseTime(a){return a?(new shaka.util.TextParser(a)).parseTime():null}};
shaka.util.TextParser.timeFormat_=/(?:(\d{1,}):)?(\d{2}):(\d{2})((\.(\d{1,3})))?/g;shaka.util.ObjectUtils=class{static cloneObject(a){const b=new WeakSet,c=d=>{switch(typeof d){case "undefined":case "boolean":case "number":case "string":case "symbol":case "function":return d;default:if(!d||ArrayBuffer.isView(d))return d;if(b.has(d))return null;const e=Array.isArray(d);if(d.constructor!=Object&&!e)return null;b.add(d);const f=e?[]:{};for(const g in d)f[g]=c(d[g]);e&&(f.length=d.length);return f}};return c(a)}static shallowCloneObject(a){const b={};for(const c in a)b[c]=a[c];return b}static alphabeticalKeyOrderStringify(a){return Array.isArray(a)?
shaka.util.ObjectUtils.arrayStringify_(a):typeof a=="function"?"":a instanceof Object?shaka.util.ObjectUtils.objectStringify_(a):JSON.stringify(a)}static objectStringify_(a){var b=Object.keys(a);b.sort();const c=[];for(const e of b){b=JSON.stringify(e);var d=a[e];d!==void 0&&(d=shaka.util.ObjectUtils.alphabeticalKeyOrderStringify(d))&&c.push(b+":"+d)}return"{"+c.join(",")+"}"}static arrayStringify_(a){const b=[];for(let d=0;d<a.length;d++){const e=d.toString();var c=a[d];c!==void 0&&(c=shaka.util.ObjectUtils.alphabeticalKeyOrderStringify(c))&&
b.push(e+":"+c)}return"["+b.join(",")+"]"}};goog.exportSymbol("shaka.util.ObjectUtils",shaka.util.ObjectUtils);goog.exportProperty(shaka.util.ObjectUtils,"alphabeticalKeyOrderStringify",shaka.util.ObjectUtils.alphabeticalKeyOrderStringify);goog.exportProperty(shaka.util.ObjectUtils,"shallowCloneObject",shaka.util.ObjectUtils.shallowCloneObject);goog.exportProperty(shaka.util.ObjectUtils,"cloneObject",shaka.util.ObjectUtils.cloneObject);/*
 @license
 tXml
 Copyright 2015 Tobias Nickel
 SPDX-License-Identifier: MIT
*/
shaka.util.TXml=class{static parseXml(a,b,c=!1){a=shaka.util.StringUtils.fromBytesAutoDetect(a);return shaka.util.TXml.parseXmlString(a,b,c)}static parseXmlString(a,b,c=!1){a=shaka.util.TXml.parse(a,c);if(!b&&a.length)return a[0];const d=b.split(",");if(b=a.find(e=>d.includes(e.tagName)))return b;shaka.log.error("parseXml root element not found!");return null}static getKnownNameSpace(a){return shaka.util.TXml.uriToNameSpace_.has(a)?shaka.util.TXml.uriToNameSpace_.get(a):""}static getKnownSchema(a){return shaka.util.TXml.nameSpaceToUri_.has(a)?
shaka.util.TXml.nameSpaceToUri_.get(a):""}static setKnownNameSpace(a,b){shaka.util.TXml.uriToNameSpace_.set(a,b);shaka.util.TXml.nameSpaceToUri_.set(b,a)}static parse(a,b){function c(g,h=!1){for(var k=[];a[e];)if(a.charCodeAt(e)==60){if(a.charCodeAt(e+1)===47){h=e+2;e=a.indexOf(">",e);h=a.substring(h,e);var l=h.indexOf(g);if(l==-1){var m=g.indexOf(".");m>0&&(g=g.substring(0,m),l=h.indexOf(g))}if(l==-1)throw k=a.substring(0,e).split("\n"),Error("Unexpected close tag\nLine: "+(k.length-1)+"\nColumn: "+
(k[k.length-1].length+1)+"\nChar: "+a[e]);e+1&&(e+=1);break}else if(a.charCodeAt(e+1)===33){if(a.charCodeAt(e+2)==45){for(;e!==-1&&(a.charCodeAt(e)!==62||a.charCodeAt(e-1)!=45||a.charCodeAt(e-2)!=45||e==-1);)e=a.indexOf(">",e+1);e===-1&&(e=a.length)}else if(a.charCodeAt(e+2)===91&&a.charCodeAt(e+8)===91&&a.substr(e+3,5).toLowerCase()==="cdata"){l=a.indexOf("]]\x3e",e);l==-1?(k.push(a.substr(e+9)),e=a.length):(k.push(a.substring(e+9,l)),e=l+3);continue}e++;continue}if(f>512)throw Error("XML is too deeply nested");
f++;a:{m=h;e++;var n=d(),q={};for(l=[];a.charCodeAt(e)!==62&&a[e];){var p=a.charCodeAt(e);if(p>64&&p<91||p>96&&p<123){p=d();for(var r=a.charCodeAt(e);r&&r!==39&&r!==34&&!(r>64&&r<91||r>96&&r<123)&&r!==62;)e++,r=a.charCodeAt(e);var t=e+1;e=a.indexOf(a[e],t);t=(" "+a.slice(t,e)).slice(1);if(r===39||r===34){if(e===-1){m={tagName:n,attributes:q,children:l,parent:null};if(b)for(n=0;n<l.length;n++)typeof l[n]!=="string"&&(l[n].parent=m);l=m;break a}}else t=null,e--;p.startsWith("xmlns:")&&(r=p.split(":"),
shaka.util.TXml.setKnownNameSpace(t,r[1]));n==="tt"&&p==="xml:space"&&t==="preserve"&&(m=!0);q[p]=t}e++}a.charCodeAt(e-1)!==47?(e++,l=c(n,m)):e++;m={tagName:n,attributes:q,children:l,parent:null};n=l.length;for(q=0;q<n;q++)p=l[q],typeof p!=="string"?b&&(p.parent=m):q==n-1&&p=="\n"&&l.pop();l=m}f--;k.push(l);if(typeof l==="string")break;l.tagName[0]==="?"&&l.children&&(k.push(...l.children),l.children=[])}else l=e,e=a.indexOf("<",e)-1,e===-2&&(e=a.length),l=(" "+a.slice(l,e+1)).slice(1),h?l.length>
0&&k.push(l):k.length&&l.length==1&&l[0]=="\n"?k.push(l):l.trim().length>0&&k.push(l),e++;return k}function d(){const g=e;for(;"\r\n\t>/= ".indexOf(a[e])===-1&&a[e];)e++;return(" "+a.slice(g,e)).slice(1)}let e=0,f=0;return c("")}static isNode(a){return!!a.tagName}static isText(a){return typeof a==="string"}static getChildNodes(a){const b=[];if(!a.children)return[];for(const c of a.children)typeof c!=="string"&&b.push(c);return b}static findChildren(a,b){const c=[];if(!a.children)return[];for(const d of a.children)d.tagName===
b&&c.push(d);return c}static getTextContents(a){const b=shaka.util.StringUtils;if(typeof a==="string")return b.htmlUnescape(a);const c=[];for(const d of a.children)typeof d==="string"&&c.push(d);a=c.join("");return a===""?null:b.htmlUnescape(a)}static getContents(a){for(const b of a.children)if(typeof b!=="string")return null;(a=shaka.util.TXml.getTextContents(a))&&(a=a.trim());return a}static getElementsByTagName(a,b,c=[]){a.tagName===b&&c.push(a);if(a.children)for(const d of a.children)shaka.util.TXml.getElementsByTagName(d,
b,c);return c}static findChild(a,b){a=shaka.util.TXml.findChildren(a,b);return a.length!=1?null:a[0]}static findChildNS(a,b,c){a=shaka.util.TXml.findChildrenNS(a,b,c);return a.length!=1?null:a[0]}static parseAttr(a,b,c,d=null){let e=null;a=a.attributes[b];a==null||a===""&&d!==null||(e=c(a));return e==null?d:e}static getAttributeNS(a,b,c){b=shaka.util.TXml.getKnownNameSpace(b);return a.attributes[`${b}:${c}`]||null}static findChildrenNS(a,b,c){const d=shaka.util.TXml.getKnownNameSpace(b);b=[];if(a.children){c=
d?`${d}:${c}`:c;for(const e of a.children)e&&e.tagName===c&&b.push(e)}return b}static getAttributeNSList(a,b,c){for(const d of b)if(b=shaka.util.TXml.getAttributeNS(a,d,c))return b;return null}static parseDate(a){if(!a)return null;/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(a)&&(a+="Z");a=Date.parse(a);return isNaN(a)?null:a/1E3}static parseDuration(a){if(!a)return null;const b=RegExp("^P(?:([0-9]*)Y)?(?:([0-9]*)M)?(?:([0-9]*)D)?(?:T(?:([0-9]*)H)?(?:([0-9]*)M)?(?:([0-9.]*)S)?)?$","i").exec(a);if(!b)return shaka.log.warning("Invalid duration string:",
a),null;a=31536E3*Number(b[1]||null)+2592E3*Number(b[2]||null)+86400*Number(b[3]||null)+3600*Number(b[4]||null)+60*Number(b[5]||null)+Number(b[6]||null);return isFinite(a)?a:null}static parseRange(a){var b=/([0-9]+)-([0-9]+)/.exec(a);if(!b)return null;a=Number(b[1]);if(!isFinite(a))return null;b=Number(b[2]);return isFinite(b)?{start:a,end:b}:null}static parseInt(a){a=Number(a);return a%1===0?a:null}static parsePositiveInt(a){a=Number(a);return a%1===0&&a>0?a:null}static parseNonNegativeInt(a){a=
Number(a);return a%1===0&&a>=0?a:null}static parseFloat(a){a=Number(a);return isNaN(a)?null:a}static parseBoolean(a){return a?a.toLowerCase()==="true":!1}static evalDivision(a){let b,c;c=(b=a.match(/^(\d+)\/(\d+)$/))?Number(b[1])/Number(b[2]):Number(a);return isNaN(c)?null:c}static parseXpath(a){const b=[];a=shaka.util.StringUtils.htmlUnescape(a).split(/\/+(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/);for(const c of a)if(a=c.match(/^([\w]+)/)){const d=c.match(/(@id='(.*?)')/),e=c.match(/(@t='(\d+)')/),f=
c.match(/(@n='(\d+)')/),g=c.match(/\[(\d+)\]/);b.push({name:a[0],id:d?d[0].match(/'(.*?)'/)[0].replace(/'/gm,""):null,t:e?Number(e[0].match(/'(.*?)'/)[0].replace(/'/gm,"")):null,n:f?Number(f[0].match(/'(.*?)'/)[0].replace(/'/gm,"")):null,position:g?Number(g[1])-1:null,attribute:c.split("/@")[1]||null})}else c.startsWith("@")&&b.length&&(b[b.length-1].attribute=c.slice(1));return b}static modifyNodes(a,b){const c=shaka.util.TXml;var d=c.parseXpath(b.attributes.sel||"");if(d.length){var e=d[d.length-
1],f=b.attributes.pos||null;d=e.position;d==null&&(e.t!==null&&(d=c.nodePositionByAttribute_(a,"t",e.t)),e.n!==null&&(d=c.nodePositionByAttribute_(a,"n",e.n)));d===null?d=f==="prepend"?0:a.length:f==="prepend"?--d:f==="after"&&++d;f=b.tagName;(e=e.attribute)&&a[d]?c.modifyNodeAttribute(a[d],f,e,c.getContents(b)||""):(f!=="remove"&&f!=="replace"||a.splice(d,1),f!=="add"&&f!=="replace"||a.splice(d,0,...b.children))}}static nodePositionByAttribute_(a,b,c){let d=0;for(const e of a){if(Number(e.attributes[b])===
c)return d;d++}return null}static modifyNodeAttribute(a,b,c,d){if(b==="remove")delete a.attributes[c];else if(b==="add"||b==="replace")a.attributes[c]=d}static txmlNodeToDomElement(a){const b=shaka.util.TXml;var c="";const d=a.tagName.split(":");d.length>0&&(c=b.getKnownSchema(d[0]));c=document.createElementNS(c,a.tagName);for(const e in a.attributes)c.setAttribute(e,a.attributes[e]);for(const e of a.children)a=typeof e=="string"?new Text(e):b.txmlNodeToDomElement(e),c.appendChild(a);return c}static cloneNode(a){if(!a)return null;
const b={tagName:a.tagName,attributes:shaka.util.ObjectUtils.shallowCloneObject(a.attributes),children:[],parent:null};for(const c of a.children)typeof c==="string"?b.children.push(c):(a=shaka.util.TXml.cloneNode(c),a.parent=b,b.children.push(a));return b}};shaka.util.TXml.uriToNameSpace_=new Map;shaka.util.TXml.nameSpaceToUri_=new Map;shaka.text.Cue=class{constructor(a,b,c){const d=shaka.text.Cue;this.startTime=a;this.endTime=b;this.payload=c;this.region=new shaka.text.CueRegion;this.position=null;this.positionAlign=d.positionAlign.AUTO;this.size=0;this.textAlign=d.textAlign.CENTER;this.direction=d.direction.HORIZONTAL_LEFT_TO_RIGHT;this.writingMode=d.writingMode.HORIZONTAL_TOP_TO_BOTTOM;this.lineInterpretation=d.lineInterpretation.LINE_NUMBER;this.line=null;this.lineHeight="";this.lineAlign=d.lineAlign.START;this.displayAlign=
d.displayAlign.AFTER;this.fontSize=this.border=this.backgroundImage=this.backgroundColor=this.color="";this.fontWeight=d.fontWeight.NORMAL;this.fontStyle=d.fontStyle.NORMAL;this.linePadding=this.letterSpacing=this.fontFamily="";this.opacity=1;this.textCombineUpright="";this.textDecoration=[];this.textStrokeWidth=this.textStrokeColor=this.textShadow="";this.wrapLine=!0;this.id="";this.nestedCues=[];this.lineBreak=this.isContainer=!1;this.rubyTag=null;this.cellResolution={columns:32,rows:15}}static lineBreak(a,
b){a=new shaka.text.Cue(a,b,"");a.lineBreak=!0;return a}clone(){const a=new shaka.text.Cue(0,0,"");for(const b in this)a[b]=this[b],Array.isArray(a[b])&&(a[b]=a[b].slice());return a}static equal(a,b){if(a.payload!=b.payload||!(Math.abs(a.startTime-b.startTime)<.001&&Math.abs(a.endTime-b.endTime)<.001))return!1;for(const c in a)if(c!="startTime"&&c!="endTime"&&c!="payload")if(c=="nestedCues"){if(!shaka.util.ArrayUtils.equal(a.nestedCues,b.nestedCues,shaka.text.Cue.equal))return!1}else if(c=="region"||
c=="cellResolution")for(const d in a[c]){if(a[c][d]!=b[c][d])return!1}else if(Array.isArray(a[c])){if(!shaka.util.ArrayUtils.equal(a[c],b[c]))return!1}else if(a[c]!=b[c])return!1;return!0}static parseCuePayload(a,b=new Map){const c=shaka.util.StringUtils,d=shaka.util.TXml;let e=a.payload;if(e.includes("<")){b.size===0&&shaka.text.Cue.addDefaultTextColor(b);e=shaka.text.Cue.replaceKaraokeStylePayload_(e);e=shaka.text.Cue.replaceVoiceStylePayload_(e);e=shaka.text.Cue.escapeInvalidChevrons_(e);a.payload=
"";var f="<span>"+e.replace(/\n/g,"<br />")+"</span>";try{var g=d.parseXmlString(f,"span")}catch(h){shaka.log.warning("cue parse fail: ",h)}if(g)if(f=g.children,f.length!=1||d.isNode(f[0]))for(const h of f)shaka.text.Cue.generateCueFromElement_(h,a,b);else a.payload=c.htmlUnescape(e);else shaka.log.warning("The cue's markup could not be parsed: ",e),a.payload=c.htmlUnescape(e)}else a.payload=c.htmlUnescape(e)}static addDefaultTextColor(a){var b=shaka.text.Cue.defaultTextColor;for(const [c,d]of Object.entries(b))b=
new shaka.text.Cue(0,0,""),b.color=d,a.set("."+c,b);b=shaka.text.Cue.defaultTextBackgroundColor;for(const [c,d]of Object.entries(b))b=new shaka.text.Cue(0,0,""),b.backgroundColor=d,a.set("."+c,b)}static replaceKaraokeStylePayload_(a){const b=[];var c=-1;for(let d=0;d<a.length;d++)a[d]==="<"?c=d+1:a[d]===">"&&c>0&&(c=a.substr(c,d-c),c.match(shaka.text.Cue.timeFormat_)&&b.push(c),c=-1);for(const d of b)a=a.replace("<"+d+">",'<div time="'+d+'">'),a+="</div>";return a}static replaceVoiceStylePayload_(a){const b=
[];let c=-1,d="",e=!1;for(let g=0;g<a.length;g++)if(a[g]==="/"){var f=a.indexOf(">",g);if(f===-1)return a;f=a.substring(g+1,f);if(!f||f!="v"){d+=a[g];continue}e=!0;let h=null;b.length&&(h=b[b.length-1]);if(h){if(h===f)d+="/"+f+">";else{if(!h.startsWith("v")){d+=a[g];continue}d+="/"+h+">"}g+=f.length+1}else d+=a[g]}else a[g]==="<"?(c=g+1,a[c]!="v"&&(c=-1)):a[g]===">"&&c>0&&(b.push(a.substr(c,g-c)),c=-1),d+=a[g];for(const g of b)a=g.replace(" ",".voice-"),d=d.replace(`<${g}>`,`<${a}>`),d=d.replace(`</${g}>`,
`</${a}>`),e||(d+=`</${a}>`);return d}static escapeInvalidChevrons_(a){const b={"< ":""," >":" &gt;"},c=/(< +>|<\s|\s>)/g,d=RegExp(c.source);return a&&d.test(a)?a.replace(c,e=>b[e]||""):a||""}static generateCueFromElement_(a,b,c){const d=shaka.util.TXml;var e=b.clone();e.nestedCues=[];e.payload="";e.rubyTag="";e.line=null;e.region=new shaka.text.CueRegion;e.position=null;e.size=0;e.textAlign=shaka.text.Cue.textAlign.CENTER;if(d.isNode(a)){var f=shaka.text.Cue.fontWeight.BOLD;const h=shaka.text.Cue.fontStyle.ITALIC,
k=shaka.text.Cue.textDecoration.UNDERLINE;var g=a.tagName.split(/(?=[ .])+/g);for(const l of g){g=l;if(g.startsWith(".voice-")){const m=g.split("-").pop();g=`v[voice="${m}"]`;c.has(g)||(g=`v[voice=${m}]`)}c.has(g)&&shaka.text.Cue.mergeStyle_(e,c.get(g));switch(l){case "br":e=shaka.text.Cue.lineBreak(e.startTime,e.endTime);b.nestedCues.push(e);return;case "b":e.fontWeight=f;break;case "i":e.fontStyle=h;break;case "u":e.textDecoration.push(k);break;case "font":if(g=a.attributes.color)e.color=g;break;
case "div":g=a.attributes.time;if(!g)break;if(g=shaka.util.TextParser.parseTime(g))e.startTime=g;break;case "ruby":case "rp":case "rt":e.rubyTag=l}}}f=a.children;if(d.isText(a)||f.length==1&&d.isText(f[0])){a=d.getTextContents(a).split("\n");c=!0;for(const h of a)c||(a=shaka.text.Cue.lineBreak(e.startTime,e.endTime),b.nestedCues.push(a)),h.length>0&&(a=e.clone(),a.payload=shaka.util.StringUtils.htmlUnescape(h),b.nestedCues.push(a)),c=!1}else{b.nestedCues.push(e);for(const h of f)shaka.text.Cue.generateCueFromElement_(h,
e,c)}}static mergeStyle_(a,b){b&&(a.backgroundColor=shaka.text.Cue.getOrDefault_(b.backgroundColor,a.backgroundColor),a.color=shaka.text.Cue.getOrDefault_(b.color,a.color),a.fontFamily=shaka.text.Cue.getOrDefault_(b.fontFamily,a.fontFamily),a.fontSize=shaka.text.Cue.getOrDefault_(b.fontSize,a.fontSize),a.textShadow=shaka.text.Cue.getOrDefault_(b.textShadow,a.textShadow),a.fontWeight=b.fontWeight,a.fontStyle=b.fontStyle,a.opacity=b.opacity,a.rubyTag=b.rubyTag,a.textCombineUpright=b.textCombineUpright,
a.wrapLine=b.wrapLine)}static getOrDefault_(a,b){return a&&a.length>0?a:b}};goog.exportSymbol("shaka.text.Cue",shaka.text.Cue);goog.exportProperty(shaka.text.Cue,"parseCuePayload",shaka.text.Cue.parseCuePayload);goog.exportProperty(shaka.text.Cue,"equal",shaka.text.Cue.equal);goog.exportProperty(shaka.text.Cue.prototype,"clone",shaka.text.Cue.prototype.clone);shaka.text.Cue.positionAlign={LEFT:"line-left",RIGHT:"line-right",CENTER:"center",AUTO:"auto"};
goog.exportProperty(shaka.text.Cue,"positionAlign",shaka.text.Cue.positionAlign);shaka.text.Cue.textAlign={LEFT:"left",RIGHT:"right",CENTER:"center",START:"start",END:"end"};goog.exportProperty(shaka.text.Cue,"textAlign",shaka.text.Cue.textAlign);shaka.text.Cue.displayAlign={BEFORE:"before",CENTER:"center",AFTER:"after"};goog.exportProperty(shaka.text.Cue,"displayAlign",shaka.text.Cue.displayAlign);shaka.text.Cue.direction={HORIZONTAL_LEFT_TO_RIGHT:"ltr",HORIZONTAL_RIGHT_TO_LEFT:"rtl"};
goog.exportProperty(shaka.text.Cue,"direction",shaka.text.Cue.direction);shaka.text.Cue.writingMode={HORIZONTAL_TOP_TO_BOTTOM:"horizontal-tb",VERTICAL_LEFT_TO_RIGHT:"vertical-lr",VERTICAL_RIGHT_TO_LEFT:"vertical-rl"};goog.exportProperty(shaka.text.Cue,"writingMode",shaka.text.Cue.writingMode);shaka.text.Cue.lineInterpretation={LINE_NUMBER:0,PERCENTAGE:1};goog.exportProperty(shaka.text.Cue,"lineInterpretation",shaka.text.Cue.lineInterpretation);
shaka.text.Cue.lineAlign={CENTER:"center",START:"start",END:"end"};goog.exportProperty(shaka.text.Cue,"lineAlign",shaka.text.Cue.lineAlign);shaka.text.Cue.defaultTextColor={white:"white",lime:"lime",cyan:"cyan",red:"red",yellow:"yellow",magenta:"magenta",blue:"blue",black:"black"};goog.exportProperty(shaka.text.Cue,"defaultTextColor",shaka.text.Cue.defaultTextColor);
shaka.text.Cue.defaultTextBackgroundColor={bg_white:"white",bg_lime:"lime",bg_cyan:"cyan",bg_red:"red",bg_yellow:"yellow",bg_magenta:"magenta",bg_blue:"blue",bg_black:"black"};goog.exportProperty(shaka.text.Cue,"defaultTextBackgroundColor",shaka.text.Cue.defaultTextBackgroundColor);shaka.text.Cue.fontWeight={NORMAL:400,BOLD:700};goog.exportProperty(shaka.text.Cue,"fontWeight",shaka.text.Cue.fontWeight);shaka.text.Cue.fontStyle={NORMAL:"normal",ITALIC:"italic",OBLIQUE:"oblique"};
goog.exportProperty(shaka.text.Cue,"fontStyle",shaka.text.Cue.fontStyle);shaka.text.Cue.textDecoration={UNDERLINE:"underline",LINE_THROUGH:"lineThrough",OVERLINE:"overline"};goog.exportProperty(shaka.text.Cue,"textDecoration",shaka.text.Cue.textDecoration);shaka.text.Cue.timeFormat_=/(?:(\d{1,}):)?(\d{2}):(\d{2})\.(\d{2,3})/g;shaka.util.IDestroyable=class{destroy(){}};shaka.transmuxer={};
shaka.transmuxer.TransmuxerEngine=class{destroy(){}static registerTransmuxer(a,b,c){const d=shaka.transmuxer.TransmuxerEngine;a=d.normalizeMimeType_(a);d.transmuxerMap_.set(a+"-"+c,{priority:c,plugin:b})}static unregisterTransmuxer(a,b){const c=shaka.transmuxer.TransmuxerEngine;a=c.normalizeMimeType_(a);c.transmuxerMap_.delete(a+"-"+b)}static findTransmuxer(a,b){const c=shaka.transmuxer.TransmuxerEngine,d=c.normalizeMimeType_(a);var e=[c.PluginPriority.APPLICATION,c.PluginPriority.PREFERRED,c.PluginPriority.PREFERRED_SECONDARY,
c.PluginPriority.FALLBACK];for(const f of e)if(e=c.transmuxerMap_.get(d+"-"+f)){const g=e.plugin(),h=g.isSupported(a,b);g.destroy();if(h)return e.plugin}return null}static normalizeMimeType_(a){return a.toLowerCase().split(";")[0]}static isSupported(a,b){return shaka.transmuxer.TransmuxerEngine.findTransmuxer(a)?!0:!1}static convertCodecs(a,b){var c=shaka.transmuxer.TransmuxerEngine.findTransmuxer(b);if(!c)return b;c=c();a=c.convertCodecs(a,b);c.destroy();return a}};
goog.exportSymbol("shaka.transmuxer.TransmuxerEngine",shaka.transmuxer.TransmuxerEngine);goog.exportProperty(shaka.transmuxer.TransmuxerEngine,"findTransmuxer",shaka.transmuxer.TransmuxerEngine.findTransmuxer);goog.exportProperty(shaka.transmuxer.TransmuxerEngine,"unregisterTransmuxer",shaka.transmuxer.TransmuxerEngine.unregisterTransmuxer);goog.exportProperty(shaka.transmuxer.TransmuxerEngine,"registerTransmuxer",shaka.transmuxer.TransmuxerEngine.registerTransmuxer);
goog.exportProperty(shaka.transmuxer.TransmuxerEngine.prototype,"destroy",shaka.transmuxer.TransmuxerEngine.prototype.destroy);shaka.transmuxer.TransmuxerEngine.transmuxerMap_=new Map;shaka.transmuxer.TransmuxerEngine.PluginPriority={FALLBACK:1,PREFERRED_SECONDARY:2,PREFERRED:3,APPLICATION:4};goog.exportProperty(shaka.transmuxer.TransmuxerEngine,"PluginPriority",shaka.transmuxer.TransmuxerEngine.PluginPriority);shaka.util.MimeUtils=class{static getFullType(a,b){let c=a;b&&!shaka.util.MimeUtils.RAW_FORMATS.includes(a)&&(c+='; codecs="'+b+'"');return c}static getFullTypeWithAllCodecs(a,b){b&&(a+='; codecs="'+b+'"');return a}static getFullOrConvertedType(a,b,c){var d=shaka.util.MimeUtils;const e=d.getFullType(a,b);b=d.getFullTypeWithAllCodecs(a,b);d=shaka.util.ManifestParserUtils.ContentType;const f=shaka.transmuxer.TransmuxerEngine;return f.isSupported(b,c)?f.convertCodecs(c,b):a!="video/mp2t"&&c==d.AUDIO?
e.replace("video","audio"):e}static getExtendedType(a,b,c){const d=[b];shaka.util.MimeUtils.EXTENDED_MIME_PARAMETERS_.forEach((e,f)=>{const g=a[f];f=="codecs"?shaka.util.MimeUtils.RAW_FORMATS.includes(a.mimeType)||d.push('codecs="'+c+'"'):g&&d.push(e+'="'+g+'"')});a.hdr=="PQ"&&d.push('eotf="smpte2084"');return d.join(";")}static getContainerType(a){return a.split(";")[0].split("/")[1]}static splitCodecs(a){return a.split(",")}static getNormalizedCodec(a){var b=shaka.util.MimeUtils.getCodecParts_(a);
a=b[0].toLowerCase();b=b[1].toLowerCase();switch(!0){case a==="mp4a"&&b==="69":case a==="mp4a"&&b==="6b":case a==="mp4a"&&b==="40.34":return"mp3";case a==="mp4a"&&b==="66":case a==="mp4a"&&b==="67":case a==="mp4a"&&b==="68":case a==="mp4a"&&b==="40.2":case a==="mp4a"&&b==="40.02":case a==="mp4a"&&b==="40.5":case a==="mp4a"&&b==="40.05":case a==="mp4a"&&b==="40.29":case a==="mp4a"&&b==="40.42":return"aac";case a==="mp4a"&&b==="a5":case a==="ac3":case a==="ac-3":return"ac-3";case a==="mp4a"&&b==="a6":case a===
"eac3":case a==="ec-3":return"ec-3";case a==="ac-4":return"ac-4";case a==="mp4a"&&b==="b2":return"dtsx";case a==="mp4a"&&b==="a9":return"dtsc";case a==="vp09":case a==="vp9":return"vp9";case a==="avc1":case a==="avc3":return"avc";case a==="hvc1":case a==="hev1":return"hevc";case a==="vvc1":case a==="vvi1":return"vvc";case a==="dvh1":case a==="dvhe":return b&&b.startsWith("05")?"dovi-p5":"dovi-hevc";case a==="dvav":case a==="dva1":return"dovi-avc";case a==="dav1":return"dovi-av1";case a==="dvc1":case a===
"dvi1":return"dovi-vvc";case a==="lvc1":return"lcevc"}return a}static getCodecBase(a){const b=[];for(const c of a.split(","))a=shaka.util.MimeUtils.getCodecParts_(c),b.push(a[0]);return b.sort().join(",")}static getBasicType(a){return a.split(";")[0]}static getCodecs(a){a=a.split(/ *; */);a.shift();return(a=a.find(b=>b.startsWith("codecs=")))?a.split("=")[1].replace(/^"|"$/g,""):""}static isHlsType(a){return a==="application/x-mpegurl"||a==="application/vnd.apple.mpegurl"||a==="audio/x-mpegurl"}static isDashType(a){return a===
"application/dash+xml"||a==="video/vnd.mpeg.dash.mpd"}static getCodecParts_(a){var b=a.split(".");a=b[0];b.shift();b=b.join(".");return[a,b]}};goog.exportSymbol("shaka.util.MimeUtils",shaka.util.MimeUtils);goog.exportProperty(shaka.util.MimeUtils,"getFullTypeWithAllCodecs",shaka.util.MimeUtils.getFullTypeWithAllCodecs);goog.exportProperty(shaka.util.MimeUtils,"getFullType",shaka.util.MimeUtils.getFullType);
shaka.util.MimeUtils.EXTENDED_MIME_PARAMETERS_=(new Map).set("codecs","codecs").set("frameRate","framerate").set("bandwidth","bitrate").set("width","width").set("height","height").set("channelsCount","channels");shaka.util.MimeUtils.CEA608_CLOSED_CAPTION_MIMETYPE="application/cea-608";shaka.util.MimeUtils.CEA708_CLOSED_CAPTION_MIMETYPE="application/cea-708";shaka.util.MimeUtils.RAW_FORMATS=["audio/aac","audio/ac3","audio/ec3","audio/mpeg"];shaka.text.TextEngine=class{constructor(a){this.parser_=null;this.displayer_=a;this.external_=this.segmentRelativeVttTiming_=!1;this.appendWindowStart_=this.timestampOffset_=0;this.appendWindowEnd_=Infinity;this.bufferEnd_=this.bufferStart_=null;this.selectedClosedCaptionId_="";this.modifyCueCallback_=(b,c)=>{};this.closedCaptionsMap_=new Map}static registerParser(a,b){shaka.text.TextEngine.parserMap_.set(a,b)}static unregisterParser(a){shaka.text.TextEngine.parserMap_.delete(a)}static findParser(a){return shaka.text.TextEngine.parserMap_.get(a)}static isTypeSupported(a){return shaka.text.TextEngine.parserMap_.has(a)?
!0:a==shaka.util.MimeUtils.CEA608_CLOSED_CAPTION_MIMETYPE||a==shaka.util.MimeUtils.CEA708_CLOSED_CAPTION_MIMETYPE?!!shaka.media.ClosedCaptionParser.findDecoder():!1}destroy(){this.displayer_=this.parser_=null;this.closedCaptionsMap_.clear();return Promise.resolve()}setDisplayer(a){this.displayer_=a}initParser(a,b,c,d,e){a==shaka.util.MimeUtils.CEA608_CLOSED_CAPTION_MIMETYPE||a==shaka.util.MimeUtils.CEA708_CLOSED_CAPTION_MIMETYPE?this.parser_=null:(a=shaka.text.TextEngine.parserMap_.get(a),goog.asserts.assert(a,
"Text type negotiation should have happened already"),this.parser_=a(),this.parser_.setSequenceMode?this.parser_.setSequenceMode(b):shaka.Deprecate.deprecateFeature(5,"Text parsers w/ setSequenceMode",'Text parsers should have a "setSequenceMode" method!'),this.parser_.setManifestType?this.parser_.setManifestType(e):shaka.Deprecate.deprecateFeature(5,"Text parsers w/ setManifestType",'Text parsers should have a "setManifestType" method!'),this.segmentRelativeVttTiming_=d,this.external_=c)}setModifyCueCallback(a){this.modifyCueCallback_=
a}async appendBuffer(a,b,c,d){goog.asserts.assert(this.parser_,"The parser should already be initialized");await Promise.resolve();if(this.parser_&&this.displayer_)if(b==null||c==null)this.parser_.parseInit(shaka.util.BufferUtils.toUint8(a));else{var e={periodStart:this.external_?0:this.timestampOffset_,segmentStart:b,segmentEnd:c,vttOffset:this.segmentRelativeVttTiming_||this.external_?b:this.timestampOffset_};a=this.parser_.parseMedia(shaka.util.BufferUtils.toUint8(a),e,d,[]);for(const f of a)this.modifyCueCallback_(f,
d||null,e);d=a.filter(f=>f.startTime>=this.appendWindowStart_&&f.startTime<this.appendWindowEnd_);this.displayer_.append(d);this.bufferStart_==null?this.bufferStart_=Math.max(b,this.appendWindowStart_):(goog.asserts.assert(this.bufferEnd_!=null,"There should already be a buffered range end."),goog.asserts.assert(b-this.bufferEnd_<=1,"There should not be a gap in text references >1s"));this.bufferEnd_=Math.min(c,this.appendWindowEnd_)}}async remove(a,b,c=!1){await Promise.resolve();if(!(a>=b)){if(c&&
(this.removeClosedCaptions_(a,b),this.selectedClosedCaptionId_===""))return;this.displayer_&&this.displayer_.remove(a,b)&&(this.bufferStart_==null?goog.asserts.assert(this.bufferEnd_==null,"end must be null if startTime is null"):(goog.asserts.assert(this.bufferEnd_!=null,"end must be non-null if startTime is non-null"),b<=this.bufferStart_||a>=this.bufferEnd_||(a<=this.bufferStart_&&b>=this.bufferEnd_?this.bufferStart_=this.bufferEnd_=null:a<=this.bufferStart_&&b<this.bufferEnd_?this.bufferStart_=
b:a>this.bufferStart_&&b>=this.bufferEnd_?this.bufferEnd_=a:goog.asserts.assert(!1,"removal from the middle is not supported by TextEngine")),this.updateRangesWithClosedCaptions_()))}}setTimestampOffset(a){this.timestampOffset_=a}setAppendWindow(a,b){this.appendWindowStart_=a;this.appendWindowEnd_=b}bufferStart(){return this.bufferStart_}bufferEnd(){return this.bufferEnd_}isBuffered(a){return this.bufferStart_==null||this.bufferEnd_==null?!1:a>=this.bufferStart_&&a<this.bufferEnd_}bufferedAheadOf(a){if(this.bufferEnd_==
null||this.bufferEnd_<a)return 0;goog.asserts.assert(this.bufferStart_!=null,"start should not be null if end is not null");return this.bufferEnd_-Math.max(a,this.bufferStart_)}setSelectedClosedCaptionId(a,b){this.selectedClosedCaptionId_=a;if(a=this.closedCaptionsMap_.get(a))a=a.filter(c=>c.endTime<=b),a.length&&this.displayer_.append(a)}applyVideoTimestampOffsetRecursive_(a,b){a.startTime+=b;a.endTime+=b;for(const c of a.nestedCues)this.applyVideoTimestampOffsetRecursive_(c,b)}storeAndAppendClosedCaptions(a,
b){const c=new Map;for(const d of a){a=d.stream;const e=d.cue;c.has(a)||c.set(a,[]);this.applyVideoTimestampOffsetRecursive_(e,b);e.startTime>=this.appendWindowStart_&&e.startTime<this.appendWindowEnd_&&(c.get(a).push(e),a==this.selectedClosedCaptionId_&&this.displayer_.append([e]))}for(const d of c.keys()){this.closedCaptionsMap_.has(d)||this.closedCaptionsMap_.set(d,[]);for(const e of c.get(d))this.closedCaptionsMap_.get(d).push(e)}this.updateRangesWithClosedCaptions_()}removeClosedCaptions_(a,
b){for(const c of this.closedCaptionsMap_.keys()){let d=this.closedCaptionsMap_.get(c);d=d.filter(e=>e.startTime<a||e.endTime>=b);this.closedCaptionsMap_.set(c,d)}}updateRangesWithClosedCaptions_(){let a=Infinity,b=-Infinity;for(const c of this.closedCaptionsMap_.values())for(const d of c)a=Math.min(a,d.startTime),b=Math.max(b,d.endTime);a!==Infinity&&b!==-Infinity&&(this.bufferStart_=this.bufferStart_==null?Math.max(a,this.appendWindowStart_):Math.min(this.bufferStart_,Math.max(a,this.appendWindowStart_)),
this.bufferEnd_=Math.max(this.bufferEnd_,Math.min(b,this.appendWindowEnd_)))}getNumberOfClosedCaptionChannels(){return this.closedCaptionsMap_.size}getNumberOfClosedCaptionsInChannel(a){return(a=this.closedCaptionsMap_.get(a))?a.length:0}};goog.exportSymbol("shaka.text.TextEngine",shaka.text.TextEngine);goog.exportProperty(shaka.text.TextEngine.prototype,"destroy",shaka.text.TextEngine.prototype.destroy);goog.exportProperty(shaka.text.TextEngine,"findParser",shaka.text.TextEngine.findParser);
goog.exportProperty(shaka.text.TextEngine,"unregisterParser",shaka.text.TextEngine.unregisterParser);goog.exportProperty(shaka.text.TextEngine,"registerParser",shaka.text.TextEngine.registerParser);shaka.text.TextEngine.parserMap_=new Map;shaka.util.Timer=class{constructor(a){this.onTick_=a;this.cancelPending_=null}tickNow(){this.stop();this.onTick_();return this}tickAfter(a){this.stop();this.schedule_(()=>{this.onTick_()},a);return this}tickEvery(a){this.stop();goog.DEBUG&&shaka.util.Timer.activeTimers.set(this,Error("Timer created").stack);this.scheduleRepeating_(a);return this}stop(){this.cancelPending_?.();this.cancelPending_=null;goog.DEBUG&&shaka.util.Timer.activeTimers.delete(this)}schedule_(a,b){let c=!0,d=null;this.cancelPending_=
()=>{clearTimeout(d);c=!1};d=setTimeout(()=>{c&&a()},b*1E3)}scheduleRepeating_(a){this.schedule_(()=>{this.scheduleRepeating_(a);this.onTick_()},a)}};goog.exportSymbol("shaka.util.Timer",shaka.util.Timer);goog.exportProperty(shaka.util.Timer.prototype,"stop",shaka.util.Timer.prototype.stop);goog.exportProperty(shaka.util.Timer.prototype,"tickEvery",shaka.util.Timer.prototype.tickEvery);goog.exportProperty(shaka.util.Timer.prototype,"tickAfter",shaka.util.Timer.prototype.tickAfter);
goog.exportProperty(shaka.util.Timer.prototype,"tickNow",shaka.util.Timer.prototype.tickNow);goog.DEBUG&&(shaka.util.Timer.activeTimers=new Map);shaka.util.Functional=class{static createFallbackPromiseChain(a,b){return a.reduce((c,d)=>c.catch(()=>b(d)),Promise.reject())}static collapseArrays(a,b){return a.concat(b)}static ignored(...a){}static noop(){}static isNotNull(a){return a!=null}static promiseWithTimeout(a,b){return Promise.race([b,new Promise((c,d)=>{(new shaka.util.Timer(d)).tickAfter(a)})])}};shaka.util.LanguageUtils=class{static areLocaleCompatible(a,b){const c=shaka.util.LanguageUtils;a=c.normalize(a);b=c.normalize(b);return a==b}static areLanguageCompatible(a,b){const c=shaka.util.LanguageUtils;a=c.normalize(a);b=c.normalize(b);a=c.disassembleLocale_(a);b=c.disassembleLocale_(b);return a[0]==b[0]}static isParentOf(a,b){const c=shaka.util.LanguageUtils;a=c.normalize(a);b=c.normalize(b);a=c.disassembleLocale_(a);b=c.disassembleLocale_(b);return a[0]==b[0]&&a.length==1&&b.length==2}static isSiblingOf(a,
b){const c=shaka.util.LanguageUtils;a=c.normalize(a);b=c.normalize(b);a=c.disassembleLocale_(a);b=c.disassembleLocale_(b);return a.length==2&&b.length==2&&a[0]==b[0]}static normalize(a){var b=shaka.util.LanguageUtils;const [c="",d=""]=a.split("-x-"),[e="",f=""]=c.split("-");a=d?`${"x-"}${d}`:"";let g=e.toLowerCase();g=b.isoMap_.get(g)||g;b=f.toUpperCase();return`${b?`${g}-${b}`:g}${a?`-${a}`:""}`}static areSiblings(a,b){var c=shaka.util.LanguageUtils;const d=c.getBase(a);c=c.getBase(b);return a!=
d&&b!=c&&d==c}static relatedness(a,b){const c=shaka.util.LanguageUtils;a=c.normalize(a);b=c.normalize(b);return b==a?4:c.isParentOf(b,a)?3:c.isSiblingOf(b,a)?2:c.isParentOf(a,b)?1:0}static getBase(a){const b=shaka.util.LanguageUtils,c=a.indexOf("-");a=c>=0?a.substring(0,c):a;a=a.toLowerCase();return a=b.isoMap_.get(a)||a}static getLocaleForText(a){const b=shaka.util.LanguageUtils;goog.asserts.assert(a.type==shaka.util.ManifestParserUtils.ContentType.TEXT,"Can only get language from text streams");
return b.normalize(a.language||"und")}static getLocaleForVariant(a){const b=shaka.util.LanguageUtils;return a.language?b.normalize(a.language):a.audio&&a.audio.language?b.normalize(a.audio.language):a.video&&a.video.language?b.normalize(a.video.language):"und"}static findClosestLocale(a,b){const c=shaka.util.LanguageUtils;a=c.normalize(a);const d=new Set;for(const e of b)d.add(c.normalize(e));for(const e of d)if(e==a)return e;for(const e of d)if(c.isParentOf(e,a))return e;for(const e of d)if(c.isSiblingOf(e,
a))return e;for(const e of d)if(c.isParentOf(a,e))return e;return null}static disassembleLocale_(a){const b=a.split("-");goog.asserts.assert(b.length<=2,["Locales should not have more than 2 components. ",a," has too many components."].join());return b}};goog.exportSymbol("shaka.util.LanguageUtils",shaka.util.LanguageUtils);goog.exportProperty(shaka.util.LanguageUtils,"findClosestLocale",shaka.util.LanguageUtils.findClosestLocale);
goog.exportProperty(shaka.util.LanguageUtils,"getLocaleForVariant",shaka.util.LanguageUtils.getLocaleForVariant);goog.exportProperty(shaka.util.LanguageUtils,"getLocaleForText",shaka.util.LanguageUtils.getLocaleForText);goog.exportProperty(shaka.util.LanguageUtils,"getBase",shaka.util.LanguageUtils.getBase);goog.exportProperty(shaka.util.LanguageUtils,"relatedness",shaka.util.LanguageUtils.relatedness);goog.exportProperty(shaka.util.LanguageUtils,"areSiblings",shaka.util.LanguageUtils.areSiblings);
goog.exportProperty(shaka.util.LanguageUtils,"normalize",shaka.util.LanguageUtils.normalize);goog.exportProperty(shaka.util.LanguageUtils,"isSiblingOf",shaka.util.LanguageUtils.isSiblingOf);goog.exportProperty(shaka.util.LanguageUtils,"isParentOf",shaka.util.LanguageUtils.isParentOf);goog.exportProperty(shaka.util.LanguageUtils,"areLanguageCompatible",shaka.util.LanguageUtils.areLanguageCompatible);goog.exportProperty(shaka.util.LanguageUtils,"areLocaleCompatible",shaka.util.LanguageUtils.areLocaleCompatible);
shaka.util.LanguageUtils.isoMap_=new Map([["aar","aa"],["abk","ab"],["afr","af"],["aka","ak"],["alb","sq"],["amh","am"],["ara","ar"],["arg","an"],["arm","hy"],["asm","as"],["ava","av"],["ave","ae"],["aym","ay"],["aze","az"],["bak","ba"],["bam","bm"],["baq","eu"],["bel","be"],["ben","bn"],["bih","bh"],["bis","bi"],["bod","bo"],["bos","bs"],["bre","br"],["bul","bg"],["bur","my"],["cat","ca"],["ces","cs"],["cha","ch"],["che","ce"],["chi","zh"],["chu","cu"],["chv","cv"],["cor","kw"],["cos","co"],["cre",
"cr"],["cym","cy"],["cze","cs"],["dan","da"],["deu","de"],["div","dv"],["dut","nl"],["dzo","dz"],["ell","el"],["eng","en"],["epo","eo"],["est","et"],["eus","eu"],["ewe","ee"],["fao","fo"],["fas","fa"],["fij","fj"],["fin","fi"],["fra","fr"],["fre","fr"],["fry","fy"],["ful","ff"],["geo","ka"],["ger","de"],["gla","gd"],["gle","ga"],["glg","gl"],["glv","gv"],["gre","el"],["grn","gn"],["guj","gu"],["hat","ht"],["hau","ha"],["heb","he"],["her","hz"],["hin","hi"],["hmo","ho"],["hrv","hr"],["hun","hu"],["hye",
"hy"],["ibo","ig"],["ice","is"],["ido","io"],["iii","ii"],["iku","iu"],["ile","ie"],["ina","ia"],["ind","id"],["ipk","ik"],["isl","is"],["ita","it"],["jav","jv"],["jpn","ja"],["kal","kl"],["kan","kn"],["kas","ks"],["kat","ka"],["kau","kr"],["kaz","kk"],["khm","km"],["kik","ki"],["kin","rw"],["kir","ky"],["kom","kv"],["kon","kg"],["kor","ko"],["kua","kj"],["kur","ku"],["lao","lo"],["lat","la"],["lav","lv"],["lim","li"],["lin","ln"],["lit","lt"],["ltz","lb"],["lub","lu"],["lug","lg"],["mac","mk"],["mah",
"mh"],["mal","ml"],["mao","mi"],["mar","mr"],["may","ms"],["mkd","mk"],["mlg","mg"],["mlt","mt"],["mon","mn"],["mri","mi"],["msa","ms"],["mya","my"],["nau","na"],["nav","nv"],["nbl","nr"],["nde","nd"],["ndo","ng"],["nep","ne"],["nld","nl"],["nno","nn"],["nob","nb"],["nor","no"],["nya","ny"],["oci","oc"],["oji","oj"],["ori","or"],["orm","om"],["oss","os"],["pan","pa"],["per","fa"],["pli","pi"],["pol","pl"],["por","pt"],["pus","ps"],["que","qu"],["roh","rm"],["ron","ro"],["rum","ro"],["run","rn"],["rus",
"ru"],["sag","sg"],["san","sa"],["sin","si"],["slk","sk"],["slo","sk"],["slv","sl"],["sme","se"],["smo","sm"],["sna","sn"],["snd","sd"],["som","so"],["sot","st"],["spa","es"],["sqi","sq"],["srd","sc"],["srp","sr"],["ssw","ss"],["sun","su"],["swa","sw"],["swe","sv"],["tah","ty"],["tam","ta"],["tat","tt"],["tel","te"],["tgk","tg"],["tgl","tl"],["tha","th"],["tib","bo"],["tir","ti"],["ton","to"],["tsn","tn"],["tso","ts"],["tuk","tk"],["tur","tr"],["twi","tw"],["uig","ug"],["ukr","uk"],["urd","ur"],["uzb",
"uz"],["ven","ve"],["vie","vi"],["vol","vo"],["wel","cy"],["wln","wa"],["wol","wo"],["xho","xh"],["yid","yi"],["yor","yo"],["zha","za"],["zho","zh"],["zul","zu"]]);shaka.util.StreamUtils=class{static chooseCodecsAndFilterManifest(a,b,c,d,e){var f=shaka.util.StreamUtils;const g=shaka.util.MimeUtils;if(e.length){var h=a.textStreams;for(const q of e)if(e=h.filter(p=>p.codecs.startsWith(q)||p.mimeType.startsWith(q)?!0:!1),e.length){h=e;break}a.textStreams=h}h=a.variants;if(b.length||c.length)h=f.choosePreferredCodecs(h,b,c);if(d.length){b=new shaka.util.MultiMap;for(var k of h)b.push(String(k.video.width||0),k);const q=[];b.forEach((p,r)=>{p=0;let t=[];for(const u of r)r=
d.filter(v=>u.decodingInfos[0][v]).length,r>p?(p=r,t=[u]):r==p&&t.push(u);q.push(...t)});h=q}k=new Set;for(var l of h)l.video&&k.add(l.video);if(k.size){var m={vp8:1,avc:1,"dovi-avc":.95,vp9:.9,vp09:.9,hevc:.85,"dovi-hevc":.8,"dovi-p5":.75,av01:.7,"dovi-av1":.65,vvc:.6};b=Array.from(k).sort((q,p)=>q.bandwidth&&p.bandwidth&&q.bandwidth!=p.bandwidth?q.bandwidth-p.bandwidth:q.width!=p.width?q.width-p.width:q.codecs&&p.codecs?(q=g.getNormalizedCodec(q.codecs),p=g.getNormalizedCodec(p.codecs),(m[q]||1)-
(m[p]||1)):0);var n=[];l=new Map;k=q=>{const p=[String(q.width||""),String(q.height||""),String(Math.round(q.frameRate||0)),q.hdr||"",q.fastSwitching];q.dependencyStream&&p.push(q.dependencyStream.baseOriginalId||"");q.roles&&p.push(q.roles.sort().join("_"));return p.join(";")};for(const q of b)b=k(q),c=l.get(b)||[],c.length?(f=g.getNormalizedCodec(c[c.length-1].codecs),e=g.getNormalizedCodec(q.codecs),f==e&&(c.push(q),n.push(q.id))):(c.push(q),n.push(q.id)),l.set(b,c);a.variants=h.filter(q=>{const p=
q.video;return p&&!n.includes(p.id)?(shaka.log.debug("Dropping Variant (better codec available)",q),!1):!0})}else a.variants=h}static choosePreferredCodecs(a,b,c){for(const d of b)if(b=a.filter(e=>e.video&&e.video.codecs.startsWith(d)),b.length){a=b;break}for(const d of c)if(c=a.filter(e=>e.audio&&e.audio.codecs.startsWith(d)),c.length){a=c;break}return a}static filterByRestrictions(a,b,c){a.variants=a.variants.filter(d=>shaka.util.StreamUtils.meetsRestrictions(d,b,c))}static meetsRestrictions(a,
b,c){if(a&&a.video&&a.video.width&&a.video.height){let d=a.video.width,e=a.video.height;e>d&&([d,e]=[e,d]);if(!(d>=b.minWidth&&d<=Math.min(b.maxWidth,c.width)&&e>=b.minHeight&&e<=Math.min(b.maxHeight,c.height)))return!1;c=d*e;if(!(c>=b.minPixels&&c<=b.maxPixels))return!1}if(a&&a.video&&a.video.frameRate&&(c=a.video.frameRate,!(c>=b.minFrameRate&&c<=b.maxFrameRate))||a&&a.audio&&a.audio.channelsCount&&(c=a.audio.channelsCount,!(c>=b.minChannelsCount&&c<=b.maxChannelsCount)))return!1;a=a.bandwidth;
return a>=b.minBandwidth&&a<=b.maxBandwidth?!0:!1}static applyRestrictions(a,b,c){let d=!1;for(const e of a)a=e.allowedByApplication,e.allowedByApplication=shaka.util.StreamUtils.meetsRestrictions(e,b,c),a!=e.allowedByApplication&&(d=!0);return d}static async filterManifest(a,b,c=[],d={}){await shaka.util.StreamUtils.filterManifestByMediaCapabilities(a,b,b.offlineSessionIds.length>0,c,d);shaka.util.StreamUtils.filterTextStreams_(b);await shaka.util.StreamUtils.filterImageStreams_(b)}static async filterManifestByMediaCapabilities(a,
b,c,d,e){goog.asserts.assert(navigator.mediaCapabilities,"MediaCapabilities should be valid.");shaka.device.DeviceFactory.getDevice().shouldOverrideDolbyVisionCodecs()&&shaka.util.StreamUtils.overrideDolbyVisionCodecs(b.variants);await shaka.util.StreamUtils.getDecodingInfosForVariants(b.variants,c,!1,d);let f=null;a&&(a=a.getDrmInfo())&&(f=a.keySystem);const g=shaka.util.StreamUtils;b.variants=b.variants.filter(h=>{const k=g.checkVariantSupported_(h,f,e);k||shaka.log.debug("Dropping variant - not compatible with platform",
g.getVariantSummaryString_(h));return k})}static overrideDolbyVisionCodecs(a){const b=(new Map).set("dvav","avc3").set("dva1","avc1").set("dvhe","hev1").set("dvh1","hvc1").set("dvc1","vvc1").set("dvi1","vvi1"),c=new Set;for(const d of a)d.video&&c.add(d.video);for(const d of c)for(const [e,f]of b)if(d.codecs.includes(e)){d.codecs=d.codecs.replace(e,f);break}}static checkVariantSupported_(a,b,c){if(!a.decodingInfos.some(k=>!k.supported||b&&(k=k.keySystemAccess)&&(c[k.keySystem]||k.keySystem)!=b?!1:
!0))return!1;var d=shaka.device.DeviceFactory.getDevice(),e=d.getDeviceName()==="Xbox";d=d.getDeviceType()===shaka.device.IDevice.DeviceType.MOBILE&&d.getBrowserEngine()===shaka.device.IDevice.BrowserEngine.GECKO;const f=a.video,g=f&&f.width||0,h=f&&f.height||0;if(e&&f&&(g>1920||h>1080)&&(f.codecs.includes("avc1.")||f.codecs.includes("avc3."))||(e=f&&f.dependencyStream)&&!shaka.lcevc.Dec.isStreamSupported(e))return!1;a=a.audio;return d&&a&&a.encrypted&&a.codecs.toLowerCase().includes("opus")||a&&
a.dependencyStream?!1:!0}static async getDecodingInfosForVariant_(a,b){const c=(g,h)=>{if(g){const k=shaka.util.ObjectUtils.shallowCloneObject(g);k.supported=g.supported&&h.supported;k.powerEfficient=g.powerEfficient&&h.powerEfficient;k.smooth=g.smooth&&h.smooth;h.keySystemAccess&&!k.keySystemAccess&&(k.keySystemAccess=h.keySystemAccess);return k}return h},d=shaka.util.StreamUtils;let e=null;const f=[];for(const g of b){const h=shaka.util.ObjectUtils.alphabeticalKeyOrderStringify(g),k=d.decodingConfigCache_;
k.has(h)?(shaka.log.v2("Using cached results of mediaCapabilities.decodingInfo","for key",h),e=c(e,k.get(h))):f.push(d.checkEachDecodingConfigCombination_(g).then(l=>{let m=null;for(const n of l||[])m=c(m,n);m&&(k.set(h,m),e=c(e,m))}))}await Promise.all(f);e&&a.decodingInfos.push(e)}static checkEachDecodingConfigCombination_(a){var b=[""];a.video&&(b=shaka.util.MimeUtils.getCodecs(a.video.contentType).split(","));let c=[""];a.audio&&(c=shaka.util.MimeUtils.getCodecs(a.audio.contentType).split(","));
const d=[];for(const e of b)for(const f of c){const g=shaka.util.ObjectUtils.cloneObject(a);a.video&&(b=shaka.util.MimeUtils.getBasicType(g.video.contentType),g.video.contentType=shaka.util.MimeUtils.getFullType(b,e));a.audio&&(b=shaka.util.MimeUtils.getBasicType(g.audio.contentType),g.audio.contentType=shaka.util.MimeUtils.getFullType(b,f));d.push(new Promise((h,k)=>{(shaka.device.DeviceFactory.getDevice().getDeviceType()==shaka.device.IDevice.DeviceType.MOBILE?shaka.util.Functional.promiseWithTimeout(5,
navigator.mediaCapabilities.decodingInfo(g)):navigator.mediaCapabilities.decodingInfo(g)).then(l=>{h(l)}).catch(k)}))}return Promise.all(d).catch(e=>{shaka.log.info("MediaCapabilities.decodingInfo() failed.",JSON.stringify(a),e);return null})}static async getDecodingInfosForVariants(a,b,c,d){if(a.some(e=>e.decodingInfos.length))shaka.log.debug("Already got the variants' decodingInfo.");else{for(const e of d){let f=!1;for(const g of a){const h=shaka.util.StreamUtils.getDecodingConfigs_(g,b,c).filter(k=>
{k=k[0];k=k.keySystemConfiguration&&k.keySystemConfiguration.keySystem;return!k||k===e});for(const k of h)await shaka.util.StreamUtils.getDecodingInfosForVariant_(g,k);g.decodingInfos.some(k=>k.supported)&&(f=!0)}if(f)return}for(const e of a){a=shaka.util.StreamUtils.getDecodingConfigs_(e,b,c).filter(f=>{f=f[0];f=f.keySystemConfiguration&&f.keySystemConfiguration.keySystem;return!f||!d.includes(f)});for(const f of a)await shaka.util.StreamUtils.getDecodingInfosForVariant_(e,f)}}}static getDecodingConfigs_(a,
b,c){const d=a.audio,e=a.video;var f=shaka.util.ManifestParserUtils.ContentType,g=shaka.util.ManifestParserUtils;const h=shaka.util.MimeUtils,k=shaka.util.StreamUtils;var l=[],m=[];if(e)for(var n of e.fullMimeTypes){var q=h.getCodecs(n);if(q.includes(",")&&!d){var p=q.split(","),r=h.getBasicType(n);q=g.guessCodecs(f.VIDEO,p);p=g.guessCodecs(f.AUDIO,p);p=k.getCorrectAudioCodecs(p,r);r=h.getFullOrConvertedType(r,p,f.AUDIO);m.push({contentType:r,channels:2,bitrate:a.bandwidth||1,samplerate:1,spatialRendering:!1})}q=
k.getCorrectVideoCodecs(q);q={contentType:h.getFullOrConvertedType(h.getBasicType(n),q,f.VIDEO),width:e.width||64,height:e.height||64,bitrate:e.bandwidth||a.bandwidth||1,framerate:e.frameRate||30};if(e.hdr)switch(e.hdr){case "PQ":q.transferFunction="pq";break;case "HLG":q.transferFunction="hlg"}e.colorGamut&&(q.colorGamut=e.colorGamut);l.push(q)}if(d)for(const x of d.fullMimeTypes)g=h.getBasicType(x),n=k.getCorrectAudioCodecs(h.getCodecs(x),g),g=h.getFullOrConvertedType(g,n,f.AUDIO),m.push({contentType:g,
channels:d.channelsCount||2,bitrate:d.bandwidth||a.bandwidth||1,samplerate:d.audioSamplingRate||1,spatialRendering:d.spatialAudio});f=[];l.length==0&&l.push(null);m.length==0&&m.push(null);for(var t of l)for(var u of m)l={type:c?"file":"media-source"},t&&(l.video=t),u&&(l.audio=u),f.push(l);m=(a.video?a.video.drmInfos:[]).concat(a.audio?a.audio.drmInfos:[]);if(!m.length)return[f];a=[];c=new Map;for(var v of m)c.get(v.keySystem)||c.set(v.keySystem,[]),c.get(v.keySystem).push(v);v=b?"required":"optional";
b=b?["persistent-license"]:["temporary"];for(const x of c.keys()){t=c.get(x);m=new Map;for(const y of t)t=`${y.videoRobustness},${y.audioRobustness}`,m.get(t)||m.set(t,[]),m.get(t).push(y);for(const y of m.values()){m=[];for(const A of f){t=Object.assign({},A);u={keySystem:x,initDataType:"cenc",persistentState:v,distinctiveIdentifier:"optional",sessionTypes:b};for(const w of y){if(w.initData&&w.initData.length){l=new Set;for(const z of w.initData)l.add(z.initDataType);l.size>1&&shaka.log.v2("DrmInfo contains more than one initDataType,",
"and we use the initDataType of the first initData.",w);u.initDataType=w.initData[0].initDataType}w.distinctiveIdentifierRequired&&(u.distinctiveIdentifier="required");w.persistentStateRequired&&(u.persistentState="required");w.sessionType&&(u.sessionTypes=[w.sessionType]);d&&(u.audio?(w.encryptionScheme&&(u.audio.encryptionScheme=u.audio.encryptionScheme||w.encryptionScheme),u.audio.robustness=u.audio.robustness||w.audioRobustness):(u.audio={robustness:w.audioRobustness},w.encryptionScheme&&(u.audio.encryptionScheme=
w.encryptionScheme)),u.audio.robustness==""&&delete u.audio.robustness);e&&(u.video?(w.encryptionScheme&&(u.video.encryptionScheme=u.video.encryptionScheme||w.encryptionScheme),u.video.robustness=u.video.robustness||w.videoRobustness):(u.video={robustness:w.videoRobustness},w.encryptionScheme&&(u.video.encryptionScheme=w.encryptionScheme)),u.video.robustness==""&&delete u.video.robustness)}t.keySystemConfiguration=u;m.push(t)}a.push(m)}}return a}static getCorrectAudioCodecs(a,b){const c=shaka.device.DeviceFactory.getDevice(),
d=shaka.device.IDevice.BrowserEngine.WEBKIT;return a.toLowerCase()=="flac"?c.getBrowserEngine()!=d?"flac":"fLaC":a.toLowerCase()==="opus"?c.getBrowserEngine()!=d?"opus":shaka.util.MimeUtils.getContainerType(b)=="mp4"?"Opus":"opus":a.toLowerCase()=="ac-3"&&c.requiresEC3InitSegments()?"ec-3":a}static getCorrectVideoCodecs(a){if(a.includes("avc1")){const b=a.split(".");if(b.length==3)return a=b.shift()+".",a+=parseInt(b.shift(),10).toString(16),a+=("000"+parseInt(b.shift(),10).toString(16)).slice(-4)}else if(a==
"vp9")return"vp09.00.41.08";return a}static filterManifestByCurrentVariant(a,b){const c=shaka.util.StreamUtils;b.variants=b.variants.filter(d=>{const e=d.audio;d=d.video;return e&&a&&a.audio&&!c.areStreamsCompatible_(e,a.audio)?(shaka.log.debug("Dropping variant - not compatible with active audio","active audio",c.getStreamSummaryString_(a.audio),"variant.audio",c.getStreamSummaryString_(e)),!1):d&&a&&a.video&&!c.areStreamsCompatible_(d,a.video)?(shaka.log.debug("Dropping variant - not compatible with active video",
"active video",c.getStreamSummaryString_(a.video),"variant.video",c.getStreamSummaryString_(d)),!1):!0})}static filterTextStreams_(a){a.textStreams=a.textStreams.filter(b=>{var c=shaka.util.MimeUtils.getFullType(b.mimeType,b.codecs);(c=shaka.text.TextEngine.isTypeSupported(c))||shaka.log.debug("Dropping text stream. Is not supported by the platform.",b);return c})}static async filterImageStreams_(a){const b=[];for(const d of a.imageStreams){let e=d.mimeType;e=="application/mp4"&&d.codecs=="mjpg"&&
(e="image/jpg");if(!shaka.util.StreamUtils.supportedImageMimeTypes_.has(e)){var c=shaka.util.StreamUtils.minImage_.get(e);c?(c=await shaka.util.StreamUtils.isImageSupported_(c),shaka.util.StreamUtils.supportedImageMimeTypes_.set(e,c)):shaka.util.StreamUtils.supportedImageMimeTypes_.set(e,!1)}shaka.util.StreamUtils.supportedImageMimeTypes_.get(e)?b.push(d):shaka.log.debug("Dropping image stream. Is not supported by the platform.",d)}a.imageStreams=b}static isImageSupported_(a){return new Promise(b=>
{const c=new Image;c.src=a;"decode"in c?c.decode().then(()=>{b(!0)}).catch(()=>{b(!1)}):c.onload=c.onerror=()=>{b(c.height===2)}})}static areStreamsCompatible_(a,b){return a.mimeType!=b.mimeType||a.codecs.split(".")[0]!=b.codecs.split(".")[0]?!1:!0}static variantToTrack(a){var b=shaka.util.ManifestParserUtils;const c=shaka.util.ManifestParserUtils.ContentType;var d=a.audio;const e=a.video;var f=d?d.mimeType:null,g=e?e.mimeType:null;const h=d?d.codecs:null,k=e?e.codecs:null,l=d?d.groupId:null;var m=
[];e&&m.push(e.mimeType);d&&m.push(d.mimeType);m=m[0]||null;var n=[];d&&n.push(d.kind);e&&n.push(e.kind);n=n[0]||null;const q=new Set;if(d)for(const p of d.roles)q.add(p);if(e)for(const p of e.roles)q.add(p);a={id:a.id,active:!1,type:"variant",bandwidth:a.bandwidth,language:a.language,label:null,videoLabel:null,kind:n,width:null,height:null,frameRate:null,pixelAspectRatio:null,hdr:null,colorGamut:null,videoLayout:null,mimeType:m,audioMimeType:f,videoMimeType:g,codecs:"",audioCodec:h,videoCodec:k,
primary:a.primary,roles:Array.from(q),audioRoles:null,videoRoles:null,forced:!1,videoId:null,audioId:null,audioGroupId:l,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,tilesLayout:null,audioBandwidth:null,videoBandwidth:null,originalVideoId:null,originalAudioId:null,originalTextId:null,originalImageId:null,accessibilityPurpose:null,originalLanguage:null};if(e){a.videoId=e.id;a.originalVideoId=e.originalId;a.width=e.width||null;a.height=e.height||null;a.frameRate=e.frameRate||null;a.pixelAspectRatio=
e.pixelAspectRatio||null;a.videoBandwidth=e.bandwidth||null;a.hdr=e.hdr||null;a.colorGamut=e.colorGamut||null;a.videoLayout=e.videoLayout||null;a.videoRoles=e.roles;a.videoLabel=e.label;if(f=e.dependencyStream)a.width=f.width||a.width,a.height=f.height||a.height,a.videoCodec=f.codecs||a.videoCodec,a.pixelAspectRatio=f.pixelAspectRatio||a.pixelAspectRatio,a.videoBandwidth&&f.bandwidth&&(a.videoBandwidth+=f.bandwidth);if(k.includes(",")){a.channelsCount=e.channelsCount;a.audioSamplingRate=e.audioSamplingRate;
a.spatialAudio=e.spatialAudio;a.originalLanguage=e.originalLanguage;a.audioMimeType=g;g=k.split(",");try{a.videoCodec=b.guessCodecs(c.VIDEO,g),a.audioCodec=b.guessCodecs(c.AUDIO,g)}catch(p){}}}d&&(a.audioId=d.id,a.originalAudioId=d.originalId,a.channelsCount=d.channelsCount,a.audioSamplingRate=d.audioSamplingRate,a.audioBandwidth=d.bandwidth||null,a.spatialAudio=d.spatialAudio,a.label=d.label,a.audioRoles=d.roles,a.accessibilityPurpose=d.accessibilityPurpose,a.originalLanguage=d.originalLanguage,
b=d.dependencyStream)&&(a.audioCodec=b.codecs||a.audioCodec,a.audioBandwidth&&b.bandwidth&&(a.audioBandwidth+=b.bandwidth));e&&!a.videoBandwidth&&(d?a.audioBandwidth&&(a.videoBandwidth=a.bandwidth-a.audioBandwidth):a.videoBandwidth=a.bandwidth);d&&!a.audioBandwidth&&(e?a.videoBandwidth&&(a.audioBandwidth=a.bandwidth-a.videoBandwidth):a.audioBandwidth=a.bandwidth);d=[];a.videoCodec&&d.push(a.videoCodec);a.audioCodec&&d.push(a.audioCodec);a.codecs=d.join(", ");return a}static textStreamToTrack(a){return{id:a.id,
active:!1,type:shaka.util.ManifestParserUtils.ContentType.TEXT,bandwidth:a.bandwidth||0,language:a.language,label:a.label,kind:a.kind||null,mimeType:a.mimeType,codecs:a.codecs||null,primary:a.primary,roles:a.roles,accessibilityPurpose:a.accessibilityPurpose,forced:a.forced,originalTextId:a.originalId,originalLanguage:a.originalLanguage}}static imageStreamToTrack(a){const b=shaka.util.ManifestParserUtils.ContentType;let c=a.width||null,d=a.height||null,e=null;a.segmentIndex&&(e=a.segmentIndex.earliestReference());
let f=a.tilesLayout;e&&(f=e.getTilesLayout()||f);f&&c!=null&&(c/=Number(f.split("x")[0]));f&&d!=null&&(d/=Number(f.split("x")[1]));return{id:a.id,type:b.IMAGE,bandwidth:a.bandwidth||0,width:c,height:d,mimeType:a.mimeType,codecs:a.codecs||null,tilesLayout:f||null,originalImageId:a.originalId}}static html5TrackId(a){a.__shaka_id||(a.__shaka_id=shaka.util.StreamUtils.nextTrackId_++);return a.__shaka_id}static html5TextTrackToTrack(a){var b=shaka.util.ManifestParserUtils.ContentType;b={id:shaka.util.StreamUtils.html5TrackId(a),
active:a.mode!="disabled",type:b.TEXT,bandwidth:0,language:shaka.util.LanguageUtils.normalize(a.language||"und"),label:a.label,kind:a.kind,mimeType:null,codecs:null,primary:!1,roles:[],accessibilityPurpose:null,forced:a.kind=="forced",originalTextId:a.id,originalLanguage:a.language};a.kind=="captions"&&(b.mimeType="unknown");a.kind=="subtitles"&&(b.mimeType="text/vtt");a.kind&&(b.roles=[a.kind]);return b}static html5AudioTrackToTrack(a){var b=a.language;b={active:a.enabled,language:shaka.util.LanguageUtils.normalize(b||
"und"),label:a.label,mimeType:null,codecs:null,primary:a.kind=="main",roles:[],accessibilityPurpose:null,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,originalLanguage:b};a.kind&&(a.kind=="description"&&(b.accessibilityPurpose=shaka.media.ManifestParser.AccessibilityPurpose.VISUALLY_IMPAIRED),b.roles.push(a.kind));a.configuration&&(a.configuration.codec&&(b.codecs=a.configuration.codec),a.configuration.sampleRate&&(b.audioSamplingRate=a.configuration.sampleRate),a.configuration.numberOfChannels&&
(b.channelsCount=a.configuration.numberOfChannels));return b}static html5TrackToShakaTrack(a,b){goog.asserts.assert(a||b,"There must be at least audioTrack or videoTrack.");var c=shaka.util.LanguageUtils;const d=a?a.language:null;c={id:shaka.util.StreamUtils.html5TrackId(a||b),active:a?a.enabled:b.selected,type:"variant",bandwidth:0,language:c.normalize(d||"und"),label:a?a.label:null,videoLabel:null,kind:a?a.kind:null,width:null,height:null,frameRate:null,pixelAspectRatio:null,hdr:null,colorGamut:null,
videoLayout:null,mimeType:null,audioMimeType:null,videoMimeType:null,codecs:null,audioCodec:null,videoCodec:null,primary:a?a.kind=="main":!1,roles:[],forced:!1,audioRoles:null,videoRoles:null,videoId:null,audioId:null,audioGroupId:null,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,tilesLayout:null,audioBandwidth:null,videoBandwidth:null,originalVideoId:b?b.id:null,originalAudioId:a?a.id:null,originalTextId:null,originalImageId:null,accessibilityPurpose:null,originalLanguage:d};a&&a.kind&&
(c.roles=[a.kind],c.audioRoles=[a.kind]);a&&a.configuration&&(a.configuration.codec&&(c.audioCodec=a.configuration.codec,c.codecs=c.audioCodec),a.configuration.bitrate&&(c.audioBandwidth=a.configuration.bitrate,c.bandwidth+=c.audioBandwidth),a.configuration.sampleRate&&(c.audioSamplingRate=a.configuration.sampleRate),a.configuration.numberOfChannels&&(c.channelsCount=a.configuration.numberOfChannels));if(b&&b.configuration&&(b.configuration.codec&&(c.videoCodec=b.configuration.codec,c.codecs=c.codecs?
c.codecs+(","+c.videoCodec):c.videoCodec),b.configuration.bitrate&&(c.videoBandwidth=b.configuration.bitrate,c.bandwidth+=c.videoBandwidth),b.configuration.framerate&&(c.frameRate=b.configuration.framerate),b.configuration.width&&(c.width=b.configuration.width),b.configuration.height&&(c.height=b.configuration.height),b.configuration.colorSpace&&b.configuration.colorSpace.transfer))switch(b.configuration.colorSpace.transfer){case "pq":c.hdr="PQ";break;case "hlg":c.hdr="HLG";break;case "bt709":c.hdr=
"SDR"}return c}static isPlayable(a){return a.allowedByApplication&&a.allowedByKeySystem&&a.disabledUntilTime==0}static getPlayableVariants(a){return a.filter(b=>shaka.util.StreamUtils.isPlayable(b))}static filterStreamsByLanguageAndRole(a,b,c,d){const e=shaka.util.LanguageUtils;let f=a;const g=a.filter(k=>k.primary);g.length&&(f=g);const h=f.length?f[0].language:"";f=f.filter(k=>k.language==h);if(b){const k=e.findClosestLocale(e.normalize(b),a.map(l=>l.language));k&&(f=a.filter(l=>e.normalize(l.language)==
k))}f=f.filter(k=>k.forced==d);if(c){a=shaka.util.StreamUtils.filterStreamsByRole_(f,c);if(a.length)return a;shaka.log.warning("No exact match for the text role could be found.")}else if(a=f.filter(k=>k.roles.length==0),a.length)return a;a=f.map(k=>k.roles).reduce(shaka.util.Functional.collapseArrays,[]);return a.length?shaka.util.StreamUtils.filterStreamsByRole_(f,a[0]):f}static filterStreamsByRole_(a,b){return a.filter(c=>c.roles.includes(b))}static isAudio(a){return a.type==shaka.util.ManifestParserUtils.ContentType.AUDIO}static isVideo(a){return a.type==
shaka.util.ManifestParserUtils.ContentType.VIDEO}static getVariantStreams(a){const b=[];a.audio&&b.push(a.audio);a.video&&b.push(a.video);return b}static isFastSwitching(a){return a.audio&&a.audio.fastSwitching||a.video&&a.video.fastSwitching?!0:!1}static setBetterIFrameStream(a,b){b.length&&(b=b.filter(c=>shaka.util.MimeUtils.getNormalizedCodec(a.codecs)==shaka.util.MimeUtils.getNormalizedCodec(c.codecs)).sort((c,d)=>c.bandwidth&&d.bandwidth&&c.bandwidth!=d.bandwidth?c.bandwidth-d.bandwidth:(c.width||
0)-(d.width||0)),a.trickModeVideo=b[0],b.length>1&&(b=b.find(c=>a.width==c.width&&a.height==c.height)))&&(a.trickModeVideo=b)}static getVariantSummaryString_(a){const b=[];a.audio&&b.push(shaka.util.StreamUtils.getStreamSummaryString_(a.audio));a.video&&b.push(shaka.util.StreamUtils.getStreamSummaryString_(a.video));return b.join(", ")}static getStreamSummaryString_(a){return shaka.util.StreamUtils.isAudio(a)?"type=audio codecs="+a.codecs+" bandwidth="+a.bandwidth+" channelsCount="+a.channelsCount+
" audioSamplingRate="+a.audioSamplingRate:shaka.util.StreamUtils.isVideo(a)?"type=video codecs="+a.codecs+" bandwidth="+a.bandwidth+" frameRate="+a.frameRate+" width="+a.width+" height="+a.height:"unexpected stream type"}static clearDecodingConfigCache(){shaka.util.StreamUtils.decodingConfigCache_.clear()}static shouldInitiallyShowText(a,b,c){const d=shaka.config.AutoShowText;if(c.autoShowText==d.NEVER)return!1;if(c.autoShowText==d.ALWAYS)return!0;const e=shaka.util.LanguageUtils,f=e.normalize(c.preferredTextLanguage);
b=e.normalize(b.language);if(c.autoShowText==d.IF_PREFERRED_TEXT_LANGUAGE)return e.areLanguageCompatible(b,f);if(c.autoShowText==d.IF_SUBTITLES_MAY_BE_NEEDED){if(!a)return!1;a=e.normalize(a.language);return e.areLanguageCompatible(b,f)&&!e.areLanguageCompatible(a,b)}shaka.log.alwaysWarn("Invalid autoShowText setting!");return!1}static createEmptyVariant(a){const b=shaka.util.ManifestParserUtils.ContentType,c={id:0,language:"und",disabledUntilTime:0,primary:!1,audio:null,video:null,bandwidth:100,allowedByApplication:!0,
allowedByKeySystem:!0,decodingInfos:[]};for(const d of a)a={id:0,originalId:null,groupId:null,createSegmentIndex:()=>Promise.resolve(),segmentIndex:null,mimeType:d?shaka.util.MimeUtils.getBasicType(d):"",codecs:d?shaka.util.MimeUtils.getCodecs(d):"",encrypted:!0,drmInfos:[],keyIds:new Set,language:"und",originalLanguage:null,label:null,type:b.VIDEO,primary:!1,trickModeVideo:null,dependencyStream:null,emsgSchemeIdUris:null,roles:[],forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,
closedCaptions:null,accessibilityPurpose:null,external:!1,fastSwitching:!1,fullMimeTypes:new Set,isAudioMuxedInVideo:!1,baseOriginalId:null},a.fullMimeTypes.add(shaka.util.MimeUtils.getFullType(a.mimeType,a.codecs)),d.startsWith("audio/")?(a.type=b.AUDIO,c.audio=a):c.video=a;return c}};goog.exportSymbol("shaka.util.StreamUtils",shaka.util.StreamUtils);goog.exportProperty(shaka.util.StreamUtils,"meetsRestrictions",shaka.util.StreamUtils.meetsRestrictions);
shaka.util.StreamUtils.decodingConfigCache_=new Map;shaka.util.StreamUtils.nextTrackId_=0;shaka.util.StreamUtils.DecodingAttributes={SMOOTH:"smooth",POWER:"powerEfficient"};shaka.util.StreamUtils.supportedImageMimeTypes_=(new Map).set("image/svg+xml",!0).set("image/png",!0).set("image/jpeg",!0).set("image/jpg",!0);shaka.util.StreamUtils.minWebPImage_="data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";
shaka.util.StreamUtils.minAvifImage_="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A=";
shaka.util.StreamUtils.minImage_=(new Map).set("image/webp",shaka.util.StreamUtils.minWebPImage_).set("image/avif",shaka.util.StreamUtils.minAvifImage_);shaka.abr.SimpleAbrManager=class{constructor(){this.switch_=null;this.enabled_=!1;this.bandwidthEstimator_=new shaka.abr.EwmaBandwidthEstimator;this.eventManager_=new shaka.util.EventManager;navigator.connection&&navigator.connection.addEventListener&&this.eventManager_.listen(navigator.connection,"change",()=>{this.config_.useNetworkInformation&&navigator.onLine&&(this.bandwidthEstimator_=new shaka.abr.EwmaBandwidthEstimator,this.config_&&this.bandwidthEstimator_.configure(this.config_.advanced),
this.trySuggestStreams())});this.variants_=[];this.playbackRate_=1;this.startupComplete_=!1;this.resizeObserver_=this.mediaElement_=this.config_=this.lastTimeChosenMs_=null;this.resizeObserverTimer_=new shaka.util.Timer(()=>{if(this.enabled_&&(this.config_.restrictToElementSize||this.config_.restrictToScreenSize)){const a=this.chooseVariant();a&&this.switch_&&this.switch_(a,this.config_.clearBufferSwitch,this.config_.safeMarginSwitch)}});this.windowToCheck_=window;"documentPictureInPicture"in window&&
this.eventManager_.listen(window.documentPictureInPicture,"enter",()=>{this.windowToCheck_=window.documentPictureInPicture.window;this.resizeObserverTimer_&&this.resizeObserverTimer_.tickNow();this.eventManager_.listenOnce(this.windowToCheck_,"pagehide",()=>{this.windowToCheck_=window;this.resizeObserverTimer_&&this.resizeObserverTimer_.tickNow()})});this.cmsdManager_=this.pictureInPictureWindow_=null}stop(){this.switch_=null;this.enabled_=!1;this.variants_=[];this.playbackRate_=1;this.mediaElement_=
this.lastTimeChosenMs_=null;this.resizeObserver_&&(this.resizeObserver_.disconnect(),this.resizeObserver_=null);this.resizeObserverTimer_&&this.resizeObserverTimer_.stop();this.cmsdManager_=this.pictureInPictureWindow_=null}release(){this.stop();this.eventManager_.release();this.resizeObserverTimer_=null}init(a){this.switch_=a}chooseVariant(a=!1){var b=Infinity,c=Infinity;this.config_.restrictToScreenSize&&(c=this.config_.ignoreDevicePixelRatio?1:this.windowToCheck_.devicePixelRatio,b=this.windowToCheck_.screen.height*
c,c*=this.windowToCheck_.screen.width);if(this.resizeObserver_&&this.config_.restrictToElementSize){var d=this.config_.ignoreDevicePixelRatio?1:this.windowToCheck_.devicePixelRatio,e=this.mediaElement_.clientHeight,f=this.mediaElement_.clientWidth;this.pictureInPictureWindow_&&document.pictureInPictureElement&&document.pictureInPictureElement==this.mediaElement_&&(e=this.pictureInPictureWindow_.height,f=this.pictureInPictureWindow_.width);b=Math.min(b,e*d);c=Math.min(c,f*d)}e=this.variants_.filter(k=>
k&&!shaka.util.StreamUtils.isFastSwitching(k));e.length||(e=this.variants_);d=e;a&&e.length!=this.variants_.length&&(d=this.variants_.filter(k=>k&&shaka.util.StreamUtils.isFastSwitching(k)));a=this.filterAndSortVariants_(this.config_.restrictions,d,Infinity,Infinity);if(b!=Infinity||c!=Infinity){a=this.getResolutionList_(a);for(var g of a)if(g.height>=b&&g.width>=c){b=g.height;c=g.width;break}a=this.filterAndSortVariants_(this.config_.restrictions,d,b,c)}b=this.getBandwidthEstimate();d.length&&!a.length&&
(shaka.log.warning("No variants met the ABR restrictions. Choosing a variant by lowest bandwidth."),a=this.filterAndSortVariants_(null,d,Infinity,Infinity),a=[a[0]]);g=a[0]||null;for(c=0;c<a.length;c++){d=a[c];var h=isNaN(this.playbackRate_)?1:Math.abs(this.playbackRate_);e=h*d.bandwidth;f=e/this.config_.bandwidthDowngradeTarget;let k={bandwidth:Infinity};for(let l=c+1;l<a.length;l++)if(d.bandwidth!=a[l].bandwidth){k=a[l];break}h=h*k.bandwidth/this.config_.bandwidthUpgradeTarget;shaka.log.v2("Bandwidth ranges:",
(e/1E6).toFixed(3),(f/1E6).toFixed(3),(h/1E6).toFixed(3));g&&d&&b>=f&&b<=h&&(g.bandwidth!=d.bandwidth||this.isSameBandwidthAndHigherResolution_(g,d))&&(g=d)}this.lastTimeChosenMs_=Date.now();return g}enable(){this.enabled_=!0;this.variants_.length&&this.trySuggestStreams()}disable(){this.enabled_=!1}segmentDownloaded(a,b,c,d,e){e=a;this.config_.removeLatencyFromFirstPacketTime&&d&&d.packetNumber===1&&d.timeToFirstByte&&(e=a-d.timeToFirstByte);e>=this.config_.cacheLoadThreshold&&(shaka.log.v2("Segment downloaded:",
"contentType="+(d&&d.contentType),"deltaTimeMs="+e,"numBytes="+b,"lastTimeChosenMs="+this.lastTimeChosenMs_,"enabled="+this.enabled_),goog.asserts.assert(e>=0,"expected a non-negative duration"),this.bandwidthEstimator_.sample(e,b));c&&this.lastTimeChosenMs_!=null&&this.enabled_&&this.suggestStreams_()}trySuggestStreams(){this.enabled_&&(this.lastTimeChosenMs_=Date.now(),this.suggestStreams_(!0))}getBandwidthEstimate(){var a=this.getDefaultBandwidth_();if(navigator.connection&&navigator.connection.downlink&&
this.config_.useNetworkInformation&&this.config_.preferNetworkInformationBandwidth)return a;a=this.bandwidthEstimator_.getBandwidthEstimate(a);return this.cmsdManager_?this.cmsdManager_.getBandwidthEstimate(a):a}setVariants(a){if(shaka.util.ArrayUtils.hasSameElements(a,this.variants_))return!1;this.variants_=a;return!0}playbackRateChanged(a){this.playbackRate_=a}setMediaElement(a){this.mediaElement_=a;this.resizeObserver_&&(this.resizeObserver_.disconnect(),this.resizeObserver_=null);const b=()=>
{this.resizeObserverTimer_.tickAfter(shaka.abr.SimpleAbrManager.RESIZE_OBSERVER_BATCH_TIME)};this.mediaElement_&&"ResizeObserver"in window&&(this.resizeObserver_=new ResizeObserver(b),this.resizeObserver_.observe(this.mediaElement_));this.eventManager_.listen(a,"enterpictureinpicture",c=>{c.pictureInPictureWindow&&(this.pictureInPictureWindow_=c.pictureInPictureWindow,this.eventManager_.listen(this.pictureInPictureWindow_,"resize",b))});this.eventManager_.listen(a,"leavepictureinpicture",()=>{this.pictureInPictureWindow_&&
this.eventManager_.unlisten(this.pictureInPictureWindow_,"resize",b);this.pictureInPictureWindow_=null})}setCmsdManager(a){this.cmsdManager_=a}configure(a){this.config_=a;this.bandwidthEstimator_&&this.config_&&this.bandwidthEstimator_.configure(this.config_.advanced)}suggestStreams_(a=!1){shaka.log.v2("Suggesting Streams...");goog.asserts.assert(this.lastTimeChosenMs_!=null,"lastTimeChosenMs_ should not be null");if(!a){if(!this.startupComplete_){if(!this.bandwidthEstimator_.hasGoodEstimate()){shaka.log.v2("Still waiting for a good estimate...");
return}this.startupComplete_=!0;this.lastTimeChosenMs_-=(this.config_.switchInterval-this.config_.minTimeToSwitch)*1E3}if(Date.now()-this.lastTimeChosenMs_<this.config_.switchInterval*1E3){shaka.log.v2("Still within switch interval...");return}}a=this.chooseVariant();var b=this.getBandwidthEstimate();b=Math.round(b/1E3);a&&this.switch_&&(shaka.log.debug("Calling switch_(), bandwidth="+b+" kbps"),this.switch_(a,this.config_.clearBufferSwitch,this.config_.safeMarginSwitch))}getDefaultBandwidth_(){let a=
this.config_.defaultBandwidthEstimate;navigator.connection&&navigator.connection.downlink&&this.config_.useNetworkInformation&&(a=navigator.connection.downlink*1E6);return a}filterAndSortVariants_(a,b,c,d){if(this.cmsdManager_){const e=this.cmsdManager_.getMaxBitrate();e&&(b=b.filter(f=>f.bandwidth&&e?f.bandwidth<=e:!0))}a&&(b=b.filter(e=>{goog.asserts.assert(a,"Restrictions should exist!");return shaka.util.StreamUtils.meetsRestrictions(e,a,{width:d,height:c})}));return b.sort((e,f)=>e.bandwidth-
f.bandwidth)}getResolutionList_(a){const b=[];for(const c of a){if(!c)continue;(a=c.video)&&a.height&&a.width&&b.push({height:a.height,width:a.width})}return b.sort((c,d)=>c.width-d.width)}isSameBandwidthAndHigherResolution_(a,b){return a.bandwidth==b.bandwidth&&a.video&&b.video?a.video.width<b.video.width||a.video.height<b.video.height:!1}};goog.exportSymbol("shaka.abr.SimpleAbrManager",shaka.abr.SimpleAbrManager);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"configure",shaka.abr.SimpleAbrManager.prototype.configure);
goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"setCmsdManager",shaka.abr.SimpleAbrManager.prototype.setCmsdManager);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"setMediaElement",shaka.abr.SimpleAbrManager.prototype.setMediaElement);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"playbackRateChanged",shaka.abr.SimpleAbrManager.prototype.playbackRateChanged);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"setVariants",shaka.abr.SimpleAbrManager.prototype.setVariants);
goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"getBandwidthEstimate",shaka.abr.SimpleAbrManager.prototype.getBandwidthEstimate);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"trySuggestStreams",shaka.abr.SimpleAbrManager.prototype.trySuggestStreams);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"segmentDownloaded",shaka.abr.SimpleAbrManager.prototype.segmentDownloaded);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"disable",shaka.abr.SimpleAbrManager.prototype.disable);
goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"enable",shaka.abr.SimpleAbrManager.prototype.enable);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"chooseVariant",shaka.abr.SimpleAbrManager.prototype.chooseVariant);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"init",shaka.abr.SimpleAbrManager.prototype.init);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"release",shaka.abr.SimpleAbrManager.prototype.release);
goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"stop",shaka.abr.SimpleAbrManager.prototype.stop);shaka.abr.SimpleAbrManager.RESIZE_OBSERVER_BATCH_TIME=1;shaka.net={};
shaka.net.Backoff=class{constructor(a,b=!1){const c=shaka.net.Backoff.defaultRetryParameters();this.maxAttempts_=a.maxAttempts==null?c.maxAttempts:a.maxAttempts;goog.asserts.assert(this.maxAttempts_>=1,"maxAttempts should be >= 1");this.baseDelay_=a.baseDelay==null?c.baseDelay:a.baseDelay;goog.asserts.assert(this.baseDelay_>=0,"baseDelay should be >= 0");this.fuzzFactor_=a.fuzzFactor==null?c.fuzzFactor:a.fuzzFactor;goog.asserts.assert(this.fuzzFactor_>=0,"fuzzFactor should be >= 0");this.backoffFactor_=
a.backoffFactor==null?c.backoffFactor:a.backoffFactor;goog.asserts.assert(this.backoffFactor_>=0,"backoffFactor should be >= 0");this.numAttempts_=0;this.nextUnfuzzedDelay_=this.baseDelay_;if(this.autoReset_=b)goog.asserts.assert(this.maxAttempts_>=2,"maxAttempts must be >= 2 for autoReset == true"),this.numAttempts_=1}async attempt(){if(this.numAttempts_>=this.maxAttempts_)if(this.autoReset_)this.reset_();else throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,
shaka.util.Error.Code.ATTEMPTS_EXHAUSTED);const a=this.numAttempts_;this.numAttempts_++;if(a==0)goog.asserts.assert(!this.autoReset_,"Failed to delay with auto-reset!");else{var b=shaka.net.Backoff.fuzz_(this.nextUnfuzzedDelay_,this.fuzzFactor_);await new Promise(c=>{shaka.net.Backoff.defer(b,c)});this.nextUnfuzzedDelay_*=this.backoffFactor_}}static defaultRetryParameters(){return{maxAttempts:2,baseDelay:1E3,backoffFactor:2,fuzzFactor:.5,timeout:3E4,stallTimeout:5E3,connectionTimeout:1E4}}static fuzz_(a,
b){return a*(1+(Math.random()*2-1)*b)}reset_(){goog.asserts.assert(this.autoReset_,"Should only be used for auto-reset!");this.numAttempts_=1;this.nextUnfuzzedDelay_=this.baseDelay_}static defer(a,b){(new shaka.util.Timer(b)).tickAfter(a/1E3)}};shaka.util.PublicPromise=class{constructor(){let a,b;const c=new Promise((d,e)=>{a=d;b=e});c.resolve=a;c.reject=b;return c}resolve(a){}reject(a){}};shaka.util.AbortableOperation=class{constructor(a,b){this.promise=a;this.onAbort_=b;this.abortPromise_=null}get aborted(){return this.abortPromise_!==null}static failed(a){return new shaka.util.AbortableOperation(Promise.reject(a),()=>Promise.resolve())}static aborted(){const a=Promise.reject(shaka.util.AbortableOperation.abortError());a.catch(()=>{});return new shaka.util.AbortableOperation(a,()=>Promise.resolve())}static abortError(){return new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.OPERATION_ABORTED)}static completed(a){return new shaka.util.AbortableOperation(Promise.resolve(a),()=>Promise.resolve())}static notAbortable(a){return new shaka.util.AbortableOperation(a,()=>a.catch(()=>{}))}abort(){this.abortPromise_||(this.abortPromise_=this.onAbort_());return this.abortPromise_}static all(a){return new shaka.util.AbortableOperation(Promise.all(a.map(b=>b.promise)),()=>Promise.all(a.map(b=>b.abort())))}finally(a){this.promise.then(b=>
a(!0),b=>a(!1));return this}chain(a,b){const c=new shaka.util.PublicPromise;c.catch(()=>{});const d=shaka.util.AbortableOperation.abortError();let e=()=>{c.reject(d);return this.abort()};const f=g=>h=>{if(this.abortPromise_&&g)c.reject(d);else{var k=g?a:b;k?e=shaka.util.AbortableOperation.wrapChainCallback_(k,h,c):(g?c.resolve:c.reject)(h)}};this.promise.then(f(!0),f(!1));return new shaka.util.AbortableOperation(c,()=>e())}static wrapChainCallback_(a,b,c){try{const d=a(b);if(d&&d.promise&&d.abort)return c.resolve(d.promise),
()=>d.abort();c.resolve(d);return()=>Promise.resolve(d).then(()=>{},()=>{})}catch(d){return c.reject(d),()=>Promise.resolve()}}};goog.exportSymbol("shaka.util.AbortableOperation",shaka.util.AbortableOperation);goog.exportProperty(shaka.util.AbortableOperation.prototype,"chain",shaka.util.AbortableOperation.prototype.chain);goog.exportProperty(shaka.util.AbortableOperation.prototype,"finally",shaka.util.AbortableOperation.prototype.finally);goog.exportProperty(shaka.util.AbortableOperation,"all",shaka.util.AbortableOperation.all);
goog.exportProperty(shaka.util.AbortableOperation.prototype,"abort",shaka.util.AbortableOperation.prototype.abort);goog.exportProperty(shaka.util.AbortableOperation,"notAbortable",shaka.util.AbortableOperation.notAbortable);goog.exportProperty(shaka.util.AbortableOperation,"completed",shaka.util.AbortableOperation.completed);goog.exportProperty(shaka.util.AbortableOperation,"aborted",shaka.util.AbortableOperation.aborted);goog.exportProperty(shaka.util.AbortableOperation,"failed",shaka.util.AbortableOperation.failed);shaka.util.FakeEvent=class{static fromRealEvent(a){const b=new shaka.util.FakeEvent(a.type);for(const c in a)Object.defineProperty(b,c,{value:a[c],writable:!0,enumerable:!0});return b}static recastDictAsObject_(a){goog.asserts.assert(!(a instanceof Map),"dict should not be a map");return a}constructor(a,b){if(b)if(b instanceof Map)for(const c of b.keys())Object.defineProperty(this,c,{value:b.get(c),writable:!0,enumerable:!0});else{b=shaka.util.FakeEvent.recastDictAsObject_(b);for(const c in b)Object.defineProperty(this,
c,{value:b[c],writable:!0,enumerable:!0})}this.defaultPrevented=this.cancelable=this.bubbles=!1;this.timeStamp=window.performance&&window.performance.now?window.performance.now():Date.now();this.type=a;this.isTrusted=!1;this.target=this.currentTarget=null;this.stopped=!1}preventDefault(){this.cancelable&&(this.defaultPrevented=!0)}stopImmediatePropagation(){this.stopped=!0}stopPropagation(){}};goog.exportSymbol("shaka.util.FakeEvent",shaka.util.FakeEvent);
shaka.util.FakeEvent.EventName={AbrStatusChanged:"abrstatuschanged",Adaptation:"adaptation",AudioTrackChanged:"audiotrackchanged",AudioTracksChanged:"audiotrackschanged",BoundaryCrossed:"boundarycrossed",Buffering:"buffering",CanUpdateStartTime:"canupdatestarttime",Complete:"complete",CurrentItemChanged:"currentitemchanged",DownloadCompleted:"downloadcompleted",DownloadFailed:"downloadfailed",DownloadHeadersReceived:"downloadheadersreceived",DrmSessionUpdate:"drmsessionupdate",Emsg:"emsg",ItemsInserted:"itemsinserted",
ItemsRemoved:"itemsremoved",Prft:"prft",Error:"error",ExpirationUpdated:"expirationupdated",FirstQuartile:"firstquartile",GapJumped:"gapjumped",KeyStatusChanged:"keystatuschanged",Loaded:"loaded",Loading:"loading",ManifestParsed:"manifestparsed",ManifestUpdated:"manifestupdated",MediaQualityChanged:"mediaqualitychanged",MediaSourceRecovered:"mediasourcerecovered",MetadataAdded:"metadataadded",Metadata:"metadata",Midpoint:"midpoint",NoSpatialVideoInfoEvent:"nospatialvideoinfo",OnStateChange:"onstatechange",
RateChange:"ratechange",SegmentAppended:"segmentappended",SessionDataEvent:"sessiondata",SpatialVideoInfoEvent:"spatialvideoinfo",StallDetected:"stalldetected",Started:"started",StateChanged:"statechanged",Streaming:"streaming",TextChanged:"textchanged",TextTrackVisibility:"texttrackvisibility",ThirdQuartile:"thirdquartile",TimelineRegionAdded:"timelineregionadded",TimelineRegionEnter:"timelineregionenter",TimelineRegionExit:"timelineregionexit",TracksChanged:"trackschanged",Unloading:"unloading",
VariantChanged:"variantchanged"};shaka.util.FakeEventTarget=class{constructor(){this.listeners_=new shaka.util.MultiMap;this.dispatchTarget=this}addEventListener(a,b,c){this.listeners_&&this.listeners_.push(a,b)}listenToAllEvents(a){this.addEventListener(shaka.util.FakeEventTarget.ALL_EVENTS_,a)}removeEventListener(a,b,c){this.listeners_&&this.listeners_.remove(a,b)}dispatchEvent(a){goog.asserts.assert(a instanceof shaka.util.FakeEvent,"FakeEventTarget can only dispatch FakeEvents!");if(!this.listeners_)return!0;let b=this.listeners_.get(a.type)||
[];const c=this.listeners_.get(shaka.util.FakeEventTarget.ALL_EVENTS_);c&&(b=b.concat(c));for(const d of b){a.target=this.dispatchTarget;a.currentTarget=this.dispatchTarget;try{d.handleEvent?d.handleEvent(a):d.call(this,a)}catch(e){shaka.log.error("Uncaught exception in event handler",e,e?e.message:null,e?e.stack:null)}if(a.stopped)break}return a.defaultPrevented}release(){this.listeners_=null}};shaka.util.FakeEventTarget.ALL_EVENTS_="All";shaka.util.OperationManager=class{constructor(){this.operations_=[]}manage(a){this.operations_.push(a.finally(()=>{shaka.util.ArrayUtils.remove(this.operations_,a)}))}destroy(){const a=[];for(const b of this.operations_)b.promise.catch(()=>{}),a.push(b.abort());this.operations_=[];return Promise.all(a)}};shaka.net.NetworkingEngine=class extends shaka.util.FakeEventTarget{constructor(a,b,c,d,e,f,g){super();this.config_=null;this.destroyed_=!1;this.operationManager_=new shaka.util.OperationManager;this.requestFilters_=new Set;this.responseFilters_=new Set;this.onProgressUpdated_=a||null;this.onHeadersReceived_=b||null;this.onDownloadCompleted_=c||null;this.onDownloadFailed_=d||null;this.onRequest_=e||null;this.onRetry_=f||null;this.onResponse_=g||null;this.hostCommonAccessTokenMap_=new Map}configure(a){this.config_=
a}static registerScheme(a,b,c,d=!1){goog.asserts.assert(c==void 0||c>0,"explicit priority must be > 0");c=c||shaka.net.NetworkingEngine.PluginPriority.APPLICATION;const e=shaka.net.NetworkingEngine.schemes_.get(a);(!e||c>=e.priority)&&shaka.net.NetworkingEngine.schemes_.set(a,{priority:c,plugin:b,progressSupport:d})}static unregisterScheme(a){shaka.net.NetworkingEngine.schemes_.delete(a)}copyFiltersInto(a){for(const b of this.requestFilters_)a.requestFilters_.add(b);for(const b of this.responseFilters_)a.responseFilters_.add(b)}registerRequestFilter(a){this.requestFilters_.add(a)}unregisterRequestFilter(a){this.requestFilters_.delete(a)}clearAllRequestFilters(){this.requestFilters_.clear()}registerResponseFilter(a){this.responseFilters_.add(a)}unregisterResponseFilter(a){this.responseFilters_.delete(a)}clearAllResponseFilters(){this.responseFilters_.clear()}clearCommonAccessTokenMap(){this.hostCommonAccessTokenMap_.clear()}static defaultRetryParameters(){return shaka.net.Backoff.defaultRetryParameters()}static makeRequest(a,
b,c=null){return{uris:a,method:"GET",body:null,headers:{},allowCrossSiteCredentials:!1,retryParameters:b,licenseRequestType:null,sessionId:null,drmInfo:null,initData:null,initDataType:null,streamDataCallback:c}}destroy(){this.destroyed_=!0;this.requestFilters_.clear();this.responseFilters_.clear();this.hostCommonAccessTokenMap_.clear();super.release();return this.operationManager_.destroy()}request(a,b,c){var d=shaka.util.ObjectUtils;const e=new shaka.net.NetworkingEngine.NumBytesRemainingClass;if(this.destroyed_)return d=
Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.OPERATION_ABORTED)),d.catch(()=>{}),new shaka.net.NetworkingEngine.PendingRequest(d,()=>Promise.resolve(),e);goog.asserts.assert(b.uris&&b.uris.length,"Request without URIs!");b.method=b.method||"GET";b.headers=b.headers||{};b.retryParameters=b.retryParameters?d.cloneObject(b.retryParameters):shaka.net.NetworkingEngine.defaultRetryParameters();b.uris=d.cloneObject(b.uris);
d=this.filterRequest_(a,b,c);const f=d.chain(()=>this.makeRequestWithRetry_(a,b,c,e)),g=f.chain(n=>this.filterResponse_(a,n,c)),h=Date.now();let k=0;d.promise.then(()=>{k=Date.now()-h},()=>{});let l=0;f.promise.then(()=>{l=Date.now()},()=>{});const m=g.chain(n=>{const q=Date.now()-l,p=n.response;p.timeMs+=k;p.timeMs+=q;n.gotProgress||!this.onProgressUpdated_||p.fromCache||b.method=="HEAD"||a!=shaka.net.NetworkingEngine.RequestType.SEGMENT||(n=this.allowSwitch_(c),this.onProgressUpdated_(p.timeMs,
p.data.byteLength,n,b,c));if(this.onResponse_)this.onResponse_(a,p,c);return p},n=>{n&&(goog.asserts.assert(n instanceof shaka.util.Error,"Wrong error type"),n.severity=shaka.util.Error.Severity.CRITICAL);throw n;});d=new shaka.net.NetworkingEngine.PendingRequest(m.promise,()=>m.abort(),e);this.operationManager_.manage(d);return d}filterRequest_(a,b,c){let d=shaka.util.AbortableOperation.completed(void 0);const e=f=>{d=d.chain(()=>{b.body&&(b.body=shaka.util.BufferUtils.toArrayBuffer(b.body));return f(a,
b,c)})};this.onRequest_&&e(this.onRequest_);for(const f of this.requestFilters_)e(f);return d.chain(void 0,f=>{if(f instanceof shaka.util.Error&&f.code==shaka.util.Error.Code.OPERATION_ABORTED)throw f;throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.REQUEST_FILTER_ERROR,f);})}makeRequestWithRetry_(a,b,c,d){const e=new shaka.net.Backoff(b.retryParameters,!1);return this.send_(a,b,c,e,0,null,d)}send_(a,b,c,d,e,f,g){goog.asserts.assert(this.config_,
"Config must not be null!");this.config_.forceHTTP&&(b.uris[e]=b.uris[e].replace("https://","http://"));this.config_.forceHTTPS&&(b.uris[e]=b.uris[e].replace("http://","https://"));if(e>0&&this.onRetry_)this.onRetry_(a,c,b.uris[e],b.uris[e-1]);var h=new goog.Uri(b.uris[e]),k=h.getScheme();let l=!1;k||(k=shaka.net.NetworkingEngine.getLocationProtocol_(),goog.asserts.assert(k[k.length-1]==":","location.protocol expected to end with a colon!"),k=k.slice(0,-1),h.setScheme(k),b.uris[e]=h.toString());k=
k.toLowerCase();const m=(k=shaka.net.NetworkingEngine.schemes_.get(k))?k.plugin:null;if(!m)return shaka.util.AbortableOperation.failed(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.UNSUPPORTED_SCHEME,h));const n=k.progressSupport;(h=this.hostCommonAccessTokenMap_.get(h.getDomain()))&&(b.headers[shaka.net.NetworkingEngine.CommonAccessTokenHeaderName_]=h);let q=null,p=null,r=!1,t=!1,u;return shaka.util.AbortableOperation.notAbortable(d.attempt()).chain(()=>
{if(this.destroyed_)return shaka.util.AbortableOperation.aborted();u=Date.now();const v=shaka.net.NetworkingEngine.RequestType.SEGMENT;let x=0;b.requestStartTime=Date.now();const y=m(b.uris[e],b,a,(z,B,C)=>{q&&q.stop();p&&p.tickAfter(w/1E3);if(this.onProgressUpdated_&&a==v){x++;b.packetNumber=x;const F=this.allowSwitch_(c);this.onProgressUpdated_(z,B,F,b,c);l=!0;g.setBytes(C)}},z=>{t=!0;b.timeToFirstByte=Date.now()-b.requestStartTime;if(this.onHeadersReceived_)this.onHeadersReceived_(z,b,a)},{minBytesForProgressEvents:this.config_.minBytesForProgressEvents});
if(!n)return y;const A=b.retryParameters.connectionTimeout;A&&(q=new shaka.util.Timer(()=>{r=!0;y.abort()}),q.tickAfter(A/1E3));const w=b.retryParameters.stallTimeout;w&&(p=new shaka.util.Timer(()=>{r=!0;y.abort()}));return y}).chain(v=>{q&&q.stop();p&&p.stop();v.timeMs==void 0&&(v.timeMs=Date.now()-u);var x=v.headers[shaka.net.NetworkingEngine.CommonAccessTokenHeaderName_];if(x){const y=new goog.Uri(v.uri);this.hostCommonAccessTokenMap_.set(y.getDomain(),x)}x={response:v,gotProgress:l};if(!t&&this.onHeadersReceived_)this.onHeadersReceived_(v.headers,
b,a);if(this.onDownloadCompleted_)this.onDownloadCompleted_(b,v);return x},v=>{q&&q.stop();p&&p.stop();if(this.onDownloadFailed_){var x=null;let y=0;v instanceof shaka.util.Error&&(x=v,v.code==shaka.util.Error.Code.BAD_HTTP_STATUS&&(y=v.data[1]));this.onDownloadFailed_(b,x,y,r)}if(this.destroyed_)return shaka.util.AbortableOperation.aborted();r&&(v=new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.TIMEOUT,b.uris[e],a));if(v instanceof
shaka.util.Error){if(v.code==shaka.util.Error.Code.OPERATION_ABORTED)throw v;if(v.code==shaka.util.Error.Code.ATTEMPTS_EXHAUSTED)throw goog.asserts.assert(f,"Should have last error"),f;if(v.severity==shaka.util.Error.Severity.RECOVERABLE){x=(new Map).set("error",v);x=new shaka.util.FakeEvent("retry",x);x.cancelable=!0;this.dispatchEvent(x);if(x.defaultPrevented)throw v;e=(e+1)%b.uris.length;return this.send_(a,b,c,d,e,v,g)}}throw v;})}filterResponse_(a,b,c){let d=shaka.util.AbortableOperation.completed(void 0);
for(const e of this.responseFilters_)d=d.chain(()=>{const f=b.response;f.data&&(f.data=shaka.util.BufferUtils.toArrayBuffer(f.data));return e(a,f,c)});return d.chain(()=>b,e=>{let f=shaka.util.Error.Severity.CRITICAL;if(e instanceof shaka.util.Error){if(e.code==shaka.util.Error.Code.OPERATION_ABORTED)throw e;f=e.severity}throw new shaka.util.Error(f,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.RESPONSE_FILTER_ERROR,e);})}allowSwitch_(a){if(a){const b=a.segment;a=a.stream;if(b&&a&&a.fastSwitching&&
b.isPartial())return!1}return!0}static getLocationProtocol_(){return location.protocol}};goog.exportSymbol("shaka.net.NetworkingEngine",shaka.net.NetworkingEngine);goog.exportProperty(shaka.net.NetworkingEngine.prototype,"request",shaka.net.NetworkingEngine.prototype.request);goog.exportProperty(shaka.net.NetworkingEngine.prototype,"destroy",shaka.net.NetworkingEngine.prototype.destroy);goog.exportProperty(shaka.net.NetworkingEngine,"makeRequest",shaka.net.NetworkingEngine.makeRequest);
goog.exportProperty(shaka.net.NetworkingEngine,"defaultRetryParameters",shaka.net.NetworkingEngine.defaultRetryParameters);goog.exportProperty(shaka.net.NetworkingEngine.prototype,"clearCommonAccessTokenMap",shaka.net.NetworkingEngine.prototype.clearCommonAccessTokenMap);goog.exportProperty(shaka.net.NetworkingEngine.prototype,"clearAllResponseFilters",shaka.net.NetworkingEngine.prototype.clearAllResponseFilters);
goog.exportProperty(shaka.net.NetworkingEngine.prototype,"unregisterResponseFilter",shaka.net.NetworkingEngine.prototype.unregisterResponseFilter);goog.exportProperty(shaka.net.NetworkingEngine.prototype,"registerResponseFilter",shaka.net.NetworkingEngine.prototype.registerResponseFilter);goog.exportProperty(shaka.net.NetworkingEngine.prototype,"clearAllRequestFilters",shaka.net.NetworkingEngine.prototype.clearAllRequestFilters);
goog.exportProperty(shaka.net.NetworkingEngine.prototype,"unregisterRequestFilter",shaka.net.NetworkingEngine.prototype.unregisterRequestFilter);goog.exportProperty(shaka.net.NetworkingEngine.prototype,"registerRequestFilter",shaka.net.NetworkingEngine.prototype.registerRequestFilter);goog.exportProperty(shaka.net.NetworkingEngine,"unregisterScheme",shaka.net.NetworkingEngine.unregisterScheme);goog.exportProperty(shaka.net.NetworkingEngine,"registerScheme",shaka.net.NetworkingEngine.registerScheme);
goog.exportProperty(shaka.net.NetworkingEngine.prototype,"configure",shaka.net.NetworkingEngine.prototype.configure);shaka.net.NetworkingEngine.NumBytesRemainingClass=class{constructor(){this.bytesToLoad_=0}setBytes(a){this.bytesToLoad_=a}getBytes(){return this.bytesToLoad_}};goog.exportProperty(shaka.net.NetworkingEngine,"NumBytesRemainingClass",shaka.net.NetworkingEngine.NumBytesRemainingClass);
shaka.net.NetworkingEngine.PendingRequest=class extends shaka.util.AbortableOperation{constructor(a,b,c){super(a,b);this.bytesRemaining_=c}getBytesRemaining(){return this.bytesRemaining_.getBytes()}};goog.exportProperty(shaka.net.NetworkingEngine,"PendingRequest",shaka.net.NetworkingEngine.PendingRequest);shaka.net.NetworkingEngine.CommonAccessTokenHeaderName_="common-access-token";
shaka.net.NetworkingEngine.RequestType={MANIFEST:0,SEGMENT:1,LICENSE:2,APP:3,TIMING:4,SERVER_CERTIFICATE:5,KEY:6,ADS:7,CONTENT_STEERING:8,CMCD:9};goog.exportProperty(shaka.net.NetworkingEngine,"RequestType",shaka.net.NetworkingEngine.RequestType);
shaka.net.NetworkingEngine.AdvancedRequestType={INIT_SEGMENT:0,MEDIA_SEGMENT:1,MEDIA_PLAYLIST:2,MASTER_PLAYLIST:3,MPD:4,MSS:5,MPD_PATCH:6,MEDIATAILOR_SESSION_INFO:7,MEDIATAILOR_TRACKING_INFO:8,MEDIATAILOR_STATIC_RESOURCE:9,MEDIATAILOR_TRACKING_EVENT:10,INTERSTITIAL_ASSET_LIST:11,INTERSTITIAL_AD_URL:12};goog.exportProperty(shaka.net.NetworkingEngine,"AdvancedRequestType",shaka.net.NetworkingEngine.AdvancedRequestType);shaka.net.NetworkingEngine.PluginPriority={FALLBACK:1,PREFERRED:2,APPLICATION:3};
goog.exportProperty(shaka.net.NetworkingEngine,"PluginPriority",shaka.net.NetworkingEngine.PluginPriority);shaka.net.NetworkingEngine.schemes_=new Map;shaka.util.Destroyer=class{constructor(a){this.destroyed_=!1;this.waitOnDestroy_=new shaka.util.PublicPromise;this.onDestroy_=a}destroyed(){return this.destroyed_}destroy(){if(this.destroyed_)return this.waitOnDestroy_;this.destroyed_=!0;return this.onDestroy_().then(()=>{this.waitOnDestroy_.resolve()},()=>{this.waitOnDestroy_.resolve()})}ensureNotDestroyed(a){if(this.destroyed_){if(a instanceof shaka.util.Error&&a.code==shaka.util.Error.Code.OBJECT_DESTROYED)throw a;throw shaka.util.Destroyer.destroyedError(a);
}}static destroyedError(a){return new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.OBJECT_DESTROYED,a)}};shaka.util.Iterables=class{static map(a,b){const c=[];for(const d of a)c.push(b(d));return c}static every(a,b){for(const c of a)if(!b(c))return!1;return!0}static some(a,b){for(const c of a)if(b(c))return!0;return!1}static filter(a,b){const c=[];for(const d of a)b(d)&&c.push(d);return c}};shaka.util.MapUtils=class{static asMap(a){const b=new Map;for(const c of Object.keys(a))b.set(c,a[c]);return b}static asObject(a){const b={};a.forEach((c,d)=>{b[d]=c});return b}static hasSameElements(a,b){if(a||b){if(a&&!b||b&&!a)return!1}else return!0;if(a.size!=b.size)return!1;for(const [c,d]of a){if(!b.has(c))return!1;a=b.get(c);if(a!=d||a==void 0)return!1}return!0}};shaka.util.DataViewReader=class{constructor(a,b){this.dataView_=shaka.util.BufferUtils.toDataView(a);this.littleEndian_=b==shaka.util.DataViewReader.Endianness.LITTLE_ENDIAN;this.position_=0}getDataView(){return this.dataView_}hasMoreData(){return this.position_<this.dataView_.byteLength}getPosition(){return this.position_}getLength(){return this.dataView_.byteLength}readUint8(){try{const a=this.dataView_.getUint8(this.position_);this.position_+=1;return a}catch(a){throw this.outOfBounds_();}}readUint16(){try{const a=
this.dataView_.getUint16(this.position_,this.littleEndian_);this.position_+=2;return a}catch(a){throw this.outOfBounds_();}}readUint32(){try{const a=this.dataView_.getUint32(this.position_,this.littleEndian_);this.position_+=4;return a}catch(a){throw this.outOfBounds_();}}readInt32(){try{const a=this.dataView_.getInt32(this.position_,this.littleEndian_);this.position_+=4;return a}catch(a){throw this.outOfBounds_();}}readUint64(){let a,b;try{this.littleEndian_?(a=this.dataView_.getUint32(this.position_,
!0),b=this.dataView_.getUint32(this.position_+4,!0)):(b=this.dataView_.getUint32(this.position_,!1),a=this.dataView_.getUint32(this.position_+4,!1))}catch(c){throw this.outOfBounds_();}if(b>2097151)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.JS_INTEGER_OVERFLOW);this.position_+=8;return b*4294967296+a}readBytes(a,b){goog.asserts.assert(a>=0,"Bad call to DataViewReader.readBytes");if(this.position_+a>this.dataView_.byteLength)throw this.outOfBounds_();
const c=shaka.util.BufferUtils.toUint8(this.dataView_,this.position_,a);this.position_+=a;return b?new Uint8Array(c):c}skip(a){goog.asserts.assert(a>=0,"Bad call to DataViewReader.skip");if(this.position_+a>this.dataView_.byteLength)throw this.outOfBounds_();this.position_+=a}rewind(a){goog.asserts.assert(a>=0,"Bad call to DataViewReader.rewind");if(this.position_<a)throw this.outOfBounds_();this.position_-=a}seek(a){goog.asserts.assert(a>=0,"Bad call to DataViewReader.seek");if(a<0||a>this.dataView_.byteLength)throw this.outOfBounds_();
this.position_=a}readTerminatedString(){for(var a=this.position_;this.hasMoreData()&&this.dataView_.getUint8(this.position_)!=0;)this.position_+=1;a=shaka.util.BufferUtils.toUint8(this.dataView_,a,this.position_-a);this.position_+=1;return shaka.util.StringUtils.fromUTF8(a)}outOfBounds_(){return new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.BUFFER_READ_OUT_OF_BOUNDS)}};goog.exportSymbol("shaka.util.DataViewReader",shaka.util.DataViewReader);
goog.exportProperty(shaka.util.DataViewReader.prototype,"readTerminatedString",shaka.util.DataViewReader.prototype.readTerminatedString);goog.exportProperty(shaka.util.DataViewReader.prototype,"seek",shaka.util.DataViewReader.prototype.seek);goog.exportProperty(shaka.util.DataViewReader.prototype,"rewind",shaka.util.DataViewReader.prototype.rewind);goog.exportProperty(shaka.util.DataViewReader.prototype,"skip",shaka.util.DataViewReader.prototype.skip);
goog.exportProperty(shaka.util.DataViewReader.prototype,"readBytes",shaka.util.DataViewReader.prototype.readBytes);goog.exportProperty(shaka.util.DataViewReader.prototype,"readUint64",shaka.util.DataViewReader.prototype.readUint64);goog.exportProperty(shaka.util.DataViewReader.prototype,"readInt32",shaka.util.DataViewReader.prototype.readInt32);goog.exportProperty(shaka.util.DataViewReader.prototype,"readUint32",shaka.util.DataViewReader.prototype.readUint32);
goog.exportProperty(shaka.util.DataViewReader.prototype,"readUint16",shaka.util.DataViewReader.prototype.readUint16);goog.exportProperty(shaka.util.DataViewReader.prototype,"readUint8",shaka.util.DataViewReader.prototype.readUint8);goog.exportProperty(shaka.util.DataViewReader.prototype,"getLength",shaka.util.DataViewReader.prototype.getLength);goog.exportProperty(shaka.util.DataViewReader.prototype,"getPosition",shaka.util.DataViewReader.prototype.getPosition);
goog.exportProperty(shaka.util.DataViewReader.prototype,"hasMoreData",shaka.util.DataViewReader.prototype.hasMoreData);shaka.util.DataViewReader.Endianness={BIG_ENDIAN:0,LITTLE_ENDIAN:1};goog.exportProperty(shaka.util.DataViewReader,"Endianness",shaka.util.DataViewReader.Endianness);shaka.util.Mp4Parser=class{constructor(){this.headers_=new Map;this.boxDefinitions_=new Map;this.done_=!1}box(a,b){a=shaka.util.Mp4Parser.typeFromString_(a);this.headers_.set(a,shaka.util.Mp4Parser.BoxType_.BASIC_BOX);this.boxDefinitions_.set(a,b);return this}boxes(a,b){for(const c of a)this.box(c,b);return this}fullBox(a,b){a=shaka.util.Mp4Parser.typeFromString_(a);this.headers_.set(a,shaka.util.Mp4Parser.BoxType_.FULL_BOX);this.boxDefinitions_.set(a,b);return this}stop(){this.done_=!0}parse(a,b,
c){a=new shaka.util.DataViewReader(a,shaka.util.DataViewReader.Endianness.BIG_ENDIAN);for(this.done_=!1;a.hasMoreData()&&!this.done_;)this.parseNext(0,a,b,c)}parseNext(a,b,c,d){const e=b.getPosition();if(d&&e+8>b.getLength())this.done_=!0;else{var f=b.readUint32(),g=b.readUint32(),h=shaka.util.Mp4Parser.typeToString(g),k=!1;shaka.log.v2("Parsing MP4 box",h);switch(f){case 0:f=b.getLength()-e;break;case 1:if(d&&b.getPosition()+8>b.getLength()){this.done_=!0;return}f=b.readUint64();k=!0}var l=this.boxDefinitions_.get(g);
if(l){let n=null;var m=null;if(this.headers_.get(g)==shaka.util.Mp4Parser.BoxType_.FULL_BOX){if(d&&b.getPosition()+4>b.getLength()){this.done_=!0;return}m=b.readUint32();n=m>>>24;m&=16777215}g=e+f;c&&g>b.getLength()&&(g=b.getLength());d&&g>b.getLength()?this.done_=!0:(g-=b.getPosition(),b=g>0?b.readBytes(g,!1):new Uint8Array(0),b=new shaka.util.DataViewReader(b,shaka.util.DataViewReader.Endianness.BIG_ENDIAN),l({name:h,parser:this,partialOkay:c||!1,stopOnPartial:d||!1,version:n,flags:m,reader:b,size:f,
start:e+a,has64BitSize:k}))}else a=Math.min(e+f-b.getPosition(),b.getLength()-b.getPosition()),b.skip(a)}}static children(a){const b=shaka.util.Mp4Parser.headerSize(a);for(;a.reader.hasMoreData()&&!a.parser.done_;)a.parser.parseNext(a.start+b,a.reader,a.partialOkay,a.stopOnPartial)}static sampleDescription(a){const b=shaka.util.Mp4Parser.headerSize(a),c=a.reader.readUint32();for(let d=0;d<c&&(a.parser.parseNext(a.start+b,a.reader,a.partialOkay,a.stopOnPartial),!a.parser.done_);d++);}static visualSampleEntry(a){const b=
shaka.util.Mp4Parser.headerSize(a);for(a.reader.skip(78);a.reader.hasMoreData()&&!a.parser.done_;)a.parser.parseNext(a.start+b,a.reader,a.partialOkay,a.stopOnPartial)}static audioSampleEntry(a){const b=shaka.util.Mp4Parser.headerSize(a);a.reader.skip(8);const c=a.reader.readUint16();a.reader.skip(6);c==2?a.reader.skip(48):a.reader.skip(12);for(c==1&&a.reader.skip(16);a.reader.hasMoreData()&&!a.parser.done_;)a.parser.parseNext(a.start+b,a.reader,a.partialOkay,a.stopOnPartial)}static allData(a,b){return c=>
{const d=c.reader.getLength()-c.reader.getPosition();a(c.reader.readBytes(d,b))}}static typeFromString_(a){goog.asserts.assert(a.length==4,"Mp4 box names must be 4 characters long");let b=0;for(const c of a)b=b<<8|c.charCodeAt(0);return b}static typeToString(a){return String.fromCharCode(a>>24&255,a>>16&255,a>>8&255,a&255)}static headerSize(a){return 8+(a.has64BitSize?8:0)+(a.flags!=null?4:0)}};goog.exportSymbol("shaka.util.Mp4Parser",shaka.util.Mp4Parser);
goog.exportProperty(shaka.util.Mp4Parser,"headerSize",shaka.util.Mp4Parser.headerSize);goog.exportProperty(shaka.util.Mp4Parser,"typeToString",shaka.util.Mp4Parser.typeToString);goog.exportProperty(shaka.util.Mp4Parser,"allData",shaka.util.Mp4Parser.allData);goog.exportProperty(shaka.util.Mp4Parser,"audioSampleEntry",shaka.util.Mp4Parser.audioSampleEntry);goog.exportProperty(shaka.util.Mp4Parser,"visualSampleEntry",shaka.util.Mp4Parser.visualSampleEntry);
goog.exportProperty(shaka.util.Mp4Parser,"sampleDescription",shaka.util.Mp4Parser.sampleDescription);goog.exportProperty(shaka.util.Mp4Parser,"children",shaka.util.Mp4Parser.children);goog.exportProperty(shaka.util.Mp4Parser.prototype,"parseNext",shaka.util.Mp4Parser.prototype.parseNext);goog.exportProperty(shaka.util.Mp4Parser.prototype,"parse",shaka.util.Mp4Parser.prototype.parse);goog.exportProperty(shaka.util.Mp4Parser.prototype,"stop",shaka.util.Mp4Parser.prototype.stop);
goog.exportProperty(shaka.util.Mp4Parser.prototype,"fullBox",shaka.util.Mp4Parser.prototype.fullBox);goog.exportProperty(shaka.util.Mp4Parser.prototype,"boxes",shaka.util.Mp4Parser.prototype.boxes);goog.exportProperty(shaka.util.Mp4Parser.prototype,"box",shaka.util.Mp4Parser.prototype.box);shaka.util.Mp4Parser.BoxType_={BASIC_BOX:0,FULL_BOX:1};shaka.util.Pssh=class{constructor(a){this.systemIds=[];this.data=[];(new shaka.util.Mp4Parser).boxes(["moov","moof"],shaka.util.Mp4Parser.children).fullBox("pssh",b=>this.parsePsshBox_(b)).parse(a);this.data.length==0&&shaka.log.v2("No pssh box found!")}parsePsshBox_(a){goog.asserts.assert(a.version!=null,"PSSH boxes are full boxes and must have a valid version");goog.asserts.assert(a.flags!=null,"PSSH boxes are full boxes and must have a valid flag");if(a.version>1)shaka.log.warning("Unrecognized PSSH version found!");
else{var b=a.reader.getDataView();goog.asserts.assert(b.byteOffset>=12,"DataView at incorrect position");b=shaka.util.BufferUtils.toUint8(b,-12,a.size);this.data.push(b);a=a.reader.readBytes(16,!1);this.systemIds.push(shaka.util.Uint8ArrayUtils.toHex(a))}}static createPssh(a,b,c,d){goog.asserts.assert(b.byteLength==16,"Invalid system ID length");const e=a.length;let f=12+b.length+4+e;d>0&&(f+=4+16*c.size);const g=new Uint8Array(f),h=shaka.util.BufferUtils.toDataView(g);let k=0;h.setUint32(k,f);k+=
4;h.setUint32(k,1886614376);k+=4;d<1?h.setUint32(k,0):h.setUint32(k,16777216);k+=4;g.set(b,k);k+=b.length;if(d>0){h.setUint32(k,c.size);k+=4;b=shaka.util.Uint8ArrayUtils;for(const l of c)c=b.fromHex(l),g.set(c,k),k+=c.length}h.setUint32(k,e);k+=4;g.set(a,k);goog.asserts.assert(k+e===f,"PSSH invalid length.");return g}static getPsshData(a){let b=8;a=shaka.util.BufferUtils.toDataView(a);const c=a.getUint8(b);b+=20;c>0&&(b+=4+16*a.getUint32(b));return shaka.util.BufferUtils.toUint8(a,b+4)}static normaliseInitData(a){if(!a)return a;
const b=new shaka.util.Pssh(a);if(b.data.length<=1)return a;a=[];for(const c of b.data)a.some(d=>shaka.util.BufferUtils.equal(d,c))||a.push(c);return shaka.util.Uint8ArrayUtils.concat(...a)}};shaka.drm.DrmEngine=class{constructor(a){this.playerInterface_=a;this.video_=this.mediaKeys_=null;this.initializedForStorage_=this.initialized_=!1;this.licenseTimeSeconds_=0;this.currentDrmInfo_=null;this.eventManager_=new shaka.util.EventManager;this.activeSessions_=new Map;this.activeRequests_=[];this.storedPersistentSessions_=new Map;this.hasInitData_=!1;this.allSessionsLoaded_=new shaka.util.PublicPromise;this.config_=null;this.onError_=b=>{b.severity==shaka.util.Error.Severity.CRITICAL&&this.allSessionsLoaded_.reject(b);
a.onError(b)};this.keyStatusByKeyId_=new Map;this.announcedKeyStatusByKeyId_=new Map;this.keyStatusTimer_=new shaka.util.Timer(()=>this.processKeyStatusChanges_());this.usePersistentLicenses_=!1;this.mediaKeyMessageEvents_=[];this.initialRequestsSent_=!1;this.expirationTimer_=new shaka.util.Timer(()=>{this.pollExpiration_()});this.allSessionsLoaded_.catch(()=>{});this.destroyer_=new shaka.util.Destroyer(()=>this.destroyNow_());this.srcEquals_=!1;this.manifestInitData_=this.mediaKeysAttached_=null;
this.isPreload_=()=>!1}destroy(){return this.destroyer_.destroy()}async destroyNow_(){this.eventManager_.release();this.eventManager_=null;this.allSessionsLoaded_.reject();this.expirationTimer_.stop();this.expirationTimer_=null;this.keyStatusTimer_.stop();this.keyStatusTimer_=null;await this.closeOpenSessions_();if(this.video_){shaka.drm.DrmUtils.isMediaKeysPolyfilled("webkit")||goog.asserts.assert(!this.video_.src&&!this.video_.getElementsByTagName("source").length,"video src must be removed first!");
try{await this.video_.setMediaKeys(null)}catch(a){shaka.log.alwaysWarn("DrmEngine.destroyNow_ exception",a)}this.video_=null}this.mediaKeys_=this.currentDrmInfo_=null;this.storedPersistentSessions_=new Map;this.config_=null;this.onError_=()=>{};this.playerInterface_=null;this.srcEquals_=!1;this.mediaKeysAttached_=null}configure(a,b){this.config_=a;b&&(this.isPreload_=b);this.expirationTimer_&&this.initialized_&&this.currentDrmInfo_&&this.expirationTimer_.tickEvery(this.config_.updateExpirationTime)}setSrcEquals(a){this.srcEquals_=
a}initForStorage(a,b){this.initializedForStorage_=!0;this.storedPersistentSessions_=new Map;this.usePersistentLicenses_=b;return this.init_(a,!1)}initForPlayback(a,b,c=!0){this.storedPersistentSessions_=new Map;for(const d of b)this.storedPersistentSessions_.set(d,{initData:null,initDataType:null});for(const d of this.config_.persistentSessionsMetadata)this.storedPersistentSessions_.set(d.sessionId,{initData:d.initData,initDataType:d.initDataType});this.usePersistentLicenses_=this.storedPersistentSessions_.size>
0;return this.init_(a,c)}async initForRemoval(a,b,c,d,e){var f=[];e.length&&f.push(e[0].contentType);d.length&&f.push(d[0].contentType);const g=h=>{h=shaka.util.ManifestParserUtils.createDrmInfo(a,h,null);h.licenseServerUri=b;h.serverCertificate=c;h.persistentStateRequired=!0;h.sessionType="persistent-license";return h};f=shaka.util.StreamUtils.createEmptyVariant(f);f.video&&(e=g(e[0].encryptionScheme||""),f.video.drmInfos.push(e));f.audio&&(d=g(d[0].encryptionScheme||""),f.audio.drmInfos.push(d));
await shaka.util.StreamUtils.getDecodingInfosForVariants([f],!0,this.srcEquals_,[]);this.destroyer_.ensureNotDestroyed();return this.queryMediaKeys_([f])}async init_(a,b){goog.asserts.assert(this.config_,"DrmEngine configure() must be called before init()!");shaka.drm.DrmEngine.configureClearKey(this.config_.clearKeys,a);const c=a.some(h=>h.video&&h.video.drmInfos.length||h.audio&&h.audio.drmInfos.length?!0:!1),d=shaka.util.MapUtils.asMap(this.config_.servers),e=shaka.util.MapUtils.asMap(this.config_.advanced||
{});!c&&b&&shaka.drm.DrmEngine.replaceDrmInfo_(a,d);b=new WeakSet;for(var f of a){const h=this.getVariantDrmInfos_(f);for(var g of h)b.has(g)||(b.add(g),shaka.drm.DrmEngine.fillInDrmInfoDefaults_(g,d,e,this.config_.keySystemsMapping))}f=(h,k)=>{const l=[];for(const m of h)if(h=m[k]||e.has(m.keySystem)&&e.get(m.keySystem)[k]||"",h==""&&shaka.drm.DrmUtils.isWidevineKeySystem(m.keySystem)&&(k=="audioRobustness"?h=[this.config_.defaultAudioRobustnessForWidevine]:k=="videoRobustness"&&(h=[this.config_.defaultVideoRobustnessForWidevine])),
typeof h==="string")l.push(m);else if(Array.isArray(h)){h.length===0&&(h=[""]);for(const n of h)l.push(Object.assign({},m,{[k]:n}))}return l};g=new WeakSet;for(const h of a)h.video&&!g.has(h.video)&&(h.video.drmInfos=f(h.video.drmInfos,"videoRobustness"),h.video.drmInfos=f(h.video.drmInfos,"audioRobustness"),g.add(h.video)),h.audio&&!g.has(h.audio)&&(h.audio.drmInfos=f(h.audio.drmInfos,"videoRobustness"),h.audio.drmInfos=f(h.audio.drmInfos,"audioRobustness"),g.add(h.audio));await shaka.util.StreamUtils.getDecodingInfosForVariants(a,
this.usePersistentLicenses_,this.srcEquals_,this.config_.preferredKeySystems);this.destroyer_.ensureNotDestroyed();if(!(c||d.size>0))return this.initialized_=!0,Promise.resolve();a=this.queryMediaKeys_(a);return c?a:a.catch(()=>{})}async attachMediaKeys_(){if(!this.video_.mediaKeys){if(this.mediaKeysAttached_)await this.mediaKeysAttached_;else try{this.mediaKeysAttached_=this.video_.setMediaKeys(this.mediaKeys_),await this.mediaKeysAttached_}catch(a){goog.asserts.assert(a instanceof Error,"Wrong error type!"),
this.onError_(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.FAILED_TO_ATTACH_TO_VIDEO,a.message))}this.destroyer_.ensureNotDestroyed()}}async onEncryptedEvent_(a){await this.attachMediaKeys_();this.newInitData(a.initDataType,shaka.util.BufferUtils.toUint8(a.initData))}async attach(a){this.video_!==a&&(this.mediaKeys_?(this.video_=a,this.config_.delayLicenseRequestUntilPlayed&&this.eventManager_.listenOnce(this.video_,"play",()=>this.onPlay_()),
this.video_.remote?(this.eventManager_.listen(this.video_.remote,"connect",()=>this.closeOpenSessions_()),this.eventManager_.listen(this.video_.remote,"connecting",()=>this.closeOpenSessions_()),this.eventManager_.listen(this.video_.remote,"disconnect",()=>this.closeOpenSessions_())):"webkitCurrentPlaybackTargetIsWireless"in this.video_&&this.eventManager_.listen(this.video_,"webkitcurrentplaybacktargetiswirelesschanged",()=>this.closeOpenSessions_()),this.manifestInitData_=this.currentDrmInfo_?this.currentDrmInfo_.initData.find(b=>
b.initData.length>0)||null:null,a=this.currentDrmInfo_.keySystem,(a=shaka.device.DeviceFactory.getDevice().needWaitForEncryptedEvent(a))||!this.manifestInitData_&&this.currentDrmInfo_.keySystem==="com.apple.fps"&&!this.storedPersistentSessions_.size||await this.attachMediaKeys_(),this.createOrLoad().catch(()=>{}),!a&&(this.manifestInitData_||this.storedPersistentSessions_.size||this.config_.parseInbandPsshEnabled)||this.eventManager_.listen(this.video_,"encrypted",b=>this.onEncryptedEvent_(b))):this.eventManager_.listenOnce(a,
"encrypted",b=>{this.onError_(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.ENCRYPTED_CONTENT_WITHOUT_DRM_INFO))}))}hasManifestInitData(){return!!this.manifestInitData_}async setServerCertificate(){goog.asserts.assert(this.initialized_,"Must call init() before setServerCertificate");if(this.mediaKeys_&&this.currentDrmInfo_){if(this.currentDrmInfo_.serverCertificateUri&&(!this.currentDrmInfo_.serverCertificate||!this.currentDrmInfo_.serverCertificate.length)){const a=
shaka.net.NetworkingEngine.makeRequest([this.currentDrmInfo_.serverCertificateUri],this.config_.retryParameters);try{const b=await this.playerInterface_.netEngine.request(shaka.net.NetworkingEngine.RequestType.SERVER_CERTIFICATE,a,{isPreload:this.isPreload_()}).promise;this.currentDrmInfo_.serverCertificate=shaka.util.BufferUtils.toUint8(b.data)}catch(b){throw goog.asserts.assert(b instanceof shaka.util.Error,"Wrong NetworkingEngine error type!"),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,shaka.util.Error.Code.SERVER_CERTIFICATE_REQUEST_FAILED,b);}if(this.destroyer_.destroyed())return}if(this.currentDrmInfo_.serverCertificate&&this.currentDrmInfo_.serverCertificate.length)try{await this.mediaKeys_.setServerCertificate(this.currentDrmInfo_.serverCertificate)||shaka.log.warning("Server certificates are not supported by the key system.  The server certificate has been ignored.")}catch(a){throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,
shaka.util.Error.Code.INVALID_SERVER_CERTIFICATE,a.message);}}}async removeSession(a){goog.asserts.assert(this.mediaKeys_,"Must call init() before removeSession");const b=await this.loadOfflineSession_(a,{initData:null,initDataType:null});if(b){var c=[],d=this.activeSessions_.get(b);d&&(d.updatePromise=new shaka.util.PublicPromise,c.push(d.updatePromise));shaka.log.v2("Attempting to remove session",a);c.push(b.remove());await Promise.all(c);this.activeSessions_.delete(b)}else shaka.log.v2("Ignoring attempt to remove missing session",
a)}async createOrLoad(){if(this.storedPersistentSessions_.size){this.storedPersistentSessions_.forEach((b,c)=>{this.loadOfflineSession_(c,b)});await this.allSessionsLoaded_;if((this.currentDrmInfo_&&this.currentDrmInfo_.keyIds||new Set([])).size>0&&this.areAllKeysUsable_())return this.allSessionsLoaded_;this.hasInitData_=!1;this.allSessionsLoaded_=new shaka.util.PublicPromise;this.allSessionsLoaded_.catch(()=>{})}const a=(this.currentDrmInfo_?this.currentDrmInfo_.initData:[])||[];for(const b of a)this.newInitData(b.initDataType,
b.initData);this.areAllSessionsLoaded_()&&this.allSessionsLoaded_.resolve();return this.allSessionsLoaded_}updateCurrentDrmInfo(a){this.currentDrmInfo_&&(this.currentDrmInfo_.mediaTypes!==a.mediaTypes&&(this.currentDrmInfo_.mediaTypes=a.mediaTypes),shaka.drm.DrmUtils.isClearKeyWihRawKey(a)&&(this.currentDrmInfo_=this.createDrmInfoByInfos_(this.currentDrmInfo_.keySystem,[this.currentDrmInfo_,a])))}newInitData(a,b){if(b.length){try{b=this.config_.initDataTransform(b,a,this.currentDrmInfo_)}catch(c){a=
c;c instanceof shaka.util.Error||(a=new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.INIT_DATA_TRANSFORM_ERROR,c));this.onError_(a);return}if(this.config_.ignoreDuplicateInitData){const c=this.activeSessions_.values();for(const e of c)if(shaka.util.BufferUtils.equal(b,e.initData)){shaka.log.debug("Ignoring duplicate init data.");return}let d=!1;this.storedPersistentSessions_.forEach((e,f)=>{!d&&shaka.util.BufferUtils.equal(b,e.initData)&&
(d=!0)});if(d){shaka.log.debug("Ignoring duplicate init data.");return}}this.hasInitData_=!0;this.activeSessions_.size>0&&this.areAllSessionsLoaded_()&&(this.allSessionsLoaded_.resolve(),this.hasInitData_=!1,this.allSessionsLoaded_=new shaka.util.PublicPromise,this.allSessionsLoaded_.catch(()=>{}));this.createSession(a,b,this.currentDrmInfo_.sessionType)}}initialized(){return this.initialized_}getSessionIds(){var a=this.activeSessions_.keys();a=shaka.util.Iterables.map(a,b=>b.sessionId);return Array.from(a)}getActiveSessionsMetadata(){var a=
this.activeSessions_.keys();a=shaka.util.Iterables.map(a,b=>{const c=this.activeSessions_.get(b);return{sessionId:b.sessionId,sessionType:c.type,initData:c.initData,initDataType:c.initDataType}});return Array.from(a)}getExpiration(){let a=Infinity;const b=this.activeSessions_.keys();for(const c of b)isNaN(c.expiration)||(a=Math.min(a,c.expiration));return a}getLicenseTime(){return this.licenseTimeSeconds_?this.licenseTimeSeconds_:NaN}getDrmInfo(){return this.currentDrmInfo_}getMediaKeys(){return this.mediaKeys_}getKeyStatuses(){return shaka.util.MapUtils.asObject(this.announcedKeyStatusByKeyId_)}async queryMediaKeys_(a){const b=
new Map;a=this.getKeySystemAccessFromVariants_(a,b);if(!a){if(!navigator.requestMediaKeySystemAccess)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.MISSING_EME_SUPPORT);throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE);}this.destroyer_.ensureNotDestroyed();try{const c=a.getConfiguration();shaka.log.v2("Got MediaKeySystemAccess with configuration",
c);const d=this.config_.keySystemsMapping[a.keySystem]||a.keySystem;this.currentDrmInfo_=this.createDrmInfoByInfos_(d,b.get(d));if(!this.currentDrmInfo_.licenseServerUri)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.NO_LICENSE_SERVER_GIVEN,this.currentDrmInfo_.keySystem);const e=await a.createMediaKeys();this.destroyer_.ensureNotDestroyed();shaka.log.info("Created MediaKeys object for key system",this.currentDrmInfo_.keySystem);this.mediaKeys_=
e;if(this.config_.minHdcpVersion!=""&&"getStatusForPolicy"in this.mediaKeys_)try{if(await this.mediaKeys_.getStatusForPolicy({minHdcpVersion:this.config_.minHdcpVersion})!="usable")throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.MIN_HDCP_VERSION_NOT_MATCH);this.destroyer_.ensureNotDestroyed()}catch(f){if(f instanceof shaka.util.Error)throw f;throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,
shaka.util.Error.Code.ERROR_CHECKING_HDCP_VERSION,f.message);}this.initialized_=!0;this.expirationTimer_.tickEvery(this.config_.updateExpirationTime);await this.setServerCertificate();this.destroyer_.ensureNotDestroyed()}catch(c){this.destroyer_.ensureNotDestroyed(c);this.currentDrmInfo_=null;if(c instanceof shaka.util.Error)throw c;throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.FAILED_TO_CREATE_CDM,c.message);}}getKeySystemAccessFromVariants_(a,
b){for(var c of a){var d=this.getVariantDrmInfos_(c);for(const f of d)b.has(f.keySystem)||b.set(f.keySystem,[]),b.get(f.keySystem).push(f)}if(b.size==1&&b.has(""))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.NO_RECOGNIZED_KEY_SYSTEMS);c=this.config_.preferredKeySystems;c.length||(d=shaka.util.MapUtils.asMap(this.config_.servers),d.size==1&&(c=Array.from(d.keys())));for(const f of c)for(var e of a)if(d=e.decodingInfos.find(g=>g.supported&&
g.keySystemAccess!=null&&g.keySystemAccess.keySystem==f))return d.keySystemAccess;for(const f of[!0,!1])for(const g of a)for(const h of g.decodingInfos){if(!h.supported||!h.keySystemAccess)continue;e=h.keySystemAccess.keySystem;if(c.includes(e))continue;d=b.get(e);!d&&this.config_.keySystemsMapping[e]&&(d=b.get(this.config_.keySystemsMapping[e]));for(const k of d)if(!!k.licenseServerUri==f)return h.keySystemAccess}return null}checkSessionsLoaded_(){this.areAllSessionsLoaded_()&&this.allSessionsLoaded_.resolve()}setLoadSessionTimeoutTimer_(a){(new shaka.util.Timer(()=>
{a.loaded=!0;this.checkSessionsLoaded_()})).tickAfter(shaka.drm.DrmEngine.SESSION_LOAD_TIMEOUT_)}async loadOfflineSession_(a,b){let c;try{shaka.log.v1("Attempting to load an offline session",a),c=this.mediaKeys_.createSession("persistent-license")}catch(d){return a=new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.FAILED_TO_CREATE_SESSION,d.message),this.onError_(a),Promise.reject(a)}this.eventManager_.listen(c,"message",d=>this.onSessionMessage_(d));
this.eventManager_.listen(c,"keystatuseschange",d=>this.onKeyStatusesChange_(d));b={initData:b.initData,initDataType:b.initDataType,loaded:!1,oldExpiration:Infinity,updatePromise:null,type:"persistent-license"};this.activeSessions_.set(c,b);try{const d=await c.load(a);this.destroyer_.ensureNotDestroyed();shaka.log.v2("Loaded offline session",a,d);d||(this.activeSessions_.delete(c),this.onError_(new shaka.util.Error(this.config_.persistentSessionOnlinePlayback?shaka.util.Error.Severity.RECOVERABLE:
shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.OFFLINE_SESSION_REMOVED)),b.loaded=!0);this.setLoadSessionTimeoutTimer_(b);this.checkSessionsLoaded_();return c}catch(d){this.destroyer_.ensureNotDestroyed(d),this.activeSessions_.delete(c),this.onError_(new shaka.util.Error(this.config_.persistentSessionOnlinePlayback?shaka.util.Error.Severity.RECOVERABLE:shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.FAILED_TO_CREATE_SESSION,
d.message)),b.loaded=!0,this.checkSessionsLoaded_()}return Promise.resolve()}createSession(a,b,c){goog.asserts.assert(this.mediaKeys_,"mediaKeys_ should be valid when creating temporary session.");let d;try{shaka.log.info("Creating new",c,"session"),d=this.mediaKeys_.createSession(c)}catch(e){this.onError_(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.FAILED_TO_CREATE_SESSION,e.message));return}this.eventManager_.listen(d,"message",e=>
this.onSessionMessage_(e));this.eventManager_.listen(d,"keystatuseschange",e=>this.onKeyStatusesChange_(e));this.activeSessions_.set(d,{initData:b,initDataType:a,loaded:!1,oldExpiration:Infinity,updatePromise:null,type:c});this.config_.logLicenseExchange&&(c=shaka.util.Uint8ArrayUtils.toBase64(b),shaka.log.info("EME init data: type=",a,"data=",c));d.generateRequest(a,b).catch(e=>{if(!this.destroyer_.destroyed()){goog.asserts.assert(e instanceof Error,"Wrong error type!");this.activeSessions_.delete(d);
var f=e.errorCode;if(f&&f.systemCode){var g=f.systemCode;g<0&&(g+=4294967296);g="0x"+g.toString(16)}this.onError_(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.FAILED_TO_GENERATE_LICENSE_REQUEST,e.message,e,g))}})}onSessionMessage_(a){this.delayLicenseRequest_()?this.mediaKeyMessageEvents_.push(a):this.sendLicenseRequest_(a)}delayLicenseRequest_(){return this.video_?this.config_.delayLicenseRequestUntilPlayed&&this.video_.paused&&!this.initialRequestsSent_:
!this.initializedForStorage_&&this.config_.delayLicenseRequestUntilPlayed}async waitForActiveRequests(){this.hasInitData_&&!this.delayLicenseRequest_()&&(await this.allSessionsLoaded_,await Promise.all(this.activeRequests_.map(a=>a.promise)))}async sendLicenseRequest_(a){var b=a.target;shaka.log.v1("Sending license request for session",b.sessionId,"of type",a.messageType);if(this.config_.logLicenseExchange){var c=shaka.util.Uint8ArrayUtils.toBase64(a.message);shaka.log.info("EME license request",
c)}c=this.activeSessions_.get(b);var d=this.currentDrmInfo_.licenseServerUri;const e=this.config_.advanced[this.currentDrmInfo_.keySystem];a.messageType=="individualization-request"&&e&&e.individualizationServer&&(d=e.individualizationServer);const f=shaka.net.NetworkingEngine.RequestType.LICENSE;d=shaka.net.NetworkingEngine.makeRequest([d],this.config_.retryParameters);d.body=a.message;d.method="POST";d.licenseRequestType=a.messageType;d.sessionId=b.sessionId;d.drmInfo=this.currentDrmInfo_;c&&(d.initData=
c.initData,d.initDataType=c.initDataType);if(e&&e.headers)for(const k in e.headers)d.headers[k]=e.headers[k];shaka.drm.DrmUtils.isClearKeySystem(this.currentDrmInfo_.keySystem)&&this.fixClearKeyRequest_(d,this.currentDrmInfo_);shaka.drm.DrmUtils.isPlayReadyKeySystem(this.currentDrmInfo_.keySystem)&&this.unpackPlayReadyRequest_(d);a=Date.now();try{var g=this.playerInterface_.netEngine.request(f,d,{isPreload:this.isPreload_()});this.activeRequests_.push(g);var h=await g.promise;shaka.util.ArrayUtils.remove(this.activeRequests_,
g)}catch(k){if(this.destroyer_.destroyed())return;goog.asserts.assert(k instanceof shaka.util.Error,"Wrong NetworkingEngine error type!");h=new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.LICENSE_REQUEST_FAILED,k,{sessionId:b.sessionId,sessionType:c.type,initData:c.initData,initDataType:c.initDataType});this.activeSessions_.size==1?(this.onError_(h),c&&c.updatePromise&&c.updatePromise.reject(h)):(c&&c.updatePromise&&c.updatePromise.reject(h),
this.activeSessions_.delete(b),this.areAllSessionsLoaded_()&&(this.allSessionsLoaded_.resolve(),this.keyStatusTimer_.tickAfter(.1)));return}if(!this.destroyer_.destroyed()){this.licenseTimeSeconds_+=(Date.now()-a)/1E3;this.config_.logLicenseExchange&&(g=shaka.util.Uint8ArrayUtils.toBase64(h.data),shaka.log.info("EME license response",g));try{shaka.log.v1("Updating session",b.sessionId),await b.update(h.data)}catch(k){b=new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,
shaka.util.Error.Code.LICENSE_RESPONSE_REJECTED,k&&k.message||String(k));this.onError_(b);c&&c.updatePromise&&c.updatePromise.reject(b);return}this.destroyer_.destroyed()||(b=new shaka.util.FakeEvent("drmsessionupdate"),this.playerInterface_.onEvent(b),c&&(c.updatePromise&&c.updatePromise.resolve(),this.setLoadSessionTimeoutTimer_(c)))}}unpackPlayReadyRequest_(a){var b=shaka.util.TXml,c=shaka.util.StringUtils.fromUTF16(a.body,!0,!0);if(c.includes("PlayReadyKeyMessage")){shaka.log.debug("Unwrapping PlayReady request.");
c=b.parseXmlString(c,"PlayReadyKeyMessage");goog.asserts.assert(c,"Failed to parse PlayReady XML!");var d=b.getElementsByTagName(c,"HttpHeader");for(const e of d){d=b.getElementsByTagName(e,"name")[0];const f=b.getElementsByTagName(e,"value")[0];goog.asserts.assert(d&&f,"Malformed PlayReady headers!");a.headers[shaka.util.TXml.getTextContents(d)]=shaka.util.TXml.getTextContents(f)}b=b.getElementsByTagName(c,"Challenge")[0];goog.asserts.assert(b,"Malformed PlayReady challenge!");goog.asserts.assert(b.attributes.encoding==
"base64encoded","Unexpected PlayReady challenge encoding!");a.body=shaka.util.Uint8ArrayUtils.fromBase64(shaka.util.TXml.getTextContents(b))}else shaka.log.debug("PlayReady request is already unwrapped."),a.headers["Content-Type"]="text/xml; charset=utf-8"}fixClearKeyRequest_(a,b){try{const c=shaka.util.StringUtils.fromBytesAutoDetect(a.body);if(c){const d=JSON.parse(c);d.type||(d.type=b.sessionType,a.body=shaka.util.StringUtils.toUTF8(JSON.stringify(d)))}}catch(c){shaka.log.info("Error unpacking ClearKey license",
c)}}onKeyStatusesChange_(a){a=a.target;shaka.log.v2("Key status changed for session",a.sessionId);const b=this.activeSessions_.get(a);let c=!1;a.keyStatuses.forEach((e,f)=>{if(typeof f=="string"){var g=f;f=e;e=g}g=shaka.device.DeviceFactory.getDevice();if(shaka.drm.DrmUtils.isPlayReadyKeySystem(this.currentDrmInfo_.keySystem)&&f.byteLength==16&&g.returnLittleEndianUsingPlayReady()){g=shaka.util.BufferUtils.toDataView(f);const h=g.getUint32(0,!0),k=g.getUint16(4,!0),l=g.getUint16(6,!0);g.setUint32(0,
h,!1);g.setUint16(4,k,!1);g.setUint16(6,l,!1)}e!="status-pending"&&(b.loaded=!0);b||goog.asserts.assert(e!="usable","Usable keys found in closed session");e=="expired"&&(c=!0);f=shaka.util.Uint8ArrayUtils.toHex(f).slice(0,32);this.keyStatusByKeyId_.set(f,e)});const d=a.expiration-Date.now();(d<0||c&&d<1E3)&&b&&!b.updatePromise&&(shaka.log.debug("Session has expired",a.sessionId),this.activeSessions_.delete(a),this.closeSession_(a));this.areAllSessionsLoaded_()&&(this.allSessionsLoaded_.resolve(),
this.keyStatusTimer_.tickAfter(shaka.drm.DrmEngine.KEY_STATUS_BATCH_TIME))}processKeyStatusChanges_(){var a=this.keyStatusByKeyId_;const b=this.announcedKeyStatusByKeyId_;b.clear();a.forEach((c,d)=>b.set(d,c));a=Array.from(b.values());if(a.length&&a.every(c=>c=="expired"))this.onError_(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.EXPIRED));this.playerInterface_.onKeyStatus(shaka.util.MapUtils.asObject(b))}static async probeSupport(){var a=
"org.w3.clearkey com.widevine.alpha com.widevine.alpha.experiment com.microsoft.playready com.microsoft.playready.hardware com.microsoft.playready.recommendation com.microsoft.playready.recommendation.3000 com.microsoft.playready.recommendation.3000.clearlead com.chromecast.playready com.apple.fps.1_0 com.apple.fps com.huawei.wiseplay".split(" ");if(!shaka.drm.DrmUtils.isBrowserSupported()){var b={};for(var c of a)b[c]=null;return b}const d="1.0 1.1 1.2 1.3 1.4 2.0 2.1 2.2 2.3".split(" ");c=["SW_SECURE_CRYPTO",
"SW_SECURE_DECODE","HW_SECURE_CRYPTO","HW_SECURE_DECODE","HW_SECURE_ALL"];c={"com.widevine.alpha":c,"com.widevine.alpha.experiment":c,"com.microsoft.playready.recommendation":["150","2000","3000"]};const e={videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42E01E"'},{contentType:'video/webm; codecs="vp8"'}],audioCapabilities:[{contentType:'audio/mp4; codecs="mp4a.40.2"'},{contentType:'audio/webm; codecs="opus"'}],initDataTypes:["cenc","sinf","skd","keyids"]},f=[null,"cenc","cbcs"],g=new Map,
h=shaka.device.DeviceFactory.getDevice(),k=async(n,q,p)=>{let r;try{if(h.createMediaKeysWhenCheckingSupport())r=await q.createMediaKeys();else throw Error("Suppressing Firefox Windows DRM in testing!");}catch(v){return}var t=q.getConfiguration().sessionTypes,u=t?t.includes("persistent-license"):!1;h.misreportsSupportForPersistentLicenses()&&(u=!1);t=q.getConfiguration().videoCapabilities;q=q.getConfiguration().audioCapabilities;u={persistentState:u,encryptionSchemes:[],videoRobustnessLevels:[],audioRobustnessLevels:[],
minHdcpVersions:[]};g.get(n)?u=g.get(n):g.set(n,u);(n=t[0].encryptionScheme)&&!u.encryptionSchemes.includes(n)&&u.encryptionSchemes.push(n);(n=t[0].robustness)&&!u.videoRobustnessLevels.includes(n)&&u.videoRobustnessLevels.push(n);(n=q[0].robustness)&&!u.audioRobustnessLevels.includes(n)&&u.audioRobustnessLevels.push(n);if(p&&"getStatusForPolicy"in r)for(const v of d)if(!u.minHdcpVersions.includes(v))if(await r.getStatusForPolicy({minHdcpVersion:v})=="usable")u.minHdcpVersions.includes(v)||u.minHdcpVersions.push(v);
else break},l=async(n,q,p,r,t=!1)=>{try{const u=shaka.util.ObjectUtils.cloneObject(e);for(const y of u.videoCapabilities)y.encryptionScheme=q,y.robustness=p;for(const y of u.audioCapabilities)y.encryptionScheme=q,y.robustness=r;const v=shaka.util.ObjectUtils.cloneObject(u);v.persistentState="required";v.sessionTypes=["persistent-license"];q=[v,u];let x;x=shaka.device.DeviceFactory.getDevice().getDeviceType()==shaka.device.IDevice.DeviceType.MOBILE?await shaka.util.Functional.promiseWithTimeout(5,
navigator.requestMediaKeySystemAccess(n,q)):await navigator.requestMediaKeySystemAccess(n,q);await k(n,x,t)}catch(u){}},m=[];for(b of a){g.set(b,null);if(shaka.device.DeviceFactory.getDevice().getBrowserEngine()===shaka.device.IDevice.BrowserEngine.WEBKIT&&shaka.drm.DrmUtils.isClearKeySystem(b))continue;a=!0;for(const n of f)m.push(l(b,n,"","",a)),a=!1;for(const n of c[b]||[])m.push(l(b,null,n,"")),m.push(l(b,null,"",n))}await Promise.all(m);return shaka.util.MapUtils.asObject(g)}onPlay_(){for(const a of this.mediaKeyMessageEvents_)this.sendLicenseRequest_(a);
this.initialRequestsSent_=!0;this.mediaKeyMessageEvents_=[]}async closeSession_(a){try{await shaka.util.Functional.promiseWithTimeout(shaka.drm.DrmEngine.CLOSE_TIMEOUT_,Promise.all([a.close().catch(()=>{}),a.closed]))}catch(b){shaka.log.warning("Timeout waiting for session close")}}async closeOpenSessions_(){const a=Array.from(this.activeSessions_.entries());this.activeSessions_.clear();await Promise.all(a.map(async([b,c])=>{try{this.initializedForStorage_||this.storedPersistentSessions_.has(b.sessionId)||
c.type!=="persistent-license"||this.config_.persistentSessionOnlinePlayback?(shaka.log.v1("Closing session",b.sessionId,c),await this.closeSession_(b)):(shaka.log.v1("Removing session",b.sessionId),await b.remove())}catch(d){shaka.log.error("Failed to close or remove the session",d)}}))}getVariantDrmInfos_(a){return(a.video?a.video.drmInfos:[]).concat(a.audio?a.audio.drmInfos:[])}pollExpiration_(){this.activeSessions_.forEach((a,b)=>{const c=a.oldExpiration;let d=b.expiration;isNaN(d)&&(d=Infinity);
d!=c&&(this.playerInterface_.onExpirationUpdated(b.sessionId,d),a.oldExpiration=d)})}areAllSessionsLoaded_(){const a=this.activeSessions_.values();return shaka.util.Iterables.every(a,b=>b.loaded)}areAllKeysUsable_(){const a=this.currentDrmInfo_&&this.currentDrmInfo_.keyIds||new Set([]);for(const b of a)if(this.keyStatusByKeyId_.get(b)!=="usable")return!1;return!0}static replaceDrmInfo_(a,b){const c=[];b.forEach((d,e)=>{c.push({keySystem:e,licenseServerUri:d,distinctiveIdentifierRequired:!1,persistentStateRequired:!1,
audioRobustness:"",videoRobustness:"",serverCertificate:null,serverCertificateUri:"",initData:[],keyIds:new Set})});for(const d of a)d.video&&(d.video.drmInfos=c),d.audio&&(d.audio.drmInfos=c)}createDrmInfoByInfos_(a,b){const c=[],d=[],e=[],f=[],g=[],h=new Set,k=new Set;shaka.drm.DrmEngine.processDrmInfos_(b,c,d,f,e,g,h,k);c.length>1&&shaka.log.warning("Multiple unique encryption schemes found! Only the first will be used.");f.length>1&&shaka.log.warning("Multiple unique server certificates found! Only the first will be used.");
d.length>1&&shaka.log.warning("Multiple unique license server URIs found! Only the first will be used.");e.length>1&&shaka.log.warning("Multiple unique server certificate URIs found! Only the first will be used.");const l=this.usePersistentLicenses_?"persistent-license":"temporary";a={keySystem:a,encryptionScheme:c[0],licenseServerUri:d[0],distinctiveIdentifierRequired:b[0].distinctiveIdentifierRequired,persistentStateRequired:b[0].persistentStateRequired,sessionType:b[0].sessionType||l,audioRobustness:b[0].audioRobustness||
"",videoRobustness:b[0].videoRobustness||"",serverCertificate:f[0],serverCertificateUri:e[0],initData:g,keyIds:h,mediaTypes:b[0].mediaTypes};k.size>0&&(a.keySystemUris=k);for(const m of b)m.distinctiveIdentifierRequired&&(a.distinctiveIdentifierRequired=m.distinctiveIdentifierRequired),m.persistentStateRequired&&(a.persistentStateRequired=m.persistentStateRequired);return a}static processDrmInfos_(a,b,c,d,e,f,g,h){var k=[];for(const m of a){b.includes(m.encryptionScheme)||b.push(m.encryptionScheme);
shaka.drm.DrmUtils.isClearKeySystem(m.keySystem)&&m.licenseServerUri.startsWith("data:application/json;base64,")?k.includes(m.licenseServerUri)||k.push(m.licenseServerUri):c.includes(m.licenseServerUri)||c.push(m.licenseServerUri);e.includes(m.serverCertificateUri)||e.push(m.serverCertificateUri);m.serverCertificate&&(d.some(n=>shaka.util.BufferUtils.equal(n,m.serverCertificate))||d.push(m.serverCertificate));if(m.initData)for(const n of m.initData)f.some(q=>{q=q.keyId&&q.keyId==n.keyId?!0:q.initDataType==
n.initDataType&&shaka.util.BufferUtils.equal(q.initData,n.initData);return q})||f.push(n);if(m.keyIds)for(const n of m.keyIds)g.add(n);if(m.keySystemUris&&h)for(const n of m.keySystemUris)h.add(n)}if(k.length==1)c.push(k[0]);else if(k.length>0){a=[];for(var l of k)k=window.atob(l.split("data:application/json;base64,").pop()),k=JSON.parse(k),a.push(...k.keys);l=JSON.stringify({keys:a});c.push("data:application/json;base64,"+window.btoa(l))}}static fillInDrmInfoDefaults_(a,b,c,d){const e=a.keySystem;
if(e&&(!shaka.drm.DrmUtils.isClearKeySystem(e)||!a.licenseServerUri)){b.size&&b.get(e)&&(b=b.get(e),a.licenseServerUri=b);a.keyIds||(a.keyIds=new Set);if(c=c.get(e))a.distinctiveIdentifierRequired||(a.distinctiveIdentifierRequired=c.distinctiveIdentifierRequired),a.persistentStateRequired||(a.persistentStateRequired=c.persistentStateRequired),a.serverCertificate||(a.serverCertificate=c.serverCertificate),c.sessionType&&(a.sessionType=c.sessionType),a.serverCertificateUri||(a.serverCertificateUri=
c.serverCertificateUri);d[e]&&(a.keySystem=d[e]);window.cast&&window.cast.__platform__&&e=="com.microsoft.playready"&&(a.keySystem="com.chromecast.playready")}}parseInbandPssh(a,b){if(!this.config_.parseInbandPsshEnabled||this.manifestInitData_)return Promise.resolve();const c=shaka.util.ManifestParserUtils.ContentType;if(![c.AUDIO,c.VIDEO].includes(a))return Promise.resolve();a=new shaka.util.Pssh(shaka.util.BufferUtils.toUint8(b));b=0;for(var d of a.data)b+=d.length;if(b==0)return Promise.resolve();
d=new Uint8Array(b);b=0;for(const e of a.data)d.set(e,b),b+=e.length;this.newInitData("cenc",d);return this.allSessionsLoaded_}static configureClearKey(a,b){a=shaka.util.MapUtils.asMap(a);if(a.size!=0){a=shaka.util.ManifestParserUtils.createDrmInfoFromClearKeys(a);for(const c of b)c.video&&(c.video.drmInfos=[a]),c.audio&&(c.audio.drmInfos=[a])}}};shaka.drm.DrmEngine.CLOSE_TIMEOUT_=1;shaka.drm.DrmEngine.SESSION_LOAD_TIMEOUT_=5;shaka.drm.DrmEngine.KEY_STATUS_BATCH_TIME=.5;shaka.util.MediaElementEvent={CAN_PLAY:"canplay",CAN_PLAY_THROUGH:"canplaythrough",DURATION_CHANGE:"durationchange",ENCRYPTED:"encrypted",ENDED:"ended",LOADED_DATA:"loadeddata",LOADED_METADATA:"loadedmetadata",PAUSE:"pause",PLAY:"play",PLAYING:"playing",PROGRESS:"progress",RATE_CHANGE:"ratechange",SEEKED:"seeked",SEEKING:"seeking",STALLED:"stalled",TIME_UPDATE:"timeupdate",VOLUME_CHANGE:"volumechange",WAITING:"waiting"};shaka.media.BufferingObserver=class{constructor(a,b){const c=shaka.media.BufferingObserver.State;this.previousState_=c.SATISFIED;this.thresholds_=(new Map).set(c.SATISFIED,b).set(c.STARVING,a);this.lastRebufferTime_=0;this.lastReportedTime_=-1}setThresholds(a,b){const c=shaka.media.BufferingObserver.State;this.thresholds_.set(c.SATISFIED,b).set(c.STARVING,a)}update(a,b){const c=shaka.media.BufferingObserver.State,d=this.thresholds_.get(this.previousState_);return this.setState(b||a>=d&&a>0?c.SATISFIED:
c.STARVING)}setState(a){const b=shaka.media.BufferingObserver.State,c=this.previousState_!==a;this.previousState_=a;c&&a===b.SATISFIED&&(this.lastRebufferTime_=Date.now());return c}getState(){return this.previousState_}getLastRebufferTime(){return this.lastRebufferTime_}resetLastRebufferTime(){this.lastRebufferTime_=0}reportEvent(a,b){shaka.log.v2("BufferingObserver got event",a,"at time",b);const c=this.lastReportedTime_;this.lastReportedTime_=b;let d=void 0;switch(a){case shaka.util.MediaElementEvent.SEEKING:case shaka.util.MediaElementEvent.WAITING:this.lastReportedTime_=
-1;d=shaka.media.BufferingObserver.State.STARVING;break;case shaka.util.MediaElementEvent.CAN_PLAY_THROUGH:case shaka.util.MediaElementEvent.PLAYING:case shaka.util.MediaElementEvent.SEEKED:d=shaka.media.BufferingObserver.State.SATISFIED;break;case shaka.util.MediaElementEvent.TIME_UPDATE:c>=0&&b-c>.01&&(d=shaka.media.BufferingObserver.State.SATISFIED)}return d!==void 0?this.setState(d):!1}};shaka.media.BufferingObserver.State={STARVING:0,SATISFIED:1};shaka.media.ManifestFilterer=class{constructor(a,b,c){goog.asserts.assert(a,"Must have config");this.config_=a;this.maxHwRes_=b;this.drmEngine_=c}setDrmEngine(a){this.drmEngine_=a}async filterManifest(a){goog.asserts.assert(a,"Manifest should exist!");await shaka.util.StreamUtils.filterManifest(this.drmEngine_,a,this.config_.drm.preferredKeySystems,this.config_.drm.keySystemsMapping);this.config_.streaming.dontChooseCodecs||shaka.util.StreamUtils.chooseCodecsAndFilterManifest(a,this.config_.preferredVideoCodecs,
this.config_.preferredAudioCodecs,this.config_.preferredDecodingAttributes,this.config_.preferredTextFormats);this.checkPlayableVariants_(a);return this.filterManifestWithRestrictions(a)}applyRestrictions(a){return shaka.util.StreamUtils.applyRestrictions(a.variants,this.config_.restrictions,this.maxHwRes_)}filterManifestWithRestrictions(a){const b=this.applyRestrictions(a);if(a){const c=this.drmEngine_?this.drmEngine_.getDrmInfo():null;if(c&&this.drmEngine_.getMediaKeys()){const d=new Set;for(const e of a.variants)e.audio&&
d.add(e.audio),e.video&&d.add(e.video);for(const e of d)this.processDrmInfos(c.keySystem,e)}this.checkRestrictedVariants(a)}return b}checkPlayableVariants_(a){if(!a.variants.some(shaka.util.StreamUtils.isPlayable))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.CONTENT_UNSUPPORTED_BY_BROWSER);}processDrmInfos(a,b){for(const c of b.drmInfos)if(c.keySystem==a){for(const d of c.initData||[])this.drmEngine_.newInitData(d.initDataType,
d.initData);this.drmEngine_.updateCurrentDrmInfo(c)}}checkRestrictedVariants(a){const b=shaka.media.ManifestFilterer.restrictedStatuses,c=this.drmEngine_?this.drmEngine_.getKeyStatuses():{};var d=Object.keys(c);const e=d.length&&d[0]=="00";d=!1;const f=new Set,g=new Set,h=new WeakSet,k=l=>{if(l&&!h.has(l)&&(h.add(l),l.keyIds.size))for(const m of l.keyIds)(l=c[e?"00":m])?b.includes(l)&&g.add(l):f.add(m)};for(const l of a.variants){if(!l.allowedByApplication)d=!0;else if(l.allowedByKeySystem)return;
k(l.audio);k(l.video)}a={hasAppRestrictions:d,missingKeys:Array.from(f),restrictedKeyStatuses:Array.from(g)};throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.RESTRICTIONS_CANNOT_BE_MET,a);}};shaka.media.ManifestFilterer.restrictedStatuses=["output-restricted","internal-error"];shaka.config.CodecSwitchingStrategy={RELOAD:"reload",SMOOTH:"smooth"};goog.exportSymbol("shaka.config.CodecSwitchingStrategy",shaka.config.CodecSwitchingStrategy);shaka.media.Capabilities=class{static isTypeSupported(a){const b=shaka.media.Capabilities.MediaSourceTypeSupportMap;if(b.has(a))return b.get(a);var c=window.ManagedMediaSource||window.MediaSource;return c?(c=c.isTypeSupported(a),b.set(a,c),c):!1}static isInfiniteLiveStreamDurationSupported(){const a=window.ManagedMediaSource||window.MediaSource;return a&&a.prototype?!!a.prototype.setLiveSeekableRange&&!!a.prototype.clearLiveSeekableRange:!1}};shaka.media.Capabilities.MediaSourceTypeSupportMap=new Map;shaka.util.Mp4BoxParsers=class{static parseTFHD(a,b){let c=null,d=null,e=null,f=null;const g=a.readUint32();b&1&&(e=a.readUint64());b&2&&(f=a.readUint32());b&8&&(c=a.readUint32());b&16&&(d=a.readUint32());return{trackId:g,defaultSampleDuration:c,defaultSampleSize:d,baseDataOffset:e,sampleDescriptionIndex:f}}static parseTFDT(a,b){return{baseMediaDecodeTime:b==1?a.readUint64():a.readUint32()}}static parseTFDTInaccurate(a,b){return b==1?(b=a.readUint32(),a=a.readUint32(),{baseMediaDecodeTime:b*4294967296+
a}):{baseMediaDecodeTime:a.readUint32()}}static parsePRFTInaccurate(a,b){a.readUint32();var c=a.readUint32();const d=a.readUint32();c=c*1E3+d/2**32*1E3;b===0?a=a.readUint32():(b=a.readUint32(),a=a.readUint32(),a=b*4294967296+a);return{mediaTime:a,ntpTimestamp:c}}static parseMDHD(a,b){b==1?(a.skip(8),a.skip(8)):(a.skip(4),a.skip(4));b=a.readUint32();a.skip(4);a=a.readUint16();a=String.fromCharCode((a>>10)+96)+String.fromCharCode(((a&960)>>5)+96)+String.fromCharCode((a&31)+96);return{timescale:b,language:a}}static parseTREX(a){a.skip(4);
a.skip(4);const b=a.readUint32();a=a.readUint32();return{defaultSampleDuration:b,defaultSampleSize:a}}static parseTRUN(a,b,c){const d=a.readUint32(),e=[];let f=null;c&1&&(f=a.readInt32());c&4&&a.skip(4);for(let g=0;g<d;g++){const h={sampleDuration:null,sampleSize:null,sampleCompositionTimeOffset:null};c&256&&(h.sampleDuration=a.readUint32());c&512&&(h.sampleSize=a.readUint32());c&1024&&a.skip(4);c&2048&&(h.sampleCompositionTimeOffset=b==0?a.readUint32():a.readInt32());e.push(h)}return{sampleCount:d,
sampleData:e,dataOffset:f}}static parseTKHD(a,b){b==1?(a.skip(8),a.skip(8)):(a.skip(4),a.skip(4));const c=a.readUint32();b==1?a.skip(8):a.skip(4);a.skip(4);a.skip(8);a.skip(2);a.skip(2);a.skip(2);a.skip(2);a.skip(36);b=a.readUint16()+a.readUint16()/16;a=a.readUint16()+a.readUint16()/16;return{trackId:c,width:b,height:a}}static visualSampleEntry(a){a.skip(24);const b=a.readUint16(),c=a.readUint16();a.skip(50);return{width:b,height:c}}static audioSampleEntry(a){a.skip(6);a.skip(2);a.skip(8);const b=
a.readUint16();a.skip(2);a.skip(2);a.skip(2);a=a.readUint16()+a.readUint16()/65536;return{channelCount:b,sampleRate:a}}static parseESDS(a){let b="mp4a";for(var c,d;a.hasMoreData();){c=a.readUint8();for(var e=a.readUint8();e&128;)e=a.readUint8();if(c==3)a.readUint16(),e=a.readUint8(),e&128&&a.readUint16(),e&64&&a.skip(a.readUint8()),e&32&&a.readUint16();else if(c==4)d=a.readUint8(),a.skip(12);else if(c==5)break}d&&(b+="."+shaka.util.Mp4BoxParsers.toHex_(d),c==5&&a.hasMoreData()&&(c=a.readUint8(),d=
(c&248)>>3,d===31&&a.hasMoreData()&&(d=32+((c&7)<<3)+((a.readUint8()&224)>>5)),b+="."+d));return{codec:b}}static parseAVCC(a,b){const c=shaka.util.Mp4BoxParsers;b.skip(1);return{codec:a+"."+c.toHex_(b.readUint8())+c.toHex_(b.readUint8())+c.toHex_(b.readUint8())}}static parseHVCC(a,b){var c=shaka.util.Mp4BoxParsers;b.skip(1);var d=b.readUint8(),e=["","A","B","C"][d>>6],f=d&31;const g=b.readUint32(),h=(d&32)>>5?"H":"L";d=[b.readUint8(),b.readUint8(),b.readUint8(),b.readUint8(),b.readUint8(),b.readUint8()];
b=b.readUint8();a=a+("."+e+f)+("."+c.toHex_(c.reverseBits_(g),!0));a+="."+h+b;c="";for(e=d.length;e--;)if((f=d[e])||c)c="."+f.toString(16).toUpperCase()+c;a+=c;return{codec:a}}static parseDVCC(a,b){const c=shaka.util.Mp4BoxParsers;b.skip(2);const d=b.readUint8();b=b.readUint8();b=d<<5&32|b>>3&31;return{codec:a+"."+c.addLeadingZero_(d>>1&127)+"."+c.addLeadingZero_(b)}}static parseDVVC(a,b){const c=shaka.util.Mp4BoxParsers;b.skip(2);const d=b.readUint8();b=b.readUint8();b=d<<5&32|b>>3&31;return{codec:a+
"."+c.addLeadingZero_(d>>1&127)+"."+c.addLeadingZero_(b)}}static parseVPCC(a,b){const c=shaka.util.Mp4BoxParsers,d=b.readUint8(),e=b.readUint8();b=b.readUint8()>>4&15;return{codec:a+"."+c.addLeadingZero_(d)+"."+c.addLeadingZero_(e)+"."+c.addLeadingZero_(b)}}static parseAV1C(a,b){const c=shaka.util.Mp4BoxParsers;b.skip(1);const d=b.readUint8();var e=b.readUint8();b=d>>>5;const f=e>>>7?"H":"M";var g=(e&64)>>6;g=b===2&&g?(e&32)>>5?12:10:g?10:8;const h=(e&16)>>4,k=(e&8)>>3,l=(e&4)>>2;e&=3;return{codec:a+
"."+b+"."+c.addLeadingZero_(d&31)+f+"."+c.addLeadingZero_(g)+"."+h+"."+k+l+e+"."+c.addLeadingZero_(1)+"."+c.addLeadingZero_(1)+"."+c.addLeadingZero_(1)+".0"}}static parseFRMA(a){a=a.readUint32();return{codec:shaka.util.Mp4Parser.typeToString(a)}}static parseTENC(a){const b=shaka.util.Uint8ArrayUtils;a.readUint8();a.readUint8();a.readUint8();a.readUint8();a=a.readBytes(16,!1);return{defaultKID:b.toHex(a)}}static parseHDLR(a){a.skip(4);a=a.readBytes(4,!1);return{handlerType:String.fromCharCode(a[0],
a[1],a[2],a[3])}}static parsePRJI(a){return{projection:a.readTerminatedString()}}static parseHFOV(a){return{hfov:a.readUint32()/1E3}}static parseCOLR(a){let b=null,c=null;var d=a.readBytes(4,!1);let e;e=""+String.fromCharCode(d[0]);e+=String.fromCharCode(d[1]);e+=String.fromCharCode(d[2]);e+=String.fromCharCode(d[3]);if(e==="nclx"){switch(a.readUint16()){case 1:case 5:case 6:case 7:b="srgb";break;case 9:b="rec2020";break;case 11:case 12:b="p3"}d=a.readUint16();a.readUint16();switch(d){case 1:case 6:case 13:case 14:case 15:c=
"SDR";break;case 16:c="PQ";break;case 18:c="HLG"}}return{colorGamut:b,videoRange:c}}static updateAV1CodecWithCOLRBox(a,b){const c=shaka.util.Mp4BoxParsers,d=b.getPosition();var e=b.readBytes(4,!1);var f=""+String.fromCharCode(e[0]);f+=String.fromCharCode(e[1]);f+=String.fromCharCode(e[2]);f+=String.fromCharCode(e[3]);if(f==="nclx"){e=b.readUint16();f=b.readUint16();const g=b.readUint16(),h=b.readUint8()>>7,k=a.split(".");k.length==10&&(k[6]=c.addLeadingZero_(e),k[7]=c.addLeadingZero_(f),k[8]=c.addLeadingZero_(g),
k[9]=String(h),a=k.join("."))}b.seek(d);return a}static toHex_(a,b=!1){a=a.toString(16).toUpperCase();return b?a:("0"+a).slice(-2)}static reverseBits_(a){let b=0;for(let c=0;c<32;c++){b|=a&1;if(c==31)break;b<<=1;a>>=1}return b}static addLeadingZero_(a){return(a<10?"0":"")+a}};shaka.util.Mp4Generator=class{constructor(a=[]){this.streamInfos_=a}initSegment(){var a=shaka.util.Mp4Generator;const b=this.moov_();a=a.FTYP_.value();const c=new Uint8Array(a.byteLength+b.byteLength);c.set(a);c.set(b,a.byteLength);return c}moov_(){if(this.streamInfos_.length===0)throw Error("StreamInfos must have elements");const a=shaka.util.Mp4Generator,b=[];for(var c of this.streamInfos_)b.push(this.trak_(c));c=this.streamInfos_[0];return a.box("moov",this.mvhd_(c),...b,this.mvex_(),this.psshs(c.stream))}mvhd_(a){const b=
shaka.util.Mp4Generator;var c=a.duration*a.timescale;const d=Math.floor(c/(b.UINT32_MAX_+1));c=Math.floor(c%(b.UINT32_MAX_+1));a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,...this.breakNumberIntoBytes_(a.timescale,4),...this.breakNumberIntoBytes_(d,4),...this.breakNumberIntoBytes_(c,4),0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return b.box("mvhd",a)}trak_(a){return shaka.util.Mp4Generator.box("trak",
this.tkhd_(a),this.mdia_(a))}tkhd_(a){const b=shaka.util.Mp4Generator;var c=a.id+1;let d=a.stream.width||0,e=a.stream.height||0;a.type==shaka.util.ManifestParserUtils.ContentType.AUDIO&&(e=d=0);var f=a.duration*a.timescale;a=Math.floor(f/(b.UINT32_MAX_+1));f=Math.floor(f%(b.UINT32_MAX_+1));c=new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,...this.breakNumberIntoBytes_(c,4),0,0,0,0,...this.breakNumberIntoBytes_(a,4),...this.breakNumberIntoBytes_(f,4),0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,...this.breakNumberIntoBytes_(d,2),0,0,...this.breakNumberIntoBytes_(e,2),0,0]);return b.box("tkhd",c)}mdia_(a){return shaka.util.Mp4Generator.box("mdia",this.mdhd_(a),this.hdlr_(a),this.minf_(a))}mdhd_(a){const b=shaka.util.Mp4Generator;var c=a.duration*a.timescale;const d=Math.floor(c/(b.UINT32_MAX_+1));c=Math.floor(c%(b.UINT32_MAX_+1));var e=a.stream.language;e=e.charCodeAt(0)-96<<10|e.charCodeAt(1)-96<<5|e.charCodeAt(2)-96;a=new Uint8Array([1,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,...this.breakNumberIntoBytes_(a.timescale,4),...this.breakNumberIntoBytes_(d,4),...this.breakNumberIntoBytes_(c,4),...this.breakNumberIntoBytes_(e,2),0,0]);return b.box("mdhd",a)}hdlr_(a){const b=shaka.util.Mp4Generator,c=shaka.util.ManifestParserUtils.ContentType;let d=new Uint8Array([]);switch(a.type){case c.VIDEO:d=b.HDLR_TYPES_.video.value();break;case c.AUDIO:d=b.HDLR_TYPES_.audio.value()}return b.box("hdlr",d)}minf_(a){const b=shaka.util.Mp4Generator,c=
shaka.util.ManifestParserUtils.ContentType;switch(a.type){case c.VIDEO:return b.box("minf",b.box("vmhd",b.VMHD_.value()),b.DINF_.value(),this.stbl_(a));case c.AUDIO:return b.box("minf",b.box("smhd",b.SMHD_.value()),b.DINF_.value(),this.stbl_(a))}return new Uint8Array([])}stbl_(a){const b=shaka.util.Mp4Generator;return b.box("stbl",this.stsd_(a),b.box("stts",b.STTS_.value()),b.box("stsc",b.STSC_.value()),b.box("stsz",b.STSZ_.value()),b.box("stco",b.STCO_.value()))}stsd_(a){const b=shaka.util.Mp4Generator,
c=shaka.util.ManifestParserUtils.ContentType;let d="aac";a.codecs.includes("mp3")?d="mp3":a.codecs.includes("ac-3")?d=shaka.device.DeviceFactory.getDevice().requiresEC3InitSegments()?"ec-3":"ac-3":a.codecs.includes("ec-3")?d="ec-3":a.codecs.includes("opus")&&(d="opus");let e=new Uint8Array([]);switch(a.type){case c.VIDEO:a.codecs.includes("avc1")?e=this.avc1_(a):a.codecs.includes("hvc1")&&(e=this.hvc1_(a));break;case c.AUDIO:e=d=="mp3"?this.mp3_(a):d=="ac-3"?this.ac3_(a):d=="ec-3"?this.ec3_(a):d==
"opus"?this.opus_(a):this.mp4a_(a)}return b.box("stsd",b.STSD_.value(),e)}avc1_(a){const b=shaka.util.Mp4Generator;var c=a.stream.width||0,d=a.stream.height||0;let e;e=a.videoConfig.byteLength>0?b.box("avcC",a.videoConfig):b.box("avcC",this.avcC_(a));c=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,...this.breakNumberIntoBytes_(c,2),...this.breakNumberIntoBytes_(d,2),0,72,0,0,0,72,0,0,0,0,0,0,0,1,19,118,105,100,101,111,106,115,45,99,111,110,116,114,105,98,45,104,108,115,0,0,0,0,0,
0,0,0,0,0,0,0,0,24,17,17]);d="avc1";const f=this.pasp_(a);let g=new Uint8Array([]);b.isStreamEncrypted_(a.stream)&&(g=this.sinf(a.stream,a.codecs),d="encv");return b.box(d,c,e,f,g)}avcC_(a){var b=7,c=[];const d=[];var e=0;let f=0,g=0;for(let h=0;h<a.videoNalus.length;h++){const k=this.hexStringToBuffer_(a.videoNalus[h]);switch(k[0]&31){case 7:c.push(k);b+=k.length+2;break;case 8:d.push(k),b+=k.length+2}}c.length>0&&(e=c[0][1],g=c[0][2],f=c[0][3]);a=new Uint8Array(b);b=0;a[b++]=1;a[b++]=e;a[b++]=g;
a[b++]=f;a[b++]=255;a[b++]=224|c.length;for(e=0;e<c.length;e++)a[b++]=(c[e].length&65280)>>8,a[b++]=c[e].length&255,a.set(c[e],b),b+=c[e].length;a[b++]=d.length;for(c=0;c<d.length;c++)a[b++]=(d[c].length&65280)>>8,a[b++]=d[c].length&255,a.set(d[c],b),b+=d[c].length;return a}hvc1_(a){const b=shaka.util.Mp4Generator;var c=a.stream.width||0,d=a.stream.height||0;let e=new Uint8Array([]);a.videoConfig.byteLength>0&&(e=b.box("hvcC",a.videoConfig));c=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,...this.breakNumberIntoBytes_(c,2),...this.breakNumberIntoBytes_(d,2),0,72,0,0,0,72,0,0,0,0,0,0,0,1,19,118,105,100,101,111,106,115,45,99,111,110,116,114,105,98,45,104,108,115,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]);d="hvc1";const f=this.pasp_(a);let g=new Uint8Array([]);b.isStreamEncrypted_(a.stream)&&(g=this.sinf(a.stream,a.codecs),d="encv");return b.box(d,c,e,f,g)}pasp_(a){if(!a.hSpacing&&!a.vSpacing)return new Uint8Array([]);const b=shaka.util.Mp4Generator,c=a.vSpacing;a=new Uint8Array([...this.breakNumberIntoBytes_(a.hSpacing,
4),...this.breakNumberIntoBytes_(c,4)]);return b.box("pasp",a)}audioStsd_(a){return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,a.stream.channelsCount||2,0,16,0,0,0,0,...this.breakNumberIntoBytes_(a.stream.audioSamplingRate||44100,2),0,0])}mp3_(a){return shaka.util.Mp4Generator.box(".mp3",this.audioStsd_(a))}ac3_(a){const b=shaka.util.Mp4Generator,c=b.box("dac3",a.audioConfig);let d="ac-3",e=new Uint8Array([]);b.isStreamEncrypted_(a.stream)&&(e=this.sinf(a.stream,a.codecs),d="enca");return b.box(d,
this.audioStsd_(a),c,e)}ec3_(a){const b=shaka.util.Mp4Generator,c=b.box("dec3",a.audioConfig);let d="ec-3",e=new Uint8Array([]);b.isStreamEncrypted_(a.stream)&&(e=this.sinf(a.stream,a.codecs),d="enca");return b.box(d,this.audioStsd_(a),c,e)}opus_(a){const b=shaka.util.Mp4Generator,c=b.box("dOps",a.audioConfig);let d="Opus",e=new Uint8Array([]);b.isStreamEncrypted_(a.stream)&&(e=this.sinf(a.stream,a.codecs),d="enca");return b.box(d,this.audioStsd_(a),c,e)}mp4a_(a){const b=shaka.util.Mp4Generator;let c;
c=a.audioConfig.byteLength>0?b.box("esds",a.audioConfig):b.box("esds",this.esds_(a));let d="mp4a",e=new Uint8Array([]);b.isStreamEncrypted_(a.stream)&&(e=this.sinf(a.stream,a.codecs),d="enca");return b.box(d,this.audioStsd_(a),c,e)}esds_(a){const b=a.id+1,c=a.stream.channelsCount||2;var d=a.stream.audioSamplingRate||44100;const e=shaka.util.ManifestParserUtils.guessCodecs(shaka.util.ManifestParserUtils.ContentType.AUDIO,a.codecs.split(",")),f={96E3:0,88200:1,64E3:2,48E3:3,44100:4,32E3:5,24E3:6,22050:7,
16E3:8,12E3:9,11025:10,8E3:11,7350:12};a=f[d];if(e==="mp4a.40.5"||e==="mp4a.40.29")a=f[d*2];d=parseInt(e.split(".").pop(),10);return new Uint8Array([0,0,0,0,3,25,...this.breakNumberIntoBytes_(b,2),0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,d<<3|a>>>1,a<<7|c<<3,6,1,2])}mvex_(){const a=shaka.util.Mp4Generator,b=[];for(const c of this.streamInfos_)b.push(this.trex_(c));return a.box("mvex",...b)}trex_(a){const b=shaka.util.Mp4Generator;a=new Uint8Array([0,0,0,0,...this.breakNumberIntoBytes_(a.id+1,4),0,0,
0,1,0,0,0,0,0,0,0,0,0,0,0,0]);return b.box("trex",a)}psshs(a){const b=[];if(!shaka.util.Mp4Generator.isStreamEncrypted_(a))return new Uint8Array([]);for(const c of a.drmInfos)if(c.initData)for(const d of c.initData)b.push(d.initData);return shaka.util.Uint8ArrayUtils.concat(...b)}sinf(a,b){return shaka.util.Mp4Generator.box("sinf",this.frma_(b),this.schm_(a),this.schi_(a))}frma_(a){var b=a.split(".")[0];a=shaka.util.Mp4Generator;b=this.stringToCharCode_(b);b=new Uint8Array([...this.breakNumberIntoBytes_(b,
4)]);return a.box("frma",b)}schm_(a){var b="cenc";(a=a.drmInfos[0])&&a.encryptionScheme&&(b=a.encryptionScheme);a=shaka.util.Mp4Generator;b=this.stringToCharCode_(b);b=new Uint8Array([0,0,0,0,...this.breakNumberIntoBytes_(b,4),0,1,0,0]);return a.box("schm",b)}schi_(a){return shaka.util.Mp4Generator.box("schi",this.tenc_(a))}tenc_(a){let b=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);for(var c of a.drmInfos)if(c&&c.keyIds&&c.keyIds.size)for(const d of c.keyIds)b=this.hexStringToBuffer_(d);a=shaka.util.Mp4Generator;
c=new Uint8Array([0,0,0,0,0,0,1,8]);goog.asserts.assert(b,"Default KID should be non-null");return a.box("tenc",c,b)}segmentData(){const a=[];for(const b of this.streamInfos_)a.push(this.moof_(b),this.mdat_(b));return shaka.util.Uint8ArrayUtils.concat(...a)}moof_(a){return shaka.util.Mp4Generator.box("moof",this.mfhd_(a),this.traf_(a))}mfhd_(a){const b=shaka.util.Mp4Generator;a=new Uint8Array([0,0,0,0,...this.breakNumberIntoBytes_(a.data?a.data.sequenceNumber:0,4)]);return b.box("mfhd",a)}traf_(a){const b=
shaka.util.Mp4Generator,c=this.sdtp_(a),d=c.length+32+20+8+16+8+8;return b.box("traf",this.tfhd_(a),this.tfdt_(a),this.trun_(a,d),c)}sdtp_(a){const b=shaka.util.Mp4Generator;a=a.data?a.data.samples:[];const c=new Uint8Array(4+a.length);for(let d=0;d<a.length;d++){const e=a[d].flags;c[d+4]=e.dependsOn<<4|e.isDependedOn<<2|e.hasRedundancy}return b.box("sdtp",c)}tfhd_(a){const b=shaka.util.Mp4Generator;a=new Uint8Array([0,0,0,58,...this.breakNumberIntoBytes_(a.id+1,4),0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0]);
return b.box("tfhd",a)}tfdt_(a){const b=shaka.util.Mp4Generator;a=a.data?a.data.baseMediaDecodeTime:0;const c=Math.floor(a%(b.UINT32_MAX_+1));a=new Uint8Array([1,0,0,0,...this.breakNumberIntoBytes_(Math.floor(a/(b.UINT32_MAX_+1)),4),...this.breakNumberIntoBytes_(c,4)]);return b.box("tfdt",a)}trun_(a,b){var c=shaka.util.ManifestParserUtils.ContentType;const d=shaka.util.Mp4Generator,e=a.data?a.data.samples:[],f=e.length;var g=12+16*f;const h=new Uint8Array(g);b+=8+g;h.set([a.type===c.VIDEO?1:0,0,15,
1,...this.breakNumberIntoBytes_(f,4),...this.breakNumberIntoBytes_(b,4)],0);for(a=0;a<f;a++){var k=e[a];b=this.breakNumberIntoBytes_(k.duration,4);c=this.breakNumberIntoBytes_(k.size,4);g=k.flags;k=this.breakNumberIntoBytes_(k.cts,4);h.set([...b,...c,g.isLeading<<2|g.dependsOn,g.isDependedOn<<6|g.hasRedundancy<<4|g.isNonSync,g.degradPrio&61440,g.degradPrio&15,...k],12+16*a)}return d.box("trun",h)}mdat_(a){const b=shaka.util.Mp4Generator;a=(a.data?a.data.samples:[]).map(c=>c.data);return b.box("mdat",
...a)}breakNumberIntoBytes_(a,b){const c=[];for(--b;b>=0;b--)c.push(a>>8*b&255);return c}hexStringToBuffer_(a){const b=new Uint8Array(a.length/2);for(let c=0;c<a.length/2;c+=1)b[c]=parseInt(String(a[c*2]+a[c*2+1]),16);return b}stringToCharCode_(a){let b=0;for(let c=0;c<a.length;c+=1)b|=a.charCodeAt(c)<<(a.length-c-1)*8;return b}static box(a,...b){let c=shaka.util.Mp4Generator.BOX_TYPES_.get(a);c||(c=[a.charCodeAt(0),a.charCodeAt(1),a.charCodeAt(2),a.charCodeAt(3)],shaka.util.Mp4Generator.BOX_TYPES_.set(a,
c));a=8;for(var d=b.length-1;d>=0;d--)a+=b[d].byteLength;d=new Uint8Array(a);d[0]=a>>24&255;d[1]=a>>16&255;d[2]=a>>8&255;d[3]=a&255;d.set(c,4);for(let e=0,f=8;e<b.length;e++)d.set(b[e],f),f+=b[e].byteLength;return d}static isStreamEncrypted_(a){return a.encrypted&&a.drmInfos.length>0}};shaka.util.Mp4Generator.UINT32_MAX_=4294967295;shaka.util.Mp4Generator.BOX_TYPES_=new Map;
shaka.util.Mp4Generator.HDLR_TYPES_={video:new shaka.util.Lazy(()=>new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0])),audio:new shaka.util.Lazy(()=>new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]))};shaka.util.Mp4Generator.STTS_=new shaka.util.Lazy(()=>new Uint8Array([0,0,0,0,0,0,0,0]));
shaka.util.Mp4Generator.STSC_=new shaka.util.Lazy(()=>new Uint8Array([0,0,0,0,0,0,0,0]));shaka.util.Mp4Generator.STCO_=new shaka.util.Lazy(()=>new Uint8Array([0,0,0,0,0,0,0,0]));shaka.util.Mp4Generator.STSZ_=new shaka.util.Lazy(()=>new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]));shaka.util.Mp4Generator.VMHD_=new shaka.util.Lazy(()=>new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]));shaka.util.Mp4Generator.SMHD_=new shaka.util.Lazy(()=>new Uint8Array([0,0,0,0,0,0,0,0]));
shaka.util.Mp4Generator.STSD_=new shaka.util.Lazy(()=>new Uint8Array([0,0,0,0,0,0,0,1]));shaka.util.Mp4Generator.FTYP_=new shaka.util.Lazy(()=>{const a=new Uint8Array([105,115,111,109]),b=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);return shaka.util.Mp4Generator.box("ftyp",a,c,a,b)});
shaka.util.Mp4Generator.DINF_=new shaka.util.Lazy(()=>{var a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]);a=shaka.util.Mp4Generator.box("dref",a);return shaka.util.Mp4Generator.box("dinf",a)});shaka.media.ContentWorkarounds=class{static correctEnca(a){a=shaka.util.BufferUtils.toUint8(a);let b=null;(new shaka.util.Mp4Parser).boxes(["moov","trak","mdia","minf","stbl"],shaka.util.Mp4Parser.children).fullBox("stsd",shaka.util.Mp4Parser.sampleDescription).box("enca",c=>{b=c.reader.getDataView();return shaka.util.Mp4Parser.audioSampleEntry(c)}).box("sinf",shaka.util.Mp4Parser.children).box("frma",c=>{c.parser.stop();({codec:c}=shaka.util.Mp4BoxParsers.parseFRMA(c.reader));c==="ec-3"&&b&&b.getUint16(16)!==
2&&b.setUint16(16,2)}).parse(a);return a}static fakeEncryption(a,b,c){const d=shaka.media.ContentWorkarounds;let e=b=shaka.util.BufferUtils.toUint8(b),f=!1,g;const h=[],k=[];(new shaka.util.Mp4Parser).boxes(["moov","trak","mdia","minf","stbl"],l=>{h.push(l);shaka.util.Mp4Parser.children(l)}).fullBox("stsd",l=>{g=l;h.push(l);shaka.util.Mp4Parser.sampleDescription(l)}).boxes(["encv","enca"],l=>{f=!0;l.parser.stop()}).boxes("dvav dva1 dvh1 dvhe dvc1 dvi1 hev1 hvc1 avc1 avc3".split(" "),l=>{k.push({box:l,
newType:d.BOX_TYPE_ENCV_})}).boxes("ac-3 ec-3 ac-4 Opus fLaC mp4a".split(" "),l=>{k.push({box:l,newType:d.BOX_TYPE_ENCA_})}).parse(b);if(f)return shaka.log.debug("Init segment already indicates encryption."),b;if(k.length==0||!g)throw shaka.log.error("Failed to find boxes needed to fake encryption!"),shaka.log.v2("Failed init segment (hex):",shaka.util.Uint8ArrayUtils.toHex(b)),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.CONTENT_TRANSFORMATION_FAILED,
c);k.reverse();for(const l of k)c=shaka.util.Mp4Parser.typeToString(l.newType),shaka.log.debug(`Inserting "${c}" box into init segment.`),e=d.insertEncryptionMetadata_(a,e,g,l.box,h,l.newType);e=d.insertPsshBoxes_(a,e);return shaka.device.DeviceFactory.getDevice().requiresClearAndEncryptedInitSegments()?(a=new Uint8Array(b.byteLength+e.byteLength),a.set(e),a.set(b,e.byteLength),a):e}static fakeMediaEncryption(a){a=shaka.util.BufferUtils.toUint8(a);const b=[];(new shaka.util.Mp4Parser).box("mdat",
e=>{b.push(e)}).parse(a);const c=[];for(let e=0;e<b.length;e++){var d=b[e-1];const f=b[e];d=a.subarray(d?d.start+d.size:0,f.start+f.size);c.push(shaka.media.ContentWorkarounds.fakeMediaEncryptionInChunk_(d))}return shaka.util.Uint8ArrayUtils.concat(...c)}static fakeMediaEncryptionInChunk_(a){let b,c,d,e;const f=[];(new shaka.util.Mp4Parser).boxes(["moof","traf"],l=>{f.push(l);shaka.util.Mp4Parser.children(l)}).fullBox("tfhd",l=>{b=l;d=shaka.util.Mp4BoxParsers.parseTFHD(l.reader,l.flags)}).fullBox("trun",
l=>{c=l;e=shaka.util.Mp4BoxParsers.parseTRUN(l.reader,l.version,l.flags)}).parse(a);if(d&&d.sampleDescriptionIndex!==2){const l=b.start+shaka.util.Mp4Parser.headerSize(b)+4+(d.baseDataOffset!==null?8:0);var g=shaka.util.BufferUtils.toDataView(a);if(d.sampleDescriptionIndex!==null)g.setUint32(l,2);else{shaka.media.ContentWorkarounds.updateBoxSize_(a,b.start,b.size+4);var h=g.getUint32(b.start+8);g.setUint32(b.start+8,h|2);if(e&&e.dataOffset!==null){h=e.dataOffset+4;var k=c.start+shaka.util.Mp4Parser.headerSize(c)+
4;g.setInt32(k,h)}h=a.subarray(0,l);g=a.subarray(l);a=new Uint8Array(a.byteLength+4);a.set(h);h=[];for(k=3;k>=0;k--)h.push(2>>8*k&255);a.set(new Uint8Array(h),l);a.set(g,l+4);for(const m of f)shaka.media.ContentWorkarounds.updateBoxSize_(a,m.start,m.size+4)}}return a}static insertEncryptionMetadata_(a,b,c,d,e,f){var g=shaka.media.ContentWorkarounds;f=g.createEncryptionMetadata_(a,b,d,f);a=new Uint8Array(b.byteLength+f.byteLength);d=shaka.device.DeviceFactory.getDevice().insertEncryptionDataBeforeClear()?
d.start:d.start+d.size;const h=b.subarray(0,d);b=b.subarray(d);a.set(h);a.set(f,d);a.set(b,d+f.byteLength);for(const k of e)goog.asserts.assert(k.start<d,"Ancestor MP4 box found in the wrong location!  Modified init segment will not make sense!"),g.updateBoxSize_(a,k.start,k.size+f.byteLength);e=shaka.util.BufferUtils.toDataView(a,c.start);c=shaka.util.Mp4Parser.headerSize(c);g=e.getUint32(c);e.setUint32(c,g+1);return a}static createEncryptionMetadata_(a,b,c,d){const e=shaka.media.ContentWorkarounds;
a=(new shaka.util.Mp4Generator).sinf(a,c.name);b=b.subarray(c.start,c.start+c.size);const f=new Uint8Array(c.size+a.byteLength);f.set(b,0);shaka.util.BufferUtils.toDataView(f).setUint32(e.BOX_TYPE_OFFSET_,d);f.set(a,c.size);e.updateBoxSize_(f,0,f.byteLength);return f}static insertPsshBoxes_(a,b){a=(new shaka.util.Mp4Generator).psshs(a);if(a.byteLength===0)return b;let c=0,d=0;(new shaka.util.Mp4Parser).box("moov",h=>{c=h.start;d=h.size;h.parser.stop()}).parse(b);const e=c+d;shaka.media.ContentWorkarounds.updateBoxSize_(b,
c,d+a.byteLength);const f=new Uint8Array(b.byteLength+a.byteLength),g=b.subarray(0,e);b=b.subarray(e);f.set(g);f.set(a,e);f.set(b,e+a.byteLength);return f}static updateBoxSize_(a,b,c){const d=shaka.media.ContentWorkarounds;a=shaka.util.BufferUtils.toDataView(a,b);b=a.getUint32(d.BOX_SIZE_OFFSET_);b!=0&&(b==1?(a.setUint32(d.BOX_SIZE_64_OFFSET_,c>>32),a.setUint32(d.BOX_SIZE_64_OFFSET_+4,c&4294967295)):a.setUint32(d.BOX_SIZE_OFFSET_,c))}static fakeEC3(a){const b=shaka.media.ContentWorkarounds,c=shaka.util.BufferUtils.toUint8(a),
d=[];(new shaka.util.Mp4Parser).boxes(["moov","trak","mdia","minf","stbl"],e=>{d.push({start:e.start,size:e.size});shaka.util.Mp4Parser.children(e)}).box("stsd",e=>{d.push({start:e.start,size:e.size});const f=shaka.util.BufferUtils.toDataView(c,e.start);for(let g=0;g<e.size-3;g++){const h=f.getUint32(g);h==b.BOX_TYPE_AC_3_?f.setUint32(g,b.BOX_TYPE_EC_3_):h==b.BOX_TYPE_DAC3_&&f.setUint32(g,b.BOX_TYPE_DEC3_)}}).parse(c);return c}};shaka.media.ContentWorkarounds.BOX_SIZE_OFFSET_=0;
shaka.media.ContentWorkarounds.BOX_TYPE_OFFSET_=4;shaka.media.ContentWorkarounds.BOX_SIZE_64_OFFSET_=8;shaka.media.ContentWorkarounds.BOX_TYPE_ENCV_=1701733238;shaka.media.ContentWorkarounds.BOX_TYPE_ENCA_=1701733217;shaka.media.ContentWorkarounds.BOX_TYPE_AC_3_=1633889587;shaka.media.ContentWorkarounds.BOX_TYPE_DAC3_=1684103987;shaka.media.ContentWorkarounds.BOX_TYPE_EC_3_=1700998451;shaka.media.ContentWorkarounds.BOX_TYPE_DEC3_=1684366131;shaka.media.InitSegmentReference=class{constructor(a,b,c,d=null,e=null,f=null,g=null,h=!1){this.getUris=a;this.startByte=b;this.endByte=c;this.mediaQuality=d;this.timescale=e;this.segmentData=f;this.aesKey=g;this.boundaryEnd=this.mimeType=this.codecs=null;this.encrypted=h}getStartByte(){return this.startByte}getEndByte(){return this.endByte}getSize(){return this.endByte?this.endByte+1-this.startByte:null}getMediaQuality(){return this.mediaQuality}setSegmentData(a){this.segmentData=a}getSegmentData(){return this.segmentData}static equal(a,
b){const c=shaka.util.ArrayUtils,d=shaka.util.BufferUtils;return a===b?!0:a&&b?a.getStartByte()==b.getStartByte()&&a.getEndByte()==b.getEndByte()&&c.equal(a.getUris().sort(),b.getUris().sort())&&d.equal(a.getSegmentData(),b.getSegmentData()):a==b}};goog.exportSymbol("shaka.media.InitSegmentReference",shaka.media.InitSegmentReference);goog.exportProperty(shaka.media.InitSegmentReference.prototype,"getEndByte",shaka.media.InitSegmentReference.prototype.getEndByte);
goog.exportProperty(shaka.media.InitSegmentReference.prototype,"getStartByte",shaka.media.InitSegmentReference.prototype.getStartByte);
shaka.media.SegmentReference=class{constructor(a,b,c,d,e,f,g,h,k,l=[],m="",n=null,q=null,p=shaka.media.SegmentReference.Status.AVAILABLE,r=null,t=!1){goog.asserts.assert(a<=b,"startTime must be less than or equal to endTime");goog.asserts.assert(e==null||d<e,"startByte must be < endByte");this.startTime=a;this.trueEndTime=this.endTime=b;this.getUrisInner=c;this.startByte=d;this.endByte=e;this.initSegmentReference=f;this.timestampOffset=g;this.appendWindowStart=h;this.appendWindowEnd=k;this.partialReferences=
l;this.tilesLayout=m;this.tileDuration=n;this.syncTime=q;this.status=p;this.preload=!1;this.independent=!0;this.byterangeOptimization=!1;this.aesKey=r;this.thumbnailSprite=null;this.discontinuitySequence=-1;this.allPartialSegments=t;this.lastPartial=this.partial=!1;for(const u of this.partialReferences)u.markAsPartial();this.allPartialSegments&&this.partialReferences.length&&this.partialReferences[this.partialReferences.length-1].markAsLastPartial();this.segmentData=this.bandwidth=this.mimeType=this.codecs=
null;this.removeSegmentDataOnGet=!1}getUris(){return this.getUrisInner()}getStartTime(){return this.startTime}getEndTime(){return this.endTime}getStartByte(){return this.startByte}getEndByte(){return this.endByte}getSize(){if(this.endByte)return this.endByte+1-this.startByte;if(this.bandwidth){const a=this.bandwidth*(this.endTime-this.startTime);if(!isNaN(a)&&a>0)return a}if(this.hasPartialSegments()&&this.hasAllPartialSegments())for(const a of this.partialReferences){a.getSize();break}return null}hasPartialSegments(){return this.partialReferences.length>
0}hasAllPartialSegments(){return this.allPartialSegments}getTilesLayout(){return this.tilesLayout}getTileDuration(){return this.tileDuration}getStatus(){return this.status}markAsUnavailable(){this.status=shaka.media.SegmentReference.Status.UNAVAILABLE}markAsPreload(){this.preload=!0}isPreload(){return this.preload}markAsNonIndependent(){this.independent=!1}isIndependent(){return this.independent}markAsPartial(){this.partial=!0}isPartial(){return this.partial}markAsLastPartial(){this.lastPartial=!0}isLastPartial(){return this.lastPartial}markAsByterangeOptimization(){this.byterangeOptimization=
!0}hasByterangeOptimization(){return this.byterangeOptimization}setThumbnailSprite(a){this.thumbnailSprite=a}getThumbnailSprite(){return this.thumbnailSprite}offset(a){this.startTime+=a;this.endTime+=a;this.trueEndTime+=a;for(const b of this.partialReferences)b.startTime+=a,b.endTime+=a,b.trueEndTime+=a}syncAgainst(a){this.syncTime==null?shaka.log.alwaysError("Sync attempted without sync time!"):(a=this.syncTime-a-this.startTime,Math.abs(a)>=.001&&this.offset(a))}setSegmentData(a,b=!1){this.segmentData=
a;this.removeSegmentDataOnGet=b}getSegmentData(a=!0){const b=this.segmentData;a&&this.removeSegmentDataOnGet&&(this.segmentData=null);return b}updateInitSegmentReference(a){this.initSegmentReference=a;for(const b of this.partialReferences)b.updateInitSegmentReference(a)}};goog.exportSymbol("shaka.media.SegmentReference",shaka.media.SegmentReference);goog.exportProperty(shaka.media.SegmentReference.prototype,"getSegmentData",shaka.media.SegmentReference.prototype.getSegmentData);
goog.exportProperty(shaka.media.SegmentReference.prototype,"setSegmentData",shaka.media.SegmentReference.prototype.setSegmentData);goog.exportProperty(shaka.media.SegmentReference.prototype,"syncAgainst",shaka.media.SegmentReference.prototype.syncAgainst);goog.exportProperty(shaka.media.SegmentReference.prototype,"offset",shaka.media.SegmentReference.prototype.offset);goog.exportProperty(shaka.media.SegmentReference.prototype,"getThumbnailSprite",shaka.media.SegmentReference.prototype.getThumbnailSprite);
goog.exportProperty(shaka.media.SegmentReference.prototype,"setThumbnailSprite",shaka.media.SegmentReference.prototype.setThumbnailSprite);goog.exportProperty(shaka.media.SegmentReference.prototype,"hasByterangeOptimization",shaka.media.SegmentReference.prototype.hasByterangeOptimization);goog.exportProperty(shaka.media.SegmentReference.prototype,"markAsByterangeOptimization",shaka.media.SegmentReference.prototype.markAsByterangeOptimization);
goog.exportProperty(shaka.media.SegmentReference.prototype,"isLastPartial",shaka.media.SegmentReference.prototype.isLastPartial);goog.exportProperty(shaka.media.SegmentReference.prototype,"markAsLastPartial",shaka.media.SegmentReference.prototype.markAsLastPartial);goog.exportProperty(shaka.media.SegmentReference.prototype,"isPartial",shaka.media.SegmentReference.prototype.isPartial);goog.exportProperty(shaka.media.SegmentReference.prototype,"markAsPartial",shaka.media.SegmentReference.prototype.markAsPartial);
goog.exportProperty(shaka.media.SegmentReference.prototype,"isIndependent",shaka.media.SegmentReference.prototype.isIndependent);goog.exportProperty(shaka.media.SegmentReference.prototype,"markAsNonIndependent",shaka.media.SegmentReference.prototype.markAsNonIndependent);goog.exportProperty(shaka.media.SegmentReference.prototype,"isPreload",shaka.media.SegmentReference.prototype.isPreload);goog.exportProperty(shaka.media.SegmentReference.prototype,"markAsPreload",shaka.media.SegmentReference.prototype.markAsPreload);
goog.exportProperty(shaka.media.SegmentReference.prototype,"markAsUnavailable",shaka.media.SegmentReference.prototype.markAsUnavailable);goog.exportProperty(shaka.media.SegmentReference.prototype,"getStatus",shaka.media.SegmentReference.prototype.getStatus);goog.exportProperty(shaka.media.SegmentReference.prototype,"getTileDuration",shaka.media.SegmentReference.prototype.getTileDuration);goog.exportProperty(shaka.media.SegmentReference.prototype,"getTilesLayout",shaka.media.SegmentReference.prototype.getTilesLayout);
goog.exportProperty(shaka.media.SegmentReference.prototype,"getEndByte",shaka.media.SegmentReference.prototype.getEndByte);goog.exportProperty(shaka.media.SegmentReference.prototype,"getStartByte",shaka.media.SegmentReference.prototype.getStartByte);goog.exportProperty(shaka.media.SegmentReference.prototype,"getEndTime",shaka.media.SegmentReference.prototype.getEndTime);goog.exportProperty(shaka.media.SegmentReference.prototype,"getStartTime",shaka.media.SegmentReference.prototype.getStartTime);
goog.exportProperty(shaka.media.SegmentReference.prototype,"getUris",shaka.media.SegmentReference.prototype.getUris);shaka.media.SegmentReference.Status={AVAILABLE:0,UNAVAILABLE:1,MISSING:2};goog.exportProperty(shaka.media.SegmentReference,"Status",shaka.media.SegmentReference.Status);shaka.media.TimeRangesUtils=class{static isBufferNegligible_(a){return a.length==1&&a.end(0)-a.start(0)<1E-4}static bufferStart(a){return!a||shaka.media.TimeRangesUtils.isBufferNegligible_(a)?null:a.length==1&&a.start(0)<0?0:a.length?a.start(0):null}static bufferEnd(a){return!a||shaka.media.TimeRangesUtils.isBufferNegligible_(a)?null:a.length?a.end(a.length-1):null}static isBuffered(a,b){return!a||!a.length||shaka.media.TimeRangesUtils.isBufferNegligible_(a)||b>a.end(a.length-1)?!1:b>=a.start(0)}static bufferedAheadOf(a,
b){if(!a||!a.length||shaka.media.TimeRangesUtils.isBufferNegligible_(a))return 0;let c=0;for(const {start:d,end:e}of shaka.media.TimeRangesUtils.getBufferedInfo(a))e>b&&(c+=e-Math.max(d,b));return c}static getGapIndex(a,b,c){const d=shaka.media.TimeRangesUtils;if(!a||!a.length||shaka.media.TimeRangesUtils.isBufferNegligible_(a))return null;a=d.getBufferedInfo(a).findIndex((e,f,g)=>e.start>b&&(f==0||g[f-1].end-b<=c));return a>=0?a:null}static getBufferedInfo(a){if(!a)return[];const b=[];for(let c=
0;c<a.length;c++)b.push({start:a.start(c),end:a.end(c)});return b}static computeAddedRange(a,b){var c=shaka.media.TimeRangesUtils;if(!a||!a.length)return null;if(!b||!b.length)return c.getBufferedInfo(b).pop();b=c.getBufferedInfo(b).reverse();a=c.getBufferedInfo(a).reverse();for(const d of b){c=!1;for(const e of a)if(e.end>=d.start&&e.end<=d.end&&(c=!0,d.end>e.end))return{start:e.end,end:d.end};if(!c)return d}return null}};shaka.util.Dom=class{static createHTMLElement(a){return document.createElement(a)}static createSVGElement(a){return document.createElementNS("http://www.w3.org/2000/svg",a)}static createButton(){const a=document.createElement("button");a.setAttribute("type","button");return a}static createSourceElement(a,b=""){const c=document.createElement("source");c.src=a;c.type=b;return c}static clearSourceFromVideo(a){let b=!1;const c=a.getElementsByTagName("source");for(let d=c.length-1;d>=0;--d)a.removeChild(c[d]),
b=!0;a.src&&(a.removeAttribute("src"),b=!0);return b}static asHTMLElement(a){return a}static asHTMLCanvasElement(a){return a}static asHTMLMediaElement(a){return a}static getElementByClassName(a,b){b=b.getElementsByClassName(a);goog.asserts.assert(b.length==1,"Should only be one element with class name "+a);return shaka.util.Dom.asHTMLElement(b[0])}static getElementByClassNameIfItExists(a,b){b=b.getElementsByClassName(a);if(!b.length)return null;goog.asserts.assert(b.length==1,"Should only be one element with class name "+
a);return shaka.util.Dom.asHTMLElement(b[0])}static removeAllChildren(a){for(;a.firstChild;)a.removeChild(a.firstChild)}static anyMediaElement(){if(shaka.util.Dom.cachedMediaElement_)return shaka.util.Dom.cachedMediaElement_;shaka.util.Dom.cacheExpirationTimer_||(shaka.util.Dom.cacheExpirationTimer_=new shaka.util.Timer(()=>{shaka.util.Dom.cachedMediaElement_=null}));shaka.util.Dom.cachedMediaElement_=document.getElementsByTagName("video")[0]||document.getElementsByTagName("audio")[0];shaka.util.Dom.cachedMediaElement_||
(shaka.util.Dom.cachedMediaElement_=document.createElement("video"));shaka.util.Dom.cacheExpirationTimer_.tickAfter(1);return shaka.util.Dom.cachedMediaElement_}static async addFont(a,b){if("fonts"in document&&"FontFace"in window&&(await document.fonts.ready,"entries"in document.fonts)){var c=d=>{d=d.entries();const e=[];let f=d.next();for(;f.done===!1;)e.push(f.value),f=d.next();return e};for(const d of c(document.fonts))if(d.family===a&&d.display==="swap")return;a=new FontFace(a,`url(${b})`,{display:"swap"});
document.fonts.add(a)}}};goog.exportSymbol("shaka.util.Dom",shaka.util.Dom);goog.exportProperty(shaka.util.Dom,"removeAllChildren",shaka.util.Dom.removeAllChildren);goog.exportProperty(shaka.util.Dom,"clearSourceFromVideo",shaka.util.Dom.clearSourceFromVideo);shaka.util.Dom.cacheExpirationTimer_=null;shaka.util.Dom.cachedMediaElement_=null;shaka.util.Id3Utils=class{static isHeader_(a,b){return b+10<=a.length&&a[b]===73&&a[b+1]===68&&a[b+2]===51&&a[b+3]<255&&a[b+4]<255&&a[b+6]<128&&a[b+7]<128&&a[b+8]<128&&a[b+9]<128?!0:!1}static isFooter_(a,b){return b+10<=a.length&&a[b]===51&&a[b+1]===68&&a[b+2]===73&&a[b+3]<255&&a[b+4]<255&&a[b+6]<128&&a[b+7]<128&&a[b+8]<128&&a[b+9]<128?!0:!1}static readSize_(a,b){let c;c=(a[b]&127)<<21;c|=(a[b+1]&127)<<14;c|=(a[b+2]&127)<<7;return c|=a[b+3]&127}static getFrameData_(a){const b=String.fromCharCode(a[0],
a[1],a[2],a[3]),c=shaka.util.Id3Utils.readSize_(a,4);return{type:b,size:c,data:a.subarray(10,10+c)}}static decodeFrame_(a){var b=shaka.util.BufferUtils,c=shaka.util.StringUtils;const d={key:a.type,description:"",data:"",mimeType:null,pictureType:null};if(a.type==="APIC"){if(a.size<2)return null;if(a.data[0]!==shaka.util.Id3Utils.UTF8_encoding)return shaka.log.warning("Ignore frame with unrecognized character encoding"),null;const g=a.data.subarray(1).indexOf(0);if(g===-1)return null;var e=c.fromUTF8(b.toUint8(a.data,
1,g)),f=a.data[2+g];const h=a.data.subarray(3+g).indexOf(0);if(h===-1)return null;const k=c.fromUTF8(b.toUint8(a.data,3+g,h));a=e==="--\x3e"?c.fromUTF8(b.toUint8(a.data,4+g+h)):b.toArrayBuffer(a.data.subarray(4+g+h));d.mimeType=e;d.pictureType=f;d.description=k;d.data=a;return d}if(a.type==="TXXX"){if(a.size<2)return null;if(a.data[0]!==shaka.util.Id3Utils.UTF8_encoding)return shaka.log.warning("Ignore frame with unrecognized character encoding"),null;f=a.data.subarray(1).indexOf(0);if(f===-1)return null;
e=c.fromUTF8(b.toUint8(a.data,1,f));a=c.fromUTF8(b.toUint8(a.data,2+f)).replace(/\0*$/,"");d.description=e;d.data=a;return d}if(a.type==="WXXX"){if(a.size<2)return null;if(a.data[0]!==shaka.util.Id3Utils.UTF8_encoding)return shaka.log.warning("Ignore frame with unrecognized character encoding"),null;f=a.data.subarray(1).indexOf(0);if(f===-1)return null;e=c.fromUTF8(b.toUint8(a.data,1,f));a=c.fromUTF8(b.toUint8(a.data,2+f)).replace(/\0*$/,"");d.description=e;d.data=a;return d}if(a.type==="PRIV"){if(a.size<
2)return null;e=a.data.indexOf(0);if(e===-1)return null;c=c.fromUTF8(b.toUint8(a.data,0,e));d.description=c;c=="com.apple.streaming.transportStreamTimestamp"?(b=a.data.subarray(c.length+1),a=b[3]&1,b=(b[4]<<23)+(b[5]<<15)+(b[6]<<7)+b[7],b/=45,a&&(b+=4.772185884E7),d.data=b):(a=b.toArrayBuffer(a.data.subarray(c.length+1)),d.data=a);return d}if(a.type[0]==="T"){if(a.size<2)return null;if(a.data[0]!==shaka.util.Id3Utils.UTF8_encoding)return shaka.log.warning("Ignore frame with unrecognized character encoding"),
null;a=c.fromUTF8(a.data.subarray(1)).replace(/\0*$/,"");d.data=a;return d}return a.type[0]==="W"?(a=c.fromUTF8(a.data).replace(/\0*$/,""),d.data=a,d):a.data?(shaka.log.warning("Unrecognized ID3 frame type:",a.type),d.data=b.toArrayBuffer(a.data),d):null}static getID3Frames(a){const b=shaka.util.Id3Utils;let c=0;const d=[];for(;b.isHeader_(a,c);){var e=b.readSize_(a,c+6);a[c+5]>>6&1&&(c+=10);c+=10;for(e=c+e;c+10<e;){const f=b.getFrameData_(a.subarray(c)),g=b.decodeFrame_(f);g&&d.push(g);c+=f.size+
10}b.isFooter_(a,c)&&(c+=10)}return d}static getID3Data(a,b=0){const c=shaka.util.Id3Utils,d=b;let e=0;for(;c.isHeader_(a,b);){a[b+5]>>6&1&&(e+=10);e+=10;const f=c.readSize_(a,b+6);e+=f;c.isFooter_(a,b+10)&&(e+=10);b+=e}return e>0?a.subarray(d,d+e):new Uint8Array([])}};goog.exportSymbol("shaka.util.Id3Utils",shaka.util.Id3Utils);goog.exportProperty(shaka.util.Id3Utils,"getID3Data",shaka.util.Id3Utils.getID3Data);goog.exportProperty(shaka.util.Id3Utils,"getID3Frames",shaka.util.Id3Utils.getID3Frames);
shaka.util.Id3Utils.UTF8_encoding=3;shaka.util.NumberUtils=class{static isFloatEqual(a,b,c=Number.EPSILON){if(a===b)return!0;a=Math.abs(a-b);return a<=c?!0:c!==Number.EPSILON?Math.abs(a-c)<=Number.EPSILON:!1}};shaka.util.TimeUtils=class{static convertNtp(a){const b=Date.UTC(1900,0,1,0,0,0,0);return(new Date(b+a)).getTime()}};/*

 Copyright Brightcove, Inc.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/
shaka.util.ExpGolomb=class{constructor(a,b=!1){this.data_=a;b&&(this.data_=this.ebsp2rbsp_(a));this.workingBytesAvailable_=this.data_.byteLength;this.workingBitsAvailable_=this.workingWord_=0}ebsp2rbsp_(a){const b=new Uint8Array(a.byteLength);let c=0;for(let d=0;d<a.byteLength;d++)d>=2&&a[d]==3&&a[d-1]==0&&a[d-2]==0||(b[c]=a[d],c++);return shaka.util.BufferUtils.toUint8(b,0,c)}loadWord_(){const a=this.data_.byteLength-this.workingBytesAvailable_,b=Math.min(4,this.workingBytesAvailable_);if(b!==0){var c=
0;for(let d=0;d<b;d++)c=c<<8|this.data_[a+d];this.workingWord_=c<<(4-b)*8;this.workingBitsAvailable_=b*8;this.workingBytesAvailable_-=b}}skipBits(a){if(this.workingBitsAvailable_<=a){a-=this.workingBitsAvailable_;const b=Math.floor(a/8);a-=b*8;this.workingBitsAvailable_-=b;this.loadWord_()}this.workingWord_<<=a;this.workingBitsAvailable_-=a}readBits(a){let b=Math.min(this.workingBitsAvailable_,a);const c=this.workingWord_>>>32-b;this.workingBitsAvailable_-=b;this.workingBitsAvailable_>0?this.workingWord_<<=
b:this.workingBytesAvailable_>0&&this.loadWord_();b=a-b;return b>0?c<<b|this.readBits(b):c}skipLeadingZeros_(){let a=0;for(;this.workingBitsAvailable_===0;){if(this.workingBytesAvailable_===0)return a;this.loadWord_()}for(;;){let b=Math.clz32(this.workingWord_);b>this.workingBitsAvailable_&&(b=this.workingBitsAvailable_);a+=b;this.workingWord_<<=b;this.workingBitsAvailable_-=b;if(this.workingBitsAvailable_>0||this.workingBytesAvailable_===0)break;this.loadWord_()}return a}skipExpGolomb(){this.skipBits(1+
this.skipLeadingZeros_())}readUnsignedExpGolomb(){const a=this.skipLeadingZeros_();return this.readBits(a+1)-1}readExpGolomb(){const a=this.readUnsignedExpGolomb();return 1&a?1+a>>>1:-1*(a>>>1)}readBoolean(){return this.readBits(1)===1}readUnsignedByte(){return this.readBits(8)}skipScalingList(a){let b=8;var c=8;for(let d=0;d<a;d++)c!==0&&(c=this.readExpGolomb(),c=(b+c+256)%256),b=c===0?b:c}readSliceType(){this.readUnsignedByte();this.readUnsignedExpGolomb();return this.readUnsignedExpGolomb()}};
goog.exportSymbol("shaka.util.ExpGolomb",shaka.util.ExpGolomb);shaka.util.TsParser=class{constructor(){this.pmtId_=null;this.pmtParsed_=!1;this.videoCodec_=this.videoPid_=null;this.videoData_=[];this.videoDataPesIndices_=[];this.videoPes_=[];this.audioCodec_=this.audioPid_=null;this.audioData_=[];this.audioDataPesIndices_=[];this.audioPes_=[];this.id3Pid_=null;this.id3Data_=[];this.id3DataPesIndices_=[];this.discontinuitySequence_=this.opusMetadata_=this.referenceDts_=this.referencePts_=null}clearData(){this.videoData_=[];this.videoDataPesIndices_=[];this.videoPes_=
[];this.audioData_=[];this.audioDataPesIndices_=[];this.audioPes_=[];this.id3Data_=[];this.id3DataPesIndices_=[]}setDiscontinuitySequence(a){this.discontinuitySequence_!=null&&this.discontinuitySequence_!=a&&(this.referenceDts_=this.referencePts_=null);this.discontinuitySequence_=a}parse(a){const b=shaka.util.TsParser.PacketLength_;if(a.length<3*b)return this;const c=Math.max(0,shaka.util.TsParser.syncOffset(a)),d=a.length-(a.length+c)%b;let e=!1;for(let h=c;h<d;h+=b)if(a[h]==71){var f=!!(a[h+1]&
64),g=((a[h+1]&31)<<8)+a[h+2];let k;if((a[h+3]&48)>>4>1){if(k=h+5+a[h+4],k==h+b)continue}else k=h+4;switch(g){case 0:f&&(k+=a[k]+1);this.pmtId_=this.getPmtId_(a,k);break;case 17:case 8191:break;case this.pmtId_:f&&(k+=a[k]+1);f=this.parsePMT_(a,k);f.video!=-1&&(this.videoPid_=f.video,this.videoCodec_=f.videoCodec);f.audio!=-1&&(this.audioPid_=f.audio,this.audioCodec_=f.audioCodec);f.id3!=-1&&(this.id3Pid_=f.id3);e&&!this.pmtParsed_&&(shaka.log.debug("reparse from beginning"),e=!1,h=c-b);this.pmtParsed_=
!0;break;case this.videoPid_:g=a.subarray(k,h+b);f?(this.videoDataPesIndices_.push(this.videoData_.length),this.videoData_.push(g)):this.videoDataPesIndices_.length&&this.videoData_.push(g);break;case this.audioPid_:g=a.subarray(k,h+b);f?(this.audioDataPesIndices_.push(this.audioData_.length),this.audioData_.push(g)):this.audioDataPesIndices_.length&&this.audioData_.push(g);break;case this.id3Pid_:g=a.subarray(k,h+b);f?(this.id3DataPesIndices_.push(this.id3Data_.length),this.id3Data_.push(g)):this.id3DataPesIndices_.length&&
this.id3Data_.push(g);break;default:e=!0}}else shaka.log.warning("Found TS packet that do not start with 0x47");return this}getPmtId_(a,b){return(a[b+10]&31)<<8|a[b+11]}parsePMT_(a,b){const c={audio:-1,video:-1,id3:-1,audioCodec:"",videoCodec:""},d=b+3+((a[b+1]&15)<<8|a[b+2])-4;for(b+=12+((a[b+10]&15)<<8|a[b+11]);b<d;){const f=(a[b+1]&31)<<8|a[b+2],g=(a[b+3]&15)<<8|a[b+4];switch(a[b]){case 6:if(g>0){let h=b+5,k=g;for(;k>2;){const l=a[h+1]+2;switch(a[h]){case 5:var e=h+2;e=a[e]<<24|a[e+1]<<16|a[e+
2]<<8|a[e+3];c.audio==-1&&e===1332770163?(c.audio=f,c.audioCodec="opus"):c.video==-1&&e===1096167473&&(c.video=f,c.videoCodec="av1");break;case 106:c.audio==-1&&(c.audio=f,c.audioCodec="ac3");break;case 122:c.audio==-1&&(c.audio=f,c.audioCodec="ec3");break;case 124:c.audio==-1&&(c.audio=f,c.audioCodec="aac");break;case 127:c.audioCodec=="opus"&&(e=null,a[h+2]===128&&(e=a[h+3]),e!=null&&(this.opusMetadata_={channelCount:(e&15)===0?2:e&15,channelConfigCode:e,sampleRate:48E3}))}h+=l;k-=l}}break;case 15:c.audio==
-1&&(c.audio=f,c.audioCodec="aac");break;case 17:c.audio==-1&&(c.audio=f,c.audioCodec="aac-loas");break;case 21:c.id3==-1&&(c.id3=f);break;case 27:c.video==-1&&(c.video=f,c.videoCodec="avc");break;case 3:case 4:c.audio==-1&&(c.audio=f,c.audioCodec="mp3");break;case 36:c.video==-1&&(c.video=f,c.videoCodec="hvc");break;case 129:c.audio==-1&&(c.audio=f,c.audioCodec="ac3");break;case 132:case 135:c.audio==-1&&(c.audio=f,c.audioCodec="ec3")}b+=g+5}return c}concatPesPackets_(a,b,c){return shaka.util.Uint8ArrayUtils.concatRange(a,
b[c],c+1<b.length?b[c+1]:a.length)}parsePES_(a){if((a[0]<<16|a[1]<<8|a[2])!==1)return null;const b=a[4]<<8|a[5];if(b&&b>a.byteLength-6)return null;let c=null;var d=null;const e=a[7];if(e&192){var f=(a[9]&14)*536870912+(a[10]&255)*4194304+(a[11]&254)*16384+(a[12]&255)*128+(a[13]&254)/2;this.referencePts_==null&&(this.referencePts_=f);d=this.referencePts_=c=this.handleRollover_(f,this.referencePts_);e&64&&(d=(a[14]&14)*536870912+(a[15]&255)*4194304+(a[16]&254)*16384+(a[17]&255)*128+(a[18]&254)/2,this.referenceDts_==
null&&(this.referenceDts_=d),d=c!=f?this.handleRollover_(d,this.referenceDts_):d);this.referenceDts_=d}f=a[8]+9;return a.byteLength<=f?null:{data:a.subarray(f),packetLength:b,pts:c,dts:d,nalus:[]}}parseAvcNalus(a,b){shaka.Deprecate.deprecateFeature(5,"TsParser.parseAvcNalus","Please use parseNalus function instead.");return this.parseNalus(a,{nalu:null,state:null})}parseNalus(a,b){var c=shaka.util.TsParser.Timescale,d=a.pts?a.pts/c:null;a=a.data;const e=a.byteLength;let f=1;this.videoCodec_=="hvc"&&
(f=2);var g=b.state||0;const h=g;let k=0;c=[];let l=-1,m=0;const n=this.videoCodec_==="hvc";g==-1&&(l=0,m=n?a[0]>>1&63:a[0]&31,g=0,k=1);for(;k<e;){var q=a[k++];if(g)if(g===1)g=q?0:2;else if(q)if(q==1){q=k-g-1;if(l>=0)g={data:a.subarray(l+f,q),fullData:a.subarray(l,q),type:m,time:d,state:null},c.push(g);else if(g=c.length?c[c.length-1]:b.nalu)h&&k<=4-h&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-h),g.fullData=g.fullData.subarray(0,g.fullData.byteLength-h)),q>0&&(q=a.subarray(0,q),g.data=
shaka.util.Uint8ArrayUtils.concat(g.data,q),g.fullData=shaka.util.Uint8ArrayUtils.concat(g.fullData,q),g.state=0);k<e?(m=n?a[k]>>1&63:a[k]&31,l=k,g=0):g=-1}else g=0;else g=3;else g=q?0:1}l>=0&&g>=0&&(d={data:a.subarray(l+f,e),fullData:a.subarray(l,e),type:m,time:d,state:g},c.push(d));!c.length&&b.nalu&&(d=c.length?c[c.length-1]:b.nalu)&&(d.data=shaka.util.Uint8ArrayUtils.concat(d.data,a),d.fullData=shaka.util.Uint8ArrayUtils.concat(d.fullData,a));b.state=g;return c}getMetadata(){const a=shaka.util.TsParser.Timescale,
b=[];for(let d=0;d<this.id3DataPesIndices_.length;d++){var c=this.concatPesPackets_(this.id3Data_,this.id3DataPesIndices_,d);(c=this.parsePES_(c))&&b.push({cueTime:c.pts?c.pts/a:null,data:c.data,frames:shaka.util.Id3Utils.getID3Frames(c.data),dts:c.dts,pts:c.pts})}return b}getAudioData(){if(this.audioDataPesIndices_.length&&!this.audioPes_.length)for(let b=0;b<this.audioDataPesIndices_.length;b++){var a=this.concatPesPackets_(this.audioData_,this.audioDataPesIndices_,b);const c=this.parsePES_(a);
let d=this.audioPes_.length?this.audioPes_[this.audioPes_.length-1]:null;c&&c.pts!=null&&c.dts!=null&&(!d||d.pts!=c.pts&&d.dts!=c.dts)?this.audioPes_.push(c):this.audioPes_.length&&(a=c?c.data:a)&&(d=this.audioPes_[this.audioPes_.length-1],d.data=shaka.util.Uint8ArrayUtils.concat(d.data,a))}return this.audioPes_}getVideoData(a=!0){if(this.videoDataPesIndices_.length&&!this.videoPes_.length){for(var b=0;b<this.videoDataPesIndices_.length;b++){var c=this.concatPesPackets_(this.videoData_,this.videoDataPesIndices_,
b);const e=this.parsePES_(c);var d=this.videoPes_.length?this.videoPes_[this.videoPes_.length-1]:null;e&&e.pts!=null&&e.dts!=null&&(!d||d.pts!=e.pts&&d.dts!=e.dts)?this.videoPes_.push(e):this.videoPes_.length&&(c=e?e.data:c)&&(d=this.videoPes_[this.videoPes_.length-1],d.data=shaka.util.Uint8ArrayUtils.concat(d.data,c))}if(a){b={nalu:null,state:null};d=[];for(const e of this.videoPes_)e.nalus=this.parseNalus(e,b),e.nalus.length&&(d.push(e),b.nalu=e.nalus[e.nalus.length-1]);this.videoPes_=d}}return a?
this.videoPes_:(a=this.videoPes_,this.videoPes_=[],a)}getStartTime(a){const b=shaka.util.TsParser.Timescale;if(a=="audio"){a=null;var c=this.getAudioData();c.length&&(a=c[0],a=Math.min(a.dts,a.pts)/b);return a}return a=="video"?(a=null,c=this.getVideoData(!1),c.length&&(a=c[0],a=Math.min(a.dts,a.pts)/b),a):null}getCodecs(){return{audio:this.audioCodec_,video:this.videoCodec_}}getVideoNalus(){const a=[];for(const b of this.getVideoData())a.push(...b.nalus);return a}getVideoResolution(){shaka.Deprecate.deprecateFeature(5,
"TsParser.getVideoResolution","Please use getVideoInfo function instead.");const a=this.getVideoInfo();return{height:a.height,width:a.width}}getVideoInfo(){return this.videoCodec_=="hvc"?this.getHvcInfo_():this.getAvcInfo_()}getFrameRate_(){const a=shaka.util.TsParser.Timescale;var b=this.getVideoData();if(b.length>1){const c=b[0].pts;goog.asserts.assert(typeof c=="number","Should be an number!");b=b[1].pts;goog.asserts.assert(typeof b=="number","Should be an number!");if(!isNaN(b-c))return String(Math.abs(1/
(b-c)*a))}return null}getAvcInfo_(){const a=shaka.util.TsParser,b={height:null,width:null,codec:null,frameRate:null};var c=this.getVideoNalus();if(!c.length)return b;c=c.find(p=>p.type==a.H264_NALU_TYPE_SPS_);if(!c)return b;c=new shaka.util.ExpGolomb(c.data);const d=c.readUnsignedByte(),e=c.readUnsignedByte(),f=c.readUnsignedByte();c.skipExpGolomb();if(a.PROFILES_WITH_OPTIONAL_SPS_DATA_.includes(d)){var g=c.readUnsignedExpGolomb();g===3&&c.skipBits(1);c.skipExpGolomb();c.skipExpGolomb();c.skipBits(1);
if(c.readBoolean()){g=g!==3?8:12;for(var h=0;h<g;h++)c.readBoolean()&&(h<6?c.skipScalingList(16):c.skipScalingList(64))}}c.skipExpGolomb();g=c.readUnsignedExpGolomb();if(g===0)c.readUnsignedExpGolomb();else if(g===1)for(c.skipBits(1),c.skipExpGolomb(),c.skipExpGolomb(),g=c.readUnsignedExpGolomb(),h=0;h<g;h++)c.skipExpGolomb();c.skipExpGolomb();c.skipBits(1);g=c.readUnsignedExpGolomb();h=c.readUnsignedExpGolomb();const k=c.readBits(1);k===0&&c.skipBits(1);c.skipBits(1);let l=0,m=0,n=0,q=0;c.readBoolean()&&
(l=c.readUnsignedExpGolomb(),m=c.readUnsignedExpGolomb(),n=c.readUnsignedExpGolomb(),q=c.readUnsignedExpGolomb());b.height=String((2-k)*(h+1)*16-n*2-q*2);b.width=String((g+1)*16-l*2-m*2);b.codec="avc1."+this.byteToHex_(d)+this.byteToHex_(e)+this.byteToHex_(f);b.frameRate=this.getFrameRate_();return b}getHvcInfo_(){const a=shaka.util.TsParser,b={height:null,width:null,codec:null,frameRate:null};var c=this.getVideoNalus();if(!c.length)return b;c=c.find(w=>w.type==a.H265_NALU_TYPE_SPS_);if(!c)return b;
var d=new shaka.util.ExpGolomb(c.fullData,!0);d.readUnsignedByte();d.readUnsignedByte();d.readBits(4);var e=d.readBits(3);d.readBoolean();const f=d.readBits(2);var g=d.readBits(1),h=d.readBits(5),k=d.readBits(32);c=d.readUnsignedByte();const l=d.readUnsignedByte(),m=d.readUnsignedByte(),n=d.readUnsignedByte(),q=d.readUnsignedByte(),p=d.readUnsignedByte(),r=d.readUnsignedByte();var t=[],u=[];for(var v=0;v<e;v++)t.push(d.readBoolean()),u.push(d.readBoolean());if(e>0)for(v=e;v<8;v++)d.readBits(2);for(v=
0;v<e;v++)t[v]&&d.readBits(88),u[v]&&d.readUnsignedByte();d.readUnsignedExpGolomb();e=d.readUnsignedExpGolomb();e==3&&d.readBits(1);t=d.readUnsignedExpGolomb();u=d.readUnsignedExpGolomb();let x=v=0,y=0,A=0;d.readBoolean()&&(v+=d.readUnsignedExpGolomb(),x+=d.readUnsignedExpGolomb(),y+=d.readUnsignedExpGolomb(),A+=d.readUnsignedExpGolomb());b.width=String(t-(v+x)*(e===1||e===2?2:1));b.height=String(u-(y+A)*(e===1?2:1));d=["","A","B","C"][f];k=(w=>{let z=0;for(let B=0;B<32;B++)z|=(w>>B&1)<<31-B;return z>>>
0})(k);g=g==1?"H":"L";h="hvc1"+("."+d+h)+("."+k.toString(16).toUpperCase());h+="."+g+r;p&&(h+="."+p.toString(16).toUpperCase());q&&(h+="."+q.toString(16).toUpperCase());n&&(h+="."+n.toString(16).toUpperCase());m&&(h+="."+m.toString(16).toUpperCase());l&&(h+="."+l.toString(16).toUpperCase());c&&(h+="."+c.toString(16).toUpperCase());b.codec=h;b.frameRate=this.getFrameRate_();return b}getOpusMetadata(){return this.opusMetadata_}byteToHex_(a){return("0"+a.toString(16).toUpperCase()).slice(-2)}handleRollover_(a,
b){let c=1;for(a>b&&(c=-1);Math.abs(b-a)>4294967296;)a+=c*8589934592;return a}static probe(a){a=shaka.util.TsParser.syncOffset(a);if(a<0)return!1;a>0&&shaka.log.warning("MPEG2-TS detected but first sync word found @ offset "+a+", junk ahead ?");return!0}static syncOffset(a){const b=shaka.util.TsParser.PacketLength_,c=Math.min(1E3,a.length-3*b);let d=0;for(;d<c;){if(a[d]==71&&a[d+b]==71&&a[d+2*b]==71)return d;const e=a.indexOf(71,d+1);d=e>=0&&e<c?e:d+1}return-1}};
goog.exportSymbol("shaka.util.TsParser",shaka.util.TsParser);goog.exportProperty(shaka.util.TsParser,"syncOffset",shaka.util.TsParser.syncOffset);goog.exportProperty(shaka.util.TsParser,"probe",shaka.util.TsParser.probe);goog.exportProperty(shaka.util.TsParser.prototype,"getVideoInfo",shaka.util.TsParser.prototype.getVideoInfo);goog.exportProperty(shaka.util.TsParser.prototype,"getVideoResolution",shaka.util.TsParser.prototype.getVideoResolution);
goog.exportProperty(shaka.util.TsParser.prototype,"getVideoNalus",shaka.util.TsParser.prototype.getVideoNalus);goog.exportProperty(shaka.util.TsParser.prototype,"getCodecs",shaka.util.TsParser.prototype.getCodecs);goog.exportProperty(shaka.util.TsParser.prototype,"getStartTime",shaka.util.TsParser.prototype.getStartTime);goog.exportProperty(shaka.util.TsParser.prototype,"getVideoData",shaka.util.TsParser.prototype.getVideoData);goog.exportProperty(shaka.util.TsParser.prototype,"getAudioData",shaka.util.TsParser.prototype.getAudioData);
goog.exportProperty(shaka.util.TsParser.prototype,"getMetadata",shaka.util.TsParser.prototype.getMetadata);goog.exportProperty(shaka.util.TsParser.prototype,"parseNalus",shaka.util.TsParser.prototype.parseNalus);goog.exportProperty(shaka.util.TsParser.prototype,"parseAvcNalus",shaka.util.TsParser.prototype.parseAvcNalus);goog.exportProperty(shaka.util.TsParser.prototype,"parse",shaka.util.TsParser.prototype.parse);goog.exportProperty(shaka.util.TsParser.prototype,"setDiscontinuitySequence",shaka.util.TsParser.prototype.setDiscontinuitySequence);
goog.exportProperty(shaka.util.TsParser.prototype,"clearData",shaka.util.TsParser.prototype.clearData);shaka.util.TsParser.Timescale=9E4;goog.exportProperty(shaka.util.TsParser,"Timescale",shaka.util.TsParser.Timescale);shaka.util.TsParser.PacketLength_=188;shaka.util.TsParser.H264_NALU_TYPE_SPS_=7;shaka.util.TsParser.H265_NALU_TYPE_SPS_=33;shaka.util.TsParser.PROFILES_WITH_OPTIONAL_SPS_DATA_=[100,110,122,244,44,83,86,118,128,138,139,134];shaka.media.MediaSourceEngine=class{constructor(a,b,c,d,e){this.video_=a;this.playerInterface_=c;this.config_=d;this.textDisplayer_=b;this.sourceBuffers_=new Map;this.sourceBufferTypes_=new Map;this.expectedEncryption_=new Map;this.textEngine_=null;this.segmentRelativeVttTiming_=!1;this.lcevcDec_=e||null;this.queues_=new Map;this.eventManager_=new shaka.util.EventManager;this.transmuxers_=new Map;this.captionParser_=null;this.mediaSourceOpen_=new shaka.util.PublicPromise;this.url_="";this.playbackHasBegun_=
!1;this.streamingAllowed_=!0;this.usingRemotePlayback_=!1;this.secondarySource_=this.source_=null;this.mediaSource_=this.createMediaSource(this.mediaSourceOpen_);this.playAfterReset_=this.reloadingMediaSource_=!1;this.destroyer_=new shaka.util.Destroyer(()=>this.doDestroy_());this.sequenceMode_=!1;this.manifestType_=shaka.media.ManifestParser.UNKNOWN;this.attemptTimestampOffsetCalculation_=this.ignoreManifestTimestampsInSegmentsMode_=!1;this.textSequenceModeOffset_=new shaka.util.PublicPromise;this.needSplitMuxedContent_=
!1;this.lastDuration_=null;this.tsParsers_=new Map;this.firstAudioReferenceStartTime_=this.firstAudioTimestamp_=this.firstVideoReferenceStartTime_=this.firstVideoTimestamp_=null;this.audioCompensation_=new shaka.util.PublicPromise;this.video_.remote&&(this.usingRemotePlayback_=this.video_.remote.state!="disconnected",this.eventManager_.listen(this.video_.remote,"connect",()=>{this.usingRemotePlayback_=this.video_.remote.state!="disconnected"}),this.eventManager_.listen(this.video_.remote,"connecting",
()=>{this.usingRemotePlayback_=this.video_.remote.state!="disconnected"}),this.eventManager_.listen(this.video_.remote,"disconnect",()=>{this.usingRemotePlayback_=this.video_.remote.state!="disconnected"}))}createMediaSource(a){this.streamingAllowed_=!0;let b;window.ManagedMediaSource?(this.secondarySource_||(this.video_.disableRemotePlayback=!0),b=new ManagedMediaSource,this.eventManager_.listen(b,"startstreaming",()=>{shaka.log.info("MMS startstreaming");this.streamingAllowed_=!0}),this.eventManager_.listen(b,
"endstreaming",()=>{shaka.log.info("MMS endstreaming");this.streamingAllowed_=!1})):b=new MediaSource;this.eventManager_.listenOnce(b,"sourceopen",()=>this.onSourceOpen_(a));this.eventManager_.listenOnce(this.video_,"playing",()=>{this.playbackHasBegun_=!0});this.url_=shaka.media.MediaSourceEngine.createObjectURL(b);this.removeSources_();this.config_.useSourceElements?(this.source_=shaka.util.Dom.createSourceElement(this.url_),this.video_.appendChild(this.source_),this.secondarySource_&&this.video_.appendChild(this.secondarySource_),
this.video_.load()):this.video_.src=this.url_;return b}addSecondarySource(a,b){this.video_&&window.ManagedMediaSource&&this.mediaSource_?this.config_.useSourceElements&&(this.secondarySource_?.parentElement===this.video_&&this.video_.removeChild(this.secondarySource_),this.secondarySource_=shaka.util.Dom.createSourceElement(a,b),this.video_.appendChild(this.secondarySource_),this.video_.disableRemotePlayback=!1):shaka.log.warning("Secondary source is used only with ManagedMediaSource")}onSourceOpen_(a){goog.asserts.assert(this.url_,
"Must have object URL");URL.revokeObjectURL(this.url_);a.resolve()}static probeSupport(){const a=shaka.util.MimeUtils;var b=['video/mp4; codecs="avc1.42E01E"','video/mp4; codecs="avc3.42E01E"','video/mp4; codecs="hev1.1.6.L93.90"','video/mp4; codecs="hvc1.1.6.L93.90"','video/mp4; codecs="hev1.2.4.L153.B0"; eotf="smpte2084"','video/mp4; codecs="hvc1.2.4.L153.B0"; eotf="smpte2084"','video/mp4; codecs="hvc1.2.20000000.L153.B0"','video/mp4; codecs="hvc1.2.4.L120.b0"','video/mp4; codecs="hvc1.2.4.L123.b0"',
'video/mp4; codecs="vp9"','video/mp4; codecs="vp09.00.10.08"','video/mp4; codecs="av01.0.01M.08"','video/mp4; codecs="av01.0.31M.10.0.111.09.16.09.0"','video/mp4; codecs="av01.0.31M.10.0.112.09.18.09.0"','video/mp4; codecs="dvh1.05.01"','video/mp4; codecs="dvh1.08.01"','video/mp4; codecs="dav1.10.01"','video/mp4; codecs="dvh1.20.01"','audio/mp4; codecs="mp4a.40.2"','audio/mp4; codecs="ac-3"','audio/mp4; codecs="ec-3"','audio/mp4; codecs="ac-4.02.01.03"','audio/mp4; codecs="opus"','audio/mp4; codecs="flac"',
'audio/mp4; codecs="dtsc"','audio/mp4; codecs="dtse"','audio/mp4; codecs="dtsx"','audio/mp4; codecs="apac.31.00"','video/webm; codecs="vp8"','video/webm; codecs="vp9"','video/webm; codecs="vp09.00.10.08"','audio/webm; codecs="vorbis"','audio/webm; codecs="opus"','video/mp2t; codecs="avc1.42E01E"','video/mp2t; codecs="avc3.42E01E"','video/mp2t; codecs="hvc1.1.6.L93.90"','video/mp2t; codecs="mp4a.40.2"','video/mp2t; codecs="ac-3"','video/mp2t; codecs="ec-3"',"text/vtt",'application/mp4; codecs="wvtt"',
"application/ttml+xml",'application/mp4; codecs="stpp"',...a.RAW_FORMATS];const c={},d=shaka.device.DeviceFactory.getDevice();for(const e of b){if(shaka.text.TextEngine.isTypeSupported(e))c[e]=!0;else if(d.supportsMediaSource()){b=a.getBasicType(e);const f=shaka.util.StreamUtils.getCorrectAudioCodecs(a.getCodecs(e),b);b=a.getFullType(b,f);c[e]=shaka.media.Capabilities.isTypeSupported(b)||shaka.transmuxer.TransmuxerEngine.isSupported(b)}else c[e]=d.supportsMediaType(e);b=e.split(";")[0];c[b]=c[b]||
c[e]}return c}destroy(){return this.destroyer_.destroy()}async doDestroy_(){const a=shaka.util.Functional,b=[];for(const [c,d]of this.queues_){const e=d[0];this.queues_.set(c,d.slice(0,1));e&&b.push(e.p.catch(a.noop));for(const f of d.slice(1))f.p.reject(shaka.util.Destroyer.destroyedError())}this.textEngine_&&b.push(this.textEngine_.destroy());await Promise.all(b);for(const c of this.transmuxers_.values())c.destroy();this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null);this.video_&&
(this.removeSources_(),this.video_.load(),this.video_.disableRemotePlayback=!1);this.textDisplayer_=this.textEngine_=this.mediaSource_=this.config_=this.secondarySource_=this.source_=this.video_=null;this.sourceBuffers_.clear();this.expectedEncryption_.clear();this.transmuxers_.clear();this.captionParser_=null;if(goog.DEBUG)for(const [c,d]of this.queues_)goog.asserts.assert(d.length==0,c+" queue should be empty after destroy!");this.queues_.clear();this.lcevcDec_=null;this.tsParsers_.clear();this.playerInterface_=
null}removeSources_(){this.video_&&(this.video_.removeAttribute("src"),this.source_?.parentElement===this.video_&&this.video_.removeChild(this.source_),this.secondarySource_?.parentElement===this.video_&&this.video_.removeChild(this.secondarySource_))}open(){return this.mediaSourceOpen_}async init(a,b=!1,c=shaka.media.ManifestParser.UNKNOWN,d=!1){const e=shaka.util.ManifestParserUtils.ContentType;await this.mediaSourceOpen_;if(this.ended()||this.closed())shaka.log.alwaysError("Expected MediaSource to be open during init(); reopening the media source."),
this.mediaSourceOpen_=new shaka.util.PublicPromise,this.mediaSource_=this.createMediaSource(this.mediaSourceOpen_),await this.mediaSourceOpen_;this.sequenceMode_=b;this.manifestType_=c;this.ignoreManifestTimestampsInSegmentsMode_=d;this.attemptTimestampOffsetCalculation_=!this.sequenceMode_&&this.manifestType_==shaka.media.ManifestParser.HLS&&!this.ignoreManifestTimestampsInSegmentsMode_;this.tsParsers_.clear();this.firstAudioReferenceStartTime_=this.firstAudioTimestamp_=this.firstVideoReferenceStartTime_=
this.firstVideoTimestamp_=null;this.audioCompensation_=new shaka.util.PublicPromise;for(const f of a.keys())b=a.get(f),this.initSourceBuffer_(f,b,b.codecs),this.needSplitMuxedContent_?(this.queues_.set(e.AUDIO,[]),this.queues_.set(e.VIDEO,[])):this.queues_.set(f,[]);(a=a.get(e.AUDIO))&&a.isAudioMuxedInVideo&&(this.needSplitMuxedContent_=!0)}initSourceBuffer_(a,b,c){var d=shaka.util.ManifestParserUtils.ContentType;a==d.AUDIO&&c&&(c=shaka.util.StreamUtils.getCorrectAudioCodecs(c,b.mimeType));a==d.VIDEO&&
c&&b.mimeType=="video/mp4"&&(c=shaka.util.StreamUtils.getCorrectVideoCodecs(c));var e=shaka.util.MimeUtils.getFullType(b.mimeType,c);if(a==d.TEXT)this.reinitText(e,this.sequenceMode_,b.external);else{var f=this.config_.forceTransmux;if(!shaka.media.Capabilities.isTypeSupported(e)||!this.sequenceMode_&&shaka.util.MimeUtils.RAW_FORMATS.includes(e))f=!0;var g=shaka.util.MimeUtils.getFullTypeWithAllCodecs(b.mimeType,c);if(f){f=shaka.util.ManifestParserUtils.guessCodecsSafe(d.AUDIO,(c||"").split(","));
c=shaka.util.ManifestParserUtils.guessCodecsSafe(d.VIDEO,(c||"").split(","));if(f&&c){this.needSplitMuxedContent_=!0;this.initSourceBuffer_(d.AUDIO,b,f);this.initSourceBuffer_(d.VIDEO,b,c);return}if(d=shaka.transmuxer.TransmuxerEngine.findTransmuxer(g))e=d(),this.transmuxers_.set(a,e),e=e.convertCodecs(a,g)}g=this.addExtraFeaturesToMimeType_(e);this.destroyer_.ensureNotDestroyed();let h;try{h=this.mediaSource_.addSourceBuffer(g)}catch(k){throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_THREW,k,"The mediaSource_ status was "+this.mediaSource_.readyState+" expected 'open'",null);}this.sequenceMode_&&(h.mode=shaka.media.MediaSourceEngine.SourceBufferMode_.SEQUENCE);this.eventManager_.listen(h,"error",()=>this.onError_(a));this.eventManager_.listen(h,"updateend",()=>this.onUpdateEnd_(a));this.sourceBuffers_.set(a,h);this.sourceBufferTypes_.set(a,e);this.expectedEncryption_.set(a,!!b.drmInfos.length)}}configure(a){this.config_=
a;this.textEngine_&&this.textEngine_.setModifyCueCallback(a.modifyCueCallback)}isStreamingAllowed(){return this.streamingAllowed_&&!this.usingRemotePlayback_&&!this.reloadingMediaSource_}reinitText(a,b,c){this.textEngine_||(this.textEngine_=new shaka.text.TextEngine(this.textDisplayer_),this.textEngine_.setModifyCueCallback(this.config_.modifyCueCallback));this.textEngine_.initParser(a,b,c,this.segmentRelativeVttTiming_,this.manifestType_)}ended(){return this.reloadingMediaSource_?!1:this.mediaSource_?
this.mediaSource_.readyState=="ended":!0}closed(){return this.reloadingMediaSource_?!1:this.mediaSource_?this.mediaSource_.readyState=="closed":!0}bufferStart(a){return this.sourceBuffers_.size?a==shaka.util.ManifestParserUtils.ContentType.TEXT?this.textEngine_.bufferStart():shaka.media.TimeRangesUtils.bufferStart(this.getBuffered_(a)):null}bufferEnd(a){return this.sourceBuffers_.size?a==shaka.util.ManifestParserUtils.ContentType.TEXT?this.textEngine_.bufferEnd():shaka.media.TimeRangesUtils.bufferEnd(this.getBuffered_(a)):
null}isBuffered(a,b){if(a==shaka.util.ManifestParserUtils.ContentType.TEXT)return this.textEngine_.isBuffered(b);a=this.getBuffered_(a);return shaka.media.TimeRangesUtils.isBuffered(a,b)}bufferedAheadOf(a,b){if(a==shaka.util.ManifestParserUtils.ContentType.TEXT)return this.textEngine_.bufferedAheadOf(b);a=this.getBuffered_(a);return shaka.media.TimeRangesUtils.bufferedAheadOf(a,b)}getBufferedInfo(){var a=shaka.util.ManifestParserUtils.ContentType,b=shaka.media.TimeRangesUtils;a={total:this.reloadingMediaSource_?
[]:b.getBufferedInfo(this.video_.buffered),audio:b.getBufferedInfo(this.getBuffered_(a.AUDIO)),video:b.getBufferedInfo(this.getBuffered_(a.VIDEO)),text:[]};if(this.textEngine_){b=this.textEngine_.bufferStart();const c=this.textEngine_.bufferEnd();b!=null&&c!=null&&a.text.push({start:b,end:c})}return a}getBuffered_(a){if(this.reloadingMediaSource_||this.usingRemotePlayback_||this.closed())return null;try{return this.sourceBuffers_.get(a).buffered}catch(b){return this.sourceBuffers_.has(a)&&shaka.log.error("failed to get buffered range for "+
a,b),null}}getCaptionParser(a){return new shaka.media.ClosedCaptionParser(a)}getTimestampAndDispatchMetadata(a,b,c,d,e,f=!1){let g=null;var h=[],k=shaka.util.BufferUtils.toUint8(b);if(shaka.util.MimeUtils.RAW_FORMATS.includes(e))b=shaka.util.Id3Utils.getID3Frames(k),b.length&&c&&((f=b.find(l=>l.description==="com.apple.streaming.transportStreamTimestamp"))&&typeof f.data=="number"&&(g=Math.round(f.data)/1E3),this.playerInterface_.onMetadata([{cueTime:c.startTime,data:k,frames:b,dts:c.startTime,pts:c.startTime}],
0,c.endTime));else if(e.includes("/mp4")&&c&&c.initSegmentReference){k=shaka.util.Mp4Parser;a=new k;const l=d.emsgSchemeIdUris!=null&&d.emsgSchemeIdUris.length>0||this.config_.dispatchAllEmsgBoxes,m=[];l&&a.fullBox("emsg",r=>{(r=this.parseEMSG_(c,d.emsgSchemeIdUris,r))&&m.push(r)});const n=c.initSegmentReference.timescale;e=n&&!isNaN(n);let q=0,p=!1;e&&a.fullBox("prft",r=>{goog.asserts.assert(typeof n=="number","Timescale should be a number!");this.parsePrft_(n,r)}).boxes(["moof","traf"],k.children).fullBox("tfdt",
r=>{p||(goog.asserts.assert(r.version==0||r.version==1,"TFDT version can only be 0 or 1"),goog.asserts.assert(typeof n=="number","Timescale should be a number!"),q=shaka.util.Mp4BoxParsers.parseTFDTInaccurate(r.reader,r.version).baseMediaDecodeTime/n,p=!0,l||r.parser.stop())});(l||e)&&a.parse(b,!1,f);p&&c.timestampOffset==0&&(g=q);for(const r of m)this.dispatchEmsg_(r,c,g)}else e.includes("/mp4")||e.includes("/webm")||!shaka.util.TsParser.probe(k)||(this.tsParsers_.has(a)||this.tsParsers_.set(a,new shaka.util.TsParser),
h=this.tsParsers_.get(a),h.clearData(),h.setDiscontinuitySequence(c.discontinuitySequence),h.parse(k),b=h.getStartTime(a),b!=null&&(g=b),h=h.getMetadata());return{timestamp:g,metadata:h}}parseEMSG_(a,b,c){let d,e,f,g,h,k,l;c.version===0?(g=c.reader.readTerminatedString(),l=c.reader.readTerminatedString(),d=c.reader.readUint32(),k=c.reader.readUint32(),f=c.reader.readUint32(),e=c.reader.readUint32(),h=a.startTime+k/d):(d=c.reader.readUint32(),h=c.reader.readUint64()/d+a.timestampOffset,k=h-a.startTime,
f=c.reader.readUint32(),e=c.reader.readUint32(),g=c.reader.readTerminatedString(),l=c.reader.readTerminatedString());a=c.reader.readBytes(c.reader.getLength()-c.reader.getPosition(),!0);if(b&&b.includes(g)||this.config_.dispatchAllEmsgBoxes)if(g=="urn:mpeg:dash:event:2012")this.playerInterface_.onManifestUpdate();else{b=h;if(g!=="https://aomedia.org/emsg/ID3"||f!==4294967295)b+=f/d;return{startTime:h,endTime:b,schemeIdUri:g,value:l,timescale:d,presentationTimeDelta:k,eventDuration:f,id:e,messageData:a}}return null}dispatchEmsg_(a,
b,c){const d=shaka.util.NumberUtils.isFloatEqual(a.startTime,b.startTime+a.presentationTimeDelta/a.timescale);c&&this.manifestType_==shaka.media.ManifestParser.HLS&&!d&&(b=-c+b.startTime,a.startTime+=b,a.endTime+=b);this.playerInterface_.onEmsg(a);!a.messageData||a.schemeIdUri!="https://aomedia.org/emsg/ID3"&&a.schemeIdUri!="https://developer.apple.com/streaming/emsg-id3"||(b=shaka.util.Id3Utils.getID3Frames(a.messageData),b.length&&(c=a.startTime,this.playerInterface_.onMetadata([{cueTime:c,data:a.messageData,
frames:b,dts:c,pts:c}],0,a.endTime)))}parsePrft_(a,b){goog.asserts.assert(b.version==0||b.version==1,"PRFT version can only be 0 or 1");b=shaka.util.Mp4BoxParsers.parsePRFTInaccurate(b.reader,b.version);const c=shaka.util.TimeUtils.convertNtp(b.ntpTimestamp);b={wallClockTime:c,programStartDate:new Date(c-b.mediaTime/a*1E3)};a=shaka.util.FakeEvent.EventName.Prft;b=(new Map).set("detail",b);a=new shaka.util.FakeEvent(a,b);this.playerInterface_.onEvent(a)}async appendBuffer(a,b,c,d,e,f=!1,g=!1,h=!1,
k=!1,l){var m=shaka.util.ManifestParserUtils.ContentType;if(a==m.TEXT)this.manifestType_==shaka.media.ManifestParser.HLS&&(f=await this.textSequenceModeOffset_,this.textEngine_.setTimestampOffset(f)),await this.textEngine_.appendBuffer(b,c?c.startTime:null,c?c.endTime:null,c?c.getUris()[0]:null);else if(!k&&this.needSplitMuxedContent_)await this.appendBuffer(m.AUDIO,b,c,d,e,f,g,h,!0),await this.appendBuffer(m.VIDEO,b,c,d,e,f,g,h,!0);else if(this.sourceBuffers_.has(a)){var n=this.sourceBuffers_.get(a).timestampOffset;
k=this.sourceBufferTypes_.get(a);this.transmuxers_.has(a)&&(k=this.transmuxers_.get(a).getOriginalMimeType());if(c){const {timestamp:r,metadata:t}=this.getTimestampAndDispatchMetadata(a,b,c,d,k,h);if(r!=null){if(this.firstVideoTimestamp_==null&&a==m.VIDEO&&(this.firstVideoTimestamp_=r,this.firstVideoReferenceStartTime_=c.startTime,this.firstAudioTimestamp_!=null)){var q=0;this.firstVideoReferenceStartTime_==this.firstAudioReferenceStartTime_&&(q=this.firstVideoTimestamp_-this.firstAudioTimestamp_);
this.audioCompensation_.resolve(q)}this.firstAudioTimestamp_==null&&a==m.AUDIO&&(this.firstAudioTimestamp_=r,this.firstAudioReferenceStartTime_=c.startTime,this.firstVideoTimestamp_!=null&&(q=0,this.firstVideoReferenceStartTime_==this.firstAudioReferenceStartTime_&&(q=this.firstVideoTimestamp_-this.firstAudioTimestamp_),this.audioCompensation_.resolve(q)));q=r;const u=shaka.util.MimeUtils.RAW_FORMATS;!this.sequenceMode_&&u.includes(this.sourceBufferTypes_.get(a))&&(q=0);q=c.startTime-q;(Math.abs(n-
q)>=.001||f||g)&&(!h||q>0||!n)&&(n=q,this.attemptTimestampOffsetCalculation_&&(this.enqueueOperation_(a,()=>this.abort_(a),null),this.enqueueOperation_(a,()=>this.setTimestampOffset_(a,n),null)));a!=m.VIDEO&&this.sourceBuffers_.has(m.VIDEO)||this.textSequenceModeOffset_.resolve(n)}if(t.length)this.playerInterface_.onMetadata(t,n,c?c.endTime:null)}e&&a==m.VIDEO&&(this.textEngine_||this.reinitText(shaka.util.MimeUtils.CEA608_CLOSED_CAPTION_MIMETYPE,this.sequenceMode_,!1),this.captionParser_||(e=k.split(";",
1)[0],this.captionParser_=this.getCaptionParser(e)),c?(l=this.captionParser_.parseFrom(b),l.length&&this.textEngine_.storeAndAppendClosedCaptions(l,n)):this.captionParser_.init(b,g,l));if(this.transmuxers_.has(a))if(l=await this.transmuxers_.get(a).transmux(b,d,c,this.mediaSource_.duration,a),ArrayBuffer.isView(l))b=l;else{if(l.init!=null){const r=l.init;this.enqueueOperation_(a,()=>{this.append_(a,r,n,d)},c?c.getUris()[0]:null)}b=l.data}b=this.workAroundBrokenPlatforms_(d,b,c,a);if(c&&this.sequenceMode_&&
a!=m.TEXT&&(f||g)){let r=c.startTime;this.manifestType_==shaka.media.ManifestParser.HLS&&!this.needSplitMuxedContent_&&a==m.AUDIO&&this.sourceBuffers_.has(m.VIDEO)&&(f=await this.audioCompensation_,Math.abs(f)>.15&&(r-=f));this.enqueueOperation_(a,()=>this.abort_(a),null);this.enqueueOperation_(a,()=>this.setTimestampOffset_(a,r),null)}var p=null;await this.enqueueOperation_(a,()=>{goog.DEBUG&&c&&!c.isPreload()&&!h&&(p=this.getBuffered_(a));this.append_(a,b,n,d)},c?c.getUris()[0]:null);goog.DEBUG&&
c&&!c.isPreload()&&!h&&(f=this.getBuffered_(a),f=shaka.media.TimeRangesUtils.computeAddedRange(p,f))&&(g=c.endTime-c.startTime,m=f.end-f.start,l=Math.abs(f.end-c.endTime),g>.1&&(l>g/2||Math.abs(g-m)>.03)&&shaka.log.error("Possible encoding problem detected!","Unexpected buffered range for reference",c,"from URIs",c.getUris(),"should be",{start:c.startTime,end:c.endTime},"but got",f))}else shaka.log.warning("Attempted to restore a non-existent source buffer")}setSelectedClosedCaptionId(a){const b=
this.bufferEnd(shaka.util.ManifestParserUtils.ContentType.VIDEO)||0;this.textEngine_.setSelectedClosedCaptionId(a,b)}clearSelectedClosedCaptionId(){this.textEngine_&&this.textEngine_.setSelectedClosedCaptionId("",0)}async remove(a,b,c,d){const e=shaka.util.ManifestParserUtils.ContentType;a==e.VIDEO&&this.captionParser_&&(this.captionParser_.remove(d),d=this.textEngine_.bufferStart()||0,this.textEngine_.remove(d,c,!0));a==e.TEXT?await this.textEngine_.remove(b,c):c>b&&(await this.enqueueOperation_(a,
()=>this.remove_(a,b,c),null),this.needSplitMuxedContent_&&await this.enqueueOperation_(e.AUDIO,()=>this.remove_(e.AUDIO,b,c),null))}async clear(a){const b=shaka.util.ManifestParserUtils.ContentType;a==b.TEXT?this.textEngine_&&await this.textEngine_.remove(0,Infinity):(a===b.VIDEO&&this.captionParser_&&this.textEngine_&&await this.textEngine_.remove(0,Infinity,!0),await this.enqueueOperation_(a,()=>this.remove_(a,0,this.mediaSource_.duration),null),this.needSplitMuxedContent_&&await this.enqueueOperation_(b.AUDIO,
()=>this.remove_(b.AUDIO,0,this.mediaSource_.duration),null))}resetCaptionParser(){this.captionParser_&&this.captionParser_.reset()}async flush(a){const b=shaka.util.ManifestParserUtils.ContentType;a!=b.TEXT&&(await this.enqueueOperation_(a,()=>this.flush_(a),null),this.needSplitMuxedContent_&&await this.enqueueOperation_(b.AUDIO,()=>this.flush_(b.AUDIO),null))}async setStreamProperties(a,b,c,d,e,f,g,h){const k=shaka.util.ManifestParserUtils.ContentType;if(a==k.TEXT)e||this.textEngine_.setTimestampOffset(b),
this.textEngine_.setAppendWindow(c,d);else{var l=[];await this.codecSwitchIfNecessary_(a,f,g,h)||(l.push(this.enqueueOperation_(a,()=>this.abort_(a),null)),this.needSplitMuxedContent_&&l.push(this.enqueueOperation_(k.AUDIO,()=>this.abort_(k.AUDIO),null)));e||(l.push(this.enqueueOperation_(a,()=>this.setTimestampOffset_(a,b),null)),this.needSplitMuxedContent_&&l.push(this.enqueueOperation_(k.AUDIO,()=>this.setTimestampOffset_(k.AUDIO,b),null)));if(c!=0||d!=Infinity)l.push(this.enqueueOperation_(a,
()=>this.setAppendWindow_(a,c,d),null)),this.needSplitMuxedContent_&&l.push(this.enqueueOperation_(k.AUDIO,()=>this.setAppendWindow_(k.AUDIO,c,d),null));l.length&&await Promise.all(l)}}async resync(a,b){const c=shaka.util.ManifestParserUtils.ContentType;if(a!=c.TEXT&&(a==c.VIDEO&&(this.textSequenceModeOffset_=new shaka.util.PublicPromise),this.sequenceMode_)){var d=this.bufferEnd(a);d&&Math.abs(d-b)<.15||(this.enqueueOperation_(a,()=>this.abort_(a),null),this.needSplitMuxedContent_&&this.enqueueOperation_(c.AUDIO,
()=>this.abort_(c.AUDIO),null),await this.enqueueOperation_(a,()=>this.setTimestampOffset_(a,b),null),this.needSplitMuxedContent_&&await this.enqueueOperation_(c.AUDIO,()=>this.setTimestampOffset_(c.AUDIO,b),null))}}async endOfStream(a){await this.enqueueBlockingOperation_(()=>{this.ended()||this.closed()||(a?this.mediaSource_.endOfStream(a):this.mediaSource_.endOfStream())})}async setDuration(a){await this.enqueueBlockingOperation_(()=>{if(this.config_.durationReductionEmitsUpdateEnd&&a<this.mediaSource_.duration)for(const b of this.sourceBuffers_.keys()){const c=
{start:()=>{},p:new shaka.util.PublicPromise,uri:null};this.queues_.get(b).unshift(c)}this.lastDuration_=this.mediaSource_.duration=a})}getDuration(){return this.mediaSource_.duration}async setLiveSeekableRange(a,b){this.destroyer_.destroyed()||this.video_.error||this.usingRemotePlayback_||this.reloadingMediaSource_||(goog.asserts.assert("setLiveSeekableRange"in this.mediaSource_,"Using setLiveSeekableRange on not supported platform"),this.ended()||this.closed()||await this.enqueueBlockingOperation_(()=>
{this.ended()||this.closed()||this.mediaSource_.setLiveSeekableRange(a,b)}))}async clearLiveSeekableRange(){this.destroyer_.destroyed()||this.video_.error||this.usingRemotePlayback_||this.reloadingMediaSource_||(goog.asserts.assert("clearLiveSeekableRange"in this.mediaSource_,"Using clearLiveSeekableRange on not supported platform"),this.ended()||this.closed()||await this.enqueueBlockingOperation_(()=>{this.ended()||this.closed()||this.mediaSource_.clearLiveSeekableRange()}))}appendDependency(a,b,
c){this.lcevcDec_&&this.lcevcDec_.appendBuffer(a,b,c)}removeDependency(a,b,c){this.lcevcDec_&&this.lcevcDec_.removeBuffer(a,b,c)}append_(a,b,c,d){this.appendDependency(b,c,d);this.sourceBuffers_.get(a).appendBuffer(b)}remove_(a,b,c){if(c<=b)this.onUpdateEnd_(a);else this.removeDependency(a,b,c),this.sourceBuffers_.get(a).remove(b,c)}abort_(a){const b=this.sourceBuffers_.get(a),c=b.appendWindowStart,d=b.appendWindowEnd;b.abort();b.appendWindowStart=c;b.appendWindowEnd=d;this.onUpdateEnd_(a)}flush_(a){goog.asserts.assert(this.video_.buffered.length==
0,"MediaSourceEngine.flush_ should only be used after clearing all data!");this.video_.currentTime-=.001;this.onUpdateEnd_(a)}setTimestampOffset_(a,b){b<0&&(b+=.001);this.sourceBuffers_.get(a).timestampOffset=b;this.onUpdateEnd_(a)}setAppendWindow_(a,b,c){const d=this.sourceBuffers_.get(a);if(d.appendWindowEnd!==c||d.appendWindowStart!==b)d.appendWindowStart=0,d.appendWindowEnd=c,d.appendWindowStart=b;this.onUpdateEnd_(a)}onError_(a){const b=this.queues_.get(a)[0];goog.asserts.assert(b,"Spurious error event!");
goog.asserts.assert(!this.sourceBuffers_.get(a).updating,"SourceBuffer should not be updating on error!");b.p.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_FAILED,this.video_.error?this.video_.error.code:0,b.uri))}onUpdateEnd_(a){if(this.reloadingMediaSource_||this.destroyer_.destroyed()){var b=this.queues_.get(a);b&&b.length&&((b=b[0])&&b.p&&b.p.resolve(),this.queues_.set(a,[]))}else b=this.queues_.get(a)[0],
goog.asserts.assert(b,"Spurious updateend event!"),b&&(goog.asserts.assert(!this.sourceBuffers_.get(a).updating,"SourceBuffer should not be updating on updateend!"),b.p.resolve(),this.popFromQueue_(a))}enqueueOperation_(a,b,c){this.destroyer_.ensureNotDestroyed();b={start:b,p:new shaka.util.PublicPromise,uri:c};this.queues_.get(a).push(b);this.queues_.get(a).length==1&&this.startOperation_(a);return b.p}async enqueueBlockingOperation_(a){this.destroyer_.ensureNotDestroyed();const b=[],c=Array.from(this.sourceBuffers_.keys()),
d=new Map;for(const e of c){const f=new shaka.util.PublicPromise,g={start:()=>f.resolve(),p:f,uri:null},h=this.queues_.get(e);h.push(g);b.push(f);d.set(e,g);h.length==1&&g.start()}try{await Promise.all(b)}catch(e){if(this.destroyer_.destroyed()){for(const f of c)a=this.queues_.get(f),d.has(f)&&shaka.util.ArrayUtils.remove(a,d.get(f));return}throw e;}if(goog.DEBUG)for(const e of c)goog.asserts.assert(this.sourceBuffers_.get(e).updating==0,"SourceBuffers should not be updating after a blocking op!");
try{await a()}catch(e){throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_THREW,e,this.video_.error||"No error in the media element",null);}finally{for(const e of c)this.popFromQueue_(e)}}popFromQueue_(a){goog.asserts.assert(this.queues_.has(a),"Queue should exist");this.queues_.get(a).shift();this.startOperation_(a)}startOperation_(a){const b=this.queues_.get(a)[0];if(b)try{b.start()}catch(c){c.name=="QuotaExceededError"?
b.p.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.QUOTA_EXCEEDED_ERROR,a)):this.isStreamingAllowed()?b.p.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_THREW,c,this.video_.error||"No error in the media element",b.uri)):b.p.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.STREAMING_NOT_ALLOWED,
a)),this.popFromQueue_(a)}}getTextDisplayer(){goog.asserts.assert(this.textDisplayer_,"TextDisplayer should only be null when this is destroyed");return this.textDisplayer_}setTextDisplayer(a){this.textDisplayer_=a;this.textEngine_&&this.textEngine_.setDisplayer(a)}setSegmentRelativeVttTiming(a){this.segmentRelativeVttTiming_=a}workAroundBrokenPlatforms_(a,b,c,d){const e=shaka.util.ManifestParserUtils.ContentType;if(shaka.util.MimeUtils.getContainerType(this.sourceBufferTypes_.get(d))!="mp4")return b;
const f=c===null,g=this.expectedEncryption_.get(d),h=this.playerInterface_.getKeySystem();let k=!1;c&&c.initSegmentReference&&(k=c.initSegmentReference.encrypted);c=c?c.getUris()[0]:null;const l=shaka.device.DeviceFactory.getDevice();this.config_.correctEc3Enca&&f&&d===e.AUDIO&&(b=shaka.media.ContentWorkarounds.correctEnca(b));this.config_.insertFakeEncryptionInInit&&g&&l.requiresEncryptionInfoInAllInitSegments(h,d)&&(f?(shaka.log.debug("Forcing fake encryption information in init segment."),b=shaka.media.ContentWorkarounds.fakeEncryption(a,
b,c)):!k&&l.requiresTfhdFix(d)&&(shaka.log.debug("Forcing fake encryption information in media segment."),b=shaka.media.ContentWorkarounds.fakeMediaEncryption(b)));f&&l.requiresEC3InitSegments()&&(shaka.log.debug("Forcing fake EC-3 information in init segment."),b=shaka.media.ContentWorkarounds.fakeEC3(b));return b}change_(a,b,c){if(a===shaka.util.ManifestParserUtils.ContentType.TEXT)shaka.log.debug(`Change not supported for ${a}`);else{var d=this.sourceBufferTypes_.get(a);shaka.log.debug(`Change Type: ${d} -> ${b}`);
shaka.device.DeviceFactory.getDevice().supportsSmoothCodecSwitching()?(this.transmuxers_.has(a)&&(this.transmuxers_.get(a).destroy(),this.transmuxers_.delete(a)),c&&this.transmuxers_.set(a,c),c=this.addExtraFeaturesToMimeType_(b),this.sourceBuffers_.get(a).changeType(c),this.sourceBufferTypes_.set(a,b)):shaka.log.debug("Change Type not supported");this.onUpdateEnd_(a)}}changeType(a,b,c){return this.enqueueOperation_(a,()=>this.change_(a,b,c),null)}async reset_(a){if(!this.reloadingMediaSource_&&!this.usingRemotePlayback_){var b=
shaka.util.ManifestParserUtils.ContentType;this.reloadingMediaSource_=!0;this.needSplitMuxedContent_=!1;var c=this.video_.currentTime,d=this.video_.autoplay;this.video_.paused||(this.playAfterReset_=!0);this.playbackHasBegun_&&(this.video_.autoplay=!1);try{this.eventManager_.removeAll();for(const n of this.transmuxers_.values())n.destroy();for(const n of this.sourceBuffers_.values())try{this.mediaSource_.removeSourceBuffer(n)}catch(q){shaka.log.debug("Exception on removeSourceBuffer",q)}this.transmuxers_.clear();
this.sourceBuffers_.clear();const e=this.mediaSource_.duration;this.mediaSourceOpen_=new shaka.util.PublicPromise;this.mediaSource_=this.createMediaSource(this.mediaSourceOpen_);await this.mediaSourceOpen_;!isNaN(e)&&e?this.mediaSource_.duration=e:!isNaN(this.lastDuration_)&&this.lastDuration_&&(this.mediaSource_.duration=this.lastDuration_);const f=new shaka.util.PublicPromise,g=this.mediaSource_.sourceBuffers,h=a.size;let k=0;const l=()=>{k++;k===h&&(f.resolve(),this.eventManager_.unlisten(g,"addsourcebuffer",
l))};this.eventManager_.listen(g,"addsourcebuffer",l);for(const n of a.keys()){const q=a.get(n);this.initSourceBuffer_(n,q,q.codecs)}const m=a.get(b.AUDIO);m&&m.isAudioMuxedInVideo&&(this.needSplitMuxedContent_=!0);this.needSplitMuxedContent_&&!this.queues_.has(b.AUDIO)&&this.queues_.set(b.AUDIO,[]);await f}finally{this.reloadingMediaSource_=!1,this.destroyer_.ensureNotDestroyed(),this.eventManager_.listenOnce(this.video_,shaka.util.MediaElementEvent.LOADED_METADATA,()=>{this.destroyer_.destroyed()||
(this.video_.currentTime=c)}),this.eventManager_.listenOnce(this.video_,shaka.util.MediaElementEvent.CAN_PLAY_THROUGH,()=>{this.destroyer_.destroyed()||(this.video_.autoplay=d,this.playAfterReset_&&(this.playAfterReset_=!1,this.video_.play()))})}}}reset(a){return this.enqueueBlockingOperation_(()=>this.reset_(a))}getRealInfo_(a,b,c){const d=shaka.util.ManifestParserUtils.ContentType;var e=shaka.util.MimeUtils;let f,g=!1;const h=shaka.util.ManifestParserUtils.guessCodecsSafe(d.AUDIO,(c||"").split(",")),
k=shaka.util.ManifestParserUtils.guessCodecsSafe(d.VIDEO,(c||"").split(","));var l=k;a==d.AUDIO&&(l=h);l||=c;let m=shaka.util.MimeUtils.getFullType(b,l);var n=e.getBasicType(this.sourceBufferTypes_.get(a)),q=this.config_.forceTransmux;!shaka.media.Capabilities.isTypeSupported(m)||!this.sequenceMode_&&shaka.util.MimeUtils.RAW_FORMATS.includes(m)?q=!0:q||b==n||(q=!shaka.device.DeviceFactory.getDevice().supportsContainerChangeType()&&shaka.util.MimeUtils.RAW_FORMATS.includes(b));n=shaka.transmuxer.TransmuxerEngine;
q&&(l=shaka.util.MimeUtils.getFullTypeWithAllCodecs(b,l),q=n.findTransmuxer(l))&&(f=q(),h&&k&&(g=!0),m=f.convertCodecs(a,l));!f&&a===d.VIDEO&&h&&(m=shaka.util.MimeUtils.getFullType(b,c));a=e.getNormalizedCodec(e.getCodecs(m));e=e.getBasicType(m);return{transmuxer:f,transmuxerMuxed:g,basicType:e,codec:a,mimeType:m}}getInfoAboutResetOrChangeType_(a,b,c,d){const e=shaka.util.ManifestParserUtils.ContentType;if(a==e.TEXT)return{type:shaka.media.MediaSourceEngine.ResetMode_.NONE,newMimeType:b,transmuxer:null};
var f=shaka.util.MimeUtils,g=f.getNormalizedCodec(f.getCodecs(this.sourceBufferTypes_.get(a)));const h=f.getBasicType(this.sourceBufferTypes_.get(a));var k=this.getRealInfo_(a,b,c);const l=k.transmuxer,m=k.transmuxerMuxed,n=k.basicType,q=k.codec;k=k.mimeType;let p=!0;m&&this.sourceBufferTypes_.has(e.AUDIO)&&(b=this.getRealInfo_(e.AUDIO,b,c),c=f.getNormalizedCodec(f.getCodecs(this.sourceBufferTypes_.get(e.AUDIO))),f=f.getBasicType(this.sourceBufferTypes_.get(e.AUDIO)),p=c==b.codec&&f==b.basicType,
b.transmuxer&&b.transmuxer.destroy());if(g===q&&h===n&&p)return{type:shaka.media.MediaSourceEngine.ResetMode_.NONE,newMimeType:k,transmuxer:l};g=!0;if(this.needSplitMuxedContent_&&!d.has(e.AUDIO)||m&&l&&!this.transmuxers_.has(a))g=!1;a=shaka.device.DeviceFactory.getDevice();if(g&&this.config_.codecSwitchingStrategy===shaka.config.CodecSwitchingStrategy.SMOOTH&&a.supportsSmoothCodecSwitching())return{type:shaka.media.MediaSourceEngine.ResetMode_.CHANGE_TYPE,newMimeType:k,transmuxer:l};l&&l.destroy();
return{type:shaka.media.MediaSourceEngine.ResetMode_.RESET,newMimeType:k,transmuxer:null}}async codecSwitchIfNecessary_(a,b,c,d){const e=shaka.util.ManifestParserUtils.ContentType,{type:f,transmuxer:g,newMimeType:h}=this.getInfoAboutResetOrChangeType_(a,b,c,d);if(b=d.get(e.AUDIO))this.needSplitMuxedContent_=b.isAudioMuxedInVideo;if(f==shaka.media.MediaSourceEngine.ResetMode_.NONE)return this.transmuxers_.has(a)&&!g?(this.transmuxers_.get(a).destroy(),this.transmuxers_.delete(a)):!this.transmuxers_.has(a)&&
g?this.transmuxers_.set(a,g):g&&(this.transmuxers_.has(a)&&this.transmuxers_.get(a).transmux!==g.transmux?(this.transmuxers_.get(a).destroy(),this.transmuxers_.set(a,g)):g.destroy()),!1;f==shaka.media.MediaSourceEngine.ResetMode_.CHANGE_TYPE?await this.changeType(a,h,g):f==shaka.media.MediaSourceEngine.ResetMode_.RESET&&(g&&g.destroy(),await this.reset(d));return!0}isResetMediaSourceNecessary(a,b,c,d){a=this.getInfoAboutResetOrChangeType_(a,b,c,d);a.transmuxer&&a.transmuxer.destroy();return a.type==
shaka.media.MediaSourceEngine.ResetMode_.RESET}updateLcevcDec(a){this.lcevcDec_=a}addExtraFeaturesToMimeType_(a){const b=this.config_.addExtraFeaturesToSourceBuffer(a);a+=b;shaka.log.debug("Using full mime type",a);return a}};shaka.media.MediaSourceEngine.createObjectURL=window.URL.createObjectURL;shaka.media.MediaSourceEngine.SourceBufferMode_={SEQUENCE:"sequence",SEGMENTS:"segments"};shaka.media.MediaSourceEngine.ResetMode_={NONE:"none",RESET:"reset",CHANGE_TYPE:"changeType"};shaka.media.PresentationTimeline=class{constructor(a,b,c=!0){this.presentationStartTime_=a;this.presentationDelay_=b;this.segmentAvailabilityDuration_=this.duration_=Infinity;this.maxSegmentDuration_=1;this.maxSegmentEndTime_=this.minSegmentStartTime_=null;this.clockOffset_=0;this.static_=!0;this.isLive2VodTransition_=!1;this.userSeekStart_=0;this.autoCorrectDrift_=c;this.availabilityTimeOffset_=0;this.startTimeLocked_=!1;this.initialProgramDateTime_=a}getDuration(){return this.duration_}getMaxSegmentDuration(){return this.maxSegmentDuration_}setPresentationStartTime(a){goog.asserts.assert(a>=
0,"presentationStartTime must be >= 0");this.presentationStartTime_=a}setDuration(a){goog.asserts.assert(a>0,"duration must be > 0");this.duration_=a}getPresentationStartTime(){return this.presentationStartTime_}setClockOffset(a){this.clockOffset_=a}setStatic(a){a&&!this.static_&&(this.isLive2VodTransition_=!0);this.static_=a}setSegmentAvailabilityDuration(a){goog.asserts.assert(a>=0,"segmentAvailabilityDuration must be >= 0");this.segmentAvailabilityDuration_=a}getSegmentAvailabilityDuration(){return this.segmentAvailabilityDuration_}setDelay(a){goog.asserts.assert(a>=
0,"delay must be >= 0");this.presentationDelay_=a}getDelay(){return this.presentationDelay_}notifyTimeRange(a,b){if(a.length!=0){var c=(Date.now()+this.clockOffset_)/1E3;a=a.filter(e=>e.start+b<c);if(a.length!=0){var d=a[a.length-1].end+b;this.notifyMinSegmentStartTime(a[0].start+b);this.maxSegmentDuration_=a.reduce((e,f)=>Math.max(e,f.end-f.start),this.maxSegmentDuration_);this.maxSegmentEndTime_=Math.max(this.maxSegmentEndTime_,d);this.presentationStartTime_!=null&&this.autoCorrectDrift_&&!this.startTimeLocked_&&
(this.presentationStartTime_=c-this.maxSegmentEndTime_-this.maxSegmentDuration_);shaka.log.v1("notifySegments:","maxSegmentDuration="+this.maxSegmentDuration_)}}}notifySegments(a){if(a.length!=0){var b=a[0].startTime,c=a[0].endTime,d=(Date.now()+this.clockOffset_)/1E3;for(const e of a)d<e.startTime||(b=Math.min(b,e.startTime),c=Math.max(c,e.endTime),this.maxSegmentDuration_=Math.max(this.maxSegmentDuration_,e.endTime-e.startTime));this.notifyMinSegmentStartTime(b);this.maxSegmentEndTime_=Math.max(this.maxSegmentEndTime_,
c);this.presentationStartTime_!=null&&this.autoCorrectDrift_&&!this.startTimeLocked_&&(this.presentationStartTime_=d-this.maxSegmentEndTime_-this.maxSegmentDuration_);shaka.log.v1("notifySegments:","maxSegmentDuration="+this.maxSegmentDuration_)}}notifyPeriodDuration(a,b){this.notifyMinSegmentStartTime(a);b==Infinity||this.isLive()||(this.maxSegmentEndTime_=Math.max(this.maxSegmentEndTime_,b))}getMaxSegmentEndTime(){return this.maxSegmentEndTime_}lockStartTime(){this.startTimeLocked_=!0}isStartTimeLocked(){return this.startTimeLocked_}setInitialProgramDateTime(a){this.initialProgramDateTime_=
a}getInitialProgramDateTime(){return this.initialProgramDateTime_}notifyMinSegmentStartTime(a){this.minSegmentStartTime_==null?this.minSegmentStartTime_=a:this.isLive2VodTransition_||(this.minSegmentStartTime_=Math.min(this.minSegmentStartTime_,a))}notifyMaxSegmentDuration(a){this.maxSegmentDuration_=Math.max(this.maxSegmentDuration_,a);shaka.log.v1("notifyNewSegmentDuration:","maxSegmentDuration="+this.maxSegmentDuration_)}offset(a){this.minSegmentStartTime_!=null&&(this.minSegmentStartTime_+=a);
this.maxSegmentEndTime_!=null&&(this.maxSegmentEndTime_+=a)}isLive(){return this.duration_==Infinity&&!this.static_}isInProgress(){return this.duration_!=Infinity&&!this.static_}getSegmentAvailabilityStart(){goog.asserts.assert(this.segmentAvailabilityDuration_>=0,"The availability duration should be positive");const a=this.getSegmentAvailabilityEnd()-this.segmentAvailabilityDuration_;return Math.max(this.userSeekStart_,a)}setUserSeekStart(a){this.userSeekStart_=a}getSegmentAvailabilityEnd(){return this.isLive()||
this.isInProgress()?Math.min(this.getLiveEdge_()+this.availabilityTimeOffset_,this.duration_):this.maxSegmentEndTime_?Math.min(this.maxSegmentEndTime_,this.duration_):this.duration_}getSafeSeekRangeStart(a){const b=Math.max(this.minSegmentStartTime_,this.userSeekStart_);if(this.segmentAvailabilityDuration_==Infinity)return Math.ceil(b*1E3)/1E3;const c=this.getSegmentAvailabilityEnd()-this.segmentAvailabilityDuration_;a=Math.min(c+a,this.getSeekRangeEnd());return Math.max(b,a)}getSeekRangeStart(){return this.getSafeSeekRangeStart(0)}getSeekRangeEnd(){const a=
this.isLive()||this.isInProgress()?this.presentationDelay_:0;return Math.max(0,this.getSegmentAvailabilityEnd()-a)}usingPresentationStartTime(){return this.presentationStartTime_==null||this.maxSegmentEndTime_!=null&&this.autoCorrectDrift_?!1:!0}getLiveEdge_(){goog.asserts.assert(this.presentationStartTime_!=null,"Cannot compute timeline live edge without start time");const a=(Date.now()+this.clockOffset_)/1E3;return Math.max(0,a-this.maxSegmentDuration_-this.presentationStartTime_)}setAvailabilityTimeOffset(a){this.availabilityTimeOffset_=
a}getAvailabilityTimeOffset(){return this.availabilityTimeOffset_}assertIsValid(){goog.DEBUG&&(this.isLive()?goog.asserts.assert(this.presentationStartTime_!=null,"Detected as live stream, but does not match our model of live!"):this.isInProgress()?goog.asserts.assert(this.presentationStartTime_!=null&&this.segmentAvailabilityDuration_==Infinity,"Detected as IPR stream, but does not match our model of IPR!"):goog.asserts.assert(this.segmentAvailabilityDuration_==Infinity&&this.duration_!=Infinity&&
this.static_,"Detected as VOD stream, but does not match our model of VOD!"))}};goog.exportSymbol("shaka.media.PresentationTimeline",shaka.media.PresentationTimeline);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getAvailabilityTimeOffset",shaka.media.PresentationTimeline.prototype.getAvailabilityTimeOffset);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"setAvailabilityTimeOffset",shaka.media.PresentationTimeline.prototype.setAvailabilityTimeOffset);
goog.exportProperty(shaka.media.PresentationTimeline.prototype,"usingPresentationStartTime",shaka.media.PresentationTimeline.prototype.usingPresentationStartTime);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getSeekRangeEnd",shaka.media.PresentationTimeline.prototype.getSeekRangeEnd);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getSeekRangeStart",shaka.media.PresentationTimeline.prototype.getSeekRangeStart);
goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getSafeSeekRangeStart",shaka.media.PresentationTimeline.prototype.getSafeSeekRangeStart);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getSegmentAvailabilityEnd",shaka.media.PresentationTimeline.prototype.getSegmentAvailabilityEnd);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"setUserSeekStart",shaka.media.PresentationTimeline.prototype.setUserSeekStart);
goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getSegmentAvailabilityStart",shaka.media.PresentationTimeline.prototype.getSegmentAvailabilityStart);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"isInProgress",shaka.media.PresentationTimeline.prototype.isInProgress);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"isLive",shaka.media.PresentationTimeline.prototype.isLive);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"offset",shaka.media.PresentationTimeline.prototype.offset);
goog.exportProperty(shaka.media.PresentationTimeline.prototype,"notifyMaxSegmentDuration",shaka.media.PresentationTimeline.prototype.notifyMaxSegmentDuration);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"notifyMinSegmentStartTime",shaka.media.PresentationTimeline.prototype.notifyMinSegmentStartTime);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getInitialProgramDateTime",shaka.media.PresentationTimeline.prototype.getInitialProgramDateTime);
goog.exportProperty(shaka.media.PresentationTimeline.prototype,"setInitialProgramDateTime",shaka.media.PresentationTimeline.prototype.setInitialProgramDateTime);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"isStartTimeLocked",shaka.media.PresentationTimeline.prototype.isStartTimeLocked);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"lockStartTime",shaka.media.PresentationTimeline.prototype.lockStartTime);
goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getMaxSegmentEndTime",shaka.media.PresentationTimeline.prototype.getMaxSegmentEndTime);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"notifyPeriodDuration",shaka.media.PresentationTimeline.prototype.notifyPeriodDuration);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"notifySegments",shaka.media.PresentationTimeline.prototype.notifySegments);
goog.exportProperty(shaka.media.PresentationTimeline.prototype,"notifyTimeRange",shaka.media.PresentationTimeline.prototype.notifyTimeRange);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getDelay",shaka.media.PresentationTimeline.prototype.getDelay);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"setDelay",shaka.media.PresentationTimeline.prototype.setDelay);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getSegmentAvailabilityDuration",shaka.media.PresentationTimeline.prototype.getSegmentAvailabilityDuration);
goog.exportProperty(shaka.media.PresentationTimeline.prototype,"setSegmentAvailabilityDuration",shaka.media.PresentationTimeline.prototype.setSegmentAvailabilityDuration);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"setStatic",shaka.media.PresentationTimeline.prototype.setStatic);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"setClockOffset",shaka.media.PresentationTimeline.prototype.setClockOffset);
goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getPresentationStartTime",shaka.media.PresentationTimeline.prototype.getPresentationStartTime);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"setDuration",shaka.media.PresentationTimeline.prototype.setDuration);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"setPresentationStartTime",shaka.media.PresentationTimeline.prototype.setPresentationStartTime);
goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getMaxSegmentDuration",shaka.media.PresentationTimeline.prototype.getMaxSegmentDuration);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getDuration",shaka.media.PresentationTimeline.prototype.getDuration);shaka.media.GapJumpingController=class{constructor(a,b,c,d){this.onEvent_=d;this.video_=a;this.timeline_=b;this.config_=c;this.eventManager_=new shaka.util.EventManager;this.seekingEventReceived_=this.started_=!1;this.startTime_=0;this.isJumpingGap_=!1;this.stallsDetected_=this.gapsJumped_=0;this.stallDetector_=this.createStallDetector_();this.hadSegmentAppended_=!1;this.eventManager_.listen(a,"waiting",()=>this.onPollGapJump_());this.gapJumpTimer_=(new shaka.util.Timer(()=>{this.onPollGapJump_()})).tickEvery(this.config_.gapJumpTimerTime)}release(){this.eventManager_&&
(this.eventManager_.release(),this.eventManager_=null);this.gapJumpTimer_!=null&&(this.gapJumpTimer_.stop(),this.gapJumpTimer_=null);this.stallDetector_&&(this.stallDetector_.release(),this.stallDetector_=null);this.video_=this.timeline_=this.onEvent_=null}onSegmentAppended(){this.hadSegmentAppended_=!0;this.gapJumpTimer_&&this.gapJumpTimer_.tickEvery(this.config_.gapJumpTimerTime);this.onPollGapJump_()}onStarted(a){this.video_.seeking&&!this.seekingEventReceived_&&(this.seekingEventReceived_=!0,
this.startTime_=a);this.gapJumpTimer_&&this.gapJumpTimer_.tickEvery(this.config_.gapJumpTimerTime);this.onPollGapJump_()}onSeeking(){this.seekingEventReceived_=!0;this.hadSegmentAppended_=!1;this.gapJumpTimer_&&this.gapJumpTimer_.tickEvery(this.config_.gapJumpTimerTime);this.onPollGapJump_()}getGapsJumped(){return this.gapsJumped_}getStallsDetected(){return this.stallsDetected_}getIsJumpingGap(){return this.isJumpingGap_}onPollGapJump_(){if(this.video_.readyState!=0){if(this.video_.seeking){if(!this.seekingEventReceived_)return}else this.seekingEventReceived_=
!1;if(!this.video_.paused||this.video_.currentTime==this.startTime_&&(this.video_.autoplay||this.video_.currentTime!=this.startTime_))if(!this.stallDetector_||!this.stallDetector_.poll()){var a=this.video_.currentTime,b=this.video_.buffered,c=shaka.media.TimeRangesUtils.getGapIndex(b,a,this.config_.gapDetectionThreshold);if(c==null&&this.stallDetector_&&!this.stallDetector_.poll()){var d=shaka.media.TimeRangesUtils.getBufferedInfo(b);for(var e=0;e<d.length-1;e++)if(Math.abs(a-d[e].end)<.1&&d[e+1].start>
d[e].end){c=e+1;break}}c==null||c==0&&!this.hadSegmentAppended_||(d=b.start(c),(e=this.config_.gapPadding)&&(d=Math.ceil((d+e)*100)/100),e=this.timeline_.getSeekRangeEnd(),d>=e||(e=d-a,e<shaka.media.GapJumpingController.BROWSER_GAP_TOLERANCE||(c==0?shaka.log.info("Jumping forward",e,"seconds because of gap before start time of",d):shaka.log.info("Jumping forward",e,"seconds because of gap starting at",b.end(c-1),"and ending at",d),this.seek_(d),a==this.startTime_&&(this.startTime_=d),this.gapsJumped_++,
this.onEvent_(new shaka.util.FakeEvent(shaka.util.FakeEvent.EventName.GapJumped)))))}}}seek_(a){this.isJumpingGap_=!0;this.eventManager_.listenOnce(this.video_,"seeked",()=>{this.isJumpingGap_=!1});this.video_.currentTime=a}createStallDetector_(){if(!this.config_.stallEnabled)return null;goog.asserts.assert(this.video_,"Must have video");const a=this.config_.stallThreshold,b=this.config_.stallSkip;return new shaka.media.StallDetector(new shaka.media.StallDetector.MediaElementImplementation(this.video_),
a,async(c,d)=>{goog.asserts.assert(this.video_,"Must have video");if(shaka.media.TimeRangesUtils.getBufferedInfo(this.video_.buffered).length){shaka.log.debug(`Stall detected at ${c} for ${d} seconds.`);if(b)shaka.log.debug(`Seeking forward ${b} seconds to break stall.`),this.video_.currentTime+=b;else{shaka.log.debug("Wait for play to avoid reject a possible other play call.");await this.video_.play();if(!this.video_)return;shaka.log.debug("Pausing and unpausing to break stall.");this.video_.pause();
this.video_.play()}this.stallsDetected_++;this.onEvent_(new shaka.util.FakeEvent(shaka.util.FakeEvent.EventName.StallDetected))}})}};shaka.media.GapJumpingController.BROWSER_GAP_TOLERANCE=.001;
shaka.media.StallDetector=class{constructor(a,b,c){this.implementation_=a;this.wasMakingProgress_=a.shouldBeMakingProgress();this.value_=a.getPresentationSeconds();this.lastUpdateSeconds_=a.getWallSeconds();this.didJump_=!1;this.stallThresholdSeconds_=b;this.onStall_=c}release(){this.implementation_&&this.implementation_.release();this.onStall_=this.implementation_=null}poll(){const a=this.implementation_;var b=a.shouldBeMakingProgress(),c=a.getPresentationSeconds();const d=a.getWallSeconds();if(this.value_!=
c||this.wasMakingProgress_!=b)this.lastUpdateSeconds_=d,this.value_=c,this.wasMakingProgress_=b,this.didJump_=!1;c=d-this.lastUpdateSeconds_;if(b=c>=this.stallThresholdSeconds_&&b&&!this.didJump_){if(this.onStall_)this.onStall_(this.value_,c);this.didJump_=!0;this.value_=a.getPresentationSeconds()}return b}};shaka.media.StallDetector.Implementation=class{shouldBeMakingProgress(){}getPresentationSeconds(){}getWallSeconds(){}release(){}};
shaka.media.StallDetector.MediaElementImplementation=class{constructor(a){this.mediaElement_=a;this.audioEventManager_=new shaka.util.EventManager;this.audioFocusPaused_=!1;this.audioEventManager_.listen(this.mediaElement_,"audiofocuspaused",()=>{shaka.log.info("Audio focus paused");this.audioFocusPaused_=!0});this.audioEventManager_.listen(this.mediaElement_,"audiofocusgranted",()=>{shaka.log.info("Audio focus granted");this.audioFocusPaused_=!1});this.audioEventManager_.listen(this.mediaElement_,
"audiofocuslost",()=>{shaka.log.info("Audio focus lost");this.audioFocusPaused_=!0})}shouldBeMakingProgress(){return this.mediaElement_.paused||this.mediaElement_.playbackRate==0||this.audioFocusPaused_||this.mediaElement_.buffered.length==0?!1:this.hasContentFor_(this.mediaElement_.buffered,this.mediaElement_.currentTime)}getPresentationSeconds(){return this.mediaElement_.currentTime}getWallSeconds(){return Date.now()/1E3}hasContentFor_(a,b){const c=shaka.media.TimeRangesUtils;for(const {start:d,
end:e}of c.getBufferedInfo(a))if(!(b<d-.1||b>e-.5))return!0;return!1}release(){this.audioEventManager_&&this.audioEventManager_.release();this.audioEventManager_=null}};shaka.util.MediaReadyState=class{static waitForReadyState(a,b,c,d){b==HTMLMediaElement.HAVE_NOTHING||a.readyState>=b?d():(b=shaka.util.MediaReadyState.READY_STATES_TO_EVENT_NAMES_.value().get(b),c.listenOnce(a,b,d))}};shaka.util.MediaReadyState.READY_STATES_TO_EVENT_NAMES_=new shaka.util.Lazy(()=>new Map([[HTMLMediaElement.HAVE_METADATA,"loadedmetadata"],[HTMLMediaElement.HAVE_CURRENT_DATA,"loadeddata"],[HTMLMediaElement.HAVE_FUTURE_DATA,"canplay"],[HTMLMediaElement.HAVE_ENOUGH_DATA,"canplaythrough"]]));shaka.media.VideoWrapper=class{constructor(a,b,c,d){this.video_=a;this.onSeek_=b;this.onStarted_=c;this.startTime_=null;this.getStartTime_=()=>{this.startTime_==null&&(this.startTime_=d());return this.startTime_};this.started_=!1;this.eventManager_=new shaka.util.EventManager;this.mover_=new shaka.media.VideoWrapper.PlayheadMover(a,10);shaka.util.MediaReadyState.waitForReadyState(this.video_,HTMLMediaElement.HAVE_METADATA,this.eventManager_,()=>{this.setStartTime_(this.getStartTime_())})}release(){this.eventManager_&&
(this.eventManager_.release(),this.eventManager_=null);this.mover_!=null&&(this.mover_.release(),this.mover_=null);this.onSeek_=()=>{};this.video_=null}getTime(){return this.started_?this.video_.currentTime:this.getStartTime_()}setTime(a){this.video_.readyState>0?this.mover_.moveTo(a):shaka.util.MediaReadyState.waitForReadyState(this.video_,HTMLMediaElement.HAVE_METADATA,this.eventManager_,()=>{this.setStartTime_(this.getStartTime_())})}setStartTime_(a){Math.abs(this.video_.currentTime-a)<.001?this.startListeningToSeeks_():
(this.eventManager_.listenOnce(this.video_,"seeking",()=>{this.startListeningToSeeks_()}),this.mover_.moveTo(this.video_.currentTime&&this.video_.currentTime!=0?this.video_.currentTime:a))}startListeningToSeeks_(){goog.asserts.assert(this.video_.readyState>0,"The media element should be ready before we listen for seeking.");this.started_=!0;this.eventManager_.listen(this.video_,"seeking",()=>this.onSeek_());this.onStarted_(this.video_.currentTime)}};
shaka.media.VideoWrapper.PlayheadMover=class{constructor(a,b){this.mediaElement_=a;this.maxAttempts_=b;this.targetTime_=this.originTime_=this.remainingAttempts_=0;this.timer_=new shaka.util.Timer(()=>this.onTick_())}release(){this.timer_&&(this.timer_.stop(),this.timer_=null);this.mediaElement_=null}moveTo(a){this.originTime_=this.mediaElement_.currentTime;this.targetTime_=a;this.remainingAttempts_=this.maxAttempts_;this.mediaElement_.currentTime=a;this.timer_.tickEvery(.1)}onTick_(){this.remainingAttempts_<=
0?(shaka.log.warning(["Failed to move playhead from",this.originTime_,"to",this.targetTime_].join(" ")),this.timer_.stop()):this.mediaElement_.currentTime!=this.originTime_||this.mediaElement_.currentTime===this.targetTime_?this.timer_.stop():(this.mediaElement_.currentTime=this.targetTime_,this.remainingAttempts_--)}};shaka.media.Playhead=class{ready(){}setStartTime(a){}getStallsDetected(){}getIsJumpingGap(){}getGapsJumped(){}getTime(){}notifyOfBufferingChange(){}isBufferedToEnd(){}};
shaka.media.SrcEqualsPlayhead=class{constructor(a){this.mediaElement_=a;this.started_=!1;this.startTime_=null;this.eventManager_=new shaka.util.EventManager}ready(){goog.asserts.assert(this.mediaElement_!=null,"Playhead should not be released before calling ready()");const a=()=>{if(this.startTime_==null||this.startTime_==0&&this.mediaElement_.duration!=Infinity)this.started_=!0;else{const b=this.mediaElement_.currentTime;let c=null;if(typeof this.startTime_==="number")c=this.startTime_;else if(this.startTime_ instanceof
Date){const d=this.getProgramStartTime_();d!==null&&(c=this.startTime_.getTime()/1E3-d,c=this.clampTime_(c))}c==null?this.started_=!0:(c<0&&(c=Math.max(0,b+c)),b!=c?(this.eventManager_.listenOnce(this.mediaElement_,"seeking",()=>{this.started_=!0}),this.mediaElement_.currentTime=c):this.started_=!0)}};shaka.util.MediaReadyState.waitForReadyState(this.mediaElement_,HTMLMediaElement.HAVE_FUTURE_DATA,this.eventManager_,()=>{a()})}release(){this.eventManager_&&(this.eventManager_.release(),this.eventManager_=
null);this.mediaElement_=null}setStartTime(a){this.startTime_=this.started_?this.startTime_:a}getTime(){let a=this.started_?this.mediaElement_.currentTime:this.startTime_;a instanceof Date&&(a=a.getTime()/1E3-(this.getProgramStartTime_()||0),a=this.clampTime_(a));return a||0}getStallsDetected(){return 0}getGapsJumped(){return 0}getIsJumpingGap(){return!1}notifyOfBufferingChange(){}isBufferedToEnd(){goog.asserts.assert(this.mediaElement_,"We need a video element to get buffering information");const a=
shaka.media.TimeRangesUtils.bufferEnd(this.mediaElement_.buffered);return a!=null&&a>=this.mediaElement_.duration-1}getProgramStartTime_(){if(this.mediaElement_.getStartDate){const a=this.mediaElement_.getStartDate().getTime();if(!isNaN(a))return a/1E3}return null}clampTime_(a){const b=this.mediaElement_.seekable;b.length>0&&(a=Math.max(b.start(0),a),a=Math.min(b.end(b.length-1),a));return a}};
shaka.media.MediaSourcePlayhead=class{constructor(a,b,c,d,e,f){this.minSeekRange_=3;this.mediaElement_=a;this.timeline_=b.presentationTimeline;this.config_=c;this.onSeek_=e;this.lastCorrectiveSeek_=null;this.gapController_=new shaka.media.GapJumpingController(a,b.presentationTimeline,c,f);this.videoWrapper_=new shaka.media.VideoWrapper(a,()=>this.onSeeking_(),g=>this.onStarted_(g),()=>this.getStartTime_(d));this.checkWindowTimer_=new shaka.util.Timer(()=>{this.onPollWindow_()})}ready(){this.checkWindowTimer_.tickEvery(.25)}release(){this.videoWrapper_&&
(this.videoWrapper_.release(),this.videoWrapper_=null);this.gapController_&&(this.gapController_.release(),this.gapController_=null);this.checkWindowTimer_&&(this.checkWindowTimer_.stop(),this.checkWindowTimer_=null);this.mediaElement_=this.videoWrapper_=this.timeline_=this.config_=null;this.onSeek_=()=>{}}setStartTime(a){this.videoWrapper_.setTime(this.getStartTime_(a))}getTime(){const a=this.videoWrapper_.getTime();return this.mediaElement_.readyState>0&&!this.mediaElement_.paused?this.clampTime_(a):
a}getStallsDetected(){return this.gapController_.getStallsDetected()}getGapsJumped(){return this.gapController_.getGapsJumped()}getIsJumpingGap(){return this.gapController_.getIsJumpingGap()}getStartTime_(a){if(a==null)a=this.timeline_.getDuration()<Infinity?this.timeline_.getSeekRangeStart():this.timeline_.getSeekRangeEnd();else if(a instanceof Date){const b=this.timeline_.getInitialProgramDateTime()||this.timeline_.getPresentationStartTime();goog.asserts.assert(b!=null,"Presentation start time should not be null!");
a=a.getTime()/1E3-b}else a<0&&(a=this.timeline_.getSeekRangeEnd()+a);return this.clampSeekToDuration_(this.clampTime_(a))}notifyOfBufferingChange(){this.gapController_.onSegmentAppended()}isBufferedToEnd(){goog.asserts.assert(this.mediaElement_,"We need a video element to get buffering information");goog.asserts.assert(this.timeline_,"We need a timeline to get buffering information");if(this.timeline_.isLive()){const a=this.timeline_.getSegmentAvailabilityEnd(),b=shaka.media.TimeRangesUtils.bufferEnd(this.mediaElement_.buffered);
if(b!=null&&b>=a)return!0}return!1}onPollWindow_(){if(this.mediaElement_.readyState!=0&&!this.mediaElement_.paused){var a=this.videoWrapper_.getTime(),b=this.timeline_.getSeekRangeStart(),c=this.timeline_.getSeekRangeEnd();c-b<this.minSeekRange_&&(b=c-this.minSeekRange_);a<b&&(b=this.reposition_(a),shaka.log.info("Jumping forward "+(b-a)+" seconds to catch up with the seek range."),this.mediaElement_.currentTime=b)}}onStarted_(a){this.gapController_.onStarted(a)}onSeeking_(){this.gapController_.onSeeking();
const a=this.videoWrapper_.getTime(),b=this.reposition_(a);var c=shaka.media.GapJumpingController.BROWSER_GAP_TOLERANCE;if(!shaka.media.Capabilities.isInfiniteLiveStreamDurationSupported()&&Math.abs(b-a)>c){c=!1;const d=shaka.device.DeviceFactory.getDevice().seekDelay();if(d){const e=Date.now()/1E3;if(!this.lastCorrectiveSeek_||this.lastCorrectiveSeek_<e-d)this.lastCorrectiveSeek_=e,c=!0}else c=!0;if(c){this.videoWrapper_.setTime(b);return}}shaka.log.v1("Seek to "+a);this.onSeek_()}clampSeekToDuration_(a){const b=
this.timeline_.getDuration();return a>=b?(goog.asserts.assert(this.config_.durationBackoff>=0,"Duration backoff must be non-negative!"),b-this.config_.durationBackoff):a}reposition_(a){goog.asserts.assert(this.config_,"Cannot reposition playhead when it has been destroyed");const b=l=>shaka.media.TimeRangesUtils.isBuffered(this.mediaElement_.buffered,l);var c=this.config_.rebufferingGoal;const d=this.config_.safeSeekOffset;let e=this.timeline_.getSeekRangeStart();const f=this.timeline_.getSeekRangeEnd(),
g=this.timeline_.getDuration();f-e<this.minSeekRange_&&(e=f-this.minSeekRange_);const h=this.timeline_.getSafeSeekRangeStart(c),k=this.timeline_.getSafeSeekRangeStart(d);c=this.timeline_.getSafeSeekRangeStart(c+d);if(a>=g)return shaka.log.v1("Playhead past duration."),this.clampSeekToDuration_(a);if(a>f)return shaka.log.v1("Playhead past end."),f-this.config_.safeSeekEndOffset;if(a<e){if(this.timeline_.isLive()&&this.config_.returnToEndOfLiveWindowWhenOutside)return f-this.config_.safeSeekEndOffset;
if(b(k))return shaka.log.v1("Playhead before start & start is buffered"),k;shaka.log.v1("Playhead before start & start is unbuffered");return c}if(a>=h||b(a))return shaka.log.v1("Playhead in safe region or in buffered region."),a;shaka.log.v1("Playhead outside safe region & in unbuffered region.");return c}clampTime_(a){var b=this.timeline_.getSeekRangeStart();if(a<b)return b;b=this.timeline_.getSeekRangeEnd();return a>b?b:a}};shaka.media.SegmentIndex=class{constructor(a){goog.DEBUG&&shaka.media.SegmentIndex.assertCorrectReferences_(a);this.references=a;this.timer_=null;this.numEvicted_=0;this.immutable_=!1}getIsImmutable(){return this.immutable_}getNumReferences(){return this.references.length}getNumEvicted(){return this.numEvicted_}release(){this.immutable_||(this.references=[],this.timer_&&this.timer_.stop(),this.timer_=null)}markImmutable(){this.immutable_=!0}forEachTopLevelReference(a){for(const b of this.references)a(b)}earliestReference(){return this.references[0]||
null}dropFirstReferences(a){this.references.splice(0,a)}find(a){var b=this.references.length-1;if(b<0)return null;if(a<this.references[0].startTime)return this.numEvicted_;const c=shaka.util.ArrayUtils.binarySearch(this.references,e=>e.startTime<=a)-1;if(c<0)return null;const d=this.references[c];b=c<b?this.references[c+1].startTime:d.endTime;return a>=d.startTime&&a<b?c+this.numEvicted_:null}get(a){if(this.references.length==0)return null;a-=this.numEvicted_;return a<0||a>=this.references.length?
null:this.references[a]}offset(a){if(!this.immutable_)for(const b of this.references)b.offset(a)}merge(a){goog.DEBUG&&shaka.media.SegmentIndex.assertCorrectReferences_(a);if(!this.immutable_&&a.length){var b=Math.round(a[0].startTime*1E3)/1E3,c=shaka.util.ArrayUtils.binarySearch(this.references,d=>Math.round(d.startTime*1E3)/1E3<b);this.references.length=c;this.references.push(...a);goog.DEBUG&&shaka.media.SegmentIndex.assertCorrectReferences_(this.references)}}mergeAndEvict(a,b){var c=Math.max(b,
this.references.length>0?this.references[0].startTime:-Infinity);let d=0;for(;d<a.length&&a[d].endTime<=c;)d++;d>0&&(a=a.slice(d));c=this.references[0];this.merge(a);a=this.references[0];c&&goog.asserts.assert(c.startTime==a.startTime,"SegmentIndex.merge should not change the first reference time!");this.evict(b)}evict(a){if(!this.immutable_){var b=shaka.util.ArrayUtils.binarySearch(this.references,c=>c.endTime<=a);b>0&&(this.numEvicted_+=b,this.references=this.references.slice(b))}}fit(a,b,c=!1){goog.asserts.assert(b!=
null,"Content duration must be known for static content!");goog.asserts.assert(b!=Infinity,"Content duration must be finite for static content!");if(!this.immutable_){for(;this.references.length;)if(this.references[this.references.length-1].startTime>=b)this.references.pop();else break;var d=shaka.util.ArrayUtils.binarySearch(this.references,e=>e.endTime<=a);d>0&&(c||(this.numEvicted_+=d),this.references=this.references.slice(d));this.references.length!=0&&(c=this.references[this.references.length-
1],b=new shaka.media.SegmentReference(c.startTime,b,c.getUrisInner,c.startByte,c.endByte,c.initSegmentReference,c.timestampOffset,c.appendWindowStart,c.appendWindowEnd,c.partialReferences,c.tilesLayout,c.tileDuration,c.syncTime,c.status,c.aesKey),b.mimeType=c.mimeType,b.codecs=c.codecs,b.discontinuitySequence=c.discontinuitySequence,this.references[this.references.length-1]=b)}}updateEvery(a,b){goog.asserts.assert(!this.timer_,"SegmentIndex timer already started!");this.immutable_||(this.timer_&&
this.timer_.stop(),this.timer_=new shaka.util.Timer(()=>{const c=b();c?this.references.push(...c):(this.timer_.stop(),this.timer_=null)}),this.timer_.tickEvery(a))}[Symbol.iterator](){const a=this.getIteratorForTime(0);goog.asserts.assert(a!=null,"Iterator for 0 should never be null!");return a}getIteratorForTime(a,b=!1,c=!1){let d=this.find(a);if(d==null)return null;const e=this.get(d);c?d++:d--;let f=-1;if(e&&e.hasPartialSegments())for(let g=e.partialReferences.length-1;g>=0;--g){let h=e.partialReferences[g];
if(a>=h.startTime&&a<h.endTime){if(!b){for(;g&&!h.isIndependent();)g--,h=e.partialReferences[g];if(!h.isIndependent())return shaka.log.alwaysError("No independent partial segment found!"),null}c?d--:d++;f=g-1;break}}return new shaka.media.SegmentIterator(this,d,f,c)}isEmpty(){return this.getNumReferences()==0}continuityTimeline(){return-1}static forSingleSegment(a,b,c){a=new shaka.media.SegmentReference(a,a+b,()=>c,0,null,null,a,a,a+b);return new shaka.media.SegmentIndex([a])}};
goog.exportSymbol("shaka.media.SegmentIndex",shaka.media.SegmentIndex);goog.exportProperty(shaka.media.SegmentIndex,"forSingleSegment",shaka.media.SegmentIndex.forSingleSegment);goog.exportProperty(shaka.media.SegmentIndex.prototype,"getIteratorForTime",shaka.media.SegmentIndex.prototype.getIteratorForTime);goog.exportProperty(shaka.media.SegmentIndex.prototype,"updateEvery",shaka.media.SegmentIndex.prototype.updateEvery);goog.exportProperty(shaka.media.SegmentIndex.prototype,"fit",shaka.media.SegmentIndex.prototype.fit);
goog.exportProperty(shaka.media.SegmentIndex.prototype,"evict",shaka.media.SegmentIndex.prototype.evict);goog.exportProperty(shaka.media.SegmentIndex.prototype,"mergeAndEvict",shaka.media.SegmentIndex.prototype.mergeAndEvict);goog.exportProperty(shaka.media.SegmentIndex.prototype,"offset",shaka.media.SegmentIndex.prototype.offset);goog.exportProperty(shaka.media.SegmentIndex.prototype,"get",shaka.media.SegmentIndex.prototype.get);goog.exportProperty(shaka.media.SegmentIndex.prototype,"find",shaka.media.SegmentIndex.prototype.find);
goog.exportProperty(shaka.media.SegmentIndex.prototype,"markImmutable",shaka.media.SegmentIndex.prototype.markImmutable);goog.exportProperty(shaka.media.SegmentIndex.prototype,"release",shaka.media.SegmentIndex.prototype.release);goog.exportProperty(shaka.media.SegmentIndex.prototype,"getNumEvicted",shaka.media.SegmentIndex.prototype.getNumEvicted);goog.exportProperty(shaka.media.SegmentIndex.prototype,"getNumReferences",shaka.media.SegmentIndex.prototype.getNumReferences);
goog.DEBUG&&(shaka.media.SegmentIndex.assertCorrectReferences_=a=>{goog.asserts.assert(a.every((b,c)=>{if(c==0)return!0;c=a[c-1];return c.startTime<b.startTime?!0:c.startTime>b.startTime?!1:c.endTime<=b.endTime?!0:!1}),"SegmentReferences are incorrect")});
shaka.media.SegmentIterator=class{constructor(a,b,c,d){this.segmentIndex_=a;this.currentPosition_=b;this.currentPartialPosition_=c;this.reverse=d}setReverse(a){this.reverse=a}currentPosition(){return this.currentPosition_}current(){let a=this.segmentIndex_.get(this.currentPosition_);a&&a.hasPartialSegments()&&a.hasAllPartialSegments()&&this.currentPartialPosition_>=a.partialReferences.length&&(this.currentPosition_++,this.currentPartialPosition_=0,a=this.segmentIndex_.get(this.currentPosition_));
return a&&a.hasPartialSegments()?a.partialReferences[this.currentPartialPosition_]:a}next(){var a=this.segmentIndex_.get(this.currentPosition_);this.reverse?a&&a.hasPartialSegments()?(this.currentPartialPosition_--,this.currentPartialPosition_<0&&(this.currentPosition_--,(a=this.segmentIndex_.get(this.currentPosition_))&&a.hasPartialSegments()?this.currentPartialPosition_=a.partialReferences.length-1:this.currentPartialPosition_=0)):(this.currentPosition_--,this.currentPartialPosition_=0):a&&a.hasPartialSegments()?
(this.currentPartialPosition_++,a.hasAllPartialSegments()&&this.currentPartialPosition_==a.partialReferences.length&&(this.currentPosition_++,this.currentPartialPosition_=0)):(this.currentPosition_++,this.currentPartialPosition_=0);a=this.current();return{value:a,done:!a}}resetToLastIndependent(){var a=this.current();if(a&&a.isPartial()&&!a.isIndependent()&&(a=this.segmentIndex_.get(this.currentPosition_))&&a.hasPartialSegments()){let b=a.partialReferences[this.currentPartialPosition_];for(;b.isIndependent()&&
!(this.currentPartialPosition_<=0);)this.currentPartialPosition_--,b=a.partialReferences[this.currentPartialPosition_]}}};goog.exportSymbol("shaka.media.SegmentIterator",shaka.media.SegmentIterator);goog.exportProperty(shaka.media.SegmentIterator.prototype,"resetToLastIndependent",shaka.media.SegmentIterator.prototype.resetToLastIndependent);goog.exportProperty(shaka.media.SegmentIterator.prototype,"next",shaka.media.SegmentIterator.prototype.next);
goog.exportProperty(shaka.media.SegmentIterator.prototype,"current",shaka.media.SegmentIterator.prototype.current);goog.exportProperty(shaka.media.SegmentIterator.prototype,"currentPosition",shaka.media.SegmentIterator.prototype.currentPosition);goog.exportProperty(shaka.media.SegmentIterator.prototype,"setReverse",shaka.media.SegmentIterator.prototype.setReverse);
shaka.media.MetaSegmentIndex=class extends shaka.media.SegmentIndex{constructor(){super([]);this.indexes_=[]}appendSegmentIndex(a){goog.asserts.assert(this.indexes_.length==0||a.getNumEvicted()==0,"Should not append a new segment index with already-evicted segments");this.indexes_.push(a)}clone(){const a=new shaka.media.MetaSegmentIndex;a.indexes_=this.indexes_.slice();a.numEvicted_=this.numEvicted_;return a}release(){this.indexes_=[]}forEachTopLevelReference(a){for(const b of this.indexes_)b.forEachTopLevelReference(a)}forEachIndex(a){for(const b of this.indexes_)a(b)}find(a){let b=
this.numEvicted_;for(const c of this.indexes_){const d=c.find(a);if(d!=null)return d+b;b+=c.getNumEvicted()+c.getNumReferences()}return null}getTimelineForTime(a){for(const b of this.indexes_)if(b.find(a)!=null)return b.continuityTimeline();return-1}get(a){let b=this.numEvicted_,c=!1;for(const e of this.indexes_){goog.asserts.assert(!c||e.getNumEvicted()==0,"Should not see evicted segments after available segments");var d=e.get(a-b);if(d)return d;d=e.getNumReferences();b+=e.getNumEvicted()+d;c=c||
d!=0}return null}offset(a){goog.asserts.assert(!1,"offset() should not be used in MetaSegmentIndex!")}merge(a){goog.asserts.assert(!1,"merge() should not be used in MetaSegmentIndex!")}evict(a){if(this.indexes_.length){var b=this.indexes_[0];b.evict(a);b.isEmpty()&&(this.indexes_.shift(),this.numEvicted_+=b.getNumEvicted(),b.release(),this.evict(a))}}mergeAndEvict(a,b){goog.asserts.assert(!1,"mergeAndEvict() should not be used in MetaSegmentIndex!")}fit(a,b){goog.asserts.assert(!1,"fit() should not be used in MetaSegmentIndex!")}updateEvery(a,
b){goog.asserts.assert(!1,"updateEvery() should not be used in MetaSegmentIndex!")}};goog.exportSymbol("shaka.media.MetaSegmentIndex",shaka.media.MetaSegmentIndex);goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"updateEvery",shaka.media.MetaSegmentIndex.prototype.updateEvery);goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"fit",shaka.media.MetaSegmentIndex.prototype.fit);goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"mergeAndEvict",shaka.media.MetaSegmentIndex.prototype.mergeAndEvict);
goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"evict",shaka.media.MetaSegmentIndex.prototype.evict);goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"merge",shaka.media.MetaSegmentIndex.prototype.merge);goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"offset",shaka.media.MetaSegmentIndex.prototype.offset);goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"get",shaka.media.MetaSegmentIndex.prototype.get);
goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"find",shaka.media.MetaSegmentIndex.prototype.find);goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"forEachTopLevelReference",shaka.media.MetaSegmentIndex.prototype.forEachTopLevelReference);goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"release",shaka.media.MetaSegmentIndex.prototype.release);shaka.media.PlayRateController=class{constructor(a){this.harness_=a;this.isBuffering_=!1;this.rate_=this.harness_.getRate();this.pollRate_=.25;this.timer_=new shaka.util.Timer(()=>{this.harness_.isPaused()||this.harness_.movePlayhead(this.rate_*this.pollRate_)})}release(){this.set(this.getDefaultRate());this.timer_&&(this.timer_.stop(),this.timer_=null);this.harness_=null}setBuffering(a){this.isBuffering_=a;this.apply_()}set(a){goog.asserts.assert(a!=0,"Should never set rate of 0 explicitly!");this.rate_=
a;this.apply_()}getRealRate(){return this.rate_}getDefaultRate(){return this.harness_.getDefaultRate()}apply_(){this.timer_.stop();const a=this.calculateCurrentRate_();shaka.log.v1("Changing effective playback rate to",a);if(a>=0&&a<=16)try{this.applyRate_(a);return}catch(b){}this.timer_.tickEvery(this.pollRate_);this.applyRate_(0)}calculateCurrentRate_(){return this.isBuffering_?0:this.rate_}applyRate_(a){const b=this.harness_.getRate();b!=a&&this.harness_.setRate(a);return b!=a}};shaka.media.IPlayheadObserver=class{poll(a,b){}};
shaka.media.PlayheadObserverManager=class{constructor(a){this.mediaElement_=a;this.eventManager_=new shaka.util.EventManager;this.observers_=new Set;this.pollingLoop_=(new shaka.util.Timer(()=>{this.pollAllObservers_(!1)})).tickNow();a.paused||this.pollingLoop_.tickEvery(.25);this.eventManager_.listen(a,"playing",()=>{this.pollingLoop_.tickNow().tickEvery(.25)});this.eventManager_.listen(a,"pause",()=>{this.pollingLoop_.stop()});this.eventManager_.listen(a,"seeked",()=>{this.pollingLoop_.tickNow();
a.paused||this.pollingLoop_.tickEvery(.25)})}release(){this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null);this.pollingLoop_.stop();for(const a of this.observers_)a.release();this.observers_.clear()}manage(a){this.observers_.add(a)}notifyOfSeek(a){this.pollAllObservers_(a)}pollAllObservers_(a){const b=this.mediaElement_.currentTime;for(const c of this.observers_)c.poll(b,a)}};shaka.media.QualityObserver=class extends shaka.util.FakeEventTarget{constructor(a){super();this.contentTypeStates_=new Map;this.getBufferedInfo_=a}release(){this.contentTypeStates_.clear();super.release()}getContentTypeState_(a){let b=this.contentTypeStates_.get(a);b||(b={qualityChangePositions:[],currentQuality:null,contentType:a},this.contentTypeStates_.set(a,b));return b}addMediaQualityChange(a,b){var c=this.getContentTypeState_(a.contentType);this.purgeQualityChangePositions_(c);a={mediaQuality:a,
position:b};c=c.qualityChangePositions;const d=c.findIndex(e=>e.position>=b);d>=0?c.splice(d,c[d].position==b?1:0,a):c.push(a)}static getMediaQualityAtPosition_(a,b){b=b.qualityChangePositions;for(let c=b.length-1;c>=0;c--){const d=b[c];if(d.position<=a)return d.mediaQuality}return null}static mediaQualitiesAreTheSame_(a,b){return a===b?!0:a&&b?a.bandwidth==b.bandwidth&&a.audioSamplingRate==b.audioSamplingRate&&a.codecs==b.codecs&&a.contentType==b.contentType&&a.frameRate==b.frameRate&&a.height==
b.height&&a.mimeType==b.mimeType&&a.channelsCount==b.channelsCount&&a.pixelAspectRatio==b.pixelAspectRatio&&a.width==b.width:!1}poll(a,b){for(const e of this.contentTypeStates_.values()){var c=e.currentQuality;const f=(b=shaka.media.QualityObserver.getMediaQualityAtPosition_(a,e))&&!shaka.media.QualityObserver.mediaQualitiesAreTheSame_(c,b);var d=b&&c&&b.label&&c.label&&c.label!==b.label;const g=b&&c&&b.language&&c.language&&c.language!==b.language;c=b&&c&&b.roles&&c.roles&&!shaka.util.ArrayUtils.equal(c.roles,
b.roles);(d||g||c)&&this.positionIsBuffered_(a,b.contentType)&&(e.currentQuality=b,d=new shaka.util.FakeEvent("audiotrackchange",new Map([["quality",b],["position",a]])),this.dispatchEvent(d));f&&this.positionIsBuffered_(a,b.contentType)&&(e.currentQuality=b,shaka.log.debug("Media quality changed at position "+a+" "+JSON.stringify(b)),b=new shaka.util.FakeEvent("qualitychange",new Map([["quality",b],["position",a]])),this.dispatchEvent(b))}}positionIsBuffered_(a,b){if((b=this.getBufferedInfo_()[b])&&
b.length>0){const c=b[b.length-1].end;if(a>=b[0].start&&a<c)return!0}return!1}purgeQualityChangePositions_(a){const b=this.getBufferedInfo_()[a.contentType];if(b&&b.length>0){const c=b[0].start,d=b[b.length-1].end,e=a.qualityChangePositions;a.qualityChangePositions=e.filter((f,g)=>f.position<=c&&g+1<e.length&&e[g+1].position<=c||f.position>=d?!1:!0)}else a.qualityChangePositions=[]}static createQualityInfo(a){const b={bandwidth:a.bandwidth||0,audioSamplingRate:null,codecs:a.codecs,contentType:a.type,
frameRate:null,height:null,mimeType:a.mimeType,channelsCount:null,pixelAspectRatio:null,width:null,label:null,roles:a.roles,language:null};a.type==shaka.util.ManifestParserUtils.ContentType.VIDEO&&(b.frameRate=a.frameRate||null,b.height=a.height||null,b.pixelAspectRatio=a.pixelAspectRatio||null,b.width=a.width||null);a.type==shaka.util.ManifestParserUtils.ContentType.AUDIO&&(b.audioSamplingRate=a.audioSamplingRate,b.channelsCount=a.channelsCount,b.label=a.label||null,b.language=a.language);return b}};shaka.media.RegionTimeline=class extends shaka.util.FakeEventTarget{constructor(a){super();this.regions_=new Map;this.getFilterRange_=a;this.filterTimer_=null}release(){this.regions_.clear();this.releaseTimer_();super.release()}addRegion(a){const b=this.generateKey_(a);this.regions_.has(b)||(this.regions_.set(b,a),a=new shaka.util.FakeEvent("regionadd",new Map([["region",a]])),this.dispatchEvent(a),this.setupTimer_())}filterByRange_(){const a=this.getFilterRange_();for(const [b,c]of this.regions_)if(c.endTime<
a.start){this.regions_.delete(b);const d=new shaka.util.FakeEvent("regionremove",new Map([["region",c]]));this.dispatchEvent(d)}this.regions_.size||this.releaseTimer_()}setupTimer_(){this.filterTimer_||(this.filterTimer_=(new shaka.util.Timer(()=>{this.filterByRange_()})).tickEvery(shaka.media.RegionTimeline.REGION_FILTER_INTERVAL))}releaseTimer_(){this.filterTimer_&&(this.filterTimer_.stop(),this.filterTimer_=null)}regions(){return this.regions_.values()}generateKey_(a){return`${a.schemeIdUri}_${a.id}_${a.startTime.toFixed(1)}_${a.endTime.toFixed(1)}`}};
shaka.media.RegionTimeline.REGION_FILTER_INTERVAL=2;shaka.media.SegmentPrefetch=class{constructor(a,b,c,d,e){this.prefetchLimit_=a;this.stream_=b;this.fetchDispatcher_=c;this.segmentPrefetchMap_=new Map;this.initSegmentPrefetchMap_=new Map;this.iterator_=null;this.reverse_=d;a=(f,g)=>g.fastSwitching&&f.isPartial()&&f.isLastPartial()?!1:!0;this.shouldPrefetchNextSegment_=e||a}replaceFetchDispatcher(a){this.fetchDispatcher_=a;for(const b of this.segmentPrefetchMap_.values())b.replaceFetchDispatcher(a)}prefetchSegmentsByTime(a,b=!1){goog.asserts.assert(this.prefetchLimit_>
0,"SegmentPrefetch can not be used when prefetchLimit <= 0.");var c=shaka.media.SegmentPrefetch.logPrefix_(this.stream_);if(!this.stream_.segmentIndex)return shaka.log.debug(c,"missing segmentIndex"),Promise.resolve();this.iterator_||(this.iterator_=this.stream_.segmentIndex.getIteratorForTime(a,!0,this.reverse_));if(!this.iterator_)return shaka.log.debug(c,"missing iterator"),Promise.resolve();b&&this.iterator_.next();for(a=[];this.segmentPrefetchMap_.size<this.prefetchLimit_;){b=this.iterator_.next().value;
if(!b)break;c=!0;b.isPreload()&&b.endByte!=null&&(c=!1);b.getStatus()==shaka.media.SegmentReference.Status.MISSING&&(c=!1);b.getSegmentData(!1)&&(c=!1);c&&b.initSegmentReference&&a.push(this.prefetchInitSegment(b.initSegmentReference));c&&!this.segmentPrefetchMap_.has(b)&&(c=new shaka.media.SegmentPrefetchOperation(this.fetchDispatcher_),a.push(c.dispatchFetch(b,this.stream_)),this.segmentPrefetchMap_.set(b,c));if(!this.shouldPrefetchNextSegment_(b,this.stream_))break}this.clearInitSegments_();return Promise.all(a)}prefetchInitSegment(a){goog.asserts.assert(this.prefetchLimit_>
0,"SegmentPrefetch can not be used when prefetchLimit <= 0.");var b=shaka.media.SegmentPrefetch.logPrefix_(this.stream_);if(!this.stream_.segmentIndex)return shaka.log.debug(b,"missing segmentIndex"),Promise.resolve();if(a.getSegmentData()||Array.from(this.initSegmentPrefetchMap_.keys()).some(d=>shaka.media.InitSegmentReference.equal(d,a)))return Promise.resolve();b=new shaka.media.SegmentPrefetchOperation(this.fetchDispatcher_);const c=b.dispatchFetch(a,this.stream_);this.initSegmentPrefetchMap_.set(a,
b);return c}getPrefetchedSegment(a,b){goog.asserts.assert(this.prefetchLimit_>0,"SegmentPrefetch can not be used when prefetchLimit <= 0.");const c=shaka.media.SegmentPrefetch.logPrefix_(this.stream_);let d=this.segmentPrefetchMap_;a instanceof shaka.media.InitSegmentReference&&(d=this.initSegmentPrefetchMap_);if(d.has(a)){const e=d.get(a);b&&e.setStreamDataCallback(b);a instanceof shaka.media.SegmentReference?shaka.log.debug(c,"reused prefetched segment at time:",a.startTime,"mapSize",d.size):shaka.log.debug(c,
"reused prefetched init segment at time, mapSize",d.size);return e.getOperation()}a instanceof shaka.media.SegmentReference?shaka.log.debug(c,"missed segment at time:",a.startTime,"mapSize",d.size):shaka.log.debug(c,"missed init segment at time, mapSize",d.size);return null}clearMap_(a){for(const b of a.keys())b&&this.abortPrefetchedSegment_(b)}resetPosition(){this.iterator_=null}clearAll(){this.clearMap_(this.segmentPrefetchMap_);this.clearMap_(this.initSegmentPrefetchMap_);this.resetPosition();
const a=shaka.media.SegmentPrefetch.logPrefix_(this.stream_);shaka.log.debug(a,"cleared all")}removeReference(a){this.abortPrefetchedSegment_(a)}evict(a,b=!1){for(const c of this.segmentPrefetchMap_.keys())a>c.endTime&&this.abortPrefetchedSegment_(c);b&&this.clearInitSegments_()}setReverse(a){this.reverse_=a;this.iterator_&&this.iterator_.setReverse(a)}clearInitSegments_(){if(this.segmentPrefetchMap_.size){var a=Array.from(this.segmentPrefetchMap_.keys());for(const b of this.initSegmentPrefetchMap_.keys())a.some(c=>
shaka.media.InitSegmentReference.equal(c.initSegmentReference,b))||this.abortPrefetchedSegment_(b)}}resetLimit(a){goog.asserts.assert(a>=0,"The new prefetch limit must be >= 0.");var b=shaka.media.SegmentPrefetch.logPrefix_(this.stream_);shaka.log.debug(b,"resetting prefetch limit to",a);this.prefetchLimit_=a;for(b=Array.from(this.segmentPrefetchMap_.keys());b.length>a;){const c=b.pop();c&&this.abortPrefetchedSegment_(c)}this.clearInitSegments_()}switchStream(a){a&&a!==this.stream_&&(this.clearAll(),
this.stream_=a)}getStream(){return this.stream_}abortPrefetchedSegment_(a){const b=shaka.media.SegmentPrefetch.logPrefix_(this.stream_);let c=this.segmentPrefetchMap_;a instanceof shaka.media.InitSegmentReference&&(c=this.initSegmentPrefetchMap_);const d=c.get(a);c.delete(a);d&&(d.abort(),a instanceof shaka.media.SegmentReference?shaka.log.debug(b,"pop and abort prefetched segment at time:",a.startTime):shaka.log.debug(b,"pop and abort prefetched init segment"))}static logPrefix_(a){return"SegmentPrefetch("+
a.type+":"+a.id+")"}};
shaka.media.SegmentPrefetchOperation=class{constructor(a){this.fetchDispatcher_=a;this.operation_=this.streamDataCallback_=null}replaceFetchDispatcher(a){this.fetchDispatcher_=a}dispatchFetch(a,b){let c=new Uint8Array(0);this.operation_=this.fetchDispatcher_(a,b,async d=>{c=c.byteLength>0?shaka.util.Uint8ArrayUtils.concat(c,d):d;this.streamDataCallback_&&(await this.streamDataCallback_(c),c=new Uint8Array(0))});return this.operation_.promise.catch(d=>d instanceof shaka.util.Error&&d.code==shaka.util.Error.Code.OPERATION_ABORTED?
Promise.resolve():Promise.reject(d))}getOperation(){return this.operation_}setStreamDataCallback(a){this.streamDataCallback_=a}abort(){this.operation_&&this.operation_.abort()}};shaka.config.CrossBoundaryStrategy={KEEP:"keep",RESET:"reset",RESET_TO_ENCRYPTED:"reset_to_encrypted",RESET_ON_ENCRYPTION_CHANGE:"RESET_ON_ENCRYPTION_CHANGE"};goog.exportSymbol("shaka.config.CrossBoundaryStrategy",shaka.config.CrossBoundaryStrategy);shaka.media.SegmentUtils=class{static getBasicInfoFromMimeType(a){const b=shaka.util.MimeUtils.getBasicType(a),c=b.split("/")[0];a=shaka.util.MimeUtils.getCodecs(a);return{type:c,mimeType:b,codecs:a,language:null,height:null,width:null,channelCount:null,sampleRate:null,closedCaptions:new Map,videoRange:null,colorGamut:null,frameRate:null,timescale:null}}static getBasicInfoFromTs(a,b,c,d){var e=shaka.util.BufferUtils.toUint8(a);const f=(new shaka.util.TsParser).parse(e),g=f.getCodecs();e=f.getVideoInfo();
const h=[];let k=!1,l=!1;if(!b)switch(g.audio){case "aac":case "aac-loas":f.getAudioData().length&&(h.push("mp4a.40.2"),k=!0);break;case "mp3":f.getAudioData().length&&(h.push("mp4a.40.34"),k=!0);break;case "ac3":f.getAudioData().length&&(h.push("ac-3"),k=!0);break;case "ec3":f.getAudioData().length&&(h.push("ec-3"),k=!0);break;case "opus":f.getAudioData().length&&(h.push("opus"),k=!0)}if(!c)switch(g.video){case "avc":e.codec?h.push(e.codec):h.push("avc1.42E01E");l=!0;break;case "hvc":e.codec?h.push(e.codec):
h.push("hvc1.1.6.L93.90");l=!0;break;case "av1":h.push("av01.0.01M.08"),l=!0}if(!h.length)return null;b=k&&!l;c=new Map;if(l&&!d){d=new shaka.media.ClosedCaptionParser("video/mp2t");d.parseFrom(a);for(const m of d.getStreams())c.set(m,m);d.reset()}return{type:b?"audio":"video",mimeType:"video/mp2t",codecs:h.join(", "),language:null,height:e.height,width:e.width,channelCount:null,sampleRate:null,closedCaptions:c,videoRange:null,colorGamut:null,frameRate:e.frameRate,timescale:null}}static getBasicInfoFromMp4(a,
b,c){const d=shaka.util.Mp4Parser,e=shaka.media.SegmentUtils,f=[];let g=[],h=!1,k=!1;const l=w=>{w=w.toLowerCase();switch(w){case "avc1":case "avc3":g.push(w+".42E01E");k=!0;break;case "hev1":case "hvc1":g.push(w+".1.6.L93.90");k=!0;break;case "dvh1":case "dvhe":g.push(w+".05.04");k=!0;break;case "vp09":g.push(w+".00.10.08");k=!0;break;case "av01":g.push(w+".0.01M.08");k=!0;break;case "mp4a":f.push("mp4a.40.2");h=!0;break;case "ac-3":case "ec-3":case "ac-4":case "opus":case "flac":f.push(w);h=!0;
break;case "apac":f.push("apac.31.00"),h=!0}};let m=null,n=null,q=null,p=null,r=null,t=null,u=null,v=null,x;var y=w=>{const z=shaka.util.Mp4BoxParsers.audioSampleEntry(w.reader);p=z.channelCount;r=z.sampleRate;l(w.name)},A=w=>{x=w.name;const z=shaka.util.Mp4BoxParsers.visualSampleEntry(w.reader);q=String(z.width);n=String(z.height);w.reader.hasMoreData()&&d.children(w)};(new d).box("moov",d.children).box("trak",d.children).box("mdia",d.children).fullBox("mdhd",w=>{goog.asserts.assert(w.version!=null,
"MDHD is a full box and should have a valid version.");w=shaka.util.Mp4BoxParsers.parseMDHD(w.reader,w.version);m=w.language;v=w.timescale}).box("minf",d.children).box("stbl",d.children).fullBox("stsd",d.sampleDescription).box("mp4a",w=>{const z=shaka.util.Mp4BoxParsers.audioSampleEntry(w.reader);p=z.channelCount;r=z.sampleRate;w.reader.hasMoreData()?d.children(w):l(w.name)}).box("esds",w=>{w=shaka.util.Mp4BoxParsers.parseESDS(w.reader);f.push(w.codec);h=!0}).box("ac-3",y).box("ec-3",y).box("ac-4",
y).box("Opus",y).box("fLaC",y).box("apac",y).box("avc1",A).box("avc3",A).box("hev1",A).box("hvc1",A).box("dva1",A).box("dvav",A).box("dvh1",A).box("dvhe",A).box("vp09",A).box("av01",A).box("avcC",w=>{let z=x||"";switch(x){case "dvav":z="avc3";break;case "dva1":z="avc1"}w=shaka.util.Mp4BoxParsers.parseAVCC(z,w.reader);g.push(w.codec);k=!0}).box("hvcC",w=>{let z=x||"";switch(x){case "dvh1":z="hvc1";break;case "dvhe":z="hev1"}w=shaka.util.Mp4BoxParsers.parseHVCC(z,w.reader);g.push(w.codec);k=!0}).box("dvcC",
w=>{let z=x||"";switch(x){case "hvc1":z="dvh1";break;case "hev1":z="dvhe";break;case "avc1":z="dva1";break;case "avc3":z="dvav";break;case "av01":z="dav1"}w=shaka.util.Mp4BoxParsers.parseDVCC(z,w.reader);g.push(w.codec);k=!0}).box("dvvC",w=>{let z=x||"";switch(x){case "hvc1":z="dvh1";break;case "hev1":z="dvhe";break;case "avc1":z="dva1";break;case "avc3":z="dvav";break;case "av01":z="dav1"}w=shaka.util.Mp4BoxParsers.parseDVVC(z,w.reader);g.push(w.codec);k=!0}).fullBox("vpcC",w=>{w=shaka.util.Mp4BoxParsers.parseVPCC(x||
"",w.reader);g.push(w.codec);k=!0}).box("av1C",w=>{let z=x||"";switch(x){case "dav1":z="av01"}w=shaka.util.Mp4BoxParsers.parseAV1C(z,w.reader);g.push(w.codec);k=!0}).box("enca",d.audioSampleEntry).box("encv",d.visualSampleEntry).box("sinf",d.children).box("frma",w=>{({codec:w}=shaka.util.Mp4BoxParsers.parseFRMA(w.reader));l(w)}).box("colr",w=>{g=g.map(C=>C.startsWith("av01.")?shaka.util.Mp4BoxParsers.updateAV1CodecWithCOLRBox(C,w.reader):C);const {videoRange:z,colorGamut:B}=shaka.util.Mp4BoxParsers.parseCOLR(w.reader);
t=z;u=B}).parse(a||b,!0,!0);if(!f.length&&!g.length)return null;y=h&&!k;A=new Map;if(k&&!c){c=new shaka.media.ClosedCaptionParser("video/mp4");a&&c.init(a);try{c.parseFrom(b);for(const w of c.getStreams())A.set(w,w)}catch(w){shaka.log.debug("Error detecting CC streams",w)}c.reset()}a=f.concat(g);return{type:y?"audio":"video",mimeType:y?"audio/mp4":"video/mp4",codecs:e.codecsFiltering(a).join(", "),language:m,height:n,width:q,channelCount:p,sampleRate:r,closedCaptions:A,videoRange:t,colorGamut:u,frameRate:null,
timescale:v}}static codecsFiltering(a){var b=shaka.util.ManifestParserUtils.ContentType;const c=shaka.util.ManifestParserUtils;var d=shaka.media.SegmentUtils;a=d.filterDuplicateCodecs_(a);const e=c.guessAllCodecsSafe(b.AUDIO,a),f=c.guessAllCodecsSafe(b.VIDEO,a);b=c.guessAllCodecsSafe(b.TEXT,a);d=d.chooseBetterCodecs_(f);d=e.concat(d).concat(b);return a.length&&!d.length?a:d}static filterDuplicateCodecs_(a){const b=new Set,c=[];for(const d of a)a=shaka.util.MimeUtils.getCodecBase(d),b.has(a)?shaka.log.debug("Ignoring duplicate codec"):
(c.push(d),b.add(a));return c}static chooseBetterCodecs_(a){if(a.length<=1)return a;const b=a.find(c=>c.startsWith("dvav.")||c.startsWith("dva1.")||c.startsWith("dvh1.")||c.startsWith("dvhe.")||c.startsWith("dav1.")||c.startsWith("dvc1.")||c.startsWith("dvi1."));return b?shaka.media.Capabilities.isTypeSupported(`video/mp4; codecs="${b}"`)?[b]:a.filter(c=>c!=b):a}static getDefaultKID(a){const b=shaka.util.Mp4Parser;let c=null;(new b).box("moov",b.children).box("trak",b.children).box("mdia",b.children).box("minf",
b.children).box("stbl",b.children).fullBox("stsd",b.sampleDescription).box("encv",b.visualSampleEntry).box("enca",b.audioSampleEntry).box("sinf",b.children).box("schi",b.children).fullBox("tenc",d=>{c=shaka.util.Mp4BoxParsers.parseTENC(d.reader).defaultKID}).parse(a,!0);return c}static async aesDecrypt(a,b,c){b.cryptoKey||(goog.asserts.assert(b.fetchKey,"If AES cryptoKey was not preloaded, fetchKey function should be provided"),await b.fetchKey(),goog.asserts.assert(b.cryptoKey,"AES cryptoKey should now be set"));
let d=b.iv;if(!d){d=shaka.util.BufferUtils.toUint8(new ArrayBuffer(16));c=b.firstMediaSequenceNumber+c;for(let e=d.byteLength-1;e>=0;e--)d[e]=c&255,c>>=8}return window.crypto.subtle.decrypt(b.blockCipherMode=="CBC"?{name:"AES-CBC",iv:d}:{name:"AES-CTR",counter:d,length:64},b.cryptoKey,a)}};shaka.net.NetworkingUtils=class{static async getMimeType(a,b,c){var d=shaka.net.NetworkingUtils.getExtension(a);if(d=shaka.net.NetworkingUtils.EXTENSIONS_TO_MIME_TYPES_.get(d))return d;const e=shaka.net.NetworkingEngine.RequestType.MANIFEST;a=shaka.net.NetworkingEngine.makeRequest([a],c);try{a.method="HEAD",d=(await b.request(e,a).promise).headers["content-type"]}catch(f){!f||f.code!=shaka.util.Error.Code.HTTP_ERROR&&f.code!=shaka.util.Error.Code.BAD_HTTP_STATUS||(a.method="GET",d=(await b.request(e,
a).promise).headers["content-type"])}return d?d.toLowerCase().split(";").shift():""}static getExtension(a){let b=a.length;for(var c=0;c<a.length;c++){var d=a.charCodeAt(c);if(d===63||d===35){b=c;break}}for(c=b-1;c>=0;c--){d=a.charCodeAt(c);if(d===46){if(c+1<b)return a.slice(c+1,b).toLowerCase();break}if(d===47)break}return""}static createSegmentRequest(a,b,c,d,e){a=shaka.net.NetworkingEngine.makeRequest(a,d,e);if(b!=0||c!=null)a.headers.Range=c?"bytes="+b+"-"+c:"bytes="+b+"-";return a}};
shaka.net.NetworkingUtils.EXTENSIONS_TO_MIME_TYPES_=(new Map).set("mp4","video/mp4").set("m4v","video/mp4").set("m4a","audio/mp4").set("webm","video/webm").set("weba","audio/webm").set("mkv","video/webm").set("ts","video/mp2t").set("ogv","video/ogg").set("ogg","audio/ogg").set("mpg","video/mpeg").set("mpeg","video/mpeg").set("mov","video/quicktime").set("m3u8","application/x-mpegurl").set("mpd","application/dash+xml").set("ism","application/vnd.ms-sstr+xml").set("mp3","audio/mpeg").set("aac","audio/aac").set("flac",
"audio/flac").set("wav","audio/wav").set("sbv","text/x-subviewer").set("srt","text/srt").set("vtt","text/vtt").set("webvtt","text/vtt").set("ttml","application/ttml+xml").set("lrc","application/x-subtitle-lrc").set("ssa","text/x-ssa").set("ass","text/x-ssa").set("jpeg","image/jpeg").set("jpg","image/jpeg").set("png","image/png").set("svg","image/svg+xml").set("webp","image/webp").set("avif","image/avif").set("html","text/html").set("htm","text/html");shaka.media.StreamingEngine=class{constructor(a,b){this.playerInterface_=b;this.manifest_=a;this.config_=null;this.deferredCloseSegmentIndex_=new Map;this.bufferingScale_=1;this.currentTextStream_=this.currentVariant_=null;this.textStreamSequenceId_=0;this.mediaStates_=new Map;this.startupComplete_=!1;this.failureCallbackBackoff_=null;this.fatalError_=!1;this.destroyer_=new shaka.util.Destroyer(()=>this.doDestroy_());this.lastMediaSourceReset_=Date.now()/1E3;this.audioPrefetchMap_=new Map;this.spatialVideoInfo_=
{projection:null,hfov:null};this.playRangeStart_=0;this.playRangeEnd_=Infinity;this.lastTextMediaStateBeforeUnload_=null;this.requestedDependencySegments_=[];this.updateLiveSeekableRangeTimer_=new shaka.util.Timer(()=>{if(this.manifest_&&this.playerInterface_)if(this.manifest_.presentationTimeline.isLive()){var c=this.manifest_.presentationTimeline.getSeekRangeStart(),d=this.manifest_.presentationTimeline.getSeekRangeEnd();d-c>1?this.playerInterface_.mediaSourceEngine.setLiveSeekableRange(c,d):this.playerInterface_.mediaSourceEngine.clearLiveSeekableRange()}else this.playerInterface_.mediaSourceEngine.clearLiveSeekableRange(),
this.updateLiveSeekableRangeTimer_&&this.updateLiveSeekableRangeTimer_.stop();else this.updateLiveSeekableRangeTimer_&&this.updateLiveSeekableRangeTimer_.stop()});this.boundaryTime_=null;this.crossBoundarySeek_=!1;this.crossBoundaryTimer_=new shaka.util.Timer(()=>{const c=this.playerInterface_.video;!c.ended&&this.boundaryTime_&&(shaka.log.info("Crossing boundary at",this.boundaryTime_),this.crossBoundarySeek_=!0,c.currentTime=this.boundaryTime_,this.boundaryTime_=null)});this.crossBoundaryEventManager_=
new shaka.util.EventManager}destroy(){return this.destroyer_.destroy()}async doDestroy_(){this.updateLiveSeekableRangeTimer_&&this.updateLiveSeekableRangeTimer_.stop();this.updateLiveSeekableRangeTimer_=null;this.crossBoundaryTimer_&&this.crossBoundaryTimer_.stop();this.crossBoundaryTimer_=null;this.crossBoundaryEventManager_&&(this.crossBoundaryEventManager_.release(),this.crossBoundaryEventManager_=null);const a=[];for(const b of this.mediaStates_.values())this.cancelUpdate_(b),a.push(this.abortOperations_(b)),
b.segmentPrefetch&&(b.segmentPrefetch.clearAll(),b.segmentPrefetch=null);for(const b of this.audioPrefetchMap_.values())b.clearAll();await Promise.all(a);this.mediaStates_.clear();this.audioPrefetchMap_.clear();this.boundaryTime_=this.config_=this.manifest_=this.playerInterface_=null}configure(a){this.config_=a;this.failureCallbackBackoff_=new shaka.net.Backoff({maxAttempts:Math.max(a.retryParameters.maxAttempts,2),baseDelay:a.retryParameters.baseDelay,backoffFactor:a.retryParameters.backoffFactor,
fuzzFactor:a.retryParameters.fuzzFactor,timeout:0,stallTimeout:0,connectionTimeout:0},!0);var b=shaka.util.ManifestParserUtils.ContentType;if(a.disableAudioPrefetch){var c=this.mediaStates_.get(b.AUDIO);c&&c.segmentPrefetch&&(c.segmentPrefetch.clearAll(),c.segmentPrefetch=null);for(const d of this.audioPrefetchMap_.keys())this.audioPrefetchMap_.get(d).clearAll(),this.audioPrefetchMap_.delete(d)}a.disableTextPrefetch&&(c=this.mediaStates_.get(b.TEXT))&&c.segmentPrefetch&&(c.segmentPrefetch.clearAll(),
c.segmentPrefetch=null);a.disableVideoPrefetch&&(b=this.mediaStates_.get(b.VIDEO))&&b.segmentPrefetch&&(b.segmentPrefetch.clearAll(),b.segmentPrefetch=null);for(const d of this.mediaStates_.keys())b=this.mediaStates_.get(d),b.segmentPrefetch?(b.segmentPrefetch.resetLimit(a.segmentPrefetchLimit),a.segmentPrefetchLimit>0||(b.segmentPrefetch.clearAll(),b.segmentPrefetch=null)):a.segmentPrefetchLimit>0&&(b.segmentPrefetch=this.createSegmentPrefetch_(b.stream));a.disableAudioPrefetch||this.updatePrefetchMapForAudio_()}applyPlayRange(a,
b){this.manifest_.presentationTimeline.isLive()||(this.playRangeStart_=a,this.playRangeEnd_=b)}async start(a){goog.asserts.assert(this.config_,"StreamingEngine configure() must be called before init()!");await this.initStreams_(a||new Map);this.destroyer_.ensureNotDestroyed();shaka.log.debug("init: completed initial Stream setup");this.startupComplete_=!0}getCurrentVariant(){return this.currentVariant_}getCurrentTextStream(){return this.currentTextStream_}async loadNewTextStream_(a){const b=shaka.util.ManifestParserUtils.ContentType;
goog.asserts.assert(!this.mediaStates_.has(b.TEXT),"Should not call loadNewTextStream_ while streaming text!");this.textStreamSequenceId_++;const c=this.textStreamSequenceId_;try{await this.playerInterface_.mediaSourceEngine.clear(b.TEXT)}catch(e){if(this.playerInterface_)this.playerInterface_.onError(e)}const d=shaka.util.MimeUtils.getFullType(a.mimeType,a.codecs);this.playerInterface_.mediaSourceEngine.reinitText(d,this.manifest_.sequenceMode,a.external);(this.playerInterface_.mediaSourceEngine.getTextDisplayer().isTextVisible()||
this.config_.alwaysStreamText)&&this.textStreamSequenceId_==c&&(a=this.createMediaState_(a),this.mediaStates_.set(b.TEXT,a),this.scheduleUpdate_(a,0))}unloadTextStream(){const a=shaka.util.ManifestParserUtils.ContentType,b=this.mediaStates_.get(a.TEXT);b&&(this.cancelUpdate_(b),this.abortOperations_(b).catch(()=>{}),this.lastTextMediaStateBeforeUnload_=this.mediaStates_.get(a.TEXT),this.mediaStates_.delete(a.TEXT),b.stream&&b.stream.closeSegmentIndex&&b.stream.closeSegmentIndex());this.currentTextStream_=
null}setTrickPlay(a){var b=shaka.util.ManifestParserUtils.ContentType;this.updateSegmentIteratorReverse_();if(b=this.mediaStates_.get(b.VIDEO)){var c=b.stream;if(c)if(shaka.log.debug("setTrickPlay",a),a)(a=c.trickModeVideo)&&!b.restoreStreamAfterTrickPlay&&(shaka.log.debug("Engaging trick mode stream",a),this.switchInternal_(a,!1,0,!1),b.restoreStreamAfterTrickPlay=c);else if(a=b.restoreStreamAfterTrickPlay)shaka.log.debug("Restoring non-trick-mode stream",a),b.restoreStreamAfterTrickPlay=null,this.switchInternal_(a,
!0,0,!1)}}switchVariant(a,b=!1,c=0,d=!1,e=!1){this.currentVariant_=a;this.startupComplete_&&(a.video&&this.switchInternal_(a.video,b,c,d,e),a.audio&&this.switchInternal_(a.audio,b,c,d,e))}async switchTextStream(a){this.lastTextMediaStateBeforeUnload_=null;this.currentTextStream_=a;if(this.startupComplete_){var b=shaka.util.ManifestParserUtils.ContentType;goog.asserts.assert(a&&a.type==b.TEXT,"Wrong stream type passed to switchTextStream!");a.segmentIndex||await a.createSegmentIndex();this.switchInternal_(a,
!0,0,!1)}}reloadTextStream(){const a=this.mediaStates_.get(shaka.util.ManifestParserUtils.ContentType.TEXT);a&&this.switchInternal_(a.stream,!0,0,!0)}handleDeferredCloseSegmentIndexes_(a){for(const [b,c]of this.deferredCloseSegmentIndex_.entries()){const d=b,e=c;d.includes(a.type)&&(e(),this.deferredCloseSegmentIndex_.delete(d))}}switchInternal_(a,b,c,d,e){const f=shaka.util.ManifestParserUtils.ContentType,g=this.mediaStates_.get(a.type);g||a.type!=f.TEXT?(goog.asserts.assert(g,"switch: expected mediaState to exist"),
g&&(g.restoreStreamAfterTrickPlay&&(shaka.log.debug("switch during trick play mode",a),a.trickModeVideo?(g.restoreStreamAfterTrickPlay=a,a=a.trickModeVideo,shaka.log.debug("switch found trick play stream",a)):(g.restoreStreamAfterTrickPlay=null,shaka.log.debug("switch found no special trick play stream"))),g.stream!=a||d?(this.audioPrefetchMap_.has(a)?g.segmentPrefetch=this.audioPrefetchMap_.get(a):g.segmentPrefetch&&g.segmentPrefetch.switchStream(a),a.type==f.TEXT&&g.stream!=a&&(d=shaka.util.MimeUtils.getFullType(a.mimeType,
a.codecs),this.playerInterface_.mediaSourceEngine.reinitText(d,this.manifest_.sequenceMode,a.external)),!this.audioPrefetchMap_.has(g.stream)&&g.stream.closeSegmentIndex&&(g.performingUpdate?(d=shaka.media.StreamingEngine.logPrefix_(g),this.deferredCloseSegmentIndex_.has(d)||this.deferredCloseSegmentIndex_.set(d,g.stream.closeSegmentIndex)):g.stream.closeSegmentIndex()),d=g.stream.isAudioMuxedInVideo!=a.isAudioMuxedInVideo,g.stream=a,g.segmentIterator=null,g.adaptation=!!e,g.dependencyMediaState=
a.dependencyStream?this.createMediaState_(a.dependencyStream):null,this.setupCrossBoundaryListeners_(),e=shaka.media.StreamingEngine.logPrefix_(g),shaka.log.debug("switch: switching to Stream "+e),d&&(g.lastInitSegmentReference=null,g.lastAppendWindowStart=null,g.lastAppendWindowEnd=null,a.isAudioMuxedInVideo&&(a=null,g.type===f.VIDEO?a=this.mediaStates_.get(f.AUDIO):g.type===f.AUDIO&&(a=this.mediaStates_.get(f.VIDEO)),a&&(this.abortOperations_(a).catch(()=>{}),a.lastInitSegmentReference=null,a.lastAppendWindowStart=
null,a.lastAppendWindowEnd=null,this.forceClearBuffer_(a),this.makeAbortDecision_(a).catch(h=>{this.playerInterface_&&(goog.asserts.assert(h instanceof shaka.util.Error,"Wrong error type!"),this.playerInterface_.onError(h))})))),b?g.clearingBuffer?g.waitingToFlushBuffer=!0:g.performingUpdate?(g.waitingToClearBuffer=!0,g.clearBufferSafeMargin=c,g.waitingToFlushBuffer=!0):(this.cancelUpdate_(g),this.clearBuffer_(g,!0,c).catch(h=>{this.playerInterface_&&(goog.asserts.assert(h instanceof shaka.util.Error,
"Wrong error type!"),this.playerInterface_.onError(h))})):g.performingUpdate||g.updateTimer||this.scheduleUpdate_(g,0),this.makeAbortDecision_(g).catch(h=>{this.playerInterface_&&(goog.asserts.assert(h instanceof shaka.util.Error,"Wrong error type!"),this.playerInterface_.onError(h))})):(b=shaka.media.StreamingEngine.logPrefix_(g),shaka.log.debug("switch: Stream "+b+" already active")))):this.loadNewTextStream_(a)}async makeAbortDecision_(a){if(a.operation){var b=a.stream,c=a.operation;b.segmentIndex||
await b.createSegmentIndex();var d=b.dependencyStream;d&&!d.segmentIndex&&await d.createSegmentIndex();a.operation==c&&a.stream==b&&(goog.asserts.assert(a.stream.segmentIndex,"Segment index should exist by now!"),this.shouldAbortCurrentRequest_(a)&&(shaka.log.info("Aborting current segment request."),a.operation.abort()))}}shouldAbortCurrentRequest_(a){goog.asserts.assert(a.operation,"Abort logic requires an ongoing operation!");goog.asserts.assert(a.stream&&a.stream.segmentIndex,"Abort logic requires a segment index");
const b=this.playerInterface_.getPresentationTime(),c=this.playerInterface_.mediaSourceEngine.bufferEnd(a.type);var d=this.getTimeNeeded_(a,b);d=a.stream.segmentIndex.find(d);var e=d==null?null:a.stream.segmentIndex.get(d);d=e?e.getSize():null;e&&!d&&(d=(e.getEndTime()-e.getStartTime())*(a.stream.bandwidth||this.currentVariant_.bandwidth)/8);if(!d)return!0;(e=e.initSegmentReference)&&(d+=e.getSize()||0);e=this.playerInterface_.getBandwidthEstimate();return d*8/e<(c||0)-b-this.config_.rebufferingGoal||
a.operation.getBytesRemaining()>d?!0:!1}seeked(){if(this.playerInterface_){var a=this.playerInterface_.getPresentationTime(),b=shaka.util.ManifestParserUtils.ContentType,c=e=>this.playerInterface_.mediaSourceEngine.isBuffered(e,a),d=!1;for(const e of this.mediaStates_.keys()){const f=this.mediaStates_.get(e),g=shaka.media.StreamingEngine.logPrefix_(f);if(!this.crossBoundarySeek_&&!c(e)){this.lastMediaSourceReset_=0;f.segmentPrefetch&&f.segmentPrefetch.resetPosition();if(f.type===b.AUDIO)for(const h of this.audioPrefetchMap_.values())h.resetPosition();
f.segmentIterator=null;if(this.playerInterface_.mediaSourceEngine.bufferEnd(e)!=null||f.performingUpdate)this.forceClearBuffer_(f),d=!0;f.operation&&(f.operation.abort(),shaka.log.debug(g,"Aborting operation due to seek"),f.operation=null);e===b.TEXT&&this.playerInterface_.mediaSourceEngine.resetCaptionParser();f.seeked=!0}!this.crossBoundarySeek_||f.clearingBuffer||f.performingUpdate||f.updateTimer||this.scheduleUpdate_(f,0)}this.shouldUseCrossBoundaryLogic_()&&this.forwardTimeForCrossBoundary_();
d||shaka.log.debug("(all): seeked: buffered seek: presentationTime="+a)}}forceClearBuffer_(a){const b=shaka.media.StreamingEngine.logPrefix_(a);a.clearingBuffer?shaka.log.debug(b,"clear: already clearing the buffer"):a.waitingToClearBuffer?shaka.log.debug(b,"clear: already waiting"):a.performingUpdate?(shaka.log.debug(b,"clear: currently updating"),a.waitingToClearBuffer=!0,a.clearBufferSafeMargin=0):this.playerInterface_.mediaSourceEngine.bufferStart(a.type)==null?(shaka.log.debug(b,"clear: nothing buffered"),
a.updateTimer==null&&this.scheduleUpdate_(a,0)):(shaka.log.debug(b,"clear: handling right now"),this.cancelUpdate_(a),this.clearBuffer_(a,!1,0).catch(c=>{this.playerInterface_&&(goog.asserts.assert(c instanceof shaka.util.Error,"Wrong error type!"),this.playerInterface_.onError(c))}))}async initStreams_(a){goog.asserts.assert(this.config_,"StreamingEngine configure() must be called before init()!");if(!this.currentVariant_)throw shaka.log.error("init: no Streams chosen"),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.STREAMING,shaka.util.Error.Code.STREAMING_ENGINE_STARTUP_INVALID_STATE);const b=this.getStreamsByType_(!0);await this.playerInterface_.mediaSourceEngine.init(b,this.manifest_.sequenceMode,this.manifest_.type,this.manifest_.ignoreManifestTimestampsInSegmentsMode);this.destroyer_.ensureNotDestroyed();this.updateDuration();for(const d of b.keys()){var c=b.get(d);if(!this.mediaStates_.has(d)){const e=this.createMediaState_(c);a.has(c.id)&&(c=a.get(c.id),c.replaceFetchDispatcher((f,
g,h)=>this.dispatchFetch_(f,g,h)),e.segmentPrefetch=c);this.mediaStates_.set(d,e);this.scheduleUpdate_(e,0)}}this.setupCrossBoundaryListeners_()}createMediaState_(a){const b={stream:a,type:a.type,segmentIterator:null,segmentPrefetch:this.createSegmentPrefetch_(a),lastSegmentReference:null,lastInitSegmentReference:null,lastTimestampOffset:null,lastAppendWindowStart:null,lastAppendWindowEnd:null,lastCodecs:null,lastMimeType:null,restoreStreamAfterTrickPlay:null,endOfStream:!1,performingUpdate:!1,updateTimer:null,
waitingToClearBuffer:!1,clearBufferSafeMargin:0,waitingToFlushBuffer:!1,clearingBuffer:!1,seeked:!0,adaptation:!1,recovering:!1,hasError:!1,operation:null,dependencyMediaState:null};a.dependencyStream&&(b.dependencyMediaState=this.createMediaState_(a.dependencyStream));return b}createSegmentPrefetch_(a){var b=shaka.util.ManifestParserUtils.ContentType;if(a.type===b.VIDEO&&this.config_.disableVideoPrefetch||a.type===b.AUDIO&&this.config_.disableAudioPrefetch)return null;var c=shaka.util.MimeUtils;
const d=c.CEA608_CLOSED_CAPTION_MIMETYPE;c=c.CEA708_CLOSED_CAPTION_MIMETYPE;return a.type===b.TEXT&&(a.mimeType==d||a.mimeType==c)||a.type===b.TEXT&&this.config_.disableTextPrefetch?null:this.audioPrefetchMap_.has(a)?this.audioPrefetchMap_.get(a):(b=(b=this.mediaStates_.get(a.type))&&b.segmentPrefetch)&&a===b.getStream()?b:this.config_.segmentPrefetchLimit>0?(b=this.playerInterface_.getPlaybackRate()<0,new shaka.media.SegmentPrefetch(this.config_.segmentPrefetchLimit,a,(e,f,g)=>this.dispatchFetch_(e,
f,g),b,this.playerInterface_.shouldPrefetchNextSegment)):null}updatePrefetchMapForAudio_(){const a=this.config_.segmentPrefetchLimit,b=this.config_.prefetchAudioLanguages,c=shaka.util.LanguageUtils;for(const e of this.manifest_.variants){if(!e.audio)continue;if(this.audioPrefetchMap_.has(e.audio)){var d=this.audioPrefetchMap_.get(e.audio);d.resetLimit(a);if(!(a>0&&b.some(f=>c.areLanguageCompatible(e.audio.language,f)))){const f=this.mediaStates_.get(e.audio.type);d!==(f&&f.segmentPrefetch)&&d.clearAll();
this.audioPrefetchMap_.delete(e.audio)}continue}if(a<=0)continue;if(!b.some(f=>c.areLanguageCompatible(e.audio.language,f)))continue;if(d=this.createSegmentPrefetch_(e.audio))e.audio.segmentIndex||e.audio.createSegmentIndex(),this.audioPrefetchMap_.set(e.audio,d)}}updateDuration(){const a=shaka.media.Capabilities.isInfiniteLiveStreamDurationSupported(),b=this.manifest_.presentationTimeline.getDuration();b<Infinity?(a&&(this.updateLiveSeekableRangeTimer_&&this.updateLiveSeekableRangeTimer_.stop(),
this.playerInterface_.mediaSourceEngine.clearLiveSeekableRange()),this.playerInterface_.mediaSourceEngine.setDuration(b)):a?(this.updateLiveSeekableRangeTimer_&&this.updateLiveSeekableRangeTimer_.tickEvery(.5),this.playerInterface_.mediaSourceEngine.setDuration(Infinity)):this.playerInterface_.mediaSourceEngine.setDuration(4294967296)}async onUpdate_(a){this.destroyer_.ensureNotDestroyed();const b=shaka.util.ManifestParserUtils.ContentType;var c=shaka.media.StreamingEngine.logPrefix_(a);goog.asserts.assert(!a.performingUpdate&&
a.updateTimer!=null,c+" unexpected call to onUpdate_()");if(!a.performingUpdate&&a.updateTimer!=null&&(goog.asserts.assert(!a.clearingBuffer,c+" onUpdate_() should not be called when clearing the buffer"),!a.clearingBuffer))if(a.updateTimer=null,a.waitingToClearBuffer)shaka.log.debug(c,"skipping update and clearing the buffer"),await this.clearBuffer_(a,a.waitingToFlushBuffer,a.clearBufferSafeMargin);else{this.handleDeferredCloseSegmentIndexes_(a);if(!a.stream.segmentIndex){var d=a.stream;try{await a.stream.createSegmentIndex()}catch(e){await this.handleStreamingError_(a,
e);return}if(d!=a.stream){d.closeSegmentIndex&&(goog.asserts.assert(!a.stream.segmentIndex,"mediaState.stream should not have segmentIndex yet."),d.closeSegmentIndex());a.performingUpdate||a.updateTimer||this.scheduleUpdate_(a,0);return}}if(a.dependencyMediaState&&!a.dependencyMediaState.stream.segmentIndex)try{await a.dependencyMediaState.stream.createSegmentIndex()}catch(e){shaka.log.warning("Could not create segment index for dependency",e)}try{const e=this.update_(a);e!=null&&(this.scheduleUpdate_(a,
e),a.hasError=!1)}catch(e){await this.handleStreamingError_(a,e);return}a.type!==b.TEXT&&(d=[],a.stream&&!a.stream.isAudioMuxedInVideo&&d.push(a),(a=this.mediaStates_.get(a.type===b.AUDIO?b.VIDEO:b.AUDIO))&&a.stream&&!a.stream.isAudioMuxedInVideo&&d.push(a),this.startupComplete_&&d.every(e=>e.endOfStream)&&(shaka.log.v1(c,"calling endOfStream()..."),await this.playerInterface_.mediaSourceEngine.endOfStream(),this.destroyer_.ensureNotDestroyed(),c=this.playerInterface_.mediaSourceEngine.getDuration(),
c!=0&&c<this.manifest_.presentationTimeline.getDuration()&&this.manifest_.presentationTimeline.setDuration(c)))}}update_(a){goog.asserts.assert(this.manifest_,"manifest_ should not be null");goog.asserts.assert(this.config_,"config_ should not be null");var b=shaka.util.ManifestParserUtils.ContentType;if(shaka.media.StreamingEngine.isEmbeddedText_(a))return this.playerInterface_.mediaSourceEngine.setSelectedClosedCaptionId(a.stream.originalId||""),null;a.type==b.TEXT&&this.playerInterface_.mediaSourceEngine.clearSelectedClosedCaptionId();
if(a.stream.isAudioMuxedInVideo&&a.type==b.AUDIO)return null;if(a.type!=b.TEXT&&this.playerInterface_.mediaSourceEngine.closed())return this.resetMediaSource(!0),null;var c=this.config_.updateIntervalSeconds/Math.max(1,Math.abs(this.playerInterface_.getPlaybackRate()));if(!this.playerInterface_.mediaSourceEngine.isStreamingAllowed()&&a.type!=b.TEXT)return c/2;var d=shaka.media.StreamingEngine.logPrefix_(a);const e=this.playerInterface_.getPresentationTime();if(a.type===b.AUDIO)for(var f of this.audioPrefetchMap_.keys()){var g=
this.audioPrefetchMap_.get(f);g.evict(e,!0);g.prefetchSegmentsByTime(e)}f=this.getTimeNeeded_(a,e);shaka.log.v2(d,"timeNeeded="+f);var h=this.playerInterface_.mediaSourceEngine.bufferedAheadOf(a.type,e);shaka.log.v2(d,"update_:","presentationTime="+e,"bufferedAhead="+h);g=Math.max(1,Math.max(this.config_.rebufferingGoal,this.config_.bufferingGoal)*this.bufferingScale_);var k=this.manifest_.presentationTimeline.getDuration()-f,l=this.playerInterface_.mediaSourceEngine.bufferEnd(a.type);if(k<1E-6&&
l)return shaka.log.debug(d,"buffered to end of presentation"),a.endOfStream=!0,a.type==b.VIDEO&&((c=this.mediaStates_.get(b.TEXT))&&shaka.media.StreamingEngine.isEmbeddedText_(c)&&(c.endOfStream=!0),(c=this.mediaStates_.get(b.AUDIO))&&c.stream.isAudioMuxedInVideo&&(c.endOfStream=!0)),null;a.endOfStream=!1;if(h>=g)return shaka.log.v2(d,"buffering goal met"),c/2;h=!a.segmentIterator;b=this.getSegmentReferenceNeeded_(a,e,l);if(!b)return d=Infinity,(a=a.lastSegmentReference)&&(d=a.endTime-a.startTime),
Math.min(d/2,c);l=a.lastInitSegmentReference;k=b.initSegmentReference;l&&k&&shaka.media.InitSegmentReference.equal(k,l)&&(l.boundaryEnd=k.boundaryEnd);l=!1;h&&a.adaptation&&(l=!0,a.adaptation=!1);h=Infinity;for(var m of this.mediaStates_.values()){if(shaka.media.StreamingEngine.isEmbeddedText_(m)||m.stream.isAudioMuxedInVideo)continue;if(m.segmentIterator&&!m.segmentIterator.current())continue;k=this.getTimeNeeded_(m,e);h=Math.min(h,k)}m=this.manifest_.presentationTimeline.getMaxSegmentDuration()*
shaka.media.StreamingEngine.MAX_RUN_AHEAD_SEGMENTS_;if(f>=h+m)return shaka.log.v2(d,"waiting for other streams to buffer"),c;a.segmentPrefetch&&a.segmentIterator&&!this.audioPrefetchMap_.has(a.stream)&&(a.segmentPrefetch.evict(b.startTime+.001),a.segmentPrefetch.prefetchSegmentsByTime(b.startTime).catch(()=>{}));if(this.shouldUseCrossBoundaryLogic_()&&this.discardReferenceByBoundary_(a,b))return null;this.fetchAndAppend_(a,e,b,l).catch(()=>{});a.dependencyMediaState&&this.fetchAndAppendDependency_(a.dependencyMediaState,
e,g);return null}getTimeNeeded_(a,b){return a.lastSegmentReference?a.lastSegmentReference.endTime:b}getSegmentReferenceNeeded_(a,b,c){var d=shaka.media.StreamingEngine.logPrefix_(a);goog.asserts.assert(a.stream.segmentIndex,"segment index should have been generated already");if(a.segmentIterator)return(d=a.segmentIterator.current())&&a.lastSegmentReference&&(b=shaka.util.NumberUtils,c=a.lastSegmentReference.endTime,b.isFloatEqual(a.lastSegmentReference.startTime,d.startTime,.002)&&b.isFloatEqual(c,
d.endTime,.002)&&(d=a.segmentIterator.next().value)),d;if(a.lastSegmentReference||c)return b=a.lastSegmentReference?a.lastSegmentReference.endTime:c,goog.asserts.assert(b!=null,"Should have a time to search"),shaka.log.v1(d,"looking up segment from new stream endTime:",b),c=this.playerInterface_.getPlaybackRate()<0,a.stream.segmentIndex&&(a.segmentIterator=a.stream.segmentIndex.getIteratorForTime(b,!1,c)),a=a.segmentIterator&&a.segmentIterator.next().value,a==null&&shaka.log.warning(d,"cannot find segment",
"endTime:",b),a;c=this.manifest_.sequenceMode||this.shouldUseCrossBoundaryLogic_()?0:this.config_.inaccurateManifestTolerance;let e=Math.max(b-c,0);var f=this.playerInterface_.mediaSourceEngine.getDuration(),g=shaka.media.StreamingEngine.LOOKUP_TIME_DURATION_THRESHOLD_;Math.abs(e-f)<g&&(c=g,e=Math.max(b-c,0));shaka.log.v1(d,"looking up segment","lookupTime:",e,"presentationTime:",b);f=this.playerInterface_.getPlaybackRate()<0;g=null;c&&(a.stream.segmentIndex&&(a.segmentIterator=a.stream.segmentIndex.getIteratorForTime(e,
!1,f)),g=a.segmentIterator&&a.segmentIterator.next().value);g||(a.stream.segmentIndex&&(a.segmentIterator=a.stream.segmentIndex.getIteratorForTime(b,!1,f)),g=a.segmentIterator&&a.segmentIterator.next().value);for(;g?.getStatus()===shaka.media.SegmentReference.Status.MISSING;)g=a.segmentIterator?.next().value??null;g==null&&shaka.log.warning(d,"cannot find segment","lookupTime:",e,"presentationTime:",b);return g}async fetchAndAppend_(a,b,c,d){const e=shaka.util.ManifestParserUtils.ContentType,f=shaka.media.StreamingEngine.logPrefix_(a);
shaka.log.v1(f,"fetchAndAppend_:","presentationTime="+b,"reference.startTime="+c.startTime,"reference.endTime="+c.endTime);const g=a.stream;var h=a.segmentIterator;a.performingUpdate=!0;try{if(c.getStatus()==shaka.media.SegmentReference.Status.MISSING)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.SEGMENT_MISSING);await this.initSourceBuffer_(a,c,d);this.destroyer_.ensureNotDestroyed();if(!this.fatalError_){shaka.log.v2(f,"fetching segment");
var k=g.mimeType=="video/mp4"||g.mimeType=="audio/mp4",l=window.ReadableStream,m=this.config_.lowLatencyMode&&this.manifest_.isLowLatency;if(m&&l&&k&&(this.manifest_.type!=shaka.media.ManifestParser.HLS||c.hasByterangeOptimization())){let p=new Uint8Array(0),r=!1,t=!1,u;const v=await this.fetch_(a,c,async x=>{if(!r&&(t=!0,this.destroyer_.ensureNotDestroyed(),!this.fatalError_))try{p=shaka.util.Uint8ArrayUtils.concat(p,x);let y=!1,A=0;(new shaka.util.Mp4Parser).box("mdat",w=>{A=w.size+w.start;y=!0}).parse(p,
!1,!0);if(y){const w=p.subarray(0,A);p=p.subarray(A);await this.append_(a,b,g,c,w,!0,d);a.segmentPrefetch&&a.segmentIterator&&a.segmentPrefetch.prefetchSegmentsByTime(c.startTime,!0)}}catch(y){u=y}});if(u)throw u;if(!t){r=!0;this.destroyer_.ensureNotDestroyed();if(this.fatalError_)return;if(a.waitingToClearBuffer){shaka.log.info(f,"waitingToClearBuffer, skip append");a.performingUpdate=!1;this.scheduleUpdate_(a,0);return}await this.append_(a,b,g,c,v,!1,d)}a.segmentPrefetch&&a.segmentIterator&&a.segmentPrefetch.prefetchSegmentsByTime(c.startTime,
!0)}else{m&&!l&&shaka.log.warning("Low latency streaming mode is enabled, but ReadableStream is not supported by the browser.");const p=await this.fetch_(a,c);this.destroyer_.ensureNotDestroyed();if(this.fatalError_)return;this.destroyer_.ensureNotDestroyed();if(a.waitingToClearBuffer){shaka.log.info(f,"waitingToClearBuffer, skip append");a.performingUpdate=!1;this.scheduleUpdate_(a,0);return}await this.append_(a,b,g,c,p,!1,d)}this.destroyer_.ensureNotDestroyed();if(!this.fatalError_){a.lastSegmentReference=
c;var n=h.next().value;shaka.log.v2(f,"advancing to next segment",n);a.performingUpdate=!1;a.recovering=!1;var q=this.playerInterface_.mediaSourceEngine.getBufferedInfo()[a.type];shaka.log.v1(f,"finished fetch and append",JSON.stringify(q));if(!a.waitingToClearBuffer)if(h=null,a.type===e.VIDEO?h=this.mediaStates_.get(e.AUDIO):a.type===e.AUDIO&&(h=this.mediaStates_.get(e.VIDEO)),h&&h.type==e.AUDIO)this.playerInterface_.onSegmentAppended(c,a.stream,h.stream.isAudioMuxedInVideo,!1);else this.playerInterface_.onSegmentAppended(c,
a.stream,a.stream.codecs.includes(","),!1);this.cancelUpdate_(a);this.scheduleUpdate_(a,0)}}}catch(p){this.destroyer_.ensureNotDestroyed(p),this.fatalError_||(goog.asserts.assert(p instanceof shaka.util.Error,"Should only receive a Shaka error"),a.performingUpdate=!1,p.code==shaka.util.Error.Code.OPERATION_ABORTED?(a.performingUpdate=!1,this.cancelUpdate_(a),this.scheduleUpdate_(a,0)):a.type==e.TEXT&&this.config_.ignoreTextStreamFailures?(p.code==shaka.util.Error.Code.BAD_HTTP_STATUS?shaka.log.warning(f,
"Text stream failed to download. Proceeding without it."):shaka.log.warning(f,"Text stream failed to parse. Proceeding without it."),this.mediaStates_.delete(e.TEXT)):p.code==shaka.util.Error.Code.QUOTA_EXCEEDED_ERROR?await this.handleQuotaExceeded_(a,p):(shaka.log.error(f,"failed fetch and append: code="+p.code),a.hasError=!0,p.category==shaka.util.Error.Category.NETWORK&&a.segmentPrefetch&&a.segmentPrefetch.removeReference(c),p.severity=shaka.util.Error.Severity.CRITICAL,await this.handleStreamingError_(a,
p)))}}async fetchAndAppendDependency_(a,b,c){var d=shaka.util.ManifestParserUtils.ContentType,e=a.stream,f=e.segmentIndex;for(b=(f=f&&f.getIteratorForTime(b))&&f.next().value;b&&this.requestedDependencySegments_.includes(b.startTime);)b=f&&f.next().value;if(b){if((f=b.initSegmentReference)&&!shaka.media.InitSegmentReference.equal(f,a.lastInitSegmentReference)){a.lastInitSegmentReference=f;try{const g=await this.fetch_(a,f);if(!this.playerInterface_)return;this.playerInterface_.mediaSourceEngine.appendDependency(g,
0,e);this.requestedDependencySegments_=[]}catch(g){throw a.lastInitSegmentReference=null,g;}}if(!a.lastSegmentReference||a.lastSegmentReference!=b){a.lastSegmentReference=b;try{const g=await this.fetch_(a,b);if(!this.playerInterface_)return;this.playerInterface_.mediaSourceEngine.appendDependency(g,0,e);this.requestedDependencySegments_.push(b.startTime)}catch(g){throw a.lastSegmentReference=null,g;}if(this.playerInterface_){if(!a.waitingToClearBuffer)if(e=null,a.type===d.VIDEO?e=this.mediaStates_.get(d.AUDIO):
a.type===d.AUDIO&&(e=this.mediaStates_.get(d.VIDEO)),e&&e.type==d.AUDIO)this.playerInterface_.onSegmentAppended(b,a.stream,e.stream.isAudioMuxedInVideo,!0);else this.playerInterface_.onSegmentAppended(b,a.stream,a.stream.codecs.includes(","),!0);d=Math.max(0,...this.requestedDependencySegments_);this.playerInterface_.getPresentationTime()+c>d&&await this.fetchAndAppendDependency_(a,b.startTime,c)}}}}retry(a){if(this.destroyer_.destroyed())return shaka.log.error("Unable to retry after StreamingEngine is destroyed!"),
!1;if(this.fatalError_)return shaka.log.error("Unable to retry after StreamingEngine encountered a fatal error!"),!1;for(const b of this.mediaStates_.values()){const c=shaka.media.StreamingEngine.logPrefix_(b);!b.hasError||b.performingUpdate||b.updateTimer||(shaka.log.info(c,"Retrying after failure..."),b.hasError=!1,this.scheduleUpdate_(b,a))}return!0}async handleQuotaExceeded_(a,b){const c=shaka.media.StreamingEngine.logPrefix_(a);var d=!1;for(const e of this.mediaStates_.values())if(e!=a&&e.recovering){d=
!0;break}if(d)shaka.log.debug(c,"MediaSource threw QuotaExceededError:","waiting for another stream to recover...");else{if(this.config_.avoidEvictionOnQuotaExceededError){(d=this.getDisabledTime_(b))&&shaka.log.debug(c,"Disabling stream due to quota",b);if(this.playerInterface_.disableStream(a.stream,d))return;this.scheduleUpdate_(a,4);return}d=Math.round(100*this.bufferingScale_);if(d>20)this.bufferingScale_-=.2;else if(d>4)this.bufferingScale_-=.04;else{(d=this.getDisabledTime_(b))&&shaka.log.debug(c,
"Disabling stream due to quota",b);this.playerInterface_.disableStream(a.stream,d)?(this.bufferingScale_=1,b=this.playerInterface_.getPresentationTime(),await this.evict_(a,b)):(shaka.log.error(c,"MediaSource threw QuotaExceededError too many times"),this.fatalError_=a.hasError=!0,this.playerInterface_.onError(b));return}shaka.log.warning(c,"MediaSource threw QuotaExceededError:","reducing buffering goals by "+(100-Math.round(100*this.bufferingScale_))+"%");a.recovering=!0;b=this.playerInterface_.getPresentationTime();
await this.evict_(a,b)}this.scheduleUpdate_(a,4)}async initSourceBuffer_(a,b,c){const d=shaka.util.ManifestParserUtils.ContentType;var e=shaka.util.MimeUtils,f=shaka.media.StreamingEngine;const g=f.logPrefix_(a);var h=a.lastSegmentReference==null;const k=[];var l=Math.max(0,Math.max(b.appendWindowStart,this.playRangeStart_)-f.APPEND_WINDOW_START_FUDGE_);f=Math.min(b.appendWindowEnd,this.playRangeEnd_)+f.APPEND_WINDOW_END_FUDGE_;goog.asserts.assert(b.startTime<=f,g+" segment should start before append window end");
var m=b.codecs||a.stream.codecs;const n=e.getCodecBase(m);e=e.getBasicType(b.mimeType||a.stream.mimeType);const q=b.timestampOffset;if(q!=a.lastTimestampOffset||l!=a.lastAppendWindowStart||f!=a.lastAppendWindowEnd||n!=a.lastCodecs||e!=a.lastMimeType)shaka.log.v1(g,"setting timestamp offset to "+q),shaka.log.v1(g,"setting append window start to "+l),shaka.log.v1(g,"setting append window end to "+f),a.lastCodecs&&a.lastMimeType&&this.playerInterface_.mediaSourceEngine.isResetMediaSourceNecessary(a.type,
e,m,this.getStreamsByType_())&&(m=null,a.type===d.VIDEO?m=this.mediaStates_.get(d.AUDIO):a.type===d.AUDIO&&(m=this.mediaStates_.get(d.VIDEO)),m&&(await this.abortOperations_(m).catch(()=>{}),m.lastInitSegmentReference=null,m.lastAppendWindowStart=null,m.lastAppendWindowEnd=null,this.forceClearBuffer_(m))),await this.setProperties_(a,q,l,f,b,n,e);if(!shaka.media.InitSegmentReference.equal(b.initSegmentReference,a.lastInitSegmentReference)&&(a.lastInitSegmentReference=b.initSegmentReference,b.isIndependent()&&
b.initSegmentReference)){shaka.log.v1(g,"fetching init segment");const p=this.fetch_(a,b.initSegmentReference);l=b.startTime;h&&(h=this.playerInterface_.mediaSourceEngine.bufferEnd(a.type),h!=null&&(l=h));this.playerInterface_.onInitSegmentAppended(l,b.initSegmentReference);k.push((async()=>{try{const r=await p;this.destroyer_.ensureNotDestroyed();let t=null;const u=new Map,v={projection:null,hfov:null};if(a.stream){const C=a.stream.videoLayout;if(C){const F=C.split("/");F.includes("PROJ-RECT")?v.projection=
"rect":F.includes("PROJ-EQUI")?v.projection="equi":F.includes("PROJ-HEQU")?v.projection="hequ":F.includes("PROJ-PRIM")?v.projection="prim":F.includes("PROJ-AIV")&&(v.projection="hequ")}}const x=new shaka.util.Mp4Parser,y=shaka.util.Mp4Parser,A=shaka.util.Mp4BoxParsers;x.box("moov",y.children).box("trak",y.children).box("mdia",y.children).fullBox("mdhd",C=>{goog.asserts.assert(C.version!=null,"MDHD is a full box and should have a valid version.");t=A.parseMDHD(C.reader,C.version).timescale}).fullBox("hdlr",
C=>{goog.asserts.assert(C.version!=null,"HDLR is a full box and should have a valid version.");switch(A.parseHDLR(C.reader).handlerType){case "soun":u.set(d.AUDIO,t);break;case "vide":u.set(d.VIDEO,t)}t=null});a.type!==d.VIDEO||v.projection||x.box("minf",y.children).box("stbl",y.children).fullBox("stsd",y.sampleDescription).boxes("encv avc1 avc3 hev1 hvc1 dvav dva1 dvh1 dvhe dvc1 dvi1".split(" "),y.visualSampleEntry).box("vexu",y.children).box("proj",y.children).fullBox("prji",C=>{C=A.parsePRJI(C.reader);
v.projection=C.projection}).box("hfov",C=>{C=A.parseHFOV(C.reader);v.hfov=C.hfov});x.parse(r,!0,!0);a.type===d.VIDEO&&this.updateSpatialVideoInfo_(v);u.has(a.type)?b.initSegmentReference.timescale=u.get(a.type):t!=null&&(b.initSegmentReference.timescale=t);const w=a.stream.segmentIndex;let z;w instanceof shaka.media.MetaSegmentIndex&&(z=w.getTimelineForTime(b.startTime));shaka.log.v1(g,"appending init segment");const B=a.stream.closedCaptions&&a.stream.closedCaptions.size>0;await this.playerInterface_.beforeAppendSegment(a.type,
r);await this.playerInterface_.mediaSourceEngine.appendBuffer(a.type,r,null,a.stream,B,a.seeked,c,!1,!1,z)}catch(r){throw a.lastInitSegmentReference=null,r;}})())}b.discontinuitySequence!=(a.lastSegmentReference?a.lastSegmentReference.discontinuitySequence:-1)&&k.push(this.playerInterface_.mediaSourceEngine.resync(a.type,b.startTime));await Promise.all(k)}async setProperties_(a,b,c,d,e,f,g){const h=shaka.util.ManifestParserUtils.ContentType,k=this.getStreamsByType_();try{a.lastAppendWindowStart=c;
a.lastAppendWindowEnd=d;f&&(a.lastCodecs=f);g&&(a.lastMimeType=g);a.lastTimestampOffset=b;const l=this.manifest_.sequenceMode||this.manifest_.type==shaka.media.ManifestParser.HLS;f=null;a.type===h.VIDEO?f=this.mediaStates_.get(h.AUDIO):a.type===h.AUDIO&&(f=this.mediaStates_.get(h.VIDEO));f&&f.stream&&f.stream.isAudioMuxedInVideo&&await this.playerInterface_.mediaSourceEngine.setStreamProperties(f.type,b,c,d,l,f.stream.mimeType,f.stream.codecs,k);await this.playerInterface_.mediaSourceEngine.setStreamProperties(a.type,
b,c,d,l,e.mimeType||a.stream.mimeType,e.codecs||a.stream.codecs,k)}catch(l){throw a.lastAppendWindowStart=null,a.lastAppendWindowEnd=null,a.lastCodecs=null,a.lastMimeType=null,a.lastTimestampOffset=null,l;}}async append_(a,b,c,d,e,f=!1,g=!1){const h=shaka.media.StreamingEngine.logPrefix_(a),k=c.closedCaptions&&c.closedCaptions.size>0;if(this.config_.shouldFixTimestampOffset){const l=c.mimeType=="video/mp4"||c.mimeType=="audio/mp4";let m=null;d.initSegmentReference&&(m=d.initSegmentReference.timescale);
l&&m&&c.type===shaka.util.ManifestParserUtils.ContentType.VIDEO&&this.manifest_.type==shaka.media.ManifestParser.DASH&&(new shaka.util.Mp4Parser).box("moof",shaka.util.Mp4Parser.children).box("traf",shaka.util.Mp4Parser.children).fullBox("tfdt",async n=>{goog.asserts.assert(n.version!=null,"TFDT is a full box and should have a valid version.");if(n=shaka.util.Mp4BoxParsers.parseTFDTInaccurate(n.reader,n.version).baseMediaDecodeTime)if(goog.asserts.assert(typeof m=="number","Should be an number!"),
n=-n/m,(Number(a.lastTimestampOffset)||0)<n){const q=a.lastAppendWindowStart,p=a.lastAppendWindowEnd;goog.asserts.assert(typeof q=="number","Should be an number!");goog.asserts.assert(typeof p=="number","Should be an number!");await this.setProperties_(a,n,q,p,d)}}).parse(e,!1,f)}await this.evict_(a,b);this.destroyer_.ensureNotDestroyed();b=a.seeked;a.seeked=!1;await this.playerInterface_.beforeAppendSegment(a.type,e);await this.playerInterface_.mediaSourceEngine.appendBuffer(a.type,e,d,c,k,b,g,f);
this.destroyer_.ensureNotDestroyed();shaka.log.v2(h,"appended media segment")}async evict_(a,b){this.lastTextMediaStateBeforeUnload_==a&&(this.lastTextMediaStateBeforeUnload_=null);var c=a.stream.segmentIndex;let d;c instanceof shaka.media.MetaSegmentIndex&&(c.evict(this.manifest_.presentationTimeline.getSegmentAvailabilityStart()),d=[],c.forEachIndex(n=>{d.push(n.continuityTimeline())}));c=shaka.media.StreamingEngine.logPrefix_(a);shaka.log.v2(c,"checking buffer length");const e=Math.max(this.config_.bufferBehind*
this.bufferingScale_,this.manifest_.presentationTimeline.getMaxSegmentDuration()),f=this.playerInterface_.mediaSourceEngine.bufferStart(a.type);if(f==null)shaka.log.v2(c,"buffer behind okay because nothing buffered:","presentationTime="+b,"bufferBehind="+e);else{var g=b-f,h=this.config_.evictionGoal,k=this.manifest_.presentationTimeline.getSeekRangeStart(),l=this.manifest_.presentationTimeline.getSeekRangeEnd(),m=g-e;l-k>h&&(m=Math.max(g-e,k-h-f));m<=h?shaka.log.v2(c,"buffer behind okay:","presentationTime="+
b,"bufferedBehind="+g,"bufferBehind="+e,"evictionGoal="+h,"underflow="+Math.abs(m)):(shaka.log.v1(c,"buffer behind too large:","presentationTime="+b,"bufferedBehind="+g,"bufferBehind="+e,"evictionGoal="+h,"overflow="+m),await this.playerInterface_.mediaSourceEngine.remove(a.type,f,f+m,d),this.destroyer_.ensureNotDestroyed(),shaka.log.v1(c,"evicted "+m+" seconds"),this.lastTextMediaStateBeforeUnload_&&(await this.evict_(this.lastTextMediaStateBeforeUnload_,b),this.destroyer_.ensureNotDestroyed()))}}static isEmbeddedText_(a){var b=
shaka.util.MimeUtils;const c=b.CEA608_CLOSED_CAPTION_MIMETYPE;b=b.CEA708_CLOSED_CAPTION_MIMETYPE;return a&&a.type==shaka.util.ManifestParserUtils.ContentType.TEXT&&(a.stream.mimeType==c||a.stream.mimeType==b)}async fetch_(a,b,c){var d=b.getSegmentData();if(d)return d;d=null;a.segmentPrefetch&&(d=a.segmentPrefetch.getPrefetchedSegment(b,c));d||=this.dispatchFetch_(b,a.stream,c);c=0;a.segmentIterator&&(c=a.segmentIterator.currentPosition());a.operation=d;d=await d.promise;a.operation=null;a=d.data;
b.aesKey&&(a=await shaka.media.SegmentUtils.aesDecrypt(a,b.aesKey,c));return a}dispatchFetch_(a,b,c,d){goog.asserts.assert(this.playerInterface_.netEngine,"Must have net engine");return shaka.media.StreamingEngine.dispatchFetch(a,b,c||null,this.config_.retryParameters,this.playerInterface_.netEngine)}static dispatchFetch(a,b,c,d,e,f=!1){const g=shaka.net.NetworkingEngine.RequestType.SEGMENT,h=a instanceof shaka.media.SegmentReference?a:void 0,k=h?shaka.net.NetworkingEngine.AdvancedRequestType.MEDIA_SEGMENT:
shaka.net.NetworkingEngine.AdvancedRequestType.INIT_SEGMENT;c=shaka.net.NetworkingUtils.createSegmentRequest(a.getUris(),a.startByte,a.endByte,d,c);c.contentType=b.type;shaka.log.v2("fetching: reference=",a);return e.request(g,c,{type:k,stream:b,segment:h,isPreload:f})}async clearBuffer_(a,b,c){const d=shaka.media.StreamingEngine.logPrefix_(a);goog.asserts.assert(!a.performingUpdate&&a.updateTimer==null,d+" unexpected call to clearBuffer_()");a.waitingToClearBuffer=!1;a.waitingToFlushBuffer=!1;a.clearBufferSafeMargin=
0;a.clearingBuffer=!0;a.lastSegmentReference=null;a.segmentIterator=null;shaka.log.debug(d,"clearing buffer");a.segmentPrefetch&&!this.audioPrefetchMap_.has(a.stream)&&a.segmentPrefetch.clearAll();if(c){b=this.playerInterface_.getPresentationTime();const e=this.playerInterface_.mediaSourceEngine.getDuration();await this.playerInterface_.mediaSourceEngine.remove(a.type,b+c,e)}else await this.playerInterface_.mediaSourceEngine.clear(a.type),this.destroyer_.ensureNotDestroyed(),b&&await this.playerInterface_.mediaSourceEngine.flush(a.type);
this.destroyer_.ensureNotDestroyed();shaka.log.debug(d,"cleared buffer");a.clearingBuffer=!1;a.endOfStream=!1;a.performingUpdate||a.updateTimer||this.scheduleUpdate_(a,0)}scheduleUpdate_(a,b){const c=shaka.media.StreamingEngine.logPrefix_(a),d=a.type;d!=shaka.util.ManifestParserUtils.ContentType.TEXT||this.mediaStates_.has(d)?(shaka.log.v2(c,"updating in "+b+" seconds"),goog.asserts.assert(a.updateTimer==null,c+" did not expect update to be scheduled"),a.updateTimer=(new shaka.util.Timer(async()=>
{try{await this.onUpdate_(a)}catch(e){if(this.playerInterface_)this.playerInterface_.onError(e)}})).tickAfter(b)):shaka.log.v1(c,"Text stream is unloaded. No update is needed.")}cancelUpdate_(a){a.updateTimer!=null&&(a.updateTimer.stop(),a.updateTimer=null)}async abortOperations_(a){a.operation&&await a.operation.abort()}async handleStreamingError_(a,b){var c=shaka.media.StreamingEngine.logPrefix_(a);if(b.code==shaka.util.Error.Code.STREAMING_NOT_ALLOWED)a.performingUpdate=!1,this.cancelUpdate_(a),
this.scheduleUpdate_(a,0);else{await this.failureCallbackBackoff_.attempt();this.destroyer_.ensureNotDestroyed();if(b.category===shaka.util.Error.Category.NETWORK&&b.code!=shaka.util.Error.Code.TIMEOUT){if(a.restoreStreamAfterTrickPlay){this.setTrickPlay(!1);return}var d=this.getDisabledTime_(b);d&&shaka.log.debug(c,"Disabling stream due to error",b);b.handled=this.playerInterface_.disableStream(a.stream,d);b.handled&&(b.severity=shaka.util.Error.Severity.RECOVERABLE)}if(!b.handled&&b.code==shaka.util.Error.Code.SEGMENT_MISSING){c=
this.playerInterface_.getPresentationTime();d=this.playerInterface_.mediaSourceEngine.bufferEnd(a.type);let e=this.getSegmentReferenceNeeded_(a,c,d);for(;e?.getStatus()===shaka.media.SegmentReference.Status.MISSING;)a.lastSegmentReference=e,e=this.getSegmentReferenceNeeded_(a,c,d);if(e){await this.playerInterface_.mediaSourceEngine.resync(a.type,e.startTime);a.performingUpdate=!1;a.hasError=!1;this.cancelUpdate_(a);this.scheduleUpdate_(a,0);return}}if(!b.handled||b.code!=shaka.util.Error.Code.SEGMENT_MISSING)this.playerInterface_.onError(b);
b.handled||this.config_.failureCallback(b)}}getDisabledTime_(a){return this.config_.maxDisabledTime===0&&a.code==shaka.util.Error.Code.SEGMENT_MISSING?1:this.config_.maxDisabledTime}async resetMediaSource(a=!1,b){b=Date.now()/1E3;var c=this.config_.minTimeBetweenRecoveries;if(!a&&(!this.config_.allowMediaSourceRecoveries||b-this.lastMediaSourceReset_<c))return!1;this.lastMediaSourceReset_=b;b=shaka.util.ManifestParserUtils.ContentType;if(a=this.mediaStates_.get(b.AUDIO))this.cancelUpdate_(a),a.operation&&
(a.operation.abort(),a.operation=null),a.lastInitSegmentReference=null,a.lastAppendWindowStart=null,a.lastAppendWindowEnd=null,a.lastInitSegmentReference=null,a.lastAppendWindowStart=null,a.lastAppendWindowEnd=null,a.performingUpdate=!1,a.waitingToClearBuffer=!1,a.clearBufferSafeMargin=0,a.waitingToFlushBuffer=!1,a.clearingBuffer=!1,a.segmentIterator&&a.segmentIterator.resetToLastIndependent();if(b=this.mediaStates_.get(b.VIDEO))this.cancelUpdate_(b),b.operation&&(b.operation.abort(),b.operation=
null),b.lastInitSegmentReference=null,b.lastAppendWindowStart=null,b.lastAppendWindowEnd=null,b.performingUpdate=!1,b.waitingToClearBuffer=!1,b.clearBufferSafeMargin=0,b.waitingToFlushBuffer=!1,b.clearingBuffer=!1,b.segmentIterator&&b.segmentIterator.resetToLastIndependent();c=this.playerInterface_.video.paused;await this.playerInterface_.mediaSourceEngine.reset(this.getStreamsByType_());!b||b.clearingBuffer||b.performingUpdate||b.updateTimer||this.scheduleUpdate_(b,0);!a||a.clearingBuffer||a.performingUpdate||
a.updateTimer||this.scheduleUpdate_(a,0);c||this.playerInterface_.video.play();return!0}updateSpatialVideoInfo_(a){if(this.spatialVideoInfo_.projection!=a.projection||this.spatialVideoInfo_.hfov!=a.hfov){var b=shaka.util.FakeEvent.EventName;if(a.projection!=null||a.hfov!=null){b=b.SpatialVideoInfoEvent;const c=(new Map).set("detail",a);b=new shaka.util.FakeEvent(b,c)}else b=new shaka.util.FakeEvent(b.NoSpatialVideoInfoEvent);b.cancelable=!0;this.playerInterface_.onEvent(b);this.spatialVideoInfo_=
a}}updateSegmentIteratorReverse_(){const a=this.playerInterface_.getPlaybackRate()<0;for(const b of this.mediaStates_.values())b.segmentIterator&&b.segmentIterator.setReverse(a),b.segmentPrefetch&&b.segmentPrefetch.setReverse(a);for(const b of this.audioPrefetchMap_.values())b.setReverse(a)}shouldUseCrossBoundaryLogic_(){if(this.config_.crossBoundaryStrategy!==shaka.config.CrossBoundaryStrategy.KEEP)return!0;const a=shaka.device.DeviceFactory.getDevice();if(!a.supportsSmoothCodecSwitching())for(var b of this.mediaStates_.keys()){var c=
this.mediaStates_.get(b);if(c.type===shaka.util.ManifestParserUtils.ContentType.TEXT)continue;if((c=c.stream)&&c.fullMimeTypes&&c.fullMimeTypes.size>1)return!0}else if(!a.supportsContainerChangeType())for(var d of this.mediaStates_.keys()){b=this.mediaStates_.get(d);if(b.type===shaka.util.ManifestParserUtils.ContentType.TEXT)continue;if((b=b.stream)&&b.fullMimeTypes&&b.fullMimeTypes.size>1){d=new Set;for(c of b.fullMimeTypes)d.add(shaka.util.MimeUtils.getContainerType(c));return d.size>1}}return!1}setupCrossBoundaryListeners_(){this.crossBoundaryEventManager_.removeAll();
this.shouldUseCrossBoundaryLogic_()&&(this.crossBoundaryEventManager_.listen(this.playerInterface_.video,"waiting",()=>this.forwardTimeForCrossBoundary_()),this.crossBoundaryEventManager_.listen(this.playerInterface_.video,"timeupdate",()=>this.forwardTimeForCrossBoundary_()))}forwardTimeForCrossBoundary_(){if(this.shouldUseCrossBoundaryLogic_()){this.crossBoundaryTimer_.stop();var a=this.playerInterface_.getPresentationTime(),b=shaka.util.ManifestParserUtils.ContentType;if((b=this.mediaStates_.get(b.VIDEO)||
this.mediaStates_.get(b.AUDIO))&&(b=b.lastInitSegmentReference)&&b.boundaryEnd!==null){var c=shaka.media.StreamingEngine.CROSS_BOUNDARY_END_THRESHOLD_;a=b.boundaryEnd-a;a<0||a>c||(this.boundaryTime_=b.boundaryEnd+shaka.media.StreamingEngine.APPEND_WINDOW_END_FUDGE_,this.crossBoundaryTimer_.tickAfter(a))}}}discardReferenceByBoundary_(a,b){const c=shaka.util.ManifestParserUtils.ContentType;if(a.type===c.TEXT)return!1;const d=a.lastInitSegmentReference;if(!d)return!1;var e=shaka.config.CrossBoundaryStrategy;
const f=shaka.media.StreamingEngine.logPrefix_(a),g=b.initSegmentReference;let h=d.boundaryEnd!==g.boundaryEnd;this.config_.crossBoundaryStrategy===e.RESET_TO_ENCRYPTED&&(d.encrypted||g.encrypted||(h=!1),d.encrypted&&(shaka.log.debug(f,"stream is encrypted, discard crossBoundaryStrategy"),this.config_.crossBoundaryStrategy=e.KEEP));this.config_.crossBoundaryStrategy===e.RESET_ON_ENCRYPTION_CHANGE&&d.encrypted==g.encrypted&&(h=!1);if(this.config_.crossBoundaryStrategy===e.KEEP&&d.mimeType&&g.mimeType){var k=
shaka.util.MimeUtils;e=k.getNormalizedCodec(k.getCodecs(d.mimeType));k=k.getNormalizedCodec(k.getCodecs(g.mimeType));d.mimeType==g.mimeType&&e==k&&(h=!1)}(this.mediaStates_.get(c.VIDEO)||this.mediaStates_.get(c.AUDIO))===a&&h&&(this.crossBoundarySeek_||a.seeked)&&(shaka.log.debug(f,"reset mediaSource","from=",a.lastInitSegmentReference,"to=",b.initSegmentReference),this.crossBoundarySeek_=!1,this.resetMediaSource(!0).then(()=>{const l=shaka.util.FakeEvent.EventName.BoundaryCrossed,m=(new Map).set("oldEncrypted",
d.encrypted).set("newEncrypted",g.encrypted);this.playerInterface_.onEvent(new shaka.util.FakeEvent(l,m))}));return h}getStreamsByType_(a=!1){const b=shaka.util.ManifestParserUtils.ContentType,c=f=>{if(f.fullMimeTypes&&f.fullMimeTypes.size>1&&this.mediaStates_.has(f.type)){var g=this.mediaStates_.get(f.type);const h=this.playerInterface_.mediaSourceEngine.bufferEnd(g.type),k=this.playerInterface_.getPresentationTime();(g=this.getSegmentReferenceNeeded_(g,k,h))&&g.codecs&&g.mimeType&&(f.codecs=g.codecs,
f.mimeType=g.mimeType)}},d=new Map;var e=this.currentVariant_.audio;e&&(c(e),d.set(b.AUDIO,e));if(e=this.currentVariant_.video)c(e),d.set(b.VIDEO,e);a&&this.currentTextStream_&&d.set(b.TEXT,this.currentTextStream_);return d}static logPrefix_(a){return"("+a.type+":"+a.stream.id+")"}};shaka.media.StreamingEngine.APPEND_WINDOW_START_FUDGE_=.1;shaka.media.StreamingEngine.APPEND_WINDOW_END_FUDGE_=.1;shaka.media.StreamingEngine.MAX_RUN_AHEAD_SEGMENTS_=1;
shaka.media.StreamingEngine.CROSS_BOUNDARY_END_THRESHOLD_=1;shaka.media.StreamingEngine.LOOKUP_TIME_DURATION_THRESHOLD_=1;shaka.util.ConfigUtils=class{static mergeConfigObjects(a,b,c,d,e){goog.asserts.assert(a,"Destination config must not be null!");const f=e in d,g=new Set(["__proto__","constructor","prototype"]);let h;h=f?c.constructor==Object&&Object.keys(d).length==0:c.constructor==Object&&Object.keys(c).length==0;const k=f||h;let l=!0;for(const n of Object.keys(b)){var m=e+"."+n;const q=f?d[e]:c[n];g.has(n)?(shaka.log.alwaysError("Invalid config, dangerous key "+m),l=!1):k||n in c?b[n]===void 0?q===void 0||k?delete a[n]:
a[n]=shaka.util.ObjectUtils.cloneObject(q):h?a[n]=b[n]:q.constructor==Object&&b[n]&&b[n].constructor==Object?(a[n]||(a[n]=shaka.util.ObjectUtils.cloneObject(q)),m=shaka.util.ConfigUtils.mergeConfigObjects(a[n],b[n],q,d,m),l=l&&m):typeof b[n]!=typeof q||b[n]==null||typeof b[n]!="function"&&b[n].constructor!=q.constructor?(shaka.log.alwaysError("Invalid config, wrong type for "+m),l=!1):typeof c[n]=="function"&&c[n].length!=b[n].length?(shaka.log.alwaysWarn("Unexpected number of arguments for "+m),
a[n]=b[n]):Array.isArray(a[n])?a[n]=b[n].slice():a[n]=b[n]:(shaka.log.alwaysError("Invalid config, unrecognized key "+m),l=!1)}return l}static convertToConfigObject(a,b){const c={};let d=c;for(var e=0,f=0;;){e=a.indexOf(".",e);if(e<0)break;if(e==0||a[e-1]!="\\")f=a.substring(f,e).replace(/\\\./g,"."),d[f]={},d=d[f],f=e+1;e+=1}d[a.substring(f).replace(/\\\./g,".")]=b;return c}static referenceParametersAndReturn(a,b){return a&&b}static getDifferenceFromConfigObjects(a,b){const c=f=>f&&typeof f==="object"&&
!Array.isArray(f),d=(f,g)=>Object.keys(f).reduce((h,k)=>{var l=f[k];if(g.hasOwnProperty(k))if(l instanceof HTMLElement&&g[k]instanceof HTMLElement)l.isEqualNode(g[k])||(h[k]=l);else if(c(l)&&c(g[k])){if(l=d(l,g[k]),Object.keys(l).length>0||!c(l))h[k]=l}else Array.isArray(l)&&Array.isArray(g[k])?shaka.util.ArrayUtils.hasSameElements(l,g[k])||(h[k]=l):Number.isNaN(l)&&Number.isNaN(g[k])||l!==g[k]&&(h[k]=l);else h[k]=l;return h},{});a=d(a,b);const e=f=>{for(const h of Object.keys(f))if(!(f[h]instanceof
HTMLElement))if(c(f[h])&&Object.keys(f[h]).length===0)delete f[h];else{var g=f[h];Array.isArray(g)&&g.length===0?delete f[h]:typeof f[h]=="function"?delete f[h]:c(f[h])&&(e(f[h]),Object.keys(f[h]).length===0&&delete f[h])}};e(a);return a}};goog.exportSymbol("shaka.util.ConfigUtils",shaka.util.ConfigUtils);goog.exportProperty(shaka.util.ConfigUtils,"getDifferenceFromConfigObjects",shaka.util.ConfigUtils.getDifferenceFromConfigObjects);
goog.exportProperty(shaka.util.ConfigUtils,"convertToConfigObject",shaka.util.ConfigUtils.convertToConfigObject);goog.exportProperty(shaka.util.ConfigUtils,"mergeConfigObjects",shaka.util.ConfigUtils.mergeConfigObjects);shaka.config.RepeatMode={OFF:0,ALL:1,SINGLE:2};goog.exportSymbol("shaka.config.RepeatMode",shaka.config.RepeatMode);shaka.drm.FairPlay=class{static async isFairPlaySupported(){const a={initDataTypes:["cenc","sinf","skd"],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42E01E"'}]};try{return await navigator.requestMediaKeySystemAccess("com.apple.fps",[a]),!0}catch(b){return!1}}static defaultGetContentId(a){a=shaka.util.StringUtils.fromBytesAutoDetect(a);return(new goog.Uri(a)).getDomain()}static defaultGetKeyId(a){a=(new goog.Uri(a)).getDomain().replace(/-/g,"").toLowerCase();return a.length===32&&/^[0-9a-f]+$/.test(a)?
a:null}static initDataTransform(a,b,c){if(!c||!c.byteLength)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.SERVER_CERTIFICATE_REQUIRED);b=typeof b=="string"?shaka.util.StringUtils.toUTF16(b,!0):b;a=shaka.util.StringUtils.fromBytesAutoDetect(a);a=shaka.util.StringUtils.toUTF16(a,!0);const d=new Uint8Array(12+a.byteLength+b.byteLength+c.byteLength);let e=0;const f=g=>{shaka.util.BufferUtils.toDataView(d).setUint32(e,g.byteLength,!0);
e+=4;d.set(shaka.util.BufferUtils.toUint8(g),e);e+=g.byteLength};f(a);f(b);f(c);goog.asserts.assert(e==d.length,"Inconsistent init data length");return d}static basicInitDataTransform_(a,b,c){if(b!=="skd")return a;b=c.serverCertificate;c=shaka.util.StringUtils.fromBytesAutoDetect(a).split("skd://").pop();return shaka.drm.FairPlay.initDataTransform(a,c,b)}static verimatrixInitDataTransform(a,b,c){return shaka.drm.FairPlay.basicInitDataTransform_(a,b,c)}static ezdrmInitDataTransform(a,b,c){if(b!=="skd")return a;
b=c.serverCertificate;c=shaka.util.StringUtils.fromBytesAutoDetect(a).split(";").pop();return shaka.drm.FairPlay.initDataTransform(a,c,b)}static conaxInitDataTransform(a,b,c){if(b!=="skd")return a;b=c.serverCertificate;c=shaka.util.StringUtils.fromBytesAutoDetect(a).split("skd://").pop().split("?").shift();c=window.atob(c);var d=new ArrayBuffer(c.length*2);d=shaka.util.BufferUtils.toUint16(d);for(let e=0,f=c.length;e<f;e++)d[e]=c.charCodeAt(e);return shaka.drm.FairPlay.initDataTransform(a,d,b)}static expressplayInitDataTransform(a,
b,c){return shaka.drm.FairPlay.basicInitDataTransform_(a,b,c)}static muxInitDataTransform(a,b,c){return shaka.drm.FairPlay.basicInitDataTransform_(a,b,c)}static verimatrixFairPlayRequest(a,b,c){a===shaka.net.NetworkingEngine.RequestType.LICENSE&&(a=b.drmInfo)&&shaka.drm.DrmUtils.isFairPlayKeySystem(a.keySystem)&&(a=shaka.util.BufferUtils.toUint8(b.body),a=shaka.util.Uint8ArrayUtils.toBase64(a),b.headers["Content-Type"]="application/x-www-form-urlencoded",b.body=shaka.util.StringUtils.toUTF8("spc="+
a))}static octetStreamFairPlayRequest_(a,b,c){a===shaka.net.NetworkingEngine.RequestType.LICENSE&&(a=b.drmInfo)&&shaka.drm.DrmUtils.isFairPlayKeySystem(a.keySystem)&&(b.headers["Content-Type"]="application/octet-stream")}static ezdrmFairPlayRequest(a,b,c){shaka.drm.FairPlay.octetStreamFairPlayRequest_(a,b)}static conaxFairPlayRequest(a,b,c){shaka.drm.FairPlay.octetStreamFairPlayRequest_(a,b)}static expressplayFairPlayRequest(a,b,c){a===shaka.net.NetworkingEngine.RequestType.LICENSE&&(c=b.drmInfo)&&
shaka.drm.DrmUtils.isFairPlayKeySystem(c.keySystem)&&shaka.drm.FairPlay.octetStreamFairPlayRequest_(a,b)}static muxFairPlayRequest(a,b,c){shaka.drm.FairPlay.octetStreamFairPlayRequest_(a,b)}static commonFairPlayResponse(a,b,c){if(a===shaka.net.NetworkingEngine.RequestType.LICENSE&&(a=b.originalRequest.drmInfo)&&shaka.drm.DrmUtils.isFairPlayKeySystem(a.keySystem)){try{var d=shaka.util.StringUtils.fromUTF8(b.data)}catch(e){return}a=!1;d=d.trim();d.substr(0,5)==="<ckc>"&&d.substr(-6)==="</ckc>"&&(d=
d.slice(5,-6),a=!0);if(!a)try{const e=JSON.parse(d);e.ckc&&(d=e.ckc,a=!0);e.CkcMessage&&(d=e.CkcMessage,a=!0);e.License&&(d=e.License,a=!0)}catch(e){}a&&(b.data=shaka.util.BufferUtils.toArrayBuffer(shaka.util.Uint8ArrayUtils.fromBase64(d)))}}};goog.exportSymbol("shaka.drm.FairPlay",shaka.drm.FairPlay);goog.exportProperty(shaka.drm.FairPlay,"commonFairPlayResponse",shaka.drm.FairPlay.commonFairPlayResponse);goog.exportProperty(shaka.drm.FairPlay,"muxFairPlayRequest",shaka.drm.FairPlay.muxFairPlayRequest);
goog.exportProperty(shaka.drm.FairPlay,"expressplayFairPlayRequest",shaka.drm.FairPlay.expressplayFairPlayRequest);goog.exportProperty(shaka.drm.FairPlay,"conaxFairPlayRequest",shaka.drm.FairPlay.conaxFairPlayRequest);goog.exportProperty(shaka.drm.FairPlay,"ezdrmFairPlayRequest",shaka.drm.FairPlay.ezdrmFairPlayRequest);goog.exportProperty(shaka.drm.FairPlay,"verimatrixFairPlayRequest",shaka.drm.FairPlay.verimatrixFairPlayRequest);goog.exportProperty(shaka.drm.FairPlay,"muxInitDataTransform",shaka.drm.FairPlay.muxInitDataTransform);
goog.exportProperty(shaka.drm.FairPlay,"expressplayInitDataTransform",shaka.drm.FairPlay.expressplayInitDataTransform);goog.exportProperty(shaka.drm.FairPlay,"conaxInitDataTransform",shaka.drm.FairPlay.conaxInitDataTransform);goog.exportProperty(shaka.drm.FairPlay,"ezdrmInitDataTransform",shaka.drm.FairPlay.ezdrmInitDataTransform);goog.exportProperty(shaka.drm.FairPlay,"verimatrixInitDataTransform",shaka.drm.FairPlay.verimatrixInitDataTransform);
goog.exportProperty(shaka.drm.FairPlay,"initDataTransform",shaka.drm.FairPlay.initDataTransform);goog.exportProperty(shaka.drm.FairPlay,"defaultGetContentId",shaka.drm.FairPlay.defaultGetContentId);goog.exportProperty(shaka.drm.FairPlay,"isFairPlaySupported",shaka.drm.FairPlay.isFairPlaySupported);shaka.media.AdaptationSet=class{constructor(a,b,c=!0){this.root_=a;this.variants_=new Set([a]);b=b||[];for(const d of b)this.add(d,c)}add(a,b){if(this.canInclude(a,b))return this.variants_.add(a),!0;shaka.log.warning("Rejecting variant - not compatible with root.");return!1}canInclude(a,b=!0){return shaka.media.AdaptationSet.areAdaptable(this.root_,a,b)}static areAdaptable(a,b,c){const d=shaka.media.AdaptationSet;if(!!a.audio!=!!b.audio||!!a.video!=!!b.video||a.language!=b.language)return!1;goog.asserts.assert(!!a.audio==
!!b.audio,"Both should either have audio or not have audio.");if(a.audio&&b.audio&&!d.areAudiosCompatible_(a.audio,b.audio,c))return!1;goog.asserts.assert(!!a.video==!!b.video,"Both should either have video or not have video.");return a.video&&b.video&&!d.areVideosCompatible_(a.video,b.video,c)?!1:!0}values(){return this.variants_.values()}static areAudiosCompatible_(a,b,c){const d=shaka.media.AdaptationSet;return(!a.channelsCount||!b.channelsCount||a.channelsCount>2||b.channelsCount>2)&&a.channelsCount!=
b.channelsCount||a.spatialAudio!==b.spatialAudio||c&&!d.canTransitionBetween_(a,b)||!d.areRolesEqual_(a.roles,b.roles)||a.groupId!==b.groupId?!1:!0}static areVideosCompatible_(a,b,c){const d=shaka.media.AdaptationSet;return c&&!d.canTransitionBetween_(a,b)||!d.areRolesEqual_(a.roles,b.roles)?!1:!0}static canTransitionBetween_(a,b){if(a.mimeType!=b.mimeType)return!1;a=shaka.util.MimeUtils.splitCodecs(a.codecs).map(c=>shaka.util.MimeUtils.getCodecBase(c));b=shaka.util.MimeUtils.splitCodecs(b.codecs).map(c=>
shaka.util.MimeUtils.getCodecBase(c));return shaka.util.ArrayUtils.hasSameElements(a,b)}static areRolesEqual_(a,b){return shaka.util.ArrayUtils.hasSameElements(a,b)}};goog.exportSymbol("shaka.media.AdaptationSet",shaka.media.AdaptationSet);shaka.media.PreferenceBasedCriteria=class{constructor(){this.lastAdaptationSet_=this.config_=null}configure(a){this.config_=a}getConfiguration(){return this.config_}create(a){var b=shaka.media.PreferenceBasedCriteria,c;if(this.config_.language){const g=b.filterByLanguage_(a,this.config_.language);g.length&&(c=g)}c||(c=a.filter(g=>g.primary),c=c.length?c:a);a=b.filterVariantsByAudioRole_(c,this.config_.role);a.length?c=a:shaka.log.warning("No exact match for variant audio role could be found.");a=
b.filterVariantsByVideoRole_(c,this.config_.videoRole);a.length?c=a:shaka.log.warning("No exact match for variant video role could be found.");this.config_.videoLayout&&(a=b.filterVariantsByVideoLayout_(c,this.config_.videoLayout),a.length?c=a:shaka.log.warning("No exact match for the video layout could be found."));this.config_.hdrLevel&&(a=b.filterVariantsByHDRLevel_(c,this.config_.hdrLevel),a.length?c=a:shaka.log.warning("No exact match for the hdr level could be found."));const d=[this.config_.channelCount,
this.config_.preferredAudioChannelCount];a=d.filter((g,h)=>g&&d.indexOf(g)===h);if(a.length)for(var e of a)if(a=b.filterVariantsByAudioChannelCount_(c,e),a.length){c=a;break}else shaka.log.warning("No exact match for the channel count could be found.");this.config_.audioLabel&&(e=b.filterVariantsByAudioLabel_(c,this.config_.audioLabel),e.length?c=e:shaka.log.warning("No exact match for audio label could be found."));this.config_.videoLabel&&(e=b.filterVariantsByVideoLabel_(c,this.config_.videoLabel),
e.length?c=e:shaka.log.warning("No exact match for video label could be found."));e=b.filterVariantsBySpatialAudio_(c,this.config_.spatialAudio);e.length?c=e:shaka.log.warning("No exact match for spatial audio could be found.");const f=[this.config_.audioCodec,this.config_.activeAudioCodec,...this.config_.preferredAudioCodecs];e=f.filter((g,h)=>g&&f.indexOf(g)===h);if(e.length)for(const g of e)if(e=b.filterVariantsByAudioCodec_(c,g),e.length){c=e;break}else shaka.log.warning("No exact match for audio codec could be found.");
b=shaka.device.DeviceFactory.getDevice();b=this.config_.codecSwitchingStrategy==shaka.config.CodecSwitchingStrategy.SMOOTH&&b.supportsSmoothCodecSwitching();return this.lastAdaptationSet_=new shaka.media.AdaptationSet(c[0],c,!b)}getLastAdaptationSet(){return this.lastAdaptationSet_}static filterByLanguage_(a,b){const c=shaka.util.LanguageUtils;b=c.normalize(b);const d=c.findClosestLocale(b,a.map(e=>c.getLocaleForVariant(e)));return d?a.filter(e=>d==c.getLocaleForVariant(e)):[]}static filterVariantsByAudioRole_(a,
b){return a.filter(c=>c.audio?b?c.audio.roles.includes(b):c.audio.roles.length==0:!1)}static filterVariantsByVideoRole_(a,b){return a.filter(c=>c.video?b?c.video.roles.includes(b):c.video.roles.length==0:!1)}static filterVariantsByAudioLabel_(a,b){return a.filter(c=>{if(!c.audio||!c.audio.label)return!1;c=c.audio.label.toLowerCase();const d=b.toLowerCase();return c==d})}static filterVariantsByVideoLabel_(a,b){return a.filter(c=>{if(!c.video||!c.video.label)return!1;c=c.video.label.toLowerCase();const d=
b.toLowerCase();return c==d})}static filterVariantsByAudioChannelCount_(a,b){return a.filter(c=>c.audio&&c.audio.channelsCount&&c.audio.channelsCount>b?!1:!0).sort((c,d)=>c.audio||d.audio?c.audio?d.audio?(d.audio.channelsCount||0)-(c.audio.channelsCount||0):1:-1:0)}static filterVariantsByHDRLevel_(a,b){if(b=="AUTO"){const c=a.some(d=>d.video&&d.video.hdr&&d.video.hdr=="HLG"?!0:!1);b=shaka.device.DeviceFactory.getDevice().getHdrLevel(c)}return a.filter(c=>c.video&&c.video.hdr&&c.video.hdr!=b?!1:!0)}static filterVariantsByVideoLayout_(a,
b){return a.filter(c=>c.video&&c.video.videoLayout&&c.video.videoLayout!=b?!1:!0)}static filterVariantsBySpatialAudio_(a,b){return a.filter(c=>c.audio&&c.audio.spatialAudio!=b?!1:!0)}static filterVariantsByAudioCodec_(a,b){return a.filter(c=>c.audio&&c.audio.codecs!=b?!1:!0)}};shaka.util.PlayerConfiguration=class{static createDefault(){let a=Infinity;const b=shaka.device.DeviceFactory.getDevice();navigator.connection&&navigator.connection.saveData&&(a=360);const c={retryParameters:shaka.net.NetworkingEngine.defaultRetryParameters(),servers:{},clearKeys:{},advanced:{},delayLicenseRequestUntilPlayed:!1,persistentSessionOnlinePlayback:!1,persistentSessionsMetadata:[],initDataTransform:(k,l,m)=>{shaka.drm.DrmUtils.isMediaKeysPolyfilled("apple")&&l=="skd"&&(l=m.serverCertificate,
m=shaka.drm.FairPlay.defaultGetContentId(k),k=shaka.drm.FairPlay.initDataTransform(k,m,l));return k},logLicenseExchange:!1,updateExpirationTime:1,preferredKeySystems:[],keySystemsMapping:{},parseInbandPsshEnabled:!1,minHdcpVersion:"",ignoreDuplicateInitData:!0,defaultAudioRobustnessForWidevine:"SW_SECURE_CRYPTO",defaultVideoRobustnessForWidevine:"SW_SECURE_DECODE"};let d=shaka.config.CodecSwitchingStrategy.RELOAD;b.supportsSmoothCodecSwitching()&&(d=shaka.config.CodecSwitchingStrategy.SMOOTH);const e=
{retryParameters:shaka.net.NetworkingEngine.defaultRetryParameters(),availabilityWindowOverride:NaN,disableAudio:!1,disableVideo:!1,disableText:!1,disableThumbnails:!1,disableIFrames:!1,defaultPresentationDelay:0,segmentRelativeVttTiming:!1,raiseFatalErrorOnManifestUpdateRequestFailure:!1,continueLoadingWhenPaused:!0,ignoreSupplementalCodecs:!1,updatePeriod:-1,ignoreDrmInfo:!1,enableAudioGroups:!0,dash:{clockSyncUri:"",disableXlinkProcessing:!0,xlinkFailGracefully:!1,ignoreMinBufferTime:!1,autoCorrectDrift:!0,
initialSegmentLimit:1E3,ignoreSuggestedPresentationDelay:!1,ignoreEmptyAdaptationSet:!1,ignoreMaxSegmentDuration:!1,keySystemsByURI:{"urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b":"org.w3.clearkey","urn:uuid:e2719d58-a985-b3c9-781a-b030af78d30e":"org.w3.clearkey","urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed":"com.widevine.alpha","urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95":"com.microsoft.playready","urn:uuid:79f0049a-4098-8642-ab92-e65be0885f95":"com.microsoft.playready","urn:uuid:94ce86fb-07ff-4f43-adb8-93d2fa968ca2":"com.apple.fps",
"urn:uuid:3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c":"com.huawei.wiseplay"},manifestPreprocessor:shaka.util.PlayerConfiguration.defaultManifestPreprocessor,manifestPreprocessorTXml:shaka.util.PlayerConfiguration.defaultManifestPreprocessorTXml,sequenceMode:!1,useStreamOnceInPeriodFlattening:!1,enableFastSwitching:!0},hls:{ignoreTextStreamFailures:!1,ignoreImageStreamFailures:!1,defaultAudioCodec:"mp4a.40.2",defaultVideoCodec:"avc1.42E01E",ignoreManifestProgramDateTime:!1,ignoreManifestProgramDateTimeForTypes:[],
mediaPlaylistFullMimeType:'video/mp2t; codecs="avc1.42E01E, mp4a.40.2"',liveSegmentsDelay:3,sequenceMode:b.supportsSequenceMode(),ignoreManifestTimestampsInSegmentsMode:!1,disableCodecGuessing:!1,disableClosedCaptionsDetection:!1,allowLowLatencyByteRangeOptimization:!0,allowRangeRequestsToGuessMimeType:!1},mss:{manifestPreprocessor:shaka.util.PlayerConfiguration.defaultManifestPreprocessor,manifestPreprocessorTXml:shaka.util.PlayerConfiguration.defaultManifestPreprocessorTXml,sequenceMode:!1,keySystemsBySystemId:{"9a04f079-9840-4286-ab92-e65be0885f95":"com.microsoft.playready",
"79f0049a-4098-8642-ab92-e65be0885f95":"com.microsoft.playready"}}},f={retryParameters:shaka.net.NetworkingEngine.defaultRetryParameters(),failureCallback:k=>{shaka.log.error("Unhandled streaming error",k);return shaka.util.ConfigUtils.referenceParametersAndReturn([k],void 0)},rebufferingGoal:0,bufferingGoal:10,bufferBehind:30,evictionGoal:1,ignoreTextStreamFailures:!1,alwaysStreamText:!1,startAtSegmentBoundary:!1,gapDetectionThreshold:.5,gapPadding:0,gapJumpTimerTime:.25,durationBackoff:1,safeSeekOffset:5,
safeSeekEndOffset:0,stallEnabled:!0,stallThreshold:1,stallSkip:.1,useNativeHlsForFairPlay:!0,inaccurateManifestTolerance:2,lowLatencyMode:!0,preferNativeDash:!1,preferNativeHls:!1,updateIntervalSeconds:1,observeQualityChanges:!1,maxDisabledTime:30,segmentPrefetchLimit:1,prefetchAudioLanguages:[],disableAudioPrefetch:!1,disableTextPrefetch:!1,disableVideoPrefetch:!1,liveSync:{enabled:!1,targetLatency:.5,targetLatencyTolerance:.5,maxPlaybackRate:1.1,minPlaybackRate:.95,panicMode:!1,panicThreshold:60,
dynamicTargetLatency:{enabled:!1,stabilityThreshold:60,rebufferIncrement:.5,maxAttempts:10,maxLatency:4,minLatency:1}},allowMediaSourceRecoveries:!0,minTimeBetweenRecoveries:5,vodDynamicPlaybackRate:!1,vodDynamicPlaybackRateLowBufferRate:.95,vodDynamicPlaybackRateBufferRatio:.5,preloadNextUrlWindow:30,loadTimeout:30,clearDecodingCache:!1,dontChooseCodecs:!1,shouldFixTimestampOffset:!1,avoidEvictionOnQuotaExceededError:!1,crossBoundaryStrategy:shaka.config.CrossBoundaryStrategy.KEEP,returnToEndOfLiveWindowWhenOutside:!1},
g={trackSelectionCallback:async k=>k,downloadSizeCallback:async k=>{if(navigator.storage&&navigator.storage.estimate){const l=await navigator.storage.estimate();return l.usage+k<l.quota*.95}return!0},progressCallback:(k,l)=>shaka.util.ConfigUtils.referenceParametersAndReturn([k,l],void 0),usePersistentLicense:!0,numberOfParallelDownloads:5},h={drm:c,manifest:e,streaming:f,networking:{forceHTTP:!1,forceHTTPS:!1,minBytesForProgressEvents:16E3},mediaSource:{codecSwitchingStrategy:d,addExtraFeaturesToSourceBuffer:k=>
shaka.util.ConfigUtils.referenceParametersAndReturn([k],""),forceTransmux:!1,insertFakeEncryptionInInit:!0,correctEc3Enca:!1,modifyCueCallback:(k,l,m)=>shaka.util.ConfigUtils.referenceParametersAndReturn([k,l,m],void 0),dispatchAllEmsgBoxes:!1,useSourceElements:!0,durationReductionEmitsUpdateEnd:!0},offline:g,abrFactory:()=>new shaka.abr.SimpleAbrManager,adaptationSetCriteriaFactory:(...k)=>new shaka.media.PreferenceBasedCriteria(...k),abr:{enabled:!0,useNetworkInformation:!0,defaultBandwidthEstimate:1E6,
switchInterval:8,bandwidthUpgradeTarget:.85,bandwidthDowngradeTarget:.95,restrictions:{minWidth:0,maxWidth:Infinity,minHeight:0,maxHeight:a,minPixels:0,maxPixels:Infinity,minFrameRate:0,maxFrameRate:Infinity,minBandwidth:0,maxBandwidth:Infinity,minChannelsCount:0,maxChannelsCount:Infinity},advanced:{minTotalBytes:128E3,minBytes:16E3,fastHalfLife:2,slowHalfLife:5},restrictToElementSize:!1,restrictToScreenSize:!1,ignoreDevicePixelRatio:!1,clearBufferSwitch:!1,safeMarginSwitch:0,cacheLoadThreshold:5,
minTimeToSwitch:0,preferNetworkInformationBandwidth:!1,removeLatencyFromFirstPacketTime:!1},autoShowText:shaka.config.AutoShowText.IF_SUBTITLES_MAY_BE_NEEDED,preferredAudioLanguage:"",preferredAudioLabel:"",preferredTextLanguage:"",preferredAudioRole:"",preferredVideoRole:"",preferredTextRole:"",preferredAudioChannelCount:2,preferredVideoHdrLevel:"AUTO",preferredVideoLayout:"",preferredVideoLabel:"",preferredVideoCodecs:[],preferredAudioCodecs:[],preferredTextFormats:[],preferForcedSubs:!1,preferSpatialAudio:!1,
preferredDecodingAttributes:[],restrictions:{minWidth:0,maxWidth:Infinity,minHeight:0,maxHeight:Infinity,minPixels:0,maxPixels:Infinity,minFrameRate:0,maxFrameRate:Infinity,minBandwidth:0,maxBandwidth:Infinity,minChannelsCount:0,maxChannelsCount:Infinity},playRangeStart:0,playRangeEnd:Infinity,textDisplayer:{captionsUpdatePeriod:.25,fontScaleFactor:1},textDisplayFactory:()=>null,cmcd:{enabled:!1,sessionId:"",contentId:"",rtpSafetyFactor:5,useHeaders:!1,includeKeys:[],version:1,targets:[]},cmsd:{enabled:!0,
applyMaximumSuggestedBitrate:!0,estimatedThroughputWeightRatio:.5},lcevc:{enabled:!1,dynamicPerformanceScaling:!0,logLevel:0,drawLogo:!1,poster:!0},ads:{customPlayheadTracker:!1,skipPlayDetection:!1,supportsMultipleMediaElements:!0,disableHLSInterstitial:!1,disableDASHInterstitial:!1,allowPreloadOnDomElements:!0,allowStartInMiddleOfInterstitial:!0},ignoreHardwareResolution:!1,queue:{preloadNextUrlWindow:Infinity,preloadPrevItem:!0,repeatMode:shaka.config.RepeatMode.OFF}};g.trackSelectionCallback=
async k=>shaka.util.PlayerConfiguration.defaultTrackSelect(k,h.preferredAudioLanguage,h.preferredVideoHdrLevel);return b.adjustConfig(h)}static createDefaultForLL(){return{streaming:{inaccurateManifestTolerance:0,segmentPrefetchLimit:2,updateIntervalSeconds:.1,maxDisabledTime:1,retryParameters:{baseDelay:100}},manifest:{dash:{autoCorrectDrift:!1},retryParameters:{baseDelay:100}},drm:{retryParameters:{baseDelay:100}}}}static mergeConfigObjects(a,b,c){const d={".drm.keySystemsMapping":"",".drm.servers":"",
".drm.clearKeys":"",".drm.advanced":{distinctiveIdentifierRequired:!1,persistentStateRequired:!1,videoRobustness:[],audioRobustness:[],sessionType:"",serverCertificate:new Uint8Array(0),serverCertificateUri:"",individualizationServer:"",headers:{}}};return shaka.util.ConfigUtils.mergeConfigObjects(a,b,c||shaka.util.PlayerConfiguration.createDefault(),d,"")}static defaultTrackSelect(a,b,c){const d=shaka.util.ManifestParserUtils.ContentType,e=shaka.util.LanguageUtils;let f=c;f=="AUTO"&&(c=a.some(l=>
l.hdr&&l.hdr=="HLG"?!0:!1),f=shaka.device.DeviceFactory.getDevice().getHdrLevel(c));var g=a.filter(l=>l.type!="variant"||l.hdr&&l.hdr!=f?!1:!0);c=[];const h=e.findClosestLocale(b,g.map(l=>l.language));h&&(c=g.filter(l=>e.normalize(l.language)==h));c.length==0&&(c=g.filter(l=>l.primary));c.length==0&&((new Set(g.map(l=>l.language))).size>1&&shaka.log.warning("Could not choose a good audio track based on language preferences or primary tracks.  An arbitrary language will be stored!"),c=g);const k=c.filter(l=>
l.height&&l.height<=480);k.length&&(k.sort((l,m)=>{goog.asserts.assert(l.height!=null,"Null height");goog.asserts.assert(m.height!=null,"Null height");return m.height-l.height}),c=k.filter(l=>l.height==k[0].height));b=[];c.length&&(g=Math.floor(c.length/2),c.sort((l,m)=>l.bandwidth-m.bandwidth),b.push(c[g]));for(const l of a)l.type!=d.TEXT&&l.type!=d.IMAGE||b.push(l);return b}static defaultManifestPreprocessor(a){return shaka.util.ConfigUtils.referenceParametersAndReturn([a],a)}static defaultManifestPreprocessorTXml(a){return shaka.util.ConfigUtils.referenceParametersAndReturn([a],
a)}};goog.exportSymbol("shaka.util.PlayerConfiguration",shaka.util.PlayerConfiguration);goog.exportProperty(shaka.util.PlayerConfiguration,"mergeConfigObjects",shaka.util.PlayerConfiguration.mergeConfigObjects);goog.exportProperty(shaka.util.PlayerConfiguration,"createDefaultForLL",shaka.util.PlayerConfiguration.createDefaultForLL);goog.exportProperty(shaka.util.PlayerConfiguration,"createDefault",shaka.util.PlayerConfiguration.createDefault);shaka.util.StateHistory=class{constructor(){this.open_=null;this.closed_=[]}update(a){return this.open_==null?(this.start_(a),!0):this.update_(a)}getTimeSpentIn(a){let b=0;this.open_&&this.open_.state==a&&(b+=this.open_.duration);for(const c of this.closed_)b+=c.state==a?c.duration:0;return b}getCopy(){const a=c=>({timestamp:c.timestamp,state:c.state,duration:c.duration}),b=[];for(const c of this.closed_)b.push(a(c));this.open_&&b.push(a(this.open_));return b}start_(a){goog.asserts.assert(this.open_==
null,"There must be no open entry in order when we start");shaka.log.v1("Changing Player state to",a);this.open_={timestamp:this.getNowInSeconds_(),state:a,duration:0}}update_(a){goog.asserts.assert(this.open_,"There must be an open entry in order to update it");const b=this.getNowInSeconds_();this.open_.duration=b-this.open_.timestamp;if(this.open_.state==a)return!1;shaka.log.v1("Changing Player state to",a);this.closed_.push(this.open_);this.open_={timestamp:b,state:a,duration:0};return!0}getNowInSeconds_(){return Date.now()/
1E3}};shaka.util.SwitchHistory=class{constructor(){this.currentText_=this.currentVariant_=null;this.history_=[]}updateCurrentVariant(a,b){this.currentVariant_!=a&&(this.currentVariant_=a,this.history_.push({timestamp:this.getNowInSeconds_(),id:a.id,type:"variant",fromAdaptation:b,bandwidth:a.bandwidth}))}updateCurrentText(a,b){this.currentText_!=a&&(this.currentText_=a,this.history_.push({timestamp:this.getNowInSeconds_(),id:a.id,type:"text",fromAdaptation:b,bandwidth:null}))}getCopy(){const a=[];for(const b of this.history_)a.push(this.clone_(b));
return a}getNowInSeconds_(){return Date.now()/1E3}clone_(a){return{timestamp:a.timestamp,id:a.id,type:a.type,fromAdaptation:a.fromAdaptation,bandwidth:a.bandwidth}}};shaka.util.Stats=class{constructor(){this.height_=this.width_=NaN;this.currentCodecs_="";this.bytesDownloaded_=this.manifestSizeBytes_=this.bandwidthEstimate_=this.currentStreamBandwidth_=this.maxSegmentDurationSeconds_=this.liveLatencySeconds_=this.licenseTimeSeconds_=this.drmTimeSeconds_=this.manifestTimeSeconds_=this.loadLatencySeconds_=this.completionPercent_=this.totalGapsJumped_=this.totalStallsDetected_=this.totalCorruptedFrames_=this.totalDecodedFrames_=this.totalDroppedFrames_=NaN;this.nonFatalErrorCount_=
0;this.manifestGapCount_=this.manifestPeriodCount_=NaN;this.stateHistory_=new shaka.util.StateHistory;this.switchHistory_=new shaka.util.SwitchHistory}setDroppedFrames(a,b){this.totalDroppedFrames_=a;this.totalDecodedFrames_=b}setCorruptedFrames(a){this.totalCorruptedFrames_=a}setStallsDetected(a){this.totalStallsDetected_=a}setGapsJumped(a){this.totalGapsJumped_=a}setResolution(a,b){this.width_=a;this.height_=b}setCodecs(a){this.currentCodecs_=a}setLoadLatency(a){a>=0&&(this.loadLatencySeconds_=
a)}setManifestTime(a){a>=0&&(this.manifestTimeSeconds_=a)}setCompletionPercent(a){isNaN(this.completionPercent_)?this.completionPercent_=a:this.completionPercent_=Math.max(this.completionPercent_,a)}setDrmTime(a){a>=0&&(this.drmTimeSeconds_=a)}setLicenseTime(a){a>=0&&(this.licenseTimeSeconds_=a)}setLiveLatency(a){a>=0&&(this.liveLatencySeconds_=a)}setMaxSegmentDuration(a){a>=0&&(this.maxSegmentDurationSeconds_=a)}setCurrentStreamBandwidth(a){this.currentStreamBandwidth_=a}setBandwidthEstimate(a){this.bandwidthEstimate_=
a}setManifestSize(a){this.manifestSizeBytes_=a}addBytesDownloaded(a){isNaN(this.bytesDownloaded_)?this.bytesDownloaded_=a:this.bytesDownloaded_+=a}addNonFatalError(){this.nonFatalErrorCount_++}setManifestPeriodCount(a){this.manifestPeriodCount_=a}setManifestGapCount(a){this.manifestGapCount_=a}getStateHistory(){return this.stateHistory_}getSwitchHistory(){return this.switchHistory_}getBlob(){return{width:this.width_,height:this.height_,currentCodecs:this.currentCodecs_,streamBandwidth:this.currentStreamBandwidth_,
decodedFrames:this.totalDecodedFrames_,droppedFrames:this.totalDroppedFrames_,corruptedFrames:this.totalCorruptedFrames_,stallsDetected:this.totalStallsDetected_,gapsJumped:this.totalGapsJumped_,estimatedBandwidth:this.bandwidthEstimate_,completionPercent:this.completionPercent_,loadLatency:this.loadLatencySeconds_,manifestTimeSeconds:this.manifestTimeSeconds_,drmTimeSeconds:this.drmTimeSeconds_,playTime:this.stateHistory_.getTimeSpentIn("playing"),pauseTime:this.stateHistory_.getTimeSpentIn("paused"),
bufferingTime:this.stateHistory_.getTimeSpentIn("buffering"),licenseTime:this.licenseTimeSeconds_,liveLatency:this.liveLatencySeconds_,maxSegmentDuration:this.maxSegmentDurationSeconds_,manifestSizeBytes:this.manifestSizeBytes_,bytesDownloaded:this.bytesDownloaded_,nonFatalErrorCount:this.nonFatalErrorCount_,manifestPeriodCount:this.manifestPeriodCount_,manifestGapCount:this.manifestGapCount_,stateHistory:this.stateHistory_.getCopy(),switchHistory:this.switchHistory_.getCopy()}}static getEmptyBlob(){return{width:NaN,
height:NaN,currentCodecs:"",streamBandwidth:NaN,decodedFrames:NaN,droppedFrames:NaN,corruptedFrames:NaN,stallsDetected:NaN,gapsJumped:NaN,estimatedBandwidth:NaN,completionPercent:NaN,loadLatency:NaN,manifestTimeSeconds:NaN,drmTimeSeconds:NaN,playTime:NaN,pauseTime:NaN,bufferingTime:NaN,licenseTime:NaN,liveLatency:NaN,maxSegmentDuration:NaN,manifestSizeBytes:NaN,bytesDownloaded:NaN,nonFatalErrorCount:NaN,manifestPeriodCount:NaN,manifestGapCount:NaN,switchHistory:[],stateHistory:[]}}};shaka.media.PreloadManager=class extends shaka.util.FakeEventTarget{constructor(a,b,c,d){super();this.assetUri_=a;this.mimeType_=b;this.networkingEngine_=d.networkingEngine;this.startTime_=c;this.currentAdaptationSetCriteria_=null;this.startTimeOfDrm_=0;this.createDrmEngine_=d.createDrmEngine;this.manifestFilterer_=d.manifestFilterer;this.manifestPlayerInterface_=d.manifestPlayerInterface;this.config_=d.config;this.parser_=this.parserFactory_=this.manifest_=null;this.parserEntrusted_=!1;this.regionTimeline_=
d.regionTimeline;this.regionTimelineEntrusted_=!1;this.drmEngine_=null;this.drmEngineEntrusted_=!1;this.abrManager_=null;this.segmentPrefetchById_=new Map;this.segmentPrefetchEntrusted_=!1;this.qualityObserver_=d.qualityObserver;this.stats_=new shaka.util.Stats;this.manifestPromise_=new shaka.util.PublicPromise;this.successPromise_=new shaka.util.PublicPromise;this.eventHandoffTarget_=null;this.destroyed_=!1;this.allowPrefetch_=d.allowPrefetch;this.prefetchedTextStream_=this.prefetchedVariant_=null;
this.hasBeenAttached_=!1;this.queuedOperations_=[];this.latePhaseQueuedOperations_=[];this.isPreload_=!0}markIsLoad(){this.isPreload_=!1}addQueuedOperation(a,b){(a=a?this.latePhaseQueuedOperations_:this.queuedOperations_)?a.push(b):b()}stopQueuingLatePhaseQueuedOperations(){if(this.latePhaseQueuedOperations_)for(const a of this.latePhaseQueuedOperations_)a();this.latePhaseQueuedOperations_=null}setEventHandoffTarget(a){this.eventHandoffTarget_=a;this.hasBeenAttached_=!0;if(this.queuedOperations_)for(const b of this.queuedOperations_)b();
this.queuedOperations_=null}setOffsetToStartTime(a){this.startTime_&&a&&(typeof this.startTime_==="number"?this.startTime_+=a:this.startTime_.setTime(this.startTime_.getTime()+a*1E3))}getStartTime(){return this.startTime_}getStartTimeOfDRM(){return this.startTimeOfDrm_}getMimeType(){return this.mimeType_}getAssetUri(){return this.assetUri_}getManifest(){return this.manifest_}getParserFactory(){return this.parserFactory_}getCurrentAdaptationSetCriteria(){return this.currentAdaptationSetCriteria_}receiveParser(){this.parserEntrusted_=
!0;return this.parser_}getParser(){return this.parser_}receiveRegionTimeline(){this.regionTimelineEntrusted_=!0;return this.regionTimeline_}getRegionTimeline(){return this.regionTimeline_}getQualityObserver(){return this.qualityObserver_}getStats(){return this.stats_}getManifestFilterer(){return this.manifestFilterer_}receiveDrmEngine(){this.drmEngineEntrusted_=!0;return this.drmEngine_}getDrmEngine(){return this.drmEngine_}setPrefetchVariant(a){this.prefetchedVariant_=a}getPrefetchedVariant(){return this.prefetchedVariant_}getPrefetchedVariantTrack(){return this.prefetchedVariant_?
shaka.util.StreamUtils.variantToTrack(this.prefetchedVariant_):null}getPrefetchedTextTrack(){return this.prefetchedTextStream_?shaka.util.StreamUtils.textStreamToTrack(this.prefetchedTextStream_):null}receiveSegmentPrefetchesById(){this.segmentPrefetchEntrusted_=!0;return this.segmentPrefetchById_}attachAdaptationSetCriteria(a){this.currentAdaptationSetCriteria_=a}attachManifest(a,b,c){this.manifest_=a;this.parser_=b;this.parserFactory_=c}start(){(async()=>{await Promise.resolve();try{await this.parseManifestInner_(),
this.throwIfDestroyed_(),shaka.drm.DrmUtils.isMediaKeysPolyfilled("webkit")||(await this.initializeDrm(),this.throwIfDestroyed_()),await this.validatePrefetchedVariant_(),this.throwIfDestroyed_(),this.allowPrefetch_&&(await this.prefetchInner_(),this.throwIfDestroyed_()),this.allowPrefetch_&&this.drmEngine_&&(await this.drmEngine_.waitForActiveRequests(),this.throwIfDestroyed_()),this.successPromise_.resolve()}catch(a){a instanceof shaka.util.Error&&(a.code==shaka.util.Error.Code.OPERATION_ABORTED||
a.code==shaka.util.Error.Code.OBJECT_DESTROYED)||this.successPromise_.reject(a)}})()}dispatchEvent(a){return this.eventHandoffTarget_?this.eventHandoffTarget_.dispatchEvent(a):super.dispatchEvent(a)}onError(a){a.severity===shaka.util.Error.Severity.CRITICAL&&(this.successPromise_.reject(a),this.destroy());const b=this.makeEvent_(shaka.util.FakeEvent.EventName.Error,(new Map).set("detail",a));this.dispatchEvent(b);b.defaultPrevented&&(a.handled=!0)}throwIfDestroyed_(){if(this.isDestroyed())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.OBJECT_DESTROYED);}makeStateChangeEvent_(a){this.dispatchEvent(new shaka.util.FakeEvent(shaka.util.FakeEvent.EventName.OnStateChange,(new Map).set("state",a)))}makeEvent_(a,b){return new shaka.util.FakeEvent(a,b)}async parseManifestInner_(){this.makeStateChangeEvent_("manifest-parser");this.parser_||(this.parserFactory_=shaka.media.ManifestParser.getFactory(this.assetUri_,this.mimeType_),goog.asserts.assert(this.parserFactory_,"Must have manifest parser"),
this.parser_=this.parserFactory_(),this.parser_.configure(this.config_.manifest,()=>this.isPreload_));const a=Date.now()/1E3;this.makeStateChangeEvent_("manifest");this.manifest_||(this.manifest_=await this.parser_.start(this.assetUri_,this.manifestPlayerInterface_),shaka.media.PreloadManager.filterForAVVariants_(this.manifest_),await this.chooseInitialVariant_());this.manifestPromise_.resolve();var b=this.makeEvent_(shaka.util.FakeEvent.EventName.ManifestParsed);await Promise.resolve();this.dispatchEvent(b);
if(this.manifest_.variants.length==0)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.NO_VARIANTS);shaka.media.PreloadManager.filterForAVVariants_(this.manifest_);this.manifestFilterer_.applyRestrictions(this.manifest_)&&(b=this.makeEvent_(shaka.util.FakeEvent.EventName.TracksChanged),await Promise.resolve(),this.throwIfDestroyed_(),this.dispatchEvent(b));b=Date.now()/1E3;this.stats_.setManifestTime(b-a)}async initializeDrm(a){if(this.manifest_&&
!this.drmEngine_){this.makeStateChangeEvent_("drm-engine");this.startTimeOfDrm_=Date.now()/1E3;this.drmEngine_=this.createDrmEngine_();this.manifestFilterer_.setDrmEngine(this.drmEngine_);this.drmEngine_.configure(this.config_.drm,()=>this.isPreload_);var b=shaka.util.StreamUtils.getPlayableVariants(this.manifest_.variants),c=!0;this.manifest_&&this.manifest_.presentationTimeline&&(c=this.manifest_.presentationTimeline.isLive());await this.drmEngine_.initForPlayback(b,this.manifest_.offlineSessionIds,
c);this.throwIfDestroyed_();a&&(await this.drmEngine_.attach(a),this.throwIfDestroyed_());await this.manifestFilterer_.filterManifest(this.manifest_)&&(a=this.makeEvent_(shaka.util.FakeEvent.EventName.TracksChanged),await Promise.resolve(),this.dispatchEvent(a))}}reconfigure(a){this.config_=a}configure(a,b){a=shaka.util.ConfigUtils.convertToConfigObject(a,b);shaka.util.PlayerConfiguration.mergeConfigObjects(this.config_,a)}getConfiguration(){return shaka.util.ObjectUtils.cloneObject(this.config_)}async chooseInitialVariant_(){this.currentAdaptationSetCriteria_||
(this.currentAdaptationSetCriteria_=this.config_.adaptationSetCriteriaFactory(),this.currentAdaptationSetCriteria_.configure({language:this.config_.preferredAudioLanguage,role:this.config_.preferredAudioRole,videoRole:this.config_.preferredVideoRole,channelCount:0,hdrLevel:this.config_.preferredVideoHdrLevel,spatialAudio:this.config_.preferSpatialAudio,videoLayout:this.config_.preferredVideoLayout,audioLabel:this.config_.preferredAudioLabel,videoLabel:this.config_.preferredVideoLabel,codecSwitchingStrategy:this.config_.mediaSource.codecSwitchingStrategy,
audioCodec:"",activeAudioCodec:"",activeAudioChannelCount:0,preferredAudioCodecs:this.config_.preferredAudioCodecs,preferredAudioChannelCount:this.config_.preferredAudioChannelCount}));this.shouldCreateSegmentIndexBeforeDrmEngineInitialization_()&&(this.prefetchedVariant_=this.configureAbrManagerAndChooseVariant_())&&await this.createSegmentIndexFromVariant_(this.prefetchedVariant_)}shouldCreateSegmentIndexBeforeDrmEngineInitialization_(){if(this.prefetchedVariant_)return!1;goog.asserts.assert(this.manifest_,
"The manifest should already be parsed.");return this.manifest_.variants.length?this.manifest_.variants.length==1||this.manifest_.type==shaka.media.ManifestParser.HLS?!0:!1:!1}async validatePrefetchedVariant_(){this.prefetchedVariant_&&!this.manifest_.variants.includes(this.prefetchedVariant_)&&(await this.closeSegmentIndexFromVariant_(this.prefetchedVariant_),(this.prefetchedVariant_=this.configureAbrManagerAndChooseVariant_())&&await this.createSegmentIndexFromVariant_(this.prefetchedVariant_))}async prefetchInner_(){if(!this.prefetchedVariant_){var a=
this.configureAbrManagerAndChooseVariant_();a&&(this.prefetchedVariant_=a)}if(this.prefetchedVariant_){a=this.manifest_.presentationTimeline.isLive();const b=[],c=this.prefetchedVariant_;c.video&&b.push(this.prefetchStream_(c.video,a));c.audio&&b.push(this.prefetchStream_(c.audio,a));const d=this.chooseTextStream_();d&&shaka.util.StreamUtils.shouldInitiallyShowText(c.audio,d,this.config_)&&(b.push(this.prefetchStream_(d,a)),this.prefetchedTextStream_=d);await Promise.all(b)}}configureAbrManagerAndChooseVariant_(){goog.asserts.assert(this.currentAdaptationSetCriteria_,
"Must have an AdaptationSetCriteria");if(!this.abrManager_){var a=this.config_.abrFactory;this.abrManager_=a();this.abrManager_.configure(this.config_.abr)}a=shaka.util.StreamUtils.getPlayableVariants(this.manifest_.variants);a=this.currentAdaptationSetCriteria_.create(a);this.abrManager_.setVariants(Array.from(a.values()));return this.abrManager_.chooseVariant(!0)}chooseTextStream_(){return shaka.util.StreamUtils.filterStreamsByLanguageAndRole(this.manifest_.textStreams,this.config_.preferredTextLanguage,
this.config_.preferredTextRole,this.config_.preferForcedSubs)[0]||null}async prefetchStream_(a,b){const c=new shaka.media.SegmentPrefetch(this.config_.streaming.segmentPrefetchLimit||2,a,(f,g,h)=>shaka.media.StreamingEngine.dispatchFetch(f,g,h||null,this.config_.streaming.retryParameters,this.networkingEngine_,this.isPreload_),!1);this.segmentPrefetchById_.set(a.id,c);a.segmentIndex||await a.createSegmentIndex();const d=a.segmentIndex.getIteratorForTime(typeof this.startTime_==="number"?this.startTime_:
0);let e=null;d&&(e=d.current(),e||(e=d.next().value));e||=a.segmentIndex.earliestReference();e&&(b?e.initSegmentReference&&await c.prefetchInitSegment(e.initSegmentReference):await c.prefetchSegmentsByTime(e.startTime))}async createSegmentIndexFromVariant_(a){const b=[];for(const c of[a.video,a.audio])c&&!c.segmentIndex&&b.push(c.createSegmentIndex());b.length>0&&await Promise.all(b)}async closeSegmentIndexFromVariant_(a){const b=[];for(const c of[a.video,a.audio])c&&c.segmentIndex&&c.closeSegmentIndex&&
b.push(c.closeSegmentIndex());b.length>0&&await Promise.all(b)}waitForFinish(){return this.successPromise_}waitForManifest(){return Promise.race([this.manifestPromise_,this.successPromise_])}async destroy(){this.destroyed_=!0;this.parser_&&!this.parserEntrusted_&&await this.parser_.stop();this.abrManager_&&this.abrManager_.release();this.regionTimeline_&&!this.regionTimelineEntrusted_&&this.regionTimeline_.release();this.drmEngine_&&!this.drmEngineEntrusted_&&await this.drmEngine_.destroy();if(this.segmentPrefetchById_.size>
0&&!this.segmentPrefetchEntrusted_)for(const a of this.segmentPrefetchById_.values())a.clearAll()}isDestroyed(){return this.destroyed_}hasBeenAttached(){return this.hasBeenAttached_}static filterForAVVariants_(a){const b=c=>c.video&&c.audio||c.video&&c.video.codecs.includes(",");a.variants.some(b)&&(shaka.log.debug("Found variant with audio and video content, so filtering out audio-only content."),a.variants=a.variants.filter(b))}};goog.exportSymbol("shaka.media.PreloadManager",shaka.media.PreloadManager);
goog.exportProperty(shaka.media.PreloadManager.prototype,"destroy",shaka.media.PreloadManager.prototype.destroy);goog.exportProperty(shaka.media.PreloadManager.prototype,"waitForFinish",shaka.media.PreloadManager.prototype.waitForFinish);goog.exportProperty(shaka.media.PreloadManager.prototype,"getPrefetchedTextTrack",shaka.media.PreloadManager.prototype.getPrefetchedTextTrack);goog.exportProperty(shaka.media.PreloadManager.prototype,"getPrefetchedVariantTrack",shaka.media.PreloadManager.prototype.getPrefetchedVariantTrack);shaka.media.RegionObserver=class extends shaka.util.FakeEventTarget{constructor(a,b){super();this.timeline_=a;this.startsPastZero_=b;this.oldPosition_=new Map;var c=shaka.media.RegionObserver.RelativePosition_;a=c.BEFORE_THE_REGION;b=c.IN_THE_REGION;c=c.AFTER_THE_REGION;this.rules_=[{weWere:null,weAre:b,invoke:(d,e)=>this.onEvent_("enter",d,e)},{weWere:a,weAre:b,invoke:(d,e)=>this.onEvent_("enter",d,e)},{weWere:c,weAre:b,invoke:(d,e)=>this.onEvent_("enter",d,e)},{weWere:b,weAre:a,invoke:(d,e)=>this.onEvent_("exit",
d,e)},{weWere:b,weAre:c,invoke:(d,e)=>this.onEvent_("exit",d,e)},{weWere:a,weAre:c,invoke:(d,e)=>{if(e)this.onEvent_("skip",d,e);else this.onEvent_("enter",d,e),this.onEvent_("exit",d,e)}},{weWere:c,weAre:a,invoke:(d,e)=>this.onEvent_("skip",d,e)}];this.eventManager_=new shaka.util.EventManager;this.eventManager_.listen(this.timeline_,"regionremove",d=>{this.oldPosition_.delete(d.region)})}release(){this.timeline_=null;this.oldPosition_.clear();this.eventManager_.release();this.eventManager_=null;
super.release()}poll(a,b){const c=shaka.media.RegionObserver;if(!this.startsPastZero_||a!=0){this.startsPastZero_=!1;for(const d of this.timeline_.regions()){const e=this.oldPosition_.get(d),f=c.determinePositionRelativeTo_(d,a);this.oldPosition_.set(d,f);for(const g of this.rules_)g.weWere==e&&g.weAre==f&&g.invoke(d,b)}}}onEvent_(a,b,c){a=new shaka.util.FakeEvent(a,new Map([["region",b],["seeking",c]]));this.dispatchEvent(a)}static determinePositionRelativeTo_(a,b){const c=shaka.media.RegionObserver.RelativePosition_;
return b<a.startTime?c.BEFORE_THE_REGION:b>a.endTime?c.AFTER_THE_REGION:c.IN_THE_REGION}};shaka.media.RegionObserver.RelativePosition_={BEFORE_THE_REGION:1,IN_THE_REGION:2,AFTER_THE_REGION:3};/*
 @license
 Copyright 2013 Ali Al Dallal

 Licensed under the MIT license.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/
var mozilla={LanguageMapping:{ach:"Lwo",ady:"\u0410\u0434\u044b\u0433\u044d\u0431\u0437\u044d",af:"Afrikaans","af-NA":"Afrikaans (Namibia)","af-ZA":"Afrikaans (South Africa)",ak:"T\u0255\u0265i",ar:"\u0627\u0644\u0639\u0631\u0628\u064a\u0629","ar-AR":"\u0627\u0644\u0639\u0631\u0628\u064a\u0629","ar-MA":"\u0627\u0644\u0639\u0631\u0628\u064a\u0629","ar-SA":"\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u0627\u0644\u0633\u0639\u0648\u062f\u064a\u0629)","ay-BO":"Aymar aru",az:"Az\u0259rbaycan dili","az-AZ":"Az\u0259rbaycan dili",
"be-BY":"\u0411\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430\u044f",bg:"\u0411\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438","bg-BG":"\u0411\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438",bn:"\u09ac\u09be\u0982\u09b2\u09be","bn-IN":"\u09ac\u09be\u0982\u09b2\u09be (\u09ad\u09be\u09b0\u09a4)","bn-BD":"\u09ac\u09be\u0982\u09b2\u09be(\u09ac\u09be\u0982\u09b2\u09be\u09a6\u09c7\u09b6)","bs-BA":"Bosanski",ca:"Catal\u00e0","ca-ES":"Catal\u00e0",cak:"Maya Kaqchikel","ck-US":"\u13e3\u13b3\u13a9 (tsalagi)",
cs:"\u010ce\u0161tina","cs-CZ":"\u010ce\u0161tina",cy:"Cymraeg","cy-GB":"Cymraeg",da:"Dansk","da-DK":"Dansk",de:"Deutsch","de-AT":"Deutsch (\u00d6sterreich)","de-DE":"Deutsch (Deutschland)","de-CH":"Deutsch (Schweiz)",dsb:"Dolnoserb\u0161\u0107ina",el:"\u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac","el-GR":"\u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac",en:"English","en-GB":"English (UK)","en-AU":"English (Australia)","en-CA":"English (Canada)","en-IE":"English (Ireland)","en-IN":"English (India)",
"en-PI":"English (Pirate)","en-UD":"English (Upside Down)","en-US":"English (US)","en-ZA":"English (South Africa)","en@pirate":"English (Pirate)",eo:"Esperanto","eo-EO":"Esperanto",es:"Espa\u00f1ol","es-AR":"Espa\u00f1ol (Argentine)","es-419":"Espa\u00f1ol (Latinoam\u00e9rica)","es-CL":"Espa\u00f1ol (Chile)","es-CO":"Espa\u00f1ol (Colombia)","es-EC":"Espa\u00f1ol (Ecuador)","es-ES":"Espa\u00f1ol (Espa\u00f1a)","es-LA":"Espa\u00f1ol (Latinoam\u00e9rica)","es-NI":"Espa\u00f1ol (Nicaragua)","es-MX":"Espa\u00f1ol (M\u00e9xico)",
"es-US":"Espa\u00f1ol (Estados Unidos)","es-VE":"Espa\u00f1ol (Venezuela)",et:"eesti keel","et-EE":"Eesti (Estonia)",eu:"Euskara","eu-ES":"Euskara",fa:"\u0641\u0627\u0631\u0633\u06cc","fa-IR":"\u0641\u0627\u0631\u0633\u06cc","fb-LT":"Leet Speak",ff:"Fulah",fi:"Suomi","fi-FI":"Suomi","fo-FO":"F\u00f8royskt",fr:"Fran\u00e7ais","fr-CA":"Fran\u00e7ais (Canada)","fr-FR":"Fran\u00e7ais (France)","fr-BE":"Fran\u00e7ais (Belgique)","fr-CH":"Fran\u00e7ais (Suisse)","fy-NL":"Frysk",ga:"Gaeilge","ga-IE":"Gaeilge (Gaelic)",
gl:"Galego","gl-ES":"Galego","gn-PY":"Ava\u00f1e'\u1ebd","gu-IN":"\u0a97\u0ac1\u0a9c\u0ab0\u0abe\u0aa4\u0ac0","gx-GR":"\u1f19\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ae \u1f00\u03c1\u03c7\u03b1\u03af\u03b1",he:"\u05e2\u05d1\u05e8\u05d9\u05ea\u200f","he-IL":"\u05e2\u05d1\u05e8\u05d9\u05ea\u200f",hi:"\u0939\u093f\u0928\u094d\u0926\u0940","hi-IN":"\u0939\u093f\u0928\u094d\u0926\u0940",hr:"Hrvatski","hr-HR":"Hrvatski",hsb:"Hornjoserb\u0161\u0107ina",ht:"Krey\u00f2l",hu:"Magyar","hu-HU":"Magyar","hy-AM":"\u0540\u0561\u0575\u0565\u0580\u0565\u0576",
id:"Bahasa Indonesia","id-ID":"Bahasa Indonesia",is:"\u00cdslenska","is-IS":"\u00cdslenska (Iceland)",it:"Italiano","it-IT":"Italiano",ja:"\u65e5\u672c\u8a9e","ja-JP":"\u65e5\u672c\u8a9e","jv-ID":"Basa Jawa","ka-GE":"\u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8","kk-KZ":"\u049a\u0430\u0437\u0430\u049b\u0448\u0430",km:"\u1797\u17b6\u179f\u17b6\u1781\u17d2\u1798\u17c2\u179a","km-KH":"\u1797\u17b6\u179f\u17b6\u1781\u17d2\u1798\u17c2\u179a",kab:"Taqbaylit",kn:"\u0c95\u0ca8\u0ccd\u0ca8\u0ca1","kn-IN":"\u0c95\u0ca8\u0ccd\u0ca8\u0ca1 (India)",
ko:"\ud55c\uad6d\uc5b4","ko-KR":"\ud55c\uad6d\uc5b4 (\u97e9\u56fd)",ku:"Kurd\u00ee","ku-TR":"Kurd\u00ee",la:"Latin","la-VA":"Latin",lb:"L\u00ebtzebuergesch","li-NL":"L\u00e8mb\u00f6rgs",lt:"Lietuvi\u0173","lt-LT":"Lietuvi\u0173",lv:"Latvie\u0161u","lv-LV":"Latvie\u0161u",mai:"\u092e\u0948\u0925\u093f\u0932\u0940, \u09ae\u09c8\u09a5\u09bf\u09b2\u09c0","mg-MG":"Malagasy",mk:"\u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438","mk-MK":"\u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438 (\u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438)",
ml:"\u0d2e\u0d32\u0d2f\u0d3e\u0d33\u0d02","ml-IN":"\u0d2e\u0d32\u0d2f\u0d3e\u0d33\u0d02","mn-MN":"\u041c\u043e\u043d\u0433\u043e\u043b",mr:"\u092e\u0930\u093e\u0920\u0940","mr-IN":"\u092e\u0930\u093e\u0920\u0940",ms:"Bahasa Melayu","ms-MY":"Bahasa Melayu",mt:"Malti","mt-MT":"Malti",my:"\u1017\u1019\u102c\u1005\u1000\u102c",nb:"Norsk (bokm\u00e5l)","nb-NO":"Norsk (bokm\u00e5l)",ne:"\u0928\u0947\u092a\u093e\u0932\u0940","ne-NP":"\u0928\u0947\u092a\u093e\u0932\u0940",nl:"Nederlands","nl-BE":"Nederlands (Belgi\u00eb)",
"nl-NL":"Nederlands (Nederland)","nn-NO":"Norsk (nynorsk)",no:"Norsk",oc:"Occitan","or-IN":"\u0b13\u0b21\u0b3c\u0b3f\u0b06",pa:"\u0a2a\u0a70\u0a1c\u0a3e\u0a2c\u0a40","pa-IN":"\u0a2a\u0a70\u0a1c\u0a3e\u0a2c\u0a40 (\u0a2d\u0a3e\u0a30\u0a24 \u0a28\u0a42\u0a70)",pl:"Polski","pl-PL":"Polski","ps-AF":"\u067e\u069a\u062a\u0648",pt:"Portugu\u00eas","pt-BR":"Portugu\u00eas (Brasil)","pt-PT":"Portugu\u00eas (Portugal)","qu-PE":"Qhichwa","rm-CH":"Rumantsch",ro:"Rom\u00e2n\u0103","ro-RO":"Rom\u00e2n\u0103",ru:"\u0420\u0443\u0441\u0441\u043a\u0438\u0439",
"ru-RU":"\u0420\u0443\u0441\u0441\u043a\u0438\u0439","sa-IN":"\u0938\u0902\u0938\u094d\u0915\u0943\u0924\u092e\u094d","se-NO":"Davvis\u00e1megiella","si-LK":"\u0db4\u0dc5\u0dcf\u0dad",sk:"Sloven\u010dina","sk-SK":"Sloven\u010dina (Slovakia)",sl:"Sloven\u0161\u010dina","sl-SI":"Sloven\u0161\u010dina","so-SO":"Soomaaliga",sq:"Shqip","sq-AL":"Shqip",sr:"\u0421\u0440\u043f\u0441\u043a\u0438","sr-RS":"\u0421\u0440\u043f\u0441\u043a\u0438 (Serbia)",su:"Basa Sunda",sv:"Svenska","sv-SE":"Svenska",sw:"Kiswahili",
"sw-KE":"Kiswahili",ta:"\u0ba4\u0bae\u0bbf\u0bb4\u0bcd","ta-IN":"\u0ba4\u0bae\u0bbf\u0bb4\u0bcd",te:"\u0c24\u0c46\u0c32\u0c41\u0c17\u0c41","te-IN":"\u0c24\u0c46\u0c32\u0c41\u0c17\u0c41",tg:"\u0437\u0430\u0431\u043e\u0301\u043d\u0438 \u0442\u043e\u04b7\u0438\u043a\u04e3\u0301","tg-TJ":"\u0442\u043e\u04b7\u0438\u043a\u04e3",th:"\u0e20\u0e32\u0e29\u0e32\u0e44\u0e17\u0e22","th-TH":"\u0e20\u0e32\u0e29\u0e32\u0e44\u0e17\u0e22 (\u0e1b\u0e23\u0e30\u0e40\u0e17\u0e28\u0e44\u0e17\u0e22)",tl:"Filipino","tl-PH":"Filipino",
tlh:"tlhIngan-Hol",tr:"T\u00fcrk\u00e7e","tr-TR":"T\u00fcrk\u00e7e","tt-RU":"\u0442\u0430\u0442\u0430\u0440\u0447\u0430",uk:"\u0423\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a\u0430","uk-UA":"\u0423\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a\u0430",ur:"\u0627\u0631\u062f\u0648","ur-PK":"\u0627\u0631\u062f\u0648",uz:"O'zbek","uz-UZ":"O'zbek",vi:"Ti\u1ebfng Vi\u1ec7t","vi-VN":"Ti\u1ebfng Vi\u1ec7t","xh-ZA":"isiXhosa",yi:"\u05d9\u05d9\u05b4\u05d3\u05d9\u05e9","yi-DE":"\u05d9\u05d9\u05b4\u05d3\u05d9\u05e9 (German)",
zh:"\u4e2d\u6587","zh-HANS":"\u4e2d\u6587\u7b80\u4f53","zh-HANT":"\u4e2d\u6587\u7e41\u9ad4","zh-CN":"\u4e2d\u6587\uff08\u4e2d\u56fd\uff09","zh-HK":"\u4e2d\u6587\uff08\u9999\u6e2f\uff09","zh-SG":"\u4e2d\u6587\uff08\u65b0\u52a0\u5761\uff09","zh-TW":"\u4e2d\u6587\uff08\u53f0\u7063\uff09","zu-ZA":"isiZulu"}};for(let a of Object.keys(mozilla.LanguageMapping))mozilla.LanguageMapping[a.toLowerCase()]=mozilla.LanguageMapping[a];shaka.text.Utils=class{static flattenPayload_(a,b){if(a.lineBreak)return"\n";if(a.nestedCues.length)return a.nestedCues.map(g=>shaka.text.Utils.flattenPayload_(g,a)).join("");if(!a.payload)return a.payload;const c=[];var d=a.fontWeight>=shaka.text.Cue.fontWeight.BOLD,e=a.fontStyle==shaka.text.Cue.fontStyle.ITALIC;const f=a.textDecoration.includes(shaka.text.Cue.textDecoration.UNDERLINE);d&&c.push(["b"]);e&&c.push(["i"]);f&&c.push(["u"]);e=a.color;e==""&&b&&(e=b.color);d="";(e=shaka.text.Utils.getColorName_(e))&&
(d+=`.${e}`);e=a.backgroundColor;e==""&&b&&(e=b.backgroundColor);(b=shaka.text.Utils.getColorName_(e))&&(d+=`.bg_${b}`);d&&c.push(["c",d]);return c.reduceRight((g,[h,k=""])=>`<${h}${k}>${g}</${h}>`,a.payload)}static getColorName_(a){a=a.toLowerCase();const b=a.replace(/\s/g,"").match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i);b?a="#"+(parseInt(b[1],10)|256).toString(16).slice(1)+(parseInt(b[2],10)|256).toString(16).slice(1)+(parseInt(b[3],10)|256).toString(16).slice(1):a.startsWith("#")&&a.length>
7&&(a=a.slice(0,7));switch(a){case "white":case "#fff":case "#ffffff":return"white";case "lime":case "#0f0":case "#00ff00":return"lime";case "cyan":case "#0ff":case "#00ffff":return"cyan";case "red":case "#f00":case "#ff0000":return"red";case "yellow":case "#ff0":case "#ffff00":return"yellow";case "magenta":case "#f0f":case "#ff00ff":return"magenta";case "blue":case "#00f":case "#0000ff":return"blue";case "black":case "#000":case "#000000":return"black"}return null}static getCuesToFlatten(a,b){const c=
[];for(const d of shaka.text.Utils.removeDuplicates(a))d.isContainer?c.push(...shaka.text.Utils.getCuesToFlatten(d.nestedCues,d)):(a=d.clone(),a.nestedCues=[],a.payload=shaka.text.Utils.flattenPayload_(d,b),c.push(a));return c}static removeDuplicates(a){const b=[];for(const c of a)b.some(d=>shaka.text.Cue.equal(c,d))||b.push(c);return b}static mapShakaCueToNativeCue(a){if(a.startTime>=a.endTime)return shaka.log.warning("Invalid cue times: "+a.startTime+" - "+a.endTime),null;const b=shaka.text.Cue,
c=new VTTCue(a.startTime,a.endTime,a.payload),d=e=>{let f=5381,g=e.length;for(;g;)f=f*33^e.charCodeAt(--g);return(f>>>0).toString()};c.id=d(a.startTime.toString())+d(a.endTime.toString())+d(a.payload);c.lineAlign=a.lineAlign;c.positionAlign=a.positionAlign;a.size&&(c.size=a.size);try{c.align=a.textAlign}catch(e){}a.textAlign=="center"&&c.align!="center"&&(c.align="middle");a.writingMode==b.writingMode.VERTICAL_LEFT_TO_RIGHT?c.vertical="lr":a.writingMode==b.writingMode.VERTICAL_RIGHT_TO_LEFT&&(c.vertical=
"rl");a.lineInterpretation==b.lineInterpretation.PERCENTAGE&&(c.snapToLines=!1);a.line!=null&&(c.line=a.line);a.position!=null&&(c.position=a.position);return c}static mapNativeCueToShakaCue(a){if(a.endTime===Infinity||a.endTime<a.startTime)return null;const b=new shaka.text.Cue(a.startTime,a.endTime,a.text);b.line=typeof a.line==="number"?a.line:null;a.lineAlign&&(b.lineAlign=a.lineAlign);b.lineInterpretation=a.snapToLines?shaka.text.Cue.lineInterpretation.LINE_NUMBER:shaka.text.Cue.lineInterpretation.PERCENTAGE;
b.position=typeof a.position==="number"?a.position:null;a.positionAlign&&(b.positionAlign=a.positionAlign);b.size=a.size;b.textAlign=a.align;a.vertical==="lr"?b.writingMode=shaka.text.Cue.writingMode.VERTICAL_LEFT_TO_RIGHT:a.vertical==="rl"&&(b.writingMode=shaka.text.Cue.writingMode.VERTICAL_RIGHT_TO_LEFT);a.region&&(b.region.id=a.region.id,b.region.height=a.region.lines,b.region.heightUnits=shaka.text.CueRegion.units.LINES,b.region.regionAnchorX=a.region.regionAnchorX,b.region.regionAnchorY=a.region.regionAnchorY,
b.region.scroll=a.region.scroll,b.region.viewportAnchorX=a.region.viewportAnchorX,b.region.viewportAnchorY=a.region.viewportAnchorY,b.region.viewportAnchorUnits=shaka.text.CueRegion.units.PERCENTAGE,b.region.width=a.region.width,b.region.widthUnits=shaka.text.CueRegion.units.PERCENTAGE);shaka.text.Cue.parseCuePayload(b);return b}static appendCuesToTextTrack(a,b){var c=shaka.text.Utils.getCuesToFlatten(b);const d=[];b=a.cues?Array.from(a.cues):[];for(const e of c)!b.some(f=>f.startTime==e.startTime&&
f.endTime==e.endTime&&f.text==e.payload?!0:!1)&&e.payload&&(c=shaka.text.Utils.mapShakaCueToNativeCue(e))&&d.push(c);b=d.slice().sort((e,f)=>e.startTime!=f.startTime?e.startTime-f.startTime:e.endTime!=f.endTime?e.endTime-f.startTime:"line"in VTTCue.prototype?d.indexOf(f)-d.indexOf(e):d.indexOf(e)-d.indexOf(f));for(const e of b)a.addCue(e)}static removeCuesFromTextTrack(a,b){let c=!1;a.mode==="disabled"&&(c=!0,a.mode="hidden",goog.asserts.assert(a.cues,'Cues should be accessible when mode is set to "hidden".'));
let d=0;for(;d<a.cues.length;){const e=a.cues[d];b(e)?a.removeCue(e):d++}c&&(a.mode="disabled")}};shaka.text.NativeTextDisplayer=class{constructor(a){this.player_=a;this.eventManager_=new shaka.util.EventManager;this.video_=null;this.trackNodes_=new Map;this.trackId_=-1;this.visible_=!1;this.timer_=null;this.onUnloading_=()=>{this.timer_?.stop();this.timer_=null;this.eventManager_.unlisten(this.player_,shaka.util.FakeEvent.EventName.TextChanged,this.onTextChanged_);this.eventManager_.unlisten(this.video_.textTracks,"change",this.onChange_);for(const b of this.trackNodes_.values())b.remove();this.trackNodes_.clear();
this.trackId_=-1;this.video_=null};this.onTextChanged_=()=>{const b=new Map;var c=this.player_.getTextTracks();for(var d of c){if(this.trackNodes_.has(d.id))c=this.trackNodes_.get(d.id),d.active||c.track.mode==="disabled"||(c.track.mode="disabled"),this.trackNodes_.delete(d.id);else{c=this.video_.ownerDocument.createElement("track");c.kind=shaka.text.NativeTextDisplayer.getTrackKind_(d);c.label=shaka.text.NativeTextDisplayer.getTrackLabel_(d);if(d.language)if(d.language in mozilla.LanguageMapping)c.srclang=
d.language;else{const e=shaka.util.LanguageUtils.getBase(d.language);c.srclang=e??"und"}else c.srclang="und";c.src="data:,WEBVTT";c.track.mode="disabled";this.video_.appendChild(c)}b.set(d.id,c);d.active&&(this.trackId_=d.id)}for(const e of this.trackNodes_.values())e.remove();this.trackId_>-1&&(b.has(this.trackId_)?(d=b.get(this.trackId_).track,d.mode==="disabled"&&(d.mode=this.visible_?"showing":"hidden")):this.trackId_=-1);this.trackNodes_=b};this.onChange_=()=>{if(!this.timer_){var b=this.video_;
this.timer_=(new shaka.util.Timer(()=>{this.timer_=null;if(this.video_===b){var c=-1,d=!1;if(this.trackNodes_.has(this.trackId_)){const e=this.trackNodes_.get(this.trackId_);e.track.mode==="showing"?(c=this.trackId_,d=!0):e.track.mode==="hidden"&&(c=this.trackId_)}if(!d)for(const [e,f]of this.trackNodes_)if(f.track.mode==="showing"){c=e;break}else c<0&&f.track.mode==="hidden"&&(c=e);for(const [e,f]of this.trackNodes_)e!==c&&f.track.mode!=="disabled"&&(f.track.mode="disabled");this.trackId_!==c&&(this.trackId_=
c,c>-1&&this.player_.selectTextTrack({id:c}));this.player_.setTextTrackVisibility(c>-1&&this.trackNodes_.get(c).track.mode==="showing")}})).tickAfter(0)}};this.eventManager_.listen(a,shaka.util.FakeEvent.EventName.Loaded,()=>this.enableTextDisplayer());this.enableTextDisplayer()}configure(a){}remove(a,b){if(this.player_)this.trackNodes_.has(this.trackId_)&&shaka.text.Utils.removeCuesFromTextTrack(this.trackNodes_.get(this.trackId_).track,c=>c.startTime<b&&c.endTime>a);else return!1;return!0}append(a){this.trackNodes_.has(this.trackId_)&&
shaka.text.Utils.appendCuesToTextTrack(this.trackNodes_.get(this.trackId_).track,a)}destroy(){if(this.player_){if(this.video_)this.onUnloading_();this.player_=null}this.timer_?.stop();this.timer_=null;this.eventManager_?.release();this.eventManager_=null;return Promise.resolve()}isTextVisible(){return this.visible_}setTextVisibility(a){this.visible_=a;if(this.trackNodes_.has(this.trackId_)){var b=this.trackNodes_.get(this.trackId_).track;b.mode!=="disabled"&&(a=a?"showing":"hidden",b.mode!==a&&(b.mode=
a))}else if(this.player_&&this.player_.getLoadMode()===3)if(b=Array.from(this.player_.getMediaElement().textTracks).filter(c=>["captions","subtitles","forced"].includes(c.kind)),a){a=null;for(const c of b)if(c.mode==="showing"){a=null;break}else a||c.mode!=="hidden"||(a=c);a&&(a.mode="showing")}else for(const c of b)c.mode==="showing"&&(c.mode="hidden")}setTextLanguage(a){}enableTextDisplayer(){!this.video_&&this.player_&&this.player_.getLoadMode()===2&&(this.video_=this.player_.getMediaElement(),
this.eventManager_.listenOnce(this.player_,shaka.util.FakeEvent.EventName.Unloading,this.onUnloading_),this.eventManager_.listen(this.player_,shaka.util.FakeEvent.EventName.TextChanged,this.onTextChanged_),this.eventManager_.listen(this.video_.textTracks,"change",this.onChange_),this.onTextChanged_())}static getTrackKind_(a){const b=shaka.device.DeviceFactory.getDevice();return a.forced&&b.getBrowserEngine()===shaka.device.IDevice.BrowserEngine.WEBKIT?"forced":a.kind===shaka.util.ManifestParserUtils.TextStreamKind.CLOSED_CAPTION?
"captions":"subtitles"}static getTrackLabel_(a){let b;if(a.label)b=a.label;else if(a.language)if(a.language in mozilla.LanguageMapping)b=mozilla.LanguageMapping[a.language];else{const c=shaka.util.LanguageUtils.getBase(a.language);c in mozilla.LanguageMapping&&(b=`${mozilla.LanguageMapping[c]} (${a.language})`)}b||(b=a.originalTextId,a.language&&a.language!==a.originalTextId&&(b+=` (${a.language})`));return b}};goog.exportSymbol("shaka.text.NativeTextDisplayer",shaka.text.NativeTextDisplayer);
goog.exportProperty(shaka.text.NativeTextDisplayer.prototype,"enableTextDisplayer",shaka.text.NativeTextDisplayer.prototype.enableTextDisplayer);goog.exportProperty(shaka.text.NativeTextDisplayer.prototype,"setTextLanguage",shaka.text.NativeTextDisplayer.prototype.setTextLanguage);goog.exportProperty(shaka.text.NativeTextDisplayer.prototype,"setTextVisibility",shaka.text.NativeTextDisplayer.prototype.setTextVisibility);goog.exportProperty(shaka.text.NativeTextDisplayer.prototype,"isTextVisible",shaka.text.NativeTextDisplayer.prototype.isTextVisible);
goog.exportProperty(shaka.text.NativeTextDisplayer.prototype,"destroy",shaka.text.NativeTextDisplayer.prototype.destroy);goog.exportProperty(shaka.text.NativeTextDisplayer.prototype,"append",shaka.text.NativeTextDisplayer.prototype.append);goog.exportProperty(shaka.text.NativeTextDisplayer.prototype,"remove",shaka.text.NativeTextDisplayer.prototype.remove);goog.exportProperty(shaka.text.NativeTextDisplayer.prototype,"configure",shaka.text.NativeTextDisplayer.prototype.configure);shaka.text.SimpleTextDisplayer=class{constructor(a,b){shaka.Deprecate.deprecateFeature(5,"SimpleTextDisplayer","Please migrate to NativeTextDisplayer");this.video_=a;this.textTrackLabel_=b;this.textTrack_=null;for(const c of Array.from(this.video_.textTracks))c.kind!=="metadata"&&c.kind!=="chapters"&&(c.mode="disabled",c.label==this.textTrackLabel_&&(this.textTrack_=c));this.textTrack_&&(this.textTrack_.mode="hidden")}configure(a){}remove(a,b){if(!this.textTrack_)return!1;shaka.text.Utils.removeCuesFromTextTrack(this.textTrack_,
c=>c.startTime<b&&c.endTime>a);return!0}append(a){this.textTrack_&&shaka.text.Utils.appendCuesToTextTrack(this.textTrack_,a)}destroy(){this.textTrack_&&(shaka.text.Utils.removeCuesFromTextTrack(this.textTrack_,a=>!0),this.textTrack_.mode="disabled");this.textTrack_=this.video_=null;return Promise.resolve()}isTextVisible(){return this.textTrack_?this.textTrack_.mode=="showing":!1}setTextVisibility(a){a&&!this.textTrack_&&this.createTextTrack_();this.textTrack_&&(this.textTrack_.mode=a?"showing":"hidden")}setTextLanguage(a){}enableTextDisplayer(){this.createTextTrack_()}createTextTrack_(){this.video_&&
!this.textTrack_&&(this.textTrack_=this.video_.addTextTrack("subtitles",this.textTrackLabel_),this.textTrack_.mode="hidden")}};goog.exportSymbol("shaka.text.SimpleTextDisplayer",shaka.text.SimpleTextDisplayer);goog.exportProperty(shaka.text.SimpleTextDisplayer.prototype,"enableTextDisplayer",shaka.text.SimpleTextDisplayer.prototype.enableTextDisplayer);goog.exportProperty(shaka.text.SimpleTextDisplayer.prototype,"setTextLanguage",shaka.text.SimpleTextDisplayer.prototype.setTextLanguage);
goog.exportProperty(shaka.text.SimpleTextDisplayer.prototype,"setTextVisibility",shaka.text.SimpleTextDisplayer.prototype.setTextVisibility);goog.exportProperty(shaka.text.SimpleTextDisplayer.prototype,"isTextVisible",shaka.text.SimpleTextDisplayer.prototype.isTextVisible);goog.exportProperty(shaka.text.SimpleTextDisplayer.prototype,"destroy",shaka.text.SimpleTextDisplayer.prototype.destroy);goog.exportProperty(shaka.text.SimpleTextDisplayer.prototype,"append",shaka.text.SimpleTextDisplayer.prototype.append);
goog.exportProperty(shaka.text.SimpleTextDisplayer.prototype,"remove",shaka.text.SimpleTextDisplayer.prototype.remove);goog.exportProperty(shaka.text.SimpleTextDisplayer.prototype,"configure",shaka.text.SimpleTextDisplayer.prototype.configure);shaka.text.StubTextDisplayer=class{configure(a){}remove(a,b){}append(a){}destroy(){}isTextVisible(){return!1}setTextVisibility(a){}setTextLanguage(a){}enableTextDisplayer(){}};goog.exportSymbol("shaka.text.StubTextDisplayer",shaka.text.StubTextDisplayer);goog.exportProperty(shaka.text.StubTextDisplayer.prototype,"enableTextDisplayer",shaka.text.StubTextDisplayer.prototype.enableTextDisplayer);goog.exportProperty(shaka.text.StubTextDisplayer.prototype,"setTextLanguage",shaka.text.StubTextDisplayer.prototype.setTextLanguage);
goog.exportProperty(shaka.text.StubTextDisplayer.prototype,"setTextVisibility",shaka.text.StubTextDisplayer.prototype.setTextVisibility);goog.exportProperty(shaka.text.StubTextDisplayer.prototype,"isTextVisible",shaka.text.StubTextDisplayer.prototype.isTextVisible);goog.exportProperty(shaka.text.StubTextDisplayer.prototype,"destroy",shaka.text.StubTextDisplayer.prototype.destroy);goog.exportProperty(shaka.text.StubTextDisplayer.prototype,"append",shaka.text.StubTextDisplayer.prototype.append);
goog.exportProperty(shaka.text.StubTextDisplayer.prototype,"remove",shaka.text.StubTextDisplayer.prototype.remove);goog.exportProperty(shaka.text.StubTextDisplayer.prototype,"configure",shaka.text.StubTextDisplayer.prototype.configure);shaka.text.UITextDisplayer=class{constructor(a,b){goog.asserts.assert(b,"videoContainer should be valid.");this.isTextVisible_=!1;this.cues_=[];this.video_=a;this.videoContainer_=b;this.config_=this.aspectRatio_=null;this.textContainer_=shaka.util.Dom.createHTMLElement("div");this.textContainer_.classList.add("shaka-text-container");this.textContainer_.style.textAlign="center";this.textContainer_.style.display="flex";this.textContainer_.style.flexDirection="column";this.textContainer_.style.alignItems=
"center";this.textContainer_.style.justifyContent="flex-end";this.captionsTimer_=new shaka.util.Timer(()=>{this.video_.paused||this.updateCaptions_()});this.configureCaptionsTimer_();this.currentCuesMap_=new Map;this.eventManager_=new shaka.util.EventManager;this.eventManager_.listen(document,"fullscreenchange",()=>{this.updateCaptions_(!0)});this.eventManager_.listen(this.video_,"seeking",()=>{this.updateCaptions_(!0)});this.eventManager_.listen(this.video_,"ratechange",()=>{this.configureCaptionsTimer_()});
this.eventManager_.listen(this.video_,"resize",()=>{var c=this.video_;const d=c.videoWidth;c=c.videoHeight;this.aspectRatio_=d&&c?d/c:null});this.pendingResize_=!1;this.resizeObserver_=null;"ResizeObserver"in window&&(this.resizeObserver_=new ResizeObserver(()=>{this.pendingResize_||(this.pendingResize_=!0,requestAnimationFrame(()=>{this.pendingResize_=!1;this.textContainer_&&this.textContainer_.parentElement&&this.isTextVisible_&&this.updateCaptions_(!0)}))}),goog.asserts.assert(this.videoContainer_,
"this.videoContainer_ must be non-null"),this.resizeObserver_.observe(this.videoContainer_));this.regionElements_=new Map}configure(a){this.config_=a;this.configureCaptionsTimer_();this.updateCaptions_(!0)}append(a){const b=[...this.cues_];for(const c of shaka.text.Utils.removeDuplicates(a))b.some(d=>shaka.text.Cue.equal(d,c))||this.cues_.push(c);this.cues_.length&&this.configureCaptionsTimer_();this.updateCaptions_()}destroy(){if(!this.textContainer_)return Promise.resolve();this.textContainer_.parentElement&&
this.videoContainer_.removeChild(this.textContainer_);this.textContainer_=null;this.isTextVisible_=!1;this.cues_=[];this.captionsTimer_&&(this.captionsTimer_.stop(),this.captionsTimer_=null);this.currentCuesMap_.clear();this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null);this.resizeObserver_&&(this.resizeObserver_.disconnect(),this.resizeObserver_=null);return Promise.resolve()}remove(a,b){if(!this.textContainer_)return!1;const c=this.cues_.length;this.cues_=this.cues_.filter(d=>
d.startTime<a||d.endTime>=b);this.updateCaptions_(c>this.cues_.length);this.cues_.length||this.configureCaptionsTimer_();return!0}isTextVisible(){return this.isTextVisible_}setTextVisibility(a){(this.isTextVisible_=a)?(this.textContainer_.parentElement||this.videoContainer_.appendChild(this.textContainer_),this.updateCaptions_(!0)):this.textContainer_.parentElement&&this.videoContainer_.removeChild(this.textContainer_)}setTextLanguage(a){a&&a!="und"?this.textContainer_.setAttribute("lang",a):this.textContainer_.setAttribute("lang",
"")}enableTextDisplayer(){}configureCaptionsTimer_(){this.captionsTimer_&&(this.cues_.length?this.captionsTimer_.tickEvery((this.config_?this.config_.captionsUpdatePeriod:.25)/Math.max(1,Math.abs(this.video_.playbackRate))):this.captionsTimer_.stop())}isElementUnderTextContainer_(a){for(;a!=null;){if(a==this.textContainer_)return!0;a=a.parentElement}return!1}updateCuesRecursive_(a,b,c,d){let e=!1;const f=[],g=[];for(const h of a){d.push(h);a=this.currentCuesMap_.get(h);const k=h.startTime<=c&&h.endTime>
c;let l=a?a.wrapper:null;a&&(f.push(a.cueElement),a.regionElement&&f.push(a.regionElement),k||(e=!0,this.currentCuesMap_.delete(h),a=null));k&&(g.push(h),a?this.isElementUnderTextContainer_(l)||(e=!0):(this.createCue_(h,d),a=this.currentCuesMap_.get(h),l=a.wrapper,e=!0));h.nestedCues.length>0&&l&&this.updateCuesRecursive_(h.nestedCues,l,c,d);a=d.pop();goog.asserts.assert(a==h,"Parent cues should be kept in order")}if(e){for(const h of f)h.parentElement&&h.parentElement.removeChild(h);g.sort((h,k)=>
h.startTime!=k.startTime?h.startTime-k.startTime:h.endTime-k.endTime);for(const h of g)c=this.currentCuesMap_.get(h),goog.asserts.assert(c,"cueRegistry should exist."),c.regionElement?(c.regionElement.contains(b)&&c.regionElement.removeChild(b),b.appendChild(c.regionElement),c.regionElement.appendChild(c.cueElement)):b.appendChild(c.cueElement)}}updateCaptions_(a=!1){if(this.textContainer_){var b=this.video_.currentTime;if(!this.isTextVisible_||a){for(const c of this.regionElements_.values())shaka.util.Dom.removeAllChildren(c);
shaka.util.Dom.removeAllChildren(this.textContainer_);this.currentCuesMap_.clear();this.regionElements_.clear()}if(this.isTextVisible_){a=new Map;if(goog.DEBUG)for(const c of this.currentCuesMap_.keys())a.set(c,this.currentCuesMap_.get(c));this.updateCuesRecursive_(this.cues_,this.textContainer_,b,[]);if(goog.DEBUG)for(const c of a.keys())this.currentCuesMap_.has(c)||(b=a.get(c).cueElement,goog.asserts.assert(!b.parentNode,"Cue was not properly removed!"))}}}generateRegionId_(a){const b=shaka.text.CueRegion.units.PERCENTAGE;
return`${a.id}_${a.width}x${a.height}${a.heightUnits==b?"%":"px"}-${a.viewportAnchorX}x${a.viewportAnchorY}${a.viewportAnchorUnits==b?"%":"px"}-${a.regionAnchorX}x${a.regionAnchorY}`}getRegionElement_(a){var b=a.region,c=this.aspectRatio_===4/3?2.5:1.9;const d=this.generateRegionId_(b);if(this.regionElements_.has(d))return this.regionElements_.get(d);const e=shaka.util.Dom.createHTMLElement("span");var f=shaka.text.CueRegion.units.LINES,g=shaka.text.CueRegion.units.PERCENTAGE,h=shaka.text.CueRegion.units.PX;
let k=b.heightUnits==g?"%":"px",l=b.widthUnits==g?"%":"px";const m=b.viewportAnchorUnits==g?"%":"px";e.id="shaka-text-region---"+d;e.classList.add("shaka-text-region");e.style.position="absolute";g=b.height;var n=b.width;b.heightUnits===f&&(g=b.height*5.33,k="%");b.widthUnits===f&&(n=b.width*c,l="%");e.style.height=g+k;e.style.width=n+l;b.viewportAnchorUnits===f?(c=b.viewportAnchorY/75*100,f=b.viewportAnchorX/(this.aspectRatio_===4/3?160:210)*100,c-=b.regionAnchorY*g/100,f-=b.regionAnchorX*n/100,
e.style.top=c+"%",e.style.left=f+"%"):(e.style.top=b.viewportAnchorY-b.regionAnchorY*g/100+m,e.style.left=b.viewportAnchorX-b.regionAnchorX*n/100+m);b.heightUnits!==h&&b.widthUnits!==h&&b.viewportAnchorUnits!==h&&(b=parseInt(e.style.top.slice(0,-1),10)||0,g=parseInt(e.style.left.slice(0,-1),10)||0,h=parseInt(e.style.height.slice(0,-1),10)||0,n=parseInt(e.style.width.slice(0,-1),10)||0,g=Math.max(0,Math.min(100-n,g)),e.style.top=Math.max(0,Math.min(100-h,b))+"%",e.style.left=g+"%");e.style.display=
"flex";e.style.flexDirection="column";e.style.alignItems="center";e.style.justifyContent=a.displayAlign==shaka.text.Cue.displayAlign.BEFORE?"flex-start":a.displayAlign==shaka.text.Cue.displayAlign.CENTER?"center":"flex-end";this.regionElements_.set(d,e);return e}createCue_(a,b){var c=b.length>1,d=c?"span":"div";a.lineBreak&&(d="br");a.rubyTag&&(d=a.rubyTag);c=!c&&a.nestedCues.length>0;const e=shaka.util.Dom.createHTMLElement(d);d!="br"&&this.setCaptionStyles_(e,a,b,c);b=null;a.region&&a.region.id&&
(b=this.getRegionElement_(a));d=e;c&&(d=shaka.util.Dom.createHTMLElement("span"),d.classList.add("shaka-text-wrapper"),d.style.backgroundColor=a.backgroundColor,d.style.lineHeight="normal",e.appendChild(d));this.currentCuesMap_.set(a,{cueElement:e,wrapper:d,regionElement:b})}computeCuePositionAlignment_(a){const b=shaka.text.Cue,{direction:c,positionAlign:d,textAlign:e}=a;return d!==b.positionAlign.AUTO?d:e===b.textAlign.LEFT||e===b.textAlign.START&&c===b.direction.HORIZONTAL_LEFT_TO_RIGHT||e===b.textAlign.END&&
c===b.direction.HORIZONTAL_RIGHT_TO_LEFT?b.positionAlign.LEFT:e===b.textAlign.RIGHT||e===b.textAlign.START&&c===b.direction.HORIZONTAL_RIGHT_TO_LEFT||e===b.textAlign.END&&c===b.direction.HORIZONTAL_LEFT_TO_RIGHT?b.positionAlign.RIGHT:b.positionAlign.CENTER}setCaptionStyles_(a,b,c,d){const e=shaka.text.Cue,f=a.style;var g=b.nestedCues.length==0,h=c.length>1;f.whiteSpace="pre-wrap";var k=b.payload.replace(/\s+$/g,l=>"\u00a0".repeat(l.length));f.webkitTextStrokeColor=b.textStrokeColor;f.webkitTextStrokeWidth=
b.textStrokeWidth;f.color=b.color;f.direction=b.direction;f.opacity=b.opacity;f.paddingLeft=shaka.text.UITextDisplayer.convertLengthValue_(b.linePadding,b,this.videoContainer_);f.paddingRight=shaka.text.UITextDisplayer.convertLengthValue_(b.linePadding,b,this.videoContainer_);f.textCombineUpright=b.textCombineUpright;f.textShadow=b.textShadow;if(b.backgroundImage)k=b.backgroundImage.replace(/['"()\\]/g,""),f.backgroundImage="url('"+k+"')",f.backgroundRepeat="no-repeat",f.backgroundSize="contain",
f.backgroundPosition="center",b.backgroundColor&&(f.backgroundColor=b.backgroundColor),f.width="100%",f.height="100%";else{let l;b.nestedCues.length?l=a:(l=shaka.util.Dom.createHTMLElement("span"),a.appendChild(l));b.border&&(l.style.border=b.border);d||((a=shaka.text.UITextDisplayer.inheritProperty_(c,m=>m.backgroundColor))?l.style.backgroundColor=a:k&&(l.style.backgroundColor="rgba(0, 0, 0, 0.8)"));k&&(l.setAttribute("translate","no"),l.textContent=k)}if(h&&!c[c.length-1].isContainer)f.display=
"inline";else{f.display="flex";f.flexDirection="column";f.alignItems="center";if(b.textAlign==e.textAlign.LEFT||b.textAlign==e.textAlign.START)f.width="100%",f.alignItems="flex-start";else if(b.textAlign==e.textAlign.RIGHT||b.textAlign==e.textAlign.END)f.width="100%",f.alignItems="flex-end";f.justifyContent=b.displayAlign==e.displayAlign.BEFORE?"flex-start":b.displayAlign==e.displayAlign.CENTER?"center":"flex-end"}g||(f.margin="0");f.fontFamily=b.fontFamily;f.fontWeight=b.fontWeight.toString();f.fontStyle=
b.fontStyle;f.letterSpacing=b.letterSpacing;c=this.config_?this.config_.fontScaleFactor:1;if(c!==1||b.fontSize)f.fontSize=shaka.text.UITextDisplayer.convertLengthValue_(b.fontSize||"1em",b,this.videoContainer_,c);c=b.line;c!=null&&(g=b.lineInterpretation,g==e.lineInterpretation.LINE_NUMBER&&(g=e.lineInterpretation.PERCENTAGE,h=16,this.aspectRatio_&&this.aspectRatio_<1&&(h=32),c=c<0?100+c/h*100:c/h*100),g==e.lineInterpretation.PERCENTAGE&&(f.position="absolute",b.writingMode==e.writingMode.HORIZONTAL_TOP_TO_BOTTOM?
(f.width="100%",b.lineAlign==e.lineAlign.START?f.top=c+"%":b.lineAlign==e.lineAlign.END&&(f.bottom=100-c+"%")):b.writingMode==e.writingMode.VERTICAL_LEFT_TO_RIGHT?(f.height="100%",b.lineAlign==e.lineAlign.START?f.left=c+"%":b.lineAlign==e.lineAlign.END&&(f.right=100-c+"%")):(f.height="100%",b.lineAlign==e.lineAlign.START?f.right=c+"%":b.lineAlign==e.lineAlign.END&&(f.left=100-c+"%"))));f.lineHeight=b.lineHeight;c=this.computeCuePositionAlignment_(b);c==e.positionAlign.LEFT?(f.cssFloat="left",b.position!==
null&&(f.position="absolute",b.writingMode==e.writingMode.HORIZONTAL_TOP_TO_BOTTOM?(f.left=b.position+"%",f.width="auto"):f.top=b.position+"%")):c==e.positionAlign.RIGHT?(f.cssFloat="right",b.position!==null&&(f.position="absolute",b.writingMode==e.writingMode.HORIZONTAL_TOP_TO_BOTTOM?(f.right=100-b.position+"%",f.width="auto"):f.bottom=b.position+"%")):b.position!==null&&b.position!=50&&(f.position="absolute",b.writingMode==e.writingMode.HORIZONTAL_TOP_TO_BOTTOM?(f.left=b.position+"%",f.width="auto"):
f.top=b.position+"%",b.size&&(f.transform="translateX(-50%)"));f.textAlign=b.textAlign;f.textDecoration=b.textDecoration.join(" ");f.writingMode=b.writingMode;"writingMode"in document.documentElement.style&&f.writingMode==b.writingMode||(f.webkitWritingMode=b.writingMode);b.size&&(b.writingMode==e.writingMode.HORIZONTAL_TOP_TO_BOTTOM?f.width=b.size+"%":f.height=b.size+"%")}static getLengthValueInfo_(a){return(a=(new RegExp(/(\d*\.?\d+)([a-z]+|%+)/)).exec(a))?{value:Number(a[1]),unit:a[2]}:null}static convertLengthValue_(a,
b,c,d=1){const e=shaka.text.UITextDisplayer.getLengthValueInfo_(a);if(!e)return a;const {unit:f,value:g}=e;a=g*d;switch(f){case "%":return shaka.text.UITextDisplayer.getAbsoluteLengthInPixels_(a/100,b,c);case "c":return shaka.text.UITextDisplayer.getAbsoluteLengthInPixels_(a,b,c);default:return a+f}}static getAbsoluteLengthInPixels_(a,b,c){return c.clientHeight*a/b.cellResolution.rows+"px"}static inheritProperty_(a,b){for(let c=a.length-1;c>=0;c--){const d=b(a[c]);if(d||d===0)return d}return null}};
goog.exportSymbol("shaka.text.UITextDisplayer",shaka.text.UITextDisplayer);goog.exportProperty(shaka.text.UITextDisplayer.prototype,"enableTextDisplayer",shaka.text.UITextDisplayer.prototype.enableTextDisplayer);goog.exportProperty(shaka.text.UITextDisplayer.prototype,"setTextLanguage",shaka.text.UITextDisplayer.prototype.setTextLanguage);goog.exportProperty(shaka.text.UITextDisplayer.prototype,"setTextVisibility",shaka.text.UITextDisplayer.prototype.setTextVisibility);
goog.exportProperty(shaka.text.UITextDisplayer.prototype,"isTextVisible",shaka.text.UITextDisplayer.prototype.isTextVisible);goog.exportProperty(shaka.text.UITextDisplayer.prototype,"remove",shaka.text.UITextDisplayer.prototype.remove);goog.exportProperty(shaka.text.UITextDisplayer.prototype,"destroy",shaka.text.UITextDisplayer.prototype.destroy);goog.exportProperty(shaka.text.UITextDisplayer.prototype,"append",shaka.text.UITextDisplayer.prototype.append);
goog.exportProperty(shaka.text.UITextDisplayer.prototype,"configure",shaka.text.UITextDisplayer.prototype.configure);shaka.text.WebVttGenerator=class{static convert(a,b){const c=e=>{var f=e;for(var g of b)g.end&&g.start<e&&(f+=g.end-g.start);e=Math.floor(f/3600);g=Math.floor(f/60%60);const h=Math.floor(f%60);f=Math.floor(f*1E3%1E3);return(e<10?"0":"")+e+":"+(g<10?"0":"")+g+":"+(h<10?"0":"")+h+"."+(f<100?f<10?"00":"0":"")+f};a=shaka.text.Utils.getCuesToFlatten(a);let d="WEBVTT\n\n";for(const e of a)d+=c(e.startTime)+" --\x3e "+c(e.endTime)+(f=>{const g=[],h=shaka.text.Cue;switch(f.textAlign){case h.textAlign.LEFT:g.push("align:left");
break;case h.textAlign.RIGHT:g.push("align:right");break;case h.textAlign.CENTER:g.push("align:middle");break;case h.textAlign.START:g.push("align:start");break;case h.textAlign.END:g.push("align:end")}switch(f.writingMode){case h.writingMode.VERTICAL_LEFT_TO_RIGHT:g.push("vertical:lr");break;case h.writingMode.VERTICAL_RIGHT_TO_LEFT:g.push("vertical:rl")}return g.length?" "+g.join(" "):""})(e)+"\n",d+=e.payload+"\n\n";return d}};goog.exportSymbol("shaka.text.WebVttGenerator",shaka.text.WebVttGenerator);shaka.util.CmcdManager=class{constructor(a,b){this.config_=b;this.player_=a;this.requestTimestampMap_=new Map;this.sf_=void 0;this.playbackStarted_=!1;this.buffering_=!0;this.lowLatency_=this.starved_=!1;this.playbackPlayingTime_=this.playbackPlayTime_=void 0;this.startTimeOfLoad_=0;this.msdSent_={request:!1,response:!1,event:!1};this.cmcdSequenceNumbers_={};this.eventManager_=new shaka.util.EventManager;this.eventTimers_=[];this.video_=null}setMediaElement(a){this.video_=a;this.setupEventListeners_()}configure(a){this.config_=
a;this.setupEventModeTimeInterval_()}reset(){this.requestTimestampMap_.clear();this.playbackStarted_=!1;this.buffering_=!0;this.lowLatency_=this.starved_=!1;this.startTimeOfLoad_=this.playbackPlayingTime_=this.playbackPlayTime_=0;this.msdSent_={request:!1,response:!1,event:!1};this.stopAndClearEventTimers_();this.cmcdSequenceNumbers_={};this.video_=null;this.eventManager_.removeAll()}setBuffering(a){a||this.playbackStarted_||(this.playbackStarted_=!0);this.playbackStarted_&&a&&(this.starved_=!0,this.reportEvent_("ps",
{sta:"r"}));this.buffering_=a}setLowLatency(a){this.lowLatency_=a;a=shaka.util.CmcdManager.StreamingFormat;this.lowLatency_?this.sf_==a.DASH?this.sf_=a.LOW_LATENCY_DASH:this.sf_==a.HLS&&(this.sf_=a.LOW_LATENCY_HLS):this.sf_==a.LOW_LATENCY_DASH?this.sf_=a.DASH:this.sf_==a.LOW_LATENCY_HLS&&(this.sf_=a.HLS)}setStartTimeOfLoad(a){if(this.config_&&this.config_.enabled&&(this.reportEvent_("ps",{sta:"d"}),this.video_&&this.video_.autoplay)){const b=this.video_.play();b&&b.then(()=>{this.startTimeOfLoad_=
a}).catch(c=>{this.startTimeOfLoad_=0})}}applyRequestData(a,b,c={}){if(this.config_.enabled)if(b.method==="HEAD")this.applyRequest_(b,{});else{var d=shaka.net.NetworkingEngine.RequestType,e=shaka.util.CmcdManager.ObjectType;switch(a){case d.MANIFEST:this.applyManifestData(b,c);break;case d.SEGMENT:this.applyRequestSegmentData(b,c);break;case d.LICENSE:case d.SERVER_CERTIFICATE:case d.KEY:this.applyRequest_(b,{ot:e.KEY});break;case d.TIMING:this.applyRequest_(b,{ot:e.OTHER})}}}applyResponseData(a,
b,c={}){if(this.getResponseModeEnabledTargets().length!==0){var d=shaka.net.NetworkingEngine.RequestType;switch(a){case d.SEGMENT:this.applyResponseSegmentData(b,c)}}}applyManifestData(a,b){try{this.config_.enabled&&(b.type&&(this.sf_=this.getStreamFormat_(b.type)),this.applyRequest_(a,{ot:shaka.util.CmcdManager.ObjectType.MANIFEST,su:!this.playbackStarted_}))}catch(c){shaka.log.warnOnce("CMCD_MANIFEST_ERROR","Could not generate manifest CMCD data.",c)}}applyResponseSegmentData(a,b){try{const c=this.getDataForSegment_(b,
a.uri);a.originalRequest&&a.originalRequest.timeToFirstByte!=null&&(c.ttfb=a.originalRequest.timeToFirstByte);a.timeMs!=null&&(c.ttlb=a.timeMs);c.url=this.removeCmcdQueryFromUri_(a.originalUri||a.uri);this.requestTimestampMap_.has(a.originalRequest)?(c.ts=this.requestTimestampMap_.get(a.originalRequest),this.requestTimestampMap_.delete(a.originalRequest)):c.ts||(c.ts=Date.now());this.applyResponse_(a,c)}catch(c){shaka.log.warnOnce("CMCD_SEGMENT_ERROR","Could not generate response segment CMCD data.",
c)}}applyRequestSegmentData(a,b){try{if(this.config_.enabled){var c=this.getDataForSegment_(b,a.uris[0]);c.ts=Date.now();this.requestTimestampMap_.has(a)&&this.requestTimestampMap_.delete(a);this.requestTimestampMap_.set(a,c.ts);this.applyRequest_(a,c)}}catch(d){shaka.log.warnOnce("CMCD_SEGMENT_ERROR","Could not generate segment CMCD data.",d)}}applyTextData(a){try{this.config_.enabled&&this.applyRequest_(a,{ot:shaka.util.CmcdManager.ObjectType.CAPTION,su:!0})}catch(b){shaka.log.warnOnce("CMCD_TEXT_ERROR",
"Could not generate text CMCD data.",b)}}removeCmcdQueryFromUri_(a){if(!a.includes("CMCD="))return a;try{const b=new URL(a);b.searchParams.delete("CMCD");return b.toString()}catch(b){return shaka.log.error("Failed to parse URI for CMCD removal:",a,b),a}}appendSrcData(a,b){try{if(!this.config_.enabled)return a;const c=this.createData_();c.ot=this.getObjectTypeFromMimeType_(b);c.su=!0;const d=shaka.util.CmcdManager.toQuery(c);return shaka.util.CmcdManager.appendQueryToUri(a,d)}catch(c){return shaka.log.warnOnce("CMCD_SRC_ERROR",
"Could not generate src CMCD data.",c),a}}appendTextTrackData(a){try{if(!this.config_.enabled)return a;const b=this.createData_();b.ot=shaka.util.CmcdManager.ObjectType.CAPTION;b.su=!0;const c=shaka.util.CmcdManager.toQuery(b);return shaka.util.CmcdManager.appendQueryToUri(a,c)}catch(b){return shaka.log.warnOnce("CMCD_TEXT_TRACK_ERROR","Could not generate text track CMCD data.",b),a}}onPlaybackPlay_(){this.playbackPlayTime_||(this.playbackPlayTime_=Date.now(),this.reportEvent_("ps",{sta:"s"}))}onPlaybackPlaying_(){this.playbackPlayingTime_||
(this.playbackPlayingTime_=Date.now())}setupEventListeners_(){this.eventManager_.listen(this.video_,"playing",()=>{this.onPlaybackPlaying_();this.reportEvent_("ps",{sta:"p"})});this.eventManager_.listen(this.video_,"volumechange",()=>{this.reportEvent_(this.video_.muted?"m":"um")});this.eventManager_.listen(this.video_,"play",()=>{this.onPlaybackPlay_()});this.eventManager_.listen(this.video_,"pause",()=>{this.reportEvent_("ps",{sta:"a"})});this.eventManager_.listen(this.player_,"buffering",()=>{this.reportEvent_("ps",
{sta:"w"})});this.eventManager_.listen(this.video_,"seeking",()=>this.reportEvent_("ps",{sta:"k"}));this.eventManager_.listen(document,"fullscreenchange",()=>{this.reportEvent_(document.fullscreenElement?"pe":"pc")});const a=this.video_;(a.webkitPresentationMode||a.webkitSupportsFullscreen)&&this.eventManager_.listen(a,"webkitpresentationmodechanged",()=>{a.webkitPresentationMode?this.reportEvent_(a.webkitPresentationMode!=="inline"?"pe":"pc"):a.webkitSupportsFullscreen&&this.reportEvent_(a.webkitDisplayingFullscreen?
"pe":"pc")});this.eventManager_.listen(this.video_,"enterpictureinpicture",()=>{this.reportEvent_("pe")});this.eventManager_.listen(this.video_,"leavepictureinpicture",()=>{this.reportEvent_("pc")});"documentPictureInPicture"in window&&this.eventManager_.listen(window.documentPictureInPicture,"enter",b=>{this.reportEvent_("pe");this.eventManager_.listenOnce(b.window,"pagehide",()=>{this.reportEvent_("pc")})});this.eventManager_.listen(document,"visibilitychange",()=>{document.hidden?this.reportEvent_("b",
{bg:!0}):this.reportEvent_("b")});this.eventManager_.listen(this.player_,"complete",()=>{this.reportEvent_("ps",{sta:"e"})})}setupEventModeTimeInterval_(){this.stopAndClearEventTimers_();var a=this.getEventModeEnabledTargets_();for(const b of a)if(a=b.timeInterval,a===void 0&&(a=shaka.util.CmcdManager.CmcdV2Constants.TIME_INTERVAL_DEFAULT_VALUE),a>=1){const c=new shaka.util.Timer(()=>this.reportEvent_(shaka.util.CmcdManager.CmcdV2Keys.TIME_INTERVAL_EVENT));c.tickEvery(a);this.eventTimers_.push(c)}}stopAndClearEventTimers_(){if(this.eventTimers_)for(const a of this.eventTimers_)a.stop();
this.eventTimers_=[]}getEventModeEnabledTargets_(){const a=this.config_.targets;return a?a.filter(b=>b.mode===shaka.util.CmcdManager.CmcdMode.EVENT&&b.enabled):[]}getResponseModeEnabledTargets(){const a=this.config_.targets;return a?a.filter(b=>b.mode===shaka.util.CmcdManager.CmcdMode.RESPONSE&&b.enabled===!0):[]}createData_(){this.config_.sessionId||(this.config_.sessionId=window.crypto.randomUUID());return{v:this.config_.version,sf:this.sf_,sid:this.config_.sessionId,cid:this.config_.contentId,
mtp:this.player_.getBandwidthEstimate()/1E3}}reportEvent_(a,b={}){a={e:a,ts:Date.now()};b=Object.assign(a,b);b=this.getGenericData_(b,shaka.util.CmcdManager.CmcdMode.EVENT);a=this.config_.targets;if(!(this.config_.version<shaka.util.CmcdManager.Version.VERSION_2)&&a){var c=this.getEventModeEnabledTargets_();a=Array.from(new Set([...shaka.util.CmcdManager.CmcdKeys.V2CommonKeys,...shaka.util.CmcdManager.CmcdKeys.V2EventKeys]));for(const d of c)c=this.checkValidKeys_(d.includeKeys||[],a,shaka.util.CmcdManager.CmcdMode.EVENT),
c.includes(shaka.util.CmcdManager.CmcdV2Keys.TIMESTAMP)||c.push(shaka.util.CmcdManager.CmcdV2Keys.TIMESTAMP),c=this.filterKeys_(b,c),this.isValidEvent_(d.events||[],c)&&this.sendCmcdRequest_(c,d)}}applyRequest_(a,b){if(this.config_.enabled){b=this.getGenericData_(b,shaka.util.CmcdManager.CmcdMode.REQUEST);var c=this.getCmcdTargetHash_({mode:shaka.util.CmcdManager.CmcdMode.REQUEST,useHeaders:this.config_.useHeaders,includeKeys:this.config_.includeKeys||[]});this.cmcdSequenceNumbers_[c]||(this.cmcdSequenceNumbers_[c]=
{request:1,response:1});b.sn=this.cmcdSequenceNumbers_[c].request++;c=this.config_.includeKeys||[];var d=this.config_.version==shaka.util.CmcdManager.Version.VERSION_2?Array.from(new Set([...shaka.util.CmcdManager.CmcdKeys.V2CommonKeys,...shaka.util.CmcdManager.CmcdKeys.V2RequestModeKeys])):shaka.util.CmcdManager.CmcdKeys.V1Keys;c=this.checkValidKeys_(c,d,shaka.util.CmcdManager.CmcdMode.REQUEST);b=this.filterKeys_(b,c);this.applyCmcdDataToRequest_(b,a,this.config_.useHeaders)}}applyResponse_(a,b){var c=
this.getResponseModeEnabledTargets();if(c.length!==0){var d=this.config_.version==shaka.util.CmcdManager.Version.VERSION_2?Array.from(new Set([...shaka.util.CmcdManager.CmcdKeys.V2CommonKeys,...shaka.util.CmcdManager.CmcdKeys.V2ResponseModeKeys])):shaka.util.CmcdManager.CmcdKeys.V1Keys;b.rc=a.status||0;b=this.getGenericData_(b,shaka.util.CmcdManager.CmcdMode.RESPONSE);a.headers&&a.headers["CMSD-Static"]&&(b.cmsds=btoa(a.headers["CMSD-Static"]));a.headers&&a.headers["CMSD-Dynamic"]&&(b.cmsdd=btoa(a.headers["CMSD-Dynamic"]));
for(const e of c){c=this.checkValidKeys_(e.includeKeys||[],d,shaka.util.CmcdManager.CmcdMode.RESPONSE);const f=this.getCmcdTargetHash_(e);this.cmcdSequenceNumbers_[f]||(this.cmcdSequenceNumbers_[f]={request:1,response:1});b.sn=this.cmcdSequenceNumbers_[f].response++;c=this.filterKeys_(b,c);this.sendCmcdRequest_(c,e,a)}}}sendCmcdRequest_(a,b,c){var d=shaka.net.NetworkingEngine.defaultRetryParameters(),e=b.url;if(b.useHeaders){a=shaka.util.CmcdManager.toHeaders(a);if(!Object.keys(a).length)return;c&&
Object.assign(c.headers,a);c=shaka.net.NetworkingEngine.makeRequest([e],d);Object.assign(c.headers,a)}else{a=shaka.util.CmcdManager.toQuery(a);if(!a)return;e=shaka.util.CmcdManager.appendQueryToUri(e,a);c&&(c.uri=e);c=shaka.net.NetworkingEngine.makeRequest([e],d)}d=shaka.net.NetworkingEngine.RequestType.CMCD;this.player_.getNetworkingEngine().request(d,c)}applyCmcdDataToRequest_(a,b,c){if(c){a=shaka.util.CmcdManager.toHeaders(a);if(!Object.keys(a).length)return;Object.assign(b.headers,a)}else{const d=
shaka.util.CmcdManager.toQuery(a);if(!d)return;b.uris=b.uris.map(e=>shaka.util.CmcdManager.appendQueryToUri(e,d))}this.getResponseModeEnabledTargets().length>0||!this.requestTimestampMap_.has(b)||this.requestTimestampMap_.delete(b)}checkValidKeys_(a,b,c){if(!a||a.length===0)return b;for(const d of a)b.includes(d)||shaka.log.error(`CMCD Key "${d}" is not allowed for ${c} mode`);return a=a.filter(d=>b.includes(d))}filterKeys_(a,b){return Object.keys(a).reduce((c,d)=>{b.includes(d)&&(c[d]=a[d]);return c},
{})}isValidEvent_(a,b){const c=shaka.util.CmcdManager.CmcdKeys.CmcdV2Events,d=shaka.util.CmcdManager.CmcdKeys.CmcdV2PlayStates,e=b.e;b=b.sta;return e&&(!c.includes(e)||!(e!=="ps"||b&&d.includes(b))||a&&a.length>0&&!a.includes(e))?!1:!0}getObjectType_(a){if(a.type===shaka.net.NetworkingEngine.AdvancedRequestType.INIT_SEGMENT)return shaka.util.CmcdManager.ObjectType.INIT;if(a=a.stream){var b=a.type;if(b=="video")return a.codecs&&a.codecs.includes(",")?shaka.util.CmcdManager.ObjectType.MUXED:shaka.util.CmcdManager.ObjectType.VIDEO;
if(b=="audio")return shaka.util.CmcdManager.ObjectType.AUDIO;if(b=="text")return a.mimeType==="application/mp4"?shaka.util.CmcdManager.ObjectType.TIMED_TEXT:shaka.util.CmcdManager.ObjectType.CAPTION}}getObjectTypeFromMimeType_(a){switch(a.toLowerCase()){case "audio/mp4":case "audio/webm":case "audio/ogg":case "audio/mpeg":case "audio/aac":case "audio/flac":case "audio/wav":return shaka.util.CmcdManager.ObjectType.AUDIO;case "video/webm":case "video/mp4":case "video/mpeg":case "video/mp2t":return shaka.util.CmcdManager.ObjectType.MUXED;
case "application/x-mpegurl":case "application/vnd.apple.mpegurl":case "audio/x-mpegurl":case "application/dash+xml":case "video/vnd.mpeg.dash.mpd":case "application/vnd.ms-sstr+xml":return shaka.util.CmcdManager.ObjectType.MANIFEST}}getCmcdTargetHash_(a){const b=Object.keys(a).sort().reduce((c,d)=>{d!=="enabled"&&(c[d]=a[d]);return c},{});return JSON.stringify(b)}getBufferLength_(a){a=this.player_.getBufferedInfo()[a];if(!a.length)return NaN;const b=this.getCurrentTime_();return(a=a.find(c=>c.start<=
b&&c.end>=b))?(a.end-b)*1E3:NaN}getRemainingBufferLength_(a){a=this.player_.getBufferedInfo()[a];if(!a.length)return 0;const b=this.getCurrentTime_();return(a=a.find(c=>c.start<=b&&c.end>=b))?(a.end-b)*1E3:0}calculateMSD_(){if(this.playbackPlayingTime_&&this.playbackPlayTime_)return this.playbackPlayingTime_-(this.startTimeOfLoad_||this.playbackPlayTime_)}calculateRtp_(a,b){const c=this.player_.getPlaybackRate()||1,d=this.getRemainingBufferLength_(a.type)||500;return(a=a.bandwidth)?a*(b.endTime-b.startTime)/
1E3/(d/c/1E3)*this.config_.rtpSafetyFactor:NaN}getStreamFormat_(a){const b=shaka.net.NetworkingEngine.AdvancedRequestType;switch(a){case b.MPD:return this.lowLatency_?shaka.util.CmcdManager.StreamingFormat.LOW_LATENCY_DASH:shaka.util.CmcdManager.StreamingFormat.DASH;case b.MASTER_PLAYLIST:case b.MEDIA_PLAYLIST:return this.lowLatency_?shaka.util.CmcdManager.StreamingFormat.LOW_LATENCY_HLS:shaka.util.CmcdManager.StreamingFormat.HLS;case b.MSS:return shaka.util.CmcdManager.StreamingFormat.SMOOTH}}getStreamType_(){return this.player_.isLive()?
shaka.util.CmcdManager.StreamType.LIVE:shaka.util.CmcdManager.StreamType.VOD}getTopBandwidth_(a){var b=this.player_.getVariantTracks();if(!b.length)return NaN;let c=b[0];for(const d of b)d.type==="variant"&&d.bandwidth>c.bandwidth&&(c=d);b=shaka.util.CmcdManager.ObjectType;switch(a){case b.VIDEO:return c.videoBandwidth||NaN;case b.AUDIO:return c.audioBandwidth||NaN;default:return c.bandwidth}}getDataForSegment_(a,b){var c=a.segment,d=0;c&&(d=c.endTime-c.startTime);d={d:d*1E3,st:this.getStreamType_()};
d.ot=this.getObjectType_(a);const e=shaka.util.CmcdManager.ObjectType,f=d.ot===e.VIDEO||d.ot===e.AUDIO||d.ot===e.MUXED||d.ot===e.TIMED_TEXT;if(a=a.stream){var g=this.player_.getPlaybackRate();if(f&&(d.bl=this.getBufferLength_(a.type),d.ot!==e.TIMED_TEXT)){const h=this.getRemainingBufferLength_(a.type);d.dl=g?h/Math.abs(g):h}a.bandwidth&&(d.br=a.bandwidth/1E3);a.segmentIndex&&c&&((g=a.segmentIndex.getIteratorForTime(c.endTime,!0,g<0))&&(g=g.next().value)&&g!=c&&(b&&!shaka.util.ArrayUtils.equal(c.getUris(),
g.getUris())&&(d.nor=shaka.util.CmcdManager.urlToRelativePath(g.getUris()[0],b)),!g.startByte&&!g.endByte||c.startByte==g.startByte&&c.endByte==g.endByte||(b=g.startByte+"-",g.endByte&&(b+=g.endByte),d.nrr=b)),c=this.calculateRtp_(a,c),isNaN(c)||(d.rtp=c))}f&&d.ot!==e.TIMED_TEXT&&(d.tb=this.getTopBandwidth_(d.ot)/1E3);return d}getCurrentTime_(){return this.video_?this.video_.currentTime:0}getGenericData_(a,b){Object.assign(a,this.createData_());a.pr=this.player_.getPlaybackRate();var c=a.ot===shaka.util.CmcdManager.ObjectType.VIDEO||
a.ot===shaka.util.CmcdManager.ObjectType.MUXED;this.starved_&&c&&(a.bs=!0,a.su=!0,this.starved_=!1);a.su==null&&(a.su=this.buffering_);this.player_.isLive()&&(c=this.player_.getLiveLatency(),a.ltc=c||void 0);document.hidden&&(a.bg=!0);c=this.calculateMSD_();c==void 0||this.msdSent_[b]||(a.msd=c,this.msdSent_[b]=!0);return a}static serialize(a){const b=[],c=g=>!Number.isNaN(g)&&g!=null&&g!==""&&g!==!1;var d=g=>Math.round(g),e=g=>Math.round(g/100)*100;d={br:d,d,bl:e,dl:e,mtp:e,nor:g=>encodeURIComponent(g),
rtp:e,tb:d,ttfb:d,ttlb:d};e=Object.keys(a||{}).sort();for(const g of e){e=a[g];if(!c(e))continue;if(g==="v"&&e===1)continue;if(g=="pr"&&e===1)continue;var f=d[g];f&&(e=f(e));f=typeof e;e=f==="string"&&g!=="ot"&&g!=="sf"&&g!=="st"?`${g}=${JSON.stringify(e)}`:f==="boolean"?g:f==="symbol"?`${g}=${e.description}`:`${g}=${e}`;b.push(e)}return b.join(",")}static toHeaders(a){var b=Object.keys(a);const c={},d=["Object","Request","Session","Status"],e=[{},{},{},{}],f={br:0,d:0,ot:0,tb:0,url:0,bl:1,dl:1,mtp:1,
nor:1,nrr:1,su:1,ltc:1,ttfb:1,ttlb:1,ts:1,rc:1,cmsdd:1,cmsds:1,sn:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,msd:2,bs:3,rtp:3,bg:3};for(const g of b)e[f[g]!=null?f[g]:1][g]=a[g];for(a=0;a<e.length;a++)(b=shaka.util.CmcdManager.serialize(e[a]))&&(c[`CMCD-${d[a]}`]=b);return c}static toQuery(a){return shaka.util.CmcdManager.serialize(a)}static appendQueryToUri(a,b){if(!b||a.includes("offline:"))return a;a=new goog.Uri(a);a.getQueryData().set("CMCD",b);return a.toString()}static urlToRelativePath(a,b){const c=
new URL(a);b=new URL(b);if(c.origin!==b.origin)return a;a=c.pathname.split("/").slice(1);b=b.pathname.split("/").slice(1,-1);const d=Math.min(a.length,b.length);for(let e=0;e<d&&a[e]===b[e];e++)a.shift(),b.shift();for(;b.length;)b.shift(),a.unshift("..");return a.join("/")+c.search+c.hash}};shaka.util.CmcdManager.ObjectType={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"};shaka.util.CmcdManager.Version={VERSION_1:1,VERSION_2:2};
shaka.util.CmcdManager.StreamType={VOD:"v",LIVE:"l"};shaka.util.CmcdManager.StreamingFormat={DASH:"d",LOW_LATENCY_DASH:"ld",HLS:"h",LOW_LATENCY_HLS:"lh",SMOOTH:"s",OTHER:"o"};goog.exportSymbol("shaka.util.CmcdManager.StreamingFormat",shaka.util.CmcdManager.StreamingFormat);
shaka.util.CmcdManager.CmcdKeys={V1Keys:"br bl bs cid d dl mtp nor nrr ot pr rtp sf sid st su tb v".split(" "),V2CommonKeys:"br ab bl tbl bs cdn cid ltc mtp pr sf sid bg sta st ts tpb tb lb tab lab pt ec msd v sn".split(" "),V2RequestModeKeys:"ab bl tbl bs cdn cid d dl ltc mtp nor ot pr rtp sf sid bg sta st su ts tpb tb lb tab lab pt ec msd v".split(" "),V2ResponseModeKeys:"d dl nor ot rtp rc su ttfb ttfbb ttlb url cmsdd cmsds".split(" "),V2EventKeys:["e","sta"],CmcdV2Events:"ps e t c b m um pe pc".split(" "),
CmcdV2PlayStates:"spawkrfeqd".split("")};shaka.util.CmcdManager.CmcdV2Constants={TIME_INTERVAL_DEFAULT_VALUE:10};shaka.util.CmcdManager.CmcdV2Keys={TIMESTAMP:"ts",TIME_INTERVAL_EVENT:"t"};shaka.util.CmcdManager.CmcdMode={REQUEST:"request",RESPONSE:"response",EVENT:"event"};shaka.util.CmsdManager=class{constructor(a){this.config_=a;this.dynamicParams_=this.staticParams_=null}configure(a){this.config_=a}reset(){this.dynamicParams_=this.staticParams_=null}processHeaders(a){if(this.config_.enabled){var b=shaka.util.CmsdManager,c=a[b.CMSD_STATIC_HEADER_NAME_];c&&(c=this.parseCMSDStatic_(c))&&(this.staticParams_=c);if(a=a[b.CMSD_DYNAMIC_HEADER_NAME_])if(a=this.parseCMSDDynamic_(a))this.dynamicParams_=a}}getMaxBitrate(){const a=shaka.util.CmsdManager.KEYS_.MAX_SUGGESTED_BITRATE;
return this.config_.enabled&&this.config_.applyMaximumSuggestedBitrate&&this.dynamicParams_&&this.dynamicParams_.has(a)?this.dynamicParams_.get(a)*1E3:null}getEstimatedThroughput(){const a=shaka.util.CmsdManager.KEYS_.ESTIMATED_THROUGHPUT;return this.config_.enabled&&this.dynamicParams_&&this.dynamicParams_.has(a)?this.dynamicParams_.get(a)*1E3:null}getResponseDelay(){const a=shaka.util.CmsdManager.KEYS_.RESPONSE_DELAY;return this.config_.enabled&&this.dynamicParams_&&this.dynamicParams_.has(a)?this.dynamicParams_.get(a):
null}getRoundTripTime(){const a=shaka.util.CmsdManager.KEYS_.ROUND_TRIP_TIME;return this.config_.enabled&&this.dynamicParams_&&this.dynamicParams_.has(a)?this.dynamicParams_.get(a):null}getBandwidthEstimate(a){const b=this.getEstimatedThroughput();if(!b)return a;const c=this.config_.estimatedThroughputWeightRatio;return c>0&&c<=1?a*(1-c)+b*c:a}parseCMSDStatic_(a){try{const b=new Map,c=a.split(",");for(a=0;a<c.length;a++){const d=c[a].split("="),e=d[0],f=this.parseParameterValue_(d[1]);b.set(e,f)}return b}catch(b){return shaka.log.warning("Failed to parse CMSD-Static response header value:",
b),null}}parseCMSDDynamic_(a){try{const b=new Map,c=a.split(";");for(a=1;a<c.length;a++){const d=c[a].split("="),e=d[0],f=this.parseParameterValue_(d[1]);b.set(e,f)}return b}catch(b){return shaka.log.warning("Failed to parse CMSD-Dynamic response header value:",b),null}}parseParameterValue_(a){return a?a.toLowerCase()==="false"?!1:/^[-0-9]/.test(a)?parseInt(a,10):a.replace(/["]+/g,""):!0}};goog.exportSymbol("shaka.util.CmsdManager",shaka.util.CmsdManager);
goog.exportProperty(shaka.util.CmsdManager.prototype,"getBandwidthEstimate",shaka.util.CmsdManager.prototype.getBandwidthEstimate);goog.exportProperty(shaka.util.CmsdManager.prototype,"getRoundTripTime",shaka.util.CmsdManager.prototype.getRoundTripTime);goog.exportProperty(shaka.util.CmsdManager.prototype,"getResponseDelay",shaka.util.CmsdManager.prototype.getResponseDelay);goog.exportProperty(shaka.util.CmsdManager.prototype,"getEstimatedThroughput",shaka.util.CmsdManager.prototype.getEstimatedThroughput);
goog.exportProperty(shaka.util.CmsdManager.prototype,"getMaxBitrate",shaka.util.CmsdManager.prototype.getMaxBitrate);shaka.util.CmsdManager.CMSD_STATIC_HEADER_NAME_="cmsd-static";shaka.util.CmsdManager.CMSD_DYNAMIC_HEADER_NAME_="cmsd-dynamic";
shaka.util.CmsdManager.KEYS_={AVAILABILITY_TIME:"at",DURESS:"du",ENCODED_BITRATE:"br",ESTIMATED_THROUGHPUT:"etp",HELD_TIME:"ht",INTERMEDIARY_IDENTIFIER:"n",MAX_SUGGESTED_BITRATE:"mb",NEXT_OBJECT_RESPONSE:"nor",NEXT_RANGE_RESPONSE:"nrr",OBJECT_DURATION:"d",OBJECT_TYPE:"ot",RESPONSE_DELAY:"rd",ROUND_TRIP_TIME:"rtt",STARTUP:"su",STREAM_TYPE:"st",STREAMING_FORMAT:"sf",VERSION:"v"};shaka.util.Mutex=class{constructor(){this.acquiredIdentifier=null;this.unlockQueue=[]}async acquire(a){shaka.log.v2(a+" has requested mutex");this.acquiredIdentifier&&await new Promise(b=>this.unlockQueue.push(b));this.acquiredIdentifier=a;shaka.log.v2(a+" has acquired mutex")}release(){shaka.log.v2(this.acquiredIdentifier+" has released mutex");this.unlockQueue.length>0?this.unlockQueue.shift()():this.acquiredIdentifier=null}releaseAll(){for(;this.acquiredIdentifier;)this.release()}};shaka.Player=class extends shaka.util.FakeEventTarget{constructor(a,b=null,c){super();this.loadMode_=shaka.Player.LoadMode.NOT_LOADED;this.video_=null;this.videoContainer_=b;this.isTextVisible_=!1;this.globalEventManager_=new shaka.util.EventManager;this.attachEventManager_=new shaka.util.EventManager;this.loadEventManager_=new shaka.util.EventManager;this.trickPlayEventManager_=new shaka.util.EventManager;this.adManagerEventManager_=new shaka.util.EventManager;this.playhead_=this.mediaSourceEngine_=
this.drmEngine_=this.networkingEngine_=null;this.operationId_=0;this.mutex_=new shaka.util.Mutex;this.startTime_=this.mimeType_=this.assetUri_=this.manifest_=this.parserFactory_=this.parser_=this.streamingEngine_=this.qualityObserver_=this.lcevcDec_=this.lcevcCanvas_=this.cmsdManager_=this.cmcdManager_=this.emsgRegionTimeline_=this.metadataRegionTimeline_=this.regionTimeline_=this.bufferObserver_=this.bufferPoller_=this.playRateController_=this.playheadObservers_=null;this.fullyLoaded_=!1;this.abrManagerFactory_=
this.abrManager_=null;this.nextExternalStreamId_=1E9;this.externalSrcEqualsThumbnailsStreams_=[];this.deferredCloseSegmentIndex_=new Map;this.externalChaptersStreams_=[];this.completionPercent_=-1;this.config_=this.defaultConfig_();this.lowLatencyConfig_=shaka.util.PlayerConfiguration.createDefaultForLL();this.currentTargetLatency_=null;this.rebufferingCount_=-1;this.targetLatencyReached_=null;this.maxHwRes_={width:Infinity,height:Infinity};this.manifestFilterer_=new shaka.media.ManifestFilterer(this.config_,
this.maxHwRes_,null);this.createdPreloadManagers_=[];this.stats_=null;this.currentAdaptationSetCriteria_=this.config_.adaptationSetCriteriaFactory();this.currentAdaptationSetCriteria_.configure({language:this.config_.preferredAudioLanguage,role:this.config_.preferredAudioRole,videoRole:this.config_.preferredVideoRole,channelCount:0,hdrLevel:this.config_.preferredVideoHdrLevel,spatialAudio:this.config_.preferSpatialAudio,videoLayout:this.config_.preferredVideoLayout,audioLabel:this.config_.preferredAudioLabel,
videoLabel:this.config_.preferredVideoLabel,codecSwitchingStrategy:this.config_.mediaSource.codecSwitchingStrategy,audioCodec:"",activeAudioCodec:"",activeAudioChannelCount:0,preferredAudioCodecs:this.config_.preferredAudioCodecs,preferredAudioChannelCount:this.config_.preferredAudioChannelCount});this.currentTextLanguage_=this.config_.preferredTextLanguage;this.currentTextRole_=this.config_.preferredTextRole;this.currentTextForced_=this.config_.preferForcedSubs;this.cleanupOnUnload_=[];c&&c(this);
this.cmcdManager_=this.createCmcd_();this.cmsdManager_=this.createCmsd_();this.networkingEngine_=this.createNetworkingEngine();this.preloadDueAdManagerVideo_=this.preloadDueAdManager_=this.queueManager_=this.adManager_=null;this.preloadDueAdManagerVideoEnded_=!1;this.externalSrcEqualsTextTracks_=[];this.preloadDueAdManagerTimer_=new shaka.util.Timer(async()=>{this.preloadDueAdManager_&&(goog.asserts.assert(this.preloadDueAdManagerVideo_,"Must have video"),await this.attach(this.preloadDueAdManagerVideo_,
!0),await this.load(this.preloadDueAdManager_),this.preloadDueAdManagerVideoEnded_?this.preloadDueAdManagerVideo_.pause():this.preloadDueAdManagerVideo_.play(),this.preloadDueAdManager_=null,this.preloadDueAdManagerVideoEnded_=!1)});shaka.Player.adManagerFactory_&&(this.adManager_=shaka.Player.adManagerFactory_(),this.adManager_.configure(this.config_.ads),this.adManagerEventManager_.listen(this.adManager_,"ad-content-pause-requested",async d=>{this.preloadDueAdManagerTimer_.stop();if(!this.preloadDueAdManager_){this.preloadDueAdManagerVideo_=
this.video_;this.preloadDueAdManagerVideoEnded_=this.isEnded();d=d.saveLivePosition||!1;let e=!0;this.isLive()&&(e=d);this.preloadDueAdManager_=await this.detachAndSavePreload(!0,e)}}),this.adManagerEventManager_.listen(this.adManager_,"ad-content-resume-requested",d=>{d=d.offset||0;this.preloadDueAdManager_&&this.preloadDueAdManager_.setOffsetToStartTime(d);this.preloadDueAdManagerTimer_.tickAfter(.1)}),this.adManagerEventManager_.listen(this.adManager_,"ad-content-attach-requested",async d=>{!this.video_&&
this.preloadDueAdManagerVideo_&&(await this.attach(this.preloadDueAdManagerVideo_,!0),this.preloadDueAdManagerVideo_=null)}));shaka.Player.queueManagerFactory_&&(this.queueManager_=shaka.Player.queueManagerFactory_(this),this.queueManager_.configure(this.config_.queue));this.globalEventManager_.listen(window,"online",()=>{this.restoreDisabledVariants_();this.retryStreaming()});this.checkVariantsTimer_=new shaka.util.Timer(()=>this.checkVariants_());this.preloadNextUrl_=null;a&&(shaka.Deprecate.deprecateFeature(5,
"Player w/ mediaElement","Please migrate from initializing Player with a mediaElement; use the attach method instead."),this.attach(a,!0));this.textDisplayer_=null}createLcevcDec_(a,b){this.lcevcDec_==null&&(this.lcevcDec_=new shaka.lcevc.Dec(this.video_,this.lcevcCanvas_,a,b),this.mediaSourceEngine_&&this.mediaSourceEngine_.updateLcevcDec(this.lcevcDec_))}closeLcevcDec_(){this.lcevcDec_!=null&&(this.lcevcDec_.hideCanvas(),this.lcevcDec_.release(),this.lcevcDec_=null)}setupLcevc_(a,b){b||a.lcevc.enabled?
(this.closeLcevcDec_(),this.createLcevcDec_(a.lcevc,b)):this.closeLcevcDec_()}static makeEvent_(a,b){return new shaka.util.FakeEvent(a,b)}async destroy(){if(this.loadMode_!=shaka.Player.LoadMode.DESTROYED){this.closeLcevcDec_();var a=this.detach();this.loadMode_=shaka.Player.LoadMode.DESTROYED;await a;await this.destroyAllPreloads();this.globalEventManager_&&(this.globalEventManager_.release(),this.globalEventManager_=null);this.attachEventManager_&&(this.attachEventManager_.release(),this.attachEventManager_=
null);this.loadEventManager_&&(this.loadEventManager_.release(),this.loadEventManager_=null);this.trickPlayEventManager_&&(this.trickPlayEventManager_.release(),this.trickPlayEventManager_=null);this.adManagerEventManager_&&(this.adManagerEventManager_.release(),this.adManagerEventManager_=null);this.cmsdManager_=this.cmcdManager_=this.videoContainer_=this.stats_=this.config_=this.abrManagerFactory_=null;this.networkingEngine_&&(await this.networkingEngine_.destroy(),this.networkingEngine_=null);
this.abrManager_&&(this.abrManager_.release(),this.abrManager_=null);this.queueManager_&&(this.queueManager_.destroy(),this.queueManager_=null);super.release()}}static registerSupportPlugin(a,b){shaka.Player.supportPlugins_.set(a,b)}static setAdManagerFactory(a){shaka.Player.adManagerFactory_=a}static setQueueManagerFactory(a){shaka.Player.queueManagerFactory_=a}static isBrowserSupported(){window.Promise||shaka.log.alwaysWarn("A Promise implementation or polyfill is required");if(!(window.Promise&&
window.Uint8Array&&Array.prototype.forEach)||(navigator.userAgent||"").includes("Trident/"))return!1;const a=shaka.device.DeviceFactory.getDevice();return a.supportsMediaSource()?!0:a.supportsMediaType("application/x-mpegurl")}static async probeSupport(a=!0){goog.asserts.assert(shaka.Player.isBrowserSupported(),"Must have basic support");let b={};a&&(b=await shaka.drm.DrmEngine.probeSupport());a=shaka.media.ManifestParser.probeSupport();const c=shaka.media.MediaSourceEngine.probeSupport();var d=shaka.device.DeviceFactory.getDevice();
goog.asserts.assert(d,"device must be non-null");d=await d.detectMaxHardwareResolution();const e={manifest:a,media:c,drm:b,hardwareResolution:d};shaka.Player.supportPlugins_.forEach((f,g)=>{e[g]=f()});return e}makeStateChangeEvent_(a){this.dispatchEvent(shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.OnStateChange,(new Map).set("state",a)))}async attach(a,b=!0){if(this.loadMode_==shaka.Player.LoadMode.DESTROYED)throw this.createAbortLoadError_();const c=this.video_&&this.video_==a;this.video_&&
this.video_!=a&&await this.detach();if(!await this.atomicOperationAcquireMutex_("attach"))try{c||(this.makeStateChangeEvent_("attach"),this.attachEventManager_.listen(a,"error",e=>this.onVideoError_(e)),this.video_=a,this.cmcdManager_&&this.cmcdManager_.setMediaElement(a));const d=shaka.device.DeviceFactory.getDevice();b&&d.supportsMediaSource()&&!this.mediaSourceEngine_&&await this.initializeMediaSourceEngineInner_()}catch(d){throw await this.detach(),d;}finally{this.mutex_.release()}}attachCanvas(a){this.lcevcCanvas_=
a}async detach(a=!1){if(this.loadMode_==shaka.Player.LoadMode.DESTROYED)throw this.createAbortLoadError_();await this.unload(!1,a);if(!await this.atomicOperationAcquireMutex_("detach"))try{this.video_&&(this.attachEventManager_.removeAll(),this.video_=null),this.makeStateChangeEvent_("detach"),this.adManager_&&!a&&this.adManager_.release()}finally{this.mutex_.release()}}async atomicOperationAcquireMutex_(a){const b=++this.operationId_;await this.mutex_.acquire(a);return b!=this.operationId_?(this.mutex_.release(),
!0):!1}async unload(a=!0,b=!1){this.loadMode_!=shaka.Player.LoadMode.DESTROYED&&(this.loadMode_=shaka.Player.LoadMode.NOT_LOADED);if(!await this.atomicOperationAcquireMutex_("unload")){try{this.fullyLoaded_=!1;this.makeStateChangeEvent_("unload");this.closeLcevcDec_();const c=this.cleanupOnUnload_.map(d=>d());this.cleanupOnUnload_=[];await Promise.all(c);this.dispatchEvent(shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.Unloading));this.regionTimeline_&&(this.regionTimeline_.release(),this.regionTimeline_=
null);this.metadataRegionTimeline_&&(this.metadataRegionTimeline_.release(),this.metadataRegionTimeline_=null);this.emsgRegionTimeline_&&(this.emsgRegionTimeline_.release(),this.emsgRegionTimeline_=null);this.video_&&(this.loadEventManager_.removeAll(),this.trickPlayEventManager_.removeAll());this.checkVariantsTimer_.stop();this.playheadObservers_&&(this.playheadObservers_.release(),this.playheadObservers_=null);this.bufferPoller_&&(this.bufferPoller_.stop(),this.bufferPoller_=null);this.parser_&&
(await this.parser_.stop(),this.parserFactory_=this.parser_=null);this.abrManager_&&this.abrManager_.stop();this.streamingEngine_&&(await this.streamingEngine_.destroy(),this.streamingEngine_=null);this.playRateController_&&(this.playRateController_.release(),this.playRateController_=null);this.playhead_&&(this.playhead_.release(),this.playhead_=null);shaka.drm.DrmUtils.isMediaKeysPolyfilled("webkit")&&this.drmEngine_&&(await this.drmEngine_.destroy(),this.drmEngine_=null);this.mediaSourceEngine_&&
(await this.mediaSourceEngine_.destroy(),this.mediaSourceEngine_=null);if(this.adManager_&&!b)this.adManager_.onAssetUnload();this.preloadDueAdManager_&&!b&&(this.preloadDueAdManager_.destroy(),this.preloadDueAdManager_=null);b||this.preloadDueAdManagerTimer_.stop();this.cmcdManager_&&this.cmcdManager_.reset();this.cmsdManager_&&this.cmsdManager_.reset();this.textDisplayer_&&(await this.textDisplayer_.destroy(),this.textDisplayer_=null);this.isTextVisible_=!1;if(this.video_){for(const d of this.externalSrcEqualsTextTracks_)d.src.startsWith("blob:")&&
URL.revokeObjectURL(d.src),d.remove();this.externalSrcEqualsTextTracks_=[];shaka.util.Dom.clearSourceFromVideo(this.video_)&&this.video_.load()}this.drmEngine_&&(await this.drmEngine_.destroy(),this.drmEngine_=null);this.preloadNextUrl_&&this.assetUri_!=this.preloadNextUrl_.getAssetUri()&&(this.preloadNextUrl_.isDestroyed()||this.preloadNextUrl_.destroy(),this.preloadNextUrl_=null);this.bufferObserver_=this.mimeType_=this.assetUri_=null;if(this.manifest_){for(const d of this.manifest_.variants)for(const e of[d.audio,
d.video])e&&e.segmentIndex&&e.segmentIndex.release();for(const d of this.manifest_.textStreams)d.segmentIndex&&d.segmentIndex.release()}this.config_&&this.config_.streaming.clearDecodingCache&&(shaka.util.StreamUtils.clearDecodingConfigCache(),shaka.drm.DrmUtils.clearMediaKeySystemAccessMap());this.manifest_=null;this.stats_=new shaka.util.Stats;this.currentTargetLatency_=this.targetLatencyReached_=this.lastTextFactory_=null;this.rebufferingCount_=-1;this.externalSrcEqualsThumbnailsStreams_=[];for(const d of this.deferredCloseSegmentIndex_.values())d.stop();
this.deferredCloseSegmentIndex_.clear();this.externalChaptersStreams_=[];this.completionPercent_=-1;this.networkingEngine_&&this.networkingEngine_.clearCommonAccessTokenMap();this.updateBufferState_()}finally{this.mutex_.release()}b=shaka.device.DeviceFactory.getDevice();a&&b.supportsMediaSource()&&!this.mediaSourceEngine_&&this.video_&&await this.initializeMediaSourceEngineInner_()}}updateStartTime(a){this.startTime_=a}async load(a,b=null,c){if(this.loadMode_==shaka.Player.LoadMode.DESTROYED)throw this.createAbortLoadError_();
!this.video_&&this.preloadDueAdManagerVideo_&&(await this.attach(this.preloadDueAdManagerVideo_,!0),this.preloadDueAdManagerVideo_=null);let d=null,e="";c=c?.toLowerCase();if(a instanceof shaka.media.PreloadManager){if(a.isDestroyed())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.PRELOAD_DESTROYED);d=a;e=d.getAssetUri()||""}else e=a||"";await this.mutex_.acquire("load");this.mutex_.release();if(!this.video_)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.NO_VIDEO_ELEMENT);this.assetUri_&&(this.assetUri_=e,await this.unload(!1));const f=++this.operationId_,g=async()=>{if(this.operationId_!=f)throw d&&await d.destroy(),this.createAbortLoadError_();};a=async(h,k)=>{try{await this.mutex_.acquire(k),await g(),await h(),await g(),d&&this.config_&&d.reconfigure(this.config_)}finally{this.mutex_.release()}};try{b==null&&d&&(b=d.getStartTime());this.startTime_=b;this.fullyLoaded_=!1;this.dispatchEvent(shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.Loading));
d?c=d.getMimeType():c||await a(async()=>{c=await this.guessMimeType_(e)},"guessMimeType_");const h=!!d;d?(d.setEventHandoffTarget(this),this.stats_=d.getStats()):(d=await this.preloadInner_(e,b,c,!0,this.config_))?(d.markIsLoad(),d.setEventHandoffTarget(this),this.stats_=d.getStats(),d.start(),d.waitForFinish().catch(()=>{})):this.stats_=new shaka.util.Stats;b=!d;const k=Date.now()/1E3;this.stats_=d?d.getStats():new shaka.util.Stats;this.assetUri_=e;this.mimeType_=c||null;this.updateBufferState_();
const l=()=>{const m=this.video_?this.video_.buffered:null;return{start:shaka.media.TimeRangesUtils.bufferStart(m)||0,end:shaka.media.TimeRangesUtils.bufferEnd(m)||0}};this.metadataRegionTimeline_=new shaka.media.RegionTimeline(l);this.metadataRegionTimeline_.addEventListener("regionadd",m=>{this.dispatchMetadataEvent_(m.region,shaka.util.FakeEvent.EventName.MetadataAdded)});if(b)await a(async()=>{goog.asserts.assert(c,"We should know the mimeType by now!");await this.initializeSrcEqualsDrmInner_(c)},
"initializeSrcEqualsDrmInner_"),await a(async()=>{goog.asserts.assert(c,"We should know the mimeType by now!");await this.srcEqualsInner_(k,c)},"srcEqualsInner_");else{this.emsgRegionTimeline_=new shaka.media.RegionTimeline(l);await a(async()=>{await d.waitForManifest();this.parserFactory_=d.getParserFactory();this.parser_=d.receiveParser();this.manifest_=d.getManifest()},"waitForFinish");this.mediaSourceEngine_||await a(async()=>{await this.initializeMediaSourceEngineInner_()},"initializeMediaSourceEngineInner_");
this.manifest_&&this.manifest_.textStreams.length&&(this.textDisplayer_.enableTextDisplayer?this.textDisplayer_.enableTextDisplayer():shaka.Deprecate.deprecateFeature(5,"Text displayer w/ enableTextDisplayer",'Text displayer should have a "enableTextDisplayer" method!'));await a(async()=>{await d.waitForFinish()},"waitForFinish");this.config_=d.getConfiguration();this.manifestFilterer_=d.getManifestFilterer();this.parser_&&this.parser_.setMediaElement&&this.video_&&this.parser_.setMediaElement(this.video_);
this.regionTimeline_=d.receiveRegionTimeline();this.qualityObserver_=d.getQualityObserver();const m=d.getCurrentAdaptationSetCriteria();m&&(this.currentAdaptationSetCriteria_=m);h&&this.video_&&this.video_.nodeName==="AUDIO"&&(this.makeManifestAudioOnly_(),this.configure("manifest.disableVideo",!0));d.getDrmEngine()||await a(async()=>{await d.initializeDrm(this.video_)},"drmEngine_.init");this.drmEngine_=d.receiveDrmEngine();await a(async()=>{await this.drmEngine_.attach(this.video_)},"drmEngine_.attach");
const n=this.config_.abrFactory;this.abrManager_&&this.abrManagerFactory_==n||(this.abrManagerFactory_=n,this.abrManager_&&this.abrManager_.release(),this.abrManager_=n(),typeof this.abrManager_.setMediaElement!="function"&&(shaka.Deprecate.deprecateFeature(5,"AbrManager w/o setMediaElement","Please use an AbrManager with setMediaElement function."),this.abrManager_.setMediaElement=()=>{}),typeof this.abrManager_.setCmsdManager!="function"&&(shaka.Deprecate.deprecateFeature(5,"AbrManager w/o setCmsdManager",
"Please use an AbrManager with setCmsdManager function."),this.abrManager_.setCmsdManager=()=>{}),typeof this.abrManager_.trySuggestStreams!="function"&&(shaka.Deprecate.deprecateFeature(5,"AbrManager w/o trySuggestStreams","Please use an AbrManager with trySuggestStreams function."),this.abrManager_.trySuggestStreams=()=>{}),this.abrManager_.configure(this.config_.abr));const q=d.receiveSegmentPrefetchesById(),p=d.getPrefetchedVariant();await a(async()=>{await this.loadInner_(k,p,q)},"loadInner_");
d.stopQueuingLatePhaseQueuedOperations();this.mimeType_&&shaka.device.DeviceFactory.getDevice().supportsAirPlay()&&shaka.util.MimeUtils.isHlsType(this.mimeType_)&&this.mediaSourceEngine_.addSecondarySource(this.assetUri_,this.mimeType_)}this.dispatchEvent(shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.Loaded))}catch(h){throw h&&h.code!=shaka.util.Error.Code.LOAD_INTERRUPTED&&await this.unload(!1),h;}finally{d&&await d.destroy(),this.preloadNextUrl_=null}}makeManifestAudioOnly_(){for(const a of this.manifest_.variants)a.video&&
(a.video.closeSegmentIndex(),a.video=null),a.bandwidth=a.audio&&a.audio.bandwidth?a.audio.bandwidth:0;this.manifest_.variants=this.manifest_.variants.filter(a=>a.audio)}async unloadAndSavePreload(a=!0,b=!1,c=!1){c=await this.savePreload_(c);await this.unload(a,b);return c}async detachAndSavePreload(a=!1,b=!1){b=await this.savePreload_(b);await this.detach(a);return b}async savePreload_(a=!1){var b=null;this.manifest_&&this.parser_&&this.parserFactory_&&this.assetUri_&&this.config_&&(b=this.video_.currentTime,
a||(b=null),b=await this.makePreloadManager_(this.assetUri_,b,this.mimeType_,this.config_,!0,!1),this.createdPreloadManagers_.push(b),this.parser_&&this.parser_.setMediaElement&&this.parser_.setMediaElement(null),(a=this.streamingEngine_?this.streamingEngine_.getCurrentVariant():null)&&b.setPrefetchVariant(a),b.attachManifest(this.manifest_,this.parser_,this.parserFactory_),b.attachAdaptationSetCriteria(this.currentAdaptationSetCriteria_),b.start(),this.abrManagerFactory_=this.abrManager_=this.parserFactory_=
this.parser_=this.manifest_=null);return b}async preload(a,b=null,c,d){goog.asserts.assert(this.config_,"Config must not be null!");c=c?.toLowerCase();const e=this.defaultConfig_();shaka.util.PlayerConfiguration.mergeConfigObjects(e,d||this.config_,this.defaultConfig_());if(a=await this.preloadInner_(a,b,c,!1,e))a.start();else this.onError_(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.SRC_EQUALS_PRELOAD_NOT_SUPPORTED));return a}async destroyAllPreloads(){const a=
[];for(const b of this.createdPreloadManagers_)b.isDestroyed()||a.push(b.destroy());this.createdPreloadManagers_=[];await Promise.all(a)}async preloadInner_(a,b,c,d=!1,e){goog.asserts.assert(this.networkingEngine_,"Should have a net engine!");goog.asserts.assert(this.config_,"Config must not be null!");c||=await this.guessMimeType_(a);if(this.shouldUseSrcEquals_(c))return null;e=e||this.config_;let f=!1;d&&this.video_&&this.video_.nodeName==="AUDIO"&&(f=!0);a=this.makePreloadManager_(a,b,c||null,
e,!d,f);return a=d?a.then(g=>{g.markIsLoad();return g}):a.then(g=>{this.createdPreloadManagers_.push(g);return g})}async makePreloadManager_(a,b,c,d,e=!0,f=!1){goog.asserts.assert(this.networkingEngine_,"Must have net engine");let g=null;d=shaka.util.ObjectUtils.cloneObject(d);f&&(d.manifest.disableVideo=!0);const h=()=>{goog.asserts.assert(g,"Must have preload manager");return g.hasBeenAttached()&&g.isDestroyed()?null:g},k=()=>h()?h().getConfiguration():this.config_;this.maxHwRes_.width!=Infinity||
this.maxHwRes_.height!=Infinity||this.config_.ignoreHardwareResolution||(f=shaka.device.DeviceFactory.getDevice(),goog.asserts.assert(f,"device must be non-null"),f=await f.detectMaxHardwareResolution(),this.maxHwRes_.width=f.width,this.maxHwRes_.height=f.height);const l=new shaka.media.ManifestFilterer(d,this.maxHwRes_,null);f={networkingEngine:this.networkingEngine_,filter:async t=>{await l.filterManifest(t)&&(t=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.TracksChanged),await Promise.resolve(),
g.dispatchEvent(t))},makeTextStreamsForClosedCaptions:t=>this.makeTextStreamsForClosedCaptions_(t),onTimelineRegionAdded:t=>{g.getRegionTimeline().addRegion(t)},onEvent:t=>g.dispatchEvent(t),onError:t=>g.onError(t),isLowLatencyMode:()=>k().streaming.lowLatencyMode,updateDuration:()=>{this.streamingEngine_&&g.hasBeenAttached()&&this.streamingEngine_.updateDuration()},newDrmInfo:t=>{const u=g.getDrmEngine(),v=u?u.getDrmInfo():null;v&&u.getMediaKeys()&&l.processDrmInfos(v.keySystem,t)},onManifestUpdated:()=>
{const t=shaka.util.FakeEvent.EventName.ManifestUpdated,u=(new Map).set("isLive",this.isLive());g.dispatchEvent(shaka.Player.makeEvent_(t,u));g.addQueuedOperation(!1,()=>{if(this.adManager_)this.adManager_.onManifestUpdated(this.isLive())})},getBandwidthEstimate:()=>this.abrManager_.getBandwidthEstimate(),onMetadata:(t,u,v,x)=>{let y=t;if(t=="com.apple.hls.interstitial"||t=="com.apple.hls.overlay")y="com.apple.quicktime.HLS",t={startTime:u,endTime:v,values:x},this.adManager_&&(goog.asserts.assert(this.video_,
"Must have video"),this.adManager_.onHLSInterstitialMetadata(this,this.video_,t));for(const A of x)A.name!="ID"&&g.addQueuedOperation(!1,()=>{this.addMetadataToRegionTimeline_(u,v,y,A)})},disableStream:t=>this.disableStream(t,this.config_.streaming.maxDisabledTime),addFont:(t,u)=>this.addFont(t,u)};const m=new shaka.media.RegionTimeline(()=>this.seekRange());m.addEventListener("regionadd",t=>{const u=t.region;this.onRegionEvent_(shaka.util.FakeEvent.EventName.TimelineRegionAdded,u,g);g.addQueuedOperation(!1,
()=>{this.adManager_&&(this.adManager_.onDashTimedMetadata(u),goog.asserts.assert(this.video_,"Must have video"),this.adManager_.onDASHInterstitialMetadata(this,this.video_,u))})});let n=null;d.streaming.observeQualityChanges&&(n=new shaka.media.QualityObserver(()=>this.getBufferedInfo()),n.addEventListener("qualitychange",t=>{this.onMediaQualityChange_(t.quality,t.position)}),n.addEventListener("audiotrackchange",t=>{this.onMediaQualityChange_(t.quality,t.position,!0)}));let q=!0;const p={netEngine:this.networkingEngine_,
onError:t=>g.onError(t),onKeyStatus:t=>{g.addQueuedOperation(!0,()=>{if(this.drmEngine_)this.onKeyStatus_(t)})},onExpirationUpdated:(t,u)=>{var v=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.ExpirationUpdated);g.dispatchEvent(v);if((v=g.getParser())&&v.onExpirationUpdated)v.onExpirationUpdated(t,u)},onEvent:t=>{g.dispatchEvent(t);t.type==shaka.util.FakeEvent.EventName.DrmSessionUpdate&&q&&(q=!1,t=Date.now()/1E3-g.getStartTimeOfDRM(),(this.stats_||g.getStats()).setDrmTime(t),this.lcevcDec_&&
this.lcevcDec_.hideCanvas())}},r=this.createNetworkingEngine(h);this.networkingEngine_.copyFiltersInto(r);return g=new shaka.media.PreloadManager(a,c,b,{config:d,manifestPlayerInterface:f,regionTimeline:m,qualityObserver:n,createDrmEngine:()=>this.createDrmEngine(p),manifestFilterer:l,networkingEngine:r,allowPrefetch:e})}async guessMimeType_(a){goog.asserts.assert(this.networkingEngine_,"Should have a net engine!");a=await shaka.net.NetworkingUtils.getMimeType(a,this.networkingEngine_,this.config_.manifest.retryParameters);
shaka.util.MimeUtils.isHlsType(a)?shaka.device.DeviceFactory.getDevice().getBrowserEngine()===shaka.device.IDevice.BrowserEngine.WEBKIT&&(a="application/vnd.apple.mpegurl"):a==="video/quicktime"&&shaka.device.DeviceFactory.getDevice().getBrowserEngine()===shaka.device.IDevice.BrowserEngine.CHROMIUM&&(a="video/mp4");return a}shouldUseSrcEquals_(a){const b=shaka.util.MimeUtils;if(!shaka.device.DeviceFactory.getDevice().supportsMediaSource())return!0;if(a){const c=(this.video_||shaka.util.Dom.anyMediaElement()).canPlayType(a)!=
"";if(!c)return!1;const d=shaka.media.ManifestParser.isSupported(a);if(!d)return!0;goog.asserts.assert(c&&d,"Both native and MSE playback should be possible!");if(b.isHlsType(a))return shaka.device.DeviceFactory.getDevice().getBrowserEngine()===shaka.device.IDevice.BrowserEngine.WEBKIT&&(this.config_.drm.servers["com.apple.fps"]||this.config_.drm.servers["com.apple.fps.1_0"])?this.config_.streaming.useNativeHlsForFairPlay:this.config_.streaming.preferNativeHls;if(b.isDashType(a))return this.config_.streaming.preferNativeDash}return!1}createAndConfigureTextDisplayer_(a=
!1){const b=this.config_.textDisplayFactory;this.lastTextFactory_!==b||a?(a=this.textDisplayer_,this.textDisplayer_=b(),this.textDisplayer_.configure?this.textDisplayer_.configure(this.config_.textDisplayer):shaka.Deprecate.deprecateFeature(5,"Text displayer w/ configure",'Text displayer should have a "configure" method!'),this.textDisplayer_.setTextLanguage||shaka.Deprecate.deprecateFeature(5,"Text displayer w/ setTextLanguage",'Text displayer should have a "setTextLanguage" method!'),a?(this.textDisplayer_.setTextVisibility(a.isTextVisible()),
a.destroy().catch(()=>{})):this.textDisplayer_.setTextVisibility(this.isTextVisible_),this.mediaSourceEngine_&&this.mediaSourceEngine_.setTextDisplayer(this.textDisplayer_),this.lastTextFactory_=b,this.streamingEngine_&&this.streamingEngine_.reloadTextStream()):this.textDisplayer_&&this.textDisplayer_.configure&&this.textDisplayer_.configure(this.config_.textDisplayer)}async initializeMediaSourceEngineInner_(){var a=shaka.device.DeviceFactory.getDevice();goog.asserts.assert(a.supportsMediaSource(),
"We should not be initializing media source on a platform that does not support media source.");goog.asserts.assert(this.video_,"We should have a media element when initializing media source.");goog.asserts.assert(this.mediaSourceEngine_==null,"We should not have a media source engine yet.");this.makeStateChangeEvent_("media-source");this.config_.mediaSource.useSourceElements&&shaka.util.Dom.clearSourceFromVideo(this.video_);this.createAndConfigureTextDisplayer_();goog.asserts.assert(this.textDisplayer_,
"Text displayer should be created already");a=this.createMediaSourceEngine(this.video_,this.textDisplayer_,{getKeySystem:()=>this.keySystem(),onMetadata:(c,d,e)=>{this.processTimedMetadataMediaSrc_(c,d,e)},onEmsg:c=>{this.addEmsgToRegionTimeline_(c)},onEvent:c=>this.dispatchEvent(c),onManifestUpdate:()=>this.onManifestUpdate_()},this.lcevcDec_,this.config_.mediaSource);const {segmentRelativeVttTiming:b}=this.config_.manifest;a.setSegmentRelativeVttTiming(b);await a.open();this.mediaSourceEngine_=
a}setupPlayRateController_(a){this.playRateController_=new shaka.media.PlayRateController({getRate:()=>a.playbackRate,getDefaultRate:()=>a.defaultPlaybackRate,setRate:b=>{a.playbackRate=b},movePlayhead:b=>{const c=a.currentTime;if(shaka.media.TimeRangesUtils.isBuffered(a.buffered,c)&&!(a.readyState<=HTMLMediaElement.HAVE_CURRENT_DATA)){b=c+b;var d=this.seekRange();b<d.start?c!==d.start&&(a.currentTime=d.start):b>d.end?c!==d.end&&(a.currentTime=d.end):a.currentTime=b}},isPaused:()=>a.paused})}addBasicMediaListeners_(a,
b){const c=()=>this.updateStateHistory_();this.loadEventManager_.listen(a,"playing",c);this.loadEventManager_.listen(a,"pause",c);this.loadEventManager_.listen(a,"ended",c);this.loadEventManager_.listen(a,"ratechange",()=>this.onRateChange_());a.remote&&(this.loadEventManager_.listen(a.remote,"connect",()=>{if(this.streamingEngine_&&a.remote.state=="connected")this.onTextChanged_();this.onTracksChanged_()}),this.loadEventManager_.listen(a.remote,"connecting",()=>this.onTracksChanged_()),this.loadEventManager_.listen(a.remote,
"disconnect",async()=>{this.streamingEngine_&&a.remote.state=="disconnected"&&(await this.streamingEngine_.resetMediaSource(),this.onTextChanged_());this.onTracksChanged_()}));a.audioTracks&&(this.loadEventManager_.listen(a.audioTracks,"addtrack",()=>this.onTracksChanged_()),this.loadEventManager_.listen(a.audioTracks,"removetrack",()=>this.onTracksChanged_()),this.loadEventManager_.listen(a.audioTracks,"change",()=>this.onTracksChanged_()));a.videoTracks&&(this.loadEventManager_.listen(a.videoTracks,
"addtrack",()=>this.onTracksChanged_()),this.loadEventManager_.listen(a.videoTracks,"removetrack",()=>this.onTracksChanged_()),this.loadEventManager_.listen(a.videoTracks,"change",()=>this.onTracksChanged_()));(a.webkitPresentationMode||a.webkitSupportsFullscreen)&&this.loadEventManager_.listen(a,"webkitpresentationmodechanged",()=>{this.videoContainer_&&this.createAndConfigureTextDisplayer_(!0)});if(a.textTracks){const d=()=>{if(this.loadMode_===shaka.Player.LoadMode.SRC_EQUALS&&this.textDisplayer_ instanceof
shaka.text.NativeTextDisplayer)this.onTextChanged_();this.onTracksChanged_()};this.loadEventManager_.listen(a.textTracks,"addtrack",e=>{if(e.track)switch(e=e.track,goog.asserts.assert(e instanceof TextTrack,"Wrong track type!"),e.kind){case "metadata":this.processTimedMetadataSrcEquals_(e);break;case "chapters":this.activateChaptersTrack_(e);break;default:d()}});this.loadEventManager_.listen(a.textTracks,"removetrack",d);this.loadEventManager_.listen(a.textTracks,"change",d)}a.preload!="none"&&this.loadEventManager_.listenOnce(a,
"loadedmetadata",()=>{const d=Date.now()/1E3-b;this.stats_.setLoadLatency(d)})}async loadInner_(a,b,c){goog.asserts.assert(this.video_,"We should have a media element by now.");goog.asserts.assert(this.manifest_,"The manifest should already be parsed.");goog.asserts.assert(this.assetUri_,"We should have an asset uri by now.");goog.asserts.assert(this.abrManager_,"We should have an abr manager by now.");this.makeStateChangeEvent_("load");const d=this.video_;this.setupPlayRateController_(d);this.addBasicMediaListeners_(d,
a);"onchange"in window.screen&&this.loadEventManager_.listen(window.screen,"change",()=>{if(this.currentAdaptationSetCriteria_.getConfiguration){const l=this.currentAdaptationSetCriteria_.getConfiguration();l.hdrLevel=="AUTO"?this.updateAbrManagerVariants_():this.config_.preferredVideoHdrLevel=="AUTO"&&this.config_.abr.enabled&&(l.hdrLevel="AUTO",this.currentAdaptationSetCriteria_.configure(l),this.updateAbrManagerVariants_())}});var e=!1;for(var f of this.manifest_.variants){var g=f.video&&f.video.dependencyStream;
g&&(e=shaka.lcevc.Dec.isStreamSupported(g))}this.setupLcevc_(this.config_,e);this.currentTextLanguage_=this.config_.preferredTextLanguage;this.currentTextRole_=this.config_.preferredTextRole;this.currentTextForced_=this.config_.preferForcedSubs;shaka.Player.applyPlayRange_(this.manifest_.presentationTimeline,this.config_.playRangeStart,this.config_.playRangeEnd);this.abrManager_.init((l,m,n)=>this.switch_(l,m,n));this.abrManager_.setMediaElement(d);this.abrManager_.setCmsdManager(this.cmsdManager_);
this.streamingEngine_=this.createStreamingEngine();this.streamingEngine_.configure(this.config_.streaming);this.loadMode_=shaka.Player.LoadMode.MEDIA_SOURCE;this.dispatchEvent(shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.Streaming));e=b;do{f=this.streamingEngine_.getCurrentVariant();f||(g=this.chooseVariant_(!0),b||(e=g),goog.asserts.assert(e,"Must choose an initial variant!"));const l=[];g=f||e;for(var h of[g.video,g.audio])h&&!h.segmentIndex&&(l.push(h.createSegmentIndex()),h.dependencyStream&&
l.push(h.dependencyStream.createSegmentIndex()));l.length>0&&await Promise.all(l)}while(!g||g.disabledUntilTime!=0);this.updateAbrManagerVariants_();if(this.parser_&&this.parser_.onInitialVariantChosen)this.parser_.onInitialVariantChosen(g);this.manifest_.isLowLatency&&(this.config_.streaming.lowLatencyMode?this.configure(this.lowLatencyConfig_):shaka.log.alwaysWarn("Low-latency live stream detected, but low-latency streaming mode is not enabled in Shaka Player. Set streaming.lowLatencyMode configuration to true, and see https://bit.ly/3clctcj for details."));
this.cmcdManager_&&(this.cmcdManager_.setLowLatency(this.manifest_.isLowLatency&&this.config_.streaming.lowLatencyMode),this.cmcdManager_.setStartTimeOfLoad(a*1E3));shaka.Player.applyPlayRange_(this.manifest_.presentationTimeline,this.config_.playRangeStart,this.config_.playRangeEnd);this.streamingEngine_.applyPlayRange(this.config_.playRangeStart,this.config_.playRangeEnd);this.fullyLoaded_=!0;this.dispatchEvent(shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.CanUpdateStartTime));a=l=>{this.playhead_=
this.createPlayhead(l);this.playheadObservers_=this.createPlayheadObserversForMSE_(l);this.startBufferManagement_(d,!1)};this.config_.streaming.startAtSegmentBoundary||(b=this.startTime_,b==null&&this.manifest_.startTime&&(b=this.manifest_.startTime),a(b));if(!f){goog.asserts.assert(e,"Must have chosen an initial variant!");if(this.config_.streaming.startAtSegmentBoundary){b=this.manifest_.presentationTimeline;var k;this.startTime_ instanceof Date&&(h=b.getInitialProgramDateTime()||b.getPresentationStartTime(),
goog.asserts.assert(h!=null,"Presentation start time should not be null!"),h=this.startTime_.getTime()/1E3-h,h!=null&&(k=h));k==null&&(k=typeof this.startTime_==="number"?this.startTime_:this.isLive()?Infinity:this.video_.currentTime);this.startTime_==null&&this.manifest_.startTime&&(k=this.manifest_.startTime);h=b.getSeekRangeStart();b=b.getSeekRangeEnd();k<h?k=h:k>b&&(k=b);k=await this.adjustStartTime_(e,k);a(k)}this.switchVariant_(e,!0,!1,0)}this.playhead_.ready();this.getTextTracks().find(l=>
l.active)||((k=this.chooseTextStream_())&&this.addTextStreamToSwitchHistory_(k,!0),e&&this.setInitialTextState_(e,k),k&&this.shouldStreamText_()&&(this.streamingEngine_.switchTextStream(k),this.setTextDisplayerLanguage_()));await this.streamingEngine_.start(c);this.config_.abr.enabled&&(this.abrManager_.enable(),this.onAbrStatusChanged_());this.onTracksChanged_();c=this.manifest_.variants.some(l=>l.primary);this.config_.preferredAudioLanguage||c||shaka.log.warning("No preferred audio language set.  We have chosen an arbitrary language initially");
((c=this.isLive())&&(this.config_.streaming.liveSync&&this.config_.streaming.liveSync.enabled||this.manifest_.serviceDescription||this.config_.streaming.liveSync.panicMode)||this.config_.streaming.vodDynamicPlaybackRate)&&this.loadEventManager_.listen(d,"timeupdate",()=>this.onTimeUpdate_());if(!c&&(this.loadEventManager_.listen(d,"timeupdate",()=>this.onVideoProgress_()),this.onVideoProgress_(),this.manifest_.nextUrl)){if(this.config_.streaming.preloadNextUrlWindow>0){const l=async()=>{const m=this.seekRange().end-
this.video_.currentTime;!isNaN(m)&&m<=this.config_.streaming.preloadNextUrlWindow&&(this.loadEventManager_.unlisten(d,"timeupdate",l),goog.asserts.assert(this.manifest_.nextUrl,"this.manifest_.nextUrl should be valid."),this.preloadNextUrl_=await this.preload(this.manifest_.nextUrl))};this.loadEventManager_.listen(d,"timeupdate",l)}this.loadEventManager_.listen(d,"ended",()=>{this.load(this.preloadNextUrl_||this.manifest_.nextUrl)})}if(this.adManager_)this.adManager_.onManifestUpdated(c)}async initializeSrcEqualsDrmInner_(a){goog.asserts.assert(this.networkingEngine_,
"|onInitializeSrcEqualsDrm_| should never be called after |destroy|");goog.asserts.assert(this.config_,"|onInitializeSrcEqualsDrm_| should never be called after |destroy|");const b=Date.now()/1E3;let c=!0;this.drmEngine_=this.createDrmEngine({netEngine:this.networkingEngine_,onError:d=>{this.onError_(d)},onKeyStatus:d=>{},onExpirationUpdated:(d,e)=>{d=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.ExpirationUpdated);this.dispatchEvent(d)},onEvent:d=>{this.dispatchEvent(d);d.type==shaka.util.FakeEvent.EventName.DrmSessionUpdate&&
c&&(c=!1,d=Date.now()/1E3-b,this.stats_.setDrmTime(d))}});this.drmEngine_.configure(this.config_.drm);a=shaka.util.StreamUtils.createEmptyVariant([a]);this.drmEngine_.setSrcEquals(!0);await this.drmEngine_.initForPlayback([a],[]);await this.drmEngine_.attach(this.video_)}async srcEqualsInner_(a,b){this.makeStateChangeEvent_("src-equals");goog.asserts.assert(this.video_,"We should have a media element when loading.");goog.asserts.assert(this.assetUri_,"We should have a valid uri when loading.");const c=
this.video_;this.playhead_=new shaka.media.SrcEqualsPlayhead(c);let d=!1;this.cleanupOnUnload_.push(()=>{d=!0});this.dispatchEvent(shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.CanUpdateStartTime));this.startTime_!=null&&this.playhead_.setStartTime(this.startTime_);this.playheadObservers_=this.createPlayheadObserversForSrcEquals_(this.startTime_||0);this.setupPlayRateController_(c);this.startBufferManagement_(c,!0);if(c.textTracks){this.createAndConfigureTextDisplayer_();const g=h=>{if(!(this.textDisplayer_ instanceof
shaka.text.NativeTextDisplayer)){var k=this.getFilteredTextTracks_().find(l=>l.mode!=="disabled");k&&(k.mode=h?"showing":"hidden");this.textDisplayer_ instanceof shaka.text.SimpleTextDisplayer&&(k=this.getGeneratedTextTrack_())&&(k.mode=!h&&this.textDisplayer_.isTextVisible()?"showing":"hidden")}};this.loadEventManager_.listen(c,"enterpictureinpicture",()=>g(!0));this.loadEventManager_.listen(c,"leavepictureinpicture",()=>g(!1));c.remote?(this.loadEventManager_.listen(c.remote,"connect",()=>g(!1)),
this.loadEventManager_.listen(c.remote,"connecting",()=>g(!1)),this.loadEventManager_.listen(c.remote,"disconnect",()=>g(!1))):"webkitCurrentPlaybackTargetIsWireless"in c&&this.loadEventManager_.listen(c,"webkitcurrentplaybacktargetiswirelesschanged",()=>g(!1));(c.webkitPresentationMode||c.webkitSupportsFullscreen)&&this.loadEventManager_.listen(c,"webkitpresentationmodechanged",()=>{c.webkitPresentationMode?g(c.webkitPresentationMode!=="inline"):c.webkitSupportsFullscreen&&g(c.webkitDisplayingFullscreen)})}this.addBasicMediaListeners_(c,
a);a=this.cmcdManager_.appendSrcData(this.assetUri_,b);!a.includes("#t=")&&(this.config_.playRangeStart>0||isFinite(this.config_.playRangeEnd))&&(a+="#t=",this.config_.playRangeStart>0&&(a+=this.config_.playRangeStart),isFinite(this.config_.playRangeEnd)&&(a+=","+this.config_.playRangeEnd));this.mediaSourceEngine_&&(await this.mediaSourceEngine_.destroy(),this.mediaSourceEngine_=null);shaka.util.Dom.clearSourceFromVideo(c);c.src=a;a=shaka.device.DeviceFactory.getDevice();a.getDeviceType()==shaka.device.IDevice.DeviceType.TV&&
c.load();c.preload!="none"&&!c.autoplay&&shaka.util.MimeUtils.isHlsType(b)&&a.getBrowserEngine()===shaka.device.IDevice.BrowserEngine.WEBKIT&&c.load();this.loadMode_=shaka.Player.LoadMode.SRC_EQUALS;this.dispatchEvent(shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.Streaming));const e=()=>new Promise(g=>{const h=new shaka.util.Timer(g);this.loadEventManager_.listen(c.textTracks,"change",()=>h.tickAfter(.5));h.tickAfter(.5)}),f=new shaka.util.PublicPromise;shaka.util.MediaReadyState.waitForReadyState(c,
HTMLMediaElement.HAVE_METADATA,this.loadEventManager_,async()=>{this.playhead_.ready();this.mimeType_&&shaka.util.MimeUtils.isHlsType(this.mimeType_)&&await e();f.resolve()});shaka.util.MediaReadyState.waitForReadyState(c,HTMLMediaElement.HAVE_CURRENT_DATA,this.loadEventManager_,async()=>{await e();if(!d){this.setupPreferredAudioOnSrc_();var g=this.getFilteredTextTracks_();g.some(h=>h.mode==="showing")&&(this.isTextVisible_=!0,this.textDisplayer_.setTextVisibility(!0));if(!(this.textDisplayer_ instanceof
shaka.text.NativeTextDisplayer)){g.length&&(this.textDisplayer_.enableTextDisplayer?this.textDisplayer_.enableTextDisplayer():shaka.Deprecate.deprecateFeature(5,"Text displayer w/ enableTextDisplayer",'Text displayer should have a "enableTextDisplayer" method'));let h=!1;for(const k of g)k.mode!=="disabled"&&(h?(k.mode="disabled",shaka.log.alwaysWarn("Found more than one enabled text track, disabling it",k)):(this.enableNativeTrack_(k),h=!0))}this.setupPreferredTextOnSrc_()}});c.error?f.reject(this.videoErrorToShakaError_()):
c.preload=="none"&&(shaka.log.alwaysWarn('With <video preload="none">, the browser will not load anything until play() is called. We are unable to measure load latency in a meaningful way, and we cannot provide track info yet. Please do not use preload="none" with Shaka Player.'),f.resolve());this.loadEventManager_.listenOnce(c,"error",()=>{f.reject(this.videoErrorToShakaError_())});await shaka.util.Functional.promiseWithTimeout(this.config_.streaming.loadTimeout,f);((b=this.isLive())&&(this.config_.streaming.liveSync&&
this.config_.streaming.liveSync.enabled||this.config_.streaming.liveSync.panicMode)||this.config_.streaming.vodDynamicPlaybackRate)&&this.loadEventManager_.listen(c,"timeupdate",()=>this.onTimeUpdate_());b||(this.loadEventManager_.listen(c,"timeupdate",()=>this.onVideoProgress_()),this.onVideoProgress_());if(this.adManager_&&(this.adManager_.onManifestUpdated(b),b)){let g=this.seekRange().end;this.loadEventManager_.listen(c,"progress",()=>{const h=this.seekRange().end;g!=h&&(this.adManager_.onManifestUpdated(this.isLive()),
g=h)})}this.fullyLoaded_=!0}setupPreferredAudioOnSrc_(){const a=this.config_.preferredAudioLanguage;a!=""&&this.selectAudioLanguage(a,this.config_.preferredAudioRole)}setupPreferredTextOnSrc_(){const a=this.config_.preferredTextLanguage;a!=""&&this.selectTextLanguage(a,this.config_.preferredTextRole,this.config_.preferForcedSubs)}processTimedMetadataSrcEquals_(a){if(a.kind=="metadata"){a.mode="hidden";this.loadEventManager_.listen(a,"cuechange",()=>{if(a.activeCues)for(var c of a.activeCues)if(this.addMetadataToRegionTimeline_(c.startTime,
c.endTime,c.type,c.value),this.adManager_)this.adManager_.onCueMetadataChange(c.value);if(a.cues){c=[];for(const d of a.cues)if(d.type=="com.apple.quicktime.HLS"&&d.startTime!=null){let e=c.find(f=>f.startTime==d.startTime&&f.endTime==d.endTime);e||(e={startTime:d.startTime,endTime:d.endTime,values:[]},c.push(e));e.values.push(d.value)}for(const d of c)d.values.some(e=>e.key=="X-ASSET-URI"||e.key=="X-ASSET-LIST")&&this.adManager_&&(c=d.startTime==0&&!this.isLive(),d.values.push({key:"CUE",description:"",
data:c?"ONCE,PRE":"ONCE",mimeType:null,pictureType:null}),goog.asserts.assert(this.video_,"Must have video"),this.adManager_.onHLSInterstitialMetadata(this,this.video_,d))}});var b=(new shaka.util.Timer(()=>{const c=this.getMetadataTracks_();for(const d of c)d.mode="hidden"})).tickNow().tickAfter(.5);this.cleanupOnUnload_.push(()=>{b.stop()})}}processTimedMetadataMediaSrc_(a,b,c){for(const d of a)if(d.data&&typeof d.cueTime=="number"&&d.frames){a=d.cueTime+b;let e=c;e&&a>e&&(e=a);for(const f of d.frames)this.addMetadataToRegionTimeline_(a,
e,"org.id3",f);if(this.adManager_)this.adManager_.onHlsTimedMetadata(d,a)}}dispatchMetadataEvent_(a,b){a=(new Map).set("startTime",a.startTime).set("endTime",a.endTime).set("metadataType",a.schemeIdUri).set("payload",a.payload);this.dispatchEvent(shaka.Player.makeEvent_(b,a))}addMetadataToRegionTimeline_(a,b,c,d){this.metadataRegionTimeline_&&(goog.asserts.assert(!b||a<=b,"Metadata start time should be less or equal to the end time!"),a={schemeIdUri:c,startTime:a,endTime:b||Infinity,id:"",payload:d},
a.id=JSON.stringify(a),this.metadataRegionTimeline_.addRegion(a))}dispatchEmsgEvent_(a){const b=shaka.util.FakeEvent.EventName.Emsg;a=a.emsg;a=(new Map).set("detail",a);this.dispatchEvent(shaka.Player.makeEvent_(b,a))}addEmsgToRegionTimeline_(a){this.emsgRegionTimeline_&&this.emsgRegionTimeline_.addRegion({schemeIdUri:a.schemeIdUri,startTime:a.startTime,endTime:a.endTime,id:String(a.id),emsg:a})}activateChaptersTrack_(a){if(a&&a.kind=="chapters"){a.mode="hidden";var b=(new shaka.util.Timer(()=>{a.mode=
"hidden"})).tickNow().tickAfter(.5);this.cleanupOnUnload_.push(()=>{b.stop()})}}releaseAllMutexes(){this.mutex_.releaseAll()}createDrmEngine(a){return new shaka.drm.DrmEngine(a)}createNetworkingEngine(a){a||=()=>null;const b=()=>a()?a().getParser():this.parser_,c=g=>{a()?a().addQueuedOperation(!0,g):g()},d=g=>{a()?a().dispatchEvent(g):this.dispatchEvent(g)},e=()=>a()?a().getStats():this.stats_,f=new shaka.net.NetworkingEngine((g,h,k,l,m)=>{c(()=>{this.abrManager_&&this.abrManager_.segmentDownloaded(g,
h,k,l,m)})},(g,h,k)=>{const l=shaka.util.FakeEvent.EventName.DownloadHeadersReceived;h=(new Map).set("headers",g).set("request",h).set("requestType",k);d(shaka.Player.makeEvent_(l,h));c(()=>{this.cmsdManager_&&this.cmsdManager_.processHeaders(g)})},(g,h)=>{const k=shaka.util.FakeEvent.EventName.DownloadCompleted;g=(new Map).set("request",g).set("response",h);d(shaka.Player.makeEvent_(k,g))},(g,h,k,l)=>{const m=shaka.util.FakeEvent.EventName.DownloadFailed;g=(new Map).set("request",g).set("error",
h).set("httpResponseCode",k).set("aborted",l);d(shaka.Player.makeEvent_(m,g))},(g,h,k)=>{c(()=>{this.cmcdManager_&&this.cmcdManager_.applyRequestData(g,h,k)})},(g,h,k,l)=>{(g=b())&&g.banLocation&&g.banLocation(l)},(g,h,k)=>{if(h.data){const l=h.data.byteLength,m=e();m&&(m.addBytesDownloaded(l),g===shaka.net.NetworkingEngine.RequestType.MANIFEST&&m.setManifestSize(l));this.cmcdManager_.applyResponseData(g,h,k)}});f.configure(this.config_.networking);return f}createPlayhead(a){goog.asserts.assert(this.manifest_,
"Must have manifest");goog.asserts.assert(this.video_,"Must have video");return new shaka.media.MediaSourcePlayhead(this.video_,this.manifest_,this.config_.streaming,a,()=>this.onSeek_(),b=>this.dispatchEvent(b))}createPlayheadObserversForMSE_(a){goog.asserts.assert(this.manifest_,"Must have manifest");goog.asserts.assert(this.regionTimeline_,"Must have region timeline");goog.asserts.assert(this.metadataRegionTimeline_,"Must have metadata region timeline");goog.asserts.assert(this.emsgRegionTimeline_,
"Must have emsg region timeline");goog.asserts.assert(this.video_,"Must have video element");var b=this.isLive()||typeof a==="number"&&a>0;a=new shaka.media.RegionObserver(this.regionTimeline_,b);a.addEventListener("enter",e=>{this.onRegionEvent_(shaka.util.FakeEvent.EventName.TimelineRegionEnter,e.region)});a.addEventListener("exit",e=>{this.onRegionEvent_(shaka.util.FakeEvent.EventName.TimelineRegionExit,e.region)});a.addEventListener("skip",e=>{const f=e.region;e.seeking||(this.onRegionEvent_(shaka.util.FakeEvent.EventName.TimelineRegionEnter,
f),this.onRegionEvent_(shaka.util.FakeEvent.EventName.TimelineRegionExit,f))});const c=new shaka.media.RegionObserver(this.metadataRegionTimeline_,b);c.addEventListener("enter",e=>{this.dispatchMetadataEvent_(e.region,shaka.util.FakeEvent.EventName.Metadata)});b=new shaka.media.RegionObserver(this.emsgRegionTimeline_,b);b.addEventListener("enter",e=>{this.dispatchEmsgEvent_(e.region)});const d=new shaka.media.PlayheadObserverManager(this.video_);d.manage(a);d.manage(c);d.manage(b);this.qualityObserver_&&
d.manage(this.qualityObserver_);return d}createPlayheadObserversForSrcEquals_(a){goog.asserts.assert(this.metadataRegionTimeline_,"Must have metadata region timeline");goog.asserts.assert(this.video_,"Must have video element");a=new shaka.media.RegionObserver(this.metadataRegionTimeline_,a instanceof Date||a>0);a.addEventListener("enter",c=>{this.dispatchMetadataEvent_(c.region,shaka.util.FakeEvent.EventName.Metadata)});const b=new shaka.media.PlayheadObserverManager(this.video_);b.manage(a);return b}startBufferManagement_(a,
b){const c=shaka.util.MediaElementEvent;goog.asserts.assert(!this.bufferObserver_,"No buffering observer should exist before initialization.");goog.asserts.assert(!this.bufferPoller_,"No buffer timer should exist before initialization.");this.bufferObserver_=new shaka.media.BufferingObserver(1,2);this.bufferObserver_.setState(shaka.media.BufferingObserver.State.STARVING);this.updateBufferingSettings_();this.updateBufferState_();this.bufferPoller_=new shaka.util.Timer(()=>{this.pollBufferState_()});
this.config_.streaming.rebufferingGoal&&this.bufferPoller_.tickEvery(.25);this.loadEventManager_.listen(a,c.WAITING,d=>this.pollBufferState_(c.WAITING));this.loadEventManager_.listen(a,c.CAN_PLAY_THROUGH,d=>this.pollBufferState_(c.CAN_PLAY_THROUGH));this.loadEventManager_.listen(a,c.PLAYING,d=>this.pollBufferState_(c.PLAYING));this.loadEventManager_.listen(a,c.SEEKED,d=>this.pollBufferState_(c.SEEKED));this.loadEventManager_.listen(a,c.TIME_UPDATE,d=>this.pollBufferState_(c.TIME_UPDATE));b&&(this.loadEventManager_.listen(a,
c.PROGRESS,d=>this.pollBufferState_(c.PROGRESS)),this.loadEventManager_.listen(a,c.STALLED,d=>this.pollBufferState_(c.STALLED)))}updateBufferingSettings_(){const a=this.config_.streaming.rebufferingGoal;this.bufferObserver_.setThresholds(a,Math.min(shaka.Player.TYPICAL_BUFFERING_THRESHOLD_,a/2))}pollBufferState_(a){goog.asserts.assert(this.video_,"Need a media element to update the buffering observer");goog.asserts.assert(this.bufferObserver_,"Need a buffering observer to update");if(this.config_.streaming.rebufferingGoal){a=
this.mediaSourceEngine_?this.mediaSourceEngine_.ended():!1;a=this.isEnded()||a||this.playhead_.isBufferedToEnd();var b=shaka.media.TimeRangesUtils.bufferedAheadOf(this.video_.buffered,this.video_.currentTime);this.bufferObserver_.update(b,a)&&this.updateBufferState_()}else a&&this.bufferObserver_.reportEvent(a,this.video_.currentTime)&&this.updateBufferState_()}createMediaSourceEngine(a,b,c,d,e){return new shaka.media.MediaSourceEngine(a,b,c,e,d)}createCmcd_(){return new shaka.util.CmcdManager(this,
this.config_.cmcd)}createCmsd_(){return new shaka.util.CmsdManager(this.config_.cmsd)}createStreamingEngine(){goog.asserts.assert(this.abrManager_&&this.mediaSourceEngine_&&this.manifest_&&this.video_,"Must not be destroyed");return new shaka.media.StreamingEngine(this.manifest_,{getPresentationTime:()=>this.playhead_?this.playhead_.getTime():0,getBandwidthEstimate:()=>this.abrManager_.getBandwidthEstimate(),getPlaybackRate:()=>this.getPlaybackRate(),video:this.video_,mediaSourceEngine:this.mediaSourceEngine_,
netEngine:this.networkingEngine_,onError:a=>this.onError_(a),onEvent:a=>this.dispatchEvent(a),onSegmentAppended:(a,b,c,d)=>{this.onSegmentAppended_(a.startTime,a.endTime,b.type,c,d);this.abrManager_&&b.fastSwitching&&a.isPartial()&&a.isLastPartial()&&this.abrManager_.trySuggestStreams()},onInitSegmentAppended:(a,b)=>{(b=b.getMediaQuality())&&this.qualityObserver_&&this.qualityObserver_.addMediaQualityChange(b,a)},beforeAppendSegment:(a,b)=>this.drmEngine_.parseInbandPssh(a,b),disableStream:(a,b)=>
this.disableStream(a,b),shouldPrefetchNextSegment:(a,b)=>this.config_.abr.enabled&&b.fastSwitching&&a.isPartial()&&a.isLastPartial()?!1:!0})}configure(a,b){goog.asserts.assert(this.config_,"Config must not be null!");goog.asserts.assert(typeof a=="object"||arguments.length==2,"String configs should have values!");const c=this.getConfiguration();arguments.length==2&&typeof a=="string"&&(a=shaka.util.ConfigUtils.convertToConfigObject(a,b));goog.asserts.assert(typeof a=="object","Should be an object!");
"preferredVariantRole"in a&&(shaka.Deprecate.deprecateFeature(5,"preferredVariantRole configuration","Please Use preferredAudioRole instead."),a.preferredAudioRole=a.preferredVariantRole,delete a.preferredVariantRole);a.streaming&&"forceTransmuxTS"in a.streaming&&(shaka.Deprecate.deprecateFeature(5,"streaming.forceTransmuxTS configuration","Please Use mediaSource.forceTransmux instead."),a.mediaSource=a.mediaSource||{},a.mediaSource.mediaSource=a.streaming.forceTransmuxTS,delete a.streaming.forceTransmuxTS);
a.streaming&&"forceTransmux"in a.streaming&&(shaka.Deprecate.deprecateFeature(5,"streaming.forceTransmux configuration","Please Use mediaSource.forceTransmux instead."),a.mediaSource=a.mediaSource||{},a.mediaSource.mediaSource=a.streaming.forceTransmux,delete a.streaming.forceTransmux);if(a.streaming&&"useNativeHlsOnSafari"in a.streaming){shaka.Deprecate.deprecateFeature(5,"streaming.useNativeHlsOnSafari configuration","Please Use streaming.useNativeHlsForFairPlay or streaming.preferNativeHls instead.");
var d=shaka.device.DeviceFactory.getDevice();a.streaming.preferNativeHls=a.streaming.useNativeHlsOnSafari&&d.getBrowserEngine()===shaka.device.IDevice.BrowserEngine.WEBKIT;delete a.streaming.useNativeHlsOnSafari}a.streaming&&typeof a.streaming.liveSync=="boolean"&&(shaka.Deprecate.deprecateFeature(5,"streaming.liveSync","Please Use streaming.liveSync.enabled instead."),d=a.streaming.liveSync,a.streaming.liveSync={},a.streaming.liveSync.enabled=d);if(a.streaming&&!(a.streaming.liveSync&&"targetLatency"in
a.streaming.liveSync)&&("liveSyncMinLatency"in a.streaming||"liveSyncMaxLatency"in a.streaming)){d=a.streaming.liveSyncMinLatency||0;const f=Math.abs((a.streaming.liveSyncMaxLatency||1)-d)/2;a.streaming.liveSync=a.streaming.liveSync||{};a.streaming.liveSync.targetLatency=d+f;a.streaming.liveSync.targetLatencyTolerance=f}a.streaming&&"liveSyncMaxLatency"in a.streaming&&(shaka.Deprecate.deprecateFeature(5,"streaming.liveSyncMaxLatency","Please Use streaming.liveSync.targetLatency and streaming.liveSync.targetLatencyTolerance instead. Or, set the values in your DASH manifest"),
delete a.streaming.liveSyncMaxLatency);a.streaming&&"liveSyncMinLatency"in a.streaming&&(shaka.Deprecate.deprecateFeature(5,"streaming.liveSyncMinLatency","Please Use streaming.liveSync.targetLatency and streaming.liveSync.targetLatencyTolerance instead. Or, set the values in your DASH manifest"),delete a.streaming.liveSyncMinLatency);a.streaming&&"liveSyncTargetLatency"in a.streaming&&(shaka.Deprecate.deprecateFeature(5,"streaming.liveSyncTargetLatency","Please Use streaming.liveSync.targetLatency instead."),
a.streaming.liveSync=a.streaming.liveSync||{},a.streaming.liveSync.targetLatency=a.streaming.liveSyncTargetLatency,delete a.streaming.liveSyncTargetLatency);a.streaming&&"liveSyncTargetLatencyTolerance"in a.streaming&&(shaka.Deprecate.deprecateFeature(5,"streaming.liveSyncTargetLatencyTolerance","Please Use streaming.liveSync.targetLatencyTolerance instead."),a.streaming.liveSync=a.streaming.liveSync||{},a.streaming.liveSync.targetLatencyTolerance=a.streaming.liveSyncTargetLatencyTolerance,delete a.streaming.liveSyncTargetLatencyTolerance);
a.streaming&&"liveSyncPlaybackRate"in a.streaming&&(shaka.Deprecate.deprecateFeature(5,"streaming.liveSyncPlaybackRate","Please Use streaming.liveSync.maxPlaybackRate instead."),a.streaming.liveSync=a.streaming.liveSync||{},a.streaming.liveSync.maxPlaybackRate=a.streaming.liveSyncPlaybackRate,delete a.streaming.liveSyncPlaybackRate);a.streaming&&"liveSyncMinPlaybackRate"in a.streaming&&(shaka.Deprecate.deprecateFeature(5,"streaming.liveSyncMinPlaybackRate","Please Use streaming.liveSync.minPlaybackRate instead."),
a.streaming.liveSync=a.streaming.liveSync||{},a.streaming.liveSync.minPlaybackRate=a.streaming.liveSyncMinPlaybackRate,delete a.streaming.liveSyncMinPlaybackRate);a.streaming&&"liveSyncPanicMode"in a.streaming&&(shaka.Deprecate.deprecateFeature(5,"streaming.liveSyncPanicMode","Please Use streaming.liveSync.panicMode instead."),a.streaming.liveSync=a.streaming.liveSync||{},a.streaming.liveSync.panicMode=a.streaming.liveSyncPanicMode,delete a.streaming.liveSyncPanicMode);a.streaming&&"liveSyncPanicThreshold"in
a.streaming&&(shaka.Deprecate.deprecateFeature(5,"streaming.liveSyncPanicThreshold","Please Use streaming.liveSync.panicThreshold instead."),a.streaming.liveSync=a.streaming.liveSync||{},a.streaming.liveSync.panicThreshold=a.streaming.liveSyncPanicThreshold,delete a.streaming.liveSyncPanicThreshold);if(a.mediaSource&&"sourceBufferExtraFeatures"in a.mediaSource){shaka.Deprecate.deprecateFeature(5,"mediaSource.sourceBufferExtraFeatures configuration","Please Use mediaSource.addExtraFeaturesToSourceBuffer() instead.");
const f=a.mediaSource.sourceBufferExtraFeatures;a.mediaSource.addExtraFeaturesToSourceBuffer=()=>f;delete a.mediaSource.sourceBufferExtraFeatures}a.manifest&&a.manifest.hls&&"useSafariBehaviorForLive"in a.manifest.hls&&(shaka.Deprecate.deprecateFeature(5,"manifest.hls.useSafariBehaviorForLive configuration","Please Use liveSync config to keep on live Edge instead."),delete a.manifest.hls.useSafariBehaviorForLive);a.streaming&&"parsePrftBox"in a.streaming&&(shaka.Deprecate.deprecateFeature(5,"streaming.parsePrftBox configuration",
"Now fired without needing a configuration."),delete a.streaming.parsePrftBox);a.manifest&&a.manifest.dash&&"enableAudioGroups"in a.manifest.dash&&(shaka.Deprecate.deprecateFeature(5,"manifest.dash.enableAudioGroups configuration","Please Use manifest.enableAudioGroups instead."),a.manifest.enableAudioGroups=a.manifest.dash.enableAudioGroups,delete a.manifest.dash.enableAudioGroups);a.streaming&&"dispatchAllEmsgBoxes"in a.streaming&&(shaka.Deprecate.deprecateFeature(5,"streaming.dispatchAllEmsgBoxes configuration",
"Please Use mediaSource.dispatchAllEmsgBoxes instead."),a.mediaSource=a.mediaSource||{},a.mediaSource.dispatchAllEmsgBoxes=a.streaming.dispatchAllEmsgBoxes,delete a.streaming.dispatchAllEmsgBoxes);a.streaming&&"autoLowLatencyMode"in a.streaming&&(shaka.Deprecate.deprecateFeature(5,"streaming.autoLowLatencyMode configuration","Please Use streaming.lowLatencyMode instead."),a.streaming.lowLatencyMode=a.streaming.autoLowLatencyMode,delete a.streaming.autoLowLatencyMode);a.manifest&&a.manifest.dash&&
"ignoreSupplementalCodecs"in a.manifest.dash&&(shaka.Deprecate.deprecateFeature(5,"manifest.dash.ignoreSupplementalCodecs configuration","Please Use manifest.ignoreSupplementalCodecs instead."),a.manifest.ignoreSupplementalCodecs=a.manifest.dash.ignoreSupplementalCodecs,delete a.manifest.dash.ignoreSupplementalCodecs);a.manifest&&a.manifest.hls&&"ignoreSupplementalCodecs"in a.manifest.hls&&(shaka.Deprecate.deprecateFeature(5,"manifest.hls.ignoreSupplementalCodecs configuration","Please Use manifest.ignoreSupplementalCodecs instead."),
a.manifest.ignoreSupplementalCodecs=a.manifest.hls.ignoreSupplementalCodecs,delete a.manifest.hls.ignoreSupplementalCodecs);a.manifest&&a.manifest.dash&&"updatePeriod"in a.manifest.dash&&(shaka.Deprecate.deprecateFeature(5,"manifest.dash.updatePeriod configuration","Please Use manifest.updatePeriod instead."),a.manifest.updatePeriod=a.manifest.dash.updatePeriod,delete a.manifest.dash.updatePeriod);a.manifest&&a.manifest.hls&&"updatePeriod"in a.manifest.hls&&(shaka.Deprecate.deprecateFeature(5,"manifest.hls.updatePeriod configuration",
"Please Use manifest.updatePeriod instead."),a.manifest.updatePeriod=a.manifest.hls.updatePeriod,delete a.manifest.hls.updatePeriod);a.manifest&&a.manifest.dash&&"ignoreDrmInfo"in a.manifest.dash&&(shaka.Deprecate.deprecateFeature(5,"manifest.dash.ignoreDrmInfo configuration","Please Use manifest.ignoreDrmInfo instead."),a.manifest.ignoreDrmInfo=a.manifest.dash.ignoreDrmInfo,delete a.manifest.dash.ignoreDrmInfo);if(a.drm&&a.drm.advanced){d=!1;for(var e in a.drm.advanced){const {videoRobustness:f,
audioRobustness:g}=a.drm.advanced[e];"videoRobustness"in a.drm.advanced[e]&&!Array.isArray(a.drm.advanced[e].videoRobustness)&&(a.drm.advanced[e].videoRobustness=[f],d=!0);"audioRobustness"in a.drm.advanced[e]&&!Array.isArray(a.drm.advanced[e].audioRobustness)&&(a.drm.advanced[e].audioRobustness=[g],d=!0)}d&&shaka.Deprecate.deprecateFeature(5,"AdvancedDrmConfiguration's videoRobustness and audioRobustness","These properties are no longer strings but array of strings, please update your usage of these properties.")}a.streaming&&
"forceHTTP"in a.streaming&&(shaka.Deprecate.deprecateFeature(5,"streaming.forceHTTP configuration","Please Use networking.forceHTTP instead."),a.networking=a.networking||{},a.networking.forceHTTP=a.streaming.forceHTTP,delete a.streaming.forceHTTP);a.streaming&&"forceHTTPS"in a.streaming&&(shaka.Deprecate.deprecateFeature(5,"streaming.forceHTTPS configuration","Please Use networking.forceHTTP instead."),a.networking=a.networking||{},a.networking.forceHTTPS=a.streaming.forceHTTPS,delete a.streaming.forceHTTPS);
a.streaming&&"minBytesForProgressEvents"in a.streaming&&(shaka.Deprecate.deprecateFeature(5,"streaming.minBytesForProgressEvents configuration","Please Use networking.minBytesForProgressEvents instead."),a.networking=a.networking||{},a.networking.minBytesForProgressEvents=a.streaming.minBytesForProgressEvents,delete a.streaming.minBytesForProgressEvents);e=shaka.util.PlayerConfiguration.mergeConfigObjects(this.config_,a,this.defaultConfig_());this.applyConfig_(c);return e}configurationForLowLatency(a){this.lowLatencyConfig_=
a}applyConfig_(a){this.manifestFilterer_=new shaka.media.ManifestFilterer(this.config_,this.maxHwRes_,this.drmEngine_);if(this.parser_){var b=shaka.util.ObjectUtils.cloneObject(this.config_.manifest);this.video_&&this.video_.nodeName==="AUDIO"&&(b.disableVideo=!0);this.parser_.configure(b)}this.drmEngine_&&this.drmEngine_.configure(this.config_.drm);if(this.streamingEngine_){this.streamingEngine_.configure(this.config_.streaming);try{if(this.loadMode_!=shaka.Player.LoadMode.DESTROYED&&this.manifestFilterer_.filterManifestWithRestrictions(this.manifest_))this.onTracksChanged_()}catch(c){this.onError_(c)}this.abrManager_&&
this.updateAbrManagerVariants_();!(b=this.streamingEngine_.getCurrentVariant())||b.allowedByApplication&&b.allowedByKeySystem||(shaka.log.debug("Choosing new variant after changing configuration"),this.chooseVariantAndSwitch_())}this.networkingEngine_&&this.networkingEngine_.configure(this.config_.networking);this.mediaSourceEngine_&&(this.mediaSourceEngine_.configure(this.config_.mediaSource),{segmentRelativeVttTiming:b}=this.config_.manifest,this.mediaSourceEngine_.setSegmentRelativeVttTiming(b));
this.textDisplayer_&&this.createAndConfigureTextDisplayer_();this.abrManager_&&(this.abrManager_.configure(this.config_.abr),this.config_.abr.enabled?this.abrManager_.enable():this.abrManager_.disable(),this.onAbrStatusChanged_());this.bufferObserver_&&this.updateBufferingSettings_();this.bufferPoller_&&(this.config_.streaming.rebufferingGoal?this.bufferPoller_.tickEvery(.25):this.bufferPoller_.stop());this.manifest_&&shaka.Player.applyPlayRange_(this.manifest_.presentationTimeline,this.config_.playRangeStart,
this.config_.playRangeEnd);this.adManager_&&this.adManager_.configure(this.config_.ads);this.cmcdManager_&&this.cmcdManager_.configure(this.config_.cmcd);this.cmsdManager_&&this.cmsdManager_.configure(this.config_.cmsd);this.queueManager_&&this.queueManager_.configure(this.config_.queue);this.applyCriteriaConfigChanges_(a)}applyCriteriaConfigChanges_(a){if(this.loadMode_==shaka.Player.LoadMode.MEDIA_SOURCE&&this.currentAdaptationSetCriteria_.getConfiguration){var b=this.currentAdaptationSetCriteria_.getConfiguration();
goog.asserts.assert(b,"criteriaConfig must not be null!");var c=!1;a.preferredVideoHdrLevel!=this.config_.preferredVideoHdrLevel&&b.hdrLevel!=this.config_.preferredVideoHdrLevel&&(b.hdrLevel=this.config_.preferredVideoHdrLevel,c=!0);a.preferredVideoLayout!=this.config_.preferredVideoLayout&&b.videoLayout!=this.config_.preferredVideoLayout&&(b.videoLayout=this.config_.preferredVideoLayout,c=!0);a.preferSpatialAudio!=this.config_.preferSpatialAudio&&b.spatialAudio!=this.config_.preferSpatialAudio&&
(b.spatialAudio=this.config_.preferSpatialAudio,c=!0);a.preferredVideoRole!=this.config_.preferredVideoRole&&b.videoRole!=this.config_.preferredVideoRole&&(b.videoRole=this.config_.preferredVideoRole,c=!0);c&&(this.currentAdaptationSetCriteria_.configure(b),this.chooseVariantAndSwitch_())}}getConfiguration(){goog.asserts.assert(this.config_,"Config must not be null!");const a=this.defaultConfig_();shaka.util.PlayerConfiguration.mergeConfigObjects(a,this.config_,this.defaultConfig_());return a}getConfigurationForLowLatency(){return this.lowLatencyConfig_}getNonDefaultConfiguration(){goog.asserts.assert(this.config_,
"Config must not be null!");const a=this.defaultConfig_();shaka.util.PlayerConfiguration.mergeConfigObjects(a,this.config_,this.defaultConfig_());return shaka.util.ConfigUtils.getDifferenceFromConfigObjects(this.config_,this.defaultConfig_())}getSharedConfiguration(){goog.asserts.assert(this.config_,"Cannot call getSharedConfiguration after call destroy!");return this.config_}getBufferFullness(){if(this.video_){var a=this.video_.buffered.length;a=a?this.video_.buffered.end(a-1):0;const b=Math.min(this.video_.currentTime+
this.config_.streaming.bufferingGoal,this.seekRange().end);if(a>=b)return 1;if(!(a<=this.video_.currentTime)&&a<b)return(a-this.video_.currentTime)/(b-this.video_.currentTime)}return 0}resetConfiguration(){goog.asserts.assert(this.config_,"Cannot be destroyed");const a=this.getConfiguration();for(const b in this.config_)delete this.config_[b];shaka.util.PlayerConfiguration.mergeConfigObjects(this.config_,this.defaultConfig_(),this.defaultConfig_());this.applyConfig_(a)}getLoadMode(){return this.loadMode_}getManifestType(){return this.manifest_?
this.manifest_.type:null}getMediaElement(){return this.video_}getNetworkingEngine(){return this.networkingEngine_}getAssetUri(){return this.assetUri_}getAdManager(){return this.adManager_?this.adManager_:null}getQueueManager(){return this.queueManager_?this.queueManager_:null}isLive(){return this.manifest_&&!this.isRemotePlayback()?this.manifest_.presentationTimeline.isLive():this.video_&&(this.video_.src||this.isRemotePlayback())?this.video_.duration==Infinity:!1}isInProgress(){return this.manifest_?
this.manifest_.presentationTimeline.isInProgress():!1}isAudioOnly(){if(this.manifest_&&!this.isRemotePlayback()){const a=this.manifest_.variants;return a.length?!a[0].video:!1}return this.video_&&(this.video_.src||this.isRemotePlayback())?this.video_.videoTracks?this.video_.videoTracks.length==0:this.video_.videoHeight==0:!1}isVideoOnly(){if(this.manifest_&&!this.isRemotePlayback()){var a=this.manifest_.variants;if(!a.length)return!1;a=a[0];return a.audio||!a.video?!1:!a.video.codecs.includes(",")}return this.video_&&
(this.video_.src||this.isRemotePlayback())&&this.video_.audioTracks?this.video_.audioTracks.length==0:!1}seekRange(){if(this.manifest_&&!this.isRemotePlayback()){if(!this.fullyLoaded_&&this.manifest_.type==shaka.media.ManifestParser.HLS)return{start:0,end:0};var a=this.manifest_.presentationTimeline;return{start:a.getSeekRangeStart(),end:a.getSeekRangeEnd()}}if(this.video_&&(this.video_.src||this.isRemotePlayback())&&(a=this.video_.seekable)&&a.length){var b=this.config_?this.config_.playRangeStart:
0;b=Math.max(a.start(0),b);const c=this.config_?this.config_.playRangeEnd:Infinity;a=Math.min(a.end(a.length-1),c);return{start:b,end:a}}return{start:0,end:0}}goToLive(){this.isLive()?this.video_.currentTime=this.seekRange().end:shaka.log.warning("goToLive is for live streams!")}isFullyLoaded(){return this.fullyLoaded_}keySystem(){return shaka.drm.DrmUtils.keySystem(this.drmInfo())}drmInfo(){return this.drmEngine_?this.drmEngine_.getDrmInfo():null}getDrmEngine(){return this.drmEngine_}getExpiration(){return this.drmEngine_?
this.drmEngine_.getExpiration():Infinity}getActiveSessionsMetadata(){return this.drmEngine_?this.drmEngine_.getActiveSessionsMetadata():[]}getKeyStatuses(){return this.drmEngine_?this.drmEngine_.getKeyStatuses():{}}isBuffering(){const a=shaka.media.BufferingObserver.State;return this.bufferObserver_?this.bufferObserver_.getState()==a.STARVING:!!this.assetUri_}getPlaybackRate(){return this.video_?this.playRateController_?this.playRateController_.getRealRate():1:0}useTrickPlayTrackIfAvailable(a){this.loadMode_==
shaka.Player.LoadMode.MEDIA_SOURCE&&this.streamingEngine_&&this.streamingEngine_.setTrickPlay(a)}trickPlay(a,b=!0){goog.asserts.assert(a!=0,"Should never set a trick play rate of 0!");if(a==0)shaka.log.alwaysWarn("A trick play rate of 0 is unsupported!");else{var c=this.video_.playbackRate,d=this.playRateController_.getRealRate();this.playRateController_.set(a);this.loadMode_==shaka.Player.LoadMode.MEDIA_SOURCE&&(this.abrManager_.playbackRateChanged(a),this.useTrickPlayTrackIfAvailable(b&&a!=1));
this.setupTrickPlayEventListeners_(a);if(c===0&&this.video_.playbackRate===0&&a!=d)this.onRateChange_()}}cancelTrickPlay(){const a=this.playRateController_.getDefaultRate();this.loadMode_==shaka.Player.LoadMode.SRC_EQUALS&&this.playRateController_.set(a);this.loadMode_==shaka.Player.LoadMode.MEDIA_SOURCE&&(this.playRateController_.set(a),this.abrManager_.playbackRateChanged(a),this.useTrickPlayTrackIfAvailable(!1));this.trickPlayEventManager_.removeAll()}getVariantTracks(){if(this.manifest_&&!this.isRemotePlayback()){var a=
this.streamingEngine_?this.streamingEngine_.getCurrentVariant():null;const b=[];let c=0;for(const d of this.manifest_.variants){if(!shaka.util.StreamUtils.isPlayable(d))continue;const e=shaka.util.StreamUtils.variantToTrack(d);e.active=d==a;e.active||c==1||a==null||d.video!=a.video||d.audio!=a.audio||(e.active=!0);e.active&&c++;b.push(e)}goog.asserts.assert(c<=1,"It should only have one active track");return b}if(this.video_&&this.video_.audioTracks){const b=this.getActiveHtml5VideoTrack_();a=Array.from(this.video_.audioTracks);
return a.length?a.map(c=>shaka.util.StreamUtils.html5TrackToShakaTrack(c,b)):b?[shaka.util.StreamUtils.html5TrackToShakaTrack(null,b)]:[]}return[]}getTextTracks(){if(this.manifest_){if(this.isRemotePlayback())return[];var a=this.streamingEngine_?this.streamingEngine_.getCurrentTextStream():null;const b=[];for(const c of this.manifest_.textStreams){const d=shaka.util.StreamUtils.textStreamToTrack(c);d.active=c==a;b.push(d)}return b}if(this.video_&&this.video_.src&&this.video_.textTracks){a=this.getFilteredTextTracks_();
const b=shaka.util.StreamUtils;return a.map(c=>b.html5TextTrackToTrack(c))}return[]}getImageTracks(){const a=shaka.util.StreamUtils;let b=this.externalSrcEqualsThumbnailsStreams_;this.manifest_&&(b=this.manifest_.imageStreams);return b.map(c=>a.imageStreamToTrack(c))}async getAllThumbnails(a){const b=await this.getBestImageStream_(a);if(!b)return null;const c=[];b.segmentIndex.forEachTopLevelReference(d=>{const e=this.parseTilesLayout_(d.getTilesLayout()||b.tilesLayout);if(e){const f=e.rows*e.columns,
g=(d.trueEndTime-d.startTime)/f;for(let h=0;h<f;h++){const k=this.getThumbnailByReference_(d,b,d.startTime+h*g,e);if(!k)break;c.push(k)}}});return c}parseTilesLayout_(a){if(!a)return null;var b=/(\d+)x(\d+)/.exec(a);if(!b)return shaka.log.warning("Tiles layout does not contain a valid format  (columns x rows)"),null;a=parseInt(b[1],10);b=parseInt(b[2],10);return{columns:a,rows:b}}async getThumbnails(a,b){a=await this.getBestImageStream_(a);if(!a)return null;var c=a.segmentIndex.find(b);if(c==null)return null;
c=a.segmentIndex.get(c);const d=this.parseTilesLayout_(c.getTilesLayout()||a.tilesLayout);return d?this.getThumbnailByReference_(c,a,b,d):null}async getBestImageStream_(a){if(this.loadMode_!=shaka.Player.LoadMode.MEDIA_SOURCE&&this.loadMode_!=shaka.Player.LoadMode.SRC_EQUALS)return null;var b=this.externalSrcEqualsThumbnailsStreams_;this.manifest_&&(b=this.manifest_.imageStreams);let c=b[0];if(!c)return null;a!=null&&(c=b.find(d=>d.id==a));if(!c)return null;c.segmentIndex||await c.createSegmentIndex();
c.closeSegmentIndex&&(this.deferredCloseSegmentIndex_.has(c)||(b=new shaka.util.Timer(()=>{c&&(c.closeSegmentIndex(),this.deferredCloseSegmentIndex_.delete(c))}),this.deferredCloseSegmentIndex_.set(c,b)),this.deferredCloseSegmentIndex_.get(c).tickAfter(5));return c}getThumbnailByReference_(a,b,c,d){var e=shaka.util.NumberUtils;const f=b.width||0,g=b.height||0;let h=f/d.columns,k=g/d.rows;const l=d.columns*d.rows;var m=a.trueEndTime-a.startTime;m=a.getTileDuration()||m/l;let n=a.startTime,q=0;var p=
0;l>1&&(p=Math.floor((c-a.startTime)/m+1E-4),n=a.startTime+p*m,q=p%d.columns*h,p=Math.floor(p/d.columns)*k);if(n>=a.endTime||e.isFloatEqual(n,a.endTime,1E-4))return null;d=!1;if(e=a.getThumbnailSprite())d=!0,k=e.height,q=e.positionX,p=e.positionY,h=e.width;return{segment:a,imageHeight:g,imageWidth:f,height:k,positionX:q,positionY:p,startTime:n,duration:m,uris:a.getUris(),startByte:a.getStartByte(),endByte:a.getEndByte(),width:h,sprite:d,mimeType:a.mimeType||b.mimeType,codecs:a.codecs||b.codecs}}selectTextTrack(a){const b=
()=>{const c=this.manifest_.textStreams.find(d=>d.id==a.id);c?c==this.streamingEngine_.getCurrentTextStream()?shaka.log.debug("Text track already selected."):(this.addTextStreamToSwitchHistory_(c,!1),this.streamingEngine_.switchTextStream(c),this.onTextChanged_(),this.setTextDisplayerLanguage_(),this.currentTextLanguage_=c.language):this.isRemotePlayback()||shaka.log.error("No stream with id",a.id)};if(this.manifest_&&this.playhead_&&(b(),!this.isRemotePlayback()))return;(()=>{if(this.video_&&this.video_.textTracks){var c=
this.getFilteredTextTracks_();const e=c.find(f=>shaka.util.StreamUtils.html5TrackId(f)===a.id);if(e){if(this.textDisplayer_ instanceof shaka.text.NativeTextDisplayer)for(var d of c)c=d===e?this.isTextVisible_?"showing":"hidden":"disabled",d.mode!==c&&(d.mode=c);else d=c.find(f=>f.mode!=="disabled"),d!==e&&(d&&(d.mode="disabled",this.loadEventManager_.unlisten(d,"cuechange"),this.textDisplayer_.remove(0,Infinity)),e&&this.enableNativeTrack_(e));this.onTextChanged_();this.setTextDisplayerLanguage_()}else shaka.log.error("No track with id",
a.id)}})()}enableNativeTrack_(a){this.loadEventManager_.listen(a,"cuechange",()=>{this.textDisplayer_.remove(0,Math.max(0,this.video_.currentTime-this.config_.streaming.bufferBehind));const b={periodStart:0,segmentStart:0,segmentEnd:this.video_.duration,vttOffset:0},c=[];var d=Array.from(a.activeCues||[]);for(const e of d)if(d=shaka.text.Utils.mapNativeCueToShakaCue(e)){const f=this.config_.mediaSource.modifyCueCallback;f&&f(d,null,b);c.push(d)}this.textDisplayer_.append(c)});a.mode=document.pictureInPictureElement?
"showing":"hidden"}selectVariantTrack(a,b=!1,c=0){const d=()=>{const e=this.manifest_.variants.find(g=>g.id==a.id);if(e)if(shaka.util.StreamUtils.isPlayable(e)){var f=this.streamingEngine_.getCurrentVariant();this.config_.abr.enabled&&(f.video!=e.video||f.audio&&e.audio&&f.audio.language==e.audio.language&&f.audio.channelsCount==e.audio.channelsCount&&f.audio.label==e.audio.label)&&shaka.log.alwaysWarn("Changing tracks while abr manager is enabled will likely result in the selected track being overridden. Consider disabling abr before calling selectVariantTrack().");
this.isRemotePlayback()?this.switchVariant_(e,!1,!1,0):this.switchVariant_(e,!1,b||!1,c||0);this.currentAdaptationSetCriteria_.configure({language:e.language,role:e.audio&&e.audio.roles&&e.audio.roles[0]||"",videoRole:e.video&&e.video.roles&&e.video.roles[0]||"",channelCount:e.audio&&e.audio.channelsCount?e.audio.channelsCount:0,hdrLevel:e.video&&e.video.hdr?e.video.hdr:"",spatialAudio:e.audio&&e.audio.spatialAudio?e.audio.spatialAudio:!1,videoLayout:e.video&&e.video.videoLayout?e.video.videoLayout:
"",audioLabel:e.audio&&e.audio.label?e.audio.label:"",videoLabel:e.video&&e.video.label?e.video.label:"",codecSwitchingStrategy:this.config_.mediaSource.codecSwitchingStrategy,audioCodec:e.audio&&e.audio.codecs?e.audio.codecs:"",activeAudioCodec:f.audio&&f.audio.codecs?f.audio.codecs:"",activeAudioChannelCount:f.audio&&f.audio.channelsCount?f.audio.channelsCount:0,preferredAudioCodecs:this.config_.preferredAudioCodecs,preferredAudioChannelCount:this.config_.preferredAudioChannelCount});this.updateAbrManagerVariants_()}else shaka.log.error("Unable to switch to restricted track",
a.id);else this.isRemotePlayback()||shaka.log.error("No variant with id",a.id)};if(this.manifest_&&this.playhead_&&(d(),!this.isRemotePlayback()))return;(()=>{if(a.originalAudioId&&this.video_&&this.video_.audioTracks){const e=Array.from(this.video_.audioTracks);for(const f of e)if(shaka.util.StreamUtils.html5TrackId(f)==a.id){this.switchHtml5Track_(f);break}}})()}selectAudioTrack(a,b=0){const c=()=>{const d=this.currentAdaptationSetCriteria_.getConfiguration();d.audioCodec=a.codecs||"";d.audioLabel=
a.label||"";d.channelCount=a.channelsCount||0;d.language=a.language;d.role=a.roles[0]||"";d.spatialAudio=a.spatialAudio;var e=this.streamingEngine_.getCurrentVariant();if(e=e&&e.audio)d.activeAudioCodec=e.codecs||"",d.activeAudioChannelCount=e.channelsCount||0;this.currentAdaptationSetCriteria_.configure(d);this.chooseVariantAndSwitch_(!0,b,!1,!1)};if(this.manifest_&&this.playhead_&&(c(),!this.isRemotePlayback()))return;(()=>{if(this.video_&&this.video_.audioTracks){const e=shaka.util.LanguageUtils,
f=e.normalize(a.language);var d=Array.from(this.video_.audioTracks);let g=null;for(const h of d)if(d=h.language||"und",h.label==a.label&&e.normalize(d)==f&&h.kind==a.roles[0]){g=h;break}g&&this.switchHtml5Track_(g)}})()}getAudioTracks(){if(this.manifest_&&!this.isRemotePlayback()){var a=this.getVariantTracks();if(!a.length)return[];const c=a.find(d=>d.active);if(!c)return[];var b=a;this.loadMode_!=shaka.Player.LoadMode.MEDIA_SOURCE||this.isRemotePlayback()||(b=a.filter(d=>d.originalVideoId===c.originalVideoId&&
(d.audioCodec||shaka.util.MimeUtils.RAW_FORMATS.includes(d.audioMimeType||""))));if(!b.length)return[];a=new Map;for(const d of b){b=[d.language,d.originalLanguage,d.label||"",(d.audioRoles||[]).join(","),d.channelsCount,d.spatialAudio,d.audioCodec||"",d.accessibilityPurpose||""].join("_");const e={active:d.active,language:d.language,label:d.label,mimeType:d.audioMimeType,codecs:d.audioCodec,primary:d.primary,roles:d.audioRoles||[],accessibilityPurpose:d.accessibilityPurpose,channelsCount:d.channelsCount,
audioSamplingRate:d.audioSamplingRate,spatialAudio:d.spatialAudio,originalLanguage:d.originalLanguage};a.has(b)?!a.get(b).active&&e.active&&a.set(b,e):a.set(b,e)}return Array.from(a.values())}return this.video_&&this.video_.audioTracks?Array.from(this.video_.audioTracks).map(c=>shaka.util.StreamUtils.html5AudioTrackToTrack(c)):[]}selectVideoTrack(a,b=!1,c=0){const d=shaka.util.ArrayUtils,e=shaka.util.MimeUtils;var f=this.getVariantTracks();if(f.length){var g=f.find(k=>k.active);if(g){f=f.filter(k=>
(k.videoBandwidth||k.bandwidth)==a.bandwidth&&k.width==a.width&&k.height==a.height&&k.frameRate==a.frameRate&&k.pixelAspectRatio==a.pixelAspectRatio&&k.hdr==a.hdr&&k.colorGamut==a.colorGamut&&k.videoLayout==a.videoLayout&&k.videoMimeType==a.mimeType&&k.videoCodec==a.codecs&&d.equal(k.videoRoles,a.roles)&&k.videoLabel==a.label);var h;(h=f.length==1?f[0]:f.find(k=>k.audioId===g.audioId))||(h=f.find(k=>k.language==g.language&&k.label===g.label&&k.channelsCount===g.channelsCount&&k.spatialAudio===g.spatialAudio&&
k.audioMimeType===g.audioMimeType&&e.getNormalizedCodec(k.audioCodec||"")===e.getNormalizedCodec(g.audioCodec||"")&&d.equal(k.audioRoles,g.audioRoles)));h&&!h.active&&this.selectVariantTrack(h,b,c)}}}getVideoTracks(){if(this.loadMode_==shaka.Player.LoadMode.SRC_EQUALS||this.isRemotePlayback())return[];var a=this.getVariantTracks();if(!a.length)return[];const b=a.find(d=>d.active);if(!b)return[];var c=a;this.isVideoOnly()||(c=a.filter(d=>{const e=shaka.util.ArrayUtils,f=shaka.util.MimeUtils;return d.videoCodec&&
d.audioGroupId===b.audioGroupId&&d.originalAudioId===b.originalAudioId?d.audioId===b.audioId?!0:d.language===b.language&&d.label===b.label&&d.channelsCount===b.channelsCount&&d.spatialAudio===b.spatialAudio&&d.audioMimeType===b.audioMimeType&&f.getNormalizedCodec(d.audioCodec||"")===f.getNormalizedCodec(b.audioCodec||"")&&e.equal(d.audioRoles,b.audioRoles):!1}));if(!c.length)return[];a=new Map;for(const d of c)(c=d.originalVideoId)||d.videoId==null||(c=String(d.videoId)),c&&a.set(c,{active:d.active,
bandwidth:d.videoBandwidth||d.bandwidth,width:d.width,height:d.height,frameRate:d.frameRate,pixelAspectRatio:d.pixelAspectRatio,hdr:d.hdr,colorGamut:d.colorGamut,videoLayout:d.videoLayout,mimeType:d.videoMimeType,codecs:d.videoCodec,roles:d.videoRoles||[],label:d.videoLabel});return Array.from(a.values())}getAudioLanguagesAndRoles(){return shaka.Player.getLanguageAndRolesFrom_(this.getVariantTracks())}getTextLanguagesAndRoles(){return shaka.Player.getLanguageAndRolesFrom_(this.getTextTracks())}getAudioLanguages(){return Array.from(shaka.Player.getLanguagesFrom_(this.getVariantTracks()))}getTextLanguages(){return Array.from(shaka.Player.getLanguagesFrom_(this.getTextTracks()))}selectAudioLanguage(a,
b,c=0,d=0,e="",f=!1,g=""){const h=()=>{var k=this.streamingEngine_.getCurrentVariant();this.currentAdaptationSetCriteria_=this.config_.adaptationSetCriteriaFactory();this.currentAdaptationSetCriteria_.configure({language:a,role:b||"",videoRole:k.video&&k.video.roles&&k.video.roles[0]||"",channelCount:c||0,hdrLevel:"",spatialAudio:f||!1,videoLayout:"",audioLabel:g||"",videoLabel:"",codecSwitchingStrategy:this.config_.mediaSource.codecSwitchingStrategy,audioCodec:e||"",activeAudioCodec:k.audio&&k.audio.codecs?
k.audio.codecs:"",activeAudioChannelCount:k.audio&&k.audio.channelsCount?k.audio.channelsCount:0,preferredAudioCodecs:this.config_.preferredAudioCodecs,preferredAudioChannelCount:this.config_.preferredAudioChannelCount});const l=(q,p)=>q.video||p.video?q.video&&p.video?Math.abs((q.video.height||0)-(p.video.height||0))+Math.abs((q.video.width||0)-(p.video.width||0)):Infinity:0,m=this.currentAdaptationSetCriteria_.create(this.manifest_.variants);let n=null;for(const q of m.values())shaka.util.StreamUtils.isPlayable(q)&&
(!n||l(n,k)>l(q,k))&&(n=q);n==k?shaka.log.debug("Audio already selected."):n?(k=shaka.util.StreamUtils.variantToTrack(n),this.selectVariantTrack(k,!0,d||0)):this.chooseVariantAndSwitch_()};if(this.manifest_&&this.playhead_&&(h(),!this.isRemotePlayback()))return;(()=>{if(this.video_&&this.video_.audioTracks){const k=shaka.util.StreamUtils.filterStreamsByLanguageAndRole(this.getVariantTracks(),a,b||"",!1)[0];k&&this.selectVariantTrack(k)}})()}selectTextLanguage(a,b,c=!1){const d=()=>{this.currentTextLanguage_=
a;this.currentTextRole_=b||"";this.currentTextForced_=c||!1;const e=this.chooseTextStream_();e&&(e==this.streamingEngine_.getCurrentTextStream()?shaka.log.debug("Text track already selected."):(this.addTextStreamToSwitchHistory_(e,!1),this.shouldStreamText_()&&(this.streamingEngine_.switchTextStream(e),this.onTextChanged_(),this.setTextDisplayerLanguage_())))};if(this.manifest_&&this.playhead_&&(d(),!this.isRemotePlayback()))return;(()=>{const e=shaka.util.StreamUtils.filterStreamsByLanguageAndRole(this.getTextTracks(),
a,b||"",c||!1)[0];e&&this.selectTextTrack(e)})()}selectVariantsByLabel(a,b=!0,c=0){const d=()=>{let e=null;for(const f of this.manifest_.variants)if(f.audio.label==a){e=f;break}e==null?shaka.log.warning("No variants were found with label: "+a+". Ignoring the request to switch."):(this.currentAdaptationSetCriteria_=this.config_.adaptationSetCriteriaFactory(),this.currentAdaptationSetCriteria_.configure({language:e.language,role:"",videoRole:"",channelCount:0,hdrLevel:"",spatialAudio:!1,videoLayout:"",
videoLabel:"",audioLabel:a,codecSwitchingStrategy:this.config_.mediaSource.codecSwitchingStrategy,audioCodec:"",activeAudioCodec:"",activeAudioChannelCount:0,preferredAudioCodecs:this.config_.preferredAudioCodecs,preferredAudioChannelCount:this.config_.preferredAudioChannelCount}),this.chooseVariantAndSwitch_(b,c))};if(this.manifest_&&this.playhead_&&(d(),!this.isRemotePlayback()))return;(()=>{if(this.video_&&this.video_.audioTracks){const e=Array.from(this.video_.audioTracks);let f=null;for(const g of e)g.label==
a&&(f=g);f&&this.switchHtml5Track_(f)}})()}isTextTrackVisible(){const a=this.isTextVisible_;if(this.textDisplayer_){const b=this.textDisplayer_.isTextVisible();goog.asserts.assert(b==a,"text visibility has fallen out of sync");return b}return a}getChaptersTracks(){return this.externalChaptersStreams_.map(a=>shaka.util.StreamUtils.textStreamToTrack(a))}getChapters(a){shaka.Deprecate.deprecateFeature(5,"getChapters","Please use an getChaptersAsync.");if(!this.externalChaptersStreams_.length)return[];
const b=shaka.util.LanguageUtils,c=b.normalize(a);a=this.externalChaptersStreams_.filter(f=>b.normalize(f.language)==c);if(!a.length)return[];const d=[],e=new Set;for(const f of a)f.segmentIndex&&f.segmentIndex.forEachTopLevelReference(g=>{const h=g.getUris()[0],k=g.startTime+"-"+g.endTime+"-"+h;g={id:k,title:h,startTime:g.startTime,endTime:g.endTime};e.has(k)||(d.push(g),e.add(k))});return d}async getChaptersAsync(a){if(!this.externalChaptersStreams_.length)return[];const b=shaka.util.LanguageUtils,
c=b.normalize(a);a=this.externalChaptersStreams_.filter(f=>b.normalize(f.language)==c);if(!a.length)return[];const d=[],e=new Set;for(const f of a)f.segmentIndex||await f.createSegmentIndex(),f.segmentIndex.forEachTopLevelReference(g=>{const h=g.getUris()[0],k=g.startTime+"-"+g.endTime+"-"+h;g={id:k,title:h,startTime:g.startTime,endTime:g.endTime};e.has(k)||(d.push(g),e.add(k))});return d}getFilteredTextTracks_(){goog.asserts.assert(this.video_.textTracks,"TextTracks should be valid.");return Array.from(this.video_.textTracks).filter(a=>
a.kind!="metadata"&&a.kind!="chapters"&&a.label!=shaka.Player.TextTrackLabel)}getGeneratedTextTrack_(){goog.asserts.assert(this.video_.textTracks,"TextTracks should be valid.");return Array.from(this.video_.textTracks).find(a=>a.label==shaka.Player.TextTrackLabel)}getMetadataTracks_(){goog.asserts.assert(this.video_.textTracks,"TextTracks should be valid.");return Array.from(this.video_.textTracks).filter(a=>a.kind=="metadata")}setTextTrackVisibility(a){a=!!a;this.isTextVisible_!=a&&(this.isTextVisible_=
a,this.loadMode_==shaka.Player.LoadMode.MEDIA_SOURCE?(this.textDisplayer_.setTextVisibility(a),this.config_.streaming.alwaysStreamText||(a?this.streamingEngine_.getCurrentTextStream()||(a=shaka.util.StreamUtils.filterStreamsByLanguageAndRole(this.manifest_.textStreams,this.currentTextLanguage_,this.currentTextRole_,this.currentTextForced_),a.length>0&&(this.streamingEngine_.switchTextStream(a[0]),this.onTextChanged_(),this.setTextDisplayerLanguage_())):this.streamingEngine_.unloadTextStream())):this.video_&&
this.video_.src&&this.video_.textTracks&&this.textDisplayer_.setTextVisibility(a),this.onTextTrackVisibility_())}getPlayheadTimeAsDate(){let a;if(this.playhead_)a=this.playhead_.getTime();else{if(this.startTime_==null)return new Date;if(this.startTime_ instanceof Date)return this.startTime_;a=this.startTime_}if(this.manifest_&&!this.isRemotePlayback()){var b=this.manifest_.presentationTimeline;b=b.getInitialProgramDateTime()||b.getPresentationStartTime();return new Date((b+a)*1E3)}if(this.video_&&
this.video_.getStartDate)return b=this.video_.getStartDate(),b instanceof Date&&!isNaN(b.getTime())?new Date(b.getTime()+a*1E3):(shaka.log.warning("EXT-X-PROGRAM-DATETIME required to get playhead time as Date!"),null);shaka.log.warning("No way to get playhead time as Date!");return null}getPresentationStartTimeAsDate(){if(this.manifest_&&!this.isRemotePlayback()){var a=this.manifest_.presentationTimeline;a=a.getInitialProgramDateTime()||a.getPresentationStartTime();return a===null?(shaka.log.info("Manifest appears to have no PDT or PST"),
null):new Date(a*1E3)}if(this.video_&&this.video_.getStartDate)return a=this.video_.getStartDate(),a instanceof Date&&!isNaN(a.getTime())?a:(shaka.log.warning("EXT-X-PROGRAM-DATETIME required to get presentation start time as Date!"),null);shaka.log.warning("No way to get presentation start time as Date!");return null}getSegmentAvailabilityDuration(){if(!this.isLive())return shaka.log.warning("getSegmentAvailabilityDuration is for live streams!"),null;if(this.manifest_)return this.manifest_.presentationTimeline.getSegmentAvailabilityDuration();
shaka.log.warning("No way to get segment segment availability duration!");return null}getBufferedInfo(){if(this.loadMode_==shaka.Player.LoadMode.MEDIA_SOURCE)return this.mediaSourceEngine_.getBufferedInfo();const a={total:[],audio:[],video:[],text:[]};this.loadMode_==shaka.Player.LoadMode.SRC_EQUALS&&(a.total=shaka.media.TimeRangesUtils.getBufferedInfo(this.video_.buffered));return a}getLiveLatency(){if(!this.video_||!this.video_.currentTime)return null;var a=this.getPresentationStartTimeAsDate();
if(!a)return null;a=a.getTime()+this.video_.currentTime*1E3;return Math.floor(Date.now()-a)}getBandwidthEstimate(){return this.abrManager_?this.abrManager_.getBandwidthEstimate():NaN}getStats(){if(this.loadMode_!=shaka.Player.LoadMode.MEDIA_SOURCE&&this.loadMode_!=shaka.Player.LoadMode.SRC_EQUALS)return shaka.util.Stats.getEmptyBlob();this.updateStateHistory_();goog.asserts.assert(this.video_,"If we have stats, we should have video_");var a=this.video_,b=a.currentTime/a.duration;isNaN(b)||this.isLive()||
this.stats_.setCompletionPercent(Math.round(100*b));this.playhead_&&(this.stats_.setGapsJumped(this.playhead_.getGapsJumped()),this.stats_.setStallsDetected(this.playhead_.getStallsDetected()));a.getVideoPlaybackQuality&&(b=a.getVideoPlaybackQuality(),this.stats_.setDroppedFrames(Number(b.droppedVideoFrames),Number(b.totalVideoFrames)),this.stats_.setCorruptedFrames(Number(b.corruptedVideoFrames)));b=this.drmEngine_?this.drmEngine_.getLicenseTime():NaN;this.stats_.setLicenseTime(b);this.stats_.setResolution(a.videoWidth||
NaN,a.videoHeight||NaN);this.stats_.setCodecs("");this.isLive()&&(a=this.getLiveLatency(),a!=null&&this.stats_.setLiveLatency(a/1E3));b=this.getVariantTracks().find(c=>c.active);a=this.getTextTracks().find(c=>c.active);if(b){if(b.bandwidth){const c=this.playRateController_?this.playRateController_.getRealRate():1;let d=c*b.bandwidth;a&&a.bandwidth&&(d+=c*a.bandwidth);this.stats_.setCurrentStreamBandwidth(d)}b.width&&b.height&&this.stats_.setResolution(b.width||NaN,b.height||NaN);b=b.codecs;a&&(b+=
","+(a.codecs||a.mimeType));b&&this.stats_.setCodecs(b)}this.loadMode_!=shaka.Player.LoadMode.MEDIA_SOURCE||this.isRemotePlayback()||(this.manifest_&&(this.stats_.setManifestPeriodCount(this.manifest_.periodCount),this.stats_.setManifestGapCount(this.manifest_.gapCount),this.manifest_.presentationTimeline&&(a=this.manifest_.presentationTimeline.getMaxSegmentDuration(),this.stats_.setMaxSegmentDuration(a))),a=this.abrManager_.getBandwidthEstimate(),this.stats_.setBandwidthEstimate(a));this.loadMode_==
shaka.Player.LoadMode.SRC_EQUALS&&this.stats_.addBytesDownloaded(NaN);return this.stats_.getBlob()}async addTextTrackAsync(a,b,c,d,e,f,g=!1){if(this.loadMode_!=shaka.Player.LoadMode.MEDIA_SOURCE&&this.loadMode_!=shaka.Player.LoadMode.SRC_EQUALS)throw shaka.log.error("Must call load() and wait for it to resolve before adding text tracks."),new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.CONTENT_NOT_LOADED);c!="subtitles"&&c!="captions"&&
shaka.log.alwaysWarn("Using a kind value different of `subtitles` or `captions` can cause unwanted issues.");d||=await this.getTextMimetype_(a);let h=[];this.adManager_&&(h=this.adManager_.getCuePoints());if(this.loadMode_==shaka.Player.LoadMode.SRC_EQUALS){e=shaka.device.DeviceFactory.getDevice();g&&e.getBrowserEngine()===shaka.device.IDevice.BrowserEngine.WEBKIT&&(c="forced");b=await this.addSrcTrackElement_(a,b,c,d,f||"",h);if(b.track)return this.onTracksChanged_(),this.onTextChanged_(),shaka.util.StreamUtils.html5TextTrackToTrack(b.track);
shaka.log.error("Cannot add this text when loaded with src=");throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS);}const k=shaka.util.ManifestParserUtils.ContentType;var l=this.seekRange();l=l.end-l.start;this.manifest_&&(l=this.manifest_.presentationTimeline.getDuration());if(l==Infinity)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM);
h.length&&(a=await this.getTextData_(a),d=this.convertToWebVTT_(a,d,h),d=new Blob([d],{type:"text/vtt"}),a=shaka.media.MediaSourceEngine.createObjectURL(d),d="text/vtt");b={id:this.nextExternalStreamId_++,originalId:null,groupId:null,createSegmentIndex:()=>Promise.resolve(),segmentIndex:shaka.media.SegmentIndex.forSingleSegment(0,l,[a]),mimeType:d||"",codecs:e||"",kind:c,encrypted:!1,drmInfos:[],keyIds:new Set,language:b,originalLanguage:b,label:f||null,type:k.TEXT,primary:!1,trickModeVideo:null,
dependencyStream:null,emsgSchemeIdUris:null,roles:[],forced:!!g,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null,accessibilityPurpose:null,external:!0,fastSwitching:!1,fullMimeTypes:new Set([shaka.util.MimeUtils.getFullType(d||"",e||"")]),isAudioMuxedInVideo:!1,baseOriginalId:null};c=shaka.util.MimeUtils.getFullType(b.mimeType,b.codecs);if(!shaka.text.TextEngine.isTypeSupported(c))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,
shaka.util.Error.Code.MISSING_TEXT_PLUGIN,d);this.manifest_.textStreams.push(b);this.onTracksChanged_();this.onTextChanged_();return shaka.util.StreamUtils.textStreamToTrack(b)}async addThumbnailsTrack(a,b){if(this.loadMode_!=shaka.Player.LoadMode.MEDIA_SOURCE&&this.loadMode_!=shaka.Player.LoadMode.SRC_EQUALS)throw shaka.log.error("Must call load() and wait for it to resolve before adding image tracks."),new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.CONTENT_NOT_LOADED);
b||=await this.getTextMimetype_(a);if(b!="text/vtt")throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.UNSUPPORTED_EXTERNAL_THUMBNAILS_URI,a);var c=shaka.util.ManifestParserUtils.ContentType,d=this.seekRange(),e=d.end-d.start;this.manifest_&&(e=this.manifest_.presentationTimeline.getDuration());if(e==Infinity)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_THUMBNAILS_TO_LIVE_STREAM);
d=await this.getTextData_(a);var f=shaka.text.TextEngine.findParser(b);if(!f)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.MISSING_TEXT_PLUGIN,b);f=f();e={periodStart:0,segmentStart:0,segmentEnd:e,vttOffset:0};d=shaka.util.BufferUtils.toUint8(d);f=f.parseMedia(d,e,a,[]);d=[];for(const g of f){let h=null;f=new shaka.media.SegmentReference(g.startTime,g.endTime,()=>{h==null&&(h=shaka.util.ManifestParserUtils.resolveUris([a],[g.payload]));
return h||[]},0,null,null,0,0,Infinity);g.payload.includes("#xywh")&&(e=g.payload.split("#xywh=")[1].split(","),e.length===4&&f.setThumbnailSprite({height:parseInt(e[3],10),positionX:parseInt(e[0],10),positionY:parseInt(e[1],10),width:parseInt(e[2],10)}));d.push(f)}d.length&&(b=await this.getTextMimetype_(d[0].getUris()[0]));c={id:this.nextExternalStreamId_++,originalId:null,groupId:null,createSegmentIndex:()=>Promise.resolve(),segmentIndex:new shaka.media.SegmentIndex(d),mimeType:b||"",codecs:"",
kind:"",encrypted:!1,drmInfos:[],keyIds:new Set,language:"und",originalLanguage:null,label:null,type:c.IMAGE,primary:!1,trickModeVideo:null,dependencyStream:null,emsgSchemeIdUris:null,roles:[],forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null,tilesLayout:"1x1",accessibilityPurpose:null,external:!0,fastSwitching:!1,fullMimeTypes:new Set([shaka.util.MimeUtils.getFullType(b||"","")]),isAudioMuxedInVideo:!1,baseOriginalId:null};this.loadMode_==shaka.Player.LoadMode.SRC_EQUALS?
this.externalSrcEqualsThumbnailsStreams_.push(c):this.manifest_.imageStreams.push(c);this.onTracksChanged_();return shaka.util.StreamUtils.imageStreamToTrack(c)}async addChaptersTrack(a,b,c){if(this.loadMode_!=shaka.Player.LoadMode.MEDIA_SOURCE&&this.loadMode_!=shaka.Player.LoadMode.SRC_EQUALS)throw shaka.log.error("Must call load() and wait for it to resolve before adding chapters tracks."),new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.CONTENT_NOT_LOADED);
c||=await this.getTextMimetype_(a);const d=shaka.util.ManifestParserUtils.ContentType;var e=this.seekRange();e=e.end-e.start;this.manifest_&&(e=this.manifest_.presentationTimeline.getDuration());if(e==Infinity)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_CHAPTERS_TO_LIVE_STREAM);var f=shaka.text.TextEngine.findParser(c);if(!f)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,
shaka.util.Error.Code.MISSING_TEXT_PLUGIN,c);c=await this.getTextData_(a);f=f();e={periodStart:0,segmentStart:0,segmentEnd:e,vttOffset:0};c=shaka.util.BufferUtils.toUint8(c);e=f.parseMedia(c,e,a,[]);a=[];for(const g of e)e=new shaka.media.SegmentReference(g.startTime,g.endTime,()=>[g.payload],0,null,null,0,0,Infinity),a.push(e);b={id:this.nextExternalStreamId_++,originalId:null,groupId:null,createSegmentIndex:()=>Promise.resolve(),segmentIndex:new shaka.media.SegmentIndex(a),mimeType:"text/plain",
codecs:"",kind:"",encrypted:!1,drmInfos:[],keyIds:new Set,language:b,originalLanguage:b,label:null,type:d.TEXT,primary:!1,trickModeVideo:null,dependencyStream:null,emsgSchemeIdUris:null,roles:[],forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null,accessibilityPurpose:null,external:!0,fastSwitching:!1,fullMimeTypes:new Set([shaka.util.MimeUtils.getFullType("text/plain","")]),isAudioMuxedInVideo:!1,baseOriginalId:null};this.externalChaptersStreams_.push(b);this.onTracksChanged_();
return shaka.util.StreamUtils.textStreamToTrack(b)}async getTextMimetype_(a){let b;try{goog.asserts.assert(this.networkingEngine_,"Need networking engine."),b=await shaka.net.NetworkingUtils.getMimeType(a,this.networkingEngine_,this.config_.streaming.retryParameters)}catch(c){}if(b)return b;shaka.log.error("The mimeType has not been provided and it could not be deduced from its uri.");throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.TEXT_COULD_NOT_GUESS_MIME_TYPE,
a);}async addSrcTrackElement_(a,b,c,d,e,f){if(d!="text/vtt"||f.length)a=await this.getTextData_(a),a=this.convertToWebVTT_(a,d,f),a=new Blob([a],{type:"text/vtt"}),a=shaka.media.MediaSourceEngine.createObjectURL(a);d=document.createElement("track");d.src=this.cmcdManager_.appendTextTrackData(a);d.label=e;d.kind=c;d.srclang=b;this.video_.getAttribute("crossorigin")||this.video_.setAttribute("crossorigin","anonymous");this.video_.appendChild(d);this.externalSrcEqualsTextTracks_.push(d);return d}async getTextData_(a){goog.asserts.assert(this.networkingEngine_,
"Need networking engine.");const b=shaka.net.NetworkingEngine.RequestType.SEGMENT;a=shaka.net.NetworkingEngine.makeRequest([a],this.config_.streaming.retryParameters);a.method="GET";this.cmcdManager_.applyTextData(a);return(await this.networkingEngine_.request(b,a).promise).data}convertToWebVTT_(a,b,c){var d=shaka.text.TextEngine.findParser(b);if(d)return b=d(),d={periodStart:0,segmentStart:0,segmentEnd:this.video_.duration,vttOffset:0},a=shaka.util.BufferUtils.toUint8(a),a=b.parseMedia(a,d,null,
[]),shaka.text.WebVttGenerator.convert(a,c);throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.MISSING_TEXT_PLUGIN,b);}setMaxHardwareResolution(a,b){this.maxHwRes_.width=a;this.maxHwRes_.height=b}retryStreaming(a=.1){return this.loadMode_==shaka.Player.LoadMode.MEDIA_SOURCE?this.streamingEngine_.retry(a):!1}getManifest(){shaka.log.alwaysWarn("Shaka Player's internal Manifest structure is NOT covered by semantic versioning compatibility guarantees.  It may change at any time!  Please consider filing a feature request for whatever you use getManifest() for.");
return this.manifest_}getManifestParserFactory(){return this.parserFactory_}getFetchedPlaybackInfo(){const a={video:null,audio:null,text:null};if(this.loadMode_!=shaka.Player.LoadMode.MEDIA_SOURCE)return a;const b=shaka.util.ManifestParserUtils.ContentType;var c=this.streamingEngine_.getCurrentVariant();const d=this.streamingEngine_.getCurrentTextStream(),e=this.video_.currentTime;for(const f of[c.video,c.audio,d]){if(!f||!f.segmentIndex)continue;c=f.segmentIndex.find(e);c=f.segmentIndex.get(c);c=
{codecs:c.codecs||f.codecs,mimeType:c.mimeType||f.mimeType,bandwidth:c.bandwidth||f.bandwidth};f.type==b.VIDEO?(c.width=f.width,c.height=f.height,a.video=c):f.type==b.AUDIO?a.audio=c:f.type==b.TEXT&&(a.text=c)}return a}addVariantToSwitchHistory_(a,b){this.stats_.getSwitchHistory().updateCurrentVariant(a,b)}addTextStreamToSwitchHistory_(a,b){this.stats_.getSwitchHistory().updateCurrentText(a,b)}defaultConfig_(){const a=shaka.util.PlayerConfiguration.createDefault();a.streaming.failureCallback=b=>{this.defaultStreamingFailureCallback_(b)};
a.textDisplayFactory=()=>{if((()=>{if(!this.videoContainer_)return!1;const b=this.video_;return b.webkitDisplayingFullscreen||b.webkitPresentationMode&&b.webkitPresentationMode!="inline"?!1:!0})())return new shaka.text.UITextDisplayer(this.video_,this.videoContainer_);if("track"in document.createElement("track"))return new shaka.text.NativeTextDisplayer(this);shaka.log.warning("Text tracks are not supported by the browser, disabling.");return new shaka.text.StubTextDisplayer};return a}setVideoContainer(a){this.videoContainer_=
a}defaultStreamingFailureCallback_(a){if(this.isLive()){var b=null;a.code==shaka.util.Error.Code.BAD_HTTP_STATUS||a.code==shaka.util.Error.Code.HTTP_ERROR?(b=1,this.config_.streaming.lowLatencyMode&&(b=.1)):a.code==shaka.util.Error.Code.TIMEOUT&&(b=.1);b!=null&&(a.severity=shaka.util.Error.Severity.RECOVERABLE,shaka.log.warning("Live streaming error.  Retrying automatically..."),this.retryStreaming(b))}}makeTextStreamsForClosedCaptions_(a){const b=shaka.util.ManifestParserUtils.ContentType,c=shaka.util.ManifestParserUtils.TextStreamKind,
d=shaka.util.MimeUtils.CEA608_CLOSED_CAPTION_MIMETYPE,e=shaka.util.MimeUtils.CEA708_CLOSED_CAPTION_MIMETYPE,f=new Set;for(var g of a.textStreams)g.mimeType!=d&&g.mimeType!=e||f.add(g.originalId);for(const k of a.variants)if((g=k.video)&&g.closedCaptions)for(const l of g.closedCaptions.keys())if(!f.has(l)){var h=l.startsWith("CC")?d:e;const m=new shaka.media.MetaSegmentIndex,n=g.closedCaptions.get(l);h={id:this.nextExternalStreamId_++,originalId:l,groupId:null,createSegmentIndex:()=>Promise.resolve(),
segmentIndex:m,mimeType:h,codecs:"",kind:c.CLOSED_CAPTION,encrypted:!1,drmInfos:[],keyIds:new Set,language:n,originalLanguage:n,label:null,type:b.TEXT,primary:!1,trickModeVideo:null,dependencyStream:null,emsgSchemeIdUris:null,roles:g.roles,forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null,accessibilityPurpose:null,external:!1,fastSwitching:!1,fullMimeTypes:new Set([shaka.util.MimeUtils.getFullType(h,"")]),isAudioMuxedInVideo:!1,baseOriginalId:null};a.textStreams.push(h);
f.add(l)}}async adjustStartTime_(a,b){var c=a.video;const d=async(e,f)=>{if(!e)return null;e.segmentIndex||await e.createSegmentIndex();e=(e=e.segmentIndex.getIteratorForTime(f))?e.next().value:null;if(!e)return null;e=e.startTime;goog.asserts.assert(e<=f,"Segment should start before target time!");return e};a=await d(a.audio,b);c=await d(c,b);return c!=null&&a!=null?Math.max(c,a):c!=null?c:a!=null?a:b}updateBufferState_(){var a=this.isBuffering();shaka.log.v2("Player changing buffering state to",
a);if(this.stats_&&this.bufferObserver_&&this.playhead_){this.config_.streaming.rebufferingGoal==0?this.playRateController_.setBuffering(!1):this.playRateController_.setBuffering(a);this.cmcdManager_&&this.cmcdManager_.setBuffering(a);this.updateStateHistory_();var b=this.config_.streaming.liveSync.dynamicTargetLatency.maxAttempts;if(this.config_.streaming.liveSync.dynamicTargetLatency.enabled&&a&&this.rebufferingCount_<b){b=this.config_.streaming.liveSync.dynamicTargetLatency.maxLatency;const c=
this.config_.streaming.liveSync.targetLatencyTolerance,d=this.config_.streaming.liveSync.dynamicTargetLatency.rebufferIncrement;this.currentTargetLatency_&&(this.currentTargetLatency_=Math.min(this.currentTargetLatency_+ ++this.rebufferingCount_*d,b-c))}}b=shaka.util.FakeEvent.EventName.Buffering;a=(new Map).set("buffering",a);this.dispatchEvent(shaka.Player.makeEvent_(b,a))}onRateChange_(){var a=this.video_.playbackRate;a==0?(a=this.getPlaybackRate(),a!==0&&a!==1&&(a=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.RateChange),
this.dispatchEvent(a))):(this.playRateController_&&(this.playRateController_.set(a),this.loadMode_==shaka.Player.LoadMode.MEDIA_SOURCE&&this.abrManager_.playbackRateChanged(a),this.setupTrickPlayEventListeners_(a)),a=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.RateChange),this.dispatchEvent(a))}setupTrickPlayEventListeners_(a){this.trickPlayEventManager_.removeAll();this.trickPlayEventManager_.listen(this.video_,"timeupdate",()=>{const b=this.video_.currentTime,c=this.seekRange(),d=this.isLive(),
e=d?this.config_.streaming.safeSeekOffset:0;a>0?d&&a>1&&Math.floor(b)>=Math.floor(c.end)&&this.cancelTrickPlay():Math.floor(b)<=Math.floor(c.start+e)&&this.cancelTrickPlay()})}updateStateHistory_(){if(this.stats_&&this.bufferObserver_){var a=shaka.media.BufferingObserver.State,b=this.stats_.getStateHistory(),c="playing";this.bufferObserver_.getState()==a.STARVING?c="buffering":this.isEnded()?c="ended":this.video_.paused&&(c="paused");b.update(c)&&(a=shaka.util.FakeEvent.EventName.StateChanged,c=(new Map).set("newstate",
c),this.dispatchEvent(shaka.Player.makeEvent_(a,c)))}}onTimeUpdate_(){const a=this.video_.playbackRate;var b=this.isLive();if(this.config_.streaming.vodDynamicPlaybackRate&&!b){var c=this.config_.streaming.vodDynamicPlaybackRateLowBufferRate,d=this.getBufferFullness(),e=this.config_.streaming.vodDynamicPlaybackRateBufferRatio;d<=e?a!=c&&(shaka.log.debug("Buffer fullness ratio ("+d+") is less than the vodDynamicPlaybackRateBufferRatio ("+e+"). Updating playbackRate to "+c),this.trickPlay(c,!1)):d==
1&&a!==this.playRateController_.getDefaultRate()&&(shaka.log.debug("Buffer is full. Cancel trick play."),this.cancelTrickPlay())}if(b&&(b=this.seekRange(),Number.isFinite(b.end)&&!(this.video_.currentTime<b.start||this.video_.paused))){c=this.config_.streaming.liveSync.targetLatencyTolerance;d=this.config_.streaming.liveSync.dynamicTargetLatency.enabled;e=this.config_.streaming.liveSync.dynamicTargetLatency.stabilityThreshold;if(this.config_.streaming.liveSync&&this.config_.streaming.liveSync.enabled){var f=
this.config_.streaming.liveSync.targetLatency;var g=f+c;var h=Math.max(0,f-c);var k=this.config_.streaming.liveSync.maxPlaybackRate;var l=this.config_.streaming.liveSync.minPlaybackRate}else this.manifest_&&this.manifest_.serviceDescription&&(f=this.manifest_.serviceDescription.targetLatency,this.manifest_.serviceDescription.targetLatency!=null?g=this.manifest_.serviceDescription.targetLatency+c:this.manifest_.serviceDescription.maxLatency!=null&&(g=this.manifest_.serviceDescription.maxLatency),this.manifest_.serviceDescription.targetLatency!=
null?h=Math.max(0,this.manifest_.serviceDescription.targetLatency-c):this.manifest_.serviceDescription.minLatency!=null&&(h=this.manifest_.serviceDescription.minLatency),k=this.manifest_.serviceDescription.maxPlaybackRate||this.config_.streaming.liveSync.maxPlaybackRate,l=this.manifest_.serviceDescription.minPlaybackRate||this.config_.streaming.liveSync.minPlaybackRate);this.currentTargetLatency_||typeof f!=="number"||(this.currentTargetLatency_=f);var m=this.config_.streaming.liveSync.dynamicTargetLatency.maxAttempts;
d&&this.targetLatencyReached_&&this.currentTargetLatency_!==null&&typeof f==="number"&&this.rebufferingCount_<m&&Date.now()-this.targetLatencyReached_>e*1E3&&(e=this.config_.streaming.liveSync.dynamicTargetLatency.minLatency,this.currentTargetLatency_=Math.max(this.currentTargetLatency_-(f-e)/2,e+c),this.targetLatencyReached_=Date.now());d&&this.currentTargetLatency_!==null&&(g=this.currentTargetLatency_+c,h=this.currentTargetLatency_-c);f=b.end-this.video_.currentTime;c=0;this.loadMode_==shaka.Player.LoadMode.SRC_EQUALS&&
(d=this.video_.buffered,d.length>0&&(c=d.end(d.length-1),c=Math.max(k,c-b.end)));b=this.config_.streaming.liveSync.panicMode;d=this.config_.streaming.liveSync.panicThreshold*1E3;e=Date.now()-this.bufferObserver_.getLastRebufferTime();b&&!l&&(l=this.config_.streaming.liveSync.minPlaybackRate);b&&l&&e<=d?a!=l&&(shaka.log.debug("Time since last rebuffer ("+e+"s) is less than the live sync panicThreshold ("+d+"s). Updating playbackRate to "+l),this.trickPlay(l,!1)):g!=void 0&&k&&f-c>g?(a!=k&&(shaka.log.debug("Latency ("+
f+"s) is greater than live sync maxLatency ("+g+"s). Updating playbackRate to "+k),this.trickPlay(k,!1)),this.targetLatencyReached_=null):h!=void 0&&l&&f-c<h?(a!=l&&(shaka.log.debug("Latency ("+f+"s) is smaller than live sync minLatency ("+h+"s). Updating playbackRate to "+l),this.trickPlay(l,!1)),this.targetLatencyReached_=null):a!==this.playRateController_.getDefaultRate()&&(this.cancelTrickPlay(),this.targetLatencyReached_=Date.now())}}isQuartile_(a,b){return(shaka.util.NumberUtils.isFloatEqual(a,
b,.01)||b>a)&&this.completionPercent_<a?(this.completionPercent_=a,!0):!1}checkEnded_(){this.config_&&this.config_.playRangeEnd!=Infinity&&this.isEnded()&&this.video_.pause()}onVideoProgress_(){if(this.video_){var a=this.seekRange();a=a.end-a.start;a=a>0?this.video_.currentTime/a:0;if(!isNaN(a)){a*=100;if(this.isQuartile_(0,a))var b=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.Started);else if(this.isQuartile_(25,a))b=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.FirstQuartile);
else if(this.isQuartile_(50,a))b=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.Midpoint);else if(this.isQuartile_(75,a))b=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.ThirdQuartile);else{if(this.isQuartile_(100,a)||a>100)b=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.Complete);this.checkEnded_()}b&&this.dispatchEvent(b)}}}onSeek_(){this.playheadObservers_&&this.playheadObservers_.notifyOfSeek(!this.playhead_.getIsJumpingGap());this.streamingEngine_&&this.streamingEngine_.seeked();
this.bufferObserver_&&this.pollBufferState_(shaka.util.MediaElementEvent.SEEKING)}updateAbrManagerVariants_(){try{goog.asserts.assert(this.manifest_,"Manifest should exist by now!"),this.manifestFilterer_.checkRestrictedVariants(this.manifest_)}catch(b){return this.onError_(b),!1}var a=shaka.util.StreamUtils.getPlayableVariants(this.manifest_.variants);a=this.currentAdaptationSetCriteria_.create(a);a=this.abrManager_.setVariants(Array.from(a.values()));return typeof a=="boolean"?a:!0}chooseVariant_(a=
!1){if(this.updateAbrManagerVariants_()){if(!this.config_.abr.enabled){var b=this.currentAdaptationSetCriteria_;typeof b.getLastAdaptationSet!="function"&&(shaka.Deprecate.deprecateFeature(5,"AdaptationSetCriteria w/o getLastAdaptationSet","Please use an AdaptationSetCriteria with getLastAdaptationSet."),b.getLastAdaptationSet=()=>null);if(b=b.getLastAdaptationSet())if(b=Array.from(b.values()),b.length){const c=this.streamingEngine_.getCurrentVariant();if(c&&c.video&&(b=b.find(d=>d.video==c.video)))return b}}return this.abrManager_.chooseVariant(a)}return null}checkVariants_(){goog.asserts.assert(this.manifest_,
"Should have manifest!");const a=Date.now()/1E3;let b=!1,c=!0;for(const f of this.manifest_.variants){if(f.disabledUntilTime>0&&f.disabledUntilTime<=a){f.disabledUntilTime=0;b=!0;var d=shaka.log,e=d.v2;let g="";f.video&&(g+="video:"+f.video.id);f.audio&&(g=g+(g?"&":"")+("audio:"+f.audio.id));e.call(d,"Re-enabled variant with "+g)}f.disabledUntilTime>0&&(c=!1)}c&&this.checkVariantsTimer_.stop();b&&this.chooseVariantAndSwitch_(!1,void 0,!1,!1)}chooseTextStream_(){return shaka.util.StreamUtils.filterStreamsByLanguageAndRole(this.manifest_.textStreams,
this.currentTextLanguage_,this.currentTextRole_,this.currentTextForced_)[0]||null}chooseVariantAndSwitch_(a=!0,b=0,c=!1,d=!0){goog.asserts.assert(this.config_,"Must not be destroyed");const e=this.chooseVariant_();e&&this.switchVariant_(e,d,a,b,c)}switchVariant_(a,b,c,d,e=!1){var f=this.streamingEngine_.getCurrentVariant();if(a==f)shaka.log.debug("Variant already selected."),c&&this.streamingEngine_.switchVariant(a,c,d,!0);else{this.addVariantToSwitchHistory_(a,b);this.streamingEngine_.switchVariant(a,
c,d,e,b);c=null;f&&(c=shaka.util.StreamUtils.variantToTrack(f));f=shaka.util.StreamUtils.variantToTrack(a);f.active=!0;this.lcevcDec_&&this.lcevcDec_.updateVariant(a,this.getManifestType());if(b)this.onAdaptation_(c,f);else this.onVariantChanged_(c,f);this.checkAudioTracksChanged_(c,f)}}switchHtml5Track_(a){const b=shaka.util.StreamUtils;goog.asserts.assert(this.video_&&this.video_.audioTracks,"Video and video.audioTracks should not be null!");var c=Array.from(this.video_.audioTracks).find(e=>e.enabled);
a.enabled=!0;if(c){a.id!==c.id&&(c.enabled=!1);var d=this.getActiveHtml5VideoTrack_();c=b.html5TrackToShakaTrack(c,d);a=b.html5TrackToShakaTrack(a,d);this.onVariantChanged_(c,a);this.checkAudioTracksChanged_(c,a)}}getActiveHtml5VideoTrack_(){return this.video_&&this.video_.videoTracks?Array.from(this.video_.videoTracks).find(a=>a.selected):null}setInitialTextState_(a,b){b?(goog.asserts.assert(this.config_,"Must not be destroyed"),shaka.util.StreamUtils.shouldInitiallyShowText(a.audio,b,this.config_)&&
(this.isTextVisible_=!0),this.isTextVisible_&&(this.textDisplayer_.setTextVisibility(!0),goog.asserts.assert(this.shouldStreamText_(),"Should be streaming text"))):(this.isTextVisible_=!1,this.textDisplayer_.setTextVisibility(!1));this.onTextTrackVisibility_()}onManifestUpdate_(){this.parser_&&this.parser_.update&&this.parser_.update()}onSegmentAppended_(a,b,c,d,e){const f=shaka.util.NumberUtils;if(c!=shaka.util.ManifestParserUtils.ContentType.TEXT){if(this.playhead_){this.playhead_.notifyOfBufferingChange();
const g=this.mediaSourceEngine_.bufferStart(c);!this.isLive()&&this.video_.paused&&!this.video_.seeking&&g!=null&&g>0&&this.playhead_.getTime()<g&&!f.isFloatEqual(this.playhead_.getTime(),g,.001)&&this.playhead_.setStartTime(g)}this.pollBufferState_()}a=(new Map).set("start",a).set("end",b).set("contentType",c).set("isMuxed",d).set("isDependency",e);this.dispatchEvent(shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.SegmentAppended,a))}switch_(a,b=!1,c=0){shaka.log.debug("switch_");goog.asserts.assert(this.config_.abr.enabled,
"AbrManager should not call switch while disabled!");this.manifest_&&this.streamingEngine_&&a!=this.streamingEngine_.getCurrentVariant()&&this.switchVariant_(a,!0,b,c)}onAdaptation_(a,b){a=(new Map).set("oldTrack",a).set("newTrack",b);a=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.Adaptation,a);this.delayDispatchEvent_(a)}onTracksChanged_(){const a=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.TracksChanged);this.delayDispatchEvent_(a);this.onAudioTracksChanged_()}onVariantChanged_(a,
b){a=(new Map).set("oldTrack",a).set("newTrack",b);a=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.VariantChanged,a);this.delayDispatchEvent_(a)}checkAudioTracksChanged_(a,b){let c=!1;a&&a.audioId==b.audioId&&a.audioGroupId==b.audioGroupId||(c=!0);if(c)this.onAudioTracksChanged_()}onAudioTracksChanged_(){const a=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.AudioTracksChanged);this.delayDispatchEvent_(a)}onTextChanged_(){const a=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.TextChanged);
this.delayDispatchEvent_(a)}onTextTrackVisibility_(){const a=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.TextTrackVisibility);this.delayDispatchEvent_(a)}onAbrStatusChanged_(){this.config_.abr.enabled||this.restoreDisabledVariants_();const a=(new Map).set("newStatus",this.config_.abr.enabled);this.delayDispatchEvent_(shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.AbrStatusChanged,a))}setTextDisplayerLanguage_(){const a=this.getTextTracks().find(b=>b.active);a&&this.textDisplayer_&&
this.textDisplayer_.setTextLanguage&&this.textDisplayer_.setTextLanguage(a.language)}restoreDisabledVariants_(a=!0){if(this.loadMode_==shaka.Player.LoadMode.MEDIA_SOURCE){goog.asserts.assert(this.manifest_,"Should have manifest!");shaka.log.v2("Restoring all disabled streams...");this.checkVariantsTimer_.stop();for(const b of this.manifest_.variants)b.disabledUntilTime=0;a&&this.updateAbrManagerVariants_()}}disableStream(a,b){if(!this.config_.abr.enabled||this.loadMode_===shaka.Player.LoadMode.DESTROYED||
!navigator.onLine||b==0||!this.manifest_)return!1;if(this.manifest_.variants.some(c=>{const d=c[a.type];return d&&d.id!==a.id&&!c.disabledUntilTime?shaka.util.StreamUtils.isAudio(a)?a.language===d.language:!0:!1})){let c=!1,d=!1;for(const e of this.manifest_.variants){const f=e[a.type];f&&(f.id===a.id?(e.disabledUntilTime=Date.now()/1E3+b,c=!0,shaka.log.v2("Disabled stream "+a.type+":"+a.id+" for "+b+" seconds...")):f.trickModeVideo&&f.trickModeVideo.id==a.id&&(d=!0))}if(!c&&d)return!1;goog.asserts.assert(c,
"Must have disabled stream");this.checkVariantsTimer_.tickEvery(1);({video:b}=this.getBufferedInfo());b=b.reduce((e,{start:f,end:g})=>e+g-f,0);this.chooseVariantAndSwitch_(!1,b,!0,!1);return!0}shaka.log.warning("No alternate stream found for active "+a.type+" stream. Will ignore request to disable stream...");return!1}async onError_(a){goog.asserts.assert(a instanceof shaka.util.Error,"Wrong error type!");if(this.loadMode_!=shaka.Player.LoadMode.DESTROYED){a.severity===shaka.util.Error.Severity.RECOVERABLE&&
this.stats_.addNonFatalError();var b=!0;if(this.fullyLoaded_&&this.manifest_&&this.streamingEngine_&&(a.code==shaka.util.Error.Code.VIDEO_ERROR||a.code==shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_FAILED||a.code==shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_THREW||a.code==shaka.util.Error.Code.STREAMING_NOT_ALLOWED||a.code==shaka.util.Error.Code.TRANSMUXING_FAILED)){if(shaka.device.DeviceFactory.getDevice().getBrowserEngine()===shaka.device.IDevice.BrowserEngine.WEBKIT&&a.code==shaka.util.Error.Code.VIDEO_ERROR)return;
try{const c=await this.streamingEngine_.resetMediaSource();b=!c;if(c){const d=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.MediaSourceRecovered);this.dispatchEvent(d)}}catch(c){b=!0}}b&&(a.severity===shaka.util.Error.Severity.CRITICAL&&this.restoreDisabledVariants_(!1),b=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.Error,(new Map).set("detail",a)),this.dispatchEvent(b),b.defaultPrevented&&(a.handled=!0))}}addFont(a,b){return shaka.util.Dom.addFont(a,b)}onRegionEvent_(a,b,c=this){b=
{schemeIdUri:b.schemeIdUri,value:b.value,startTime:b.startTime,endTime:b.endTime,id:b.id,timescale:b.timescale,eventElement:b.eventElement,eventNode:b.eventNode};b=(new Map).set("detail",b);c.dispatchEvent(shaka.Player.makeEvent_(a,b))}onMediaQualityChange_(a,b,c=!1){a={bandwidth:a.bandwidth,audioSamplingRate:a.audioSamplingRate,codecs:a.codecs,contentType:a.contentType,frameRate:a.frameRate,height:a.height,mimeType:a.mimeType,channelsCount:a.channelsCount,pixelAspectRatio:a.pixelAspectRatio,width:a.width,
label:a.label,roles:a.roles,language:a.language};b=(new Map).set("mediaQuality",a).set("position",b);this.dispatchEvent(shaka.Player.makeEvent_(c?shaka.util.FakeEvent.EventName.AudioTrackChanged:shaka.util.FakeEvent.EventName.MediaQualityChanged,b))}videoErrorToShakaError_(a=!0){goog.asserts.assert(this.video_.error,"Video error expected, but missing!");if(!this.video_.error)return a?new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.VIDEO_ERROR):
null;const b=this.video_.error.code;if(!a&&b==1)return null;if(a=this.video_.error.msExtendedCode)a<0&&(a+=4294967296),a=a.toString(16);return new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.VIDEO_ERROR,b,a,this.video_.error.message)}onVideoError_(a){if(a=this.videoErrorToShakaError_(!1))this.onError_(a)}onKeyStatus_(a){if(this.streamingEngine_){var b=shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.KeyStatusChanged);this.dispatchEvent(b);
var c=Object.keys(a);c.length==0&&shaka.log.warning("Got a key status event without any key statuses, so we don't know the real key statuses. If we don't have all the keys, you'll need to set restrictions so we don't select those tracks.");c.length==1&&c[0]==""&&(c=["00"],a={"00":a[""]});var d=c.length==1&&c[0]=="00";d&&shaka.log.warning("Got a synthetic key status event, so we don't know the real key statuses. If we don't have all the keys, you'll need to set restrictions so we don't select those tracks.");
var e=shaka.media.ManifestFilterer.restrictedStatuses;b=!1;goog.asserts.assert(this.drmEngine_,"drmEngine should be non-null here.");if(c.length){c=this.keySystem();const h=shaka.util.MapUtils.asMap(this.config_.drm.clearKeys),k=(l,m)=>{l.allowedByKeySystem=!0;for(const n of m)if((m=a[d?"00":n])||this.drmEngine_.hasManifestInitData())l.allowedByKeySystem=l.allowedByKeySystem&&!!m&&!e.includes(m)};for(var f of this.manifest_.variants){var g=shaka.util.StreamUtils.getVariantStreams(f);for(const l of g){g=
f.allowedByKeySystem;if(l.keyIds.size)if(l.drmInfos.length&&!h.size&&this.manifest_.type==shaka.media.ManifestParser.HLS)for(const m of l.drmInfos)m.keySystem==c&&(m.keyIds.size?k(f,m.keyIds):k(f,l.keyIds));else k(f,l.keyIds);g!=f.allowedByKeySystem&&(b=!0)}}}b&&(this.onTracksChanged_(),(f=this.streamingEngine_.getCurrentVariant())&&!f.allowedByKeySystem?(shaka.log.debug("Choosing new streams after key status changed"),this.chooseVariantAndSwitch_()):this.updateAbrManagerVariants_())}}shouldStreamText_(){return this.config_.streaming.alwaysStreamText||
this.isTextTrackVisible()}static applyPlayRange_(a,b,c){b>0&&(a.isLive()?shaka.log.warning("|playRangeStart| has been configured for live content. Ignoring the setting."):a.setUserSeekStart(b));b=a.getDuration();c<b&&(a.isLive()?shaka.log.warning("|playRangeEnd| has been configured for live content. Ignoring the setting."):a.setDuration(c))}async delayDispatchEvent_(a){await Promise.resolve();this.loadMode_!=shaka.Player.LoadMode.DESTROYED&&this.dispatchEvent(a)}static getLanguagesFrom_(a){const b=
new Set;for(const c of a)c.language?b.add(shaka.util.LanguageUtils.normalize(c.language)):b.add("und");return b}static getLanguageAndRolesFrom_(a){const b=new Map,c=new Map;for(let e=0;e<a.length;e++){const f=a[e];let g="und",h=[];f.language&&(g=shaka.util.LanguageUtils.normalize(f.language));(h=f.type=="variant"?f.audioRoles:f.roles)&&h.length||(h=[""]);b.has(g)||b.set(g,new Set);for(const k of h)b.get(g).add(k),f.label&&(c.has(g)||c.set(g,new Map),c.get(g).set(k,f.label))}const d=[];b.forEach((e,
f)=>{for(const g of e)e=null,c.has(f)&&c.get(f).has(g)&&(e=c.get(f).get(g)),d.push({language:f,role:g,label:e})});return d}createAbortLoadError_(){return new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.LOAD_INTERRUPTED)}isRemotePlayback(){return this.video_&&this.video_.remote?this.video_.remote.state!="disconnected":!1}isEnded(){return!this.video_||this.video_.ended?!0:this.fullyLoaded_&&!this.isLive()&&this.video_.currentTime>=this.seekRange().end}};
goog.exportSymbol("shaka.Player",shaka.Player);goog.exportProperty(shaka.Player.prototype,"isEnded",shaka.Player.prototype.isEnded);goog.exportProperty(shaka.Player.prototype,"isRemotePlayback",shaka.Player.prototype.isRemotePlayback);goog.exportProperty(shaka.Player.prototype,"addFont",shaka.Player.prototype.addFont);goog.exportProperty(shaka.Player.prototype,"setVideoContainer",shaka.Player.prototype.setVideoContainer);goog.exportProperty(shaka.Player.prototype,"getFetchedPlaybackInfo",shaka.Player.prototype.getFetchedPlaybackInfo);
goog.exportProperty(shaka.Player.prototype,"getManifestParserFactory",shaka.Player.prototype.getManifestParserFactory);goog.exportProperty(shaka.Player.prototype,"getManifest",shaka.Player.prototype.getManifest);goog.exportProperty(shaka.Player.prototype,"retryStreaming",shaka.Player.prototype.retryStreaming);goog.exportProperty(shaka.Player.prototype,"setMaxHardwareResolution",shaka.Player.prototype.setMaxHardwareResolution);goog.exportProperty(shaka.Player.prototype,"addChaptersTrack",shaka.Player.prototype.addChaptersTrack);
goog.exportProperty(shaka.Player.prototype,"addThumbnailsTrack",shaka.Player.prototype.addThumbnailsTrack);goog.exportProperty(shaka.Player.prototype,"addTextTrackAsync",shaka.Player.prototype.addTextTrackAsync);goog.exportProperty(shaka.Player.prototype,"getStats",shaka.Player.prototype.getStats);goog.exportProperty(shaka.Player.prototype,"getBufferedInfo",shaka.Player.prototype.getBufferedInfo);goog.exportProperty(shaka.Player.prototype,"getSegmentAvailabilityDuration",shaka.Player.prototype.getSegmentAvailabilityDuration);
goog.exportProperty(shaka.Player.prototype,"getPresentationStartTimeAsDate",shaka.Player.prototype.getPresentationStartTimeAsDate);goog.exportProperty(shaka.Player.prototype,"getPlayheadTimeAsDate",shaka.Player.prototype.getPlayheadTimeAsDate);goog.exportProperty(shaka.Player.prototype,"setTextTrackVisibility",shaka.Player.prototype.setTextTrackVisibility);goog.exportProperty(shaka.Player.prototype,"getChaptersAsync",shaka.Player.prototype.getChaptersAsync);
goog.exportProperty(shaka.Player.prototype,"getChapters",shaka.Player.prototype.getChapters);goog.exportProperty(shaka.Player.prototype,"getChaptersTracks",shaka.Player.prototype.getChaptersTracks);goog.exportProperty(shaka.Player.prototype,"isTextTrackVisible",shaka.Player.prototype.isTextTrackVisible);goog.exportProperty(shaka.Player.prototype,"selectVariantsByLabel",shaka.Player.prototype.selectVariantsByLabel);goog.exportProperty(shaka.Player.prototype,"selectTextLanguage",shaka.Player.prototype.selectTextLanguage);
goog.exportProperty(shaka.Player.prototype,"selectAudioLanguage",shaka.Player.prototype.selectAudioLanguage);goog.exportProperty(shaka.Player.prototype,"getTextLanguages",shaka.Player.prototype.getTextLanguages);goog.exportProperty(shaka.Player.prototype,"getAudioLanguages",shaka.Player.prototype.getAudioLanguages);goog.exportProperty(shaka.Player.prototype,"getTextLanguagesAndRoles",shaka.Player.prototype.getTextLanguagesAndRoles);
goog.exportProperty(shaka.Player.prototype,"getAudioLanguagesAndRoles",shaka.Player.prototype.getAudioLanguagesAndRoles);goog.exportProperty(shaka.Player.prototype,"getVideoTracks",shaka.Player.prototype.getVideoTracks);goog.exportProperty(shaka.Player.prototype,"selectVideoTrack",shaka.Player.prototype.selectVideoTrack);goog.exportProperty(shaka.Player.prototype,"getAudioTracks",shaka.Player.prototype.getAudioTracks);goog.exportProperty(shaka.Player.prototype,"selectAudioTrack",shaka.Player.prototype.selectAudioTrack);
goog.exportProperty(shaka.Player.prototype,"selectVariantTrack",shaka.Player.prototype.selectVariantTrack);goog.exportProperty(shaka.Player.prototype,"selectTextTrack",shaka.Player.prototype.selectTextTrack);goog.exportProperty(shaka.Player.prototype,"getThumbnails",shaka.Player.prototype.getThumbnails);goog.exportProperty(shaka.Player.prototype,"getAllThumbnails",shaka.Player.prototype.getAllThumbnails);goog.exportProperty(shaka.Player.prototype,"getImageTracks",shaka.Player.prototype.getImageTracks);
goog.exportProperty(shaka.Player.prototype,"getTextTracks",shaka.Player.prototype.getTextTracks);goog.exportProperty(shaka.Player.prototype,"getVariantTracks",shaka.Player.prototype.getVariantTracks);goog.exportProperty(shaka.Player.prototype,"cancelTrickPlay",shaka.Player.prototype.cancelTrickPlay);goog.exportProperty(shaka.Player.prototype,"trickPlay",shaka.Player.prototype.trickPlay);goog.exportProperty(shaka.Player.prototype,"useTrickPlayTrackIfAvailable",shaka.Player.prototype.useTrickPlayTrackIfAvailable);
goog.exportProperty(shaka.Player.prototype,"getPlaybackRate",shaka.Player.prototype.getPlaybackRate);goog.exportProperty(shaka.Player.prototype,"isBuffering",shaka.Player.prototype.isBuffering);goog.exportProperty(shaka.Player.prototype,"getKeyStatuses",shaka.Player.prototype.getKeyStatuses);goog.exportProperty(shaka.Player.prototype,"getActiveSessionsMetadata",shaka.Player.prototype.getActiveSessionsMetadata);goog.exportProperty(shaka.Player.prototype,"getExpiration",shaka.Player.prototype.getExpiration);
goog.exportProperty(shaka.Player.prototype,"drmInfo",shaka.Player.prototype.drmInfo);goog.exportProperty(shaka.Player.prototype,"keySystem",shaka.Player.prototype.keySystem);goog.exportProperty(shaka.Player.prototype,"isFullyLoaded",shaka.Player.prototype.isFullyLoaded);goog.exportProperty(shaka.Player.prototype,"goToLive",shaka.Player.prototype.goToLive);goog.exportProperty(shaka.Player.prototype,"seekRange",shaka.Player.prototype.seekRange);
goog.exportProperty(shaka.Player.prototype,"isVideoOnly",shaka.Player.prototype.isVideoOnly);goog.exportProperty(shaka.Player.prototype,"isAudioOnly",shaka.Player.prototype.isAudioOnly);goog.exportProperty(shaka.Player.prototype,"isInProgress",shaka.Player.prototype.isInProgress);goog.exportProperty(shaka.Player.prototype,"isLive",shaka.Player.prototype.isLive);goog.exportProperty(shaka.Player.prototype,"getQueueManager",shaka.Player.prototype.getQueueManager);
goog.exportProperty(shaka.Player.prototype,"getAdManager",shaka.Player.prototype.getAdManager);goog.exportProperty(shaka.Player.prototype,"getAssetUri",shaka.Player.prototype.getAssetUri);goog.exportProperty(shaka.Player.prototype,"getNetworkingEngine",shaka.Player.prototype.getNetworkingEngine);goog.exportProperty(shaka.Player.prototype,"getMediaElement",shaka.Player.prototype.getMediaElement);goog.exportProperty(shaka.Player.prototype,"getManifestType",shaka.Player.prototype.getManifestType);
goog.exportProperty(shaka.Player.prototype,"getLoadMode",shaka.Player.prototype.getLoadMode);goog.exportProperty(shaka.Player.prototype,"resetConfiguration",shaka.Player.prototype.resetConfiguration);goog.exportProperty(shaka.Player.prototype,"getBufferFullness",shaka.Player.prototype.getBufferFullness);goog.exportProperty(shaka.Player.prototype,"getNonDefaultConfiguration",shaka.Player.prototype.getNonDefaultConfiguration);
goog.exportProperty(shaka.Player.prototype,"getConfigurationForLowLatency",shaka.Player.prototype.getConfigurationForLowLatency);goog.exportProperty(shaka.Player.prototype,"getConfiguration",shaka.Player.prototype.getConfiguration);goog.exportProperty(shaka.Player.prototype,"configurationForLowLatency",shaka.Player.prototype.configurationForLowLatency);goog.exportProperty(shaka.Player.prototype,"configure",shaka.Player.prototype.configure);
goog.exportProperty(shaka.Player.prototype,"releaseAllMutexes",shaka.Player.prototype.releaseAllMutexes);goog.exportProperty(shaka.Player.prototype,"destroyAllPreloads",shaka.Player.prototype.destroyAllPreloads);goog.exportProperty(shaka.Player.prototype,"preload",shaka.Player.prototype.preload);goog.exportProperty(shaka.Player.prototype,"detachAndSavePreload",shaka.Player.prototype.detachAndSavePreload);goog.exportProperty(shaka.Player.prototype,"unloadAndSavePreload",shaka.Player.prototype.unloadAndSavePreload);
goog.exportProperty(shaka.Player.prototype,"load",shaka.Player.prototype.load);goog.exportProperty(shaka.Player.prototype,"updateStartTime",shaka.Player.prototype.updateStartTime);goog.exportProperty(shaka.Player.prototype,"unload",shaka.Player.prototype.unload);goog.exportProperty(shaka.Player.prototype,"detach",shaka.Player.prototype.detach);goog.exportProperty(shaka.Player.prototype,"attachCanvas",shaka.Player.prototype.attachCanvas);goog.exportProperty(shaka.Player.prototype,"attach",shaka.Player.prototype.attach);
goog.exportProperty(shaka.Player,"probeSupport",shaka.Player.probeSupport);goog.exportProperty(shaka.Player,"isBrowserSupported",shaka.Player.isBrowserSupported);goog.exportProperty(shaka.Player,"setQueueManagerFactory",shaka.Player.setQueueManagerFactory);goog.exportProperty(shaka.Player,"setAdManagerFactory",shaka.Player.setAdManagerFactory);goog.exportProperty(shaka.Player,"registerSupportPlugin",shaka.Player.registerSupportPlugin);goog.exportProperty(shaka.Player.prototype,"destroy",shaka.Player.prototype.destroy);
shaka.Player.LoadMode={DESTROYED:0,NOT_LOADED:1,MEDIA_SOURCE:2,SRC_EQUALS:3};goog.exportProperty(shaka.Player,"LoadMode",shaka.Player.LoadMode);shaka.Player.TYPICAL_BUFFERING_THRESHOLD_=.5;shaka.Player.version="v4.16.37-debug";goog.exportProperty(shaka.Player,"version",shaka.Player.version);shaka.Deprecate.init(shaka.Player.version);shaka.Player.supportPlugins_=new Map;shaka.Player.adManagerFactory_=null;shaka.Player.queueManagerFactory_=null;shaka.Player.TextTrackLabel="Shaka Player TextTrack";shaka.ads={};
shaka.ads.AdsStats=class{constructor(){this.loadTimes_=[];this.errors_=this.skipped_=this.playedCompletely_=this.overlayAds_=this.started_=0}addLoadTime(a){this.loadTimes_.push(a)}incrementStarted(){this.started_++}incrementOverlayAds(){this.overlayAds_++}incrementPlayedCompletely(){this.playedCompletely_++}incrementSkipped(){this.skipped_++}incrementErrors(){this.errors_++}getAverageLoadTime_(){return this.loadTimes_.length?this.loadTimes_.reduce((a,b)=>a+b,0)/this.loadTimes_.length:0}getBlob(){return{loadTimes:this.loadTimes_,
averageLoadTime:this.getAverageLoadTime_(),started:this.started_,overlayAds:this.overlayAds_,playedCompletely:this.playedCompletely_,skipped:this.skipped_,errors:this.errors_}}};shaka.ads.ClientSideAd=class{constructor(a,b,c){this.ad_=a;this.manager_=b;this.video_=c;this.isPaused_=!1;this.volume_=this.manager_.getVolume();this.eventManager_=new shaka.util.EventManager;this.eventManager_.listen(this.manager_,google.ima.AdEvent.Type.PAUSED,()=>{this.isPaused_=!0});this.eventManager_.listen(this.manager_,google.ima.AdEvent.Type.RESUMED,()=>{this.isPaused_=!1})}needsSkipUI(){return!1}isClientRendering(){return!0}hasCustomClick(){return!0}isUsingAnotherMediaElement(){return!0}getDuration(){return this.ad_.getDuration()}getMinSuggestedDuration(){return this.ad_.getMinSuggestedDuration()}getRemainingTime(){return this.manager_.getRemainingTime()}isPaused(){return this.isPaused_}isSkippable(){return this.ad_.getSkipTimeOffset()>=
0}getTimeUntilSkippable(){var a=this.ad_.getSkipTimeOffset();a=this.getRemainingTime()-a;return Math.max(a,0)}canSkipNow(){return this.manager_.getAdSkippableState()}skip(){return this.manager_.skip()}setPaused(a){this.isPaused_=a}pause(){return this.manager_.pause()}play(){return this.manager_.resume()}getVolume(){return this.manager_.getVolume()}setVolume(a){this.video_.volume=a;return this.manager_.setVolume(a)}isMuted(){return this.manager_.getVolume()==0}isLinear(){return this.ad_.isLinear()}resize(a,
b){this.manager_.resize(a,b)}setMuted(a){(this.video_.muted=a)?(this.volume_=this.getVolume(),this.manager_.setVolume(0)):this.manager_.setVolume(this.volume_)}setInitialMuted(a){this.volume_=a;this.manager_.setVolume(0)}getSequenceLength(){const a=this.ad_.getAdPodInfo();return a==null?1:a.getTotalAds()}getPositionInSequence(){const a=this.ad_.getAdPodInfo();return a==null?1:a.getAdPosition()}getTitle(){return this.ad_.getTitle()}getDescription(){return this.ad_.getDescription()}getVastMediaBitrate(){return this.ad_.getVastMediaBitrate()}getVastMediaHeight(){return this.ad_.getVastMediaHeight()}getVastMediaWidth(){return this.ad_.getVastMediaWidth()}getVastAdId(){return""}getAdId(){return this.ad_.getAdId()}getCreativeAdId(){return this.ad_.getCreativeAdId()}getAdvertiserName(){return this.ad_.getAdvertiserName()}getMediaUrl(){return this.ad_.getMediaUrl()}getTimeOffset(){const a=
this.ad_.getAdPodInfo();return a==null?0:a.getTimeOffset()}getPodIndex(){const a=this.ad_.getAdPodInfo();return a==null?0:a.getPodIndex()}release(){this.manager_=this.ad_=null}};goog.exportSymbol("shaka.ads.ClientSideAd",shaka.ads.ClientSideAd);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"release",shaka.ads.ClientSideAd.prototype.release);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getPodIndex",shaka.ads.ClientSideAd.prototype.getPodIndex);
goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getTimeOffset",shaka.ads.ClientSideAd.prototype.getTimeOffset);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getMediaUrl",shaka.ads.ClientSideAd.prototype.getMediaUrl);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getAdvertiserName",shaka.ads.ClientSideAd.prototype.getAdvertiserName);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getCreativeAdId",shaka.ads.ClientSideAd.prototype.getCreativeAdId);
goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getAdId",shaka.ads.ClientSideAd.prototype.getAdId);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getVastAdId",shaka.ads.ClientSideAd.prototype.getVastAdId);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getVastMediaWidth",shaka.ads.ClientSideAd.prototype.getVastMediaWidth);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getVastMediaHeight",shaka.ads.ClientSideAd.prototype.getVastMediaHeight);
goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getVastMediaBitrate",shaka.ads.ClientSideAd.prototype.getVastMediaBitrate);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getDescription",shaka.ads.ClientSideAd.prototype.getDescription);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getTitle",shaka.ads.ClientSideAd.prototype.getTitle);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getPositionInSequence",shaka.ads.ClientSideAd.prototype.getPositionInSequence);
goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getSequenceLength",shaka.ads.ClientSideAd.prototype.getSequenceLength);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"setMuted",shaka.ads.ClientSideAd.prototype.setMuted);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"resize",shaka.ads.ClientSideAd.prototype.resize);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"isLinear",shaka.ads.ClientSideAd.prototype.isLinear);
goog.exportProperty(shaka.ads.ClientSideAd.prototype,"isMuted",shaka.ads.ClientSideAd.prototype.isMuted);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"setVolume",shaka.ads.ClientSideAd.prototype.setVolume);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getVolume",shaka.ads.ClientSideAd.prototype.getVolume);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"play",shaka.ads.ClientSideAd.prototype.play);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"pause",shaka.ads.ClientSideAd.prototype.pause);
goog.exportProperty(shaka.ads.ClientSideAd.prototype,"skip",shaka.ads.ClientSideAd.prototype.skip);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"canSkipNow",shaka.ads.ClientSideAd.prototype.canSkipNow);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getTimeUntilSkippable",shaka.ads.ClientSideAd.prototype.getTimeUntilSkippable);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"isSkippable",shaka.ads.ClientSideAd.prototype.isSkippable);
goog.exportProperty(shaka.ads.ClientSideAd.prototype,"isPaused",shaka.ads.ClientSideAd.prototype.isPaused);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getRemainingTime",shaka.ads.ClientSideAd.prototype.getRemainingTime);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getMinSuggestedDuration",shaka.ads.ClientSideAd.prototype.getMinSuggestedDuration);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getDuration",shaka.ads.ClientSideAd.prototype.getDuration);
goog.exportProperty(shaka.ads.ClientSideAd.prototype,"isUsingAnotherMediaElement",shaka.ads.ClientSideAd.prototype.isUsingAnotherMediaElement);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"hasCustomClick",shaka.ads.ClientSideAd.prototype.hasCustomClick);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"isClientRendering",shaka.ads.ClientSideAd.prototype.isClientRendering);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"needsSkipUI",shaka.ads.ClientSideAd.prototype.needsSkipUI);shaka.ads.Utils=class{static parseVastToInterstitials(a,b){const c=shaka.util.TXml,d=[];for(const e of c.findChildren(a,"Ad")){a=c.findChild(e,"InLine");if(!a)continue;if(a=c.findChild(a,"Creatives"))for(const f of c.findChildren(a,"Creative"))if((a=c.findChild(f,"Linear"))&&shaka.ads.Utils.processLinearAd_(d,b,a),a=c.findChild(f,"NonLinearAds")){a=c.findChildren(a,"NonLinear");for(const g of a)shaka.ads.Utils.processNonLinearAd_(d,b,g)}}return d}static processLinearAd_(a,b,c){const d=shaka.util.TXml;
let e=0;b!=null&&(e=b);let f=null;c.attributes.skipoffset&&(f=shaka.util.TextParser.parseTime(c.attributes.skipoffset),isNaN(f)&&(f=null));var g=d.findChild(c,"MediaFiles");if(g){var h=null;(c=d.findChild(c,"VideoClicks"))&&(c=d.findChild(c,"ClickThrough"))&&(c=d.getContents(c))&&(h=c);g=c=d.findChildren(g,"MediaFile");c=c.filter(k=>k.attributes.delivery=="streaming");c.length&&(g=c);g=g.sort((k,l)=>{k=parseInt(k.attributes.height,10)||0;return(parseInt(l.attributes.height,10)||0)-k});for(const k of g){if(k.attributes.apiFramework)continue;
if(g=d.getContents(k)){a.push({id:null,groupId:null,startTime:e,endTime:null,uri:g,mimeType:k.attributes.type||null,isSkippable:f!=null,skipOffset:f,skipFor:null,canJump:!1,resumeOffset:0,playoutLimit:null,once:!0,pre:b==null,post:b==Infinity,timelineRange:!1,loop:!1,overlay:null,displayOnBackground:!1,currentVideo:null,background:null,clickThroughUrl:h});break}}}}static processNonLinearAd_(a,b,c){var d=shaka.util.TXml;let e;var f=d.findChild(c,"StaticResource");if(f)e=f.attributes.creativeType;else{f=
d.findChild(c,"HTMLResource");if(!f)return;e="text/html"}if(f=d.getContents(f)){e==="text/html"&&(f="data:text/html;charset=UTF-8,"+encodeURIComponent(f));var g=d.parseAttr(c,"width",d.parseInt)||d.parseAttr(c,"expandedWidth",d.parseInt),h=d.parseAttr(c,"height",d.parseInt)||d.parseAttr(c,"expandedHeight",d.parseInt);if(g||h){var k=null,l=d.findChild(c,"NonLinearClickThrough");l&&(d=d.getContents(l))&&(k=d);d=null;(c=c.attributes.minSuggestedDuration)&&(d=shaka.util.TextParser.parseTime(c));c=0;b!=
null&&(c=b);a.push({id:null,groupId:null,startTime:c,endTime:null,uri:f,mimeType:e,isSkippable:!1,skipOffset:null,skipFor:null,canJump:!1,resumeOffset:0,playoutLimit:d,once:!0,pre:b==null,post:b==Infinity,timelineRange:!1,loop:!1,overlay:{viewport:{x:0,y:0},topLeft:{x:0,y:0},size:{x:g||0,y:h||0}},displayOnBackground:!1,currentVideo:null,background:null,clickThroughUrl:k})}}}static parseVMAP(a){const b=shaka.util.TXml,c=[];for(const e of b.findChildren(a,"vmap:AdBreak")){a=e.attributes.timeOffset;
if(!a)continue;a=a=="start"?null:a=="end"?Infinity:shaka.util.TextParser.parseTime(a);var d=b.findChild(e,"vmap:AdSource");if(!d)continue;d=b.findChild(d,"vmap:AdTagURI");if(!d)continue;(d=b.getTextContents(d))&&c.push({time:a,uri:d})}return c}};goog.exportSymbol("shaka.ads.Utils",shaka.ads.Utils);shaka.ads.Utils.ADS_LOADED="ads-loaded";goog.exportProperty(shaka.ads.Utils,"ADS_LOADED",shaka.ads.Utils.ADS_LOADED);shaka.ads.Utils.AD_STARTED="ad-started";
goog.exportProperty(shaka.ads.Utils,"AD_STARTED",shaka.ads.Utils.AD_STARTED);shaka.ads.Utils.AD_FIRST_QUARTILE="ad-first-quartile";goog.exportProperty(shaka.ads.Utils,"AD_FIRST_QUARTILE",shaka.ads.Utils.AD_FIRST_QUARTILE);shaka.ads.Utils.AD_MIDPOINT="ad-midpoint";goog.exportProperty(shaka.ads.Utils,"AD_MIDPOINT",shaka.ads.Utils.AD_MIDPOINT);shaka.ads.Utils.AD_THIRD_QUARTILE="ad-third-quartile";goog.exportProperty(shaka.ads.Utils,"AD_THIRD_QUARTILE",shaka.ads.Utils.AD_THIRD_QUARTILE);
shaka.ads.Utils.AD_COMPLETE="ad-complete";goog.exportProperty(shaka.ads.Utils,"AD_COMPLETE",shaka.ads.Utils.AD_COMPLETE);shaka.ads.Utils.AD_STOPPED="ad-stopped";goog.exportProperty(shaka.ads.Utils,"AD_STOPPED",shaka.ads.Utils.AD_STOPPED);shaka.ads.Utils.AD_SKIPPED="ad-skipped";goog.exportProperty(shaka.ads.Utils,"AD_SKIPPED",shaka.ads.Utils.AD_SKIPPED);shaka.ads.Utils.AD_VOLUME_CHANGED="ad-volume-changed";goog.exportProperty(shaka.ads.Utils,"AD_VOLUME_CHANGED",shaka.ads.Utils.AD_VOLUME_CHANGED);
shaka.ads.Utils.AD_MUTED="ad-muted";goog.exportProperty(shaka.ads.Utils,"AD_MUTED",shaka.ads.Utils.AD_MUTED);shaka.ads.Utils.AD_PAUSED="ad-paused";goog.exportProperty(shaka.ads.Utils,"AD_PAUSED",shaka.ads.Utils.AD_PAUSED);shaka.ads.Utils.AD_RESUMED="ad-resumed";goog.exportProperty(shaka.ads.Utils,"AD_RESUMED",shaka.ads.Utils.AD_RESUMED);shaka.ads.Utils.AD_SKIP_STATE_CHANGED="ad-skip-state-changed";goog.exportProperty(shaka.ads.Utils,"AD_SKIP_STATE_CHANGED",shaka.ads.Utils.AD_SKIP_STATE_CHANGED);
shaka.ads.Utils.CUEPOINTS_CHANGED="ad-cue-points-changed";goog.exportProperty(shaka.ads.Utils,"CUEPOINTS_CHANGED",shaka.ads.Utils.CUEPOINTS_CHANGED);shaka.ads.Utils.IMA_AD_MANAGER_LOADED="ima-ad-manager-loaded";goog.exportProperty(shaka.ads.Utils,"IMA_AD_MANAGER_LOADED",shaka.ads.Utils.IMA_AD_MANAGER_LOADED);shaka.ads.Utils.IMA_STREAM_MANAGER_LOADED="ima-stream-manager-loaded";goog.exportProperty(shaka.ads.Utils,"IMA_STREAM_MANAGER_LOADED",shaka.ads.Utils.IMA_STREAM_MANAGER_LOADED);
shaka.ads.Utils.AD_CLICKED="ad-clicked";goog.exportProperty(shaka.ads.Utils,"AD_CLICKED",shaka.ads.Utils.AD_CLICKED);shaka.ads.Utils.AD_PROGRESS="ad-progress";goog.exportProperty(shaka.ads.Utils,"AD_PROGRESS",shaka.ads.Utils.AD_PROGRESS);shaka.ads.Utils.AD_BUFFERING="ad-buffering";goog.exportProperty(shaka.ads.Utils,"AD_BUFFERING",shaka.ads.Utils.AD_BUFFERING);shaka.ads.Utils.AD_IMPRESSION="ad-impression";goog.exportProperty(shaka.ads.Utils,"AD_IMPRESSION",shaka.ads.Utils.AD_IMPRESSION);
shaka.ads.Utils.AD_DURATION_CHANGED="ad-duration-changed";goog.exportProperty(shaka.ads.Utils,"AD_DURATION_CHANGED",shaka.ads.Utils.AD_DURATION_CHANGED);shaka.ads.Utils.AD_CLOSED="ad-closed";goog.exportProperty(shaka.ads.Utils,"AD_CLOSED",shaka.ads.Utils.AD_CLOSED);shaka.ads.Utils.AD_LOADED="ad-loaded";goog.exportProperty(shaka.ads.Utils,"AD_LOADED",shaka.ads.Utils.AD_LOADED);shaka.ads.Utils.ALL_ADS_COMPLETED="all-ads-completed";goog.exportProperty(shaka.ads.Utils,"ALL_ADS_COMPLETED",shaka.ads.Utils.ALL_ADS_COMPLETED);
shaka.ads.Utils.AD_LINEAR_CHANGED="ad-linear-changed";goog.exportProperty(shaka.ads.Utils,"AD_LINEAR_CHANGED",shaka.ads.Utils.AD_LINEAR_CHANGED);shaka.ads.Utils.AD_METADATA="ad-metadata";goog.exportProperty(shaka.ads.Utils,"AD_METADATA",shaka.ads.Utils.AD_METADATA);shaka.ads.Utils.AD_RECOVERABLE_ERROR="ad-recoverable-error";goog.exportProperty(shaka.ads.Utils,"AD_RECOVERABLE_ERROR",shaka.ads.Utils.AD_RECOVERABLE_ERROR);shaka.ads.Utils.AD_ERROR="ad-error";
goog.exportProperty(shaka.ads.Utils,"AD_ERROR",shaka.ads.Utils.AD_ERROR);shaka.ads.Utils.AD_BREAK_READY="ad-break-ready";goog.exportProperty(shaka.ads.Utils,"AD_BREAK_READY",shaka.ads.Utils.AD_BREAK_READY);shaka.ads.Utils.AD_INTERACTION="ad-interaction";goog.exportProperty(shaka.ads.Utils,"AD_INTERACTION",shaka.ads.Utils.AD_INTERACTION);shaka.ads.Utils.AD_CONTENT_PAUSE_REQUESTED="ad-content-pause-requested";goog.exportProperty(shaka.ads.Utils,"AD_CONTENT_PAUSE_REQUESTED",shaka.ads.Utils.AD_CONTENT_PAUSE_REQUESTED);
shaka.ads.Utils.AD_CONTENT_RESUME_REQUESTED="ad-content-resume-requested";goog.exportProperty(shaka.ads.Utils,"AD_CONTENT_RESUME_REQUESTED",shaka.ads.Utils.AD_CONTENT_RESUME_REQUESTED);shaka.ads.Utils.AD_CONTENT_ATTACH_REQUESTED="ad-content-attach-requested";goog.exportProperty(shaka.ads.Utils,"AD_CONTENT_ATTACH_REQUESTED",shaka.ads.Utils.AD_CONTENT_ATTACH_REQUESTED);shaka.ads.ClientSideAdManager=class{constructor(a,b,c,d,e){this.adContainer_=a;this.video_=b;this.videoPlayed_=!1;this.resizeObserver_=this.config_=null;this.requestAdsStartTime_=NaN;this.onEvent_=e;this.ad_=null;this.eventManager_=new shaka.util.EventManager;google.ima.settings.setLocale(c);google.ima.settings.setDisableCustomPlaybackForIOS10Plus(!0);this.adDisplayContainer_=new google.ima.AdDisplayContainer(this.adContainer_,this.video_);this.adDisplayContainer_.initialize();this.adsLoader_=new google.ima.AdsLoader(this.adDisplayContainer_);
this.adsLoader_.getSettings().setPlayerType("shaka-player");this.adsLoader_.getSettings().setPlayerVersion(shaka.Player.version);this.imaAdsManager_=null;this.adsRenderingSettings_=d||new google.ima.AdsRenderingSettings;this.eventManager_.listen(this.adsLoader_,google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,f=>{this.onAdsManagerLoaded_(f)});this.eventManager_.listen(this.adsLoader_,google.ima.AdErrorEvent.Type.AD_ERROR,f=>{this.onAdError_(f)});this.eventManager_.listen(this.video_,"ended",
()=>{this.adsLoader_.contentComplete()});this.eventManager_.listenOnce(this.video_,"play",()=>{this.videoPlayed_=!0})}configure(a){this.config_=a}requestAds(a){goog.asserts.assert(a.adTagUrl||a.adsResponse,"The ad tag needs to be set up before requesting ads, or adsResponse must be filled.");this.imaAdsManager_&&this.imaAdsManager_.destroy();this.adsLoader_&&this.adsLoader_.contentComplete();this.requestAdsStartTime_=Date.now()/1E3;this.adsLoader_.requestAds(a)}updateAdsRenderingSettings(a){this.adsRenderingSettings_=
a;this.imaAdsManager_&&this.imaAdsManager_.updateAdsRenderingSettings(this.adsRenderingSettings_)}stop(){this.imaAdsManager_&&this.imaAdsManager_.stop();this.adContainer_&&shaka.util.Dom.removeAllChildren(this.adContainer_)}release(){this.stop();this.resizeObserver_&&this.resizeObserver_.disconnect();this.eventManager_&&this.eventManager_.release();this.imaAdsManager_&&this.imaAdsManager_.destroy();this.adsLoader_.destroy();this.adDisplayContainer_.destroy()}onAdError_(a){shaka.log.warning("There was an ad error from the IMA SDK: "+
a.getError());shaka.log.warning("Resuming playback.");a=(new Map).set("originalEvent",a);this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_ERROR,a));this.onAdComplete_(null);this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.CUEPOINTS_CHANGED,(new Map).set("cuepoints",[])))}onAdsManagerLoaded_(a){goog.asserts.assert(this.video_!=null,"Video should not be null!");var b=Date.now()/1E3-this.requestAdsStartTime_;this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.ADS_LOADED,(new Map).set("loadTime",
b)));if(this.config_.customPlayheadTracker){const c={currentTime:this.video_.currentTime};this.imaAdsManager_=a.getAdsManager(c,this.adsRenderingSettings_);this.video_.muted?this.imaAdsManager_.setVolume(0):this.imaAdsManager_.setVolume(this.video_.volume);this.eventManager_.listen(this.video_,"timeupdate",()=>{this.video_.duration&&(c.currentTime=this.video_.currentTime)});this.eventManager_.listen(this.video_,"volumechange",()=>{this.ad_&&(this.ad_.setVolume(this.video_.volume),this.video_.muted&&
this.ad_.setMuted(!0))})}else this.imaAdsManager_=a.getAdsManager(this.video_,this.adsRenderingSettings_);this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.IMA_AD_MANAGER_LOADED,(new Map).set("imaAdManager",this.imaAdsManager_)));a=this.imaAdsManager_.getCuePoints();if(a.length){b=[];for(const c of a)b.push({start:c,end:null});this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.CUEPOINTS_CHANGED,(new Map).set("cuepoints",b)))}this.addImaEventListeners_();try{this.imaAdsManager_.init(this.video_.offsetWidth,
this.video_.offsetHeight),this.eventManager_.listen(this.video_,"loadeddata",()=>{this.imaAdsManager_.resize(this.video_.offsetWidth,this.video_.offsetHeight)}),"ResizeObserver"in window?(this.resizeObserver_=new ResizeObserver(()=>{this.imaAdsManager_.resize(this.video_.offsetWidth,this.video_.offsetHeight)}),this.resizeObserver_.observe(this.video_)):this.eventManager_.listen(document,"fullscreenchange",()=>{this.imaAdsManager_.resize(this.video_.offsetWidth,this.video_.offsetHeight)}),this.videoPlayed_||
this.config_.skipPlayDetection?this.imaAdsManager_.start():this.eventManager_.listenOnce(this.video_,"play",()=>{this.videoPlayed_=!0;this.imaAdsManager_.start()})}catch(c){this.onAdComplete_(null)}}addImaEventListeners_(){const a=(b,c)=>{b=(new Map).set("originalEvent",b);this.onEvent_(new shaka.util.FakeEvent(c,b))};this.eventManager_.listen(this.imaAdsManager_,google.ima.AdErrorEvent.Type.AD_ERROR,b=>{this.onAdError_(b)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,
b=>{this.onAdStart_(b)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.STARTED,b=>{this.onAdStart_(b)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.FIRST_QUARTILE,b=>{a(b,shaka.ads.Utils.AD_FIRST_QUARTILE)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.MIDPOINT,b=>{a(b,shaka.ads.Utils.AD_MIDPOINT)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.THIRD_QUARTILE,b=>{a(b,shaka.ads.Utils.AD_THIRD_QUARTILE)});
this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.COMPLETE,b=>{a(b,shaka.ads.Utils.AD_COMPLETE)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,b=>{this.onAdComplete_(b)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.ALL_ADS_COMPLETED,b=>{a(b,shaka.ads.Utils.ALL_ADS_COMPLETED);this.onAdComplete_(b)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.SKIPPED,b=>{a(b,shaka.ads.Utils.AD_SKIPPED)});
this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.VOLUME_CHANGED,b=>{a(b,shaka.ads.Utils.AD_VOLUME_CHANGED)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.VOLUME_MUTED,b=>{a(b,shaka.ads.Utils.AD_MUTED)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.PAUSED,b=>{this.ad_&&(this.ad_.setPaused(!0),a(b,shaka.ads.Utils.AD_PAUSED))});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.RESUMED,b=>{this.ad_&&(this.ad_.setPaused(!1),
a(b,shaka.ads.Utils.AD_RESUMED))});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.SKIPPABLE_STATE_CHANGED,b=>{this.ad_&&a(b,shaka.ads.Utils.AD_SKIP_STATE_CHANGED)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.CLICK,b=>{a(b,shaka.ads.Utils.AD_CLICKED)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.AD_PROGRESS,b=>{a(b,shaka.ads.Utils.AD_PROGRESS)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.AD_BUFFERING,
b=>{a(b,shaka.ads.Utils.AD_BUFFERING)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.IMPRESSION,b=>{a(b,shaka.ads.Utils.AD_IMPRESSION)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.DURATION_CHANGE,b=>{a(b,shaka.ads.Utils.AD_DURATION_CHANGED)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.USER_CLOSE,b=>{a(b,shaka.ads.Utils.AD_CLOSED)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.LOADED,b=>{a(b,shaka.ads.Utils.AD_LOADED)});
this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.LINEAR_CHANGED,b=>{a(b,shaka.ads.Utils.AD_LINEAR_CHANGED)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.AD_METADATA,b=>{a(b,shaka.ads.Utils.AD_METADATA)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.LOG,b=>{a(b,shaka.ads.Utils.AD_RECOVERABLE_ERROR)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.AD_BREAK_READY,b=>{a(b,shaka.ads.Utils.AD_BREAK_READY)});this.eventManager_.listen(this.imaAdsManager_,
google.ima.AdEvent.Type.INTERACTION,b=>{a(b,shaka.ads.Utils.AD_INTERACTION)})}onAdStart_(a){goog.asserts.assert(this.imaAdsManager_,"Should have an ads manager at this point!");const b=a.getAd();if(b){this.ad_=new shaka.ads.ClientSideAd(b,this.imaAdsManager_,this.video_);if(a.type==google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED&&!this.config_.supportsMultipleMediaElements)this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_CONTENT_PAUSE_REQUESTED));a=(new Map).set("ad",this.ad_).set("sdkAdObject",
b).set("originalEvent",a);this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_STARTED,a));this.ad_.isLinear()&&(this.adContainer_.setAttribute("ad-active","true"),this.config_.customPlayheadTracker||this.video_.pause(),this.video_.muted?this.ad_.setInitialMuted(this.video_.volume):this.ad_.setVolume(this.video_.volume))}else shaka.log.alwaysWarn("The IMA SDK fired a "+a.type+" event with no associated ad. Unable to play ad!")}onAdComplete_(a){if(a&&a.type==google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED&&
!this.config_.supportsMultipleMediaElements)this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_CONTENT_RESUME_REQUESTED));this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_STOPPED,(new Map).set("originalEvent",a)));this.ad_&&this.ad_.isLinear()&&(this.adContainer_.removeAttribute("ad-active"),this.config_.customPlayheadTracker||this.video_.ended||this.video_.play())}};shaka.ads.InterstitialAd=class{constructor(a,b,c,d,e,f){this.video_=a;this.interstitial_=b;this.skipOffset_=(this.isSkippable_=b.isSkippable)?b.skipOffset||0:b.skipOffset;this.skipFor_=b.skipFor;this.onSkip_=c;this.sequenceLength_=d;this.adPosition_=e;this.isUsingAnotherMediaElement_=f;this.overlay_=b.overlay}needsSkipUI(){return!0}isClientRendering(){return!0}hasCustomClick(){return this.interstitial_.clickThroughUrl!=null}isUsingAnotherMediaElement(){return this.isUsingAnotherMediaElement_}getDuration(){const a=
this.video_.duration;return isNaN(a)?-1:a}getMinSuggestedDuration(){return this.getDuration()}getRemainingTime(){const a=this.video_.duration;return isNaN(a)?-1:a-this.video_.currentTime}isPaused(){return this.video_.paused}isSkippable(){return this.isSkippable_&&this.skipFor_!=null?this.getDuration()-this.getRemainingTime()<this.skipOffset_+this.skipFor_:this.isSkippable_}getTimeUntilSkippable(){if(this.isSkippable()){const a=this.getRemainingTime()+this.skipOffset_-this.getDuration();return Math.max(a,
0)}return Math.max(this.getRemainingTime(),0)}canSkipNow(){return this.isSkippable_&&this.getTimeUntilSkippable()==0}skip(){if(this.canSkipNow())this.onSkip_()}pause(){return this.video_.pause()}play(){return this.video_.play()}getVolume(){return this.video_.volume}setVolume(a){this.video_.volume=a}isMuted(){return this.video_.muted}isLinear(){return this.overlay_==null}resize(a,b){}setMuted(a){this.video_.muted=a}getSequenceLength(){return this.sequenceLength_}getPositionInSequence(){return this.adPosition_}getTitle(){return""}getDescription(){return""}getVastMediaBitrate(){return 0}getVastMediaHeight(){return 0}getVastMediaWidth(){return 0}getVastAdId(){return""}getAdId(){return this.interstitial_.id||
""}getCreativeAdId(){return""}getAdvertiserName(){return""}getMediaUrl(){return this.interstitial_.uri}getTimeOffset(){return this.interstitial_.pre?0:this.interstitial_.post?-1:this.interstitial_.startTime}getPodIndex(){return 0}release(){this.video_=null}};goog.exportSymbol("shaka.ads.InterstitialAd",shaka.ads.InterstitialAd);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"release",shaka.ads.InterstitialAd.prototype.release);
goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getPodIndex",shaka.ads.InterstitialAd.prototype.getPodIndex);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getTimeOffset",shaka.ads.InterstitialAd.prototype.getTimeOffset);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getMediaUrl",shaka.ads.InterstitialAd.prototype.getMediaUrl);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getAdvertiserName",shaka.ads.InterstitialAd.prototype.getAdvertiserName);
goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getCreativeAdId",shaka.ads.InterstitialAd.prototype.getCreativeAdId);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getAdId",shaka.ads.InterstitialAd.prototype.getAdId);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getVastAdId",shaka.ads.InterstitialAd.prototype.getVastAdId);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getVastMediaWidth",shaka.ads.InterstitialAd.prototype.getVastMediaWidth);
goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getVastMediaHeight",shaka.ads.InterstitialAd.prototype.getVastMediaHeight);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getVastMediaBitrate",shaka.ads.InterstitialAd.prototype.getVastMediaBitrate);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getDescription",shaka.ads.InterstitialAd.prototype.getDescription);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getTitle",shaka.ads.InterstitialAd.prototype.getTitle);
goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getPositionInSequence",shaka.ads.InterstitialAd.prototype.getPositionInSequence);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getSequenceLength",shaka.ads.InterstitialAd.prototype.getSequenceLength);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"setMuted",shaka.ads.InterstitialAd.prototype.setMuted);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"resize",shaka.ads.InterstitialAd.prototype.resize);
goog.exportProperty(shaka.ads.InterstitialAd.prototype,"isLinear",shaka.ads.InterstitialAd.prototype.isLinear);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"isMuted",shaka.ads.InterstitialAd.prototype.isMuted);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"setVolume",shaka.ads.InterstitialAd.prototype.setVolume);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getVolume",shaka.ads.InterstitialAd.prototype.getVolume);
goog.exportProperty(shaka.ads.InterstitialAd.prototype,"play",shaka.ads.InterstitialAd.prototype.play);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"pause",shaka.ads.InterstitialAd.prototype.pause);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"skip",shaka.ads.InterstitialAd.prototype.skip);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"canSkipNow",shaka.ads.InterstitialAd.prototype.canSkipNow);
goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getTimeUntilSkippable",shaka.ads.InterstitialAd.prototype.getTimeUntilSkippable);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"isSkippable",shaka.ads.InterstitialAd.prototype.isSkippable);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"isPaused",shaka.ads.InterstitialAd.prototype.isPaused);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getRemainingTime",shaka.ads.InterstitialAd.prototype.getRemainingTime);
goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getMinSuggestedDuration",shaka.ads.InterstitialAd.prototype.getMinSuggestedDuration);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"getDuration",shaka.ads.InterstitialAd.prototype.getDuration);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"isUsingAnotherMediaElement",shaka.ads.InterstitialAd.prototype.isUsingAnotherMediaElement);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"hasCustomClick",shaka.ads.InterstitialAd.prototype.hasCustomClick);
goog.exportProperty(shaka.ads.InterstitialAd.prototype,"isClientRendering",shaka.ads.InterstitialAd.prototype.isClientRendering);goog.exportProperty(shaka.ads.InterstitialAd.prototype,"needsSkipUI",shaka.ads.InterstitialAd.prototype.needsSkipUI);shaka.ads.InterstitialStaticAd=class{constructor(a,b,c){this.interstitial_=a;this.sequenceLength_=b;this.adPosition_=c;this.isLinear_=a.overlay==null}needsSkipUI(){return!0}isClientRendering(){return!0}hasCustomClick(){return this.interstitial_.clickThroughUrl!=null}isUsingAnotherMediaElement(){return!1}getDuration(){return-1}getMinSuggestedDuration(){return this.getDuration()}getRemainingTime(){return-1}isPaused(){return!1}isSkippable(){return!1}getTimeUntilSkippable(){return 0}canSkipNow(){return!1}skip(){}pause(){}play(){}getVolume(){return 1}setVolume(a){}isMuted(){return!1}isLinear(){return this.isLinear_}resize(a,
b){}setMuted(a){}getSequenceLength(){return this.sequenceLength_}getPositionInSequence(){return this.adPosition_}getTitle(){return""}getDescription(){return""}getVastMediaBitrate(){return 0}getVastMediaHeight(){return 0}getVastMediaWidth(){return 0}getVastAdId(){return""}getAdId(){return this.interstitial_.id||""}getCreativeAdId(){return""}getAdvertiserName(){return""}getMediaUrl(){return this.interstitial_.uri}getTimeOffset(){return this.interstitial_.pre?0:this.interstitial_.post?-1:this.interstitial_.startTime}getPodIndex(){return 0}release(){}};
goog.exportSymbol("shaka.ads.InterstitialStaticAd",shaka.ads.InterstitialStaticAd);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"release",shaka.ads.InterstitialStaticAd.prototype.release);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getPodIndex",shaka.ads.InterstitialStaticAd.prototype.getPodIndex);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getTimeOffset",shaka.ads.InterstitialStaticAd.prototype.getTimeOffset);
goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getMediaUrl",shaka.ads.InterstitialStaticAd.prototype.getMediaUrl);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getAdvertiserName",shaka.ads.InterstitialStaticAd.prototype.getAdvertiserName);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getCreativeAdId",shaka.ads.InterstitialStaticAd.prototype.getCreativeAdId);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getAdId",shaka.ads.InterstitialStaticAd.prototype.getAdId);
goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getVastAdId",shaka.ads.InterstitialStaticAd.prototype.getVastAdId);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getVastMediaWidth",shaka.ads.InterstitialStaticAd.prototype.getVastMediaWidth);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getVastMediaHeight",shaka.ads.InterstitialStaticAd.prototype.getVastMediaHeight);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getVastMediaBitrate",shaka.ads.InterstitialStaticAd.prototype.getVastMediaBitrate);
goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getDescription",shaka.ads.InterstitialStaticAd.prototype.getDescription);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getTitle",shaka.ads.InterstitialStaticAd.prototype.getTitle);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getPositionInSequence",shaka.ads.InterstitialStaticAd.prototype.getPositionInSequence);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getSequenceLength",shaka.ads.InterstitialStaticAd.prototype.getSequenceLength);
goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"setMuted",shaka.ads.InterstitialStaticAd.prototype.setMuted);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"resize",shaka.ads.InterstitialStaticAd.prototype.resize);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"isLinear",shaka.ads.InterstitialStaticAd.prototype.isLinear);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"isMuted",shaka.ads.InterstitialStaticAd.prototype.isMuted);
goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"setVolume",shaka.ads.InterstitialStaticAd.prototype.setVolume);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getVolume",shaka.ads.InterstitialStaticAd.prototype.getVolume);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"play",shaka.ads.InterstitialStaticAd.prototype.play);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"pause",shaka.ads.InterstitialStaticAd.prototype.pause);
goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"skip",shaka.ads.InterstitialStaticAd.prototype.skip);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"canSkipNow",shaka.ads.InterstitialStaticAd.prototype.canSkipNow);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getTimeUntilSkippable",shaka.ads.InterstitialStaticAd.prototype.getTimeUntilSkippable);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"isSkippable",shaka.ads.InterstitialStaticAd.prototype.isSkippable);
goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"isPaused",shaka.ads.InterstitialStaticAd.prototype.isPaused);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getRemainingTime",shaka.ads.InterstitialStaticAd.prototype.getRemainingTime);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getMinSuggestedDuration",shaka.ads.InterstitialStaticAd.prototype.getMinSuggestedDuration);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"getDuration",shaka.ads.InterstitialStaticAd.prototype.getDuration);
goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"isUsingAnotherMediaElement",shaka.ads.InterstitialStaticAd.prototype.isUsingAnotherMediaElement);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"hasCustomClick",shaka.ads.InterstitialStaticAd.prototype.hasCustomClick);goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"isClientRendering",shaka.ads.InterstitialStaticAd.prototype.isClientRendering);
goog.exportProperty(shaka.ads.InterstitialStaticAd.prototype,"needsSkipUI",shaka.ads.InterstitialStaticAd.prototype.needsSkipUI);shaka.ads.InterstitialAdManager=class{constructor(a,b,c,d){this.config_=null;this.adContainer_=a;this.basePlayer_=b;this.baseVideo_=c;this.adVideo_=null;this.usingBaseVideo_=!0;this.video_=this.baseVideo_;this.onEvent_=d;this.hlsInterstitialIds_=new Set;this.interstitialIds_=new Set;this.interstitials_=new Set;this.preloadManagerInterstitials_=new Map;this.preloadOnDomElements_=new Map;this.player_=new shaka.Player;this.updatePlayerConfig_();this.eventManager_=new shaka.util.EventManager;this.adEventManager_=
new shaka.util.EventManager;this.playingAd_=!1;this.lastOnSkip_=this.playoutLimitTimer_=this.lastPlayedAd_=this.lastTime_=null;this.usingListeners_=!1;this.videoCallbackId_=-1;const e=f=>f?f.overlay?!0:this.baseVideo_.ended?f.post:this.baseVideo_.paused?!1:!0:!1;this.checkForInterstitials_=()=>{if(!this.playingAd_&&this.lastTime_&&!this.basePlayer_.isRemotePlayback()){this.lastTime_=this.baseVideo_.currentTime;var f=this.getCurrentInterstitial_();f&&e(f)&&this.setupAd_(f,1,1,Date.now())}};this.onTimeUpdate_=
()=>{if(!(this.playingAd_||this.lastTime_||this.basePlayer_.isRemotePlayback())){this.baseVideo_.paused||(this.lastTime_=this.baseVideo_.currentTime);var f;this.lastPlayedAd_||(f=this.getCurrentInterstitial_(!0));f||=this.getCurrentInterstitial_();f&&e(f)&&this.setupAd_(f,1,1,Date.now())}};this.onSeeked_=()=>{if(!this.playingAd_&&this.lastTime_&&!this.basePlayer_.isRemotePlayback()){var f=this.baseVideo_.currentTime;this.lastPlayedAd_&&!this.lastPlayedAd_.pre&&!this.lastPlayedAd_.post&&f<(this.lastPlayedAd_.endTime||
this.lastPlayedAd_.startTime)&&(this.lastPlayedAd_=null)}};this.timeUpdateTimer_=new shaka.util.Timer(this.checkForInterstitials_);this.pollTimer_=new shaka.util.Timer(async()=>{if(this.interstitials_.size&&this.lastTime_!=null){var f=this.basePlayer_.getLoadMode();if(f!=shaka.Player.LoadMode.DESTROYED&&f!=shaka.Player.LoadMode.NOT_LOADED){f=!1;var g=Array.from(this.interstitials_),h=this.basePlayer_.seekRange();for(const k of g)k!=this.lastPlayedAd_&&(h.start-(k.endTime||k.startTime)>=1?(this.preloadManagerInterstitials_.has(k)&&
((g=await this.preloadManagerInterstitials_.get(k))&&g.destroy(),this.preloadManagerInterstitials_.delete(k)),this.removePreloadOnDomElements_(k),g=k.id||JSON.stringify(k),this.interstitialIds_.has(g)&&this.interstitialIds_.delete(g),this.interstitials_.delete(k),this.removeEventListeners_(),k.overlay||(f=!0)):(g=k.startTime-this.lastTime_,g>0&&g<=10&&(!this.preloadManagerInterstitials_.has(k)&&this.isPreloadAllowed_(k)&&this.preloadManagerInterstitials_.set(k,this.player_.preload(k.uri,null,k.mimeType||
void 0)),this.checkPreloadOnDomElements_(k))));f&&this.cuepointsChanged_()}}});this.configure(this.basePlayer_.getConfiguration().ads)}configure(a){this.config_=a;this.playingAd_||this.determineIfUsingBaseVideo_()}addEventListeners_(){if(!this.usingListeners_&&this.interstitials_.size){this.eventManager_.listen(this.baseVideo_,"playing",this.onTimeUpdate_);this.eventManager_.listen(this.baseVideo_,"timeupdate",this.onTimeUpdate_);this.eventManager_.listen(this.baseVideo_,"seeked",this.onSeeked_);
this.eventManager_.listen(this.baseVideo_,"ended",this.checkForInterstitials_);if("requestVideoFrameCallback"in this.baseVideo_&&!this.isSmartTV_()){const a=this.baseVideo_,b=(c,d)=>{this.videoCallbackId_!=-1&&(this.checkForInterstitials_(),this.videoCallbackId_!=-1&&(this.videoCallbackId_=a.requestVideoFrameCallback(b)))};this.videoCallbackId_=a.requestVideoFrameCallback(b)}else this.timeUpdateTimer_.tickEvery(.025);this.pollTimer_&&this.pollTimer_.tickEvery(1);this.usingListeners_=!0}}removeEventListeners_(){this.usingListeners_&&
!this.interstitials_.size&&(this.eventManager_.unlisten(this.baseVideo_,"playing",this.onTimeUpdate_),this.eventManager_.unlisten(this.baseVideo_,"timeupdate",this.onTimeUpdate_),this.eventManager_.unlisten(this.baseVideo_,"seeked",this.onSeeked_),this.eventManager_.unlisten(this.baseVideo_,"ended",this.checkForInterstitials_),this.videoCallbackId_!=-1&&(this.baseVideo_.cancelVideoFrameCallback(this.videoCallbackId_),this.videoCallbackId_=-1),this.timeUpdateTimer_&&this.timeUpdateTimer_.stop(),this.pollTimer_&&
this.pollTimer_.stop(),this.usingListeners_=!1)}determineIfUsingBaseVideo_(){if(this.adContainer_&&this.config_){var a=this.config_.supportsMultipleMediaElements,b=this.baseVideo_;b.controls?a=!1:b.webkitPresentationMode&&b.webkitPresentationMode!=="inline"?a=!1:b.webkitDisplayingFullscreen&&(a=!1);this.usingBaseVideo_==a&&((this.usingBaseVideo_=!a)?(this.video_=this.baseVideo_,this.adVideo_&&(this.adVideo_.parentElement&&this.adContainer_.removeChild(this.adVideo_),this.adVideo_=null)):(this.adVideo_||
(this.adVideo_=this.createMediaElement_()),this.video_=this.adVideo_))}else this.usingBaseVideo_=!0}stop(){this.adEventManager_&&this.adEventManager_.removeAll();this.hlsInterstitialIds_.clear();this.interstitialIds_.clear();this.interstitials_.clear();this.player_.destroyAllPreloads();if(this.preloadManagerInterstitials_.size){var a=Array.from(this.preloadManagerInterstitials_.values());for(const b of a)b&&b.then(c=>{c&&c.destroy()})}this.preloadManagerInterstitials_.clear();if(this.preloadOnDomElements_.size){a=
Array.from(this.preloadOnDomElements_.keys());for(const b of a)this.removePreloadOnDomElements_(b)}this.preloadOnDomElements_.clear();this.player_.detach();this.playingAd_=!1;this.lastPlayedAd_=this.lastTime_=null;this.usingBaseVideo_=!0;this.video_=this.baseVideo_;this.adVideo_=null;this.removeBaseStyles_();this.removeEventListeners_();this.adContainer_&&shaka.util.Dom.removeAllChildren(this.adContainer_);this.playoutLimitTimer_&&(this.playoutLimitTimer_.stop(),this.playoutLimitTimer_=null)}release(){this.stop();
this.eventManager_&&this.eventManager_.release();this.adEventManager_&&this.adEventManager_.release();this.timeUpdateTimer_&&(this.timeUpdateTimer_.stop(),this.timeUpdateTimer_=null);this.pollTimer_&&(this.pollTimer_.stop(),this.pollTimer_=null);this.player_.destroy()}getPlayer(){return this.player_}async addMetadata(a){var b=null;const c=a.values.find(d=>d.key=="ID");c&&(b=c.data);if(b){if(this.hlsInterstitialIds_.has(b))return;this.hlsInterstitialIds_.add(b)}this.updatePlayerConfig_();b=[];b=a&&
a.values.find(d=>d.key=="X-OVERLAY-ID")?this.getOverlaysInfo_(a):await this.getInterstitialsInfo_(a);b.length?this.addInterstitials(b):shaka.log.alwaysWarn("Unsupported HLS interstitial",a)}addRegion(a){var b=shaka.util.TXml;const c=a.schemeIdUri=="urn:mpeg:dash:event:alternativeMPD:replace:2025",d=a.schemeIdUri=="urn:mpeg:dash:event:alternativeMPD:insert:2025";if(c||d){var e=a.startTime,f=a.endTime,g=null,h=0;for(const m of a.eventNode.children)if(m.tagName=="AlternativeMPD"){var k=m.attributes.uri;
if(k){var l=k;break}}else if(m.tagName=="InsertPresentation"||m.tagName=="ReplacePresentation")if(k=m.attributes.uri||m.attributes.url){l=shaka.util.StringUtils.htmlUnescape(k);(k=b.parseAttr(m,"maxDuration",b.parseInt))&&(g=k/a.timescale);(b=b.parseAttr(m,"returnOffset",b.parseInt))&&(h=b/a.timescale);c&&h&&(f=e+h);break}l?this.addInterstitials([{id:a.id,groupId:null,startTime:e,endTime:f,uri:l,mimeType:null,isSkippable:!1,skipOffset:null,skipFor:null,canJump:!0,resumeOffset:d?h:null,playoutLimit:g,
once:!1,pre:!1,post:!1,timelineRange:c&&!d,loop:!1,overlay:null,displayOnBackground:!1,currentVideo:null,background:null,clickThroughUrl:null}]):shaka.log.warning("Unsupported alternative media presentation",a)}else shaka.log.warning("Unsupported alternative media presentation",a)}addOverlayRegion(a){var b=shaka.util.TXml;goog.asserts.assert(a.eventNode,"Need a region eventNode");var c=b.findChild(a.eventNode,"OverlayEvent");const d=c.attributes.uri,e=c.attributes.mimeType,f=c.attributes.loop=="true",
g=b.parseAttr(c,"z",b.parseInt);if(d&&g!=0){var h=null,k=b.findChild(c,"Background");k&&(h=(h=k.attributes.uri)?`center / contain no-repeat url('${h}')`:b.getContents(k));k=1920;var l=1080,m=b.findChild(c,"Viewport");if(m){k=b.parseAttr(m,"x",b.parseInt);if(k==null){shaka.log.warning("Unsupported OverlayEvent",a);return}l=b.parseAttr(m,"y",b.parseInt);if(l==null){shaka.log.warning("Unsupported OverlayEvent",a);return}}var n={viewport:{x:k,y:l},topLeft:{x:0,y:0},size:{x:k,y:l}},q=b.findChild(c,"Overlay");
if(m&&q){var p=b.findChild(q,"TopLeft"),r=b.findChild(q,"Size");if(p&&r){q=b.parseAttr(p,"x",b.parseInt);if(q==null){shaka.log.warning("Unsupported OverlayEvent",a);return}p=b.parseAttr(p,"y",b.parseInt);if(p==null){shaka.log.warning("Unsupported OverlayEvent",a);return}const t=b.parseAttr(r,"x",b.parseInt);if(t==null){shaka.log.warning("Unsupported OverlayEvent",a);return}r=b.parseAttr(r,"y",b.parseInt);if(r==null){shaka.log.warning("Unsupported OverlayEvent",a);return}n.topLeft.x=q;n.topLeft.y=
p;n.size.x=t;n.size.y=r}}q=null;c=b.findChild(c,"Squeeze");if(m&&c&&(r=b.findChild(c,"TopLeft"),c=b.findChild(c,"Size"),r&&c)){m=b.parseAttr(r,"x",b.parseInt);if(m==null){shaka.log.warning("Unsupported OverlayEvent",a);return}q=b.parseAttr(r,"y",b.parseInt);if(q==null){shaka.log.warning("Unsupported OverlayEvent",a);return}r=b.parseAttr(c,"x",b.parseInt);if(r==null){shaka.log.warning("Unsupported OverlayEvent",a);return}b=b.parseAttr(c,"y",b.parseInt);if(b==null){shaka.log.warning("Unsupported OverlayEvent",
a);return}q={viewport:{x:k,y:l},topLeft:{x:m,y:q},size:{x:r,y:b}}}this.addInterstitials([{id:a.id,groupId:null,startTime:a.startTime,endTime:a.endTime,uri:d,mimeType:e,isSkippable:!1,skipOffset:null,skipFor:null,canJump:!0,resumeOffset:null,playoutLimit:null,once:!1,pre:!1,post:!1,timelineRange:!0,loop:f,overlay:n,displayOnBackground:g==-1,currentVideo:q,background:h,clickThroughUrl:null}])}else shaka.log.warning("Unsupported OverlayEvent",a)}async addAdUrlInterstitial(a){const b={type:shaka.net.NetworkingEngine.AdvancedRequestType.INTERSTITIAL_AD_URL};
a=await this.makeAdRequest_(a,b);a=shaka.util.TXml.parseXml(a,"VAST,vmap:VMAP");if(!a)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.ADS,shaka.util.Error.Code.VAST_INVALID_XML);let c=[];if(a.tagName=="VAST")c=shaka.ads.Utils.parseVastToInterstitials(a,this.lastTime_);else if(a.tagName=="vmap:VMAP"){const d=async f=>{var g=await this.makeAdRequest_(f.uri,b);g=shaka.util.TXml.parseXml(g,"VAST");if(!g)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.ADS,shaka.util.Error.Code.VAST_INVALID_XML);c.push(...shaka.ads.Utils.parseVastToInterstitials(g,f.time))},e=[];for(const f of shaka.ads.Utils.parseVMAP(a))e.push(d(f));e.length&&await Promise.all(e)}this.addInterstitials(c)}async addInterstitials(a){let b=!1;for(const c of a){if(!c.uri){shaka.log.alwaysWarn("Missing URL in interstitial",c);continue}if(!c.mimeType)try{const d=this.player_.getNetworkingEngine();goog.asserts.assert(d,"Need networking engine");c.mimeType=await shaka.net.NetworkingUtils.getMimeType(c.uri,
d,this.basePlayer_.getConfiguration().streaming.retryParameters)}catch(d){}a=c.id||JSON.stringify(c);if(this.interstitialIds_.has(a))continue;c.loop&&!c.overlay&&shaka.log.alwaysWarn("Loop is only supported in overlay interstitials",c);c.overlay||(b=!0);this.interstitialIds_.add(a);this.interstitials_.add(c);a=!1;if(c.pre&&this.lastTime_==null)a=!0;else if(c.startTime==0&&!c.canJump)a=!0;else if(this.lastTime_!=null){const d=c.startTime-this.lastTime_;d>0&&d<=10&&(a=!0)}a&&(!this.preloadManagerInterstitials_.has(c)&&
this.isPreloadAllowed_(c)&&this.preloadManagerInterstitials_.set(c,this.player_.preload(c.uri,null,c.mimeType||void 0)),this.checkPreloadOnDomElements_(c))}b&&this.cuepointsChanged_();this.addEventListeners_()}createMediaElement_(){const a=document.createElement(this.baseVideo_.tagName);a.autoplay=!0;a.style.position="absolute";a.style.top="0";a.style.left="0";a.style.width="100%";a.style.height="100%";a.style.display="none";a.setAttribute("playsinline","");return a}getCurrentInterstitial_(a=!1,b=
null){let c=0,d=null;if(this.interstitials_.size&&this.lastTime_!=null){const g=this.baseVideo_.ended;var e=Array.from(this.interstitials_).sort((h,k)=>k.startTime-h.startTime),f=e;f=a?e.filter(h=>h.pre):g?e.filter(h=>h.post):e.filter(h=>!h.pre&&!h.post);for(const h of f){e=!1;if(a)e=h.pre;else if(g)e=h.post;else if(!h.pre&&!h.post){f=this.lastTime_-Math.round(h.startTime*1E3)/1E3;let k=1;this.config_.allowStartInMiddleOfInterstitial&&h.endTime&&h.endTime!=Infinity&&(k=h.endTime-h.startTime);(f>0||
f==0&&this.lastTime_==0)&&(f<=k||!h.canJump)&&(e=b==null&&this.lastPlayedAd_&&!this.lastPlayedAd_.pre&&!this.lastPlayedAd_.post&&this.lastPlayedAd_.startTime>=h.startTime?!1:!0)}e&&(!this.lastPlayedAd_||h.startTime>=this.lastPlayedAd_.startTime)&&(c==(b||0)?d=h:d&&!h.canJump&&Math.round(h.startTime*1E3)/1E3-Math.round(d.startTime*1E3)/1E3>.001&&(d=h,c=0),c++)}}return d}setupAd_(a,b,c,d,e=0){shaka.log.info("Starting interstitial",a.startTime,"at",this.lastTime_);this.lastPlayedAd_=a;this.determineIfUsingBaseVideo_();
goog.asserts.assert(this.video_,"Must have video");this.usingBaseVideo_||!this.adContainer_||this.video_.parentElement||this.adContainer_.appendChild(this.video_);c==1&&b==1&&(b=Array.from(this.interstitials_).filter(f=>a.pre?f.pre==a.pre:a.post?f.post==a.post:Math.abs(f.startTime-a.startTime)<.001).length);a.once&&(e++,this.interstitials_.delete(a),this.removeEventListeners_(),a.overlay||this.cuepointsChanged_());a.mimeType&&(a.mimeType.startsWith("image/")||a.mimeType==="text/html")?a.overlay?(shaka.log.info("Starting interstitial",
a),this.setupStaticAd_(a,b,c,e)):shaka.log.alwaysWarn("Unsupported interstitial",a):this.usingBaseVideo_&&a.overlay?shaka.log.alwaysWarn("Unsupported interstitial",a):(shaka.log.info("Starting interstitial",a),this.setupVideoAd_(a,b,c,d,e))}setupStaticAd_(a,b,c,d){this.playingAd_=!0;var e=a.overlay;goog.asserts.assert(e,"Must have overlay");const f=a.mimeType=="text/html"?"iframe":"img",g=document.createElement(f);g.style.objectFit="contain";g.style.position="absolute";g.style.border="none";this.setBaseStyles_(a);
const h=()=>{this.playoutLimitTimer_&&(this.playoutLimitTimer_.stop(),this.playoutLimitTimer_=null);this.adContainer_.removeChild(g);this.removeBaseStyles_(a);this.sendEvent_(shaka.ads.Utils.AD_STOPPED);this.adEventManager_.removeAll();const n=this.getCurrentInterstitial_(a.pre,c-d);n?this.setupAd_(n,b,++c,Date.now(),d):this.playingAd_=!1};var k=new shaka.ads.InterstitialStaticAd(a,b,c);this.sendEvent_(shaka.ads.Utils.AD_IMPRESSION);this.sendEvent_(shaka.ads.Utils.AD_STARTED,(new Map).set("ad",k));
f=="iframe"?g.src=a.uri:(g.src=a.uri,g.onerror=n=>{this.sendEvent_(shaka.ads.Utils.AD_ERROR,(new Map).set("originalEvent",n));h()});k=e.viewport;const l=e.topLeft;e=e.size;k.x==0&&k.y==0?(g.width=a.overlay.size.x,g.height=a.overlay.size.y,g.style.bottom="10%",g.style.left="0",g.style.right="0",g.style.width="100%",a.overlay.size.y||f!="iframe"||(g.style.height="auto")):(g.style.height=e.y/k.y*100+"%",g.style.left=l.x/k.x*100+"%",g.style.top=l.y/k.y*100+"%",g.style.width=e.x/k.x*100+"%");this.adContainer_.appendChild(g);
const m=Date.now();this.playoutLimitTimer_&&this.playoutLimitTimer_.stop();this.playoutLimitTimer_=new shaka.util.Timer(()=>{a.playoutLimit&&(Date.now()-m)/1E3>a.playoutLimit?(this.sendEvent_(shaka.ads.Utils.AD_COMPLETE),h()):a.endTime&&this.baseVideo_.currentTime>a.endTime?(this.sendEvent_(shaka.ads.Utils.AD_COMPLETE),h()):this.baseVideo_.currentTime<a.startTime&&(this.sendEvent_(shaka.ads.Utils.AD_SKIPPED),h())});a.playoutLimit&&!a.endTime?this.playoutLimitTimer_.tickAfter(a.playoutLimit):a.endTime&&
this.playoutLimitTimer_.tickEvery(.025);this.adEventManager_.listen(this.baseVideo_,"seeked",()=>{const n=this.baseVideo_.currentTime;if(n<a.startTime||a.endTime&&n>a.endTime)this.playoutLimitTimer_&&this.playoutLimitTimer_.stop(),this.sendEvent_(shaka.ads.Utils.AD_SKIPPED),h()});a.clickThroughUrl&&this.adEventManager_.listen(g,"click",n=>{a.clickThroughUrl&&window.open(a.clickThroughUrl,"_blank")})}async setupVideoAd_(a,b,c,d,e){goog.asserts.assert(this.video_,"Must have video");var f=Date.now();
this.playingAd_=!0;let g=!1;const h=()=>{if(!this.usingBaseVideo_&&!a.overlay&&a.resumeOffset==null)if(a.timelineRange&&a.endTime&&a.endTime!=Infinity)this.baseVideo_.currentTime!=a.endTime&&(this.baseVideo_.currentTime=a.endTime);else{const r=Date.now();this.baseVideo_.currentTime+=(r-d)/1E3;d=r}},k=async r=>{h();let t=this.getCurrentInterstitial_(a.pre,c-e);if(r&&a.groupId)for(;t&&t.groupId==a.groupId;)c++,t=this.getCurrentInterstitial_(a.pre,c-e);this.playoutLimitTimer_&&(!a.groupId||t&&t.groupId!=
a.groupId)&&(this.playoutLimitTimer_.stop(),this.playoutLimitTimer_=null);this.removeBaseStyles_(a);if(!t||t.overlay)a.post&&(this.lastPlayedAd_=this.lastTime_=null),this.usingBaseVideo_?await this.player_.detach():await this.player_.unload(),this.usingBaseVideo_&&(r=a.resumeOffset,r==null&&(r=a.timelineRange&&a.endTime&&a.endTime!=Infinity?a.endTime-(this.lastTime_||0):(Date.now()-d)/1E3),this.sendEvent_(shaka.ads.Utils.AD_CONTENT_RESUME_REQUESTED,(new Map).set("offset",r))),this.sendEvent_(shaka.ads.Utils.AD_STOPPED),
this.adEventManager_.removeAll(),this.playingAd_=!1,this.usingBaseVideo_?this.cuepointsChanged_():(this.video_.style.display="none",h(),this.baseVideo_.ended||this.baseVideo_.play());this.determineIfUsingBaseVideo_();t&&(this.sendEvent_(shaka.ads.Utils.AD_STOPPED),this.adEventManager_.removeAll(),this.setupAd_(t,b,++c,d,e))},l=async r=>{g||(g=!0,this.sendEvent_(shaka.ads.Utils.AD_ERROR,(new Map).set("originalEvent",r)),await k(!1))},m=async()=>{g||(g=!0,await k(!1),this.sendEvent_(shaka.ads.Utils.AD_COMPLETE))};
this.lastOnSkip_=async()=>{g||(g=!0,this.sendEvent_(shaka.ads.Utils.AD_SKIPPED),await k(!0))};const n=new shaka.ads.InterstitialAd(this.video_,a,this.lastOnSkip_,b,c,!this.usingBaseVideo_);this.usingBaseVideo_||(n.setMuted(this.baseVideo_.muted),n.setVolume(this.baseVideo_.volume));this.sendEvent_(shaka.ads.Utils.AD_STARTED,(new Map).set("ad",n));let q=n.canSkipNow();q&&this.sendEvent_(shaka.ads.Utils.AD_SKIP_STATE_CHANGED);this.adEventManager_.listenOnce(this.player_,"error",l);this.adEventManager_.listen(this.video_,
"timeupdate",()=>{if(this.video_.duration){var r=n.canSkipNow();q!=r&&n.getRemainingTime()>0&&n.getDuration()>0&&this.sendEvent_(shaka.ads.Utils.AD_SKIP_STATE_CHANGED);q=r;!this.usingBaseVideo_&&!a.overlay&&a.resumeOffset==null&&a.timelineRange&&a.endTime&&a.endTime!=Infinity&&this.baseVideo_.currentTime!=a.endTime&&this.basePlayer_.seekRange().end>=a.endTime&&(this.baseVideo_.currentTime=a.endTime)}});this.adEventManager_.listenOnce(this.player_,"firstquartile",()=>{h();this.sendEvent_(shaka.ads.Utils.AD_FIRST_QUARTILE)});
this.adEventManager_.listenOnce(this.player_,"midpoint",()=>{h();this.sendEvent_(shaka.ads.Utils.AD_MIDPOINT)});this.adEventManager_.listenOnce(this.player_,"thirdquartile",()=>{h();this.sendEvent_(shaka.ads.Utils.AD_THIRD_QUARTILE)});this.adEventManager_.listenOnce(this.player_,"complete",m);this.adEventManager_.listen(this.video_,"play",()=>{this.sendEvent_(shaka.ads.Utils.AD_RESUMED)});this.adEventManager_.listen(this.video_,"pause",()=>{const r=this.player_.getConfiguration();this.video_.currentTime>=
r.playRangeEnd?m():this.sendEvent_(shaka.ads.Utils.AD_PAUSED)});this.adEventManager_.listen(this.video_,"volumechange",()=>{this.video_.muted?this.sendEvent_(shaka.ads.Utils.AD_MUTED):this.sendEvent_(shaka.ads.Utils.AD_VOLUME_CHANGED);this.usingBaseVideo_||(this.baseVideo_.volume=this.video_.volume,this.baseVideo_.muted=this.video_.muted)});a.clickThroughUrl&&this.adEventManager_.listen(this.adContainer_||this.video_,"click",r=>{a.clickThroughUrl&&(n.isPaused()||n.pause(),window.open(a.clickThroughUrl,
"_blank"))});if(this.usingBaseVideo_&&c==1){this.sendEvent_(shaka.ads.Utils.AD_CONTENT_PAUSE_REQUESTED,(new Map).set("saveLivePosition",!0));const r=new shaka.util.PublicPromise,t=async u=>{u.state=="detach"&&(this.isSmartTV_()&&await new Promise(v=>(new shaka.util.Timer(v)).tickAfter(.1)),r.resolve(),this.adEventManager_.unlisten(this.basePlayer_,"onstatechange",t))};this.adEventManager_.listen(this.basePlayer_,"onstatechange",t);await r}this.setBaseStyles_(a);if(!this.usingBaseVideo_)if(this.video_.style.display=
"",a.overlay){this.video_.loop=a.loop;var p=a.overlay.viewport;const r=a.overlay.topLeft,t=a.overlay.size;this.video_.style.height=t.y/p.y*100+"%";this.video_.style.left=r.x/p.x*100+"%";this.video_.style.top=r.y/p.y*100+"%";this.video_.style.width=t.x/p.x*100+"%"}else this.baseVideo_.pause(),a.resumeOffset!=null&&a.resumeOffset!=0&&(this.baseVideo_.currentTime+=a.resumeOffset),this.video_.loop=!1,this.video_.style.height="100%",this.video_.style.left="0",this.video_.style.top="0",this.video_.style.width=
"100%";try{this.updatePlayerConfig_();if(a.startTime&&a.endTime&&a.endTime!=Infinity&&a.startTime!=a.endTime){const t=a.endTime-a.startTime;t>0&&this.player_.configure("playRangeEnd",t)}a.playoutLimit&&!this.playoutLimitTimer_&&(this.playoutLimitTimer_=(new shaka.util.Timer(()=>{this.lastOnSkip_()})).tickAfter(a.playoutLimit),this.player_.configure("playRangeEnd",a.playoutLimit));await this.player_.attach(this.video_);p=null;if(!a.pre&&!a.post&&this.config_.allowStartInMiddleOfInterstitial&&this.lastTime_!=
null){const t=this.lastTime_-a.startTime;Math.abs(t)>.25&&(p=t)}if(this.preloadManagerInterstitials_.has(a)){const t=await this.preloadManagerInterstitials_.get(a);this.preloadManagerInterstitials_.delete(a);t?await this.player_.load(t):await this.player_.load(a.uri,p,a.mimeType||void 0)}else await this.player_.load(a.uri,p,a.mimeType||void 0);a.overlay&&this.baseVideo_.paused?this.video_.pause():this.video_.play();const r=(Date.now()-f)/1E3;this.sendEvent_(shaka.ads.Utils.ADS_LOADED,(new Map).set("loadTime",
r));this.usingBaseVideo_&&this.baseVideo_.play();a.overlay&&(a.pre||a.post||this.basePlayer_.isLive()&&!(a.startTime>0)||(f=()=>{const t=this.baseVideo_.currentTime-a.startTime;Math.abs(t-this.video_.currentTime)>.1&&(this.video_.currentTime=t)},this.adEventManager_.listenOnce(this.video_,"playing",f),this.adEventManager_.listen(this.baseVideo_,"seeking",f)),this.adEventManager_.listen(this.baseVideo_,"seeked",()=>{const t=this.baseVideo_.currentTime;(t<a.startTime||a.endTime&&t>a.endTime)&&this.lastOnSkip_()}))}catch(r){this.playingAd_&&
l(r)}}setBaseStyles_(a){a.displayOnBackground&&(this.baseVideo_.style.zIndex="1");if(a.currentVideo!=null){var b=a.currentVideo;this.baseVideo_.style.transformOrigin="top left";let d=!0;const e=[];var c=b.topLeft.x/b.viewport.x*100;c>0&&c<=100&&(e.push(`translateX(${c}%)`),d=!1);c=b.topLeft.y/b.viewport.y*100;c>0&&c<=100&&(e.push(`translateY(${c}%)`),d=!1);c=b.size.x/b.viewport.x;c<1&&e.push(`scaleX(${c})`);b=b.size.y/b.viewport.y;c<1&&e.push(`scaleY(${b})`);e.length&&(this.baseVideo_.style.transform=
e.join(" "));d&&(this.baseVideo_.style.transition="transform 250ms")}this.adContainer_&&(a.clickThroughUrl?(this.adContainer_.setAttribute("ad-active","true"),this.adContainer_.style.pointerEvents=""):this.adContainer_.style.pointerEvents="none",a.background&&(this.adContainer_.style.background=a.background));this.adVideo_&&(this.adVideo_.style.background=a.overlay?"":"rgb(0, 0, 0)")}removeBaseStyles_(a){if(!a||a.displayOnBackground)this.baseVideo_.style.zIndex="";a&&a.currentVideo==null||(this.baseVideo_.style.transformOrigin=
"",this.baseVideo_.style.transition="",this.baseVideo_.style.transform="");this.adContainer_&&(this.adContainer_.removeAttribute("ad-active"),this.adContainer_.style.pointerEvents="",!a||a.background)&&(this.adContainer_.style.background="");this.adVideo_&&(this.adVideo_.style.background="")}async getInterstitialsInfo_(a){const b=[];if(!a)return b;var c=a.values.find(A=>A.key=="X-ASSET-URI");const d=a.values.find(A=>A.key=="X-ASSET-LIST");if(!c&&!d)return b;let e=null;var f=a.values.find(A=>A.key==
"ID");f&&(e=f.data);f=e==null?Math.floor(a.startTime*10)/10:a.startTime;let g=a.endTime;a.endTime&&a.endTime!=Infinity&&typeof a.endTime=="number"&&(g=e==null?Math.floor(a.endTime*10)/10:a.endTime);var h=a.values.find(A=>A.key=="X-RESTRICT");let k=!0;var l=!0;h&&h.data&&(l=h.data,k=!l.includes("SKIP"),l=!l.includes("JUMP"));h=k?0:null;var m=a.values.find(A=>A.key=="X-ENABLE-SKIP-AFTER");m&&(h=parseFloat(m.data),isNaN(h)&&(h=k?0:null));m=null;var n=a.values.find(A=>A.key=="X-ENABLE-SKIP-FOR");n&&(m=
parseFloat(n.data),isNaN(h)&&(m=null));n=null;const q=a.values.find(A=>A.key=="X-RESUME-OFFSET");q&&(n=parseFloat(q.data),isNaN(n)&&(n=null));let p=null;var r=a.values.find(A=>A.key=="X-PLAYOUT-LIMIT");r&&(p=parseFloat(r.data),isNaN(p)&&(p=null));let t=r=!1;var u=!1,v=a.values.find(A=>A.key=="CUE");v&&(u=v.data,r=u.includes("ONCE"),t=u.includes("PRE"),u=u.includes("POST"));v=!1;(a=a.values.find(A=>A.key=="X-TIMELINE-OCCUPIES"))?v=a.data.includes("RANGE"):!q&&this.basePlayer_.isLive()&&(v=!t&&!u);
if(c){var x=c.data;if(!x)return b;b.push({id:e,groupId:null,startTime:f,endTime:g,uri:x,mimeType:null,isSkippable:k,skipOffset:h,skipFor:m,canJump:l,resumeOffset:n,playoutLimit:p,once:r,pre:t,post:u,timelineRange:v,loop:!1,overlay:null,displayOnBackground:!1,currentVideo:null,background:null,clickThroughUrl:null})}else if(d){c=d.data;if(!c)return b;try{var y=await this.makeAdRequest_(c,{type:shaka.net.NetworkingEngine.AdvancedRequestType.INTERSTITIAL_ASSET_LIST});const A=shaka.util.StringUtils.fromUTF8(y);
x=JSON.parse(A);const w=x["SKIP-CONTROL"];if(w){const z=w["ENABLE-SKIP-AFTER"];typeof z=="number"&&(h=parseFloat(z),isNaN(z)&&(h=k?0:null));const B=w["ENABLE-SKIP-FOR"];typeof B=="number"&&(m=parseFloat(B),isNaN(B)&&(m=null))}for(y=0;y<x.ASSETS.length;y++){const z=x.ASSETS[y];z.URI&&b.push({id:e+"_shaka_asset_"+y,groupId:e,startTime:f,endTime:g,uri:z.URI,mimeType:null,isSkippable:k,skipOffset:h,skipFor:m,canJump:l,resumeOffset:n,playoutLimit:p,once:r,pre:t,post:u,timelineRange:v,loop:!1,overlay:null,
displayOnBackground:!1,currentVideo:null,background:null,clickThroughUrl:null})}}catch(A){}}return b}getOverlaysInfo_(a){const b=[];if(!a)return b;var c=a.values.find(u=>u.key=="X-ASSET-URI");if(!c)return b;c=c.data;if(!c)return b;let d=null;var e=a.values.find(u=>u.key=="X-OVERLAY-ID");e&&(d=e.data);e=d==null?Math.floor(a.startTime*10)/10:a.startTime;let f=a.endTime;a.endTime&&a.endTime!=Infinity&&typeof a.endTime=="number"&&(f=d==null?Math.floor(a.endTime*10)/10:a.endTime);let g=!1,h=!1;var k=!1,
l=a.values.find(u=>u.key=="CUE");l&&(k=l.data,g=k.includes("ONCE"),h=k.includes("PRE"),k=k.includes("POST"));l=null;var m=a.values.find(u=>u.key=="X-ASSET-MIMETYPE");m&&(l=m.data);m=!1;var n=a.values.find(u=>u.key=="X-LOOP");n&&(m=n.data=="YES");n=1;var q=a.values.find(u=>u.key=="X-DEPTH");q&&(n=parseFloat(q.data),isNaN(n)&&(n=1));q=null;var p=a.values.find(u=>u.key=="X-BACKGROUND");p&&(q=p.data);p=1920;var r=1080,t=a.values.find(u=>u.key=="X-VIEWPORT");if(t){r=t.data.split("x");if(r.length!=2)return b;
p=parseFloat(r[0]);r=parseFloat(r[1])}p={viewport:{x:p,y:r},topLeft:{x:0,y:0},size:{x:p,y:r}};if(r=a.values.find(u=>u.key=="X-OVERLAY-POSITION")){r=r.data.split("x");if(r.length!=2)return b;p.topLeft.x=parseFloat(r[0]);p.topLeft.y=parseFloat(r[1])}if(r=a.values.find(u=>u.key=="X-OVERLAY-SIZE")){r=r.data.split("x");if(r.length!=2)return b;p.size.x=parseFloat(r[0]);p.size.y=parseFloat(r[1])}r=null;if(t=a.values.find(u=>u.key=="X-SQUEEZECURRENT"))if(r=parseFloat(t.data),isNaN(r)&&(r=1),r={viewport:{x:1920,
y:1080},topLeft:{x:0,y:0},size:{x:1920*r,y:1080*r}},a=a.values.find(u=>u.key=="X-SQUEEZECURRENT-POSITION")){a=a.data.split("x");if(a.length!=2)return b;r.topLeft.x=parseFloat(a[0]);r.topLeft.y=parseFloat(a[1])}b.push({id:d,groupId:null,startTime:e,endTime:f,uri:c,mimeType:l,isSkippable:!1,skipOffset:null,skipFor:null,canJump:!0,resumeOffset:null,playoutLimit:null,once:g,pre:h,post:k,timelineRange:!0,loop:m,overlay:p,displayOnBackground:n==-1,currentVideo:r,background:q,clickThroughUrl:null});return b}cuepointsChanged_(){const a=
[];for(const b of this.interstitials_){if(b.overlay)continue;const c={start:b.startTime,end:null};b.pre?(c.start=0,c.end=null):b.post?(c.start=-1,c.end=null):b.timelineRange&&(c.end=b.endTime);a.find(d=>c.start==d.start&&c.end==d.end)||a.push(c)}this.sendEvent_(shaka.ads.Utils.CUEPOINTS_CHANGED,(new Map).set("cuepoints",a))}updatePlayerConfig_(){goog.asserts.assert(this.player_,"Must have player");goog.asserts.assert(this.basePlayer_,"Must have base player");this.player_.configure(this.basePlayer_.getNonDefaultConfiguration());
this.player_.configure("ads.disableHLSInterstitial",!0);this.player_.configure("ads.disableDASHInterstitial",!0);this.player_.configure("playRangeEnd",Infinity);const a=this.player_.getNetworkingEngine();goog.asserts.assert(a,"Need networking engine");this.basePlayer_.getNetworkingEngine().copyFiltersInto(a)}async makeAdRequest_(a,b){const c=shaka.net.NetworkingEngine.RequestType.ADS;a=shaka.net.NetworkingEngine.makeRequest([a],shaka.net.NetworkingEngine.defaultRetryParameters());return(await this.basePlayer_.getNetworkingEngine().request(c,
a,b).promise).data}isPreloadAllowed_(a){return(a=a.mimeType)?!a.startsWith("image/")&&a!=="text/html":!0}getInterstitials(){return Array.from(this.interstitials_)}isSmartTV_(){const a=shaka.device.DeviceFactory.getDevice().getDeviceType();return a==shaka.device.IDevice.DeviceType.TV||a==shaka.device.IDevice.DeviceType.CONSOLE||a==shaka.device.IDevice.DeviceType.CAST?!0:!1}checkPreloadOnDomElements_(a){if(!(this.preloadOnDomElements_.has(a)||this.config_&&!this.config_.allowPreloadOnDomElements)){var b=
d=>{const e=document.createElement("link");e.rel="preload";e.href=d;e.as="image";document.head.appendChild(e);return e},c=[];if(a.background){const d=a.background.match(/url\(('|")?([^'"()]+)('|")\)?/);d&&c.push(b(d[2]))}a.mimeType&&a.mimeType.startsWith("image/")&&c.push(b(a.uri));this.preloadOnDomElements_.set(a,c)}}removePreloadOnDomElements_(a){if(this.preloadOnDomElements_.has(a)){var b=this.preloadOnDomElements_.get(a);for(const c of b)c.parentNode.removeChild(c);this.preloadOnDomElements_.delete(a)}}sendEvent_(a,
b){shaka.log.info("Interstitial event",a);this.onEvent_(new shaka.util.FakeEvent(a,b))}};shaka.ads.MediaTailorAd=class{constructor(a,b,c,d,e){this.ad_=a;this.skipOffset_=shaka.util.TextParser.parseTime(this.ad_.skipOffset);this.video_=e;this.adPosition_=b;this.totalAds_=c;this.isLinear_=d;this.isSkipped_=!1}needsSkipUI(){return!0}isClientRendering(){return!1}hasCustomClick(){return!1}isUsingAnotherMediaElement(){return!1}getDuration(){return this.ad_.durationInSeconds}getMinSuggestedDuration(){return this.getDuration()}getRemainingTime(){return this.ad_.startTimeInSeconds+this.ad_.durationInSeconds-
this.video_.currentTime}isPaused(){return this.video_.paused}isSkippable(){return typeof this.skipOffset_=="number"?!0:!1}getTimeUntilSkippable(){if(typeof this.skipOffset_!="number")return this.getRemainingTime();const a=this.getRemainingTime()+this.skipOffset_-this.getDuration();return Math.max(a,0)}canSkipNow(){return this.getTimeUntilSkippable()==0}skip(){this.isSkipped_=!0;this.video_.currentTime+=this.getRemainingTime()}pause(){return this.video_.pause()}play(){return this.video_.play()}getVolume(){return this.video_.volume}setVolume(a){this.video_.volume=
a}isMuted(){return this.video_.muted}isLinear(){return this.isLinear_}resize(a,b){}setMuted(a){this.video_.muted=a}getSequenceLength(){return this.totalAds_?this.totalAds_:1}getPositionInSequence(){return this.adPosition_?this.adPosition_:1}getTitle(){return this.ad_.adTitle}getDescription(){return""}getVastMediaBitrate(){return 0}getVastMediaHeight(){return 0}getVastMediaWidth(){return 0}getVastAdId(){return this.ad_.vastAdId||""}getAdId(){return this.ad_.adId}getCreativeAdId(){return this.ad_.creativeId}getAdvertiserName(){return""}getMediaUrl(){return null}getTimeOffset(){return 0}getPodIndex(){return 0}release(){this.totalAds_=
this.adPosition_=this.video_=this.ad_=null}isSkipped(){return this.isSkipped_}};goog.exportSymbol("shaka.ads.MediaTailorAd",shaka.ads.MediaTailorAd);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"release",shaka.ads.MediaTailorAd.prototype.release);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getPodIndex",shaka.ads.MediaTailorAd.prototype.getPodIndex);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getTimeOffset",shaka.ads.MediaTailorAd.prototype.getTimeOffset);
goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getMediaUrl",shaka.ads.MediaTailorAd.prototype.getMediaUrl);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getAdvertiserName",shaka.ads.MediaTailorAd.prototype.getAdvertiserName);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getCreativeAdId",shaka.ads.MediaTailorAd.prototype.getCreativeAdId);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getAdId",shaka.ads.MediaTailorAd.prototype.getAdId);
goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getVastAdId",shaka.ads.MediaTailorAd.prototype.getVastAdId);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getVastMediaWidth",shaka.ads.MediaTailorAd.prototype.getVastMediaWidth);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getVastMediaHeight",shaka.ads.MediaTailorAd.prototype.getVastMediaHeight);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getVastMediaBitrate",shaka.ads.MediaTailorAd.prototype.getVastMediaBitrate);
goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getDescription",shaka.ads.MediaTailorAd.prototype.getDescription);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getTitle",shaka.ads.MediaTailorAd.prototype.getTitle);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getPositionInSequence",shaka.ads.MediaTailorAd.prototype.getPositionInSequence);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getSequenceLength",shaka.ads.MediaTailorAd.prototype.getSequenceLength);
goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"setMuted",shaka.ads.MediaTailorAd.prototype.setMuted);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"resize",shaka.ads.MediaTailorAd.prototype.resize);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"isLinear",shaka.ads.MediaTailorAd.prototype.isLinear);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"isMuted",shaka.ads.MediaTailorAd.prototype.isMuted);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"setVolume",shaka.ads.MediaTailorAd.prototype.setVolume);
goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getVolume",shaka.ads.MediaTailorAd.prototype.getVolume);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"play",shaka.ads.MediaTailorAd.prototype.play);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"pause",shaka.ads.MediaTailorAd.prototype.pause);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"skip",shaka.ads.MediaTailorAd.prototype.skip);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"canSkipNow",shaka.ads.MediaTailorAd.prototype.canSkipNow);
goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getTimeUntilSkippable",shaka.ads.MediaTailorAd.prototype.getTimeUntilSkippable);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"isSkippable",shaka.ads.MediaTailorAd.prototype.isSkippable);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"isPaused",shaka.ads.MediaTailorAd.prototype.isPaused);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getRemainingTime",shaka.ads.MediaTailorAd.prototype.getRemainingTime);
goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getMinSuggestedDuration",shaka.ads.MediaTailorAd.prototype.getMinSuggestedDuration);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"getDuration",shaka.ads.MediaTailorAd.prototype.getDuration);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"isUsingAnotherMediaElement",shaka.ads.MediaTailorAd.prototype.isUsingAnotherMediaElement);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"hasCustomClick",shaka.ads.MediaTailorAd.prototype.hasCustomClick);
goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"isClientRendering",shaka.ads.MediaTailorAd.prototype.isClientRendering);goog.exportProperty(shaka.ads.MediaTailorAd.prototype,"needsSkipUI",shaka.ads.MediaTailorAd.prototype.needsSkipUI);shaka.ads.MediaTailorAdManager=class{constructor(a,b,c,d){this.adContainer_=a;this.networkingEngine_=b;this.video_=c;this.streamPromise_=null;this.streamRequestStartTime_=NaN;this.onEvent_=d;this.isLive_=!1;this.snapForwardTime_=null;this.adBreaks_=[];this.playedAds_=[];this.mediaTailorAdBreak_=this.mediaTailorAd_=this.ad_=null;this.staticResources_=new Map;this.adListeners_=[];this.eventsSent=[];this.trackingUrl_="";this.firstTrackingRequest_=!0;this.backupUrl_="";this.currentCuePoints_=[];this.eventManager_=
new shaka.util.EventManager}streamRequest(a,b,c){if(this.streamPromise_)return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.ADS,shaka.util.Error.Code.CURRENT_DAI_REQUEST_NOT_FINISHED));this.streamPromise_=new shaka.util.PublicPromise;this.requestSessionInfo_(a,b);this.backupUrl_=c||"";this.streamRequestStartTime_=Date.now()/1E3;return this.streamPromise_}addTrackingUrl(a){this.trackingUrl_=a;this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.ADS_LOADED,
(new Map).set("loadTime",0)))}stop(){for(const a of this.adListeners_)this.eventManager_.unlisten(a.target,a.type,a.listener);this.onEnded_();this.adListeners_=[];this.eventsSent=[];this.trackingUrl_="";this.firstTrackingRequest_=!0;this.backupUrl_="";this.snapForwardTime_=null;this.adBreaks_=[];this.playedAds_=[];this.staticResources_.clear()}release(){this.stop();this.eventManager_&&this.eventManager_.release()}onManifestUpdated(a){this.isLive_=a;this.trackingUrl_!=""&&(this.requestTrackingInfo_(this.trackingUrl_,
this.firstTrackingRequest_),this.firstTrackingRequest_=!1)}getCuePoints(){const a=[];for(const b of this.adBreaks_)for(const c of b.ads)a.push({start:c.startTimeInSeconds,end:c.startTimeInSeconds+c.durationInSeconds});return a}async requestSessionInfo_(a,b){var c=shaka.net.NetworkingEngine,d=c.RequestType.ADS;const e={type:c.AdvancedRequestType.MEDIATAILOR_SESSION_INFO};c=c.makeRequest([a],c.defaultRetryParameters());c.method="POST";b&&(b=JSON.stringify(b),c.body=shaka.util.StringUtils.toUTF8(b));
d=this.networkingEngine_.request(d,c,e);try{const f=await d.promise,g=shaka.util.StringUtils.fromUTF8(f.data),h=JSON.parse(g);if(h.manifestUrl&&h.trackingUrl){const k=new goog.Uri(a),l=new goog.Uri(h.trackingUrl);this.trackingUrl_=k.resolve(l).toString();const m=Date.now()/1E3-this.streamRequestStartTime_;this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.ADS_LOADED,(new Map).set("loadTime",m)));const n=new goog.Uri(h.manifestUrl);this.streamPromise_.resolve(k.resolve(n).toString());this.streamPromise_=
null}else throw Error("Insufficient data from MediaTailor.");}catch(f){this.backupUrl_.length?(shaka.log.warning("MediaTailor request returned an error. Falling back to the backup asset uri."),this.streamPromise_.resolve(this.backupUrl_)):this.streamPromise_.reject("MediaTailor request returned an error and there was no backup asset uri provided."),this.streamPromise_=null}}async requestTrackingInfo_(a,b){const c=shaka.net.NetworkingEngine;var d=c.RequestType.ADS;const e={type:c.AdvancedRequestType.MEDIATAILOR_TRACKING_INFO};
a=c.makeRequest([a],c.defaultRetryParameters());d=this.networkingEngine_.request(d,a,e);try{const f=await d.promise;d=[];const g=shaka.util.StringUtils.fromUTF8(f.data),h=JSON.parse(g);if(h.avails.length>0){if(JSON.stringify(this.adBreaks_)!=JSON.stringify(h.avails)){this.adBreaks_=h.avails;for(const k of this.adBreaks_)for(const l of k.nonLinearAdsList)for(const m of l.nonLinearAdList)this.requestStaticResource_(m);d=this.getCuePoints();this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.CUEPOINTS_CHANGED,
(new Map).set("cuepoints",d)))}}else{if(this.adBreaks_.length)this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.CUEPOINTS_CHANGED,(new Map).set("cuepoints",d)));this.onEnded_();this.adBreaks_=[]}b&&(this.isLive_||d.length>0)&&this.setupAdBreakListeners_()}catch(f){}}async requestStaticResource_(a){if(a.staticResource){var b=this.getCacheKeyForNonLinear_(a);if(!this.staticResources_.get(b)){var c=shaka.net.NetworkingEngine,d=c.RequestType.ADS,e={type:c.AdvancedRequestType.MEDIATAILOR_STATIC_RESOURCE};
a=c.makeRequest([a.staticResource],c.defaultRetryParameters());d=this.networkingEngine_.request(d,a,e);try{this.staticResources_.set(b,[]);const f=await d.promise,g=shaka.util.StringUtils.fromUTF8(f.data),h=JSON.parse(g).apps;this.staticResources_.set(b,h)}catch(f){this.staticResources_.delete(b)}}}}getCacheKeyForNonLinear_(a){return[a.adId,a.adParameters,a.adSystem,a.adTitle,a.creativeAdId,a.creativeId,a.creativeSequence,a.height,a.width,a.staticResource].join("")}setupAdBreakListeners_(){this.onTimeupdate_();
this.isLive_||(this.checkForSnapback_(),this.eventManager_.listen(this.video_,"seeked",()=>{this.checkForSnapback_()}),this.eventManager_.listen(this.video_,"ended",()=>{this.onEnded_()}));this.eventManager_.listen(this.video_,"timeupdate",()=>{this.onTimeupdate_()})}checkForSnapback_(){const a=this.video_.currentTime;if(a!=0&&this.snapForwardTime_==null){for(const d of this.adBreaks_)for(const e of d.ads)if(!b){if(e.startTimeInSeconds<a){var b=e;var c=d}}else if(e.startTimeInSeconds<a&&e.startTimeInSeconds>
b.startTimeInSeconds+b.durationInSeconds){b=e;c=d;break}c&&b&&!this.playedAds_.includes(b.adId)&&(shaka.log.info("Seeking back to the start of the ad break at "+c.startTimeInSeconds+" and will return to "+a),this.snapForwardTime_=a,this.video_.currentTime=c.startTimeInSeconds)}}onAdBreakEnded_(){const a=this.video_.currentTime;this.snapForwardTime_&&this.snapForwardTime_>a&&(this.video_.currentTime=this.snapForwardTime_);this.snapForwardTime_=null}onTimeupdate_(){if(this.video_.duration&&(this.ad_||
this.adBreaks_.length)){var a=this.video_.currentTime,b=!1;if(this.ad_){b=!0;goog.asserts.assert(this.mediaTailorAd_,"Ad should be defined");this.sendInProgressEvents_(a,this.mediaTailorAd_);const c=this.ad_.getRemainingTime(),d=this.ad_.getDuration();this.ad_.canSkipNow()&&c>0&&d>0&&this.sendTrackingEvent_(shaka.ads.MediaTailorAdManager.SKIP_STATE_CHANGED_);if(d>0&&(c<=0||c>d))this.onEnded_()}if(!this.ad_||!this.ad_.isLinear())if(this.checkLinearAds_(a),this.ad_||this.checkNonLinearAds_(a),b&&!this.ad_)this.onAdBreakEnded_()}}sendInProgressEvents_(a,
b){const c=shaka.ads.MediaTailorAdManager,d=b.startTimeInSeconds+.5*b.durationInSeconds,e=b.startTimeInSeconds+.75*b.durationInSeconds;a>=b.startTimeInSeconds+.25*b.durationInSeconds&&!this.eventsSent.includes(c.FIRSTQUARTILE_)?(this.eventsSent.push(c.FIRSTQUARTILE_),this.sendTrackingEvent_(c.FIRSTQUARTILE_)):a>=d&&!this.eventsSent.includes(c.MIDPOINT_)?(this.eventsSent.push(c.MIDPOINT_),this.sendTrackingEvent_(c.MIDPOINT_)):a>=e&&!this.eventsSent.includes(c.THIRDQUARTILE_)&&(this.eventsSent.push(c.THIRDQUARTILE_),
this.sendTrackingEvent_(c.THIRDQUARTILE_))}checkLinearAds_(a){const b=shaka.ads.MediaTailorAdManager;for(const c of this.adBreaks_){if(this.ad_&&this.ad_.isLinear())break;for(let d=0;d<c.ads.length;d++){const e=c.ads[d],f=e.startTimeInSeconds+e.durationInSeconds;if(e.startTimeInSeconds<=a&&f>a){if(this.playedAds_.includes(e.adId)){if(this.video_.ended)continue;this.video_.currentTime=f;return}this.onEnded_();this.mediaTailorAdBreak_=c;this.ad_=new shaka.ads.MediaTailorAd(e,d+1,c.ads.length,!0,this.video_);
this.mediaTailorAd_=e;d===0&&this.sendTrackingEvent_(b.BREAK_START_);this.setupCurrentAdListeners_();break}}}}checkNonLinearAds_(a){const b=shaka.ads.MediaTailorAdManager;for(const d of this.adBreaks_){if(this.ad_)break;for(let e=0;e<d.nonLinearAdsList.length;e++){const f=d.nonLinearAdsList[e];if(!f.nonLinearAdList.length)continue;const g=d.startTimeInSeconds;var c=this.getCacheKeyForNonLinear_(f.nonLinearAdList[0]);c=this.staticResources_.get(c);if(g<=a&&c&&c.length){this.onEnded_();this.displayNonLinearAd_(c);
this.mediaTailorAdBreak_=d;this.ad_=new shaka.ads.MediaTailorAd(f,e+1,d.ads.length,!1,this.video_);this.mediaTailorAd_=f;e===0&&this.sendTrackingEvent_(b.BREAK_START_);this.setupCurrentAdListeners_();break}}}}displayNonLinearAd_(a){for(const b of a){if(!b.data.source.length)continue;a=document.createElement("img");a.src=b.data.source[0].url;a.style.top=(b.placeholder.top||0)+"%";a.style.height=100-(b.placeholder.top||0)+"%";a.style.left=(b.placeholder.left||0)+"%";a.style.maxWidth=100-(b.placeholder.left||
0)+"%";a.style.objectFit="contain";a.style.position="absolute";this.adContainer_.appendChild(a)}}onEnded_(){if(this.ad_){for(;this.adContainer_.lastChild;)this.adContainer_.removeChild(this.adContainer_.firstChild);this.isLive_||this.playedAds_.push(this.mediaTailorAd_.adId);this.removeCurrentAdListeners_(this.ad_.isSkipped());const a=this.ad_.getPositionInSequence(),b=this.ad_.getSequenceLength();a===b&&this.sendTrackingEvent_(shaka.ads.MediaTailorAdManager.BREAK_END_);this.mediaTailorAdBreak_=this.mediaTailorAd_=
this.ad_=null}}setupCurrentAdListeners_(){const a=shaka.ads.MediaTailorAdManager;let b=!1;this.video_.paused?b=!0:(this.sendTrackingEvent_(a.IMPRESSION_),this.sendTrackingEvent_(a.START_));this.adListeners_.push({target:this.video_,type:"volumechange",listener:()=>{this.video_.muted&&this.sendTrackingEvent_(a.MUTE_)}});this.adListeners_.push({target:this.video_,type:"volumechange",listener:()=>{this.video_.muted||this.sendTrackingEvent_(a.UNMUTE_)}});this.adListeners_.push({target:this.video_,type:"play",
listener:()=>{b?(this.sendTrackingEvent_(a.IMPRESSION_),this.sendTrackingEvent_(a.START_),b=!1):this.sendTrackingEvent_(a.RESUME_)}});this.adListeners_.push({target:this.video_,type:"pause",listener:()=>{this.sendTrackingEvent_(a.PAUSE_)}});for(const c of this.adListeners_)this.eventManager_.listen(c.target,c.type,c.listener)}removeCurrentAdListeners_(a=!1){a?this.sendTrackingEvent_(shaka.ads.MediaTailorAdManager.SKIPPED_):this.sendTrackingEvent_(shaka.ads.MediaTailorAdManager.COMPLETE_);for(const b of this.adListeners_)this.eventManager_.unlisten(b.target,
b.type,b.listener);this.adListeners_=[];this.eventsSent=[]}sendTrackingEvent_(a){var b=this.mediaTailorAd_.trackingEvents.find(c=>c.eventType==a);b||=this.mediaTailorAdBreak_.adBreakTrackingEvents.find(c=>c.eventType==a);if(b){const c=shaka.net.NetworkingEngine,d=c.RequestType.ADS,e={type:c.AdvancedRequestType.MEDIATAILOR_TRACKING_EVENT};for(const f of b.beaconUrls){if(!f||f=="")continue;b=c.makeRequest([f],c.defaultRetryParameters());b.method="POST";this.networkingEngine_.request(d,b,e)}}switch(a){case shaka.ads.MediaTailorAdManager.IMPRESSION_:this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_IMPRESSION));
break;case shaka.ads.MediaTailorAdManager.START_:this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_STARTED,(new Map).set("ad",this.ad_)));break;case shaka.ads.MediaTailorAdManager.MUTE_:this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_MUTED));break;case shaka.ads.MediaTailorAdManager.UNMUTE_:this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_VOLUME_CHANGED));break;case shaka.ads.MediaTailorAdManager.RESUME_:this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_RESUMED));
break;case shaka.ads.MediaTailorAdManager.PAUSE_:this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_PAUSED));break;case shaka.ads.MediaTailorAdManager.FIRSTQUARTILE_:this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_FIRST_QUARTILE));break;case shaka.ads.MediaTailorAdManager.MIDPOINT_:this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_MIDPOINT));break;case shaka.ads.MediaTailorAdManager.THIRDQUARTILE_:this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_THIRD_QUARTILE));
break;case shaka.ads.MediaTailorAdManager.COMPLETE_:this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_COMPLETE));this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_STOPPED));break;case shaka.ads.MediaTailorAdManager.SKIPPED_:this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_SKIPPED));this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_STOPPED));break;case shaka.ads.MediaTailorAdManager.BREAK_START_:this.adContainer_.setAttribute("ad-active","true");break;case shaka.ads.MediaTailorAdManager.BREAK_END_:this.adContainer_.removeAttribute("ad-active");
break;case shaka.ads.MediaTailorAdManager.SKIP_STATE_CHANGED_:this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_SKIP_STATE_CHANGED))}}};shaka.ads.MediaTailorAdManager.IMPRESSION_="impression";shaka.ads.MediaTailorAdManager.START_="start";shaka.ads.MediaTailorAdManager.MUTE_="mute";shaka.ads.MediaTailorAdManager.UNMUTE_="unmute";shaka.ads.MediaTailorAdManager.RESUME_="resume";shaka.ads.MediaTailorAdManager.PAUSE_="pause";shaka.ads.MediaTailorAdManager.FIRSTQUARTILE_="firstQuartile";
shaka.ads.MediaTailorAdManager.MIDPOINT_="midpoint";shaka.ads.MediaTailorAdManager.THIRDQUARTILE_="thirdQuartile";shaka.ads.MediaTailorAdManager.COMPLETE_="complete";shaka.ads.MediaTailorAdManager.SKIPPED_="skip";shaka.ads.MediaTailorAdManager.BREAK_START_="breakStart";shaka.ads.MediaTailorAdManager.BREAK_END_="breakEnd";shaka.ads.MediaTailorAdManager.SKIP_STATE_CHANGED_="skipStateChanged";shaka.ads.ServerSideAd=class{constructor(a,b){this.ad_=a;this.adProgressData_=null;this.video_=b}setProgressData(a){this.adProgressData_=a}needsSkipUI(){return!0}isClientRendering(){return!1}hasCustomClick(){return!0}isUsingAnotherMediaElement(){return!1}getDuration(){return this.adProgressData_?this.adProgressData_.duration:-1}getMinSuggestedDuration(){return this.getDuration()}getRemainingTime(){return this.adProgressData_?this.adProgressData_.duration-this.adProgressData_.currentTime:-1}isPaused(){return this.video_.paused}isSkippable(){return this.ad_.isSkippable()}getTimeUntilSkippable(){var a=
this.ad_.getSkipTimeOffset();a=this.getRemainingTime()-a;return Math.max(a,0)}canSkipNow(){return this.getTimeUntilSkippable()==0}skip(){this.video_.currentTime+=this.getRemainingTime()}pause(){return this.video_.pause()}play(){return this.video_.play()}getVolume(){return this.video_.volume}setVolume(a){this.video_.volume=a}isMuted(){return this.video_.muted}isLinear(){return!0}resize(a,b){}setMuted(a){this.video_.muted=a}getSequenceLength(){const a=this.ad_.getAdPodInfo();return a==null?1:a.getTotalAds()}getPositionInSequence(){const a=
this.ad_.getAdPodInfo();return a==null?1:a.getAdPosition()}getTitle(){return this.ad_.getTitle()}getDescription(){return this.ad_.getDescription()}getVastMediaBitrate(){return 0}getVastMediaHeight(){return this.ad_.getVastMediaHeight()}getVastMediaWidth(){return this.ad_.getVastMediaWidth()}getVastAdId(){return""}getAdId(){return this.ad_.getAdId()}getCreativeAdId(){return this.ad_.getCreativeAdId()}getAdvertiserName(){return this.ad_.getAdvertiserName()}getMediaUrl(){return null}getTimeOffset(){const a=
this.ad_.getAdPodInfo();return a==null?0:a.getTimeOffset()}getPodIndex(){const a=this.ad_.getAdPodInfo();return a==null?0:a.getPodIndex()}release(){this.video_=this.adProgressData_=this.ad_=null}};goog.exportSymbol("shaka.ads.ServerSideAd",shaka.ads.ServerSideAd);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"release",shaka.ads.ServerSideAd.prototype.release);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getPodIndex",shaka.ads.ServerSideAd.prototype.getPodIndex);
goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getTimeOffset",shaka.ads.ServerSideAd.prototype.getTimeOffset);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getMediaUrl",shaka.ads.ServerSideAd.prototype.getMediaUrl);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getAdvertiserName",shaka.ads.ServerSideAd.prototype.getAdvertiserName);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getCreativeAdId",shaka.ads.ServerSideAd.prototype.getCreativeAdId);
goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getAdId",shaka.ads.ServerSideAd.prototype.getAdId);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getVastAdId",shaka.ads.ServerSideAd.prototype.getVastAdId);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getVastMediaWidth",shaka.ads.ServerSideAd.prototype.getVastMediaWidth);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getVastMediaHeight",shaka.ads.ServerSideAd.prototype.getVastMediaHeight);
goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getVastMediaBitrate",shaka.ads.ServerSideAd.prototype.getVastMediaBitrate);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getDescription",shaka.ads.ServerSideAd.prototype.getDescription);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getTitle",shaka.ads.ServerSideAd.prototype.getTitle);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getPositionInSequence",shaka.ads.ServerSideAd.prototype.getPositionInSequence);
goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getSequenceLength",shaka.ads.ServerSideAd.prototype.getSequenceLength);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"setMuted",shaka.ads.ServerSideAd.prototype.setMuted);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"resize",shaka.ads.ServerSideAd.prototype.resize);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"isLinear",shaka.ads.ServerSideAd.prototype.isLinear);
goog.exportProperty(shaka.ads.ServerSideAd.prototype,"isMuted",shaka.ads.ServerSideAd.prototype.isMuted);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"setVolume",shaka.ads.ServerSideAd.prototype.setVolume);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getVolume",shaka.ads.ServerSideAd.prototype.getVolume);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"play",shaka.ads.ServerSideAd.prototype.play);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"pause",shaka.ads.ServerSideAd.prototype.pause);
goog.exportProperty(shaka.ads.ServerSideAd.prototype,"skip",shaka.ads.ServerSideAd.prototype.skip);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"canSkipNow",shaka.ads.ServerSideAd.prototype.canSkipNow);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getTimeUntilSkippable",shaka.ads.ServerSideAd.prototype.getTimeUntilSkippable);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"isSkippable",shaka.ads.ServerSideAd.prototype.isSkippable);
goog.exportProperty(shaka.ads.ServerSideAd.prototype,"isPaused",shaka.ads.ServerSideAd.prototype.isPaused);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getRemainingTime",shaka.ads.ServerSideAd.prototype.getRemainingTime);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getMinSuggestedDuration",shaka.ads.ServerSideAd.prototype.getMinSuggestedDuration);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getDuration",shaka.ads.ServerSideAd.prototype.getDuration);
goog.exportProperty(shaka.ads.ServerSideAd.prototype,"isUsingAnotherMediaElement",shaka.ads.ServerSideAd.prototype.isUsingAnotherMediaElement);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"hasCustomClick",shaka.ads.ServerSideAd.prototype.hasCustomClick);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"isClientRendering",shaka.ads.ServerSideAd.prototype.isClientRendering);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"needsSkipUI",shaka.ads.ServerSideAd.prototype.needsSkipUI);shaka.ads.ServerSideAdManager=class{constructor(a,b,c,d){this.adContainer_=a;this.video_=b;this.streamPromise_=this.config_=null;this.streamRequestStartTime_=NaN;this.onEvent_=d;this.isLiveContent_=!1;this.adProgressData_=this.ad_=this.snapForwardTime_=null;this.backupUrl_="";this.currentCuePoints_=[];this.eventManager_=new shaka.util.EventManager;a=new google.ima.dai.api.UiSettings;a.setLocale(c);this.streamManager_=new google.ima.dai.api.StreamManager(this.video_,this.adContainer_,a);this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.IMA_STREAM_MANAGER_LOADED,
(new Map).set("imaStreamManager",this.streamManager_)));this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.LOADED,e=>{shaka.log.info("Ad SS Loaded");this.onLoaded_(e)});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.ERROR,()=>{shaka.log.info("Ad SS Error");this.onError_()});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.AD_BREAK_STARTED,()=>{shaka.log.info("Ad Break Started")});this.eventManager_.listen(this.streamManager_,
google.ima.dai.api.StreamEvent.Type.STARTED,e=>{shaka.log.info("Ad Started");this.onAdStart_(e)});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.AD_BREAK_ENDED,()=>{shaka.log.info("Ad Break Ended");this.onAdBreakEnded_()});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.AD_PROGRESS,e=>{this.onAdProgress_(e)});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.FIRST_QUARTILE,()=>{shaka.log.info("Ad event: First Quartile");
this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_FIRST_QUARTILE))});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.MIDPOINT,()=>{shaka.log.info("Ad event: Midpoint");this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_MIDPOINT))});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.THIRD_QUARTILE,()=>{shaka.log.info("Ad event: Third Quartile");this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_THIRD_QUARTILE))});
this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.COMPLETE,()=>{shaka.log.info("Ad event: Complete");this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_COMPLETE));this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_STOPPED));this.adContainer_.removeAttribute("ad-active");this.ad_=null});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.SKIPPED,()=>{shaka.log.info("Ad event: Skipped");this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_SKIPPED));
this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_STOPPED))});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.CUEPOINTS_CHANGED,e=>{shaka.log.info("Ad event: Cue points changed");this.onCuePointsChanged_(e)})}configure(a){this.config_=a}streamRequest(a,b){if(this.streamPromise_)return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.ADS,shaka.util.Error.Code.CURRENT_DAI_REQUEST_NOT_FINISHED));a instanceof
google.ima.dai.api.LiveStreamRequest&&(this.isLiveContent_=!0);this.streamPromise_=new shaka.util.PublicPromise;this.streamManager_.requestStream(a);this.backupUrl_=b||"";this.streamRequestStartTime_=Date.now()/1E3;return this.streamPromise_}replaceAdTagParameters(a){this.streamManager_.replaceAdTagParameters(a)}stop(){this.backupUrl_="";this.snapForwardTime_=null;this.currentCuePoints_=[]}release(){this.stop();this.eventManager_&&this.eventManager_.release()}onTimedMetadata(a,b,c){this.streamManager_.processMetadata(a,
b,c)}onCueMetadataChange(a){if(a.key&&a.data){const b={};b[a.key]=a.data;this.streamManager_.onTimedMetadata(b)}}getCuePoints(){return this.currentCuePoints_}checkForSnapback_(){const a=this.video_.currentTime;if(a!=0){this.streamManager_.streamTimeForContentTime(a);var b=this.streamManager_.previousCuePointForStreamTime(a);b&&!b.played&&(shaka.log.info("Seeking back to the start of the ad break at "+b.start+" and will return to "+a),this.snapForwardTime_=a,this.video_.currentTime=b.start)}}onAdStart_(a){goog.asserts.assert(this.streamManager_,
"Should have a stream manager at this point!");a=a.getAd();this.ad_=new shaka.ads.ServerSideAd(a,this.video_);this.adProgressData_&&this.ad_.setProgressData(this.adProgressData_);this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_STARTED,(new Map).set("ad",this.ad_)));this.adContainer_.setAttribute("ad-active","true")}onAdBreakEnded_(){this.adContainer_.removeAttribute("ad-active");const a=this.video_.currentTime;this.snapForwardTime_&&this.snapForwardTime_>a&&(this.video_.currentTime=this.snapForwardTime_,
this.snapForwardTime_=null)}onLoaded_(a){const b=Date.now()/1E3-this.streamRequestStartTime_;this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.ADS_LOADED,(new Map).set("loadTime",b)));a=a.getStreamData().url;this.streamPromise_.resolve(a);this.streamPromise_=null;this.isLiveContent_||this.eventManager_.listen(this.video_,"seeked",()=>{this.checkForSnapback_()})}onError_(){this.backupUrl_.length?(shaka.log.warning("IMA stream request returned an error. Falling back to the backup asset uri."),
this.streamPromise_.resolve(this.backupUrl_)):this.streamPromise_.reject("IMA Stream request returned an error and there was no backup asset uri provided.");this.streamPromise_=null}onAdProgress_(a){this.adProgressData_=a.getStreamData().adProgressData;this.ad_&&this.ad_.setProgressData(this.adProgressData_)}onCuePointsChanged_(a){a=a.getStreamData();const b=[];for(const c of a.cuepoints)b.push({start:c.start,end:c.end});this.currentCuePoints_=b;this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.CUEPOINTS_CHANGED,
(new Map).set("cuepoints",b)))}};shaka.ads.AdManager=class extends shaka.util.FakeEventTarget{constructor(){super();this.ssAdManager_=this.mtAdManager_=this.csAdManager_=this.interstitialAdManager_=null;this.stats_=new shaka.ads.AdsStats;this.locale_=navigator.language;this.config_=null}setLocale(a){this.locale_=a}configure(a){this.config_=a;this.interstitialAdManager_&&this.interstitialAdManager_.configure(this.config_);this.csAdManager_&&this.csAdManager_.configure(this.config_);this.ssAdManager_&&this.ssAdManager_.configure(this.config_)}initInterstitial(a,
b,c){a||shaka.log.info("Initializing interstitials without ad container");this.interstitialAdManager_&&this.interstitialAdManager_.release();this.interstitialAdManager_=new shaka.ads.InterstitialAdManager(a,b,c,d=>this.processAndDispatchEvent_(d));goog.asserts.assert(this.config_,"Config must not be null!");this.interstitialAdManager_.configure(this.config_)}initClientSide(a,b,c){if(!window.google||!google.ima||!google.ima.AdsLoader)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.ADS,
shaka.util.Error.Code.CS_IMA_SDK_MISSING);this.csAdManager_&&this.csAdManager_.release();this.csAdManager_=new shaka.ads.ClientSideAdManager(a,b,this.locale_,c,d=>this.processAndDispatchEvent_(d));goog.asserts.assert(this.config_,"Config must not be null!");this.csAdManager_.configure(this.config_)}release(){this.interstitialAdManager_&&(this.interstitialAdManager_.release(),this.interstitialAdManager_=null);this.csAdManager_&&(this.csAdManager_.release(),this.csAdManager_=null);this.mtAdManager_&&
(this.mtAdManager_.release(),this.mtAdManager_=null);this.ssAdManager_&&(this.ssAdManager_.release(),this.ssAdManager_=null);super.release()}onAssetUnload(){this.interstitialAdManager_&&this.interstitialAdManager_.stop();this.csAdManager_&&this.csAdManager_.stop();this.mtAdManager_&&this.mtAdManager_.stop();this.ssAdManager_&&this.ssAdManager_.stop();this.dispatchEvent(new shaka.util.FakeEvent(shaka.ads.Utils.AD_STOPPED));this.dispatchEvent(new shaka.util.FakeEvent(shaka.ads.Utils.AD_CONTENT_ATTACH_REQUESTED));
this.stats_=new shaka.ads.AdsStats}requestClientSideAds(a){if(!this.csAdManager_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.ADS,shaka.util.Error.Code.CS_AD_MANAGER_NOT_INITIALIZED);this.csAdManager_.requestAds(a)}updateClientSideAdsRenderingSettings(a){if(!this.csAdManager_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.ADS,shaka.util.Error.Code.CS_AD_MANAGER_NOT_INITIALIZED);this.csAdManager_.updateAdsRenderingSettings(a)}initMediaTailor(a,
b,c){this.mtAdManager_&&this.mtAdManager_.release();this.mtAdManager_=new shaka.ads.MediaTailorAdManager(a,b,c,d=>this.processAndDispatchEvent_(d))}requestMediaTailorStream(a,b,c=""){if(!this.mtAdManager_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.ADS,shaka.util.Error.Code.MT_AD_MANAGER_NOT_INITIALIZED);return this.mtAdManager_.streamRequest(a,b,c)}addMediaTailorTrackingUrl(a){if(!this.mtAdManager_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,
shaka.util.Error.Category.ADS,shaka.util.Error.Code.MT_AD_MANAGER_NOT_INITIALIZED);this.mtAdManager_.addTrackingUrl(a)}initServerSide(a,b){if(!window.google||!google.ima||!google.ima.dai)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.ADS,shaka.util.Error.Code.SS_IMA_SDK_MISSING);this.ssAdManager_&&this.ssAdManager_.release();this.ssAdManager_=new shaka.ads.ServerSideAdManager(a,b,this.locale_,c=>this.processAndDispatchEvent_(c));goog.asserts.assert(this.config_,
"Config must not be null!");this.ssAdManager_.configure(this.config_)}requestServerSideStream(a,b=""){if(!this.ssAdManager_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.ADS,shaka.util.Error.Code.SS_AD_MANAGER_NOT_INITIALIZED);a.adTagParameters||(a.adTagParameters={});const c=a.adTagParameters;(c.mpt||c.mpv)&&shaka.log.alwaysWarn('You have attempted to set "mpt" and/or "mpv" parameters of the ad tag. Please note that those parameters are used for Shaka adoption tracking and will be overridden.');
a.adTagParameters.mpt="shaka-player";a.adTagParameters.mpv=shaka.Player.version;return this.ssAdManager_.streamRequest(a,b)}replaceServerSideAdTagParameters(a){if(!this.ssAdManager_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.ADS,shaka.util.Error.Code.SS_AD_MANAGER_NOT_INITIALIZED);(a.mpt||a.mpv)&&shaka.log.alwaysWarn('You have attempted to set "mpt" and/or "mpv" parameters of the ad tag. Please note that those parameters are used for Shaka adoption tracking and will be overridden.');
a.mpt="Shaka Player";a.mpv=shaka.Player.version;this.ssAdManager_.replaceAdTagParameters(a)}getServerSideCuePoints(){shaka.Deprecate.deprecateFeature(5,"AdManager.getServerSideCuePoints","Please use getCuePoints function.");return this.getCuePoints()}getCuePoints(){let a=[];this.ssAdManager_&&(a=a.concat(this.ssAdManager_.getCuePoints()));this.mtAdManager_&&(a=a.concat(this.mtAdManager_.getCuePoints()));return a}getStats(){return this.stats_.getBlob()}onManifestUpdated(a){if(this.mtAdManager_)this.mtAdManager_.onManifestUpdated(a)}onDashTimedMetadata(a){if(this.ssAdManager_&&
a.schemeIdUri=="urn:google:dai:2018")this.ssAdManager_.onTimedMetadata(a.schemeIdUri,a.eventNode?a.eventNode.attributes.messageData:null,a.startTime)}onHlsTimedMetadata(a,b){if(this.ssAdManager_)this.ssAdManager_.onTimedMetadata("ID3",a.data,b)}onCueMetadataChange(a){if(this.ssAdManager_)this.ssAdManager_.onCueMetadataChange(a)}onHLSInterstitialMetadata(a,b,c){this.config_&&this.config_.disableHLSInterstitial||(this.interstitialAdManager_||this.initInterstitial(null,a,b),this.interstitialAdManager_&&
this.interstitialAdManager_.addMetadata(c))}onDASHInterstitialMetadata(a,b,c){if(!this.config_||!this.config_.disableDASHInterstitial){var d=c.schemeIdUri;d=="urn:mpeg:dash:event:alternativeMPD:insert:2025"||d=="urn:mpeg:dash:event:alternativeMPD:replace:2025"?(this.interstitialAdManager_||this.initInterstitial(null,a,b),this.interstitialAdManager_&&this.interstitialAdManager_.addRegion(c)):(d=="urn:mpeg:dash:event:2012"||d=="urn:scte:dash:scte214-events")&&c.eventNode&&shaka.util.TXml.findChild(c.eventNode,
"OverlayEvent")&&(this.interstitialAdManager_||this.initInterstitial(null,a,b),this.interstitialAdManager_&&this.interstitialAdManager_.addOverlayRegion(c))}}addCustomInterstitial(a){if(!this.interstitialAdManager_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.ADS,shaka.util.Error.Code.INTERSTITIAL_AD_MANAGER_NOT_INITIALIZED);this.interstitialAdManager_.addInterstitials([a])}addAdUrlInterstitial(a){if(!this.interstitialAdManager_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,
shaka.util.Error.Category.ADS,shaka.util.Error.Code.INTERSTITIAL_AD_MANAGER_NOT_INITIALIZED);return this.interstitialAdManager_.addAdUrlInterstitial(a)}getInterstitialPlayer(){if(!this.interstitialAdManager_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.ADS,shaka.util.Error.Code.INTERSTITIAL_AD_MANAGER_NOT_INITIALIZED);return this.interstitialAdManager_.getPlayer()}processAndDispatchEvent_(a){if(a&&a.type)switch(a.type){case shaka.ads.Utils.ADS_LOADED:this.stats_.addLoadTime(a.loadTime);
break;case shaka.ads.Utils.AD_STARTED:this.stats_.incrementStarted();const b=a.ad;b&&!b.isLinear()&&this.stats_.incrementOverlayAds();break;case shaka.ads.Utils.AD_COMPLETE:this.stats_.incrementPlayedCompletely();break;case shaka.ads.Utils.AD_SKIPPED:this.stats_.incrementSkipped();break;case shaka.ads.Utils.AD_ERROR:this.stats_.incrementErrors()}this.dispatchEvent(a)}};goog.exportSymbol("shaka.ads.AdManager",shaka.ads.AdManager);
goog.exportProperty(shaka.ads.AdManager.prototype,"getInterstitialPlayer",shaka.ads.AdManager.prototype.getInterstitialPlayer);goog.exportProperty(shaka.ads.AdManager.prototype,"addAdUrlInterstitial",shaka.ads.AdManager.prototype.addAdUrlInterstitial);goog.exportProperty(shaka.ads.AdManager.prototype,"addCustomInterstitial",shaka.ads.AdManager.prototype.addCustomInterstitial);goog.exportProperty(shaka.ads.AdManager.prototype,"onDASHInterstitialMetadata",shaka.ads.AdManager.prototype.onDASHInterstitialMetadata);
goog.exportProperty(shaka.ads.AdManager.prototype,"onHLSInterstitialMetadata",shaka.ads.AdManager.prototype.onHLSInterstitialMetadata);goog.exportProperty(shaka.ads.AdManager.prototype,"onCueMetadataChange",shaka.ads.AdManager.prototype.onCueMetadataChange);goog.exportProperty(shaka.ads.AdManager.prototype,"onHlsTimedMetadata",shaka.ads.AdManager.prototype.onHlsTimedMetadata);goog.exportProperty(shaka.ads.AdManager.prototype,"onDashTimedMetadata",shaka.ads.AdManager.prototype.onDashTimedMetadata);
goog.exportProperty(shaka.ads.AdManager.prototype,"onManifestUpdated",shaka.ads.AdManager.prototype.onManifestUpdated);goog.exportProperty(shaka.ads.AdManager.prototype,"getStats",shaka.ads.AdManager.prototype.getStats);goog.exportProperty(shaka.ads.AdManager.prototype,"getCuePoints",shaka.ads.AdManager.prototype.getCuePoints);goog.exportProperty(shaka.ads.AdManager.prototype,"getServerSideCuePoints",shaka.ads.AdManager.prototype.getServerSideCuePoints);
goog.exportProperty(shaka.ads.AdManager.prototype,"replaceServerSideAdTagParameters",shaka.ads.AdManager.prototype.replaceServerSideAdTagParameters);goog.exportProperty(shaka.ads.AdManager.prototype,"requestServerSideStream",shaka.ads.AdManager.prototype.requestServerSideStream);goog.exportProperty(shaka.ads.AdManager.prototype,"initServerSide",shaka.ads.AdManager.prototype.initServerSide);goog.exportProperty(shaka.ads.AdManager.prototype,"addMediaTailorTrackingUrl",shaka.ads.AdManager.prototype.addMediaTailorTrackingUrl);
goog.exportProperty(shaka.ads.AdManager.prototype,"requestMediaTailorStream",shaka.ads.AdManager.prototype.requestMediaTailorStream);goog.exportProperty(shaka.ads.AdManager.prototype,"initMediaTailor",shaka.ads.AdManager.prototype.initMediaTailor);goog.exportProperty(shaka.ads.AdManager.prototype,"updateClientSideAdsRenderingSettings",shaka.ads.AdManager.prototype.updateClientSideAdsRenderingSettings);goog.exportProperty(shaka.ads.AdManager.prototype,"requestClientSideAds",shaka.ads.AdManager.prototype.requestClientSideAds);
goog.exportProperty(shaka.ads.AdManager.prototype,"onAssetUnload",shaka.ads.AdManager.prototype.onAssetUnload);goog.exportProperty(shaka.ads.AdManager.prototype,"release",shaka.ads.AdManager.prototype.release);goog.exportProperty(shaka.ads.AdManager.prototype,"initClientSide",shaka.ads.AdManager.prototype.initClientSide);goog.exportProperty(shaka.ads.AdManager.prototype,"initInterstitial",shaka.ads.AdManager.prototype.initInterstitial);
goog.exportProperty(shaka.ads.AdManager.prototype,"configure",shaka.ads.AdManager.prototype.configure);goog.exportProperty(shaka.ads.AdManager.prototype,"setLocale",shaka.ads.AdManager.prototype.setLocale);shaka.ads.AdManager.ADS_LOADED="ads-loaded";goog.exportProperty(shaka.ads.AdManager,"ADS_LOADED",shaka.ads.AdManager.ADS_LOADED);shaka.ads.AdManager.AD_STARTED="ad-started";goog.exportProperty(shaka.ads.AdManager,"AD_STARTED",shaka.ads.AdManager.AD_STARTED);
shaka.ads.AdManager.AD_FIRST_QUARTILE="ad-first-quartile";goog.exportProperty(shaka.ads.AdManager,"AD_FIRST_QUARTILE",shaka.ads.AdManager.AD_FIRST_QUARTILE);shaka.ads.AdManager.AD_MIDPOINT="ad-midpoint";goog.exportProperty(shaka.ads.AdManager,"AD_MIDPOINT",shaka.ads.AdManager.AD_MIDPOINT);shaka.ads.AdManager.AD_THIRD_QUARTILE="ad-third-quartile";goog.exportProperty(shaka.ads.AdManager,"AD_THIRD_QUARTILE",shaka.ads.AdManager.AD_THIRD_QUARTILE);shaka.ads.AdManager.AD_COMPLETE="ad-complete";
goog.exportProperty(shaka.ads.AdManager,"AD_COMPLETE",shaka.ads.AdManager.AD_COMPLETE);shaka.ads.AdManager.AD_STOPPED="ad-stopped";goog.exportProperty(shaka.ads.AdManager,"AD_STOPPED",shaka.ads.AdManager.AD_STOPPED);shaka.ads.AdManager.AD_SKIPPED="ad-skipped";goog.exportProperty(shaka.ads.AdManager,"AD_SKIPPED",shaka.ads.AdManager.AD_SKIPPED);shaka.ads.AdManager.AD_VOLUME_CHANGED="ad-volume-changed";goog.exportProperty(shaka.ads.AdManager,"AD_VOLUME_CHANGED",shaka.ads.AdManager.AD_VOLUME_CHANGED);
shaka.ads.AdManager.AD_MUTED="ad-muted";goog.exportProperty(shaka.ads.AdManager,"AD_MUTED",shaka.ads.AdManager.AD_MUTED);shaka.ads.AdManager.AD_PAUSED="ad-paused";goog.exportProperty(shaka.ads.AdManager,"AD_PAUSED",shaka.ads.AdManager.AD_PAUSED);shaka.ads.AdManager.AD_RESUMED="ad-resumed";goog.exportProperty(shaka.ads.AdManager,"AD_RESUMED",shaka.ads.AdManager.AD_RESUMED);shaka.ads.AdManager.AD_SKIP_STATE_CHANGED="ad-skip-state-changed";
goog.exportProperty(shaka.ads.AdManager,"AD_SKIP_STATE_CHANGED",shaka.ads.AdManager.AD_SKIP_STATE_CHANGED);shaka.ads.AdManager.CUEPOINTS_CHANGED="ad-cue-points-changed";goog.exportProperty(shaka.ads.AdManager,"CUEPOINTS_CHANGED",shaka.ads.AdManager.CUEPOINTS_CHANGED);shaka.ads.AdManager.IMA_AD_MANAGER_LOADED="ima-ad-manager-loaded";goog.exportProperty(shaka.ads.AdManager,"IMA_AD_MANAGER_LOADED",shaka.ads.AdManager.IMA_AD_MANAGER_LOADED);shaka.ads.AdManager.IMA_STREAM_MANAGER_LOADED="ima-stream-manager-loaded";
goog.exportProperty(shaka.ads.AdManager,"IMA_STREAM_MANAGER_LOADED",shaka.ads.AdManager.IMA_STREAM_MANAGER_LOADED);shaka.ads.AdManager.AD_CLICKED="ad-clicked";goog.exportProperty(shaka.ads.AdManager,"AD_CLICKED",shaka.ads.AdManager.AD_CLICKED);shaka.ads.AdManager.AD_PROGRESS="ad-progress";goog.exportProperty(shaka.ads.AdManager,"AD_PROGRESS",shaka.ads.AdManager.AD_PROGRESS);shaka.ads.AdManager.AD_BUFFERING="ad-buffering";goog.exportProperty(shaka.ads.AdManager,"AD_BUFFERING",shaka.ads.AdManager.AD_BUFFERING);
shaka.ads.AdManager.AD_IMPRESSION="ad-impression";goog.exportProperty(shaka.ads.AdManager,"AD_IMPRESSION",shaka.ads.AdManager.AD_IMPRESSION);shaka.ads.AdManager.AD_DURATION_CHANGED="ad-duration-changed";goog.exportProperty(shaka.ads.AdManager,"AD_DURATION_CHANGED",shaka.ads.AdManager.AD_DURATION_CHANGED);shaka.ads.AdManager.AD_CLOSED="ad-closed";goog.exportProperty(shaka.ads.AdManager,"AD_CLOSED",shaka.ads.AdManager.AD_CLOSED);shaka.ads.AdManager.AD_LOADED="ad-loaded";
goog.exportProperty(shaka.ads.AdManager,"AD_LOADED",shaka.ads.AdManager.AD_LOADED);shaka.ads.AdManager.ALL_ADS_COMPLETED="all-ads-completed";goog.exportProperty(shaka.ads.AdManager,"ALL_ADS_COMPLETED",shaka.ads.AdManager.ALL_ADS_COMPLETED);shaka.ads.AdManager.AD_LINEAR_CHANGED="ad-linear-changed";goog.exportProperty(shaka.ads.AdManager,"AD_LINEAR_CHANGED",shaka.ads.AdManager.AD_LINEAR_CHANGED);shaka.ads.AdManager.AD_METADATA="ad-metadata";goog.exportProperty(shaka.ads.AdManager,"AD_METADATA",shaka.ads.AdManager.AD_METADATA);
shaka.ads.AdManager.AD_RECOVERABLE_ERROR="ad-recoverable-error";goog.exportProperty(shaka.ads.AdManager,"AD_RECOVERABLE_ERROR",shaka.ads.AdManager.AD_RECOVERABLE_ERROR);shaka.ads.AdManager.AD_ERROR="ad-error";goog.exportProperty(shaka.ads.AdManager,"AD_ERROR",shaka.ads.AdManager.AD_ERROR);shaka.ads.AdManager.AD_BREAK_READY="ad-break-ready";goog.exportProperty(shaka.ads.AdManager,"AD_BREAK_READY",shaka.ads.AdManager.AD_BREAK_READY);shaka.ads.AdManager.AD_INTERACTION="ad-interaction";
goog.exportProperty(shaka.ads.AdManager,"AD_INTERACTION",shaka.ads.AdManager.AD_INTERACTION);shaka.ads.AdManager.AD_CONTENT_PAUSE_REQUESTED="ad-content-pause-requested";goog.exportProperty(shaka.ads.AdManager,"AD_CONTENT_PAUSE_REQUESTED",shaka.ads.AdManager.AD_CONTENT_PAUSE_REQUESTED);shaka.ads.AdManager.AD_CONTENT_RESUME_REQUESTED="ad-content-resume-requested";goog.exportProperty(shaka.ads.AdManager,"AD_CONTENT_RESUME_REQUESTED",shaka.ads.AdManager.AD_CONTENT_RESUME_REQUESTED);
shaka.ads.AdManager.AD_CONTENT_ATTACH_REQUESTED="ad-content-attach-requested";goog.exportProperty(shaka.ads.AdManager,"AD_CONTENT_ATTACH_REQUESTED",shaka.ads.AdManager.AD_CONTENT_ATTACH_REQUESTED);shaka.Player.setAdManagerFactory(()=>new shaka.ads.AdManager);shaka.cast={};
shaka.cast.CastUtils=class{static serialize(a){return JSON.stringify(a,(b,c)=>{if(typeof c!="function"){b=c instanceof shaka.util.FakeEvent;if(c instanceof Event||b){const d={};for(const e in c){const f=c[e];f&&typeof f=="object"?e=="detail"?d[e]=f:f instanceof Event||f instanceof shaka.util.FakeEvent?d[e]=shaka.cast.CastUtils.unpackEvent_(f):b&&Array.isArray(f)&&(d[e]=f):e in Event||(d[e]=f)}return d}return c instanceof Error?shaka.cast.CastUtils.unpackError_(c):c instanceof TimeRanges?shaka.cast.CastUtils.unpackTimeRanges_(c):
ArrayBuffer.isView(c)&&c.BYTES_PER_ELEMENT===1?shaka.cast.CastUtils.unpackUint8Array_(c):typeof c=="number"?isNaN(c)?"NaN":isFinite(c)?c:c<0?"-Infinity":"Infinity":c}})}static deserialize(a){return JSON.parse(a,(b,c)=>c=="NaN"?NaN:c=="-Infinity"?-Infinity:c=="Infinity"?Infinity:c&&typeof c=="object"&&c.__type__=="TimeRanges"?shaka.cast.CastUtils.simulateTimeRanges_(c):c&&typeof c=="object"&&c.__type__=="Uint8Array"?shaka.cast.CastUtils.makeUint8Array_(c):c&&typeof c=="object"&&c.__type__=="Error"?
shaka.cast.CastUtils.makeError_(c):c&&typeof c=="object"&&c.__type__=="Event"?shaka.cast.CastUtils.makeEvent_(c):c)}static unpackTimeRanges_(a){const b={__type__:"TimeRanges",length:a.length,start:[],end:[]},c=shaka.media.TimeRangesUtils;for(const {start:d,end:e}of c.getBufferedInfo(a))b.start.push(d),b.end.push(e);return b}static simulateTimeRanges_(a){return{length:a.length,start:b=>a.start[b],end:b=>a.end[b]}}static unpackUint8Array_(a){return{__type__:"Uint8Array",entries:Array.from(a)}}static makeUint8Array_(a){return new Uint8Array(a.entries)}static unpackEvent_(a){return{__type__:"Event",
event:shaka.cast.CastUtils.serialize(a)}}static makeEvent_(a){return shaka.cast.CastUtils.deserialize(a.event)}static unpackError_(a){const b=new Set(["name","message","stack"]);for(var c in a)b.add(c);for(const d of Object.getOwnPropertyNames(a))b.add(d);c={};for(const d of b)c[d]=a[d];return{__type__:"Error",contents:c}}static makeError_(a){a=a.contents;const b=Error(a.message);for(const c in a)b[c]=a[c];return b}};shaka.cast.CastUtils.VideoEvents="ended play playing pause pausing ratechange seeked seeking timeupdate volumechange".split(" ");
shaka.cast.CastUtils.VideoAttributes="buffered currentTime duration ended loop muted paused playbackRate seeking videoHeight videoWidth volume".split(" ");shaka.cast.CastUtils.VideoInitStateAttributes=["loop","playbackRate"];shaka.cast.CastUtils.VideoVoidMethods=["pause","play"];
shaka.cast.CastUtils.PlayerGetterMethods=(new Map).set("getAssetUri",2).set("getAudioLanguages",4).set("getAudioLanguagesAndRoles",4).set("getBufferFullness",1).set("getBufferedInfo",2).set("getExpiration",2).set("getKeyStatuses",2).set("getPlaybackRate",2).set("getTextLanguages",4).set("getTextLanguagesAndRoles",4).set("isAudioOnly",10).set("isBuffering",1).set("isInProgress",1).set("isLive",10).set("isTextTrackVisible",1).set("isVideoOnly",10).set("keySystem",10).set("seekRange",1).set("getLoadMode",
10).set("getManifestType",10).set("isFullyLoaded",1).set("isEnded",1).set("getBandwidthEstimate",1).set("isRemotePlayback",1);shaka.cast.CastUtils.LargePlayerGetterMethods=(new Map).set("getConfiguration",4).set("getConfigurationForLowLatency",4).set("getStats",5).set("getAudioTracks",2).set("getChaptersTracks",2).set("getImageTracks",2).set("getVideoTracks",2).set("getTextTracks",2).set("getVariantTracks",2);
shaka.cast.CastUtils.PlayerGetterMethodsThatRequireLive=(new Map).set("getPlayheadTimeAsDate",1).set("getPresentationStartTimeAsDate",20).set("getSegmentAvailabilityDuration",20);shaka.cast.CastUtils.PlayerInitState=[["getConfiguration","configure","getConfigurationForLowLatency","configurationForLowLatency"]];shaka.cast.CastUtils.PlayerInitAfterLoadState=[["isTextTrackVisible","setTextTrackVisibility"]];shaka.cast.CastUtils.PlayerVoidMethods="cancelTrickPlay configure configurationForLowLatency getChapters resetConfiguration retryStreaming selectAudioLanguage selectAudioTrack selectTextLanguage selectTextTrack selectVariantTrack selectVariantsByLabel selectVideoTrack setTextTrackVisibility trickPlay updateStartTime goToLive useTrickPlayTrackIfAvailable".split(" ");
shaka.cast.CastUtils.PlayerPromiseMethods="addChaptersTrack addTextTrackAsync addThumbnailsTrack getAllThumbnails getChaptersAsync getThumbnails attach attachCanvas detach load unload".split(" ");shaka.cast.CastUtils.SHAKA_MESSAGE_NAMESPACE="urn:x-cast:com.google.shaka.v2";shaka.cast.CastUtils.GENERIC_MESSAGE_NAMESPACE="urn:x-cast:com.google.cast.media";shaka.cast.CastSender=class{constructor(a,b,c,d,e,f,g){this.receiverAppId_=a;this.androidReceiverCompatible_=g;this.statusChangeTimer_=new shaka.util.Timer(b);this.onFirstCastStateUpdate_=c;this.hasJoinedExistingSession_=!1;this.onRemoteEvent_=d;this.onResumeLocal_=e;this.onInitStateRequired_=f;this.isCasting_=this.apiReady_=!1;this.receiverName_="";this.appData_=null;this.onConnectionStatusChangedBound_=()=>this.onConnectionStatusChanged_();this.onMessageReceivedBound_=(h,k)=>this.onMessageReceived_(h,
k);this.cachedProperties_={video:{},player:{}};this.nextAsyncCallId_=0;this.asyncCallPromises_=new Map;this.castPromise_=null;shaka.cast.CastSender.instances_.add(this)}destroy(){shaka.cast.CastSender.instances_.delete(this);this.rejectAllPromises_();shaka.cast.CastSender.session_&&this.removeListeners_();this.statusChangeTimer_&&(this.statusChangeTimer_.stop(),this.statusChangeTimer_=null);this.onResumeLocal_=this.onRemoteEvent_=null;this.isCasting_=this.apiReady_=!1;this.onMessageReceivedBound_=
this.onConnectionStatusChangedBound_=this.castPromise_=this.asyncCallPromises_=this.cachedProperties_=this.appData_=null;return Promise.resolve()}apiReady(){return this.apiReady_}hasReceivers(){return shaka.cast.CastSender.hasReceivers_}isCasting(){return this.isCasting_}receiverName(){return this.receiverName_}hasRemoteProperties(){return Object.keys(this.cachedProperties_.video).length!=0}init(){const a=shaka.cast.CastSender;if(this.receiverAppId_.length)if(window.chrome&&chrome.cast&&chrome.cast.isAvailable){this.apiReady_=
!0;this.statusChangeTimer_.tickNow();var b=new chrome.cast.SessionRequest(this.receiverAppId_,[],null,this.androidReceiverCompatible_,null);b=new chrome.cast.ApiConfig(b,c=>a.onExistingSessionJoined_(c),c=>a.onReceiverStatusChanged_(c),"origin_scoped");chrome.cast.initialize(b,()=>{shaka.log.debug("CastSender: init")},c=>{shaka.log.error("CastSender: init error",c)});shaka.cast.CastSender.hasReceivers_&&this.statusChangeTimer_.tickAfter(shaka.cast.CastSender.STATUS_DELAY);(b=shaka.cast.CastSender.session_)&&
b.status!=chrome.cast.SessionStatus.STOPPED?(shaka.log.debug("CastSender: re-using existing connection"),this.onExistingSessionJoined_(b)):shaka.cast.CastSender.session_=null}else window.__onGCastApiAvailable!==a.onGCastApiAvailable_&&(a.__onGCastApiAvailable_=window.__onGCastApiAvailable||null,window.__onGCastApiAvailable=a.onGCastApiAvailable_)}setAppData(a){this.appData_=a;this.isCasting_&&this.sendMessage_({type:"appData",appData:this.appData_})}async cast(){if(!this.apiReady_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,
shaka.util.Error.Category.CAST,shaka.util.Error.Code.CAST_API_UNAVAILABLE);if(!shaka.cast.CastSender.hasReceivers_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.CAST,shaka.util.Error.Code.NO_CAST_RECEIVERS);if(this.isCasting_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.CAST,shaka.util.Error.Code.ALREADY_CASTING);this.castPromise_=new shaka.util.PublicPromise;chrome.cast.requestSession(a=>this.onSessionInitiated_(a),
a=>this.onConnectionError_(a));await this.castPromise_}showDisconnectDialog(){this.isCasting_&&chrome.cast.requestSession(a=>this.onSessionInitiated_(a),a=>this.onConnectionError_(a))}forceDisconnect(){if(this.isCasting_){this.rejectAllPromises_();if(shaka.cast.CastSender.session_){this.removeListeners_();try{shaka.cast.CastSender.session_.stop(()=>{},()=>{})}catch(a){}shaka.cast.CastSender.session_=null}this.onConnectionStatusChanged_()}}get(a,b){goog.asserts.assert(a=="video"||a=="player","Unexpected target name");
const c=shaka.cast.CastUtils;if(a=="video"){if(c.VideoVoidMethods.includes(b))return(...d)=>this.remoteCall_(a,b,...d)}else if(a=="player"){if(c.PlayerGetterMethodsThatRequireLive.has(b)){const d=this.get("player","isLive")();goog.asserts.assert(d,b+" should be called on a live stream!");if(!d)return()=>{}}if(c.PlayerVoidMethods.includes(b))return(...d)=>this.remoteCall_(a,b,...d);if(c.PlayerPromiseMethods.includes(b))return(...d)=>this.remoteAsyncCall_(a,b,...d);if(c.PlayerGetterMethods.has(b)||
c.LargePlayerGetterMethods.has(b))return()=>this.propertyGetter_(a,b)}return this.propertyGetter_(a,b)}set(a,b,c){goog.asserts.assert(a=="video"||a=="player","Unexpected target name");this.cachedProperties_[a][b]=c;this.sendMessage_({type:"set",targetName:a,property:b,value:c})}onSessionInitiated_(a){shaka.log.debug("CastSender: onSessionInitiated");const b=this.onInitStateRequired_();this.onSessionCreated_(a);this.sendMessage_({type:"init",initState:b,appData:this.appData_});this.castPromise_.resolve()}onConnectionError_(a){let b=
shaka.util.Error.Code.UNEXPECTED_CAST_ERROR;switch(a.code){case "cancel":b=shaka.util.Error.Code.CAST_CANCELED_BY_USER;break;case "timeout":b=shaka.util.Error.Code.CAST_CONNECTION_TIMED_OUT;break;case "receiver_unavailable":b=shaka.util.Error.Code.CAST_RECEIVER_APP_UNAVAILABLE}this.castPromise_.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.CAST,b,a))}propertyGetter_(a,b){goog.asserts.assert(a=="video"||a=="player","Unexpected target name");return this.cachedProperties_[a][b]}remoteCall_(a,
b,...c){goog.asserts.assert(a=="video"||a=="player","Unexpected target name");this.sendMessage_({type:"call",targetName:a,methodName:b,args:c})}remoteAsyncCall_(a,b,...c){goog.asserts.assert(a=="video"||a=="player","Unexpected target name");const d=new shaka.util.PublicPromise,e=this.nextAsyncCallId_.toString();this.nextAsyncCallId_++;this.asyncCallPromises_.set(e,d);try{this.sendMessage_({type:"asyncCall",targetName:a,methodName:b,args:c,id:e})}catch(f){d.reject(f)}return d}static onExistingSessionJoined_(a){for(const b of shaka.cast.CastSender.instances_)b.onExistingSessionJoined_(a)}onExistingSessionJoined_(a){shaka.log.debug("CastSender: onExistingSessionJoined");
this.castPromise_=new shaka.util.PublicPromise;this.hasJoinedExistingSession_=!0;this.onSessionInitiated_(a)}static onReceiverStatusChanged_(a){for(const b of shaka.cast.CastSender.instances_)b.onReceiverStatusChanged_(a)}onReceiverStatusChanged_(a){shaka.log.debug("CastSender: receiver status",a);shaka.cast.CastSender.hasReceivers_=a=="available";this.statusChangeTimer_.tickNow()}onSessionCreated_(a){shaka.cast.CastSender.session_=a;a.addUpdateListener(this.onConnectionStatusChangedBound_);a.addMessageListener(shaka.cast.CastUtils.SHAKA_MESSAGE_NAMESPACE,
this.onMessageReceivedBound_);this.onConnectionStatusChanged_()}removeListeners_(){const a=shaka.cast.CastSender.session_;a.removeUpdateListener(this.onConnectionStatusChangedBound_);a.removeMessageListener(shaka.cast.CastUtils.SHAKA_MESSAGE_NAMESPACE,this.onMessageReceivedBound_)}onConnectionStatusChanged_(){const a=shaka.cast.CastSender.session_?shaka.cast.CastSender.session_.status=="connected":!1;shaka.log.info("CastSender: connection status",a);if(this.isCasting_&&!a){this.onResumeLocal_();for(const b in this.cachedProperties_)this.cachedProperties_[b]=
{};this.rejectAllPromises_()}this.receiverName_=(this.isCasting_=a)?shaka.cast.CastSender.session_.receiver.friendlyName:"";this.statusChangeTimer_.tickNow();this.receiverName_&&shaka.log.info("CastSender: connected to",this.receiverName_)}rejectAllPromises_(){if(this.asyncCallPromises_)for(const a of this.asyncCallPromises_.keys()){const b=this.asyncCallPromises_.get(a);this.asyncCallPromises_.delete(a);b.reject(new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.PLAYER,
shaka.util.Error.Code.LOAD_INTERRUPTED))}}onMessageReceived_(a,b){a=shaka.cast.CastUtils.deserialize(b);shaka.log.v2("CastSender: message",a);switch(a.type){case "event":var c=a.targetName,d=shaka.util.FakeEvent.fromRealEvent(a.event);this.onRemoteEvent_(c,d);break;case "update":c=a.update;for(d in c){a=this.cachedProperties_[d]||{};for(var e in c[d])a[e]=c[d][e]}this.hasJoinedExistingSession_&&(this.onFirstCastStateUpdate_(),this.hasJoinedExistingSession_=!1);break;case "asyncComplete":if(e=a.id,
d=a.error,b=a.res,a=this.asyncCallPromises_.get(e),this.asyncCallPromises_.delete(e),goog.asserts.assert(a,"Unexpected async id"),a)if(d){e=new shaka.util.Error(d.severity,d.category,d.code);for(c in d)e[c]=d[c];a.reject(e)}else a.resolve(b)}}sendMessage_(a){a=shaka.cast.CastUtils.serialize(a);var b=shaka.cast.CastSender.session_;try{b.sendMessage(shaka.cast.CastUtils.SHAKA_MESSAGE_NAMESPACE,a,()=>{},shaka.log.error)}catch(c){throw shaka.log.error("Cast session sendMessage threw",c),a=new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.CAST,shaka.util.Error.Code.CAST_CONNECTION_TIMED_OUT,c),b=new shaka.util.FakeEvent("error",(new Map).set("detail",a)),this.onRemoteEvent_("player",b),this.forceDisconnect(),a;}}};shaka.cast.CastSender.STATUS_DELAY=.02;shaka.cast.CastSender.hasReceivers_=!1;shaka.cast.CastSender.session_=null;shaka.cast.CastSender.__onGCastApiAvailable_=null;shaka.cast.CastSender.instances_=new Set;shaka.cast.CastSender.onSdkLoaded_=a=>{if(a)for(const b of shaka.cast.CastSender.instances_)b.init()};
shaka.cast.CastSender.onGCastApiAvailable_=a=>{shaka.cast.CastSender.__onGCastApiAvailable_?window.__onGCastApiAvailable=shaka.cast.CastSender.__onGCastApiAvailable_:delete window.__onGCastApiAvailable;shaka.cast.CastSender.__onGCastApiAvailable_=null;shaka.cast.CastSender.onSdkLoaded_(a);typeof window.__onGCastApiAvailable==="function"&&window.__onGCastApiAvailable(a)};shaka.cast.CastProxy=class extends shaka.util.FakeEventTarget{constructor(a,b,c,d=!1){super();this.localVideo_=a;this.localPlayer_=b;this.eventManager_=this.playerEventTarget_=this.videoEventTarget_=this.playerProxy_=this.videoProxy_=null;this.receiverAppId_=c;this.androidReceiverCompatible_=d;this.addThumbnailsTrackCalls_=[];this.addTextTrackAsyncCalls_=[];this.addChaptersTrackCalls_=[];this.compiledToExternNames_=new Map;this.sender_=null;this.shouldInitCastSender_()?(this.sender_=new shaka.cast.CastSender(c,
()=>this.onCastStatusChanged_(),()=>this.onFirstCastStateUpdate_(),(e,f)=>this.onRemoteEvent_(e,f),()=>this.onResumeLocal_(),()=>this.getInitState_(),d),this.init_()):this.initWithoutSender_()}destroy(a=!1){this.sender_&&a&&this.sender_.forceDisconnect();this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null);a=[];this.localPlayer_&&(a.push(this.localPlayer_.destroy()),this.localPlayer_=null);this.sender_&&(a.push(this.sender_.destroy()),this.sender_=null);this.playerProxy_=this.videoProxy_=
this.localVideo_=null;super.release();return Promise.all(a)}getVideo(){return this.videoProxy_}getPlayer(){return this.playerProxy_}canCast(){return this.sender_?this.sender_.apiReady()&&this.sender_.hasReceivers():!1}isCasting(){return this.sender_?this.sender_.isCasting():!1}receiverName(){return this.sender_?this.sender_.receiverName():""}async cast(){this.sender_&&(await this.sender_.cast(),this.localPlayer_&&await this.localPlayer_.unload())}setAppData(a){this.sender_&&this.sender_.setAppData(a)}suggestDisconnect(){this.sender_&&
this.sender_.showDisconnectDialog()}forceDisconnect(){this.sender_&&this.sender_.forceDisconnect()}async changeReceiverId(a,b=!1){if(a!=this.receiverAppId_||b!=this.androidReceiverCompatible_)this.receiverAppId_=a,this.androidReceiverCompatible_=b,this.sender_&&(this.sender_.forceDisconnect(),await this.sender_.destroy(),this.sender_=null,this.sender_=new shaka.cast.CastSender(a,()=>this.onCastStatusChanged_(),()=>this.onFirstCastStateUpdate_(),(c,d)=>this.onRemoteEvent_(c,d),()=>this.onResumeLocal_(),
()=>this.getInitState_(),b),this.sender_.init())}initWithoutSender_(){this.videoProxy_=this.localVideo_;this.playerProxy_=this.localPlayer_}init_(){this.sender_.init();this.eventManager_=new shaka.util.EventManager;for(const a of shaka.cast.CastUtils.VideoEvents)this.eventManager_.listen(this.localVideo_,a,b=>this.videoProxyLocalEvent_(b));for(const a in shaka.util.FakeEvent.EventName)this.eventManager_.listen(this.localPlayer_,shaka.util.FakeEvent.EventName[a],b=>this.playerProxyLocalEvent_(b));
this.videoProxy_={};for(const a in this.localVideo_)Object.defineProperty(this.videoProxy_,a,{configurable:!1,enumerable:!0,get:()=>this.videoProxyGet_(a),set:b=>{this.videoProxySet_(a,b)}});this.playerProxy_={};this.iterateOverPlayerMethods_((a,b)=>{goog.asserts.assert(this.playerProxy_,"Must have player proxy!");Object.defineProperty(this.playerProxy_,a,{configurable:!1,enumerable:!0,get:()=>this.playerProxyGet_(a)})});COMPILED&&this.mapCompiledToUncompiledPlayerMethodNames_();this.videoEventTarget_=
new shaka.util.FakeEventTarget;this.videoEventTarget_.dispatchTarget=this.videoProxy_;this.playerEventTarget_=new shaka.util.FakeEventTarget;this.playerEventTarget_.dispatchTarget=this.playerProxy_;this.eventManager_.listen(this.localPlayer_,shaka.util.FakeEvent.EventName.Unloading,()=>{this.sender_&&this.sender_.isCasting()||this.resetExternalTracks()})}mapCompiledToUncompiledPlayerMethodNames_(){const a=new Map;this.iterateOverPlayerMethods_((b,c)=>{a.has(c)?(c=a.get(c),b.length<c.length?this.compiledToExternNames_.set(b,
c):this.compiledToExternNames_.set(c,b)):a.set(c,b)})}iterateOverPlayerMethods_(a){function b(g){return g=="constructor"||typeof c[g]!="function"?!1:!d.has(g)}goog.asserts.assert(this.localPlayer_,"Must have player!");const c=this.localPlayer_,d=new Set;for(var e in c)b(e)&&(d.add(e),a(e,c[e]));e=Object.getPrototypeOf(c);const f=Object.getPrototypeOf({});for(;e&&e!=f;){for(const g of Object.getOwnPropertyNames(e))b(g)&&(d.add(g),a(g,c[g]));e=Object.getPrototypeOf(e)}}getInitState_(){const a={video:{},
player:{},playerAfterLoad:{},manifest:this.localPlayer_.getAssetUri(),startTime:null,addThumbnailsTrackCalls:this.addThumbnailsTrackCalls_,addTextTrackAsyncCalls:this.addTextTrackAsyncCalls_,addChaptersTrackCalls:this.addChaptersTrackCalls_};this.localVideo_.pause();for(var b of shaka.cast.CastUtils.VideoInitStateAttributes)a.video[b]=this.localVideo_[b];this.localVideo_.ended||(a.startTime=this.localVideo_.currentTime);for(var c of shaka.cast.CastUtils.PlayerInitState){b=c[1];const d=this.localPlayer_[c[0]]();
a.player[b]=d}for(const d of shaka.cast.CastUtils.PlayerInitAfterLoadState)c=d[1],b=this.localPlayer_[d[0]](),a.playerAfterLoad[c]=b;return a}onCastStatusChanged_(){const a=new shaka.util.FakeEvent("caststatuschanged");this.dispatchEvent(a)}onFirstCastStateUpdate_(){const a=new shaka.util.FakeEvent(this.videoProxy_.paused?"pause":"play");this.videoEventTarget_.dispatchEvent(a)}onResumeLocal_(){for(var a of shaka.cast.CastUtils.PlayerInitState){var b=a[1],c=this.sender_.get("player",a[0])();this.localPlayer_[b](c)}const d=
this.addThumbnailsTrackCalls_,e=this.addTextTrackAsyncCalls_,f=this.addChaptersTrackCalls_;this.resetExternalTracks();const g=this.sender_.get("player","getAssetUri")();c=this.sender_.get("video","ended");a=Promise.resolve();const h=this.localVideo_.autoplay;b=null;c||(b=this.sender_.get("video","currentTime"));let k;(c=this.sender_.get("player","getTextTracks")())&&c.length&&(k=c.find(n=>n.active));const l=this.sender_.get("player","isTextTrackVisible")();g&&(this.localVideo_.autoplay=!1,a=this.localPlayer_.load(g,
b));const m={};for(const n of shaka.cast.CastUtils.VideoInitStateAttributes)m[n]=this.sender_.get("video",n);a.then(()=>{if(this.localVideo_){for(var n of d)this.getPlayer().addThumbnailsTrack(...n);for(var q of e)this.getPlayer().addTextTrackAsync(...q);for(const p of f)this.getPlayer().addChaptersTrack(...p);for(const p of shaka.cast.CastUtils.VideoInitStateAttributes)this.localVideo_[p]=m[p];for(const p of shaka.cast.CastUtils.PlayerInitAfterLoadState)n=p[1],q=this.sender_.get("player",p[0])(),
this.localPlayer_[n](q);this.localPlayer_.setTextTrackVisibility(l);k&&this.localPlayer_.selectTextLanguage(k.language,k.roles,k.forced);this.localVideo_.autoplay=h;g&&this.localVideo_.play()}},n=>{goog.asserts.assert(n instanceof shaka.util.Error,"Wrong error type!");var q=shaka.util.FakeEvent.EventName.Error;n=(new Map).set("detail",n);q=new shaka.util.FakeEvent(q,n);this.localPlayer_.dispatchEvent(q)})}videoProxyGet_(a){if(a=="addEventListener")return(b,c,d)=>this.videoEventTarget_.addEventListener(b,
c,d);if(a=="removeEventListener")return(b,c,d)=>this.videoEventTarget_.removeEventListener(b,c,d);if(this.sender_.isCasting()&&!this.sender_.hasRemoteProperties()){const b=this.localVideo_[a];if(typeof b!="function")return b}return this.sender_.isCasting()?this.sender_.get("video",a):(a=this.localVideo_[a],typeof a=="function"&&(a=a.bind(this.localVideo_)),a)}videoProxySet_(a,b){this.sender_.isCasting()?this.sender_.set("video",a,b):this.localVideo_[a]=b}videoProxyLocalEvent_(a){this.sender_.isCasting()||
(a=shaka.util.FakeEvent.fromRealEvent(a),this.videoEventTarget_.dispatchEvent(a))}playerProxyGet_(a,b=!1){this.compiledToExternNames_.has(a)&&(a=this.compiledToExternNames_.get(a));if(a=="addEventListener")return(c,d,e)=>this.playerEventTarget_.addEventListener(c,d,e);if(a=="removeEventListener")return(c,d,e)=>this.playerEventTarget_.removeEventListener(c,d,e);if(a=="getMediaElement")return()=>this.videoProxy_;if(a=="getSharedConfiguration")return shaka.log.warning("Can't share configuration across a network. Returning copy."),
this.sender_.get("player","getConfiguration");if(a=="getNetworkingEngine")return this.sender_.isCasting()&&shaka.log.warning("NOTE: getNetworkingEngine() is always local!"),()=>this.localPlayer_.getNetworkingEngine();if(a=="getDrmEngine")return this.sender_.isCasting()&&shaka.log.warning("NOTE: getDrmEngine() is always local!"),()=>this.localPlayer_.getDrmEngine();if(a=="getAdManager")return this.sender_.isCasting()&&shaka.log.warning("NOTE: getAdManager() is always local!"),()=>this.localPlayer_.getAdManager();
if(a=="getQueueManager")return()=>this.localPlayer_.getQueueManager();if(a=="setVideoContainer")return this.sender_.isCasting()&&shaka.log.warning("NOTE: setVideoContainer() is always local!"),c=>this.localPlayer_.setVideoContainer(c);if(!b){if(a=="addThumbnailsTrack")return(...c)=>{this.addThumbnailsTrackCalls_.push(c);return this.playerProxyGet_(a,!0)(...c)};if(a=="addTextTrackAsync")return(...c)=>{this.addTextTrackAsyncCalls_.push(c);return this.playerProxyGet_(a,!0)(...c)};if(a=="addChaptersTrack")return(...c)=>
{this.addChaptersTrackCalls_.push(c);return this.playerProxyGet_(a,!0)(...c)}}if(this.sender_.isCasting()){if(a=="getManifest"||a=="drmInfo")return()=>{shaka.log.alwaysWarn(a+"() does not work while casting!");return null};if(a=="attach"||a=="detach")return()=>{shaka.log.alwaysWarn(a+"() does not work while casting!");return Promise.resolve()};if(a=="getChapters")return()=>{shaka.log.alwaysWarn(a+"() does not work while casting!");return[]}}return this.sender_.isCasting()&&!this.sender_.hasRemoteProperties()&&
(shaka.cast.CastUtils.PlayerGetterMethods.has(a)||shaka.cast.CastUtils.LargePlayerGetterMethods.has(a))||!this.sender_.isCasting()?(b=this.localPlayer_[a],goog.asserts.assert(typeof b=="function","only methods on Player"),b.bind(this.localPlayer_)):this.sender_.get("player",a)}playerProxyLocalEvent_(a){this.sender_.isCasting()||this.playerEventTarget_.dispatchEvent(a)}onRemoteEvent_(a,b){goog.asserts.assert(this.sender_.isCasting(),"Should only receive remote events while casting");this.sender_.isCasting()&&
(a=="video"?this.videoEventTarget_.dispatchEvent(b):a=="player"&&(b.type==shaka.util.FakeEvent.EventName.Unloading&&this.resetExternalTracks(),this.playerEventTarget_.dispatchEvent(b)))}resetExternalTracks(){this.addThumbnailsTrackCalls_=[];this.addTextTrackAsyncCalls_=[];this.addChaptersTrackCalls_=[]}shouldInitCastSender_(){return window.chrome&&shaka.device.DeviceFactory.getDevice().getDeviceType()!=shaka.device.IDevice.DeviceType.CAST?!0:!1}};goog.exportSymbol("shaka.cast.CastProxy",shaka.cast.CastProxy);
goog.exportProperty(shaka.cast.CastProxy.prototype,"changeReceiverId",shaka.cast.CastProxy.prototype.changeReceiverId);goog.exportProperty(shaka.cast.CastProxy.prototype,"forceDisconnect",shaka.cast.CastProxy.prototype.forceDisconnect);goog.exportProperty(shaka.cast.CastProxy.prototype,"suggestDisconnect",shaka.cast.CastProxy.prototype.suggestDisconnect);goog.exportProperty(shaka.cast.CastProxy.prototype,"setAppData",shaka.cast.CastProxy.prototype.setAppData);
goog.exportProperty(shaka.cast.CastProxy.prototype,"cast",shaka.cast.CastProxy.prototype.cast);goog.exportProperty(shaka.cast.CastProxy.prototype,"receiverName",shaka.cast.CastProxy.prototype.receiverName);goog.exportProperty(shaka.cast.CastProxy.prototype,"isCasting",shaka.cast.CastProxy.prototype.isCasting);goog.exportProperty(shaka.cast.CastProxy.prototype,"canCast",shaka.cast.CastProxy.prototype.canCast);goog.exportProperty(shaka.cast.CastProxy.prototype,"getPlayer",shaka.cast.CastProxy.prototype.getPlayer);
goog.exportProperty(shaka.cast.CastProxy.prototype,"getVideo",shaka.cast.CastProxy.prototype.getVideo);goog.exportProperty(shaka.cast.CastProxy.prototype,"destroy",shaka.cast.CastProxy.prototype.destroy);shaka.cast.CastReceiver=class extends shaka.util.FakeEventTarget{constructor(a,b,c,d){super();this.video_=a;this.player_=b;this.eventManager_=new shaka.util.EventManager;this.targets_={video:a,player:b};this.appDataCallback_=c||(()=>{});this.contentIdCallback_=d||(e=>e);this.metadata_=null;this.isConnected_=!1;this.isIdle_=!0;this.updateNumber_=0;this.startUpdatingUpdateNumber_=!1;this.initialStatusUpdatePending_=!0;this.genericBus_=this.shakaBus_=null;this.pollTimer_=new shaka.util.Timer(()=>{this.pollAttributes_()});
this.init_()}isConnected(){return this.isConnected_}isIdle(){return this.isIdle_}setContentMetadata(a){this.metadata_=a}clearContentMetadata(){this.metadata_=null}setContentTitle(a){this.metadata_||(this.metadata_={metadataType:cast.receiver.media.MetadataType.GENERIC});this.metadata_.title=a}setContentImage(a){this.metadata_||(this.metadata_={metadataType:cast.receiver.media.MetadataType.GENERIC});this.metadata_.images=[{url:a}]}setContentArtist(a){this.metadata_||(this.metadata_={});this.metadata_.artist=
a;this.metadata_.metadataType=cast.receiver.media.MetadataType.MUSIC_TRACK}async destroy(){this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null);const a=[];this.player_&&(a.push(this.player_.destroy()),this.player_=null);this.pollTimer_&&(this.pollTimer_.stop(),this.pollTimer_=null);this.appDataCallback_=this.targets_=this.video_=null;this.isConnected_=!1;this.isIdle_=!0;this.genericBus_=this.shakaBus_=null;super.release();await Promise.all(a);cast.receiver.CastReceiverManager.getInstance().stop()}init_(){const a=
cast.receiver.CastReceiverManager.getInstance();a.onSenderConnected=()=>this.onSendersChanged_();a.onSenderDisconnected=()=>this.onSendersChanged_();a.onSystemVolumeChanged=()=>this.fakeVolumeChangeEvent_();this.genericBus_=a.getCastMessageBus(shaka.cast.CastUtils.GENERIC_MESSAGE_NAMESPACE);this.genericBus_.onMessage=b=>this.onGenericMessage_(b);this.shakaBus_=a.getCastMessageBus(shaka.cast.CastUtils.SHAKA_MESSAGE_NAMESPACE);this.shakaBus_.onMessage=b=>this.onShakaMessage_(b);goog.DEBUG?shaka.device.DeviceFactory.getDevice().getDeviceType()===
shaka.device.IDevice.DeviceType.CAST&&a.start():a.start();for(const b of shaka.cast.CastUtils.VideoEvents)this.eventManager_.listen(this.video_,b,c=>this.proxyEvent_("video",c));for(const b in shaka.util.FakeEvent.EventName)this.eventManager_.listen(this.player_,shaka.util.FakeEvent.EventName[b],c=>this.proxyEvent_("player",c));this.eventManager_.listen(this.video_,"loadeddata",()=>{this.startUpdatingUpdateNumber_=!0});this.eventManager_.listen(this.player_,"loading",()=>{this.isIdle_=!1;this.onCastStatusChanged_()});
this.eventManager_.listen(this.video_,"playing",()=>{this.isIdle_=!1;this.onCastStatusChanged_()});this.eventManager_.listen(this.video_,"pause",()=>{this.onCastStatusChanged_()});this.eventManager_.listen(this.player_,"unloading",()=>{this.isIdle_=!0;this.onCastStatusChanged_()});this.eventManager_.listen(this.video_,"ended",()=>{(new shaka.util.Timer(()=>{this.video_&&this.video_.ended&&(this.isIdle_=!0,this.onCastStatusChanged_())})).tickAfter(shaka.cast.CastReceiver.IDLE_INTERVAL)})}onSendersChanged_(){this.updateNumber_=
0;this.initialStatusUpdatePending_=!0;this.isConnected_=cast.receiver.CastReceiverManager.getInstance().getSenders().length!=0;this.onCastStatusChanged_()}async onCastStatusChanged_(){await Promise.resolve();if(this.player_){var a=new shaka.util.FakeEvent("caststatuschanged");this.dispatchEvent(a);this.maybeSendMediaInfoMessage_()||this.sendMediaStatus_()}}async initState_(a,b){for(const d in a.player)this.player_[d](a.player[d]);this.appDataCallback_(b);b=this.video_.autoplay;if(a.manifest){this.video_.autoplay=
!1;try{await this.player_.load(a.manifest,a.startTime);if(a.addThumbnailsTrackCalls)for(var c of a.addThumbnailsTrackCalls)this.player_.addThumbnailsTrack(...c);if(a.addTextTrackAsyncCalls)for(const d of a.addTextTrackAsyncCalls)this.player_.addTextTrackAsync(...d);if(a.addChaptersTrackCalls)for(const d of a.addChaptersTrackCalls)this.player_.addChaptersTrack(...d)}catch(d){goog.asserts.assert(d instanceof shaka.util.Error,"Wrong error type! Error: "+d);a=shaka.util.FakeEvent.EventName.Error;c=(new Map).set("detail",
d);a=new shaka.util.FakeEvent(a,c);this.player_&&this.player_.dispatchEvent(a);return}}else await Promise.resolve();if(this.player_){for(const d in a.video)this.video_[d]=a.video[d];for(const d in a.playerAfterLoad)this.player_[d](a.playerAfterLoad[d]);this.video_.autoplay=b;a.manifest&&(this.video_.play(),this.sendMediaStatus_())}}proxyEvent_(a,b){this.player_&&(this.pollAttributes_(),this.sendMessage_({type:"event",targetName:a,event:b},this.shakaBus_))}pollAttributes_(){this.pollTimer_.tickAfter(shaka.cast.CastReceiver.POLL_INTERVAL);
const a={video:{},player:{}};for(var b of shaka.cast.CastUtils.VideoAttributes)a.video[b]=this.video_[b];this.player_.isLive()&&shaka.cast.CastUtils.PlayerGetterMethodsThatRequireLive.forEach((c,d)=>{this.updateNumber_%c==0&&(a.player[d]=this.player_[d]())});shaka.cast.CastUtils.PlayerGetterMethods.forEach((c,d)=>{this.updateNumber_%c==0&&(a.player[d]=this.player_[d]())});if(b=cast.receiver.CastReceiverManager.getInstance().getSystemVolume())a.video.volume=b.level,a.video.muted=b.muted;this.sendMessage_({type:"update",
update:a},this.shakaBus_);shaka.cast.CastUtils.LargePlayerGetterMethods.forEach((c,d)=>{this.updateNumber_%c==0&&(c={player:{}},c.player[d]=this.player_[d](),this.sendMessage_({type:"update",update:c},this.shakaBus_))});this.startUpdatingUpdateNumber_&&(this.updateNumber_+=1);this.maybeSendMediaInfoMessage_()}maybeSendMediaInfoMessage_(){return this.initialStatusUpdatePending_&&(this.video_.duration||this.player_.isLive())?(this.sendMediaInfoMessage_(),this.initialStatusUpdatePending_=!1,!0):!1}sendMediaInfoMessage_(a=
0){const b={contentId:this.player_.getAssetUri(),streamType:this.player_.isLive()?"LIVE":"BUFFERED",contentType:""};this.player_.isLive()||(b.duration=this.video_.duration);this.metadata_&&(b.metadata=this.metadata_);this.sendMediaStatus_(a,b)}fakeVolumeChangeEvent_(){const a=cast.receiver.CastReceiverManager.getInstance().getSystemVolume();goog.asserts.assert(a,"System volume should not be null!");a&&this.sendMessage_({type:"update",update:{video:{volume:a.level,muted:a.muted}}},this.shakaBus_);
this.sendMessage_({type:"event",targetName:"video",event:{type:"volumechange"}},this.shakaBus_)}onShakaMessage_(a){var b=shaka.cast.CastUtils.deserialize(a.data);shaka.log.debug("CastReceiver: message",b);switch(b.type){case "init":this.updateNumber_=0;this.startUpdatingUpdateNumber_=!1;this.initialStatusUpdatePending_=!0;this.initState_(b.initState,b.appData);this.pollAttributes_();break;case "appData":this.appDataCallback_(b.appData);break;case "set":var c=b.targetName,d=b.property;b=b.value;if(c==
"video")if(a=cast.receiver.CastReceiverManager.getInstance(),d=="volume"){a.setSystemVolumeLevel(b);break}else if(d=="muted"){a.setSystemVolumeMuted(b);break}this.targets_[c][d]=b;break;case "call":c=this.targets_[b.targetName];c[b.methodName].apply(c,b.args);break;case "asyncCall":c=b.targetName;d=b.methodName;c=="player"&&d=="load"&&(this.updateNumber_=0,this.startUpdatingUpdateNumber_=!1);const e=b.id,f=a.senderId;a=this.targets_[c];b=a[d].apply(a,b.args);c=="player"&&d=="load"&&(b=b.then(()=>
{this.initialStatusUpdatePending_=!0}));b.then(g=>this.sendAsyncComplete_(f,e,null,g),g=>this.sendAsyncComplete_(f,e,g,null))}}onGenericMessage_(a){const b=shaka.cast.CastUtils.deserialize(a.data);shaka.log.debug("CastReceiver: message",b);switch(b.type){case "PLAY":this.video_.play();this.sendMediaStatus_();break;case "PAUSE":this.video_.pause();this.sendMediaStatus_();break;case "SEEK":a=b.currentTime;var c=b.resumeState;a!=null&&(this.video_.currentTime=Number(a));c&&c=="PLAYBACK_START"?(this.video_.play(),
this.sendMediaStatus_()):c&&c=="PLAYBACK_PAUSE"&&(this.video_.pause(),this.sendMediaStatus_());break;case "STOP":this.player_.unload().then(()=>{this.player_&&this.sendMediaStatus_()});break;case "GET_STATUS":this.sendMediaInfoMessage_(Number(b.requestId));break;case "VOLUME":c=b.volume;a=c.level;c=c.muted;var d=this.video_.volume,e=this.video_.muted;a!=null&&(this.video_.volume=Number(a));c!=null&&(this.video_.muted=c);d==this.video_.volume&&e==this.video_.muted||this.sendMediaStatus_();break;case "LOAD":this.updateNumber_=
0;this.initialStatusUpdatePending_=this.startUpdatingUpdateNumber_=!1;a=b.media;c=b.currentTime;d=this.contentIdCallback_(a.contentId);e=b.autoplay||!0;this.appDataCallback_(a.customData);e&&(this.video_.autoplay=!0);this.player_.load(d,c).then(()=>{this.player_&&this.sendMediaInfoMessage_()}).catch(f=>{goog.asserts.assert(f instanceof shaka.util.Error,"Wrong error type!");let g="LOAD_FAILED";f.category==shaka.util.Error.Category.PLAYER&&f.code==shaka.util.Error.Code.LOAD_INTERRUPTED&&(g="LOAD_CANCELLED");
this.sendMessage_({requestId:Number(b.requestId),type:g},this.genericBus_)});break;default:shaka.log.warning("Unrecognized message type from the generic Chromecast controller!",b.type),this.sendMessage_({requestId:Number(b.requestId),type:"INVALID_REQUEST",reason:"INVALID_COMMAND"},this.genericBus_)}}sendAsyncComplete_(a,b,c,d){this.player_&&this.sendMessage_({type:"asyncComplete",id:b,error:c,res:d},this.shakaBus_,a)}sendMessage_(a,b,c){this.isConnected_&&(a=shaka.cast.CastUtils.serialize(a),c?b.getCastChannel(c).send(a):
b.broadcast(a))}getPlayState_(){const a=shaka.cast.CastReceiver.PLAY_STATE;return this.isIdle_?a.IDLE:this.player_.isBuffering()?a.BUFFERING:this.video_.paused?a.PAUSED:a.PLAYING}sendMediaStatus_(a=0,b=null){const c={mediaSessionId:0,playbackRate:this.video_.playbackRate,playerState:this.getPlayState_(),currentTime:this.video_.currentTime,supportedMediaCommands:63,volume:{level:this.video_.volume,muted:this.video_.muted}};b&&(c.media=b);this.sendMessage_({requestId:a,type:"MEDIA_STATUS",status:[c]},
this.genericBus_)}};goog.exportSymbol("shaka.cast.CastReceiver",shaka.cast.CastReceiver);goog.exportProperty(shaka.cast.CastReceiver.prototype,"destroy",shaka.cast.CastReceiver.prototype.destroy);goog.exportProperty(shaka.cast.CastReceiver.prototype,"setContentArtist",shaka.cast.CastReceiver.prototype.setContentArtist);goog.exportProperty(shaka.cast.CastReceiver.prototype,"setContentImage",shaka.cast.CastReceiver.prototype.setContentImage);
goog.exportProperty(shaka.cast.CastReceiver.prototype,"setContentTitle",shaka.cast.CastReceiver.prototype.setContentTitle);goog.exportProperty(shaka.cast.CastReceiver.prototype,"clearContentMetadata",shaka.cast.CastReceiver.prototype.clearContentMetadata);goog.exportProperty(shaka.cast.CastReceiver.prototype,"setContentMetadata",shaka.cast.CastReceiver.prototype.setContentMetadata);goog.exportProperty(shaka.cast.CastReceiver.prototype,"isIdle",shaka.cast.CastReceiver.prototype.isIdle);
goog.exportProperty(shaka.cast.CastReceiver.prototype,"isConnected",shaka.cast.CastReceiver.prototype.isConnected);shaka.cast.CastReceiver.POLL_INTERVAL=.5;shaka.cast.CastReceiver.IDLE_INTERVAL=5;shaka.cast.CastReceiver.PLAY_STATE={IDLE:"IDLE",PLAYING:"PLAYING",BUFFERING:"BUFFERING",PAUSED:"PAUSED"};shaka.cea.CeaUtils=class{static getParsedCaption(a,b,c,d,e){if(d>=e)return null;var f=-1;let g=-1;for(var h=0;h<c.length;h++)if(c[h].some(t=>t!=null&&t.getChar().trim()!="")){f=h;break}for(h=c.length-1;h>=0;h--)if(c[h].some(t=>t!=null&&t.getChar().trim()!="")){g=h;break}if(f===-1||g===-1)return null;let k=h=!1,l=shaka.cea.CeaUtils.DEFAULT_TXT_COLOR,m=shaka.cea.CeaUtils.DEFAULT_BG_COLOR;for(var n=shaka.cea.CeaUtils.createStyledCue(d,e,h,k,l,m);f<=g;f++){var q=c[f],p=-1;let t=-1;for(var r=0;r<q.length;r++)if(q[r]!=
null&&q[r].getChar().trim()!==""){p=r;break}for(r=q.length-1;r>=0;r--)if(q[r]!=null&&q[r].getChar().trim()!==""){t=r;break}if(p===-1||t===-1)q=shaka.cea.CeaUtils.createLineBreakCue(d,e),a.nestedCues.push(q);else{for(;p<=t;p++){r=q[p];if(!r){n.payload+=" ";continue}const u=r.isUnderlined(),v=r.isItalicized(),x=r.getTextColor(),y=r.getBackgroundColor();if(u!=h||v!=k||x!=l||y!=m)n.payload&&a.nestedCues.push(n),n=shaka.cea.CeaUtils.createStyledCue(d,e,u,v,x,y),h=u,k=v,l=x,m=y;n.payload+=r.getChar()}n.payload&&
a.nestedCues.push(n);f!==g&&(n=shaka.cea.CeaUtils.createLineBreakCue(d,e),a.nestedCues.push(n));n=shaka.cea.CeaUtils.createStyledCue(d,e,h,k,l,m)}}return a.nestedCues.length?{cue:a,stream:b}:null}static createStyledCue(a,b,c,d,e,f){a=new shaka.text.Cue(a,b,"");c&&a.textDecoration.push(shaka.text.Cue.textDecoration.UNDERLINE);d&&(a.fontStyle=shaka.text.Cue.fontStyle.ITALIC);a.color=e;a.backgroundColor=f;return a}static createLineBreakCue(a,b){a=new shaka.text.Cue(a,b,"");a.lineBreak=!0;return a}};
shaka.cea.CeaUtils.StyledChar=class{constructor(a,b,c,d,e){this.character_=a;this.underline_=b;this.italics_=c;this.backgroundColor_=d;this.textColor_=e}getChar(){return this.character_}isUnderlined(){return this.underline_}isItalicized(){return this.italics_}getBackgroundColor(){return this.backgroundColor_}getTextColor(){return this.textColor_}};shaka.cea.CeaUtils.DEFAULT_BG_COLOR="black";shaka.cea.CeaUtils.DEFAULT_TXT_COLOR="white";shaka.cea.CeaUtils.H264_NALU_TYPE_SEI=6;
shaka.cea.CeaUtils.H265_PREFIX_NALU_TYPE_SEI=39;shaka.cea.CeaUtils.H265_SUFFIX_NALU_TYPE_SEI=40;shaka.cea.CeaUtils.H266_PREFIX_NALU_TYPE_SEI=23;shaka.cea.CeaUtils.H266_SUFFIX_NALU_TYPE_SEI=24;shaka.cea.CeaUtils.DEFAULT_TIMESCALE_VALUE=9E4;shaka.cea.Cea608Memory=class{constructor(a,b){this.rows_=[];this.row_=1;this.scrollRows_=0;this.fieldNum_=a;this.channelNum_=b;this.italics_=this.underline_=!1;this.textColor_=shaka.cea.CeaUtils.DEFAULT_TXT_COLOR;this.backgroundColor_=shaka.cea.CeaUtils.DEFAULT_BG_COLOR;this.indent_=this.offset_=null;this.reset()}forceEmit(a,b){const c=shaka.cea.Cea608Memory,d=`CC${(this.fieldNum_<<1|this.channelNum_)+1}`,e=new shaka.text.Cue(a,b,"");e.lineInterpretation=shaka.text.Cue.lineInterpretation.PERCENTAGE;
let f=c.ROW_TO_LINE_CONVERSION_.get(this.row_);f&&(e.line=f);this.indent_!=null&&this.offset_!=null&&(e.position=10+Math.min(70,this.indent_*10)+this.offset_*2.5);(a=shaka.cea.CeaUtils.getParsedCaption(e,d,this.rows_,a,b))&&this.row_+a.cue.nestedCues.length-3>15&&(f=c.ROW_TO_LINE_CONVERSION_.get(this.row_+3-a.cue.nestedCues.length))&&(e.line=f);return a}reset(){this.resetAllRows();this.row_=1}getRow(){return this.row_}setRow(a){this.row_=a}getScrollSize(){return this.scrollRows_}setScrollSize(a){this.scrollRows_=
a}addChar(a,b){if(!(b<32||b>127)){var c="";switch(a){case shaka.cea.Cea608Memory.CharSet.BASIC_NORTH_AMERICAN:c=shaka.cea.Cea608Memory.CharSet.BasicNorthAmericanChars.has(b)?shaka.cea.Cea608Memory.CharSet.BasicNorthAmericanChars.get(b):String.fromCharCode(b);break;case shaka.cea.Cea608Memory.CharSet.SPECIAL_NORTH_AMERICAN:c=shaka.cea.Cea608Memory.CharSet.SpecialNorthAmericanChars.get(b);break;case shaka.cea.Cea608Memory.CharSet.SPANISH_FRENCH:this.eraseChar();c=shaka.cea.Cea608Memory.CharSet.ExtendedSpanishFrench.get(b);
break;case shaka.cea.Cea608Memory.CharSet.PORTUGUESE_GERMAN:this.eraseChar(),c=shaka.cea.Cea608Memory.CharSet.ExtendedPortugueseGerman.get(b)}c&&(a=new shaka.cea.CeaUtils.StyledChar(c,this.underline_,this.italics_,this.backgroundColor_,this.textColor_),this.rows_[this.row_].push(a))}}eraseChar(){this.rows_[this.row_].pop()}moveRows(a,b,c){if(!(b<0||a<0))if(a>=b)for(--c;c>=0;c--)this.rows_[a+c]=this.rows_[b+c].map(d=>d);else for(let d=0;d<c;d++)this.rows_[a+d]=this.rows_[b+d].map(e=>e)}resetRows(a,
b){for(let c=0;c<=b;c++)this.rows_[a+c]=[]}resetAllRows(){this.resetRows(0,shaka.cea.Cea608Memory.CC_ROWS)}eraseBuffer(){this.row_=this.scrollRows_>0?this.scrollRows_:0;this.resetAllRows()}setUnderline(a){this.underline_=a}setItalics(a){this.italics_=a}setTextColor(a){this.textColor_=a}setBackgroundColor(a){this.backgroundColor_=a}setOffset(a){this.offset_=a}setIndent(a){this.indent_=a}};shaka.cea.Cea608Memory.CC_ROWS=15;
shaka.cea.Cea608Memory.CharSet={BASIC_NORTH_AMERICAN:0,SPECIAL_NORTH_AMERICAN:1,SPANISH_FRENCH:2,PORTUGUESE_GERMAN:3};shaka.cea.Cea608Memory.CharSet.BasicNorthAmericanChars=new Map([[39,"\u2019"],[42,"\u00e1"],[92,"\u00e9"],[92,"\u00e9"],[94,"\u00ed"],[95,"\u00f3"],[96,"\u00fa"],[123,"\u00e7"],[124,"\u00f7"],[125,"\u00d1"],[126,"\u00f1"],[127,"\u2588"]]);
shaka.cea.Cea608Memory.CharSet.SpecialNorthAmericanChars=new Map([[48,"\u00ae"],[49,"\u00b0"],[50,"\u00bd"],[51,"\u00bf"],[52,"\u2122"],[53,"\u00a2"],[54,"\u00a3"],[55,"\u266a"],[56,"\u00e0"],[57," "],[58,"\u00e8"],[59,"\u00e2"],[60,"\u00ea"],[61,"\u00ee"],[62,"\u00f4"],[63,"\u00fb"]]);
shaka.cea.Cea608Memory.CharSet.ExtendedSpanishFrench=new Map([[32,"\u00c1"],[33,"\u00c9"],[34,"\u00d3"],[35,"\u00da"],[36,"\u00dc"],[37,"\u00fc"],[38,"\u2018"],[39,"\u00a1"],[40,"*"],[41,"'"],[42,"\u2500"],[43,"\u00a9"],[44,"\u2120"],[45,"\u00b7"],[46,"\u201c"],[47,"\u201d"],[48,"\u00c0"],[49,"\u00c2"],[50,"\u00c7"],[51,"\u00c8"],[52,"\u00ca"],[53,"\u00cb"],[54,"\u00eb"],[55,"\u00ce"],[56,"\u00cf"],[57,"\u00ef"],[58,"\u00d4"],[59,"\u00d9"],[60,"\u00f9"],[61,"\u00db"],[62,"\u00ab"],[63,"\u00bb"]]);
shaka.cea.Cea608Memory.CharSet.ExtendedPortugueseGerman=new Map([[32,"\u00c3"],[33,"\u00e3"],[34,"\u00cd"],[35,"\u00cc"],[36,"\u00ec"],[37,"\u00d2"],[38,"\u00f2"],[39,"\u00d5"],[40,"\u00f5"],[41,"{"],[42,"}"],[43,"\\"],[44,"^"],[45,"_"],[46,"|"],[47,"~"],[48,"\u00c4"],[49,"\u00e4"],[50,"\u00d6"],[51,"\u00f6"],[52,"\u00df"],[53,"\u00a5"],[54,"\u00a4"],[55,"\u2502"],[56,"\u00c5"],[57,"\u00e5"],[58,"\u00d8"],[59,"\u00f8"],[60,"\u250c"],[61,"\u2510"],[62,"\u2514"],[63,"\u2518"]]);
shaka.cea.Cea608Memory.ROW_TO_LINE_CONVERSION_=new Map([[1,10],[2,15.33],[3,20.66],[4,26],[5,31.33],[6,36.66],[7,42],[8,47.33],[9,52.66],[10,58],[11,63.33],[12,68.66],[13,74],[14,79.33],[15,84.66]]);shaka.cea.Cea608DataChannel=class{constructor(a,b){this.type_=shaka.cea.Cea608DataChannel.CaptionType.NONE;this.text_=new shaka.cea.Cea608Memory(a,b);this.displayedMemory_=new shaka.cea.Cea608Memory(a,b);this.curBuf_=this.nonDisplayedMemory_=new shaka.cea.Cea608Memory(a,b);this.prevEndTime_=0;this.lastCp_=null}reset(){this.type_=shaka.cea.Cea608DataChannel.CaptionType.NONE;this.curBuf_=this.nonDisplayedMemory_;this.lastCp_=null;this.displayedMemory_.reset();this.nonDisplayedMemory_.reset();this.text_.reset()}firstPts(a){this.prevEndTime_=
a}pacToRow_(a,b){return[11,11,1,2,3,4,12,13,14,15,5,6,7,8,9,10][(a&7)<<1|b>>5&1]}controlPac_(a,b){a=this.pacToRow_(a,b);let c=shaka.cea.CeaUtils.DEFAULT_TXT_COLOR,d=!1,e=null;var f=b>95?b-96:b-64;f<=13?c=shaka.cea.Cea608DataChannel.TEXT_COLORS[Math.floor(f/2)]:f<=15?d=!0:e=Math.floor((f-16)/2);b=(b&1)===1;if(this.type_!==shaka.cea.Cea608DataChannel.CaptionType.TEXT){f=this.curBuf_;if(this.type_===shaka.cea.Cea608DataChannel.CaptionType.ROLLUP&&a!==f.getRow()){const g=1+f.getRow()-f.getScrollSize(),
h=1+a-f.getScrollSize();f.moveRows(h,g,f.getScrollSize());f.resetRows(0,h-1);f.resetRows(a+1,shaka.cea.Cea608Memory.CC_ROWS-a)}f.setRow(a);f.setUnderline(b);f.setItalics(d);f.setTextColor(c);f.setIndent(e);f.setBackgroundColor(shaka.cea.CeaUtils.DEFAULT_BG_COLOR)}}controlMidrow_(a){this.curBuf_.setUnderline(!1);this.curBuf_.setItalics(!1);this.curBuf_.setTextColor(shaka.cea.CeaUtils.DEFAULT_TXT_COLOR);this.curBuf_.addChar(shaka.cea.Cea608Memory.CharSet.BASIC_NORTH_AMERICAN,32);let b,c=!1;b=shaka.cea.Cea608DataChannel.TEXT_COLORS[(a&
14)>>1];b==="white_italics"&&(b="white",c=!0);this.curBuf_.setUnderline((a&1)===1);this.curBuf_.setItalics(c);this.curBuf_.setTextColor(b)}controlBackgroundAttribute_(a,b){let c=shaka.cea.CeaUtils.DEFAULT_BG_COLOR;(a&7)===0&&(c=shaka.cea.Cea608DataChannel.BG_COLORS[(b&14)>>1]);this.curBuf_.setBackgroundColor(c)}controlMiscellaneous_(a){const b=shaka.cea.Cea608DataChannel.MiscCmd_,c=a.pts;let d=null;switch(a.ccData2){case b.RCL:this.controlRcl_();break;case b.BS:this.controlBs_();break;case b.AOD:case b.AON:break;
case b.DER:break;case b.RU2:d=this.controlRu_(2,c);break;case b.RU3:d=this.controlRu_(3,c);break;case b.RU4:d=this.controlRu_(4,c);break;case b.FON:this.controlFon_();break;case b.RDC:this.controlRdc_(c);break;case b.TR:this.controlTr_();break;case b.RTD:this.controlRtd_();break;case b.EDM:d=this.controlEdm_(c);break;case b.CR:d=this.controlCr_(c);break;case b.ENM:this.controlEnm_();break;case b.EOC:d=this.controlEoc_(c)}return d}controlCr_(a){const b=this.curBuf_;if(this.type_!==shaka.cea.Cea608DataChannel.CaptionType.ROLLUP)return null;
const c=b.forceEmit(this.prevEndTime_,a),d=b.getRow()-b.getScrollSize()+1;b.moveRows(d-1,d,b.getScrollSize());b.resetRows(0,d-1);b.resetRows(b.getRow(),shaka.cea.Cea608Memory.CC_ROWS-b.getRow());this.prevEndTime_=a;return c}controlRu_(a,b){const c=this.curBuf_=this.displayedMemory_;let d=null;this.type_!==shaka.cea.Cea608DataChannel.CaptionType.ROLLUP&&this.type_!==shaka.cea.Cea608DataChannel.CaptionType.TEXT&&(d=c.forceEmit(this.prevEndTime_,b),this.displayedMemory_.eraseBuffer(),this.nonDisplayedMemory_.eraseBuffer(),
c.setRow(shaka.cea.Cea608Memory.CC_ROWS));this.type_=shaka.cea.Cea608DataChannel.CaptionType.ROLLUP;c.setScrollSize(a);return d}controlFon_(){this.curBuf_.addChar(shaka.cea.Cea608Memory.CharSet.BASIC_NORTH_AMERICAN,32)}controlEdm_(a){const b=this.displayedMemory_;let c=null;this.type_!==shaka.cea.Cea608DataChannel.CaptionType.TEXT&&(c=b.forceEmit(this.prevEndTime_,a));b.resetAllRows();return c}controlRdc_(a){this.type_=shaka.cea.Cea608DataChannel.CaptionType.PAINTON;this.curBuf_=this.displayedMemory_;
this.curBuf_.setScrollSize(0);this.prevEndTime_=a}controlEnm_(){this.nonDisplayedMemory_.resetAllRows()}controlEoc_(a){let b=null;this.type_!==shaka.cea.Cea608DataChannel.CaptionType.TEXT&&(b=this.displayedMemory_.forceEmit(this.prevEndTime_,a));const c=this.nonDisplayedMemory_;this.nonDisplayedMemory_=this.displayedMemory_;this.displayedMemory_=c;this.controlRcl_();this.prevEndTime_=a;return b}controlRcl_(){this.type_=shaka.cea.Cea608DataChannel.CaptionType.POPON;this.curBuf_=this.nonDisplayedMemory_;
this.curBuf_.setScrollSize(0)}controlBs_(){this.curBuf_.eraseChar()}controlTr_(){this.text_.reset();this.controlRtd_()}controlRtd_(){shaka.log.warnOnce("Cea608DataChannel","CEA-608 text mode entered, but is unsupported");this.curBuf_=this.text_;this.type_=shaka.cea.Cea608DataChannel.CaptionType.TEXT}handleBasicNorthAmericanChar(a,b){this.curBuf_.addChar(shaka.cea.Cea608Memory.CharSet.BASIC_NORTH_AMERICAN,a);this.curBuf_.addChar(shaka.cea.Cea608Memory.CharSet.BASIC_NORTH_AMERICAN,b)}handleExtendedWesternEuropeanChar_(a,
b){this.curBuf_.addChar(a&1?shaka.cea.Cea608Memory.CharSet.PORTUGUESE_GERMAN:shaka.cea.Cea608Memory.CharSet.SPANISH_FRENCH,b)}handleOffset_(a){this.curBuf_.setOffset(a)}handleControlCode(a){const b=a.ccData1,c=a.ccData2;if(this.lastCp_===(b<<8|c))return this.lastCp_=null;this.lastCp_=b<<8|c;if(this.isPAC_(b,c))this.controlPac_(b,c);else if(this.isMidrowStyleChange_(b,c))this.controlMidrow_(c);else if(this.isBackgroundAttribute_(b,c))this.controlBackgroundAttribute_(b,c);else if(this.isSpecialNorthAmericanChar_(b,
c))this.curBuf_.addChar(shaka.cea.Cea608Memory.CharSet.SPECIAL_NORTH_AMERICAN,c);else if(this.isExtendedWesternEuropeanChar_(b,c))this.handleExtendedWesternEuropeanChar_(b,c);else{if(this.isMiscellaneous_(b,c))return this.controlMiscellaneous_(a);this.isOffset_(b,c)&&this.handleOffset_(c-32)}return null}isMiscellaneous_(a,b){return(a&246)===20&&(b&240)===32}isOffset_(a,b){return(a==23||a==31)&&b>=33&&b<=35}isPAC_(a,b){return(a&240)===16&&(b&192)===64}isMidrowStyleChange_(a,b){return(a&247)===17&&
(b&240)===32}isBackgroundAttribute_(a,b){return(a&247)===16&&(b&240)===32||(a&247)===23&&(b&255)===45}isSpecialNorthAmericanChar_(a,b){return(a&247)===17&&(b&240)===48}isExtendedWesternEuropeanChar_(a,b){return(a&246)===18&&(b&224)===32}static isControlCode(a){return(a&112)===16}static isXdsControlCode(a){return a>=1&&a<=15}};shaka.cea.Cea608DataChannel.MiscCmd_={RCL:32,BS:33,AOD:34,AON:35,DER:36,RU2:37,RU3:38,RU4:39,FON:40,RDC:41,TR:42,RTD:43,EDM:44,CR:45,ENM:46,EOC:47};
shaka.cea.Cea608DataChannel.CaptionType={NONE:0,POPON:1,PAINTON:2,ROLLUP:3,TEXT:4};shaka.cea.Cea608DataChannel.BG_COLORS="black green blue cyan red yellow magenta black".split(" ");shaka.cea.Cea608DataChannel.TEXT_COLORS="white green blue cyan red yellow magenta white_italics".split(" ");shaka.cea.Cea708Window=class{constructor(a,b){this.parentService_=b;this.windowNum_=a;this.relativeToggle_=this.visible_=!1;this.colCount_=this.rowCount_=this.anchorId_=this.verticalAnchor_=this.horizontalAnchor_=0;this.justification_=shaka.cea.Cea708Window.TextJustification.CENTER;this.memory_=[];this.col_=this.row_=this.startTime_=0;this.underline_=this.italics_=!1;this.textColor_=shaka.cea.CeaUtils.DEFAULT_TXT_COLOR;this.backgroundColor_=shaka.cea.CeaUtils.DEFAULT_BG_COLOR;this.resetMemory()}defineWindow(a,
b,c,d,e,f,g){this.visible_=a;this.verticalAnchor_=b;this.horizontalAnchor_=c;this.anchorId_=d;this.relativeToggle_=e;this.rowCount_=f;this.colCount_=g}resetMemory(){this.memory_=[];for(let a=0;a<shaka.cea.Cea708Window.MAX_ROWS;a++)this.memory_.push(this.createNewRow_())}createNewRow_(){const a=[];for(let b=0;b<shaka.cea.Cea708Window.MAX_COLS;b++)a.push(null);return a}setCharacter(a){this.isPenInBounds_()&&(a=new shaka.cea.CeaUtils.StyledChar(a,this.underline_,this.italics_,this.backgroundColor_,this.textColor_),
this.memory_[this.row_][this.col_]=a,this.col_++)}backspace(){!this.isPenInBounds_()||this.col_<=0&&this.row_<=0||(this.col_<=0?(this.col_=this.colCount_-1,this.row_--):this.col_--,this.memory_[this.row_][this.col_]=null)}isPenInBounds_(){const a=this.col_<this.colCount_&&this.col_>=0;return this.row_<this.rowCount_&&this.row_>=0&&a}isVisible(){return this.visible_}moveUpRows_(a){let b=0;for(var c=a;c<shaka.cea.Cea708Window.MAX_ROWS;c++,b++)this.memory_[b]=this.memory_[c];for(c=0;c<a;c++,b++)this.memory_[b]=
this.createNewRow_()}carriageReturn(){this.row_+1>=this.rowCount_?this.moveUpRows_(1):this.row_++;this.col_=0}horizontalCarriageReturn(){this.memory_[this.row_]=this.createNewRow_();this.col_=0}forceEmit(a,b){b=`svc${b}`;const c=shaka.cea.Cea708Window.TextJustification,d=new shaka.text.Cue(this.startTime_,a,"");d.textAlign=this.justification_===c.LEFT?shaka.text.Cue.textAlign.LEFT:this.justification_===c.RIGHT?shaka.text.Cue.textAlign.RIGHT:shaka.text.Cue.textAlign.CENTER;this.adjustRegion_(d.region);
(b=shaka.cea.CeaUtils.getParsedCaption(d,b,this.memory_,this.startTime_,a))&&this.setStartTime(a);return b}setPenLocation(a,b){this.row_=a;this.col_=b}setPenBackgroundColor(a){this.backgroundColor_=a}setPenTextColor(a){this.textColor_=a}setPenUnderline(a){this.underline_=a}setPenItalics(a){this.italics_=a}resetPen(){this.col_=this.row_=0;this.italics_=this.underline_=!1;this.textColor_=shaka.cea.CeaUtils.DEFAULT_TXT_COLOR;this.backgroundColor_=shaka.cea.CeaUtils.DEFAULT_BG_COLOR}setJustification(a){this.justification_=
a}display(){this.visible_=!0}hide(){this.visible_=!1}toggle(){this.visible_=!this.visible_}setStartTime(a){this.startTime_=a}adjustRegion_(a){this.parentService_&&(a.id+="svc"+this.parentService_);a.id+="win"+this.windowNum_;a.height=this.rowCount_;a.width=this.colCount_;a.heightUnits=shaka.text.CueRegion.units.LINES;a.widthUnits=shaka.text.CueRegion.units.LINES;a.viewportAnchorX=this.horizontalAnchor_;a.viewportAnchorY=this.verticalAnchor_;a.viewportAnchorUnits=this.relativeToggle_?shaka.text.CueRegion.units.PERCENTAGE:
shaka.text.CueRegion.units.LINES;const b=shaka.cea.Cea708Window.AnchorId;switch(this.anchorId_){case b.UPPER_LEFT:a.regionAnchorX=0;a.regionAnchorY=0;break;case b.UPPER_CENTER:a.regionAnchorX=50;a.regionAnchorY=0;break;case b.UPPER_RIGHT:a.regionAnchorX=100;a.regionAnchorY=0;break;case b.MIDDLE_LEFT:a.regionAnchorX=0;a.regionAnchorY=50;break;case b.MIDDLE_CENTER:a.regionAnchorX=50;a.regionAnchorY=50;break;case b.MIDDLE_RIGHT:a.regionAnchorX=100;a.regionAnchorY=50;break;case b.LOWER_LEFT:a.regionAnchorX=
0;a.regionAnchorY=100;break;case b.LOWER_CENTER:a.regionAnchorX=50;a.regionAnchorY=100;break;case b.LOWER_RIGHT:a.regionAnchorX=100,a.regionAnchorY=100}}};shaka.cea.Cea708Window.TextJustification={LEFT:0,RIGHT:1,CENTER:2,FULL:3};shaka.cea.Cea708Window.AnchorId={UPPER_LEFT:0,UPPER_CENTER:1,UPPER_RIGHT:2,MIDDLE_LEFT:3,MIDDLE_CENTER:4,MIDDLE_RIGHT:5,LOWER_LEFT:6,LOWER_CENTER:7,LOWER_RIGHT:8};shaka.cea.Cea708Window.MAX_COLS=42;shaka.cea.Cea708Window.MAX_ROWS=16;shaka.cea.DtvccPacketBuilder=class{constructor(){this.builtPackets_=[];this.currentPacketBeingBuilt_=null;this.bytesLeftToAddInCurrentPacket_=0}addByte(a){a.type===shaka.cea.DtvccPacketBuilder.DTVCC_PACKET_START?(this.bytesLeftToAddInCurrentPacket_=(a.value&63)*2-1,this.currentPacketBeingBuilt_=[]):this.currentPacketBeingBuilt_&&(this.bytesLeftToAddInCurrentPacket_>0&&(this.currentPacketBeingBuilt_.push(a),this.bytesLeftToAddInCurrentPacket_--),this.bytesLeftToAddInCurrentPacket_===0&&(a=new shaka.cea.DtvccPacket(this.currentPacketBeingBuilt_),
this.builtPackets_.push(a),this.currentPacketBeingBuilt_=null,this.bytesLeftToAddInCurrentPacket_=0))}getBuiltPackets(){return this.builtPackets_}clearBuiltPackets(){this.builtPackets_=[]}clear(){this.builtPackets_=[];this.currentPacketBeingBuilt_=[];this.bytesLeftToAddInCurrentPacket_=0}};
shaka.cea.DtvccPacket=class{constructor(a){this.pos_=0;this.packetData_=a}hasMoreData(){return this.pos_<this.packetData_.length}getPosition(){return this.pos_}readByte(){if(!this.hasMoreData())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.BUFFER_READ_OUT_OF_BOUNDS);return this.packetData_[this.pos_++]}skip(a){if(this.pos_+a>this.packetData_.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,
shaka.util.Error.Code.BUFFER_READ_OUT_OF_BOUNDS);this.pos_+=a}rewind(a){if(this.pos_-a<0)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.BUFFER_READ_OUT_OF_BOUNDS);this.pos_-=a}};shaka.cea.DtvccPacketBuilder.DTVCC_PACKET_DATA=2;shaka.cea.DtvccPacketBuilder.DTVCC_PACKET_START=3;shaka.cea.Cea708Service=class{constructor(a){this.serviceNumber_=a;this.windows_=[null,null,null,null,null,null,null,null];this.currentWindow_=null}handleCea708ControlCode(a){var b=a.readByte();let c=b.value;b=b.pts;if(c===shaka.cea.Cea708Service.EXT_CEA708_CTRL_CODE_BYTE1){const d=a.readByte();c=c<<16|d.value}if(c>=0&&c<=31)return this.handleC0_(a,c,b);if(c>=128&&c<=159)return this.handleC1_(a,c,b);c>=4096&&c<=4127?this.handleC2_(a,c&255):c>=4224&&c<=4255?this.handleC3_(a,c&255):c>=32&&c<=127?this.handleG0_(c):
c>=160&&c<=255?this.handleG1_(c):c>=4128&&c<=4223?this.handleG2_(c&255):c>=4256&&c<=4351&&this.handleG3_(c&255);return[]}handleG0_(a){this.currentWindow_&&(a===127?this.currentWindow_.setCharacter("\u266a"):this.currentWindow_.setCharacter(String.fromCharCode(a)))}handleG1_(a){this.currentWindow_&&this.currentWindow_.setCharacter(String.fromCharCode(a))}handleG2_(a){this.currentWindow_&&(shaka.cea.Cea708Service.G2Charset.has(a)?(a=shaka.cea.Cea708Service.G2Charset.get(a),this.currentWindow_.setCharacter(a)):
this.currentWindow_.setCharacter("_"))}handleG3_(a){this.currentWindow_&&(a!=160?this.currentWindow_.setCharacter("_"):this.currentWindow_.setCharacter("[CC]"))}handleC0_(a,b,c){if(!this.currentWindow_)return[];if(b==24)return b=a.readByte().value,c=a.readByte().value,b=(e=>e.map(f=>("0"+(f&255).toString(16)).slice(-2)).join(""))([b,c]),b=String.fromCharCode(parseInt(b,16)),this.currentWindow_.setCharacter(b),[];a=this.currentWindow_;let d=null;switch(b){case shaka.cea.Cea708Service.ASCII_BACKSPACE:a.backspace();
break;case shaka.cea.Cea708Service.ASCII_CARRIAGE_RETURN:a.isVisible()&&(d=a.forceEmit(c,this.serviceNumber_));a.carriageReturn();break;case shaka.cea.Cea708Service.ASCII_HOR_CARRIAGE_RETURN:a.isVisible()&&(d=a.forceEmit(c,this.serviceNumber_));a.horizontalCarriageReturn();break;case shaka.cea.Cea708Service.ASCII_FORM_FEED:a.isVisible()&&(d=a.forceEmit(c,this.serviceNumber_)),a.resetMemory(),a.setPenLocation(0,0)}return d?[d]:[]}handleC1_(a,b,c){if(b>=128&&b<=135)this.setCurrentWindow_(b&7);else{if(b===
136)return a=a.readByte().value,this.clearWindows_(a,c);if(b===137)a=a.readByte().value,this.displayWindows_(a,c);else{if(b===138)return a=a.readByte().value,this.hideWindows_(a,c);if(b===139)return a=a.readByte().value,this.toggleWindows_(a,c);if(b===140)return a=a.readByte().value,this.deleteWindows_(a,c);if(b===143)return this.reset_(c);b===144?this.setPenAttributes_(a):b===145?this.setPenColor_(a):b===146?this.setPenLocation_(a):b===151?this.setWindowAttributes_(a):b>=152&&b<=159&&this.defineWindow_(a,
(b&15)-8,c)}}return[]}handleC2_(a,b){b>=8&&b<=15?a.skip(1):b>=16&&b<=23?a.skip(2):b>=24&&b<=31&&a.skip(3)}handleC3_(a,b){b>=128&&b<=135?a.skip(4):b>=136&&b<=143&&a.skip(5)}setCurrentWindow_(a){this.windows_[a]&&(this.currentWindow_=this.windows_[a])}getSpecifiedWindowIds_(a){const b=[];for(let c=0;c<8;c++)(a&1)===1&&this.windows_[c]&&b.push(c),a>>=1;return b}clearWindows_(a,b){const c=[];for(const d of this.getSpecifiedWindowIds_(a)){a=this.windows_[d];if(a.isVisible()){const e=a.forceEmit(b,this.serviceNumber_);
e&&c.push(e)}a.resetMemory()}return c}displayWindows_(a,b){for(const c of this.getSpecifiedWindowIds_(a))a=this.windows_[c],a.isVisible()||a.setStartTime(b),a.display()}hideWindows_(a,b){let c=null;for(const d of this.getSpecifiedWindowIds_(a))a=this.windows_[d],a.isVisible()&&(c=a.forceEmit(b,this.serviceNumber_)),a.hide();return c?[c]:[]}toggleWindows_(a,b){let c=null;for(const d of this.getSpecifiedWindowIds_(a))a=this.windows_[d],a.isVisible()?c=a.forceEmit(b,this.serviceNumber_):a.setStartTime(b),
a.toggle();return c?[c]:[]}deleteWindows_(a,b){const c=[];for(const d of this.getSpecifiedWindowIds_(a))a=this.windows_[d],a.isVisible()&&(a=a.forceEmit(b,this.serviceNumber_))&&c.push(a),this.windows_[d]=null;return c}reset_(a){a=this.deleteWindows_(255,a);this.clear();return a}clear(){this.currentWindow_=null;this.windows_=[null,null,null,null,null,null,null,null]}setPenAttributes_(a){a.skip(1);a=a.readByte().value;if(this.currentWindow_){var b=(a&64)>0;this.currentWindow_.setPenItalics((a&128)>
0);this.currentWindow_.setPenUnderline(b)}}setPenColor_(a){var b=a.readByte().value,c=a.readByte().value;a.skip(1);if(this.currentWindow_){a=c&3;var d=(c&12)>>2;c=(c&48)>>4;b=this.rgbColorToHex_((b&48)>>4,(b&12)>>2,b&3);a=this.rgbColorToHex_(c,d,a);this.currentWindow_.setPenTextColor(b);this.currentWindow_.setPenBackgroundColor(a)}}setPenLocation_(a){const b=a.readByte().value;a=a.readByte().value;this.currentWindow_&&this.currentWindow_.setPenLocation(b&15,a&63)}setWindowAttributes_(a){a.skip(1);
a.skip(1);const b=a.readByte().value;a.skip(1);this.currentWindow_&&this.currentWindow_.setJustification(b&3)}defineWindow_(a,b,c){const d=this.windows_[b]!==null;if(!d){var e=new shaka.cea.Cea708Window(b,this.serviceNumber_);e.setStartTime(c);this.windows_[b]=e}var f=a.readByte().value,g=a.readByte().value;c=a.readByte().value;var h=a.readByte().value;e=a.readByte().value;a=a.readByte().value;f=(f&32)>0;const k=g&127;g=(g&128)>0;const l=(h&15)+1;h=(h&240)>>4;e=(e&63)+1;d&&(a&7)===0||this.windows_[b].resetPen();
this.windows_[b].defineWindow(f,k,c,h,g,l,e);this.currentWindow_=this.windows_[b]}rgbColorToHex_(a,b,c){const d={0:0,1:0,2:1,3:1};a=d[a];b=d[b];c=d[c];return shaka.cea.Cea708Service.Colors[a<<2|b<<1|c]}};shaka.cea.Cea708Service.ASCII_BACKSPACE=8;shaka.cea.Cea708Service.ASCII_FORM_FEED=12;shaka.cea.Cea708Service.ASCII_CARRIAGE_RETURN=13;shaka.cea.Cea708Service.ASCII_HOR_CARRIAGE_RETURN=14;shaka.cea.Cea708Service.EXT_CEA708_CTRL_CODE_BYTE1=16;
shaka.cea.Cea708Service.G2Charset=new Map([[32," "],[33,"\u00a0"],[37,"\u2026"],[42,"\u0160"],[44,"\u0152"],[48,"\u2588"],[49,"\u2018"],[50,"\u2019"],[51,"\u201c"],[52,"\u201d"],[53,"\u2022"],[57,"\u2122"],[58,"\u0161"],[60,"\u0153"],[61,"\u2120"],[63,"\u0178"],[118,"\u215b"],[119,"\u215c"],[120,"\u215d"],[121,"\u215e"],[122,"\u2502"],[123,"\u2510"],[124,"\u2514"],[125,"\u2500"],[126,"\u2518"],[127,"\u250c"]]);shaka.cea.Cea708Service.Colors="black blue green cyan red magenta yellow white".split(" ");shaka.cea.CeaDecoder=class{constructor(){this.cea608DataArray_=[];this.cea708DataArray_=[];this.dtvccPacketBuilder_=new shaka.cea.DtvccPacketBuilder;this.badFrames_=0;this.cea608ModeToStream_=new Map([["CC1",new shaka.cea.Cea608DataChannel(0,0)],["CC2",new shaka.cea.Cea608DataChannel(0,1)],["CC3",new shaka.cea.Cea608DataChannel(1,0)],["CC4",new shaka.cea.Cea608DataChannel(1,1)]]);this.currentField2Channel_=this.currentField1Channel_=0;this.serviceNumberToService_=new Map;this.waitingForFirstPacket_=
!0;this.streams_=new Set;this.reset()}clear(){shaka.log.debug("Clearing CEA decoder");this.badFrames_=0;this.cea608DataArray_=[];this.cea708DataArray_=[];this.dtvccPacketBuilder_.clear();this.reset();for(const a of this.serviceNumberToService_.values())a.clear()}reset(){shaka.log.debug("Resetting CEA decoder");this.currentField2Channel_=this.currentField1Channel_=0;for(const a of this.cea608ModeToStream_.values())a.reset();this.waitingForFirstPacket_=!0}extract(a,b){if(this.waitingForFirstPacket_){shaka.log.debug("Setting first pts value to",
b);for(var c of this.cea608ModeToStream_.values())c.firstPts(b);this.waitingForFirstPacket_=!1}a=new shaka.util.DataViewReader(a,shaka.util.DataViewReader.Endianness.BIG_ENDIAN);if(!(a.getLength()<shaka.cea.CeaDecoder.MIN_LENGTH)&&a.readUint8()===shaka.cea.CeaDecoder.USA_COUNTRY_CODE&&a.readUint16()===shaka.cea.CeaDecoder.ATSC_PROVIDER_CODE&&a.readUint32()===shaka.cea.CeaDecoder.ATSC1_USER_IDENTIFIER&&a.readUint8()===3&&(c=a.readUint8(),(c&64)!==0)){c&=31;a.skip(1);for(let e=0;e<c;e++){var d=a.readUint8();
const f=(d&4)>>2,g=a.readUint8(),h=a.readUint8();f&&(d&=3,d===shaka.cea.CeaDecoder.NTSC_CC_FIELD_1||d===shaka.cea.CeaDecoder.NTSC_CC_FIELD_2?this.cea608DataArray_.push({pts:b,type:d,ccData1:g,ccData2:h,order:this.cea608DataArray_.length}):(this.cea708DataArray_.push({pts:b,type:d,value:g,order:this.cea708DataArray_.length}),this.cea708DataArray_.push({pts:b,type:shaka.cea.DtvccPacketBuilder.DTVCC_PACKET_DATA,value:h,order:this.cea708DataArray_.length})))}}}decode(){const a=[];var b=(d,e)=>d.pts-e.pts||
d.order-e.order;this.cea608DataArray_.sort(b);this.cea708DataArray_.sort(b);for(var c of this.cea608DataArray_)(b=this.decodeCea608_(c))&&a.push(b);for(const d of this.cea708DataArray_)this.dtvccPacketBuilder_.addByte(d);c=this.dtvccPacketBuilder_.getBuiltPackets();for(const d of c)c=this.decodeCea708_(d),a.push(...c);this.dtvccPacketBuilder_.clearBuiltPackets();this.cea608DataArray_=[];this.cea708DataArray_=[];return a}decodeCea608_(a){var b=a.type;if(shaka.cea.Cea608DataChannel.isControlCode(a.ccData1)){var c=
a.ccData1>>3&1;b===0?this.currentField1Channel_=c:this.currentField2Channel_=c}b=`CC${(b<<1|(b?this.currentField2Channel_:this.currentField1Channel_))+1}`;c=this.cea608ModeToStream_.get(b);if(a.ccData1===255&&a.ccData2===255||!a.ccData1&&!a.ccData2||!this.isOddParity_(a.ccData1)||!this.isOddParity_(a.ccData2))return++this.badFrames_>=45&&this.reset(),null;this.badFrames_=0;a.ccData1&=127;a.ccData2&=127;if(shaka.cea.Cea608DataChannel.isXdsControlCode(a.ccData1)||!a.ccData1&&!a.ccData2)return null;
let d=null;shaka.cea.Cea608DataChannel.isControlCode(a.ccData1)?(this.streams_.add(b),d=c.handleControlCode(a)):c.handleBasicNorthAmericanChar(a.ccData1,a.ccData2);return d}decodeCea708_(a){const b=[];try{for(;a.hasMoreData();){const c=a.readByte().value;let d=(c&224)>>5;const e=c&31;d===7&&e!=0&&(d=a.readByte().value&63);if(d!=0){this.streams_.add("svc"+d);if(!this.serviceNumberToService_.has(d)){const h=new shaka.cea.Cea708Service(d);this.serviceNumberToService_.set(d,h)}const f=this.serviceNumberToService_.get(d),
g=a.getPosition();for(;a.getPosition()-g<e;){const h=f.handleCea708ControlCode(a);b.push(...h)}}}}catch(c){if(c instanceof shaka.util.Error&&c.code===shaka.util.Error.Code.BUFFER_READ_OUT_OF_BOUNDS)shaka.log.warnOnce("CEA708_INVALID_DATA","Buffer read out of bounds / invalid CEA-708 Data.");else throw c;}return b}isOddParity_(a){let b=0;for(;a;)b^=a&1,a>>=1;return b===1}getStreams(){return Array.from(this.streams_)}};goog.exportSymbol("shaka.cea.CeaDecoder",shaka.cea.CeaDecoder);
shaka.cea.CeaDecoder.ATSC_PROVIDER_CODE=49;shaka.cea.CeaDecoder.ATSC1_USER_IDENTIFIER=1195456820;shaka.cea.CeaDecoder.NTSC_CC_FIELD_1=0;shaka.cea.CeaDecoder.NTSC_CC_FIELD_2=1;shaka.cea.CeaDecoder.USA_COUNTRY_CODE=181;shaka.cea.CeaDecoder.MIN_LENGTH=8;shaka.media.ClosedCaptionParser.registerDecoder(()=>new shaka.cea.CeaDecoder);shaka.cea.SeiProcessor=class{process(a){const b=[];a=this.removeEmu(a);let c=0;for(;c<a.length;){let d=0;for(;a[c]==255;)d+=255,c++;d+=a[c++];let e=0;for(;a[c]==255;)e+=255,c++;e+=a[c++];d==4&&b.push(a.subarray(c,c+e));c+=e}return b}removeEmu(a){var b=a;let c=a=0;for(;c<b.length;)a==2&&b[c]==3?(a=0,b=[...b],b.splice(c,1),b=new Uint8Array(b)):b[c]==0?a++:a=0,c++;return b}};shaka.cea.Mp4CeaParser=class{constructor(){this.seiProcessor_=new shaka.cea.SeiProcessor;this.trackIdToTimescale_=new Map;this.defaultSampleSize_=this.defaultSampleDuration_=0;this.bitstreamFormat_=shaka.cea.Mp4CeaParser.BitstreamFormat.UNKNOWN}init(a){const b=shaka.util.Mp4Parser,c=shaka.cea.Mp4CeaParser.BitstreamFormat,d=[],e=[];(new b).boxes("moov trak mdia minf stbl mvex".split(" "),b.children).fullBox("trex",f=>{f=shaka.util.Mp4BoxParsers.parseTREX(f.reader);this.defaultSampleDuration_=f.defaultSampleDuration;
this.defaultSampleSize_=f.defaultSampleSize}).fullBox("tkhd",f=>{goog.asserts.assert(f.version!=null,"TKHD is a full box and should have a valid version.");f=shaka.util.Mp4BoxParsers.parseTKHD(f.reader,f.version);d.push(f.trackId)}).fullBox("mdhd",f=>{goog.asserts.assert(f.version!=null,"MDHD is a full box and should have a valid version.");f=shaka.util.Mp4BoxParsers.parseMDHD(f.reader,f.version);e.push(f.timescale)}).fullBox("stsd",b.sampleDescription).boxes("avc1 avc3 dvav dva1 hev1 hvc1 dvh1 dvhe vvc1 vvi1 dvc1 dvi1".split(" "),
f=>this.setBitstreamFormat_(f.name)).box("encv",b.visualSampleEntry).box("sinf",b.children).box("frma",f=>{({codec:f}=shaka.util.Mp4BoxParsers.parseFRMA(f.reader));this.setBitstreamFormat_(f)}).parse(a,!0,!0);if(!d.length||!e.length||d.length!=e.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_MP4_CEA);this.bitstreamFormat_==c.UNKNOWN&&shaka.log.alwaysWarn("Unable to determine bitstream format for CEA parsing!");d.forEach((f,
g)=>{this.trackIdToTimescale_.set(f,e[g])})}parse(a){const b=shaka.util.Mp4Parser;if(this.bitstreamFormat_==shaka.cea.Mp4CeaParser.BitstreamFormat.UNKNOWN)return[];const c=[];let d=0,e=[];(new b).box("moof",f=>{d=f.start;e=[];b.children(f)}).box("traf",f=>{e.push({baseMediaDecodeTime:null,defaultSampleDuration:this.defaultSampleDuration_,defaultSampleSize:this.defaultSampleSize_,parsedTRUNs:[],timescale:shaka.cea.CeaUtils.DEFAULT_TIMESCALE_VALUE});b.children(f)}).fullBox("trun",f=>{goog.asserts.assert(f.version!=
null&&f.flags!=null,"TRUN is a full box and should have a valid version & flags.");const g=e[e.length-1];f=shaka.util.Mp4BoxParsers.parseTRUN(f.reader,f.version,f.flags);g.parsedTRUNs.push(f)}).fullBox("tfhd",f=>{goog.asserts.assert(f.flags!=null,"TFHD is a full box and should have valid flags.");const g=e[e.length-1];f=shaka.util.Mp4BoxParsers.parseTFHD(f.reader,f.flags);g.defaultSampleDuration=f.defaultSampleDuration||this.defaultSampleDuration_;g.defaultSampleSize=f.defaultSampleSize||this.defaultSampleSize_;
f=f.trackId;this.trackIdToTimescale_.has(f)&&(g.timescale=this.trackIdToTimescale_.get(f))}).fullBox("tfdt",f=>{goog.asserts.assert(f.version!=null,"TFDT is a full box and should have a valid version.");const g=e[e.length-1];f=shaka.util.Mp4BoxParsers.parseTFDTInaccurate(f.reader,f.version);g.baseMediaDecodeTime=f.baseMediaDecodeTime}).box("mdat",f=>{const g=d-f.start-8,h=f.reader.getPosition();for(const k of e)k.baseMediaDecodeTime===null?shaka.log.alwaysWarn("Unable to find base media decode time for CEA captions!"):
(f.reader.seek(h),this.parseMdat_(f.reader,k.baseMediaDecodeTime,k.timescale,k.defaultSampleDuration,k.defaultSampleSize,g,k.parsedTRUNs,c))}).parse(a,!1,!0);return c}parseMdat_(a,b,c,d,e,f,g,h){const k=shaka.cea.Mp4CeaParser.BitstreamFormat,l=shaka.cea.CeaUtils;let m=0,n=e;var q=g.map(t=>t.sampleData);q=[].concat(...q);q.length&&(n=q[0].sampleSize||e);for(a.skip(f+g[0].dataOffset);a.hasMoreData();){f=a.readUint32();var p=a.readUint8(),r=null;r=!1;g=1;goog.asserts.assert(this.bitstreamFormat_!=k.UNKNOWN,
"Bitstream format should have been checked before now!");switch(this.bitstreamFormat_){case k.H264:r=p&31;r=r==l.H264_NALU_TYPE_SEI;break;case k.H265:g=2;a.skip(1);r=p>>1&63;r=r==l.H265_PREFIX_NALU_TYPE_SEI||r==l.H265_SUFFIX_NALU_TYPE_SEI;break;case k.H266:g=2;a.skip(1);r=p>>1&63;r=r==l.H266_PREFIX_NALU_TYPE_SEI||r==l.H266_SUFFIX_NALU_TYPE_SEI;break;default:return}if(r){p=0;m<q.length&&(p=q[m].sampleCompositionTimeOffset||0);p=(b+p)/c;g=a.readBytes(f-g,!1);for(const t of this.seiProcessor_.process(g))h.push({packet:t,
pts:p})}else try{a.skip(f-g)}catch(t){break}n-=f+4;n==0&&(b=m<q.length?b+(q[m].sampleDuration||d):b+d,m++,n=m<q.length?q[m].sampleSize||e:e)}}setBitstreamFormat_(a){shaka.cea.Mp4CeaParser.CodecBitstreamMap_.has(a)&&(this.bitstreamFormat_=shaka.cea.Mp4CeaParser.CodecBitstreamMap_.get(a))}};goog.exportSymbol("shaka.cea.Mp4CeaParser",shaka.cea.Mp4CeaParser);shaka.cea.Mp4CeaParser.BitstreamFormat={UNKNOWN:0,H264:1,H265:2,H266:3};
shaka.cea.Mp4CeaParser.CodecBitstreamMap_=(new Map).set("avc1",shaka.cea.Mp4CeaParser.BitstreamFormat.H264).set("avc3",shaka.cea.Mp4CeaParser.BitstreamFormat.H264).set("dvav",shaka.cea.Mp4CeaParser.BitstreamFormat.H264).set("dva1",shaka.cea.Mp4CeaParser.BitstreamFormat.H264).set("hev1",shaka.cea.Mp4CeaParser.BitstreamFormat.H265).set("hvc1",shaka.cea.Mp4CeaParser.BitstreamFormat.H265).set("dvh1",shaka.cea.Mp4CeaParser.BitstreamFormat.H265).set("dvhe",shaka.cea.Mp4CeaParser.BitstreamFormat.H265).set("vvc1",
shaka.cea.Mp4CeaParser.BitstreamFormat.H266).set("vvi1",shaka.cea.Mp4CeaParser.BitstreamFormat.H266).set("dvc1",shaka.cea.Mp4CeaParser.BitstreamFormat.H266).set("dvi1",shaka.cea.Mp4CeaParser.BitstreamFormat.H266);shaka.media.ClosedCaptionParser.registerParser("video/mp4",()=>new shaka.cea.Mp4CeaParser);shaka.cea.TsCeaParser=class{constructor(){this.seiProcessor_=new shaka.cea.SeiProcessor;this.tsParser_=null}init(a){}parse(a){const b=shaka.cea.CeaUtils;this.tsParser_?this.tsParser_.clearData():this.tsParser_=new shaka.util.TsParser;const c=[];a=shaka.util.BufferUtils.toUint8(a);if(!shaka.util.TsParser.probe(a))return c;var d=this.tsParser_.parse(a);a=d.getCodecs();d=d.getVideoNalus();const e=[];switch(a.video){case "avc":e.push(b.H264_NALU_TYPE_SEI);break;case "hvc":e.push(b.H265_PREFIX_NALU_TYPE_SEI),
e.push(b.H265_SUFFIX_NALU_TYPE_SEI)}if(!e.length)return c;for(const f of d)if(e.includes(f.type)&&f.time!=null)for(const g of this.seiProcessor_.process(f.data))c.push({packet:g,pts:f.time});return c}};goog.exportSymbol("shaka.cea.TsCeaParser",shaka.cea.TsCeaParser);shaka.media.ClosedCaptionParser.registerParser("video/mp2t",()=>new shaka.cea.TsCeaParser);shaka.drm.PlayReady=class{static parseMsProRecords_(a,b){const c=[];for(;b<a.byteLength-1;){const d=a.getUint16(b,!0);b+=2;const e=a.getUint16(b,!0);b+=2;if((e&1)!=0||e+b>a.byteLength)return shaka.log.warning("Malformed MS PRO object"),[];const f=shaka.util.BufferUtils.toUint8(a,b,e);c.push({type:d,value:f});b+=e}return c}static parseMsPro_(a){let b=0;const c=shaka.util.BufferUtils.toDataView(a),d=c.getUint32(b,!0);b+=4;return d!=a.byteLength?(shaka.log.warning("PlayReady Object with invalid length encountered."),
[]):shaka.drm.PlayReady.parseMsProRecords_(c,b+2)}static getLaurl_(a){const b=shaka.util.TXml;for(const c of b.getElementsByTagName(a,"DATA"))if(c.children)for(const d of c.children)if(d.tagName=="LA_URL")return shaka.util.TXml.getTextContents(d);return""}static getPlayReadyHeaderObject_(a){const b=shaka.drm.PlayReady.PLAYREADY_RECORD_TYPES;a=shaka.util.Uint8ArrayUtils.fromBase64(shaka.util.TXml.getTextContents(a));a=shaka.drm.PlayReady.parseMsPro_(a).filter(c=>c.type===b.RIGHTS_MANAGEMENT)[0];if(!a)return null;
a=shaka.util.StringUtils.fromUTF16(a.value,!0);return(a=shaka.util.TXml.parseXmlString(a,"WRMHEADER"))?a:null}static getLicenseUrl(a){try{const b=shaka.drm.PlayReady.getPlayReadyHeaderObject_(a);return b?shaka.drm.PlayReady.getLaurl_(b):""}catch(b){return""}}static getPlayReadyKID(a){var b=shaka.drm.PlayReady.getPlayReadyHeaderObject_(a);if(!b)return null;a=shaka.util.TXml;for(var c of a.getElementsByTagName(b,"DATA"))if(b=a.findChild(c,"KID"))return c=shaka.util.Uint8ArrayUtils.fromBase64(shaka.util.TXml.getTextContents(b)),
c=new Uint8Array([c[3],c[2],c[1],c[0],c[5],c[4],c[7],c[6],...c.slice(8)]),shaka.util.Uint8ArrayUtils.toHex(c);return null}};shaka.drm.PlayReady.PLAYREADY_RECORD_TYPES={RIGHTS_MANAGEMENT:1,RESERVED:2,EMBEDDED_LICENSE:3};shaka.dash={};
shaka.dash.ContentProtection=class{constructor(){this.psshToInitData_=new Map}release(){this.psshToInitData_.clear()}parseFromAdaptationSet(a,b,c){const d=shaka.dash.ContentProtection;var e=shaka.util.ManifestParserUtils;const f=this.parseElements_(a);let g=null;a=[];var h=[];let k=null;const l=new Set(f.map(n=>n.keyId));l.delete(null);let m="cenc";if(l.size>1)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_CONFLICTING_KEY_IDS);if(!b){h=
f.filter(n=>n.schemeUri==d.Aes128Protection_);if(h.length>1)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_CONFLICTING_AES_128);h.length&&(k=d.parseAes128_(h[0]));(h=f.find(n=>n.schemeUri==d.MP4Protection_))&&h.encryptionScheme&&(m=h.encryptionScheme);h=f.filter(n=>n.schemeUri==d.MP4Protection_?(goog.asserts.assert(!n.init||n.init.length,"Init data must be null or non-empty."),g=n.init||g,!1):n.schemeUri!=d.Aes128Protection_);
h.length&&(a=d.convertElements_(g,m,h,c,l),a.length==0&&(a=[e.createDrmInfo("",m,g)]))}if(f.length&&!k&&(b||!h.length)){a=[];for(const n of Object.values(c))shaka.drm.DrmUtils.isClearKeySystem(n)||(b=e.createDrmInfo(n,m,g),a.push(b))}if(e=Array.from(l)[0]||null)for(const n of a)for(const q of n.initData)q.keyId=e;return{defaultKeyId:e,defaultInit:g,drmInfos:a,aes128Info:k,firstRepresentation:!0}}parseFromRepresentation(a,b,c,d){const e=this.parseFromAdaptationSet(a,c,d);if(b.firstRepresentation){a=
b.drmInfos.length==1&&!b.drmInfos[0].keySystem;c=e.drmInfos.length==0;if(b.drmInfos.length==0||a&&!c)b.drmInfos=e.drmInfos;b.firstRepresentation=!1}else if(e.drmInfos.length>0&&(b.drmInfos=b.drmInfos.filter(f=>e.drmInfos.some(g=>g.keySystem==f.keySystem)),b.drmInfos.length==0))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_NO_COMMON_KEY_SYSTEM);return e.defaultKeyId||b.defaultKeyId}static getFairPlayLicenseUrl(a){if(shaka.drm.DrmUtils.isMediaKeysPolyfilled("apple"))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_MSE_ENCRYPTED_LEGACY_APPLE_MEDIA_KEYS_NOT_SUPPORTED);if(a=shaka.util.TXml.findChildNS(a.node,shaka.dash.ContentProtection.DashIfNamespaceUri_,"Laurl"))if(a=shaka.util.TXml.getTextContents(a))return a;return""}static getWidevineLicenseUrl(a){const b=shaka.util.StringUtils;var c=shaka.util.TXml.findChildNS(a.node,shaka.dash.ContentProtection.DashIfNamespaceUri_,"Laurl");return c&&(c=shaka.util.TXml.getTextContents(c))?c:(a=shaka.util.TXml.findChildNS(a.node,
"urn:microsoft","laurl"))?b.htmlUnescape(a.attributes.licenseUrl)||"":""}static getClearKeyLicenseUrl(a){var b=shaka.util.TXml.findChildNS(a.node,shaka.dash.ContentProtection.DashIfNamespaceUri_,"Laurl");return b&&(b=shaka.util.TXml.getTextContents(b))?b:(a=shaka.util.TXml.findChildNS(a.node,shaka.dash.ContentProtection.ClearKeyNamespaceUri_,"Laurl"))&&a.attributes.Lic_type==="EME-1.0"&&a&&(a=shaka.util.TXml.getTextContents(a))?a:""}static getPlayReadyLicenseUrl(a){var b=shaka.util.TXml,c=b.findChildNS(a.node,
shaka.dash.ContentProtection.DashIfNamespaceUri_,"Laurl");if(c&&(c=b.getTextContents(c)))return c;if((c=b.findChildNS(a.node,"urn:microsoft:playready","pro"))&&b.getTextContents(c))return shaka.drm.PlayReady.getLicenseUrl(c);if(a=b.findChildNS(a.node,shaka.dash.ContentProtection.CencNamespaceUri_,"pssh"))if(a=b.getTextContents(a))return a=shaka.util.Pssh.getPsshData(shaka.util.Uint8ArrayUtils.fromBase64(a)),a=shaka.util.Uint8ArrayUtils.toStandardBase64(a),b=b.parseXmlString("<pro>"+a+"</pro>"),goog.asserts.assert(b,
"Must have pro node"),shaka.drm.PlayReady.getLicenseUrl(b);return""}static getInitDataFromPro_(a){var b=shaka.util.TXml.findChildNS(a.node,"urn:microsoft:playready","pro");if(!b||!shaka.util.TXml.getTextContents(b))return null;var c=shaka.util.Uint8ArrayUtils;b=shaka.util.TXml.getTextContents(b);c=c.fromBase64(b);b=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);const d=new Set;return[{initData:shaka.util.Pssh.createPssh(c,b,d,0),initDataType:"cenc",keyId:a.keyId}]}static getInitDataClearKey_(a,
b){if(b.size==0)return null;const c=new Uint8Array([16,119,239,236,192,178,77,2,172,227,60,30,82,226,251,75]),d=new Uint8Array([]);return[{initData:shaka.util.Pssh.createPssh(d,c,b,1),initDataType:"cenc",keyId:a.keyId}]}static convertElements_(a,b,c,d,e){const f=shaka.dash.ContentProtection,g=shaka.util.ManifestParserUtils,h=f.licenseUrlParsers_,k=[];for(const m of c)if(c=d[m.schemeUri]){goog.asserts.assert(!m.init||m.init.length,"Init data must be null or non-empty.");var l=f.getInitDataFromPro_(m);
let n=null;m.schemeUri===shaka.dash.ContentProtection.ClearKeySchemeUri_&&(n=f.getInitDataClearKey_(m,e));l=g.createDrmInfo(c,b,m.init||a||l||n);if(c=h.get(c))l.licenseServerUri=c(m);l.serverCertificateUri=f.getServerCertificateUri(m);k.push(l)}return k}static getServerCertificateUri(a){if(a=shaka.util.TXml.findChildNS(a.node,shaka.dash.ContentProtection.DashIfNamespaceUri_,"Certurl"))if(a=shaka.util.TXml.getTextContents(a))return a;return""}parseElements_(a){const b=[];for(const c of a)(a=this.parseElement_(c))&&
b.push(a);return b}parseElement_(a){var b=shaka.dash.ContentProtection.CencNamespaceUri_,c=shaka.util.TXml;let d=a.attributes.schemeIdUri,e=c.getAttributeNS(a,b,"default_KID");b=c.findChildrenNS(a,b,"pssh").map(c.getContents);c=a.attributes.value;if(!d)return shaka.log.error("Missing required schemeIdUri attribute on","ContentProtection element",a),null;d=d.toLowerCase();if(e&&(e=e.replace(/-/g,"").toLowerCase(),e.includes(" ")))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,
shaka.util.Error.Code.DASH_MULTIPLE_KEY_IDS_NOT_SUPPORTED);let f=[];try{f=b.map(g=>{if(!this.psshToInitData_.has(g)){const h=shaka.util.Uint8ArrayUtils.fromBase64(g);this.psshToInitData_.set(g,h)}return{initDataType:"cenc",initData:this.psshToInitData_.get(g),keyId:null}})}catch(g){throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_PSSH_BAD_ENCODING);}return{node:a,schemeUri:d,keyId:e,init:f.length>0?f:null,encryptionScheme:c}}static parseAes128_(a){if(!window.crypto||
!window.crypto.subtle)throw shaka.log.alwaysWarn("Web Crypto API is not available to decrypt AES-128. (Web Crypto only exists in secure origins like https)"),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.NO_WEB_CRYPTO_API);var b=shaka.util.TXml.findChildNS(a.node,"urn:mpeg:dash:schema:sea:2012","SegmentEncryption");if(!b)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_UNSUPPORTED_AES_128);
if(b.attributes.schemeIdUri!="urn:mpeg:dash:sea:aes128-cbc:2013")throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_UNSUPPORTED_AES_128);b=shaka.util.TXml.findChildNS(a.node,"urn:mpeg:dash:schema:sea:2012","CryptoPeriod");if(!b)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_UNSUPPORTED_AES_128);a=b.attributes.IV;b=shaka.util.StringUtils.htmlUnescape(b.attributes.keyUriTemplate);
if(!a||!b)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_UNSUPPORTED_AES_128);a=shaka.util.Uint8ArrayUtils.fromHex(a.substr(2));if(a.byteLength!=16)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.AES_128_INVALID_IV_LENGTH);return{keyUri:b,iv:a}}};
shaka.dash.ContentProtection.licenseUrlParsers_=(new Map).set("com.apple.fps",shaka.dash.ContentProtection.getFairPlayLicenseUrl).set("com.widevine.alpha",shaka.dash.ContentProtection.getWidevineLicenseUrl).set("com.microsoft.playready",shaka.dash.ContentProtection.getPlayReadyLicenseUrl).set("com.microsoft.playready.recommendation",shaka.dash.ContentProtection.getPlayReadyLicenseUrl).set("com.microsoft.playready.software",shaka.dash.ContentProtection.getPlayReadyLicenseUrl).set("com.microsoft.playready.hardware",
shaka.dash.ContentProtection.getPlayReadyLicenseUrl).set("org.w3.clearkey",shaka.dash.ContentProtection.getClearKeyLicenseUrl);shaka.dash.ContentProtection.MP4Protection_="urn:mpeg:dash:mp4protection:2011";shaka.dash.ContentProtection.Aes128Protection_="urn:mpeg:dash:sea:2012";shaka.dash.ContentProtection.CencNamespaceUri_="urn:mpeg:cenc:2013";shaka.dash.ContentProtection.ClearKeyNamespaceUri_="http://dashif.org/guidelines/clearKey";shaka.dash.ContentProtection.ClearKeySchemeUri_="urn:uuid:e2719d58-a985-b3c9-781a-b030af78d30e";
shaka.dash.ContentProtection.DashIfNamespaceUri_="https://dashif.org/CPS";shaka.dash.MpdUtils=class{static fillUriTemplate(a,b,c,d,e,f){const g=(new Map).set("RepresentationID",b).set("Number",c).set("SubNumber",d).set("Bandwidth",e).set("Time",f);return a.replace(/\$(RepresentationID|Number|SubNumber|Bandwidth|Time)?(?:%0([0-9]+)([diouxX]))?\$/g,(h,k,l,m)=>{if(h=="$$")return"$";let n=g.get(k);goog.asserts.assert(n!==void 0,"Unrecognized identifier");if(n==null)return shaka.log.warning("URL template does not have an available substitution for ",'identifier "'+k+'":',a),
h;k=="RepresentationID"&&l&&(shaka.log.warning("URL template should not contain a width specifier for identifier",'"RepresentationID":',a),l=void 0);k=="Time"&&typeof n!="bigint"&&(goog.asserts.assert(typeof n=="number","Time value should be a number or bigint!"),Math.abs(n-Math.round(n))>=.2&&shaka.log.alwaysWarn("Calculated $Time$ values must be close to integers"),n=Math.round(n));switch(m){case void 0:case "d":case "i":case "u":h=n.toString();break;case "o":h=n.toString(8);break;case "x":h=n.toString(16);
break;case "X":h=n.toString(16).toUpperCase();break;default:goog.asserts.assert(!1,"Unhandled format specifier"),h=n.toString()}l=window.parseInt(l,10)||1;return Array(Math.max(0,l-h.length)+1).join("0")+h})}static createTimeline(a,b,c,d,e){goog.asserts.assert(b>0&&b<Infinity,"timescale must be a positive, finite integer");goog.asserts.assert(d>0,"period duration must be a positive integer");const f=shaka.util.TXml,g=[];var h=-c;for(let q=0;q<a.length;++q){var k=a[q],l=a[q+1],m=f.parseAttr(k,"t",
f.parseNonNegativeInt);const p=f.parseAttr(k,"d",f.parseNonNegativeInt);var n=f.parseAttr(k,"r",f.parseInt);const r=f.parseAttr(k,"k",f.parseInt)||0;m!=null&&(m-=c);if(!p){shaka.log.warning('"S" element must have a duration: ignoring this element.',k);continue}m=m!=null?m:h;n=n||0;if(n<0)if(l){l=f.parseAttr(l,"t",f.parseNonNegativeInt);if(l==null){shaka.log.warning('An "S" element cannot have a negative repeat','if the next "S" element does not have a valid start time:','ignoring the remaining "S" elements.',
k);break}else if(m>=l){shaka.log.warning('An "S" element cannot have a negative repeat if its start ','time exceeds the next "S" element\'s start time:','ignoring the remaining "S" elements.',k);break}n=Math.ceil((l-m)/p)-1}else{if(d==Infinity){shaka.log.warning('The last "S" element cannot have a negative repeat',"if the Period has an infinite duration:",'ignoring the last "S" element.',k);break}else if(m/b>=d){shaka.log.warning('The last "S" element cannot have a negative repeat',"if its start time exceeds the Period's duration:",
'ignoring the last "S" element.',k);break}n=Math.ceil((d*b-m)/p)-1}g.length>0&&m!=h&&(Math.abs((m-h)/b)>=shaka.util.ManifestParserUtils.GAP_OVERLAP_TOLERANCE_SECONDS&&shaka.log.warning("SegmentTimeline contains a large gap/overlap:","the content may have errors in it.",k),g[g.length-1].end=m/b);for(k=0;k<=n;++k)h=m+p,g.push({start:m/b,unscaledStart:m,end:h/b,unscaledEnd:h,partialSegments:r,segmentPosition:g.length+e}),m=h}return g}static parseSegmentInfo(a,b){goog.asserts.assert(b(a.representation),
"There must be at least one element of the given type.");const c=shaka.dash.MpdUtils;var d=shaka.util.TXml,e=c.inheritAttribute(a,b,"timescale");let f=1;e&&(f=d.parsePositiveInt(e)||1);e=c.inheritAttribute(a,b,"duration");const g=(e=d.parsePositiveInt(e||""))?e/f:null;var h=c.inheritAttribute(a,b,"startNumber");const k=Number(c.inheritAttribute(a,b,"presentationTimeOffset"))||0;let l=d.parseNonNegativeInt(h||"");if(h==null||l==null)l=1;h=null;if(b=c.inheritChild(a,b,"SegmentTimeline"))d=d.findChildren(b,
"S"),h=c.createTimeline(d,f,k,a.periodInfo.duration||Infinity,l);return{timescale:f,unscaledSegmentDuration:e,segmentDuration:g,startNumber:l,scaledPresentationTimeOffset:k/f||0,unscaledPresentationTimeOffset:k,timeline:h}}static getNodes(a,b){const c=shaka.util.Functional;goog.asserts.assert(b(a.representation),"There must be at least one element of the given type.");return[b(a.representation),b(a.adaptationSet),b(a.period)].filter(c.isNotNull)}static inheritAttribute(a,b,c){a=shaka.dash.MpdUtils.getNodes(a,
b);b=null;for(const d of a)if(b=d.attributes[c])break;return b}static inheritChild(a,b,c){a=shaka.dash.MpdUtils.getNodes(a,b);b=shaka.util.TXml;let d=null;for(const e of a)if(d=b.findChild(e,c))break;return d}static handleXlinkInElement_(a,b,c,d,e,f){const g=shaka.util.TXml,h=shaka.util.Error;var k=shaka.util.ManifestParserUtils;const l=shaka.dash.MpdUtils.XlinkNamespaceUri_,m=g.getAttributeNS(a,l,"href"),n=g.getAttributeNS(a,l,"actuate")||"onRequest";for(const p of Object.keys(a.attributes)){const r=
p.split(":"),t=shaka.util.TXml.getKnownNameSpace(l);r[0]==t&&delete a.attributes[p]}if(f>=5)return shaka.util.AbortableOperation.failed(new h(h.Severity.CRITICAL,h.Category.MANIFEST,h.Code.DASH_XLINK_DEPTH_LIMIT));if(n!="onLoad")return shaka.util.AbortableOperation.failed(new h(h.Severity.CRITICAL,h.Category.MANIFEST,h.Code.DASH_UNSUPPORTED_XLINK_ACTUATE));const q=k.resolveUris([d],[m]);d=shaka.net.NetworkingEngine.RequestType.MANIFEST;k=shaka.net.NetworkingEngine.makeRequest(q,b);d=e.request(d,k);
goog.asserts.assert(d instanceof shaka.util.AbortableOperation,"Unexpected implementation of IAbortableOperation!");return d.chain(p=>{p=g.parseXml(p.data,a.tagName);if(!p)return shaka.util.AbortableOperation.failed(new h(h.Severity.CRITICAL,h.Category.MANIFEST,h.Code.DASH_INVALID_XML,m));for(a.children=[];p.children.length;){const r=p.children.shift();a.children.push(r)}for(const r of Object.keys(p.attributes))a.attributes[r]=p.attributes[r];return shaka.dash.MpdUtils.processXlinks(a,b,c,q[0],e,
f+1)})}static processXlinks(a,b,c,d,e,f=0){const g=shaka.dash.MpdUtils;var h=shaka.util.TXml;const k=g.XlinkNamespaceUri_;if(h.getAttributeNS(a,k,"href"))return h=g.handleXlinkInElement_(a,b,c,d,e,f),c&&(h=h.chain(void 0,m=>g.processXlinks(a,b,c,d,e,f))),h;const l=[];for(const m of shaka.util.TXml.getChildNodes(a))h.getAttributeNS(m,k,"href")=="urn:mpeg:dash:resolve-to-zero:2013"?a.children=a.children.filter(n=>n!==m):m.tagName!="SegmentTimeline"&&l.push(shaka.dash.MpdUtils.processXlinks(m,b,c,d,
e,f));return shaka.util.AbortableOperation.all(l).chain(()=>a)}};shaka.dash.MpdUtils.XlinkNamespaceUri_="http://www.w3.org/1999/xlink";shaka.dash.Mp4SegmentIndexParser=class{static parse(a,b,c,d,e,f,g,h){const k=shaka.dash.Mp4SegmentIndexParser;let l;const m=(new shaka.util.Mp4Parser).fullBox("sidx",n=>{l=k.parseSIDX_(b,d,e,f,g,c,n,h)});a&&m.parse(a);if(l)return l;shaka.log.error('Invalid box type, expected "sidx".');throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.MP4_SIDX_WRONG_BOX_TYPE);}static parseSIDX_(a,b,c,d,e,f,g,h=!1){goog.asserts.assert(g.version!=null,
"SIDX is a full box and should have a valid version.");const k=[];g.reader.skip(4);const l=g.reader.readUint32();if(l==0)throw shaka.log.error("Invalid timescale."),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.MP4_SIDX_INVALID_TIMESCALE);if(g.version==0){var m=g.reader.readUint32();var n=g.reader.readUint32()}else m=g.reader.readUint64(),n=g.reader.readUint64();g.reader.skip(2);const q=g.reader.readUint16();a=(h?-g.size:a)+g.size+n;
for(h=0;h<q;h++){var p=g.reader.readUint32();n=(p&2147483648)>>>31;p&=2147483647;const r=g.reader.readUint32();g.reader.skip(4);if(n==1)throw shaka.log.error("Hierarchical SIDXs are not supported."),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.MP4_SIDX_TYPE_NOT_SUPPORTED);k.push(new shaka.media.SegmentReference(m/l+c,(m+r)/l+c,()=>f,a,a+p-1,b,c,d,e));m+=r;a+=p}g.parser.stop();return k}};shaka.dash.EbmlParser=class{constructor(a){this.dataView_=shaka.util.BufferUtils.toDataView(a);this.reader_=new shaka.util.DataViewReader(this.dataView_,shaka.util.DataViewReader.Endianness.BIG_ENDIAN)}hasMoreData(){return this.reader_.hasMoreData()}parseElement(){const a=this.parseId_();var b=this.parseVint_();b=shaka.dash.EbmlParser.isDynamicSizeValue_(b)?this.dataView_.byteLength-this.reader_.getPosition():shaka.dash.EbmlParser.getVintValue_(b);b=this.reader_.getPosition()+b<=this.dataView_.byteLength?
b:this.dataView_.byteLength-this.reader_.getPosition();const c=shaka.util.BufferUtils.toDataView(this.dataView_,this.reader_.getPosition(),b);this.reader_.skip(b);return new shaka.util.EbmlElement(a,c)}parseId_(){const a=this.parseVint_();if(a.length>7)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.EBML_OVERFLOW);let b=0;for(const c of a)b=256*b+c;return b}parseVint_(){const a=this.reader_.getPosition();var b=this.reader_.readUint8();
if(b==0)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.EBML_OVERFLOW);b=8-Math.floor(Math.log2(b));goog.asserts.assert(b<=8&&b>=1,"Incorrect log2 value");this.reader_.skip(b-1);return shaka.util.BufferUtils.toUint8(this.dataView_,a,b)}static getVintValue_(a){if(a.length==8&&a[1]&224)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.JS_INTEGER_OVERFLOW);let b=0;for(let c=
0;c<a.length;c++){const d=a[c];b=c==0?d&(1<<8-a.length)-1:256*b+d}return b}static isDynamicSizeValue_(a){const b=shaka.dash.EbmlParser,c=shaka.util.BufferUtils;for(const d of b.DYNAMIC_SIZES)if(c.equal(a,new Uint8Array(d)))return!0;return!1}};shaka.dash.EbmlParser.DYNAMIC_SIZES=[[255],[127,255],[63,255,255],[31,255,255,255],[15,255,255,255,255],[7,255,255,255,255,255],[3,255,255,255,255,255,255],[1,255,255,255,255,255,255,255]];
shaka.util.EbmlElement=class{constructor(a,b){this.id=a;this.dataView_=b}getOffset(){return this.dataView_.byteOffset}createParser(){return new shaka.dash.EbmlParser(this.dataView_)}getUint(){if(this.dataView_.byteLength>8)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.EBML_OVERFLOW);if(this.dataView_.byteLength==8&&this.dataView_.getUint8(0)&224)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,
shaka.util.Error.Code.JS_INTEGER_OVERFLOW);let a=0;for(let b=0;b<this.dataView_.byteLength;b++){const c=this.dataView_.getUint8(b);a=256*a+c}return a}getFloat(){if(this.dataView_.byteLength==4)return this.dataView_.getFloat32(0);if(this.dataView_.byteLength==8)return this.dataView_.getFloat64(0);throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.EBML_BAD_FLOATING_POINT_SIZE);}};shaka.dash.WebmSegmentIndexParser=class{static parse(a,b,c,d,e,f,g){b=shaka.dash.WebmSegmentIndexParser.parseWebmContainer_(b);a=(new shaka.dash.EbmlParser(a)).parseElement();if(a.id!=shaka.dash.WebmSegmentIndexParser.CUES_ID)throw shaka.log.error("Not a Cues element."),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.WEBM_CUES_ELEMENT_MISSING);return shaka.dash.WebmSegmentIndexParser.parseCues_(a,b.segmentOffset,b.timecodeScale,b.duration,
c,d,e,f,g)}static parseWebmContainer_(a){a=new shaka.dash.EbmlParser(a);if(a.parseElement().id!=shaka.dash.WebmSegmentIndexParser.EBML_ID)throw shaka.log.error("Not an EBML element."),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.WEBM_EBML_HEADER_ELEMENT_MISSING);var b=a.parseElement();if(b.id!=shaka.dash.WebmSegmentIndexParser.SEGMENT_ID)throw shaka.log.error("Not a Segment element."),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.WEBM_SEGMENT_ELEMENT_MISSING);a=b.getOffset();b=shaka.dash.WebmSegmentIndexParser.parseSegment_(b);return{segmentOffset:a,timecodeScale:b.timecodeScale,duration:b.duration}}static parseSegment_(a){a=a.createParser();let b=null;for(;a.hasMoreData();){const c=a.parseElement();if(c.id==shaka.dash.WebmSegmentIndexParser.INFO_ID){b=c;break}}if(!b)throw shaka.log.error("Not an Info element."),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,
shaka.util.Error.Code.WEBM_INFO_ELEMENT_MISSING);return shaka.dash.WebmSegmentIndexParser.parseInfo_(b)}static parseInfo_(a){var b=a.createParser();let c=1E6;for(a=null;b.hasMoreData();){const d=b.parseElement();d.id==shaka.dash.WebmSegmentIndexParser.TIMECODE_SCALE_ID?c=d.getUint():d.id==shaka.dash.WebmSegmentIndexParser.DURATION_ID&&(a=d.getFloat())}if(a==null)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.WEBM_DURATION_ELEMENT_MISSING);
b=c/1E9;return{timecodeScale:b,duration:a*b}}static parseCues_(a,b,c,d,e,f,g,h,k){const l=[],m=()=>e;a=a.createParser();let n=null,q=null;for(;a.hasMoreData();){var p=a.parseElement();if(p.id!=shaka.dash.WebmSegmentIndexParser.CUE_POINT_ID)continue;var r=shaka.dash.WebmSegmentIndexParser.parseCuePoint_(p);if(!r)continue;p=c*r.unscaledTime;r=b+r.relativeOffset;n!=null&&(goog.asserts.assert(q!=null,"last offset cannot be null"),l.push(new shaka.media.SegmentReference(n+g,p+g,m,q,r-1,f,g,h,k)));n=p;
q=r}n!=null&&(goog.asserts.assert(q!=null,"last offset cannot be null"),l.push(new shaka.media.SegmentReference(n+g,d+g,m,q,null,f,g,h,k)));return l}static parseCuePoint_(a){var b=a.createParser();a=b.parseElement();if(a.id!=shaka.dash.WebmSegmentIndexParser.CUE_TIME_ID)throw shaka.log.warning("Not a CueTime element."),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.WEBM_CUE_TIME_ELEMENT_MISSING);a=a.getUint();b=b.parseElement();if(b.id!=
shaka.dash.WebmSegmentIndexParser.CUE_TRACK_POSITIONS_ID)throw shaka.log.warning("Not a CueTrackPositions element."),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.WEBM_CUE_TRACK_POSITIONS_ELEMENT_MISSING);b=b.createParser();let c=0;for(;b.hasMoreData();){const d=b.parseElement();if(d.id==shaka.dash.WebmSegmentIndexParser.CUE_CLUSTER_POSITION){c=d.getUint();break}}return{unscaledTime:a,relativeOffset:c}}};
shaka.dash.WebmSegmentIndexParser.EBML_ID=440786851;shaka.dash.WebmSegmentIndexParser.SEGMENT_ID=408125543;shaka.dash.WebmSegmentIndexParser.INFO_ID=357149030;shaka.dash.WebmSegmentIndexParser.TIMECODE_SCALE_ID=2807729;shaka.dash.WebmSegmentIndexParser.DURATION_ID=17545;shaka.dash.WebmSegmentIndexParser.CUES_ID=475249515;shaka.dash.WebmSegmentIndexParser.CUE_POINT_ID=187;shaka.dash.WebmSegmentIndexParser.CUE_TIME_ID=179;shaka.dash.WebmSegmentIndexParser.CUE_TRACK_POSITIONS_ID=183;
shaka.dash.WebmSegmentIndexParser.CUE_CLUSTER_POSITION=241;shaka.dash.SegmentBase=class{static createInitSegment(a,b,c){var d=shaka.util.TXml,e=shaka.util.ManifestParserUtils,f=shaka.util.StringUtils;b=shaka.dash.MpdUtils.inheritChild(a,b,"Initialization");if(!b)return null;let g=a.representation.getBaseUris();const h=b.attributes.sourceURL;h&&(g=e.resolveUris(g,[f.htmlUnescape(h)],a.urlParams()));e=0;f=null;if(d=d.parseAttr(b,"range",d.parseRange))e=d.start,f=d.end;d=shaka.dash.SegmentBase.createQualityInfo(a);c=new shaka.media.InitSegmentReference(()=>
g,e,f,d,null,null,c,a.adaptationSet.encrypted);c.codecs=a.representation.codecs;c.mimeType=a.representation.mimeType;a.periodInfo&&!a.periodInfo.isLastPeriod&&(c.boundaryEnd=a.periodInfo.start+a.periodInfo.duration);return c}static createStreamInfo(a,b,c){goog.asserts.assert(a.representation.segmentBase,"Should only be called with SegmentBase");var d=shaka.dash.MpdUtils;const e=shaka.dash.SegmentBase,f=shaka.util.TXml,g=Number(d.inheritAttribute(a,e.fromInheritance_,"presentationTimeOffset"))||0;
d=d.inheritAttribute(a,e.fromInheritance_,"timescale");let h=1;d&&(h=f.parsePositiveInt(d)||1);const k=g/h||0,l=e.createInitSegment(a,e.fromInheritance_,c);e.checkSegmentIndexRangeSupport_(a,l);const m=shaka.util.ObjectUtils.shallowCloneObject(a);return{endTime:-1,timeline:-1,generateSegmentIndex:()=>e.generateSegmentIndex_(m,b,l,k),timescale:h}}static async generateSegmentIndexFromUris(a,b,c,d,e,f,g){const h=a.presentationTimeline,k=!a.dynamic||!a.periodInfo.isLastPeriod,l=a.periodInfo.start;var m=
a.periodInfo.duration;const n=a.representation.mimeType.split("/")[1];var q=b;b=null;f=[q(d,e,f,!1),n=="webm"?q(c.getUris(),c.startByte,c.endByte,!0):null];q=null;q=await Promise.all(f);f=q[0];q=q[1]||null;var p=null;g=l-g;m=m?l+m:Infinity;p=a.representation.getBaseUris();const r=p.length!=d.length||p.some((t,u)=>t!=d[u]);n=="mp4"?p=shaka.dash.Mp4SegmentIndexParser.parse(f,e,p,c,g,l,m,r):(goog.asserts.assert(q,"WebM requires init data"),p=shaka.dash.WebmSegmentIndexParser.parse(f,q,p,c,g,l,m));for(const t of p)t.codecs=
a.representation.codecs,t.mimeType=a.representation.mimeType,t.bandwidth=a.bandwidth;h.notifySegments(p);goog.asserts.assert(!b,"Should not call generateSegmentIndex twice");b=new shaka.media.SegmentIndex(p);k&&b.fit(l,m,!0);return b}static fromInheritance_(a){return a.segmentBase}static computeIndexRange_(a){const b=shaka.dash.MpdUtils,c=shaka.dash.SegmentBase,d=shaka.util.TXml,e=b.inheritChild(a,c.fromInheritance_,"RepresentationIndex");a=b.inheritAttribute(a,c.fromInheritance_,"indexRange");a=
d.parseRange(a||"");e&&(a=d.parseAttr(e,"range",d.parseRange,a));return a}static computeIndexUris_(a){const b=shaka.util.ManifestParserUtils;var c=shaka.util.StringUtils;const d=shaka.dash.MpdUtils.inheritChild(a,shaka.dash.SegmentBase.fromInheritance_,"RepresentationIndex");let e=a.representation.getBaseUris();d&&(c=c.htmlUnescape(d.attributes.sourceURL))&&(e=b.resolveUris(e,[c],a.urlParams()));return e}static checkSegmentIndexRangeSupport_(a,b){const c=shaka.dash.SegmentBase;c.checkSegmentIndexSupport(a,
b);if(!c.computeIndexRange_(a))throw shaka.log.error("SegmentBase does not contain sufficient segment information:","the SegmentBase does not contain @indexRange","or a RepresentationIndex element.",a.representation),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_NO_SEGMENT_INFO);}static checkSegmentIndexSupport(a,b){const c=shaka.util.ManifestParserUtils.ContentType,d=a.representation.contentType,e=a.representation.mimeType.split("/")[1];
if(d!=c.TEXT&&e!="mp4"&&e!="webm")throw shaka.log.error("SegmentBase specifies an unsupported container type.",a.representation),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_UNSUPPORTED_CONTAINER);if(e=="webm"&&!b)throw shaka.log.error("SegmentBase does not contain sufficient segment information:","the SegmentBase uses a WebM container,","but does not contain an Initialization element.",a.representation),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_WEBM_MISSING_INIT);}static generateSegmentIndex_(a,b,c,d){var e=shaka.dash.SegmentBase;const f=e.computeIndexUris_(a);e=e.computeIndexRange_(a);goog.asserts.assert(e,"Index range should not be null!");return shaka.dash.SegmentBase.generateSegmentIndexFromUris(a,b,c,f,e.start,e.end,d)}static createQualityInfo(a){const b=a.representation;return{bandwidth:a.bandwidth,audioSamplingRate:b.audioSamplingRate,codecs:b.codecs,contentType:b.contentType,
frameRate:b.frameRate||null,height:b.height||null,mimeType:b.mimeType,channelsCount:b.numChannels,pixelAspectRatio:b.pixelAspectRatio||null,width:b.width||null,label:a.adaptationSet.label||null,roles:a.roles||null,language:a.adaptationSet.language||null}}};shaka.dash.SegmentList=class{static createStreamInfo(a,b,c){goog.asserts.assert(a.representation.segmentList,"Should only be called with SegmentList");const d=shaka.dash.SegmentList,e=shaka.dash.SegmentBase.createInitSegment(a,d.fromInheritance_,c),f=d.parseSegmentListInfo_(a);d.checkSegmentListInfo_(a,f);let g=null,h=null;a.period.id&&a.representation.id&&(h=b.get(a.period.id+","+a.representation.id))&&(g=h.segmentIndex);const k=d.createSegmentReferences_(a.periodInfo.start,a.periodInfo.duration,
f.startNumber,a.representation.getBaseUris,f,e,c,a.representation.mimeType,a.representation.codecs,a.bandwidth,a.urlParams);b=!g;g?(c=a.presentationTimeline.getSegmentAvailabilityStart(),g.mergeAndEvict(k,c)):g=new shaka.media.SegmentIndex(k);a.presentationTimeline.notifySegments(k);a.dynamic&&a.periodInfo.isLastPeriod||g.fit(a.periodInfo.start,a.periodInfo.duration?a.periodInfo.start+a.periodInfo.duration:Infinity,b);h&&(h.segmentIndex=g);return{endTime:-1,timeline:-1,generateSegmentIndex:()=>{g&&
!g.isEmpty()||g.merge(k);return Promise.resolve(g)},timescale:f.timescale}}static fromInheritance_(a){return a.segmentList}static parseSegmentListInfo_(a){var b=shaka.dash.SegmentList,c=shaka.dash.MpdUtils;const d=b.parseMediaSegments_(a);a=c.parseSegmentInfo(a,b.fromInheritance_);b=a.startNumber;b==0&&(shaka.log.warning("SegmentList@startNumber must be > 0"),b=1);c=0;a.segmentDuration?c=a.segmentDuration*(b-1):a.timeline&&a.timeline.length>0&&(c=a.timeline[0].start);return{segmentDuration:a.segmentDuration,
startTime:c,startNumber:b,scaledPresentationTimeOffset:a.scaledPresentationTimeOffset,timescale:a.timescale,timeline:a.timeline,mediaSegments:d}}static checkSegmentListInfo_(a,b){if(!b.segmentDuration&&!b.timeline&&b.mediaSegments.length>1)throw shaka.log.warning("SegmentList does not contain sufficient segment information:","the SegmentList specifies multiple segments,","but does not specify a segment duration or timeline.",a.representation),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_NO_SEGMENT_INFO);if(!b.segmentDuration&&!a.periodInfo.duration&&!b.timeline&&b.mediaSegments.length==1)throw shaka.log.warning("SegmentList does not contain sufficient segment information:","the SegmentList specifies one segment,","but does not specify a segment duration, period duration,","or timeline.",a.representation),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_NO_SEGMENT_INFO);
if(b.timeline&&b.timeline.length==0)throw shaka.log.warning("SegmentList does not contain sufficient segment information:","the SegmentList has an empty timeline.",a.representation),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_NO_SEGMENT_INFO);}static createSegmentReferences_(a,b,c,d,e,f,g,h,k,l,m){const n=shaka.util.ManifestParserUtils;c=e.mediaSegments.length;e.timeline&&e.timeline.length!=e.mediaSegments.length&&(c=Math.min(e.timeline.length,
e.mediaSegments.length),shaka.log.warning("The number of items in the segment timeline and the number of ","segment URLs do not match, truncating",e.mediaSegments.length,"to",c));const q=a-e.scaledPresentationTimeOffset,p=b?a+b:Infinity,r=[];var t=e.startTime;for(let v=0;v<c;v++){const x=e.mediaSegments[v];var u=t;e.segmentDuration!=null?t=u+e.segmentDuration:e.timeline?t=e.timeline[v].end:(goog.asserts.assert(e.mediaSegments.length==1&&b,"There should be exactly one segment with a Period duration."),
t=u+b);let y=null;u=new shaka.media.SegmentReference(a+u,a+t,()=>{y==null&&(y=n.resolveUris(d(),[x.mediaUri],m()));return y},x.start,x.end,f,q,a,p,[],"",null,null,shaka.media.SegmentReference.Status.AVAILABLE,g);u.codecs=k;u.mimeType=h;u.bandwidth=l;r.push(u)}return r}static parseMediaSegments_(a){const b=[a.representation.segmentList,a.adaptationSet.segmentList,a.period.segmentList].filter(shaka.util.Functional.isNotNull),c=shaka.util.TXml,d=shaka.util.StringUtils;return b.map(e=>c.findChildren(e,
"SegmentURL")).reduce((e,f)=>e.length>0?e:f).map(e=>{e.attributes.indexRange&&!a.indexRangeWarningGiven&&(a.indexRangeWarningGiven=!0,shaka.log.warning("We do not support the SegmentURL@indexRange attribute on SegmentList.  We only use the SegmentList@duration attribute or SegmentTimeline, which must be accurate."));const f=d.htmlUnescape(e.attributes.media);e=c.parseAttr(e,"mediaRange",c.parseRange,{start:0,end:null});return{mediaUri:f,start:e.start,end:e.end}})}};shaka.dash.SegmentTemplate=class{static createStreamInfo(a,b,c,d,e,f,g,h,k,l){goog.asserts.assert(a.representation.segmentTemplate,"Should only be called with SegmentTemplate or segment info defined");var m=shaka.dash.MpdUtils;const n=shaka.dash.SegmentTemplate;var q=shaka.dash.TimelineSegmentIndex;k||a.representation.initialization||(a.representation.initialization=m.inheritAttribute(a,n.fromInheritance_,"initialization"));const p=a.representation.initialization?n.createInitSegment_(a,g):null,r=
n.parseSegmentTemplateInfo_(a);n.checkSegmentTemplateInfo_(a,r);const t=shaka.util.ObjectUtils.shallowCloneObject(a);if(r.indexTemplate)return shaka.dash.SegmentBase.checkSegmentIndexSupport(a,p),{endTime:-1,timeline:-1,generateSegmentIndex:()=>n.generateSegmentIndexFromIndexTemplate_(t,b,p,r),timescale:r.timescale};if(r.segmentDuration){if(!d&&a.adaptationSet.contentType!=="image"&&a.adaptationSet.contentType!=="text"){l=a.periodInfo.start;q=a.period.id;var u=a.periodInfo.duration;q=(q=q!=null&&
f.get(q)||u)?l+q:Infinity;a.presentationTimeline.notifyMaxSegmentDuration(r.segmentDuration);a.presentationTimeline.notifyPeriodDuration(l,q)}return{endTime:-1,timeline:-1,generateSegmentIndex:()=>n.generateSegmentIndexFromDuration_(t,r,e,p,f,g,h,a.representation.segmentSequenceCadence),timescale:r.timescale}}let v=null;d=d=null;a.period.id&&a.representation.id&&(d=a.period.id+","+a.representation.id,d=c.get(d))&&(v=d.segmentIndex);const x=a.periodInfo.start,y=a.periodInfo.duration?x+a.periodInfo.duration:
Infinity;shaka.log.debug(`New manifest ${x} - ${y}`);if(v)l=v,l.appendTemplateInfo(r,x,y,p,a.dynamic),q=a.presentationTimeline.getSegmentAvailabilityStart(),l.evict(q);else{c=0;k=-1;if(a.period.id!=null&&a.representation.id!=null)if(m=l.get(a.period.id))k=m.timeline;else for(u of l.values())if(Math.abs(r.scaledPresentationTimeOffset-u.endTime)<=shaka.util.ManifestParserUtils.GAP_OVERLAP_TOLERANCE_SECONDS&&u.reps.includes(a.representation.id)){k=u.timeline;break}else u.timeline>=c&&(c=u.timeline+1);
k==-1&&(k=c);shaka.log.debug(`Creating TSI with end ${y}`);v=new q(a.dynamic,r,a.representation.originalId,a.bandwidth,a.representation.getBaseUris,a.urlParams,x,y,p,g,a.representation.segmentSequenceCadence,k)}r.timeline&&a.adaptationSet.contentType!=="image"&&a.adaptationSet.contentType!=="text"&&(l=v.getTimeline(),a.presentationTimeline.notifyTimeRange(l,x));d&&a.dynamic&&(d.segmentIndex=v);l=(l=(l=r.timeline)&&l[l.length-1])?l.end+r.scaledPresentationTimeOffset:-1;q=-1;v instanceof shaka.dash.TimelineSegmentIndex&&
(q=v.continuityTimeline());return{endTime:l,timeline:q,generateSegmentIndex:()=>{v instanceof shaka.dash.TimelineSegmentIndex&&v.isEmpty()&&v.appendTemplateInfo(r,x,y,p,a.dynamic);return Promise.resolve(v)},timescale:r.timescale}}static modifyTimepoints(a,b){const c=shaka.util.TXml;a=shaka.dash.MpdUtils.inheritChild(a,shaka.dash.SegmentTemplate.fromInheritance_,"SegmentTimeline");goog.asserts.assert(a,"timeline node not found");const d=c.findChildren(a,"S");goog.asserts.assert(d,"timepoints should exist");
c.modifyNodes(d,b);a.children=d}static removeTimepoints(a){a=shaka.dash.MpdUtils.inheritChild(a,shaka.dash.SegmentTemplate.fromInheritance_,"SegmentTimeline");goog.asserts.assert(a,"timeline node not found");a.children=[]}static fromInheritance_(a){return a.segmentTemplate}static parseSegmentTemplateInfo_(a){var b=shaka.dash.SegmentTemplate,c=shaka.dash.MpdUtils;const d=shaka.util.StringUtils,e=c.parseSegmentInfo(a,b.fromInheritance_),f=c.inheritAttribute(a,b.fromInheritance_,"media"),g=c.inheritAttribute(a,
b.fromInheritance_,"index");b=c.inheritAttribute(a,b.fromInheritance_,"k");c=0;b&&(c=parseInt(b,10));return{unscaledSegmentDuration:e.unscaledSegmentDuration,segmentDuration:e.segmentDuration,timescale:e.timescale,startNumber:e.startNumber,scaledPresentationTimeOffset:e.scaledPresentationTimeOffset,unscaledPresentationTimeOffset:e.unscaledPresentationTimeOffset,timeline:e.timeline,mediaTemplate:f&&d.htmlUnescape(f),indexTemplate:g,mimeType:a.representation.mimeType,codecs:a.representation.codecs,
bandwidth:a.bandwidth,numChunks:c}}static checkSegmentTemplateInfo_(a,b){let c;c=b.indexTemplate?1:0;c+=b.timeline?1:0;c+=b.segmentDuration?1:0;if(c==0)throw shaka.log.error("SegmentTemplate does not contain any segment information:","the SegmentTemplate must contain either an index URL template","a SegmentTimeline, or a segment duration.",a.representation),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_NO_SEGMENT_INFO);c!=1&&
(shaka.log.warning("SegmentTemplate contains multiple segment information sources:","the SegmentTemplate should only contain an index URL template,","a SegmentTimeline or a segment duration.",a.representation),b.indexTemplate?(shaka.log.info("Using the index URL template by default."),b.timeline=null):(goog.asserts.assert(b.timeline,"There should be a timeline"),shaka.log.info("Using the SegmentTimeline by default.")),b.unscaledSegmentDuration=null,b.segmentDuration=null);if(!b.indexTemplate&&!b.mediaTemplate)throw shaka.log.error("SegmentTemplate does not contain sufficient segment information:",
"the SegmentTemplate's media URL template is missing.",a.representation),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_NO_SEGMENT_INFO);}static generateSegmentIndexFromIndexTemplate_(a,b,c,d){var e=shaka.dash.MpdUtils,f=shaka.util.ManifestParserUtils;goog.asserts.assert(d.indexTemplate,"must be using index template");e=e.fillUriTemplate(d.indexTemplate,a.representation.originalId,null,null,a.bandwidth||null,null);f=f.resolveUris(a.representation.getBaseUris(),
[e]);return shaka.dash.SegmentBase.generateSegmentIndexFromUris(a,b,c,f,0,null,d.scaledPresentationTimeOffset)}static generateSegmentIndexFromDuration_(a,b,c,d,e,f,g,h){goog.asserts.assert(b.mediaTemplate,"There should be a media template with duration");const k=shaka.dash.MpdUtils,l=shaka.util.ManifestParserUtils,m=a.presentationTimeline,n=a.periodInfo.start,q=a.period.id,p=a.periodInfo.duration,r=()=>{const D=q!=null&&e.get(q)||p;return D?n+D:Infinity},t=b.segmentDuration;goog.asserts.assert(t!=
null,"Segment duration must not be null!");const u=b.startNumber,v=b.mediaTemplate,x=a.bandwidth||null,y=a.representation.originalId,A=a.representation.getBaseUris,w=a.urlParams,z=n-b.scaledPresentationTimeOffset,B=()=>{var D=[Math.max(m.getSegmentAvailabilityStart(),n),Math.min(m.getSegmentAvailabilityEnd(),r())];goog.asserts.assert(D.every(isFinite),"Available presentation times must be finite!");goog.asserts.assert(D.every(J=>J>=0),"Available presentation times must be positive!");goog.asserts.assert(t!=
null,"Segment duration must not be null!");D=D.map(J=>J-n);D=[Math.ceil(D[0]/t),Math.ceil(D[1]/t)-1];a.representation.availabilityTimeOffset&&D[1]++;return D.map(J=>J+u)};var C=B();c=a.dynamic?Math.max(C[0],C[1]-c+1):C[0];g=g||C[1];const F=D=>{goog.asserts.assert(t!=null,"Segment duration must not be null!");var J=D-u,G=J*t,E=b.unscaledSegmentDuration;goog.asserts.assert(E!=null,"Segment duration must not be null!");let K=J*E;"BigInt"in window&&K>Number.MAX_SAFE_INTEGER&&(K=BigInt(J)*BigInt(E));G+=
n;J=G+t;E=Math.min(J,r());goog.asserts.assert(G<E,"Generated a segment outside of the period!");const L=[],M=b.numChunks;if(M){const P=(E-G)/M;for(let O=0;O<M;O++){var N=G+P*O;const Q=O;N=new shaka.media.SegmentReference(N,N+P,()=>{const R=k.fillUriTemplate(v,y,D,Q,x,K);return l.resolveUris(A(),[R],w())},0,null,d,z,n,r(),[],"",null,null,shaka.media.SegmentReference.Status.AVAILABLE,f);N.codecs=a.representation.codecs;N.mimeType=a.representation.mimeType;h==0?O>0&&N.markAsNonIndependent():O%h!=0&&
N.markAsNonIndependent();L.push(N)}}G=new shaka.media.SegmentReference(G,E,()=>{if(M)return[];const P=k.fillUriTemplate(v,y,D,null,x,K);return l.resolveUris(A(),[P],w())},0,null,d,z,n,r(),L,"",null,null,shaka.media.SegmentReference.Status.AVAILABLE,f,L.length>0);G.codecs=a.representation.codecs;G.mimeType=a.representation.mimeType;G.bandwidth=a.bandwidth;G.trueEndTime=J;return G},H=new shaka.dash.SegmentTemplate.FixedDurationSegmentIndex_(c,g,u,n,t,F);C=m.getSegmentAvailabilityEnd()<r();const I=m.isLive();
if(C||I){let D=Math.max(c,g+1);c=t;a.representation.availabilityTimeOffset&&(c=.1);H.updateEvery(c,()=>{const J=m.getSegmentAvailabilityStart();H.evict(J);const [,G]=B(),E=[];for(;D<=G;){const K=F(D);E.push(K);D++}return J>r()&&!E.length?null:E})}return Promise.resolve(H)}static createInitSegment_(a,b){const c=shaka.dash.MpdUtils,d=shaka.util.ManifestParserUtils;var e=shaka.dash.SegmentTemplate;let f=a.representation.initialization;f||=c.inheritAttribute(a,e.fromInheritance_,"initialization");if(!f)return null;
f=shaka.util.StringUtils.htmlUnescape(f);const g=a.representation.originalId,h=a.bandwidth||null,k=a.representation.getBaseUris,l=a.urlParams;e=shaka.dash.SegmentBase.createQualityInfo(a);b=new shaka.media.InitSegmentReference(()=>{goog.asserts.assert(f,"Should have returned earlier");const m=c.fillUriTemplate(f,g,null,null,h,null);return d.resolveUris(k(),[m],l())},0,null,e,null,null,b,a.adaptationSet.encrypted);b.codecs=a.representation.codecs;b.mimeType=a.representation.mimeType;a.periodInfo&&
!a.periodInfo.isLastPeriod&&(b.boundaryEnd=a.periodInfo.start+a.periodInfo.duration);return b}};
shaka.dash.SegmentTemplate.FixedDurationSegmentIndex_=class extends shaka.media.SegmentIndex{constructor(a,b,c,d,e,f){super(Array(Math.max(0,b-a+1)));this.minPosition_=a;this.startNumber_=c;this.periodStart_=d;this.segmentDuration_=e;this.createReference_=f}find(a){var b=this.references.length-1;if(b<0)return null;var c=this.get(this.numEvicted_);if(!c)return null;if(a<c.startTime)return this.numEvicted_;c=Math.floor((a-this.periodStart_)/this.segmentDuration_)+this.startNumber_-this.minPosition_;
if(c<this.numEvicted_)return null;const d=this.get(c);if(!d)return null;b=(b=c-this.numEvicted_<b?this.get(c+1):null)?b.startTime:d.endTime;return a>=d.startTime&&a<b?c:null}get(a){const b=a-this.numEvicted_;if(b<0||b>=this.references.length)return null;let c=this.references[b];c||(c=this.createReference_(this.minPosition_+a),this.references[b]=c);return c}earliestReference(){return this.get(this.numEvicted_)}forEachTopLevelReference(a){for(let b=0;b<this.references.length;b++){const c=this.get(b+
this.numEvicted_);c&&a(c)}}evict(a){if(!this.getIsImmutable()){var b=this.references.length-1;if(!(b<0)){var c=this.get(this.numEvicted_);!c||c.endTime>a||(a=(b=this.get(this.numEvicted_+b))&&b.endTime<=a?this.references.length:Math.max(0,Math.min(this.references.length,Math.floor((a-this.periodStart_)/this.segmentDuration_+this.startNumber_-1)-(this.minPosition_+this.numEvicted_)+1)),a>0&&(this.numEvicted_+=a,this.references=this.references.slice(a)))}}}};
shaka.dash.TimelineSegmentIndex=class extends shaka.media.SegmentIndex{constructor(a,b,c,d,e,f,g,h,k,l,m,n){super([]);this.dynamic_=a;this.templateInfo_=b;this.representationId_=c;this.bandwidth_=d;this.getBaseUris_=e;this.urlParams_=f;this.periodStart_=g;this.periodEnd_=h;this.initSegmentReference_=k;this.aesKey_=l;this.segmentSequenceCadence_=m;this.timeline_=n;this.fitTimeline()}getNumReferences(){return this.templateInfo_?this.templateInfo_.timeline.length:0}release(){super.release();this.templateInfo_=
null}evict(a){if(this.templateInfo_){shaka.log.debug(`${this.representationId_} Evicting at ${a}`);var b=this.templateInfo_.timeline;if(b){for(var c=0;c<b.length&&b[c].end+this.periodStart_<=a;)c++;c>0&&(this.templateInfo_.timeline=b.slice(c),this.references.length>=c&&(this.references=this.references.slice(c)),this.numEvicted_+=c,this.getNumReferences()===0&&this.release())}}}appendTemplateInfo(a,b,c,d,e){this.updateInitSegmentReference(d);this.dynamic_=e;if(this.templateInfo_){if(this.templateInfo_.unscaledPresentationTimeOffset!==
a.unscaledPresentationTimeOffset)for(b=a.unscaledPresentationTimeOffset-this.templateInfo_.unscaledPresentationTimeOffset,shaka.log.error("Possibly suboptimal manifest detected!","presentationTimeOffset is "+a.unscaledPresentationTimeOffset,"which differs "+b+" from the cache template."),d=0;d<a.timeline.length;d++)e=a.timeline[d],e.unscaledStart+=b,e.unscaledEnd+=b,e.start=(e.unscaledStart+b)/a.timescale,e.end=(e.unscaledEnd+b)/a.timescale;this.templateInfo_.mediaTemplate!==a.mediaTemplate&&(this.templateInfo_.mediaTemplate=
a.mediaTemplate);b=this.templateInfo_.timeline;if(b.length){const f=b[b.length-1];a=a.timeline.filter(g=>g.end>f.end)}else a=a.timeline.slice();a.length>0&&(shaka.log.debug(`Appending ${a.length} entries`),this.templateInfo_.timeline.push(...a));this.periodEnd_!==c&&(this.periodEnd_=c)}else this.templateInfo_=a,this.periodStart_=b,this.periodEnd_=c;this.fitTimeline()}updateInitSegmentReference(a){if(this.initSegmentReference_!==a){this.initSegmentReference_=a;for(const b of this.references)b&&b.updateInitSegmentReference(a)}}isBeforeFirstEntry(a){return this.templateInfo_&&
this.templateInfo_.timeline&&this.templateInfo_.timeline.length?a<this.templateInfo_.timeline[0].start+this.periodStart_:!1}fitTimeline(){if(this.templateInfo_&&!this.getIsImmutable()){var a=this.templateInfo_.timeline;goog.asserts.assert(a,"Timeline should be non-null!");var b=[];for(const c of a)c.start>=this.periodEnd_||c.end<=0||b.push(c);this.templateInfo_.timeline=b;this.evict(this.periodStart_)}}getTimeline(){if(!this.templateInfo_)return[];const a=this.templateInfo_.timeline;goog.asserts.assert(a,
"Timeline should be non-null!");return a}find(a){shaka.log.debug(`Find ${a}`);if(this.isBeforeFirstEntry(a))return this.numEvicted_;if(!this.templateInfo_)return null;var b=this.templateInfo_.timeline;if(a<this.periodStart_||a>=this.periodEnd_)return null;const c=b.length-1,d=shaka.util.ArrayUtils.binarySearch(b,g=>g.start+this.periodStart_<=a)-1;if(d<0)return null;const e=b[d],f=e.start+this.periodStart_;b=d<c?b[d+1].start+this.periodStart_:this.periodEnd_===Infinity?e.end+this.periodStart_:this.periodEnd_;
return a>=f&&a<b?d+this.numEvicted_:null}get(a){a-=this.numEvicted_;if(a<0||a>=this.getNumReferences()||!this.templateInfo_)return null;var b=this.references[a];if(!b){b=this.templateInfo_.timeline[a];const e=b.segmentPosition,f=b.unscaledStart+this.templateInfo_.unscaledPresentationTimeOffset,g=this.periodStart_-this.templateInfo_.scaledPresentationTimeOffset,h=this.periodStart_+b.end;let k=h;a===this.getNumReferences()-1&&this.periodEnd_!==Infinity&&(k=this.dynamic_&&Math.abs(k-this.periodEnd_)>
.1?Math.min(k,this.periodEnd_):this.periodEnd_);const l=this.templateInfo_.codecs,m=this.templateInfo_.mimeType,n=this.templateInfo_.bandwidth,q=[];var c=!1;b.partialSegments&&this.templateInfo_&&this.templateInfo_.mediaTemplate&&(c=this.templateInfo_.mediaTemplate.includes("$SubNumber$"));if(c){c=(b.end-b.start)/b.partialSegments;for(let p=0;p<b.partialSegments;p++){var d=b.start+c*p;const r=p;let t=null;d=new shaka.media.SegmentReference(this.periodStart_+d,this.periodStart_+(d+c),()=>{if(!this.templateInfo_)return[];
t==null&&(t=shaka.dash.TimelineSegmentIndex.createUris_(this.templateInfo_.mediaTemplate,this.representationId_,e,this.bandwidth_,f,r,this.getBaseUris_,this.urlParams_));return t},0,null,this.initSegmentReference_,g,this.periodStart_,this.periodEnd_,[],"",null,null,shaka.media.SegmentReference.Status.AVAILABLE,this.aesKey_);d.codecs=l;d.mimeType=m;d.bandwidth=n;this.segmentSequenceCadence_==0?p>0&&d.markAsNonIndependent():p%this.segmentSequenceCadence_!=0&&d.markAsNonIndependent();q.push(d)}}b=new shaka.media.SegmentReference(this.periodStart_+
b.start,k,()=>q.length>0||!this.templateInfo_?[]:shaka.dash.TimelineSegmentIndex.createUris_(this.templateInfo_.mediaTemplate,this.representationId_,e,this.bandwidth_,f,null,this.getBaseUris_,this.urlParams_),0,null,this.initSegmentReference_,g,this.periodStart_,this.periodEnd_,q,"",null,null,shaka.media.SegmentReference.Status.AVAILABLE,this.aesKey_,q.length>0);b.codecs=l;b.mimeType=m;b.trueEndTime=h;b.bandwidth=n;this.references[a]=b}return b}forEachTopLevelReference(a){this.fitTimeline();for(let b=
0;b<this.getNumReferences();b++){const c=this.get(b+this.numEvicted_);c&&a(c)}}static createUris_(a,b,c,d,e,f,g,h){a=shaka.dash.MpdUtils.fillUriTemplate(a,b,c,f,d||null,e);return shaka.util.ManifestParserUtils.resolveUris(g(),[a],h()).map(k=>k.toString())}continuityTimeline(){return this.timeline_}};shaka.util.ContentSteeringManager=class{constructor(a){this.config_=null;this.playerInterface_=a;this.operationManager_=new shaka.util.OperationManager;this.baseUris_=[];this.defaultPathwayId_=null;this.pathwayPriority_=[];this.lastPathwayUsed_=null;this.pathwayClones_=[];this.lastTTL_=300;this.locations_=new Map;this.bannedLocations_=new Map;this.updateTimer_=null;this.manifestType_=shaka.media.ManifestParser.UNKNOWN}configure(a){this.config_=a}destroy(){this.playerInterface_=this.config_=null;this.baseUris_=
[];this.defaultPathwayId_=null;this.pathwayPriority_=[];this.pathwayClones_=[];this.locations_.clear();this.updateTimer_!=null&&(this.updateTimer_.stop(),this.updateTimer_=null);return this.operationManager_.destroy()}setManifestType(a){this.manifestType_=a}setBaseUris(a){this.baseUris_=a}setDefaultPathwayId(a){this.defaultPathwayId_=a}async requestInfo(a){var b=shaka.util.ManifestParserUtils.resolveUris(this.baseUris_,[this.addQueryParams_(a)]),c=shaka.net.NetworkingEngine.RequestType.CONTENT_STEERING;
b=shaka.net.NetworkingEngine.makeRequest(b,this.config_.retryParameters);c=this.playerInterface_.networkingEngine.request(c,b);this.operationManager_.manage(c);try{const d=await c.promise,e=shaka.util.StringUtils.fromUTF8(d.data),f=JSON.parse(e);f.VERSION==1&&this.processManifest_(f,d.uri)}catch(d){d&&d.code==shaka.util.Error.Code.OPERATION_ABORTED||(this.updateTimer_!=null&&(this.updateTimer_.stop(),this.updateTimer_=null),this.updateTimer_=new shaka.util.Timer(()=>{this.requestInfo(a)}),this.updateTimer_.tickAfter(this.lastTTL_))}}addQueryParams_(a){if(!this.pathwayPriority_.length)return a;
a=new goog.Uri(a);const b=this.lastPathwayUsed_||this.pathwayPriority_[0],c=Math.round(this.playerInterface_.getBandwidthEstimate()),d=a.getQueryData();this.manifestType_==shaka.media.ManifestParser.DASH?(d.add("_DASH_pathway",b),d.add("_DASH_throughput",String(c))):this.manifestType_==shaka.media.ManifestParser.HLS&&(d.add("_HLS_pathway",b),d.add("_HLS_throughput",String(c)));d.getCount()&&a.setQueryData(d);return a.toString()}processManifest_(a,b){this.updateTimer_!=null&&(this.updateTimer_.stop(),
this.updateTimer_=null);const c=a["RELOAD-URI"]||b;this.updateTimer_=new shaka.util.Timer(()=>{this.requestInfo(c)});if(b=a.TTL)this.lastTTL_=b;this.updateTimer_.tickAfter(this.lastTTL_);this.pathwayPriority_=a["PATHWAY-PRIORITY"]||[];this.pathwayClones_=a["PATHWAY-CLONES"]||[]}clearPreviousLocations(){this.locations_.clear()}addLocation(a,b,c){let d=this.locations_.get(a);d||=new Map;d.set(b,c);this.locations_.set(a,d)}banLocation(a){const b=Date.now()+6E4;this.bannedLocations_.set(a,b)}getLocations(a,
b=!1){a=this.locations_.get(a)||new Map;var c=[];for(const g of this.pathwayPriority_){var d=a.get(g);if(d)c.push({pathwayId:g,location:d});else if(d=this.pathwayClones_.find(h=>h.ID==g)){var e=a.get(d["BASE-ID"]);e&&(d["URI-REPLACEMENT"].HOST?(e=new goog.Uri(e),e.setDomain(d["URI-REPLACEMENT"].HOST),c.push({pathwayId:g,location:e.toString()})):c.push({pathwayId:g,location:e}))}}d=Date.now();for(var f of this.bannedLocations_.keys())e=this.bannedLocations_.get(f),d>e&&this.bannedLocations_.delete(f);
c=c.filter(g=>{for(const h of this.bannedLocations_.keys())if(h.includes((new goog.Uri(g.location)).getDomain()))return!1;return!0});c.length&&(this.lastPathwayUsed_=c[0].pathwayId);f=c.map(g=>g.location);if(!f.length&&this.defaultPathwayId_)for(const g of this.defaultPathwayId_.split(","))if(c=a.get(g))this.lastPathwayUsed_=this.defaultPathwayId_,f.push(c);if(!f.length)for(const g of a.values())f.push(g);return b?f:shaka.util.ManifestParserUtils.resolveUris(this.baseUris_,f)}};shaka.util.PeriodCombiner=class{constructor(){this.variants_=[];this.audioStreams_=[];this.videoStreams_=[];this.textStreams_=[];this.imageStreams_=[];this.useStreamOnce_=!1;this.usedPeriodIds_=new Set}release(){const a=this.audioStreams_.concat(this.videoStreams_,this.textStreams_,this.imageStreams_);for(const b of a)b.segmentIndex&&b.segmentIndex.release();this.audioStreams_=[];this.videoStreams_=[];this.textStreams_=[];this.imageStreams_=[];this.variants_=[];this.useStreamOnce_=!1;this.usedPeriodIds_.clear()}getVariants(){return this.variants_}getTextStreams(){return this.textStreams_.slice()}getImageStreams(){return this.imageStreams_}deleteStream(a,
b){if(a){var c=shaka.util.ManifestParserUtils.ContentType;if(a.type==c.AUDIO)for(const d of this.audioStreams_)d.matchedStreams=d.matchedStreams.filter(e=>e!==a);else if(a.type==c.VIDEO)for(const d of this.videoStreams_)d.matchedStreams=d.matchedStreams.filter(e=>e!==a),d.trickModeVideo&&(d.trickModeVideo.matchedStreams=d.trickModeVideo.matchedStreams.filter(e=>e!==a)),d.dependencyStream&&(d.dependencyStream.matchedStreams=d.dependencyStream.matchedStreams.filter(e=>e!==a));else if(a.type==c.TEXT)for(const d of this.textStreams_)d.matchedStreams=
d.matchedStreams.filter(e=>e!==a);else if(a.type==c.IMAGE)for(const d of this.imageStreams_)d.matchedStreams=d.matchedStreams.filter(e=>e!==a);a.segmentIndex&&a.closeSegmentIndex();this.usedPeriodIds_.delete(b)}}getStreamsPerPeriod_(a,b){const c=shaka.util.ManifestParserUtils.ContentType,d=shaka.util.PeriodCombiner,e=[],f=[],g=[],h=[];for(const l of a){a=new Map(l.audioStreams.map(p=>[d.generateAudioKey_(p),p]));const m=new Map(l.videoStreams.map(p=>[d.generateVideoKey_(p),p])),n=new Map(l.textStreams.map(p=>
[d.generateTextKey_(p),p])),q=new Map(l.imageStreams.map(p=>[d.generateImageKey_(p),p]));if(b){var k=d.dummyStream_(c.TEXT);n.set(d.generateTextKey_(k),k);k=d.dummyStream_(c.IMAGE);q.set(d.generateImageKey_(k),k)}e.push(a);f.push(m);g.push(n);h.push(q)}return{audioStreamsPerPeriod:e,videoStreamsPerPeriod:f,textStreamsPerPeriod:g,imageStreamsPerPeriod:h}}async combinePeriods(a,b,c=!1){var d=shaka.util.ManifestParserUtils.ContentType;if(b||a.length!=1){b=c?this.usedPeriodIds_.size:0;c=-1;for(let n=
0;n<a.length;n++){const q=a[n];this.usedPeriodIds_.has(q.id)||(this.usedPeriodIds_.add(q.id),c==-1&&(c=n))}if(c==-1)return;const {audioStreamsPerPeriod:h,videoStreamsPerPeriod:k,textStreamsPerPeriod:l,imageStreamsPerPeriod:m}=this.getStreamsPerPeriod_(a,!0);await Promise.all([this.combine_(this.audioStreams_,h,c,shaka.util.PeriodCombiner.cloneStream_,shaka.util.PeriodCombiner.concatenateStreams_,b),this.combine_(this.videoStreams_,k,c,shaka.util.PeriodCombiner.cloneStream_,shaka.util.PeriodCombiner.concatenateStreams_,
b),this.combine_(this.textStreams_,l,c,shaka.util.PeriodCombiner.cloneStream_,shaka.util.PeriodCombiner.concatenateStreams_,b),this.combine_(this.imageStreams_,m,c,shaka.util.PeriodCombiner.cloneStream_,shaka.util.PeriodCombiner.concatenateStreams_,b)])}else{const {audioStreamsPerPeriod:h,videoStreamsPerPeriod:k,textStreamsPerPeriod:l,imageStreamsPerPeriod:m}=this.getStreamsPerPeriod_(a,!1);this.audioStreams_=Array.from(h[0].values());this.videoStreams_=Array.from(k[0].values());this.textStreams_=
Array.from(l[0].values());this.imageStreams_=Array.from(m[0].values())}a=0;b=[];if(this.videoStreams_.length&&this.audioStreams_.length)for(var e of this.audioStreams_)for(var f of this.videoStreams_){d=shaka.drm.DrmUtils.getCommonDrmInfos(e.drmInfos,f.drmInfos);if(e.drmInfos.length&&f.drmInfos.length&&!d.length){shaka.log.warning("Incompatible DRM in audio & video, skipping variant creation.",e,f);continue}var g=(e.bandwidth||0)+(f.bandwidth||0);e.dependencyStream&&(g+=e.dependencyStream.bandwidth||
0);f.dependencyStream&&(g+=f.dependencyStream.bandwidth||0);c=a++;b.push({id:c,language:e.language,disabledUntilTime:0,primary:e.primary,audio:e,video:f,bandwidth:g,drmInfos:d,allowedByApplication:!0,allowedByKeySystem:!0,decodingInfos:[]})}else{e=this.videoStreams_.length?this.videoStreams_:this.audioStreams_;for(g of e)e=a++,f=g.bandwidth||0,g.dependencyStream&&(f+=g.dependencyStream.bandwidth||0),b.push({id:e,language:g.language,disabledUntilTime:0,primary:g.primary,audio:g.type==d.AUDIO?g:null,
video:g.type==d.VIDEO?g:null,bandwidth:f,drmInfos:g.drmInfos,allowedByApplication:!0,allowedByKeySystem:!0,decodingInfos:[]})}this.variants_=b}static async combineDbStreams(a){const b=shaka.util.ManifestParserUtils.ContentType,c=shaka.util.PeriodCombiner;if(a.length==1)return a[0];var d=a.map(m=>new Map(m.filter(n=>n.type===b.AUDIO).map(n=>[c.generateAudioKey_(n),n]))),e=a.map(m=>new Map(m.filter(n=>n.type===b.VIDEO).map(n=>[c.generateVideoKey_(n),n]))),f=a.map(m=>new Map(m.filter(n=>n.type===b.TEXT).map(n=>
[c.generateTextKey_(n),n])));a=a.map(m=>new Map(m.filter(n=>n.type===b.IMAGE).map(n=>[c.generateImageKey_(n),n])));for(var g of f){const m=c.dummyStreamDB_(b.TEXT);g.set(c.generateTextKey_(m),m)}for(var h of a)g=c.dummyStreamDB_(b.IMAGE),h.set(c.generateImageKey_(g),g);h=new shaka.util.PeriodCombiner;d=await h.combine_([],d,0,shaka.util.PeriodCombiner.cloneStreamDB_,shaka.util.PeriodCombiner.concatenateStreamDBs_,0);e=await h.combine_([],e,0,shaka.util.PeriodCombiner.cloneStreamDB_,shaka.util.PeriodCombiner.concatenateStreamDBs_,
0);f=await h.combine_([],f,0,shaka.util.PeriodCombiner.cloneStreamDB_,shaka.util.PeriodCombiner.concatenateStreamDBs_,0);a=await h.combine_([],a,0,shaka.util.PeriodCombiner.cloneStreamDB_,shaka.util.PeriodCombiner.concatenateStreamDBs_,0);h=0;if(e.length&&d.length)for(var k of d)for(const m of e){var l=h++;m.variantIds.push(l);k.variantIds.push(l)}else{k=e.concat(d);for(l of k)l.variantIds=[h++]}return e.concat(d).concat(f).concat(a)}async combine_(a,b,c,d,e,f){const g=[];for(let h=0;h<b.length;h++)h>=
c?g.push(new Set(b[h].values())):g.push(new Set);for(const h of a)if(!await this.extendExistingOutputStream_(h,b,c,e,g,f))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.PERIOD_FLATTENING_FAILED);for(const h of g)for(const k of h)(c=this.createNewOutputStream_(a,k,b,d,e,g))&&a.push(c);for(const h of g)for(const k of h)if(!shaka.util.PeriodCombiner.isDummy_(k)&&a.some(l=>this.areAVStreamsCompatible_(k,l)))throw shaka.log.error("Unused stream in period-flattening!",
k,a),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.PERIOD_FLATTENING_FAILED);return a}async extendExistingOutputStream_(a,b,c,d,e,f){this.findMatchesInAllPeriods_(b,a,f>0);goog.asserts.assert(a.createSegmentIndex,"outputStream should be a Stream type!");if(!a.matchedStreams)return shaka.log.error("No matches extending output stream!",a,b),!1;a.segmentIndex&&await shaka.util.PeriodCombiner.extendOutputSegmentIndex_(a,c+f);shaka.util.PeriodCombiner.extendOutputStream_(a,
c,d,e,f);return!0}static async extendOutputSegmentIndex_(a,b){var c=[];const d=a.matchedStreams;goog.asserts.assert(d,"matched streams should be valid");for(let e=b;e<d.length;e++){const f=d[e];c.push(f.createSegmentIndex());f.trickModeVideo&&!f.trickModeVideo.segmentIndex&&c.push(f.trickModeVideo.createSegmentIndex());f.dependencyStream&&!f.dependencyStream.segmentIndex&&c.push(f.dependencyStream.createSegmentIndex())}await Promise.all(c);if(a.segmentIndex instanceof shaka.media.MetaSegmentIndex)for(;b<
d.length;b++)c=d[b],goog.asserts.assert(c.segmentIndex,"stream should have a segmentIndex."),c.segmentIndex&&a.segmentIndex.appendSegmentIndex(c.segmentIndex)}createNewOutputStream_(a,b,c,d,e,f){if(shaka.util.PeriodCombiner.isDummy_(b))return null;const g=d(b);this.findMatchesInAllPeriods_(c,g);g.createSegmentIndex&&(g.createSegmentIndex=async()=>{g.segmentIndex||(g.segmentIndex=new shaka.media.MetaSegmentIndex,await shaka.util.PeriodCombiner.extendOutputSegmentIndex_(g,0))},g.closeSegmentIndex=()=>
{g.segmentIndex&&(g.segmentIndex.release(),g.segmentIndex=null);if(g.matchedStreams)for(const h of g.matchedStreams)h.segmentIndex&&!shaka.util.PeriodCombiner.isStreamActivelyUsed_(h,g,a)&&(h.segmentIndex.release(),h.segmentIndex=null)});if(!g.matchedStreams||!g.matchedStreams.length)return null;shaka.util.PeriodCombiner.extendOutputStream_(g,0,e,f,0);return g}static extendOutputStream_(a,b,c,d,e){const f=shaka.util.ManifestParserUtils.ContentType,g=shaka.util.LanguageUtils,h=a.matchedStreams;goog.asserts.assert(a.matchedStreams,
"matchedStreams should be non-null");for(b+=e;b<h.length;b++){const l=h[b];c(a,l);var k=!0;a.type==f.AUDIO&&g.relatedness(a.language,l.language)==0&&(k=!1);if(k&&((k=d[b-e])&&k.delete(l),l.fullMimeTypes))for(const m of l.fullMimeTypes.values())a.fullMimeTypes.add(m)}}static cloneStream_(a){const b=Object.assign({},a);b.originalId=null;b.createSegmentIndex=()=>Promise.resolve();b.closeSegmentIndex=()=>{};b.roles=b.roles.slice();b.segmentIndex=null;b.emsgSchemeIdUris=[];b.keyIds=new Set(a.keyIds);b.closedCaptions=
a.closedCaptions?new Map(a.closedCaptions):null;b.trickModeVideo=null;b.dependencyStream=null;return b}static cloneStreamDB_(a){const b=Object.assign({},a);b.roles=b.roles.slice();b.keyIds=new Set(a.keyIds);b.segments=[];b.variantIds=[];b.closedCaptions=a.closedCaptions?new Map(a.closedCaptions):null;return b}static concatenateStreams_(a,b){var c=(d,e)=>{d||=[];for(const f of e)d.includes(f)||d.push(f);return d};a.roles=c(a.roles,b.roles);b.emsgSchemeIdUris&&(a.emsgSchemeIdUris=c(a.emsgSchemeIdUris,
b.emsgSchemeIdUris));for(const d of b.keyIds)a.keyIds.add(d);a.originalId==null?a.originalId=b.originalId:(c=b.originalId||"")&&!a.originalId.endsWith(c)&&(a.originalId+=","+c);c=shaka.drm.DrmUtils.getCommonDrmInfos(a.drmInfos,b.drmInfos);if(b.drmInfos.length&&a.drmInfos.length&&!c.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.INCONSISTENT_DRM_ACROSS_PERIODS);a.drmInfos=c;a.encrypted=a.encrypted||b.encrypted;if(b.closedCaptions){a.closedCaptions||
(a.closedCaptions=new Map);for(const [d,e]of b.closedCaptions)a.closedCaptions.set(d,e)}a.bandwidth&&b.bandwidth&&(a.bandwidth=Math.max(a.bandwidth,b.bandwidth));b.trickModeVideo?(a.trickModeVideo||(a.trickModeVideo=shaka.util.PeriodCombiner.cloneStream_(b.trickModeVideo),a.trickModeVideo.matchedStreams=[],a.trickModeVideo.createSegmentIndex=()=>{if(a.trickModeVideo.segmentIndex)return Promise.resolve();const d=new shaka.media.MetaSegmentIndex;goog.asserts.assert(a.trickModeVideo.matchedStreams,"trickmode matched streams should exist");
for(const e of a.trickModeVideo.matchedStreams)goog.asserts.assert(e.segmentIndex,"trickmode segment index should exist"),d.appendSegmentIndex(e.segmentIndex);a.trickModeVideo.segmentIndex=d;return Promise.resolve()}),a.trickModeVideo.matchedStreams.push(b.trickModeVideo),shaka.util.PeriodCombiner.concatenateStreams_(a.trickModeVideo,b.trickModeVideo)):a.trickModeVideo&&(a.trickModeVideo.matchedStreams.push(b),shaka.util.PeriodCombiner.concatenateStreams_(a.trickModeVideo,b));b.dependencyStream?(a.dependencyStream||
(a.dependencyStream=shaka.util.PeriodCombiner.cloneStream_(b.dependencyStream),a.dependencyStream.matchedStreams=[],a.dependencyStream.createSegmentIndex=()=>{if(a.dependencyStream.segmentIndex)return Promise.resolve();const d=new shaka.media.MetaSegmentIndex;goog.asserts.assert(a.dependencyStream.matchedStreams,"dependency video matched streams should exist");for(const e of a.dependencyStream.matchedStreams)goog.asserts.assert(e.segmentIndex,"dependency video segment index should exist"),d.appendSegmentIndex(e.segmentIndex);
a.dependencyStream.segmentIndex=d;return Promise.resolve()}),a.dependencyStream.matchedStreams.push(b.dependencyStream),shaka.util.PeriodCombiner.concatenateStreams_(a.dependencyStream,b.dependencyStream)):a.dependencyStream&&(a.dependencyStream.matchedStreams.push(b),shaka.util.PeriodCombiner.concatenateStreams_(a.dependencyStream,b))}static concatenateStreamDBs_(a,b){var c=a.roles,d=b.roles;c||=[];for(const e of d)c.includes(e)||c.push(e);a.roles=c;for(const e of b.keyIds)a.keyIds.add(e);a.encrypted=
a.encrypted&&b.encrypted;a.segments.push(...b.segments);if(b.closedCaptions){a.closedCaptions||(a.closedCaptions=new Map);for(const [e,f]of b.closedCaptions)a.closedCaptions.set(e,f)}}findMatchesInAllPeriods_(a,b,c=!1){c=c?b.matchedStreams:[];for(const d of a){a=this.findBestMatchInPeriod_(d,b);if(!a)return;c.push(a)}b.matchedStreams=c}findBestMatchInPeriod_(a,b){const c={audio:shaka.util.PeriodCombiner.generateAudioKey_,video:shaka.util.PeriodCombiner.generateVideoKey_,text:shaka.util.PeriodCombiner.generateTextKey_,
image:shaka.util.PeriodCombiner.generateImageKey_}[b.type];let d=null;var e=c(b);if(a.has(e))d=a.get(e);else{e={audio:(g,h)=>this.areAVStreamsCompatible_(g,h),video:(g,h)=>this.areAVStreamsCompatible_(g,h),text:shaka.util.PeriodCombiner.areTextStreamsCompatible_,image:shaka.util.PeriodCombiner.areImageStreamsCompatible_}[b.type];const f={audio:shaka.util.PeriodCombiner.isAudioStreamBetterMatch_,video:shaka.util.PeriodCombiner.isVideoStreamBetterMatch_,text:shaka.util.PeriodCombiner.isTextStreamBetterMatch_,
image:shaka.util.PeriodCombiner.isImageStreamBetterMatch_}[b.type];for(const g of a.values())!e(b,g)||b.fastSwitching!=g.fastSwitching||d&&!f(b,d,g)||(d=g)}this.useStreamOnce_&&!shaka.util.PeriodCombiner.isDummy_(d)&&a.delete(c(d));return d}static areAVStreamsExactMatch_(a,b){return a.mimeType===b.mimeType&&a.codecs===b.codecs}static areAVStreamsCodecsCompatible_(a,b){return a.mimeType!=b.mimeType?!1:shaka.util.PeriodCombiner.getCodec_(a.codecs)===shaka.util.PeriodCombiner.getCodec_(b.codecs)}setUseStreamOnce(a){this.useStreamOnce_=
a}areAVStreamsCompatible_(a,b){return a.drmInfos&&!shaka.drm.DrmUtils.areDrmCompatible(a.drmInfos,b.drmInfos)?!1:!0}static areTextStreamsCompatible_(a,b){return b.language?a.forced!==b.forced||shaka.util.LanguageUtils.relatedness(a.language,b.language)==0||b.kind!=a.kind?!1:!0:!0}static areImageStreamsCompatible_(a,b){return!0}static isAudioStreamBetterMatch_(a,b,c){var d=shaka.util.LanguageUtils;const {BETTER:e,WORSE:f}=shaka.util.PeriodCombiner.BetterOrWorse;var g=shaka.util.PeriodCombiner.compareCodecs_(a,
b,c);if(g===e)return!0;if(g===f)return!1;g=d.relatedness(a.language,b.language);d=d.relatedness(a.language,c.language);if(d>g)return!0;if(d<g)return!1;if(b.label!==c.label){if(a.label===b.label)return!1;if(a.label===c.label)return!0}if(a.roles.length){d=b.roles.filter(h=>a.roles.includes(h));g=c.roles.filter(h=>a.roles.includes(h));if(g.length>d.length)return!0;if(g.length<d.length)return!1;if(c.roles.length!==b.roles.length)return c.roles.length<b.roles.length}else{if(!c.roles.length&&b.roles.length)return!0;
if(c.roles.length&&!b.roles.length)return!1}if(!b.primary&&c.primary)return!0;if(b.primary&&!c.primary)return!1;d=shaka.util.PeriodCombiner.compareClosestPreferLower(a.channelsCount,b.channelsCount,c.channelsCount);if(d==e)return!0;if(d==f)return!1;d=shaka.util.PeriodCombiner.compareClosestPreferLower(a.audioSamplingRate,b.audioSamplingRate,c.audioSamplingRate);return d==e?!0:d==f?!1:a.bandwidth&&shaka.util.PeriodCombiner.compareClosestPreferMinimalAbsDiff_(a.bandwidth,b.bandwidth,c.bandwidth)==e?
!0:!1}static isVideoStreamBetterMatch_(a,b,c){const {BETTER:d,WORSE:e}=shaka.util.PeriodCombiner.BetterOrWorse;var f=shaka.util.PeriodCombiner.compareCodecs_(a,b,c);if(f===d)return!0;if(f===e)return!1;f=shaka.util.PeriodCombiner.compareClosestPreferLower(a.width*a.height,b.width*b.height,c.width*c.height);if(f==d)return!0;if(f==e)return!1;if(a.frameRate){f=shaka.util.PeriodCombiner.compareClosestPreferLower(a.frameRate,b.frameRate,c.frameRate);if(f==d)return!0;if(f==e)return!1}return a.bandwidth&&
shaka.util.PeriodCombiner.compareClosestPreferMinimalAbsDiff_(a.bandwidth,b.bandwidth,c.bandwidth)==d?!0:!1}static isTextStreamBetterMatch_(a,b,c){var d=shaka.util.LanguageUtils,e=d.relatedness(a.language,b.language);d=d.relatedness(a.language,c.language);if(d>e)return!0;if(d<e)return!1;if(!b.primary&&c.primary)return!0;if(b.primary&&!c.primary)return!1;if(b.label!==c.label){if(a.label===b.label)return!1;if(a.label===c.label)return!0}if(a.roles.length){e=b.roles.filter(f=>a.roles.includes(f));d=c.roles.filter(f=>
a.roles.includes(f));if(d.length>e.length)return!0;if(d.length<e.length)return!1}else{if(!c.roles.length&&b.roles.length)return!0;if(c.roles.length&&!b.roles.length)return!1}return c.mimeType!=a.mimeType||c.codecs!=a.codecs||b.mimeType==a.mimeType&&b.codecs==a.codecs?!1:!0}static isImageStreamBetterMatch_(a,b,c){const {BETTER:d}=shaka.util.PeriodCombiner.BetterOrWorse;return shaka.util.PeriodCombiner.compareClosestPreferLower(a.width*a.height,b.width*b.height,c.width*c.height)==d?!0:!1}static dummyStreamDB_(a){return{id:0,
originalId:"",groupId:null,primary:!1,type:a,mimeType:"",codecs:"",language:"",originalLanguage:null,label:null,width:null,height:null,encrypted:!1,keyIds:new Set,segments:[],variantIds:[],roles:[],forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null,external:!1,fastSwitching:!1,isAudioMuxedInVideo:!1,baseOriginalId:null}}static dummyStream_(a){return{id:0,originalId:"",groupId:null,createSegmentIndex:()=>Promise.resolve(),segmentIndex:new shaka.media.SegmentIndex([]),
mimeType:"",codecs:"",encrypted:!1,drmInfos:[],keyIds:new Set,language:"",originalLanguage:null,label:null,type:a,primary:!1,trickModeVideo:null,dependencyStream:null,emsgSchemeIdUris:null,roles:[],forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null,accessibilityPurpose:null,external:!1,fastSwitching:!1,fullMimeTypes:new Set,isAudioMuxedInVideo:!1,baseOriginalId:null}}static compareClosestPreferLower(a,b,c){const {BETTER:d,EQUAL:e,WORSE:f}=shaka.util.PeriodCombiner.BetterOrWorse;
if(b==a&&a!=c)return f;if(c==a&&a!=b)return d;if(b>a){if(c<=a||c-a<b-a)return d;if(c-a>b-a)return f}else{if(c>a)return f;if(a-c<a-b)return d;if(a-c>a-b)return f}return e}static compareCodecs_(a,b,c){const {BETTER:d,EQUAL:e,WORSE:f}=shaka.util.PeriodCombiner.BetterOrWorse,g=shaka.util.PeriodCombiner.areAVStreamsExactMatch_(a,b),h=shaka.util.PeriodCombiner.areAVStreamsExactMatch_(a,c);if(g&&!h)return f;if(!g&&h)return d;b=shaka.util.PeriodCombiner.areAVStreamsCodecsCompatible_(a,b);a=shaka.util.PeriodCombiner.areAVStreamsCodecsCompatible_(a,
c);return b&&!a?f:!b&&a?d:e}static compareClosestPreferMinimalAbsDiff_(a,b,c){const {BETTER:d,EQUAL:e,WORSE:f}=shaka.util.PeriodCombiner.BetterOrWorse;b=Math.abs(a-b);a=Math.abs(a-c);return a<b?d:b<a?f:e}static isDummy_(a){const b=shaka.util.ManifestParserUtils.ContentType;switch(a.type){case b.TEXT:return!a.language;case b.IMAGE:return!a.tilesLayout;default:return!1}}static generateVideoKey_(a){return shaka.util.PeriodCombiner.generateKey_([a.fastSwitching,a.width,a.frameRate,a.codecs,a.mimeType,
a.label,a.roles,a.closedCaptions?Array.from(a.closedCaptions.entries()):null,a.bandwidth,a.dependencyStream?a.dependencyStream.baseOriginalId:null,Array.from(a.keyIds)])}static generateAudioKey_(a){return shaka.util.PeriodCombiner.generateKey_([a.fastSwitching,a.channelsCount,a.language,a.bandwidth,a.label,a.codecs,a.mimeType,a.roles,a.audioSamplingRate,a.primary,a.dependencyStream?a.dependencyStream.baseOriginalId:null,Array.from(a.keyIds)])}static generateTextKey_(a){return shaka.util.PeriodCombiner.generateKey_([a.language,
a.label,a.codecs,a.mimeType,a.bandwidth,a.roles])}static generateImageKey_(a){return shaka.util.PeriodCombiner.generateKey_([a.width,a.codecs,a.mimeType])}static generateKey_(a){return JSON.stringify(a)}static getCodec_(a){if(!shaka.util.PeriodCombiner.memoizedCodecs.has(a)){const b=shaka.util.MimeUtils.getNormalizedCodec(a);shaka.util.PeriodCombiner.memoizedCodecs.set(a,b)}return shaka.util.PeriodCombiner.memoizedCodecs.get(a)}static isStreamActivelyUsed_(a,b,c){for(const d of c)if(d!==b&&d.segmentIndex&&
d.matchedStreams&&d.matchedStreams.includes(a))return shaka.log.v2(`Stream ${a.id} is already used in output stream ${d.id}, cannot close it now.`),!0;shaka.log.v2(`Stream ${a.id} not used anywhere else besides ${b.id}, good to close.`);return!1}};goog.exportSymbol("shaka.util.PeriodCombiner",shaka.util.PeriodCombiner);goog.exportProperty(shaka.util.PeriodCombiner.prototype,"setUseStreamOnce",shaka.util.PeriodCombiner.prototype.setUseStreamOnce);
goog.exportProperty(shaka.util.PeriodCombiner.prototype,"combinePeriods",shaka.util.PeriodCombiner.prototype.combinePeriods);goog.exportProperty(shaka.util.PeriodCombiner.prototype,"deleteStream",shaka.util.PeriodCombiner.prototype.deleteStream);goog.exportProperty(shaka.util.PeriodCombiner.prototype,"getImageStreams",shaka.util.PeriodCombiner.prototype.getImageStreams);goog.exportProperty(shaka.util.PeriodCombiner.prototype,"getTextStreams",shaka.util.PeriodCombiner.prototype.getTextStreams);
goog.exportProperty(shaka.util.PeriodCombiner.prototype,"getVariants",shaka.util.PeriodCombiner.prototype.getVariants);shaka.util.PeriodCombiner.BetterOrWorse={BETTER:1,EQUAL:0,WORSE:-1};shaka.util.PeriodCombiner.memoizedCodecs=new Map;shaka.util.XmlUtils=class{static parseXmlString(a,b){var c=new DOMParser,d=shaka.util.XmlUtils.trustedHTMLFromString_.value()(a);a=null;try{a=c.parseFromString(d,"text/xml")}catch(e){return shaka.log.error("XML parsing exception:",e),null}goog.asserts.assert(a,"Parsed XML document cannot be null!");c=a.documentElement;if(!c)return shaka.log.error("XML document was empty!"),null;d=c.getElementsByTagName("parsererror");if(d.length)return shaka.log.error("XML parser error found:",d[0]),null;if(c.tagName!=
b)return shaka.log.error(`XML tag name does not match expected "${b}":`,c.tagName),null;if(!("createNodeIterator"in document))return c;for(b=document.createNodeIterator(a,NodeFilter.SHOW_ALL);a=b.nextNode();)if(a instanceof HTMLElement||a instanceof SVGElement)return shaka.log.error("XML document embeds unsafe content!"),null;return c}static parseXml(a,b){try{const c=shaka.util.StringUtils.fromBytesAutoDetect(a);return shaka.util.XmlUtils.parseXmlString(c,b)}catch(c){return shaka.log.error("parseXmlString threw!",
c),null}}static toArrayBuffer(a){return shaka.util.StringUtils.toUTF8(a.outerHTML)}};shaka.util.XmlUtils.trustedHTMLFromString_=new shaka.util.Lazy(()=>{if(typeof trustedTypes!=="undefined"){const a=trustedTypes.createPolicy("shaka-player#xml",{createHTML:b=>b});return b=>a.createHTML(b)}return a=>a});shaka.dash.DashParser=class{constructor(){this.playerInterface_=this.config_=null;this.manifestUris_=[];this.manifest_=null;this.globalId_=1;this.patchLocationNodes_=[];this.manifestPatchContext_={mpdId:"",type:"",profiles:[],mediaPresentationDuration:null,availabilityTimeOffset:0,getBaseUris:null,publishTime:0};this.contextCache_=new Map;this.continuityCache_=new Map;this.parsedPeriodCache_=new Map;this.streamMap_=new Map;this.indexStreamMap_=new Map;this.periodDurations_=new Map;this.periodCombiner_=
new shaka.util.PeriodCombiner;this.updatePeriod_=0;this.averageUpdateDuration_=new shaka.abr.Ewma(5);this.updateTimer_=new shaka.util.Timer(()=>{if(this.mediaElement_&&!this.config_.continueLoadingWhenPaused&&(this.eventManager_.unlisten(this.mediaElement_,"timeupdate"),this.mediaElement_.paused)){this.eventManager_.listenOnce(this.mediaElement_,"timeupdate",()=>this.onUpdate_());return}this.onUpdate_()});this.operationManager_=new shaka.util.OperationManager;this.largestPeriodStartTime_=null;this.lastManifestUpdatePeriodIds_=
[];this.minTotalAvailabilityTimeOffset_=Infinity;this.lowLatencyMode_=!1;this.contentSteeringManager_=null;this.gapCount_=0;this.isLowLatency_=!1;this.eventManager_=new shaka.util.EventManager;this.mediaElement_=null;this.isTransitionFromDynamicToStatic_=!1;this.lastManifestQueryParams_="";this.isPreloadFn_=()=>!1;this.lastCalculatedBaseUris_=[];this.parsedPrftNodes_=new Set;this.contentProtection_=new shaka.dash.ContentProtection}configure(a,b){goog.asserts.assert(a.dash!=null,"DashManifestConfiguration should not be null!");
const c=this.playerInterface_&&a.updatePeriod!=this.config_.updatePeriod&&a.updatePeriod>=0;this.config_=a;b&&(this.isPreloadFn_=b);c&&this.manifest_&&this.manifest_.presentationTimeline.isLive()&&this.updateNow_();this.contentSteeringManager_&&this.contentSteeringManager_.configure(this.config_);this.periodCombiner_&&this.periodCombiner_.setUseStreamOnce(this.config_.dash.useStreamOnceInPeriodFlattening)}async start(a,b){goog.asserts.assert(this.config_,"Must call configure() before start()!");this.lowLatencyMode_=
b.isLowLatencyMode();this.manifestUris_=[a];this.playerInterface_=b;a=await this.requestManifest_();this.playerInterface_&&this.setUpdateTimer_(a);if(!this.playerInterface_)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.OPERATION_ABORTED);goog.asserts.assert(this.manifest_,"Manifest should be non-null!");return this.manifest_}stop(){for(const a of this.streamMap_.values())a.segmentIndex&&a.segmentIndex.release();this.periodCombiner_&&
this.periodCombiner_.release();this.config_=this.playerInterface_=null;this.manifestUris_=[];this.manifest_=null;this.streamMap_.clear();this.indexStreamMap_.clear();this.contextCache_.clear();this.continuityCache_.clear();this.parsedPeriodCache_.clear();this.manifestPatchContext_={mpdId:"",type:"",profiles:[],mediaPresentationDuration:null,availabilityTimeOffset:0,getBaseUris:null,publishTime:0};this.periodCombiner_=null;this.updateTimer_!=null&&(this.updateTimer_.stop(),this.updateTimer_=null);
this.contentSteeringManager_&&this.contentSteeringManager_.destroy();this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null);this.parsedPrftNodes_.clear();this.contentProtection_.release();return this.operationManager_.destroy()}async update(){try{await this.requestManifest_()}catch(a){this.playerInterface_&&a&&(goog.asserts.assert(a instanceof shaka.util.Error,"Bad error type"),this.playerInterface_.onError(a))}}onExpirationUpdated(a,b){}onInitialVariantChosen(a){if(this.manifest_&&
this.manifest_.presentationTimeline.isLive()){var b=a.video||a.audio;if(b&&b.segmentIndex){a=this.manifest_.presentationTimeline.getSegmentAvailabilityEnd();const c=b.segmentIndex.find(a);c!=null&&(b=b.segmentIndex.get(c))&&(this.updatePeriod_=b.endTime-a,this.setUpdateTimer_(0))}}}banLocation(a){this.contentSteeringManager_&&this.contentSteeringManager_.banLocation(a)}setMediaElement(a){this.mediaElement_=a}async requestManifest_(){var a=shaka.net.NetworkingEngine.RequestType.MANIFEST;let b=shaka.net.NetworkingEngine.AdvancedRequestType.MPD;
var c="MPD",d=this.getPatchLocationUris_(),e=this.manifestUris_;d.length?(e=d,c="Patch",b=shaka.net.NetworkingEngine.AdvancedRequestType.MPD_PATCH):this.manifestUris_.length>1&&this.contentSteeringManager_&&(d=this.contentSteeringManager_.getLocations("Location",!0),d.length&&(e=d));d=shaka.net.NetworkingEngine.makeRequest(e,this.config_.retryParameters);e=Date.now();a=await this.makeNetworkRequest_(d,a,{type:b});if(!this.playerInterface_)return 0;a.uri&&a.uri!=a.originalUri&&!this.manifestUris_.includes(a.uri)&&
this.manifestUris_.unshift(a.uri);this.lastManifestQueryParams_=(new goog.Uri(a.uri)).getQueryData().toString();await this.parseManifest_(a.data,a.uri,c);c=(Date.now()-e)/1E3;this.averageUpdateDuration_.sample(1,c);this.parsedPrftNodes_.clear();return c}async parseManifest_(a,b,c){var d=a;a=this.config_.dash.manifestPreprocessor;if(a!=shaka.util.PlayerConfiguration.defaultManifestPreprocessor){shaka.Deprecate.deprecateFeature(5,"manifest.dash.manifestPreprocessor configuration","Please Use manifest.dash.manifestPreprocessorTXml instead.");
d=shaka.util.XmlUtils.parseXml(d,c);if(!d)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_INVALID_XML,b);a(d);d=shaka.util.XmlUtils.toArrayBuffer(d)}a=shaka.util.TXml.parseXml(d,c);if(!a)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_INVALID_XML,b);d=this.config_.dash.manifestPreprocessorTXml;d!=shaka.util.PlayerConfiguration.defaultManifestPreprocessorTXml&&
d(a);if(c==="Patch")return this.processPatchManifest_(a);if(this.config_.dash.disableXlinkProcessing)return this.processManifest_(a,b);c=shaka.dash.MpdUtils.processXlinks(a,this.config_.retryParameters,this.config_.dash.xlinkFailGracefully,b,this.playerInterface_.networkingEngine);this.operationManager_.manage(c);c=await c.promise;return this.processManifest_(c,b)}async processManifest_(a,b){var c=shaka.util.TXml;goog.asserts.assert(this.config_,"Must call configure() before processManifest_()!");
this.contentSteeringManager_&&this.contentSteeringManager_.clearPreviousLocations();b=[b];var d=[],e=new Map,f=c.findChildren(a,"Location");for(var g of f){f=g.attributes.serviceLocation;var h=c.getContents(g);if(!h)continue;h=shaka.util.ManifestParserUtils.resolveUris(b,[h])[0];f&&(this.contentSteeringManager_?this.contentSteeringManager_.addLocation("Location",f,h):e.set(f,h));d.push(h)}this.contentSteeringManager_?(g=this.contentSteeringManager_.getLocations("Location",!0),g.length>0&&(b=this.manifestUris_=
g)):d.length&&(b=this.manifestUris_=d);this.manifestPatchContext_.mpdId=a.attributes.id||"";this.manifestPatchContext_.publishTime=c.parseAttr(a,"publishTime",c.parseDate)||0;this.patchLocationNodes_=c.findChildren(a,"PatchLocation");g=Promise.resolve();if((d=c.findChild(a,"ContentSteering"))&&this.playerInterface_){f=d.attributes.defaultServiceLocation;this.contentSteeringManager_?(this.contentSteeringManager_.setBaseUris(b),this.contentSteeringManager_.setDefaultPathwayId(f)):(this.contentSteeringManager_=
new shaka.util.ContentSteeringManager(this.playerInterface_),this.contentSteeringManager_.configure(this.config_),this.contentSteeringManager_.setManifestType(shaka.media.ManifestParser.DASH),this.contentSteeringManager_.setBaseUris(b),this.contentSteeringManager_.setDefaultPathwayId(f),(f=c.getContents(d))&&(c.parseAttr(d,"queryBeforeStart",c.parseBoolean,!1)?g=this.contentSteeringManager_.requestInfo(f):this.contentSteeringManager_.requestInfo(f)));for(var k of e.keys())d=e.get(k),this.contentSteeringManager_.addLocation("Location",
k,d)}k=c.findChildren(a,"BaseURL");e=!1;if(this.contentSteeringManager_)for(var l of k)d=l.attributes.serviceLocation,f=c.getContents(l),d&&f&&(this.contentSteeringManager_.addLocation("BaseURL",d,f),e=!0);this.lastCalculatedBaseUris_.splice(0);e&&this.contentSteeringManager_||(l=k.map(c.getContents),this.lastCalculatedBaseUris_.push(...shaka.util.ManifestParserUtils.resolveUris(b,l)));b=shaka.dash.DashParser.makeBaseUriGetter_.call(shaka.dash.DashParser,this.contentSteeringManager_,e,this.lastCalculatedBaseUris_);
this.manifestPatchContext_.getBaseUris=b;d=0;k&&k.length&&(d=c.parseAttr(k[0],"availabilityTimeOffset",c.parseFloat)||0);this.manifestPatchContext_.availabilityTimeOffset=d;this.updatePeriod_=c.parseAttr(a,"minimumUpdatePeriod",c.parseDuration,-1);h=c.parseAttr(a,"availabilityStartTime",c.parseDate);f=c.parseAttr(a,"timeShiftBufferDepth",c.parseDuration);l=null;this.config_.dash.ignoreSuggestedPresentationDelay||(l=c.parseAttr(a,"suggestedPresentationDelay",c.parseDuration));k=null;this.config_.dash.ignoreMaxSegmentDuration||
(k=c.parseAttr(a,"maxSegmentDuration",c.parseDuration));e=a.attributes.type||"static";this.manifest_&&this.manifest_.presentationTimeline&&(this.isTransitionFromDynamicToStatic_=this.manifest_.presentationTimeline.isLive()&&e=="static");this.manifestPatchContext_.type=e;if(this.manifest_){c=this.manifest_.presentationTimeline;h=c.getSegmentAvailabilityStart();for(var m of this.streamMap_.values())m.segmentIndex&&m.segmentIndex.evict(h)}else m=0,this.config_.dash.ignoreMinBufferTime||(m=c.parseAttr(a,
"minBufferTime",c.parseDuration)||0),c=new shaka.media.PresentationTimeline(h,l!=null?Math.min(l,f||Infinity):this.config_.defaultPresentationDelay>0?this.config_.defaultPresentationDelay:Math.min(m*1.5,f||Infinity),this.config_.dash.autoCorrectDrift);c.setStatic(e=="static");c.isLive()&&!isNaN(this.config_.availabilityWindowOverride)&&(f=this.config_.availabilityWindowOverride);f==null&&(f=Infinity);c.setSegmentAvailabilityDuration(f);m=a.attributes.profiles||"";this.manifestPatchContext_.profiles=
m.split(",");d={dynamic:e!="static",presentationTimeline:c,period:null,periodInfo:null,adaptationSet:null,representation:null,bandwidth:0,indexRangeWarningGiven:!1,availabilityTimeOffset:d,mediaPresentationDuration:null,profiles:m.split(","),roles:null,urlParams:shaka.dash.DashParser.defaultUrlParams_};await g;this.gapCount_=0;g=this.parsePeriods_(d,b,a,!1);f=g.duration;m=g.periods;(e!="static"||this.isTransitionFromDynamicToStatic_)&&g.durationDerivedFromPeriods||c.setDuration(f||Infinity);this.isLowLatency_&&
this.lowLatencyMode_&&c.setAvailabilityTimeOffset(this.minTotalAvailabilityTimeOffset_);c.notifyMaxSegmentDuration(k||1);goog.DEBUG&&!this.isTransitionFromDynamicToStatic_&&c.assertIsValid();this.isLowLatency_&&this.lowLatencyMode_&&c.setDelay(l!=null?l:this.config_.defaultPresentationDelay);if(this.manifest_)this.manifest_.periodCount=m.length,this.manifest_.gapCount=this.gapCount_,await this.postPeriodProcessing_(m,!1);else{await this.periodCombiner_.combinePeriods(m,d.dynamic);this.manifest_={presentationTimeline:c,
variants:this.periodCombiner_.getVariants(),textStreams:this.periodCombiner_.getTextStreams(),imageStreams:this.periodCombiner_.getImageStreams(),offlineSessionIds:[],sequenceMode:this.config_.dash.sequenceMode,ignoreManifestTimestampsInSegmentsMode:!1,type:shaka.media.ManifestParser.DASH,serviceDescription:this.parseServiceDescription_(a),nextUrl:this.parseMpdChaining_(a),periodCount:m.length,gapCount:this.gapCount_,isLowLatency:this.isLowLatency_,startTime:null};if(c.usingPresentationStartTime()){a=
shaka.util.TXml.findChildren(a,"UTCTiming");a=await this.parseUtcTiming_(b,a);if(!this.playerInterface_)return;c.setClockOffset(a)}c.lockStartTime();this.periodCombiner_&&!this.manifest_.presentationTimeline.isLive()&&this.periodCombiner_.release()}this.playerInterface_.makeTextStreamsForClosedCaptions(this.manifest_);this.cleanStreamMap_();this.cleanContinuityCache_(m)}async postPeriodProcessing_(a,b){await this.periodCombiner_.combinePeriods(a,!0,b);this.manifest_.variants=this.periodCombiner_.getVariants();
a=this.periodCombiner_.getTextStreams();a.length>0&&(this.manifest_.textStreams=a);this.manifest_.imageStreams=this.periodCombiner_.getImageStreams();this.playerInterface_.filter(this.manifest_)}async processPatchManifest_(a){const b=shaka.util.TXml;var c=a.attributes.mpdId,d=b.parseAttr(a,"originalPublishTime",b.parseDate);if(!c||c!==this.manifestPatchContext_.mpdId||d!==this.manifestPatchContext_.publishTime)throw this.patchLocationNodes_=[],new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,
shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_INVALID_PATCH);c=[];d=[];const e=new Set;for(const g of b.getChildNodes(a)){a=!0;var f=b.parseXpath(g.attributes.sel||"");f=f[f.length-1];const h=b.getContents(g)||"";if(f.name==="MPD")f.attribute==="mediaPresentationDuration"?(f=b.getContents(g)||"",this.parsePatchMediaPresentationDurationChange_(f)):f.attribute==="type"?this.parsePatchMpdTypeChange_(h):f.attribute==="publishTime"?this.manifestPatchContext_.publishTime=b.parseDate(h)||
0:f.attribute===null&&g.tagName==="add"?d.push(g):a=!1;else if(f.name==="PatchLocation")this.updatePatchLocationNodes_(g);else if(f.name==="Period")g.tagName==="add"?d.push(g):g.tagName==="remove"&&f.id&&this.removePatchPeriod_(f.id);else if(f.name==="SegmentTemplate"){f=this.modifySegmentTemplate_(g);for(const k of f)e.add(k)}else if(f.name==="SegmentTimeline"||f.name==="S"){f=this.modifyTimepoints_(g);for(const k of f)e.add(k)}else a=!1;a||shaka.log.warning("Unhandled "+g.tagName+" operation",g.attributes.sel)}for(const g of e)this.parsePatchSegment_(g);
for(const g of d)c.push(...this.parsePatchPeriod_(g));c.length&&(this.manifest_.periodCount+=c.length,this.manifest_.gapCount=this.gapCount_,await this.postPeriodProcessing_(c,!0));this.manifestPatchContext_.type=="static"&&this.manifest_.presentationTimeline.setDuration(this.manifestPatchContext_.mediaPresentationDuration||Infinity)}parsePatchMpdTypeChange_(a){this.manifest_.presentationTimeline.setStatic(a=="static");this.manifestPatchContext_.type=a;for(const b of this.contextCache_.values())b.dynamic=
a=="dynamic";a=="static"&&(this.updatePeriod_=-1)}parsePatchMediaPresentationDurationChange_(a){a=shaka.util.TXml.parseDuration(a);if(a!=null){this.manifestPatchContext_.mediaPresentationDuration=a;for(const b of this.contextCache_.values())b.mediaPresentationDuration=a}}parsePatchPeriod_(a){goog.asserts.assert(this.manifestPatchContext_.getBaseUris,"Must provide getBaseUris on manifestPatchContext_");return this.parsePeriods_({dynamic:this.manifestPatchContext_.type=="dynamic",presentationTimeline:this.manifest_.presentationTimeline,
period:null,periodInfo:null,adaptationSet:null,representation:null,bandwidth:0,indexRangeWarningGiven:!1,availabilityTimeOffset:this.manifestPatchContext_.availabilityTimeOffset,profiles:this.manifestPatchContext_.profiles,mediaPresentationDuration:this.manifestPatchContext_.mediaPresentationDuration,roles:null,urlParams:shaka.dash.DashParser.defaultUrlParams_},this.manifestPatchContext_.getBaseUris,a,!0).periods}removePatchPeriod_(a){const b=shaka.dash.SegmentTemplate;this.manifest_.periodCount--;
for(const c of this.contextCache_.keys())if(c.startsWith(a)){const d=this.contextCache_.get(c);b.removeTimepoints(d);this.parsePatchSegment_(c);this.contextCache_.delete(c)}this.lastManifestUpdatePeriodIds_=this.lastManifestUpdatePeriodIds_.filter(c=>c!==a);this.parsedPeriodCache_.delete(a)}getContextIdsFromPath_(a){let b="",c="",d=-1,e="";for(const f of a)f.name==="Period"?b=f.id:f.name==="AdaptationSet"?(c=f.id,f.position!==null&&(d=f.position)):f.name==="Representation"&&(e=f.id);a=[];if(e)a.push(b+
","+e);else if(c)for(const f of this.contextCache_.values())f.period.id===b&&f.adaptationSet.id===c&&f.representation.id&&a.push(b+","+f.representation.id);else if(d>-1)for(const f of this.contextCache_.values())f.period.id===b&&f.adaptationSet.position===d&&f.representation.id&&a.push(b+","+f.representation.id);return a}modifySegmentTemplate_(a){const b=shaka.util.TXml;var c=b.parseXpath(a.attributes.sel||"");const d=c[c.length-1];if(!d.attribute)return[];c=this.getContextIdsFromPath_(c);const e=
b.getContents(a)||"";for(const f of c){const g=this.contextCache_.get(f);goog.asserts.assert(g&&g.representation.segmentTemplate,"cannot modify segment template");b.modifyNodeAttribute(g.representation.segmentTemplate,a.tagName,d.attribute,e)}return c}modifyTimepoints_(a){const b=shaka.dash.SegmentTemplate;var c=shaka.util.TXml.parseXpath(a.attributes.sel||"");c=this.getContextIdsFromPath_(c);for(const d of c){const e=this.contextCache_.get(d);b.modifyTimepoints(e,a)}return c}parsePatchSegment_(a){var b=
this.contextCache_.get(a);const c=this.streamMap_.get(a);goog.asserts.assert(c,"stream should exist");c.segmentIndex&&c.segmentIndex.evict(this.manifest_.presentationTimeline.getSegmentAvailabilityStart());try{const d=shaka.dash.SegmentTemplate.createStreamInfo(b,(e,f,g,h)=>this.requestSegment_(e,f,g,h),this.streamMap_,!0,this.config_.dash.initialSegmentLimit,this.periodDurations_,b.representation.aesKey,null,!0,this.continuityCache_);c.createSegmentIndex=async()=>{c.segmentIndex||(c.segmentIndex=
await d.generateSegmentIndex())}}catch(d){a=shaka.util.ManifestParserUtils.ContentType;b=b.representation.contentType;const e=b==a.IMAGE;if(b!=a.TEXT&&b!=a.APPLICATION&&!e||d.code!=shaka.util.Error.Code.DASH_NO_SEGMENT_INFO)throw d;}}parseServiceDescription_(a){var b=shaka.util.TXml,c=b.findChild(a,"ServiceDescription");if(!c)return null;a=b.findChild(c,"Latency");b=b.findChild(c,"PlaybackRate");if(!a&&!b)return null;c={};a&&("target"in a.attributes&&(c.targetLatency=parseInt(a.attributes.target,
10)/1E3),"max"in a.attributes&&(c.maxLatency=parseInt(a.attributes.max,10)/1E3),"min"in a.attributes&&(c.minLatency=parseInt(a.attributes.min,10)/1E3));b&&("max"in b.attributes&&(c.maxPlaybackRate=parseFloat(b.attributes.max)),"min"in b.attributes&&(c.minPlaybackRate=parseFloat(b.attributes.min)));return c}parseMpdChaining_(a){a=shaka.util.TXml.findChildren(a,"SupplementalProperty");if(!a.length)return null;for(const b of a)if(b.attributes.schemeIdUri=="urn:mpeg:dash:chaining:2016")return b.attributes.value;
return null}parsePeriods_(a,b,c,d){const e=shaka.util.TXml;let f=a.mediaPresentationDuration;f||(f=e.parseAttr(c,"mediaPresentationDuration",e.parseDuration),this.manifestPatchContext_.mediaPresentationDuration=f);let g=0;this.manifest_&&this.manifest_.presentationTimeline&&this.isTransitionFromDynamicToStatic_&&(g=this.manifest_.presentationTimeline.getSeekRangeStart());const h=[];var k=g;c=e.findChildren(c,"Period");const l=a.dynamic;l||this.parsedPeriodCache_.clear();const m=l&&!d?new Set(this.lastManifestUpdatePeriodIds_.slice(1,
-1)):null;for(let t=0;t<c.length;t++){var n=c[t];const u=c[t+1];let v=e.parseAttr(n,"start",e.parseDuration,k);var q=n.attributes.id,p=e.parseAttr(n,"duration",e.parseDuration);v=t==0&&v==0&&this.isTransitionFromDynamicToStatic_?g:v;let x=null;if(u){var r=e.parseAttr(u,"start",e.parseDuration);r!=null&&(x=r-v+g)}else f!=null&&(x=f-v+g);r=shaka.util.ManifestParserUtils.GAP_OVERLAP_TOLERANCE_SECONDS;x&&p&&Math.abs(x-p)>r&&(shaka.log.warning("There is a gap/overlap between Periods",n),x>p&&this.gapCount_++);
x==null&&(x=p);if(this.largestPeriodStartTime_!==null&&q!=null&&v!==null&&v<this.largestPeriodStartTime_&&!this.lastManifestUpdatePeriodIds_.includes(q)&&t+1!=c.length){shaka.log.debug(`Skipping Period with ID ${q} as its start time is smaller`+" than the largest period start time that has been seen, and ID is unseen before");continue}v!==null&&(this.largestPeriodStartTime_===null||v>this.largestPeriodStartTime_)&&(this.largestPeriodStartTime_=v);k={start:v,duration:x,node:n,isLastPeriod:x==null||
!u};n=null;p=t>0&&t<c.length-1;l&&m&&p&&!d&&(q??=this.periodIdFallback_(v),m.has(q)&&(q=this.parsedPeriodCache_.get(q))&&(n=q));n||(n=this.parsePeriod_(a,b,k),l&&n.id&&this.parsedPeriodCache_.set(n.id,n));h.push(n);n.id&&x&&this.periodDurations_.set(n.id,x);if(x==null){u&&shaka.log.warning("Skipping Period",t+1,"and any subsequent Periods:","Period",t+1,"does not have a valid start time.",u);k=null;break}k=v+x}l&&!d&&this.prunePeriodCache_(h);if(d)for(const t of h)a=t.id,this.lastManifestUpdatePeriodIds_.includes(a)||
this.lastManifestUpdatePeriodIds_.push(a);else this.lastManifestUpdatePeriodIds_=h.map(t=>t.id);return f!=null?(k!=null&&Math.abs(k-g-f)>shaka.util.ManifestParserUtils.GAP_OVERLAP_TOLERANCE_SECONDS&&shaka.log.warning("@mediaPresentationDuration does not match the total duration ","of all Periods."),{periods:h,duration:f+g,durationDerivedFromPeriods:!1}):{periods:h,duration:k,durationDerivedFromPeriods:!0}}prunePeriodCache_(a){a=new Set(a.map(b=>b.id));for(const b of Array.from(this.parsedPeriodCache_.keys()))a.has(b)||
this.parsedPeriodCache_.delete(b)}periodIdFallback_(a){return"__shaka_period_"+a}cleanStreamMap_(){var a=Array.from(this.indexStreamMap_.keys()).filter(b=>!this.lastManifestUpdatePeriodIds_.includes(b));for(const b of a){a=!0;for(const c of this.indexStreamMap_.get(b)){const d=this.streamMap_.get(c);d&&(d.segmentIndex&&!d.segmentIndex.isEmpty()?a=!1:(this.periodCombiner_&&this.periodCombiner_.deleteStream(d,b),this.streamMap_.delete(c)))}a&&this.indexStreamMap_.delete(b)}}cleanContinuityCache_(a){a=
new Set(a.map(b=>b.id));for(const b of this.continuityCache_.keys())a.has(b)||this.continuityCache_.delete(b)}parsePeriod_(a,b,c){const d=shaka.util.Functional,e=shaka.util.TXml;var f=shaka.util.ManifestParserUtils.ContentType;goog.asserts.assert(c.node,"periodInfo.node should exist");a.period=this.createFrame_(c.node,null,b);a.periodInfo=c;a.period.availabilityTimeOffset=a.availabilityTimeOffset;a.period.id||(shaka.log.info("No Period ID given for Period with start time "+c.start+",  Assigning a default"),
a.period.id=this.periodIdFallback_(c.start));b=e.findChildren(c.node,"EventStream");const g=a.presentationTimeline.getSegmentAvailabilityStart();for(var h of b)this.parseEventStream_(c.start,c.duration,h,g);h=e.findChildren(c.node,"SupplementalProperty");for(var k of h)k.attributes.schemeIdUri=="urn:mpeg:dash:urlparam:2014"&&(h=this.getURLParametersFunction_(k))&&(a.urlParams=h);k=e.findChildren(c.node,"AdaptationSet").map((v,x)=>this.parseAdaptationSet_(a,x,v)).filter(d.isNotNull);if(a.dynamic){h=
[];for(var l of k)for(var m of l.representationIds)h.push(m);l=new Set(h);if(h.length!=l.size)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_DUPLICATE_REPRESENTATION_ID);}l=new Map;for(var n of k)for(const [v,x]of n.dependencyStreamMap)l.set(v,x);if(l.size){n=null;for(const v of k){m=[];for(const x of v.streams)if(l.has(x.originalId)){n||=e.findChildren(c.node,"AdaptationSet").map((y,A)=>this.parseAdaptationSet_(a,A,y)).filter(d.isNotNull);
for(const y of n)if(h=y.streams.find(A=>A.originalId==x.originalId))h.dependencyStream=l.get(h.originalId),h.originalId+=h.dependencyStream.originalId,m.push(h)}m.length&&v.streams.push(...m)}}const [q,p]=shaka.util.ArrayUtils.partition(k,v=>!!v.trickModeFor);if(!this.config_.disableIFrames)for(var r of q){c=r.trickModeFor.split(" ");for(var t of p)if(c.includes(t.id))for(var u of t.streams)shaka.util.StreamUtils.setBetterIFrameStream(u,r.streams)}r=this.getStreamsFromSets_(this.config_.disableAudio,
p,f.AUDIO);t=this.getStreamsFromSets_(this.config_.disableVideo,p,f.VIDEO);u=this.getStreamsFromSets_(this.config_.disableText,p,f.TEXT);f=this.getStreamsFromSets_(this.config_.disableThumbnails,p,f.IMAGE);if(t.length===0&&r.length===0)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_EMPTY_PERIOD);return{id:a.period.id,audioStreams:r,videoStreams:t,textStreams:u,imageStreams:f}}getStreamsFromSets_(a,b,c){return a||!b.length?
[]:b.reduce((d,e)=>{if(e.contentType!=c)return d;d.push(...e.streams);return d},[])}parseAdaptationSet_(a,b,c){var d=shaka.util.TXml,e=shaka.util.Functional,f=shaka.util.ManifestParserUtils,g=f.ContentType;a.adaptationSet=this.createFrame_(c,a.period,null);a.adaptationSet.position=b;let h=!1;b=d.findChildren(c,"Role");const k=b.map(E=>E.attributes.value).filter(e.isNotNull);let l=void 0;if(e=a.adaptationSet.contentType==g.TEXT)l=f.TextStreamKind.SUBTITLE;for(var m of b)if(b=m.attributes.schemeIdUri,
b==null||b=="urn:mpeg:dash:role:2011")switch(b=m.attributes.value,b){case "main":h=!0;break;case "caption":case "subtitle":l=b}let n,q;b=E=>{switch(E){case 1:case 6:case 13:case 14:case 15:return"SDR";case 16:return"PQ";case 18:return"HLG"}};var p=E=>{switch(E){case 1:case 5:case 6:case 7:return"srgb";case 9:return"rec2020";case 11:case 12:return"p3"}},r=E=>{const K=E.attributes["dvb:fontFamily"];E=E.attributes["dvb:url"];K&&E&&(E=shaka.util.ManifestParserUtils.resolveUris(a.adaptationSet.getBaseUris(),
[E],a.urlParams()),this.playerInterface_.addFont(K,E[0]))},t=d.findChildren(c,"EssentialProperty");m=null;let u=!1,v=null,x=!1;for(var y of t)t=y.attributes.schemeIdUri,t=="http://dashif.org/guidelines/trickmode"?m=y.attributes.value:t=="urn:mpeg:mpegB:cicp:TransferCharacteristics"?n=b(parseInt(y.attributes.value,10)):t=="urn:mpeg:mpegB:cicp:ColourPrimaries"?q=p(parseInt(y.attributes.value,10)):t!="urn:mpeg:mpegB:cicp:MatrixCoefficients"&&(t=="urn:mpeg:dash:ssr:2023"&&this.config_.dash.enableFastSwitching?
u=!0:t=="urn:dvb:dash:fontdownload:2014"?r(y):t=="urn:mpeg:dash:urlparam:2014"?(v=this.getURLParametersFunction_(y))||(x=!0):x=!0);if(x)return null;let A=null;y=d.findChildren(c,"SupplementalProperty");for(var w of y)y=w.attributes.schemeIdUri,y=="http://dashif.org/guidelines/last-segment-number"?A=parseInt(w.attributes.value,10)-1:y=="urn:mpeg:mpegB:cicp:TransferCharacteristics"?n=b(parseInt(w.attributes.value,10)):y=="urn:mpeg:mpegB:cicp:ColourPrimaries"?q=p(parseInt(w.attributes.value,10)):y==
"urn:dvb:dash:fontdownload:2014"?r(w):y=="urn:mpeg:dash:urlparam:2014"&&(v=this.getURLParametersFunction_(w));v&&(a.urlParams=v);y=d.findChildren(c,"Accessibility");w=shaka.util.LanguageUtils;const z=new Map;let B;for(var C of y)if(y=C.attributes.schemeIdUri,b=C.attributes.value,y!="urn:scte:dash:cc:cea-608:2015"||this.config_.disableText)if(y!="urn:scte:dash:cc:cea-708:2015"||this.config_.disableText)y=="urn:mpeg:dash:role:2011"?b!=null&&(k.push(b),b=="captions"&&(l=f.TextStreamKind.CLOSED_CAPTION)):
y=="urn:tva:metadata:cs:AudioPurposeCS:2007"&&(b=="1"?B=shaka.media.ManifestParser.AccessibilityPurpose.VISUALLY_IMPAIRED:b=="2"?B=shaka.media.ManifestParser.AccessibilityPurpose.HARD_OF_HEARING:b=="9"&&(B=shaka.media.ManifestParser.AccessibilityPurpose.SPOKEN_SUBTITLES));else if(y=1,b!=null)for(const E of b.split(";"))E.includes("=")?(p=E.split("="),b=`svc${p[0]}`,p=p[1].split(",")[0].split(":").pop()):(b=`svc${y}`,y++,p=E),z.set(b,w.normalize(p));else z.set("svc1","und");else if(y=1,b!=null){b=
b.split(";");for(var F of b)F.includes("=")?(r=F.split("="),p=r[0].startsWith("CC")?r[0]:`CC${r[0]}`,r=r[1]||"und"):(p=`CC${y}`,b.length==2?y+=2:y++,r=F),z.set(p,w.normalize(r))}else z.set("CC1","und");f=d.findChildren(c,"ContentProtection");const H=this.contentProtection_.parseFromAdaptationSet(f,this.config_.ignoreDrmInfo,this.config_.dash.keySystemsByURI);a.adaptationSet.encrypted=f.length>0;const I=shaka.util.LanguageUtils.normalize(a.adaptationSet.language||"und"),D=a.adaptationSet.label,J=new Map;
c=d.findChildren(c,"Representation");if(!this.config_.ignoreSupplementalCodecs){f=[];for(const E of c)if(C=d.getAttributeNS(E,shaka.dash.DashParser.SCTE214_,"supplementalCodecs"))F=shaka.util.ObjectUtils.cloneObject(E),F.attributes.codecs=C.split(" ").join(","),F.attributes.id&&(F.attributes.supplementalId=F.attributes.id+"_supplementalCodecs"),f.push(F);c.push(...f)}d=c.map(E=>{const K=this.parseRepresentation_(a,H,l,I,D,h,k,z,E,B,A);return K&&(K.hdr=K.hdr||n,K.colorGamut=K.colorGamut||q,K.fastSwitching=
u,E=E.attributes.dependencyId)?(K.baseOriginalId=E,J.set(E,K),null):K}).filter(E=>!!E);if(d.length==0&&J.size==0){var G=a.adaptationSet.contentType==g.IMAGE;if(this.config_.dash.ignoreEmptyAdaptationSet||e||G)return null;throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_EMPTY_ADAPTATION_SET);}if(!a.adaptationSet.contentType||a.adaptationSet.contentType==g.APPLICATION){a.adaptationSet.contentType=shaka.dash.DashParser.guessContentType_(d[0].mimeType,
d[0].codecs);for(const E of d)E.type=a.adaptationSet.contentType}g=a.adaptationSet.id||"__fake__"+this.globalId_++;for(G of d){for(const E of H.drmInfos)E.keyIds=E.keyIds&&G.keyIds?new Set([...E.keyIds,...G.keyIds]):E.keyIds||G.keyIds;this.config_.enableAudioGroups&&(G.groupId=g)}G=c.map(E=>E.attributes.supplementalId||E.attributes.id).filter(shaka.util.Functional.isNotNull);return{id:g,contentType:a.adaptationSet.contentType,language:I,main:h,streams:d,drmInfos:H.drmInfos,trickModeFor:m,representationIds:G,
dependencyStreamMap:J}}getURLParametersFunction_(a){const b=shaka.util.TXml;if((a=b.findChildNS(a,shaka.dash.DashParser.UP_NAMESPACE_,"UrlQueryInfo"))&&b.parseAttr(a,"useMPDUrlQuery",b.parseBoolean,!1)){const c=a.attributes.queryTemplate;if(c)return()=>c=="$querypart$"?this.lastManifestQueryParams_:c.split("&").map(d=>{if(d=="$querypart$")return this.lastManifestQueryParams_;var e=/\$query:(.*?)\$/g.exec(d);if(e&&e.length==2){e=e[1];const f=(new goog.Uri.QueryData(this.lastManifestQueryParams_)).get(e);
if(f.length)return e+"="+f[0]}return d}).join("&")}return null}parseRepresentation_(a,b,c,d,e,f,g,h,k,l,m){var n=shaka.util.TXml,q=shaka.util.ManifestParserUtils.ContentType;a.representation=this.createFrame_(k,a.adaptationSet,null);var p=a.representation.id;this.minTotalAvailabilityTimeOffset_=Math.min(this.minTotalAvailabilityTimeOffset_,a.representation.availabilityTimeOffset);this.isLowLatency_=this.minTotalAvailabilityTimeOffset_>0;if(!this.verifyRepresentation_(a.representation))return shaka.log.warning("Skipping Representation",
a.representation),null;const r=a.periodInfo.start;a.bandwidth=n.parseAttr(k,"bandwidth",n.parsePositiveInt)||0;a.roles=g;var t=n.findChildren(k,"SupplementalProperty"),u=n.findChildren(k,"EssentialProperty");n=n.findChildren(k,"ContentProtection");k=null;var v=u.find(B=>B.attributes.schemeIdUri=="urn:mpeg:dash:urlparam:2014");v?k=this.getURLParametersFunction_(v):(v=t.find(B=>B.attributes.schemeIdUri=="urn:mpeg:dash:urlparam:2014"))&&(k=this.getURLParametersFunction_(v));k&&(a.urlParams=k);let x;
v=a.representation.contentType;k=v==q.TEXT||v==q.APPLICATION;q=v==q.IMAGE;n.length&&(a.adaptationSet.encrypted=!0);try{let B=void 0;if(b.aes128Info){var y=a.representation.getBaseUris;const C=a.urlParams,F=shaka.util.ManifestParserUtils.resolveUris(y(),[b.aes128Info.keyUri],C()),H=shaka.net.NetworkingEngine.RequestType.KEY,I=shaka.net.NetworkingEngine.makeRequest(F,this.config_.retryParameters);B={bitsKey:128,blockCipherMode:"CBC",iv:b.aes128Info.iv,firstMediaSequenceNumber:0,fetchKey:async()=>{const D=
await this.makeNetworkRequest_(I,H);if(!D.data||D.data.byteLength!=16)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.AES_128_INVALID_KEY_LENGTH);B.cryptoKey=await window.crypto.subtle.importKey("raw",D.data,{name:"AES-CBC"},!0,["decrypt"]);B.fetchKey=void 0}}}a.representation.aesKey=B;y=(C,F,H,I)=>this.requestSegment_(C,F,H,I);if(a.representation.segmentBase)x=shaka.dash.SegmentBase.createStreamInfo(a,y,B);else if(a.representation.segmentList)x=
shaka.dash.SegmentList.createStreamInfo(a,this.streamMap_,B);else if(a.representation.segmentTemplate)x=shaka.dash.SegmentTemplate.createStreamInfo(a,y,this.streamMap_,!!this.manifest_,this.config_.dash.initialSegmentLimit,this.periodDurations_,B,m,!1,this.continuityCache_);else{goog.asserts.assert(k,"Must have Segment* with non-text streams.");const C=a.periodInfo.duration||0,F=a.representation.getBaseUris,H=a.representation.mimeType,I=a.representation.codecs;x={endTime:-1,timeline:-1,generateSegmentIndex:()=>
{const D=shaka.media.SegmentIndex.forSingleSegment(r,C,F());D.forEachTopLevelReference(J=>{J.mimeType=H;J.codecs=I});return Promise.resolve(D)},timescale:1}}}catch(B){if((k||q)&&B.code==shaka.util.Error.Code.DASH_NO_SEGMENT_INFO)return null;throw B;}m=this.contentProtection_.parseFromRepresentation(n,b,this.config_.ignoreDrmInfo,this.config_.dash.keySystemsByURI);m=new Set(m?[m]:[]);y=t.some(B=>B.attributes.schemeIdUri=="tag:dolby.com,2018:dash:EC3_ExtensionType:2018"&&B.attributes.value=="JOC");
t=t.some(B=>B.attributes.schemeIdUri=="tag:dolby.com,2016:dash:virtualized_content:2016"&&B.attributes.value=="1");t=y||t;y=!1;k&&(y=g.includes("forced_subtitle")||g.includes("forced-subtitle"));let A;if(q&&((u=u.find(B=>["http://dashif.org/thumbnail_tile","http://dashif.org/guidelines/thumbnail_tile"].includes(B.attributes.schemeIdUri)))&&(A=u.attributes.value),!A))return null;let w;k=a.representation.codecs;a.profiles.includes("http://dashif.org/guidelines/dash-if-uhd#hevc-hdr-pq10")&&(k.includes("hvc1.2.4.L153.B0")||
k.includes("hev1.2.4.L153.B0"))&&(w="PQ");u=a.representation.id?a.period.id+","+a.representation.id:"";this.patchLocationNodes_.length&&p&&this.contextCache_.set(`${a.period.id},${p}`,this.cloneContext_(a));a.representation.producerReferenceTime&&this.parseProducerReferenceTime_(a.representation.producerReferenceTime,x,a.presentationTimeline);x.endTime!=-1&&a.period.id!=null&&a.representation.id!=null&&((p=this.continuityCache_.get(a.period.id))?(p.endTime=x.endTime,p.reps.includes(a.representation.id)||
p.reps.push(a.representation.id),this.continuityCache_.set(a.period.id,p)):this.continuityCache_.set(a.period.id,{endTime:x.endTime,timeline:x.timeline,reps:[a.representation.id]}));let z;z=u&&this.streamMap_.has(u)?this.streamMap_.get(u):{id:this.globalId_++,originalId:a.representation.id,groupId:null,createSegmentIndex:()=>Promise.resolve(),closeSegmentIndex:()=>{z.segmentIndex&&(z.segmentIndex.release(),z.segmentIndex=null)},segmentIndex:null,mimeType:a.representation.mimeType,codecs:k,frameRate:a.representation.frameRate,
pixelAspectRatio:a.representation.pixelAspectRatio,bandwidth:a.bandwidth,width:a.representation.width,height:a.representation.height,kind:c,encrypted:b.drmInfos.length>0,drmInfos:b.drmInfos,keyIds:m,language:d,originalLanguage:a.adaptationSet.language,label:e,type:a.adaptationSet.contentType,primary:f,trickModeVideo:null,dependencyStream:null,emsgSchemeIdUris:a.representation.emsgSchemeIdUris,roles:g,forced:y,channelsCount:a.representation.numChannels,audioSamplingRate:a.representation.audioSamplingRate,
spatialAudio:t,closedCaptions:h,hdr:w,colorGamut:void 0,videoLayout:void 0,tilesLayout:A,accessibilityPurpose:l,external:!1,fastSwitching:!1,fullMimeTypes:new Set([shaka.util.MimeUtils.getFullType(a.representation.mimeType,a.representation.codecs)]),isAudioMuxedInVideo:!1,baseOriginalId:null};z.createSegmentIndex=async()=>{z.segmentIndex||(z.segmentIndex=await x.generateSegmentIndex())};u&&a.dynamic&&!this.streamMap_.has(u)&&(a=a.period.id||"",this.indexStreamMap_.has(a)||this.indexStreamMap_.set(a,
[]),this.streamMap_.set(u,z),this.indexStreamMap_.get(a).push(u));return z}parseProducerReferenceTime_(a,b,c){const d=shaka.util.TXml;if(!this.parsedPrftNodes_.has(a)){this.parsedPrftNodes_.add(a);var e=d.parseAttr(a,"presentationTime",d.parseNonNegativeInt)||0,f=d.findChild(a,"UTCTiming");f&&f.attributes.schemeIdUri&&!shaka.dash.DashParser.isNtpScheme_(f.attributes.schemeIdUri)?a=(d.parseAttr(a,"wallClockTime",d.parseDate)||0)*1E3:(a=d.parseAttr(a,"wallClockTime",d.parseNonNegativeInt)||0,a=shaka.util.TimeUtils.convertNtp(a));
b=new Date(a-e/b.timescale*1E3);e=b.getTime()/1E3;isNaN(e)||(c.isStartTimeLocked()||c.setInitialProgramDateTime(e),b={wallClockTime:a,programStartDate:b},c=shaka.util.FakeEvent.EventName.Prft,b=(new Map).set("detail",b),c=new shaka.util.FakeEvent(c,b),this.playerInterface_.onEvent(c))}}cloneContext_(a){const b=c=>{if(!c)return null;c=shaka.util.ObjectUtils.shallowCloneObject(c);c.segmentBase=null;c.segmentList=null;c.segmentTemplate=shaka.util.TXml.cloneNode(c.segmentTemplate);c.producerReferenceTime=
null;return c};a=shaka.util.ObjectUtils.shallowCloneObject(a);a.period=b(a.period);a.adaptationSet=b(a.adaptationSet);a.representation=b(a.representation);a.periodInfo&&(a.periodInfo=shaka.util.ObjectUtils.shallowCloneObject(a.periodInfo),a.periodInfo.node=null);return a}async onUpdate_(){goog.asserts.assert(this.updatePeriod_>=0,"There should be an update period");shaka.log.info("Updating manifest...");let a=0;try{a=await this.requestManifest_()}catch(b){if(goog.asserts.assert(b instanceof shaka.util.Error,
"Should only receive a Shaka error"),this.playerInterface_){if(this.config_.raiseFatalErrorOnManifestUpdateRequestFailure){this.playerInterface_.onError(b);return}b.severity=shaka.util.Error.Severity.RECOVERABLE;this.playerInterface_.onError(b)}}this.playerInterface_&&(this.playerInterface_.onManifestUpdated(),this.setUpdateTimer_(a))}updateNow_(){this.updateTimer_.tickNow()}setUpdateTimer_(a){if(!(this.updatePeriod_<0)){var b=this.updatePeriod_;this.config_.updatePeriod>=0&&(b=this.config_.updatePeriod);
a=Math.max(b-a,this.averageUpdateDuration_.getEstimate());this.updateTimer_.tickAfter(a)}}createFrame_(a,b,c){goog.asserts.assert(b||c,"Must provide either parent or getBaseUris");var d=shaka.media.SegmentUtils;const e=shaka.util.ManifestParserUtils,f=shaka.util.TXml;b=b||{contentType:"",mimeType:"",codecs:"",emsgSchemeIdUris:[],frameRate:void 0,pixelAspectRatio:void 0,numChannels:null,audioSamplingRate:null,availabilityTimeOffset:0,segmentSequenceCadence:1,encrypted:!1};c=c||b.getBaseUris;const g=
f.parseNonNegativeInt;var h=f.evalDivision;const k=a.attributes.id,l=a.attributes.supplementalId,m=f.findChildren(a,"BaseURL");let n,q=!1;if(this.contentSteeringManager_)for(var p of m){var r=p.attributes.serviceLocation,t=f.getContents(p);r&&t&&(this.contentSteeringManager_.addLocation(k,r,t),q=!0)}q&&this.contentSteeringManager_||(n=m.map(f.getContents));const u=this.contentSteeringManager_;p=a.attributes.contentType||b.contentType;r=a.attributes.mimeType||b.mimeType;d=d.codecsFiltering([a.attributes.codecs||
b.codecs]).join(",");h=f.parseAttr(a,"frameRate",h)||b.frameRate;t=a.attributes.sar||b.pixelAspectRatio;const v=this.emsgSchemeIdUris_(f.findChildren(a,"InbandEventStream"),b.emsgSchemeIdUris);var x=f.findChildren(a,"AudioChannelConfiguration");x=this.parseAudioChannels_(x)||b.numChannels;const y=f.parseAttr(a,"audioSamplingRate",g)||b.audioSamplingRate;p||=shaka.dash.DashParser.guessContentType_(r,d);const A=f.findChild(a,"SegmentBase"),w=f.findChild(a,"SegmentTemplate");var z=A?f.parseAttr(A,"availabilityTimeOffset",
f.parseFloat)||0:0,B=w?f.parseAttr(w,"availabilityTimeOffset",f.parseFloat)||0:0,C=m&&m.length?f.parseAttr(m[0],"availabilityTimeOffset",f.parseFloat)||0:0;z=b.availabilityTimeOffset+C+z+B;B=null;(C=f.findChild(a,"SegmentSequenceProperties"))&&(C=f.parseAttr(C,"cadence",f.parsePositiveInt))&&(B=C);C=a.attributes.label;var F=f.findChildren(a,"Label");F&&F.length&&(F=F[0],f.getTextContents(F)&&(C=f.getTextContents(F)));return{getBaseUris:()=>e.resolveUris(c(),m.length?u&&q?u.getLocations(k):n?n:[]:
[]),segmentBase:A||b.segmentBase,segmentList:f.findChild(a,"SegmentList")||b.segmentList,segmentTemplate:w||b.segmentTemplate,producerReferenceTime:f.findChild(a,"ProducerReferenceTime")||b.producerReferenceTime,width:f.parseAttr(a,"width",g)||b.width,height:f.parseAttr(a,"height",g)||b.height,contentType:p,mimeType:r,codecs:d,frameRate:h,pixelAspectRatio:t,emsgSchemeIdUris:v,id:l||k,originalId:k,language:a.attributes.lang,numChannels:x,audioSamplingRate:y,availabilityTimeOffset:z,initialization:null,
segmentSequenceCadence:B||b.segmentSequenceCadence,label:C||null,encrypted:!1}}emsgSchemeIdUris_(a,b){b=b.slice();for(const c of a)a=c.attributes.schemeIdUri,b.includes(a)||b.push(a);return b}parseAudioChannels_(a){for(const e of a){a=e.attributes.schemeIdUri;if(!a)continue;var b=e.attributes.value;if(b)switch(a){case "urn:mpeg:dash:outputChannelPositionList:2012":return b.trim().split(/ +/).length;case "urn:mpeg:dash:23003:3:audio_channel_configuration:2011":case "urn:dts:dash:audio_channel_configuration:2012":var c=
parseInt(b,10);if(!c){shaka.log.warning("Channel parsing failure! Ignoring scheme and value",a,b);continue}return c;case "tag:dolby.com,2015:dash:audio_channel_configuration:2015":c=[2,1,2,2,2,2,1,2,2,1,1,1,1,2,1,1,2,2];var d=parseInt(b,16);if(!d){shaka.log.warning("Channel parsing failure! Ignoring scheme and value",a,b);continue}a=0;for(b=0;b<c.length;b++)d&1<<b&&(a+=c[b]);if(a)return a;continue;case "tag:dolby.com,2014:dash:audio_channel_configuration:2011":case "urn:dolby:dash:audio_channel_configuration:2011":c=
[1,1,1,1,1,2,2,1,1,2,2,2,1,2,1,1].reverse();d=parseInt(b,16);if(!d){shaka.log.warning("Channel parsing failure! Ignoring scheme and value",a,b);continue}a=0;for(b=0;b<c.length;b++)d&1<<b&&(a+=c[b]);if(a)return a;continue;case "urn:mpeg:mpegB:cicp:ChannelConfiguration":c=[0,1,2,3,4,5,6,8,2,3,4,7,8,24,8,12,10,12,14,12,14];d=parseInt(b,10);if(!d){shaka.log.warning("Channel parsing failure! Ignoring scheme and value",a,b);continue}if(d>0&&d<c.length)return c[d];continue;default:shaka.log.warning("Unrecognized audio channel scheme:",
a,b)}}return null}verifyRepresentation_(a){const b=shaka.util.ManifestParserUtils.ContentType;let c;c=a.segmentBase?1:0;c+=a.segmentList?1:0;c+=a.segmentTemplate?1:0;if(c==0){if(a.contentType==b.TEXT||a.contentType==b.APPLICATION)return!0;shaka.log.warning("Representation does not contain a segment information source:","the Representation must contain one of SegmentBase, SegmentList,",'SegmentTemplate, or explicitly indicate that it is "text".',a);return!1}c!=1&&(shaka.log.warning("Representation contains multiple segment information sources:",
"the Representation should only contain one of SegmentBase,","SegmentList, or SegmentTemplate.",a),a.segmentBase?(shaka.log.info("Using SegmentBase by default."),a.segmentList=null):(goog.asserts.assert(a.segmentList,"There should be a SegmentList"),shaka.log.info("Using SegmentList by default.")),a.segmentTemplate=null);return!0}async requestForTiming_(a,b,c){b=[shaka.util.StringUtils.htmlUnescape(b)];a=shaka.util.ManifestParserUtils.resolveUris(a(),b);a=shaka.net.NetworkingEngine.makeRequest(a,
this.config_.retryParameters);a.method=c;a=this.playerInterface_.networkingEngine.request(shaka.net.NetworkingEngine.RequestType.TIMING,a,{isPreload:this.isPreloadFn_()});this.operationManager_.manage(a);a=await a.promise;if(c=="HEAD"){if(!a.headers||!a.headers.date)return shaka.log.warning("UTC timing response is missing","expected date header"),0;c=a.headers.date}else c=shaka.util.StringUtils.fromUTF8(a.data);c=Date.parse(c);return isNaN(c)?(shaka.log.warning("Unable to parse date from UTC timing response"),
0):c-Date.now()}async parseUtcTiming_(a,b){b=b.map(d=>({scheme:d.attributes.schemeIdUri,value:d.attributes.value}));const c=this.config_.dash.clockSyncUri;!b.length&&c&&b.push({scheme:"urn:mpeg:dash:utc:http-head:2014",value:c});for(const d of b)try{const e=d.scheme,f=d.value;switch(e){case "urn:mpeg:dash:utc:http-head:2014":case "urn:mpeg:dash:utc:http-head:2012":return await this.requestForTiming_(a,f,"HEAD");case "urn:mpeg:dash:utc:http-xsdate:2014":case "urn:mpeg:dash:utc:http-iso:2014":case "urn:mpeg:dash:utc:http-xsdate:2012":case "urn:mpeg:dash:utc:http-iso:2012":return await this.requestForTiming_(a,
f,"GET");case "urn:mpeg:dash:utc:direct:2014":case "urn:mpeg:dash:utc:direct:2012":const g=Date.parse(f);return isNaN(g)?0:g-Date.now();case "urn:mpeg:dash:utc:http-ntp:2014":case "urn:mpeg:dash:utc:ntp:2014":case "urn:mpeg:dash:utc:sntp:2014":shaka.log.alwaysWarn("NTP UTCTiming scheme is not supported");break;default:shaka.log.alwaysWarn("Unrecognized scheme in UTCTiming element",e)}}catch(e){shaka.log.warning("Error fetching time from UTCTiming elem",e.message)}shaka.log.alwaysWarn("A UTCTiming element should always be given in live manifests! This content may not play on clients with bad clocks!");
return 0}parseEventStream_(a,b,c,d){const e=shaka.util.TXml,f=shaka.util.TXml.parseNonNegativeInt,g=c.attributes.schemeIdUri||"",h=c.attributes.value||"",k=e.parseAttr(c,"timescale",f)||1,l=e.parseAttr(c,"presentationTimeOffset",f)||0;for(const n of e.findChildren(c,"Event")){var m=e.parseAttr(n,"presentationTime",f)||0;c=e.parseAttr(n,"duration",f)||0;m=Math.max((m-l)/k+a,a);c=m+c/k;b!=null&&(m=Math.min(m,a+b),c=Math.min(c,a+b));if(c<d)continue;c={schemeIdUri:g,value:h,startTime:m,endTime:c,id:n.attributes.id||
"",timescale:k,eventElement:e.txmlNodeToDomElement(n),eventNode:e.cloneNode(n)};this.playerInterface_.onTimelineRegionAdded(c)}}async requestSegment_(a,b,c,d){const e=shaka.net.NetworkingEngine.RequestType.SEGMENT;d=d?shaka.net.NetworkingEngine.AdvancedRequestType.INIT_SEGMENT:shaka.net.NetworkingEngine.AdvancedRequestType.MEDIA_SEGMENT;a=shaka.net.NetworkingUtils.createSegmentRequest(a,b,c,this.config_.retryParameters);return(await this.makeNetworkRequest_(a,e,{type:d})).data}static guessContentType_(a,
b){b=shaka.util.MimeUtils.getFullType(a,b);return shaka.text.TextEngine.isTypeSupported(b)?shaka.util.ManifestParserUtils.ContentType.TEXT:a.split("/")[0]}makeNetworkRequest_(a,b,c){c||={};c.isPreload=this.isPreloadFn_();a=this.playerInterface_.networkingEngine.request(b,a,c);this.operationManager_.manage(a);return a.promise}updatePatchLocationNodes_(a){shaka.util.TXml.modifyNodes(this.patchLocationNodes_,a)}getPatchLocationUris_(){const a=shaka.util.TXml,b=this.manifestPatchContext_.publishTime;
if(!this.manifestPatchContext_.mpdId||!b||!this.patchLocationNodes_.length)return[];const c=Date.now()/1E3,d=this.patchLocationNodes_.filter(e=>{e=a.parseNonNegativeInt(e.attributes.ttl);return!e||b+e>c}).map(a.getContents).filter(shaka.util.Functional.isNotNull);return d.length?shaka.util.ManifestParserUtils.resolveUris(this.manifestUris_,d):[]}static isNtpScheme_(a){return a==="urn:mpeg:dash:utc:http-ntp:2014"||a==="urn:mpeg:dash:utc:ntp:2014"||a==="urn:mpeg:dash:utc:sntp:2014"}static defaultUrlParams_(){return""}static makeBaseUriGetter_(a,
b,c){return()=>a&&b?a.getLocations("BaseURL"):c.slice()}};goog.exportSymbol("shaka.dash.DashParser",shaka.dash.DashParser);shaka.dash.DashParser.SCTE214_="urn:scte:dash:scte214-extensions";shaka.dash.DashParser.UP_NAMESPACE_="urn:mpeg:dash:schema:urlparam:2014";shaka.media.ManifestParser.registerParserByMime("application/dash+xml",()=>new shaka.dash.DashParser);shaka.media.ManifestParser.registerParserByMime("video/vnd.mpeg.dash.mpd",()=>new shaka.dash.DashParser);shaka.debug={};shaka.debug.RunningInLab=!1;shaka.dependencies=class{static add(a,b){if(!shaka.dependencies.Allowed[a])throw Error(`${a} is not supported`);a==shaka.dependencies.Allowed.muxjs?shaka.Deprecate.deprecateFeature(5,"mux.js","mux.js is no longer used in Shaka Player."):shaka.dependencies.dependencies_.set(a,()=>b)}static has(a){return shaka.dependencies.dependencies_.has(a)}static isoBoxer(){return shaka.dependencies.dependencies_.get(shaka.dependencies.Allowed.ISOBoxer)()}};goog.exportSymbol("shaka.dependencies",shaka.dependencies);
goog.exportProperty(shaka.dependencies,"has",shaka.dependencies.has);goog.exportProperty(shaka.dependencies,"add",shaka.dependencies.add);shaka.dependencies.Allowed={muxjs:"muxjs",ISOBoxer:"ISOBoxer"};goog.exportProperty(shaka.dependencies,"Allowed",shaka.dependencies.Allowed);shaka.dependencies.dependencies_=new Map([[shaka.dependencies.Allowed.ISOBoxer,()=>window.ISOBoxer]]);shaka.device.AbstractDevice=class{constructor(){this.abstractDeviceType_=new shaka.util.Lazy(()=>{var a=navigator.userAgent.toLowerCase(),b=[{type:shaka.device.IDevice.DeviceType.VR,regex:/oculus|quest/},{type:shaka.device.IDevice.DeviceType.TV,regex:/smart[ _]?tv|android ?tv/},{type:shaka.device.IDevice.DeviceType.MOBILE,regex:/iphone|ipad|ipod|android/}];for(const c of b)if(c.regex.test(a))return c.type;a=navigator.userAgentData;b=a?.platform?.toLowerCase()||"";if(a){if(a.mobile)return shaka.device.IDevice.DeviceType.MOBILE;
if(b.includes("android"))return shaka.device.IDevice.DeviceType.TV}return shaka.device.IDevice.DeviceType.DESKTOP});this.browserEngine_=new shaka.util.Lazy(()=>{const a=navigator.userAgent;return navigator.vendor.includes("Apple")&&(a.includes("Version/")||a.includes("OS/"))?shaka.device.IDevice.BrowserEngine.WEBKIT:a.includes("Edge/")?shaka.device.IDevice.BrowserEngine.EDGE:a.includes("Chrome/")?shaka.device.IDevice.BrowserEngine.CHROMIUM:a.includes("Firefox/")?shaka.device.IDevice.BrowserEngine.GECKO:
shaka.device.IDevice.BrowserEngine.UNKNOWN})}supportsMediaSource(){const a=window.ManagedMediaSource||window.MediaSource;return a&&a.isTypeSupported?!0:!1}supportsMediaType(a){return shaka.util.Dom.anyMediaElement().canPlayType(a)!=""}supportsMediaCapabilities(){return!!navigator.mediaCapabilities}getDeviceType(){return this.abstractDeviceType_.value()}getBrowserEngine(){return this.browserEngine_.value()}requiresEncryptionInfoInAllInitSegments(a,b){return!1}requiresClearAndEncryptedInitSegments(){return!1}insertEncryptionDataBeforeClear(){return!1}requiresTfhdFix(a){return!1}requiresEC3InitSegments(){return!1}supportsSequenceMode(){return!0}supportsSmoothCodecSwitching(){const a=
window.ManagedSourceBuffer||window.SourceBuffer;return!!a&&!!a.prototype&&!!a.prototype.changeType}supportsServerCertificate(){return!0}seekDelay(){return 0}detectMaxHardwareResolution(){return Promise.resolve({width:Infinity,height:Infinity})}shouldOverrideDolbyVisionCodecs(){return!1}shouldAvoidUseTextDecoderEncoder(){return!1}adjustConfig(a){const b=this.getDeviceType();if(b===shaka.device.IDevice.DeviceType.TV||b===shaka.device.IDevice.DeviceType.CONSOLE||b===shaka.device.IDevice.DeviceType.CAST)a.ads.customPlayheadTracker=
!0,a.ads.skipPlayDetection=!0,a.ads.supportsMultipleMediaElements=!1;return a}supportsOfflineStorage(){return!!window.indexedDB}rejectCodecs(){return[]}getHdrLevel(a){return window.matchMedia!==void 0&&(window.matchMedia("(color-gamut: p3)").matches||window.matchMedia("(dynamic-range: high)").matches)?a?"HLG":"PQ":"SDR"}supportsAirPlay(){return!1}misreportAC3UsingDrm(){return!1}returnLittleEndianUsingPlayReady(){return!1}supportsEncryptionSchemePolyfill(){return!0}misreportsSupportForPersistentLicenses(){return!1}supportStandardVP9Checking(){return!0}createMediaKeysWhenCheckingSupport(){return!0}disableHEVCSupport(){return!1}supportsCbcsWithoutEncryptionSchemeSupport(){return!1}needWaitForEncryptedEvent(a){return a===
"com.apple.fps"}supportsContainerChangeType(){return!0}toString(){return`Device: ${this.getDeviceName()} v${this.getVersion()}; Type: ${this.getDeviceType()}`}};shaka.device.AppleBrowser=class extends shaka.device.AbstractDevice{constructor(){super();this.version_=new shaka.util.Lazy(()=>{let a=navigator.userAgent.match(/Version\/(\d+)(?:\.(\d+))?/);a||=navigator.userAgent.match(/OS (\d+)(?:_(\d+))?/);return a?[parseInt(a[1],10),parseInt(a[2]||"0",10)]:[0,0]});this.deviceType_=new shaka.util.Lazy(()=>/(?:iPhone|iPad|iPod)/.test(navigator.userAgent)||navigator.maxTouchPoints>1?"xr"in navigator?shaka.device.IDevice.DeviceType.APPLE_VR:shaka.device.IDevice.DeviceType.MOBILE:
"xr"in navigator?shaka.device.IDevice.DeviceType.APPLE_VR:shaka.device.IDevice.DeviceType.DESKTOP)}getVersion(){return this.version_.value()[0]}getDeviceName(){return"Apple Browser"}getDeviceType(){return this.deviceType_.value()}getBrowserEngine(){return shaka.device.IDevice.BrowserEngine.WEBKIT}supportsMediaCapabilities(){return!1}requiresEncryptionInfoInAllInitSegments(a,b){return!this.supportsMixedClearEncryptedContent_()&&b==="audio"}insertEncryptionDataBeforeClear(){return!this.supportsMixedClearEncryptedContent_()}requiresTfhdFix(a){return!this.supportsMixedClearEncryptedContent_()&&
a==="audio"}adjustConfig(a){super.adjustConfig(a);a.abr.minTimeToSwitch=.5;return a}supportsAirPlay(){return!0}supportsContainerChangeType(){return!1}supportsMixedClearEncryptedContent_(){const a=this.version_.value();return a[0]>=27?!0:a[0]===26&&a[1]>=4}static isAppleBrowser_(){return(navigator.vendor||"").includes("Apple")?/(?:iPhone|iPad|iPod)/.test(navigator.userAgent)||navigator.maxTouchPoints>1||navigator.userAgentData&&navigator.userAgentData.platform&&navigator.userAgentData.platform.toLowerCase()==
"macos"||navigator.platform&&navigator.platform.toLowerCase().includes("mac")?!0:!1:!1}};shaka.device.AppleBrowser.isAppleBrowser_()&&shaka.device.DeviceFactory.registerDeviceFactory(()=>new shaka.device.AppleBrowser);shaka.device.Chromecast=class extends shaka.device.AbstractDevice{constructor(){if(!shaka.device.Chromecast.isChromecast_())throw Error("Not a Chromecast device!");super();this.version_=new shaka.util.Lazy(()=>{const a=navigator.userAgent.match(/Chrome\/(\d+)/);return a?parseInt(a[1],10):null});this.osType_=new shaka.util.Lazy(()=>{let a=navigator.userAgentData&&navigator.userAgentData.platform||navigator.userAgent;a=a.toLowerCase();return a.includes("android")?shaka.device.Chromecast.OsType_.ANDROID:
a.includes("fuchsia")?shaka.device.Chromecast.OsType_.FUCHSIA:shaka.device.Chromecast.OsType_.LINUX})}getVersion(){return this.version_.value()}getDeviceName(){return"Chromecast with "+this.osType_.value()}getDeviceType(){return shaka.device.IDevice.DeviceType.CAST}getBrowserEngine(){return shaka.device.IDevice.BrowserEngine.CHROMIUM}supportsMediaCapabilities(){return super.supportsMediaCapabilities()&&this.osType_.value()!==shaka.device.Chromecast.OsType_.LINUX}supportsSmoothCodecSwitching(){return super.supportsSmoothCodecSwitching()&&
this.osType_.value()!==shaka.device.Chromecast.OsType_.LINUX}seekDelay(){switch(this.osType_.value()){case shaka.device.Chromecast.OsType_.ANDROID:return 0;case shaka.device.Chromecast.OsType_.FUCHSIA:return 3;default:return 1}}async detectMaxHardwareResolution(){const a=window.cast&&cast.__platform__&&cast.__platform__.canDisplayType,b={width:1280,height:720};try{a&&await cast.__platform__.canDisplayType('video/mp4; codecs="avc1.640028"; width=3840; height=2160')?(b.width=3840,b.height=2160):a&&
await cast.__platform__.canDisplayType('video/mp4; codecs="avc1.640028"; width=1920; height=1080')&&(b.width=1920,b.height=1080)}catch(c){shaka.log.alwaysError("Failed to check canDisplayType:",c)}return b}adjustConfig(a){super.adjustConfig(a);a.streaming.stallSkip=0;return a}supportsOfflineStorage(){return!1}supportsCbcsWithoutEncryptionSchemeSupport(){return!0}static isChromecast_(){return navigator.userAgent.includes("CrKey")&&!navigator.userAgent.includes("VIZIO SmartCast")}};
shaka.device.Chromecast.OsType_={ANDROID:"Android",FUCHSIA:"Fuchsia",LINUX:"Linux"};shaka.device.Chromecast.isChromecast_()&&shaka.device.DeviceFactory.registerDeviceFactory(()=>new shaka.device.Chromecast);shaka.device.DefaultBrowser=class extends shaka.device.AbstractDevice{constructor(){super();this.version_=new shaka.util.Lazy(()=>{const a=navigator.userAgent.match(/(Chrome|Firefox)\/(\d+)/);return a?parseInt(a[2],10):null});this.deviceName_=new shaka.util.Lazy(()=>navigator.userAgent.match(/Edge?\//)?"Edge":navigator.userAgent.includes("Chrome")?"Chrome":navigator.userAgent.includes("Firefox")?"Firefox":"Unknown");this.isWindows_=new shaka.util.Lazy(()=>navigator.userAgentData&&navigator.userAgentData.platform?
navigator.userAgentData.platform.toLowerCase()=="windows":navigator.platform?navigator.platform.toLowerCase().includes("win32"):!1);this.supportsSmoothCodecSwitching_=new shaka.util.Lazy(()=>super.supportsSmoothCodecSwitching()?navigator.userAgent.match(/Edge?\//)?!this.isWindows_.value():!0:!1);this.isSonyTV_=new shaka.util.Lazy(()=>navigator.userAgent.includes("sony.hbbtv.tv"));this.isAndroid_=new shaka.util.Lazy(()=>navigator.userAgentData&&navigator.userAgentData.platform?navigator.userAgentData.platform.toLowerCase()==
"android":navigator.userAgent.includes("Android")?!0:!1)}getVersion(){return this.version_.value()}getDeviceName(){return this.deviceName_.value()}requiresEncryptionInfoInAllInitSegments(a){return shaka.drm.DrmUtils.isPlayReadyKeySystem(a)?this.deviceName_.value()==="Edge"&&this.isWindows_.value():!1}requiresClearAndEncryptedInitSegments(){return this.deviceName_.value()==="Edge"&&this.isWindows_.value()}insertEncryptionDataBeforeClear(){return this.deviceName_.value()==="Edge"&&this.isWindows_.value()}supportsSmoothCodecSwitching(){return this.supportsSmoothCodecSwitching_.value()}adjustConfig(a){super.adjustConfig(a);
if(this.isWindows_.value())switch(this.deviceName_.value()){case "Firefox":a.drm.keySystemsMapping={"com.microsoft.playready":"com.microsoft.playready.recommendation"};break;case "Chrome":a.drm.keySystemsMapping={"com.microsoft.playready":"com.microsoft.playready.recommendation.3000","com.microsoft.playready.recommendation":"com.microsoft.playready.recommendation.3000"}}this.isAndroid_.value()&&(a.drm.defaultAudioRobustnessForWidevine="",a.drm.defaultVideoRobustnessForWidevine="");return a}returnLittleEndianUsingPlayReady(){return this.deviceName_.value()===
"Edge"||this.isSonyTV_.value()}createMediaKeysWhenCheckingSupport(){return goog.DEBUG&&shaka.debug.RunningInLab&&this.isWindows_.value()&&this.getBrowserEngine()===shaka.device.IDevice.BrowserEngine.GECKO?!1:!0}disableHEVCSupport(){return this.isWindows_.value()&&this.getBrowserEngine()===shaka.device.IDevice.BrowserEngine.GECKO}supportsCbcsWithoutEncryptionSchemeSupport(){if(this.getBrowserEngine()===shaka.device.IDevice.BrowserEngine.GECKO){const a=this.getVersion();return a!==null?a>=100:super.supportsCbcsWithoutEncryptionSchemeSupport()}return super.supportsCbcsWithoutEncryptionSchemeSupport()}needWaitForEncryptedEvent(a){return this.getBrowserEngine()===
shaka.device.IDevice.BrowserEngine.GECKO?a.startsWith("com.microsoft.playready.recommendation"):super.needWaitForEncryptedEvent(a)}};shaka.device.DeviceFactory.registerDefaultDeviceFactory(()=>new shaka.device.DefaultBrowser);shaka.device.Hisense=class extends shaka.device.AbstractDevice{getVersion(){return null}getDeviceName(){return"Hisense"}getDeviceType(){return shaka.device.IDevice.DeviceType.TV}supportsMediaCapabilities(){return!1}supportsSmoothCodecSwitching(){return!1}detectMaxHardwareResolution(){const a={width:1920,height:1080};let b=null;if(window.Hisense_Get4KSupportState)try{b=window.Hisense_Get4KSupportState()}catch(c){shaka.log.debug("Hisense: Failed to get 4K support state",c)}b==null&&(b=navigator.userAgent.includes("UHD"));
b&&(a.width=3840,a.height=2160);return Promise.resolve(a)}adjustConfig(a){super.adjustConfig(a);a.streaming.stallSkip=0;return a}static isHisense_(){return navigator.userAgent.includes("Hisense")||navigator.userAgent.includes("VIDAA")}};shaka.device.Hisense.isHisense_()&&shaka.device.DeviceFactory.registerDeviceFactory(()=>new shaka.device.Hisense);shaka.device.PlayStation=class extends shaka.device.AbstractDevice{constructor(){super();this.version_=new shaka.util.Lazy(()=>{const a=navigator.userAgent.match(/PlayStation (\d+)/);return a?parseInt(a[1],10):null})}getDeviceName(){return"PlayStation"}getDeviceType(){return shaka.device.IDevice.DeviceType.CONSOLE}getBrowserEngine(){return shaka.device.IDevice.BrowserEngine.WEBKIT}getVersion(){return this.version_.value()}supportsMediaCapabilities(){return!1}supportsSequenceMode(){return!1}supportsSmoothCodecSwitching(){return!1}shouldAvoidUseTextDecoderEncoder(){return this.getVersion()===
4}async detectMaxHardwareResolution(){const a={width:1920,height:1080};let b=!1;try{b=(await window.msdk.device.getDisplayInfo()).resolution==="4K"}catch(c){try{b=(await window.msdk.device.getDisplayInfoImmediate()).resolution==="4K"}catch(d){shaka.log.alwaysWarn("PlayStation: Failed to get the display info:",d)}}b&&(a.width=3840,a.height=2160);return a}adjustConfig(a){super.adjustConfig(a);this.getVersion()===4&&a.drm.preferredKeySystems.push("com.microsoft.playready");a.streaming.clearDecodingCache=
!0;return a}returnLittleEndianUsingPlayReady(){return this.getVersion()===4}supportsEncryptionSchemePolyfill(){return this.getVersion()!==4}static isPlayStation_(){return navigator.userAgent.includes("PlayStation")}};shaka.device.PlayStation.isPlayStation_()&&shaka.device.DeviceFactory.registerDeviceFactory(()=>new shaka.device.PlayStation);shaka.device.Tizen=class extends shaka.device.AbstractDevice{constructor(){super();const a=navigator.userAgent.match(/Tizen (\d+).(\d+)/);this.osMajorVersion_=a?parseInt(a[1],10):null;this.osMinorVersion_=a?parseInt(a[2],10):null}getVersion(){return this.osMajorVersion_}getDeviceName(){return"Tizen"}getBrowserEngine(){return shaka.device.IDevice.BrowserEngine.CHROMIUM}getDeviceType(){return shaka.device.IDevice.DeviceType.TV}requiresEncryptionInfoInAllInitSegments(a){return!0}requiresEC3InitSegments(){return this.getVersion()===
3}supportsMediaCapabilities(){return!1}supportsSequenceMode(){const a=this.getVersion();return a!==null?a>=4:super.supportsSequenceMode()}supportsSmoothCodecSwitching(){return!1}supportsServerCertificate(){return this.osMajorVersion_&&this.osMinorVersion_?this.osMajorVersion_===5?this.osMinorVersion_>=5:this.osMajorVersion_>5:super.supportsServerCertificate()}detectMaxHardwareResolution(){var a=window.devicePixelRatio;a={width:window.screen.width*a>1920?3840:1920,height:window.screen.height*a>1080?
2160:1080};try{if(webapis.systeminfo&&webapis.systeminfo.getMaxVideoResolution){const b=webapis.systeminfo.getMaxVideoResolution();a.width=b.width;a.height=b.height}else webapis.productinfo.is8KPanelSupported&&webapis.productinfo.is8KPanelSupported()?(a.width=7680,a.height=4320):webapis.productinfo.isUdPanelSupported&&webapis.productinfo.isUdPanelSupported()&&(a.width=3840,a.height=2160)}catch(b){shaka.log.alwaysWarn("Tizen: Error detecting screen size, default screen size 1920x1080.")}return Promise.resolve(a)}adjustConfig(a){super.adjustConfig(a);
a.drm.ignoreDuplicateInitData=this.getVersion()!==2;this.getVersion()===3&&(a.streaming.crossBoundaryStrategy=shaka.config.CrossBoundaryStrategy.RESET_TO_ENCRYPTED);a.streaming.shouldFixTimestampOffset=!0;a.streaming.stallSkip=0;a.streaming.gapPadding=2;return a}rejectCodecs(){const a=[];this.osMajorVersion_!==null&&this.osMajorVersion_<5&&a.push("opus");return a}getHdrLevel(a){try{if(webapis.avinfo.isHdrTvSupport())return a?"HLG":"PQ"}catch(b){return super.getHdrLevel(a)}return"SDR"}misreportAC3UsingDrm(){return!0}misreportsSupportForPersistentLicenses(){return this.getVersion()===
3}static isTizen_(){return navigator.userAgent.includes("Tizen")}};shaka.device.Tizen.isTizen_()&&shaka.device.DeviceFactory.registerDeviceFactory(()=>new shaka.device.Tizen);shaka.device.Vizio=class extends shaka.device.AbstractDevice{getVersion(){return null}getDeviceName(){return"Vizio"}getDeviceType(){return shaka.device.IDevice.DeviceType.TV}supportsMediaCapabilities(){return!1}static isVizio_(){return navigator.userAgent.includes("VIZIO SmartCast")}};shaka.device.Vizio.isVizio_()&&shaka.device.DeviceFactory.registerDeviceFactory(()=>new shaka.device.Vizio);shaka.device.WebKitSTB=class extends shaka.device.AbstractDevice{constructor(){super();this.isSkyQ_=new shaka.util.Lazy(()=>navigator.userAgent.includes("DT_STB_BCM")||navigator.userAgent.includes("Sky_STB"));this.isOrange_=new shaka.util.Lazy(()=>navigator.userAgent.includes("SOPOpenBrowser"));this.version_=new shaka.util.Lazy(()=>{if(navigator.userAgent.includes("DT_STB_BCM"))return 11;let a=navigator.userAgent.match(/Version\/(\d+)/);return a?parseInt(a[1],10):(a=navigator.userAgent.match(/OS (\d+)(?:_\d+)?/))?
parseInt(a[1],10):null})}getVersion(){return this.version_.value()}getDeviceName(){return"WebKit STB"}getDeviceType(){return shaka.device.IDevice.DeviceType.TV}getBrowserEngine(){return shaka.device.IDevice.BrowserEngine.WEBKIT}supportsMediaCapabilities(){return!1}supportsSequenceMode(){const a=this.version_.value();return a!==null?a>=15:!0}requiresEncryptionInfoInAllInitSegments(a){return this.isOrange_.value()}detectMaxHardwareResolution(){return Promise.resolve({width:window.screen.width*window.devicePixelRatio,
height:window.screen.height*window.devicePixelRatio})}supportsEncryptionSchemePolyfill(){return!this.isSkyQ_.value()}supportsContainerChangeType(){return!1}static isWebkitSTB_(){return navigator.userAgent.includes("SOPOpenBrowser")||navigator.userAgent.includes("DT_STB_BCM")||navigator.userAgent.includes("Sky_STB")?!0:!(navigator.vendor||"").includes("Apple")||/(?:iPhone|iPad|iPod)/.test(navigator.userAgent)||navigator.maxTouchPoints>1||navigator.userAgentData&&navigator.userAgentData.platform&&navigator.userAgentData.platform.toLowerCase()==
"macos"||navigator.platform&&navigator.platform.toLowerCase().includes("mac")?!1:!0}};shaka.device.WebKitSTB.isWebkitSTB_()&&shaka.device.DeviceFactory.registerDeviceFactory(()=>new shaka.device.WebKitSTB);shaka.device.WebOS=class extends shaka.device.AbstractDevice{constructor(){super();this.osVersion_=this.guessWebOSVersion_();this.supportHdr_=null;try{const a=new PalmServiceBridge;a.onservicecallback=b=>{shaka.log.info("WebOS: config support",b);b=JSON.parse(b);this.supportHdr_=b.configs?.["tv.model.supportHDR"]??b.configs?.["tv.config.supportDolbyHDRContents"]??!1};a.call("luna://com.webos.service.config/getConfigs",JSON.stringify({configNames:["tv.model.supportHDR","tv.config.supportDolbyHDRContents"]}))}catch(a){shaka.log.alwaysWarn("WebOS: getConfigs call failed",
a)}}getVersion(){return this.osVersion_}getDeviceName(){return"WebOS"}getDeviceType(){return shaka.device.IDevice.DeviceType.TV}getBrowserEngine(){return shaka.device.IDevice.BrowserEngine.CHROMIUM}supportsMediaCapabilities(){return!1}supportsSequenceMode(){const a=this.getVersion();return a!==null?a>3:super.supportsSequenceMode()}supportsSmoothCodecSwitching(){return!1}supportsServerCertificate(){const a=this.getVersion();return a!==null?a>3:super.supportsServerCertificate()}detectMaxHardwareResolution(){const a=
{width:1920,height:1080};try{const b=JSON.parse(window.PalmSystem.deviceInfo);a.width=Math.max(1920,b.screenWidth);a.height=Math.max(1080,b.screenHeight)}catch(b){shaka.log.alwaysWarn("WebOS: Error detecting screen size, default screen size 1920x1080.")}return Promise.resolve(a)}adjustConfig(a){super.adjustConfig(a);this.getVersion()===3&&(a.streaming.crossBoundaryStrategy=shaka.config.CrossBoundaryStrategy.RESET);a.streaming.shouldFixTimestampOffset=!0;a.streaming.stallSkip=0;return a}getHdrLevel(a){return this.supportHdr_==
null?(shaka.log.alwaysWarn("WebOS: getConfigs call haven't finished"),super.getHdrLevel(a)):this.supportHdr_?a?"HLG":"PQ":"SDR"}guessWebOSVersion_(){let a=null;const b=navigator.userAgent.match(/Chrome\/(\d+)/);b&&(a=parseInt(b[1],10));switch(a){case 38:return 3;case 53:return 4;case 68:return 5;case 79:return 6;case 87:return 22;case 94:return 23;case 108:return 24;case 120:return 25;default:return null}}supportStandardVP9Checking(){return!1}supportsCbcsWithoutEncryptionSchemeSupport(){const a=this.getVersion();
return a!==null?a>=6:super.supportsCbcsWithoutEncryptionSchemeSupport()}static isWebOS_(){return navigator.userAgent.includes("Web0S")}};if(shaka.device.WebOS.isWebOS_()){const a=new shaka.device.WebOS;shaka.device.DeviceFactory.registerDeviceFactory(()=>a)};shaka.device.Xbox=class extends shaka.device.AbstractDevice{constructor(){super();this.isLegacyEdge_=navigator.userAgent.includes("Edge/");const a=navigator.userAgent.match(/Edge?\/(\d+)/);this.version_=a?parseInt(a[1],10):null}getVersion(){return this.version_}getDeviceName(){return"Xbox"}getDeviceType(){return shaka.device.IDevice.DeviceType.CONSOLE}getBrowserEngine(){return this.isLegacyEdge_?shaka.device.IDevice.BrowserEngine.EDGE:shaka.device.IDevice.BrowserEngine.CHROMIUM}requiresEncryptionInfoInAllInitSegments(a){return!0}requiresClearAndEncryptedInitSegments(){return!0}insertEncryptionDataBeforeClear(){return!0}shouldOverrideDolbyVisionCodecs(){return this.isLegacyEdge_}detectMaxHardwareResolution(){const a=
{width:1920,height:1080};var b=shaka.device.Xbox.getWinRT_();if(b)try{const c=new b.Media.Protection.ProtectionCapabilities,d=b.Media.Protection.ProtectionCapabilityResult;b=null;do b=c.isTypeSupported('video/mp4;codecs="hvc1,mp4a";features="decode-res-x=3840,decode-res-y=2160,decode-bitrate=20000,decode-fps=30,decode-bpc=10,display-res-x=3840,display-res-y=2160,display-bpc=8"',"com.microsoft.playready.recommendation");while(b===d.maybe);b===d.probably&&(a.width=3840,a.height=2160)}catch(c){shaka.log.alwaysWarn("Xbox: Error detecting screen size, default screen size 1920x1080.")}return Promise.resolve(a)}adjustConfig(a){super.adjustConfig(a);
a.drm.parseInbandPsshEnabled=this.isLegacyEdge_;a.drm.preferredKeySystems.push("com.microsoft.playready");this.isLegacyEdge_&&(a.streaming.gapPadding=.01);return a}returnLittleEndianUsingPlayReady(){return!0}supportsOfflineStorage(){return!1}static getWinRT_(){let a=null;try{a=typeof Windows!=="undefined"?Windows:chrome.webview.hostObjects.sync.Windows}catch(b){}return a}static isXbox_(){return navigator.userAgent.includes("Xbox One")||shaka.device.Xbox.getWinRT_()!==null}};
shaka.device.Xbox.isXbox_()&&shaka.device.DeviceFactory.registerDeviceFactory(()=>new shaka.device.Xbox);shaka.hls={};shaka.hls.Playlist=class{constructor(a,b,c){this.type=a;this.tags=b;this.segments=c||null}};shaka.hls.PlaylistType={MASTER:0,MEDIA:1};
shaka.hls.Tag=class{constructor(a,b,c,d=null){this.id=a;this.name=b;this.attributes=c;this.value=d}toString(a){var b=d=>{const e=isNaN(Number(d.value))?'"'+d.value+'"':d.value;return d.name+"="+e};let c="#"+this.name;b=this.attributes?this.attributes.filter(d=>a?!a.has(d.name):!0).map(b):[];this.value&&b.unshift(this.value);b.length>0&&(c+=":"+b.join(","));return c}getTagKey(a){if(a)return this.toString();a=(new Set).add("AUDIO").add("VIDEO").add("SUBTITLES").add("PATHWAY-ID").add("GROUP-ID").add("URI");
return this.toString(a)}addAttribute(a){this.attributes.push(a)}getAttribute(a){return this.attributes.find(b=>b.name===a)||null}getAttributeValue(a,b){return(a=this.getAttribute(a))?a.value:b||null}getRequiredAttrValue(a){const b=this.getAttribute(a);if(!b)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_REQUIRED_ATTRIBUTE_MISSING,a);return b.value}setName(a){this.name=a}};
shaka.hls.Segment=class{constructor(a,b,c=[]){this.tags=b;this.verbatimSegmentUri=a;this.partialSegments=c}};shaka.hls.Attribute=class{constructor(a,b){this.name=a;this.value=b}};shaka.hls.Utils=class{static filterTagsByName(a,b){return a.filter(c=>c.name==b)}static filterTagsByType(a,b){return a.filter(c=>c.getRequiredAttrValue("TYPE")==b)}static getFirstTagWithName(a,b){for(const c of a)if(c.name===b)return c;return null}static getFirstTagWithNameAsNumber(a,b,c=0){return(a=shaka.hls.Utils.getFirstTagWithName(a,b))?Number(a.value):c}static constructSegmentUris(a,b,c){return b?shaka.hls.Utils.constructUris(a,[b],c):[]}static constructUris(a,b,c){if(!b.length)return[];let d=
b;c&&c.size&&(d=b.map(e=>shaka.hls.Utils.variableSubstitution(e,c)));return shaka.util.ManifestParserUtils.resolveUris(a,d)}static variableSubstitution(a,b){if(!b||!b.size)return a;a=String(a).replace(/%7B/g,"{").replace(/%7D/g,"}");var c=a.match(/{\$\w*}/g);if(c)for(const d of c){c=d.slice(2,d.length-1);const e=b.get(c);if(e)a=a.replace(d,e);else throw shaka.log.error("A variable has been found that is not declared",c),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,
shaka.util.Error.Code.HLS_VARIABLE_NOT_FOUND,c);}return a}static getExtinfDuration(a){a=a.value;const b=a.indexOf(",");return Number(b===-1?a:a.substring(0,b))}static isComment(a){return a.startsWith("#")&&!a.startsWith("#EXT")}};shaka.hls.ManifestTextParser=class{constructor(){this.globalId_=0}parsePlaylist(a){var b=shaka.util.StringUtils.fromUTF8(a).trim().split(/[\r\n]+/);if(!b[0].startsWith("#EXTM3U"))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_PLAYLIST_HEADER_MISSING);a=shaka.hls.PlaylistType.MASTER;let c=!1;const d=[];var e=!0;for(let g=0;g<b.length;g++){var f=b[g];const h=b[g+1];if(shaka.hls.Utils.isComment(f)||e){e=!1;continue}f=this.parseTag_(f);
c||(shaka.hls.ManifestTextParser.MEDIA_PLAYLIST_TAGS.has(f.name)?(a=shaka.hls.PlaylistType.MEDIA,c=!0):f.name=="EXT-X-STREAM-INF"||f.name=="EXT-X-MEDIA"?c=!0:shaka.hls.ManifestTextParser.SEGMENT_TAGS.has(f.name)&&(a=shaka.hls.PlaylistType.MEDIA,c=!0));if(shaka.hls.ManifestTextParser.SEGMENT_TAGS.has(f.name)){if(a!=shaka.hls.PlaylistType.MEDIA)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_INVALID_PLAYLIST_HIERARCHY);b=this.parseSegments_(b,
g,d);return new shaka.hls.Playlist(a,d,b)}d.push(f);f.name=="EXT-X-STREAM-INF"&&(e=new shaka.hls.Attribute("URI",h),f.addAttribute(e),e=!0)}return new shaka.hls.Playlist(a,d)}parseSegments_(a,b,c){const d=Array(Math.max(100,Math.floor((a.length-b)/2)));let e=0;var f=[];let g=[],h=null;for(;b<a.length;b++){var k=a[b];k.startsWith("#EXT")?(k=this.parseTag_(k),shaka.hls.ManifestTextParser.MEDIA_PLAYLIST_TAGS.has(k.name)?c.push(k):k.name=="EXT-X-MAP"?h=k:k.name=="EXT-X-PART"?g.push(k):k.name=="EXT-X-PRELOAD-HINT"?
k.getAttributeValue("TYPE")=="PART"?g.push(k):k.getAttributeValue("TYPE")=="MAP"&&(k.setName("EXT-X-MAP"),h=k):f.push(k)):shaka.hls.Utils.isComment(k)||(k=k.trim(),h&&f.push(h),f=new shaka.hls.Segment(k,f,g),e<d.length?d[e++]=f:(d.push(f),e++),f=[],g=[])}g.length&&(h&&f.push(h),a=new shaka.hls.Segment("",f,g),e<d.length?d[e++]=a:(d.push(a),e++));return e<d.length?d.slice(0,e):d}parseTag_(a){return shaka.hls.ManifestTextParser.parseTag(this.globalId_++,a)}static parseTag(a,b){const {name:c,data:d}=
shaka.hls.ManifestTextParser.splitTag_(b);if(d===null)return new shaka.hls.Tag(a,c,[]);if(d.indexOf("=")===-1)return new shaka.hls.Tag(a,c,[],d);b=shaka.hls.ManifestTextParser.parseAttributes_(d);return new shaka.hls.Tag(a,c,b.list,b.value)}static splitTag_(a){const b=a.indexOf(":"),c=b===-1?a.substring(1):a.substring(1,b);if(!c.startsWith("EXT"))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.INVALID_HLS_TAG,a);a=b===-1?null:
a.substring(b+1);return{name:c,data:a}}static parseAttributes_(a){const b=[];let c=null,d=0;var e=a.indexOf(","),f=a.indexOf("=");e!==-1&&e<f&&(c=a.substring(0,e),d=e+1);for(;d<a.length;){for(;a[d]===" ";)d++;f=a.indexOf("=",d);if(f===-1)break;e=a.substring(d,f);d=f+1;if(a[d]==='"'){d++;var g=a.indexOf('"',d);f=g===-1?a.substring(d):a.substring(d,g);d=g===-1?a.length:g+1}else g=a.indexOf(",",d),f=g===-1?a.substring(d):a.substring(d,g),d=g===-1?a.length:g;d<a.length&&a[d]===","&&d++;b.push(new shaka.hls.Attribute(e,
f))}return{value:c,list:b}}};shaka.hls.ManifestTextParser.MEDIA_PLAYLIST_TAGS=new Set("EXT-X-TARGETDURATION EXT-X-MEDIA-SEQUENCE EXT-X-DISCONTINUITY-SEQUENCE EXT-X-PLAYLIST-TYPE EXT-X-I-FRAMES-ONLY EXT-X-ENDLIST EXT-X-SERVER-CONTROL EXT-X-SKIP EXT-X-PART-INF EXT-X-DATERANGE".split(" "));shaka.hls.ManifestTextParser.SEGMENT_TAGS=new Set("EXTINF EXT-X-BYTERANGE EXT-X-DISCONTINUITY EXT-X-PROGRAM-DATE-TIME EXT-X-KEY EXT-X-DATERANGE EXT-X-MAP EXT-X-GAP EXT-X-TILES".split(" "));shaka.net.DataUriPlugin=class{static parse(a,b,c,d){try{const e=shaka.net.DataUriPlugin.parseRaw(a);return shaka.util.AbortableOperation.completed({uri:a,originalUri:a,data:e.data,headers:{"content-type":e.contentType},originalRequest:b})}catch(e){return shaka.util.AbortableOperation.failed(e)}}static parseRaw(a){if(!a.startsWith("data:"))throw shaka.log.error("Bad data URI, failed to parse scheme"),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.MALFORMED_DATA_URI,
a);var b=a.substring(5),c=b.indexOf(",");if(c<0)throw shaka.log.error("Bad data URI, failed to extract encoding and MIME type"),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.MALFORMED_DATA_URI,a);a=b.substring(0,c);b=b.substring(c+1);b=decodeURIComponent(b);a=a.split(";");c=a[0];let d=!1;a.length>1&&a[a.length-1].toLowerCase()=="base64"&&(d=!0,a.pop());return{data:d?shaka.util.Uint8ArrayUtils.fromBase64(b):shaka.util.StringUtils.toUTF8(b),
contentType:c,typeInfoList:a}}};goog.exportSymbol("shaka.net.DataUriPlugin",shaka.net.DataUriPlugin);goog.exportProperty(shaka.net.DataUriPlugin,"parse",shaka.net.DataUriPlugin.parse);shaka.net.NetworkingEngine.registerScheme("data",shaka.net.DataUriPlugin.parse);shaka.hls.HlsParser=class{constructor(){this.config_=this.playerInterface_=null;this.globalId_=1;this.globalVariables_=new Map;this.groupIdToStreamInfosMap_=new Map;this.mediaSequenceToStartTimeByType_=new Map;const a=shaka.util.ManifestParserUtils.ContentType;this.mediaSequenceToStartTimeByType_.set(a.VIDEO,new Map);this.mediaSequenceToStartTimeByType_.set(a.AUDIO,new Map);this.mediaSequenceToStartTimeByType_.set(a.TEXT,new Map);this.mediaSequenceToStartTimeByType_.set(a.IMAGE,new Map);this.keyFormatsToDrmParsers_=
(new Map).set("com.apple.streamingkeydelivery",(b,c,d)=>this.fairplayDrmParser_(b,c,d)).set("urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed",(b,c,d)=>this.widevineDrmParser_(b,c,d)).set("com.microsoft.playready",(b,c,d)=>this.playreadyDrmParser_(b,c,d)).set("urn:uuid:3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c",(b,c,d)=>this.wiseplayDrmParser_(b,c,d));this.variantUriSet_=new Set;this.uriToStreamInfosMap_=new Map;this.presentationTimeline_=null;this.masterPlaylistUri_="";this.manifestTextParser_=new shaka.hls.ManifestTextParser;
this.minSequenceNumber_=-1;this.lowestSyncTime_=Infinity;this.codecInfoInManifest_=this.streamsFinalized_=this.usesProgramDateTime_=!1;this.updatePlaylistTimer_=new shaka.util.Timer(()=>{if(this.mediaElement_&&!this.config_.continueLoadingWhenPaused&&(this.eventManager_.unlisten(this.mediaElement_,"timeupdate"),this.mediaElement_.paused)){this.eventManager_.listenOnce(this.mediaElement_,"timeupdate",()=>this.onUpdate_());return}this.onUpdate_()});this.presentationType_=shaka.hls.HlsParser.PresentationType_.VOD;
this.manifest_=null;this.maxTargetDuration_=0;this.lastTargetDuration_=Infinity;this.lowLatencyPresentationDelay_=this.presentationDelay_=this.partialTargetDuration_=0;this.operationManager_=new shaka.util.OperationManager;this.groupIdToClosedCaptionsMap_=new Map;this.groupIdToCodecsMap_=new Map;this.mapTagToInitSegmentRefMap_=new Map;this.aesKeyInfoMap_=new Map;this.aesKeyMap_=new Map;this.identityKeyMap_=new Map;this.initSegmentToKidMap_=new Map;this.lowLatencyByterangeOptimization_=this.lowLatencyMode_=
!1;this.averageUpdateDuration_=new shaka.abr.Ewma(5);this.contentSteeringManager_=null;this.needsClosedCaptionsDetection_=!0;this.eventManager_=new shaka.util.EventManager;this.startTime_=this.mediaElement_=null;this.isPreloadFn_=()=>!1;this.psshToInitData_=new Map}configure(a,b){const c=this.playerInterface_&&a.updatePeriod!=this.config_.updatePeriod&&a.updatePeriod>=0;this.config_=a;b&&(this.isPreloadFn_=b);this.contentSteeringManager_&&this.contentSteeringManager_.configure(this.config_);c&&this.manifest_&&
this.manifest_.presentationTimeline.isLive()&&this.updatePlaylistTimer_.tickNow()}async start(a,b){goog.asserts.assert(this.config_,"Must call configure() before start()!");this.playerInterface_=b;this.lowLatencyMode_=b.isLowLatencyMode();a=await this.requestManifest_([a]).promise;this.masterPlaylistUri_=a.uri;goog.asserts.assert(a.data,"Response data should be non-null!");await this.parseManifest_(a.data);goog.asserts.assert(this.manifest_,"Manifest should be non-null");return this.manifest_}stop(){this.updatePlaylistTimer_&&
(this.updatePlaylistTimer_.stop(),this.updatePlaylistTimer_=null);const a=[];this.operationManager_&&(a.push(this.operationManager_.destroy()),this.operationManager_=null);this.config_=this.playerInterface_=null;this.variantUriSet_.clear();this.manifest_=null;this.uriToStreamInfosMap_.clear();this.groupIdToStreamInfosMap_.clear();this.groupIdToCodecsMap_.clear();this.globalVariables_.clear();this.mapTagToInitSegmentRefMap_.clear();this.aesKeyInfoMap_.clear();this.aesKeyMap_.clear();this.identityKeyMap_.clear();
this.initSegmentToKidMap_.clear();this.psshToInitData_.clear();this.contentSteeringManager_&&this.contentSteeringManager_.destroy();this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null);return Promise.all(a)}async update(){if(this.isLive_()){var a=[],b=Array.from(this.uriToStreamInfosMap_.values()).filter(c=>!c.stream.isAudioMuxedInVideo&&c.stream.segmentIndex);if(b.length===0)shaka.log.warning("No active streams found during update");else{this.lastTargetDuration_=Infinity;this.manifest_.gapCount=
0;for(const c of b)a.push(this.updateStream_(c));await Promise.all(a);this.notifySegmentsForStreams_(b.map(c=>c.stream));a=b.some(c=>c.hasEndList==0);b.length&&!a&&(this.setPresentationType_(shaka.hls.HlsParser.PresentationType_.VOD),this.determineDuration_());a&&this.determineDuration_();for(const c of b)c.stream.isAudioMuxedInVideo||!c.stream.segmentIndex||c.stream.segmentIndex.earliestReference()||this.playerInterface_.disableStream(c.stream)}}}getMediaSequenceToStartTimeFor_(a){return this.isLive_()?
this.mediaSequenceToStartTimeByType_.get(a.type):a.mediaSequenceToStartTime}async updateStream_(a){if(!a.stream.isAudioMuxedInVideo){var b=[];for(var c of a.getUris()){var d=new goog.Uri(c),e=d.getQueryData();a.canBlockReload&&(a.nextMediaSequence>=0&&e.add("_HLS_msn",String(a.nextMediaSequence)),a.nextPart>=0&&e.add("_HLS_part",String(a.nextPart)));a.canSkipSegments&&e.add("_HLS_skip","YES");b.push(d.toString())}try{var f=await this.requestManifest_(b,!0).promise}catch(p){throw this.playerInterface_&&
this.playerInterface_.disableStream(a.stream),p;}if(a.stream.segmentIndex){b=this.manifestTextParser_.parsePlaylist(f.data);if(b.type!=shaka.hls.PlaylistType.MEDIA)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_INVALID_PLAYLIST_HIERARCHY);c=f.uri;c==f.originalUri||a.getUris().includes(c)||a.redirectUris.push(c);f=shaka.hls.Utils.filterTagsByName(b.tags,"EXT-X-DEFINE");f=this.parseMediaVariables_(f,c);c=a.stream;d=this.getMediaSequenceToStartTimeFor_(a);
var {keyIds:g,drmInfos:h,encrypted:k,aesEncrypted:l}=await this.parseDrmInfo_(b,c.mimeType,a.getUris,f);c.encrypted||!k||l||(c.encrypted=!0);((p,r)=>p.size===r.size&&[...p].every(t=>r.has(t)))(c.keyIds,g)||(c.keyIds=g,c.drmInfos=h,this.playerInterface_.newDrmInfo(c));var {segments:m,bandwidth:n}=this.createSegments_(b,d,f,a.getUris,a.type);n&&(c.bandwidth=n);e=shaka.media.QualityObserver.createQualityInfo(c);for(var q of m)q.initSegmentReference&&(q.initSegmentReference.mediaQuality=e);c.segmentIndex.mergeAndEvict(m,
this.presentationTimeline_.getSegmentAvailabilityStart());if(m.length){q=shaka.hls.Utils.getFirstTagWithNameAsNumber(b.tags,"EXT-X-MEDIA-SEQUENCE",0);e=(e=shaka.hls.Utils.getFirstTagWithName(b.tags,"EXT-X-SKIP"))?Number(e.getAttributeValue("SKIPPED-SEGMENTS")):0;const {nextMediaSequence:p,nextPart:r}=this.getNextMediaSequenceAndPart_(q,m);a.nextMediaSequence=p+e;a.nextPart=r;q=d.get(q);c.segmentIndex.evict(q)}if(q=c.segmentIndex.earliestReference())a.minTimestamp=q.startTime,q=m[m.length-1],goog.asserts.assert(q,
"Should have segments!"),a.maxTimestamp=q.endTime;shaka.hls.Utils.getFirstTagWithName(b.tags,"EXT-X-ENDLIST")&&(a.hasEndList=!0);this.determineLastTargetDuration_(b);this.processDateRangeTags_(b.tags,c.type,f,a.getUris)}}}onExpirationUpdated(a,b){}onInitialVariantChosen(a){}banLocation(a){this.contentSteeringManager_&&this.contentSteeringManager_.banLocation(a)}setMediaElement(a){this.mediaElement_=a}syncStreamsWithSequenceNumber_(a,b=!1){var c=this.minSequenceNumber_==-1;for(const e of a){var d=
e.stream.segmentIndex;goog.asserts.assert(d,"Only loaded streams should be synced");const f=this.getMediaSequenceToStartTimeFor_(e);if(d=d.earliestReference()){goog.DEBUG&&f.values().next().value!=d.startTime&&shaka.log.warning("Sequence number map is not ordered as expected!");for(const [g,h]of f)if(h==d.startTime){c&&(this.minSequenceNumber_=Math.max(this.minSequenceNumber_,g));e.firstSequenceNumber=g;break}}}if(!(this.minSequenceNumber_<0)){shaka.log.debug("Syncing HLS streams against base sequence number:",
this.minSequenceNumber_);for(const e of a){if(!this.ignoreManifestProgramDateTimeFor_(e.type)&&!b)continue;if(a=e.stream.segmentIndex)if(c=this.minSequenceNumber_-e.firstSequenceNumber,c>0&&(a.dropFirstReferences(c),a=a.earliestReference()))a=-a.startTime,e.stream.segmentIndex.offset(a),this.offsetStreamInfo_(e,a)}}}syncStreamsWithProgramDateTime_(a){if(this.lowestSyncTime_==Infinity)for(var b of a)a=b.stream.segmentIndex,goog.asserts.assert(a,"Only loaded streams should be synced"),a=a.earliestReference(),
a!=null&&a.syncTime!=null&&(this.lowestSyncTime_=Math.min(this.lowestSyncTime_,a.syncTime));b=this.lowestSyncTime_;if(b!=Infinity){shaka.log.debug("Syncing HLS streams against base time:",b);for(const c of this.uriToStreamInfosMap_.values()){if(this.ignoreManifestProgramDateTimeFor_(c.type))continue;a=c.stream.segmentIndex;if(a!=null){const d=a.earliestReference();if(d)if(d.syncTime==null)shaka.log.alwaysError("Missing EXT-X-PROGRAM-DATE-TIME for stream",c.getUris(),"Expect AV sync issues!");else{this.offsetStreamInfo_(c,
d.syncTime-b-d.startTime);for(const e of a)e.syncAgainst(b)}}}}}offsetStreamInfo_(a,b){if(!(Math.abs(b)<.001)){a.minTimestamp+=b;a.maxTimestamp+=b;goog.asserts.assert(a.maxTimestamp>=0,"Negative maxTimestamp after adjustment!");var c=this.getMediaSequenceToStartTimeFor_(a);for(const [d,e]of c)c.set(d,e+b);shaka.log.debug("Offset",b,"applied to",a.getUris())}}async parseManifest_(a){var b=shaka.hls.Utils,c=shaka.util.ManifestParserUtils.ContentType;goog.asserts.assert(this.masterPlaylistUri_,"Master playlist URI must be set before calling parseManifest_!");
a=this.manifestTextParser_.parsePlaylist(a);var d=b.filterTagsByName(a.tags,"EXT-X-DEFINE"),e=[],f=[],g=[];goog.asserts.assert(this.presentationTimeline_==null,"Presentation timeline created early!");this.presentationTimeline_=new shaka.media.PresentationTimeline(null,0);this.presentationTimeline_.setStatic(!0);const h=()=>[this.masterPlaylistUri_];var k=null;let l=new Map;this.manifest_={presentationTimeline:this.presentationTimeline_,variants:e,textStreams:f,imageStreams:g,offlineSessionIds:[],
sequenceMode:this.config_.hls.sequenceMode,ignoreManifestTimestampsInSegmentsMode:this.config_.hls.ignoreManifestTimestampsInSegmentsMode,type:shaka.media.ManifestParser.HLS,serviceDescription:null,nextUrl:null,periodCount:1,gapCount:0,isLowLatency:!1,startTime:this.startTime_};if(a.type==shaka.hls.PlaylistType.MEDIA){this.needsClosedCaptionsDetection_=!1;k=shaka.hls.Utils.filterTagsByName(a.tags,"EXT-X-DEFINE");l=this.parseMediaVariables_(k,this.masterPlaylistUri_);k=c.VIDEO;var m=new Map;m=await this.convertParsedPlaylistIntoStreamInfo_(this.globalId_++,
l,a,h,"",k,"",!0,"Media Playlist",null,m,null,!1,null,!1);this.uriToStreamInfosMap_.set(this.masterPlaylistUri_,m);if(m.stream){const p=shaka.media.QualityObserver.createQualityInfo(m.stream);m.stream.segmentIndex.forEachTopLevelReference(r=>{r.initSegmentReference&&(r.initSegmentReference.mediaQuality=p)})}k=m.stream.type;c=!0;this.config_.disableAudio&&m.type=="audio"?c=!1:this.config_.disableVideo&&m.type=="video"&&!m.stream.codecs.includes(",")&&(c=!1);c&&e.push({id:0,language:this.getLanguage_(""),
disabledUntilTime:0,primary:!0,audio:m.type=="audio"?m.stream:null,video:m.type=="video"?m.stream:null,bandwidth:m.stream.bandwidth||0,allowedByApplication:!0,allowedByKeySystem:!0,decodingInfos:[]})}else{this.parseMasterVariables_(d);f=b.filterTagsByName(a.tags,"EXT-X-MEDIA");e=b.filterTagsByName(a.tags,"EXT-X-STREAM-INF");g=b.filterTagsByName(a.tags,"EXT-X-IMAGE-STREAM-INF");c=b.filterTagsByName(a.tags,"EXT-X-I-FRAME-STREAM-INF");d=b.filterTagsByName(a.tags,"EXT-X-SESSION-KEY");var n=b.filterTagsByName(a.tags,
"EXT-X-SESSION-DATA");b=b.filterTagsByName(a.tags,"EXT-X-CONTENT-STEERING");this.processSessionData_(n);await this.processContentSteering_(b);if(!this.config_.ignoreSupplementalCodecs){b=[];for(var q of e){n=q.getAttributeValue("SUPPLEMENTAL-CODECS");if(!n)continue;const p=n.split(/\s*,\s*/).map(r=>r.split("/")[0]);n=q.attributes.map(r=>{const t=r.name;let u=r.value;t=="CODECS"&&(u=p.join(","),r=r.value.split(","),r.length>1&&(r=shaka.util.ManifestParserUtils.guessCodecsSafe(shaka.util.ManifestParserUtils.ContentType.AUDIO,
r))&&(u+=","+r));return new shaka.hls.Attribute(t,u)});b.push(new shaka.hls.Tag(q.id,q.name,n,null))}e.push(...b);q=[];for(m of c){b=m.getAttributeValue("SUPPLEMENTAL-CODECS");if(!b)continue;const p=b.split(/\s*,\s*/).map(r=>r.split("/")[0]);b=m.attributes.map(r=>{const t=r.name;r=r.value;t=="CODECS"&&(r=p.join(","));return new shaka.hls.Attribute(t,r)});q.push(new shaka.hls.Tag(m.id,m.name,b,null))}c.push(...q)}this.parseCodecs_(e);this.parseClosedCaptions_(f);m=this.parseIFrames_(c);e=await this.createVariantsForTags_(e,
d,f,h,this.globalVariables_,m);f=this.parseTexts_(f);g=await this.parseImages_(g,c)}if(!this.playerInterface_)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.OPERATION_ABORTED);this.determineStartTime_(a);a.type==shaka.hls.PlaylistType.MEDIA&&(this.isLive_()&&(this.changePresentationTimelineToLive_(a),m=this.getUpdatePlaylistDelay_(),this.updatePlaylistTimer_.tickAfter(m)),m=Array.from(this.uriToStreamInfosMap_.values()),this.finalizeStreams_(m),
this.determineDuration_(),goog.asserts.assert(k,"mediaPlaylistType should be non-null"),this.processDateRangeTags_(a.tags,k,l,h));this.manifest_.variants=e;this.manifest_.textStreams=f;this.manifest_.imageStreams=g;this.manifest_.startTime=this.startTime_;if(!this.codecInfoInManifest_&&this.config_.hls.disableCodecGuessing){a=[];for(const p of this.manifest_.variants)p.audio&&p.audio.codecs===""&&a.push(p.audio.createSegmentIndex()),p.video&&p.video.codecs===""&&a.push(p.video.createSegmentIndex());
await Promise.all(a)}this.playerInterface_.makeTextStreamsForClosedCaptions(this.manifest_)}async getBasicInfoFromSegments_(a){const b=shaka.media.SegmentUtils.getBasicInfoFromMimeType(this.config_.hls.mediaPlaylistFullMimeType);if(!a.length)return b;const {segment:c,segmentIndex:d}=this.getAvailableSegment_(a);a=c.getUris();var e=shaka.net.NetworkingUtils.getExtension(a[0]);if(e&&(a=shaka.hls.HlsParser.RAW_FORMATS_TO_MIME_TYPES_.get(e)))return shaka.media.SegmentUtils.getBasicInfoFromMimeType(a);
var f=await Promise.all([this.getInfoFromSegment_(c.initSegmentReference,0),this.getInfoFromSegment_(c,d)]);a=f[1].mimeType;const g=f[0].data;f=f[1].data;const h="mp4 mp4a m4s m4i m4a m4f cmfa mp4v m4v cmfv fmp4".split(" ");var k=["audio/mp4","video/mp4","video/iso.segment"];k=c.initSegmentReference||k.includes(a);if(!k&&shaka.util.TsParser.probe(shaka.util.BufferUtils.toUint8(f))){if(e=shaka.media.SegmentUtils.getBasicInfoFromTs(f,this.config_.disableAudio,this.config_.disableVideo,this.config_.disableText))return e}else if(k||
h.includes(e))if(e=shaka.media.SegmentUtils.getBasicInfoFromMp4(g,f,this.config_.disableText))return e;return a?shaka.media.SegmentUtils.getBasicInfoFromMimeType(a):b}async getInfoFromSegment_(a,b){if(!a)return{mimeType:null,data:null};var c=shaka.net.NetworkingEngine.RequestType.SEGMENT,d=shaka.net.NetworkingUtils.createSegmentRequest(a.getUris(),a.getStartByte(),a.getEndByte(),this.config_.retryParameters);d=await this.makeNetworkRequest_(d,c,{type:a instanceof shaka.media.SegmentReference?shaka.net.NetworkingEngine.AdvancedRequestType.MEDIA_SEGMENT:
shaka.net.NetworkingEngine.AdvancedRequestType.INIT_SEGMENT}).promise;c=d.data;a.aesKey&&(c=await shaka.media.SegmentUtils.aesDecrypt(c,a.aesKey,b));a instanceof shaka.media.SegmentReference?a.setSegmentData(c,!0):a.setSegmentData(c);(a=d.headers["content-type"])&&(a=a.split(";")[0].toLowerCase());return{mimeType:a,data:c}}determineDuration_(){goog.asserts.assert(this.presentationTimeline_,"Presentation timeline not created!");if(this.isLive_()){if(this.presentationType_==shaka.hls.HlsParser.PresentationType_.LIVE){var a=
this.getLiveDuration_()||0;isNaN(this.config_.availabilityWindowOverride)||(a=this.config_.availabilityWindowOverride);this.presentationTimeline_.setSegmentAvailabilityDuration(a)}}else this.presentationTimeline_.setDuration(this.getMinDuration_());if(!this.presentationTimeline_.isStartTimeLocked())for(const b of this.uriToStreamInfosMap_.values()){if(!b.stream.segmentIndex)continue;if(b.type!="audio"&&b.type!="video")continue;(a=b.stream.segmentIndex.earliestReference())&&a.syncTime!=null&&this.presentationTimeline_.setInitialProgramDateTime(a.syncTime)}this.presentationTimeline_.lockStartTime();
goog.asserts.assert(!this.presentationTimeline_.usingPresentationStartTime(),"We should not be using the presentation start time in HLS!")}parseMasterVariables_(a){const b=(new goog.Uri(this.masterPlaylistUri_)).getQueryData();for(const d of a){var c=d.getAttributeValue("NAME");const e=d.getAttributeValue("VALUE");a=d.getAttributeValue("QUERYPARAM");c&&e&&(this.globalVariables_.has(c)||this.globalVariables_.set(c,e));a&&(c=b.get(a)[0])&&!this.globalVariables_.has(c)&&this.globalVariables_.set(a,c)}}parseMediaVariables_(a,
b){b=(new goog.Uri(b)).getQueryData();const c=new Map;for(const f of a){var d=f.getAttributeValue("NAME");const g=f.getAttributeValue("VALUE");var e=f.getAttributeValue("QUERYPARAM");a=f.getAttributeValue("IMPORT");d&&g&&(c.has(d)||c.set(d,g));e&&(d=b.get(e)[0])&&!c.has(d)&&c.set(e,d);a&&(e=this.globalVariables_.get(a))&&c.set(a,e)}return c}parseCodecs_(a){const b=shaka.util.ManifestParserUtils.ContentType;for(const e of a){var c=e.getAttributeValue("AUDIO");a=e.getAttributeValue("VIDEO");var d=e.getAttributeValue("SUBTITLES");
const f=this.getCodecsForVariantTag_(e);if(d){const g=shaka.util.ManifestParserUtils.guessCodecsSafe(b.TEXT,f);goog.asserts.assert(g!=null,"Text codecs should be valid.");this.groupIdToCodecsMap_.set(d,g);shaka.util.ArrayUtils.remove(f,g)}c&&(d=shaka.util.ManifestParserUtils.guessCodecsSafe(b.AUDIO,f),d||(d=this.config_.hls.defaultAudioCodec),this.groupIdToCodecsMap_.set(c,d));a&&(c=shaka.util.ManifestParserUtils.guessCodecsSafe(b.VIDEO,f),c||(c=this.config_.hls.defaultVideoCodec),this.groupIdToCodecsMap_.set(a,
c))}}processSessionData_(a){for(const c of a){var b=c.getAttributeValue("DATA-ID");a=c.getAttributeValue("URI");const d=c.getAttributeValue("LANGUAGE"),e=c.getAttributeValue("VALUE");b=(new Map).set("id",b);a&&b.set("uri",shaka.hls.Utils.constructSegmentUris([this.masterPlaylistUri_],a,this.globalVariables_)[0]);d&&b.set("language",d);e&&b.set("value",e);a=new shaka.util.FakeEvent("sessiondata",b);if(this.playerInterface_)this.playerInterface_.onEvent(a)}}async processContentSteering_(a){if(this.playerInterface_&&
this.config_){for(const c of a){a=c.getAttributeValue("PATHWAY-ID");const d=c.getAttributeValue("SERVER-URI");if(a&&d){this.contentSteeringManager_=new shaka.util.ContentSteeringManager(this.playerInterface_);this.contentSteeringManager_.configure(this.config_);this.contentSteeringManager_.setBaseUris([this.masterPlaylistUri_]);this.contentSteeringManager_.setManifestType(shaka.media.ManifestParser.HLS);this.contentSteeringManager_.setDefaultPathwayId(a);var b=this.contentSteeringManager_.requestInfo(d);
break}}await b}}parseTexts_(a){a=shaka.hls.Utils.filterTagsByType(a,"SUBTITLES");var b={};for(var c of a){const e=c.getTagKey(!this.contentSteeringManager_);b[e]?b[e].push(c):b[e]=[c]}c=[];if(!this.config_.disableText)for(var d in b)try{c.push(this.createStreamInfoFromMediaTags_(b[d],new Map).stream)}catch(e){if(!this.config_.hls.ignoreTextStreamFailures)throw e;}d=shaka.util.ManifestParserUtils.ContentType.TEXT;for(const e of a)if(b=e.getRequiredAttrValue("GROUP-ID"),a=this.groupIdToCodecsMap_.get(b))if(b=
this.groupIdToStreamInfosMap_.get(b))for(const f of b)f.stream.codecs=a,f.stream.mimeType=this.guessMimeTypeBeforeLoading_(d,a)||this.guessMimeTypeFallback_(d),this.setFullTypeForStream_(f.stream);return c.filter(e=>e)}setFullTypeForStream_(a){const b=new Set([shaka.util.MimeUtils.getFullType(a.mimeType,a.codecs)]);a.segmentIndex&&a.segmentIndex.forEachTopLevelReference(c=>{c.mimeType&&b.add(shaka.util.MimeUtils.getFullType(c.mimeType,a.codecs))});a.fullMimeTypes=b}async parseImages_(a,b){a=a.map(async c=>
{if(this.config_.disableThumbnails)return null;try{return(await this.createStreamInfoFromImageTag_(c)).stream}catch(d){if(this.config_.hls.ignoreImageStreamFailures)return null;throw d;}}).concat(b.map(c=>{if(this.config_.disableThumbnails)return null;try{const d=this.createStreamInfoFromIframeTag_(c);return d.stream.type!==shaka.util.ManifestParserUtils.ContentType.IMAGE?null:d.stream}catch(d){if(this.config_.hls.ignoreImageStreamFailures)return null;throw d;}}));return(await Promise.all(a)).filter(c=>
c)}createStreamInfosFromMediaTags_(a,b){a=a.filter(d=>{const e=d.getAttributeValue("URI")||"";d=d.getAttributeValue("TYPE");return d!="SUBTITLES"&&(e!=""||d=="AUDIO")});const c={};for(const d of a)a=d.getTagKey(!this.contentSteeringManager_),c[a]?c[a].push(d):c[a]=[d];for(const d in c)this.createStreamInfoFromMediaTags_(c[d],b,!1)}parseIFrames_(a){return a.map(b=>{b=this.createStreamInfoFromIframeTag_(b);return b.stream.type!==shaka.util.ManifestParserUtils.ContentType.VIDEO?null:b.stream}).filter(b=>
b)}async createVariantsForTags_(a,b,c,d,e,f){const g=[],h=new Set;if(!this.config_.ignoreDrmInfo&&b.length>0)for(var k of b){var l=k.getRequiredAttrValue("METHOD");b=k.getAttributeValue("KEYFORMAT")||"identity";var m=null;if(l!="NONE")if(this.isAesMethod_(l))m=shaka.hls.Utils.constructSegmentUris(d(),k.getRequiredAttrValue("URI"),e),b=m.sort().join(""),this.aesKeyMap_.has(b)||(l=shaka.net.NetworkingEngine.RequestType.KEY,m=shaka.net.NetworkingEngine.makeRequest(m,this.config_.retryParameters),l=this.makeNetworkRequest_(m,
l).promise,this.aesKeyMap_.set(b,l));else if(m=b=="identity"?await this.identityDrmParser_(k,"",d,null,e):(l=this.keyFormatsToDrmParsers_.get(b))?await l(k,"",null):null,m){if(m.keyIds)for(var n of m.keyIds)h.add(n);g.push(m)}else shaka.log.warning("Unsupported HLS KEYFORMAT",b)}d={};for(var q of a)a=q.getTagKey(!this.contentSteeringManager_),d[a]?d[a].push(q):d[a]=[q];q=[];for(const p in d){n=d[p];l=n[0];a=l.getAttributeValue("FRAME-RATE");e=Number(l.getRequiredAttrValue("BANDWIDTH"))||Number(l.getAttributeValue("AVERAGE-BANDWIDTH"));
b=l.getAttributeValue("RESOLUTION");const [r,t]=b?b.split("x"):[null,null];k=l.getAttributeValue("VIDEO-RANGE");(l=l.getAttributeValue("REQ-VIDEO-LAYOUT"))&&l.includes(",")&&(l=l.split(",").filter(u=>u=="CH-STEREO"||u=="CH-MONO")[0]);l=l||"CH-MONO";n=this.createStreamInfosForVariantTags_(n,c,b,a);goog.asserts.assert(n.audio.length||n.video.length,"We should have created a stream!");q.push(...this.createVariants_(n.audio,n.video,e,r,t,a,k,l,g,h,f))}return q.filter(p=>p!=null)}createStreamInfosForVariantTags_(a,
b,c,d){d=shaka.util.ManifestParserUtils.ContentType;c={audio:[],video:[]};var e=new Map;const f=[];var g=!1,h=!1;for(var k of a){var l=k.getAttributeValue("AUDIO");const n=k.getAttributeValue("VIDEO");goog.asserts.assert(l==null||n==null,"Unexpected: both video and audio described by media tags!");const q=l||n;if(!q)continue;f.includes(q)||f.push(q);const p=k.getAttributeValue("PATHWAY-ID");p&&e.set(q,p);l?g=!0:n&&(h=!0);shaka.log.debug("Guessing stream type for",k.toString())}f.length&&b.length&&
(b=b.filter(n=>f.includes(n.getRequiredAttrValue("GROUP-ID"))),this.createStreamInfosFromMediaTags_(b,e));k=(b=f.sort().join(","))&&this.groupIdToStreamInfosMap_.has(b)?this.groupIdToStreamInfosMap_.get(b):[];g?c.audio.push(...k):h&&c.video.push(...k);h=!1;const m=a.map(n=>n.getRequiredAttrValue("URI"));g=c.audio.find(n=>n&&n.getUris().find(q=>m.includes(q)));k=this.getCodecsForVariantTag_(a[0]);e=shaka.util.ManifestParserUtils.guessCodecsSafe(d.VIDEO,k);(l=shaka.util.ManifestParserUtils.guessCodecsSafe(d.AUDIO,
k))&&!e?(g=d.AUDIO,shaka.log.debug("Guessing audio-only."),h=c.audio.length>0&&!c.audio.some(n=>n.stream.isAudioMuxedInVideo)):!c.audio.length&&!c.video.length&&l&&e?(shaka.log.debug("Guessing multiplexed audio+video."),g=d.VIDEO,k=[[e,l].join()]):c.audio.length&&g?(shaka.log.debug("Guessing audio-only."),g=d.AUDIO,h=!0):c.video.length&&!c.audio.length?(shaka.log.debug("Guessing audio-only."),g=d.AUDIO):(shaka.log.debug("Guessing video-only."),g=d.VIDEO);h||(a=this.createStreamInfoFromVariantTags_(a,
k,g),b&&this.config_.enableAudioGroups&&(a.stream.groupId=b),a.stream.type==d.AUDIO&&g===d.AUDIO&&c.audio.some(n=>n.stream.isAudioMuxedInVideo)&&(d=c.audio[0].stream,a.stream.language=d.language,a.stream.channelsCount=d.channelsCount,a.stream.label=d.label,a.stream.audioSamplingRate=d.audioSamplingRate,a.stream.originalId=d.originalId,a.stream.originalLanguage=d.originalLanguage),c[a.stream.type]=[a]);return c}getCodecsForVariantTag_(a){a=a.getAttributeValue("CODECS")||"";this.codecInfoInManifest_=
a.length>0;this.codecInfoInManifest_||this.config_.hls.disableCodecGuessing||(a=[],this.config_.disableVideo||a.push(this.config_.hls.defaultVideoCodec),this.config_.disableAudio||a.push(this.config_.hls.defaultAudioCodec),a=a.join(","));a=a.split(/\s*,\s*/);return shaka.media.SegmentUtils.codecsFiltering(a)}getChannelsCount_(a){a=a.getAttributeValue("CHANNELS");if(!a)return null;a=a.split("/")[0];return parseInt(a,10)}getSampleRate_(a){return(a=a.getAttributeValue("SAMPLE-RATE"))?parseInt(a,10):
null}isSpatialAudio_(a){a=a.getAttributeValue("CHANNELS");if(!a)return!1;a=a.split("/");return a.length!=2?!1:a[1]==="JOC"||a[1].includes("ATMOS")||a[1].includes("IMSA")}getClosedCaptions_(a,b){const c=shaka.util.ManifestParserUtils.ContentType;a=a.getAttributeValue("CLOSED-CAPTIONS");if(b==c.VIDEO){if(this.config_.disableText)return this.needsClosedCaptionsDetection_=!1,null;if(a){if(a!="NONE")return this.groupIdToClosedCaptionsMap_.get(a);this.needsClosedCaptionsDetection_=!1}else if(!a&&this.groupIdToClosedCaptionsMap_.size)for(const d of this.groupIdToClosedCaptionsMap_.keys())return this.groupIdToClosedCaptionsMap_.get(d)}return null}getLanguage_(a){return shaka.util.LanguageUtils.normalize(a||
"und")}getType_(a){a=a.getRequiredAttrValue("TYPE").toLowerCase();a=="subtitles"&&(a=shaka.util.ManifestParserUtils.ContentType.TEXT);return a}createVariants_(a,b,c,d,e,f,g,h,k,l,m){const n=shaka.util.ManifestParserUtils.ContentType,q=shaka.drm.DrmUtils;for(var p of b)this.addVideoAttributes_(p.stream,d,e,f,g,h,null);d=this.config_.disableVideo;if(!b.length||d)b=[null];d&&(a=a.filter(r=>!r.stream.isAudioMuxedInVideo));d=this.config_.disableAudio;if(!a.length||d)a=[null];d=[];for(const r of a)for(const t of b){if(a=
r?r.stream:null)a.drmInfos=k,a.keyIds=l;if(e=t?t.stream:null)e.drmInfos=k,e.keyIds=l,this.config_.disableIFrames||shaka.util.StreamUtils.setBetterIFrameStream(e,m);e&&!a&&(e.bandwidth=c);!e&&a&&(a.bandwidth=c);f=r?r.stream.drmInfos:null;g=t?t.stream.drmInfos:null;h=t?t.getUris().sort().join(","):"";p=r?r.getUris().sort().join(","):"";const u=[];a&&a.codecs&&u.push(a.codecs);e&&e.codecs&&u.push(e.codecs);h=[h,p,u.sort()].join("-");if(a&&e&&!q.areDrmCompatible(f,g)){shaka.log.warning("Incompatible DRM info in HLS variant.  Skipping.");
continue}if(this.variantUriSet_.has(h)){shaka.log.debug("Skipping variant which only differs in text streams.");continue}goog.asserts.assert(!a||a.type==n.AUDIO,"Audio parameter mismatch!");goog.asserts.assert(!e||e.type==n.VIDEO,"Video parameter mismatch!");a={id:this.globalId_++,language:a?a.language:"und",disabledUntilTime:0,primary:!!a&&a.primary||!!e&&e.primary,audio:a,video:e,bandwidth:c,allowedByApplication:!0,allowedByKeySystem:!0,decodingInfos:[]};d.push(a);this.variantUriSet_.add(h)}return d}parseClosedCaptions_(a){a=
shaka.hls.Utils.filterTagsByType(a,"CLOSED-CAPTIONS");this.needsClosedCaptionsDetection_=a.length==0;for(const c of a){goog.asserts.assert(c.name=="EXT-X-MEDIA","Should only be called on media tags!");var b=c.getAttributeValue("LANGUAGE");a=this.getLanguage_(b);b||(b=c.getAttributeValue("NAME"))&&(a=b);b=c.getRequiredAttrValue("GROUP-ID");const d=c.getRequiredAttrValue("INSTREAM-ID").replace("SERVICE","svc");this.groupIdToClosedCaptionsMap_.get(b)||this.groupIdToClosedCaptionsMap_.set(b,new Map);
this.groupIdToClosedCaptionsMap_.get(b).set(d,a)}}createStreamInfoFromMediaTags_(a,b,c=!0){var d=[],e=[],f=new Map;for(var g of a){goog.asserts.assert(g.name=="EXT-X-MEDIA","Should only be called on media tags!");var h=++this.globalId_,k=c?g.getRequiredAttrValue("URI"):g.getAttributeValue("URI")||shaka.hls.HlsParser.FAKE_MUXED_URL_+h;h=g.getRequiredAttrValue("GROUP-ID");d.push(k);e.push(h);f.set(h,k);(k=g.getAttributeValue("PATHWAY-ID"))&&b.set(h,k)}c=e.sort().join(",");h=a[0];a="";g=this.getType_(h);
if(g==shaka.util.ManifestParserUtils.ContentType.TEXT)a=h.getAttributeValue("CODECS")||"";else for(var l of e)if(this.groupIdToCodecsMap_.has(l)){a=this.groupIdToCodecsMap_.get(l);break}e=d.sort().join(",");g=="audio"&&c&&(e+=c);if(this.uriToStreamInfosMap_.has(e))return this.uriToStreamInfosMap_.get(e);l=this.globalId_++;if(this.contentSteeringManager_)for(const [r,t]of f)(f=b.get(r))&&this.contentSteeringManager_.addLocation(l,f,t);b=h.getAttributeValue("LANGUAGE");f=h.getAttributeValue("NAME");
k=h.getAttributeValue("DEFAULT")=="YES";const m=g=="audio"?this.getChannelsCount_(h):null,n=g=="audio"?this.isSpatialAudio_(h):!1,q=h.getAttributeValue("CHARACTERISTICS"),p=h.getAttributeValue("FORCED")=="YES";h=g=="audio"?this.getSampleRate_(h):null;d=this.createStreamInfo_(l,d,a,g,b,k,f,m,null,q,p,h,n);d.stream&&this.config_.enableAudioGroups&&(d.stream.groupId=c);this.groupIdToStreamInfosMap_.has(c)?this.groupIdToStreamInfosMap_.get(c).push(d):this.groupIdToStreamInfosMap_.set(c,[d]);this.uriToStreamInfosMap_.set(e,
d);return d}async createStreamInfoFromImageTag_(a){goog.asserts.assert(a.name=="EXT-X-IMAGE-STREAM-INF","Should only be called on image tags!");var b=shaka.util.ManifestParserUtils.ContentType.IMAGE;const c=a.getRequiredAttrValue("URI");var d=a.getAttributeValue("CODECS","jpeg")||"";if(this.uriToStreamInfosMap_.has(c))return this.uriToStreamInfosMap_.get(c);var e=a.getAttributeValue("LANGUAGE");const f=a.getAttributeValue("NAME"),g=a.getAttributeValue("CHARACTERISTICS");b=this.createStreamInfo_(this.globalId_++,
[c],d,b,e,!1,f,null,null,g,!1,null,!1);if(d=a.getAttributeValue("RESOLUTION")){await b.stream.createSegmentIndex();if(e=b.stream.segmentIndex.earliestReference().getTilesLayout())b.stream.width=Number(d.split("x")[0])*Number(e.split("x")[0]),b.stream.height=Number(d.split("x")[1])*Number(e.split("x")[1]);b.stream.closeSegmentIndex()}if(a=a.getAttributeValue("BANDWIDTH"))b.stream.bandwidth=Number(a);this.uriToStreamInfosMap_.set(c,b);return b}createStreamInfoFromIframeTag_(a){goog.asserts.assert(a.name==
"EXT-X-I-FRAME-STREAM-INF","Should only be called on iframe tags!");var b=shaka.util.ManifestParserUtils.ContentType.VIDEO;const c=a.getRequiredAttrValue("URI");var d=a.getAttributeValue("CODECS")||"";d=="mjpg"&&(b=shaka.util.ManifestParserUtils.ContentType.IMAGE);if(this.uriToStreamInfosMap_.has(c))return this.uriToStreamInfosMap_.get(c);const e=a.getAttributeValue("LANGUAGE"),f=a.getAttributeValue("NAME"),g=a.getAttributeValue("CHARACTERISTICS");b=this.createStreamInfo_(this.globalId_++,[c],d,b,
e,!1,f,null,null,g,!1,null,!1);d=a.getAttributeValue("RESOLUTION");const [h,k]=d?d.split("x"):[null,null];b.stream.width=Number(h)||void 0;b.stream.height=Number(k)||void 0;if(a=a.getAttributeValue("BANDWIDTH"))b.stream.bandwidth=Number(a);this.uriToStreamInfosMap_.set(c,b);return b}createStreamInfoFromVariantTags_(a,b,c){const d=this.globalId_++,e=[];for(var f of a){goog.asserts.assert(f.name=="EXT-X-STREAM-INF","Should only be called on variant tags!");var g=f.getRequiredAttrValue("URI");const h=
f.getAttributeValue("PATHWAY-ID");this.contentSteeringManager_&&h&&this.contentSteeringManager_.addLocation(d,h,g);e.push(g)}f=e.sort().join(",")+b.sort().join(",");if(this.uriToStreamInfosMap_.has(f))return this.uriToStreamInfosMap_.get(f);g=e.join(",");a=this.getClosedCaptions_(a[0],c);b=shaka.util.ManifestParserUtils.guessCodecs(c,b);c=this.createStreamInfo_(d,e,b,c,null,!1,g,null,a,null,!1,null,!1);this.uriToStreamInfosMap_.set(f,c);return c}createStreamInfo_(a,b,c,d,e,f,g,h,k,l,m,n,q){const p=
this.makeStreamObject_(a,c,d,e,f,g,h,k,l,m,n,q);b.some(y=>y.startsWith(shaka.hls.HlsParser.FAKE_MUXED_URL_))&&(p.isAudioMuxedInVideo=!0,p.mimeType="video/mp2t",this.setFullTypeForStream_(p));const r={stream:p,type:d,redirectUris:[],getUris:()=>{},minTimestamp:0,maxTimestamp:0,mediaSequenceToStartTime:new Map,canSkipSegments:!1,canBlockReload:!1,hasEndList:!1,firstSequenceNumber:-1,nextMediaSequence:-1,nextPart:-1},t=()=>this.contentSteeringManager_&&b.length>1?this.contentSteeringManager_.getLocations(a):
r.redirectUris.concat(shaka.hls.Utils.constructUris([this.masterPlaylistUri_],b,this.globalVariables_));r.getUris=t;const u=async y=>{const A=shaka.util.ManifestParserUtils.ContentType;try{const G=await y.promise;if(!y.aborted){var w=G.uri;w!=G.originalUri&&(r.getUris().includes(w)||r.redirectUris.push(w));var z=this.manifestTextParser_.parsePlaylist(G.data);if(z.type!=shaka.hls.PlaylistType.MEDIA)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_INVALID_PLAYLIST_HIERARCHY);
var B=shaka.hls.Utils.filterTagsByName(z.tags,"EXT-X-DEFINE"),C=this.parseMediaVariables_(B,w);w=!1;(!this.codecInfoInManifest_&&this.config_.hls.disableCodecGuessing||this.needsClosedCaptionsDetection_&&d==A.VIDEO&&!this.config_.hls.disableClosedCaptionsDetection)&&z.segments.length>0&&(this.needsClosedCaptionsDetection_=!1,w=!0);var F=!this.codecInfoInManifest_&&this.config_.hls.disableCodecGuessing,H=this.isLive_(),I=await this.convertParsedPlaylistIntoStreamInfo_(a,C,z,t,c,d,e,f,g,h,k,l,m,n,q,
void 0,w,F);if(!y.aborted){var D=I.stream;this.determineStartTime_(z);this.isLive_()&&!H&&this.changePresentationTimelineToLive_(z);r.minTimestamp=I.minTimestamp;r.maxTimestamp=I.maxTimestamp;r.canSkipSegments=I.canSkipSegments;r.canBlockReload=I.canBlockReload;r.hasEndList=I.hasEndList;r.mediaSequenceToStartTime=I.mediaSequenceToStartTime;r.nextMediaSequence=I.nextMediaSequence;r.nextPart=I.nextPart;p.segmentIndex=D.segmentIndex;p.encrypted=D.encrypted;p.drmInfos=D.drmInfos;p.keyIds=D.keyIds;p.mimeType=
D.mimeType;p.bandwidth=p.bandwidth||D.bandwidth;p.codecs=p.codecs||D.codecs;p.closedCaptions=p.closedCaptions||D.closedCaptions;p.width=p.width||D.width;p.height=p.height||D.height;p.hdr=p.hdr||D.hdr;p.colorGamut=p.colorGamut||D.colorGamut;p.frameRate=p.frameRate||D.frameRate;p.language=="und"&&D.language!="und"&&(p.language=D.language);p.language=p.language||D.language;p.channelsCount=p.channelsCount||D.channelsCount;p.audioSamplingRate=p.audioSamplingRate||D.audioSamplingRate;this.setFullTypeForStream_(p);
p.drmInfos.length&&this.playerInterface_.newDrmInfo(p);y=!1;if(!k&&p.closedCaptions||k&&p.closedCaptions&&k.size!=p.closedCaptions.size)y=!0;this.manifest_&&y&&this.playerInterface_.makeTextStreamsForClosedCaptions(this.manifest_);if(d==A.TEXT){const E=D.segmentIndex.earliestReference();E&&E.initSegmentReference&&(p.mimeType="application/mp4",this.setFullTypeForStream_(p))}var J=shaka.media.QualityObserver.createQualityInfo(p);p.segmentIndex.forEachTopLevelReference(E=>{E.initSegmentReference&&(E.initSegmentReference.mediaQuality=
J)});if(this.hasEnoughInfoToFinalizeStreams_())if(this.streamsFinalized_)this.finalizeStreams_([r]);else{this.streamsFinalized_=!0;const E=Array.from(this.uriToStreamInfosMap_.values()).filter(L=>L.stream.segmentIndex);this.finalizeStreams_(E);this.determineDuration_();const K=this.getUpdatePlaylistDelay_();K>0&&this.updatePlaylistTimer_.tickAfter(K)}this.processDateRangeTags_(z.tags,p.type,C,t);this.manifest_&&(this.manifest_.startTime=this.startTime_)}}}catch(G){if(p.closeSegmentIndex(),G.code!==
shaka.util.Error.Code.OPERATION_ABORTED&&!this.playerInterface_.disableStream(p))throw G;}};let v=null,x;p.createSegmentIndex=()=>{if(v)return v;if(p.isAudioMuxedInVideo){const y=new shaka.media.SegmentIndex([]);p.segmentIndex=y;return Promise.resolve()}x=this.requestManifest_(r.getUris(),!0);return v=new Promise(y=>{y(u(x))})};p.closeSegmentIndex=()=>{v&&!p.segmentIndex&&x.abort();p.segmentIndex&&(p.segmentIndex.release(),p.segmentIndex=null);v=null};return r}getMinDuration_(){let a=Infinity;for(const b of this.uriToStreamInfosMap_.values())b.stream.segmentIndex&&
b.stream.type!="text"&&!b.stream.isAudioMuxedInVideo&&(a=Math.min(a,b.maxTimestamp));return a}getLiveDuration_(){let a=Infinity,b=Infinity;for(const c of this.uriToStreamInfosMap_.values())c.stream.segmentIndex&&c.stream.type!="text"&&!c.stream.isAudioMuxedInVideo&&(a=Math.min(a,c.maxTimestamp),b=Math.min(b,c.minTimestamp));return a-b}notifySegmentsForStreams_(a){const b=[];for(const c of a)c.segmentIndex&&c.segmentIndex.forEachTopLevelReference(d=>{b.push(d)});this.presentationTimeline_.notifySegments(b)}finalizeStreams_(a){if(!this.isLive_()){var b=
this.getMinDuration_();for(var c of a)c.stream.segmentIndex.fit(0,b)}this.notifySegmentsForStreams_(a.map(f=>f.stream));c=Array.from(this.uriToStreamInfosMap_.values()).filter(f=>f.stream.segmentIndex);const d=shaka.util.ManifestParserUtils.ContentType;b=c.some(f=>f.stream.type==d.AUDIO);const e=c.some(f=>f.stream.type==d.VIDEO);c=this.isLive_()&&!this.usesProgramDateTime_;b=!this.isLive_()&&this.usesProgramDateTime_&&!(b&&e);this.config_.hls.ignoreManifestProgramDateTime||c||b?this.syncStreamsWithSequenceNumber_(a,
c):(this.syncStreamsWithProgramDateTime_(a),this.config_.hls.ignoreManifestProgramDateTimeForTypes.length>0&&this.syncStreamsWithSequenceNumber_(a))}ignoreManifestProgramDateTimeFor_(a){return this.config_.hls.ignoreManifestProgramDateTime?!0:this.config_.hls.ignoreManifestProgramDateTimeForTypes.includes(a)}hasEnoughInfoToFinalizeStreams_(){if(!this.manifest_||!this.manifest_.variants.length)return!1;const a=[],b=[];for(const c of this.manifest_.variants)c.video&&a.push(c.video),c.audio&&b.push(c.audio);
return a.length>0&&!a.some(c=>c.segmentIndex)||b.length>0&&!b.some(c=>c.segmentIndex)?!1:!0}async convertParsedPlaylistIntoStreamInfo_(a,b,c,d,e,f,g,h,k,l,m,n,q,p,r,t,u=!0,v=!0){var x=c.segments||[],y=x.every(K=>shaka.hls.Utils.getFirstTagWithName(K.tags,"EXT-X-GAP")?!0:!1);if(!x.length||y)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_EMPTY_MEDIA_PLAYLIST);this.determinePresentationType_(c);this.isLive_()&&this.determineLastTargetDuration_(c);
x=this.isLive_()?this.mediaSequenceToStartTimeByType_.get(f):new Map;const {segments:A,bandwidth:w}=this.createSegments_(c,x,b,d,f);let z=y=null,B=null,C=null,F=null;A.length>0&&u&&(u=await this.getBasicInfoFromSegments_(A),f!=u.type&&this.isLive_()&&(this.mediaSequenceToStartTimeByType_.set(u.type,this.mediaSequenceToStartTimeByType_.get(f)),this.mediaSequenceToStartTimeByType_.set(f,new Map)),f=u.type,g=u.language,l=u.channelCount,p=u.sampleRate,this.config_.disableText||(m=u.closedCaptions),z=
u.height,y=u.width,B=u.videoRange,C=u.colorGamut,F=u.frameRate,v&&(t=u.mimeType,e=u.codecs));t||(t=await this.guessMimeType_(f,e,A),f!=shaka.util.ManifestParserUtils.ContentType.TEXT||e||t!="application/mp4"||!A[0]||A[0].initSegmentReference||(t="text/vtt"));const {drmInfos:H,keyIds:I,encrypted:D,aesEncrypted:J}=await this.parseDrmInfo_(c,t,d,b);if(D&&!H.length&&!J)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_KEYFORMATS_NOT_SUPPORTED);
a=this.makeStreamObject_(a,e,f,g,h,k,l,m,n,q,p,r);a.encrypted=D&&!J;a.drmInfos=H;a.keyIds=I;a.mimeType=t;w&&(a.bandwidth=w);this.setFullTypeForStream_(a);f==shaka.util.ManifestParserUtils.ContentType.VIDEO&&(y||z||B||C)&&this.addVideoAttributes_(a,y,z,F,B,null,C);this.isLive_()&&this.determineLastTargetDuration_(c);t=A[0].startTime;b=A[A.length-1].endTime;e=new shaka.media.SegmentIndex(A);a.segmentIndex=e;e=(g=shaka.hls.Utils.getFirstTagWithName(c.tags,"EXT-X-SERVER-CONTROL"))?g.getAttribute("CAN-SKIP-UNTIL")!=
null:!1;g=g?g.getAttribute("CAN-BLOCK-RELOAD")!=null:!1;c=shaka.hls.Utils.getFirstTagWithNameAsNumber(c.tags,"EXT-X-MEDIA-SEQUENCE",0);const {nextMediaSequence:G,nextPart:E}=this.getNextMediaSequenceAndPart_(c,A);return{stream:a,type:f,redirectUris:[],getUris:d,minTimestamp:t,maxTimestamp:b,canSkipSegments:e,canBlockReload:g,hasEndList:!1,firstSequenceNumber:-1,nextMediaSequence:G,nextPart:E,mediaSequenceToStartTime:x}}getNextMediaSequenceAndPart_(a,b){a=a+b.length-1;let c=-1;if(!b.length)return a++,
{nextMediaSequence:a,nextPart:c};b=b[b.length-1];const d=b.partialReferences;if(!b.partialReferences.length)return a++,b.hasByterangeOptimization()&&(c=0),{nextMediaSequence:a,nextPart:c};c=d.length-1;d[d.length-1].isPreload()||(a++,c=0);return{nextMediaSequence:a,nextPart:c}}makeStreamObject_(a,b,c,d,e,f,g,h,k,l,m,n){a=this.guessMimeTypeBeforeLoading_(c,b)||this.guessMimeTypeFallback_(c);const q=[];if(k)for(var p of k.split(","))q.push(p);p=void 0;k=null;c==shaka.util.ManifestParserUtils.ContentType.TEXT?
p=q.includes("public.accessibility.transcribes-spoken-dialog")&&q.includes("public.accessibility.describes-music-and-sound")?shaka.util.ManifestParserUtils.TextStreamKind.CLOSED_CAPTION:shaka.util.ManifestParserUtils.TextStreamKind.SUBTITLE:q.includes("public.accessibility.describes-video")&&(k=shaka.media.ManifestParser.AccessibilityPurpose.VISUALLY_IMPAIRED);q.length||p!==shaka.util.ManifestParserUtils.TextStreamKind.SUBTITLE||q.push(shaka.util.ManifestParserUtils.TextStreamKind.SUBTITLE);p=null;
c!=shaka.util.ManifestParserUtils.ContentType.VIDEO&&(p=f);b={id:this.globalId_++,originalId:f,groupId:null,createSegmentIndex:()=>Promise.resolve(),segmentIndex:null,mimeType:a,codecs:b,kind:c==shaka.util.ManifestParserUtils.ContentType.TEXT?shaka.util.ManifestParserUtils.TextStreamKind.SUBTITLE:void 0,encrypted:!1,drmInfos:[],keyIds:new Set,language:this.getLanguage_(d),originalLanguage:d,label:p,type:c,primary:e,trickModeVideo:null,dependencyStream:null,emsgSchemeIdUris:null,frameRate:void 0,pixelAspectRatio:void 0,
width:void 0,height:void 0,bandwidth:void 0,roles:q,forced:l,channelsCount:g,audioSamplingRate:m,spatialAudio:n,closedCaptions:h,hdr:void 0,colorGamut:void 0,videoLayout:void 0,tilesLayout:void 0,accessibilityPurpose:k,external:!1,fastSwitching:!1,fullMimeTypes:new Set,isAudioMuxedInVideo:!1,baseOriginalId:null};this.setFullTypeForStream_(b);return b}async parseDrmInfo_(a,b,c,d){var e=new Map;if(!this.config_.ignoreDrmInfo&&a.segments)for(var f of a.segments){var g=shaka.hls.Utils.filterTagsByName(f.tags,
"EXT-X-KEY"),h=void 0;if(g.length){h=this.getInitSegmentReference_(a,f.tags,c,d);for(var k of g)e.set(k,h)}}f=a=!1;g=[];h=new Set;for(const [m,n]of e){k=m;const q=n;var l=k.getRequiredAttrValue("METHOD");if(l!="NONE")if(a=!0,e=k.getAttributeValue("KEYFORMAT")||"identity",this.isAesMethod_(l))f=!0;else if(k=e=="identity"?await this.identityDrmParser_(k,b,c,q,d):(l=this.keyFormatsToDrmParsers_.get(e))?await l(k,b,q):null,k){if(k.keyIds)for(const p of k.keyIds)h.add(p);g.push(k)}else shaka.log.warning("Unsupported HLS KEYFORMAT",
e)}return{drmInfos:g,keyIds:h,encrypted:a,aesEncrypted:f}}parseAESDrmTag_(a,b,c,d){if(!window.crypto||!window.crypto.subtle)throw shaka.log.alwaysWarn("Web Crypto API is not available to decrypt AES. (Web Crypto only exists in secure origins like https)"),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.NO_WEB_CRYPTO_API);let e=0,f;const g=a.getAttributeValue("IV","");if(g){if(f=shaka.util.Uint8ArrayUtils.fromHex(g.substr(2)),f.byteLength!=
16)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.AES_128_INVALID_IV_LENGTH);}else e=shaka.hls.Utils.getFirstTagWithNameAsNumber(b.tags,"EXT-X-MEDIA-SEQUENCE",0);const h=shaka.hls.Utils.constructSegmentUris(c(),a.getRequiredAttrValue("URI"),d),k=h.sort().join("");b=`${a.toString()}-${e}-${k}`;if(!this.aesKeyInfoMap_.has(b)){const l={bitsKey:128,blockCipherMode:"CBC",iv:f,firstMediaSequenceNumber:e};switch(a.getRequiredAttrValue("METHOD")){case "AES-256":l.bitsKey=
256;break;case "AES-256-CTR":l.bitsKey=256,l.blockCipherMode="CTR"}l.fetchKey=async()=>{if(!this.aesKeyMap_.has(k)){var m=shaka.net.NetworkingEngine.RequestType.KEY;const n=shaka.net.NetworkingEngine.makeRequest(h,this.config_.retryParameters);m=this.makeNetworkRequest_(n,m).promise;this.aesKeyMap_.set(k,m)}m=await this.aesKeyMap_.get(k);if(!m.data||m.data.byteLength!=l.bitsKey/8)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.AES_128_INVALID_KEY_LENGTH);
l.cryptoKey=await window.crypto.subtle.importKey("raw",m.data,{name:l.blockCipherMode=="CTR"?"AES-CTR":"AES-CBC",length:l.bitsKey},!0,["decrypt"]);l.fetchKey=void 0};this.aesKeyInfoMap_.set(b,l)}return this.aesKeyInfoMap_.get(b)}determineStartTime_(a){this.startTime_==null&&(a=shaka.hls.Utils.getFirstTagWithName(a.tags,"EXT-X-START"))&&(this.startTime_=Number(a.getRequiredAttrValue("TIME-OFFSET")))}determinePresentationType_(a){const b=shaka.hls.HlsParser.PresentationType_;var c=shaka.hls.Utils.getFirstTagWithName(a.tags,
"EXT-X-PLAYLIST-TYPE");a=shaka.hls.Utils.getFirstTagWithName(a.tags,"EXT-X-ENDLIST");a=c&&c.value=="VOD"||a;c=c&&c.value=="EVENT"&&!a;c=!a&&!c;a?this.setPresentationType_(b.VOD):c?this.setPresentationType_(b.LIVE):this.setPresentationType_(b.EVENT)}determineLastTargetDuration_(a){var b=Infinity,c=a.segments;if(c.length)for(var d=c.length-1;d>=0;){const e=shaka.hls.Utils.getFirstTagWithName(c[d].tags,"EXTINF");if(e){b=shaka.hls.Utils.getExtinfDuration(e);break}d--}c=this.getRequiredTag_(a.tags,"EXT-X-TARGETDURATION");
c=Number(c.value);if(d=shaka.hls.Utils.getFirstTagWithName(a.tags,"EXT-X-PART-INF"))this.partialTargetDuration_=Number(d.getRequiredAttrValue("PART-TARGET"));a=shaka.hls.Utils.getFirstTagWithName(a.tags,"EXT-X-SERVER-CONTROL");this.lowLatencyMode_&&this.partialTargetDuration_?(this.lastTargetDuration_=this.lowLatencyByterangeOptimization_?this.partialTargetDuration_*5<=b?Math.min(this.partialTargetDuration_,this.lastTargetDuration_):Math.min(b,this.lastTargetDuration_):Math.min(this.partialTargetDuration_,
this.lastTargetDuration_),this.lowLatencyPresentationDelay_=a?Number(a.getRequiredAttrValue("PART-HOLD-BACK")):0):(this.lastTargetDuration_=Math.min(b,this.lastTargetDuration_),this.presentationDelay_=(b=a?a.getAttribute("HOLD-BACK"):null)?Number(b.value):0);this.maxTargetDuration_=Math.max(c,this.maxTargetDuration_)}changePresentationTimelineToLive_(a){let b=0;if(this.config_.defaultPresentationDelay)b=this.config_.defaultPresentationDelay;else if(this.lowLatencyPresentationDelay_)b=this.lowLatencyPresentationDelay_;
else if(this.presentationDelay_)b=this.presentationDelay_;else{const d=a.segments.length;var c=Math.min(d,this.config_.hls.liveSegmentsDelay);for(c=d-c;c<d;c++){const e=shaka.hls.Utils.getFirstTagWithName(a.segments[c].tags,"EXTINF");b=e?b+shaka.hls.Utils.getExtinfDuration(e):b+this.maxTargetDuration_}}this.startTime_&&this.startTime_<0&&(b=Math.min(-this.startTime_,b),this.startTime_+=b);this.presentationTimeline_.setPresentationStartTime(0);this.presentationTimeline_.setDelay(b);this.presentationTimeline_.setStatic(!1)}getInitSegmentReference_(a,
b,c,d){const e=shaka.hls.Utils.getFirstTagWithName(b,"EXT-X-MAP");if(!e)return null;var f=e.getRequiredAttrValue("URI");const g=shaka.hls.Utils.constructSegmentUris(c(),f,d);f=[g.toString(),e.getAttributeValue("BYTERANGE","")].join("-");if(!this.mapTagToInitSegmentRefMap_.has(f)){let h=void 0,k=null,l=!1;for(const m of b)m.name=="EXT-X-KEY"?(b=m.getRequiredAttrValue("METHOD"),this.isAesMethod_(b)&&m.id<e.id?(l=!1,h=this.parseAESDrmTag_(m,a,c,d)):l=b!="NONE"):m.name=="EXT-X-BYTERANGE"&&m.id<e.id&&
(k=m);a=this.createInitSegmentReference_(g,e,k,h,l);this.mapTagToInitSegmentRefMap_.set(f,a)}return this.mapTagToInitSegmentRefMap_.get(f)}createInitSegmentReference_(a,b,c,d,e){var f=0,g=null;b=b.getAttributeValue("BYTERANGE");!b&&c&&(b=c.value);b&&(f=b.split("@"),g=Number(f[0]),f=Number(f[1]),g=f+g-1,d&&(c=g+1-f,c%16&&(g+=16-c%16)));return new shaka.media.InitSegmentReference(()=>a,f,g,null,null,null,d,e)}createSegmentReference_(a,b,c,d,e,f,g,h,k,l){f=shaka.hls.HlsParser;const m=c.tags;var n=shaka.hls.Utils.getFirstTagWithName(m,
"EXTINF"),q=0;let p=0,r=null;c.partialSegments.length&&(this.manifest_.isLowLatency=!0);let t=null;if(!this.config_.hls.ignoreManifestProgramDateTime){var u=shaka.hls.Utils.getFirstTagWithName(m,"EXT-X-PROGRAM-DATE-TIME");u&&u.value&&(t=shaka.util.TXml.parseDate(u.value),goog.asserts.assert(t!=null,"EXT-X-PROGRAM-DATE-TIME format not valid"),this.usesProgramDateTime_=!0)}let v=shaka.media.SegmentReference.Status.AVAILABLE;shaka.hls.Utils.getFirstTagWithName(m,"EXT-X-GAP")&&(this.manifest_.gapCount++,
v=shaka.media.SegmentReference.Status.MISSING);if(!n){if(c.partialSegments.length==0)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_REQUIRED_TAG_MISSING,"EXTINF");if(!this.lowLatencyMode_)return null}let x=[];u=!1;let y=null,A=!1,w=!1;if(this.lowLatencyMode_&&c.partialSegments.length){q=a&&window.ReadableStream&&this.config_.hls.allowLowLatencyByteRangeOptimization;let J=t;for(let G=0;G<c.partialSegments.length;G++){var z=
c.partialSegments[G],B=G==0?b:x[x.length-1],C=G==0?d:B.endTime;const E=Number(z.getAttributeValue("DURATION"))||this.partialTargetDuration_;if(!E)continue;var F=C+E,H=0,I=null;z.name=="EXT-X-PRELOAD-HINT"?(H=(H=z.getAttributeValue("BYTERANGE-START"))?Number(H):0,(B=z.getAttributeValue("BYTERANGE-LENGTH"))?I=H+Number(B)-1:H&&(I=Number.MAX_SAFE_INTEGER)):(I=z.getAttributeValue("BYTERANGE"),[H,I]=this.parseByteRange_(B,I));const K=z.getAttributeValue("URI");if(!K)continue;B=shaka.media.SegmentReference.Status.AVAILABLE;
z.getAttributeValue("GAP")=="YES"&&(this.manifest_.gapCount++,B=shaka.media.SegmentReference.Status.MISSING,A=!0);let L=null;const M=()=>{L==null&&(goog.asserts.assert(K,"Partial uri should be defined!"),L=shaka.hls.Utils.constructSegmentUris(h(),K,e));return L};q&&H>=0&&I!=null&&(y=M,u=!0);C=new shaka.media.SegmentReference(C,F,M,H,I,a,0,0,Infinity,[],"",null,J,B,l);z.name=="EXT-X-PRELOAD-HINT"&&(C.markAsPreload(),w=!0);z.getAttributeValue("INDEPENDENT")!="YES"&&G>0&&C.markAsNonIndependent();z=k;
z||(x.length&&x[0].mimeType?z=x[0].mimeType:K&&(z=shaka.hls.HlsParser,F=shaka.net.NetworkingUtils.getExtension(K),z=z.EXTENSION_MAP_BY_CONTENT_TYPE_.get(g).get(F)||null));z&&(C.mimeType=z,f.MIME_TYPES_WITHOUT_INIT_SEGMENT_.has(z)&&(C.initSegmentReference=null));x.push(C);J&&(J+=E)}}if(n){n=shaka.hls.Utils.getExtinfDuration(n);if(n==0)return null;q=d+n}else if(x.length)q=x[x.length-1].endTime;else return null;u&&(A||x[0].startByte!=0?(u=!1,y=null):x=[]);(n=shaka.hls.Utils.getFirstTagWithName(m,"EXT-X-BYTERANGE"))?
[p,r]=this.parseByteRange_(b,n.value):x.length&&(p=x[0].startByte,r=x[x.length-1].endByte);b="";n=null;g==shaka.util.ManifestParserUtils.ContentType.IMAGE&&(b="1x1",g=shaka.hls.Utils.getFirstTagWithName(m,"EXT-X-TILES"))&&(b=g.getRequiredAttrValue("LAYOUT"),(g=g.getAttributeValue("DURATION"))&&(n=Number(g)));let D=null;a=new shaka.media.SegmentReference(d,q,()=>{if(y)return y();D==null&&(D=shaka.hls.Utils.constructSegmentUris(h(),c.verbatimSegmentUri,e));return D||[]},p,r,a,0,0,Infinity,x,b,n,t,v,
l,x.length>0&&!!c.verbatimSegmentUri);k&&(a.mimeType=k,f.MIME_TYPES_WITHOUT_INIT_SEGMENT_.has(k)&&(a.initSegmentReference=null));u&&(this.lowLatencyByterangeOptimization_=!0,a.markAsByterangeOptimization(),w&&a.markAsPreload());return a}parseByteRange_(a,b){var c=0;let d=null;b&&(c=b.split("@"),b=Number(c[0]),c[1]?c=Number(c[1]):(goog.asserts.assert(a,"Cannot refer back to previous HLS segment!"),c=a.endByte+1),d=c+b-1);return[c,d]}processDateRangeTags_(a,b,c,d){var e=shaka.util.ManifestParserUtils.ContentType;
if(b==e.VIDEO||b==e.AUDIO){e=shaka.hls.Utils;var f=this.presentationTimeline_.getInitialProgramDateTime();if(f!=null&&!this.ignoreManifestProgramDateTimeFor_(b))for(a=shaka.hls.Utils.filterTagsByName(a,"EXT-X-DATERANGE"),a=a.filter(h=>h.getAttribute("START-DATE")!=null).sort((h,k)=>{h=h.getRequiredAttrValue("START-DATE");k=k.getRequiredAttrValue("START-DATE");return h<k?-1:h>k?1:0}),b=0;b<a.length;b++){const h=a[b];try{const k=h.getRequiredAttrValue("START-DATE"),l=shaka.util.TXml.parseDate(k);if(isNaN(l))continue;
goog.asserts.assert(l!=null,"Start date should not be null!");const m=Math.max(0,l-f);let n=null;const q=h.getAttributeValue("END-DATE");if(q){const u=shaka.util.TXml.parseDate(q);if(!isNaN(u)&&(goog.asserts.assert(u!=null,"End date should not be null!"),n=u-f,n<0))continue}if(n==null){const u=h.getAttributeValue("DURATION")||h.getAttributeValue("PLANNED-DURATION");if(u){const v=parseFloat(u);isNaN(v)||(n=m+v);if(l-f+v<0)continue}}const p=h.getAttributeValue("CLASS")||"com.apple.quicktime.HLS",r=
h.getAttributeValue("END-ON-NEXT")=="YES";if(n==null&&r){for(var g=b+1;g<a.length;g++){const u=a[g].getAttributeValue("CLASS")||"com.apple.quicktime.HLS";if(p!=u)continue;const v=a[g].getRequiredAttrValue("START-DATE"),x=shaka.util.TXml.parseDate(v);if(!isNaN(x)&&x&&x>l){n=Math.max(0,x-f);break}}if(n==null)continue}g=["CLASS","START-DATE","END-DATE","DURATION","END-ON-NEXT"];const t=[];for(const u of h.attributes){if(g.includes(u.name))continue;let v=e.variableSubstitution(u.value,c);if(u.name=="X-ASSET-URI"||
u.name=="X-ASSET-LIST")v=e.constructSegmentUris(d(),u.value,c)[0];t.push({key:u.name,description:"",data:v,mimeType:null,pictureType:null})}if(t.length>1)this.playerInterface_.onMetadata(p,m,n,t)}catch(k){shaka.log.warning("Ignoring DATERANGE with errors",h.toString())}}}}createSegments_(a,b,c,d,e){const f=a.segments;goog.asserts.assert(f.length,"Playlist should have segments!");let g=null,h=null,k=null,l=null,m=void 0,n=shaka.hls.Utils.getFirstTagWithNameAsNumber(a.tags,"EXT-X-DISCONTINUITY-SEQUENCE",
-1);const q=shaka.hls.Utils.getFirstTagWithNameAsNumber(a.tags,"EXT-X-MEDIA-SEQUENCE",0);var p=shaka.hls.Utils.getFirstTagWithName(a.tags,"EXT-X-SKIP");const r=p?Number(p.getAttributeValue("SKIPPED-SEGMENTS")):0;var t=q+r;let u=0;this.isLive_()&&b.has(t)&&(u=b.get(t));u===0&&this.presentationType_==shaka.hls.HlsParser.PresentationType_.LIVE&&b.size>0&&!b.has(t)&&this.presentationTimeline_.getPresentationStartTime()!=null&&(u=this.presentationTimeline_.getSegmentAvailabilityStart());const v=[];var x=
null;p=[];const y=B=>{const C=shaka.hls.HlsParser;B=shaka.net.NetworkingUtils.getExtension(B);if(!B)return null;let F=C.EXTENSION_MAP_BY_CONTENT_TYPE_.get(e).get(B);F||=C.RAW_FORMATS_TO_MIME_TYPES_.get(B);return F};for(let B=0;B<f.length;B++){var A=f[B];(t=shaka.hls.Utils.getFirstTagWithName(A.tags,"EXT-X-MAP"))&&t.id!==h&&(g=this.getInitSegmentReference_(a,A.tags,d,c),h=t.id);t=A.verbatimSegmentUri;var w="";t&&(w=shaka.net.NetworkingUtils.getExtension(t));w!==l&&(k=y(t),l=w);w=B==0?u:x.endTime;t=
q+r+B;shaka.hls.Utils.getFirstTagWithName(A.tags,"EXT-X-DISCONTINUITY")&&(n++,x&&x.initSegmentReference&&(x.initSegmentReference.boundaryEnd=w));for(const C of A.tags)C.name=="EXT-X-KEY"&&(m=this.isAesMethod_(C.getRequiredAttrValue("METHOD"))?this.parseAESDrmTag_(C,a,d,c):void 0);b.set(t,w);if(w=this.createSegmentReference_(g,x,A,w,c,a,e,d,k,m)){if(x=shaka.hls.Utils.getFirstTagWithNameAsNumber(A.tags,"EXT-X-BITRATE"))p.push({bitrate:x,duration:w.endTime-w.startTime}),w.bandwidth=x;else if(w.endByte){if(A=
w.getSize())x=w.endTime-w.startTime,A=A*8/x/1E3,p.push({bitrate:A,duration:x}),w.bandwidth=A}else p.length&&(x=p[p.length-1],x.duration+=w.endTime-w.startTime,w.bandwidth=x.bitrate);if(w.bandwidth)for(const C of w.partialReferences)C.bandwidth=w.bandwidth;x=w;w.discontinuitySequence=n;this.ignoreManifestProgramDateTimeFor_(e)&&this.minSequenceNumber_!=null&&t<this.minSequenceNumber_||v.push(w)}}a=void 0;p.length&&(a=p.reduce((B,C)=>B+C.duration,0),a=Math.round(p.reduce((B,C)=>B+C.bitrate*C.duration,
0)/a*1E3));if(p=v.some(B=>B.syncTime!=null))for(b=0;b<v.length;b++){const B=v[b];if(B.syncTime!=null)continue;let C=0,F=b;c=()=>{const D=v[F];if(D){if(D.syncTime!=null)return D.syncTime+C;C-=D.endTime-D.startTime;F+=1}return null};let H=0,I=b;for(d=()=>{const D=v[I];if(D){D!=B&&(H+=D.endTime-D.startTime);if(D.syncTime!=null)return D.syncTime+H;--I}return null};B.syncTime==null;)B.syncTime=d(),B.syncTime==null&&(B.syncTime=c())}if(p)for(var z of v){b=z.syncTime;for(const B of z.partialReferences)B.syncTime=
b,b+=B.endTime-B.startTime}z=this.lowestSyncTime_;if(p&&z!=Infinity&&!this.ignoreManifestProgramDateTimeFor_(e))for(const B of v)B.syncAgainst(z);return{segments:v,bandwidth:a}}guessMimeTypeBeforeLoading_(a,b){if(a==shaka.util.ManifestParserUtils.ContentType.TEXT){if(b=="vtt"||b=="wvtt")return"text/vtt";if(b&&b!=="")return"application/mp4"}return a!=shaka.util.ManifestParserUtils.ContentType.IMAGE||b&&b!="jpeg"?a==shaka.util.ManifestParserUtils.ContentType.AUDIO&&b=="mp4a.40.34"?"audio/mpeg":b=="mjpg"?
"application/mp4":null:"image/jpeg"}guessMimeTypeFallback_(a){return a==shaka.util.ManifestParserUtils.ContentType.TEXT?"text/vtt":shaka.hls.HlsParser.EXTENSION_MAP_BY_CONTENT_TYPE_.get(a).get("mp4")}getAvailableSegment_(a){goog.asserts.assert(a.length,"Should have segments!");let b=this.isLive_()?Math.trunc((a.length-1)/2):0,c=a[b];for(;c.getStatus()==shaka.media.SegmentReference.Status.MISSING&&b+1<a.length;)b++,c=a[b];return{segment:c,segmentIndex:b}}async guessMimeType_(a,b,c){var d=shaka.hls.HlsParser;
const e=shaka.net.NetworkingEngine.RequestType.SEGMENT;({segment:c}=this.getAvailableSegment_(c));if(c.status==shaka.media.SegmentReference.Status.MISSING)return this.guessMimeTypeFallback_(a);c=c.getUris();const f=shaka.net.NetworkingUtils.getExtension(c[0]);if(f){let k=d.EXTENSION_MAP_BY_CONTENT_TYPE_.get(a).get(f);if(k||(k=d.RAW_FORMATS_TO_MIME_TYPES_.get(f)))return k}if(b=this.guessMimeTypeBeforeLoading_(a,b))return b;let g;d=shaka.net.NetworkingEngine.AdvancedRequestType.MEDIA_SEGMENT;c=shaka.net.NetworkingEngine.makeRequest(c,
this.config_.retryParameters);let h;try{c.method="HEAD",h=await this.makeNetworkRequest_(c,e,{type:d}).promise,g=h.headers["content-type"]}catch(k){!k||k.code!=shaka.util.Error.Code.HTTP_ERROR&&k.code!=shaka.util.Error.Code.BAD_HTTP_STATUS||(c.method="GET",this.config_.hls.allowRangeRequestsToGuessMimeType&&(c.headers.Range="bytes=0-0"),h=await this.makeNetworkRequest_(c,e,{type:d}).promise,g=h.headers["content-type"])}return g&&(b=g.toLowerCase().split(";")[0],b=="application/octet-stream"&&(h.data.byteLength||
(c.method="GET",h=await this.makeNetworkRequest_(c,e,{type:d}).promise),shaka.util.TsParser.probe(shaka.util.BufferUtils.toUint8(h.data))&&(b="video/mp2t")),b!="application/octet-stream")?b:this.guessMimeTypeFallback_(a)}getRequiredTag_(a,b){a=shaka.hls.Utils.getFirstTagWithName(a,b);if(!a)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_REQUIRED_TAG_MISSING,b);return a}addVideoAttributes_(a,b,c,d,e,f,g){a&&(a.width=Number(b)||
void 0,a.height=Number(c)||void 0,a.frameRate=Number(d)||void 0,a.hdr=e||void 0,a.videoLayout=f||void 0,a.colorGamut=g||void 0)}requestManifest_(a,b){const c=shaka.net.NetworkingEngine.RequestType.MANIFEST;a=shaka.net.NetworkingEngine.makeRequest(a,this.config_.retryParameters);return this.makeNetworkRequest_(a,c,{type:b?shaka.net.NetworkingEngine.AdvancedRequestType.MEDIA_PLAYLIST:shaka.net.NetworkingEngine.AdvancedRequestType.MASTER_PLAYLIST})}async onUpdate_(){shaka.log.info("Updating manifest...");
goog.asserts.assert(this.getUpdatePlaylistDelay_()>0,"We should only call |onUpdate_| when we are suppose to be updating.");if(this.playerInterface_){try{const a=Date.now();await this.update();const b=Date.now();if(this.isLive_()){this.averageUpdateDuration_.sample(1,(b-a)/1E3);const c=this.config_.updatePeriod>0?this.config_.updatePeriod:this.getUpdatePlaylistDelay_(),d=Math.max(0,c-this.averageUpdateDuration_.getEstimate());isFinite(d)?this.updatePlaylistTimer_.tickAfter(d):this.updatePlaylistTimer_.tickAfter(1)}}catch(a){if(!this.playerInterface_)return;
goog.asserts.assert(a instanceof shaka.util.Error,"Should only receive a Shaka error");if(this.config_.raiseFatalErrorOnManifestUpdateRequestFailure){this.playerInterface_.onError(a);return}a.severity=shaka.util.Error.Severity.RECOVERABLE;this.playerInterface_.onError(a);this.updatePlaylistTimer_.tickAfter(.1)}if(this.playerInterface_)this.playerInterface_.onManifestUpdated()}}isLive_(){return this.presentationType_!=shaka.hls.HlsParser.PresentationType_.VOD}getUpdatePlaylistDelay_(){return this.lastTargetDuration_}setPresentationType_(a){this.presentationType_=
a;this.presentationTimeline_&&this.presentationTimeline_.setStatic(!this.isLive_());this.isLive_()||this.updatePlaylistTimer_.stop()}makeNetworkRequest_(a,b,c){if(!this.operationManager_)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.OPERATION_ABORTED);c||={};c.isPreload=this.isPreloadFn_();a=this.playerInterface_.networkingEngine.request(b,a,c);this.operationManager_.manage(a);return a}isAesMethod_(a){return a=="AES-128"||a=="AES-256"||
a=="AES-256-CTR"}async fairplayDrmParser_(a,b,c){if(b=="video/mp2t")throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_MSE_ENCRYPTED_MP2T_NOT_SUPPORTED);if(shaka.drm.DrmUtils.isMediaKeysPolyfilled("apple"))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_MSE_ENCRYPTED_LEGACY_APPLE_MEDIA_KEYS_NOT_SUPPORTED);b=a.getRequiredAttrValue("METHOD");var d=["SAMPLE-AES",
"SAMPLE-AES-CTR"];if(!d.includes(b))return shaka.log.error("FairPlay in HLS is only supported with [",d.join(", "),"], not",b),null;d="cenc";b=="SAMPLE-AES"&&(d="cbcs");a=a.getRequiredAttrValue("URI");b=shaka.util.ManifestParserUtils.createDrmInfo("com.apple.fps",d,null,a);a=shaka.drm.FairPlay.defaultGetKeyId(a);!a&&c&&(a=await this.getKeyIdFromInitSegment_(c));a&&b.keyIds.add(a);return b}widevineDrmParser_(a,b,c){c=a.getRequiredAttrValue("METHOD");b=["SAMPLE-AES","SAMPLE-AES-CTR"];if(!b.includes(c))return shaka.log.error("Widevine in HLS is only supported with [",
b.join(", "),"], not",c),Promise.resolve(null);b="cenc";c=="SAMPLE-AES"&&(b="cbcs");var d=a.getRequiredAttrValue("URI");c=shaka.net.DataUriPlugin.parseRaw(d.split("?")[0]);d=d.split("?")[0];if(!this.psshToInitData_.has(d)){const e=shaka.util.BufferUtils.toUint8(c.data);this.psshToInitData_.set(d,e)}b=shaka.util.ManifestParserUtils.createDrmInfo("com.widevine.alpha",b,[{initDataType:"cenc",initData:this.psshToInitData_.get(d)}],void 0,c.typeInfoList);if(a=a.getAttributeValue("KEYID"))a=a.toLowerCase(),
goog.asserts.assert(a.startsWith("0x"),"Incorrect KEYID format!"),b.keyIds.add(a.substr(2));return Promise.resolve(b)}playreadyDrmParser_(a,b,c){c=a.getRequiredAttrValue("METHOD");b=["SAMPLE-AES","SAMPLE-AES-CTR"];if(!b.includes(c))return shaka.log.error("PlayReady in HLS is only supported with [",b.join(", "),"], not",c),Promise.resolve(null);b="cenc";c=="SAMPLE-AES"&&(b="cbcs");a=a.getRequiredAttrValue("URI");c=shaka.net.DataUriPlugin.parseRaw(a.split("?")[0]);a=shaka.util.BufferUtils.toUint8(c.data);
var d=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);const e=new Set;d=shaka.util.Pssh.createPssh(a,d,e,0);b=shaka.util.ManifestParserUtils.createDrmInfo("com.microsoft.playready",b,[{initDataType:"cenc",initData:d}],void 0,c.typeInfoList);if(a=shaka.util.TXml.parseXmlString(["<PLAYREADY>",shaka.util.Uint8ArrayUtils.toBase64(a),"</PLAYREADY>"].join("\n")))b.licenseServerUri=shaka.drm.PlayReady.getLicenseUrl(a);return Promise.resolve(b)}wiseplayDrmParser_(a,b,c){c=a.getRequiredAttrValue("METHOD");
b=["SAMPLE-AES","SAMPLE-AES-CTR"];if(!b.includes(c))return shaka.log.error("WisePlay in HLS is only supported with [",b.join(", "),"], not",c),Promise.resolve(null);b="cenc";c=="SAMPLE-AES"&&(b="cbcs");var d=a.getRequiredAttrValue("URI");c=shaka.net.DataUriPlugin.parseRaw(d.split("?")[0]);d=d.split("?")[0];if(!this.psshToInitData_.has(d)){const e=shaka.util.BufferUtils.toUint8(c.data);this.psshToInitData_.set(d,e)}b=shaka.util.ManifestParserUtils.createDrmInfo("com.huawei.wiseplay",b,[{initDataType:"cenc",
initData:this.psshToInitData_.get(d)}],void 0,c.typeInfoList);if(a=a.getAttributeValue("KEYID"))a=a.toLowerCase(),goog.asserts.assert(a.startsWith("0x"),"Incorrect KEYID format!"),b.keyIds.add(a.substr(2));return Promise.resolve(b)}async identityDrmParser_(a,b,c,d,e){if(b=="video/mp2t")throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_MSE_ENCRYPTED_MP2T_NOT_SUPPORTED);if(shaka.drm.DrmUtils.isMediaKeysPolyfilled("apple"))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_MSE_ENCRYPTED_LEGACY_APPLE_MEDIA_KEYS_NOT_SUPPORTED);b=a.getRequiredAttrValue("METHOD");const f=["SAMPLE-AES","SAMPLE-AES-CTR"];if(!f.includes(b))return shaka.log.error("Identity (ClearKey) in HLS is only supported with [",f.join(", "),"], not",b),null;e=shaka.hls.Utils.constructSegmentUris(c(),a.getRequiredAttrValue("URI"),e);e[0].startsWith("data:text/plain;base64,")?a=shaka.util.Uint8ArrayUtils.toHex(shaka.util.Uint8ArrayUtils.fromBase64(e[0].split("data:text/plain;base64,").pop())):
(a=e.sort().join(""),this.identityKeyMap_.has(a)||(c=shaka.net.NetworkingEngine.RequestType.KEY,e=shaka.net.NetworkingEngine.makeRequest(e,this.config_.retryParameters),c=this.makeNetworkRequest_(e,c).promise,this.identityKeyMap_.set(a,c)),a=await this.identityKeyMap_.get(a),a=shaka.util.Uint8ArrayUtils.toHex(a.data));c="00000000000000000000000000000000";d&&(d=await this.getKeyIdFromInitSegment_(d))&&(c=d);d=new Map;d.set(c,a);a="cenc";b=="SAMPLE-AES"&&(a="cbcs");return shaka.util.ManifestParserUtils.createDrmInfoFromClearKeys(d,
a)}async getKeyIdFromInitSegment_(a){if(this.initSegmentToKidMap_.has(a))var b=this.initSegmentToKidMap_.get(a);else b=shaka.net.NetworkingUtils.createSegmentRequest(a.getUris(),a.getStartByte(),a.getEndByte(),this.config_.retryParameters),b=await this.makeNetworkRequest_(b,shaka.net.NetworkingEngine.RequestType.SEGMENT,{type:shaka.net.NetworkingEngine.AdvancedRequestType.INIT_SEGMENT}).promise,a.setSegmentData(b.data),b=shaka.media.SegmentUtils.getDefaultKID(b.data),this.initSegmentToKidMap_.set(a,
b);return b}};goog.exportSymbol("shaka.hls.HlsParser",shaka.hls.HlsParser);shaka.hls.HlsParser.RAW_FORMATS_TO_MIME_TYPES_=(new Map).set("aac","audio/aac").set("ac3","audio/ac3").set("ec3","audio/ec3").set("mp3","audio/mpeg");shaka.hls.HlsParser.AUDIO_EXTENSIONS_TO_MIME_TYPES_=(new Map).set("mp4","audio/mp4").set("mp4a","audio/mp4").set("m4s","audio/mp4").set("m4i","audio/mp4").set("m4a","audio/mp4").set("m4f","audio/mp4").set("cmfa","audio/mp4").set("ts","video/mp2t").set("tsa","video/mp2t");
shaka.hls.HlsParser.VIDEO_EXTENSIONS_TO_MIME_TYPES_=(new Map).set("mp4","video/mp4").set("mp4v","video/mp4").set("m4s","video/mp4").set("m4i","video/mp4").set("m4v","video/mp4").set("m4f","video/mp4").set("cmfv","video/mp4").set("ts","video/mp2t").set("tsv","video/mp2t");
shaka.hls.HlsParser.TEXT_EXTENSIONS_TO_MIME_TYPES_=(new Map).set("mp4","application/mp4").set("m4s","application/mp4").set("m4i","application/mp4").set("m4f","application/mp4").set("cmft","application/mp4").set("vtt","text/vtt").set("webvtt","text/vtt").set("ttml","application/ttml+xml");shaka.hls.HlsParser.IMAGE_EXTENSIONS_TO_MIME_TYPES_=(new Map).set("jpg","image/jpeg").set("png","image/png").set("svg","image/svg+xml").set("webp","image/webp").set("avif","image/avif");
shaka.hls.HlsParser.EXTENSION_MAP_BY_CONTENT_TYPE_=(new Map).set("audio",shaka.hls.HlsParser.AUDIO_EXTENSIONS_TO_MIME_TYPES_).set("video",shaka.hls.HlsParser.VIDEO_EXTENSIONS_TO_MIME_TYPES_).set("text",shaka.hls.HlsParser.TEXT_EXTENSIONS_TO_MIME_TYPES_).set("image",shaka.hls.HlsParser.IMAGE_EXTENSIONS_TO_MIME_TYPES_);shaka.hls.HlsParser.MIME_TYPES_WITHOUT_INIT_SEGMENT_=new Set(["video/mp2t",...shaka.util.MimeUtils.RAW_FORMATS]);shaka.hls.HlsParser.PresentationType_={VOD:"VOD",EVENT:"EVENT",LIVE:"LIVE"};
shaka.hls.HlsParser.FAKE_MUXED_URL_="shaka://hls-muxed";shaka.media.ManifestParser.registerParserByMime("application/x-mpegurl",()=>new shaka.hls.HlsParser);shaka.media.ManifestParser.registerParserByMime("application/vnd.apple.mpegurl",()=>new shaka.hls.HlsParser);shaka.media.ManifestParser.registerParserByMime("audio/x-mpegurl",()=>new shaka.hls.HlsParser);shaka.mss={};
shaka.mss.ContentProtection=class{static parseFromProtection(a,b){const c=shaka.mss.ContentProtection,d=shaka.util.TXml;let e=[];for(const f of a)e=e.concat(d.findChildren(f,"ProtectionHeader"));return e.length?c.convertElements_(e,b):[]}static getPlayReadyLicenseUrl(a){return shaka.drm.PlayReady.getLicenseUrl(a)}static getPlayReadyKID_(a){return shaka.drm.PlayReady.getPlayReadyKID(a)}static getInitDataFromPro_(a,b,c){var d=shaka.util.Uint8ArrayUtils;a=d.fromBase64(shaka.util.TXml.getTextContents(a));b=
d.fromHex(b.replace(/-/g,""));d=new Set;return[{initData:shaka.util.Pssh.createPssh(a,b,d,0),initDataType:"cenc",keyId:c}]}static convertElements_(a,b){const c=shaka.mss.ContentProtection,d=shaka.util.ManifestParserUtils,e=c.licenseUrlParsers_,f=[];for(let k=0;k<a.length;k++){const l=a[k];var g=l.attributes.SystemID.toLowerCase(),h=b[g];if(h){const m=c.getPlayReadyKID_(l);g=c.getInitDataFromPro_(l,g,m);g=d.createDrmInfo(h,"cenc",g);m&&g.keyIds.add(m);if(h=e.get(h))g.licenseServerUri=h(l);f.push(g)}}return f}};
shaka.mss.ContentProtection.licenseUrlParsers_=(new Map).set("com.microsoft.playready",shaka.mss.ContentProtection.getPlayReadyLicenseUrl).set("com.microsoft.playready.recommendation",shaka.mss.ContentProtection.getPlayReadyLicenseUrl).set("com.microsoft.playready.software",shaka.mss.ContentProtection.getPlayReadyLicenseUrl).set("com.microsoft.playready.hardware",shaka.mss.ContentProtection.getPlayReadyLicenseUrl);shaka.mss.MssParser=class{constructor(){this.playerInterface_=this.config_=null;this.manifestUris_=[];this.manifest_=null;this.globalId_=1;this.updatePeriod_=0;this.presentationTimeline_=null;this.averageUpdateDuration_=new shaka.abr.Ewma(5);this.updateTimer_=new shaka.util.Timer(()=>{this.onUpdate_()});this.operationManager_=new shaka.util.OperationManager;this.initSegmentDataByStreamId_=new Map;this.isPreloadFn_=()=>!1}configure(a,b){goog.asserts.assert(a.mss!=null,"MssManifestConfiguration should not be null!");
this.config_=a;b&&(this.isPreloadFn_=b)}async start(a,b){goog.asserts.assert(this.config_,"Must call configure() before start()!");this.manifestUris_=[a];this.playerInterface_=b;await this.requestManifest_();if(!this.playerInterface_)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.OPERATION_ABORTED);this.setUpdateTimer_();goog.asserts.assert(this.manifest_,"Manifest should be non-null!");return this.manifest_}async onUpdate_(){goog.asserts.assert(this.updatePeriod_>=
0,"There should be an update period");shaka.log.info("Updating manifest...");try{await this.requestManifest_()}catch(a){goog.asserts.assert(a instanceof shaka.util.Error,"Should only receive a Shaka error"),this.playerInterface_&&(a.severity=shaka.util.Error.Severity.RECOVERABLE,this.playerInterface_.onError(a))}this.playerInterface_&&this.setUpdateTimer_()}setUpdateTimer_(){if(!(this.updatePeriod_<=0)){var a=Math.max(shaka.mss.MssParser.MIN_UPDATE_PERIOD_,this.updatePeriod_,this.averageUpdateDuration_.getEstimate());
this.updateTimer_.tickAfter(a)}}stop(){this.config_=this.playerInterface_=null;this.manifestUris_=[];this.manifest_=null;this.updateTimer_!=null&&(this.updateTimer_.stop(),this.updateTimer_=null);this.initSegmentDataByStreamId_.clear();return this.operationManager_.destroy()}async update(){try{await this.requestManifest_()}catch(a){this.playerInterface_&&a&&(goog.asserts.assert(a instanceof shaka.util.Error,"Bad error type"),this.playerInterface_.onError(a))}}onExpirationUpdated(a,b){}onInitialVariantChosen(a){}banLocation(a){}setMediaElement(a){}async requestManifest_(){var a=
shaka.net.NetworkingEngine.RequestType.MANIFEST;const b=shaka.net.NetworkingEngine.AdvancedRequestType.MSS,c=shaka.net.NetworkingEngine.makeRequest(this.manifestUris_,this.config_.retryParameters),d=this.playerInterface_.networkingEngine,e=Date.now();a=d.request(a,c,{type:b,isPreload:this.isPreloadFn_()});this.operationManager_.manage(a);a=await a.promise;this.playerInterface_&&(a.uri&&!this.manifestUris_.includes(a.uri)&&this.manifestUris_.unshift(a.uri),this.parseManifest_(a.data,a.uri),a=Date.now(),
this.averageUpdateDuration_.sample(1,(a-e)/1E3))}parseManifest_(a,b){var c=a;a=this.config_.mss.manifestPreprocessor;if(a!=shaka.util.PlayerConfiguration.defaultManifestPreprocessor){shaka.Deprecate.deprecateFeature(5,"manifest.mss.manifestPreprocessor configuration","Please Use manifest.mss.manifestPreprocessorTXml instead.");c=shaka.util.XmlUtils.parseXml(c,"SmoothStreamingMedia");if(!c)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.MSS_INVALID_XML,
b);a(c);c=shaka.util.XmlUtils.toArrayBuffer(c)}a=shaka.util.TXml.parseXml(c,"SmoothStreamingMedia");if(!a)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.MSS_INVALID_XML,b);c=this.config_.mss.manifestPreprocessorTXml;c!=shaka.util.PlayerConfiguration.defaultManifestPreprocessorTXml&&c(a);this.processManifest_(a,b);return Promise.resolve()}processManifest_(a,b){var c=shaka.util.TXml;this.presentationTimeline_||(this.presentationTimeline_=
new shaka.media.PresentationTimeline(null,0));if(b=c.parseAttr(a,"IsLive",c.parseBoolean,!1))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.MSS_LIVE_CONTENT_NOT_SUPPORTED);this.presentationTimeline_.setStatic(!b);const d=c.parseAttr(a,"TimeScale",c.parseNonNegativeInt,shaka.mss.MssParser.DEFAULT_TIME_SCALE_);goog.asserts.assert(d&&d>=0,"Timescale must be defined!");let e=c.parseAttr(a,"DVRWindowLength",c.parseNonNegativeInt);
b&&(e===0||isNaN(e))&&(e=Infinity);var f=c.parseAttr(a,"CanSeek",c.parseBoolean,!1);e===0&&f&&(e=Infinity);f=null;e&&e>0&&(f=e/d);b&&!isNaN(this.config_.availabilityWindowOverride)&&(f=this.config_.availabilityWindowOverride);f==null&&(f=Infinity);this.presentationTimeline_.setSegmentAvailabilityDuration(f);c=c.parseAttr(a,"Duration",c.parseNonNegativeInt,Infinity);goog.asserts.assert(c&&c>=0,"Duration must be defined!");b||this.presentationTimeline_.setDuration(c/d);b={variants:[],textStreams:[],
timescale:d,duration:c/d};this.parseStreamIndexes_(a,b);this.manifest_?(this.manifest_.variants=b.variants,this.manifest_.textStreams=b.textStreams,this.playerInterface_.filter(this.manifest_)):(this.manifest_={presentationTimeline:this.presentationTimeline_,variants:b.variants,textStreams:b.textStreams,imageStreams:[],offlineSessionIds:[],sequenceMode:this.config_.mss.sequenceMode,ignoreManifestTimestampsInSegmentsMode:!1,type:shaka.media.ManifestParser.MSS,serviceDescription:null,nextUrl:null,periodCount:1,
gapCount:0,isLowLatency:!1,startTime:null},this.presentationTimeline_.lockStartTime())}parseStreamIndexes_(a,b){var c=shaka.mss.ContentProtection,d=shaka.util.TXml;const e=shaka.util.ManifestParserUtils.ContentType;var f=d.findChildren(a,"Protection");const g=c.parseFromProtection(f,this.config_.mss.keySystemsBySystemId);c=[];f=[];const h=[];a=d.findChildren(a,"StreamIndex");for(const l of a){var k=d.findChildren(l,"QualityLevel");a=this.createTimeline_(l,b.timescale,b.duration);for(const m of k)(k=
this.createStream_(l,m,a,g,b))&&(k.type!=e.AUDIO||this.config_.disableAudio?k.type!=e.VIDEO||this.config_.disableVideo?k.type!=e.TEXT||this.config_.disableText||h.push(k):f.push(k):c.push(k))}d=[];for(const l of c.length>0?c:[null])for(const m of f.length>0?f:[null])d.push(this.createVariant_(l,m));b.variants=d;b.textStreams=h}createStream_(a,b,c,d,e){var f=shaka.util.TXml;const g=shaka.util.ManifestParserUtils.ContentType;var h=shaka.mss.MssParser;const k=a.attributes.Type;if(k!=="audio"&&k!=="video"&&
k!=="text")return shaka.log.alwaysWarn("Ignoring unrecognized type:",k),null;const l=a.attributes.Language,m=this.globalId_++,n=f.parseAttr(b,"Bitrate",f.parsePositiveInt),q=f.parseAttr(b,"MaxWidth",f.parsePositiveInt),p=f.parseAttr(b,"MaxHeight",f.parsePositiveInt),r=f.parseAttr(b,"Channels",f.parsePositiveInt);f=f.parseAttr(b,"SamplingRate",f.parsePositiveInt);let t=e.duration;c.length&&(t=c[c.length-1].end-c[0].start);var u=this.presentationTimeline_.getDuration();this.presentationTimeline_.setDuration(Math.min(t,
u));(u=a.attributes.Name)&&(u+=b.attributes.Index);u||=String(m);const v={id:m,originalId:u,groupId:null,createSegmentIndex:()=>Promise.resolve(),closeSegmentIndex:()=>Promise.resolve(),segmentIndex:null,mimeType:"",codecs:"",frameRate:void 0,pixelAspectRatio:void 0,bandwidth:n||0,width:q||void 0,height:p||void 0,kind:"",encrypted:d.length>0,drmInfos:d,keyIds:new Set,language:shaka.util.LanguageUtils.normalize(l||"und"),originalLanguage:l,label:"",type:"",primary:!1,trickModeVideo:null,dependencyStream:null,
emsgSchemeIdUris:[],roles:[],forced:!1,channelsCount:r,audioSamplingRate:f,spatialAudio:!1,closedCaptions:null,hdr:void 0,colorGamut:void 0,videoLayout:void 0,tilesLayout:void 0,matchedStreams:[],mssPrivateData:{duration:t,timescale:e.timescale,codecPrivateData:null},accessibilityPurpose:null,external:!1,fastSwitching:!1,fullMimeTypes:new Set,isAudioMuxedInVideo:!1,baseOriginalId:null};if(d=a.attributes.Subtype)(d=h.ROLE_MAPPING_.get(d))&&v.roles.push(d),d==="main"&&(v.primary=!0);d=b.attributes.FourCC;
if(d===null||d==="")d=a.attributes.FourCC;if(!d)if(k==="audio")d="AAC";else if(k==="video")return shaka.log.alwaysWarn('FourCC is not defined whereas it is required for a QualityLevel element for a StreamIndex of type "video"'),null;if(!h.SUPPORTED_CODECS_.includes(d.toUpperCase()))return shaka.log.alwaysWarn("Codec not supported:",d),null;h=this.getCodecPrivateData_(b,k,d,v);v.mssPrivateData.codecPrivateData=h;switch(k){case "audio":if(!h)return shaka.log.alwaysWarn("Quality unsupported without CodecPrivateData",
k),null;v.type=g.AUDIO;v.mimeType="mss/audio/mp4";v.codecs=this.getAACCodec_(b,d,h);break;case "video":if(!h)return shaka.log.alwaysWarn("Quality unsupported without CodecPrivateData",k),null;v.type=g.VIDEO;v.mimeType="mss/video/mp4";v.codecs=this.getH264Codec_(b,h);break;case "text":if(v.type=g.TEXT,v.mimeType="application/mp4",d==="TTML"||d==="DFXP")v.codecs="stpp"}v.fullMimeTypes.add(shaka.util.MimeUtils.getFullType(v.mimeType,v.codecs));v.createSegmentIndex=()=>{if(v.segmentIndex)return Promise.resolve();
if(this.initSegmentDataByStreamId_.has(v.id))var x=this.initSegmentDataByStreamId_.get(v.id);else x=[],v.type==g.VIDEO&&(x=v.mssPrivateData.codecPrivateData.split("00000001").slice(1)),x={id:v.id,type:v.type,codecs:v.codecs,encrypted:v.encrypted,timescale:v.mssPrivateData.timescale,duration:v.mssPrivateData.duration,videoNalus:x,audioConfig:new Uint8Array([]),videoConfig:new Uint8Array([]),hSpacing:0,vSpacing:0,data:null,stream:v},x=(new shaka.util.Mp4Generator([x])).initSegment(),this.initSegmentDataByStreamId_.set(v.id,
x);const y=shaka.media.QualityObserver.createQualityInfo(v);x=new shaka.media.InitSegmentReference(()=>[],0,null,y,v.mssPrivateData.timescale,x,null,v.encrypted);x=this.createSegments_(x,v,a,c);v.segmentIndex=new shaka.media.SegmentIndex(x);return Promise.resolve()};v.closeSegmentIndex=()=>{v.segmentIndex&&(v.segmentIndex.release(),v.segmentIndex=null)};return v}getCodecPrivateData_(a,b,c,d){if(a=a.attributes.CodecPrivateData)return a;if(b!=="audio")return null;b=d.channelsCount||2;a=d.audioSamplingRate||
44100;const e={96E3:0,88200:1,64E3:2,48E3:3,44100:4,32E3:5,24E3:6,22050:7,16E3:8,12E3:9,11025:10,8E3:11,7350:12};d=e[a];if(c==="AACH")return c=new Uint8Array(4),a=e[a*2],c[0]=40|d>>1,c[1]=d<<7|b<<3|a>>1,c[2]=a<<7|8,c[3]=0,b=new Uint16Array(2),b[0]=(c[0]<<8)+c[1],b[1]=(c[2]<<8)+c[3],b[0].toString(16)+b[1].toString(16);c=new Uint8Array(2);c[0]=16|d>>1;c[1]=d<<7|b<<3;b=new Uint16Array(1);b[0]=(c[0]<<8)+c[1];return b[0].toString(16)}getAACCodec_(a,b,c){a=0;b==="AACH"&&(a=5);c?a===0&&(a=(parseInt(c.substr(0,
2),16)&248)>>3):(a=2,b==="AACH"&&(a=5));return"mp4a.40."+a}getH264Codec_(a,b){a=/00000001[0-9]7/.exec(b);return a.length&&b?"avc1."+b.substr(b.indexOf(a[0])+10,6):""}createSegments_(a,b,c,d){const e=shaka.util.ManifestParserUtils;c=c.attributes.Url;goog.asserts.assert(c,"Missing URL for segments");const f=c.replace("{bitrate}",String(b.bandwidth));c=[];for(const g of d)c.push(new shaka.media.SegmentReference(g.start,g.end,()=>e.resolveUris(this.manifestUris_,[f.replace("{start time}",String(g.unscaledStart))]),
0,null,a,0,0,b.mssPrivateData.duration));return c}createTimeline_(a,b,c){goog.asserts.assert(b>0&&b<Infinity,"timescale must be a positive, finite integer");goog.asserts.assert(c>0,"duration must be a positive integer");const d=shaka.util.TXml;a=d.findChildren(a,"c");const e=[];var f=0;for(let m=0;m<a.length;++m){var g=a[m],h=a[m+1],k=d.parseAttr(g,"t",d.parseNonNegativeInt);const n=d.parseAttr(g,"d",d.parseNonNegativeInt);var l=d.parseAttr(g,"r",d.parseInt);if(!n){shaka.log.warning('"c" element must have a duration:',
'ignoring the remaining "c" elements.',g);break}k=k!=null?k:f;(l=l||0)&&l--;if(l<0)if(h){h=d.parseAttr(h,"t",d.parseNonNegativeInt);if(h==null){shaka.log.warning('An "c" element cannot have a negative repeat','if the next "c" element does not have a valid start time:','ignoring the remaining "c" elements.',g);break}else if(k>=h){shaka.log.warning('An "c" element cannot have a negative repeat if its start ','time exceeds the next "c" element\'s start time:','ignoring the remaining "c" elements.',g);
break}l=Math.ceil((h-k)/n)-1}else{if(c==Infinity){shaka.log.warning('The last "c" element cannot have a negative repeat',"if the Period has an infinite duration:",'ignoring the last "c" element.',g);break}else if(k/b>=c){shaka.log.warning('The last "c" element cannot have a negative repeat',"if its start time exceeds the duration:",'ignoring the last "c" element.',g);break}l=Math.ceil((c*b-k)/n)-1}for(g=0;g<=l;++g)f=k+n,e.push({start:k/b,end:f/b,unscaledStart:k}),k=f}return e}createVariant_(a,b){var c=
shaka.util.ManifestParserUtils.ContentType;goog.asserts.assert(!a||a.type==c.AUDIO,"Audio parameter mismatch!");goog.asserts.assert(!b||b.type==c.VIDEO,"Video parameter mismatch!");c=0;a&&a.bandwidth&&a.bandwidth>0&&(c+=a.bandwidth);b&&b.bandwidth&&b.bandwidth>0&&(c+=b.bandwidth);return{id:this.globalId_++,language:a?a.language:"und",disabledUntilTime:0,primary:!!a&&a.primary||!!b&&b.primary,audio:a,video:b,bandwidth:c,allowedByApplication:!0,allowedByKeySystem:!0,decodingInfos:[]}}};
goog.exportSymbol("shaka.mss.MssParser",shaka.mss.MssParser);shaka.mss.MssParser.MIN_UPDATE_PERIOD_=3;shaka.mss.MssParser.DEFAULT_TIME_SCALE_=1E7;shaka.mss.MssParser.SUPPORTED_CODECS_="AAC AACL AACH AACP AVC1 H264 TTML DFXP".split(" ");shaka.mss.MssParser.ROLE_MAPPING_=(new Map).set("CAPT","main").set("SUBT","alternate").set("DESC","main");shaka.media.ManifestParser.registerParserByMime("application/vnd.ms-sstr+xml",()=>new shaka.mss.MssParser);shaka.net.HttpPluginUtils=class{static makeResponse(a,b,c,d,e,f,g){goog.asserts.assert(b,"Data should be non-null!");if(c>=200&&c<=299&&c!=202||c==304)return{uri:e||d,originalUri:d,data:b,status:c,headers:a,fromCache:!!a["x-shaka-from-cache"],originalRequest:f};f=null;try{f=shaka.util.StringUtils.fromBytesAutoDetect(b)}catch(h){}shaka.log.debug("HTTP error text:",f);throw new shaka.util.Error(c==401||c==403?shaka.util.Error.Severity.CRITICAL:shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,
shaka.util.Error.Code.BAD_HTTP_STATUS,d,c,f,a,g,e||d);}};shaka.net.HttpFetchPlugin=class{static parse(a,b,c,d,e,f){const g=new shaka.net.HttpFetchPlugin.Headers_;try{shaka.util.MapUtils.asMap(b.headers).forEach((l,m)=>{g.append(m,l)})}catch(l){return shaka.log.debug("Failed to create headers:",l),shaka.util.AbortableOperation.failed(new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.HTTP_ERROR,a,l,c))}const h=new shaka.net.HttpFetchPlugin.AbortController_,k={canceled:!1,timedOut:!1};a=shaka.net.HttpFetchPlugin.request_(a,
b,c,{body:b.body||void 0,headers:g,method:b.method,signal:h.signal,credentials:b.allowCrossSiteCredentials?"include":void 0},k,d,e,b.streamDataCallback,f.minBytesForProgressEvents||0);a=new shaka.util.AbortableOperation(a,()=>{k.canceled=!0;h.abort();return Promise.resolve()});if(b=b.retryParameters.timeout){const l=new shaka.util.Timer(()=>{k.timedOut=!0;h.abort()});l.tickAfter(b/1E3);a.finally(()=>{l.stop()})}return a}static async request_(a,b,c,d,e,f,g,h,k){const l=shaka.net.HttpFetchPlugin.fetch_,
m=shaka.net.HttpFetchPlugin.ReadableStream_;let n,q=new ArrayBuffer(0),p=0,r=0,t={},u=Date.now();try{n=await l(a,d);t=shaka.net.HttpFetchPlugin.headersToGenericObject_(n.headers);g(t);if(d.method!="HEAD"){goog.asserts.assert(n.body,"non-HEAD responses should have a body");const v=n.headers.get("Content-Length"),x=v?parseInt(v,10):0;if(n.body){const y=n.clone().body.getReader();new m({start:A=>{const w=async()=>{let z;try{z=await y.read()}catch(F){shaka.log.v1("error reading from stream",F.message);
return}z.done||(p+=z.value.byteLength,h&&await h(z.value));const B=Date.now(),C=p-r;if(B-u>100&&C>=k||z.done)f(B-u,C,z.done?0:x-p),r=p,u=B;z.done?(goog.asserts.assert(!z.value,'readObj should be unset when "done" is true.'),A.close()):(A.enqueue(z.value),w())};w()}});q=await n.arrayBuffer()}else{q=await n.arrayBuffer();const y=Date.now();f(y-u,q.byteLength,0)}}if(b.headers.Range){const v=b.headers.Range.replace("bytes=","").split("-").filter(x=>x).map(x=>parseInt(x,10));v.length==2&&q.byteLength!=
v[1]-v[0]+1&&shaka.log.alwaysWarn("Payload length does not match range requested bytes",b,n)}}catch(v){if(e.canceled)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.OPERATION_ABORTED,a,c);if(e.timedOut)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.TIMEOUT,a,c);throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,
shaka.util.Error.Code.HTTP_ERROR,a,v,c);}return shaka.net.HttpPluginUtils.makeResponse(t,q,n.status,a,n.url,b,c)}static headersToGenericObject_(a){const b={};a.forEach((c,d)=>{b[d.trim()]=c});return b}static isSupported(){if(window.ReadableStream)try{new ReadableStream({})}catch(a){return!1}else return!1;if(window.Response){if(!(new Response("")).body)return!1}else return!1;return!(!window.fetch||"polyfill"in window.fetch||!window.AbortController)}};goog.exportSymbol("shaka.net.HttpFetchPlugin",shaka.net.HttpFetchPlugin);
goog.exportProperty(shaka.net.HttpFetchPlugin,"isSupported",shaka.net.HttpFetchPlugin.isSupported);goog.exportProperty(shaka.net.HttpFetchPlugin,"parse",shaka.net.HttpFetchPlugin.parse);shaka.net.HttpFetchPlugin.fetch_=window.fetch;shaka.net.HttpFetchPlugin.AbortController_=window.AbortController;shaka.net.HttpFetchPlugin.ReadableStream_=window.ReadableStream;shaka.net.HttpFetchPlugin.Headers_=window.Headers;
shaka.net.HttpFetchPlugin.isSupported()&&(shaka.net.NetworkingEngine.registerScheme("http",shaka.net.HttpFetchPlugin.parse,shaka.net.NetworkingEngine.PluginPriority.PREFERRED,!0),shaka.net.NetworkingEngine.registerScheme("https",shaka.net.HttpFetchPlugin.parse,shaka.net.NetworkingEngine.PluginPriority.PREFERRED,!0),shaka.net.NetworkingEngine.registerScheme("blob",shaka.net.HttpFetchPlugin.parse,shaka.net.NetworkingEngine.PluginPriority.PREFERRED,!0));shaka.net.HttpXHRPlugin=class{static parse(a,b,c,d,e,f){const g=new shaka.net.HttpXHRPlugin.Xhr_;let h=Date.now(),k=0;const l=new Promise((m,n)=>{g.open(b.method,a,!0);g.responseType="arraybuffer";g.timeout=b.retryParameters.timeout;g.withCredentials=b.allowCrossSiteCredentials;let q={};g.onabort=()=>{n(new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.OPERATION_ABORTED,a,c))};g.onreadystatechange=p=>{g.readyState===XMLHttpRequest.HEADERS_RECEIVED&&
(q=shaka.net.HttpXHRPlugin.headersToGenericObject_(g),e(q))};g.onload=p=>{goog.asserts.assert(g.response instanceof ArrayBuffer,"XHR should have a response by now!");p=g.response;try{const r=shaka.net.HttpPluginUtils.makeResponse(q,p,g.status,a,g.responseURL,b,c);m(r)}catch(r){goog.asserts.assert(r instanceof shaka.util.Error,"Wrong error type!"),n(r)}};g.onerror=p=>{n(new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.HTTP_ERROR,a,p,
c))};g.ontimeout=p=>{n(new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.TIMEOUT,a,c))};g.onprogress=p=>{const r=Date.now(),t=f.minBytesForProgressEvents||0,u=p.loaded-k;if(r-h>100&&u>=t||p.lengthComputable&&p.loaded==p.total)d(r-h,u,g.readyState==4?0:p.total-p.loaded),k=p.loaded,h=r};for(const p in b.headers)try{const r=p.toLowerCase();g.setRequestHeader(r,b.headers[p])}catch(r){throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,
shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.HTTP_ERROR,a,r,c);}g.send(b.body)});return new shaka.util.AbortableOperation(l,()=>{g.abort();return Promise.resolve()})}static headersToGenericObject_(a){var b=a.getAllResponseHeaders().trim().split("\r\n");a={};for(const c of b)b=c.indexOf(": "),b!==-1&&(a[c.slice(0,b).toLowerCase()]=c.slice(b+2));return a}};goog.exportSymbol("shaka.net.HttpXHRPlugin",shaka.net.HttpXHRPlugin);goog.exportProperty(shaka.net.HttpXHRPlugin,"parse",shaka.net.HttpXHRPlugin.parse);
shaka.net.HttpXHRPlugin.Xhr_=window.XMLHttpRequest;shaka.net.NetworkingEngine.registerScheme("http",shaka.net.HttpXHRPlugin.parse,shaka.net.NetworkingEngine.PluginPriority.FALLBACK,!0);shaka.net.NetworkingEngine.registerScheme("https",shaka.net.HttpXHRPlugin.parse,shaka.net.NetworkingEngine.PluginPriority.FALLBACK,!0);shaka.net.NetworkingEngine.registerScheme("blob",shaka.net.HttpXHRPlugin.parse,shaka.net.NetworkingEngine.PluginPriority.FALLBACK,!0);shaka.offline={};
shaka.offline.DownloadInfo=class{constructor(a,b,c,d,e){this.ref=a;this.estimateId=b;this.groupId=c;this.isInitSegment=d;this.refPosition=e}static idForSegmentRef(a){const b=a.getSegmentData(!1);return b?shaka.util.Uint8ArrayUtils.toBase64(b):a.getUris().map(c=>"{"+encodeURI(c.split("#xywh=")[0])+"}").join("")+":"+a.startByte+":"+a.endByte}getRefId(){return shaka.offline.DownloadInfo.idForSegmentRef(this.ref)}makeSegmentRequest(a){return shaka.net.NetworkingUtils.createSegmentRequest(this.ref.getUris(),this.ref.startByte,
this.ref.endByte,a.streaming.retryParameters)}};shaka.offline.DownloadProgressEstimator=class{constructor(){this.actualDownloaded_=this.estimatedDownloaded_=this.estimatedTotal_=0;this.pending_=new Map;this.nextId_=0}open(a){this.estimatedTotal_+=a;const b=this.nextId_;this.nextId_++;this.pending_.set(b,a);return b}close(a,b){if(this.pending_.has(a)){var c=this.pending_.get(a);this.pending_.delete(a);this.estimatedDownloaded_+=c;this.actualDownloaded_+=b}}getEstimatedProgress(){return this.estimatedTotal_==0?0:this.estimatedDownloaded_/this.estimatedTotal_}getTotalDownloaded(){return this.actualDownloaded_}};shaka.offline.DownloadManager=class{constructor(a){this.networkingEngine_=a;this.groups_=new Map;this.destroyer_=new shaka.util.Destroyer(()=>this.abortAll().catch(()=>{}));this.abortCallbacks_=[];this.onProgress_=(b,c)=>{};this.onInitData_=(b,c)=>{};this.estimator_=new shaka.offline.DownloadProgressEstimator;this.aborted_=!1}destroy(){return this.destroyer_.destroy()}setCallbacks(a,b){this.onProgress_=a;this.onInitData_=b}abortAll(){this.aborted_=!0;const a=this.abortCallbacks_.map(b=>b());this.abortCallbacks_=
[];return Promise.all(a)}isAborted(){return this.aborted_}addDownloadEstimate(a){return this.estimator_.open(a)}queue(a,b,c,d,e){this.destroyer_.ensureNotDestroyed();const f=(this.groups_.get(a)||Promise.resolve()).then(async()=>{const g=await this.fetchSegment_(b);if(this.destroyer_.destroyed())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.OPERATION_ABORTED);if(d){var h=shaka.util.BufferUtils.toUint8(g);h=new shaka.util.Pssh(h);
for(const k in h.data){const l=Number(k);this.onInitData_(h.data[l],h.systemIds[l])}}this.estimator_.close(c,g.byteLength);this.onProgress_(this.estimator_.getEstimatedProgress(),this.estimator_.getTotalDownloaded());return e(g)});this.groups_.set(a,f);return f}queueData(a,b,c,d,e){this.destroyer_.ensureNotDestroyed();const f=(this.groups_.get(a)||Promise.resolve()).then(()=>{if(this.destroyer_.destroyed())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,
shaka.util.Error.Code.OPERATION_ABORTED);if(d){var g=shaka.util.BufferUtils.toUint8(b);g=new shaka.util.Pssh(g);for(const h in g.data){const k=Number(h);this.onInitData_(g.data[k],g.systemIds[k])}}this.estimator_.close(c,b.byteLength);this.onProgress_(this.estimator_.getEstimatedProgress(),this.estimator_.getTotalDownloaded());return e(b)});this.groups_.set(a,f);return f}queueWork(a,b){this.destroyer_.ensureNotDestroyed();const c=(this.groups_.get(a)||Promise.resolve()).then(async()=>{await b()});
this.groups_.set(a,c);return c}async waitToFinish(){await Promise.all(this.groups_.values());return this.estimator_.getTotalDownloaded()}async fetchSegment_(a){const b=this.networkingEngine_.request(shaka.net.NetworkingEngine.RequestType.SEGMENT,a);a=()=>b.abort();this.abortCallbacks_.push(a);const c=await b.promise;shaka.util.ArrayUtils.remove(this.abortCallbacks_,a);return c.data}};shaka.offline.indexeddb={};
shaka.offline.indexeddb.DBOperation=class{constructor(a,b){this.transaction_=a;this.store_=a.objectStore(b);this.promise_=new shaka.util.PublicPromise;a.onabort=c=>{c.preventDefault();this.promise_.reject()};a.onerror=c=>{c.preventDefault();this.promise_.reject()};a.oncomplete=c=>{this.promise_.resolve()}}async abort(){try{this.transaction_.abort()}catch(a){}try{await this.promise_}catch(a){}}forEachEntry(a){return new Promise((b,c)=>{const d=this.store_.openCursor();d.onerror=c;d.onsuccess=async e=>
{d.result==null?b():(e=d.result,await a(e.key,e.value,e),e.continue())}})}store(){return this.store_}promise(){return this.promise_}};shaka.offline.indexeddb.DBConnection=class{constructor(a){this.connection_=a;this.pending_=[]}destroy(){return Promise.all(this.pending_.map(a=>a.abort()))}startReadOnlyOperation(a){return this.startOperation_(a,"readonly")}startReadWriteOperation(a){return this.startOperation_(a,"readwrite")}startOperation_(a,b){b=this.connection_.transaction([a],b);const c=new shaka.offline.indexeddb.DBOperation(b,a);this.pending_.push(c);c.promise().then(()=>this.stopTracking_(c),()=>this.stopTracking_(c));return c}stopTracking_(a){shaka.util.ArrayUtils.remove(this.pending_,
a)}};shaka.offline.indexeddb.BaseStorageCell=class{constructor(a,b,c){this.connection_=new shaka.offline.indexeddb.DBConnection(a);this.segmentStore_=b;this.manifestStore_=c}destroy(){return this.connection_.destroy()}hasFixedKeySpace(){return!0}addSegments(a){return this.rejectAdd(this.segmentStore_)}removeSegments(a,b){return this.remove_(this.segmentStore_,a,b)}async getSegments(a){return(await this.get_(this.segmentStore_,a)).map(b=>this.convertSegmentData(b))}addManifests(a){return this.rejectAdd(this.manifestStore_)}updateManifest(a,
b){return this.rejectUpdate(this.manifestStore_)}updateManifestImplementation(a,b){const c=this.connection_.startReadWriteOperation(this.manifestStore_),d=c.store();d.get(a).onsuccess=e=>{d.put(b,a)};return c.promise()}updateManifestExpiration(a,b){const c=this.connection_.startReadWriteOperation(this.manifestStore_),d=c.store();d.get(a).onsuccess=e=>{if(e=e.target.result)e.expiration=b,d.put(e,a)};return c.promise()}removeManifests(a,b){return this.remove_(this.manifestStore_,a,b)}async getManifests(a){a=
await this.get_(this.manifestStore_,a);return Promise.all(a.map(b=>this.convertManifest(b)))}async getAllManifests(){const a=this.connection_.startReadOnlyOperation(this.manifestStore_),b=new Map;await a.forEachEntry(async(c,d)=>{d=await this.convertManifest(d);b.set(c,d)});await a.promise();return b}convertSegmentData(a){return a}convertManifest(a){return Promise.resolve(a)}rejectAdd(a){return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,
shaka.util.Error.Code.NEW_KEY_OPERATION_NOT_SUPPORTED,"Cannot add new value to "+a))}rejectUpdate(a){return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.MODIFY_OPERATION_NOT_SUPPORTED,"Cannot modify values in "+a))}async add(a,b){a=this.connection_.startReadWriteOperation(a);const c=a.store(),d=[];for(const e of b){const f=c.add(e);f.onsuccess=g=>{d.push(f.result)}}await a.promise();return d}remove_(a,b,c){a=this.connection_.startReadWriteOperation(a);
const d=a.store();for(const e of b)d.delete(e).onsuccess=()=>c(e);return a.promise()}async get_(a,b){a=this.connection_.startReadOnlyOperation(a);const c=a.store(),d={},e=[];for(const f of b){const g=c.get(f);g.onsuccess=()=>{g.result==void 0&&e.push(f);d[f]=g.result}}await a.promise();if(e.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.KEY_NOT_FOUND,"Could not find values for "+e);return b.map(f=>d[f])}};shaka.offline.indexeddb.EmeSessionStorageCell=class{constructor(a,b){this.connection_=new shaka.offline.indexeddb.DBConnection(a);this.store_=b}destroy(){return this.connection_.destroy()}async getAll(){const a=this.connection_.startReadOnlyOperation(this.store_),b=[];await a.forEachEntry((c,d)=>{b.push(d)});await a.promise();return b}add(a){const b=this.connection_.startReadWriteOperation(this.store_),c=b.store();for(const d of a)c.add(d);return b.promise()}async remove(a){const b=this.connection_.startReadWriteOperation(this.store_);
await b.forEachEntry((c,d,e)=>{a.includes(d.sessionId)&&e.delete()});await b.promise()}};shaka.offline.StorageCellHandle={};shaka.offline.StorageCellPath={};
shaka.offline.StorageMuxer=class{constructor(){this.mechanisms_=new Map}destroy(){const a=[];for(const b of this.mechanisms_.values())a.push(b.destroy());this.mechanisms_.clear();return Promise.all(a)}init(){shaka.offline.StorageMuxer.getRegistry_().forEach((b,c)=>{(b=b())?this.mechanisms_.set(c,b):shaka.log.info("Skipping "+c+" as it is not supported on this platform")});const a=[];for(const b of this.mechanisms_.values())a.push(b.init());return Promise.all(a)}getActive(){let a=null;this.mechanisms_.forEach((b,
c)=>{b.getCells().forEach((d,e)=>{d.hasFixedKeySpace()||a||(a={path:{mechanism:c,cell:e},cell:d})})});if(a)return a;throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.MISSING_STORAGE_CELL,"Could not find a cell that supports add-operations");}forEachCell(a){this.mechanisms_.forEach((b,c)=>{b.getCells().forEach((d,e)=>{a({mechanism:c,cell:e},d)})})}getCell(a,b){const c=this.mechanisms_.get(a);if(!c)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.MISSING_STORAGE_CELL,"Could not find mechanism with name "+a);a=c.getCells().get(b);if(!a)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.MISSING_STORAGE_CELL,"Could not find cell with name "+b);return a}forEachEmeSessionCell(a){this.mechanisms_.forEach((b,c)=>{a(b.getEmeSessionCell())})}getEmeSessionCell(){const a=Array.from(this.mechanisms_.keys());if(!a.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.STORAGE_NOT_SUPPORTED,"No supported storage mechanisms found");return this.mechanisms_.get(a[0]).getEmeSessionCell()}resolvePath(a){const b=this.mechanisms_.get(a.mechanism);return b?b.getCells().get(a.cell):null}async erase(){const a=Array.from(this.mechanisms_.values()),b=a.length>0;b||shaka.offline.StorageMuxer.getRegistry_().forEach((c,d)=>{(c=c())&&a.push(c)});await Promise.all(a.map(c=>c.erase()));b||await Promise.all(a.map(c=>c.destroy()))}static register(a,
b){shaka.offline.StorageMuxer.registry_.set(a,b)}static unregister(a){shaka.offline.StorageMuxer.registry_.delete(a)}static support(){var a=shaka.offline.StorageMuxer.getRegistry_();for(const b of a.values())if(a=b())return a.destroy(),!0;return!1}static overrideSupport(a){shaka.offline.StorageMuxer.override_=a}static clearOverride(){shaka.offline.StorageMuxer.override_=null}static getRegistry_(){const a=shaka.offline.StorageMuxer.override_,b=shaka.offline.StorageMuxer.registry_;return COMPILED?b:
a||b}};goog.exportSymbol("shaka.offline.StorageMuxer",shaka.offline.StorageMuxer);goog.exportProperty(shaka.offline.StorageMuxer,"unregister",shaka.offline.StorageMuxer.unregister);goog.exportProperty(shaka.offline.StorageMuxer,"register",shaka.offline.StorageMuxer.register);goog.exportProperty(shaka.offline.StorageMuxer.prototype,"destroy",shaka.offline.StorageMuxer.prototype.destroy);shaka.offline.StorageMuxer.override_=null;shaka.offline.StorageMuxer.registry_=new Map;shaka.offline.indexeddb.V1StorageCell=class extends shaka.offline.indexeddb.BaseStorageCell{async updateManifestExpiration(a,b){const c=this.connection_.startReadWriteOperation(this.manifestStore_),d=c.store(),e=new shaka.util.PublicPromise;d.get(a).onsuccess=f=>{(f=f.target.result)?(goog.asserts.assert(f.key==a,"With in-line keys, the keys should match"),f.expiration=b,d.put(f),e.resolve()):e.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.KEY_NOT_FOUND,
"Could not find values for "+a))};await Promise.all([c.promise(),e])}async convertManifest(a){var b=shaka.offline.indexeddb.V1StorageCell;const c=[];for(let d=0;d<a.periods.length;++d){const e=b.convertPeriod_(a.periods[d],(d==a.periods.length-1?a.duration:a.periods[d+1].startTime)-a.periods[d].startTime);c.push(e)}b=await shaka.util.PeriodCombiner.combineDbStreams(c);return{creationTime:0,originalManifestUri:a.originalManifestUri,duration:a.duration,size:a.size,expiration:a.expiration==null?Infinity:
a.expiration,streams:b,sessionIds:a.sessionIds,drmInfo:a.drmInfo,appMetadata:a.appMetadata,sequenceMode:!1}}static convertPeriod_(a,b){const c=shaka.offline.indexeddb.V1StorageCell;c.fillMissingVariants_(a);for(const d of a.streams)goog.asserts.assert(d.variantIds,"After filling in missing variants, each stream should have variant ids");return a.streams.map(d=>c.convertStream_(d,a.startTime,b))}static convertStream_(a,b,c){const d=shaka.offline.indexeddb.V1StorageCell,e=a.initSegmentUri?d.getKeyFromSegmentUri_(a.initSegmentUri):
null,f=b+a.presentationTimeOffset,g=b+c;return{id:a.id,originalId:null,groupId:null,primary:a.primary,type:a.contentType,mimeType:a.mimeType,codecs:a.codecs,frameRate:a.frameRate,pixelAspectRatio:void 0,hdr:void 0,colorGamut:void 0,videoLayout:void 0,kind:a.kind,language:a.language,originalLanguage:a.language||null,label:a.label,width:a.width,height:a.height,initSegmentKey:e,encrypted:a.encrypted,keyIds:new Set([a.keyId]),segments:a.segments.map(h=>d.convertSegment_(h,e,b,g,f)),variantIds:a.variantIds,
roles:[],forced:!1,audioSamplingRate:null,channelsCount:null,spatialAudio:!1,closedCaptions:null,tilesLayout:void 0,external:!1,fastSwitching:!1,isAudioMuxedInVideo:!1}}static convertSegment_(a,b,c,d,e){const f=shaka.offline.indexeddb.V1StorageCell.getKeyFromSegmentUri_(a.uri);return{startTime:c+a.startTime,endTime:c+a.endTime,dataKey:f,initSegmentKey:b,appendWindowStart:c,appendWindowEnd:d,timestampOffset:e,tilesLayout:"",mimeType:null,codecs:null,thumbnailSprite:null}}convertSegmentData(a){return{data:a.data}}static getKeyFromSegmentUri_(a){let b;
if((b=/^offline:[0-9]+\/[0-9]+\/([0-9]+)$/.exec(a))||(b=/^offline:segment\/([0-9]+)$/.exec(a)))return Number(b[1]);throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.MALFORMED_OFFLINE_URI,"Could not parse uri "+a);}static fillMissingVariants_(a){const b=shaka.util.ManifestParserUtils.ContentType.AUDIO,c=shaka.util.ManifestParserUtils.ContentType.VIDEO;var d=a.streams.filter(h=>h.contentType==b);a=a.streams.filter(h=>h.contentType==
c);if(!d.every(h=>h.variantIds)||!a.every(h=>h.variantIds)){goog.asserts.assert(d.every(h=>!h.variantIds),"Some audio streams have variant ids and some do not.");goog.asserts.assert(a.every(h=>!h.variantIds),"Some video streams have variant ids and some do not.");for(var e of d)e.variantIds=[];for(var f of a)f.variantIds=[];e=0;if(a.length&&!d.length){shaka.log.debug("Found video-only content. Creating variants for video.");f=e++;for(var g of a)g.variantIds.push(f)}if(!a.length&&d.length){shaka.log.debug("Found audio-only content. Creating variants for audio.");
g=e++;for(const h of d)h.variantIds.push(g)}if(a.length&&d.length){shaka.log.debug("Found audio-video content. Creating variants.");for(const h of d)for(const k of a)d=e++,h.variantIds.push(d),k.variantIds.push(d)}}}};shaka.offline.indexeddb.V2StorageCell=class extends shaka.offline.indexeddb.BaseStorageCell{async convertManifest(a){var b=[];for(let c=0;c<a.periods.length;++c){const d=this.convertPeriod_(a.periods[c],(c==a.periods.length-1?a.duration:a.periods[c+1].startTime)-a.periods[c].startTime);b.push(d)}b=await shaka.util.PeriodCombiner.combineDbStreams(b);return{appMetadata:a.appMetadata,creationTime:0,drmInfo:a.drmInfo,duration:a.duration,expiration:a.expiration==null?Infinity:a.expiration,originalManifestUri:a.originalManifestUri,
sessionIds:a.sessionIds,size:a.size,streams:b,sequenceMode:!1}}convertPeriod_(a,b){const c=[];for(const d of a.streams)d.variantIds.length!=0&&c.push(this.convertStream_(d,a.startTime,a.startTime+b));return c}convertStream_(a,b,c){return{id:a.id,originalId:a.originalId,groupId:null,primary:a.primary,type:a.contentType,mimeType:a.mimeType,codecs:a.codecs,frameRate:a.frameRate,pixelAspectRatio:a.pixelAspectRatio,hdr:void 0,colorGamut:void 0,videoLayout:void 0,kind:a.kind,language:a.language,originalLanguage:a.language||
null,label:a.label,width:a.width,height:a.height,encrypted:a.encrypted,keyIds:new Set([a.keyId]),segments:a.segments.map(d=>this.convertSegment_(d,a.initSegmentKey,b,c,a.presentationTimeOffset)),variantIds:a.variantIds,roles:[],forced:!1,audioSamplingRate:null,channelsCount:null,spatialAudio:!1,closedCaptions:null,tilesLayout:void 0,external:!1,fastSwitching:!1,isAudioMuxedInVideo:!1}}convertSegment_(a,b,c,d,e){return{startTime:c+a.startTime,endTime:c+a.endTime,initSegmentKey:b,appendWindowStart:c,
appendWindowEnd:d,timestampOffset:c-e,dataKey:a.dataKey,tilesLayout:"",mimeType:null,codecs:null,thumbnailSprite:null}}};shaka.offline.indexeddb.V5StorageCell=class extends shaka.offline.indexeddb.BaseStorageCell{hasFixedKeySpace(){return!1}addSegments(a){return this.add(this.segmentStore_,a)}addManifests(a){return this.add(this.manifestStore_,a)}updateManifest(a,b){return this.updateManifestImplementation(a,b)}convertManifest(a){a.expiration==null&&(a.expiration=Infinity);return Promise.resolve(a)}};shaka.offline.indexeddb.StorageMechanism=class{constructor(){this.sessions_=this.v5_=this.v3_=this.v2_=this.v1_=this.db_=null}init(){const a=shaka.offline.indexeddb.StorageMechanism.DB_NAME,b=shaka.offline.indexeddb.StorageMechanism.VERSION,c=new shaka.util.PublicPromise;let d=!1;const e=new shaka.util.Timer(()=>{d=!0;c.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.INDEXED_DB_INIT_TIMED_OUT))}),f=shaka.offline.indexeddb.StorageMechanismOpenTimeout;
typeof f==="number"&&f>0&&e.tickAfter(f);const g=window.indexedDB.open(a,b);g.onsuccess=h=>{d||(e.stop(),this.db_=h=g.result,this.v1_=shaka.offline.indexeddb.StorageMechanism.createV1_(h),this.v2_=shaka.offline.indexeddb.StorageMechanism.createV2_(h),this.v3_=shaka.offline.indexeddb.StorageMechanism.createV3_(h),this.v5_=shaka.offline.indexeddb.StorageMechanism.createV5_(h),this.sessions_=shaka.offline.indexeddb.StorageMechanism.createEmeSessionCell_(h),c.resolve())};g.onupgradeneeded=h=>{this.createStores_(g.result)};
g.onerror=h=>{d||(e.stop(),c.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.INDEXED_DB_ERROR,g.error)),h.preventDefault())};return c}async destroy(){this.v1_&&await this.v1_.destroy();this.v2_&&await this.v2_.destroy();this.v3_&&await this.v3_.destroy();this.v5_&&await this.v5_.destroy();this.sessions_&&await this.sessions_.destroy();this.db_&&this.db_.close()}getCells(){const a=new Map;this.v1_&&a.set("v1",this.v1_);this.v2_&&
a.set("v2",this.v2_);this.v3_&&a.set("v3",this.v3_);this.v5_&&a.set("v5",this.v5_);return a}getEmeSessionCell(){goog.asserts.assert(this.sessions_,"Cannot be destroyed.");return this.sessions_}async erase(){this.v1_&&await this.v1_.destroy();this.v2_&&await this.v2_.destroy();this.v3_&&await this.v3_.destroy();this.v5_&&await this.v5_.destroy();this.db_&&this.db_.close();await shaka.offline.indexeddb.StorageMechanism.deleteAll_();this.v5_=this.v3_=this.v2_=this.v1_=this.db_=null;await this.init()}static createV1_(a){var b=
shaka.offline.indexeddb.StorageMechanism;const c=b.V1_SEGMENT_STORE;b=b.V1_MANIFEST_STORE;const d=a.objectStoreNames;return d.contains(b)&&d.contains(c)?(shaka.log.debug("Mounting v1 idb storage cell"),new shaka.offline.indexeddb.V1StorageCell(a,c,b)):null}static createV2_(a){var b=shaka.offline.indexeddb.StorageMechanism;const c=b.V2_SEGMENT_STORE;b=b.V2_MANIFEST_STORE;const d=a.objectStoreNames;return d.contains(b)&&d.contains(c)?(shaka.log.debug("Mounting v2 idb storage cell"),new shaka.offline.indexeddb.V2StorageCell(a,
c,b)):null}static createV3_(a){var b=shaka.offline.indexeddb.StorageMechanism;const c=b.V3_SEGMENT_STORE;b=b.V3_MANIFEST_STORE;const d=a.objectStoreNames;return d.contains(b)&&d.contains(c)?(shaka.log.debug("Mounting v3 idb storage cell"),new shaka.offline.indexeddb.V2StorageCell(a,c,b)):null}static createV5_(a){var b=shaka.offline.indexeddb.StorageMechanism;const c=b.V5_SEGMENT_STORE;b=b.V5_MANIFEST_STORE;const d=a.objectStoreNames;return d.contains(b)&&d.contains(c)?(shaka.log.debug("Mounting v5 idb storage cell"),
new shaka.offline.indexeddb.V5StorageCell(a,c,b)):null}static createEmeSessionCell_(a){const b=shaka.offline.indexeddb.StorageMechanism.SESSION_ID_STORE;return a.objectStoreNames.contains(b)?(shaka.log.debug("Mounting session ID idb storage cell"),new shaka.offline.indexeddb.EmeSessionStorageCell(a,b)):null}createStores_(a){const b=[shaka.offline.indexeddb.StorageMechanism.V5_SEGMENT_STORE,shaka.offline.indexeddb.StorageMechanism.V5_MANIFEST_STORE,shaka.offline.indexeddb.StorageMechanism.SESSION_ID_STORE];
for(const c of b)a.objectStoreNames.contains(c)||a.createObjectStore(c,{autoIncrement:!0})}static deleteAll_(){const a=shaka.offline.indexeddb.StorageMechanism.DB_NAME,b=new shaka.util.PublicPromise,c=window.indexedDB.deleteDatabase(a);c.onblocked=d=>{shaka.log.warning("Deleting",a,"is being blocked",d)};c.onsuccess=d=>{b.resolve()};c.onerror=d=>{b.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.INDEXED_DB_ERROR,c.error));d.preventDefault()};
return b}};shaka.offline.indexeddb.StorageMechanism.DB_NAME="shaka_offline_db";shaka.offline.indexeddb.StorageMechanism.VERSION=5;shaka.offline.indexeddb.StorageMechanism.V1_SEGMENT_STORE="segment";shaka.offline.indexeddb.StorageMechanism.V2_SEGMENT_STORE="segment-v2";shaka.offline.indexeddb.StorageMechanism.V3_SEGMENT_STORE="segment-v3";shaka.offline.indexeddb.StorageMechanism.V5_SEGMENT_STORE="segment-v5";shaka.offline.indexeddb.StorageMechanism.V1_MANIFEST_STORE="manifest";
shaka.offline.indexeddb.StorageMechanism.V2_MANIFEST_STORE="manifest-v2";shaka.offline.indexeddb.StorageMechanism.V3_MANIFEST_STORE="manifest-v3";shaka.offline.indexeddb.StorageMechanism.V5_MANIFEST_STORE="manifest-v5";shaka.offline.indexeddb.StorageMechanism.SESSION_ID_STORE="session-ids";shaka.offline.indexeddb.StorageMechanismOpenTimeout=5;goog.exportSymbol("shaka.offline.indexeddb.StorageMechanismOpenTimeout",shaka.offline.indexeddb.StorageMechanismOpenTimeout);
shaka.offline.StorageMuxer.register("idb",()=>shaka.device.DeviceFactory.getDevice().supportsOfflineStorage()?new shaka.offline.indexeddb.StorageMechanism:null);shaka.offline.OfflineUri=class{constructor(a,b,c,d){this.type_=a;this.mechanism_=b;this.cell_=c;this.key_=d;this.asString_=["offline:",a,"/",b,"/",c,"/",d].join("")}isManifest(){return this.type_=="manifest"}isSegment(){return this.type_=="segment"}mechanism(){return this.mechanism_}cell(){return this.cell_}key(){return this.key_}toString(){return this.asString_}static parse(a){a=/^offline:([a-z]+)\/([^/]+)\/([^/]+)\/([0-9]+)$/.exec(a);if(a==null)return null;const b=a[1];if(b!="manifest"&&b!="segment")return null;
const c=a[2];if(!c)return null;const d=a[3];return d&&b!=null?new shaka.offline.OfflineUri(b,c,d,Number(a[4])):null}static manifest(a,b,c){return new shaka.offline.OfflineUri("manifest",a,b,c)}static segment(a,b,c){return new shaka.offline.OfflineUri("segment",a,b,c)}};shaka.offline.ManifestConverter=class{constructor(a,b){this.mechanism_=a;this.cell_=b}fromManifestDB(a){const b=new shaka.media.PresentationTimeline(null,0);b.setDuration(a.duration);var c=a.streams.filter(g=>this.isAudio_(g)),d=a.streams.filter(g=>this.isVideo_(g));c=this.createVariants(c,d,b);d=a.streams.filter(g=>this.isText_(g)).map(g=>this.fromStreamDB_(g,b));const e=a.streams.filter(g=>this.isImage_(g)).map(g=>this.fromStreamDB_(g,b)),f=a.drmInfo?[a.drmInfo]:[];if(a.drmInfo)for(const g of c.values())g.audio&&
g.audio.encrypted&&(g.audio.drmInfos=f),g.video&&g.video.encrypted&&(g.video.drmInfos=f);return{presentationTimeline:b,offlineSessionIds:a.sessionIds,variants:Array.from(c.values()),textStreams:d,imageStreams:e,sequenceMode:a.sequenceMode||!1,ignoreManifestTimestampsInSegmentsMode:!1,type:a.type||shaka.media.ManifestParser.UNKNOWN,serviceDescription:null,nextUrl:null,periodCount:1,gapCount:0,isLowLatency:!1,startTime:null}}createVariants(a,b,c){var d=new Set;for(var e of a)for(const g of e.variantIds)d.add(g);
for(const g of b)for(const h of g.variantIds)d.add(h);e=new Map;for(const g of d)e.set(g,this.createEmptyVariant_(g));for(var f of a){a=this.fromStreamDB_(f,c);for(const g of f.variantIds)d=e.get(g),goog.asserts.assert(!d.audio,"A variant should only have one audio stream"),d.language=a.language,d.primary=d.primary||a.primary,d.audio=a}for(const g of b){b=this.fromStreamDB_(g,c);for(const h of g.variantIds)f=e.get(h),goog.asserts.assert(!f.video,"A variant should only have one video stream"),f.primary=
f.primary||b.primary,f.video=b}return e}fromStreamDB_(a,b){const c=a.segments.map((d,e)=>this.fromSegmentDB_(e,d,a));b.notifySegments(c);b=new shaka.media.SegmentIndex(c);return{id:a.id,originalId:a.originalId,groupId:a.groupId,createSegmentIndex:()=>Promise.resolve(),segmentIndex:b,mimeType:a.mimeType,codecs:a.codecs,width:a.width||void 0,height:a.height||void 0,frameRate:a.frameRate,pixelAspectRatio:a.pixelAspectRatio,hdr:a.hdr,colorGamut:a.colorGamut,videoLayout:a.videoLayout,kind:a.kind,encrypted:a.encrypted,
drmInfos:[],keyIds:a.keyIds,language:a.language,originalLanguage:a.originalLanguage||null,label:a.label,type:a.type,primary:a.primary,trickModeVideo:null,dependencyStream:null,emsgSchemeIdUris:null,roles:a.roles,forced:a.forced,channelsCount:a.channelsCount,audioSamplingRate:a.audioSamplingRate,spatialAudio:a.spatialAudio,closedCaptions:a.closedCaptions,tilesLayout:a.tilesLayout,mssPrivateData:a.mssPrivateData,accessibilityPurpose:null,external:a.external,fastSwitching:a.fastSwitching,fullMimeTypes:new Set([shaka.util.MimeUtils.getFullType(a.mimeType,
a.codecs)]),isAudioMuxedInVideo:a.isAudioMuxedInVideo||!1,baseOriginalId:null}}fromSegmentDB_(a,b,c){const d=shaka.offline.OfflineUri.segment(this.mechanism_,this.cell_,b.dataKey);a=b.initSegmentKey!=null?this.fromInitSegmentDB_(b.initSegmentKey):null;a=new shaka.media.SegmentReference(b.startTime,b.endTime,()=>[d.toString()],0,null,a,b.timestampOffset,b.appendWindowStart,b.appendWindowEnd,[],b.tilesLayout||"");a.mimeType=b.mimeType||c.mimeType||"";a.codecs=b.codecs||c.codecs||"";b.thumbnailSprite&&
a.setThumbnailSprite(b.thumbnailSprite);return a}fromInitSegmentDB_(a){const b=shaka.offline.OfflineUri.segment(this.mechanism_,this.cell_,a);return new shaka.media.InitSegmentReference(()=>[b.toString()],0,null)}isAudio_(a){return a.type==shaka.util.ManifestParserUtils.ContentType.AUDIO}isVideo_(a){return a.type==shaka.util.ManifestParserUtils.ContentType.VIDEO}isText_(a){return a.type==shaka.util.ManifestParserUtils.ContentType.TEXT}isImage_(a){return a.type==shaka.util.ManifestParserUtils.ContentType.IMAGE}createEmptyVariant_(a){return{id:a,
language:"",disabledUntilTime:0,primary:!1,audio:null,video:null,bandwidth:0,allowedByApplication:!0,allowedByKeySystem:!0,decodingInfos:[]}}};shaka.offline.OfflineManifestParser=class{constructor(){this.uri_=null}configure(a){}async start(a,b){const c=shaka.offline.OfflineUri.parse(a);this.uri_=c;if(c==null||!c.isManifest())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.MALFORMED_OFFLINE_URI,a);a=new shaka.offline.StorageMuxer;try{await a.init();const d=(await (await a.getCell(c.mechanism(),c.cell())).getManifests([c.key()]))[0],e=(new shaka.offline.ManifestConverter(c.mechanism(),
c.cell())).fromManifestDB(d);b.makeTextStreamsForClosedCaptions(e);return e}finally{await a.destroy()}}stop(){return Promise.resolve()}update(){}async onExpirationUpdated(a,b){goog.asserts.assert(this.uri_,"Should not get update event before start has been called");const c=this.uri_,d=new shaka.offline.StorageMuxer;try{await d.init();const e=await d.getCell(c.mechanism(),c.cell()),f=(await e.getManifests([c.key()]))[0],g=f.sessionIds.includes(a),h=f.expiration==void 0||f.expiration>b;g&&h&&(shaka.log.debug("Updating expiration for stored content"),
await e.updateManifestExpiration(c.key(),b))}catch(e){shaka.log.error("There was an error updating",c,e)}finally{await d.destroy()}}onInitialVariantChosen(a){}banLocation(a){}setMediaElement(a){}};shaka.media.ManifestParser.registerParserByMime("application/x-offline-manifest",()=>new shaka.offline.OfflineManifestParser);shaka.offline.OfflineScheme=class{static plugin(a,b,c,d){return(c=shaka.offline.OfflineUri.parse(a))&&c.isManifest()?shaka.offline.OfflineScheme.getManifest_(a,b):c&&c.isSegment()?shaka.offline.OfflineScheme.getSegment_(c.key(),c,b):shaka.util.AbortableOperation.failed(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.MALFORMED_OFFLINE_URI,a))}static getManifest_(a,b){a={uri:a,originalUri:a,data:new ArrayBuffer(0),headers:{"content-type":"application/x-offline-manifest"},
originalRequest:b};return shaka.util.AbortableOperation.completed(a)}static getSegment_(a,b,c){goog.asserts.assert(b.isSegment(),"Only segment uri's should be given to getSegment");const d=new shaka.offline.StorageMuxer;return shaka.util.AbortableOperation.completed(void 0).chain(()=>d.init()).chain(()=>d.getCell(b.mechanism(),b.cell())).chain(e=>e.getSegments([b.key()])).chain(e=>({uri:b,data:e[0].data,headers:{},originalRequest:c})).finally(()=>d.destroy())}};
goog.exportSymbol("shaka.offline.OfflineScheme",shaka.offline.OfflineScheme);goog.exportProperty(shaka.offline.OfflineScheme,"plugin",shaka.offline.OfflineScheme.plugin);shaka.net.NetworkingEngine.registerScheme("offline",shaka.offline.OfflineScheme.plugin);shaka.offline.SessionDeleter=class{async delete(a,b,c){const d=shaka.offline.SessionDeleter;let e=[];for(const f of d.createBuckets_(c))c=await this.doDelete_(a,b,f),e=e.concat(c);return e}async doDelete_(a,b,c){const d=new shaka.drm.DrmEngine({netEngine:b,onError:()=>{},onKeyStatus:()=>{},onExpirationUpdated:()=>{},onEvent:()=>{}});try{d.configure(a),await d.initForRemoval(c.info.keySystem,c.info.licenseUri,c.info.serverCertificate,c.info.audioCapabilities,c.info.videoCapabilities)}catch(f){return shaka.log.warning("Error initializing EME",
f),await d.destroy(),[]}const e=[];await Promise.all(c.sessionIds.map(async f=>{try{await d.removeSession(f),e.push(f)}catch(g){shaka.log.warning("Error deleting offline session",g)}}));await d.destroy();return e}static createBuckets_(a){const b=shaka.offline.SessionDeleter,c=[];for(const d of a){a=!1;for(const e of c)if(b.isCompatible_(e.info,d)){e.sessionIds.push(d.sessionId);a=!0;break}a||c.push({info:d,sessionIds:[d.sessionId]})}return c}static isCompatible_(a,b){const c=shaka.util.ArrayUtils,
d=(e,f)=>e.robustness==f.robustness&&e.contentType==f.contentType;return a.keySystem==b.keySystem&&a.licenseUri==b.licenseUri&&c.hasSameElements(a.audioCapabilities,b.audioCapabilities,d)&&c.hasSameElements(a.videoCapabilities,b.videoCapabilities,d)}};shaka.offline.StoredContentUtils=class{static fromManifest(a,b,c,d){goog.asserts.assert(b.variants.length,"Cannot create stored content from manifest with no variants.");const e=b.presentationTimeline.getDuration();b=shaka.offline.StoredContentUtils.getTracks_(b);return{offlineUri:null,originalManifestUri:a,duration:e,size:c,expiration:Infinity,tracks:b,appMetadata:d,isIncomplete:!1}}static fromManifestDB(a,b){goog.asserts.assert(b.streams.length,"Cannot create stored content from manifestDB with no streams.");
var c=(new shaka.offline.ManifestConverter(a.mechanism(),a.cell())).fromManifestDB(b);const d=b.appMetadata||{};c=shaka.offline.StoredContentUtils.getTracks_(c);goog.asserts.assert(b.expiration!=null,"Manifest expiration must be set by now!");return{offlineUri:a.toString(),originalManifestUri:b.originalManifestUri,duration:b.duration,size:b.size,expiration:b.expiration,tracks:c,appMetadata:d,isIncomplete:b.isIncomplete||!1}}static getTracks_(a){const b=shaka.util.StreamUtils,c=[],d=b.getPlayableVariants(a.variants);
for(const e of d)c.push(b.variantToTrack(e));a=a.textStreams;for(const e of a)c.push(b.textStreamToTrack(e));return c}};shaka.offline.StreamBandwidthEstimator=class{constructor(){this.estimateByStreamId_=new Map}addVariant(a){const b=a.audio,c=a.video;b&&!c&&this.setBitrate_(b.id,b.bandwidth||a.bandwidth);!b&&c&&this.setBitrate_(c.id,c.bandwidth||a.bandwidth);if(b&&c){const d=b.bandwidth||shaka.offline.StreamBandwidthEstimator.DEFAULT_AUDIO_BITRATE_;let e=c.bandwidth||a.bandwidth-d;e<=0&&(shaka.log.warning("Audio bit rate consumes variants bandwidth. Setting video bandwidth to match variant's bandwidth."),e=a.bandwidth);
this.setBitrate_(b.id,d);this.setBitrate_(c.id,e)}}setBitrate_(a,b){this.estimateByStreamId_.set(a,b)}addText(a){this.estimateByStreamId_.set(a.id,shaka.offline.StreamBandwidthEstimator.DEFAULT_TEXT_BITRATE_)}addImage(a){this.estimateByStreamId_.set(a.id,a.bandwidth||shaka.offline.StreamBandwidthEstimator.DEFAULT_IMAGE_BITRATE_)}getSegmentEstimate(a,b){b=b.endTime-b.startTime;return this.getEstimate_(a)*b}getInitSegmentEstimate(a){return this.getEstimate_(a)*.5}getEstimate_(a){a=this.estimateByStreamId_.get(a);
a==null&&(a=0,shaka.log.error("Asking for bitrate of stream not given to the estimator"));a==0&&shaka.log.warning("Using bitrate of 0, this stream won't affect progress");return a}};shaka.offline.StreamBandwidthEstimator.DEFAULT_AUDIO_BITRATE_=393216;shaka.offline.StreamBandwidthEstimator.DEFAULT_TEXT_BITRATE_=52;shaka.offline.StreamBandwidthEstimator.DEFAULT_IMAGE_BITRATE_=2048;shaka.offline.Storage=class{constructor(a){if(a&&a.constructor!=shaka.Player)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.LOCAL_PLAYER_INSTANCE_REQUIRED);this.networkingEngine_=this.config_=null;a?(this.config_=a.getSharedConfiguration(),this.networkingEngine_=a.getNetworkingEngine(),goog.asserts.assert(this.networkingEngine_,"Storage should not be initialized with a player that had |destroy| called on it.")):(this.config_=shaka.util.PlayerConfiguration.createDefault(),
this.networkingEngine_=new shaka.net.NetworkingEngine,this.networkingEngine_.configure(this.config_.networking));this.openOperations_=[];this.openDownloadManagers_=[];const b=!a;this.destroyer_=new shaka.util.Destroyer(async()=>{await Promise.all(this.openDownloadManagers_.map(e=>e.abortAll()));const c=()=>{},d=[];for(const e of this.openOperations_)d.push(e.then(c,c));await Promise.all(d);b&&await this.networkingEngine_.destroy();this.networkingEngine_=this.config_=null});this.nextExternalStreamId_=
1E9}static support(){return shaka.device.DeviceFactory.getDevice().supportsMediaSource()?shaka.offline.StorageMuxer.support():!1}destroy(){return this.destroyer_.destroy()}configure(a,b){goog.asserts.assert(typeof a=="object"||arguments.length==2,"String configs should have values!");arguments.length==2&&typeof a=="string"&&(a=shaka.util.ConfigUtils.convertToConfigObject(a,b));goog.asserts.assert(typeof a=="object","Should be an object!");goog.asserts.assert(this.config_,"Cannot reconfigure storage after calling destroy.");
return shaka.util.PlayerConfiguration.mergeConfigObjects(this.config_,a)}getConfiguration(){goog.asserts.assert(this.config_,"Config must not be null!");const a=shaka.util.PlayerConfiguration.createDefault();shaka.util.PlayerConfiguration.mergeConfigObjects(a,this.config_,shaka.util.PlayerConfiguration.createDefault());return a}getNetworkingEngine(){return this.networkingEngine_}store(a,b,c,d,e){goog.asserts.assert(this.networkingEngine_,"Cannot call |store| after calling |destroy|.");const f=this.getConfiguration(),
g=new shaka.offline.DownloadManager(this.networkingEngine_);this.openDownloadManagers_.push(g);b=this.store_(a,b||{},d||[],e||[],async()=>{goog.asserts.assert(this.networkingEngine_,"Should not call |store| after |destroy|");c||=await shaka.net.NetworkingUtils.getMimeType(a,this.networkingEngine_,f.manifest.retryParameters);return shaka.media.ManifestParser.getFactory(a,c||null)()},f,g);b=new shaka.util.AbortableOperation(b,()=>g.abortAll());b.finally(()=>{shaka.util.ArrayUtils.remove(this.openDownloadManagers_,
g)});return this.startAbortableOperation_(b)}async store_(a,b,c,d,e,f,g){this.requireSupport_();let h=null,k=null;const l=new shaka.offline.StorageMuxer;let m=null,n=null,q=null;try{h=await e();const p=await this.parseManifest(a,h,f);this.ensureNotDestroyed_();if(p.presentationTimeline.isLive()||p.presentationTimeline.isInProgress())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.CANNOT_STORE_LIVE_OFFLINE,a);for(const A of c){const w=
await this.createExternalImageStream_(A,p);p.imageStreams.push(w);this.ensureNotDestroyed_()}for(const A of d){const w=await this.createExternalTextStream_(p,A.uri,A.language,A.kind,A.mime,A.codecs);p.textStreams.push(w);this.ensureNotDestroyed_()}shaka.drm.DrmEngine.configureClearKey(f.drm.clearKeys,p.variants);const r=p.variants.some(A=>{if(A.audio)for(const w of A.audio.drmInfos)if(w.licenseServerUri.startsWith("data:"))return!0;if(A.video)for(const w of A.video.drmInfos)if(w.licenseServerUri.startsWith("data:"))return!0;
return!1});let t=f.offline.usePersistentLicense;r&&(t=!1);k=await this.createDrmEngine(p,A=>{q=q||A},f,t);this.ensureNotDestroyed_();if(q)throw q;await this.filterManifest_(p,k,f,t);await l.init();this.ensureNotDestroyed_();m=await l.getActive();this.ensureNotDestroyed_();goog.asserts.assert(k,"drmEngine should be non-null here.");const {manifestDB:u,toDownload:v}=this.makeManifestDB_(k,p,a,b,f,g,t),x=await m.cell.addManifests([u]);this.ensureNotDestroyed_();n=x[0];goog.asserts.assert(k,"drmEngine should be non-null here.");
this.ensureNotDestroyed_();if(q)throw q;await this.downloadSegments_(v,n,u,g,f,m.cell,p,k,t);this.ensureNotDestroyed_();this.setManifestDrmFields_(p,u,k,t);await m.cell.updateManifest(n,u);this.ensureNotDestroyed_();const y=shaka.offline.OfflineUri.manifest(m.path.mechanism,m.path.cell,n);return shaka.offline.StoredContentUtils.fromManifestDB(y,u)}catch(p){throw n!=null&&await shaka.offline.Storage.cleanStoredManifest(n),q||p;}finally{await l.destroy(),h&&await h.stop(),k&&await k.destroy()}}async downloadSegments_(a,
b,c,d,e,f,g,h,k){let l={},m=0;const n=()=>{if(this.destroyer_.destroyed()||d.isAborted())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.OPERATION_ABORTED);};var q=async(p,r)=>{for(const t of p){n();p=t.makeSegmentRequest(e);const u=t.estimateId,v=t.isInitSegment,x=async A=>{var w=t.ref,z=w.getSegmentData(!1);w.aesKey&&!z&&(A=await shaka.media.SegmentUtils.aesDecrypt(A,w.aesKey,t.refPosition));w=shaka.offline.DownloadInfo.idForSegmentRef(w);
z=await f.addSegments([{data:A}]);n();l[w]=z[0];m+=A.byteLength},y=t.ref.getSegmentData(!1);y?d.queueData(t.groupId,y,u,v,x):d.queue(t.groupId,p,u,v,x)}await d.waitToFinish();n();r&&!d.isAborted()&&(this.setManifestDrmFields_(g,c,h,k),await f.updateManifest(b,c))};try{this.getManifestIsEncrypted_(g),await q(a,!1),n(),a=l,q=m,l={},m=0,await shaka.offline.Storage.assignSegmentsToManifest(f,b,c,a,q,()=>n()),n(),goog.asserts.assert(!c.isIncomplete,"The manifest should be complete by now")}catch(p){throw a=
Object.values(l),await f.removeSegments(a,r=>{}),p;}}static async cleanStoredManifest(a){const b=new shaka.offline.StorageMuxer;await b.init();const c=await b.getActive();a=shaka.offline.OfflineUri.manifest(c.path.mechanism,c.path.cell,a);await b.destroy();await (new shaka.offline.Storage).remove(a.toString())}static async assignSegmentsToManifest(a,b,c,d,e,f){let g=!1;try{let h=!0;for(const k of c.streams)for(const l of k.segments){let m=l.pendingSegmentRefId?d[l.pendingSegmentRefId]:null;m!=null&&
(l.dataKey=m,l.pendingSegmentRefId=void 0);m=l.pendingInitSegmentRefId?d[l.pendingInitSegmentRefId]:null;m!=null&&(l.initSegmentKey=m,l.pendingInitSegmentRefId=void 0);l.pendingSegmentRefId&&(h=!1);l.pendingInitSegmentRefId&&(h=!1)}c.size+=e;h&&(c.isIncomplete=!1);await a.updateManifest(b,c);g=!0;f()}catch(h){throw await shaka.offline.Storage.cleanStoredManifest(b),g||(b=Object.values(d),await a.removeSegments(b,k=>{})),h;}}async filterManifest_(a,b,c,d){shaka.util.StreamUtils.filterByRestrictions(a,
c.restrictions,{width:Infinity,height:Infinity});await shaka.util.StreamUtils.filterManifestByMediaCapabilities(b,a,d,c.drm.preferredKeySystems,c.drm.keySystemsMapping);b=[];shaka.util.StreamUtils.chooseCodecsAndFilterManifest(a,c.preferredVideoCodecs,c.preferredAudioCodecs,c.preferredDecodingAttributes,c.preferredTextFormats);for(var e of a.variants)goog.asserts.assert(shaka.util.StreamUtils.isPlayable(e),'We should have already filtered by "is playable"'),b.push(shaka.util.StreamUtils.variantToTrack(e));
for(var f of a.textStreams)b.push(shaka.util.StreamUtils.textStreamToTrack(f));for(var g of a.imageStreams)b.push(shaka.util.StreamUtils.imageStreamToTrack(g));e=await c.offline.trackSelectionCallback(b);f=a.presentationTimeline.getDuration();g=0;for(const m of e)g+=m.bandwidth*f/8;try{if(!await c.offline.downloadSizeCallback(g))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.STORAGE_LIMIT_REACHED);}catch(m){if(m instanceof shaka.util.Error)throw m;
shaka.log.warning("downloadSizeCallback has produced an unexpected error",m);throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.DOWNLOAD_SIZE_CALLBACK_ERROR);}const h=new Set,k=new Set,l=new Set;for(const m of e)m.type=="variant"&&h.add(m.id),m.type=="text"&&k.add(m.id),m.type=="image"&&l.add(m.id);a.variants=a.variants.filter(m=>h.has(m.id));a.textStreams=a.textStreams.filter(m=>k.has(m.id));a.imageStreams=a.imageStreams.filter(m=>
l.has(m.id));shaka.offline.Storage.validateManifest_(a)}makeManifestDB_(a,b,c,d,e,f,g){const h=shaka.offline.StoredContentUtils.fromManifest(c,b,0,d),k=e.offline.progressCallback;f.setCallbacks((r,t)=>{h.size=t;k(h,r)},(r,t)=>{l&&g&&m==t&&a.newInitData("cenc",r)});const l=this.getManifestIsEncrypted_(b)&&!this.getManifestIncludesInitData_(b);let m=null;if(l){var n=a.getDrmInfo();m=shaka.offline.Storage.defaultSystemIds_.get(n.keySystem)}n=new shaka.offline.StreamBandwidthEstimator;for(const r of b.textStreams)n.addText(r);
for(const r of b.imageStreams)n.addImage(r);for(const r of b.variants)n.addVariant(r);const {streams:q,toDownload:p}=this.createStreams_(f,n,a,b,e);(e=a.getDrmInfo())&&g&&(e.initData=[]);return{manifestDB:{creationTime:Date.now(),originalManifestUri:c,duration:b.presentationTimeline.getDuration(),size:0,expiration:a.getExpiration(),streams:q,sessionIds:g?a.getSessionIds():[],drmInfo:e,appMetadata:d,isIncomplete:!0,sequenceMode:b.sequenceMode,type:b.type},toDownload:p}}getManifestIsEncrypted_(a){return a.variants.some(b=>
{const c=b.audio&&b.audio.encrypted;return b.video&&b.video.encrypted||c})}getManifestIncludesInitData_(a){return a.variants.some(b=>(b.video?b.video.drmInfos:[]).concat(b.audio?b.audio.drmInfos:[]).some(c=>c.initData&&c.initData.length))}setManifestDrmFields_(a,b,c,d){b.expiration=c.getExpiration();c=c.getSessionIds();b.sessionIds=d?c:[];if(this.getManifestIsEncrypted_(a)&&d&&!c.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.NO_INIT_DATA_FOR_OFFLINE);
}remove(a){return this.startOperation_(this.remove_(a))}async remove_(a){this.requireSupport_();const b=shaka.offline.OfflineUri.parse(a);if(b==null||!b.isManifest())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.MALFORMED_OFFLINE_URI,a);a=new shaka.offline.StorageMuxer;try{await a.init();const c=await a.getCell(b.mechanism(),b.cell()),d=(await c.getManifests([b.key()]))[0];await Promise.all([this.removeFromDRM_(b,d,a),this.removeFromStorage_(c,
b,d)])}finally{await a.destroy()}}static getCapabilities_(a,b){const c=shaka.util.MimeUtils,d=[];for(const e of a.streams)b&&e.type=="video"?d.push({contentType:c.getFullType(e.mimeType,e.codecs),robustness:a.drmInfo.videoRobustness}):b||e.type!="audio"||d.push({contentType:c.getFullType(e.mimeType,e.codecs),robustness:a.drmInfo.audioRobustness});return d}async removeFromDRM_(a,b,c){goog.asserts.assert(this.networkingEngine_,"Cannot be destroyed");await shaka.offline.Storage.deleteLicenseFor_(this.networkingEngine_,
this.config_.drm,c,b)}removeFromStorage_(a,b,c){const d=shaka.offline.Storage.getAllSegmentIds_(c),e=d.length+1;let f=0;const g=shaka.offline.StoredContentUtils.fromManifestDB(b,c);c=h=>{f+=1;this.config_.offline.progressCallback(g,f/e)};return Promise.all([a.removeSegments(d,c),a.removeManifests([b.key()],c)])}removeEmeSessions(){return this.startOperation_(this.removeEmeSessions_())}async removeEmeSessions_(){this.requireSupport_();goog.asserts.assert(this.networkingEngine_,"Cannot be destroyed");
const a=this.networkingEngine_,b=this.config_.drm,c=new shaka.offline.StorageMuxer,d=new shaka.offline.SessionDeleter;let e=!1;try{await c.init();const f=[];c.forEachEmeSessionCell(g=>f.push(g));for(const g of f){const h=await g.getAll(),k=await d.delete(b,a,h);await g.remove(k);k.length!=h.length&&(e=!0)}}finally{await c.destroy()}return!e}list(){return this.startOperation_(this.list_())}async list_(){this.requireSupport_();const a=[],b=new shaka.offline.StorageMuxer;try{await b.init();let c=Promise.resolve();
b.forEachCell((d,e)=>{c=c.then(async()=>{(await e.getAllManifests()).forEach((f,g)=>{g=shaka.offline.OfflineUri.manifest(d.mechanism,d.cell,g);f=shaka.offline.StoredContentUtils.fromManifestDB(g,f);a.push(f)})})});await c}finally{await b.destroy()}return a}async parseManifest(a,b,c){let d=null;var e=this.networkingEngine_;goog.asserts.assert(e,"Should be initialized!");e={networkingEngine:e,filter:()=>Promise.resolve(),makeTextStreamsForClosedCaptions:f=>{},onTimelineRegionAdded:()=>{},onEvent:()=>
{},onError:f=>{d=f},isLowLatencyMode:()=>!1,updateDuration:()=>{},newDrmInfo:f=>{},onManifestUpdated:()=>{},getBandwidthEstimate:()=>c.abr.defaultBandwidthEstimate,onMetadata:()=>{},disableStream:f=>{},addFont:(f,g)=>{}};b.configure(c.manifest);this.ensureNotDestroyed_();a=await b.start(a,e);this.ensureNotDestroyed_();b=shaka.offline.Storage.getAllStreamsFromManifest_(a);await Promise.all(shaka.util.Iterables.map(b,f=>f.createSegmentIndex()));this.ensureNotDestroyed_();if(d)throw d;return a}async createExternalImageStream_(a,
b){var c=await this.getTextMimetype_(a);if(c!="text/vtt")throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.UNSUPPORTED_EXTERNAL_THUMBNAILS_URI,a);goog.asserts.assert(this.networkingEngine_,"Need networking engine.");var d=await this.getTextData_(a,this.networkingEngine_,this.config_.streaming.retryParameters),e=shaka.text.TextEngine.findParser(c);if(!e)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,
shaka.util.Error.Code.MISSING_TEXT_PLUGIN,c);e=e();b={periodStart:0,segmentStart:0,segmentEnd:b.presentationTimeline.getDuration(),vttOffset:0};d=shaka.util.BufferUtils.toUint8(d);e=e.parseMedia(d,b,a,[]);d=[];for(const f of e){let g=null;e=new shaka.media.SegmentReference(f.startTime,f.endTime,()=>{g==null&&(g=shaka.util.ManifestParserUtils.resolveUris([a],[f.payload]));return g||[]},0,null,null,0,0,Infinity);f.payload.includes("#xywh")&&(b=f.payload.split("#xywh=")[1].split(","),b.length===4&&e.setThumbnailSprite({height:parseInt(b[3],
10),positionX:parseInt(b[0],10),positionY:parseInt(b[1],10),width:parseInt(b[2],10)}));d.push(e)}d.length&&(c=await shaka.net.NetworkingUtils.getMimeType(d[0].getUris()[0],this.networkingEngine_,this.config_.manifest.retryParameters));return{id:this.nextExternalStreamId_++,originalId:null,groupId:null,createSegmentIndex:()=>Promise.resolve(),segmentIndex:new shaka.media.SegmentIndex(d),mimeType:c||"",codecs:"",kind:"",encrypted:!1,drmInfos:[],keyIds:new Set,language:"und",originalLanguage:null,label:null,
type:shaka.util.ManifestParserUtils.ContentType.IMAGE,primary:!1,trickModeVideo:null,dependencyStream:null,emsgSchemeIdUris:null,roles:[],forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null,tilesLayout:"1x1",accessibilityPurpose:null,external:!0,fastSwitching:!1,fullMimeTypes:new Set([shaka.util.MimeUtils.getFullType(c||"","")]),isAudioMuxedInVideo:!1,baseOriginalId:null}}async createExternalTextStream_(a,b,c,d,e,f){e||=await this.getTextMimetype_(b);a={id:this.nextExternalStreamId_++,
originalId:null,groupId:null,createSegmentIndex:()=>Promise.resolve(),segmentIndex:shaka.media.SegmentIndex.forSingleSegment(0,a.presentationTimeline.getDuration(),[b]),mimeType:e||"",codecs:f||"",kind:d,encrypted:!1,drmInfos:[],keyIds:new Set,language:c,originalLanguage:c,label:null,type:shaka.util.ManifestParserUtils.ContentType.TEXT,primary:!1,trickModeVideo:null,dependencyStream:null,emsgSchemeIdUris:null,roles:[],forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null,
accessibilityPurpose:null,external:!0,fastSwitching:!1,fullMimeTypes:new Set([shaka.util.MimeUtils.getFullType(e||"",f||"")]),isAudioMuxedInVideo:!1,baseOriginalId:null};b=shaka.util.MimeUtils.getFullType(a.mimeType,a.codecs);if(!shaka.text.TextEngine.isTypeSupported(b))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.MISSING_TEXT_PLUGIN,e);return a}async getTextMimetype_(a){let b;try{goog.asserts.assert(this.networkingEngine_,"Need networking engine."),
b=await shaka.net.NetworkingUtils.getMimeType(a,this.networkingEngine_,this.config_.streaming.retryParameters)}catch(c){}if(b)return b;shaka.log.error("The mimeType has not been provided and it could not be deduced from its uri.");throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.TEXT_COULD_NOT_GUESS_MIME_TYPE,a);}async getTextData_(a,b,c){const d=shaka.net.NetworkingEngine.RequestType.SEGMENT;a=shaka.net.NetworkingEngine.makeRequest([a],
c);a.method="GET";return(await b.request(d,a).promise).data}async createDrmEngine(a,b,c,d){goog.asserts.assert(this.networkingEngine_,"Cannot call |createDrmEngine| after |destroy|");b=new shaka.drm.DrmEngine({netEngine:this.networkingEngine_,onError:b,onKeyStatus:()=>{},onExpirationUpdated:()=>{},onEvent:()=>{}});b.configure(c.drm);await b.initForStorage(a.variants,d);d&&await b.createOrLoad();return b}createStreams_(a,b,c,d,e){c=new Map;var f=shaka.offline.Storage.getAllStreamsFromManifest_(d);
const g=new Map;for(const h of f)f=this.createStream_(a,b,d,h,e,c),g.set(h.id,f);for(const h of d.variants)h.audio&&g.get(h.audio.id).variantIds.push(h.id),h.video&&g.get(h.video.id).variantIds.push(h.id);return{streams:Array.from(g.values()),toDownload:Array.from(c.values())}}createStream_(a,b,c,d,e,f){const g={id:d.id,originalId:d.originalId,groupId:d.groupId,primary:d.primary,type:d.type,mimeType:d.mimeType,codecs:d.codecs,frameRate:d.frameRate,pixelAspectRatio:d.pixelAspectRatio,hdr:d.hdr,colorGamut:d.colorGamut,
videoLayout:d.videoLayout,kind:d.kind,language:d.language,originalLanguage:d.originalLanguage,label:d.label,width:d.width||null,height:d.height||null,encrypted:d.encrypted,keyIds:d.keyIds,segments:[],variantIds:[],roles:d.roles,forced:d.forced,channelsCount:d.channelsCount,audioSamplingRate:d.audioSamplingRate,spatialAudio:d.spatialAudio,closedCaptions:d.closedCaptions,tilesLayout:d.tilesLayout,mssPrivateData:d.mssPrivateData,external:d.external,fastSwitching:d.fastSwitching,isAudioMuxedInVideo:d.isAudioMuxedInVideo};
c=c.presentationTimeline.getSegmentAvailabilityStart();const h=e.offline.numberOfParallelDownloads;let k=h===0?d.id:0;shaka.offline.Storage.forEachSegment_(d,c,(l,m)=>{const n=shaka.offline.DownloadInfo.idForSegmentRef(l);let q=void 0;if(!f.has(n)){var p=a.addDownloadEstimate(b.getSegmentEstimate(d.id,l));p=new shaka.offline.DownloadInfo(l,p,k,!1,m);f.set(n,p)}l.initSegmentReference&&(q=shaka.offline.DownloadInfo.idForSegmentRef(l.initSegmentReference),f.has(q)||(p=a.addDownloadEstimate(b.getInitSegmentEstimate(d.id)),
m=new shaka.offline.DownloadInfo(l.initSegmentReference,p,k,!0,m),f.set(q,m)));g.segments.push({pendingInitSegmentRefId:q,initSegmentKey:q?0:null,startTime:l.startTime,endTime:l.endTime,appendWindowStart:l.appendWindowStart,appendWindowEnd:l.appendWindowEnd,timestampOffset:l.timestampOffset,tilesLayout:l.tilesLayout,pendingSegmentRefId:n,dataKey:0,mimeType:l.mimeType,codecs:l.codecs,thumbnailSprite:l.thumbnailSprite});h!==0&&(k=(k+1)%h)});return g}static forEachSegment_(a,b,c){b=a.segmentIndex.find(b);
if(b!=null)for(var d=a.segmentIndex.get(b);d;)c(d,b),d=a.segmentIndex.get(++b)}ensureNotDestroyed_(){if(this.destroyer_.destroyed())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.OPERATION_ABORTED);}requireSupport_(){if(!shaka.offline.Storage.support())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.STORAGE_NOT_SUPPORTED);}async startOperation_(a){this.openOperations_.push(a);
try{return await a}finally{shaka.util.ArrayUtils.remove(this.openOperations_,a)}}startAbortableOperation_(a){const b=a.promise;this.openOperations_.push(b);return a.finally(()=>{shaka.util.ArrayUtils.remove(this.openOperations_,b)})}static getAllSegmentIds_(a){const b=new Set;for(const c of a.streams)for(const d of c.segments)d.initSegmentKey!=null&&b.add(d.initSegmentKey),b.add(d.dataKey);return Array.from(b)}static async deleteAll(){const a=new shaka.offline.StorageMuxer;try{await a.erase()}finally{await a.destroy()}}static async deleteLicenseFor_(a,
b,c,d){if(d.drmInfo){c=c.getEmeSessionCell();var e=d.sessionIds.map(g=>({sessionId:g,keySystem:d.drmInfo.keySystem,licenseUri:d.drmInfo.licenseServerUri,serverCertificate:d.drmInfo.serverCertificate,audioCapabilities:shaka.offline.Storage.getCapabilities_(d,!1),videoCapabilities:shaka.offline.Storage.getCapabilities_(d,!0)})),f=await (new shaka.offline.SessionDeleter).delete(b,a,e);await c.remove(f);await c.add(e.filter(g=>!f.includes(g.sessionId)))}}static getAllStreamsFromManifest_(a){const b=new Set;
for(const c of a.variants)c.audio&&b.add(c.audio),c.video&&b.add(c.video);for(const c of a.textStreams)b.add(c);for(const c of a.imageStreams)b.add(c);return b}static validateManifest_(a){const b=new Set(a.variants.map(d=>d.video)),c=new Set(a.variants.map(d=>d.audio));a=a.textStreams;b.size>1&&shaka.log.warning("Multiple video tracks selected to be stored");for(const d of c)for(const e of c)d!=e&&d.language==e.language&&shaka.log.warning("Similar audio tracks were selected to be stored",d.id,e.id);
for(const d of a)for(const e of a)d!=e&&d.language==e.language&&shaka.log.warning("Similar text tracks were selected to be stored",d.id,e.id)}};goog.exportSymbol("shaka.offline.Storage",shaka.offline.Storage);goog.exportProperty(shaka.offline.Storage,"deleteAll",shaka.offline.Storage.deleteAll);goog.exportProperty(shaka.offline.Storage.prototype,"list",shaka.offline.Storage.prototype.list);goog.exportProperty(shaka.offline.Storage.prototype,"removeEmeSessions",shaka.offline.Storage.prototype.removeEmeSessions);
goog.exportProperty(shaka.offline.Storage.prototype,"remove",shaka.offline.Storage.prototype.remove);goog.exportProperty(shaka.offline.Storage.prototype,"store",shaka.offline.Storage.prototype.store);goog.exportProperty(shaka.offline.Storage.prototype,"getNetworkingEngine",shaka.offline.Storage.prototype.getNetworkingEngine);goog.exportProperty(shaka.offline.Storage.prototype,"getConfiguration",shaka.offline.Storage.prototype.getConfiguration);
goog.exportProperty(shaka.offline.Storage.prototype,"configure",shaka.offline.Storage.prototype.configure);goog.exportProperty(shaka.offline.Storage.prototype,"destroy",shaka.offline.Storage.prototype.destroy);goog.exportProperty(shaka.offline.Storage,"support",shaka.offline.Storage.support);
shaka.offline.Storage.defaultSystemIds_=(new Map).set("org.w3.clearkey","1077efecc0b24d02ace33c1e52e2fb4b").set("com.widevine.alpha","edef8ba979d64acea3c827dcd51d21ed").set("com.microsoft.playready","9a04f07998404286ab92e65be0885f95").set("com.microsoft.playready.recommendation","9a04f07998404286ab92e65be0885f95").set("com.microsoft.playready.software","9a04f07998404286ab92e65be0885f95").set("com.microsoft.playready.hardware","9a04f07998404286ab92e65be0885f95").set("com.huawei.wiseplay","3d5e6d359b9a41e8b843dd3c6e72c42c");
shaka.Player.registerSupportPlugin("offline",shaka.offline.Storage.support);shaka.polyfill=class{static installAll(){for(const a of shaka.polyfill.polyfills_)try{a.callback()}catch(b){shaka.log.alwaysWarn("Error installing polyfill!",b)}}static register(a,b){a={priority:b||0,callback:a};for(b=0;b<shaka.polyfill.polyfills_.length;b++)if(shaka.polyfill.polyfills_[b].priority<a.priority){shaka.polyfill.polyfills_.splice(b,0,a);return}shaka.polyfill.polyfills_.push(a)}};goog.exportSymbol("shaka.polyfill",shaka.polyfill);goog.exportProperty(shaka.polyfill,"register",shaka.polyfill.register);
goog.exportProperty(shaka.polyfill,"installAll",shaka.polyfill.installAll);shaka.polyfill.polyfills_=[];shaka.polyfill.EmeEncryptionSchemePolyfillMediaKeySystemAccess=class{constructor(a,b,c){this.mksa_=a;this.videoScheme_=b||null;this.audioScheme_=c||null;this.keySystem=a.keySystem}getConfiguration(){const a=this.mksa_.getConfiguration();if(a.videoCapabilities)for(const b of a.videoCapabilities)b.encryptionScheme=this.videoScheme_;if(a.audioCapabilities)for(const b of a.audioCapabilities)b.encryptionScheme=this.audioScheme_;return a}createMediaKeys(){return this.mksa_.createMediaKeys()}};shaka.polyfill.EncryptionSchemeUtils=class{static guessSupportedScheme(a){const b=shaka.drm.DrmUtils;if(b.isFairPlayKeySystem(a))return"cbcs";if(b.isWidevineKeySystem(a)||b.isPlayReadyKeySystem(a)||b.isClearKeySystem(a)||b.isWisePlayKeySystem(a))return"cenc";shaka.log.alwaysWarn("EmeEncryptionSchemePolyfill: Unknown key system:",a,"Please contribute!");return null}static hasEncryptionScheme(a){if(!a)return!1;a=a.getConfiguration();const b=a.audioCapabilities&&a.audioCapabilities[0];return(a=a.videoCapabilities&&
a.videoCapabilities[0]||b)&&a.encryptionScheme!==void 0?!0:!1}static checkSupportedScheme(a,b){return!a||a==b||(a=="cbcs"||a=="cbcs-1-9")&&shaka.device.DeviceFactory.getDevice().supportsCbcsWithoutEncryptionSchemeSupport()?!0:!1}};shaka.polyfill.EmeEncryptionScheme=class{static install(){shaka.device.DeviceFactory.getDevice().supportsEncryptionSchemePolyfill()&&(shaka.polyfill.EmeEncryptionScheme.originalRMKSA_||navigator.emeEncryptionSchemePolyfilled?shaka.log.debug("EmeEncryptionSchemePolyfill:","Already installed."):navigator.requestMediaKeySystemAccess&&MediaKeySystemAccess.prototype.getConfiguration?(shaka.polyfill.EmeEncryptionScheme.originalRMKSA_=navigator.requestMediaKeySystemAccess,shaka.log.debug("EmeEncryptionSchemePolyfill:",
"Waiting to detect encryptionScheme support."),navigator.requestMediaKeySystemAccess=shaka.polyfill.EmeEncryptionScheme.probeRMKSA_,navigator.emeEncryptionSchemePolyfilled=!0):shaka.log.debug("EmeEncryptionSchemePolyfill:","EME not found"))}static async probeRMKSA_(a,b){goog.asserts.assert(this==navigator,'bad "this" for requestMediaKeySystemAccess');const c=await shaka.polyfill.EmeEncryptionScheme.originalRMKSA_.call(this,a,b);if(shaka.polyfill.EncryptionSchemeUtils.hasEncryptionScheme(c))return shaka.log.debug("EmeEncryptionSchemePolyfill:",
"Native encryptionScheme support found."),navigator.requestMediaKeySystemAccess=shaka.polyfill.EmeEncryptionScheme.originalRMKSA_,c;shaka.log.debug("EmeEncryptionSchemePolyfill:","No native encryptionScheme support found. Patching encryptionScheme support.");navigator.requestMediaKeySystemAccess=shaka.polyfill.EmeEncryptionScheme.polyfillRMKSA_;return shaka.polyfill.EmeEncryptionScheme.polyfillRMKSA_.call(this,a,b)}static async polyfillRMKSA_(a,b){goog.asserts.assert(this==navigator,'bad "this" for requestMediaKeySystemAccess');
var c=shaka.polyfill.EncryptionSchemeUtils.guessSupportedScheme(a),d=[];for(var e of b){b=shaka.polyfill.EmeEncryptionScheme.filterCapabilities_(e.videoCapabilities,c);const f=shaka.polyfill.EmeEncryptionScheme.filterCapabilities_(e.audioCapabilities,c);if(!e.videoCapabilities||!e.videoCapabilities.length||b.length)if(!e.audioCapabilities||!e.audioCapabilities.length||f.length){const g=Object.assign({},e);g.videoCapabilities=b;g.audioCapabilities=f;d.push(g)}}if(!d.length)throw d=Error("Unsupported keySystem or supportedConfigurations."),
d.name="NotSupportedError",d.code=DOMException.NOT_SUPPORTED_ERR,d;a=await shaka.polyfill.EmeEncryptionScheme.originalRMKSA_.call(this,a,d);e=c=null;d[0]&&(d[0].videoCapabilities&&(c=d[0].videoCapabilities[0].encryptionScheme),d[0].audioCapabilities&&(e=d[0].audioCapabilities[0].encryptionScheme));return new shaka.polyfill.EmeEncryptionSchemePolyfillMediaKeySystemAccess(a,c,e)}static filterCapabilities_(a,b){return a?a.filter(c=>shaka.polyfill.EncryptionSchemeUtils.checkSupportedScheme(c.encryptionScheme,
b)):a}};goog.exportProperty(shaka.polyfill,"EmeEncryptionScheme",shaka.polyfill.EmeEncryptionScheme);goog.exportProperty(shaka.polyfill.EmeEncryptionScheme,"install",shaka.polyfill.EmeEncryptionScheme.install);shaka.polyfill.register(shaka.polyfill.EmeEncryptionScheme.install);shaka.polyfill.MCapEncryptionScheme=class{static install(){shaka.device.DeviceFactory.getDevice().supportsEncryptionSchemePolyfill()&&(shaka.polyfill.MCapEncryptionScheme.originalDecodingInfo_||navigator.mediaCapabilitiesEncryptionSchemePolyfilled?shaka.log.debug("McEncryptionSchemePolyfill:","Already installed."):navigator.mediaCapabilities?(shaka.polyfill.MCapEncryptionScheme.originalDecodingInfo_=navigator.mediaCapabilities.decodingInfo,shaka.log.debug("McEncryptionSchemePolyfill:","Waiting to detect encryptionScheme support."),
navigator.mediaCapabilities.decodingInfo=shaka.polyfill.MCapEncryptionScheme.probeDecodingInfo_,navigator.mediaCapabilitiesEncryptionSchemePolyfilled=!0):shaka.log.debug("McEncryptionSchemePolyfill:","MediaCapabilities not found"))}static async probeDecodingInfo_(a){goog.asserts.assert(this==navigator.mediaCapabilities,'bad "this" for decodingInfo');const b=await shaka.polyfill.MCapEncryptionScheme.originalDecodingInfo_.call(this,a);if(!b.supported||!a.keySystemConfiguration)return b;const c=b.keySystemAccess;
if(shaka.polyfill.EncryptionSchemeUtils.hasEncryptionScheme(c))return shaka.log.debug("McEncryptionSchemePolyfill:","Native encryptionScheme support found."),navigator.mediaCapabilities.decodingInfo=shaka.polyfill.MCapEncryptionScheme.originalDecodingInfo_,b;shaka.log.debug("McEncryptionSchemePolyfill:","No native encryptionScheme support found. Patching encryptionScheme support.");navigator.mediaCapabilities.decodingInfo=shaka.polyfill.MCapEncryptionScheme.polyfillDecodingInfo_;return c?shaka.polyfill.MCapEncryptionScheme.polyfillDecodingInfo_.call(this,
a):(b.keySystemAccess=await shaka.polyfill.MCapEncryptionScheme.getMediaKeySystemAccess_(a),b)}static async polyfillDecodingInfo_(a){goog.asserts.assert(this==navigator.mediaCapabilities,'bad "this" for decodingInfo');var b=null;let c=null;if(a.keySystemConfiguration){b=a.keySystemConfiguration;var d=b.keySystem;c=b.audio&&b.audio.encryptionScheme;b=b.video&&b.video.encryptionScheme;d=shaka.polyfill.EncryptionSchemeUtils.guessSupportedScheme(d);const e={powerEfficient:!1,smooth:!1,supported:!1,keySystemAccess:null,
configuration:a};if(!shaka.polyfill.EncryptionSchemeUtils.checkSupportedScheme(c,d)||!shaka.polyfill.EncryptionSchemeUtils.checkSupportedScheme(b,d))return e}d=await shaka.polyfill.MCapEncryptionScheme.originalDecodingInfo_.call(this,a);d.keySystemAccess?d.keySystemAccess=new shaka.polyfill.EmeEncryptionSchemePolyfillMediaKeySystemAccess(d.keySystemAccess,b,c):a.keySystemConfiguration&&(d.keySystemAccess=await shaka.polyfill.MCapEncryptionScheme.getMediaKeySystemAccess_(a));return d}static async getMediaKeySystemAccess_(a){const b=
shaka.polyfill.MCapEncryptionScheme.convertToMediaKeySystemConfig_(a);return await navigator.requestMediaKeySystemAccess(a.keySystemConfiguration.keySystem,[b])}static convertToMediaKeySystemConfig_(a){const b=a.keySystemConfiguration,c=[],d=[];b.audio&&c.push({robustness:b.audio.robustness||"",contentType:a.audio.contentType,encryptionScheme:b.audio.encryptionScheme});b.video&&d.push({robustness:b.video.robustness||"",contentType:a.video.contentType,encryptionScheme:b.video.encryptionScheme});a=
{initDataTypes:b.initDataType?[b.initDataType]:[],distinctiveIdentifier:b.distinctiveIdentifier,persistentState:b.persistentState,sessionTypes:b.sessionTypes};c.length&&(a.audioCapabilities=c);d.length&&(a.videoCapabilities=d);return a}};goog.exportProperty(shaka.polyfill,"MCapEncryptionScheme",shaka.polyfill.MCapEncryptionScheme);goog.exportProperty(shaka.polyfill.MCapEncryptionScheme,"install",shaka.polyfill.MCapEncryptionScheme.install);
shaka.polyfill.register(shaka.polyfill.MCapEncryptionScheme.install,-2);shaka.polyfill.MediaCapabilities=class{static install(){shaka.device.DeviceFactory.getDevice().supportsMediaCapabilities()?shaka.log.info("MediaCapabilities: Native mediaCapabilities support found."):(shaka.log.info("MediaCapabilities: install"),navigator.mediaCapabilities||(navigator.mediaCapabilities={}),shaka.polyfill.MediaCapabilities.originalMcap=navigator.mediaCapabilities,navigator.mediaCapabilities.decodingInfo=shaka.polyfill.MediaCapabilities.decodingInfo_)}static async decodingInfo_(a){const b=
{supported:!1,powerEfficient:!0,smooth:!0,keySystemAccess:null,configuration:a},c=shaka.device.DeviceFactory.getDevice(),d=a.video,e=a.audio;if(a.type=="media-source"){if(!c.supportsMediaSource()||d&&!await shaka.polyfill.MediaCapabilities.checkVideoSupport_(d)||e&&!await shaka.polyfill.MediaCapabilities.checkAudioSupport_(e))return b}else if(a.type=="file"){if(d&&!c.supportsMediaType(d.contentType)||e&&!c.supportsMediaType(e.contentType))return b}else return b;if(a.keySystemConfiguration){if(a=await shaka.polyfill.MediaCapabilities.checkDrmSupport_(d,
e,a.keySystemConfiguration))b.supported=!0,b.keySystemAccess=a}else b.supported=!0;return b}static async checkVideoSupport_(a){return shaka.device.DeviceFactory.getDevice().getDeviceType()===shaka.device.IDevice.DeviceType.CAST?await shaka.polyfill.MediaCapabilities.canCastDisplayType_(a):shaka.media.Capabilities.isTypeSupported(a.contentType)}static async checkAudioSupport_(a){var b=shaka.device.DeviceFactory.getDevice().getDeviceType();let c=a.contentType;return b===shaka.device.IDevice.DeviceType.CAST&&
a.spatialRendering&&(c+="; spatialRendering=true",window.cast&&cast.__platform__&&cast.__platform__.canDisplayType)?(b=shaka.polyfill.MediaCapabilities.memoizedCanDisplayTypeRequests_,b.has(c)?a=b.get(c):(a=await cast.__platform__.canDisplayType(c),b.set(c,a)),a):shaka.media.Capabilities.isTypeSupported(c)}static async checkDrmSupport_(a,b,c){var d=shaka.util.MimeUtils,e=[];const f=[],g=[];if(c.audio){var h={robustness:c.audio.robustness||"",contentType:b.contentType};shaka.device.DeviceFactory.getDevice().misreportAC3UsingDrm()&&
b.contentType.includes('codecs="ac-3"')&&(h.contentType='audio/mp4; codecs="ec-3"');c.audio.encryptionScheme&&(h.encryptionScheme=c.audio.encryptionScheme,g.push(c.audio.encryptionScheme));e.push(h)}c.video&&(h={robustness:c.video.robustness||"",contentType:a.contentType},c.video.encryptionScheme&&(h.encryptionScheme=c.video.encryptionScheme,g.push(c.video.encryptionScheme)),f.push(h));h={initDataTypes:[c.initDataType],distinctiveIdentifier:c.distinctiveIdentifier,persistentState:c.persistentState,
sessionTypes:c.sessionTypes};e.length&&(h.audioCapabilities=e);f.length&&(h.videoCapabilities=f);a=a?a.contentType:"";e=b?b.contentType:"";b=d.getBasicType(a)+";"+d.getCodecBase(a);d=d.getBasicType(e)+";"+d.getCodecBase(e);a=c.keySystem;e=null;try{shaka.drm.DrmUtils.hasMediaKeySystemAccess(b,d,a,g)?e=shaka.drm.DrmUtils.getMediaKeySystemAccess(b,d,a,g):(e=await navigator.requestMediaKeySystemAccess(c.keySystem,[h]),shaka.drm.DrmUtils.setMediaKeySystemAccess(b,d,a,g,e))}catch(k){shaka.log.info("navigator.requestMediaKeySystemAccess failed.")}return e}static async canCastDisplayType_(a){if(!(window.cast&&
cast.__platform__&&cast.__platform__.canDisplayType))return shaka.log.warning("Expected cast APIs to be available! Falling back to shaka.media.Capabilities.isTypeSupported() for type support."),shaka.media.Capabilities.isTypeSupported(a.contentType);let b=a.contentType;a.width&&a.height&&a.width>1280&&a.height>720&&(b+=`; width=${a.width}; height=${a.height}`);if(a.framerate){var c=Math.round(a.framerate);if(c<24||c>30)b+=`; framerate=${a.framerate}`}switch(a.transferFunction||""){case "":case "srgb":break;
case "pq":b+="; eotf=smpte2084";break;case "hlg":b+="; eotf=arib-std-b67";break;default:return!1}c=shaka.polyfill.MediaCapabilities.memoizedCanDisplayTypeRequests_;c.has(b)?a=c.get(b):(a=await cast.__platform__.canDisplayType(b),c.set(b,a));return a}};goog.exportProperty(shaka.polyfill,"MediaCapabilities",shaka.polyfill.MediaCapabilities);goog.exportProperty(shaka.polyfill.MediaCapabilities,"install",shaka.polyfill.MediaCapabilities.install);shaka.polyfill.MediaCapabilities.originalMcap=null;
goog.exportProperty(shaka.polyfill.MediaCapabilities,"originalMcap",shaka.polyfill.MediaCapabilities.originalMcap);shaka.polyfill.MediaCapabilities.memoizedCanDisplayTypeRequests_=new Map;shaka.polyfill.register(shaka.polyfill.MediaCapabilities.install,-1);shaka.polyfill.MediaSource=class{static install(){shaka.log.debug("MediaSource.install");var a=shaka.device.IDevice.BrowserEngine;const b=shaka.device.DeviceFactory.getDevice();a=b.getBrowserEngine()===a.WEBKIT?b.getVersion():null;window.MediaSource||window.ManagedMediaSource?a&&window.MediaSource?a<=12?(shaka.log.info("Patching Safari 8-12 MSE bugs."),shaka.polyfill.MediaSource.stubAbort_(),shaka.polyfill.MediaSource.patchRemovalRange_()):a<=15&&(shaka.log.info("Patching Safari 13 & 14 & 15 MSE bugs."),
shaka.polyfill.MediaSource.stubAbort_()):shaka.log.info("Using native MSE as-is."):shaka.log.info("No MSE implementation available.");for(const c of b.rejectCodecs())shaka.log.info(`Rejecting ${c}.`),shaka.polyfill.MediaSource.rejectCodec_(c);(window.MediaSource||window.ManagedMediaSource)&&shaka.polyfill.MediaSource.rejectContainer_("mp2t");window.MediaSource&&MediaSource.isTypeSupported('video/webm; codecs="vp9"')&&!MediaSource.isTypeSupported('video/webm; codecs="vp09.00.10.08"')&&(shaka.log.info("Patching vp09 support queries."),
shaka.polyfill.MediaSource.patchVp09_())}static stubAbort_(){const a=MediaSource.prototype.addSourceBuffer;MediaSource.prototype.addSourceBuffer=function(...b){b=a.apply(this,b);b.abort=function(){};return b}}static patchRemovalRange_(){const a=SourceBuffer.prototype.remove;SourceBuffer.prototype.remove=function(b,c){return a.call(this,b,c-.001)}}static rejectContainer_(a){if(window.MediaSource){const b=MediaSource.isTypeSupported.bind(MediaSource);MediaSource.isTypeSupported=c=>shaka.util.MimeUtils.getContainerType(c)!=
a&&b(c)}if(window.ManagedMediaSource){const b=ManagedMediaSource.isTypeSupported.bind(ManagedMediaSource);window.ManagedMediaSource.isTypeSupported=c=>shaka.util.MimeUtils.getContainerType(c)!=a&&b(c)}}static rejectCodec_(a){const b=MediaSource.isTypeSupported.bind(MediaSource);MediaSource.isTypeSupported=c=>shaka.util.MimeUtils.getCodecBase(c)!=a&&b(c);if(window.ManagedMediaSource){const c=ManagedMediaSource.isTypeSupported.bind(ManagedMediaSource);window.ManagedMediaSource.isTypeSupported=d=>shaka.util.MimeUtils.getCodecBase(d)!=
a&&c(d)}}static patchVp09_(){const a=MediaSource.isTypeSupported;shaka.device.DeviceFactory.getDevice().supportStandardVP9Checking()&&(MediaSource.isTypeSupported=b=>{const c=b.split(/ *; */),d=c.findIndex(g=>g.startsWith("codecs="));if(d<0)return a(b);const e=c[d].replace("codecs=","").replace(/"/g,"").split(/\s*,\s*/),f=e.findIndex(g=>g.startsWith("vp09"));f>=0&&(e[f]="vp9",c[d]='codecs="'+e.join(",")+'"',b=c.join("; "));return a(b)})}};goog.exportProperty(shaka.polyfill,"MediaSource",shaka.polyfill.MediaSource);
goog.exportProperty(shaka.polyfill.MediaSource,"install",shaka.polyfill.MediaSource.install);shaka.polyfill.register(shaka.polyfill.MediaSource.install);shaka.polyfill.PatchedMediaKeysApple=class{static defaultInstall(){window.HTMLVideoElement&&window.WebKitMediaKeys&&(navigator.requestMediaKeySystemAccess&&MediaKeySystemAccess.prototype.getConfiguration||shaka.polyfill.PatchedMediaKeysApple.install())}static install(a=!1){const b=shaka.polyfill.PatchedMediaKeysApple;window.HTMLVideoElement&&window.WebKitMediaKeys&&window.shakaMediaKeysPolyfill!=b.apiName_&&(a&&(b.enableUninstall=!0,b.originalHTMLMediaElementPrototypeMediaKeys=Object.getOwnPropertyDescriptor(HTMLMediaElement.prototype,
"mediaKeys"),b.originalHTMLMediaElementPrototypeSetMediaKeys=HTMLMediaElement.prototype.setMediaKeys,b.originalWindowMediaKeys=window.MediaKeys,b.originalWindowMediaKeySystemAccess=window.MediaKeySystemAccess,b.originalNavigatorRequestMediaKeySystemAccess=navigator.requestMediaKeySystemAccess),shaka.log.info("Using Apple-prefixed EME"),delete HTMLMediaElement.prototype.mediaKeys,HTMLMediaElement.prototype.mediaKeys=null,HTMLMediaElement.prototype.setMediaKeys=b.setMediaKeys,window.MediaKeys=b.MediaKeys,
window.MediaKeySystemAccess=b.MediaKeySystemAccess,navigator.requestMediaKeySystemAccess=b.requestMediaKeySystemAccess,window.shakaMediaKeysPolyfill=b.apiName_,shaka.util.StreamUtils.clearDecodingConfigCache(),shaka.drm.DrmUtils.clearMediaKeySystemAccessMap())}static uninstall(){const a=shaka.polyfill.PatchedMediaKeysApple;window.shakaMediaKeysPolyfill==a.apiName_&&a.enableUninstall&&(shaka.log.info("Un-installing Apple-prefixed EME"),a.enableUninstall=!1,Object.defineProperty(HTMLMediaElement.prototype,
"mediaKeys",a.originalHTMLMediaElementPrototypeMediaKeys),HTMLMediaElement.prototype.setMediaKeys=a.originalHTMLMediaElementPrototypeSetMediaKeys,window.MediaKeys=a.originalWindowMediaKeys,window.MediaKeySystemAccess=a.originalWindowMediaKeySystemAccess,navigator.requestMediaKeySystemAccess=a.originalNavigatorRequestMediaKeySystemAccess,a.originalWindowMediaKeys=null,a.originalWindowMediaKeySystemAccess=null,a.originalHTMLMediaElementPrototypeSetMediaKeys=null,a.originalNavigatorRequestMediaKeySystemAccess=
null,a.originalHTMLMediaElementPrototypeMediaKeys=null,window.shakaMediaKeysPolyfill="",shaka.util.StreamUtils.clearDecodingConfigCache(),shaka.drm.DrmUtils.clearMediaKeySystemAccessMap())}static requestMediaKeySystemAccess(a,b){shaka.log.debug("PatchedMediaKeysApple.requestMediaKeySystemAccess");goog.asserts.assert(this==navigator,'bad "this" for requestMediaKeySystemAccess');const c=shaka.polyfill.PatchedMediaKeysApple;try{const d=new c.MediaKeySystemAccess(a,b);return Promise.resolve(d)}catch(d){return Promise.reject(d)}}static setMediaKeys(a){shaka.log.debug("PatchedMediaKeysApple.setMediaKeys");
goog.asserts.assert(this instanceof HTMLMediaElement,'bad "this" for setMediaKeys');const b=shaka.polyfill.PatchedMediaKeysApple,c=this.mediaKeys;c&&c!=a&&(goog.asserts.assert(c instanceof b.MediaKeys,"non-polyfill instance of oldMediaKeys"),c.setMedia(null));delete this.mediaKeys;return(this.mediaKeys=a)?(goog.asserts.assert(a instanceof b.MediaKeys,"non-polyfill instance of newMediaKeys"),a.setMedia(this)):Promise.resolve()}static onWebkitNeedKey_(a){shaka.log.debug("PatchedMediaKeysApple.onWebkitNeedKey_",
a);goog.asserts.assert(this.mediaKeys instanceof shaka.polyfill.PatchedMediaKeysApple.MediaKeys,"non-polyfill instance of newMediaKeys");goog.asserts.assert(a.initData!=null,"missing init data!");a=shaka.util.BufferUtils.toUint8(a.initData);if(shaka.util.BufferUtils.toDataView(a).getUint32(0,!0)+4!=a.byteLength)throw new RangeError("Malformed FairPlay init data");a=shaka.util.StringUtils.fromUTF16(a.subarray(4),!0);a=shaka.util.StringUtils.toUTF8(a);const b=new Event("encrypted");b.initDataType="skd";
b.initData=shaka.util.BufferUtils.toArrayBuffer(a);this.dispatchEvent(b)}};goog.exportProperty(shaka.polyfill,"PatchedMediaKeysApple",shaka.polyfill.PatchedMediaKeysApple);goog.exportProperty(shaka.polyfill.PatchedMediaKeysApple,"uninstall",shaka.polyfill.PatchedMediaKeysApple.uninstall);goog.exportProperty(shaka.polyfill.PatchedMediaKeysApple,"install",shaka.polyfill.PatchedMediaKeysApple.install);
shaka.polyfill.PatchedMediaKeysApple.MediaKeySystemAccess=class{constructor(a,b){shaka.log.debug("PatchedMediaKeysApple.MediaKeySystemAccess");this.keySystem=a;if(a.startsWith("com.apple.fps"))for(var c of b)if(a=this.checkConfig_(c)){this.configuration_=a;return}c=Error("Unsupported keySystem");c.name="NotSupportedError";c.code=DOMException.NOT_SUPPORTED_ERR;throw c;}checkConfig_(a){if(a.persistentState=="required")return null;const b={audioCapabilities:[],videoCapabilities:[],persistentState:"optional",
distinctiveIdentifier:"optional",initDataTypes:a.initDataTypes,sessionTypes:["temporary"],label:a.label};let c=!1,d=!1;if(a.audioCapabilities)for(const e of a.audioCapabilities)if(e.contentType){c=!0;const f=e.contentType.split(";")[0];WebKitMediaKeys.isTypeSupported(this.keySystem,f)&&(b.audioCapabilities.push(e),d=!0)}if(a.videoCapabilities)for(const e of a.videoCapabilities)e.contentType&&(c=!0,a=e.contentType.split(";")[0],WebKitMediaKeys.isTypeSupported(this.keySystem,a)&&(b.videoCapabilities.push(e),
d=!0));c||(d=WebKitMediaKeys.isTypeSupported(this.keySystem,"video/mp4"));return d?b:null}createMediaKeys(){shaka.log.debug("PatchedMediaKeysApple.MediaKeySystemAccess.createMediaKeys");const a=new shaka.polyfill.PatchedMediaKeysApple.MediaKeys(this.keySystem);return Promise.resolve(a)}getConfiguration(){shaka.log.debug("PatchedMediaKeysApple.MediaKeySystemAccess.getConfiguration");return this.configuration_}};
shaka.polyfill.PatchedMediaKeysApple.MediaKeys=class{constructor(a){shaka.log.debug("PatchedMediaKeysApple.MediaKeys");this.nativeMediaKeys_=new WebKitMediaKeys(a);this.eventManager_=new shaka.util.EventManager}createSession(a){shaka.log.debug("PatchedMediaKeysApple.MediaKeys.createSession");a=a||"temporary";if(a!="temporary")throw new TypeError("Session type "+a+" is unsupported on this platform.");return new shaka.polyfill.PatchedMediaKeysApple.MediaKeySession(this.nativeMediaKeys_,a)}setServerCertificate(a){shaka.log.debug("PatchedMediaKeysApple.MediaKeys.setServerCertificate");
return Promise.resolve(!1)}setMedia(a){const b=shaka.polyfill.PatchedMediaKeysApple;this.eventManager_.removeAll();if(!a)return Promise.resolve();this.eventManager_.listen(a,"webkitneedkey",b.onWebkitNeedKey_);try{return shaka.util.MediaReadyState.waitForReadyState(a,HTMLMediaElement.HAVE_METADATA,this.eventManager_,()=>{a.webkitSetMediaKeys(this.nativeMediaKeys_)}),Promise.resolve()}catch(c){return Promise.reject(c)}}getStatusForPolicy(a){return Promise.resolve("usable")}};
shaka.polyfill.PatchedMediaKeysApple.MediaKeySession=class extends shaka.util.FakeEventTarget{constructor(a,b){shaka.log.debug("PatchedMediaKeysApple.MediaKeySession");super();this.nativeMediaKeySession_=null;this.nativeMediaKeys_=a;this.updatePromise_=this.generateRequestPromise_=null;this.eventManager_=new shaka.util.EventManager;this.sessionId="";this.expiration=NaN;this.closed=new shaka.util.PublicPromise;this.keyStatuses=new shaka.polyfill.PatchedMediaKeysApple.MediaKeyStatusMap;this.onkeystatuseschange=
null}generateRequest(a,b){shaka.log.debug("PatchedMediaKeysApple.MediaKeySession.generateRequest");this.generateRequestPromise_=new shaka.util.PublicPromise;try{const c=this.nativeMediaKeys_.createSession("video/mp4",shaka.util.BufferUtils.toUint8(b));this.nativeMediaKeySession_=c;this.sessionId=c.sessionId||"";this.eventManager_.listen(this.nativeMediaKeySession_,"webkitkeymessage",d=>this.onWebkitKeyMessage_(d));this.eventManager_.listen(c,"webkitkeyadded",d=>this.onWebkitKeyAdded_(d));this.eventManager_.listen(c,
"webkitkeyerror",d=>this.onWebkitKeyError_(d));this.updateKeyStatus_("status-pending")}catch(c){this.generateRequestPromise_.reject(c)}return this.generateRequestPromise_}load(){shaka.log.debug("PatchedMediaKeysApple.MediaKeySession.load");return Promise.reject(Error("MediaKeySession.load not yet supported"))}update(a){shaka.log.debug("PatchedMediaKeysApple.MediaKeySession.update");this.updatePromise_=new shaka.util.PublicPromise;try{this.nativeMediaKeySession_.update(shaka.util.BufferUtils.toUint8(a))}catch(b){this.updatePromise_.reject(b)}return this.updatePromise_}close(){shaka.log.debug("PatchedMediaKeysApple.MediaKeySession.close");
try{this.nativeMediaKeySession_.close(),this.closed.resolve(),this.eventManager_.removeAll()}catch(a){this.closed.reject(a)}return this.closed}remove(){shaka.log.debug("PatchedMediaKeysApple.MediaKeySession.remove");return Promise.reject(Error("MediaKeySession.remove is only applicable for persistent licenses, which are not supported on this platform"))}onWebkitKeyMessage_(a){shaka.log.debug("PatchedMediaKeysApple.onWebkitKeyMessage_",a);goog.asserts.assert(this.generateRequestPromise_,"generateRequestPromise_ should be set before now!");
this.generateRequestPromise_&&(this.generateRequestPromise_.resolve(),this.generateRequestPromise_=null);const b=this.keyStatuses.getStatus()==void 0;a=(new Map).set("messageType",b?"license-request":"license-renewal").set("message",shaka.util.BufferUtils.toArrayBuffer(a.message));a=new shaka.util.FakeEvent("message",a);this.dispatchEvent(a)}onWebkitKeyAdded_(a){shaka.log.debug("PatchedMediaKeysApple.onWebkitKeyAdded_",a);goog.asserts.assert(!this.generateRequestPromise_,"Key added during generate!");
goog.asserts.assert(this.updatePromise_,"updatePromise_ should be set before now!");this.updatePromise_&&(this.updateKeyStatus_("usable"),this.updatePromise_.resolve(),this.updatePromise_=null)}onWebkitKeyError_(a){shaka.log.debug("PatchedMediaKeysApple.onWebkitKeyError_",a);a=Error("EME PatchedMediaKeysApple key error");a.errorCode=this.nativeMediaKeySession_.error;if(this.generateRequestPromise_!=null)this.generateRequestPromise_.reject(a),this.generateRequestPromise_=null;else if(this.updatePromise_!=
null)this.updatePromise_.reject(a),this.updatePromise_=null;else switch(this.nativeMediaKeySession_.error.code){case WebKitMediaKeyError.MEDIA_KEYERR_OUTPUT:case WebKitMediaKeyError.MEDIA_KEYERR_HARDWARECHANGE:this.updateKeyStatus_("output-not-allowed");break;default:this.updateKeyStatus_("internal-error")}}updateKeyStatus_(a){this.keyStatuses.setStatus(a);a=new shaka.util.FakeEvent("keystatuseschange");this.dispatchEvent(a);if(this.onkeystatuseschange)this.onkeystatuseschange(a)}};
shaka.polyfill.PatchedMediaKeysApple.MediaKeyStatusMap=class{constructor(){this.size=0;this.status_=void 0}setStatus(a){this.size=a==void 0?0:1;this.status_=a}getStatus(){return this.status_}forEach(a){this.status_&&a(this.status_,shaka.drm.DrmUtils.DUMMY_KEY_ID.value())}get(a){if(this.has(a))return this.status_}has(a){const b=shaka.drm.DrmUtils.DUMMY_KEY_ID.value();return this.status_&&shaka.util.BufferUtils.equal(a,b)?!0:!1}entries(){goog.asserts.assert(!1,"Not used!  Provided only for the compiler.")}keys(){goog.asserts.assert(!1,
"Not used!  Provided only for the compiler.")}values(){goog.asserts.assert(!1,"Not used!  Provided only for the compiler.")}};shaka.polyfill.PatchedMediaKeysApple.apiName_="apple";shaka.polyfill.register(shaka.polyfill.PatchedMediaKeysApple.defaultInstall);shaka.polyfill.PatchedMediaKeysCert=class{static install(){if(window.MediaKeys){var a=shaka.device.DeviceFactory.getDevice();MediaKeys.prototype.setServerCertificate&&a.supportsServerCertificate()||(shaka.log.info("Patching MediaKeys.setServerCertificate"),MediaKeys.prototype.setServerCertificate=shaka.polyfill.PatchedMediaKeysCert.setServerCertificate_)}}static setServerCertificate_(a){shaka.log.debug("PatchedMediaKeysCert.setServerCertificate");return Promise.resolve(!1)}};
goog.exportProperty(shaka.polyfill,"PatchedMediaKeysCert",shaka.polyfill.PatchedMediaKeysCert);goog.exportProperty(shaka.polyfill.PatchedMediaKeysCert,"install",shaka.polyfill.PatchedMediaKeysCert.install);shaka.polyfill.register(shaka.polyfill.PatchedMediaKeysCert.install);shaka.polyfill.PatchedMediaKeysWebkit=class{static install(){const a=shaka.polyfill.PatchedMediaKeysWebkit;if(!(!window.HTMLVideoElement||navigator.requestMediaKeySystemAccess&&MediaKeySystemAccess.prototype.getConfiguration)){if(HTMLMediaElement.prototype.webkitGenerateKeyRequest)shaka.log.info("Using webkit-prefixed EME v0.1b"),a.prefix_="webkit";else if(HTMLMediaElement.prototype.generateKeyRequest)shaka.log.info("Using nonprefixed EME v0.1b");else return;goog.asserts.assert(HTMLMediaElement.prototype[a.prefixApi_("generateKeyRequest")],
"PatchedMediaKeysWebkit APIs not available!");navigator.requestMediaKeySystemAccess=a.requestMediaKeySystemAccess;delete HTMLMediaElement.prototype.mediaKeys;HTMLMediaElement.prototype.mediaKeys=null;HTMLMediaElement.prototype.setMediaKeys=a.setMediaKeys;window.MediaKeys=a.MediaKeys;window.MediaKeySystemAccess=a.MediaKeySystemAccess;window.shakaMediaKeysPolyfill=a.apiName_}}static prefixApi_(a){const b=shaka.polyfill.PatchedMediaKeysWebkit.prefix_;return b?b+a.charAt(0).toUpperCase()+a.slice(1):a}static requestMediaKeySystemAccess(a,
b){shaka.log.debug("PatchedMediaKeysWebkit.requestMediaKeySystemAccess");goog.asserts.assert(this==navigator,'bad "this" for requestMediaKeySystemAccess');const c=shaka.polyfill.PatchedMediaKeysWebkit;try{const d=new c.MediaKeySystemAccess(a,b);return Promise.resolve(d)}catch(d){return Promise.reject(d)}}static setMediaKeys(a){shaka.log.debug("PatchedMediaKeysWebkit.setMediaKeys");goog.asserts.assert(this instanceof HTMLMediaElement,'bad "this" for setMediaKeys');const b=shaka.polyfill.PatchedMediaKeysWebkit,
c=this.mediaKeys;c&&c!=a&&(goog.asserts.assert(c instanceof b.MediaKeys,"non-polyfill instance of oldMediaKeys"),c.setMedia(null));delete this.mediaKeys;if(this.mediaKeys=a)goog.asserts.assert(a instanceof b.MediaKeys,"non-polyfill instance of newMediaKeys"),a.setMedia(this);return Promise.resolve()}static getVideoElement_(){const a=document.getElementsByTagName("video");return a.length?a[0]:document.createElement("video")}};goog.exportProperty(shaka.polyfill,"PatchedMediaKeysWebkit",shaka.polyfill.PatchedMediaKeysWebkit);
goog.exportProperty(shaka.polyfill.PatchedMediaKeysWebkit,"install",shaka.polyfill.PatchedMediaKeysWebkit.install);
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySystemAccess=class{constructor(a,b){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySystemAccess");this.internalKeySystem_=this.keySystem=a;var c=!1;a=="org.w3.clearkey"&&(this.internalKeySystem_="webkit-org.w3.clearkey",c=!1);let d=!1;const e=shaka.polyfill.PatchedMediaKeysWebkit.getVideoElement_();for(const f of b){b={audioCapabilities:[],videoCapabilities:[],persistentState:"optional",distinctiveIdentifier:"optional",initDataTypes:f.initDataTypes,sessionTypes:["temporary"],
label:f.label};let g=!1;if(f.audioCapabilities)for(const h of f.audioCapabilities)if(h.contentType){g=!0;const k=h.contentType.split(";")[0];e.canPlayType(k,this.internalKeySystem_)&&(b.audioCapabilities.push(h),d=!0)}if(f.videoCapabilities)for(const h of f.videoCapabilities)h.contentType&&(g=!0,e.canPlayType(h.contentType,this.internalKeySystem_)&&(b.videoCapabilities.push(h),d=!0));g||(d=e.canPlayType("video/mp4",this.internalKeySystem_)||e.canPlayType("video/webm",this.internalKeySystem_));f.persistentState==
"required"&&(c?(b.persistentState="required",b.sessionTypes=["persistent-license"]):d=!1);if(d){this.configuration_=b;return}}c="Unsupported keySystem";if(a=="org.w3.clearkey"||a=="com.widevine.alpha")c="None of the requested configurations were supported.";a=Error(c);a.name="NotSupportedError";a.code=DOMException.NOT_SUPPORTED_ERR;throw a;}createMediaKeys(){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySystemAccess.createMediaKeys");const a=new shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys(this.internalKeySystem_);
return Promise.resolve(a)}getConfiguration(){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySystemAccess.getConfiguration");return this.configuration_}};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys=class{constructor(a){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeys");this.keySystem_=a;this.media_=null;this.eventManager_=new shaka.util.EventManager;this.newSessions_=[];this.sessionMap_=new Map}setMedia(a){this.media_=a;this.eventManager_.removeAll();const b=shaka.polyfill.PatchedMediaKeysWebkit.prefix_;a&&(this.eventManager_.listen(a,b+"needkey",c=>this.onWebkitNeedKey_(c)),this.eventManager_.listen(a,b+"keymessage",c=>this.onWebkitKeyMessage_(c)),
this.eventManager_.listen(a,b+"keyadded",c=>this.onWebkitKeyAdded_(c)),this.eventManager_.listen(a,b+"keyerror",c=>this.onWebkitKeyError_(c)))}createSession(a){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeys.createSession");a=a||"temporary";if(a!="temporary"&&a!="persistent-license")throw new TypeError("Session type "+a+" is unsupported on this platform.");const b=shaka.polyfill.PatchedMediaKeysWebkit,c=this.media_||document.createElement("video");c.src||(c.src="about:blank");a=new b.MediaKeySession(c,
this.keySystem_,a);this.newSessions_.push(a);return a}setServerCertificate(a){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeys.setServerCertificate");return Promise.resolve(!1)}getStatusForPolicy(a){return Promise.resolve("usable")}onWebkitNeedKey_(a){shaka.log.debug("PatchedMediaKeysWebkit.onWebkitNeedKey_",a);goog.asserts.assert(this.media_,"media_ not set in onWebkitNeedKey_");const b=new CustomEvent("encrypted");b.initDataType="cenc";b.initData=shaka.util.BufferUtils.toArrayBuffer(a.initData);
this.media_.dispatchEvent(b)}onWebkitKeyMessage_(a){shaka.log.debug("PatchedMediaKeysWebkit.onWebkitKeyMessage_",a);const b=this.findSession_(a.sessionId);if(b){var c=b.keyStatuses.getStatus()==void 0;a=(new Map).set("messageType",c?"licenserequest":"licenserenewal").set("message",a.message);a=new shaka.util.FakeEvent("message",a);b.generated();b.dispatchEvent(a)}else shaka.log.error("Session not found",a.sessionId)}onWebkitKeyAdded_(a){shaka.log.debug("PatchedMediaKeysWebkit.onWebkitKeyAdded_",a);
a=this.findSession_(a.sessionId);goog.asserts.assert(a,"unable to find session in onWebkitKeyAdded_");a&&a.ready()}onWebkitKeyError_(a){shaka.log.debug("PatchedMediaKeysWebkit.onWebkitKeyError_",a);const b=this.findSession_(a.sessionId);goog.asserts.assert(b,"unable to find session in onWebkitKeyError_");b&&b.handleError(a)}findSession_(a){let b=this.sessionMap_.get(a);return b?(shaka.log.debug("PatchedMediaKeysWebkit.MediaKeys.findSession_",b),b):(b=this.newSessions_.shift())?(b.sessionId=a,this.sessionMap_.set(a,
b),shaka.log.debug("PatchedMediaKeysWebkit.MediaKeys.findSession_",b),b):null}};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession=class extends shaka.util.FakeEventTarget{constructor(a,b,c){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession");super();this.media_=a;this.initialized_=!1;this.updatePromise_=this.generatePromise_=null;this.keySystem_=b;this.type_=c;this.sessionId="";this.expiration=NaN;this.closed=new shaka.util.PublicPromise;this.keyStatuses=new shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap;this.onkeystatuseschange=null}generated(){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession.generated");
this.generatePromise_&&(this.generatePromise_.resolve(),this.generatePromise_=null)}ready(){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession.ready");this.updateKeyStatus_("usable");this.updatePromise_&&this.updatePromise_.resolve();this.updatePromise_=null}handleError(a){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession.handleError",a);var b=Error("EME v0.1b key error");const c=a.errorCode;c.systemCode=a.systemCode;b.errorCode=c;!a.sessionId&&this.generatePromise_?(a.systemCode==45&&
(b.message="Unsupported session type."),this.generatePromise_.reject(b),this.generatePromise_=null):a.sessionId&&this.updatePromise_?(this.updatePromise_.reject(b),this.updatePromise_=null):(b=a.systemCode,a.errorCode.code==MediaKeyError.MEDIA_KEYERR_OUTPUT?this.updateKeyStatus_("output-restricted"):b==1?this.updateKeyStatus_("expired"):this.updateKeyStatus_("internal-error"))}generate_(a,b){const c=shaka.polyfill.PatchedMediaKeysWebkit;if(this.initialized_)return Promise.reject(Error("The session is already initialized."));
this.initialized_=!0;let d;try{if(this.type_=="persistent-license"){const f=shaka.util.StringUtils;if(b)d=shaka.util.BufferUtils.toUint8(f.toUTF8("LOAD_SESSION|"+b));else{goog.asserts.assert(a,"expecting init data");const g=f.toUTF8("PERSISTENT|");d=shaka.util.Uint8ArrayUtils.concat(g,a)}}else goog.asserts.assert(this.type_=="temporary","expected temporary session"),goog.asserts.assert(!b,"unexpected offline session ID"),goog.asserts.assert(a,"expecting init data"),d=shaka.util.BufferUtils.toUint8(a);
goog.asserts.assert(d,"init data not set!")}catch(f){return Promise.reject(f)}goog.asserts.assert(this.generatePromise_==null,"generatePromise_ should be null");this.generatePromise_=new shaka.util.PublicPromise;const e=c.prefixApi_("generateKeyRequest");try{this.media_[e](this.keySystem_,d)}catch(f){if(f.name!="InvalidStateError")return this.generatePromise_=null,Promise.reject(f);(new shaka.util.Timer(()=>{try{this.media_[e](this.keySystem_,d)}catch(g){this.generatePromise_.reject(g),this.generatePromise_=
null}})).tickAfter(.01)}return this.generatePromise_}update_(a,b){var c=shaka.polyfill.PatchedMediaKeysWebkit;if(this.updatePromise_)this.updatePromise_.then(()=>this.update_(a,b)).catch(()=>this.update_(a,b));else{this.updatePromise_=a;if(this.keySystem_=="webkit-org.w3.clearkey"){var d=shaka.util.Uint8ArrayUtils;var e=shaka.util.StringUtils.fromUTF8(b);const f=JSON.parse(e);f.keys[0].kty!="oct"&&(this.updatePromise_.reject(Error("Response is not a valid JSON Web Key Set.")),this.updatePromise_=
null);e=d.fromBase64(f.keys[0].k);d=d.fromBase64(f.keys[0].kid)}else e=shaka.util.BufferUtils.toUint8(b),d=null;c=c.prefixApi_("addKey");try{this.media_[c](this.keySystem_,e,d,this.sessionId)}catch(f){this.updatePromise_.reject(f),this.updatePromise_=null}}}updateKeyStatus_(a){this.keyStatuses.setStatus(a);a=new shaka.util.FakeEvent("keystatuseschange");this.dispatchEvent(a);if(this.onkeystatuseschange)this.onkeystatuseschange(a)}generateRequest(a,b){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession.generateRequest");
return this.generate_(b,null)}load(a){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession.load");return this.type_=="persistent-license"?this.generate_(null,a):Promise.reject(Error("Not a persistent session."))}update(a){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession.update",a);goog.asserts.assert(this.sessionId,"update without session ID");const b=new shaka.util.PublicPromise;this.update_(b,a);return b}close(){var a=shaka.polyfill.PatchedMediaKeysWebkit;shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession.close");
if(this.type_!="persistent-license"){if(!this.sessionId)return this.closed.reject(Error("The session is not callable.")),this.closed;a=a.prefixApi_("cancelKeyRequest");try{this.media_[a](this.keySystem_,this.sessionId)}catch(b){shaka.log.debug(`${a} exception`,b)}}this.closed.resolve();return this.closed}remove(){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession.remove");return this.type_!="persistent-license"?Promise.reject(Error("Not a persistent session.")):this.close()}};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap=class{constructor(){this.size=0;this.status_=void 0}setStatus(a){this.size=a==void 0?0:1;this.status_=a}getStatus(){return this.status_}forEach(a){this.status_&&a(this.status_,shaka.drm.DrmUtils.DUMMY_KEY_ID.value())}get(a){if(this.has(a))return this.status_}has(a){const b=shaka.drm.DrmUtils.DUMMY_KEY_ID.value();return this.status_&&shaka.util.BufferUtils.equal(a,b)?!0:!1}entries(){goog.asserts.assert(!1,"Not used!  Provided only for compiler.")}keys(){goog.asserts.assert(!1,
"Not used!  Provided only for compiler.")}values(){goog.asserts.assert(!1,"Not used!  Provided only for compiler.")}};shaka.polyfill.PatchedMediaKeysWebkit.prefix_="";shaka.polyfill.PatchedMediaKeysWebkit.apiName_="webkit";shaka.polyfill.register(shaka.polyfill.PatchedMediaKeysWebkit.install);shaka.polyfill.RandomUUID=class{static install(){shaka.log.debug("randomUUID.install");window.crypto?"randomUUID"in window.crypto?shaka.log.debug("RandomUUID: Native window.crypto.randomUUID() support found."):window.crypto.randomUUID=shaka.polyfill.RandomUUID.randomUUID_:shaka.log.debug("window.crypto must be available to install randomUUID polyfill.")}static randomUUID_(){const a=URL.createObjectURL(new Blob),b=a.toString();URL.revokeObjectURL(a);return b.substr(b.lastIndexOf("/")+1)}};
goog.exportProperty(shaka.polyfill,"RandomUUID",shaka.polyfill.RandomUUID);goog.exportProperty(shaka.polyfill.RandomUUID,"install",shaka.polyfill.RandomUUID.install);shaka.polyfill.register(shaka.polyfill.RandomUUID.install);shaka.polyfill.Symbol=class{static install(){shaka.log.debug("Symbol.install");const a=Symbol.prototype;"description"in a||Object.defineProperty(a,"description",{get:shaka.polyfill.Symbol.getSymbolDescription_})}static getSymbolDescription_(){const a=/\((.*)\)/.exec(this.toString());return a?a[1]:void 0}};goog.exportProperty(shaka.polyfill,"Symbol",shaka.polyfill.Symbol);goog.exportProperty(shaka.polyfill.Symbol,"install",shaka.polyfill.Symbol.install);shaka.polyfill.register(shaka.polyfill.Symbol.install);shaka.polyfill.TypedArray=class{static install(){const a=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,Int8Array,Int16Array,Int32Array,Float32Array,Float64Array];for(const b of a){let c;(c=b.prototype).indexOf??(c.indexOf=Array.prototype.indexOf);let d;(d=b.prototype).lastIndexOf??(d.lastIndexOf=Array.prototype.lastIndexOf);let e;(e=b.prototype).includes??(e.includes=Array.prototype.includes)}}};goog.exportProperty(shaka.polyfill,"TypedArray",shaka.polyfill.TypedArray);
goog.exportProperty(shaka.polyfill.TypedArray,"install",shaka.polyfill.TypedArray.install);shaka.polyfill.register(shaka.polyfill.TypedArray.install);shaka.polyfill.VideoPlayPromise=class{static install(){shaka.log.debug("VideoPlayPromise.install");if(window.HTMLMediaElement){const a=HTMLMediaElement.prototype.play;HTMLMediaElement.prototype.play=function(){const b=a.apply(this);b&&b.catch(()=>{});return b}}}};goog.exportProperty(shaka.polyfill,"VideoPlayPromise",shaka.polyfill.VideoPlayPromise);goog.exportProperty(shaka.polyfill.VideoPlayPromise,"install",shaka.polyfill.VideoPlayPromise.install);shaka.polyfill.register(shaka.polyfill.VideoPlayPromise.install);shaka.polyfill.VideoPlaybackQuality=class{static install(){if(window.HTMLVideoElement){var a=HTMLVideoElement.prototype;!a.getVideoPlaybackQuality&&("webkitDroppedFrameCount"in a||typeof shaka.util.Dom.anyMediaElement().webkitDroppedFrameCount==="number")&&(a.getVideoPlaybackQuality=shaka.polyfill.VideoPlaybackQuality.webkit_)}}static webkit_(){return{droppedVideoFrames:this.webkitDroppedFrameCount,totalVideoFrames:this.webkitDecodedFrameCount,corruptedVideoFrames:0,creationTime:NaN,totalFrameDelay:0}}};
goog.exportProperty(shaka.polyfill,"VideoPlaybackQuality",shaka.polyfill.VideoPlaybackQuality);goog.exportProperty(shaka.polyfill.VideoPlaybackQuality,"install",shaka.polyfill.VideoPlaybackQuality.install);shaka.polyfill.register(shaka.polyfill.VideoPlaybackQuality.install);shaka.polyfill.VTTCue=class{static install(){if(window.VTTCue)shaka.log.info("Using native VTTCue.");else if(window.TextTrackCue){var a=null,b=TextTrackCue.length;b==3?(shaka.log.info("Using VTTCue polyfill from 3 argument TextTrackCue."),a=shaka.polyfill.VTTCue.from3ArgsTextTrackCue_):b==6?(shaka.log.info("Using VTTCue polyfill from 6 argument TextTrackCue."),a=shaka.polyfill.VTTCue.from6ArgsTextTrackCue_):shaka.polyfill.VTTCue.canUse3ArgsTextTrackCue_()&&(shaka.log.info("Using VTTCue polyfill from 3 argument TextTrackCue."),
a=shaka.polyfill.VTTCue.from3ArgsTextTrackCue_);a?window.VTTCue=function(c,d,e){return a(c,d,e)}:shaka.log.error("No recognized signature for TextTrackCue found!")}else shaka.log.error("VTTCue not available.")}static from3ArgsTextTrackCue_(a,b,c){return new window.TextTrackCue(a,b,c)}static from6ArgsTextTrackCue_(a,b,c){return new window.TextTrackCue(a+"-"+b+"-"+c,a,b,c)}static canUse3ArgsTextTrackCue_(){try{return!!shaka.polyfill.VTTCue.from3ArgsTextTrackCue_(1,2,"")}catch(a){return!1}}};
goog.exportProperty(shaka.polyfill,"VTTCue",shaka.polyfill.VTTCue);goog.exportProperty(shaka.polyfill.VTTCue,"install",shaka.polyfill.VTTCue.install);shaka.polyfill.register(shaka.polyfill.VTTCue.install);shaka.queue={};
shaka.queue.QueueManager=class extends shaka.util.FakeEventTarget{constructor(a){super();this.player_=a;this.config_=null;this.items_=[];this.currentItemIndex_=-1;this.preloadPrev_=this.preloadNext_=null;this.eventManager_=new shaka.util.EventManager}async destroy(){await this.removeAllItems();this.player_=null;this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null);super.release()}configure(a){this.config_=a}getConfiguration(){return this.config_}getCurrentItem(){return this.items_.length&&this.currentItemIndex_>=
0&&this.currentItemIndex_<this.items_.length?this.items_[this.currentItemIndex_]:null}getCurrentItemIndex(){return this.currentItemIndex_}getItems(){return this.items_.slice()}insertItems(a){this.items_.push(...a);this.dispatchEvent(new shaka.util.FakeEvent(shaka.util.FakeEvent.EventName.ItemsInserted))}async removeAllItems(){this.eventManager_.removeAll();this.items_.length&&this.currentItemIndex_>=0&&await this.player_.unload();const a=[];this.preloadPrev_&&(this.preloadPrev_.preloadManager.isDestroyed()||
a.push(this.preloadPrev_.preloadManager.destroy()),this.preloadPrev_=null);this.preloadNext_&&(this.preloadNext_.preloadManager.isDestroyed()||a.push(this.preloadNext_.preloadManager.destroy()),this.preloadNext_=null);for(const b of this.items_)b.preloadManager&&!b.preloadManager.isDestroyed()&&a.push(b.preloadManager.destroy());a.length&&await Promise.all(a);this.items_=[];this.currentItemIndex_=-1;this.dispatchEvent(new shaka.util.FakeEvent(shaka.util.FakeEvent.EventName.ItemsRemoved))}async playItem(a){goog.asserts.assert(this.player_,
"We should have player");this.eventManager_.removeAll();if(!this.items_.length||a>=this.items_.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.QUEUE_INDEX_OUT_OF_BOUNDS);const b=this.getCurrentItem(),c=this.items_[a];this.currentItemIndex_!=a&&(this.currentItemIndex_=a,this.dispatchEvent(new shaka.util.FakeEvent(shaka.util.FakeEvent.EventName.CurrentItemChanged)));const d=this.player_.getMediaElement(),e=this.config_?this.config_.preloadNextUrlWindow:
0;if(e>0){let g=!1;this.eventManager_.listen(d,"timeupdate",async()=>{if(!(this.preloadNext_||this.items_.length<=1||g||this.player_.isLive())&&d.duration){var h=this.player_.seekRange().end-d.currentTime;if(!isNaN(h)&&h<=e){var k=this.config_&&this.config_.repeatMode;h=null;this.currentItemIndex_+1<this.items_.length?h=this.items_[this.currentItemIndex_+1]:k==shaka.config.RepeatMode.ALL&&(h=this.items_[0]);if(h&&(!h.preloadManager||h.preloadManager.isDestroyed())){g=!0;k=null;try{k=await this.player_.preload(h.manifestUri,
h.startTime,h.mimeType,h.config)}catch(l){k=null}this.preloadNext_={item:h,preloadManager:k};g=!1}}}})}this.eventManager_.listen(this.player_,"complete",()=>{const g=this.config_&&this.config_.repeatMode;let h=!1;if(g==shaka.config.RepeatMode.SINGLE)h=!0;else{const k=this.currentItemIndex_+1;k<this.items_.length?this.playItem(k):g==shaka.config.RepeatMode.ALL&&(this.items_.length==1?h=!0:this.playItem(0))}h&&(d.paused?(d.currentTime=this.player_.seekRange().start,d.play()):this.eventManager_.listen(d,
"paused",()=>{d.currentTime=this.player_.seekRange().start;d.play()}))});a=c.manifestUri;c.preloadManager&&!c.preloadManager.isDestroyed()&&(a=c.preloadManager);var f=!1;this.preloadNext_&&this.preloadNext_.item==c&&this.preloadNext_.preloadManager?a=this.preloadNext_.preloadManager:this.preloadPrev_&&this.preloadPrev_.item==c&&this.preloadPrev_.preloadManager&&(a=this.preloadPrev_.preloadManager,f=!0);this.preloadPrev_&&(f||this.preloadPrev_.preloadManager.isDestroyed()||await this.preloadPrev_.preloadManager.destroy(),
this.preloadPrev_=null);if(this.config_&&this.config_.preloadPrevItem&&b&&this.player_.getLoadMode()===shaka.Player.LoadMode.MEDIA_SOURCE){f=null;try{f=await this.player_.unloadAndSavePreload()}catch(g){f=null}this.preloadPrev_={item:b,preloadManager:f}}c.config&&(this.player_.resetConfiguration(),this.player_.configure(c.config));await this.player_.load(a,c.startTime,c.mimeType);this.preloadNext_=null;if(c.extraText)for(const g of c.extraText)g.mime?this.player_.addTextTrackAsync(g.uri,g.language,
g.kind,g.mime,g.codecs):this.player_.addTextTrackAsync(g.uri,g.language,g.kind);if(c.extraThumbnail)for(const g of c.extraThumbnail)this.player_.addThumbnailsTrack(g);if(c.extraChapter)for(const g of c.extraChapter)this.player_.addChaptersTrack(g.uri,g.language,g.mime)}};goog.exportSymbol("shaka.queue.QueueManager",shaka.queue.QueueManager);goog.exportProperty(shaka.queue.QueueManager.prototype,"playItem",shaka.queue.QueueManager.prototype.playItem);
goog.exportProperty(shaka.queue.QueueManager.prototype,"removeAllItems",shaka.queue.QueueManager.prototype.removeAllItems);goog.exportProperty(shaka.queue.QueueManager.prototype,"insertItems",shaka.queue.QueueManager.prototype.insertItems);goog.exportProperty(shaka.queue.QueueManager.prototype,"getItems",shaka.queue.QueueManager.prototype.getItems);goog.exportProperty(shaka.queue.QueueManager.prototype,"getCurrentItemIndex",shaka.queue.QueueManager.prototype.getCurrentItemIndex);
goog.exportProperty(shaka.queue.QueueManager.prototype,"getCurrentItem",shaka.queue.QueueManager.prototype.getCurrentItem);goog.exportProperty(shaka.queue.QueueManager.prototype,"getConfiguration",shaka.queue.QueueManager.prototype.getConfiguration);goog.exportProperty(shaka.queue.QueueManager.prototype,"configure",shaka.queue.QueueManager.prototype.configure);goog.exportProperty(shaka.queue.QueueManager.prototype,"destroy",shaka.queue.QueueManager.prototype.destroy);
shaka.Player.setQueueManagerFactory(a=>new shaka.queue.QueueManager(a));shaka.text.LrcTextParser=class{parseInit(a){goog.asserts.assert(!1,"LRC does not have init segments")}setSequenceMode(a){}setManifestType(a){}parseMedia(a,b){const c=shaka.text.LrcTextParser;let d=null;const e=[];a=shaka.util.StringUtils.fromUTF8(a).split(/\r?\n/);for(const g of a){if(!g||/^\s+$/.test(g))continue;var f=c.lyricLine_.exec(g);f?(a=c.parseTime_(f[1]),f=new shaka.text.Cue(a,b.segmentEnd?b.segmentEnd:a+2,f[2]),d&&(d.endTime=a,e.push(d)),d=f):shaka.log.warning("LrcTextParser encountered an unknown line.",
g)}d&&e.push(d);return e}static parseTime_(a){var b=shaka.text.LrcTextParser.timeFormat_.exec(a);a=parseInt(b[1],10);b=parseFloat(b[2].replace(",","."));return a*60+b}};goog.exportSymbol("shaka.text.LrcTextParser",shaka.text.LrcTextParser);goog.exportProperty(shaka.text.LrcTextParser.prototype,"parseMedia",shaka.text.LrcTextParser.prototype.parseMedia);goog.exportProperty(shaka.text.LrcTextParser.prototype,"setManifestType",shaka.text.LrcTextParser.prototype.setManifestType);
goog.exportProperty(shaka.text.LrcTextParser.prototype,"setSequenceMode",shaka.text.LrcTextParser.prototype.setSequenceMode);goog.exportProperty(shaka.text.LrcTextParser.prototype,"parseInit",shaka.text.LrcTextParser.prototype.parseInit);shaka.text.LrcTextParser.lyricLine_=/^\[(\d{1,2}:\d{1,2}(?:[.,]\d{1,3})?)\](.*)/;shaka.text.LrcTextParser.timeFormat_=/^(\d+):(\d{1,2}(?:[.,]\d{1,3})?)$/;shaka.text.TextEngine.registerParser("application/x-subtitle-lrc",()=>new shaka.text.LrcTextParser);shaka.text.TtmlTextParser=class{constructor(){this.manifestType_=shaka.media.ManifestParser.UNKNOWN}parseInit(a){goog.asserts.assert(!1,"TTML does not have init segments")}setSequenceMode(a){}setManifestType(a){this.manifestType_=a}parseMedia(a,b,c,d){var e=shaka.text.TtmlTextParser;const f=shaka.util.TXml;var g=e.parameterNs_,h=e.styleNs_,k=shaka.util.StringUtils.fromUTF8(a);a=[];if(k=="")return a;var l=f.parseXmlString(k,"tt",!0);if(!l)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_XML,"Failed to parse TTML.");k=f.getElementsByTagName(l,"body")[0];if(!k)return[];var m=f.getAttributeNSList(l,g,"frameRate"),n=f.getAttributeNSList(l,g,"subFrameRate"),q=f.getAttributeNSList(l,g,"frameRateMultiplier"),p=f.getAttributeNSList(l,g,"tickRate"),r=f.getAttributeNSList(l,g,"cellResolution");g=l.attributes["xml:space"]||"default";h=f.getAttributeNSList(l,h,"extent");if(g!="default"&&g!="preserve")throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_XML,"Invalid xml:space value: "+g);g=g=="default";e=new e.RateInfo_(m,n,q,p);m=this.getCellResolution_(r);n=f.getElementsByTagName(l,"metadata")[0];n=(n?n.children:[]).filter(t=>t!="\n");q=f.getElementsByTagName(l,"style");l=f.getElementsByTagName(l,"region");p=[];for(const t of l)(r=this.parseCueRegion_(t,q,h))&&p.push(r);if(f.findChildren(k,"p").length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,
shaka.util.Error.Code.INVALID_TEXT_CUE,"<p> can only be inside <div> in TTML");for(const t of f.findChildren(k,"div"))if(f.findChildren(t,"span").length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_TEXT_CUE,"<span> can only be inside <p> in TTML");if(b=this.parseCue_(k,b,e,n,q,l,p,g,m,null,!1,c,d))b.backgroundColor||(b.backgroundColor="transparent"),a.push(b);return a}parseCue_(a,b,c,d,e,f,g,h,k,l,m,n,q){const p=shaka.util.TXml;
var r=shaka.util.StringUtils;let t,u=l;if(p.isText(a)){if(!m)return null;t={tagName:"span",children:[p.getTextContents(a)],attributes:{},parent:null}}else t=a;goog.asserts.assert(t,"cueElement should be non-null!");let v=null;for(var x of shaka.text.TtmlTextParser.smpteNsList_)if(v=this.getElementsFromCollection_(t,"backgroundImage",d,"#",x)[0])break;x=null;var y=p.getAttributeNSList(t,shaka.text.TtmlTextParser.smpteNsList_,"backgroundImage"),A=/^(urn:)(mpeg:[a-z0-9][a-z0-9-]{0,31}:)(subs:)([0-9]+)$/;
if(y&&A.test(y)){x=parseInt(y.split(":").pop(),10)-1;if(x>=q.length)return null;x=q[x]}else n&&y&&!y.startsWith("#")&&(A=new goog.Uri(n),y=new goog.Uri(y),(y=A.resolve(y).toString())&&(x=y));if(a.tagName=="p"||v||x)m=!0;a=m;y=(t.attributes["xml:space"]||(h?"default":"preserve"))=="default";A=t.children.every(p.isText);h=[];if(!A)for(const B of t.children){const C=this.parseCue_(B,b,c,d,e,f,g,y,k,t,m,n,q);C&&h.push(C)}d=l!=null;n=p.getTextContents(t);n=t.children.length&&n&&/\S/.test(n);q=t.attributes.begin||
t.attributes.end||t.attributes.dur;if(!(q||n||t.tagName=="br"||h.length!=0||d&&!y))return null;let {start:w,end:z}=this.parseTime_(t,c);for(;u&&p.isNode(u)&&u.tagName!="tt";)({start:w,end:z}=this.resolveTime_(u,c,w,z)),u=u.parent;w==null&&(w=0);w+=b.periodStart;z=z==null?Infinity:z+b.periodStart;this.manifestType_!==shaka.media.ManifestParser.HLS&&(w=Math.max(w,b.segmentStart),z=Math.min(z,b.segmentEnd));if(!q&&h.length>0){w=Infinity;z=0;for(const B of h)w=Math.min(w,B.startTime),z=Math.max(z,B.endTime)}if(t.tagName==
"br")return e=new shaka.text.Cue(w,z,""),e.lineBreak=!0,e;b="";A&&(b=r.htmlUnescape(shaka.util.TXml.getTextContents(t)||""),y&&(b=b.replace(/\s+/g," ")));r=new shaka.text.Cue(w,z,b);r.nestedCues=h;m||(r.isContainer=!0);k&&(r.cellResolution=k);k=this.getElementsFromCollection_(t,"region",f,"")[0];if(t.attributes.region&&k&&k.attributes["xml:id"]){const B=k.attributes["xml:id"];r.region=g.filter(C=>C.id==B)[0]}g=k;l&&d&&!t.attributes.region&&!t.attributes.style&&(g=this.getElementsFromCollection_(l,
"region",f,"")[0]);this.addStyle_(r,t,g,v,x,e,a,h.length==0);return r}parseCueRegion_(a,b,c){const d=shaka.text.TtmlTextParser,e=new shaka.text.CueRegion;var f=a.attributes["xml:id"];if(!f)return shaka.log.warning("TtmlTextParser parser encountered a region with no id. Region will be ignored."),null;e.id=f;f=null;c&&(f=d.percentValues_.exec(c)||d.pixelValues_.exec(c));c=f?Number(f[1]):null;f=f?Number(f[2]):null;let g,h;const k=this.getStyleAttributeFromRegion_(a,b,"extent");k&&(g=(h=d.percentValues_.exec(k))||
d.pixelValues_.exec(k),g!=null&&(e.width=Number(g[1]),e.height=Number(g[2]),h||(c!=null&&(e.width=e.width*100/c),f!=null&&(e.height=e.height*100/f)),e.widthUnits=h||c!=null?shaka.text.CueRegion.units.PERCENTAGE:shaka.text.CueRegion.units.PX,e.heightUnits=h||f!=null?shaka.text.CueRegion.units.PERCENTAGE:shaka.text.CueRegion.units.PX));if(a=this.getStyleAttributeFromRegion_(a,b,"origin"))if(g=(h=d.percentValues_.exec(a))||d.pixelValues_.exec(a),g!=null)e.viewportAnchorX=Number(g[1]),e.viewportAnchorY=
Number(g[2]),h?k||(e.width=100-e.viewportAnchorX,e.widthUnits=shaka.text.CueRegion.units.PERCENTAGE,e.height=100-e.viewportAnchorY,e.heightUnits=shaka.text.CueRegion.units.PERCENTAGE):(f!=null&&(e.viewportAnchorY=e.viewportAnchorY*100/f),c!=null&&(e.viewportAnchorX=e.viewportAnchorX*100/c)),e.viewportAnchorUnits=h||c!=null?shaka.text.CueRegion.units.PERCENTAGE:shaka.text.CueRegion.units.PX;return e}convertTTMLrgbaToHTMLrgba_(a){var b=a.match(/rgba\(([^)]+)\)/);return b&&(b=b[1].split(","),b.length==
4)?(b[3]=String(Number(b[3])/255),"rgba("+b.join(",")+")"):a}addStyle_(a,b,c,d,e,f,g,h){var k=shaka.text.TtmlTextParser;const l=shaka.util.TXml;var m=shaka.text.Cue;g=g||h;this.getStyleAttribute_(b,c,f,"direction",g)=="rtl"&&(a.direction=m.direction.HORIZONTAL_RIGHT_TO_LEFT);h=this.getStyleAttribute_(b,c,f,"writingMode",g);h=="tb"||h=="tblr"?a.writingMode=m.writingMode.VERTICAL_LEFT_TO_RIGHT:h=="tbrl"?a.writingMode=m.writingMode.VERTICAL_RIGHT_TO_LEFT:h=="rltb"||h=="rl"?a.direction=m.direction.HORIZONTAL_RIGHT_TO_LEFT:
h&&(a.direction=m.direction.HORIZONTAL_LEFT_TO_RIGHT);(h=this.getStyleAttribute_(b,c,f,"textAlign",!0))?(a.positionAlign=k.textAlignToPositionAlign_.get(h),a.lineAlign=k.textAlignToLineAlign_.get(h),goog.asserts.assert(h.toUpperCase()in m.textAlign,h.toUpperCase()+" Should be in Cue.textAlign values!"),a.textAlign=m.textAlign[h.toUpperCase()]):a.textAlign=m.textAlign.CENTER;if(h=this.getStyleAttribute_(b,c,f,"displayAlign",!0))goog.asserts.assert(h.toUpperCase()in m.displayAlign,h.toUpperCase()+" Should be in Cue.displayAlign values!"),
a.displayAlign=m.displayAlign[h.toUpperCase()];if(h=this.getStyleAttribute_(b,c,f,"color",g))a.color=this.convertTTMLrgbaToHTMLrgba_(h);if(h=this.getStyleAttribute_(b,c,f,"backgroundColor",g))a.backgroundColor=this.convertTTMLrgbaToHTMLrgba_(h);if(h=this.getStyleAttribute_(b,c,f,"border",g))a.border=h;if(h=this.getStyleAttribute_(b,c,f,"fontFamily",g))switch(h){case "monospaceSerif":a.fontFamily="Courier New,Liberation Mono,Courier,monospace";break;case "proportionalSansSerif":a.fontFamily="Arial,Helvetica,Liberation Sans,sans-serif";
break;case "sansSerif":a.fontFamily="sans-serif";break;case "monospaceSansSerif":a.fontFamily="Consolas,monospace";break;case "proportionalSerif":a.fontFamily="serif";break;default:a.fontFamily=h.split(",").filter(n=>n!="default").join(",")}(h=this.getStyleAttribute_(b,c,f,"fontWeight",g))&&h=="bold"&&(a.fontWeight=m.fontWeight.BOLD);h=this.getStyleAttribute_(b,c,f,"wrapOption",g);a.wrapLine=h&&h=="noWrap"?!1:!0;(h=this.getStyleAttribute_(b,c,f,"lineHeight",g))&&h.match(k.unitValues_)&&(a.lineHeight=
h);(h=this.getStyleAttribute_(b,c,f,"fontSize",g))&&(h.match(k.unitValues_)||h.match(k.percentValue_))&&(a.fontSize=h);if(h=this.getStyleAttribute_(b,c,f,"fontStyle",g))goog.asserts.assert(h.toUpperCase()in m.fontStyle,h.toUpperCase()+" Should be in Cue.fontStyle values!"),a.fontStyle=m.fontStyle[h.toUpperCase()];d?(e=d.attributes.imageType||d.attributes.imagetype,m=d.attributes.encoding,d=l.getTextContents(d).trim(),e=="PNG"&&m=="Base64"&&d&&(a.backgroundImage="data:image/png;base64,"+d)):e&&(a.backgroundImage=
e);if(d=this.getStyleAttribute_(b,c,f,"textOutline",g))d=d.split(" "),d[0].match(k.unitValues_)?a.textStrokeColor=a.color:(a.textStrokeColor=this.convertTTMLrgbaToHTMLrgba_(d[0]),d.shift()),d[0]&&d[0].match(k.unitValues_)?a.textStrokeWidth=d[0]:a.textStrokeColor="";(d=this.getStyleAttribute_(b,c,f,"letterSpacing",g))&&d.match(k.unitValues_)&&(a.letterSpacing=d);(d=this.getStyleAttribute_(b,c,f,"linePadding",g))&&d.match(k.unitValues_)&&(a.linePadding=d);if(k=this.getStyleAttribute_(b,c,f,"opacity",
g))a.opacity=parseFloat(k);(k=this.getStyleAttributeFromRegion_(c,f,"textDecoration"))&&this.addTextDecoration_(a,k);(k=this.getStyleAttributeFromElement_(b,f,"textDecoration"))&&this.addTextDecoration_(a,k);if(k=this.getStyleAttribute_(b,c,f,"textCombine",g))a.textCombineUpright=k;switch(this.getStyleAttribute_(b,c,f,"ruby",g)){case "container":a.rubyTag="ruby";break;case "text":a.rubyTag="rt"}}addTextDecoration_(a,b){const c=shaka.text.Cue;for(const d of b.split(" "))switch(d){case "underline":a.textDecoration.includes(c.textDecoration.UNDERLINE)||
a.textDecoration.push(c.textDecoration.UNDERLINE);break;case "noUnderline":a.textDecoration.includes(c.textDecoration.UNDERLINE)&&shaka.util.ArrayUtils.remove(a.textDecoration,c.textDecoration.UNDERLINE);break;case "lineThrough":a.textDecoration.includes(c.textDecoration.LINE_THROUGH)||a.textDecoration.push(c.textDecoration.LINE_THROUGH);break;case "noLineThrough":a.textDecoration.includes(c.textDecoration.LINE_THROUGH)&&shaka.util.ArrayUtils.remove(a.textDecoration,c.textDecoration.LINE_THROUGH);
break;case "overline":a.textDecoration.includes(c.textDecoration.OVERLINE)||a.textDecoration.push(c.textDecoration.OVERLINE);break;case "noOverline":a.textDecoration.includes(c.textDecoration.OVERLINE)&&shaka.util.ArrayUtils.remove(a.textDecoration,c.textDecoration.OVERLINE)}}getStyleAttribute_(a,b,c,d,e=!0){return(a=this.getStyleAttributeFromElement_(a,c,d))?a:e?this.getStyleAttributeFromRegion_(b,c,d):null}getStyleAttributeFromRegion_(a,b,c){if(!a)return null;const d=shaka.util.TXml.getAttributeNSList(a,
shaka.text.TtmlTextParser.styleNs_,c);return d?d:this.getInheritedStyleAttribute_(a,b,c)}getStyleAttributeFromElement_(a,b,c){const d=shaka.util.TXml.getAttributeNSList(a,shaka.text.TtmlTextParser.styleNs_,c);return d?d:this.getInheritedStyleAttribute_(a,b,c)}getInheritedStyleAttribute_(a,b,c){const d=shaka.util.TXml,e=shaka.text.TtmlTextParser.styleNs_,f=shaka.text.TtmlTextParser.styleEbuttsNs_;a=this.getElementsFromCollection_(a,"style",b,"");let g=null;for(let h=0;h<a.length;h++){let k=d.getAttributeNS(a[h],
f,c);k||=d.getAttributeNSList(a[h],e,c);k||=this.getStyleAttributeFromElement_(a[h],b,c);k&&(g=k)}return g}getElementsFromCollection_(a,b,c,d,e){const f=[];if(!a||c.length<1)return f;if(a=this.getInheritedAttribute_(a,b,e)){a=a.split(" ");for(const g of a)for(const h of c)if(d+h.attributes["xml:id"]==g){f.push(h);break}}return f}getInheritedAttribute_(a,b,c){let d=null;const e=shaka.util.TXml;for(;!d&&!(d=c?e.getAttributeNS(a,c,b):a.attributes[b])&&(a=a.parent,a););return d}resolveTime_(a,b,c,d){a=
this.parseTime_(a,b);c==null?c=a.start:a.start!=null&&(c+=a.start);d==null?d=a.end:a.start!=null&&(d+=a.start);return{start:c,end:d}}parseTime_(a,b){const c=this.parseTimeAttribute_(a.attributes.begin,b);let d=this.parseTimeAttribute_(a.attributes.end,b);a=this.parseTimeAttribute_(a.attributes.dur,b);d==null&&a!=null&&(d=c+a);return{start:c,end:d}}parseTimeAttribute_(a,b){let c=null;const d=shaka.text.TtmlTextParser;if(d.timeColonFormatFrames_.test(a))c=this.parseColonTimeWithFrames_(b,a);else if(d.timeColonFormat_.test(a))c=
this.parseTimeFromRegex_(d.timeColonFormat_,a);else if(d.timeColonFormatMilliseconds_.test(a))c=this.parseTimeFromRegex_(d.timeColonFormatMilliseconds_,a);else if(d.timeFramesFormat_.test(a))c=this.parseFramesTime_(b,a);else if(d.timeTickFormat_.test(a))c=this.parseTickTime_(b,a);else if(d.timeHMSFormat_.test(a))c=this.parseTimeFromRegex_(d.timeHMSFormat_,a);else if(a)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_TEXT_CUE,
"Could not parse cue time range in TTML");return c}parseFramesTime_(a,b){b=shaka.text.TtmlTextParser.timeFramesFormat_.exec(b);return Number(b[1])/a.frameRate}parseTickTime_(a,b){b=shaka.text.TtmlTextParser.timeTickFormat_.exec(b);return Number(b[1])/a.tickRate}parseColonTimeWithFrames_(a,b){b=shaka.text.TtmlTextParser.timeColonFormatFrames_.exec(b);const c=Number(b[1]),d=Number(b[2]);let e=Number(b[3]),f=Number(b[4]);f+=(Number(b[5])||0)/a.subFrameRate;e+=f/a.frameRate;return e+d*60+c*3600}parseTimeFromRegex_(a,
b){a=a.exec(b);return a==null||a[0]==""?null:(Number(a[4])||0)/1E3+(Number(a[3])||0)+(Number(a[2])||0)*60+(Number(a[1])||0)*3600}getCellResolution_(a){if(!a)return null;var b=/^(\d+) (\d+)$/.exec(a);if(!b)return null;a=parseInt(b[1],10);b=parseInt(b[2],10);return{columns:a,rows:b}}};goog.exportSymbol("shaka.text.TtmlTextParser",shaka.text.TtmlTextParser);goog.exportProperty(shaka.text.TtmlTextParser.prototype,"parseMedia",shaka.text.TtmlTextParser.prototype.parseMedia);
goog.exportProperty(shaka.text.TtmlTextParser.prototype,"setManifestType",shaka.text.TtmlTextParser.prototype.setManifestType);goog.exportProperty(shaka.text.TtmlTextParser.prototype,"setSequenceMode",shaka.text.TtmlTextParser.prototype.setSequenceMode);goog.exportProperty(shaka.text.TtmlTextParser.prototype,"parseInit",shaka.text.TtmlTextParser.prototype.parseInit);
shaka.text.TtmlTextParser.RateInfo_=class{constructor(a,b,c,d){this.frameRate=Number(a)||30;this.subFrameRate=Number(b)||1;this.tickRate=Number(d);this.tickRate==0&&(this.tickRate=a?this.frameRate*this.subFrameRate:1);c&&(a=/^(\d+) (\d+)$/g.exec(c))&&(this.frameRate*=Number(a[1])/Number(a[2]))}};shaka.text.TtmlTextParser.percentValues_=/^(\d{1,2}(?:\.\d+)?|100(?:\.0+)?)% (\d{1,2}(?:\.\d+)?|100(?:\.0+)?)%$/;shaka.text.TtmlTextParser.percentValue_=/^(\d{1,4}(?:\.\d+)?|100)%$/;
shaka.text.TtmlTextParser.unitValues_=/^(\d+px|\d+em|\d*\.?\d+c)$/;shaka.text.TtmlTextParser.pixelValues_=/^(\d+)px (\d+)px$/;shaka.text.TtmlTextParser.timeColonFormatFrames_=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/;shaka.text.TtmlTextParser.timeColonFormat_=/^(?:(\d{2,}):)?(\d{2}):(\d{2})$/;shaka.text.TtmlTextParser.timeColonFormatMilliseconds_=/^(?:(\d{2,}):)?(\d{2}):(\d{2}\.\d+)$/;shaka.text.TtmlTextParser.timeFramesFormat_=/^(\d*(?:\.\d*)?)f$/;shaka.text.TtmlTextParser.timeTickFormat_=/^(\d*(?:\.\d*)?)t$/;
shaka.text.TtmlTextParser.timeHMSFormat_=RegExp("^(?:(\\d*(?:\\.\\d*)?)h)?(?:(\\d*(?:\\.\\d*)?)m)?(?:(\\d*(?:\\.\\d*)?)s)?(?:(\\d*(?:\\.\\d*)?)ms)?$");shaka.text.TtmlTextParser.textAlignToLineAlign_=(new Map).set("left",shaka.text.Cue.lineAlign.START).set("center",shaka.text.Cue.lineAlign.CENTER).set("right",shaka.text.Cue.lineAlign.END).set("start",shaka.text.Cue.lineAlign.START).set("end",shaka.text.Cue.lineAlign.END);
shaka.text.TtmlTextParser.textAlignToPositionAlign_=(new Map).set("left",shaka.text.Cue.positionAlign.LEFT).set("center",shaka.text.Cue.positionAlign.CENTER).set("right",shaka.text.Cue.positionAlign.RIGHT).set("start",shaka.text.Cue.positionAlign.LEFT).set("end",shaka.text.Cue.positionAlign.RIGHT);shaka.text.TtmlTextParser.parameterNs_=["http://www.w3.org/ns/ttml#parameter","http://www.w3.org/2006/10/ttaf1#parameter"];shaka.text.TtmlTextParser.styleNs_=["http://www.w3.org/ns/ttml#styling","http://www.w3.org/2006/10/ttaf1#styling"];
shaka.text.TtmlTextParser.styleEbuttsNs_="urn:ebu:tt:style";shaka.text.TtmlTextParser.smpteNsList_=["http://www.smpte-ra.org/schemas/2052-1/2010/smpte-tt","http://www.smpte-ra.org/schemas/2052-1/2013/smpte-tt"];shaka.text.TextEngine.registerParser("application/ttml+xml",()=>new shaka.text.TtmlTextParser);shaka.text.Mp4TtmlParser=class{constructor(){this.parser_=new shaka.text.TtmlTextParser}parseInit(a){const b=shaka.util.Mp4Parser;let c=!1;(new b).boxes(["moov","trak","mdia","minf","stbl"],b.children).fullBox("stsd",b.sampleDescription).box("stpp",d=>{c=!0;d.parser.stop()}).parse(a);if(!c)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_MP4_TTML);}setSequenceMode(a){this.parser_.setSequenceMode(a)}setManifestType(a){this.parser_.setManifestType(a)}parseMedia(a,
b,c){var d=shaka.util.Mp4Parser;let e=[],f=null;const g=[],h=new Map,k=[];(new d).boxes(["moof","traf"],d.children).fullBox("tfhd",m=>{goog.asserts.assert(m.flags!=null,"A TFHD box should have a valid flags value");f=shaka.util.Mp4BoxParsers.parseTFHD(m.reader,m.flags).defaultSampleSize}).fullBox("trun",m=>{goog.asserts.assert(m.version!=null,"A TRUN box should have a valid version value");goog.asserts.assert(m.flags!=null,"A TRUN box should have a valid flags value");m=shaka.util.Mp4BoxParsers.parseTRUN(m.reader,
m.version,m.flags);for(const n of m.sampleData)k.push(n.sampleSize||f||0)}).fullBox("subs",m=>{const n=m.reader,q=n.readUint32();let p=-1;for(let t=0;t<q;t++){var r=n.readUint32();p+=r;r=n.readUint16();const u=[];for(let v=0;v<r;v++)m.version==1?u.push(n.readUint32()):u.push(n.readUint16()),n.readUint8(),n.readUint8(),n.readUint32();h.set(p,u)}}).box("mdat",d.allData(m=>{g.push(m)},!1)).parse(a,!1);if(g.length==0)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,
shaka.util.Error.Code.INVALID_MP4_TTML);a=shaka.util.Uint8ArrayUtils.concat(...g);d=0;for(let m=0;m<k.length;m++){const n=shaka.util.BufferUtils.toUint8(a,d,k[m]);d+=k[m];const q=h.get(m);if(q&&q.length){const p=shaka.util.BufferUtils.toUint8(n,0,q[0]),r=[];let t=q[0];for(let u=1;u<q.length;u++){var l=shaka.util.BufferUtils.toUint8(n,t,q[u]);l=shaka.util.Uint8ArrayUtils.toStandardBase64(l);r.push("data:image/png;base64,"+l);t+=q[u]}e=e.concat(this.parser_.parseMedia(p,b,c,r))}else e=e.concat(this.parser_.parseMedia(n,
b,c,[]))}return e}};goog.exportSymbol("shaka.text.Mp4TtmlParser",shaka.text.Mp4TtmlParser);goog.exportProperty(shaka.text.Mp4TtmlParser.prototype,"parseMedia",shaka.text.Mp4TtmlParser.prototype.parseMedia);goog.exportProperty(shaka.text.Mp4TtmlParser.prototype,"setManifestType",shaka.text.Mp4TtmlParser.prototype.setManifestType);goog.exportProperty(shaka.text.Mp4TtmlParser.prototype,"setSequenceMode",shaka.text.Mp4TtmlParser.prototype.setSequenceMode);
goog.exportProperty(shaka.text.Mp4TtmlParser.prototype,"parseInit",shaka.text.Mp4TtmlParser.prototype.parseInit);shaka.text.TextEngine.registerParser('application/mp4; codecs="stpp"',()=>new shaka.text.Mp4TtmlParser);shaka.text.TextEngine.registerParser('application/mp4; codecs="stpp.ttml"',()=>new shaka.text.Mp4TtmlParser);shaka.text.TextEngine.registerParser('application/mp4; codecs="stpp.ttml.im1i"',()=>new shaka.text.Mp4TtmlParser);
shaka.text.TextEngine.registerParser('application/mp4; codecs="stpp.ttml.im1t"',()=>new shaka.text.Mp4TtmlParser);shaka.text.TextEngine.registerParser('application/mp4; codecs="stpp.ttml.im2i"',()=>new shaka.text.Mp4TtmlParser);shaka.text.TextEngine.registerParser('application/mp4; codecs="stpp.ttml.im2t"',()=>new shaka.text.Mp4TtmlParser);shaka.text.TextEngine.registerParser('application/mp4; codecs="stpp.ttml.etd1"',()=>new shaka.text.Mp4TtmlParser);
shaka.text.TextEngine.registerParser('application/mp4; codecs="stpp.ttml.etd1|im1t"',()=>new shaka.text.Mp4TtmlParser);shaka.text.TextEngine.registerParser('application/mp4; codecs="stpp.ttml.im1t|etd1"',()=>new shaka.text.Mp4TtmlParser);shaka.text.TextEngine.registerParser('application/mp4; codecs="stpp.TTML.im1t"',()=>new shaka.text.Mp4TtmlParser);shaka.text.VttTextParser=class{constructor(){this.sequenceMode_=!1;this.manifestType_=shaka.media.ManifestParser.UNKNOWN}parseInit(a){goog.asserts.assert(!1,"VTT does not have init segments")}setSequenceMode(a){this.sequenceMode_=a}setManifestType(a){this.manifestType_=a}parseMedia(a,b){const c=shaka.text.VttTextParser;a=shaka.util.StringUtils.fromUTF8(a);a=a.replace(/\r\n|\r(?=[^\n]|$)/gm,"\n");var d=a.split(/\n{2,}/m);if(!/^WEBVTT($|[ \t\n])/m.test(d[0]))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_TEXT_HEADER);a=b.vttOffset;this.manifestType_==shaka.media.ManifestParser.HLS&&d[0].includes("X-TIMESTAMP-MAP")&&(a=this.computeHlsOffset_(d[0],b));b=[];for(var e of d[0].split("\n"))if(/^Region:/.test(e)){var f=c.parseRegion_(e);b.push(f)}e=new Map;shaka.text.Cue.addDefaultTextColor(e);f=[];for(const g of d.slice(1))d=g.split("\n"),c.parseStyle_(d,e),(d=c.parseCue_(d,a,b,e))&&f.push(d);return f}computeHlsOffset_(a,b){var c=a.match(/LOCAL:((?:(\d{1,}):)?(\d{2}):(\d{2})\.(\d{3}))/m);
a=a.match(/MPEGTS:(\d+)/m);if(!c||!a)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_TEXT_HEADER);c=shaka.util.TextParser.parseTime(c[1]);if(c==null)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_TEXT_HEADER);a=Number(a[1]);const d=shaka.text.VttTextParser.MPEG_TIMESCALE_,e=shaka.text.VttTextParser.TS_ROLLOVER_/d;let f=b.segmentStart-b.periodStart;
for(;f>=e;)f-=e,a+=shaka.text.VttTextParser.TS_ROLLOVER_;return b.periodStart+a/d-c}static parseRegion_(a){const b=shaka.text.VttTextParser;a=new shaka.util.TextParser(a);const c=new shaka.text.CueRegion;a.readWord();a.skipWhitespace();let d=a.readWord();for(;d;)b.parseRegionSetting_(c,d)||shaka.log.warning("VTT parser encountered an invalid VTTRegion setting: ",d," The setting will be ignored."),a.skipWhitespace(),d=a.readWord();return c}static parseStyle_(a,b){if((a.length!=1||a[0])&&!shaka.text.VttTextParser.REGEX_NOTE_.test(a[0])&&
a[0]=="STYLE"){var c=[],d=-1;for(var e=1;e<a.length;e++)a[e].includes("::cue")&&(c.push([]),d=c.length-1),d!=-1&&(c[d].push(a[e]),a[e].includes("}")&&(d=-1));for(const f of c){a="global";(c=f[0].match(/\((.*)\)/))&&(a=c.pop());c=f.slice(1,-1);f[0].includes("}")&&(d=/\{(.*?)\}/.exec(f[0]))&&(c=d[1].split(";"));(d=b.get(a))||(d=new shaka.text.Cue(0,0,""));e=!1;for(let g=0;g<c.length;g++){const h=/^\s*([^:]+):\s*(.*)/.exec(c[g]);if(h){const k=h[1].trim(),l=h[2].trim().replace(";","");switch(k){case "background-color":case "background":e=
!0;d.backgroundColor=l;break;case "color":e=!0;d.color=l;break;case "font-family":e=!0;d.fontFamily=l;break;case "font-size":e=!0;d.fontSize=l;break;case "font-weight":if(parseInt(l,10)>=700||l=="bold")e=!0,d.fontWeight=shaka.text.Cue.fontWeight.BOLD;break;case "font-style":switch(l){case "normal":e=!0;d.fontStyle=shaka.text.Cue.fontStyle.NORMAL;break;case "italic":e=!0;d.fontStyle=shaka.text.Cue.fontStyle.ITALIC;break;case "oblique":e=!0,d.fontStyle=shaka.text.Cue.fontStyle.OBLIQUE}break;case "opacity":e=
!0;d.opacity=parseFloat(l);break;case "text-combine-upright":e=!0;d.textCombineUpright=l;break;case "text-shadow":e=!0;d.textShadow=l;break;case "white-space":e=!0;d.wrapLine=l!="noWrap";break;default:shaka.log.warning("VTT parser encountered an unsupported style: ",h)}}}e&&b.set(a,d)}}}static parseCue_(a,b,c,d){const e=shaka.text.VttTextParser;if(a.length==1&&!a[0]||shaka.text.VttTextParser.REGEX_NOTE_.test(a[0])||a[0]=="STYLE"||a[0]=="REGION")return null;let f=null,g=0;a[0].includes("--\x3e")||
(f=a[0],g=1);const h=new shaka.util.TextParser(a[g]);var k=h.parseTime(),l=h.readRegex(/[ \t]+--\x3e[ \t]+/g);let m=h.parseTime();if(k==null||l==null||m==null)return shaka.log.alwaysWarn("Failed to parse VTT time code. Cue skipped:",f,a),null;k+=b;m+=b;k<0&&(k=0);b="";for(l=g+1;l<a.length;l++)l>g+1&&(b+="\n"),b+=a[l];b=b.trim();d.has("global")?(a=d.get("global").clone(),a.startTime=k,a.endTime=m,a.payload=b):a=new shaka.text.Cue(k,m,b);h.skipWhitespace();for(k=h.readWord();k;)e.parseCueSetting(a,
k,c)||shaka.log.warning("VTT parser encountered an invalid VTT setting: ",k," The setting will be ignored."),h.skipWhitespace(),k=h.readWord();shaka.text.Cue.parseCuePayload(a,d);f!=null&&(a.id=f);return a}static parseCueSetting(a,b,c){const d=shaka.text.VttTextParser;let e;if(e=d.REGEX_ALIGN_.exec(b))d.setTextAlign_(a,e[1]);else if(e=d.REGEX_VERTICAL_.exec(b))d.setVerticalWritingMode_(a,e[1]);else if(e=d.REGEX_SIZE_.exec(b))a.size=Number(e[1]);else if(e=d.REGEX_POSITION_.exec(b))a.position=Number(e[1]),
e[2]&&d.setPositionAlign_(a,e[2]);else if(e=d.REGEX_REGION_.exec(b)){if(b=d.getRegionById_(c,e[1]))a.region=b}else return d.parsedLineValueAndInterpretation_(a,b);return!0}static getRegionById_(a,b){a=a.filter(c=>c.id==b);if(!a.length)return shaka.log.warning("VTT parser could not find a region with id: ",b," The region will be ignored."),null;goog.asserts.assert(a.length==1,"VTTRegion ids should be unique!");return a[0]}static parseRegionSetting_(a,b){let c;if(c=/^id=(.*)$/.exec(b))a.id=c[1];else if(c=
/^width=(\d{1,2}|100)%$/.exec(b))a.width=Number(c[1]);else if(c=/^lines=(\d+)$/.exec(b))a.height=Number(c[1]),a.heightUnits=shaka.text.CueRegion.units.LINES;else if(c=/^regionanchor=(\d{1,2}|100)%,(\d{1,2}|100)%$/.exec(b))a.regionAnchorX=Number(c[1]),a.regionAnchorY=Number(c[2]);else if(c=/^viewportanchor=(\d{1,2}|100)%,(\d{1,2}|100)%$/.exec(b))a.viewportAnchorX=Number(c[1]),a.viewportAnchorY=Number(c[2]);else if(/^scroll=up$/.exec(b))a.scroll=shaka.text.CueRegion.scrollMode.UP;else return!1;return!0}static setTextAlign_(a,
b){const c=shaka.text.Cue;b=="middle"?a.textAlign=c.textAlign.CENTER:(goog.asserts.assert(b.toUpperCase()in c.textAlign,b.toUpperCase()+" Should be in Cue.textAlign values!"),a.textAlign=c.textAlign[b.toUpperCase()])}static setPositionAlign_(a,b){const c=shaka.text.Cue;a.positionAlign=b=="line-left"||b=="start"?c.positionAlign.LEFT:b=="line-right"||b=="end"?c.positionAlign.RIGHT:b=="center"||b=="middle"?c.positionAlign.CENTER:c.positionAlign.AUTO}static setVerticalWritingMode_(a,b){const c=shaka.text.Cue;
a.writingMode=b=="lr"?c.writingMode.VERTICAL_LEFT_TO_RIGHT:c.writingMode.VERTICAL_RIGHT_TO_LEFT}static parsedLineValueAndInterpretation_(a,b){const c=shaka.text.Cue;let d;if(d=shaka.text.VttTextParser.REGEX_LINE_PCT_.exec(b))a.lineInterpretation=c.lineInterpretation.PERCENTAGE,a.line=Number(d[1]),d[2]&&(goog.asserts.assert(d[2].toUpperCase()in c.lineAlign,d[2].toUpperCase()+" Should be in Cue.lineAlign values!"),a.lineAlign=c.lineAlign[d[2].toUpperCase()]);else if(d=shaka.text.VttTextParser.REGEX_LINE_NUM_.exec(b))a.lineInterpretation=
c.lineInterpretation.LINE_NUMBER,a.line=Number(d[1]),d[2]&&(goog.asserts.assert(d[2].toUpperCase()in c.lineAlign,d[2].toUpperCase()+" Should be in Cue.lineAlign values!"),a.lineAlign=c.lineAlign[d[2].toUpperCase()]);else return!1;return!0}};goog.exportSymbol("shaka.text.VttTextParser",shaka.text.VttTextParser);goog.exportProperty(shaka.text.VttTextParser.prototype,"parseMedia",shaka.text.VttTextParser.prototype.parseMedia);goog.exportProperty(shaka.text.VttTextParser.prototype,"setManifestType",shaka.text.VttTextParser.prototype.setManifestType);
goog.exportProperty(shaka.text.VttTextParser.prototype,"setSequenceMode",shaka.text.VttTextParser.prototype.setSequenceMode);goog.exportProperty(shaka.text.VttTextParser.prototype,"parseInit",shaka.text.VttTextParser.prototype.parseInit);shaka.text.VttTextParser.MPEG_TIMESCALE_=9E4;shaka.text.VttTextParser.TS_ROLLOVER_=8589934592;shaka.text.VttTextParser.REGEX_NOTE_=/^NOTE($|[ \t])/;shaka.text.VttTextParser.REGEX_ALIGN_=/^align:(start|middle|center|end|left|right)$/;
shaka.text.VttTextParser.REGEX_VERTICAL_=/^vertical:(lr|rl)$/;shaka.text.VttTextParser.REGEX_SIZE_=/^size:([\d.]+)%$/;shaka.text.VttTextParser.REGEX_POSITION_=/^position:([\d.]+)%(?:,(line-left|line-right|middle|center|start|end|auto))?$/;shaka.text.VttTextParser.REGEX_REGION_=/^region:(.*)$/;shaka.text.VttTextParser.REGEX_LINE_PCT_=/^line:([\d.]+)%(?:,(start|end|center))?$/;shaka.text.VttTextParser.REGEX_LINE_NUM_=/^line:(-?\d+)(?:,(start|end|center))?$/;
shaka.text.TextEngine.registerParser("text/vtt",()=>new shaka.text.VttTextParser);shaka.text.TextEngine.registerParser('text/vtt; codecs="vtt"',()=>new shaka.text.VttTextParser);shaka.text.TextEngine.registerParser('text/vtt; codecs="wvtt"',()=>new shaka.text.VttTextParser);shaka.text.Mp4VttParser=class{constructor(){this.timescale_=null}parseInit(a){const b=shaka.util.Mp4Parser;let c=!1;(new b).boxes(["moov","trak","mdia","minf","stbl"],b.children).fullBox("mdhd",d=>{goog.asserts.assert(d.version==0||d.version==1,"MDHD version can only be 0 or 1");this.timescale_=shaka.util.Mp4BoxParsers.parseMDHD(d.reader,d.version).timescale}).fullBox("stsd",b.sampleDescription).box("wvtt",d=>{c=!0}).parse(a);if(!this.timescale_)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_MP4_VTT);if(!c)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_MP4_VTT);}setSequenceMode(a){}setManifestType(a){}parseMedia(a,b){if(!a.length)return[];if(!this.timescale_)throw shaka.log.error("No init segment for MP4+VTT!"),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_MP4_VTT);var c=shaka.util.Mp4Parser;
let d=0,e=[],f;const g=[];let h=!1,k=!1,l=!1,m=null;(new c).boxes(["moof","traf"],c.children).fullBox("tfdt",p=>{h=!0;goog.asserts.assert(p.version==0||p.version==1,"TFDT version can only be 0 or 1");d=shaka.util.Mp4BoxParsers.parseTFDTInaccurate(p.reader,p.version).baseMediaDecodeTime}).fullBox("tfhd",p=>{goog.asserts.assert(p.flags!=null,"A TFHD box should have a valid flags value");m=shaka.util.Mp4BoxParsers.parseTFHD(p.reader,p.flags).defaultSampleDuration}).fullBox("trun",p=>{k=!0;goog.asserts.assert(p.version!=
null,"A TRUN box should have a valid version value");goog.asserts.assert(p.flags!=null,"A TRUN box should have a valid flags value");e=shaka.util.Mp4BoxParsers.parseTRUN(p.reader,p.version,p.flags).sampleData}).box("mdat",c.allData(p=>{goog.asserts.assert(!l,"VTT cues in mp4 with multiple MDAT are not currently supported");l=!0;f=p},!1)).parse(a,!1);if(!l&&!h&&!k)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_MP4_VTT);a=d;
c=new shaka.util.DataViewReader(f,shaka.util.DataViewReader.Endianness.BIG_ENDIAN);for(const p of e){const r=p.sampleDuration||m,t=p.sampleCompositionTimeOffset?d+p.sampleCompositionTimeOffset:a;a=t+(r||0);let u=0;do{var n=c.readUint32();u+=n;var q=c.readUint32();q=shaka.util.Mp4Parser.typeToString(q);let v=null;q=="vttc"?n>8&&(v=c.readBytes(n-8,!1)):(q!="vtte"&&shaka.log.error("Unknown box "+q+"! Skipping!"),c.skip(n-8));r?v&&(goog.asserts.assert(this.timescale_!=null,"Timescale should not be null!"),
n=shaka.text.Mp4VttParser.parseVTTC_(v,b.periodStart+t/this.timescale_,b.periodStart+a/this.timescale_),g.push(n)):shaka.log.error("WVTT sample duration unknown, and no default found!");goog.asserts.assert(!p.sampleSize||u<=p.sampleSize,"The samples do not fit evenly into the sample sizes given in the TRUN box!")}while(p.sampleSize&&u<p.sampleSize)}goog.asserts.assert(!c.hasMoreData(),"MDAT which contain VTT cues and non-VTT data are not currently supported!");return g.filter(shaka.util.Functional.isNotNull)}static parseVTTC_(a,
b,c){let d,e,f;(new shaka.util.Mp4Parser).box("payl",shaka.util.Mp4Parser.allData(g=>{d=shaka.util.StringUtils.fromUTF8(g)},!1)).box("iden",shaka.util.Mp4Parser.allData(g=>{e=shaka.util.StringUtils.fromUTF8(g)},!1)).box("sttg",shaka.util.Mp4Parser.allData(g=>{f=shaka.util.StringUtils.fromUTF8(g)},!1)).parse(a);return d?shaka.text.Mp4VttParser.assembleCue_(d,e,f,b,c):null}static assembleCue_(a,b,c,d,e){a=new shaka.text.Cue(d,e,a);shaka.text.Cue.parseCuePayload(a);b&&(a.id=b);if(c)for(b=new shaka.util.TextParser(c),
c=b.readWord();c;)shaka.text.VttTextParser.parseCueSetting(a,c,[])||shaka.log.warning("VTT parser encountered an invalid VTT setting: ",c," The setting will be ignored."),b.skipWhitespace(),c=b.readWord();return a}};goog.exportSymbol("shaka.text.Mp4VttParser",shaka.text.Mp4VttParser);goog.exportProperty(shaka.text.Mp4VttParser.prototype,"parseMedia",shaka.text.Mp4VttParser.prototype.parseMedia);goog.exportProperty(shaka.text.Mp4VttParser.prototype,"setManifestType",shaka.text.Mp4VttParser.prototype.setManifestType);
goog.exportProperty(shaka.text.Mp4VttParser.prototype,"setSequenceMode",shaka.text.Mp4VttParser.prototype.setSequenceMode);goog.exportProperty(shaka.text.Mp4VttParser.prototype,"parseInit",shaka.text.Mp4VttParser.prototype.parseInit);shaka.text.TextEngine.registerParser('application/mp4; codecs="wvtt"',()=>new shaka.text.Mp4VttParser);shaka.text.SbvTextParser=class{parseInit(a){goog.asserts.assert(!1,"SubViewer does not have init segments")}setSequenceMode(a){}setManifestType(a){}parseMedia(a,b){b=shaka.util.StringUtils.fromUTF8(a).replace(/\r+/g,"");b=b.trim();a=[];if(b=="")return a;b=b.split("\n\n");for(const e of b){var c=e.split("\n"),d=new shaka.util.TextParser(c[0]);b=d.parseTime();const f=d.readRegex(/,/g);d=d.parseTime();if(b==null||f==null||d==null)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,
shaka.util.Error.Code.INVALID_TEXT_CUE,"Could not parse cue time range in SubViewer");c=c.slice(1).join("\n").trim();b=new shaka.text.Cue(b,d,c);a.push(b)}return a}};goog.exportSymbol("shaka.text.SbvTextParser",shaka.text.SbvTextParser);goog.exportProperty(shaka.text.SbvTextParser.prototype,"parseMedia",shaka.text.SbvTextParser.prototype.parseMedia);goog.exportProperty(shaka.text.SbvTextParser.prototype,"setManifestType",shaka.text.SbvTextParser.prototype.setManifestType);
goog.exportProperty(shaka.text.SbvTextParser.prototype,"setSequenceMode",shaka.text.SbvTextParser.prototype.setSequenceMode);goog.exportProperty(shaka.text.SbvTextParser.prototype,"parseInit",shaka.text.SbvTextParser.prototype.parseInit);shaka.text.TextEngine.registerParser("text/x-subviewer",()=>new shaka.text.SbvTextParser);shaka.text.SrtTextParser=class{constructor(){this.parser_=new shaka.text.VttTextParser}parseInit(a){goog.asserts.assert(!1,"SRT does not have init segments")}setSequenceMode(a){}setManifestType(a){}parseMedia(a,b,c){var d=shaka.util.BufferUtils;const e=shaka.util.StringUtils;a=e.fromUTF8(a);a=this.srt2webvtt_(a);d=d.toUint8(e.toUTF8(a));return this.parser_.parseMedia(d,b,c,[])}srt2webvtt_(a){let b="WEBVTT\n\n";if(a=="")return b;a=a.replace(/\r+/g,"");a=a.trim();a=a.split("\n\n");for(const c of a)b+=
this.convertSrtCue_(c);return b}convertSrtCue_(a){a=a.split(/\n/);a[0].match(/\d+/)&&a.shift();a[0]=a[0].replace(/,/g,".");return a.join("\n").replace(/{b}/g,"<b>").replace(/{\/b}/g,"</b>").replace(/{i}/g,"<i>").replace(/{\/i}/g,"</i>").replace(/{u}/g,"<u>").replace(/{\/u}/g,"</u>")+"\n\n"}};goog.exportSymbol("shaka.text.SrtTextParser",shaka.text.SrtTextParser);goog.exportProperty(shaka.text.SrtTextParser.prototype,"parseMedia",shaka.text.SrtTextParser.prototype.parseMedia);
goog.exportProperty(shaka.text.SrtTextParser.prototype,"setManifestType",shaka.text.SrtTextParser.prototype.setManifestType);goog.exportProperty(shaka.text.SrtTextParser.prototype,"setSequenceMode",shaka.text.SrtTextParser.prototype.setSequenceMode);goog.exportProperty(shaka.text.SrtTextParser.prototype,"parseInit",shaka.text.SrtTextParser.prototype.parseInit);shaka.text.TextEngine.registerParser("text/srt",()=>new shaka.text.SrtTextParser);shaka.text.SsaTextParser=class{parseInit(a){goog.asserts.assert(!1,"SSA does not have init segments")}setSequenceMode(a){}setManifestType(a){}parseMedia(a,b){b=shaka.text.SsaTextParser;var c="",d="",e=null,f=null;a=shaka.util.StringUtils.fromUTF8(a).split(/\r?\n\s*\r?\n/);for(var g of a){f=g;if(a=b.ssaContent_.exec(g))e=a[1],f=a[2];e=="V4 Styles"||e=="V4+ Styles"?(c=f,c=d?c+("\n"+f):f):e=="Events"?d=d?d+("\n"+f):f:e!="Script Info"&&shaka.log.warning("SsaTextParser parser encountered an unknown part.",
f)}g=[];e=null;c=c.split(/\r?\n/);for(var h of c){if(/^\s*;/.test(h))continue;if(a=b.lineParts_.exec(h))if(c=a[1].trim(),a=a[2].trim(),c=="Format")e=a.split(b.valuesFormat_);else if(c=="Style"){c=a.split(b.valuesFormat_);a={};for(f=0;f<e.length&&f<c.length;f++)a[e[f]]=c[f];g.push(a)}}h=[];e=null;d=d.split(/\r?\n/);for(const k of d){if(/^\s*;/.test(k))continue;if(c=b.lineParts_.exec(k))if(d=c[1].trim(),c=c[2].trim(),d=="Format")e=c.split(b.valuesFormat_);else if(d=="Dialogue"){c=c.split(b.valuesFormat_);
d={};for(a=0;a<e.length&&a<c.length;a++)d[e[a]]=c[a];a=b.parseTime_(d.Start);f=b.parseTime_(d.End);c=c.slice(e.length-1).join(",").replace(/\\N/g,"\n").replace(/\{[^}]+\}/g,"");c=new shaka.text.Cue(a,f,c);const l=d.Style;(d=g.find(m=>m.Name==l))&&b.addStyle_(c,d);h.push(c)}}return h}static addStyle_(a,b){const c=shaka.text.Cue;var d=shaka.text.SsaTextParser,e=b.Fontname;e&&(a.fontFamily=e);if(e=b.Fontsize)a.fontSize=e+"px";if(e=b.PrimaryColour)if(e=d.parseSsaColor_(e))a.color=e;if(e=b.BackColour)if(d=
d.parseSsaColor_(e))a.backgroundColor=d;b.Bold&&(a.fontWeight=c.fontWeight.BOLD);b.Italic&&(a.fontStyle=c.fontStyle.ITALIC);b.Underline&&a.textDecoration.push(c.textDecoration.UNDERLINE);if(d=b.Spacing)a.letterSpacing=d+"px";if(d=b.Alignment)switch(parseInt(d,10)){case 1:a.displayAlign=c.displayAlign.AFTER;a.textAlign=c.textAlign.START;break;case 2:a.displayAlign=c.displayAlign.AFTER;a.textAlign=c.textAlign.CENTER;break;case 3:a.displayAlign=c.displayAlign.AFTER;a.textAlign=c.textAlign.END;break;
case 5:a.displayAlign=c.displayAlign.BEFORE;a.textAlign=c.textAlign.START;break;case 6:a.displayAlign=c.displayAlign.BEFORE;a.textAlign=c.textAlign.CENTER;break;case 7:a.displayAlign=c.displayAlign.BEFORE;a.textAlign=c.textAlign.END;break;case 9:a.displayAlign=c.displayAlign.CENTER;a.textAlign=c.textAlign.START;break;case 10:a.displayAlign=c.displayAlign.CENTER;a.textAlign=c.textAlign.CENTER;break;case 11:a.displayAlign=c.displayAlign.CENTER,a.textAlign=c.textAlign.END}if(b=b.AlphaLevel)a.opacity=
parseFloat(b)}static parseSsaColor_(a){a=parseInt(a.replace("&H",""),16);return a>=0?"rgba("+(a&255)+","+(a>>8&255)+","+(a>>16&255)+","+(a>>24&255^255)/255+")":null}static parseTime_(a){var b=shaka.text.SsaTextParser.timeFormat_.exec(a);a=b[1]?parseInt(b[1].replace(":",""),10):0;const c=parseInt(b[2],10);b=parseFloat(b[3]);return a*3600+c*60+b}};goog.exportSymbol("shaka.text.SsaTextParser",shaka.text.SsaTextParser);goog.exportProperty(shaka.text.SsaTextParser.prototype,"parseMedia",shaka.text.SsaTextParser.prototype.parseMedia);
goog.exportProperty(shaka.text.SsaTextParser.prototype,"setManifestType",shaka.text.SsaTextParser.prototype.setManifestType);goog.exportProperty(shaka.text.SsaTextParser.prototype,"setSequenceMode",shaka.text.SsaTextParser.prototype.setSequenceMode);goog.exportProperty(shaka.text.SsaTextParser.prototype,"parseInit",shaka.text.SsaTextParser.prototype.parseInit);shaka.text.SsaTextParser.ssaContent_=/^\s*\[([^\]]+)\]\r?\n([\s\S]*)/;shaka.text.SsaTextParser.lineParts_=/^\s*([^:]+):\s*(.*)/;
shaka.text.SsaTextParser.valuesFormat_=/\s*,\s*/;shaka.text.SsaTextParser.timeFormat_=/^(\d+:)?(\d{1,2}):(\d{1,2}(?:[.]\d{1,3})?)?$/;shaka.text.TextEngine.registerParser("text/x-ssa",()=>new shaka.text.SsaTextParser);shaka.transmuxer.ADTS=class{static parseHeader(a,b){const c=shaka.transmuxer.ADTS,d=c.getHeaderLength(a,b);return b+d<=a.length&&(a=c.getFullFrameLength(a,b)-d,a>0)?{headerLength:d,frameLength:a}:null}static parseInfo(a,b){const c=[96E3,88200,64E3,48E3,44100,32E3,24E3,22050,16E3,12E3,11025,8E3,7350],d=(a[b+2]&60)>>>2;if(d>c.length-1)return null;const e=((a[b+2]&192)>>>6)+1;let f=(a[b+2]&1)<<2;f|=(a[b+3]&192)>>>6;return{sampleRate:c[d],channelCount:f,codec:"mp4a.40."+e}}static isHeaderPattern(a,b){return a[b]===
255&&(a[b+1]&246)===240}static getHeaderLength(a,b){return a[b+1]&1?7:9}static getFullFrameLength(a,b){return(a[b+3]&3)<<11|a[b+4]<<3|(a[b+5]&224)>>>5}static isHeader(a,b){const c=shaka.transmuxer.ADTS;return b+1<a.length&&c.isHeaderPattern(a,b)}static probe(a,b){const c=shaka.transmuxer.ADTS;if(c.isHeader(a,b)){const d=c.getHeaderLength(a,b);if(b+d>=a.length)return!1;const e=c.getFullFrameLength(a,b);if(e<=d)return!1;b+=e;return b===a.length||c.isHeader(a,b)}return!1}static getFrameDuration(a){return shaka.transmuxer.ADTS.AAC_SAMPLES_PER_FRAME*
9E4/a}static getSilentFrame(a,b){switch(a){case "mp4a.40.2":if(b===1)return new Uint8Array([0,200,0,128,35,128]);if(b===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(b===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(b===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(b===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(b===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,
4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(b===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(b===2||b===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}return null}};
shaka.transmuxer.ADTS.AAC_SAMPLES_PER_FRAME=1024;shaka.transmuxer.TransmuxerUtils=class{};shaka.transmuxer.TransmuxerUtils.AUDIO_SAMPLE_FLAGS=Object.freeze({isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:2,isNonSync:0});shaka.transmuxer.TransmuxerUtils.VIDEO_KEYFRAME_FLAGS=Object.freeze({isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:2,isNonSync:0});shaka.transmuxer.TransmuxerUtils.VIDEO_NON_KEYFRAME_FLAGS=Object.freeze({isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1,isNonSync:1});shaka.transmuxer.AacTransmuxer=class{constructor(a){this.originalMimeType_=a;this.frameIndex_=0;this.initSegments=new Map;this.lastInitSegment_=null}destroy(){this.initSegments.clear()}isSupported(a,b){b=shaka.media.Capabilities;return this.isAacContainer_(a)?b.isTypeSupported(this.convertCodecs(shaka.util.ManifestParserUtils.ContentType.AUDIO,a)):!1}isAacContainer_(a){return a.toLowerCase().split(";")[0]=="audio/aac"}convertCodecs(a,b){return this.isAacContainer_(b)?`audio/mp4; codecs="${shaka.util.MimeUtils.getCodecs(b)||
"mp4a.40.2"}"`:b}getOriginalMimeType(){return this.originalMimeType_}transmux(a,b,c,d){var e=shaka.transmuxer.ADTS;const f=shaka.util.BufferUtils.toUint8(a);var g=shaka.util.Id3Utils.getID3Data(f);let h=g.length;for(;h<f.length&&!e.probe(f,h);h++);a=c.endTime*1E3;g=shaka.util.Id3Utils.getID3Frames(g);g.length&&c&&(g=g.find(l=>l.description==="com.apple.streaming.transportStreamTimestamp"))&&(a=g.data);g=e.parseInfo(f,h);if(!g)return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,c?c.getUris()[0]:null));b.audioSamplingRate=g.sampleRate;b.channelsCount=g.channelCount;const k=[];for(;h<f.length;){const l=e.parseHeader(f,h);if(!l)return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,c?c.getUris()[0]:null));const m=l.headerLength+l.frameLength;if(h+m<=f.length){const n=f.subarray(h+l.headerLength,h+m);k.push({data:n,
size:l.frameLength,duration:e.AAC_SAMPLES_PER_FRAME,cts:0,flags:shaka.transmuxer.TransmuxerUtils.AUDIO_SAMPLE_FLAGS})}h+=m}e=g.sampleRate;a=Math.floor(a*e/1E3);d={id:b.id,type:shaka.util.ManifestParserUtils.ContentType.AUDIO,codecs:g.codec,timescale:e,duration:d,videoNalus:[],audioConfig:new Uint8Array([]),videoConfig:new Uint8Array([]),hSpacing:0,vSpacing:0,data:{sequenceNumber:this.frameIndex_,baseMediaDecodeTime:a,samples:k},stream:b};d=new shaka.util.Mp4Generator([d]);c=b.id+"_"+c.discontinuitySequence;
this.initSegments.has(c)?b=this.initSegments.get(c):(b=d.initSegment(),this.initSegments.set(c,b));c=this.lastInitSegment_!==b;d=d.segmentData();this.lastInitSegment_=b;this.frameIndex_++;return Promise.resolve({data:d,init:c?b:null})}};goog.exportSymbol("shaka.transmuxer.AacTransmuxer",shaka.transmuxer.AacTransmuxer);goog.exportProperty(shaka.transmuxer.AacTransmuxer.prototype,"transmux",shaka.transmuxer.AacTransmuxer.prototype.transmux);
goog.exportProperty(shaka.transmuxer.AacTransmuxer.prototype,"getOriginalMimeType",shaka.transmuxer.AacTransmuxer.prototype.getOriginalMimeType);goog.exportProperty(shaka.transmuxer.AacTransmuxer.prototype,"convertCodecs",shaka.transmuxer.AacTransmuxer.prototype.convertCodecs);goog.exportProperty(shaka.transmuxer.AacTransmuxer.prototype,"isSupported",shaka.transmuxer.AacTransmuxer.prototype.isSupported);goog.exportProperty(shaka.transmuxer.AacTransmuxer.prototype,"destroy",shaka.transmuxer.AacTransmuxer.prototype.destroy);
shaka.transmuxer.TransmuxerEngine.registerTransmuxer("audio/aac",()=>new shaka.transmuxer.AacTransmuxer("audio/aac"),shaka.transmuxer.TransmuxerEngine.PluginPriority.FALLBACK);shaka.transmuxer.Ac3=class{static parseFrame(a,b,c){if(b+8>a.length||a[b]!==11||a[b+1]!==119)return!1;const d=a[b+4]>>6;if(d>=3)return!1;const e=a[b+4]&63,f=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,
1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][e*3+d]*2;if(b+f>a.length)return!1;const g=a[b+6]>>5;var h=0;g===2?h+=2:(g&1&&g!==1&&(h+=2),g&4&&(h+=2));h=(a[b+6]<<8|a[b+7])>>12-h&1;const k=a[b+5]&7;a=new Uint8Array([d<<6|a[b+5]>>3<<1|k>>2,(k&3)<<6|g<<3|h<<2|e>>4,e<<4&224]);c.sampleRate=[48E3,44100,32E3][d];c.channelCount=[2,1,2,3,3,4,4,5][g]+h;c.audioConfig=a;c.frameLength=f;return!0}static probe(a,b){if(a[b]===11&&a[b+1]===
119){let d=0,e=5;b+=e;let f;for(;e>0;){f=a[b];const g=Math.min(e,8),h=8-g;var c=4278190080>>>24+h<<h;c=(f&c)>>h;d=d?d<<g|c:c;b+=1;e-=g}if(d<16)return!0}return!1}};shaka.transmuxer.Ac3.AC3_SAMPLES_PER_FRAME=1536;shaka.transmuxer.Ac3Transmuxer=class{constructor(a){this.originalMimeType_=a;this.frameIndex_=0;this.initSegments=new Map;this.lastInitSegment_=null}destroy(){this.initSegments.clear()}isSupported(a,b){b=shaka.media.Capabilities;return this.isAc3Container_(a)?b.isTypeSupported(this.convertCodecs(shaka.util.ManifestParserUtils.ContentType.AUDIO,a)):!1}isAc3Container_(a){return a.toLowerCase().split(";")[0]=="audio/ac3"}convertCodecs(a,b){return this.isAc3Container_(b)?shaka.device.DeviceFactory.getDevice().requiresEC3InitSegments()?
'audio/mp4; codecs="ec-3"':'audio/mp4; codecs="ac-3"':b}getOriginalMimeType(){return this.originalMimeType_}transmux(a,b,c,d){var e=shaka.transmuxer.Ac3;a=shaka.util.BufferUtils.toUint8(a);var f=shaka.util.Id3Utils.getID3Data(a);let g=f.length;for(;g<a.length&&!e.probe(a,g);g++);let h=c.endTime*1E3;f=shaka.util.Id3Utils.getID3Frames(f);f.length&&c&&(f=f.find(n=>n.description==="com.apple.streaming.transportStreamTimestamp"))&&(h=f.data);f=0;let k=new Uint8Array([]);const l=[],m={sampleRate:0,channelCount:0,
audioConfig:new Uint8Array(0),frameLength:0};for(;g<a.length;){if(!e.parseFrame(a,g,m))return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,c?c.getUris()[0]:null));b.audioSamplingRate=m.sampleRate;b.channelsCount=m.channelCount;f=m.sampleRate;k=m.audioConfig;const n=a.subarray(g,g+m.frameLength);l.push({data:n,size:m.frameLength,duration:e.AC3_SAMPLES_PER_FRAME,cts:0,flags:shaka.transmuxer.TransmuxerUtils.AUDIO_SAMPLE_FLAGS});
g+=m.frameLength}e=Math.floor(h*f/1E3);d={id:b.id,type:shaka.util.ManifestParserUtils.ContentType.AUDIO,codecs:"ac-3",timescale:f,duration:d,videoNalus:[],audioConfig:k,videoConfig:new Uint8Array([]),hSpacing:0,vSpacing:0,data:{sequenceNumber:this.frameIndex_,baseMediaDecodeTime:e,samples:l},stream:b};d=new shaka.util.Mp4Generator([d]);c=b.id+"_"+c.discontinuitySequence;this.initSegments.has(c)?b=this.initSegments.get(c):(b=d.initSegment(),this.initSegments.set(c,b));c=this.lastInitSegment_!==b;d=
d.segmentData();this.lastInitSegment_=b;this.frameIndex_++;return Promise.resolve({data:d,init:c?b:null})}};goog.exportSymbol("shaka.transmuxer.Ac3Transmuxer",shaka.transmuxer.Ac3Transmuxer);goog.exportProperty(shaka.transmuxer.Ac3Transmuxer.prototype,"transmux",shaka.transmuxer.Ac3Transmuxer.prototype.transmux);goog.exportProperty(shaka.transmuxer.Ac3Transmuxer.prototype,"getOriginalMimeType",shaka.transmuxer.Ac3Transmuxer.prototype.getOriginalMimeType);
goog.exportProperty(shaka.transmuxer.Ac3Transmuxer.prototype,"convertCodecs",shaka.transmuxer.Ac3Transmuxer.prototype.convertCodecs);goog.exportProperty(shaka.transmuxer.Ac3Transmuxer.prototype,"isSupported",shaka.transmuxer.Ac3Transmuxer.prototype.isSupported);goog.exportProperty(shaka.transmuxer.Ac3Transmuxer.prototype,"destroy",shaka.transmuxer.Ac3Transmuxer.prototype.destroy);shaka.transmuxer.TransmuxerEngine.registerTransmuxer("audio/ac3",()=>new shaka.transmuxer.Ac3Transmuxer("audio/ac3"),shaka.transmuxer.TransmuxerEngine.PluginPriority.FALLBACK);shaka.transmuxer.Ec3=class{static parseFrame(a,b,c){if(b+8>a.length||!shaka.transmuxer.Ec3.probe(a,b))return!1;var d=new shaka.util.ExpGolomb(a.subarray(b+2));d.skipBits(2);d.skipBits(3);const e=d.readBits(11)+1<<1;var f=d.readBits(2);let g;f==3?(f=d.readBits(2),f=[24E3,22060,16E3][f],g=3):(f=[48E3,44100,32E3][f],g=d.readBits(2));const h=d.readBits(3),k=d.readBits(1);d=d.readBits(5);if(b+e>a.byteLength)return!1;a=Math.floor(e*f/([1,2,3,6][g]*16));a=new Uint8Array([(a&8160)>>5,(a&31)<<3,f<<6|d<<1|
0,0|h<<1|k<<0,0]);c.sampleRate=f;c.channelCount=[2,1,2,3,3,4,4,5][h]+k;c.audioConfig=a;c.frameLength=e;return!0}static probe(a,b){return(a[b]<<8|a[b+1]<<0)===2935?!0:!1}};shaka.transmuxer.Ec3.EC3_SAMPLES_PER_FRAME=1536;shaka.transmuxer.Ec3Transmuxer=class{constructor(a){this.originalMimeType_=a;this.frameIndex_=0;this.initSegments=new Map;this.lastInitSegment_=null}destroy(){this.initSegments.clear()}isSupported(a,b){b=shaka.media.Capabilities;return this.isEc3Container_(a)?b.isTypeSupported(this.convertCodecs(shaka.util.ManifestParserUtils.ContentType.AUDIO,a)):!1}isEc3Container_(a){return a.toLowerCase().split(";")[0]=="audio/ec3"}convertCodecs(a,b){return this.isEc3Container_(b)?'audio/mp4; codecs="ec-3"':b}getOriginalMimeType(){return this.originalMimeType_}transmux(a,
b,c,d){var e=shaka.transmuxer.Ec3;a=shaka.util.BufferUtils.toUint8(a);var f=shaka.util.Id3Utils.getID3Data(a);let g=f.length;for(;g<a.length&&!e.probe(a,g);g++);let h=c.endTime*1E3;f=shaka.util.Id3Utils.getID3Frames(f);f.length&&c&&(f=f.find(n=>n.description==="com.apple.streaming.transportStreamTimestamp"))&&(h=f.data);f=0;let k=new Uint8Array([]);const l=[],m={sampleRate:0,channelCount:0,audioConfig:new Uint8Array(0),frameLength:0};for(;g<a.length;){if(!e.parseFrame(a,g,m))return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,c?c.getUris()[0]:null));b.audioSamplingRate=m.sampleRate;b.channelsCount=m.channelCount;f=m.sampleRate;k=m.audioConfig;const n=a.subarray(g,g+m.frameLength);l.push({data:n,size:m.frameLength,duration:e.EC3_SAMPLES_PER_FRAME,cts:0,flags:shaka.transmuxer.TransmuxerUtils.AUDIO_SAMPLE_FLAGS});g+=m.frameLength}e=Math.floor(h*f/1E3);d={id:b.id,type:shaka.util.ManifestParserUtils.ContentType.AUDIO,codecs:"ec-3",timescale:f,duration:d,
videoNalus:[],audioConfig:k,videoConfig:new Uint8Array([]),hSpacing:0,vSpacing:0,data:{sequenceNumber:this.frameIndex_,baseMediaDecodeTime:e,samples:l},stream:b};d=new shaka.util.Mp4Generator([d]);c=b.id+"_"+c.discontinuitySequence;this.initSegments.has(c)?b=this.initSegments.get(c):(b=d.initSegment(),this.initSegments.set(c,b));c=this.lastInitSegment_!==b;d=d.segmentData();this.lastInitSegment_=b;this.frameIndex_++;return Promise.resolve({data:d,init:c?b:null})}};
goog.exportSymbol("shaka.transmuxer.Ec3Transmuxer",shaka.transmuxer.Ec3Transmuxer);goog.exportProperty(shaka.transmuxer.Ec3Transmuxer.prototype,"transmux",shaka.transmuxer.Ec3Transmuxer.prototype.transmux);goog.exportProperty(shaka.transmuxer.Ec3Transmuxer.prototype,"getOriginalMimeType",shaka.transmuxer.Ec3Transmuxer.prototype.getOriginalMimeType);goog.exportProperty(shaka.transmuxer.Ec3Transmuxer.prototype,"convertCodecs",shaka.transmuxer.Ec3Transmuxer.prototype.convertCodecs);
goog.exportProperty(shaka.transmuxer.Ec3Transmuxer.prototype,"isSupported",shaka.transmuxer.Ec3Transmuxer.prototype.isSupported);goog.exportProperty(shaka.transmuxer.Ec3Transmuxer.prototype,"destroy",shaka.transmuxer.Ec3Transmuxer.prototype.destroy);shaka.transmuxer.TransmuxerEngine.registerTransmuxer("audio/ec3",()=>new shaka.transmuxer.Ec3Transmuxer("audio/ec3"),shaka.transmuxer.TransmuxerEngine.PluginPriority.FALLBACK);shaka.transmuxer.H264=class{static parseInfo(a){const b=shaka.transmuxer.H264;if(!a.length)return null;var c=a.find(p=>p.type==b.NALU_TYPE_SPS_);a=a.find(p=>p.type==b.NALU_TYPE_PPS_);if(!c||!a)return null;var d=new shaka.util.ExpGolomb(c.data),e=d.readUnsignedByte();d.readUnsignedByte();d.readUnsignedByte();d.skipExpGolomb();if(b.PROFILES_WITH_OPTIONAL_SPS_DATA_.includes(e)&&(e=d.readUnsignedExpGolomb(),e===3&&d.skipBits(1),d.skipExpGolomb(),d.skipExpGolomb(),d.skipBits(1),d.readBoolean())){e=e!==
3?8:12;for(var f=0;f<e;f++)d.readBoolean()&&(f<6?d.skipScalingList(16):d.skipScalingList(64))}d.skipExpGolomb();e=d.readUnsignedExpGolomb();if(e===0)d.readUnsignedExpGolomb();else if(e===1)for(d.skipBits(1),d.skipExpGolomb(),d.skipExpGolomb(),e=d.readUnsignedExpGolomb(),f=0;f<e;f++)d.skipExpGolomb();d.skipExpGolomb();d.skipBits(1);var g=d.readUnsignedExpGolomb(),h=d.readUnsignedExpGolomb(),k=d.readBits(1);k===0&&d.skipBits(1);d.skipBits(1);var l=0,m=0;let n=0,q=0;d.readBoolean()&&(l=d.readUnsignedExpGolomb(),
m=d.readUnsignedExpGolomb(),n=d.readUnsignedExpGolomb(),q=d.readUnsignedExpGolomb());f=e=1;if(d.readBoolean()&&d.readBoolean()){const p=d.readUnsignedByte(),r=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],t=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];p>0&&p<=16?(e=r[p-1],f=t[p-1]):p===255&&(e=d.readBits(16),f=d.readBits(16))}d=(2-k)*(h+1)*16-n*2-q*2;g=(g+1)*16-l*2-m*2;c=c.fullData;l=c.byteLength;a=a.fullData;m=a.byteLength;h=0;k=new Uint8Array(11+l+m);k[h++]=1;k[h++]=c[1];k[h++]=c[2];k[h++]=c[3];
k[h++]=255;k[h++]=225;k[h++]=l>>>8&255;k[h++]=l&255;k.set(c,h);h+=l;k[h++]=1;k[h++]=m>>>8&255;k[h++]=m&255;k.set(a,h);return{height:d,width:g,videoConfig:k,hSpacing:e,vSpacing:f}}static getVideoSamples(a){const b=shaka.transmuxer.H264,c=[];let d=null,e=!1;const f=()=>{if(d&&d.nalus.length&&d.frame){var m=d.nalus.length*4;for(var n of d.nalus)m+=n.fullData.byteLength;m=new Uint8Array(m);n=0;for(const q of d.nalus){const p=q.fullData.byteLength;m[n]=p>>24&255;m[n+1]=p>>16&255;m[n+2]=p>>8&255;m[n+3]=
p&255;m.set(q.fullData,n+4);n+=4+p}d.data=m;c.push(d)}},g=new Uint8Array(0),h=m=>{d={data:g,frame:!1,isKeyframe:!1,pts:m.pts,dts:m.dts,nalus:[]}};for(let m=0;m<a.length;m++){const n=a[m];var k=n.nalus;let q=!1;d&&k.length&&!e&&(f(),h(n));for(const p of n.nalus){k=!1;switch(p.type){case b.NALU_TYPE_NDR_:let r=!1;k=!0;var l=p.data;q&&l.length>4&&(l=(new shaka.util.ExpGolomb(l)).readSliceType(),l===2||l===4||l===7||l===9)&&(r=!0);r&&d&&d.frame&&!d.isKeyframe&&(f(),d=null);d||h(n);d.frame=!0;d.isKeyframe=
r;break;case b.NALU_TYPE_IDR_:k=!0;d&&d.frame&&!d.isKeyframe&&(f(),d=null);d||h(n);d.frame=!0;d.isKeyframe=!0;break;case b.NALU_TYPE_SEI_:k=!0;break;case b.NALU_TYPE_SPS_:q=k=!0;break;case b.NALU_TYPE_PPS_:k=!0;break;case b.NALU_TYPE_AUD_:e=k=!0;d&&d.frame&&(f(),d=null);d||h(n);break;case b.NALU_TYPE_FILLER_DATA_:k=!0;break;default:k=!1}d&&k&&d.nalus.push(p)}}f();return c}};shaka.transmuxer.H264.NALU_TYPE_NDR_=1;shaka.transmuxer.H264.NALU_TYPE_IDR_=5;shaka.transmuxer.H264.NALU_TYPE_SEI_=6;
shaka.transmuxer.H264.NALU_TYPE_SPS_=7;shaka.transmuxer.H264.NALU_TYPE_PPS_=8;shaka.transmuxer.H264.NALU_TYPE_AUD_=9;shaka.transmuxer.H264.NALU_TYPE_FILLER_DATA_=12;shaka.transmuxer.H264.PROFILES_WITH_OPTIONAL_SPS_DATA_=[100,110,122,244,44,83,86,118,128,138,139,134];shaka.transmuxer.H265=class{static parseInfo(a){const b=shaka.transmuxer.H265;if(!a.length)return null;var c=a.find(h=>h.type==b.NALU_TYPE_VPS_);const d=a.find(h=>h.type==b.NALU_TYPE_SPS_),e=a.find(h=>h.type==b.NALU_TYPE_PPS_);if(!c||!d||!e)return null;const f=b.parseVPS_(c.fullData);a=b.parseSPS_(d.fullData);const g=b.parsePPS_(e.fullData);c=b.getVideoConfiguration_(c.fullData,d.fullData,e.fullData,{numTemporalLayers:f.numTemporalLayers,temporalIdNested:f.temporalIdNested,generalProfileSpace:a.generalProfileSpace,
generalTierFlag:a.generalTierFlag,generalLevelIdc:a.generalLevelIdc,generalProfileIdc:a.generalProfileIdc,generalProfileCompatibilityFlags1:a.generalProfileCompatibilityFlags1,generalProfileCompatibilityFlags2:a.generalProfileCompatibilityFlags2,generalProfileCompatibilityFlags3:a.generalProfileCompatibilityFlags3,generalProfileCompatibilityFlags4:a.generalProfileCompatibilityFlags4,generalConstraintIndicatorFlags1:a.generalConstraintIndicatorFlags1,generalConstraintIndicatorFlags2:a.generalConstraintIndicatorFlags2,
generalConstraintIndicatorFlags3:a.generalConstraintIndicatorFlags3,generalConstraintIndicatorFlags4:a.generalConstraintIndicatorFlags4,generalConstraintIndicatorFlags5:a.generalConstraintIndicatorFlags5,generalConstraintIndicatorFlags6:a.generalConstraintIndicatorFlags6,minSpatialSegmentationIdc:a.minSpatialSegmentationIdc,chromaFormatIdc:a.chromaFormatIdc,bitDepthLumaMinus8:a.bitDepthLumaMinus8,bitDepthChromaMinus8:a.bitDepthChromaMinus8,parallelismType:g.parallelismType,frameRateFps:a.frameRateFps,
frameRateFixed:a.frameRateFixed});return{height:a.height,width:a.width,videoConfig:c,hSpacing:a.sarWidth,vSpacing:a.sarHeight}}static parseVPS_(a){var b=new shaka.util.ExpGolomb(a,!0);b.readUnsignedByte();b.readUnsignedByte();b.readBits(4);b.readBits(2);b.readBits(6);a=b.readBits(3);b=b.readBoolean();return{numTemporalLayers:a+1,temporalIdNested:b}}static parseSPS_(a){a=new shaka.util.ExpGolomb(a,!0);a.readUnsignedByte();a.readUnsignedByte();let b=0,c=0,d=0,e=0;a.readBits(4);const f=a.readBits(3);
a.readBoolean();const g=a.readBits(2),h=a.readBits(1),k=a.readBits(5),l=a.readUnsignedByte(),m=a.readUnsignedByte(),n=a.readUnsignedByte(),q=a.readUnsignedByte(),p=a.readUnsignedByte(),r=a.readUnsignedByte(),t=a.readUnsignedByte(),u=a.readUnsignedByte(),v=a.readUnsignedByte(),x=a.readUnsignedByte(),y=a.readUnsignedByte();var A=[],w=[];for(var z=0;z<f;z++)A.push(a.readBoolean()),w.push(a.readBoolean());if(f>0)for(z=f;z<8;z++)a.readBits(2);for(z=0;z<f;z++)A[z]&&a.readBits(88),w[z]&&a.readUnsignedByte();
a.readUnsignedExpGolomb();A=a.readUnsignedExpGolomb();A==3&&a.readBits(1);w=a.readUnsignedExpGolomb();z=a.readUnsignedExpGolomb();a.readBoolean()&&(b+=a.readUnsignedExpGolomb(),c+=a.readUnsignedExpGolomb(),d+=a.readUnsignedExpGolomb(),e+=a.readUnsignedExpGolomb());const B=a.readUnsignedExpGolomb(),C=a.readUnsignedExpGolomb();var F=a.readUnsignedExpGolomb();if(a.readBoolean())for(var H=0;H<=f;H++)a.readUnsignedExpGolomb(),a.readUnsignedExpGolomb(),a.readUnsignedExpGolomb();else a.readUnsignedExpGolomb(),
a.readUnsignedExpGolomb(),a.readUnsignedExpGolomb();a.readUnsignedExpGolomb();a.readUnsignedExpGolomb();a.readUnsignedExpGolomb();a.readUnsignedExpGolomb();a.readUnsignedExpGolomb();a.readUnsignedExpGolomb();if(a.readBoolean()&&a.readBoolean())for(H=0;H<4;H++)for(var I=0;I<(H===3?2:6);I++)if(a.readBoolean()){var D=Math.min(64,1<<4+(H<<1));H>1&&a.readExpGolomb();for(var J=0;J<D;J++)a.readExpGolomb()}else a.readUnsignedExpGolomb();a.readBoolean();a.readBoolean();a.readBoolean()&&(a.readUnsignedByte(),
a.readUnsignedExpGolomb(),a.readUnsignedExpGolomb(),a.readBoolean());H=a.readUnsignedExpGolomb();I=0;for(D=0;D<H;D++)if(J=!1,D!==0&&(J=a.readBoolean()),J){D===H&&a.readUnsignedExpGolomb();a.readBoolean();a.readUnsignedExpGolomb();J=0;for(var G=0;G<=I;G++){var E=a.readBoolean(),K=!1;E||(K=a.readBoolean());(E||K)&&J++}I=J}else{G=a.readUnsignedExpGolomb();J=a.readUnsignedExpGolomb();I=G+J;for(E=0;E<G;E++)a.readUnsignedExpGolomb(),a.readBoolean();for(G=0;G<J;G++)a.readUnsignedExpGolomb(),a.readBoolean()}if(a.readBoolean())for(H=
a.readUnsignedExpGolomb(),I=0;I<H;I++){for(D=0;D<F+4;D++)a.readBits(1);a.readBits(1)}H=F=1;I=!0;D=1;G=J=0;a.readBoolean();a.readBoolean();if(a.readBoolean()){if(a.readBoolean()){E=a.readUnsignedByte();K=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2];var L=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];E>0&&E<=16?(F=K[E-1],H=L[E-1]):E===255&&(F=a.readBits(16),H=a.readBits(16))}a.readBoolean()&&a.readBoolean();a.readBoolean()&&(a.readBits(3),a.readBoolean(),a.readBoolean()&&(a.readUnsignedByte(),a.readUnsignedByte(),
a.readUnsignedByte()));a.readBoolean()&&(a.readUnsignedExpGolomb(),a.readUnsignedExpGolomb());a.readBoolean();a.readBoolean();a.readBoolean();if(E=a.readBoolean())a.skipExpGolomb(),a.skipExpGolomb(),a.skipExpGolomb(),a.skipExpGolomb();if(a.readBoolean()&&(D=a.readBits(32),J=a.readBits(32),a.readBoolean()&&a.readUnsignedExpGolomb(),a.readBoolean())){L=!1;E=a.readBoolean();K=a.readBoolean();if(E||K){if(L=a.readBoolean())a.readUnsignedByte(),a.readBits(5),a.readBoolean(),a.readBits(5);a.readBits(4);
a.readBits(4);L&&a.readBits(4);a.readBits(5);a.readBits(5);a.readBits(5)}for(let N=0;N<=f;N++){I=a.readBoolean();var M=!0;let P=1;I||(M=a.readBoolean());let O=!1;M?a.readUnsignedExpGolomb():O=a.readBoolean();O||(P=a.readUnsignedExpGolomb()+1);if(E){for(M=0;M<P;M++)a.readUnsignedExpGolomb(),a.readUnsignedExpGolomb(),L&&(a.readUnsignedExpGolomb(),a.readUnsignedExpGolomb());a.readBoolean()}if(K){for(M=0;M<P;M++)a.readUnsignedExpGolomb(),a.readUnsignedExpGolomb(),L&&(a.readUnsignedExpGolomb(),a.readUnsignedExpGolomb());
a.readBoolean()}}}a.readBoolean()&&(a.readBoolean(),a.readBoolean(),a.readBoolean(),G=a.readUnsignedExpGolomb(),a.readUnsignedExpGolomb(),a.readUnsignedExpGolomb(),a.readUnsignedExpGolomb(),a.readUnsignedExpGolomb())}return{generalLevelIdc:y,generalProfileSpace:g,generalTierFlag:h,generalProfileIdc:k,generalProfileCompatibilityFlags1:l,generalProfileCompatibilityFlags2:m,generalProfileCompatibilityFlags3:n,generalProfileCompatibilityFlags4:q,generalConstraintIndicatorFlags1:p,generalConstraintIndicatorFlags2:r,
generalConstraintIndicatorFlags3:t,generalConstraintIndicatorFlags4:u,generalConstraintIndicatorFlags5:v,generalConstraintIndicatorFlags6:x,minSpatialSegmentationIdc:G,chromaFormatIdc:A,bitDepthLumaMinus8:B,bitDepthChromaMinus8:C,width:w-(b+c)*(A===1||A===2?2:1),height:z-(d+e)*(A===1?2:1),sarWidth:F,sarHeight:H,frameRateFps:J/D,frameRateFixed:I}}static parsePPS_(a){var b=new shaka.util.ExpGolomb(a,!0);b.readUnsignedByte();b.readUnsignedByte();b.readUnsignedExpGolomb();b.readUnsignedExpGolomb();b.readBoolean();
b.readBoolean();b.readBits(3);b.readBoolean();b.readBoolean();b.readUnsignedExpGolomb();b.readUnsignedExpGolomb();b.readExpGolomb();b.readBoolean();b.readBoolean();b.readBoolean()&&b.readUnsignedExpGolomb();b.readExpGolomb();b.readExpGolomb();b.readBoolean();b.readBoolean();b.readBoolean();b.readBoolean();a=b.readBoolean();b=b.readBoolean();let c=1;b&&a?c=0:b?c=3:a&&(c=2);return{parallelismType:c}}static getVideoConfiguration_(a,b,c,d){const e=new Uint8Array(23+(5+a.byteLength)+(5+b.byteLength)+(5+
c.byteLength));e[0]=1;e[1]=(d.generalProfileSpace&3)<<6|(d.generalTierFlag?1:0)<<5|d.generalProfileIdc&31;e[2]=d.generalProfileCompatibilityFlags1;e[3]=d.generalProfileCompatibilityFlags2;e[4]=d.generalProfileCompatibilityFlags3;e[5]=d.generalProfileCompatibilityFlags4;e[6]=d.generalConstraintIndicatorFlags1;e[7]=d.generalConstraintIndicatorFlags2;e[8]=d.generalConstraintIndicatorFlags3;e[9]=d.generalConstraintIndicatorFlags4;e[10]=d.generalConstraintIndicatorFlags5;e[11]=d.generalConstraintIndicatorFlags6;
e[12]=d.generalLevelIdc;e[13]=240|(d.minSpatialSegmentationIdc&3840)>>8;e[14]=d.minSpatialSegmentationIdc&255;e[15]=252|d.parallelismType&3;e[16]=252|d.chromaFormatIdc&3;e[17]=248|d.bitDepthLumaMinus8&7;e[18]=248|d.bitDepthChromaMinus8&7;e[19]=0;e[20]=parseInt(d.frameRateFps,10);e[21]=((d.frameRateFixed?1:0)&3)<<6|(d.numTemporalLayers&7)<<3|(d.temporalIdNested?1:0)<<2|3;e[22]=3;a=[a,b,c];b=23;c=a.length-1;for(d=0;d<a.length;d+=1)e.set(new Uint8Array([32+d|(d===c?128:0),0,1,a[d].byteLength>>8,a[d].byteLength&
255]),b),b+=5,e.set(a[d],b),b+=a[d].byteLength;return e}static parseFrame(a,b){var c=shaka.transmuxer.H265;let d=!1;var e=[],f=0;let g=!1;for(const h of a){switch(h.type){case c.NALU_TYPE_TRAIL_N_:case c.NALU_TYPE_TRAIL_R_:a=g=!0;break;case c.NALU_TYPE_IDR_W_RADL_:case c.NALU_TYPE_IDR_N_LP_:case c.NALU_TYPE_CRA_NUT_:d=a=g=!0;break;case c.NALU_TYPE_VPS_:case c.NALU_TYPE_SPS_:case c.NALU_TYPE_PPS_:a=!0;break;case c.NALU_TYPE_AUD_:g=a=!0;break;case c.NALU_TYPE_SEI_PREFIX_:case c.NALU_TYPE_SEI_SUFFIX_:a=
!0;break;default:a=!1}g&&a&&(e.push(h.fullData),f+=h.fullData.byteLength)}if(!e.length)return!1;f+=4*e.length;c=new Uint8Array(f);f=0;for(const h of e)e=h.byteLength,c[f]=e>>24&255,c[f+1]=e>>16&255,c[f+2]=e>>8&255,c[f+3]=e&255,c.set(h,f+4),f+=e+4;b.data=c;b.isKeyframe=d;return!0}};shaka.transmuxer.H265.NALU_TYPE_TRAIL_N_=1;shaka.transmuxer.H265.NALU_TYPE_TRAIL_R_=0;shaka.transmuxer.H265.NALU_TYPE_IDR_W_RADL_=19;shaka.transmuxer.H265.NALU_TYPE_IDR_N_LP_=20;
shaka.transmuxer.H265.NALU_TYPE_CRA_NUT_=21;shaka.transmuxer.H265.NALU_TYPE_VPS_=32;shaka.transmuxer.H265.NALU_TYPE_SPS_=33;shaka.transmuxer.H265.NALU_TYPE_PPS_=34;shaka.transmuxer.H265.NALU_TYPE_AUD_=35;shaka.transmuxer.H265.NALU_TYPE_SEI_PREFIX_=39;shaka.transmuxer.H265.NALU_TYPE_SEI_SUFFIX_=40;shaka.transmuxer.MpegAudio=class{static parseHeader(a,b){var c=shaka.transmuxer.MpegAudio,d=a[b+1]>>3&3;const e=a[b+1]>>1&3;var f=a[b+2]>>4&15,g=a[b+2]>>2&3;if(d!==1&&f!==0&&f!==15&&g!==3){const k=a[b+3]>>6;f=c.BITRATES_MAP_[(d===3?3-e:e===3?3:4)*14+f-1]*1E3;g=c.SAMPLING_RATE_MAP_[(d===3?0:d===2?1:2)*3+g];const l=k===3?1:2;d=c.SAMPLES_COEFFICIENTS_[d][e];var h=c.BYTES_IN_SLOT_[e];c=d*8*h;d=Math.floor(d*f/g+(a[b+2]>>1&1))*h;(h=(h=(navigator.userAgent||"").match(/Chrome\/(\d+)/i))?parseInt(h[1],10):
0)&&h<=87&&e===2&&f>=224E3&&k===0&&(a[b+3]|=128);return{sampleRate:g,channelCount:l,frameLength:d,samplesPerFrame:c}}return null}static isHeaderPattern(a,b){return a[b]===255&&(a[b+1]&224)===224&&(a[b+1]&6)!==0}static isHeader(a,b){return b+1<a.length&&shaka.transmuxer.MpegAudio.isHeaderPattern(a,b)}static probe(a,b){const c=shaka.transmuxer.MpegAudio;if(b+1<a.length&&c.isHeaderPattern(a,b)){const d=c.parseHeader(a,b);let e=4;d&&d.frameLength&&(e=d.frameLength);b+=e;return b===a.length||c.isHeader(a,
b)}return!1}};shaka.transmuxer.MpegAudio.BITRATES_MAP_=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160];shaka.transmuxer.MpegAudio.SAMPLING_RATE_MAP_=[44100,48E3,32E3,22050,24E3,16E3,11025,12E3,8E3];shaka.transmuxer.MpegAudio.SAMPLES_COEFFICIENTS_=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]];
shaka.transmuxer.MpegAudio.BYTES_IN_SLOT_=[0,1,1,4];shaka.transmuxer.MpegAudio.MPEG_AUDIO_SAMPLE_PER_FRAME=1152;shaka.transmuxer.Mp3Transmuxer=class{constructor(a){this.originalMimeType_=a;this.frameIndex_=0;this.initSegments=new Map;this.lastInitSegment_=null}destroy(){this.initSegments.clear()}isSupported(a,b){b=shaka.media.Capabilities;return this.isMpegContainer_(a)?b.isTypeSupported(this.convertCodecs(shaka.util.ManifestParserUtils.ContentType.AUDIO,a)):!1}isMpegContainer_(a){return a.toLowerCase().split(";")[0]=="audio/mpeg"}convertCodecs(a,b){return this.isMpegContainer_(b)?'audio/mp4; codecs="mp3"':
b}getOriginalMimeType(){return this.originalMimeType_}transmux(a,b,c,d){var e=shaka.transmuxer.MpegAudio;const f=shaka.util.BufferUtils.toUint8(a);let g=shaka.util.Id3Utils.getID3Data(f).length;for(;g<f.length&&!e.probe(f,g);g++);let h;for(a=[];g<f.length;){const k=e.parseHeader(f,g);if(!k)return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,c?c.getUris()[0]:null));h||=k;g+k.frameLength<=f.length&&a.push({data:f.subarray(g,
g+k.frameLength),size:k.frameLength,duration:e.MPEG_AUDIO_SAMPLE_PER_FRAME,cts:0,flags:shaka.transmuxer.TransmuxerUtils.AUDIO_SAMPLE_FLAGS});g+=k.frameLength}if(!h)return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,c?c.getUris()[0]:null));e=h.samplesPerFrame*9E4/h.sampleRate*this.frameIndex_;d={id:b.id,type:shaka.util.ManifestParserUtils.ContentType.AUDIO,codecs:"mp3",timescale:h.sampleRate,duration:d,
videoNalus:[],audioConfig:new Uint8Array([]),videoConfig:new Uint8Array([]),hSpacing:0,vSpacing:0,data:{sequenceNumber:this.frameIndex_,baseMediaDecodeTime:e,samples:a},stream:b};d=new shaka.util.Mp4Generator([d]);c=b.id+"_"+c.discontinuitySequence;this.initSegments.has(c)?b=this.initSegments.get(c):(b=d.initSegment(),this.initSegments.set(c,b));c=this.lastInitSegment_!==b;d=d.segmentData();this.lastInitSegment_=b;this.frameIndex_++;return Promise.resolve({data:d,init:c?b:null})}};
goog.exportSymbol("shaka.transmuxer.Mp3Transmuxer",shaka.transmuxer.Mp3Transmuxer);goog.exportProperty(shaka.transmuxer.Mp3Transmuxer.prototype,"transmux",shaka.transmuxer.Mp3Transmuxer.prototype.transmux);goog.exportProperty(shaka.transmuxer.Mp3Transmuxer.prototype,"getOriginalMimeType",shaka.transmuxer.Mp3Transmuxer.prototype.getOriginalMimeType);goog.exportProperty(shaka.transmuxer.Mp3Transmuxer.prototype,"convertCodecs",shaka.transmuxer.Mp3Transmuxer.prototype.convertCodecs);
goog.exportProperty(shaka.transmuxer.Mp3Transmuxer.prototype,"isSupported",shaka.transmuxer.Mp3Transmuxer.prototype.isSupported);goog.exportProperty(shaka.transmuxer.Mp3Transmuxer.prototype,"destroy",shaka.transmuxer.Mp3Transmuxer.prototype.destroy);shaka.transmuxer.TransmuxerEngine.registerTransmuxer("audio/mpeg",()=>new shaka.transmuxer.Mp3Transmuxer("audio/mpeg"),shaka.transmuxer.TransmuxerEngine.PluginPriority.FALLBACK);shaka.transmuxer.MpegTsTransmuxer=class{constructor(a){this.originalMimeType_=a;this.tsParser_=null}destroy(){}isSupported(a,b){b=shaka.media.Capabilities;if(!this.isTsContainer_(a))return!1;const c=shaka.util.ManifestParserUtils.ContentType,d=shaka.util.MimeUtils;var e=d.getCodecs(a),f=d.splitCodecs(e);e=shaka.util.ManifestParserUtils.guessCodecsSafe(c.AUDIO,f);f=shaka.util.ManifestParserUtils.guessCodecsSafe(c.VIDEO,f);return!e||f||d.getNormalizedCodec(e)!="mp3"?!1:b.isTypeSupported(this.convertCodecs(c.AUDIO,
a))}isTsContainer_(a){return a.toLowerCase().split(";")[0]=="video/mp2t"}convertCodecs(a,b){return this.isTsContainer_(b)?"audio/mpeg":b}getOriginalMimeType(){return this.originalMimeType_}transmux(a,b,c,d,e){b=shaka.transmuxer.MpegAudio;var f=shaka.util.ManifestParserUtils.ContentType;d=shaka.util.Uint8ArrayUtils;this.tsParser_?this.tsParser_.clearData():this.tsParser_=new shaka.util.TsParser;this.tsParser_.setDiscontinuitySequence(c.discontinuitySequence);a=shaka.util.BufferUtils.toUint8(a);a=this.tsParser_.parse(a);
if(a.getCodecs().audio!="mp3"||e!=f.AUDIO)return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,c?c.getUris()[0]:null));c=new Uint8Array([]);for(const g of a.getAudioData()){e=g.data;if(!e)continue;for(a=0;a<e.length;)(f=b.parseHeader(e,a))?(a+f.frameLength<=e.length&&(c=d.concat(c,e.subarray(a,a+f.frameLength))),a+=f.frameLength):a++}return Promise.resolve(c)}};
goog.exportSymbol("shaka.transmuxer.MpegTsTransmuxer",shaka.transmuxer.MpegTsTransmuxer);goog.exportProperty(shaka.transmuxer.MpegTsTransmuxer.prototype,"transmux",shaka.transmuxer.MpegTsTransmuxer.prototype.transmux);goog.exportProperty(shaka.transmuxer.MpegTsTransmuxer.prototype,"getOriginalMimeType",shaka.transmuxer.MpegTsTransmuxer.prototype.getOriginalMimeType);goog.exportProperty(shaka.transmuxer.MpegTsTransmuxer.prototype,"convertCodecs",shaka.transmuxer.MpegTsTransmuxer.prototype.convertCodecs);
goog.exportProperty(shaka.transmuxer.MpegTsTransmuxer.prototype,"isSupported",shaka.transmuxer.MpegTsTransmuxer.prototype.isSupported);goog.exportProperty(shaka.transmuxer.MpegTsTransmuxer.prototype,"destroy",shaka.transmuxer.MpegTsTransmuxer.prototype.destroy);shaka.transmuxer.TransmuxerEngine.registerTransmuxer("video/mp2t",()=>new shaka.transmuxer.MpegTsTransmuxer("video/mp2t"),shaka.transmuxer.TransmuxerEngine.PluginPriority.PREFERRED_SECONDARY);/*
 @license
 MSS Transmuxer
 Copyright 2015 Dash Industry Forum
 SPDX-License-Identifier: BSD-3-Clause
*/
shaka.transmuxer.MssTransmuxer=class{constructor(a){this.originalMimeType_=a;(this.isoBoxer_=shaka.dependencies.isoBoxer())&&this.addSpecificBoxProcessor_()}addSpecificBoxProcessor_(){this.isoBoxer_.addBoxProcessor("saio",function(){this._procFullBox();this.flags&1&&(this._procField("aux_info_type","uint",32),this._procField("aux_info_type_parameter","uint",32));this._procField("entry_count","uint",32);this._procFieldArray("offset",this.entry_count,"uint",this.version===1?64:32)});this.isoBoxer_.addBoxProcessor("saiz",
function(){this._procFullBox();this.flags&1&&(this._procField("aux_info_type","uint",32),this._procField("aux_info_type_parameter","uint",32));this._procField("default_sample_info_size","uint",8);this._procField("sample_count","uint",32);this.default_sample_info_size===0&&this._procFieldArray("sample_info_size",this.sample_count,"uint",8)});const a=function(){this._procFullBox();this.flags&1&&(this._procField("AlgorithmID","uint",24),this._procField("IV_size","uint",8),this._procFieldArray("KID",
16,"uint",8));this._procField("sample_count","uint",32);this._procEntries("entry",this.sample_count,function(b){this._procEntryField(b,"InitializationVector","data",8);this.flags&2&&(this._procEntryField(b,"NumberOfEntries","uint",16),this._procSubEntries(b,"clearAndCryptedData",b.NumberOfEntries,function(c){this._procEntryField(c,"BytesOfClearData","uint",16);this._procEntryField(c,"BytesOfEncryptedData","uint",32)}))})};this.isoBoxer_.addBoxProcessor("senc",a);this.isoBoxer_.addBoxProcessor("uuid",
function(){const b=shaka.transmuxer.MssTransmuxer;let c=!0;for(let d=0;d<16;d++)this.usertype[d]!==b.UUID_SENC_[d]&&(c=!1);c&&(this._parsing&&(this.type="sepiff"),a.call(this))})}destroy(){}isSupported(a,b){const c=shaka.media.Capabilities;var d=a.startsWith("mss/");if(!this.isoBoxer_||!d)return!1;if(b)return c.isTypeSupported(this.convertCodecs(b,a));d=shaka.util.ManifestParserUtils.ContentType;b=this.convertCodecs(d.AUDIO,a);a=this.convertCodecs(d.VIDEO,a);return c.isTypeSupported(b)||c.isTypeSupported(a)}convertCodecs(a,
b){return b.replace("mss/","")}getOriginalMimeType(){return this.originalMimeType_}transmux(a,b,c){if(!c)return Promise.resolve(shaka.util.BufferUtils.toUint8(a));if(!b.mssPrivateData)return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.MSS_MISSING_DATA_FOR_TRANSMUXING,c?c.getUris()[0]:null));try{const d=this.processMediaSegment_(a,b,c);return Promise.resolve(d)}catch(d){return d instanceof shaka.util.Error?Promise.reject(d):
Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.MSS_TRANSMUXING_FAILED,c?c.getUris()[0]:null))}}processMediaSegment_(a,b,c){a=this.isoBoxer_.parseBuffer(a);var d=a.fetch("tfhd");d.track_ID=b.id+1;var e=a.fetch("tfdt");var f=a.fetch("traf");e===null&&(e=this.isoBoxer_.createFullBox("tfdt",f,d),e.version=1,e.flags=0,e.baseMediaDecodeTime=Math.floor(c.startTime*b.mssPrivateData.timescale));b=a.fetch("trun");(c=a.fetch("tfxd"))&&
c._parent.boxes.splice(c._parent.boxes.indexOf(c),1);(c=a.fetch("tfrf"))&&c._parent.boxes.splice(c._parent.boxes.indexOf(c),1);c=a.fetch("sepiff");if(c!==null&&(c.type="senc",c.usertype=void 0,e=a.fetch("saio"),e===null)){e=this.isoBoxer_.createFullBox("saio",f);e.version=0;e.flags=0;e.entry_count=1;e.offset=[0];const g=this.isoBoxer_.createFullBox("saiz",f);g.version=0;g.flags=0;g.sample_count=c.sample_count;g.default_sample_info_size=0;g.sample_info_size=[];if(c.flags&2)for(e=0;e<c.sample_count;e+=
1)g.sample_info_size[e]=10+6*c.entry[e].NumberOfEntries;else g.default_sample_info_size=8}d.flags&=16777214;d.flags|=131072;b.flags|=1;d=a.fetch("moof");c=d.getLength();b.data_offset=c+8;b=a.fetch("saio");b!==null&&(d=this.getBoxOffset_(d,"traf"),f=this.getBoxOffset_(f,"senc"),b.offset[0]=d+f+16);return shaka.util.BufferUtils.toUint8(a.write())}getBoxOffset_(a,b){let c=8;for(let d=0;d<a.boxes.length&&a.boxes[d].type!==b;d++)c+=a.boxes[d].size;return c}};
goog.exportSymbol("shaka.transmuxer.MssTransmuxer",shaka.transmuxer.MssTransmuxer);goog.exportProperty(shaka.transmuxer.MssTransmuxer.prototype,"transmux",shaka.transmuxer.MssTransmuxer.prototype.transmux);goog.exportProperty(shaka.transmuxer.MssTransmuxer.prototype,"getOriginalMimeType",shaka.transmuxer.MssTransmuxer.prototype.getOriginalMimeType);goog.exportProperty(shaka.transmuxer.MssTransmuxer.prototype,"convertCodecs",shaka.transmuxer.MssTransmuxer.prototype.convertCodecs);
goog.exportProperty(shaka.transmuxer.MssTransmuxer.prototype,"isSupported",shaka.transmuxer.MssTransmuxer.prototype.isSupported);goog.exportProperty(shaka.transmuxer.MssTransmuxer.prototype,"destroy",shaka.transmuxer.MssTransmuxer.prototype.destroy);shaka.transmuxer.MssTransmuxer.UUID_SENC_=new Uint8Array([162,57,79,82,90,155,79,20,162,68,108,66,124,100,141,244]);shaka.transmuxer.TransmuxerEngine.registerTransmuxer("mss/audio/mp4",()=>new shaka.transmuxer.MssTransmuxer("mss/audio/mp4"),shaka.transmuxer.TransmuxerEngine.PluginPriority.FALLBACK);
shaka.transmuxer.TransmuxerEngine.registerTransmuxer("mss/video/mp4",()=>new shaka.transmuxer.MssTransmuxer("mss/video/mp4"),shaka.transmuxer.TransmuxerEngine.PluginPriority.FALLBACK);shaka.transmuxer.Opus=class{static getAudioConfig(a){let b=[];switch(a.channelConfigCode){case 1:case 2:b=[0];break;case 0:b=[255,1,1,0,1];break;case 128:b=[255,2,0,0,1];break;case 3:b=[1,2,1,0,2,1];break;case 4:b=[1,2,2,0,1,2,3];break;case 5:b=[1,3,2,0,4,1,2,3];break;case 6:b=[1,4,2,0,4,1,2,3,5];break;case 7:b=[1,4,2,0,4,1,2,3,5,6];break;case 8:b=[1,5,3,0,6,1,2,3,4,5,7];break;case 130:b=[1,1,2,0,1];break;case 131:b=[1,1,3,0,1,2];break;case 132:b=[1,1,4,0,1,2,3];break;case 133:b=[1,1,5,0,1,2,3,4];
break;case 134:b=[1,1,6,0,1,2,3,4,5];break;case 135:b=[1,1,7,0,1,2,3,4,5,6];break;case 136:b=[1,1,8,0,1,2,3,4,5,6,7]}return new Uint8Array([0,a.channelCount,0,0,a.sampleRate>>>24&255,a.sampleRate>>>17&255,a.sampleRate>>>8&255,a.sampleRate>>>0&255,0,0,...b])}static getPacketSampleCount(a){if(a.length<1)return shaka.transmuxer.Opus.OPUS_AUDIO_SAMPLE_PER_FRAME;var b=a[0];const c=b&3;b=shaka.transmuxer.Opus.SAMPLES_PER_FRAME_BY_CONFIG_[b>>3&31];if(c===0)a=1;else if(c===1||c===2)a=2;else{if(a.length<2)return b;
a=a[1]&63;if(a===0)return b}return b*a}};shaka.transmuxer.Opus.SAMPLES_PER_FRAME_BY_CONFIG_=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960];shaka.transmuxer.Opus.OPUS_AUDIO_SAMPLE_PER_FRAME=960;shaka.transmuxer.TsTransmuxer=class{constructor(a){this.originalMimeType_=a;this.frameIndex_=0;this.initSegments=new Map;this.lastInitSegment_=this.aacTransmuxer_=this.tsParser_=null}destroy(){this.initSegments.clear();this.aacTransmuxer_&&this.aacTransmuxer_.destroy()}isSupported(a,b){const c=shaka.media.Capabilities;if(!this.isTsContainer_(a))return!1;const d=shaka.util.ManifestParserUtils.ContentType;var e=shaka.util.MimeUtils,f=a;b&&(f=this.convertCodecs(b,a));f=e.getCodecs(f);f=e.splitCodecs(f);
var g=shaka.util.ManifestParserUtils.guessCodecsSafe(d.AUDIO,f);const h=shaka.util.ManifestParserUtils.guessCodecsSafe(d.VIDEO,f);f=shaka.transmuxer.TsTransmuxer;if(g&&(g=e.getNormalizedCodec(g),!f.SUPPORTED_AUDIO_CODECS_.includes(g))||h&&(e=e.getNormalizedCodec(h),!f.SUPPORTED_VIDEO_CODECS_.includes(e)))return!1;if(b)return c.isTypeSupported(this.convertCodecs(b,a));b=this.convertCodecs(d.AUDIO,a);a=this.convertCodecs(d.VIDEO,a);return c.isTypeSupported(b)||c.isTypeSupported(a)}isTsContainer_(a){return a.toLowerCase().split(";")[0]==
"video/mp2t"}convertCodecs(a,b){if(this.isTsContainer_(b)){const c=shaka.util.ManifestParserUtils.ContentType,d=shaka.util.StreamUtils;b=shaka.util.MimeUtils.getCodecs(b).replace("mp4a.40.34","mp3").split(",").map(e=>d.getCorrectAudioCodecs(e,"audio/mp4")).map(d.getCorrectVideoCodecs).join(",");return a==c.AUDIO?`audio/mp4; codecs="${b}"`:`video/mp4; codecs="${b}"`}return b}getOriginalMimeType(){return this.originalMimeType_}transmux(a,b,c,d,e){var f=shaka.util.ManifestParserUtils.ContentType,g=shaka.util.BufferUtils.toUint8(a);
if(e==f.AUDIO&&!shaka.util.TsParser.probe(g)){f=shaka.util.Id3Utils.getID3Data(g);for(var h=f.length;h<g.length;h++)if(shaka.transmuxer.MpegAudio.probe(g,h))return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,c?c.getUris()[0]:null));for(h=f.length;h<g.length;h++)if(shaka.transmuxer.ADTS.probe(g,h))return this.aacTransmuxer_||(this.aacTransmuxer_=new shaka.transmuxer.AacTransmuxer("audio/aac")),this.aacTransmuxer_.transmux(a,
b,c,d,e);return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,c?c.getUris()[0]:null))}this.tsParser_?this.tsParser_.clearData():this.tsParser_=new shaka.util.TsParser;this.tsParser_.setDiscontinuitySequence(c.discontinuitySequence);a=this.tsParser_.parse(g);g=[];h=a.getCodecs();try{let k=null;if(e==f.VIDEO){switch(h.video){case "avc":k=this.getAvcStreamInfo_(a,b,d,c);break;case "hvc":k=this.getHvcStreamInfo_(a,
b,d,c)}k&&(g.push(k),k=null)}if(e==f.AUDIO){switch(h.audio){case "aac":k=this.getAacStreamInfo_(a,b,d,c);break;case "ac3":k=this.getAc3StreamInfo_(a,b,d,c);break;case "ec3":k=this.getEc3StreamInfo_(a,b,d,c);break;case "mp3":k=this.getMp3StreamInfo_(a,b,d,c);break;case "opus":k=this.getOpusStreamInfo_(a,b,d,c)}k&&g.push(k)}}catch(k){return k&&k.code==shaka.util.Error.Code.TRANSMUXING_NO_VIDEO_DATA?Promise.resolve(new Uint8Array([])):Promise.reject(k)}if(!g.length)return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,c?c.getUris()[0]:null));d=new shaka.util.Mp4Generator(g);c=b.id+"_"+c.discontinuitySequence;this.initSegments.has(c)?b=this.initSegments.get(c):(b=d.initSegment(),this.initSegments.set(c,b));c=this.lastInitSegment_!==b;d=d.segmentData();this.lastInitSegment_=b;this.frameIndex_++;return Promise.resolve({data:d,init:c?b:null})}getAacStreamInfo_(a,b,c,d){var e=shaka.transmuxer.ADTS,f=shaka.util.TsParser.Timescale,g=shaka.util.Uint8ArrayUtils;
const h=[];let k=null,l=null,m=null;for(var n of a.getAudioData()){a=n.data;if(!a)continue;let p=0;if(l==-1&&m)a=g.concat(m,n.data),l=null;else if(l!=null&&m){p=Math.max(0,l);var q=g.concat(m,a.subarray(0,p));h.push({data:q,size:q.byteLength,duration:e.AAC_SAMPLES_PER_FRAME,cts:0,flags:shaka.transmuxer.TransmuxerUtils.AUDIO_SAMPLE_FLAGS});l=m=null}q=e.parseInfo(a,p);if(!q)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,
d?d.getUris()[0]:null);b.audioSamplingRate=q.sampleRate;b.channelsCount=q.channelCount;k==null&&n.pts!==null&&(k=n.pts);for(;p<a.length;){const r=e.parseHeader(a,p);if(!r){m=a.subarray(p,a.length);l=-1;break}const t=r.headerLength+r.frameLength;l=Math.max(0,p+t-a.length);if(l!=0)m=a.subarray(p+r.headerLength,p+t);else if(p+t<=a.length){const u=a.subarray(p+r.headerLength,p+t);h.push({data:u,size:r.frameLength,duration:e.AAC_SAMPLES_PER_FRAME,cts:0,flags:shaka.transmuxer.TransmuxerUtils.AUDIO_SAMPLE_FLAGS})}p+=
t}}if(!q||k==null){k=d.startTime*f;q=shaka.util.MimeUtils.splitCodecs(b.codecs);g=shaka.util.ManifestParserUtils.guessCodecsSafe(shaka.util.ManifestParserUtils.ContentType.AUDIO,q);if(!g||!b.channelsCount||!b.audioSamplingRate)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,d?d.getUris()[0]:null);q={sampleRate:b.audioSamplingRate,channelCount:b.channelsCount,codec:g};g=e.getSilentFrame(g,b.channelsCount);if(!g)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,d?d.getUris()[0]:null);d=k+(d.endTime-d.startTime)*f;for(n=k;n<d;)h.push({data:g,size:g.byteLength,duration:e.AAC_SAMPLES_PER_FRAME,cts:0,flags:shaka.transmuxer.TransmuxerUtils.AUDIO_SAMPLE_FLAGS}),n+=e.AAC_SAMPLES_PER_FRAME/q.sampleRate*f}e=q.sampleRate;f=k/f*e;return{id:b.id,type:shaka.util.ManifestParserUtils.ContentType.AUDIO,codecs:q.codec,timescale:e,duration:c,videoNalus:[],audioConfig:new Uint8Array([]),videoConfig:new Uint8Array([]),
hSpacing:0,vSpacing:0,data:{sequenceNumber:this.frameIndex_,baseMediaDecodeTime:f,samples:h},stream:b}}getAc3StreamInfo_(a,b,c,d){const e=shaka.transmuxer.Ac3,f=shaka.util.TsParser.Timescale,g=[];let h=0,k=new Uint8Array([]),l=null;const m={sampleRate:0,channelCount:0,audioConfig:new Uint8Array(0),frameLength:0};for(const n of a.getAudioData()){a=n.data;l==null&&n.pts!==null&&(l=n.pts);let q=0;for(;q<a.length;){if(!e.parseFrame(a,q,m)){q++;continue}b.audioSamplingRate=m.sampleRate;b.channelsCount=
m.channelCount;h=m.sampleRate;k=m.audioConfig;const p=a.subarray(q,q+m.frameLength);g.push({data:p,size:m.frameLength,duration:e.AC3_SAMPLES_PER_FRAME,cts:0,flags:shaka.transmuxer.TransmuxerUtils.AUDIO_SAMPLE_FLAGS});q+=m.frameLength}}if(h==0||k.byteLength==0||l==null)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,d?d.getUris()[0]:null);d=l/f*h;return{id:b.id,type:shaka.util.ManifestParserUtils.ContentType.AUDIO,
codecs:"ac-3",timescale:h,duration:c,videoNalus:[],audioConfig:k,videoConfig:new Uint8Array([]),hSpacing:0,vSpacing:0,data:{sequenceNumber:this.frameIndex_,baseMediaDecodeTime:d,samples:g},stream:b}}getEc3StreamInfo_(a,b,c,d){const e=shaka.transmuxer.Ec3,f=shaka.util.TsParser.Timescale,g=[];let h=0,k=new Uint8Array([]),l=null;const m={sampleRate:0,channelCount:0,audioConfig:new Uint8Array(0),frameLength:0};for(const n of a.getAudioData()){a=n.data;l==null&&n.pts!==null&&(l=n.pts);let q=0;for(;q<a.length;){if(!e.parseFrame(a,
q,m)){q++;continue}b.audioSamplingRate=m.sampleRate;b.channelsCount=m.channelCount;h=m.sampleRate;k=m.audioConfig;const p=a.subarray(q,q+m.frameLength);g.push({data:p,size:m.frameLength,duration:e.EC3_SAMPLES_PER_FRAME,cts:0,flags:shaka.transmuxer.TransmuxerUtils.AUDIO_SAMPLE_FLAGS});q+=m.frameLength}}if(h==0||k.byteLength==0||l==null)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,d?d.getUris()[0]:null);d=l/f*
h;return{id:b.id,type:shaka.util.ManifestParserUtils.ContentType.AUDIO,codecs:"ec-3",timescale:h,duration:c,videoNalus:[],audioConfig:k,videoConfig:new Uint8Array([]),hSpacing:0,vSpacing:0,data:{sequenceNumber:this.frameIndex_,baseMediaDecodeTime:d,samples:g},stream:b}}getMp3StreamInfo_(a,b,c,d){const e=shaka.transmuxer.MpegAudio;var f=shaka.util.TsParser.Timescale;const g=[];let h,k=null;for(const l of a.getAudioData()){a=l.data;if(!a)continue;k==null&&l.pts!==null&&(k=l.pts);let m=0;for(;m<a.length;){const n=
e.parseHeader(a,m);n?(h||=n,m+n.frameLength<=a.length&&g.push({data:a.subarray(m,m+n.frameLength),size:n.frameLength,duration:e.MPEG_AUDIO_SAMPLE_PER_FRAME,cts:0,flags:shaka.transmuxer.TransmuxerUtils.AUDIO_SAMPLE_FLAGS}),m+=n.frameLength):m++}}if(!h||k==null)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,d?d.getUris()[0]:null);d=h.sampleRate;f=k/f*d;return{id:b.id,type:shaka.util.ManifestParserUtils.ContentType.AUDIO,
codecs:"mp3",timescale:d,duration:c,videoNalus:[],audioConfig:new Uint8Array([]),videoConfig:new Uint8Array([]),hSpacing:0,vSpacing:0,data:{sequenceNumber:this.frameIndex_,baseMediaDecodeTime:f,samples:g},stream:b}}getOpusStreamInfo_(a,b,c,d){const e=shaka.transmuxer.Opus,f=shaka.util.TsParser.Timescale,g=[];let h=null;const k=a.getOpusMetadata();if(!k)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,d?d.getUris()[0]:
null);const l=e.getAudioConfig(k),m=k.sampleRate;for(const p of a.getAudioData()){a=p.data;h==null&&p.pts!==null&&(h=p.pts);for(var n=0;n<a.length;){var q=(a[n+1]&16)!==0;const r=(a[n+1]&8)!==0;n+=2;let t=0;for(;a[n]===255;)t+=255,n+=1;t+=a[n];n+=1;n+=q?2:0;n+=r?2:0;q=a.slice(n,n+t);g.push({data:q,size:q.byteLength,duration:e.getPacketSampleCount(q),cts:0,flags:shaka.transmuxer.TransmuxerUtils.AUDIO_SAMPLE_FLAGS});n+=t}}if(l.byteLength==0||h==null)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,d?d.getUris()[0]:null);b.audioSamplingRate=k.sampleRate;b.channelsCount=k.channelCount;d=h/f*m;return{id:b.id,type:shaka.util.ManifestParserUtils.ContentType.AUDIO,codecs:"opus",timescale:m,duration:c,videoNalus:[],audioConfig:l,videoConfig:new Uint8Array([]),hSpacing:0,vSpacing:0,data:{sequenceNumber:this.frameIndex_,baseMediaDecodeTime:d,samples:g},stream:b}}getAvcStreamInfo_(a,b,c,d){var e=shaka.transmuxer.H264;const f=shaka.util.TsParser.Timescale,
g=[];let h=null;a=a.getVideoData();var k=e.getVideoSamples(a);if(!k.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_NO_VIDEO_DATA,d?d.getUris()[0]:null);for(let l=0;l<k.length;l++){const m=k[l];h==null&&(h=m.dts);g.push({data:m.data,size:m.data.byteLength,duration:l+1<k.length?(k[l+1].dts||0)-(m.dts||0):k.length>1?(m.dts||0)-(k[l-1].dts||0):(d.endTime-d.startTime)*f,cts:Math.round((m.pts||0)-(m.dts||0)),flags:m.isKeyframe?
shaka.transmuxer.TransmuxerUtils.VIDEO_KEYFRAME_FLAGS:shaka.transmuxer.TransmuxerUtils.VIDEO_NON_KEYFRAME_FLAGS})}k=[];for(const l of a)k.push(...l.nalus);e=e.parseInfo(k);if(!e||h==null)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,d?d.getUris()[0]:null);b.height=b.height||e.height;b.width=b.width||e.width;return{id:b.id,type:shaka.util.ManifestParserUtils.ContentType.VIDEO,codecs:"avc1",timescale:f,duration:c,
videoNalus:[],audioConfig:new Uint8Array([]),videoConfig:e.videoConfig,hSpacing:e.hSpacing,vSpacing:e.vSpacing,data:{sequenceNumber:this.frameIndex_,baseMediaDecodeTime:h,samples:g},stream:b}}getHvcStreamInfo_(a,b,c,d){var e=shaka.transmuxer.H265;const f=shaka.util.TsParser.Timescale,g=[];let h=null;const k=[];a=a.getVideoData();const l={data:new Uint8Array(0),isKeyframe:!1};if(!a.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_NO_VIDEO_DATA,
d?d.getUris()[0]:null);for(let m=0;m<a.length;m++){const n=a[m],q=n.nalus;k.push(...q);e.parseFrame(q,l)&&(h==null&&n.dts!=null&&(h=n.dts),g.push({data:l.data,size:l.data.byteLength,duration:m+1<a.length?(a[m+1].dts||0)-(n.dts||0):a.length>1?(n.dts||0)-(a[m-1].dts||0):(d.endTime-d.startTime)*f,cts:Math.round((n.pts||0)-(n.dts||0)),flags:l.isKeyframe?shaka.transmuxer.TransmuxerUtils.VIDEO_KEYFRAME_FLAGS:shaka.transmuxer.TransmuxerUtils.VIDEO_NON_KEYFRAME_FLAGS}))}e=e.parseInfo(k);if(!e||h==null)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED,d?d.getUris()[0]:null);b.height=b.height||e.height;b.width=b.width||e.width;return{id:b.id,type:shaka.util.ManifestParserUtils.ContentType.VIDEO,codecs:"hvc1",timescale:f,duration:c,videoNalus:[],audioConfig:new Uint8Array([]),videoConfig:e.videoConfig,hSpacing:e.hSpacing,vSpacing:e.vSpacing,data:{sequenceNumber:this.frameIndex_,baseMediaDecodeTime:h,samples:g},stream:b}}};goog.exportSymbol("shaka.transmuxer.TsTransmuxer",shaka.transmuxer.TsTransmuxer);
goog.exportProperty(shaka.transmuxer.TsTransmuxer.prototype,"transmux",shaka.transmuxer.TsTransmuxer.prototype.transmux);goog.exportProperty(shaka.transmuxer.TsTransmuxer.prototype,"getOriginalMimeType",shaka.transmuxer.TsTransmuxer.prototype.getOriginalMimeType);goog.exportProperty(shaka.transmuxer.TsTransmuxer.prototype,"convertCodecs",shaka.transmuxer.TsTransmuxer.prototype.convertCodecs);goog.exportProperty(shaka.transmuxer.TsTransmuxer.prototype,"isSupported",shaka.transmuxer.TsTransmuxer.prototype.isSupported);
goog.exportProperty(shaka.transmuxer.TsTransmuxer.prototype,"destroy",shaka.transmuxer.TsTransmuxer.prototype.destroy);shaka.transmuxer.TsTransmuxer.SUPPORTED_AUDIO_CODECS_=["aac","ac-3","ec-3","mp3","opus"];shaka.transmuxer.TsTransmuxer.SUPPORTED_VIDEO_CODECS_=["avc","hevc"];shaka.transmuxer.TransmuxerEngine.registerTransmuxer("video/mp2t",()=>new shaka.transmuxer.TsTransmuxer("video/mp2t"),shaka.transmuxer.TransmuxerEngine.PluginPriority.PREFERRED);shaka.util.FairPlayUtils=class extends shaka.drm.FairPlay{};goog.exportSymbol("shaka.util.FairPlayUtils",shaka.util.FairPlayUtils);}).call(exportTo,innerGlobal,innerGlobal,undefined);if(typeof exports!="undefined")for(var k in exportTo.shaka)exports[k]=exportTo.shaka[k];else if(typeof define=="function"&&define.amd)define(function(){return exportTo.shaka});else innerGlobal.shaka=exportTo.shaka})();

//# sourceMappingURL=shaka-player.compiled-es2021.debug.map