From 3612b716fe4f34334ea8504e3ba0a0d4d8da4422 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 11 May 2017 01:15:43 -0400 Subject: [PATCH] update bitrate detection --- .../bower_components/emby-apiclient/apiclient.js | 2 +- .../emby-webcomponents/input/gamepadtokey.js | 2 +- .../playback/playbackmanager.js | 4 ++-- .../bower_components/hlsjs/dist/hls.min.js | 16 ++++++++-------- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/dashboard-ui/bower_components/emby-apiclient/apiclient.js b/dashboard-ui/bower_components/emby-apiclient/apiclient.js index c19c8d84aa..323ec33783 100644 --- a/dashboard-ui/bower_components/emby-apiclient/apiclient.js +++ b/dashboard-ui/bower_components/emby-apiclient/apiclient.js @@ -1,2 +1,2 @@ -define(["events"],function(events){"use strict";function redetectBitrate(instance){stopBitrateDetection(instance),instance.accessToken()&&instance.enableAutomaticBitrateDetection!==!1&&setTimeout(redetectBitrateInternal.bind(instance),6e3)}function redetectBitrateInternal(){this.accessToken()&&this.detectBitrate()}function stopBitrateDetection(instance){instance.detectTimeout&&clearTimeout(instance.detectTimeout)}function replaceAll(originalString,strReplace,strWith){var reg=new RegExp(strReplace,"ig");return originalString.replace(reg,strWith)}function onFetchFail(instance,url,response){events.trigger(instance,"requestfail",[{url:url,status:response.status,errorCode:response.headers?response.headers.get("X-Application-Error-Code"):null}])}function paramsToString(params){var values=[];for(var key in params){var value=params[key];null!==value&&void 0!==value&&""!==value&&values.push(encodeURIComponent(key)+"="+encodeURIComponent(value))}return values.join("&")}function fetchWithTimeout(url,options,timeoutMs){return new Promise(function(resolve,reject){var timeout=setTimeout(reject,timeoutMs);options=options||{},options.credentials="same-origin",fetch(url,options).then(function(response){clearTimeout(timeout),resolve(response)},function(error){clearTimeout(timeout),reject(error)})})}function getFetchPromise(request){var headers=request.headers||{};"json"===request.dataType&&(headers.accept="application/json");var fetchRequest={headers:headers,method:request.type,credentials:"same-origin"},contentType=request.contentType;return request.data&&("string"==typeof request.data?fetchRequest.body=request.data:(fetchRequest.body=paramsToString(request.data),contentType=contentType||"application/x-www-form-urlencoded; charset=UTF-8")),contentType&&(headers["Content-Type"]=contentType),request.timeout?fetchWithTimeout(request.url,fetchRequest,request.timeout):fetch(request.url,fetchRequest)}function ApiClient(serverAddress,appName,appVersion,deviceName,deviceId,devicePixelRatio){if(!serverAddress)throw new Error("Must supply a serverAddress");console.log("ApiClient serverAddress: "+serverAddress),console.log("ApiClient appName: "+appName),console.log("ApiClient appVersion: "+appVersion),console.log("ApiClient deviceName: "+deviceName),console.log("ApiClient deviceId: "+deviceId),this._serverInfo={},this._serverAddress=serverAddress,this._deviceId=deviceId,this._deviceName=deviceName,this._appName=appName,this._appVersion=appVersion}function switchConnectionMode(instance,connectionMode){var currentServerInfo=instance.serverInfo(),newConnectionMode=connectionMode;return newConnectionMode--,newConnectionMode<0&&(newConnectionMode=MediaBrowser.ConnectionMode.Manual),MediaBrowser.ServerInfo.getServerAddress(currentServerInfo,newConnectionMode)?newConnectionMode:(newConnectionMode--,newConnectionMode<0&&(newConnectionMode=MediaBrowser.ConnectionMode.Manual),MediaBrowser.ServerInfo.getServerAddress(currentServerInfo,newConnectionMode)?newConnectionMode:connectionMode)}function tryReconnectInternal(instance,resolve,reject,connectionMode,currentRetryCount){connectionMode=switchConnectionMode(instance,connectionMode);var url=MediaBrowser.ServerInfo.getServerAddress(instance.serverInfo(),connectionMode);console.log("Attempting reconnection to "+url);var timeout=connectionMode===MediaBrowser.ConnectionMode.Local?7e3:15e3;fetchWithTimeout(url+"/system/info/public",{method:"GET",accept:"application/json"},timeout).then(function(){console.log("Reconnect succeeded to "+url),instance.serverInfo().LastConnectionMode=connectionMode,instance.serverAddress(url),resolve()},function(){if(console.log("Reconnect attempt failed to "+url),currentRetryCount<5){var newConnectionMode=switchConnectionMode(instance,connectionMode);setTimeout(function(){tryReconnectInternal(instance,resolve,reject,newConnectionMode,currentRetryCount+1)},300)}else reject()})}function tryReconnect(instance){return new Promise(function(resolve,reject){setTimeout(function(){tryReconnectInternal(instance,resolve,reject,instance.serverInfo().LastConnectionMode,0)},300)})}function onWebSocketMessage(instance,msg){if("UserDeleted"===msg.MessageType)instance._currentUser=null;else if("UserUpdated"===msg.MessageType||"UserConfigurationUpdated"===msg.MessageType){var user=msg.Data;user.Id===instance.getCurrentUserId()&&(instance._currentUser=null)}events.trigger(instance,"websocketmessage",[msg])}function normalizeReturnBitrate(instance,bitrate){if(!bitrate)return instance.lastDetectedBitrate?instance.lastDetectedBitrate:Promise.reject();var result=Math.round(.8*bitrate);return instance.lastDetectedBitrate=result,instance.lastDetectedBitrateTime=(new Date).getTime(),result}function detectBitrateInternal(instance,tests,index,currentBitrate){if(index>=tests.length)return normalizeReturnBitrate(instance,currentBitrate);var test=tests[index];return instance.getDownloadSpeed(test.bytes).then(function(bitrate){return bitrate1800?this.ajax({type:"POST",url:this.getUrl("LiveTv/Programs"),data:JSON.stringify(options),contentType:"application/json",dataType:"json"}):this.ajax({type:"GET",url:this.getUrl("LiveTv/Programs",options),dataType:"json"})},ApiClient.prototype.getLiveTvRecommendedPrograms=function(options){return options=options||{},this.ajax({type:"GET",url:this.getUrl("LiveTv/Programs/Recommended",options),dataType:"json"})},ApiClient.prototype.getLiveTvRecordings=function(options){var url=this.getUrl("LiveTv/Recordings",options||{});return this.getJSON(url)},ApiClient.prototype.getLiveTvRecordingSeries=function(options){var url=this.getUrl("LiveTv/Recordings/Series",options||{});return this.getJSON(url)},ApiClient.prototype.getLiveTvRecordingGroups=function(options){var url=this.getUrl("LiveTv/Recordings/Groups",options||{});return this.getJSON(url)},ApiClient.prototype.getLiveTvRecordingGroup=function(id){if(!id)throw new Error("null id");var url=this.getUrl("LiveTv/Recordings/Groups/"+id);return this.getJSON(url)},ApiClient.prototype.getLiveTvRecording=function(id,userId){if(!id)throw new Error("null id");var options={};userId&&(options.userId=userId);var url=this.getUrl("LiveTv/Recordings/"+id,options);return this.getJSON(url)},ApiClient.prototype.getLiveTvProgram=function(id,userId){if(!id)throw new Error("null id");var options={};userId&&(options.userId=userId);var url=this.getUrl("LiveTv/Programs/"+id,options);return this.getJSON(url)},ApiClient.prototype.deleteLiveTvRecording=function(id){if(!id)throw new Error("null id");var url=this.getUrl("LiveTv/Recordings/"+id);return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.cancelLiveTvTimer=function(id){if(!id)throw new Error("null id");var url=this.getUrl("LiveTv/Timers/"+id);return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.getLiveTvTimers=function(options){var url=this.getUrl("LiveTv/Timers",options||{});return this.getJSON(url)},ApiClient.prototype.getLiveTvTimer=function(id){if(!id)throw new Error("null id");var url=this.getUrl("LiveTv/Timers/"+id);return this.getJSON(url)},ApiClient.prototype.getNewLiveTvTimerDefaults=function(options){options=options||{};var url=this.getUrl("LiveTv/Timers/Defaults",options);return this.getJSON(url)},ApiClient.prototype.createLiveTvTimer=function(item){if(!item)throw new Error("null item");var url=this.getUrl("LiveTv/Timers");return this.ajax({type:"POST",url:url,data:JSON.stringify(item),contentType:"application/json"})},ApiClient.prototype.updateLiveTvTimer=function(item){if(!item)throw new Error("null item");var url=this.getUrl("LiveTv/Timers/"+item.Id);return this.ajax({type:"POST",url:url,data:JSON.stringify(item),contentType:"application/json"})},ApiClient.prototype.resetLiveTvTuner=function(id){if(!id)throw new Error("null id");var url=this.getUrl("LiveTv/Tuners/"+id+"/Reset");return this.ajax({type:"POST",url:url})},ApiClient.prototype.getLiveTvSeriesTimers=function(options){var url=this.getUrl("LiveTv/SeriesTimers",options||{});return this.getJSON(url)},ApiClient.prototype.getFileOrganizationResults=function(options){var url=this.getUrl("Library/FileOrganization",options||{});return this.getJSON(url)},ApiClient.prototype.deleteOriginalFileFromOrganizationResult=function(id){var url=this.getUrl("Library/FileOrganizations/"+id+"/File");return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.clearOrganizationLog=function(){var url=this.getUrl("Library/FileOrganizations");return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.performOrganization=function(id){var url=this.getUrl("Library/FileOrganizations/"+id+"/Organize");return this.ajax({type:"POST",url:url})},ApiClient.prototype.performEpisodeOrganization=function(id,options){var url=this.getUrl("Library/FileOrganizations/"+id+"/Episode/Organize");return this.ajax({type:"POST",url:url,data:JSON.stringify(options),contentType:"application/json"})},ApiClient.prototype.getLiveTvSeriesTimer=function(id){if(!id)throw new Error("null id");var url=this.getUrl("LiveTv/SeriesTimers/"+id);return this.getJSON(url)},ApiClient.prototype.cancelLiveTvSeriesTimer=function(id){if(!id)throw new Error("null id");var url=this.getUrl("LiveTv/SeriesTimers/"+id);return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.createLiveTvSeriesTimer=function(item){if(!item)throw new Error("null item");var url=this.getUrl("LiveTv/SeriesTimers");return this.ajax({type:"POST",url:url,data:JSON.stringify(item),contentType:"application/json"})},ApiClient.prototype.updateLiveTvSeriesTimer=function(item){if(!item)throw new Error("null item");var url=this.getUrl("LiveTv/SeriesTimers/"+item.Id);return this.ajax({type:"POST",url:url,data:JSON.stringify(item),contentType:"application/json"})},ApiClient.prototype.getRegistrationInfo=function(feature){var url=this.getUrl("Registrations/"+feature);return this.getJSON(url)},ApiClient.prototype.getSystemInfo=function(){var url=this.getUrl("System/Info");return this.getJSON(url)},ApiClient.prototype.getPublicSystemInfo=function(){var url=this.getUrl("System/Info/Public");return this.getJSON(url,!1)},ApiClient.prototype.getInstantMixFromItem=function(itemId,options){var url=this.getUrl("Items/"+itemId+"/InstantMix",options);return this.getJSON(url)},ApiClient.prototype.getEpisodes=function(itemId,options){var url=this.getUrl("Shows/"+itemId+"/Episodes",options);return this.getJSON(url)},ApiClient.prototype.getDisplayPreferences=function(id,userId,app){var url=this.getUrl("DisplayPreferences/"+id,{userId:userId,client:app});return this.getJSON(url)},ApiClient.prototype.updateDisplayPreferences=function(id,obj,userId,app){var url=this.getUrl("DisplayPreferences/"+id,{userId:userId,client:app});return this.ajax({type:"POST",url:url,data:JSON.stringify(obj),contentType:"application/json"})},ApiClient.prototype.getSeasons=function(itemId,options){var url=this.getUrl("Shows/"+itemId+"/Seasons",options);return this.getJSON(url)},ApiClient.prototype.getSimilarItems=function(itemId,options){var url=this.getUrl("Items/"+itemId+"/Similar",options);return this.getJSON(url)},ApiClient.prototype.getCultures=function(){var url=this.getUrl("Localization/cultures");return this.getJSON(url)},ApiClient.prototype.getCountries=function(){var url=this.getUrl("Localization/countries");return this.getJSON(url)},ApiClient.prototype.getPluginSecurityInfo=function(){var url=this.getUrl("Plugins/SecurityInfo");return this.getJSON(url)},ApiClient.prototype.getPlaybackInfo=function(itemId,options,deviceProfile){var postData={DeviceProfile:deviceProfile};return this.ajax({url:this.getUrl("Items/"+itemId+"/PlaybackInfo",options),type:"POST",data:JSON.stringify(postData),contentType:"application/json",dataType:"json"})},ApiClient.prototype.getIntros=function(itemId){return this.getJSON(this.getUrl("Users/"+this.getCurrentUserId()+"/Items/"+itemId+"/Intros"))},ApiClient.prototype.getDirectoryContents=function(path,options){if(!path)throw new Error("null path");if("string"!=typeof path)throw new Error("invalid path");options=options||{},options.path=path;var url=this.getUrl("Environment/DirectoryContents",options);return this.getJSON(url)},ApiClient.prototype.getNetworkShares=function(path){if(!path)throw new Error("null path");var options={};options.path=path;var url=this.getUrl("Environment/NetworkShares",options);return this.getJSON(url)},ApiClient.prototype.getParentPath=function(path){if(!path)throw new Error("null path");var options={};options.path=path;var url=this.getUrl("Environment/ParentPath",options);return this.ajax({type:"GET",url:url,dataType:"text"})},ApiClient.prototype.getDrives=function(){var url=this.getUrl("Environment/Drives");return this.getJSON(url)},ApiClient.prototype.getNetworkDevices=function(){var url=this.getUrl("Environment/NetworkDevices");return this.getJSON(url)},ApiClient.prototype.cancelPackageInstallation=function(installationId){if(!installationId)throw new Error("null installationId");var url=this.getUrl("Packages/Installing/"+installationId);return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.refreshItem=function(itemId,options){if(!itemId)throw new Error("null itemId");var url=this.getUrl("Items/"+itemId+"/Refresh",options||{});return this.ajax({type:"POST",url:url})},ApiClient.prototype.installPlugin=function(name,guid,updateClass,version){if(!name)throw new Error("null name");if(!updateClass)throw new Error("null updateClass");var options={updateClass:updateClass,AssemblyGuid:guid};version&&(options.version=version);var url=this.getUrl("Packages/Installed/"+name,options);return this.ajax({type:"POST",url:url})},ApiClient.prototype.restartServer=function(){var url=this.getUrl("System/Restart");return this.ajax({type:"POST",url:url})},ApiClient.prototype.shutdownServer=function(){var url=this.getUrl("System/Shutdown");return this.ajax({type:"POST",url:url})},ApiClient.prototype.getPackageInfo=function(name,guid){if(!name)throw new Error("null name");var options={AssemblyGuid:guid},url=this.getUrl("Packages/"+name,options);return this.getJSON(url)},ApiClient.prototype.getAvailableApplicationUpdate=function(){var url=this.getUrl("Packages/Updates",{PackageType:"System"});return this.getJSON(url)},ApiClient.prototype.getAvailablePluginUpdates=function(){var url=this.getUrl("Packages/Updates",{PackageType:"UserInstalled"});return this.getJSON(url)},ApiClient.prototype.getVirtualFolders=function(){var url="Library/VirtualFolders";return url=this.getUrl(url),this.getJSON(url)},ApiClient.prototype.getPhysicalPaths=function(){var url=this.getUrl("Library/PhysicalPaths");return this.getJSON(url)},ApiClient.prototype.getServerConfiguration=function(){var url=this.getUrl("System/Configuration");return this.getJSON(url)},ApiClient.prototype.getDevicesOptions=function(){var url=this.getUrl("System/Configuration/devices");return this.getJSON(url)},ApiClient.prototype.getContentUploadHistory=function(){var url=this.getUrl("Devices/CameraUploads",{DeviceId:this.deviceId()});return this.getJSON(url)},ApiClient.prototype.getNamedConfiguration=function(name){var url=this.getUrl("System/Configuration/"+name);return this.getJSON(url)},ApiClient.prototype.getScheduledTasks=function(options){options=options||{};var url=this.getUrl("ScheduledTasks",options);return this.getJSON(url)},ApiClient.prototype.startScheduledTask=function(id){if(!id)throw new Error("null id");var url=this.getUrl("ScheduledTasks/Running/"+id);return this.ajax({type:"POST",url:url})},ApiClient.prototype.getScheduledTask=function(id){if(!id)throw new Error("null id");var url=this.getUrl("ScheduledTasks/"+id);return this.getJSON(url)},ApiClient.prototype.getNextUpEpisodes=function(options){var url=this.getUrl("Shows/NextUp",options);return this.getJSON(url)},ApiClient.prototype.stopScheduledTask=function(id){if(!id)throw new Error("null id");var url=this.getUrl("ScheduledTasks/Running/"+id);return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.getPluginConfiguration=function(id){if(!id)throw new Error("null Id");var url=this.getUrl("Plugins/"+id+"/Configuration");return this.getJSON(url)},ApiClient.prototype.getAvailablePlugins=function(options){options=options||{},options.PackageType="UserInstalled";var url=this.getUrl("Packages",options);return this.getJSON(url)},ApiClient.prototype.uninstallPlugin=function(id){if(!id)throw new Error("null Id");var url=this.getUrl("Plugins/"+id);return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.removeVirtualFolder=function(name,refreshLibrary){if(!name)throw new Error("null name");var url="Library/VirtualFolders";return url=this.getUrl(url,{refreshLibrary:!!refreshLibrary,name:name}),this.ajax({type:"DELETE",url:url})},ApiClient.prototype.addVirtualFolder=function(name,type,refreshLibrary,libraryOptions){if(!name)throw new Error("null name");var options={};type&&(options.collectionType=type),options.refreshLibrary=!!refreshLibrary,options.name=name;var url="Library/VirtualFolders";return url=this.getUrl(url,options),this.ajax({type:"POST",url:url,data:JSON.stringify({LibraryOptions:libraryOptions}),contentType:"application/json"})},ApiClient.prototype.updateVirtualFolderOptions=function(id,libraryOptions){if(!id)throw new Error("null name");var url="Library/VirtualFolders/LibraryOptions";return url=this.getUrl(url),this.ajax({type:"POST",url:url,data:JSON.stringify({Id:id,LibraryOptions:libraryOptions}),contentType:"application/json"})},ApiClient.prototype.renameVirtualFolder=function(name,newName,refreshLibrary){if(!name)throw new Error("null name");var url="Library/VirtualFolders/Name";return url=this.getUrl(url,{refreshLibrary:!!refreshLibrary,newName:newName,name:name}),this.ajax({type:"POST",url:url})},ApiClient.prototype.addMediaPath=function(virtualFolderName,mediaPath,networkSharePath,refreshLibrary){if(!virtualFolderName)throw new Error("null virtualFolderName");if(!mediaPath)throw new Error("null mediaPath");var url="Library/VirtualFolders/Paths",pathInfo={Path:mediaPath};return networkSharePath&&(pathInfo.NetworkPath=networkSharePath),url=this.getUrl(url,{refreshLibrary:!!refreshLibrary}),this.ajax({type:"POST",url:url,data:JSON.stringify({Name:virtualFolderName,PathInfo:pathInfo}),contentType:"application/json"})},ApiClient.prototype.updateMediaPath=function(virtualFolderName,pathInfo){if(!virtualFolderName)throw new Error("null virtualFolderName"); +define(["events"],function(events){"use strict";function redetectBitrate(instance){stopBitrateDetection(instance),instance.accessToken()&&instance.enableAutomaticBitrateDetection!==!1&&setTimeout(redetectBitrateInternal.bind(instance),6e3)}function redetectBitrateInternal(){this.accessToken()&&this.detectBitrate()}function stopBitrateDetection(instance){instance.detectTimeout&&clearTimeout(instance.detectTimeout)}function replaceAll(originalString,strReplace,strWith){var reg=new RegExp(strReplace,"ig");return originalString.replace(reg,strWith)}function onFetchFail(instance,url,response){events.trigger(instance,"requestfail",[{url:url,status:response.status,errorCode:response.headers?response.headers.get("X-Application-Error-Code"):null}])}function paramsToString(params){var values=[];for(var key in params){var value=params[key];null!==value&&void 0!==value&&""!==value&&values.push(encodeURIComponent(key)+"="+encodeURIComponent(value))}return values.join("&")}function fetchWithTimeout(url,options,timeoutMs){return new Promise(function(resolve,reject){var timeout=setTimeout(reject,timeoutMs);options=options||{},options.credentials="same-origin",fetch(url,options).then(function(response){clearTimeout(timeout),resolve(response)},function(error){clearTimeout(timeout),reject(error)})})}function getFetchPromise(request){var headers=request.headers||{};"json"===request.dataType&&(headers.accept="application/json");var fetchRequest={headers:headers,method:request.type,credentials:"same-origin"},contentType=request.contentType;return request.data&&("string"==typeof request.data?fetchRequest.body=request.data:(fetchRequest.body=paramsToString(request.data),contentType=contentType||"application/x-www-form-urlencoded; charset=UTF-8")),contentType&&(headers["Content-Type"]=contentType),request.timeout?fetchWithTimeout(request.url,fetchRequest,request.timeout):fetch(request.url,fetchRequest)}function ApiClient(serverAddress,appName,appVersion,deviceName,deviceId,devicePixelRatio){if(!serverAddress)throw new Error("Must supply a serverAddress");console.log("ApiClient serverAddress: "+serverAddress),console.log("ApiClient appName: "+appName),console.log("ApiClient appVersion: "+appVersion),console.log("ApiClient deviceName: "+deviceName),console.log("ApiClient deviceId: "+deviceId),this._serverInfo={},this._serverAddress=serverAddress,this._deviceId=deviceId,this._deviceName=deviceName,this._appName=appName,this._appVersion=appVersion}function switchConnectionMode(instance,connectionMode){var currentServerInfo=instance.serverInfo(),newConnectionMode=connectionMode;return newConnectionMode--,newConnectionMode<0&&(newConnectionMode=MediaBrowser.ConnectionMode.Manual),MediaBrowser.ServerInfo.getServerAddress(currentServerInfo,newConnectionMode)?newConnectionMode:(newConnectionMode--,newConnectionMode<0&&(newConnectionMode=MediaBrowser.ConnectionMode.Manual),MediaBrowser.ServerInfo.getServerAddress(currentServerInfo,newConnectionMode)?newConnectionMode:connectionMode)}function tryReconnectInternal(instance,resolve,reject,connectionMode,currentRetryCount){connectionMode=switchConnectionMode(instance,connectionMode);var url=MediaBrowser.ServerInfo.getServerAddress(instance.serverInfo(),connectionMode);console.log("Attempting reconnection to "+url);var timeout=connectionMode===MediaBrowser.ConnectionMode.Local?7e3:15e3;fetchWithTimeout(url+"/system/info/public",{method:"GET",accept:"application/json"},timeout).then(function(){console.log("Reconnect succeeded to "+url),instance.serverInfo().LastConnectionMode=connectionMode,instance.serverAddress(url),resolve()},function(){if(console.log("Reconnect attempt failed to "+url),currentRetryCount<5){var newConnectionMode=switchConnectionMode(instance,connectionMode);setTimeout(function(){tryReconnectInternal(instance,resolve,reject,newConnectionMode,currentRetryCount+1)},300)}else reject()})}function tryReconnect(instance){return new Promise(function(resolve,reject){setTimeout(function(){tryReconnectInternal(instance,resolve,reject,instance.serverInfo().LastConnectionMode,0)},300)})}function onWebSocketMessage(instance,msg){if("UserDeleted"===msg.MessageType)instance._currentUser=null;else if("UserUpdated"===msg.MessageType||"UserConfigurationUpdated"===msg.MessageType){var user=msg.Data;user.Id===instance.getCurrentUserId()&&(instance._currentUser=null)}events.trigger(instance,"websocketmessage",[msg])}function normalizeReturnBitrate(instance,bitrate){if(!bitrate)return instance.lastDetectedBitrate?instance.lastDetectedBitrate:Promise.reject();var result=Math.round(.8*bitrate);return instance.lastDetectedBitrate=result,instance.lastDetectedBitrateTime=(new Date).getTime(),result}function detectBitrateInternal(instance,tests,index,currentBitrate){if(index>=tests.length)return normalizeReturnBitrate(instance,currentBitrate);var test=tests[index];return instance.getDownloadSpeed(test.bytes).then(function(bitrate){return bitrate1800?this.ajax({type:"POST",url:this.getUrl("LiveTv/Programs"),data:JSON.stringify(options),contentType:"application/json",dataType:"json"}):this.ajax({type:"GET",url:this.getUrl("LiveTv/Programs",options),dataType:"json"})},ApiClient.prototype.getLiveTvRecommendedPrograms=function(options){return options=options||{},this.ajax({type:"GET",url:this.getUrl("LiveTv/Programs/Recommended",options),dataType:"json"})},ApiClient.prototype.getLiveTvRecordings=function(options){var url=this.getUrl("LiveTv/Recordings",options||{});return this.getJSON(url)},ApiClient.prototype.getLiveTvRecordingSeries=function(options){var url=this.getUrl("LiveTv/Recordings/Series",options||{});return this.getJSON(url)},ApiClient.prototype.getLiveTvRecordingGroups=function(options){var url=this.getUrl("LiveTv/Recordings/Groups",options||{});return this.getJSON(url)},ApiClient.prototype.getLiveTvRecordingGroup=function(id){if(!id)throw new Error("null id");var url=this.getUrl("LiveTv/Recordings/Groups/"+id);return this.getJSON(url)},ApiClient.prototype.getLiveTvRecording=function(id,userId){if(!id)throw new Error("null id");var options={};userId&&(options.userId=userId);var url=this.getUrl("LiveTv/Recordings/"+id,options);return this.getJSON(url)},ApiClient.prototype.getLiveTvProgram=function(id,userId){if(!id)throw new Error("null id");var options={};userId&&(options.userId=userId);var url=this.getUrl("LiveTv/Programs/"+id,options);return this.getJSON(url)},ApiClient.prototype.deleteLiveTvRecording=function(id){if(!id)throw new Error("null id");var url=this.getUrl("LiveTv/Recordings/"+id);return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.cancelLiveTvTimer=function(id){if(!id)throw new Error("null id");var url=this.getUrl("LiveTv/Timers/"+id);return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.getLiveTvTimers=function(options){var url=this.getUrl("LiveTv/Timers",options||{});return this.getJSON(url)},ApiClient.prototype.getLiveTvTimer=function(id){if(!id)throw new Error("null id");var url=this.getUrl("LiveTv/Timers/"+id);return this.getJSON(url)},ApiClient.prototype.getNewLiveTvTimerDefaults=function(options){options=options||{};var url=this.getUrl("LiveTv/Timers/Defaults",options);return this.getJSON(url)},ApiClient.prototype.createLiveTvTimer=function(item){if(!item)throw new Error("null item");var url=this.getUrl("LiveTv/Timers");return this.ajax({type:"POST",url:url,data:JSON.stringify(item),contentType:"application/json"})},ApiClient.prototype.updateLiveTvTimer=function(item){if(!item)throw new Error("null item");var url=this.getUrl("LiveTv/Timers/"+item.Id);return this.ajax({type:"POST",url:url,data:JSON.stringify(item),contentType:"application/json"})},ApiClient.prototype.resetLiveTvTuner=function(id){if(!id)throw new Error("null id");var url=this.getUrl("LiveTv/Tuners/"+id+"/Reset");return this.ajax({type:"POST",url:url})},ApiClient.prototype.getLiveTvSeriesTimers=function(options){var url=this.getUrl("LiveTv/SeriesTimers",options||{});return this.getJSON(url)},ApiClient.prototype.getFileOrganizationResults=function(options){var url=this.getUrl("Library/FileOrganization",options||{});return this.getJSON(url)},ApiClient.prototype.deleteOriginalFileFromOrganizationResult=function(id){var url=this.getUrl("Library/FileOrganizations/"+id+"/File");return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.clearOrganizationLog=function(){var url=this.getUrl("Library/FileOrganizations");return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.performOrganization=function(id){var url=this.getUrl("Library/FileOrganizations/"+id+"/Organize");return this.ajax({type:"POST",url:url})},ApiClient.prototype.performEpisodeOrganization=function(id,options){var url=this.getUrl("Library/FileOrganizations/"+id+"/Episode/Organize");return this.ajax({type:"POST",url:url,data:JSON.stringify(options),contentType:"application/json"})},ApiClient.prototype.getLiveTvSeriesTimer=function(id){if(!id)throw new Error("null id");var url=this.getUrl("LiveTv/SeriesTimers/"+id);return this.getJSON(url)},ApiClient.prototype.cancelLiveTvSeriesTimer=function(id){if(!id)throw new Error("null id");var url=this.getUrl("LiveTv/SeriesTimers/"+id);return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.createLiveTvSeriesTimer=function(item){if(!item)throw new Error("null item");var url=this.getUrl("LiveTv/SeriesTimers");return this.ajax({type:"POST",url:url,data:JSON.stringify(item),contentType:"application/json"})},ApiClient.prototype.updateLiveTvSeriesTimer=function(item){if(!item)throw new Error("null item");var url=this.getUrl("LiveTv/SeriesTimers/"+item.Id);return this.ajax({type:"POST",url:url,data:JSON.stringify(item),contentType:"application/json"})},ApiClient.prototype.getRegistrationInfo=function(feature){var url=this.getUrl("Registrations/"+feature);return this.getJSON(url)},ApiClient.prototype.getSystemInfo=function(){var url=this.getUrl("System/Info");return this.getJSON(url)},ApiClient.prototype.getPublicSystemInfo=function(){var url=this.getUrl("System/Info/Public");return this.getJSON(url,!1)},ApiClient.prototype.getInstantMixFromItem=function(itemId,options){var url=this.getUrl("Items/"+itemId+"/InstantMix",options);return this.getJSON(url)},ApiClient.prototype.getEpisodes=function(itemId,options){var url=this.getUrl("Shows/"+itemId+"/Episodes",options);return this.getJSON(url)},ApiClient.prototype.getDisplayPreferences=function(id,userId,app){var url=this.getUrl("DisplayPreferences/"+id,{userId:userId,client:app});return this.getJSON(url)},ApiClient.prototype.updateDisplayPreferences=function(id,obj,userId,app){var url=this.getUrl("DisplayPreferences/"+id,{userId:userId,client:app});return this.ajax({type:"POST",url:url,data:JSON.stringify(obj),contentType:"application/json"})},ApiClient.prototype.getSeasons=function(itemId,options){var url=this.getUrl("Shows/"+itemId+"/Seasons",options);return this.getJSON(url)},ApiClient.prototype.getSimilarItems=function(itemId,options){var url=this.getUrl("Items/"+itemId+"/Similar",options);return this.getJSON(url)},ApiClient.prototype.getCultures=function(){var url=this.getUrl("Localization/cultures");return this.getJSON(url)},ApiClient.prototype.getCountries=function(){var url=this.getUrl("Localization/countries");return this.getJSON(url)},ApiClient.prototype.getPluginSecurityInfo=function(){var url=this.getUrl("Plugins/SecurityInfo");return this.getJSON(url)},ApiClient.prototype.getPlaybackInfo=function(itemId,options,deviceProfile){var postData={DeviceProfile:deviceProfile};return this.ajax({url:this.getUrl("Items/"+itemId+"/PlaybackInfo",options),type:"POST",data:JSON.stringify(postData),contentType:"application/json",dataType:"json"})},ApiClient.prototype.getIntros=function(itemId){return this.getJSON(this.getUrl("Users/"+this.getCurrentUserId()+"/Items/"+itemId+"/Intros"))},ApiClient.prototype.getDirectoryContents=function(path,options){if(!path)throw new Error("null path");if("string"!=typeof path)throw new Error("invalid path");options=options||{},options.path=path;var url=this.getUrl("Environment/DirectoryContents",options);return this.getJSON(url)},ApiClient.prototype.getNetworkShares=function(path){if(!path)throw new Error("null path");var options={};options.path=path;var url=this.getUrl("Environment/NetworkShares",options);return this.getJSON(url)},ApiClient.prototype.getParentPath=function(path){if(!path)throw new Error("null path");var options={};options.path=path;var url=this.getUrl("Environment/ParentPath",options);return this.ajax({type:"GET",url:url,dataType:"text"})},ApiClient.prototype.getDrives=function(){var url=this.getUrl("Environment/Drives");return this.getJSON(url)},ApiClient.prototype.getNetworkDevices=function(){var url=this.getUrl("Environment/NetworkDevices");return this.getJSON(url)},ApiClient.prototype.cancelPackageInstallation=function(installationId){if(!installationId)throw new Error("null installationId");var url=this.getUrl("Packages/Installing/"+installationId);return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.refreshItem=function(itemId,options){if(!itemId)throw new Error("null itemId");var url=this.getUrl("Items/"+itemId+"/Refresh",options||{});return this.ajax({type:"POST",url:url})},ApiClient.prototype.installPlugin=function(name,guid,updateClass,version){if(!name)throw new Error("null name");if(!updateClass)throw new Error("null updateClass");var options={updateClass:updateClass,AssemblyGuid:guid};version&&(options.version=version);var url=this.getUrl("Packages/Installed/"+name,options);return this.ajax({type:"POST",url:url})},ApiClient.prototype.restartServer=function(){var url=this.getUrl("System/Restart");return this.ajax({type:"POST",url:url})},ApiClient.prototype.shutdownServer=function(){var url=this.getUrl("System/Shutdown");return this.ajax({type:"POST",url:url})},ApiClient.prototype.getPackageInfo=function(name,guid){if(!name)throw new Error("null name");var options={AssemblyGuid:guid},url=this.getUrl("Packages/"+name,options);return this.getJSON(url)},ApiClient.prototype.getAvailableApplicationUpdate=function(){var url=this.getUrl("Packages/Updates",{PackageType:"System"});return this.getJSON(url)},ApiClient.prototype.getAvailablePluginUpdates=function(){var url=this.getUrl("Packages/Updates",{PackageType:"UserInstalled"});return this.getJSON(url)},ApiClient.prototype.getVirtualFolders=function(){var url="Library/VirtualFolders";return url=this.getUrl(url),this.getJSON(url)},ApiClient.prototype.getPhysicalPaths=function(){var url=this.getUrl("Library/PhysicalPaths");return this.getJSON(url)},ApiClient.prototype.getServerConfiguration=function(){var url=this.getUrl("System/Configuration");return this.getJSON(url)},ApiClient.prototype.getDevicesOptions=function(){var url=this.getUrl("System/Configuration/devices");return this.getJSON(url)},ApiClient.prototype.getContentUploadHistory=function(){var url=this.getUrl("Devices/CameraUploads",{DeviceId:this.deviceId()});return this.getJSON(url)},ApiClient.prototype.getNamedConfiguration=function(name){var url=this.getUrl("System/Configuration/"+name);return this.getJSON(url)},ApiClient.prototype.getScheduledTasks=function(options){options=options||{};var url=this.getUrl("ScheduledTasks",options);return this.getJSON(url)},ApiClient.prototype.startScheduledTask=function(id){if(!id)throw new Error("null id");var url=this.getUrl("ScheduledTasks/Running/"+id);return this.ajax({type:"POST",url:url})},ApiClient.prototype.getScheduledTask=function(id){if(!id)throw new Error("null id");var url=this.getUrl("ScheduledTasks/"+id);return this.getJSON(url)},ApiClient.prototype.getNextUpEpisodes=function(options){var url=this.getUrl("Shows/NextUp",options);return this.getJSON(url)},ApiClient.prototype.stopScheduledTask=function(id){if(!id)throw new Error("null id");var url=this.getUrl("ScheduledTasks/Running/"+id);return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.getPluginConfiguration=function(id){if(!id)throw new Error("null Id");var url=this.getUrl("Plugins/"+id+"/Configuration");return this.getJSON(url)},ApiClient.prototype.getAvailablePlugins=function(options){options=options||{},options.PackageType="UserInstalled";var url=this.getUrl("Packages",options);return this.getJSON(url)},ApiClient.prototype.uninstallPlugin=function(id){if(!id)throw new Error("null Id");var url=this.getUrl("Plugins/"+id);return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.removeVirtualFolder=function(name,refreshLibrary){if(!name)throw new Error("null name");var url="Library/VirtualFolders";return url=this.getUrl(url,{refreshLibrary:!!refreshLibrary,name:name}),this.ajax({type:"DELETE",url:url})},ApiClient.prototype.addVirtualFolder=function(name,type,refreshLibrary,libraryOptions){if(!name)throw new Error("null name");var options={};type&&(options.collectionType=type),options.refreshLibrary=!!refreshLibrary,options.name=name;var url="Library/VirtualFolders";return url=this.getUrl(url,options),this.ajax({type:"POST",url:url,data:JSON.stringify({LibraryOptions:libraryOptions}),contentType:"application/json"})},ApiClient.prototype.updateVirtualFolderOptions=function(id,libraryOptions){if(!id)throw new Error("null name");var url="Library/VirtualFolders/LibraryOptions";return url=this.getUrl(url),this.ajax({type:"POST",url:url,data:JSON.stringify({Id:id,LibraryOptions:libraryOptions}),contentType:"application/json"})},ApiClient.prototype.renameVirtualFolder=function(name,newName,refreshLibrary){if(!name)throw new Error("null name");var url="Library/VirtualFolders/Name";return url=this.getUrl(url,{refreshLibrary:!!refreshLibrary,newName:newName,name:name}),this.ajax({type:"POST",url:url})},ApiClient.prototype.addMediaPath=function(virtualFolderName,mediaPath,networkSharePath,refreshLibrary){if(!virtualFolderName)throw new Error("null virtualFolderName");if(!mediaPath)throw new Error("null mediaPath");var url="Library/VirtualFolders/Paths",pathInfo={Path:mediaPath};return networkSharePath&&(pathInfo.NetworkPath=networkSharePath),url=this.getUrl(url,{refreshLibrary:!!refreshLibrary}),this.ajax({type:"POST",url:url,data:JSON.stringify({Name:virtualFolderName,PathInfo:pathInfo}),contentType:"application/json"})},ApiClient.prototype.updateMediaPath=function(virtualFolderName,pathInfo){if(!virtualFolderName)throw new Error("null virtualFolderName"); if(!pathInfo)throw new Error("null pathInfo");var url="Library/VirtualFolders/Paths/Update";return url=this.getUrl(url),this.ajax({type:"POST",url:url,data:JSON.stringify({Name:virtualFolderName,PathInfo:pathInfo}),contentType:"application/json"})},ApiClient.prototype.removeMediaPath=function(virtualFolderName,mediaPath,refreshLibrary){if(!virtualFolderName)throw new Error("null virtualFolderName");if(!mediaPath)throw new Error("null mediaPath");var url="Library/VirtualFolders/Paths";return url=this.getUrl(url,{refreshLibrary:!!refreshLibrary,path:mediaPath,name:virtualFolderName}),this.ajax({type:"DELETE",url:url})},ApiClient.prototype.deleteUser=function(id){if(!id)throw new Error("null id");var url=this.getUrl("Users/"+id);return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.deleteUserImage=function(userId,imageType,imageIndex){if(!userId)throw new Error("null userId");if(!imageType)throw new Error("null imageType");var url=this.getUrl("Users/"+userId+"/Images/"+imageType);return null!=imageIndex&&(url+="/"+imageIndex),this.ajax({type:"DELETE",url:url})},ApiClient.prototype.deleteItemImage=function(itemId,imageType,imageIndex){if(!imageType)throw new Error("null imageType");var url=this.getUrl("Items/"+itemId+"/Images");return url+="/"+imageType,null!=imageIndex&&(url+="/"+imageIndex),this.ajax({type:"DELETE",url:url})},ApiClient.prototype.deleteItem=function(itemId){if(!itemId)throw new Error("null itemId");var url=this.getUrl("Items/"+itemId);return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.stopActiveEncodings=function(playSessionId){var options={deviceId:this.deviceId()};playSessionId&&(options.PlaySessionId=playSessionId);var url=this.getUrl("Videos/ActiveEncodings",options);return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.reportCapabilities=function(options){var url=this.getUrl("Sessions/Capabilities/Full");return this.ajax({type:"POST",url:url,data:JSON.stringify(options),contentType:"application/json"})},ApiClient.prototype.updateItemImageIndex=function(itemId,imageType,imageIndex,newIndex){if(!imageType)throw new Error("null imageType");var options={newIndex:newIndex},url=this.getUrl("Items/"+itemId+"/Images/"+imageType+"/"+imageIndex+"/Index",options);return this.ajax({type:"POST",url:url})},ApiClient.prototype.getItemImageInfos=function(itemId){var url=this.getUrl("Items/"+itemId+"/Images");return this.getJSON(url)},ApiClient.prototype.getCriticReviews=function(itemId,options){if(!itemId)throw new Error("null itemId");var url=this.getUrl("Items/"+itemId+"/CriticReviews",options);return this.getJSON(url)},ApiClient.prototype.getItemDownloadUrl=function(itemId){if(!itemId)throw new Error("itemId cannot be empty");var url="Items/"+itemId+"/Download";return this.getUrl(url,{api_key:this.accessToken()})},ApiClient.prototype.getSessions=function(options){var url=this.getUrl("Sessions",options);return this.getJSON(url)},ApiClient.prototype.uploadUserImage=function(userId,imageType,file){if(!userId)throw new Error("null userId");if(!imageType)throw new Error("null imageType");if(!file)throw new Error("File must be an image.");if("image/png"!==file.type&&"image/jpeg"!==file.type&&"image/jpeg"!==file.type)throw new Error("File must be an image.");var instance=this;return new Promise(function(resolve,reject){var reader=new FileReader;reader.onerror=function(){reject()},reader.onabort=function(){reject()},reader.onload=function(e){var data=e.target.result.split(",")[1],url=instance.getUrl("Users/"+userId+"/Images/"+imageType);instance.ajax({type:"POST",url:url,data:data,contentType:"image/"+file.name.substring(file.name.lastIndexOf(".")+1)}).then(resolve,reject)},reader.readAsDataURL(file)})},ApiClient.prototype.uploadItemImage=function(itemId,imageType,file){if(!itemId)throw new Error("null itemId");if(!imageType)throw new Error("null imageType");if(!file)throw new Error("File must be an image.");if("image/png"!==file.type&&"image/jpeg"!==file.type&&"image/jpeg"!==file.type)throw new Error("File must be an image.");var url=this.getUrl("Items/"+itemId+"/Images");url+="/"+imageType;var instance=this;return new Promise(function(resolve,reject){var reader=new FileReader;reader.onerror=function(){reject()},reader.onabort=function(){reject()},reader.onload=function(e){var data=e.target.result.split(",")[1];instance.ajax({type:"POST",url:url,data:data,contentType:"image/"+file.name.substring(file.name.lastIndexOf(".")+1)}).then(resolve,reject)},reader.readAsDataURL(file)})},ApiClient.prototype.getInstalledPlugins=function(){var options={},url=this.getUrl("Plugins",options);return this.getJSON(url)},ApiClient.prototype.getUser=function(id){if(!id)throw new Error("Must supply a userId");var url=this.getUrl("Users/"+id);return this.getJSON(url)},ApiClient.prototype.getStudio=function(name,userId){if(!name)throw new Error("null name");var options={};userId&&(options.userId=userId);var url=this.getUrl("Studios/"+this.encodeName(name),options);return this.getJSON(url)},ApiClient.prototype.getGenre=function(name,userId){if(!name)throw new Error("null name");var options={};userId&&(options.userId=userId);var url=this.getUrl("Genres/"+this.encodeName(name),options);return this.getJSON(url)},ApiClient.prototype.getMusicGenre=function(name,userId){if(!name)throw new Error("null name");var options={};userId&&(options.userId=userId);var url=this.getUrl("MusicGenres/"+this.encodeName(name),options);return this.getJSON(url)},ApiClient.prototype.getGameGenre=function(name,userId){if(!name)throw new Error("null name");var options={};userId&&(options.userId=userId);var url=this.getUrl("GameGenres/"+this.encodeName(name),options);return this.getJSON(url)},ApiClient.prototype.getArtist=function(name,userId){if(!name)throw new Error("null name");var options={};userId&&(options.userId=userId);var url=this.getUrl("Artists/"+this.encodeName(name),options);return this.getJSON(url)},ApiClient.prototype.getPerson=function(name,userId){if(!name)throw new Error("null name");var options={};userId&&(options.userId=userId);var url=this.getUrl("Persons/"+this.encodeName(name),options);return this.getJSON(url)},ApiClient.prototype.getPublicUsers=function(){var url=this.getUrl("users/public");return this.ajax({type:"GET",url:url,dataType:"json"},!1)},ApiClient.prototype.getUsers=function(options){var url=this.getUrl("users",options||{});return this.getJSON(url)},ApiClient.prototype.getParentalRatings=function(){var url=this.getUrl("Localization/ParentalRatings");return this.getJSON(url)},ApiClient.prototype.getDefaultImageQuality=function(imageType){return"backdrop"===imageType.toLowerCase()?80:90},ApiClient.prototype.getUserImageUrl=function(userId,options){if(!userId)throw new Error("null userId");options=options||{};var url="Users/"+userId+"/Images/"+options.type;return null!=options.index&&(url+="/"+options.index),normalizeImageOptions(this,options),delete options.type,delete options.index,this.getUrl(url,options)},ApiClient.prototype.getImageUrl=function(itemId,options){if(!itemId)throw new Error("itemId cannot be empty");options=options||{};var url="Items/"+itemId+"/Images/"+options.type;return null!=options.index&&(url+="/"+options.index),options.quality=options.quality||this.getDefaultImageQuality(options.type),this.normalizeImageOptions&&this.normalizeImageOptions(options),delete options.type,delete options.index,this.getUrl(url,options)},ApiClient.prototype.getScaledImageUrl=function(itemId,options){if(!itemId)throw new Error("itemId cannot be empty");options=options||{};var url="Items/"+itemId+"/Images/"+options.type;return null!=options.index&&(url+="/"+options.index),normalizeImageOptions(this,options),delete options.type,delete options.index,delete options.minScale,this.getUrl(url,options)},ApiClient.prototype.getThumbImageUrl=function(item,options){if(!item)throw new Error("null item");return options=options||{},options.imageType="thumb",item.ImageTags&&item.ImageTags.Thumb?(options.tag=item.ImageTags.Thumb,this.getImageUrl(item.Id,options)):item.ParentThumbItemId?(options.tag=item.ImageTags.ParentThumbImageTag,this.getImageUrl(item.ParentThumbItemId,options)):null},ApiClient.prototype.updateUserPassword=function(userId,currentPassword,newPassword){if(!userId)return Promise.reject();var url=this.getUrl("Users/"+userId+"/Password"),instance=this;return new Promise(function(resolve,reject){require(["cryptojs-sha1"],function(){instance.ajax({type:"POST",url:url,data:{currentPassword:CryptoJS.SHA1(currentPassword).toString(),newPassword:CryptoJS.SHA1(newPassword).toString()}}).then(resolve,reject)})})},ApiClient.prototype.updateEasyPassword=function(userId,newPassword){var instance=this;return new Promise(function(resolve,reject){if(!userId)return void reject();var url=this.getUrl("Users/"+userId+"/EasyPassword");require(["cryptojs-sha1"],function(){instance.ajax({type:"POST",url:url,data:{newPassword:CryptoJS.SHA1(newPassword).toString()}}).then(resolve,reject)})})},ApiClient.prototype.resetUserPassword=function(userId){if(!userId)throw new Error("null userId");var url=this.getUrl("Users/"+userId+"/Password"),postData={};return postData.resetPassword=!0,this.ajax({type:"POST",url:url,data:postData})},ApiClient.prototype.resetEasyPassword=function(userId){if(!userId)throw new Error("null userId");var url=this.getUrl("Users/"+userId+"/EasyPassword"),postData={};return postData.resetPassword=!0,this.ajax({type:"POST",url:url,data:postData})},ApiClient.prototype.updateServerConfiguration=function(configuration){if(!configuration)throw new Error("null configuration");var url=this.getUrl("System/Configuration");return this.ajax({type:"POST",url:url,data:JSON.stringify(configuration),contentType:"application/json"})},ApiClient.prototype.updateNamedConfiguration=function(name,configuration){if(!configuration)throw new Error("null configuration");var url=this.getUrl("System/Configuration/"+name);return this.ajax({type:"POST",url:url,data:JSON.stringify(configuration),contentType:"application/json"})},ApiClient.prototype.updateItem=function(item){if(!item)throw new Error("null item");var url=this.getUrl("Items/"+item.Id);return this.ajax({type:"POST",url:url,data:JSON.stringify(item),contentType:"application/json"})},ApiClient.prototype.updatePluginSecurityInfo=function(info){var url=this.getUrl("Plugins/SecurityInfo");return this.ajax({type:"POST",url:url,data:JSON.stringify(info),contentType:"application/json"})},ApiClient.prototype.createUser=function(name){var url=this.getUrl("Users/New");return this.ajax({type:"POST",url:url,data:{Name:name},dataType:"json"})},ApiClient.prototype.updateUser=function(user){if(!user)throw new Error("null user");var url=this.getUrl("Users/"+user.Id);return this.ajax({type:"POST",url:url,data:JSON.stringify(user),contentType:"application/json"})},ApiClient.prototype.updateUserPolicy=function(userId,policy){if(!userId)throw new Error("null userId");if(!policy)throw new Error("null policy");var url=this.getUrl("Users/"+userId+"/Policy");return this.ajax({type:"POST",url:url,data:JSON.stringify(policy),contentType:"application/json"})},ApiClient.prototype.updateUserConfiguration=function(userId,configuration){if(!userId)throw new Error("null userId");if(!configuration)throw new Error("null configuration");var url=this.getUrl("Users/"+userId+"/Configuration");return this.ajax({type:"POST",url:url,data:JSON.stringify(configuration),contentType:"application/json"})},ApiClient.prototype.updateScheduledTaskTriggers=function(id,triggers){if(!id)throw new Error("null id");if(!triggers)throw new Error("null triggers");var url=this.getUrl("ScheduledTasks/"+id+"/Triggers");return this.ajax({type:"POST",url:url,data:JSON.stringify(triggers),contentType:"application/json"})},ApiClient.prototype.updatePluginConfiguration=function(id,configuration){if(!id)throw new Error("null Id");if(!configuration)throw new Error("null configuration");var url=this.getUrl("Plugins/"+id+"/Configuration");return this.ajax({type:"POST",url:url,data:JSON.stringify(configuration),contentType:"application/json"})},ApiClient.prototype.getAncestorItems=function(itemId,userId){if(!itemId)throw new Error("null itemId");var options={};userId&&(options.userId=userId);var url=this.getUrl("Items/"+itemId+"/Ancestors",options);return this.getJSON(url)},ApiClient.prototype.getItems=function(userId,options){var url;return url="string"===(typeof userId).toString().toLowerCase()?this.getUrl("Users/"+userId+"/Items",options):this.getUrl("Items",options),this.getJSON(url)},ApiClient.prototype.getMovieRecommendations=function(options){return this.getJSON(this.getUrl("Movies/Recommendations",options))},ApiClient.prototype.getUpcomingEpisodes=function(options){return this.getJSON(this.getUrl("Shows/Upcoming",options))},ApiClient.prototype.getChannels=function(query){return this.getJSON(this.getUrl("Channels",query||{}))},ApiClient.prototype.getLatestChannelItems=function(query){return this.getJSON(this.getUrl("Channels/Items/Latest",query))},ApiClient.prototype.getUserViews=function(options,userId){options=options||{};var url=this.getUrl("Users/"+(userId||this.getCurrentUserId())+"/Views",options);return this.getJSON(url)},ApiClient.prototype.getArtists=function(userId,options){if(!userId)throw new Error("null userId");options=options||{},options.userId=userId;var url=this.getUrl("Artists",options);return this.getJSON(url)},ApiClient.prototype.getAlbumArtists=function(userId,options){if(!userId)throw new Error("null userId");options=options||{},options.userId=userId;var url=this.getUrl("Artists/AlbumArtists",options);return this.getJSON(url)},ApiClient.prototype.getGenres=function(userId,options){if(!userId)throw new Error("null userId");options=options||{},options.userId=userId;var url=this.getUrl("Genres",options);return this.getJSON(url)},ApiClient.prototype.getMusicGenres=function(userId,options){if(!userId)throw new Error("null userId");options=options||{},options.userId=userId;var url=this.getUrl("MusicGenres",options);return this.getJSON(url)},ApiClient.prototype.getGameGenres=function(userId,options){if(!userId)throw new Error("null userId");options=options||{},options.userId=userId;var url=this.getUrl("GameGenres",options);return this.getJSON(url)},ApiClient.prototype.getPeople=function(userId,options){if(!userId)throw new Error("null userId");options=options||{},options.userId=userId;var url=this.getUrl("Persons",options);return this.getJSON(url)},ApiClient.prototype.getStudios=function(userId,options){if(!userId)throw new Error("null userId");options=options||{},options.userId=userId;var url=this.getUrl("Studios",options);return this.getJSON(url)},ApiClient.prototype.getLocalTrailers=function(userId,itemId){if(!userId)throw new Error("null userId");if(!itemId)throw new Error("null itemId");var url=this.getUrl("Users/"+userId+"/Items/"+itemId+"/LocalTrailers");return this.getJSON(url)},ApiClient.prototype.getGameSystems=function(){var options={},userId=this.getCurrentUserId();userId&&(options.userId=userId);var url=this.getUrl("Games/SystemSummaries",options);return this.getJSON(url)},ApiClient.prototype.getAdditionalVideoParts=function(userId,itemId){if(!itemId)throw new Error("null itemId");var options={};userId&&(options.userId=userId);var url=this.getUrl("Videos/"+itemId+"/AdditionalParts",options);return this.getJSON(url)},ApiClient.prototype.getThemeMedia=function(userId,itemId,inherit){if(!itemId)throw new Error("null itemId");var options={};userId&&(options.userId=userId),options.InheritFromParent=inherit||!1;var url=this.getUrl("Items/"+itemId+"/ThemeMedia",options);return this.getJSON(url)},ApiClient.prototype.getSearchHints=function(options){var url=this.getUrl("Search/Hints",options),serverId=this.serverId();return this.getJSON(url).then(function(result){return result.SearchHints.forEach(function(i){i.ServerId=serverId}),result})},ApiClient.prototype.getSpecialFeatures=function(userId,itemId){if(!userId)throw new Error("null userId");if(!itemId)throw new Error("null itemId");var url=this.getUrl("Users/"+userId+"/Items/"+itemId+"/SpecialFeatures");return this.getJSON(url)},ApiClient.prototype.getDateParamValue=function(date){function formatDigit(i){return i<10?"0"+i:i}var d=date;return""+d.getFullYear()+formatDigit(d.getMonth()+1)+formatDigit(d.getDate())+formatDigit(d.getHours())+formatDigit(d.getMinutes())+formatDigit(d.getSeconds())},ApiClient.prototype.markPlayed=function(userId,itemId,date){if(!userId)throw new Error("null userId");if(!itemId)throw new Error("null itemId");var options={};date&&(options.DatePlayed=this.getDateParamValue(date));var url=this.getUrl("Users/"+userId+"/PlayedItems/"+itemId,options);return this.ajax({type:"POST",url:url,dataType:"json"})},ApiClient.prototype.markUnplayed=function(userId,itemId){if(!userId)throw new Error("null userId");if(!itemId)throw new Error("null itemId");var url=this.getUrl("Users/"+userId+"/PlayedItems/"+itemId);return this.ajax({type:"DELETE",url:url,dataType:"json"})},ApiClient.prototype.updateFavoriteStatus=function(userId,itemId,isFavorite){if(!userId)throw new Error("null userId");if(!itemId)throw new Error("null itemId");var url=this.getUrl("Users/"+userId+"/FavoriteItems/"+itemId),method=isFavorite?"POST":"DELETE";return this.ajax({type:method,url:url,dataType:"json"})},ApiClient.prototype.updateUserItemRating=function(userId,itemId,likes){if(!userId)throw new Error("null userId");if(!itemId)throw new Error("null itemId");var url=this.getUrl("Users/"+userId+"/Items/"+itemId+"/Rating",{likes:likes});return this.ajax({type:"POST",url:url,dataType:"json"})},ApiClient.prototype.getItemCounts=function(userId){var options={};userId&&(options.userId=userId);var url=this.getUrl("Items/Counts",options);return this.getJSON(url)},ApiClient.prototype.clearUserItemRating=function(userId,itemId){if(!userId)throw new Error("null userId");if(!itemId)throw new Error("null itemId");var url=this.getUrl("Users/"+userId+"/Items/"+itemId+"/Rating");return this.ajax({type:"DELETE",url:url,dataType:"json"})},ApiClient.prototype.reportPlaybackStart=function(options){if(!options)throw new Error("null options");this.lastPlaybackProgressReport=0,stopBitrateDetection(this);var url=this.getUrl("Sessions/Playing");return this.ajax({type:"POST",data:JSON.stringify(options),contentType:"application/json",url:url})},ApiClient.prototype.reportPlaybackProgress=function(options){if(!options)throw new Error("null options");if("timeupdate"===(options.EventName||"timeupdate")){var now=(new Date).getTime();if(now-(this.lastPlaybackProgressReport||0)<=1e4)return;this.lastPlaybackProgressReport=now}else this.lastPlaybackProgressReport=0;var url=this.getUrl("Sessions/Playing/Progress");return this.ajax({type:"POST",data:JSON.stringify(options),contentType:"application/json",url:url})},ApiClient.prototype.reportOfflineActions=function(actions){if(!actions)throw new Error("null actions");var url=this.getUrl("Sync/OfflineActions");return this.ajax({type:"POST",data:JSON.stringify(actions),contentType:"application/json",url:url})},ApiClient.prototype.syncData=function(data){if(!data)throw new Error("null data");var url=this.getUrl("Sync/Data");return this.ajax({type:"POST",data:JSON.stringify(data),contentType:"application/json",url:url,dataType:"json"})},ApiClient.prototype.getReadySyncItems=function(deviceId){if(!deviceId)throw new Error("null deviceId");var url=this.getUrl("Sync/Items/Ready",{TargetId:deviceId});return this.getJSON(url)},ApiClient.prototype.reportSyncJobItemTransferred=function(syncJobItemId){if(!syncJobItemId)throw new Error("null syncJobItemId");var url=this.getUrl("Sync/JobItems/"+syncJobItemId+"/Transferred");return this.ajax({type:"POST",url:url})},ApiClient.prototype.cancelSyncItems=function(itemIds,targetId){if(!itemIds)throw new Error("null itemIds");var url=this.getUrl("Sync/"+(targetId||this.deviceId())+"/Items",{ItemIds:itemIds.join(",")});return this.ajax({type:"DELETE",url:url})},ApiClient.prototype.reportPlaybackStopped=function(options){if(!options)throw new Error("null options");this.lastPlaybackProgressReport=0,redetectBitrate(this);var url=this.getUrl("Sessions/Playing/Stopped");return this.ajax({type:"POST",data:JSON.stringify(options),contentType:"application/json",url:url})},ApiClient.prototype.sendPlayCommand=function(sessionId,options){if(!sessionId)throw new Error("null sessionId");if(!options)throw new Error("null options");var url=this.getUrl("Sessions/"+sessionId+"/Playing",options);return this.ajax({type:"POST",url:url})},ApiClient.prototype.sendCommand=function(sessionId,command){if(!sessionId)throw new Error("null sessionId");if(!command)throw new Error("null command");var url=this.getUrl("Sessions/"+sessionId+"/Command"),ajaxOptions={type:"POST",url:url};return ajaxOptions.data=JSON.stringify(command),ajaxOptions.contentType="application/json",this.ajax(ajaxOptions)},ApiClient.prototype.sendMessageCommand=function(sessionId,options){if(!sessionId)throw new Error("null sessionId");if(!options)throw new Error("null options");var url=this.getUrl("Sessions/"+sessionId+"/Message",options);return this.ajax({type:"POST",url:url})},ApiClient.prototype.sendPlayStateCommand=function(sessionId,command,options){if(!sessionId)throw new Error("null sessionId");if(!command)throw new Error("null command");var url=this.getUrl("Sessions/"+sessionId+"/Playing/"+command,options||{});return this.ajax({type:"POST",url:url})},ApiClient.prototype.createPackageReview=function(review){var url=this.getUrl("Packages/Reviews/"+review.id,review);return this.ajax({type:"POST",url:url})},ApiClient.prototype.getPackageReviews=function(packageId,minRating,maxRating,limit){if(!packageId)throw new Error("null packageId");var options={};minRating&&(options.MinRating=minRating),maxRating&&(options.MaxRating=maxRating),limit&&(options.Limit=limit);var url=this.getUrl("Packages/"+packageId+"/Reviews",options);return this.getJSON(url)},ApiClient.prototype.getSmartMatchInfos=function(options){options=options||{};var url=this.getUrl("Library/FileOrganizations/SmartMatches",options);return this.ajax({type:"GET",url:url,dataType:"json"})},ApiClient.prototype.deleteSmartMatchEntries=function(entries){var url=this.getUrl("Library/FileOrganizations/SmartMatches/Delete"),postData={Entries:entries};return this.ajax({type:"POST",url:url,data:JSON.stringify(postData),contentType:"application/json"})},ApiClient.prototype.getEndpointInfo=function(){return this.getJSON(this.getUrl("System/Endpoint"))},ApiClient.prototype.getLatestItems=function(options){return options=options||{},this.getJSON(this.getUrl("Users/"+this.getCurrentUserId()+"/Items/Latest",options))},ApiClient}); \ No newline at end of file diff --git a/dashboard-ui/bower_components/emby-webcomponents/input/gamepadtokey.js b/dashboard-ui/bower_components/emby-webcomponents/input/gamepadtokey.js index 3a3efd6803..bae55cb1a3 100644 --- a/dashboard-ui/bower_components/emby-webcomponents/input/gamepadtokey.js +++ b/dashboard-ui/bower_components/emby-webcomponents/input/gamepadtokey.js @@ -1 +1 @@ -require(["apphost"],function(appHost){"use strict";function throttle(key){var time=times[key]||0,now=(new Date).getTime();return now-time>=200}function resetThrottle(key){times[key]=(new Date).getTime()}function allowInput(){return!document.hidden}function raiseEvent(name,key,keyCode){if(allowInput()){var event=document.createEvent("Event");event.initEvent(name,!0,!0),event.key=key,event.keyCode=keyCode,(document.activeElement||document.body).dispatchEvent(event)}}function clickElement(elem){allowInput()&&elem.click()}function raiseKeyEvent(oldPressedState,newPressedState,key,keyCode,enableRepeatKeyDown,clickonKeyUp){if(newPressedState===!0){var fire=!1;oldPressedState===!1?(fire=!0,resetThrottle(key)):enableRepeatKeyDown&&(fire=throttle(key)),fire&&keyCode&&raiseEvent("keydown",key,keyCode)}else newPressedState===!1&&oldPressedState===!0&&(resetThrottle(key),keyCode&&raiseEvent("keyup",key,keyCode),clickonKeyUp&&clickElement(document.activeElement||window))}function runInputLoop(){var gamepads;navigator.getGamepads?gamepads=navigator.getGamepads():navigator.webkitGetGamepads&&(gamepads=navigator.webkitGetGamepads()),gamepads=gamepads||[];var i,j,len;for(i=0,len=gamepads.length;i_THUMB_STICK_THRESHOLD?_ButtonPressedState.setleftThumbstickRight(!0):leftStickX<-_THUMB_STICK_THRESHOLD?_ButtonPressedState.setleftThumbstickLeft(!0):leftStickY<-_THUMB_STICK_THRESHOLD?_ButtonPressedState.setleftThumbstickUp(!0):leftStickY>_THUMB_STICK_THRESHOLD?_ButtonPressedState.setleftThumbstickDown(!0):(_ButtonPressedState.setleftThumbstickLeft(!1),_ButtonPressedState.setleftThumbstickRight(!1),_ButtonPressedState.setleftThumbstickUp(!1),_ButtonPressedState.setleftThumbstickDown(!1));var buttons=gamepad.buttons;for(j=0,len=buttons.length;j=200}function resetThrottle(key){times[key]=(new Date).getTime()}function allowInput(){return!0}function raiseEvent(name,key,keyCode){if(allowInput()){var event=document.createEvent("Event");event.initEvent(name,!0,!0),event.key=key,event.keyCode=keyCode,(document.activeElement||document.body).dispatchEvent(event)}}function clickElement(elem){allowInput()&&elem.click()}function raiseKeyEvent(oldPressedState,newPressedState,key,keyCode,enableRepeatKeyDown,clickonKeyUp){if(newPressedState===!0){var fire=!1;oldPressedState===!1?(fire=!0,resetThrottle(key)):enableRepeatKeyDown&&(fire=throttle(key)),fire&&keyCode&&raiseEvent("keydown",key,keyCode)}else newPressedState===!1&&oldPressedState===!0&&(resetThrottle(key),keyCode&&raiseEvent("keyup",key,keyCode),clickonKeyUp&&clickElement(document.activeElement||window))}function runInputLoop(){var gamepads;navigator.getGamepads?gamepads=navigator.getGamepads():navigator.webkitGetGamepads&&(gamepads=navigator.webkitGetGamepads()),gamepads=gamepads||[];var i,j,len;for(i=0,len=gamepads.length;i_THUMB_STICK_THRESHOLD?_ButtonPressedState.setleftThumbstickRight(!0):leftStickX<-_THUMB_STICK_THRESHOLD?_ButtonPressedState.setleftThumbstickLeft(!0):leftStickY<-_THUMB_STICK_THRESHOLD?_ButtonPressedState.setleftThumbstickUp(!0):leftStickY>_THUMB_STICK_THRESHOLD?_ButtonPressedState.setleftThumbstickDown(!0):(_ButtonPressedState.setleftThumbstickLeft(!1),_ButtonPressedState.setleftThumbstickRight(!1),_ButtonPressedState.setleftThumbstickUp(!1),_ButtonPressedState.setleftThumbstickDown(!1));var buttons=gamepad.buttons;for(j=0,len=buttons.length;j=interceptors.length)return void resolve();var interceptor=interceptors[index];interceptor.intercept(options).then(function(){runNextPrePlay(interceptors,index+1,options,resolve,reject)},reject)}function playAfterBitrateDetect(connectionManager,maxBitrate,item,playOptions,onPlaybackStartedFn){var promise,startPosition=playOptions.startPositionTicks,player=getPlayer(item,playOptions),activePlayer=currentPlayer;return activePlayer?(playNextAfterEnded=!1,promise=onPlaybackChanging(activePlayer,player,item)):promise=Promise.resolve(),isServerItem(item)&&"Game"!==item.MediaType?Promise.all([promise,player.getDeviceProfile(item)]).then(function(responses){var deviceProfile=responses[1],apiClient=connectionManager.getApiClient(item.ServerId);return getPlaybackMediaSource(apiClient,deviceProfile,maxBitrate,item,startPosition).then(function(mediaSource){return createStreamInfo(apiClient,item.MediaType,item,mediaSource,startPosition).then(function(streamInfo){return streamInfo.fullscreen=playOptions.fullscreen,getPlayerData(player).isChangingStream=!1,getPlayerData(player).maxStreamingBitrate=maxBitrate,player.play(streamInfo).then(function(){loading.hide(),onPlaybackStartedFn(),onPlaybackStarted(player,playOptions,streamInfo,mediaSource)},function(){onPlaybackStartedFn(),onPlaybackStarted(player,playOptions,streamInfo,mediaSource),setTimeout(function(err){onPlaybackError.call(player,err,{type:"mediadecodeerror"})},100)})})})}):promise.then(function(){var streamInfo=createStreamInfoFromUrlItem(item);return streamInfo.fullscreen=playOptions.fullscreen,getPlayerData(player).isChangingStream=!1,player.play(streamInfo).then(function(){loading.hide(),onPlaybackStartedFn(),onPlaybackStarted(player,playOptions,streamInfo)},function(){self.stop(player)})})}function createStreamInfoFromUrlItem(item){return{url:item.Url||item.Path,playMethod:"DirectPlay",item:item,textTracks:[],mediaType:item.MediaType}}function backdropImageUrl(apiClient,item,options){return options=options||{},options.type=options.type||"Backdrop",options.maxWidth||options.width||options.maxHeight||options.height||(options.quality=100),item.BackdropImageTags&&item.BackdropImageTags.length?(options.tag=item.BackdropImageTags[0],apiClient.getScaledImageUrl(item.Id,options)):item.ParentBackdropImageTags&&item.ParentBackdropImageTags.length?(options.tag=item.ParentBackdropImageTags[0],apiClient.getScaledImageUrl(item.ParentBackdropItemId,options)):null}function getMimeType(type,container){if(container=(container||"").toLowerCase(),"audio"===type){if("opus"===container)return"audio/ogg";if("webma"===container)return"audio/webm";if("m4a"===container)return"audio/mp4"}else if("video"===type){if("mkv"===container)return"video/x-matroska";if("m4v"===container)return"video/mp4";if("mov"===container)return"video/quicktime";if("mpg"===container)return"video/mpeg";if("flv"===container)return"video/x-flv"}return type+"/"+container}function createStreamInfo(apiClient,type,item,mediaSource,startPosition,forceTranscoding){var mediaUrl,contentType,directOptions,transcodingOffsetTicks=0,playerStartPositionTicks=startPosition,liveStreamId=mediaSource.LiveStreamId,playMethod="Transcode",mediaSourceContainer=(mediaSource.Container||"").toLowerCase();if("Video"===type)contentType=getMimeType("video",mediaSourceContainer),mediaSource.enableDirectPlay&&!forceTranscoding?(mediaUrl=mediaSource.Path,playMethod="DirectPlay"):mediaSource.SupportsDirectStream&&!forceTranscoding?(directOptions={Static:!0,mediaSourceId:mediaSource.Id,deviceId:apiClient.deviceId(),api_key:apiClient.accessToken()},mediaSource.ETag&&(directOptions.Tag=mediaSource.ETag),mediaSource.LiveStreamId&&(directOptions.LiveStreamId=mediaSource.LiveStreamId),mediaUrl=apiClient.getUrl("Videos/"+item.Id+"/stream."+mediaSourceContainer,directOptions),playMethod="DirectStream"):mediaSource.SupportsTranscoding&&(mediaUrl=apiClient.getUrl(mediaSource.TranscodingUrl),"hls"===mediaSource.TranscodingSubProtocol?contentType="application/x-mpegURL":(playerStartPositionTicks=null,contentType=getMimeType("video",mediaSource.TranscodingContainer),mediaUrl.toLowerCase().indexOf("copytimestamps=true")===-1&&(transcodingOffsetTicks=startPosition||0)));else if("Audio"===type)if(contentType=getMimeType("audio",mediaSourceContainer),mediaSource.enableDirectPlay&&!forceTranscoding)mediaUrl=mediaSource.Path,playMethod="DirectPlay";else{var isDirectStream=mediaSource.SupportsDirectStream;isDirectStream&&!forceTranscoding?(directOptions={Static:!0,mediaSourceId:mediaSource.Id,deviceId:apiClient.deviceId(),api_key:apiClient.accessToken()},mediaSource.ETag&&(directOptions.Tag=mediaSource.ETag),mediaSource.LiveStreamId&&(directOptions.LiveStreamId=mediaSource.LiveStreamId),mediaUrl=apiClient.getUrl("Audio/"+item.Id+"/stream."+mediaSourceContainer,directOptions),playMethod="DirectStream"):mediaSource.SupportsTranscoding&&(mediaUrl=apiClient.getUrl(mediaSource.TranscodingUrl),"hls"===mediaSource.TranscodingSubProtocol?contentType="application/x-mpegURL":(transcodingOffsetTicks=startPosition||0,playerStartPositionTicks=null,contentType=getMimeType("audio",mediaSource.TranscodingContainer)))}else"Game"===type&&(mediaUrl=mediaSource.Path,playMethod="DirectPlay");!mediaUrl&&mediaSource.SupportsDirectPlay&&(mediaUrl=mediaSource.Path,playMethod="DirectPlay");var resultInfo={url:mediaUrl,mimeType:contentType,transcodingOffsetTicks:transcodingOffsetTicks,playMethod:playMethod,playerStartPositionTicks:playerStartPositionTicks,item:item,mediaSource:mediaSource,textTracks:getTextTracks(apiClient,mediaSource),tracks:getTextTracks(apiClient,mediaSource),mediaType:type,liveStreamId:liveStreamId,playSessionId:getParam("playSessionId",mediaUrl),title:item.Name},backdropUrl=backdropImageUrl(apiClient,item,{});return backdropUrl&&(resultInfo.backdropUrl=backdropUrl),Promise.resolve(resultInfo)}function getParam(name,url){name=name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var regexS="[\\?&]"+name+"=([^&#]*)",regex=new RegExp(regexS,"i"),results=regex.exec(url);return null==results?"":decodeURIComponent(results[1].replace(/\+/g," "))}function getTextTracks(apiClient,mediaSource){for(var subtitleStreams=mediaSource.MediaStreams.filter(function(s){return"Subtitle"===s.Type}),textStreams=subtitleStreams.filter(function(s){return"External"===s.DeliveryMethod}),tracks=[],i=0,length=textStreams.length;i=playlistLength&&(newIndex=0);break;default:newIndex=self.getCurrentPlaylistIndex(player)+1}if(newIndex<0||newIndex>=playlistLength)return null;var item=playlist[newIndex];return item?{item:item,index:newIndex}:null}function queue(options,mode,player){if(player=player||currentPlayer,!player)return self.play(options);if(!enableLocalPlaylistManagement(player))return"next"===mode?player.queueNext(item):player.queue(item);if(options.items)return translateItemsForPlayback(options.items,options).then(function(items){queueAll(items,mode)});if(!options.serverId)throw new Error("serverId required!");return getItemsForPlayback(options.serverId,{Ids:options.ids.join(",")}).then(function(result){return translateItemsForPlayback(result.Items,options).then(function(items){queueAll(items,mode)})})}function queueAll(items,mode){for(var i=0,length=items.length;idatetime.parseISO8601Date(item.EndDate).getTime()||(new Date).getTime()=supported.length&&(index=0),self.setAspectRatio(supported[index].id,player)}},self.setAspectRatio=function(val,player){player=player||currentPlayer,player&&player.setAspectRatio&&player.setAspectRatio(val)},self.getSupportedAspectRatios=function(player){return player=player||currentPlayer,player&&player.getSupportedAspectRatios?player.getSupportedAspectRatios():[]},self.getAspectRatio=function(player){if(player=player||currentPlayer,player&&player.getAspectRatio)return player.getAspectRatio()};var brightnessOsdLoaded;self.setBrightness=function(val,player){player=player||currentPlayer,player&&(brightnessOsdLoaded||(brightnessOsdLoaded=!0,require(["brightnessOsd"])),player.setBrightness(val))},self.getBrightness=function(player){if(player=player||currentPlayer)return player.getBrightness()},self.setVolume=function(val,player){player=player||currentPlayer,player&&player.setVolume(val)},self.getVolume=function(player){if(player=player||currentPlayer)return player.getVolume()},self.volumeUp=function(player){player=player||currentPlayer,player&&player.volumeUp()},self.volumeDown=function(player){player=player||currentPlayer,player&&player.volumeDown()},self.changeAudioStreamIndex=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.changeAudioStreamIndex()},self.changeSubtitleStreamIndex=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.changeSubtitleStreamIndex()},self.getAudioStreamIndex=function(player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getAudioStreamIndex():getPlayerData(player).audioStreamIndex},self.setAudioStreamIndex=function(index,player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.setAudioStreamIndex(index):void("Transcode"!==getPlayerData(player).streamInfo.playMethod&&player.canSetAudioStreamIndex()?(player.setAudioStreamIndex(index),getPlayerData(player).audioStreamIndex=index):(changeStream(player,getCurrentTicks(player),{AudioStreamIndex:index}),getPlayerData(player).audioStreamIndex=index))},self.getMaxStreamingBitrate=function(player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getMaxStreamingBitrate():getPlayerData(player).maxStreamingBitrate||appSettings.maxStreamingBitrate()},self.enableAutomaticBitrateDetection=function(player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.enableAutomaticBitrateDetection():appSettings.enableAutomaticBitrateDetection()},self.setMaxStreamingBitrate=function(options,player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.setMaxStreamingBitrate(options);var promise;options.enableAutomaticBitrateDetection?(appSettings.enableAutomaticBitrateDetection(!0),promise=connectionManager.getApiClient(self.currentItem(player).ServerId).detectBitrate(!0)):(appSettings.enableAutomaticBitrateDetection(!1),promise=Promise.resolve(options.maxBitrate)),promise.then(function(bitrate){appSettings.maxStreamingBitrate(bitrate),changeStream(player,getCurrentTicks(player),{MaxStreamingBitrate:bitrate})})},self.isFullscreen=function(player){return player=player||currentPlayer,!player.isLocalPlayer||player.isFullscreen?player.isFullscreen():fullscreenManager.isFullScreen()},self.toggleFullscreen=function(player){return player=player||currentPlayer,!player.isLocalPlayer||player.toggleFulscreen?player.toggleFulscreen():void(fullscreenManager.isFullScreen()?fullscreenManager.exitFullscreen():fullscreenManager.requestFullscreen())},self.togglePictureInPicture=function(player){return player=player||currentPlayer,player.togglePictureInPicture()},self.getSubtitleStreamIndex=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.getSubtitleStreamIndex();if(!player)throw new Error("player cannot be null");return getPlayerData(player).subtitleStreamIndex},self.setSubtitleStreamIndex=function(index,player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.setSubtitleStreamIndex(index);var currentStream=getCurrentSubtitleStream(player),newStream=getSubtitleStream(player,index);if(currentStream||newStream){var selectedTrackElementIndex=-1,currentPlayMethod=(getPlayerData(player).streamInfo||{}).playMethod;currentStream&&!newStream?("Encode"===currentStream.DeliveryMethod||"Embed"===currentStream.DeliveryMethod&&"Transcode"===currentPlayMethod)&&changeStream(player,getCurrentTicks(player),{SubtitleStreamIndex:-1}):!currentStream&&newStream?"External"===newStream.DeliveryMethod?selectedTrackElementIndex=index:"Embed"===newStream.DeliveryMethod&&"Transcode"!==currentPlayMethod?selectedTrackElementIndex=index:changeStream(player,getCurrentTicks(player),{SubtitleStreamIndex:index}):currentStream&&newStream&&("External"===newStream.DeliveryMethod||"Embed"===newStream.DeliveryMethod&&"Transcode"!==currentPlayMethod?(selectedTrackElementIndex=index,"External"!==currentStream.DeliveryMethod&&"Embed"!==currentStream.DeliveryMethod&&changeStream(player,getCurrentTicks(player),{SubtitleStreamIndex:-1})):changeStream(player,getCurrentTicks(player),{SubtitleStreamIndex:index})),player.setSubtitleStreamIndex(selectedTrackElementIndex),getPlayerData(player).subtitleStreamIndex=index}},self.toggleDisplayMirroring=function(){self.enableDisplayMirroring(!self.enableDisplayMirroring())},self.enableDisplayMirroring=function(enabled){if(null!=enabled){var val=enabled?"1":"0";return void appSettings.set("displaymirror",val)}return"0"!==(appSettings.get("displaymirror")||"")},self.stop=function(player){return player=player||currentPlayer,player?(playNextAfterEnded=!1,player.stop(!0,!0)):Promise.resolve()},self.playPause=function(player){if(player=player||currentPlayer)return player.playPause?player.playPause():player.paused()?self.unpause(player):self.pause(player)},self.paused=function(player){if(player=player||currentPlayer)return player.paused()},self.pause=function(player){player=player||currentPlayer,player&&player.pause()},self.unpause=function(player){player=player||currentPlayer,player&&player.unpause()},self.seek=function(ticks,player){return ticks=Math.max(0,ticks),player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.seek(ticks):void changeStream(player,ticks)},self.nextChapter=function(player){player=player||currentPlayer;var item=self.currentItem(player),ticks=getCurrentTicks(player),nextChapter=(item.Chapters||[]).filter(function(i){return i.StartPositionTicks>ticks})[0];nextChapter?self.seek(nextChapter.StartPositionTicks,player):self.nextTrack(player)},self.previousChapter=function(player){player=player||currentPlayer;var item=self.currentItem(player),ticks=getCurrentTicks(player);ticks-=1e8,0===self.getCurrentPlaylistIndex(player)&&(ticks=Math.max(ticks,0));var previousChapters=(item.Chapters||[]).filter(function(i){return i.StartPositionTicks<=ticks});previousChapters.length?self.seek(previousChapters[previousChapters.length-1].StartPositionTicks,player):self.previousTrack(player)},self.fastForward=function(player){if(player=player||currentPlayer,null!=player.fastForward)return void player.fastForward(userSettings.skipForwardLength());var ticks=getCurrentTicks(player);ticks+=1e4*userSettings.skipForwardLength();var runTimeTicks=self.duration(player)||0;ticks0||canPlayerSeek(player)),item&&(state.NowPlayingItem=getNowPlayingItemForReporting(player,item,mediaSource)),state.MediaSource=mediaSource,Promise.resolve(state)},self.currentTime=function(player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.currentTime():getCurrentTicks(player)},self.duration=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.duration();if(!player)throw new Error("player cannot be null");var streamInfo=getPlayerData(player).streamInfo;if(streamInfo&&streamInfo.mediaSource&&streamInfo.mediaSource.RunTimeTicks)return streamInfo.mediaSource.RunTimeTicks;var playerDuration=player.duration();return playerDuration&&(playerDuration*=1e4),playerDuration};var currentId=0;self.getSubtitleUrl=function(textStream,serverId){var apiClient=connectionManager.getApiClient(serverId),textStreamUrl=textStream.IsExternalUrl?textStream.DeliveryUrl:apiClient.getUrl(textStream.DeliveryUrl);return textStreamUrl},self.setCurrentPlaylistItem=function(playlistItemId,player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.setCurrentPlaylistItem(playlistItemId);for(var newItem,newItemIndex,i=0,length=playlist.length;i=playlist.length)throw new Error("newIndex out of bounds");moveInArray(playlist,oldIndex,newIndex),events.trigger(player,"playlistitemmove",[{playlistItemId:playlistItemId,newIndex:newIndex}])}},self.getCurrentPlaylistIndex=function(i,player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getCurrentPlaylistIndex():findPlaylistIndex(currentPlaylistItemId,playlist)},self.getCurrentPlaylistItemId=function(i,player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getCurrentPlaylistItemId():currentPlaylistItemId},self.setRepeatMode=function(value,player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.setRepeatMode(value):(repeatMode=value,void events.trigger(player,"repeatmodechange"))},self.getRepeatMode=function(player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getRepeatMode():repeatMode},self.nextTrack=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.nextTrack();var newItemInfo=getNextItemInfo(player);if(newItemInfo){console.log("playing next track");var playOptions=Object.assign({},currentPlayOptions,{startPositionTicks:0});playInternal(newItemInfo.item,playOptions,function(){setPlaylistState(newItemInfo.item.PlaylistItemId,newItemInfo.index)})}},self.previousTrack=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.previousTrack();var newIndex=self.getCurrentPlaylistIndex(player)-1;if(newIndex>=0){var newItem=playlist[newIndex];if(newItem){var playOptions=Object.assign({},currentPlayOptions,{startPositionTicks:0});playInternal(newItem,playOptions,function(){setPlaylistState(newItem.PlaylistItemId,newIndex)})}}},self.queue=function(options,player){queue(options,"",player)},self.queueNext=function(options,player){queue(options,"next",player)},events.on(pluginManager,"registered",function(e,plugin){"mediaplayer"===plugin.type&&initMediaPlayer(plugin)}),pluginManager.ofType("mediaplayer").map(initMediaPlayer),window.addEventListener("beforeunload",function(e){var player=currentPlayer;player&&self.isPlaying(player)&&(playNextAfterEnded=!1,onPlaybackStopped.call(player))}),events.on(serverNotifications,"ServerShuttingDown",function(e,apiClient,data){self.setDefaultPlayerActive()}),events.on(serverNotifications,"ServerRestarting",function(e,apiClient,data){self.setDefaultPlayerActive()})}return PlaybackManager.prototype.sendCommand=function(cmd,player){switch(console.log("MediaController received command: "+cmd.Name),cmd.Name){case"SetRepeatMode":this.setRepeatMode(cmd.Arguments.RepeatMode,player);break;case"VolumeUp":this.volumeUp(player);break;case"VolumeDown":this.volumeDown(player);break;case"Mute":this.setMute(!0,player);break;case"Unmute":this.setMute(!1,player);break;case"ToggleMute":this.toggleMute(player);break;case"SetVolume":this.setVolume(cmd.Arguments.Volume,player);break;case"SetAspectRatio":this.setAspectRatio(cmd.Arguments.AspectRatio,player);break;case"SetBrightness":this.setBrightness(cmd.Arguments.Brightness,player);break;case"SetAudioStreamIndex":this.setAudioStreamIndex(parseInt(cmd.Arguments.Index),player);break;case"SetSubtitleStreamIndex":this.setSubtitleStreamIndex(parseInt(cmd.Arguments.Index),player);break;case"SetMaxStreamingBitrate":break;case"ToggleFullscreen":this.toggleFullscreen(player);break;default:player.sendCommand&&player.sendCommand(cmd)}},new PlaybackManager}); \ No newline at end of file +define(["events","datetime","appSettings","pluginManager","userSettings","globalize","connectionManager","loading","serverNotifications","apphost","fullscreenManager","layoutManager"],function(events,datetime,appSettings,pluginManager,userSettings,globalize,connectionManager,loading,serverNotifications,apphost,fullscreenManager,layoutManager){"use strict";function enableLocalPlaylistManagement(player){return!!player.isLocalPlayer}function bindToFullscreenChange(player){events.on(fullscreenManager,"fullscreenchange",function(){events.trigger(player,"fullscreenchange")})}function triggerPlayerChange(playbackManagerInstance,newPlayer,newTarget,previousPlayer,previousTargetInfo){(newPlayer||previousPlayer)&&(newTarget&&previousTargetInfo&&newTarget.id===previousTargetInfo.id||events.trigger(playbackManagerInstance,"playerchange",[newPlayer,newTarget,previousPlayer]))}function reportPlayback(state,serverId,method,progressEventName){if(serverId){var info=Object.assign({},state.PlayState);info.ItemId=state.NowPlayingItem.Id,progressEventName&&(info.EventName=progressEventName);var apiClient=connectionManager.getApiClient(serverId);apiClient[method](info)}}function PlaybackManager(){function displayPlayerInLocalGroup(player){return player.isLocalPlayer}function getSupportedCommands(player){if(player.isLocalPlayer){var list=["GoHome","GoToSettings","VolumeUp","VolumeDown","Mute","Unmute","ToggleMute","SetVolume","SetAudioStreamIndex","SetSubtitleStreamIndex","SetMaxStreamingBitrate","DisplayContent","GoToSearch","DisplayMessage","SetRepeatMode"];return apphost.supports("fullscreenchange")&&!layoutManager.tv&&list.push("ToggleFullscreen"),player.supports&&(player.supports("PictureInPicture")&&list.push("PictureInPicture"),player.supports("SetBrightness")&&list.push("SetBrightness"),player.supports("SetAspectRatio")&&list.push("SetAspectRatio")),list}throw new Error("player must define supported commands")}function createTarget(player){return{name:player.name,id:player.id,playerName:player.name,playableMediaTypes:["Audio","Video","Game"].map(player.canPlayMediaType),isLocalPlayer:player.isLocalPlayer,supportedCommands:getSupportedCommands(player)}}function getPlayerTargets(player){return player.getTargets?player.getTargets():Promise.resolve([createTarget(player)])}function getCurrentSubtitleStream(player){if(!player)throw new Error("player cannot be null");var index=getPlayerData(player).subtitleStreamIndex;return null==index||index===-1?null:getSubtitleStream(player,index)}function getSubtitleStream(player,index){return self.currentMediaSource(player).MediaStreams.filter(function(s){return"Subtitle"===s.Type&&s.Index===index})[0]}function setCurrentPlayerInternal(player,targetInfo){var previousPlayer=currentPlayer,previousTargetInfo=currentTargetInfo;if(player&&!targetInfo&&player.isLocalPlayer&&(targetInfo=createTarget(player)),player&&!targetInfo)throw new Error("targetInfo cannot be null");currentPairingId=null,currentPlayer=player,currentTargetInfo=targetInfo,targetInfo&&console.log("Active player: "+JSON.stringify(targetInfo)),player&&player.isLocalPlayer&&(lastLocalPlayer=player),previousPlayer&&self.endPlayerUpdates(previousPlayer),player&&self.beginPlayerUpdates(player),triggerPlayerChange(self,player,targetInfo,previousPlayer,previousTargetInfo)}function getAutomaticPlayers(){var player=currentPlayer;return player&&!enableLocalPlaylistManagement(player)?[player]:self.getPlayers().filter(enableLocalPlaylistManagement)}function canPlayerSeek(player){if(!player)throw new Error("player cannot be null");var playerData=getPlayerData(player),currentSrc=(playerData.streamInfo.url||"").toLowerCase();return currentSrc.indexOf(".m3u8")!==-1||"Transcode"!==playerData.streamInfo.playMethod&&player.duration()}function changeStream(player,ticks,params){if(canPlayerSeek(player)&&null==params)return void player.currentTime(parseInt(ticks/1e4));params=params||{};var liveStreamId=getPlayerData(player).streamInfo.liveStreamId,playSessionId=getPlayerData(player).streamInfo.playSessionId,playerData=getPlayerData(player),currentItem=playerData.streamInfo.item;player.getDeviceProfile(currentItem,{isRetry:params.EnableDirectPlay===!1}).then(function(deviceProfile){var audioStreamIndex=null==params.AudioStreamIndex?getPlayerData(player).audioStreamIndex:params.AudioStreamIndex,subtitleStreamIndex=null==params.SubtitleStreamIndex?getPlayerData(player).subtitleStreamIndex:params.SubtitleStreamIndex,currentMediaSource=playerData.streamInfo.mediaSource,apiClient=connectionManager.getApiClient(currentItem.ServerId);ticks&&(ticks=parseInt(ticks));var maxBitrate=params.MaxStreamingBitrate||self.getMaxStreamingBitrate(player);getPlaybackInfo(apiClient,currentItem.Id,deviceProfile,maxBitrate,ticks,currentMediaSource,audioStreamIndex,subtitleStreamIndex,liveStreamId,params.EnableDirectPlay,params.EnableDirectStream,params.AllowVideoStreamCopy,params.AllowAudioStreamCopy).then(function(result){validatePlaybackInfoResult(result)&&(currentMediaSource=result.MediaSources[0],createStreamInfo(apiClient,currentItem.MediaType,currentItem,currentMediaSource,ticks).then(function(streamInfo){return streamInfo.fullscreen=currentPlayOptions.fullscreen,streamInfo.url?(getPlayerData(player).subtitleStreamIndex=subtitleStreamIndex,getPlayerData(player).audioStreamIndex=audioStreamIndex,getPlayerData(player).maxStreamingBitrate=maxBitrate,void changeStreamToUrl(apiClient,player,playSessionId,streamInfo)):(showPlaybackInfoErrorMessage("NoCompatibleStream"),void self.nextTrack())}))})})}function changeStreamToUrl(apiClient,player,playSessionId,streamInfo,newPositionTicks){var playerData=getPlayerData(player);playerData.isChangingStream=!0,"Video"===playerData.MediaType?apiClient.stopActiveEncodings(playSessionId).then(function(){setSrcIntoPlayer(apiClient,player,streamInfo)}):setSrcIntoPlayer(apiClient,player,streamInfo)}function setSrcIntoPlayer(apiClient,player,streamInfo){player.play(streamInfo).then(function(){var playerData=getPlayerData(player);playerData.isChangingStream=!1,playerData.streamInfo=streamInfo,sendProgressUpdate(player,"timeupdate")},function(e){onPlaybackError.call(player,e,{type:"mediadecodeerror"})})}function getPlayerData(player){if(!player)throw new Error("player cannot be null");if(!player.name)throw new Error("player name cannot be null");var state=playerStates[player.name];return state||(playerStates[player.name]={},state=playerStates[player.name]),player}function getCurrentTicks(player){if(!player)throw new Error("player cannot be null");var playerTime=Math.floor(1e4*(player||currentPlayer).currentTime());return playerTime+=getPlayerData(player).streamInfo.transcodingOffsetTicks||0}function getNowPlayingItemForReporting(player,item,mediaSource){var nowPlayingItem=Object.assign({},item);return mediaSource&&(nowPlayingItem.RunTimeTicks=mediaSource.RunTimeTicks),nowPlayingItem.RunTimeTicks=nowPlayingItem.RunTimeTicks||1e4*player.duration(),nowPlayingItem}function translateItemsForPlayback(items,options){var promise,firstItem=items[0],serverId=firstItem.ServerId;return"Program"===firstItem.Type?promise=getItemsForPlayback(serverId,{Ids:firstItem.ChannelId}):"Playlist"===firstItem.Type?promise=getItemsForPlayback(serverId,{ParentId:firstItem.Id}):"MusicArtist"===firstItem.Type?promise=getItemsForPlayback(serverId,{ArtistIds:firstItem.Id,Filters:"IsNotFolder",Recursive:!0,SortBy:"SortName",MediaTypes:"Audio"}):"MusicGenre"===firstItem.Type?promise=getItemsForPlayback(serverId,{Genres:firstItem.Name,Filters:"IsNotFolder",Recursive:!0,SortBy:"SortName",MediaTypes:"Audio"}):firstItem.IsFolder?promise=getItemsForPlayback(serverId,{ParentId:firstItem.Id,Filters:"IsNotFolder",Recursive:!0,SortBy:"SortName",MediaTypes:"Audio,Video"}):"Episode"===firstItem.Type&&1===items.length&&getPlayer(firstItem,options).supportsProgress!==!1&&(promise=new Promise(function(resolve,reject){var apiClient=connectionManager.getApiClient(firstItem.ServerId);apiClient.getCurrentUser().then(function(user){return user.Configuration.EnableNextEpisodeAutoPlay&&firstItem.SeriesId?void apiClient.getEpisodes(firstItem.SeriesId,{IsVirtualUnaired:!1,IsMissing:!1,UserId:apiClient.getCurrentUserId(),Fields:"MediaSources,Chapters"}).then(function(episodesResult){var foundItem=!1;episodesResult.Items=episodesResult.Items.filter(function(e){return!!foundItem||e.Id===firstItem.Id&&(foundItem=!0,!0)}),episodesResult.TotalRecordCount=episodesResult.Items.length,resolve(episodesResult)},reject):void resolve(null)})})),promise?promise.then(function(result){return result?result.Items:items}):Promise.resolve(items)}function enableIntros(item){return"Video"===item.MediaType&&("TvChannel"!==item.Type&&("InProgress"!==item.Status&&isServerItem(item)))}function playWithIntros(items,options,user){var firstItem=items[0];"Video"===firstItem.MediaType;var afterPlayInternal=function(){for(var i=0,length=items.length;i=interceptors.length)return void resolve();var interceptor=interceptors[index];interceptor.intercept(options).then(function(){runNextPrePlay(interceptors,index+1,options,resolve,reject)},reject)}function playAfterBitrateDetect(connectionManager,maxBitrate,item,playOptions,onPlaybackStartedFn){var promise,startPosition=playOptions.startPositionTicks,player=getPlayer(item,playOptions),activePlayer=currentPlayer;return activePlayer?(playNextAfterEnded=!1,promise=onPlaybackChanging(activePlayer,player,item)):promise=Promise.resolve(),isServerItem(item)&&"Game"!==item.MediaType?Promise.all([promise,player.getDeviceProfile(item)]).then(function(responses){var deviceProfile=responses[1],apiClient=connectionManager.getApiClient(item.ServerId);return getPlaybackMediaSource(apiClient,deviceProfile,maxBitrate,item,startPosition).then(function(mediaSource){return createStreamInfo(apiClient,item.MediaType,item,mediaSource,startPosition).then(function(streamInfo){return streamInfo.fullscreen=playOptions.fullscreen,getPlayerData(player).isChangingStream=!1,getPlayerData(player).maxStreamingBitrate=maxBitrate,player.play(streamInfo).then(function(){loading.hide(),onPlaybackStartedFn(),onPlaybackStarted(player,playOptions,streamInfo,mediaSource)},function(){onPlaybackStartedFn(),onPlaybackStarted(player,playOptions,streamInfo,mediaSource),setTimeout(function(err){onPlaybackError.call(player,err,{type:"mediadecodeerror"})},100)})})})}):promise.then(function(){var streamInfo=createStreamInfoFromUrlItem(item);return streamInfo.fullscreen=playOptions.fullscreen,getPlayerData(player).isChangingStream=!1,player.play(streamInfo).then(function(){loading.hide(),onPlaybackStartedFn(),onPlaybackStarted(player,playOptions,streamInfo)},function(){self.stop(player)})})}function createStreamInfoFromUrlItem(item){return{url:item.Url||item.Path,playMethod:"DirectPlay",item:item,textTracks:[],mediaType:item.MediaType}}function backdropImageUrl(apiClient,item,options){return options=options||{},options.type=options.type||"Backdrop",options.maxWidth||options.width||options.maxHeight||options.height||(options.quality=100),item.BackdropImageTags&&item.BackdropImageTags.length?(options.tag=item.BackdropImageTags[0],apiClient.getScaledImageUrl(item.Id,options)):item.ParentBackdropImageTags&&item.ParentBackdropImageTags.length?(options.tag=item.ParentBackdropImageTags[0],apiClient.getScaledImageUrl(item.ParentBackdropItemId,options)):null}function getMimeType(type,container){if(container=(container||"").toLowerCase(),"audio"===type){if("opus"===container)return"audio/ogg";if("webma"===container)return"audio/webm";if("m4a"===container)return"audio/mp4"}else if("video"===type){if("mkv"===container)return"video/x-matroska";if("m4v"===container)return"video/mp4";if("mov"===container)return"video/quicktime";if("mpg"===container)return"video/mpeg";if("flv"===container)return"video/x-flv"}return type+"/"+container}function createStreamInfo(apiClient,type,item,mediaSource,startPosition,forceTranscoding){var mediaUrl,contentType,directOptions,transcodingOffsetTicks=0,playerStartPositionTicks=startPosition,liveStreamId=mediaSource.LiveStreamId,playMethod="Transcode",mediaSourceContainer=(mediaSource.Container||"").toLowerCase();if("Video"===type)contentType=getMimeType("video",mediaSourceContainer),mediaSource.enableDirectPlay&&!forceTranscoding?(mediaUrl=mediaSource.Path,playMethod="DirectPlay"):mediaSource.SupportsDirectStream&&!forceTranscoding?(directOptions={Static:!0,mediaSourceId:mediaSource.Id,deviceId:apiClient.deviceId(),api_key:apiClient.accessToken()},mediaSource.ETag&&(directOptions.Tag=mediaSource.ETag),mediaSource.LiveStreamId&&(directOptions.LiveStreamId=mediaSource.LiveStreamId),mediaUrl=apiClient.getUrl("Videos/"+item.Id+"/stream."+mediaSourceContainer,directOptions),playMethod="DirectStream"):mediaSource.SupportsTranscoding&&(mediaUrl=apiClient.getUrl(mediaSource.TranscodingUrl),"hls"===mediaSource.TranscodingSubProtocol?contentType="application/x-mpegURL":(playerStartPositionTicks=null,contentType=getMimeType("video",mediaSource.TranscodingContainer),mediaUrl.toLowerCase().indexOf("copytimestamps=true")===-1&&(transcodingOffsetTicks=startPosition||0)));else if("Audio"===type)if(contentType=getMimeType("audio",mediaSourceContainer),mediaSource.enableDirectPlay&&!forceTranscoding)mediaUrl=mediaSource.Path,playMethod="DirectPlay";else{var isDirectStream=mediaSource.SupportsDirectStream;isDirectStream&&!forceTranscoding?(directOptions={Static:!0,mediaSourceId:mediaSource.Id,deviceId:apiClient.deviceId(),api_key:apiClient.accessToken()},mediaSource.ETag&&(directOptions.Tag=mediaSource.ETag),mediaSource.LiveStreamId&&(directOptions.LiveStreamId=mediaSource.LiveStreamId),mediaUrl=apiClient.getUrl("Audio/"+item.Id+"/stream."+mediaSourceContainer,directOptions),playMethod="DirectStream"):mediaSource.SupportsTranscoding&&(mediaUrl=apiClient.getUrl(mediaSource.TranscodingUrl),"hls"===mediaSource.TranscodingSubProtocol?contentType="application/x-mpegURL":(transcodingOffsetTicks=startPosition||0,playerStartPositionTicks=null,contentType=getMimeType("audio",mediaSource.TranscodingContainer)))}else"Game"===type&&(mediaUrl=mediaSource.Path,playMethod="DirectPlay");!mediaUrl&&mediaSource.SupportsDirectPlay&&(mediaUrl=mediaSource.Path,playMethod="DirectPlay");var resultInfo={url:mediaUrl,mimeType:contentType,transcodingOffsetTicks:transcodingOffsetTicks,playMethod:playMethod,playerStartPositionTicks:playerStartPositionTicks,item:item,mediaSource:mediaSource,textTracks:getTextTracks(apiClient,mediaSource),tracks:getTextTracks(apiClient,mediaSource),mediaType:type,liveStreamId:liveStreamId,playSessionId:getParam("playSessionId",mediaUrl),title:item.Name},backdropUrl=backdropImageUrl(apiClient,item,{});return backdropUrl&&(resultInfo.backdropUrl=backdropUrl),Promise.resolve(resultInfo)}function getParam(name,url){name=name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var regexS="[\\?&]"+name+"=([^&#]*)",regex=new RegExp(regexS,"i"),results=regex.exec(url);return null==results?"":decodeURIComponent(results[1].replace(/\+/g," "))}function getTextTracks(apiClient,mediaSource){for(var subtitleStreams=mediaSource.MediaStreams.filter(function(s){return"Subtitle"===s.Type}),textStreams=subtitleStreams.filter(function(s){return"External"===s.DeliveryMethod}),tracks=[],i=0,length=textStreams.length;i=playlistLength&&(newIndex=0);break;default:newIndex=self.getCurrentPlaylistIndex(player)+1}if(newIndex<0||newIndex>=playlistLength)return null;var item=playlist[newIndex];return item?{item:item,index:newIndex}:null}function queue(options,mode,player){if(player=player||currentPlayer,!player)return self.play(options);if(!enableLocalPlaylistManagement(player))return"next"===mode?player.queueNext(item):player.queue(item);if(options.items)return translateItemsForPlayback(options.items,options).then(function(items){queueAll(items,mode)});if(!options.serverId)throw new Error("serverId required!");return getItemsForPlayback(options.serverId,{Ids:options.ids.join(",")}).then(function(result){return translateItemsForPlayback(result.Items,options).then(function(items){queueAll(items,mode)})})}function queueAll(items,mode){for(var i=0,length=items.length;idatetime.parseISO8601Date(item.EndDate).getTime()||(new Date).getTime()=supported.length&&(index=0),self.setAspectRatio(supported[index].id,player)}},self.setAspectRatio=function(val,player){player=player||currentPlayer,player&&player.setAspectRatio&&player.setAspectRatio(val)},self.getSupportedAspectRatios=function(player){return player=player||currentPlayer,player&&player.getSupportedAspectRatios?player.getSupportedAspectRatios():[]},self.getAspectRatio=function(player){if(player=player||currentPlayer,player&&player.getAspectRatio)return player.getAspectRatio()};var brightnessOsdLoaded;self.setBrightness=function(val,player){player=player||currentPlayer,player&&(brightnessOsdLoaded||(brightnessOsdLoaded=!0,require(["brightnessOsd"])),player.setBrightness(val))},self.getBrightness=function(player){if(player=player||currentPlayer)return player.getBrightness()},self.setVolume=function(val,player){player=player||currentPlayer,player&&player.setVolume(val)},self.getVolume=function(player){if(player=player||currentPlayer)return player.getVolume()},self.volumeUp=function(player){player=player||currentPlayer,player&&player.volumeUp()},self.volumeDown=function(player){player=player||currentPlayer,player&&player.volumeDown()},self.changeAudioStreamIndex=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.changeAudioStreamIndex()},self.changeSubtitleStreamIndex=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.changeSubtitleStreamIndex()},self.getAudioStreamIndex=function(player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getAudioStreamIndex():getPlayerData(player).audioStreamIndex},self.setAudioStreamIndex=function(index,player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.setAudioStreamIndex(index):void("Transcode"!==getPlayerData(player).streamInfo.playMethod&&player.canSetAudioStreamIndex()?(player.setAudioStreamIndex(index),getPlayerData(player).audioStreamIndex=index):(changeStream(player,getCurrentTicks(player),{AudioStreamIndex:index}),getPlayerData(player).audioStreamIndex=index))},self.getMaxStreamingBitrate=function(player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getMaxStreamingBitrate():getPlayerData(player).maxStreamingBitrate||appSettings.maxStreamingBitrate()},self.enableAutomaticBitrateDetection=function(player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.enableAutomaticBitrateDetection():appSettings.enableAutomaticBitrateDetection()},self.setMaxStreamingBitrate=function(options,player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.setMaxStreamingBitrate(options);var promise;options.enableAutomaticBitrateDetection?(appSettings.enableAutomaticBitrateDetection(!0),promise=connectionManager.getApiClient(self.currentItem(player).ServerId).detectBitrate(!0)):(appSettings.enableAutomaticBitrateDetection(!1),promise=Promise.resolve(options.maxBitrate)),promise.then(function(bitrate){appSettings.maxStreamingBitrate(bitrate),changeStream(player,getCurrentTicks(player),{MaxStreamingBitrate:bitrate})})},self.isFullscreen=function(player){return player=player||currentPlayer,!player.isLocalPlayer||player.isFullscreen?player.isFullscreen():fullscreenManager.isFullScreen()},self.toggleFullscreen=function(player){return player=player||currentPlayer,!player.isLocalPlayer||player.toggleFulscreen?player.toggleFulscreen():void(fullscreenManager.isFullScreen()?fullscreenManager.exitFullscreen():fullscreenManager.requestFullscreen())},self.togglePictureInPicture=function(player){return player=player||currentPlayer,player.togglePictureInPicture()},self.getSubtitleStreamIndex=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.getSubtitleStreamIndex();if(!player)throw new Error("player cannot be null");return getPlayerData(player).subtitleStreamIndex},self.setSubtitleStreamIndex=function(index,player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.setSubtitleStreamIndex(index);var currentStream=getCurrentSubtitleStream(player),newStream=getSubtitleStream(player,index);if(currentStream||newStream){var selectedTrackElementIndex=-1,currentPlayMethod=(getPlayerData(player).streamInfo||{}).playMethod;currentStream&&!newStream?("Encode"===currentStream.DeliveryMethod||"Embed"===currentStream.DeliveryMethod&&"Transcode"===currentPlayMethod)&&changeStream(player,getCurrentTicks(player),{SubtitleStreamIndex:-1}):!currentStream&&newStream?"External"===newStream.DeliveryMethod?selectedTrackElementIndex=index:"Embed"===newStream.DeliveryMethod&&"Transcode"!==currentPlayMethod?selectedTrackElementIndex=index:changeStream(player,getCurrentTicks(player),{SubtitleStreamIndex:index}):currentStream&&newStream&&("External"===newStream.DeliveryMethod||"Embed"===newStream.DeliveryMethod&&"Transcode"!==currentPlayMethod?(selectedTrackElementIndex=index,"External"!==currentStream.DeliveryMethod&&"Embed"!==currentStream.DeliveryMethod&&changeStream(player,getCurrentTicks(player),{SubtitleStreamIndex:-1})):changeStream(player,getCurrentTicks(player),{SubtitleStreamIndex:index})),player.setSubtitleStreamIndex(selectedTrackElementIndex),getPlayerData(player).subtitleStreamIndex=index}},self.toggleDisplayMirroring=function(){self.enableDisplayMirroring(!self.enableDisplayMirroring())},self.enableDisplayMirroring=function(enabled){if(null!=enabled){var val=enabled?"1":"0";return void appSettings.set("displaymirror",val)}return"0"!==(appSettings.get("displaymirror")||"")},self.stop=function(player){return player=player||currentPlayer,player?(playNextAfterEnded=!1,player.stop(!0,!0)):Promise.resolve()},self.playPause=function(player){if(player=player||currentPlayer)return player.playPause?player.playPause():player.paused()?self.unpause(player):self.pause(player)},self.paused=function(player){if(player=player||currentPlayer)return player.paused()},self.pause=function(player){player=player||currentPlayer,player&&player.pause()},self.unpause=function(player){player=player||currentPlayer,player&&player.unpause()},self.seek=function(ticks,player){return ticks=Math.max(0,ticks),player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.seek(ticks):void changeStream(player,ticks)},self.nextChapter=function(player){player=player||currentPlayer;var item=self.currentItem(player),ticks=getCurrentTicks(player),nextChapter=(item.Chapters||[]).filter(function(i){return i.StartPositionTicks>ticks})[0];nextChapter?self.seek(nextChapter.StartPositionTicks,player):self.nextTrack(player)},self.previousChapter=function(player){player=player||currentPlayer;var item=self.currentItem(player),ticks=getCurrentTicks(player);ticks-=1e8,0===self.getCurrentPlaylistIndex(player)&&(ticks=Math.max(ticks,0));var previousChapters=(item.Chapters||[]).filter(function(i){return i.StartPositionTicks<=ticks});previousChapters.length?self.seek(previousChapters[previousChapters.length-1].StartPositionTicks,player):self.previousTrack(player)},self.fastForward=function(player){if(player=player||currentPlayer,null!=player.fastForward)return void player.fastForward(userSettings.skipForwardLength());var ticks=getCurrentTicks(player);ticks+=1e4*userSettings.skipForwardLength();var runTimeTicks=self.duration(player)||0;ticks0||canPlayerSeek(player)),item&&(state.NowPlayingItem=getNowPlayingItemForReporting(player,item,mediaSource)),state.MediaSource=mediaSource,Promise.resolve(state)},self.currentTime=function(player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.currentTime():getCurrentTicks(player)},self.duration=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.duration();if(!player)throw new Error("player cannot be null");var streamInfo=getPlayerData(player).streamInfo;if(streamInfo&&streamInfo.mediaSource&&streamInfo.mediaSource.RunTimeTicks)return streamInfo.mediaSource.RunTimeTicks;var playerDuration=player.duration();return playerDuration&&(playerDuration*=1e4),playerDuration};var currentId=0;self.getSubtitleUrl=function(textStream,serverId){var apiClient=connectionManager.getApiClient(serverId),textStreamUrl=textStream.IsExternalUrl?textStream.DeliveryUrl:apiClient.getUrl(textStream.DeliveryUrl);return textStreamUrl},self.setCurrentPlaylistItem=function(playlistItemId,player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.setCurrentPlaylistItem(playlistItemId);for(var newItem,newItemIndex,i=0,length=playlist.length;i=playlist.length)throw new Error("newIndex out of bounds");moveInArray(playlist,oldIndex,newIndex),events.trigger(player,"playlistitemmove",[{playlistItemId:playlistItemId,newIndex:newIndex}])}},self.getCurrentPlaylistIndex=function(i,player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getCurrentPlaylistIndex():findPlaylistIndex(currentPlaylistItemId,playlist)},self.getCurrentPlaylistItemId=function(i,player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getCurrentPlaylistItemId():currentPlaylistItemId},self.setRepeatMode=function(value,player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.setRepeatMode(value):(repeatMode=value,void events.trigger(player,"repeatmodechange"))},self.getRepeatMode=function(player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getRepeatMode():repeatMode},self.nextTrack=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.nextTrack();var newItemInfo=getNextItemInfo(player);if(newItemInfo){console.log("playing next track");var playOptions=Object.assign({},currentPlayOptions,{startPositionTicks:0});playInternal(newItemInfo.item,playOptions,function(){setPlaylistState(newItemInfo.item.PlaylistItemId,newItemInfo.index)})}},self.previousTrack=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.previousTrack();var newIndex=self.getCurrentPlaylistIndex(player)-1;if(newIndex>=0){var newItem=playlist[newIndex];if(newItem){var playOptions=Object.assign({},currentPlayOptions,{startPositionTicks:0});playInternal(newItem,playOptions,function(){setPlaylistState(newItem.PlaylistItemId,newIndex)})}}},self.queue=function(options,player){queue(options,"",player)},self.queueNext=function(options,player){queue(options,"next",player)},events.on(pluginManager,"registered",function(e,plugin){"mediaplayer"===plugin.type&&initMediaPlayer(plugin)}),pluginManager.ofType("mediaplayer").map(initMediaPlayer),window.addEventListener("beforeunload",function(e){var player=currentPlayer;player&&self.isPlaying(player)&&(playNextAfterEnded=!1,onPlaybackStopped.call(player))}),events.on(serverNotifications,"ServerShuttingDown",function(e,apiClient,data){self.setDefaultPlayerActive()}),events.on(serverNotifications,"ServerRestarting",function(e,apiClient,data){self.setDefaultPlayerActive()})}return PlaybackManager.prototype.sendCommand=function(cmd,player){switch(console.log("MediaController received command: "+cmd.Name),cmd.Name){case"SetRepeatMode":this.setRepeatMode(cmd.Arguments.RepeatMode,player);break;case"VolumeUp":this.volumeUp(player);break;case"VolumeDown":this.volumeDown(player);break;case"Mute":this.setMute(!0,player);break;case"Unmute":this.setMute(!1,player);break;case"ToggleMute":this.toggleMute(player);break;case"SetVolume":this.setVolume(cmd.Arguments.Volume,player);break;case"SetAspectRatio":this.setAspectRatio(cmd.Arguments.AspectRatio,player);break;case"SetBrightness":this.setBrightness(cmd.Arguments.Brightness,player);break;case"SetAudioStreamIndex":this.setAudioStreamIndex(parseInt(cmd.Arguments.Index),player);break;case"SetSubtitleStreamIndex":this.setSubtitleStreamIndex(parseInt(cmd.Arguments.Index),player);break;case"SetMaxStreamingBitrate":break;case"ToggleFullscreen":this.toggleFullscreen(player);break;default:player.sendCommand&&player.sendCommand(cmd)}},new PlaybackManager}); \ No newline at end of file diff --git a/dashboard-ui/bower_components/hlsjs/dist/hls.min.js b/dashboard-ui/bower_components/hlsjs/dist/hls.min.js index 77d12c2df3..d9be19fd8a 100644 --- a/dashboard-ui/bower_components/hlsjs/dist/hls.min.js +++ b/dashboard-ui/bower_components/hlsjs/dist/hls.min.js @@ -1,8 +1,8 @@ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.Hls=e()}}(function(){var e;return function e(t,r,i){function a(s,o){if(!r[s]){if(!t[s]){var l="function"==typeof require&&require;if(!o&&l)return l(s,!0);if(n)return n(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var d=r[s]={exports:{}};t[s][0].call(d.exports,function(e){var r=t[s][1][e];return a(r?r:e)},d,d.exports,e,t,r,i)}return r[s].exports}for(var n="function"==typeof require&&require,s=0;s0&&this._events[e].length>r&&(this._events[e].warned=!0,console.trace),this},i.prototype.on=i.prototype.addListener,i.prototype.once=function(e,t){function r(){this.removeListener(e,r),i||(i=!0,t.apply(this,arguments))}if(!a(t))throw TypeError("listener must be a function");var i=!1;return r.listener=t,this.on(e,r),this},i.prototype.removeListener=function(e,t){var r,i,n,o;if(!a(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=this._events[e],n=r.length,i=-1,r===t||a(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(s(r)){for(o=n;o-- >0;)if(r[o]===t||r[o].listener&&r[o].listener===t){i=o;break}if(i<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(i,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},i.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[e],a(r))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},i.prototype.listeners=function(e){return this._events&&this._events[e]?a(this._events[e])?[this._events[e]]:this._events[e].slice():[]},i.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(a(t))return 1;if(t)return t.length}return 0},i.listenerCount=function(e,t){return e.listenerCount(t)}},{}],2:[function(t,r,i){!function(t){var a=/^((?:[^\/;?#]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/,n=/^([^\/;?#]*)(.*)$/,s={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var i=this.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");return i.path=s.normalizePath(i.path),s.buildURLFromParts(i)}var a=this.parseURL(t);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return r.alwaysNormalize?(a.path=s.normalizePath(a.path),s.buildURLFromParts(a)):t;var o=this.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=n.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var u={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(u.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var d=o.path,f=d.substring(0,d.lastIndexOf("/")+1)+a.path;u.path=s.normalizePath(f)}else u.path=o.path,a.params||(u.params=o.params,a.query||(u.query=o.query));return null===u.path&&(u.path=r.alwaysNormalize?s.normalizePath(a.path):a.path),s.buildURLFromParts(u)},parseURL:function(e){var t=a.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(/(?:\/|^)\.(?=\/)/g,"");e.length!==(e=e.replace(/(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/g,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};"object"==typeof i&&"object"==typeof r?r.exports=s:"function"==typeof e&&e.amd?e([],function(){return s}):"object"==typeof i?i.URLToolkit=s:t.URLToolkit=s}(this)},{}],3:[function(e,t,r){var i=arguments[3],a=arguments[4],n=arguments[5],s=JSON.stringify;t.exports=function(e,t){function r(e){p[e]=!0;for(var t in a[e][1]){var i=a[e][1][t];p[i]||r(i)}}for(var o,l=Object.keys(n),u=0,d=l.length;u500*r.duration/o){var l=e.levels,d=Math.max(1,n.bw?n.bw/8:1e3*n.loaded/s),f=l[r.level],c=f.realBitrate?Math.max(f.realBitrate,f.bitrate):f.bitrate,g=n.total?n.total:Math.max(n.loaded,Math.round(r.duration*c/8)),p=t.currentTime,y=(g-n.loaded)/d,m=(h.default.bufferInfo(t,p,e.config.maxBufferHole).end-p)/o;if(m<2*r.duration/o&&y>m){var E=void 0,b=void 0;for(b=r.level-1;b>a;b--){var T=l[b].realBitrate?Math.max(l[b].realBitrate,l[b].bitrate):l[b].bitrate;if((E=r.duration*T/(6.4*d))=i;u--){var d=l[u],f=d.details,c=f?f.totalduration/f.fragments.length:t,h=!!f&&f.live,g=void 0;g=u<=e?s*r:o*r;var p=l[u].realBitrate?Math.max(l[u].realBitrate,l[u].bitrate):l[u].bitrate,y=p*c/g;if(v.logger.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+u+"/"+Math.round(g)+"/"+p+"/"+c+"/"+n+"/"+y),g>p&&(!y||h||y=0)return c;v.logger.trace("rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering");var g=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay,p=i.abrBandWidthFactor,y=i.abrBandWidthUpFactor;if(0===f){var m=this.bitrateTestDelay;if(m){g=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-m,v.logger.trace("bitrate test took "+Math.round(1e3*m)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*g)+" ms"),p=y=1}}return c=this._findBestLevel(s,o,d,a,t,f+g,p,y,r),Math.max(c,0)}}]),t}(f.default);r.default=m},{31:31,32:32,33:33,35:35,49:49,51:51}],6:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;r0&&e===-1?(k.logger.log("audio:override startPosition with lastCurrentTime @"+t.toFixed(3)),this.state=R.IDLE):(this.lastCurrentTime=this.startPosition?this.startPosition:e,this.state=R.STARTING),this.nextLoadPosition=this.startPosition=this.lastCurrentTime,this.tick()}else this.startPosition=e,this.state=R.STOPPED}},{key:"stopLoad",value:function(){var e=this.fragCurrent;e&&(e.loader&&e.loader.abort(),this.fragCurrent=null),this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=R.STOPPED}},{key:"tick",value:function(){1===++this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(this.tick,1),this.ticks=0)}},{key:"doTick",value:function(){var e,t,r,i=this.hls,a=i.config;switch(this.state){case R.ERROR:case R.PAUSED:case R.BUFFER_FLUSHING:break;case R.STARTING:this.state=R.WAITING_TRACK,this.loadedmetadata=!1;break;case R.IDLE:var n=this.tracks;if(!n)break;if(!this.media&&(this.startFragRequested||!a.startFragPrefetch))break;e=this.loadedmetadata?this.media.currentTime:this.nextLoadPosition;var s=this.mediaBuffer?this.mediaBuffer:this.media,o=f.default.bufferInfo(s,e,a.maxBufferHole),l=o.len,d=o.end,c=this.fragPrevious,h=a.maxMaxBufferLength,g=this.audioSwitch,p=this.trackId;if((lE||o.nextStart))return;k.logger.log("alt audio track ahead of main track, seek to start of alt audio track"),this.media.currentTime=E+.05}if(r.initSegment&&!r.initSegment.data)T=r.initSegment;else if(d<=E){if(T=y[0],r.live&&T.loadIdx&&T.loadIdx===this.fragLoadIdx){var A=o.nextStart?o.nextStart:E;return k.logger.log("no alt audio available @currentTime:"+this.media.currentTime+", seeking @"+(A+.05)),void(this.media.currentTime=A+.05)}}else{var S=void 0,L=a.maxFragLookUpTolerance,w=c?y[c.sn-y[0].sn+1]:void 0,D=function(e){var t=Math.min(L,e.duration);return e.start+e.duration-t<=d?1:e.start-t>d&&e.start?-1:0};db-L&&(L=0),S=w&&!D(w)?w:u.default.search(y,D)):S=y[m-1],S&&(T=S,E=S.start,c&&T.level===c.level&&T.sn===c.sn&&(T.snO&&Math.abs(this.fragLoadIdx-T.loadIdx)=P||C)&&(k.logger.log("audioStreamController: retryDate reached, switch back to IDLE state"),this.state=R.IDLE);break;case R.WAITING_INIT_PTS:case R.STOPPED:case R.FRAG_LOADING:case R.PARSING:case R.PARSED:case R.ENDED:}}},{key:"onMediaAttached",value:function(e){var t=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),t.addEventListener("seeking",this.onvseeking),t.addEventListener("ended",this.onvended);var r=this.config;this.tracks&&r.autoStartLoad&&this.startLoad(r.startPosition)}},{key:"onMediaDetaching",value:function(){var e=this.media;e&&e.ended&&(k.logger.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0);var t=this.tracks;t&&t.forEach(function(e){e.details&&e.details.fragments.forEach(function(e){e.loadCounter=void 0})}),e&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvseeked=this.onvended=null),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.stopLoad()}},{key:"onMediaSeeking",value:function(){this.state===R.ENDED&&(this.state=R.IDLE),this.media&&(this.lastCurrentTime=this.media.currentTime),void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold),this.tick()}},{key:"onMediaEnded",value:function(){this.startPosition=this.lastCurrentTime=0}},{key:"onAudioTracksUpdated",value:function(e){k.logger.log("audio tracks updated"),this.tracks=e.audioTracks}},{key:"onAudioTrackSwitching",value:function(e){var t=!!e.url;this.trackId=e.id,this.state=R.IDLE,this.fragCurrent=null,this.state=R.PAUSED,this.waitingFragment=null,t?this.timer||(this.timer=setInterval(this.ontick,100)):this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),t&&(this.audioSwitch=!0,this.state=R.IDLE,void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold)),this.tick()}},{key:"onAudioTrackLoaded",value:function(e){var t=e.details,r=e.id,i=this.tracks[r],a=t.totalduration,n=0;if(k.logger.log("track "+r+" loaded ["+t.startSN+","+t.endSN+"],duration:"+a),t.live){var s=i.details;s&&t.fragments.length>0?(E.default.mergeDetails(s,t),n=t.fragments[0].start,t.PTSKnown?k.logger.log("live audio playlist sliding:"+n.toFixed(3)):k.logger.log("live audio playlist - outdated PTS, unknown sliding")):(t.PTSKnown=!1,k.logger.log("live audio playlist - first load, unknown sliding"))}else t.PTSKnown=!1;if(i.details=t,!this.startFragRequested){if(this.startPosition===-1){var o=t.startTimeOffset;isNaN(o)?this.startPosition=0:(k.logger.log("start time offset found in playlist, adjust startPosition to "+o),this.startPosition=o)}this.nextLoadPosition=this.startPosition}this.state===R.WAITING_TRACK&&(this.state=R.IDLE),this.tick()}},{key:"onKeyLoaded",value:function(){this.state===R.KEY_LOADING&&(this.state=R.IDLE,this.tick())}},{key:"onFragLoaded",value:function(e){var t=this.fragCurrent,r=e.frag;if(this.state===R.FRAG_LOADING&&t&&"audio"===r.type&&r.level===t.level&&r.sn===t.sn){var i=this.tracks[this.trackId],a=i.details,n=a.totalduration,s=t.level,o=t.sn,l=t.cc,u=this.config.defaultAudioCodec||i.audioCodec||"mp4a.40.2",d=this.stats=e.stats;if("initSegment"===o)this.state=R.IDLE,d.tparsed=d.tbuffered=performance.now(),a.initSegment.data=e.payload,this.hls.trigger(v.default.FRAG_BUFFERED,{stats:d,frag:t,id:"audio"}),this.tick();else{this.state=R.PARSING,this.appended=!1,this.demuxer||(this.demuxer=new h.default(this.hls,"audio"));var f=this.initPTS[l],c=a.initSegment?a.initSegment.data:[];if(a.initSegment||void 0!==f){this.pendingBuffering=!0,k.logger.log("Demuxing "+o+" of ["+a.startSN+" ,"+a.endSN+"],track "+s);this.demuxer.push(e.payload,c,u,null,t,n,!1,f)}else k.logger.log("unknown video PTS for continuity counter "+l+", waiting for video PTS before demuxing audio frag "+o+" of ["+a.startSN+" ,"+a.endSN+"],track "+s),this.waitingFragment=e,this.state=R.WAITING_INIT_PTS}}this.fragLoadError=0}},{key:"onFragParsingInitSegment",value:function(e){var t=this.fragCurrent,r=e.frag;if(t&&"audio"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===R.PARSING){var i=e.tracks,a=void 0;if(i.video&&delete i.video,a=i.audio){a.levelCodec="mp4a.40.2",a.id=e.id,this.hls.trigger(v.default.BUFFER_CODECS,i),k.logger.log("audio track:audio,container:"+a.container+",codecs[level/parsed]=["+a.levelCodec+"/"+a.codec+"]");var n=a.initSegment;if(n){var s={type:"audio",data:n,parent:"audio",content:"initSegment"};this.audioSwitch?this.pendingData=[s]:(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(v.default.BUFFER_APPENDING,s))}this.tick()}}}},{key:"onFragParsingData",value:function(e){var t=this,r=this.fragCurrent,i=e.frag;if(r&&"audio"===e.id&&"audio"===e.type&&i.sn===r.sn&&i.level===r.level&&this.state===R.PARSING){var a=this.trackId,n=this.tracks[a],s=this.hls;isNaN(e.endPTS)&&(e.endPTS=e.startPTS+r.duration,e.endDTS=e.startDTS+r.duration),k.logger.log("parsed "+e.type+",PTS:["+e.startPTS.toFixed(3)+","+e.endPTS.toFixed(3)+"],DTS:["+e.startDTS.toFixed(3)+"/"+e.endDTS.toFixed(3)+"],nb:"+e.nb),E.default.updateFragPTSDTS(n.details,r,e.startPTS,e.endPTS);var o=this.audioSwitch,l=this.media,u=!1;if(o&&l)if(l.readyState){var d=l.currentTime;k.logger.log("switching audio track : currentTime:"+d),d>=e.startPTS&&(k.logger.log("switching audio track : flushing all audio"),this.state=R.BUFFER_FLUSHING,s.trigger(v.default.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),u=!0,this.audioSwitch=!1,s.trigger(v.default.AUDIO_TRACK_SWITCHED,{id:a}))}else this.audioSwitch=!1,s.trigger(v.default.AUDIO_TRACK_SWITCHED,{id:a});var f=this.pendingData;this.audioSwitch||([e.data1,e.data2].forEach(function(t){t&&t.length&&f.push({type:e.type,data:t,parent:"audio",content:"data"})}),!u&&f.length&&(f.forEach(function(e){t.state===R.PARSING&&(t.pendingBuffering=!0,t.hls.trigger(v.default.BUFFER_APPENDING,e))}),this.pendingData=[],this.appended=!0)),this.tick()}}},{key:"onFragParsed",value:function(e){var t=this.fragCurrent,r=e.frag;t&&"audio"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===R.PARSING&&(this.stats.tparsed=performance.now(),this.state=R.PARSED,this._checkAppendedParsed())}},{key:"onBufferCreated",value:function(e){var t=e.tracks.audio;t&&(this.mediaBuffer=t.buffer,this.loadedmetadata=!0)}},{key:"onBufferAppended",value:function(e){if("audio"===e.parent){var t=this.state;t!==R.PARSING&&t!==R.PARSED||(this.pendingBuffering=e.pending>0,this._checkAppendedParsed())}}},{key:"_checkAppendedParsed",value:function(){if(!(this.state!==R.PARSED||this.appended&&this.pendingBuffering)){var e=this.fragCurrent,t=this.stats,r=this.hls;if(e){this.fragPrevious=e,t.tbuffered=performance.now(),r.trigger(v.default.FRAG_BUFFERED,{stats:t,frag:e,id:"audio"});var i=this.mediaBuffer?this.mediaBuffer:this.media;k.logger.log("audio buffered : "+T.default.toString(i.buffered)),this.audioSwitch&&this.appended&&(this.audioSwitch=!1,r.trigger(v.default.AUDIO_TRACK_SWITCHED,{id:this.trackId})),this.state=R.IDLE}this.tick()}}},{key:"onError",value:function(e){var t=e.frag;if(!t||"audio"===t.type)switch(e.details){case _.ErrorDetails.FRAG_LOAD_ERROR:case _.ErrorDetails.FRAG_LOAD_TIMEOUT:if(!e.fatal){var r=this.fragLoadError;r?r++:r=1;var i=this.config;if(r<=i.fragLoadingMaxRetry){this.fragLoadError=r,t.loadCounter=0;var a=Math.min(Math.pow(2,r-1)*i.fragLoadingRetryDelay,i.fragLoadingMaxRetryTimeout);k.logger.warn("audioStreamController: frag loading failed, retry in "+a+" ms"),this.retryDate=performance.now()+a,this.state=R.FRAG_LOADING_WAITING_RETRY}else k.logger.error("audioStreamController: "+e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.state=R.ERROR}break;case _.ErrorDetails.FRAG_LOOP_LOADING_ERROR:case _.ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case _.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:case _.ErrorDetails.KEY_LOAD_ERROR:case _.ErrorDetails.KEY_LOAD_TIMEOUT:this.state!==R.ERROR&&(this.state=e.fatal?R.ERROR:R.IDLE,k.logger.warn("audioStreamController: "+e.details+" while loading frag,switch to "+this.state+" state ..."));break;case _.ErrorDetails.BUFFER_FULL_ERROR:if("audio"===e.parent&&(this.state===R.PARSING||this.state===R.PARSED)){var n=this.mediaBuffer,s=this.media.currentTime;if(n&&f.default.isBuffered(n,s)&&f.default.isBuffered(n,s+.5)){var o=this.config;o.maxMaxBufferLength>=o.maxBufferLength&&(o.maxMaxBufferLength/=2,k.logger.warn("audio:reduce max buffer length to "+o.maxMaxBufferLength+"s"),this.fragLoadIdx+=2*o.fragLoadingLoopThreshold),this.state=R.IDLE}else k.logger.warn("buffer full error also media.currentTime is not buffered, flush audio buffer"),this.fragCurrent=null,this.state=R.BUFFER_FLUSHING,this.hls.trigger(v.default.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"})}}}},{key:"onBufferFlushed",value:function(){var e=this,t=this.pendingData;t&&t.length?(k.logger.log("appending pending audio data on Buffer Flushed"),t.forEach(function(t){e.hls.trigger(v.default.BUFFER_APPENDING,t)}),this.appended=!0,this.pendingData=[],this.state=R.PARSED):(this.state=R.IDLE,this.fragPrevious=null,this.tick())}},{key:"state",set:function(e){if(this.state!==e){var t=this.state;this._state=e,k.logger.log("audio stream:"+t+"->"+e)}},get:function(){return this._state}}]),t}(y.default);r.default=A},{25:25,31:31,32:32,33:33,35:35,36:36,46:46,51:51,52:52}],7:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;r1&&setTimeout(this.tick,1),this.ticks=0)}},{key:"doTick",value:function(){this.updateTrack(this.trackId)}},{key:"onManifestLoading",value:function(){this.tracks=[],this.trackId=-1}},{key:"onManifestLoaded",value:function(e){var t=this,r=e.audioTracks||[],i=!1;this.tracks=r,this.hls.trigger(u.default.AUDIO_TRACKS_UPDATED,{audioTracks:r});var a=0;r.forEach(function(e){if(e.default)return t.audioTrack=a,void(i=!0);a++}),i===!1&&r.length&&(c.logger.log("no default audio track defined, use first audio track as default"),this.audioTrack=0)}},{key:"onAudioTrackLoaded",value:function(e){e.id=0&&e=0&&e.1){var a=i.updating;try{i.abort()}catch(e){a=!0,c.logger.warn("can not abort audio buffer: "+e)}a?this.audioTimestampOffset=e.start:(c.logger.warn("change mpeg audio timestamp offset from "+i.timestampOffset+" to "+e.start),i.timestampOffset=e.start)}}}},{key:"onManifestParsed",value:function(e){var t=e.audio,r=e.video,i=0;e.altAudio&&(t||r)&&(i=(t?1:0)+(r?1:0),c.logger.log(i+" sourceBuffer(s) expected")),this.sourceBufferNb=i}},{key:"onMediaAttaching",value:function(e){var t=this.media=e.media;if(t){var r=this.mediaSource=new MediaSource;this.onmso=this.onMediaSourceOpen.bind(this),this.onmse=this.onMediaSourceEnded.bind(this),this.onmsc=this.onMediaSourceClose.bind(this),r.addEventListener("sourceopen",this.onmso),r.addEventListener("sourceended",this.onmse),r.addEventListener("sourceclose",this.onmsc),t.src=URL.createObjectURL(r)}}},{key:"onMediaDetaching",value:function(){c.logger.log("media source detaching");var e=this.mediaSource;if(e){if("open"===e.readyState)try{e.endOfStream()}catch(e){c.logger.warn("onMediaDetaching:"+e.message+" while calling endOfStream")}e.removeEventListener("sourceopen",this.onmso),e.removeEventListener("sourceended",this.onmse),e.removeEventListener("sourceclose",this.onmsc),this.media&&(URL.revokeObjectURL(this.media.src),this.media.removeAttribute("src"),this.media.load()),this.mediaSource=null,this.media=null,this.pendingTracks={},this.tracks={},this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0}this.onmso=this.onmse=this.onmsc=null,this.hls.trigger(u.default.MEDIA_DETACHED)}},{key:"onMediaSourceOpen",value:function(){c.logger.log("media source opened"),this.hls.trigger(u.default.MEDIA_ATTACHED,{media:this.media});var e=this.mediaSource;e&&e.removeEventListener("sourceopen",this.onmso),this.checkPendingTracks()}},{key:"checkPendingTracks",value:function(){var e=this.pendingTracks,t=Object.keys(e).length;t&&(this.sourceBufferNb<=t||0===this.sourceBufferNb)&&(this.createSourceBuffers(e),this.pendingTracks={},this.doAppending())}},{key:"onMediaSourceClose",value:function(){c.logger.log("media source closed")}},{key:"onMediaSourceEnded",value:function(){c.logger.log("media source ended")}},{key:"onSBUpdateEnd",value:function(){if(this.audioTimestampOffset){var e=this.sourceBuffer.audio;c.logger.warn("change mpeg audio timestamp offset from "+e.timestampOffset+" to "+this.audioTimestampOffset),e.timestampOffset=this.audioTimestampOffset,delete this.audioTimestampOffset}this._needsFlush&&this.doFlush(),this._needsEos&&this.checkEos(),this.appending=!1;var t=this.parent,r=this.segments.reduce(function(e,r){return r.parent===t?e+1:e},0);this.hls.trigger(u.default.BUFFER_APPENDED,{parent:t,pending:r}),this._needsFlush||this.doAppending(),this.updateMediaElementDuration()}},{key:"onSBUpdateError",value:function(e){c.logger.error("sourceBuffer error:",e),this.hls.trigger(u.default.ERROR,{type:h.ErrorTypes.MEDIA_ERROR,details:h.ErrorDetails.BUFFER_APPENDING_ERROR,fatal:!1})}},{key:"onBufferReset",value:function(){var e=this.sourceBuffer;for(var t in e){var r=e[t];try{this.mediaSource.removeSourceBuffer(r),r.removeEventListener("updateend",this.onsbue),r.removeEventListener("error",this.onsbe)}catch(e){}}this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0}},{key:"onBufferCodecs",value:function(e){if(0===Object.keys(this.sourceBuffer).length){for(var t in e)this.pendingTracks[t]=e[t];var r=this.mediaSource;r&&"open"===r.readyState&&this.checkPendingTracks()}}},{key:"createSourceBuffers",value:function(e){var t=this.sourceBuffer,r=this.mediaSource;for(var i in e)if(!t[i]){var a=e[i],n=a.levelCodec||a.codec,s=a.container+";codecs="+n;c.logger.log("creating sourceBuffer("+s+")");try{var o=t[i]=r.addSourceBuffer(s);o.addEventListener("updateend",this.onsbue),o.addEventListener("error",this.onsbe),this.tracks[i]={codec:n,container:a.container},a.buffer=o}catch(e){c.logger.error("error while trying to add sourceBuffer:"+e.message),this.hls.trigger(u.default.ERROR,{type:h.ErrorTypes.MEDIA_ERROR,details:h.ErrorDetails.BUFFER_ADD_CODEC_ERROR,fatal:!1,err:e,mimeType:s})}}this.hls.trigger(u.default.BUFFER_CREATED,{tracks:e})}},{key:"onBufferAppending",value:function(e){this._needsFlush||(this.segments?this.segments.push(e):this.segments=[e],this.doAppending())}},{key:"onBufferAppendFail",value:function(e){c.logger.error("sourceBuffer error:",e.event),this.hls.trigger(u.default.ERROR,{type:h.ErrorTypes.MEDIA_ERROR,details:h.ErrorDetails.BUFFER_APPENDING_ERROR,fatal:!1})}},{key:"onBufferEos",value:function(e){var t=this.sourceBuffer,r=e.type;for(var i in t)r&&i!==r||t[i].ended||(t[i].ended=!0,c.logger.log(i+" sourceBuffer now EOS"));this.checkEos()}},{key:"checkEos",value:function(){var e=this.sourceBuffer,t=this.mediaSource;if(!t||"open"!==t.readyState)return void(this._needsEos=!1);for(var r in e){var i=e[r];if(!i.ended)return;if(i.updating)return void(this._needsEos=!0)}c.logger.log("all media data available, signal endOfStream() to MediaSource and stop loading fragment");try{t.endOfStream()}catch(e){c.logger.warn("exception while calling mediaSource.endOfStream()")}this._needsEos=!1}},{key:"onBufferFlushing",value:function(e){this.flushRange.push({start:e.startOffset,end:e.endOffset,type:e.type}),this.flushBufferCounter=0,this.doFlush()}},{key:"onLevelUpdated",value:function(e){var t=e.details;0!==t.fragments.length&&(this._levelDuration=t.totalduration+t.fragments[0].start,this.updateMediaElementDuration())}},{key:"updateMediaElementDuration",value:function(){var e=this.media,t=this.mediaSource,r=this.sourceBuffer,i=this._levelDuration;if(null!==i&&e&&t&&r&&0!==e.readyState&&"open"===t.readyState){for(var a in r)if(r[a].updating)return;null===this._msDuration&&(this._msDuration=t.duration);var n=e.duration;(i>this._msDuration&&i>n||n===1/0||isNaN(n))&&(c.logger.log("Updating mediasource duration to "+i.toFixed(3)),this._msDuration=t.duration=i)}}},{key:"doFlush",value:function(){for(;this.flushRange.length;){var e=this.flushRange[0];if(!this.flushBuffer(e.start,e.end,e.type))return void(this._needsFlush=!0);this.flushRange.shift(),this.flushBufferCounter=0}if(0===this.flushRange.length){this._needsFlush=!1;var t=0,r=this.sourceBuffer;try{for(var i in r)t+=r[i].buffered.length}catch(e){c.logger.error("error while accessing sourceBuffer.buffered")}this.appended=t,this.hls.trigger(u.default.BUFFER_FLUSHED)}}},{key:"doAppending",value:function(){var e=this.hls,t=this.sourceBuffer,r=this.segments;if(Object.keys(t).length){if(this.media.error)return this.segments=[],void c.logger.error("trying to append although a media error occured, flush segment and abort");if(this.appending)return;if(r&&r.length){var i=r.shift();try{var a=i.type,n=t[a];n?n.updating?r.unshift(i):(n.ended=!1,this.parent=i.parent,n.appendBuffer(i.data),this.appendError=0,this.appended++,this.appending=!0):this.onSBUpdateEnd()}catch(t){c.logger.error("error while trying to append buffer:"+t.message),r.unshift(i);var s={type:h.ErrorTypes.MEDIA_ERROR,parent:i.parent};if(22===t.code)return this.segments=[],s.details=h.ErrorDetails.BUFFER_FULL_ERROR,s.fatal=!1,void e.trigger(u.default.ERROR,s);if(this.appendError?this.appendError++:this.appendError=1,s.details=h.ErrorDetails.BUFFER_APPEND_ERROR,this.appendError>e.config.appendErrorMaxRetry)return c.logger.log("fail "+e.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),r=[],s.fatal=!0,void e.trigger(u.default.ERROR,s);s.fatal=!1,e.trigger(u.default.ERROR,s)}}}}},{key:"flushBuffer",value:function(e,t,r){var i,a,n,s,o,l,u=this.sourceBuffer;if(Object.keys(u).length){if(c.logger.log("flushBuffer,pos/start/end: "+this.media.currentTime.toFixed(3)+"/"+e+"/"+t),this.flushBufferCounter.5)return this.flushBufferCounter++,c.logger.log("flush "+d+" ["+o+","+l+"], of ["+n+","+s+"], pos:"+this.media.currentTime),i.remove(o,l),!1}catch(e){c.logger.warn("exception while accessing sourcebuffer, it might have been removed from MediaSource")}}}else c.logger.warn("abort flushing too many retries");c.logger.log("buffer flushed")}return!0}}]),t}(f.default);r.default=g},{31:31,32:32,33:33,51:51}],9:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;rthis.autoLevelCapping&&t.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}},{key:"getMaxLevel",value:function(e){var t=0,r=void 0,i=void 0,a=this.mediaWidth,n=this.mediaHeight,s=0,o=0;for(r=0;r<=e&&(i=this.levels[r],!this.isLevelRestricted(r))&&(t=r,s=i.width,o=i.height,!(a<=s||n<=o));r++);return t}},{key:"isLevelRestricted",value:function(e){return!(!this.restrictedLevels||this.restrictedLevels.indexOf(e)===-1)}},{key:"contentScaleFactor",get:function(){var e=1;try{e=window.devicePixelRatio}catch(e){}return e}},{key:"mediaWidth",get:function(){var e=void 0,t=this.media;return t&&(e=t.width||t.clientWidth||t.offsetWidth,e*=this.contentScaleFactor),e}},{key:"mediaHeight",get:function(){var e=void 0,t=this.media;return t&&(e=t.height||t.clientHeight||t.offsetHeight,e*=this.contentScaleFactor),e}}]),t}(f.default);r.default=c},{32:32,33:33}],10:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;r0&&n>l.config.fpsDroppedMonitoringThreshold*s){var d=l.currentLevel;c.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=d)&&(d-=1,l.trigger(u.default.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:l.currentLevel}),l.autoLevelCapping=d,l.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}},{key:"checkFPSInterval",value:function(){var e=this.video;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}]),t}(f.default);r.default=h},{32:32,33:33,51:51}],11:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;r>4){case 0:return i;case 1:case 2:case 3:case 4:case 5:case 6:case 7:i+=String.fromCharCode(s);break;case 12:case 13:t=e[a++],i+=String.fromCharCode((31&s)<<6|63&t);break;case 14:t=e[a++],r=e[a++],i+=String.fromCharCode((15&s)<<12|(63&t)<<6|(63&r)<<0)}}return i}}]),t}(f.default);r.default=c},{32:32,33:33}],12:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;r0})}else o.trigger(u.default.ERROR,{type:h.ErrorTypes.MEDIA_ERROR,details:h.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:o.url,reason:"no level with compatible codecs found in manifest"})}},{key:"setLevelInternal",value:function(e){var t=this._levels,r=this.hls;if(e>=0&&e1&&a.loadErrore&&(this._level===e&&void 0!==t[e].details||this.setLevelInternal(e))}},{key:"manualLevel",get:function(){return this._manualLevel},set:function(e){this._manualLevel=e,void 0===this._startLevel&&(this._startLevel=e),e!==-1&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this._firstLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"nextLoadLevel",get:function(){return this._manualLevel!==-1?this._manualLevel:this.hls.nextAutoLevel},set:function(e){this.level=e,this._manualLevel===-1&&(this.hls.nextAutoLevel=e)}}]),t}(f.default);r.default=p},{31:31,32:32,33:33,35:35,51:51}],13:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;r0&&e===-1&&(k.logger.log("override startPosition with lastCurrentTime @"+t.toFixed(3)),e=t),this.state=R.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this.forceStartLoad=!0,this.state=R.STOPPED}},{key:"stopLoad",value:function(){var e=this.fragCurrent;e&&(e.loader&&e.loader.abort(),this.fragCurrent=null),this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=R.STOPPED,this.forceStartLoad=!1}},{key:"tick",value:function(){1===++this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(this.tick,1),this.ticks=0)}},{key:"doTick",value:function(){switch(this.state){case R.ERROR:break;case R.BUFFER_FLUSHING:this.fragLoadError=0;break;case R.IDLE:this._doTickIdle();break;case R.WAITING_LEVEL:var e=this.levels[this.level];e&&e.details&&(this.state=R.IDLE);break;case R.FRAG_LOADING_WAITING_RETRY:var t=performance.now(),r=this.retryDate;(!r||t>=r||this.media&&this.media.seeking)&&(k.logger.log("mediaController: retryDate reached, switch back to IDLE state"),this.state=R.IDLE);break;case R.ERROR:case R.STOPPED:case R.FRAG_LOADING:case R.PARSING:case R.PARSED:case R.ENDED:}this._checkBuffer(),this._checkFragmentChanged()}},{key:"_doTickIdle",value:function(){ -var e=this.hls,t=e.config,r=this.media;if(void 0===this.levelLastLoaded||r||!this.startFragRequested&&t.startFragPrefetch){var i=void 0;i=this.loadedmetadata?r.currentTime:this.nextLoadPosition;var a=e.nextLoadLevel,n=this.levels[a],s=n.bitrate,o=void 0;o=s?Math.max(8*t.maxBufferSize/s,t.maxBufferLength):t.maxBufferLength,o=Math.min(o,t.maxMaxBufferLength);var l=f.default.bufferInfo(this.mediaBuffer?this.mediaBuffer:r,i,t.maxBufferHole),u=l.len;if(!(u>=o)){k.logger.trace("buffer length of "+u.toFixed(3)+" is below max of "+o.toFixed(3)+". checking for more payload ..."),this.level=e.nextLoadLevel=a;var d=n.details;if(void 0===d||d.live&&this.levelLastLoaded!==a)return void(this.state=R.WAITING_LEVEL);var c=this.fragPrevious;if(!d.live&&c&&c.sn===d.endSN){if(Math.min(r.duration,c.start+c.duration)-Math.max(l.end,c.start)<=Math.max(.2,c.duration/2)){var h={};return this.altAudio&&(h.type="video"),this.hls.trigger(v.default.BUFFER_EOS,h),void(this.state=R.ENDED)}}this._fetchPayloadOrEos(i,l,d)}}}},{key:"_fetchPayloadOrEos",value:function(e,t,r){var i=this.fragPrevious,a=this.level,n=r.fragments,s=n.length;if(0!==s){var o=n[0].start,l=n[s-1].start+n[s-1].duration,u=t.end,d=void 0;if(r.initSegment&&!r.initSegment.data)d=r.initSegment;else if(r.live){var f=this.config.initialLiveManifestSize;if(sf&&(l.currentTime=f)}if(e.PTSKnown&&t>i&&l&&l.readyState)return null;if(this.startFragRequested&&!e.PTSKnown){if(a){var c=a.sn+1;c>=e.startSN&&c<=e.endSN&&(u=n[c-e.startSN],k.logger.log("live playlist, switching playlist, load frag with next SN: "+u.sn))}u||(u=n[Math.min(s-1,Math.round(s/2))],k.logger.log("live playlist, switching playlist, unknown, load middle frag : "+u.sn))}return u}},{key:"_findFragment",value:function(e,t,r,i,a,n,s){var o=this.hls.config,l=void 0,d=void 0,f=o.maxFragLookUpTolerance,c=t?i[t.sn-i[0].sn+1]:void 0,h=function(e){var t=Math.min(f,e.duration);return e.start+e.duration-t<=a?1:e.start-t>a&&e.start?-1:0};if(an-f&&(f=0),d=c&&!h(c)?c:u.default.search(i,h)):d=i[r-1],d){l=d;var g=l.sn-s.startSN,v=t&&l.level===t.level,p=i[g-1],y=i[g+1];if(v&&l.sn===t.sn)if(l.sno.maxBufferHole&&t.dropped&&g?(l=p,k.logger.warn("SN just loaded, with large PTS gap between audio and video, maybe frag is not starting with a keyframe ? load previous one to try to overcome this"),t.loadCounter--):(l=y,k.logger.log("SN just loaded, load next one: "+l.sn))}else l=null;else l.dropped&&!v&&(y&&y.backtracked?(k.logger.warn("Already backtracked from fragment "+(g+1)+", will not backtrack to fragment "+g+". Loading fragment "+(g+1)),l=y):(k.logger.warn("Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe"),l.dropped=0,p?(p.loadCounter&&p.loadCounter--,l=p):l=null))}return l}},{key:"_loadFragmentOrKey",value:function(e,t,r,i,a){var n=this.hls,s=n.config;if(!e.decryptdata||null==e.decryptdata.uri||null!=e.decryptdata.key){if(k.logger.log("Loading "+e.sn+" of ["+r.startSN+" ,"+r.endSN+"],level "+t+", currentTime:"+i.toFixed(3)+",bufferEnd:"+a.toFixed(3)),void 0!==this.fragLoadIdx?this.fragLoadIdx++:this.fragLoadIdx=0,e.loadCounter){e.loadCounter++;var o=s.fragLoadingLoopThreshold;if(e.loadCounter>o&&Math.abs(this.fragLoadIdx-e.loadIdx)t.endPTS?1:0})}},{key:"followingBufferedFrag",value:function(e){return e?this.getBufferedFrag(e.endPTS+.5):null}},{key:"_checkFragmentChanged",value:function(){var e,t,r=this.media;if(r&&r.readyState&&r.seeking===!1&&(t=r.currentTime,t>r.playbackRate*this.lastCurrentTime&&(this.lastCurrentTime=t),f.default.isBuffered(r,t)?e=this.getBufferedFrag(t):f.default.isBuffered(r,t+.1)&&(e=this.getBufferedFrag(t+.1)),e)){var i=e;if(i!==this.fragPlaying){this.hls.trigger(v.default.FRAG_CHANGED,{frag:i});var a=i.level;this.fragPlaying&&this.fragPlaying.level===a||this.hls.trigger(v.default.LEVEL_SWITCHED,{level:a}),this.fragPlaying=i}}}},{key:"immediateLevelSwitch",value:function(){if(k.logger.log("immediateLevelSwitch"),!this.immediateSwitch){this.immediateSwitch=!0;var e=this.media,t=void 0;e?(t=e.paused,e.pause()):t=!0,this.previouslyPaused=t}var r=this.fragCurrent;r&&r.loader&&r.loader.abort(),this.fragCurrent=null,this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}},{key:"immediateLevelSwitchEnd",value:function(){var e=this.media;e&&e.buffered.length&&(this.immediateSwitch=!1,f.default.isBuffered(e,e.currentTime)&&(e.currentTime-=1e-4),this.previouslyPaused||e.play())}},{key:"nextLevelSwitch",value:function(){var e=this.media;if(e&&e.readyState){var t=void 0,r=void 0,i=void 0;if(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold,r=this.getBufferedFrag(e.currentTime),r&&r.startPTS>1&&this.flushMainBuffer(0,r.startPTS-1),e.paused)t=0;else{var a=this.hls.nextLoadLevel,n=this.levels[a],s=this.fragLastKbps;t=s&&this.fragCurrent?this.fragCurrent.duration*n.bitrate/(1e3*s)+1:0}if((i=this.getBufferedFrag(e.currentTime+t))&&(i=this.followingBufferedFrag(i))){var o=this.fragCurrent;o&&o.loader&&o.loader.abort(),this.fragCurrent=null,this.flushMainBuffer(i.startPTS,Number.POSITIVE_INFINITY)}}}},{key:"flushMainBuffer",value:function(e,t){this.state=R.BUFFER_FLUSHING;var r={startOffset:e,endOffset:t};this.altAudio&&(r.type="video"),this.hls.trigger(v.default.BUFFER_FLUSHING,r)}},{key:"onMediaAttached",value:function(e){var t=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),this.onvended=this.onMediaEnded.bind(this),t.addEventListener("seeking",this.onvseeking),t.addEventListener("seeked",this.onvseeked),t.addEventListener("ended",this.onvended);var r=this.config;this.levels&&r.autoStartLoad&&this.hls.startLoad(r.startPosition)}},{key:"onMediaDetaching",value:function(){var e=this.media;e&&e.ended&&(k.logger.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0);var t=this.levels;t&&t.forEach(function(e){e.details&&e.details.fragments.forEach(function(e){e.loadCounter=void 0,e.backtracked=void 0})}),e&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("seeked",this.onvseeked),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvseeked=this.onvended=null),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.stopLoad()}},{key:"onMediaSeeking",value:function(){var e=this.media,t=e?e.currentTime:void 0,r=this.config;if(k.logger.log("media seeking to "+t.toFixed(3)),this.state===R.FRAG_LOADING){var i=this.mediaBuffer?this.mediaBuffer:e,a=f.default.bufferInfo(i,t,this.config.maxBufferHole),n=this.fragCurrent;if(0===a.len&&n){var s=r.maxFragLookUpTolerance,o=n.start-s,l=n.start+n.duration+s;tl?(n.loader&&(k.logger.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),n.loader.abort()),this.fragCurrent=null,this.fragPrevious=null,this.state=R.IDLE):k.logger.log("seeking outside of buffer but within currently loaded fragment range")}}else this.state===R.ENDED&&(this.state=R.IDLE);e&&(this.lastCurrentTime=t),this.state!==R.FRAG_LOADING&&void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*r.fragLoadingLoopThreshold),this.loadedmetadata||(this.nextLoadPosition=this.startPosition=t),this.tick()}},{key:"onMediaSeeked",value:function(){k.logger.log("media seeked to "+this.media.currentTime.toFixed(3)),this.tick()}},{key:"onMediaEnded",value:function(){k.logger.log("media ended"),this.startPosition=this.lastCurrentTime=0}},{key:"onManifestLoading",value:function(){k.logger.log("trigger BUFFER_RESET"),this.hls.trigger(v.default.BUFFER_RESET),this._bufferedFrags=[],this.stalled=!1,this.startPosition=this.lastCurrentTime=0}},{key:"onManifestParsed",value:function(e){var t,r=!1,i=!1;e.levels.forEach(function(e){(t=e.audioCodec)&&(t.indexOf("mp4a.40.2")!==-1&&(r=!0),t.indexOf("mp4a.40.5")!==-1&&(i=!0))}),this.audioCodecSwitch=r&&i,this.audioCodecSwitch&&k.logger.log("both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startLevelLoaded=!1,this.startFragRequested=!1;var a=this.config;(a.autoStartLoad||this.forceStartLoad)&&this.hls.startLoad(a.startPosition)}},{key:"onLevelLoaded",value:function(e){var t=e.details,r=e.level,i=this.levels[r],a=t.totalduration,n=0;if(k.logger.log("level "+r+" loaded ["+t.startSN+","+t.endSN+"],duration:"+a),this.levelLastLoaded=r,t.live){var s=i.details;s&&t.fragments.length>0?(E.default.mergeDetails(s,t),n=t.fragments[0].start,this.liveSyncPosition=this.computeLivePosition(n,s),t.PTSKnown?k.logger.log("live playlist sliding:"+n.toFixed(3)):k.logger.log("live playlist - outdated PTS, unknown sliding")):(t.PTSKnown=!1,k.logger.log("live playlist - first load, unknown sliding"))}else t.PTSKnown=!1;if(i.details=t,this.hls.trigger(v.default.LEVEL_UPDATED,{details:t,level:r}),this.startFragRequested===!1){if(this.startPosition===-1||this.lastCurrentTime===-1){var o=t.startTimeOffset;isNaN(o)?t.live?(this.startPosition=this.computeLivePosition(n,t),k.logger.log("configure startPosition to "+this.startPosition)):this.startPosition=0:(o<0&&(k.logger.log("negative start time offset "+o+", count from end of last fragment"),o=n+a+o),k.logger.log("start time offset found in playlist, adjust startPosition to "+o),this.startPosition=o),this.lastCurrentTime=this.startPosition}this.nextLoadPosition=this.startPosition}this.state===R.WAITING_LEVEL&&(this.state=R.IDLE),this.tick()}},{key:"onKeyLoaded",value:function(){this.state===R.KEY_LOADING&&(this.state=R.IDLE,this.tick())}},{key:"onFragLoaded",value:function(e){var t=this.fragCurrent,r=e.frag;if(this.state===R.FRAG_LOADING&&t&&"main"===r.type&&r.level===t.level&&r.sn===t.sn){var i=e.stats,a=this.levels[t.level],n=a.details;if(k.logger.log("Loaded "+t.sn+" of ["+n.startSN+" ,"+n.endSN+"],level "+t.level),this.bitrateTest=!1,this.stats=i,r.bitrateTest===!0&&this.hls.nextLoadLevel)this.state=R.IDLE,this.startFragRequested=!1,i.tparsed=i.tbuffered=performance.now(),this.hls.trigger(v.default.FRAG_BUFFERED,{stats:i,frag:t,id:"main"}),this.tick();else if("initSegment"===r.sn)this.state=R.IDLE,i.tparsed=i.tbuffered=performance.now(),n.initSegment.data=e.payload,this.hls.trigger(v.default.FRAG_BUFFERED,{stats:i,frag:t,id:"main"}),this.tick();else{this.state=R.PARSING;var s=n.totalduration,o=t.level,l=t.sn,u=this.config.defaultAudioCodec||a.audioCodec;this.audioCodecSwap&&(k.logger.log("swapping playlist audio codec"),void 0===u&&(u=this.lastAudioCodec),u&&(u=u.indexOf("mp4a.40.5")!==-1?"mp4a.40.2":"mp4a.40.5")),this.pendingBuffering=!0,this.appended=!1,k.logger.log("Parsing "+l+" of ["+n.startSN+" ,"+n.endSN+"],level "+o+", cc "+t.cc);var d=this.demuxer;d||(d=this.demuxer=new h.default(this.hls,"main"));var f=this.media,c=f&&f.seeking,g=!c&&(n.PTSKnown||!n.live),p=n.initSegment?n.initSegment.data:[];d.push(e.payload,p,u,a.videoCodec,t,s,g,void 0)}}this.fragLoadError=0}},{key:"onFragParsingInitSegment",value:function(e){var t=this.fragCurrent,r=e.frag;if(t&&"main"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===R.PARSING){var i,a,n=e.tracks;if(n.audio&&this.altAudio&&delete n.audio,a=n.audio){var s=this.levels[this.level].audioCodec,o=navigator.userAgent.toLowerCase();s&&this.audioCodecSwap&&(k.logger.log("swapping playlist audio codec"),s=s.indexOf("mp4a.40.5")!==-1?"mp4a.40.2":"mp4a.40.5"),this.audioCodecSwitch&&1!==a.metadata.channelCount&&o.indexOf("firefox")===-1&&(s="mp4a.40.5"),o.indexOf("android")!==-1&&"audio/mpeg"!==a.container&&(s="mp4a.40.2",k.logger.log("Android: force audio codec to "+s)),a.levelCodec=s,a.id=e.id}a=n.video,a&&(a.levelCodec=this.levels[this.level].videoCodec,a.id=e.id),this.hls.trigger(v.default.BUFFER_CODECS,n);for(i in n){a=n[i],k.logger.log("main track:"+i+",container:"+a.container+",codecs[level/parsed]=["+a.levelCodec+"/"+a.codec+"]");var l=a.initSegment;l&&(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(v.default.BUFFER_APPENDING,{type:i,data:l,parent:"main",content:"initSegment"}))}this.tick()}}},{key:"onFragParsingData",value:function(e){var t=this,r=this.fragCurrent,i=e.frag;if(r&&"main"===e.id&&i.sn===r.sn&&i.level===r.level&&("audio"!==e.type||!this.altAudio)&&this.state===R.PARSING){var a=this.levels[this.level],n=r;if(isNaN(e.endPTS)&&(e.endPTS=e.startPTS+r.duration,e.endDTS=e.startDTS+r.duration),k.logger.log("Parsed "+e.type+",PTS:["+e.startPTS.toFixed(3)+","+e.endPTS.toFixed(3)+"],DTS:["+e.startDTS.toFixed(3)+"/"+e.endDTS.toFixed(3)+"],nb:"+e.nb+",dropped:"+(e.dropped||0)),"video"===e.type)if(n.dropped=e.dropped,n.dropped){if(!n.backtracked)return n.backtracked=!0,this.nextLoadPosition=e.startPTS,this.state=R.IDLE,void this.tick();k.logger.warn("Already backtracked on this fragment, appending with the gap")}else n.backtracked=!1;var s=E.default.updateFragPTSDTS(a.details,n,e.startPTS,e.endPTS,e.startDTS,e.endDTS),o=this.hls;o.trigger(v.default.LEVEL_PTS_UPDATED,{details:a.details,level:this.level,drift:s,type:e.type,start:e.startPTS,end:e.endPTS}),[e.data1,e.data2].forEach(function(r){r&&r.length&&t.state===R.PARSING&&(t.appended=!0,t.pendingBuffering=!0,o.trigger(v.default.BUFFER_APPENDING,{type:e.type,data:r,parent:"main",content:"data"}))}),this.tick()}}},{key:"onFragParsed",value:function(e){var t=this.fragCurrent,r=e.frag;t&&"main"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===R.PARSING&&(this.stats.tparsed=performance.now(),this.state=R.PARSED,this._checkAppendedParsed())}},{key:"onAudioTrackSwitching",value:function(e){var t=!!e.url,r=e.id;if(!t){if(this.mediaBuffer!==this.media){k.logger.log("switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var i=this.fragCurrent;i.loader&&(k.logger.log("switching to main audio track, cancel main fragment load"),i.loader.abort()),this.fragCurrent=null,this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=R.IDLE}var a=this.hls;a.trigger(v.default.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),a.trigger(v.default.AUDIO_TRACK_SWITCHED,{id:r}),this.altAudio=!1}}},{key:"onAudioTrackSwitched",value:function(e){var t=e.id,r=!!this.hls.audioTracks[t].url;if(r){var i=this.videoBuffer;i&&this.mediaBuffer!==i&&(k.logger.log("switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r,this.tick()}},{key:"onBufferCreated",value:function(e){var t=e.tracks,r=void 0,i=void 0,a=!1;for(var n in t){var s=t[n];"main"===s.id?(i=n,r=s,"video"===n&&(this.videoBuffer=t[n].buffer)):a=!0}a&&r?(k.logger.log("alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}},{key:"onBufferAppended",value:function(e){if("main"===e.parent){var t=this.state;t!==R.PARSING&&t!==R.PARSED||(this.pendingBuffering=e.pending>0,this._checkAppendedParsed())}}},{key:"_checkAppendedParsed",value:function(){if(!(this.state!==R.PARSED||this.appended&&this.pendingBuffering)){var e=this.fragCurrent;if(e){var t=this.mediaBuffer?this.mediaBuffer:this.media;k.logger.log("main buffered : "+T.default.toString(t.buffered));var r=this._bufferedFrags.filter(function(e){return f.default.isBuffered(t,(e.startPTS+e.endPTS)/2)});r.push(e),this._bufferedFrags=r.sort(function(e,t){return e.startPTS-t.startPTS}),this.fragPrevious=e;var i=this.stats;i.tbuffered=performance.now(),this.fragLastKbps=Math.round(8*i.total/(i.tbuffered-i.tfirst)),this.hls.trigger(v.default.FRAG_BUFFERED,{stats:i,frag:e,id:"main"}),this.state=R.IDLE}this.tick()}}},{key:"onError",value:function(e){var t=e.frag||this.fragCurrent;if(!t||"main"===t.type){var r=this.media,i=r&&f.default.isBuffered(r,r.currentTime)&&f.default.isBuffered(r,r.currentTime+.5);switch(e.details){case _.ErrorDetails.FRAG_LOAD_ERROR:case _.ErrorDetails.FRAG_LOAD_TIMEOUT:case _.ErrorDetails.KEY_LOAD_ERROR:case _.ErrorDetails.KEY_LOAD_TIMEOUT:if(!e.fatal){var a=this.fragLoadError;a?a++:a=1;var n=this.config;if(a<=n.fragLoadingMaxRetry||i||t.autoLevel&&t.level){this.fragLoadError=a,t.loadCounter=0;var s=Math.min(Math.pow(2,a-1)*n.fragLoadingRetryDelay,n.fragLoadingMaxRetryTimeout);k.logger.warn("mediaController: frag loading failed, retry in "+s+" ms"),this.retryDate=performance.now()+s,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.state=R.FRAG_LOADING_WAITING_RETRY}else k.logger.error("mediaController: "+e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.state=R.ERROR}break;case _.ErrorDetails.FRAG_LOOP_LOADING_ERROR:e.fatal||(i?(this._reduceMaxBufferLength(t.duration),this.state=R.IDLE):t.autoLevel&&0!==t.level||(e.fatal=!0,this.state=R.ERROR));break;case _.ErrorDetails.LEVEL_LOAD_ERROR:case _.ErrorDetails.LEVEL_LOAD_TIMEOUT:this.state!==R.ERROR&&(e.fatal?(this.state=R.ERROR,k.logger.warn("streamController: "+e.details+",switch to "+this.state+" state ...")):this.state===R.WAITING_LEVEL&&(this.state=R.IDLE));break;case _.ErrorDetails.BUFFER_FULL_ERROR:"main"!==e.parent||this.state!==R.PARSING&&this.state!==R.PARSED||(i?(this._reduceMaxBufferLength(this.config.maxBufferLength),this.state=R.IDLE):(k.logger.warn("buffer full error also media.currentTime is not buffered, flush everything"),this.fragCurrent=null,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)))}}}},{key:"_reduceMaxBufferLength",value:function(e){var t=this.config;t.maxMaxBufferLength>=e&&(t.maxMaxBufferLength/=2,k.logger.warn("main:reduce max buffer length to "+t.maxMaxBufferLength+"s"),this.fragLoadIdx+=2*t.fragLoadingLoopThreshold)}},{key:"_checkBuffer",value:function(){var e=this.media;if(e&&e.readyState){var t=e.currentTime,r=this.mediaBuffer?this.mediaBuffer:e,i=r.buffered;if(!this.loadedmetadata&&i.length){this.loadedmetadata=!0;var a=e.seeking?t:this.startPosition,n=f.default.isBuffered(r,a);t===a&&n||(k.logger.log("target start position:"+a),n||(a=i.start(0),k.logger.log("target start position not buffered, seek to buffered.start(0) "+a)),k.logger.log("adjust currentTime from "+t+" to "+a),e.currentTime=a)}else if(this.immediateSwitch)this.immediateLevelSwitchEnd();else{var s=f.default.bufferInfo(e,t,0),o=!(e.paused||e.ended||0===e.buffered.length),l=t!==this.lastCurrentTime,u=this.config;if(l)this.stallReported&&(k.logger.warn("playback not stuck anymore @"+t+", after "+Math.round(performance.now()-this.stalled)+"ms"),this.stallReported=!1),this.stalled=void 0,this.nudgeRetry=0;else if(o){var d=performance.now(),c=this.hls;if(this.stalled){var h=d-this.stalled,g=s.len,p=this.nudgeRetry||0;if(g<=.5&&h>1e3*u.lowBufferWatchdogPeriod){this.stallReported||(this.stallReported=!0,k.logger.warn("playback stalling in low buffer @"+t),c.trigger(v.default.ERROR,{type:_.ErrorTypes.MEDIA_ERROR,details:_.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,buffer:g}));var y=s.nextStart,m=y-t;if(y&&m0){this.nudgeRetry=++p;var E=p*u.nudgeOffset;k.logger.log("adjust currentTime from "+e.currentTime+" to next buffered @ "+y+" + nudge "+E),e.currentTime=y+E,this.stalled=void 0,c.trigger(v.default.ERROR,{type:_.ErrorTypes.MEDIA_ERROR,details:_.ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,hole:y+E-t})}}else if(g>.5&&h>1e3*u.highBufferWatchdogPeriod)if(this.stallReported||(this.stallReported=!0,k.logger.warn("playback stalling in high buffer @"+t),c.trigger(v.default.ERROR,{type:_.ErrorTypes.MEDIA_ERROR,details:_.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,buffer:g})),this.stalled=void 0,this.nudgeRetry=++p,p"+e),this.hls.trigger(v.default.STREAM_STATE_TRANSITION,{previousState:t,nextState:e})}},get:function(){return this._state}},{key:"currentLevel",get:function(){var e=this.media;if(e){var t=this.getBufferedFrag(e.currentTime);if(t)return t.level}return-1}},{key:"nextBufferedFrag",get:function(){var e=this.media;return e?this.followingBufferedFrag(this.getBufferedFrag(e.currentTime)):null}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"liveSyncPosition",get:function(){return this._liveSyncPosition},set:function(e){this._liveSyncPosition=e}}]),t}(y.default);r.default=A},{25:25,31:31,32:32,33:33,35:35,36:36,46:46,51:51,52:52}],14:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;r-1&&this.vttFragQueues[this.currentTrackId].length){var e=this.currentlyProcessing=this.vttFragQueues[this.currentTrackId].shift();this.hls.trigger(u.default.FRAG_LOADING,{frag:e})}}},{key:"onSubtitleFragProcessed",value:function(e){e.success&&this.vttFragSNsProcessed[e.frag.trackId].push(e.frag.sn),this.currentlyProcessing=null,this.nextFrag()}},{key:"onError",value:function(e){var t=e.frag;t&&"subtitle"!==t.type||this.currentlyProcessing&&(this.currentlyProcessing=null,this.nextFrag())}},{key:"onSubtitleTracksUpdated",value:function(e){var t=this;c.logger.log("subtitle tracks updated"),this.tracks=e.subtitleTracks,this.clearVttFragQueues(),this.vttFragSNsProcessed={},this.tracks.forEach(function(e){t.vttFragSNsProcessed[e.id]=[]})}},{key:"onSubtitleTrackSwitch",value:function(e){this.currentTrackId=e.id,this.clearVttFragQueues()}},{key:"onSubtitleTrackLoaded",value:function(e){var t=this.vttFragSNsProcessed[e.id],r=this.vttFragQueues[e.id],i=this.currentlyProcessing?this.currentlyProcessing.sn:-1,a=function(e){return t.indexOf(e.sn)>-1},n=function(e){return r.some(function(t){return t.sn===e.sn})};e.details.fragments.forEach(function(t){a(t)||t.sn===i||n(t)||(t.trackId=e.id,r.push(t))}),this.nextFrag()}}]),t}(f.default);r.default=h},{32:32,33:33,51:51}],15:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function o(e){for(var t=[],r=0;r=0&&e0;)e.removeCue(e.cues[0])}function l(e,t){return e&&e.label===t.name&&!(e.textTrack1||e.textTrack2)}function u(e,t,r,i){return Math.min(t,i)-Math.max(e,r)}Object.defineProperty(r,"__esModule",{value:!0});var d=function(){function e(e,t){for(var r=0;r=0&&(o[0]=Math.min(o[0],t),o[1]=Math.max(o[1],r),n=!0,l/(r-t)>.5))return}n||a.push([t,r]),this.Cues.newCue(this[e],t,r,i)}},{key:"onInitPtsFound",value:function(e){var t=this;void 0===this.initPTS&&(this.initPTS=e.initPTS),this.unparsedVttFrags.length&&(this.unparsedVttFrags.forEach(function(e){t.onFragLoaded(e)}),this.unparsedVttFrags=[])}},{key:"getExistingTrack",value:function(e){var t=this.media;if(t)for(var r=0;r>>8^255&p^99,e[h]=p,t[p]=h;var y=c[h],m=c[y],E=c[m],b=257*c[p]^16843008*p;i[h]=b<<24|b>>>8,a[h]=b<<16|b>>>16,n[h]=b<<8|b>>>24,s[h]=b,b=16843009*E^65537*m^257*y^16843008*h,l[p]=b<<24|b>>>8,u[p]=b<<16|b>>>16,d[p]=b<<8|b>>>24,f[p]=b,h?(h=y^c[c[c[E^y]]],g^=c[c[g]]):h=g=1}}},{key:"expandKey",value:function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i>8|e>>>24}},{key:"decrypt",value:function(e,t,r){for(var i,a,n=this.keySize+6,s=this.invKeySchedule,o=this.invSBox,l=this.invSubMix,u=l[0],d=l[1],f=l[2],c=l[3],h=this.uint8ArrayToUint32Array_(r),g=h[0],v=h[1],p=h[2],y=h[3],m=new Int32Array(e),E=new Int32Array(m.length),b=void 0,T=void 0,_=void 0,k=void 0,R=void 0,A=void 0,S=void 0,L=void 0,w=void 0,D=void 0,O=void 0,I=void 0,P=this.networkToHostOrderSwap;t>>24]^d[A>>16&255]^f[S>>8&255]^c[255&L]^s[i],T=u[A>>>24]^d[S>>16&255]^f[L>>8&255]^c[255&R]^s[i+1],_=u[S>>>24]^d[L>>16&255]^f[R>>8&255]^c[255&A]^s[i+2],k=u[L>>>24]^d[R>>16&255]^f[A>>8&255]^c[255&S]^s[i+3],R=b,A=T,S=_,L=k,i+=4;b=o[R>>>24]<<24^o[A>>16&255]<<16^o[S>>8&255]<<8^o[255&L]^s[i],T=o[A>>>24]<<24^o[S>>16&255]<<16^o[L>>8&255]<<8^o[255&R]^s[i+1],_=o[S>>>24]<<24^o[L>>16&255]<<16^o[R>>8&255]<<8^o[255&A]^s[i+2],k=o[L>>>24]<<24^o[R>>16&255]<<16^o[A>>8&255]<<8^o[255&S]^s[i+3],i+=3,E[t]=P(b^g),E[t+1]=P(k^v),E[t+2]=P(_^p),E[t+3]=P(T^y),g=w,v=D,p=O,y=I,t+=4}return E.buffer}},{key:"destroy",value:function(){this.key=void 0,this.keySize=void 0,this.ksRows=void 0,this.sBox=void 0,this.invSBox=void 0,this.subMix=void 0,this.invSubMix=void 0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.rcon=void 0}}]),e}();r.default=n},{}],19:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r>>5,(s-=h)>0&&c+h+s<=v);)for(g=m+f*u,p={unit:e.subarray(c+h,c+h+s),pts:g,dts:g},a.samples.push(p),a.len+=s,c+=s+h,f++;c>>6),(o=(60&t[r+2])>>>2)>h.length-1?void e.trigger(Event.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+o}):(u=(1&t[r+2])<<2,u|=(192&t[r+3])>>>6,i.logger.log("manifest codec:"+n+",ADTS data:type:"+s+",sampleingIndex:"+o+"["+h[o]+"Hz],channelConfig:"+u),/firefox/i.test(f)?o>=6?(s=5,d=new Array(4),l=o-3):(s=2,d=new Array(2),l=o):f.indexOf("android")!==-1?(s=2,d=new Array(2),l=o):(s=5,d=new Array(4),n&&(n.indexOf("mp4a.40.29")!==-1||n.indexOf("mp4a.40.5")!==-1)||!n&&o>=6?l=o-3:((n&&n.indexOf("mp4a.40.2")!==-1&&o>=6&&1===u||!n&&1===u)&&(s=2,d=new Array(2)),l=o)),d[0]=s<<3,d[0]|=(14&o)>>1,d[1]|=(1&o)<<7,d[1]|=u<<3,5===s&&(d[1]|=(14&l)>>1,d[2]=(1&l)<<7,d[2]|=8,d[3]=0),{config:d,samplerate:h[o],channelCount:u,codec:"mp4a.40."+s,manifestCodec:c})}};t.exports=n},{31:31,51:51}],23:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r0&&null!=t&&null!=t.key&&"AES-128"===t.method){var g=this.decrypter;null==g&&(g=this.decrypter=new d.default(this.observer,this.config));var v,p=this;try{v=performance.now()}catch(e){v=Date.now()}g.decrypt(e,t.key.buffer,t.iv.buffer,function(e){var d;try{d=performance.now()}catch(e){d=Date.now()}p.observer.trigger(o.default.FRAG_DECRYPTED,{stats:{tstart:v,tdecrypt:d}}),p.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),i,a,n,s,l,u,f,c,h)})}else this.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),i,a,n,s,l,u,f,c,h)}},{key:"pushDecrypted",value:function(e,t,r,i,a,n,s,u,d,f,h,v){var y=this.demuxer;if(!y||s&&!this.probe(e)){var E=this.observer,T=this.typeSupported,_=this.config,k=[{demux:p.default,remux:m.default},{demux:c.default,remux:m.default},{demux:g.default,remux:b.default}];for(var R in k){var A=k[R],S=A.demux.probe;if(S(e)){var L=this.remuxer=new A.remux(E,_,T,this.vendor);y=new A.demux(E,L,_,T),this.probe=S;break}}if(!y)return void E.trigger(o.default.ERROR,{type:l.ErrorTypes.MEDIA_ERROR,details:l.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"});this.demuxer=y}var w=this.remuxer;(s||u)&&(y.resetInitSegment(r,i,a,f),w.resetInitSegment()),s&&(y.resetTimeStamp(),w.resetTimeStamp(v)),"function"==typeof y.setDecryptData&&y.setDecryptData(t),y.append(e,n,d,h)}}]),e}();r.default=T},{19:19,21:21,28:28,30:30,31:31,33:33,43:43,44:44}],24:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(r,"__esModule",{value:!0});var a=e(23),n=i(a),s=e(33),o=i(s),l=e(51),u=e(1),d=i(u),f=function(e){var t=new d.default;t.trigger=function(e){for(var r=arguments.length,i=Array(r>1?r-1:0),a=1;a1?r-1:0),a=1;a1?t-1:0),i=1;i1?t-1:0),i=1;ie?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t>>3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}},{key:"readBits",value:function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;return e>32&&n.logger.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0?this.word<<=t:this.bytesAvailable>0&&this.loadWord(),t=e-t,t>0&&this.bitsAvailable?r<>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}},{key:"skipUEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"skipEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"readUEG",value:function(){var e=this.skipLZ();return this.readBits(e+1)-1}},{key:"readEG",value:function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}},{key:"readBoolean",value:function(){return 1===this.readBits(1)}},{key:"readUByte",value:function(){return this.readBits(8)}},{key:"readUShort",value:function(){return this.readBits(16)}},{key:"readUInt",value:function(){return this.readBits(32)}},{key:"skipScalingList",value:function(e){var t,r,i=8,a=8;for(t=0;t=8){var r=e.bin2str(t.subarray(4,8));return["moof","ftyp","styp"].indexOf(r)>=0}return!1}},{key:"bin2str",value:function(e){return String.fromCharCode.apply(null,e)}},{key:"findBox",value:function(t,r){var i,a,n,s,o,l=[];if(!r.length)return null;for(i=0;i1?i+a:t.byteLength,n===r[0]&&(1===r.length?l.push(t.subarray(i+8,s)):(o=e.findBox(t.subarray(i+8,s),r.slice(1)),o.length&&(l=l.concat(o)))),i=s;return l}},{key:"parseInitSegment",value:function(t){var r=[];return e.findBox(t,["moov","trak"]).forEach(function(t){var i=e.findBox(t,["tkhd"])[0];if(i){var a=i[0],n=0===a?12:20,s=i[n]<<24|i[n+1]<<16|i[n+2]<<8|i[n+3];s=s<0?4294967296+s:s;var o=e.findBox(t,["mdia","mdhd"])[0];if(o){a=o[0],n=0===a?12:20;var l=o[n]<<24|o[n+1]<<16|o[n+2]<<8|o[n+3],u=e.findBox(t,["mdia","hdlr"])[0];if(u){var d=e.bin2str(u.subarray(8,12)),f={soun:"audio",vide:"video"}[d];f&&(r[s]={timescale:l,type:f},r[f]={timescale:l,id:s})}}}}),r}},{key:"startDTS",value:function(t,r){var i,a,n;return i=e.findBox(r,["moof","traf"]),a=[].concat.apply([],i.map(function(r){return e.findBox(r,["tfhd"]).map(function(i){var a,n,s;return a=i[4]<<24|i[5]<<16|i[6]<<8|i[7],n=t[a].timescale||9e4,s=e.findBox(r,["tfdt"]).map(function(e){var t,r;return t=e[0],r=e[4]<<24|e[5]<<16|e[6]<<8|e[7],1===t&&(r*=Math.pow(2,32),r+=e[8]<<24|e[9]<<16|e[10]<<8|e[11]),r})[0],(s=s||1/0)/n})})),n=Math.min.apply(null,a),isFinite(n)?n:0}}]),e}();r.default=o},{33:33}],29:[function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r=e.length)return void r();if(!(e[t].unit.length<32)){var i=this.decrypter.isSync();if(this.decryptAacSample(e,t,r,i),!i)return}}}},{key:"getAvcEncryptedData",value:function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,a=32;a<=e.length-16;a+=160,i+=16)r.set(e.subarray(a,a+16),i);return r}},{key:"getAvcDecryptedUnit",value:function(e,t){t=new Uint8Array(t);for(var r=0,i=32;i<=e.length-16;i+=160,r+=16)e.set(t.subarray(r,r+16),i);return e}},{key:"decryptAvcSample",value:function(e,t,r,i,a,n){var s=this.discardEPB(a.data),o=this.getAvcEncryptedData(s),l=this;this.decryptBuffer(o.buffer,function(o){a.data=l.getAvcDecryptedUnit(s,o),n||l.decryptAvcSamples(e,t,r+1,i)})}},{key:"decryptAvcSamples",value:function(e,t,r,i){for(;;t++,r=0){if(t>=e.length)return void i();for(var a=e[t].units;!(r>=a.length);r++){var n=a[r];if(!(n.length<=48||1!==n.type&&5!==n.type)){var s=this.decrypter.isSync();if(this.decryptAvcSample(e,t,r,i,n,s),!s)return}}}}}]),e}();r.default=o},{19:19}],30:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r>4>1){if((o=a+5+e[a+4])===a+188)continue}else o=a+4;switch(s){case m:n&&(_&&(l=L(_))&&w(l,!1),_={data:[],size:0}),_&&(_.data.push(e.subarray(o,a+188)),_.size+=a+188-o);break;case E:n&&(k&&(l=L(k))&&(p.isAAC?D(l):O(l)),k={data:[],size:0}),k&&(k.data.push(e.subarray(o,a+188)),k.size+=a+188-o);break;case b:n&&(R&&(l=L(R))&&I(l),R={data:[],size:0}),R&&(R.data.push(e.subarray(o,a+188)),R.size+=a+188-o);break;case 0:n&&(o+=e[o]+1),T=this._pmtId=A(e,o);break;case T:n&&(o+=e[o]+1);var P=S(e,o,this.typeSupported.mpeg===!0||this.typeSupported.mp3===!0,null!=this.sampleAes);m=P.avc,m>0&&(h.id=m),E=P.audio,E>0&&(p.id=E,p.isAAC=P.isAAC),b=P.id3,b>0&&(y.id=b),f&&!c&&(g.logger.log("reparse from beginning"),f=!1,a=-188),c=this.pmtParsed=!0;break;case 17:case 8191:break;default:f=!0}}else this.observer.trigger(u.default.ERROR,{type:v.ErrorTypes.MEDIA_ERROR,details:v.ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,reason:"TS packet did not start with 0x47"});_&&(l=L(_))?(w(l,!0),h.pesData=null):h.pesData=_,k&&(l=L(k))?(p.isAAC?D(l):O(l),p.pesData=null):(k&&k.size&&g.logger.log("last AAC PES packet truncated,might overlap between fragments"),p.pesData=k),R&&(l=L(R))?(I(l),y.pesData=null):y.pesData=R,null==this.sampleAes?this.remuxer.remux(p,h,y,this._txtTrack,t,r,i):this.decryptAndRemux(p,h,y,this._txtTrack,t,r,i)}},{key:"decryptAndRemux",value:function(e,t,r,i,a,n,s){if(e.samples&&e.isAAC){var o=this;this.sampleAes.decryptAacSamples(e.samples,0,function(){o.decryptAndRemuxAvc(e,t,r,i,a,n,s)})}else this.decryptAndRemuxAvc(e,t,r,i,a,n,s)}},{key:"decryptAndRemuxAvc",value:function(e,t,r,i,a,n,s){if(t.samples){var o=this;this.sampleAes.decryptAvcSamples(t.samples,0,0,function(){o.remuxer.remux(e,t,r,i,a,n,s)})}else this.remuxer.remux(e,t,r,i,a,n,s)}},{key:"destroy",value:function(){this._initPTS=this._initDTS=void 0,this._duration=0}},{key:"_parsePAT",value:function(e,t){return(31&e[t+10])<<8|e[t+11]}},{key:"_parsePMT",value:function(e,t,r,i){var a,n,s,o,l={audio:-1,avc:-1,id3:-1,isAAC:!0};for(a=(15&e[t+1])<<8|e[t+2],n=t+3+a-4,s=(15&e[t+10])<<8|e[t+11],t+=12+s;t1;){var f=new Uint8Array(d[0].length+d[1].length);f.set(d[0]),f.set(d[1],d[0].length),d[0]=f,d.splice(1,1)}if(t=d[0],1===(t[0]<<16)+(t[1]<<8)+t[2]){if((i=(t[4]<<8)+t[5])&&i>e.size-6)return null;r=t[7],192&r&&(s=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,s>4294967295&&(s-=8589934592),64&r?(o=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2,o>4294967295&&(o-=8589934592),s-o>54e5&&(g.logger.warn(Math.round((s-o)/9e4)+"s delta between PTS and DTS, align them"),s=o)):o=s),a=t[8],l=a+9,e.size-=l,n=new Uint8Array(e.size);for(var c=0,h=d.length;cv){l-=v;continue}t=t.subarray(l),v-=l,l=0}n.set(t,u),u+=v}return i&&(i-=a+3),{data:n,pts:s,dts:o,len:i}}return null}},{key:"pushAccesUnit",value:function(e,t){if(e.units.length&&e.frame){var r=t.samples,i=r.length;!this.config.forceKeyFrameOnDiscontinuity||e.key===!0||t.sps&&(i||this.contiguous)?(e.id=i,r.push(e)):t.dropped++}e.debug.length&&g.logger.log(e.pts+"/"+e.dts+":"+e.debug)}},{key:"_parseAVCPES",value:function(e,t){var r,i,a,n=this,s=this._avcTrack,o=this._parseAVCNALu(e.data),l=this.avcSample;e.data=null,o.forEach(function(t){switch(t.type){case 1:i=!0,l.frame=!0;var o=t.data;if(o.length>4){var u=new f.default(o).readSliceType();2!==u&&4!==u&&7!==u&&9!==u||(l.key=!0)}break;case 5:i=!0,l||(l=n.avcSample=n._createAVCSample(!0,e.pts,e.dts,"")),l.key=!0,l.frame=!0;break;case 6:i=!0,r=new f.default(n.discardEPB(t.data)),r.readUByte();for(var d=0,c=0,h=!1,g=0;!h&&r.bytesAvailable>1;){d=0;do{g=r.readUByte(),d+=g}while(255===g);c=0;do{g=r.readUByte(),c+=g}while(255===g);if(4===d&&0!==r.bytesAvailable){h=!0;if(181===r.readUByte()){if(49===r.readUShort()){if(1195456820===r.readUInt()){if(3===r.readUByte()){var v=r.readUByte(),p=r.readUByte(),y=31&v,m=[v,p];for(a=0;a0){if(t.pts>=e[r-1].pts)e.push(t);else for(var i=r-1;i>=0;i--)if(t.pts=0)i={data:e.subarray(c,s-u-1),type:n},f.push(i);else{var h=this._getLastNalUnit();if(h&&(d&&s<=4-d&&h.state&&(h.data=h.data.subarray(0,h.data.byteLength-d)),(r=s-u-1)>0)){var g=new Uint8Array(h.data.byteLength+r);g.set(h.data,0),g.set(e.subarray(0,r),h.data.byteLength),h.data=g}}s=0&&u>=0&&(i={data:e.subarray(c,o),type:n,state:u},f.push(i)),0===f.length){var v=this._getLastNalUnit();if(v){var p=new Uint8Array(v.data.byteLength+e.byteLength);p.set(v.data,0),p.set(e,v.data.byteLength),v.data=p}}return l.naluState=u,f}},{key:"discardEPB",value:function(e){for(var t,r,i=e.byteLength,a=[],n=1;n1&&(g.logger.log("AAC: align PTS for overlapping frames by "+Math.round((k-p)/90)),p=k)}for(;n+5>>5,(r-=s)>0&&n+s+r<=d);)for(l=p+a*i,f={unit:h.subarray(n+s,n+s+r),pts:l,dts:l},c.samples.push(f),c.len+=r,n+=r+s,a++;n0;)s+=t}},{key:"_onMpegFrame",value:function(e,t,r,i,a,n){var s=1152/r*1e3,o=n+a*s,l=this._audioTrack;l.config=[],l.channelCount=i,l.samplerate=r,l.duration=this._duration,l.samples.push({unit:e,pts:o,dts:o}),l.len+=e.length}},{key:"_onMpegNoise",value:function(e){g.logger.warn("mpeg audio has noise: "+e.length+" bytes")}},{key:"_parseMpeg",value:function(e,t,r,i,a){var n=[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],s=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3];if(t+2>r)return-1;if(255===e[t]||224==(224&e[t+1])){if(t+24>r)return-1;var o=e[t+1]>>3&3,l=e[t+1]>>1&3,u=e[t+2]>>4&15,d=e[t+2]>>2&3,f=!!(2&e[t+2]);if(1!==o&&0!==u&&15!==u&&3!==d){var c=3===o?3-l:3===l?3:4,h=1e3*n[14*c+u-1],g=3===o?0:2===o?1:2,v=s[3*g+d],p=f?1:0,y=e[t+3]>>6==3?1:2,m=3===l?(3===o?12:6)*h/v+p<<2:(3===o?144:72)*h/v+p|0;return t+m>r?-1:(this._onMpegFrame&&this._onMpegFrame(e.subarray(t,t+m),h,v,y,i,a),m)}}for(var E=t+2;E=564&&71===e[0]&&71===e[188]&&71===e[376]}}]),e}();r.default=p},{22:22,26:26,29:29,31:31,33:33,51:51}],31:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});r.ErrorTypes={NETWORK_ERROR:"networkError",MEDIA_ERROR:"mediaError",MUX_ERROR:"muxError",OTHER_ERROR:"otherError"},r.ErrorDetails={MANIFEST_LOAD_ERROR:"manifestLoadError",MANIFEST_LOAD_TIMEOUT:"manifestLoadTimeOut",MANIFEST_PARSING_ERROR:"manifestParsingError",MANIFEST_INCOMPATIBLE_CODECS_ERROR:"manifestIncompatibleCodecsError",LEVEL_LOAD_ERROR:"levelLoadError",LEVEL_LOAD_TIMEOUT:"levelLoadTimeOut",LEVEL_SWITCH_ERROR:"levelSwitchError",AUDIO_TRACK_LOAD_ERROR:"audioTrackLoadError",AUDIO_TRACK_LOAD_TIMEOUT:"audioTrackLoadTimeOut",FRAG_LOAD_ERROR:"fragLoadError",FRAG_LOOP_LOADING_ERROR:"fragLoopLoadingError",FRAG_LOAD_TIMEOUT:"fragLoadTimeOut",FRAG_DECRYPT_ERROR:"fragDecryptError",FRAG_PARSING_ERROR:"fragParsingError",REMUX_ALLOC_ERROR:"remuxAllocError",KEY_LOAD_ERROR:"keyLoadError",KEY_LOAD_TIMEOUT:"keyLoadTimeOut",BUFFER_ADD_CODEC_ERROR:"bufferAddCodecError",BUFFER_APPEND_ERROR:"bufferAppendError",BUFFER_APPENDING_ERROR:"bufferAppendingError",BUFFER_STALLED_ERROR:"bufferStalledError",BUFFER_FULL_ERROR:"bufferFullError",BUFFER_SEEK_OVER_HOLE:"bufferSeekOverHole",BUFFER_NUDGE_ON_STALL:"bufferNudgeOnStall",INTERNAL_EXCEPTION:"internalException",WEBVTT_EXCEPTION:"webVTTException"}},{}],32:[function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n=function(){function e(e,t){for(var r=0;r1?r-1:0),n=1;n=r.start(i)&&t<=r.end(i))return!0;return!1},bufferInfo:function(e,t,r){if(e){var i,a=e.buffered,n=[];for(i=0;id&&(l[u-1].end=e[o].end):l.push(e[o])}else l.push(e[o])}for(o=0,i=0,a=n=t;o=f&&t=0&&oe.endSN)return 0;var d,f,c;for(d=u-e.startSN,f=e.fragments,t=f[d],c=d;c>0;c--)a.updatePTS(f,c,c-1);for(c=d;ct?a.start+a.duration:Math.max(a.start-n.duration,0):r>t?(a.duration=s-a.start,a.duration<0&&i.logger.warn("negative duration computed for frag "+a.sn+",level "+a.level+", there should be some duration drift between playlist and fragment!")):(n.duration=a.start-s,n.duration<0&&i.logger.warn("negative duration computed for frag "+n.sn+",level "+n.level+", there should be some duration drift between playlist and fragment!"))}};t.exports=a},{51:51}],37:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{};a(this,e);var i=e.DefaultConfig;if((r.liveSyncDurationCount||r.liveMaxLatencyDurationCount)&&(r.liveSyncDuration||r.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");for(var n in i)n in r||(r[n]=i[n]);if(void 0!==r.liveMaxLatencyDurationCount&&r.liveMaxLatencyDurationCount<=r.liveSyncDurationCount)throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');if(void 0!==r.liveMaxLatencyDuration&&(r.liveMaxLatencyDuration<=r.liveSyncDuration||void 0===r.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');(0,k.enableLogs)(r.debug),this.config=r,this._autoLevelCapping=-1;var s=this.observer=new A.default;s.trigger=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i1?t-1:0),i=1;i0&&void 0!==arguments[0]?arguments[0]:-1;k.logger.log("startLoad("+e+")"),this.networkControllers.forEach(function(t){t.startLoad(e)})}},{key:"stopLoad",value:function(){k.logger.log("stopLoad"),this.networkControllers.forEach(function(e){e.stopLoad()})}},{key:"swapAudioCodec",value:function(){k.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}},{key:"recoverMediaError",value:function(){k.logger.log("recoverMediaError");var e=this.media;this.detachMedia(),this.attachMedia(e)}},{key:"levels",get:function(){return this.levelController.levels}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){k.logger.log("set currentLevel:"+e),this.loadLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){k.logger.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){k.logger.log("set loadLevel:"+e),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){k.logger.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){return this.levelController.startLevel},set:function(e){k.logger.log("set startLevel:"+e);var t=this;e!==-1&&(e=Math.max(e,t.minAutoLevel)),t.levelController.startLevel=e}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){k.logger.log("set autoLevelCapping:"+e),this._autoLevelCapping=e}},{key:"autoLevelEnabled",get:function(){return this.levelController.manualLevel===-1}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){for(var e=this,t=e.levels,r=e.config.minAutoBitrate,i=t?t.length:0,a=0;ar)return a}return 0}},{key:"maxAutoLevel",get:function(){var e=this,t=e.levels,r=e.autoLevelCapping;return r===-1&&t&&t.length?t.length-1:r}},{key:"nextAutoLevel",get:function(){var e=this;return Math.min(Math.max(e.abrController.nextAutoLevel,e.minAutoLevel),e.maxAutoLevel)},set:function(e){var t=this;t.abrController.nextAutoLevel=Math.max(t.minAutoLevel,e)}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"liveSyncPosition",get:function(){return this.streamController.liveSyncPosition}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}}]),e}();r.default=L},{1:1,11:11,12:12,13:13,2:2,31:31,33:33,39:39,4:4,40:40,41:41,51:51}],38:[function(e,t,r){"use strict";t.exports=e(37).default},{37:37}],39:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;r>8*(15-r)&255;return t}},{key:"fragmentDecryptdataFromLevelkey",value:function(e,t){var r=e;return e&&e.method&&e.uri&&!e.iv&&(r=new T,r.method=e.method,r.baseuri=e.baseuri,r.reluri=e.reluri,r.iv=this.createInitializationVector(t)),r}},{key:"cloneObj",value:function(e){return JSON.parse(JSON.stringify(e))}},{key:"url",get:function(){return!this._url&&this.relurl&&(this._url=u.default.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url},set:function(e){this._url=e}},{key:"programDateTime",get:function(){return!this._programDateTime&&this.rawProgramDateTime&&(this._programDateTime=new Date(Date.parse(this.rawProgramDateTime))),this._programDateTime}},{key:"byteRange",get:function(){if(!this._byteRange){var e=this._byteRange=[];if(this.rawByteRange){var t=this.rawByteRange.split("@",2);if(1===t.length){var r=this.lastByteRangeEndOffset;e[0]=r?r:0}else e[0]=parseInt(t[1]);e[1]=parseInt(t[0])+e[0]}}return this._byteRange}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"decryptdata",get:function(){return this._decryptdata||(this._decryptdata=this.fragmentDecryptdataFromLevelkey(this.levelkey,this.sn)),this._decryptdata}}]),e}(),k=function(e){function t(e){s(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,f.default.MANIFEST_LOADING,f.default.LEVEL_LOADING,f.default.AUDIO_TRACK_LOADING,f.default.SUBTITLE_TRACK_LOADING));return r.loaders={},r}return n(t,e),o(t,[{key:"destroy",value:function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy()}this.loaders={},h.default.prototype.destroy.call(this)}},{key:"onManifestLoading",value:function(e){this.load(e.url,{type:"manifest"})}},{key:"onLevelLoading",value:function(e){this.load(e.url,{type:"level",level:e.level,id:e.id})}},{key:"onAudioTrackLoading",value:function(e){this.load(e.url,{type:"audioTrack",id:e.id})}},{key:"onSubtitleTrackLoading",value:function(e){this.load(e.url,{type:"subtitleTrack",id:e.id})}},{key:"load",value:function(e,t){var r=this.loaders[t.type];if(r){var i=r.context;if(i&&i.url===e)return void y.logger.trace("playlist request ongoing");y.logger.warn("abort previous loader for type:"+t.type),r.abort()}var a=this.hls.config,n=void 0,s=void 0,o=void 0,l=void 0;"manifest"===t.type?(n=a.manifestLoadingMaxRetry,s=a.manifestLoadingTimeOut,o=a.manifestLoadingRetryDelay,l=a.manifestLoadingMaxRetryTimeout):(n=a.levelLoadingMaxRetry,s=a.levelLoadingTimeOut,o=a.levelLoadingRetryDelay,l=a.levelLoadingMaxRetryTimeout,y.logger.log("loading playlist for "+t.type+" "+(t.level||t.id))),r=this.loaders[t.type]=t.loader=void 0!==a.pLoader?new a.pLoader(a):new a.loader(a),t.url=e,t.responseType="";var u=void 0,d=void 0;u={timeout:s,maxRetry:n,retryDelay:o,maxRetryDelay:l},d={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)},r.load(t,u,d)}},{key:"resolve",value:function(e,t){return u.default.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}},{key:"parseMasterPlaylist",value:function(e,t){var r=[],i=void 0;for(m.lastIndex=0;null!=(i=m.exec(e));){var a={},n=a.attrs=new p.default(i[1]);a.url=this.resolve(i[2],t);var s=n.decimalResolution("RESOLUTION");s&&(a.width=s.width,a.height=s.height),a.bitrate=n.decimalInteger("AVERAGE-BANDWIDTH")||n.decimalInteger("BANDWIDTH"),a.name=n.NAME;var o=n.CODECS;if(o){o=o.split(/[ ,]+/);for(var l=0;l2?(t=r.shift()+".",t+=parseInt(r.shift()).toString(16),t+=("000"+parseInt(r.shift()).toString(16)).substr(-4)):t=e,t}},{key:"parseLevelPlaylist",value:function(e,t,r,i){var a,n,s=0,o=0,l={type:null,version:null,url:t,fragments:[],live:!0,startSN:0},u=new T,d=0,f=null,c=new _;for(b.lastIndex=0;null!==(a=b.exec(e));){var h=a[1];if(h){c.duration=parseFloat(h);var g=(" "+a[2]).slice(1);c.title=g?g:null,c.tagList.push(g?["INF",h,g]:["INF",h])}else if(a[3]){if(!isNaN(c.duration)){var v=s++;c.type=i,c.start=o,c.levelkey=u,c.sn=v,c.level=r,c.cc=d,c.baseurl=t,c.relurl=(" "+a[3]).slice(1),l.fragments.push(c),f=c,o+=c.duration,c=new _}}else if(a[4]){if(c.rawByteRange=(" "+a[4]).slice(1),f){var m=f.byteRangeEndOffset;m&&(c.lastByteRangeEndOffset=m)}}else if(a[5])c.rawProgramDateTime=(" "+a[5]).slice(1),c.tagList.push(["PROGRAM-DATE-TIME",c.rawProgramDateTime]);else{for(a=a[0].match(/(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)(.*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/),n=1;n=0&&(u.method=S,u.baseuri=t,u.reluri=L,u.key=null,u.iv=w));break;case"START":var D=E,O=new p.default(D),I=O.decimalFloatingPoint("TIME-OFFSET");isNaN(I)||(l.startTimeOffset=I);break;case"MAP":var P=new p.default(E);c.relurl=P.URI,c.rawByteRange=P.BYTERANGE,c.baseurl=t,c.level=r,c.type=i,c.sn="initSegment",l.initSegment=c,c=new _;break;default:y.logger.warn("line parsed but not handled: "+a)}}}return c=f,c&&!c.relurl&&(l.fragments.pop(),o-=c.duration),l.totalduration=o,l.averagetargetduration=o/l.fragments.length,l.endSN=s-1,l}},{key:"loadsuccess",value:function(e,t,r){var i=e.data,a=e.url,n=r.type,s=r.id,o=r.level,l=this.hls;if(this.loaders[n]=void 0,void 0!==a&&0!==a.indexOf("data:")||(a=r.url),t.tload=performance.now(),0===i.indexOf("#EXTM3U"))if(i.indexOf("#EXTINF:")>0){var u="audioTrack"!==n&&"subtitleTrack"!==n,d=isNaN(o)?isNaN(s)?0:s:o,c=this.parseLevelPlaylist(i,a,d,"audioTrack"===n?"audio":"subtitleTrack"===n?"subtitle":"main");c.tload=t.tload,"manifest"===n&&l.trigger(f.default.MANIFEST_LOADED,{levels:[{url:a,details:c}],audioTracks:[],url:a,stats:t}),t.tparsed=performance.now(),c.targetduration?u?l.trigger(f.default.LEVEL_LOADED,{details:c,level:o||0,id:s||0,stats:t}):"audioTrack"===n?l.trigger(f.default.AUDIO_TRACK_LOADED,{details:c,id:s,stats:t}):"subtitleTrack"===n&&l.trigger(f.default.SUBTITLE_TRACK_LOADED,{details:c,id:s,stats:t}):l.trigger(f.default.ERROR,{type:g.ErrorTypes.NETWORK_ERROR,details:g.ErrorDetails.MANIFEST_PARSING_ERROR,fatal:!0,url:a,reason:"invalid targetduration"})}else{var h=this.parseMasterPlaylist(i,a);if(h.length){var v=this.parseMasterPlaylistMedia(i,a,"AUDIO"),p=this.parseMasterPlaylistMedia(i,a,"SUBTITLES");if(v.length){var m=!1;v.forEach(function(e){e.url||(m=!0)}),m===!1&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(y.logger.log("audio codec signaled in quality level, but no embedded audio track signaled, create one"),v.unshift({type:"main",name:"main"}))}l.trigger(f.default.MANIFEST_LOADED,{levels:h,audioTracks:v,subtitles:p,url:a,stats:t})}else l.trigger(f.default.ERROR,{type:g.ErrorTypes.NETWORK_ERROR,details:g.ErrorDetails.MANIFEST_PARSING_ERROR,fatal:!0,url:a,reason:"no level found in manifest"})}else l.trigger(f.default.ERROR,{type:g.ErrorTypes.NETWORK_ERROR,details:g.ErrorDetails.MANIFEST_PARSING_ERROR,fatal:!0,url:a,reason:"no EXTM3U delimiter"})}},{key:"loaderror",value:function(e,t){var r,i,a=t.loader;switch(t.type){case"manifest":r=g.ErrorDetails.MANIFEST_LOAD_ERROR,i=!0;break;case"level":r=g.ErrorDetails.LEVEL_LOAD_ERROR,i=!1;break;case"audioTrack":r=g.ErrorDetails.AUDIO_TRACK_LOAD_ERROR,i=!1}a&&(a.abort(),this.loaders[t.type]=void 0),this.hls.trigger(f.default.ERROR,{type:g.ErrorTypes.NETWORK_ERROR,details:r,fatal:i,url:a.url,loader:a,response:e,context:t})}},{key:"loadtimeout",value:function(e,t){var r,i,a=t.loader;switch(t.type){case"manifest":r=g.ErrorDetails.MANIFEST_LOAD_TIMEOUT,i=!0;break;case"level":r=g.ErrorDetails.LEVEL_LOAD_TIMEOUT,i=!1;break;case"audioTrack":r=g.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT,i=!1}a&&(a.abort(),this.loaders[t.type]=void 0),this.hls.trigger(f.default.ERROR,{type:g.ErrorTypes.NETWORK_ERROR,details:r,fatal:i,url:a.url,loader:a,context:t})}}]),t}(h.default);r.default=k},{2:2,31:31,32:32,33:33,45:45,51:51}],42:[function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r>24&255,t[1]=i>>16&255,t[2]=i>>8&255,t[3]=255&i,t.set(e,4),a=0,i=8;a>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,85,196,0,0]))}},{key:"mdia",value:function(t){return e.box(e.types.mdia,e.mdhd(t.timescale,t.duration),e.hdlr(t.type),e.minf(t))}},{key:"mfhd",value:function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}},{key:"minf",value:function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))}},{key:"moof",value:function(t,r,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))}},{key:"moov",value:function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(e.mvex(t)))}},{key:"mvex",value:function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(i))}},{key:"mvhd",value:function(t,r){r*=t;var i=Math.floor(r/(n+1)),a=Math.floor(r%(n+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,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 e.box(e.types.mvhd,s)}},{key:"sdtp",value:function(t){var r,i,a=t.samples||[],n=new Uint8Array(4+a.length);for(i=0;i>>8&255),n.push(255&a),n=n.concat(Array.prototype.slice.call(i));for(r=0;r>>8&255),s.push(255&a),s=s.concat(Array.prototype.slice.call(i));var o=e.box(e.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(s))),l=t.width,u=t.height,d=t.pixelRatio[0],f=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,f>>24,f>>16&255,f>>8&255,255&f])))}},{key:"esds",value:function(e){var t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}},{key:"mp4a",value:function(t){var r=t.samplerate;return e.box(e.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),e.box(e.types.esds,e.esds(t)))}},{key:"mp3",value:function(t){var r=t.samplerate;return e.box(e.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))}},{key:"stsd",value:function(t){return"audio"===t.type?t.isAAC||"mp3"!==t.codec?e.box(e.types.stsd,e.STSD,e.mp4a(t)):e.box(e.types.stsd,e.STSD,e.mp3(t)):e.box(e.types.stsd,e.STSD,e.avc1(t))}},{key:"tkhd",value:function(t){var r=t.id,i=t.duration*t.timescale,a=t.width,s=t.height,o=Math.floor(i/(n+1)),l=Math.floor(i%(n+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,o>>24,o>>16&255,o>>8&255,255&o,l>>24,l>>16&255,l>>8&255,255&l,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,a>>8&255,255&a,0,0,s>>8&255,255&s,0,0]))}},{key:"traf",value:function(t,r){var i=e.sdtp(t),a=t.id,s=Math.floor(r/(n+1)),o=Math.floor(r%(n+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o])),e.trun(t,i.length+16+20+8+16+8+8),i)}},{key:"trak",value:function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))}},{key:"trex",value:function(t){var r=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}},{key:"trun",value:function(t,r){var i,a,n,s,o,l,u=t.samples||[],d=u.length,f=12+16*d,c=new Uint8Array(f);for(r+=8+f,c.set([0,0,15,1,d>>>24&255,d>>>16&255,d>>>8&255,255&d,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i>>24&255,n>>>16&255,n>>>8&255,255&n,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return e.box(e.types.trun,c)}},{key:"initSegment",value:function(t){e.types||e.init();var r,i=e.moov(t);return r=new Uint8Array(e.FTYP.byteLength+i.byteLength),r.set(e.FTYP),r.set(i,e.FTYP.byteLength),r}}]),e}();r.default=s},{}],43:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r-1&&s&&!s.match("CriOS"),this.ISGenerated=!1}return n(e,[{key:"destroy",value:function(){}},{key:"resetTimeStamp",value:function(e){this._initPTS=this._initDTS=e}},{key:"resetInitSegment",value:function(){this.ISGenerated=!1}},{key:"remux",value:function(e,t,r,i,a,n,s){if(this.ISGenerated||this.generateIS(e,t,a),this.ISGenerated)if(e.samples.length){e.timescale||(d.logger.warn("regenerate InitSegment as audio detected"),this.generateIS(e,t,a));var o=this.remuxAudio(e,a,n,s);if(t.samples.length){var l=void 0;o&&(l=o.endPTS-o.startPTS),t.timescale||(d.logger.warn("regenerate InitSegment as video detected"),this.generateIS(e,t,a)),this.remuxVideo(t,a,n,l)}}else{var f=void 0;t.samples.length&&(f=this.remuxVideo(t,a,n)),f&&e.codec&&this.remuxEmptyAudio(e,a,n,f)}r.samples.length&&this.remuxID3(r,a),i.samples.length&&this.remuxText(i,a),this.observer.trigger(u.default.FRAG_PARSED)}},{key:"generateIS",value:function(e,t,r){var i,a,n=this.observer,s=e.samples,o=t.samples,l=this.typeSupported,f="audio/mp4",g={},v={tracks:g},p=void 0===this._initPTS;if(p&&(i=a=1/0),e.config&&s.length&&(e.timescale=e.samplerate,d.logger.log("audio sampling rate : "+e.samplerate),e.isAAC||(l.mpeg?(f="audio/mpeg",e.codec=""):l.mp3&&(e.codec="mp3")),g.audio={container:f,codec:e.codec,initSegment:!e.isAAC&&l.mpeg?new Uint8Array:c.default.initSegment([e]),metadata:{channelCount:e.channelCount}},p&&(i=a=s[0].pts-e.inputTimeScale*r)),t.sps&&t.pps&&o.length){var y=t.inputTimeScale;t.timescale=y,g.video={container:"video/mp4",codec:t.codec,initSegment:c.default.initSegment([t]),metadata:{width:t.width,height:t.height}},p&&(i=Math.min(i,o[0].pts-y*r),a=Math.min(a,o[0].dts-y*r),this.observer.trigger(u.default.INIT_PTS_FOUND,{initPTS:i}))}Object.keys(g).length?(n.trigger(u.default.FRAG_PARSING_INIT_SEGMENT,v),this.ISGenerated=!0,p&&(this._initPTS=i,this._initDTS=a)):n.trigger(u.default.ERROR,{type:h.ErrorTypes.MEDIA_ERROR,details:h.ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,reason:"no audio/video samples found"})}},{key:"remuxVideo",value:function(e,t,r,i){var a,n,s,o,l,f,g,v=8,p=e.timescale,y=e.samples,m=[],E=y.length,b=this._PTSNormalize,T=this._initDTS;y.sort(function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r?r:i?i:e.id-t.id});var _=y.reduce(function(e,t){return Math.max(Math.min(e,t.pts-t.dts),-18e3)},0);if(_<0){d.logger.warn("PTS < DTS detected in video samples, shifting DTS by "+Math.round(_/90)+" ms to overcome this issue");for(var k=0;k1?d.logger.log("AVC:"+S+" ms hole between fragments detected,filling it"):S<-1&&d.logger.log("AVC:"+-S+" ms overlapping between fragments detected"),l=R,y[0].dts=l+T,o=Math.max(o-S,R),y[0].pts=o+T,d.logger.log("Video/PTS/DTS adjusted: "+Math.round(o/90)+"/"+Math.round(l/90)+",delta:"+S+" ms")),A=y[y.length-1],g=Math.max(b(A.dts-T,R),0),f=Math.max(b(A.pts-T,R),0),f=Math.max(f,g);var L=this.isSafari;L&&(a=Math.round((g-l)/(y.length-1)));for(var w=0,D=0,O=0;O0?U-1:U].dts;if(z.stretchShortVideoTrack){var Q=z.maxBufferHole,J=z.maxSeekHole,Z=Math.floor(Math.min(Q,J)*p),$=(i?o+i*p:this.nextAudioPts)-B.pts;$>Z?(a=$-q,a<0&&(a=q),d.logger.log("It is approximately "+$/90+" ms to the next segment; using duration "+a/90+" ms for the last video frame.")):a=q}else a=q}K=Math.round(B.pts-B.dts)}m.push({size:j,duration:a,cts:K,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:B.key?2:1,isNonSync:B.key?0:1}})}this.nextAvcDts=g+a;var ee=e.dropped;if(e.len=0,e.nbNalu=0,e.dropped=0,m.length&&navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var te=m[0].flags;te.dependsOn=2,te.isNonSync=0}e.samples=m,s=c.default.moof(e.sequenceNumber++,l,e),e.samples=[];var re={data1:s,data2:n,startPTS:o/p,endPTS:(f+a)/p,startDTS:l/p,endDTS:this.nextAvcDts/p,type:"video",nb:m.length,dropped:ee};return this.observer.trigger(u.default.FRAG_PARSING_DATA,re),re}},{key:"remuxAudio",value:function(e,t,r,i){var a,n,s,l,f,g,v,p,y,m,E,b,T,_,k,R,A=e.inputTimeScale,S=e.timescale,L=A/S,w=e.isAAC?1024:1152,D=w*L,O=this._PTSNormalize,I=this._initDTS,P=!e.isAAC&&this.typeSupported.mpeg,C=P?0:8,x=[],F=[];if(e.samples.sort(function(e,t){return e.pts-t.pts}),F=e.samples,R=this.nextAudioPts,r|=F.length&&R&&(i&&Math.abs(t-R/A)<.1||Math.abs(F[0].pts-R-I)<20*D),r||(R=t*A),i&&e.isAAC)for(var M=0,N=R;M=D&&N){var j=Math.round(G/D);d.logger.warn("Injecting "+j+" audio frame @ "+(N/A).toFixed(3)+"s due to "+1e3*G/A+" ms gap.");for(var K=0;K0)Y=Math.round((b-R)/D),d.logger.log(V+" ms hole between AAC samples detected,filling it"),Y>0&&(_=o.default.getSilentFrame(e.manifestCodec||e.codec,e.channelCount),_||(_=l.subarray()),e.len+=Y*_.length);else if(V<-12){d.logger.log("drop overlapping AAC sample, expected/parsed/delta:"+(R/A).toFixed(3)+"s/"+(b/A).toFixed(3)+"s/"+-V+"ms"),e.len-=l.byteLength;continue}b=T=R}if(v=Math.max(0,b),p=Math.max(0,T),!(e.len>0))return;var X=P?e.len:e.len+8;try{f=new Uint8Array(X)}catch(e){return void this.observer.trigger(u.default.ERROR,{type:h.ErrorTypes.MUX_ERROR,details:h.ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,bytes:X,reason:"fail allocating audio mdat "+X})}P||(a=new DataView(f.buffer),a.setUint32(0,X),f.set(c.default.types.mdat,4));for(var z=0;z=2&&(Q=x[J-2].duration,s.duration=Q),J){this.nextAudioPts=b+L*Q,e.len=0,e.samples=x,g=P?new Uint8Array:c.default.moof(e.sequenceNumber++,p/L,e),e.samples=[];var Z={data1:g,data2:f,startPTS:v/A,endPTS:this.nextAudioPts/A,startDTS:p/A,endDTS:(T+L*Q)/A,type:"audio",nb:J};return this.observer.trigger(u.default.FRAG_PARSING_DATA,Z),Z}return null}},{key:"remuxEmptyAudio",value:function(e,t,r,i){var a=e.inputTimeScale,n=e.samplerate?e.samplerate:a,s=a/n,l=this.nextAudioPts,u=(void 0!==l?l:i.startDTS*a)+this._initDTS,f=i.endDTS*a+this._initDTS,c=1024*s,h=Math.ceil((f-u)/c),g=o.default.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(d.logger.warn("remux empty Audio"),!g)return void d.logger.trace("Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!");for(var v=[],p=0;p4294967296;)e+=r;return e}}]),e}();r.default=g},{31:31,33:33,34:34,42:42,51:51}],44:[function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;rNumber.MAX_SAFE_INTEGER?1/0:t}},{key:"hexadecimalInteger",value:function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),i=0;iNumber.MAX_SAFE_INTEGER?1/0:t}},{key:"decimalFloatingPoint",value:function(e){return parseFloat(this[e])}},{key:"enumeratedString",value:function(e){return this[e]}},{key:"decimalResolution",value:function(e){var t=n.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}}],[{key:"parseAttrList",value:function(e){var t,r={};for(s.lastIndex=0;null!==(t=s.exec(e));){var i=t[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[t[1]]=i}return r}}]),e}();r.default=o},{}],46:[function(e,t,r){"use strict";var i={search:function(e,t){for(var r=0,i=e.length-1,a=null,n=null;r<=i;){a=(r+i)/2|0,n=e[a];var s=t(n);if(s>0)r=a+1;else{ -if(!(s<0))return n;i=a-1}}return null}};t.exports=i},{}],47:[function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;rl&&(g.log("ERROR","Too large cursor position "+this.pos),this.pos=l)}},{key:"moveCursor",value:function(e){var t=this.pos+e;if(e>1)for(var r=this.pos+1;r=144&&this.backSpace();var t=s(e);if(this.pos>=l)return void g.log("ERROR","Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}},{key:"clearFromPos",value:function(e){var t;for(t=e;t0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r}},{key:"getTextAndFormat",value:function(){return this.rows}}]),e}(),b=function(){function e(t,r){i(this,e),this.chNr=t,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new E,this.nonDisplayedMemory=new E,this.lastOutputScreen=new E,this.currRollUpRow=this.displayedMemory.rows[o-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}return a(e,[{key:"reset",value:function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.currRollUpRow=this.displayedMemory.rows[o-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.lastCueEndTime=null}},{key:"getHandler",value:function(){return this.outputFilter}},{key:"setHandler",value:function(e){this.outputFilter=e}},{key:"setPAC",value:function(e){this.writeScreen.setPAC(e)}},{key:"setBkgData",value:function(e){this.writeScreen.setBkgData(e)}},{key:"setMode",value:function(e){e!==this.mode&&(this.mode=e,g.log("INFO","MODE="+e),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}},{key:"insertChars",value:function(e){for(var t=0;t=46,t.italics)t.foreground="white";else{var r=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[r]}g.log("INFO","MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}},{key:"outputDataUpdate",value:function(){var e=g.time;null!==e&&this.outputFilter&&(this.outputFilter.updateData&&this.outputFilter.updateData(e,this.displayedMemory),null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}},{key:"cueSplitAtTime",value:function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}]),e}(),T=function(){function e(t,r,a){i(this,e),this.field=t||1,this.outputs=[r,a],this.channels=[new b(1,r),new b(2,a)],this.currChNr=-1,this.lastCmdA=null,this.lastCmdB=null,this.bufferedData=[],this.startTime=null,this.lastTime=null,this.dataCounters={padding:0,char:0,cmd:0,other:0}}return a(e,[{key:"getHandler",value:function(e){return this.channels[e].getHandler()}},{key:"setHandler",value:function(e,t){this.channels[e].setHandler(t)}},{key:"addData",value:function(e,t){var r,i,a,n=!1;this.lastTime=e,g.setTime(e);for(var s=0;s ("+v([i,a])+")"),r=this.parseCmd(i,a),r||(r=this.parseMidrow(i,a)),r||(r=this.parsePAC(i,a)),r||(r=this.parseBackgroundAttributes(i,a)),!r&&(n=this.parseChars(i,a)))if(this.currChNr&&this.currChNr>=0){var o=this.channels[this.currChNr-1];o.insertChars(n)}else g.log("WARNING","No channel found yet. TEXT-MODE?");r?this.dataCounters.cmd+=2:n?this.dataCounters.char+=2:(this.dataCounters.other+=2,g.log("WARNING","Couldn't parse cleaned data "+v([i,a])+" orig: "+v([t[s],t[s+1]])))}else this.dataCounters.padding+=2}},{key:"parseCmd",value:function(e,t){var r=null,i=(20===e||28===e)&&32<=t&&t<=47,a=(23===e||31===e)&&33<=t&&t<=35;if(!i&&!a)return!1;if(e===this.lastCmdA&&t===this.lastCmdB)return this.lastCmdA=null,this.lastCmdB=null,g.log("DEBUG","Repeated command ("+v([e,t])+") is dropped"),!0;r=20===e||23===e?1:2;var n=this.channels[r-1];return 20===e||28===e?32===t?n.ccRCL():33===t?n.ccBS():34===t?n.ccAOF():35===t?n.ccAON():36===t?n.ccDER():37===t?n.ccRU(2):38===t?n.ccRU(3):39===t?n.ccRU(4):40===t?n.ccFON():41===t?n.ccRDC():42===t?n.ccTR():43===t?n.ccRTD():44===t?n.ccEDM():45===t?n.ccCR():46===t?n.ccENM():47===t&&n.ccEOC():n.ccTO(t-32),this.lastCmdA=e,this.lastCmdB=t,this.currChNr=r,!0}},{key:"parseMidrow",value:function(e,t){var r=null;if((17===e||25===e)&&32<=t&&t<=47){if((r=17===e?1:2)!==this.currChNr)return g.log("ERROR","Mismatch channel in midrow parsing"),!1;return this.channels[r-1].ccMIDROW(t),g.log("DEBUG","MIDROW ("+v([e,t])+")"),!0}return!1}},{key:"parsePAC",value:function(e,t){var r=null,i=null,a=(17<=e&&e<=23||25<=e&&e<=31)&&64<=t&&t<=127,n=(16===e||24===e)&&64<=t&&t<=95;if(!a&&!n)return!1;if(e===this.lastCmdA&&t===this.lastCmdB)return this.lastCmdA=null,this.lastCmdB=null,!0;r=e<=23?1:2,i=64<=t&&t<=95?1===r?u[e]:f[e]:1===r?d[e]:c[e];var s=this.interpretPAC(i,t);return this.channels[r-1].setPAC(s),this.lastCmdA=e,this.lastCmdB=t,this.currChNr=r,!0}},{key:"interpretPAC",value:function(e,t){var r=t,i={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,i.underline=1==(1&r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i}},{key:"parseChars",value:function(e,t){var r=null,i=null,a=null;if(e>=25?(r=2,a=e-8):(r=1,a=e),17<=a&&a<=19){var n=t;n=17===a?t+80:18===a?t+112:t+144,g.log("INFO","Special char '"+s(n)+"' in channel "+r),i=[n]}else 32<=e&&e<=127&&(i=0===t?[e]:[e,t]);if(i){var o=v(i);g.log("DEBUG","Char codes = "+o.join(",")),this.lastCmdA=null,this.lastCmdB=null}return i}},{key:"parseBackgroundAttributes",value:function(e,t){var r,i,a,n,s=(16===e||24===e)&&32<=t&&t<=47,o=(23===e||31===e)&&45<=t&&t<=47;return!(!s&&!o)&&(r={},16===e||24===e?(i=Math.floor((t-32)/2),r.background=h[i],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0)),a=e<24?1:2,n=this.channels[a-1],n.setBkgData(r),this.lastCmdA=null,this.lastCmdB=null,!0)}},{key:"reset",value:function(){for(var e=0;e=16?l--:l++,navigator.userAgent.match(/Firefox\//)?s.line=f+1:s.line=f>7?f-2:f+1,s.align="left",s.position=Math.max(0,Math.min(100,l/32*100+(navigator.userAgent.match(/Firefox\//)?50:0))),e.addCue(s)}}};t.exports=a},{54:54}],49:[function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r=this.minWeight_}},{key:"getEstimate",value:function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}},{key:"destroy",value:function(){}}]),e}();r.default=o},{50:50}],50:[function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r "+t}function n(e){var t=self.console[e];return t?function(){for(var r=arguments.length,i=Array(r),n=0;n1?t-1:0),i=1;i100)throw new Error("Position must be between 0 and 100.");b=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},u,{get:function(){return T},set:function(e){var r=t(e);if(!r)throw new SyntaxError("An invalid or illegal string was specified.");T=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},u,{get:function(){return _},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");_=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},u,{get:function(){return k},set:function(e){var r=t(e);if(!r)throw new SyntaxError("An invalid or illegal string was specified.");k=r,this.hasBeenReset=!0}})),o.displayState=void 0,l)return o}if("undefined"!=typeof window&&window.VTTCue)return window.VTTCue;var a="auto",n={"":!0,lr:!0,rl:!0},s={start:!0,middle:!0,end:!0,left:!0,right:!0};return i.prototype.getCueAsHTML=function(){return window.WebVTT.convertCueToDOMTree(window,this.text)},i}()},{}],54:[function(e,t,r){"use strict";function i(){this.window=window,this.state="INITIAL",this.buffer="",this.decoder=new f,this.regionList=[]}function a(e){function t(e,t,r,i){return 3600*(0|e)+60*(0|t)+(0|r)+(0|i)/1e3}var r=e.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);return r?r[3]?t(r[1],r[2],r[3].replace(":",""),r[4]):r[1]>59?t(r[1],r[2],0,r[4]):t(0,r[1],r[2],r[4]):null}function n(){this.values=Object.create(null)}function s(e,t,r,i){var a=i?e.split(i):[e];for(var n in a)if("string"==typeof a[n]){var s=a[n].split(r);if(2===s.length){var o=s[0],l=s[1];t(o,l)}}}function o(e,t,r){function i(){var t=a(e);if(null===t)throw new Error("Malformed timestamp: "+l);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function o(){e=e.replace(/^\s+/,"")}var l=e;if(o(),t.startTime=i(),o(),"-->"!==e.substr(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+l);e=e.substr(3),o(),t.endTime=i(),o(),function(e,t){var i=new n;s(e,function(e,t){switch(e){case"region":for(var a=r.length-1;a>=0;a--)if(r[a].id===t){i.set(e,r[a].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":var n=t.split(","),s=n[0];i.integer(e,s),i.percent(e,s)&&i.set("snapToLines",!1),i.alt(e,s,["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",h,"end"]);break;case"position":n=t.split(","),i.percent(e,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",h,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",h,"end","left","right"])}},/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");var a=i.get("line","auto");"auto"===a&&c.line===-1&&(a=-1),t.line=a,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",h);var o=i.get("position","auto");"auto"===o&&50===c.position&&(o="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=o}(e,t)}function l(e){return e.replace(//gi,"\n")}Object.defineProperty(r,"__esModule",{value:!0}),r.fixLineBreaks=void 0;var u=e(53),d=function(e){return e&&e.__esModule?e:{default:e}}(u),f=function(){return{decode:function(e){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}};n.prototype={set:function(e,t){this.get(e)||""===t||(this.values[e]=t)},get:function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t},has:function(e){return e in this.values},alt:function(e,t,r){for(var i=0;i=0&&t<=100)&&(this.set(e,t),!0)}};var c=new d.default(0,0,0),h="middle"===c.align?"middle":"center";i.prototype={parse:function(e){function t(){var e=r.buffer,t=0;for(e=l(e);t")===-1){r.cue.id=i;continue}case"CUE":try{o(i,r.cue,r.regionList)}catch(e){r.cue=null,r.state="BADCUE";continue}r.state="CUETEXT";continue;case"CUETEXT":var u=i.indexOf("-->")!==-1;if(!i||u&&(n=!0)){r.oncue&&r.oncue(r.cue),r.cue=null,r.state="ID";continue}r.cue.text&&(r.cue.text+="\n"),r.cue.text+=i;continue;case"BADCUE":i||(r.state="ID");continue}}}catch(e){"CUETEXT"===r.state&&r.cue&&r.oncue&&r.oncue(r.cue),r.cue=null,r.state="INITIAL"===r.state?"BADWEBVTT":"BADCUE"}return this},flush:function(){var e=this;try{if(e.buffer+=e.decoder.decode(),(e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state)throw new Error("Malformed WebVTT signature.")}catch(e){throw e}return e.onflush&&e.onflush(),this}},r.fixLineBreaks=l,r.default=i},{53:53}],55:[function(e,t,r){"use strict";var i=e(54),a=function(e){return e&&e.__esModule?e:{default:e}}(i),n=function(e){var t=parseInt(e.substr(-3)),r=parseInt(e.substr(-6,2)),i=parseInt(e.substr(-9,2)),a=e.length>9?parseInt(e.substr(0,e.indexOf(":"))):0;return isNaN(t)||isNaN(r)||isNaN(i)||isNaN(a)?-1:(t+=1e3*r,t+=6e4*i,t+=36e5*a)},s=function(e,t,r){var i=e[t],a=e[i.prevCC];if(!a||!a.new&&i.new)return e.ccOffset=e.presentationOffset=i.start,void(i.new=!1);for(;a&&a.new;)e.ccOffset+=i.start-a.start,i.new=!1,i=a,a=e[i.prevCC];e.presentationOffset=r},o={parse:function(e,t,r,i,o,l){var u=String.fromCharCode.apply(null,new Uint8Array(e)).trim().replace(/\r\n|\n\r|\n|\r/g,"\n").split("\n"),d="00:00.000",f=0,c=0,h=0,g=[],v=void 0,p=!0,y=new a.default;y.oncue=function(e){var t=r[i],a=r.ccOffset;t&&t.new&&(c?a=r.ccOffset=t.start:s(r,i,h)),h&&!c&&(a=h+r.ccOffset-r.presentationOffset),e.startTime+=a-c,e.endTime+=a-c,e.text=decodeURIComponent(escape(e.text)),e.endTime>0&&g.push(e)},y.onparsingerror=function(e){v=e},y.onflush=function(){if(v&&l)return void l(v);o(g)},u.forEach(function(e){if(p){if(e.startsWith("X-TIMESTAMP-MAP=")){p=!1,e.substr(16).split(",").forEach(function(e){e.startsWith("LOCAL:")?d=e.substr(6):e.startsWith("MPEGTS:")&&(f=parseInt(e.substr(7)))});try{t=t<0?t+8589934592:t,f-=t,c=n(d)/1e3,h=f/9e4,c===-1&&(v=new Error("Malformed X-TIMESTAMP-MAP: "+e))}catch(t){v=new Error("Malformed X-TIMESTAMP-MAP: "+e)}return}""===e&&(p=!1)}y.parse(e+"\n")}),y.flush()}};t.exports=o},{54:54}],56:[function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r=2)if(window.clearTimeout(this.requestTimeout),0===i.tfirst&&(i.tfirst=Math.max(performance.now(),i.trequest)),4===r){var o=t.status;if(o>=200&&o<300){i.tload=Math.max(i.tfirst,performance.now());var l=void 0,u=void 0;"arraybuffer"===a.responseType?(l=t.response,u=l.byteLength):(l=t.responseText,u=l.length),i.loaded=i.total=u;var d={url:t.responseURL,data:l};this.callbacks.onSuccess(d,i,a)}else i.retry>=s.maxRetry||o>=400&&o<499?(n.logger.error(o+" while loading "+a.url),this.callbacks.onError({code:o,text:t.statusText},a)):(n.logger.warn(o+" while loading "+a.url+", retrying in "+this.retryDelay+"..."),this.destroy(),this.retryTimeout=window.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,s.maxRetryDelay),i.retry++)}else this.requestTimeout=window.setTimeout(this.loadtimeout.bind(this),s.timeout)}},{key:"loadtimeout",value:function(){n.logger.warn("timeout while loading "+this.context.url),this.callbacks.onTimeout(this.stats,this.context)}},{key:"loadprogress",value:function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total);var r=this.callbacks.onProgress;r&&r(t,this.context,null)}}]),e}() -;r.default=s},{51:51}]},{},[38])(38)}); +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.Hls=e()}}(function(){var e;return function e(t,r,i){function a(s,o){if(!r[s]){if(!t[s]){var l="function"==typeof require&&require;if(!o&&l)return l(s,!0);if(n)return n(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var d=r[s]={exports:{}};t[s][0].call(d.exports,function(e){var r=t[s][1][e];return a(r?r:e)},d,d.exports,e,t,r,i)}return r[s].exports}for(var n="function"==typeof require&&require,s=0;s0&&this._events[e].length>r&&(this._events[e].warned=!0,console.trace),this},i.prototype.on=i.prototype.addListener,i.prototype.once=function(e,t){function r(){this.removeListener(e,r),i||(i=!0,t.apply(this,arguments))}if(!a(t))throw TypeError("listener must be a function");var i=!1;return r.listener=t,this.on(e,r),this},i.prototype.removeListener=function(e,t){var r,i,n,o;if(!a(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=this._events[e],n=r.length,i=-1,r===t||a(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(s(r)){for(o=n;o-- >0;)if(r[o]===t||r[o].listener&&r[o].listener===t){i=o;break}if(i<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(i,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},i.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[e],a(r))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},i.prototype.listeners=function(e){return this._events&&this._events[e]?a(this._events[e])?[this._events[e]]:this._events[e].slice():[]},i.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(a(t))return 1;if(t)return t.length}return 0},i.listenerCount=function(e,t){return e.listenerCount(t)}},{}],2:[function(t,r,i){!function(t){var a=/^((?:[^\/;?#]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/,n=/^([^\/;?#]*)(.*)$/,s={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var i=this.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");return i.path=s.normalizePath(i.path),s.buildURLFromParts(i)}var a=this.parseURL(t);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return r.alwaysNormalize?(a.path=s.normalizePath(a.path),s.buildURLFromParts(a)):t;var o=this.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=n.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var u={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(u.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var d=o.path,f=d.substring(0,d.lastIndexOf("/")+1)+a.path;u.path=s.normalizePath(f)}else u.path=o.path,a.params||(u.params=o.params,a.query||(u.query=o.query));return null===u.path&&(u.path=r.alwaysNormalize?s.normalizePath(a.path):a.path),s.buildURLFromParts(u)},parseURL:function(e){var t=a.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(/(?:\/|^)\.(?=\/)/g,"");e.length!==(e=e.replace(/(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/g,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};"object"==typeof i&&"object"==typeof r?r.exports=s:"function"==typeof e&&e.amd?e([],function(){return s}):"object"==typeof i?i.URLToolkit=s:t.URLToolkit=s}(this)},{}],3:[function(e,t,r){var i=arguments[3],a=arguments[4],n=arguments[5],s=JSON.stringify;t.exports=function(e,t){function r(e){p[e]=!0;for(var t in a[e][1]){var i=a[e][1][t];p[i]||r(i)}}for(var o,l=Object.keys(n),u=0,d=l.length;u500*r.duration/o){var l=e.levels,d=Math.max(1,n.bw?n.bw/8:1e3*n.loaded/s),f=l[r.level],c=f.realBitrate?Math.max(f.realBitrate,f.bitrate):f.bitrate,g=n.total?n.total:Math.max(n.loaded,Math.round(r.duration*c/8)),p=t.currentTime,y=(g-n.loaded)/d,m=(h.default.bufferInfo(t,p,e.config.maxBufferHole).end-p)/o;if(m<2*r.duration/o&&y>m){var E=void 0,b=void 0;for(b=r.level-1;b>a;b--){var T=l[b].realBitrate?Math.max(l[b].realBitrate,l[b].bitrate):l[b].bitrate;if((E=r.duration*T/(6.4*d))=i;u--){var d=l[u],f=d.details,c=f?f.totalduration/f.fragments.length:t,h=!!f&&f.live,g=void 0;g=u<=e?s*r:o*r;var p=l[u].realBitrate?Math.max(l[u].realBitrate,l[u].bitrate):l[u].bitrate,y=p*c/g;if(v.logger.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+u+"/"+Math.round(g)+"/"+p+"/"+c+"/"+n+"/"+y),g>p&&(!y||h||y=0)return c;v.logger.trace("rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering");var g=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay,p=i.abrBandWidthFactor,y=i.abrBandWidthUpFactor;if(0===f){var m=this.bitrateTestDelay;if(m){g=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-m,v.logger.trace("bitrate test took "+Math.round(1e3*m)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*g)+" ms"),p=y=1}}return c=this._findBestLevel(s,o,d,a,t,f+g,p,y,r),Math.max(c,0)}}]),t}(f.default);r.default=m},{33:33,34:34,35:35,37:37,51:51,53:53}],6:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;r0&&e===-1?(_.logger.log("audio:override startPosition with lastCurrentTime @"+t.toFixed(3)),this.state=R.IDLE):(this.lastCurrentTime=this.startPosition?this.startPosition:e,this.state=R.STARTING),this.nextLoadPosition=this.startPosition=this.lastCurrentTime,this.tick()}else this.startPosition=e,this.state=R.STOPPED}},{key:"stopLoad",value:function(){var e=this.fragCurrent;e&&(e.loader&&e.loader.abort(),this.fragCurrent=null),this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=R.STOPPED}},{key:"tick",value:function(){1===++this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(this.tick,1),this.ticks=0)}},{key:"doTick",value:function(){var e,t,r,i=this.hls,a=i.config;switch(this.state){case R.ERROR:case R.PAUSED:case R.BUFFER_FLUSHING:break;case R.STARTING:this.state=R.WAITING_TRACK,this.loadedmetadata=!1;break;case R.IDLE:var n=this.tracks;if(!n)break;if(!this.media&&(this.startFragRequested||!a.startFragPrefetch))break;e=this.loadedmetadata?this.media.currentTime:this.nextLoadPosition;var s=this.mediaBuffer?this.mediaBuffer:this.media,o=f.default.bufferInfo(s,e,a.maxBufferHole),l=o.len,d=o.end,c=this.fragPrevious,h=a.maxMaxBufferLength,g=this.audioSwitch,p=this.trackId;if((lE||o.nextStart))return;_.logger.log("alt audio track ahead of main track, seek to start of alt audio track"),this.media.currentTime=E+.05}if(r.initSegment&&!r.initSegment.data)T=r.initSegment;else if(d<=E){if(T=y[0],r.live&&T.loadIdx&&T.loadIdx===this.fragLoadIdx){var A=o.nextStart?o.nextStart:E;return _.logger.log("no alt audio available @currentTime:"+this.media.currentTime+", seeking @"+(A+.05)),void(this.media.currentTime=A+.05)}}else{var S=void 0,L=a.maxFragLookUpTolerance,w=c?y[c.sn-y[0].sn+1]:void 0,D=function(e){var t=Math.min(L,e.duration);return e.start+e.duration-t<=d?1:e.start-t>d&&e.start?-1:0};db-L&&(L=0),S=w&&!D(w)?w:u.default.search(y,D)):S=y[m-1],S&&(T=S,E=S.start,c&&T.level===c.level&&T.sn===c.sn&&(T.snO&&Math.abs(this.fragLoadIdx-T.loadIdx)=P||C)&&(_.logger.log("audioStreamController: retryDate reached, switch back to IDLE state"),this.state=R.IDLE);break;case R.WAITING_INIT_PTS:case R.STOPPED:case R.FRAG_LOADING:case R.PARSING:case R.PARSED:case R.ENDED:}}},{key:"onMediaAttached",value:function(e){var t=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),t.addEventListener("seeking",this.onvseeking),t.addEventListener("ended",this.onvended);var r=this.config;this.tracks&&r.autoStartLoad&&this.startLoad(r.startPosition)}},{key:"onMediaDetaching",value:function(){var e=this.media;e&&e.ended&&(_.logger.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0);var t=this.tracks;t&&t.forEach(function(e){e.details&&e.details.fragments.forEach(function(e){e.loadCounter=void 0})}),e&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvseeked=this.onvended=null),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.stopLoad()}},{key:"onMediaSeeking",value:function(){this.state===R.ENDED&&(this.state=R.IDLE),this.media&&(this.lastCurrentTime=this.media.currentTime),void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold),this.tick()}},{key:"onMediaEnded",value:function(){this.startPosition=this.lastCurrentTime=0}},{key:"onAudioTracksUpdated",value:function(e){_.logger.log("audio tracks updated"),this.tracks=e.audioTracks}},{key:"onAudioTrackSwitching",value:function(e){var t=!!e.url;this.trackId=e.id,this.state=R.IDLE,this.fragCurrent=null,this.state=R.PAUSED,this.waitingFragment=null,t?this.timer||(this.timer=setInterval(this.ontick,100)):this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),t&&(this.audioSwitch=!0,this.state=R.IDLE,void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold)),this.tick()}},{key:"onAudioTrackLoaded",value:function(e){var t=e.details,r=e.id,i=this.tracks[r],a=t.totalduration,n=0;if(_.logger.log("track "+r+" loaded ["+t.startSN+","+t.endSN+"],duration:"+a),t.live){var s=i.details;s&&t.fragments.length>0?(E.default.mergeDetails(s,t),n=t.fragments[0].start,t.PTSKnown?_.logger.log("live audio playlist sliding:"+n.toFixed(3)):_.logger.log("live audio playlist - outdated PTS, unknown sliding")):(t.PTSKnown=!1,_.logger.log("live audio playlist - first load, unknown sliding"))}else t.PTSKnown=!1;if(i.details=t,!this.startFragRequested){if(this.startPosition===-1){var o=t.startTimeOffset;isNaN(o)?this.startPosition=0:(_.logger.log("start time offset found in playlist, adjust startPosition to "+o),this.startPosition=o)}this.nextLoadPosition=this.startPosition}this.state===R.WAITING_TRACK&&(this.state=R.IDLE),this.tick()}},{key:"onKeyLoaded",value:function(){this.state===R.KEY_LOADING&&(this.state=R.IDLE,this.tick())}},{key:"onFragLoaded",value:function(e){var t=this.fragCurrent,r=e.frag;if(this.state===R.FRAG_LOADING&&t&&"audio"===r.type&&r.level===t.level&&r.sn===t.sn){var i=this.tracks[this.trackId],a=i.details,n=a.totalduration,s=t.level,o=t.sn,l=t.cc,u=this.config.defaultAudioCodec||i.audioCodec||"mp4a.40.2",d=this.stats=e.stats;if("initSegment"===o)this.state=R.IDLE,d.tparsed=d.tbuffered=performance.now(),a.initSegment.data=e.payload,this.hls.trigger(v.default.FRAG_BUFFERED,{stats:d,frag:t,id:"audio"}),this.tick();else{this.state=R.PARSING,this.appended=!1,this.demuxer||(this.demuxer=new h.default(this.hls,"audio"));var f=this.initPTS[l],c=a.initSegment?a.initSegment.data:[];if(a.initSegment||void 0!==f){this.pendingBuffering=!0,_.logger.log("Demuxing "+o+" of ["+a.startSN+" ,"+a.endSN+"],track "+s);this.demuxer.push(e.payload,c,u,null,t,n,!1,f)}else _.logger.log("unknown video PTS for continuity counter "+l+", waiting for video PTS before demuxing audio frag "+o+" of ["+a.startSN+" ,"+a.endSN+"],track "+s),this.waitingFragment=e,this.state=R.WAITING_INIT_PTS}}this.fragLoadError=0}},{key:"onFragParsingInitSegment",value:function(e){var t=this.fragCurrent,r=e.frag;if(t&&"audio"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===R.PARSING){var i=e.tracks,a=void 0;if(i.video&&delete i.video,a=i.audio){a.levelCodec="mp4a.40.2",a.id=e.id,this.hls.trigger(v.default.BUFFER_CODECS,i),_.logger.log("audio track:audio,container:"+a.container+",codecs[level/parsed]=["+a.levelCodec+"/"+a.codec+"]");var n=a.initSegment;if(n){var s={type:"audio",data:n,parent:"audio",content:"initSegment"};this.audioSwitch?this.pendingData=[s]:(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(v.default.BUFFER_APPENDING,s))}this.tick()}}}},{key:"onFragParsingData",value:function(e){var t=this,r=this.fragCurrent,i=e.frag;if(r&&"audio"===e.id&&"audio"===e.type&&i.sn===r.sn&&i.level===r.level&&this.state===R.PARSING){var a=this.trackId,n=this.tracks[a],s=this.hls;isNaN(e.endPTS)&&(e.endPTS=e.startPTS+r.duration,e.endDTS=e.startDTS+r.duration),_.logger.log("parsed "+e.type+",PTS:["+e.startPTS.toFixed(3)+","+e.endPTS.toFixed(3)+"],DTS:["+e.startDTS.toFixed(3)+"/"+e.endDTS.toFixed(3)+"],nb:"+e.nb),E.default.updateFragPTSDTS(n.details,r,e.startPTS,e.endPTS);var o=this.audioSwitch,l=this.media,u=!1;if(o&&l)if(l.readyState){var d=l.currentTime;_.logger.log("switching audio track : currentTime:"+d),d>=e.startPTS&&(_.logger.log("switching audio track : flushing all audio"),this.state=R.BUFFER_FLUSHING,s.trigger(v.default.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),u=!0,this.audioSwitch=!1,s.trigger(v.default.AUDIO_TRACK_SWITCHED,{id:a}))}else this.audioSwitch=!1,s.trigger(v.default.AUDIO_TRACK_SWITCHED,{id:a});var f=this.pendingData;this.audioSwitch||([e.data1,e.data2].forEach(function(t){t&&t.length&&f.push({type:e.type,data:t,parent:"audio",content:"data"})}),!u&&f.length&&(f.forEach(function(e){t.state===R.PARSING&&(t.pendingBuffering=!0,t.hls.trigger(v.default.BUFFER_APPENDING,e))}),this.pendingData=[],this.appended=!0)),this.tick()}}},{key:"onFragParsed",value:function(e){var t=this.fragCurrent,r=e.frag;t&&"audio"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===R.PARSING&&(this.stats.tparsed=performance.now(),this.state=R.PARSED,this._checkAppendedParsed())}},{key:"onBufferCreated",value:function(e){var t=e.tracks.audio;t&&(this.mediaBuffer=t.buffer,this.loadedmetadata=!0)}},{key:"onBufferAppended",value:function(e){if("audio"===e.parent){var t=this.state;t!==R.PARSING&&t!==R.PARSED||(this.pendingBuffering=e.pending>0,this._checkAppendedParsed())}}},{key:"_checkAppendedParsed",value:function(){if(!(this.state!==R.PARSED||this.appended&&this.pendingBuffering)){var e=this.fragCurrent,t=this.stats,r=this.hls;if(e){this.fragPrevious=e,t.tbuffered=performance.now(),r.trigger(v.default.FRAG_BUFFERED,{stats:t,frag:e,id:"audio"});var i=this.mediaBuffer?this.mediaBuffer:this.media;_.logger.log("audio buffered : "+T.default.toString(i.buffered)),this.audioSwitch&&this.appended&&(this.audioSwitch=!1,r.trigger(v.default.AUDIO_TRACK_SWITCHED,{id:this.trackId})),this.state=R.IDLE}this.tick()}}},{key:"onError",value:function(e){var t=e.frag;if(!t||"audio"===t.type)switch(e.details){case k.ErrorDetails.FRAG_LOAD_ERROR:case k.ErrorDetails.FRAG_LOAD_TIMEOUT:if(!e.fatal){var r=this.fragLoadError;r?r++:r=1;var i=this.config;if(r<=i.fragLoadingMaxRetry){this.fragLoadError=r,t.loadCounter=0;var a=Math.min(Math.pow(2,r-1)*i.fragLoadingRetryDelay,i.fragLoadingMaxRetryTimeout);_.logger.warn("audioStreamController: frag loading failed, retry in "+a+" ms"),this.retryDate=performance.now()+a,this.state=R.FRAG_LOADING_WAITING_RETRY}else _.logger.error("audioStreamController: "+e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.state=R.ERROR}break;case k.ErrorDetails.FRAG_LOOP_LOADING_ERROR:case k.ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case k.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:case k.ErrorDetails.KEY_LOAD_ERROR:case k.ErrorDetails.KEY_LOAD_TIMEOUT:this.state!==R.ERROR&&(this.state=e.fatal?R.ERROR:R.IDLE,_.logger.warn("audioStreamController: "+e.details+" while loading frag,switch to "+this.state+" state ..."));break;case k.ErrorDetails.BUFFER_FULL_ERROR:if("audio"===e.parent&&(this.state===R.PARSING||this.state===R.PARSED)){var n=this.mediaBuffer,s=this.media.currentTime;if(n&&f.default.isBuffered(n,s)&&f.default.isBuffered(n,s+.5)){var o=this.config;o.maxMaxBufferLength>=o.maxBufferLength&&(o.maxMaxBufferLength/=2,_.logger.warn("audio:reduce max buffer length to "+o.maxMaxBufferLength+"s"),this.fragLoadIdx+=2*o.fragLoadingLoopThreshold),this.state=R.IDLE}else _.logger.warn("buffer full error also media.currentTime is not buffered, flush audio buffer"),this.fragCurrent=null,this.state=R.BUFFER_FLUSHING,this.hls.trigger(v.default.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"})}}}},{key:"onBufferFlushed",value:function(){var e=this,t=this.pendingData;t&&t.length?(_.logger.log("appending pending audio data on Buffer Flushed"),t.forEach(function(t){e.hls.trigger(v.default.BUFFER_APPENDING,t)}),this.appended=!0,this.pendingData=[],this.state=R.PARSED):(this.state=R.IDLE,this.fragPrevious=null,this.tick())}},{key:"state",set:function(e){if(this.state!==e){var t=this.state;this._state=e,_.logger.log("audio stream:"+t+"->"+e)}},get:function(){return this._state}}]),t}(y.default);r.default=A},{25:25,33:33,34:34,35:35,37:37,38:38,48:48,53:53,54:54}],7:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;r1&&setTimeout(this.tick,1),this.ticks=0)}},{key:"doTick",value:function(){this.updateTrack(this.trackId)}},{key:"onManifestLoading",value:function(){this.tracks=[],this.trackId=-1}},{key:"onManifestLoaded",value:function(e){var t=this,r=e.audioTracks||[],i=!1;this.tracks=r,this.hls.trigger(u.default.AUDIO_TRACKS_UPDATED,{audioTracks:r});var a=0;r.forEach(function(e){if(e.default)return t.audioTrack=a,void(i=!0);a++}),i===!1&&r.length&&(c.logger.log("no default audio track defined, use first audio track as default"),this.audioTrack=0)}},{key:"onAudioTrackLoaded",value:function(e){e.id=0&&e=0&&e.1){var a=i.updating;try{i.abort()}catch(e){a=!0,c.logger.warn("can not abort audio buffer: "+e)}a?this.audioTimestampOffset=e.start:(c.logger.warn("change mpeg audio timestamp offset from "+i.timestampOffset+" to "+e.start),i.timestampOffset=e.start)}}}},{key:"onManifestParsed",value:function(e){var t=e.audio,r=e.video,i=0;e.altAudio&&(t||r)&&(i=(t?1:0)+(r?1:0),c.logger.log(i+" sourceBuffer(s) expected")),this.sourceBufferNb=i}},{key:"onMediaAttaching",value:function(e){var t=this.media=e.media;if(t){var r=this.mediaSource=new MediaSource;this.onmso=this.onMediaSourceOpen.bind(this),this.onmse=this.onMediaSourceEnded.bind(this),this.onmsc=this.onMediaSourceClose.bind(this),r.addEventListener("sourceopen",this.onmso),r.addEventListener("sourceended",this.onmse),r.addEventListener("sourceclose",this.onmsc),t.src=URL.createObjectURL(r)}}},{key:"onMediaDetaching",value:function(){c.logger.log("media source detaching");var e=this.mediaSource;if(e){if("open"===e.readyState)try{e.endOfStream()}catch(e){c.logger.warn("onMediaDetaching:"+e.message+" while calling endOfStream")}e.removeEventListener("sourceopen",this.onmso),e.removeEventListener("sourceended",this.onmse),e.removeEventListener("sourceclose",this.onmsc),this.media&&(URL.revokeObjectURL(this.media.src),this.media.removeAttribute("src"),this.media.load()),this.mediaSource=null,this.media=null,this.pendingTracks={},this.tracks={},this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0}this.onmso=this.onmse=this.onmsc=null,this.hls.trigger(u.default.MEDIA_DETACHED)}},{key:"onMediaSourceOpen",value:function(){c.logger.log("media source opened"),this.hls.trigger(u.default.MEDIA_ATTACHED,{media:this.media});var e=this.mediaSource;e&&e.removeEventListener("sourceopen",this.onmso),this.checkPendingTracks()}},{key:"checkPendingTracks",value:function(){var e=this.pendingTracks,t=Object.keys(e).length;t&&(this.sourceBufferNb<=t||0===this.sourceBufferNb)&&(this.createSourceBuffers(e),this.pendingTracks={},this.doAppending())}},{key:"onMediaSourceClose",value:function(){c.logger.log("media source closed")}},{key:"onMediaSourceEnded",value:function(){c.logger.log("media source ended")}},{key:"onSBUpdateEnd",value:function(){if(this.audioTimestampOffset){var e=this.sourceBuffer.audio;c.logger.warn("change mpeg audio timestamp offset from "+e.timestampOffset+" to "+this.audioTimestampOffset),e.timestampOffset=this.audioTimestampOffset,delete this.audioTimestampOffset}this._needsFlush&&this.doFlush(),this._needsEos&&this.checkEos(),this.appending=!1;var t=this.parent,r=this.segments.reduce(function(e,r){return r.parent===t?e+1:e},0);this.hls.trigger(u.default.BUFFER_APPENDED,{parent:t,pending:r}),this._needsFlush||this.doAppending(),this.updateMediaElementDuration()}},{key:"onSBUpdateError",value:function(e){c.logger.error("sourceBuffer error:",e),this.hls.trigger(u.default.ERROR,{type:h.ErrorTypes.MEDIA_ERROR,details:h.ErrorDetails.BUFFER_APPENDING_ERROR,fatal:!1})}},{key:"onBufferReset",value:function(){var e=this.sourceBuffer;for(var t in e){var r=e[t];try{this.mediaSource.removeSourceBuffer(r),r.removeEventListener("updateend",this.onsbue),r.removeEventListener("error",this.onsbe)}catch(e){}}this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0}},{key:"onBufferCodecs",value:function(e){if(0===Object.keys(this.sourceBuffer).length){for(var t in e)this.pendingTracks[t]=e[t];var r=this.mediaSource;r&&"open"===r.readyState&&this.checkPendingTracks()}}},{key:"createSourceBuffers",value:function(e){var t=this.sourceBuffer,r=this.mediaSource;for(var i in e)if(!t[i]){var a=e[i],n=a.levelCodec||a.codec,s=a.container+";codecs="+n;c.logger.log("creating sourceBuffer("+s+")");try{var o=t[i]=r.addSourceBuffer(s);o.addEventListener("updateend",this.onsbue),o.addEventListener("error",this.onsbe),this.tracks[i]={codec:n,container:a.container},a.buffer=o}catch(e){c.logger.error("error while trying to add sourceBuffer:"+e.message),this.hls.trigger(u.default.ERROR,{type:h.ErrorTypes.MEDIA_ERROR,details:h.ErrorDetails.BUFFER_ADD_CODEC_ERROR,fatal:!1,err:e,mimeType:s})}}this.hls.trigger(u.default.BUFFER_CREATED,{tracks:e})}},{key:"onBufferAppending",value:function(e){this._needsFlush||(this.segments?this.segments.push(e):this.segments=[e],this.doAppending())}},{key:"onBufferAppendFail",value:function(e){c.logger.error("sourceBuffer error:",e.event),this.hls.trigger(u.default.ERROR,{type:h.ErrorTypes.MEDIA_ERROR,details:h.ErrorDetails.BUFFER_APPENDING_ERROR,fatal:!1})}},{key:"onBufferEos",value:function(e){var t=this.sourceBuffer,r=e.type;for(var i in t)r&&i!==r||t[i].ended||(t[i].ended=!0,c.logger.log(i+" sourceBuffer now EOS"));this.checkEos()}},{key:"checkEos",value:function(){var e=this.sourceBuffer,t=this.mediaSource;if(!t||"open"!==t.readyState)return void(this._needsEos=!1);for(var r in e){var i=e[r];if(!i.ended)return;if(i.updating)return void(this._needsEos=!0)}c.logger.log("all media data available, signal endOfStream() to MediaSource and stop loading fragment");try{t.endOfStream()}catch(e){c.logger.warn("exception while calling mediaSource.endOfStream()")}this._needsEos=!1}},{key:"onBufferFlushing",value:function(e){this.flushRange.push({start:e.startOffset,end:e.endOffset,type:e.type}),this.flushBufferCounter=0,this.doFlush()}},{key:"onLevelUpdated",value:function(e){var t=e.details;0!==t.fragments.length&&(this._levelDuration=t.totalduration+t.fragments[0].start,this.updateMediaElementDuration())}},{key:"updateMediaElementDuration",value:function(){var e=this.media,t=this.mediaSource,r=this.sourceBuffer,i=this._levelDuration;if(null!==i&&e&&t&&r&&0!==e.readyState&&"open"===t.readyState){for(var a in r)if(r[a].updating)return;null===this._msDuration&&(this._msDuration=t.duration);var n=e.duration;(i>this._msDuration&&i>n||n===1/0||isNaN(n))&&(c.logger.log("Updating mediasource duration to "+i.toFixed(3)),this._msDuration=t.duration=i)}}},{key:"doFlush",value:function(){for(;this.flushRange.length;){var e=this.flushRange[0];if(!this.flushBuffer(e.start,e.end,e.type))return void(this._needsFlush=!0);this.flushRange.shift(),this.flushBufferCounter=0}if(0===this.flushRange.length){this._needsFlush=!1;var t=0,r=this.sourceBuffer;try{for(var i in r)t+=r[i].buffered.length}catch(e){c.logger.error("error while accessing sourceBuffer.buffered")}this.appended=t,this.hls.trigger(u.default.BUFFER_FLUSHED)}}},{key:"doAppending",value:function(){var e=this.hls,t=this.sourceBuffer,r=this.segments;if(Object.keys(t).length){if(this.media.error)return this.segments=[],void c.logger.error("trying to append although a media error occured, flush segment and abort");if(this.appending)return;if(r&&r.length){var i=r.shift();try{var a=i.type,n=t[a];n?n.updating?r.unshift(i):(n.ended=!1,this.parent=i.parent,n.appendBuffer(i.data),this.appendError=0,this.appended++,this.appending=!0):this.onSBUpdateEnd()}catch(t){c.logger.error("error while trying to append buffer:"+t.message),r.unshift(i);var s={type:h.ErrorTypes.MEDIA_ERROR,parent:i.parent};if(22===t.code)return this.segments=[],s.details=h.ErrorDetails.BUFFER_FULL_ERROR,s.fatal=!1,void e.trigger(u.default.ERROR,s);if(this.appendError?this.appendError++:this.appendError=1,s.details=h.ErrorDetails.BUFFER_APPEND_ERROR,this.appendError>e.config.appendErrorMaxRetry)return c.logger.log("fail "+e.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),r=[],s.fatal=!0,void e.trigger(u.default.ERROR,s);s.fatal=!1,e.trigger(u.default.ERROR,s)}}}}},{key:"flushBuffer",value:function(e,t,r){var i,a,n,s,o,l,u=this.sourceBuffer;if(Object.keys(u).length){if(c.logger.log("flushBuffer,pos/start/end: "+this.media.currentTime.toFixed(3)+"/"+e+"/"+t),this.flushBufferCounter.5)return this.flushBufferCounter++,c.logger.log("flush "+d+" ["+o+","+l+"], of ["+n+","+s+"], pos:"+this.media.currentTime),i.remove(o,l),!1}catch(e){c.logger.warn("exception while accessing sourcebuffer, it might have been removed from MediaSource")}}}else c.logger.warn("abort flushing too many retries");c.logger.log("buffer flushed")}return!0}}]),t}(f.default);r.default=g},{33:33,34:34,35:35,53:53}],9:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;rthis.autoLevelCapping&&t.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}},{key:"getMaxLevel",value:function(e){var t=0,r=void 0,i=void 0,a=this.mediaWidth,n=this.mediaHeight,s=0,o=0;for(r=0;r<=e&&(i=this.levels[r],!this.isLevelRestricted(r))&&(t=r,s=i.width,o=i.height,!(a<=s||n<=o));r++);return t}},{key:"isLevelRestricted",value:function(e){return!(!this.restrictedLevels||this.restrictedLevels.indexOf(e)===-1)}},{key:"contentScaleFactor",get:function(){var e=1;try{e=window.devicePixelRatio}catch(e){}return e}},{key:"mediaWidth",get:function(){var e=void 0,t=this.media;return t&&(e=t.width||t.clientWidth||t.offsetWidth,e*=this.contentScaleFactor),e}},{key:"mediaHeight",get:function(){var e=void 0,t=this.media;return t&&(e=t.height||t.clientHeight||t.offsetHeight,e*=this.contentScaleFactor),e}}]),t}(f.default);r.default=c},{34:34,35:35}],10:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;r0&&n>l.config.fpsDroppedMonitoringThreshold*s){var d=l.currentLevel;c.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=d)&&(d-=1,l.trigger(u.default.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:l.currentLevel}),l.autoLevelCapping=d,l.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}},{key:"checkFPSInterval",value:function(){var e=this.video;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}]),t}(f.default);r.default=h},{34:34,35:35,53:53}],11:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;r>4){case 0:return i;case 1:case 2:case 3:case 4:case 5:case 6:case 7:i+=String.fromCharCode(s);break;case 12:case 13:t=e[a++],i+=String.fromCharCode((31&s)<<6|63&t);break;case 14:t=e[a++],r=e[a++],i+=String.fromCharCode((15&s)<<12|(63&t)<<6|(63&r)<<0)}}return i}}]),t}(f.default);r.default=c},{34:34,35:35}],12:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;r0})}else o.trigger(u.default.ERROR,{type:h.ErrorTypes.MEDIA_ERROR,details:h.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:o.url,reason:"no level with compatible codecs found in manifest"})}},{key:"setLevelInternal",value:function(e){var t=this._levels,r=this.hls;if(e>=0&&e1&&a.loadErrore&&(this._level===e&&void 0!==t[e].details||this.setLevelInternal(e))}},{key:"manualLevel",get:function(){return this._manualLevel},set:function(e){this._manualLevel=e,void 0===this._startLevel&&(this._startLevel=e),e!==-1&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this._firstLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"nextLoadLevel",get:function(){return this._manualLevel!==-1?this._manualLevel:this.hls.nextAutoLevel},set:function(e){this.level=e,this._manualLevel===-1&&(this.hls.nextAutoLevel=e)}}]),t}(f.default);r.default=p},{33:33,34:34,35:35,37:37,53:53}],13:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;r0&&e===-1&&(_.logger.log("override startPosition with lastCurrentTime @"+t.toFixed(3)),e=t),this.state=R.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this.forceStartLoad=!0,this.state=R.STOPPED}},{key:"stopLoad",value:function(){var e=this.fragCurrent;e&&(e.loader&&e.loader.abort(),this.fragCurrent=null),this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=R.STOPPED,this.forceStartLoad=!1}},{key:"tick",value:function(){1===++this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(this.tick,1),this.ticks=0)}},{key:"doTick",value:function(){switch(this.state){case R.ERROR:break;case R.BUFFER_FLUSHING:this.fragLoadError=0;break;case R.IDLE:this._doTickIdle();break;case R.WAITING_LEVEL:var e=this.levels[this.level];e&&e.details&&(this.state=R.IDLE);break;case R.FRAG_LOADING_WAITING_RETRY:var t=performance.now(),r=this.retryDate;(!r||t>=r||this.media&&this.media.seeking)&&(_.logger.log("mediaController: retryDate reached, switch back to IDLE state"),this.state=R.IDLE);break;case R.ERROR:case R.STOPPED:case R.FRAG_LOADING:case R.PARSING:case R.PARSED:case R.ENDED:}this._checkBuffer(),this._checkFragmentChanged()}},{key:"_doTickIdle",value:function(){ +var e=this.hls,t=e.config,r=this.media;if(void 0===this.levelLastLoaded||r||!this.startFragRequested&&t.startFragPrefetch){var i=void 0;i=this.loadedmetadata?r.currentTime:this.nextLoadPosition;var a=e.nextLoadLevel,n=this.levels[a],s=n.bitrate,o=void 0;o=s?Math.max(8*t.maxBufferSize/s,t.maxBufferLength):t.maxBufferLength,o=Math.min(o,t.maxMaxBufferLength);var l=f.default.bufferInfo(this.mediaBuffer?this.mediaBuffer:r,i,t.maxBufferHole),u=l.len;if(!(u>=o)){_.logger.trace("buffer length of "+u.toFixed(3)+" is below max of "+o.toFixed(3)+". checking for more payload ..."),this.level=e.nextLoadLevel=a;var d=n.details;if(void 0===d||d.live&&this.levelLastLoaded!==a)return void(this.state=R.WAITING_LEVEL);var c=this.fragPrevious;if(!d.live&&c&&c.sn===d.endSN){if(Math.min(r.duration,c.start+c.duration)-Math.max(l.end,c.start)<=Math.max(.2,c.duration/2)){var h={};return this.altAudio&&(h.type="video"),this.hls.trigger(v.default.BUFFER_EOS,h),void(this.state=R.ENDED)}}this._fetchPayloadOrEos(i,l,d)}}}},{key:"_fetchPayloadOrEos",value:function(e,t,r){var i=this.fragPrevious,a=this.level,n=r.fragments,s=n.length;if(0!==s){var o=n[0].start,l=n[s-1].start+n[s-1].duration,u=t.end,d=void 0;if(r.initSegment&&!r.initSegment.data)d=r.initSegment;else if(r.live){var f=this.config.initialLiveManifestSize;if(sf&&(l.currentTime=f)}if(e.PTSKnown&&t>i&&l&&l.readyState)return null;if(this.startFragRequested&&!e.PTSKnown){if(a){var c=a.sn+1;c>=e.startSN&&c<=e.endSN&&(u=n[c-e.startSN],_.logger.log("live playlist, switching playlist, load frag with next SN: "+u.sn))}u||(u=n[Math.min(s-1,Math.round(s/2))],_.logger.log("live playlist, switching playlist, unknown, load middle frag : "+u.sn))}return u}},{key:"_findFragment",value:function(e,t,r,i,a,n,s){var o=this.hls.config,l=void 0,d=void 0,f=o.maxFragLookUpTolerance,c=t?i[t.sn-i[0].sn+1]:void 0,h=function(e){var t=Math.min(f,e.duration);return e.start+e.duration-t<=a?1:e.start-t>a&&e.start?-1:0};if(an-f&&(f=0),d=c&&!h(c)?c:u.default.search(i,h)):d=i[r-1],d){l=d;var g=l.sn-s.startSN,v=t&&l.level===t.level,p=i[g-1],y=i[g+1];if(v&&l.sn===t.sn)if(l.sno.maxBufferHole&&t.dropped&&g?(l=p,_.logger.warn("SN just loaded, with large PTS gap between audio and video, maybe frag is not starting with a keyframe ? load previous one to try to overcome this"),t.loadCounter--):(l=y,_.logger.log("SN just loaded, load next one: "+l.sn))}else l=null;else l.dropped&&!v&&(y&&y.backtracked?(_.logger.warn("Already backtracked from fragment "+(g+1)+", will not backtrack to fragment "+g+". Loading fragment "+(g+1)),l=y):(_.logger.warn("Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe"),l.dropped=0,p?(p.loadCounter&&p.loadCounter--,l=p):l=null))}return l}},{key:"_loadFragmentOrKey",value:function(e,t,r,i,a){var n=this.hls,s=n.config;if(!e.decryptdata||null==e.decryptdata.uri||null!=e.decryptdata.key){if(_.logger.log("Loading "+e.sn+" of ["+r.startSN+" ,"+r.endSN+"],level "+t+", currentTime:"+i.toFixed(3)+",bufferEnd:"+a.toFixed(3)),void 0!==this.fragLoadIdx?this.fragLoadIdx++:this.fragLoadIdx=0,e.loadCounter){e.loadCounter++;var o=s.fragLoadingLoopThreshold;if(e.loadCounter>o&&Math.abs(this.fragLoadIdx-e.loadIdx)t.endPTS?1:0})}},{key:"followingBufferedFrag",value:function(e){return e?this.getBufferedFrag(e.endPTS+.5):null}},{key:"_checkFragmentChanged",value:function(){var e,t,r=this.media;if(r&&r.readyState&&r.seeking===!1&&(t=r.currentTime,t>r.playbackRate*this.lastCurrentTime&&(this.lastCurrentTime=t),f.default.isBuffered(r,t)?e=this.getBufferedFrag(t):f.default.isBuffered(r,t+.1)&&(e=this.getBufferedFrag(t+.1)),e)){var i=e;if(i!==this.fragPlaying){this.hls.trigger(v.default.FRAG_CHANGED,{frag:i});var a=i.level;this.fragPlaying&&this.fragPlaying.level===a||this.hls.trigger(v.default.LEVEL_SWITCHED,{level:a}),this.fragPlaying=i}}}},{key:"immediateLevelSwitch",value:function(){if(_.logger.log("immediateLevelSwitch"),!this.immediateSwitch){this.immediateSwitch=!0;var e=this.media,t=void 0;e?(t=e.paused,e.pause()):t=!0,this.previouslyPaused=t}var r=this.fragCurrent;r&&r.loader&&r.loader.abort(),this.fragCurrent=null,this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}},{key:"immediateLevelSwitchEnd",value:function(){var e=this.media;e&&e.buffered.length&&(this.immediateSwitch=!1,f.default.isBuffered(e,e.currentTime)&&(e.currentTime-=1e-4),this.previouslyPaused||e.play())}},{key:"nextLevelSwitch",value:function(){var e=this.media;if(e&&e.readyState){var t=void 0,r=void 0,i=void 0;if(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold,r=this.getBufferedFrag(e.currentTime),r&&r.startPTS>1&&this.flushMainBuffer(0,r.startPTS-1),e.paused)t=0;else{var a=this.hls.nextLoadLevel,n=this.levels[a],s=this.fragLastKbps;t=s&&this.fragCurrent?this.fragCurrent.duration*n.bitrate/(1e3*s)+1:0}if((i=this.getBufferedFrag(e.currentTime+t))&&(i=this.followingBufferedFrag(i))){var o=this.fragCurrent;o&&o.loader&&o.loader.abort(),this.fragCurrent=null,this.flushMainBuffer(i.startPTS,Number.POSITIVE_INFINITY)}}}},{key:"flushMainBuffer",value:function(e,t){this.state=R.BUFFER_FLUSHING;var r={startOffset:e,endOffset:t};this.altAudio&&(r.type="video"),this.hls.trigger(v.default.BUFFER_FLUSHING,r)}},{key:"onMediaAttached",value:function(e){var t=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),this.onvended=this.onMediaEnded.bind(this),t.addEventListener("seeking",this.onvseeking),t.addEventListener("seeked",this.onvseeked),t.addEventListener("ended",this.onvended);var r=this.config;this.levels&&r.autoStartLoad&&this.hls.startLoad(r.startPosition)}},{key:"onMediaDetaching",value:function(){var e=this.media;e&&e.ended&&(_.logger.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0);var t=this.levels;t&&t.forEach(function(e){e.details&&e.details.fragments.forEach(function(e){e.loadCounter=void 0,e.backtracked=void 0})}),e&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("seeked",this.onvseeked),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvseeked=this.onvended=null),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.stopLoad()}},{key:"onMediaSeeking",value:function(){var e=this.media,t=e?e.currentTime:void 0,r=this.config;_.logger.log("media seeking to "+t.toFixed(3));var i=this.mediaBuffer?this.mediaBuffer:e,a=f.default.bufferInfo(i,t,this.config.maxBufferHole);if(this.state===R.FRAG_LOADING){var n=this.fragCurrent;if(0===a.len&&n){var s=r.maxFragLookUpTolerance,o=n.start-s,l=n.start+n.duration+s;tl?(n.loader&&(_.logger.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),n.loader.abort()),this.fragCurrent=null,this.fragPrevious=null,this.state=R.IDLE):_.logger.log("seeking outside of buffer but within currently loaded fragment range")}}else this.state===R.ENDED&&(0===a.len&&(this.fragPrevious=0),this.state=R.IDLE);e&&(this.lastCurrentTime=t),this.state!==R.FRAG_LOADING&&void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*r.fragLoadingLoopThreshold),this.loadedmetadata||(this.nextLoadPosition=this.startPosition=t),this.tick()}},{key:"onMediaSeeked",value:function(){_.logger.log("media seeked to "+this.media.currentTime.toFixed(3)),this.tick()}},{key:"onMediaEnded",value:function(){_.logger.log("media ended"),this.startPosition=this.lastCurrentTime=0}},{key:"onManifestLoading",value:function(){_.logger.log("trigger BUFFER_RESET"),this.hls.trigger(v.default.BUFFER_RESET),this._bufferedFrags=[],this.stalled=!1,this.startPosition=this.lastCurrentTime=0}},{key:"onManifestParsed",value:function(e){var t,r=!1,i=!1;e.levels.forEach(function(e){(t=e.audioCodec)&&(t.indexOf("mp4a.40.2")!==-1&&(r=!0),t.indexOf("mp4a.40.5")!==-1&&(i=!0))}),this.audioCodecSwitch=r&&i,this.audioCodecSwitch&&_.logger.log("both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startLevelLoaded=!1,this.startFragRequested=!1;var a=this.config;(a.autoStartLoad||this.forceStartLoad)&&this.hls.startLoad(a.startPosition)}},{key:"onLevelLoaded",value:function(e){var t=e.details,r=e.level,i=this.levels[r],a=t.totalduration,n=0;if(_.logger.log("level "+r+" loaded ["+t.startSN+","+t.endSN+"],duration:"+a),this.levelLastLoaded=r,t.live){var s=i.details;s&&t.fragments.length>0?(E.default.mergeDetails(s,t),n=t.fragments[0].start,this.liveSyncPosition=this.computeLivePosition(n,s),t.PTSKnown?_.logger.log("live playlist sliding:"+n.toFixed(3)):_.logger.log("live playlist - outdated PTS, unknown sliding")):(t.PTSKnown=!1,_.logger.log("live playlist - first load, unknown sliding"))}else t.PTSKnown=!1;if(i.details=t,this.hls.trigger(v.default.LEVEL_UPDATED,{details:t,level:r}),this.startFragRequested===!1){if(this.startPosition===-1||this.lastCurrentTime===-1){var o=t.startTimeOffset;isNaN(o)?t.live?(this.startPosition=this.computeLivePosition(n,t),_.logger.log("configure startPosition to "+this.startPosition)):this.startPosition=0:(o<0&&(_.logger.log("negative start time offset "+o+", count from end of last fragment"),o=n+a+o),_.logger.log("start time offset found in playlist, adjust startPosition to "+o),this.startPosition=o),this.lastCurrentTime=this.startPosition}this.nextLoadPosition=this.startPosition}this.state===R.WAITING_LEVEL&&(this.state=R.IDLE),this.tick()}},{key:"onKeyLoaded",value:function(){this.state===R.KEY_LOADING&&(this.state=R.IDLE,this.tick())}},{key:"onFragLoaded",value:function(e){var t=this.fragCurrent,r=e.frag;if(this.state===R.FRAG_LOADING&&t&&"main"===r.type&&r.level===t.level&&r.sn===t.sn){var i=e.stats,a=this.levels[t.level],n=a.details;if(_.logger.log("Loaded "+t.sn+" of ["+n.startSN+" ,"+n.endSN+"],level "+t.level),this.bitrateTest=!1,this.stats=i,r.bitrateTest===!0&&this.hls.nextLoadLevel)this.state=R.IDLE,this.startFragRequested=!1,i.tparsed=i.tbuffered=performance.now(),this.hls.trigger(v.default.FRAG_BUFFERED,{stats:i,frag:t,id:"main"}),this.tick();else if("initSegment"===r.sn)this.state=R.IDLE,i.tparsed=i.tbuffered=performance.now(),n.initSegment.data=e.payload,this.hls.trigger(v.default.FRAG_BUFFERED,{stats:i,frag:t,id:"main"}),this.tick();else{this.state=R.PARSING;var s=n.totalduration,o=t.level,l=t.sn,u=this.config.defaultAudioCodec||a.audioCodec;this.audioCodecSwap&&(_.logger.log("swapping playlist audio codec"),void 0===u&&(u=this.lastAudioCodec),u&&(u=u.indexOf("mp4a.40.5")!==-1?"mp4a.40.2":"mp4a.40.5")),this.pendingBuffering=!0,this.appended=!1,_.logger.log("Parsing "+l+" of ["+n.startSN+" ,"+n.endSN+"],level "+o+", cc "+t.cc);var d=this.demuxer;d||(d=this.demuxer=new h.default(this.hls,"main"));var f=this.media,c=f&&f.seeking,g=!c&&(n.PTSKnown||!n.live),p=n.initSegment?n.initSegment.data:[];d.push(e.payload,p,u,a.videoCodec,t,s,g,void 0)}}this.fragLoadError=0}},{key:"onFragParsingInitSegment",value:function(e){var t=this.fragCurrent,r=e.frag;if(t&&"main"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===R.PARSING){var i,a,n=e.tracks;if(n.audio&&this.altAudio&&delete n.audio,a=n.audio){var s=this.levels[this.level].audioCodec,o=navigator.userAgent.toLowerCase();s&&this.audioCodecSwap&&(_.logger.log("swapping playlist audio codec"),s=s.indexOf("mp4a.40.5")!==-1?"mp4a.40.2":"mp4a.40.5"),this.audioCodecSwitch&&1!==a.metadata.channelCount&&o.indexOf("firefox")===-1&&(s="mp4a.40.5"),o.indexOf("android")!==-1&&"audio/mpeg"!==a.container&&(s="mp4a.40.2",_.logger.log("Android: force audio codec to "+s)),a.levelCodec=s,a.id=e.id}a=n.video,a&&(a.levelCodec=this.levels[this.level].videoCodec,a.id=e.id),this.hls.trigger(v.default.BUFFER_CODECS,n);for(i in n){a=n[i],_.logger.log("main track:"+i+",container:"+a.container+",codecs[level/parsed]=["+a.levelCodec+"/"+a.codec+"]");var l=a.initSegment;l&&(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(v.default.BUFFER_APPENDING,{type:i,data:l,parent:"main",content:"initSegment"}))}this.tick()}}},{key:"onFragParsingData",value:function(e){var t=this,r=this.fragCurrent,i=e.frag;if(r&&"main"===e.id&&i.sn===r.sn&&i.level===r.level&&("audio"!==e.type||!this.altAudio)&&this.state===R.PARSING){var a=this.levels[this.level],n=r;if(isNaN(e.endPTS)&&(e.endPTS=e.startPTS+r.duration,e.endDTS=e.startDTS+r.duration),_.logger.log("Parsed "+e.type+",PTS:["+e.startPTS.toFixed(3)+","+e.endPTS.toFixed(3)+"],DTS:["+e.startDTS.toFixed(3)+"/"+e.endDTS.toFixed(3)+"],nb:"+e.nb+",dropped:"+(e.dropped||0)),"video"===e.type)if(n.dropped=e.dropped,n.dropped){if(!n.backtracked)return n.backtracked=!0,this.nextLoadPosition=e.startPTS,this.state=R.IDLE,void this.tick();_.logger.warn("Already backtracked on this fragment, appending with the gap")}else n.backtracked=!1;var s=E.default.updateFragPTSDTS(a.details,n,e.startPTS,e.endPTS,e.startDTS,e.endDTS),o=this.hls;o.trigger(v.default.LEVEL_PTS_UPDATED,{details:a.details,level:this.level,drift:s,type:e.type,start:e.startPTS,end:e.endPTS}),[e.data1,e.data2].forEach(function(r){r&&r.length&&t.state===R.PARSING&&(t.appended=!0,t.pendingBuffering=!0,o.trigger(v.default.BUFFER_APPENDING,{type:e.type,data:r,parent:"main",content:"data"}))}),this.tick()}}},{key:"onFragParsed",value:function(e){var t=this.fragCurrent,r=e.frag;t&&"main"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===R.PARSING&&(this.stats.tparsed=performance.now(),this.state=R.PARSED,this._checkAppendedParsed())}},{key:"onAudioTrackSwitching",value:function(e){var t=!!e.url,r=e.id;if(!t){if(this.mediaBuffer!==this.media){_.logger.log("switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var i=this.fragCurrent;i.loader&&(_.logger.log("switching to main audio track, cancel main fragment load"),i.loader.abort()),this.fragCurrent=null,this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=R.IDLE}var a=this.hls;a.trigger(v.default.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),a.trigger(v.default.AUDIO_TRACK_SWITCHED,{id:r}),this.altAudio=!1}}},{key:"onAudioTrackSwitched",value:function(e){var t=e.id,r=!!this.hls.audioTracks[t].url;if(r){var i=this.videoBuffer;i&&this.mediaBuffer!==i&&(_.logger.log("switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r,this.tick()}},{key:"onBufferCreated",value:function(e){var t=e.tracks,r=void 0,i=void 0,a=!1;for(var n in t){var s=t[n];"main"===s.id?(i=n,r=s,"video"===n&&(this.videoBuffer=t[n].buffer)):a=!0}a&&r?(_.logger.log("alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}},{key:"onBufferAppended",value:function(e){if("main"===e.parent){var t=this.state;t!==R.PARSING&&t!==R.PARSED||(this.pendingBuffering=e.pending>0,this._checkAppendedParsed())}}},{key:"_checkAppendedParsed",value:function(){if(!(this.state!==R.PARSED||this.appended&&this.pendingBuffering)){var e=this.fragCurrent;if(e){var t=this.mediaBuffer?this.mediaBuffer:this.media;_.logger.log("main buffered : "+T.default.toString(t.buffered));var r=this._bufferedFrags.filter(function(e){return f.default.isBuffered(t,(e.startPTS+e.endPTS)/2)});r.push(e),this._bufferedFrags=r.sort(function(e,t){return e.startPTS-t.startPTS}),this.fragPrevious=e;var i=this.stats;i.tbuffered=performance.now(),this.fragLastKbps=Math.round(8*i.total/(i.tbuffered-i.tfirst)),this.hls.trigger(v.default.FRAG_BUFFERED,{stats:i,frag:e,id:"main"}),this.state=R.IDLE}this.tick()}}},{key:"onError",value:function(e){var t=e.frag||this.fragCurrent;if(!t||"main"===t.type){var r=this.media,i=r&&f.default.isBuffered(r,r.currentTime)&&f.default.isBuffered(r,r.currentTime+.5);switch(e.details){case k.ErrorDetails.FRAG_LOAD_ERROR:case k.ErrorDetails.FRAG_LOAD_TIMEOUT:case k.ErrorDetails.KEY_LOAD_ERROR:case k.ErrorDetails.KEY_LOAD_TIMEOUT:if(!e.fatal){var a=this.fragLoadError;a?a++:a=1;var n=this.config;if(a<=n.fragLoadingMaxRetry||i||t.autoLevel&&t.level){this.fragLoadError=a,t.loadCounter=0;var s=Math.min(Math.pow(2,a-1)*n.fragLoadingRetryDelay,n.fragLoadingMaxRetryTimeout);_.logger.warn("mediaController: frag loading failed, retry in "+s+" ms"),this.retryDate=performance.now()+s,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.state=R.FRAG_LOADING_WAITING_RETRY}else _.logger.error("mediaController: "+e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.state=R.ERROR}break;case k.ErrorDetails.FRAG_LOOP_LOADING_ERROR:e.fatal||(i?(this._reduceMaxBufferLength(t.duration),this.state=R.IDLE):t.autoLevel&&0!==t.level||(e.fatal=!0,this.state=R.ERROR));break;case k.ErrorDetails.LEVEL_LOAD_ERROR:case k.ErrorDetails.LEVEL_LOAD_TIMEOUT:this.state!==R.ERROR&&(e.fatal?(this.state=R.ERROR,_.logger.warn("streamController: "+e.details+",switch to "+this.state+" state ...")):e.levelRetry||this.state!==R.WAITING_LEVEL||(this.state=R.IDLE));break;case k.ErrorDetails.BUFFER_FULL_ERROR:"main"!==e.parent||this.state!==R.PARSING&&this.state!==R.PARSED||(i?(this._reduceMaxBufferLength(this.config.maxBufferLength),this.state=R.IDLE):(_.logger.warn("buffer full error also media.currentTime is not buffered, flush everything"),this.fragCurrent=null,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)))}}}},{key:"_reduceMaxBufferLength",value:function(e){var t=this.config;t.maxMaxBufferLength>=e&&(t.maxMaxBufferLength/=2,_.logger.warn("main:reduce max buffer length to "+t.maxMaxBufferLength+"s"),this.fragLoadIdx+=2*t.fragLoadingLoopThreshold)}},{key:"_checkBuffer",value:function(){var e=this.media;if(e&&e.readyState){var t=e.currentTime,r=this.mediaBuffer?this.mediaBuffer:e,i=r.buffered;if(!this.loadedmetadata&&i.length){this.loadedmetadata=!0;var a=e.seeking?t:this.startPosition,n=f.default.isBuffered(r,a);t===a&&n||(_.logger.log("target start position:"+a),n||(a=i.start(0),_.logger.log("target start position not buffered, seek to buffered.start(0) "+a)),_.logger.log("adjust currentTime from "+t+" to "+a),e.currentTime=a)}else if(this.immediateSwitch)this.immediateLevelSwitchEnd();else{var s=f.default.bufferInfo(e,t,0),o=!(e.paused||e.ended||0===e.buffered.length),l=t!==this.lastCurrentTime,u=this.config;if(l)this.stallReported&&(_.logger.warn("playback not stuck anymore @"+t+", after "+Math.round(performance.now()-this.stalled)+"ms"),this.stallReported=!1),this.stalled=void 0,this.nudgeRetry=0;else if(o){var d=performance.now(),c=this.hls;if(this.stalled){var h=d-this.stalled,g=s.len,p=this.nudgeRetry||0;if(g<=.5&&h>1e3*u.lowBufferWatchdogPeriod){this.stallReported||(this.stallReported=!0,_.logger.warn("playback stalling in low buffer @"+t),c.trigger(v.default.ERROR,{type:k.ErrorTypes.MEDIA_ERROR,details:k.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,buffer:g}));var y=s.nextStart,m=y-t;if(y&&m0){this.nudgeRetry=++p;var E=p*u.nudgeOffset;_.logger.log("adjust currentTime from "+e.currentTime+" to next buffered @ "+y+" + nudge "+E),e.currentTime=y+E,this.stalled=void 0,c.trigger(v.default.ERROR,{type:k.ErrorTypes.MEDIA_ERROR,details:k.ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,hole:y+E-t})}}else if(g>.5&&h>1e3*u.highBufferWatchdogPeriod)if(this.stallReported||(this.stallReported=!0,_.logger.warn("playback stalling in high buffer @"+t),c.trigger(v.default.ERROR,{type:k.ErrorTypes.MEDIA_ERROR,details:k.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,buffer:g})),this.stalled=void 0,this.nudgeRetry=++p,p"+e),this.hls.trigger(v.default.STREAM_STATE_TRANSITION,{previousState:t,nextState:e})}},get:function(){return this._state}},{key:"currentLevel",get:function(){var e=this.media;if(e){var t=this.getBufferedFrag(e.currentTime);if(t)return t.level}return-1}},{key:"nextBufferedFrag",get:function(){var e=this.media;return e?this.followingBufferedFrag(this.getBufferedFrag(e.currentTime)):null}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"liveSyncPosition",get:function(){return this._liveSyncPosition},set:function(e){this._liveSyncPosition=e}}]),t}(y.default);r.default=A},{25:25,33:33,34:34,35:35,37:37,38:38,48:48,53:53,54:54}],14:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;r-1&&this.vttFragQueues[this.currentTrackId].length){var e=this.currentlyProcessing=this.vttFragQueues[this.currentTrackId].shift();this.hls.trigger(u.default.FRAG_LOADING,{frag:e})}}},{key:"onSubtitleFragProcessed",value:function(e){e.success&&this.vttFragSNsProcessed[e.frag.trackId].push(e.frag.sn),this.currentlyProcessing=null,this.nextFrag()}},{key:"onError",value:function(e){var t=e.frag;t&&"subtitle"!==t.type||this.currentlyProcessing&&(this.currentlyProcessing=null,this.nextFrag())}},{key:"onSubtitleTracksUpdated",value:function(e){var t=this;c.logger.log("subtitle tracks updated"),this.tracks=e.subtitleTracks,this.clearVttFragQueues(),this.vttFragSNsProcessed={},this.tracks.forEach(function(e){t.vttFragSNsProcessed[e.id]=[]})}},{key:"onSubtitleTrackSwitch",value:function(e){this.currentTrackId=e.id,this.clearVttFragQueues()}},{key:"onSubtitleTrackLoaded",value:function(e){var t=this.vttFragSNsProcessed[e.id],r=this.vttFragQueues[e.id],i=this.currentlyProcessing?this.currentlyProcessing.sn:-1,a=function(e){return t.indexOf(e.sn)>-1},n=function(e){return r.some(function(t){return t.sn===e.sn})};e.details.fragments.forEach(function(t){a(t)||t.sn===i||n(t)||(t.trackId=e.id,r.push(t))}),this.nextFrag()}}]),t}(f.default);r.default=h},{34:34,35:35,53:53}],15:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function o(e){for(var t=[],r=0;r=0&&e0;)e.removeCue(e.cues[0])}function l(e,t){return e&&e.label===t.name&&!(e.textTrack1||e.textTrack2)}function u(e,t,r,i){return Math.min(t,i)-Math.max(e,r)}Object.defineProperty(r,"__esModule",{value:!0});var d=function(){function e(e,t){for(var r=0;r=0&&(o[0]=Math.min(o[0],t),o[1]=Math.max(o[1],r),n=!0,l/(r-t)>.5))return}n||a.push([t,r]),this.Cues.newCue(this[e],t,r,i)}},{key:"onInitPtsFound",value:function(e){var t=this;void 0===this.initPTS&&(this.initPTS=e.initPTS),this.unparsedVttFrags.length&&(this.unparsedVttFrags.forEach(function(e){t.onFragLoaded(e)}),this.unparsedVttFrags=[])}},{key:"getExistingTrack",value:function(e){var t=this.media;if(t)for(var r=0;r>>8^255&p^99,e[h]=p,t[p]=h;var y=c[h],m=c[y],E=c[m],b=257*c[p]^16843008*p;i[h]=b<<24|b>>>8,a[h]=b<<16|b>>>16,n[h]=b<<8|b>>>24,s[h]=b,b=16843009*E^65537*m^257*y^16843008*h,l[p]=b<<24|b>>>8,u[p]=b<<16|b>>>16,d[p]=b<<8|b>>>24,f[p]=b,h?(h=y^c[c[c[E^y]]],g^=c[c[g]]):h=g=1}}},{key:"expandKey",value:function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i>8|e>>>24}},{key:"decrypt",value:function(e,t,r){for(var i,a,n=this.keySize+6,s=this.invKeySchedule,o=this.invSBox,l=this.invSubMix,u=l[0],d=l[1],f=l[2],c=l[3],h=this.uint8ArrayToUint32Array_(r),g=h[0],v=h[1],p=h[2],y=h[3],m=new Int32Array(e),E=new Int32Array(m.length),b=void 0,T=void 0,k=void 0,_=void 0,R=void 0,A=void 0,S=void 0,L=void 0,w=void 0,D=void 0,O=void 0,I=void 0,P=this.networkToHostOrderSwap;t>>24]^d[A>>16&255]^f[S>>8&255]^c[255&L]^s[i],T=u[A>>>24]^d[S>>16&255]^f[L>>8&255]^c[255&R]^s[i+1],k=u[S>>>24]^d[L>>16&255]^f[R>>8&255]^c[255&A]^s[i+2],_=u[L>>>24]^d[R>>16&255]^f[A>>8&255]^c[255&S]^s[i+3],R=b,A=T,S=k,L=_,i+=4;b=o[R>>>24]<<24^o[A>>16&255]<<16^o[S>>8&255]<<8^o[255&L]^s[i],T=o[A>>>24]<<24^o[S>>16&255]<<16^o[L>>8&255]<<8^o[255&R]^s[i+1],k=o[S>>>24]<<24^o[L>>16&255]<<16^o[R>>8&255]<<8^o[255&A]^s[i+2],_=o[L>>>24]<<24^o[R>>16&255]<<16^o[A>>8&255]<<8^o[255&S]^s[i+3],i+=3,E[t]=P(b^g),E[t+1]=P(_^v),E[t+2]=P(k^p),E[t+3]=P(T^y),g=w,v=D,p=O,y=I,t+=4}return E.buffer}},{key:"destroy",value:function(){this.key=void 0,this.keySize=void 0,this.ksRows=void 0,this.sBox=void 0,this.invSBox=void 0,this.subMix=void 0,this.invSubMix=void 0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.rcon=void 0}}]),e}();r.default=n},{}],19:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r>>5,(s-=h)>0&&c+h+s<=v);)for(g=m+f*u,p={unit:e.subarray(c+h,c+h+s),pts:g,dts:g},a.samples.push(p),a.len+=s,c+=s+h,f++;c>>6),(o=(60&t[r+2])>>>2)>h.length-1?void e.trigger(Event.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+o}):(u=(1&t[r+2])<<2,u|=(192&t[r+3])>>>6,i.logger.log("manifest codec:"+n+",ADTS data:type:"+s+",sampleingIndex:"+o+"["+h[o]+"Hz],channelConfig:"+u),/firefox/i.test(f)?o>=6?(s=5,d=new Array(4),l=o-3):(s=2,d=new Array(2),l=o):f.indexOf("android")!==-1?(s=2,d=new Array(2),l=o):(s=5,d=new Array(4),n&&(n.indexOf("mp4a.40.29")!==-1||n.indexOf("mp4a.40.5")!==-1)||!n&&o>=6?l=o-3:((n&&n.indexOf("mp4a.40.2")!==-1&&o>=6&&1===u||!n&&1===u)&&(s=2,d=new Array(2)),l=o)),d[0]=s<<3,d[0]|=(14&o)>>1,d[1]|=(1&o)<<7,d[1]|=u<<3,5===s&&(d[1]|=(14&l)>>1,d[2]=(1&l)<<7,d[2]|=8,d[3]=0),{config:d,samplerate:h[o],channelCount:u,codec:"mp4a.40."+s,manifestCodec:c})}};t.exports=n},{33:33,53:53}],23:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r0&&null!=t&&null!=t.key&&"AES-128"===t.method){var g=this.decrypter;null==g&&(g=this.decrypter=new d.default(this.observer,this.config));var v,p=this;try{v=performance.now()}catch(e){v=Date.now()}g.decrypt(e,t.key.buffer,t.iv.buffer,function(e){var d;try{d=performance.now()}catch(e){d=Date.now()}p.observer.trigger(o.default.FRAG_DECRYPTED,{stats:{tstart:v,tdecrypt:d}}),p.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),i,a,n,s,l,u,f,c,h)})}else this.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),i,a,n,s,l,u,f,c,h)}},{key:"pushDecrypted",value:function(e,t,r,i,a,n,s,u,d,f,h,v){var y=this.demuxer;if(!y||s&&!this.probe(e)){var E=this.observer,T=this.typeSupported,_=this.config,R=[{demux:p.default,remux:b.default},{demux:m.default,remux:b.default},{demux:c.default,remux:b.default},{demux:g.default,remux:k.default}];for(var A in R){var S=R[A],L=S.demux.probe;if(L(e)){var w=this.remuxer=new S.remux(E,_,T,this.vendor);y=new S.demux(E,w,_,T),this.probe=L;break}}if(!y)return void E.trigger(o.default.ERROR,{type:l.ErrorTypes.MEDIA_ERROR,details:l.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"});this.demuxer=y}var D=this.remuxer;(s||u)&&(y.resetInitSegment(r,i,a,f),D.resetInitSegment()),s&&(y.resetTimeStamp(),D.resetTimeStamp(v)),"function"==typeof y.setDecryptData&&y.setDecryptData(t),y.append(e,n,d,h)}}]),e}();r.default=_},{19:19,21:21,28:28,29:29,32:32,33:33,35:35,45:45,46:46}],24:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(r,"__esModule",{value:!0});var a=e(23),n=i(a),s=e(35),o=i(s),l=e(53),u=e(1),d=i(u),f=function(e){var t=new d.default;t.trigger=function(e){for(var r=arguments.length,i=Array(r>1?r-1:0),a=1;a1?r-1:0),a=1;a1?t-1:0),i=1;i1?t-1:0),i=1;ie?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t>>3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}},{key:"readBits",value:function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;return e>32&&n.logger.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0?this.word<<=t:this.bytesAvailable>0&&this.loadWord(),t=e-t,t>0&&this.bitsAvailable?r<>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}},{key:"skipUEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"skipEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"readUEG",value:function(){var e=this.skipLZ();return this.readBits(e+1)-1}},{key:"readEG",value:function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}},{key:"readBoolean",value:function(){return 1===this.readBits(1)}},{key:"readUByte",value:function(){return this.readBits(8)}},{key:"readUShort",value:function(){return this.readBits(16)}},{key:"readUInt",value:function(){return this.readBits(32)}},{key:"skipScalingList",value:function(e){var t,r,i=8,a=8;for(t=0;t=8){var r=e.bin2str(t.subarray(4,8));return["moof","ftyp","styp"].indexOf(r)>=0}return!1}},{key:"bin2str",value:function(e){return String.fromCharCode.apply(null,e)}},{key:"findBox",value:function(t,r){var i,a,n,s,o,l=[];if(!r.length)return null;for(i=0;i1?i+a:t.byteLength,n===r[0]&&(1===r.length?l.push(t.subarray(i+8,s)):(o=e.findBox(t.subarray(i+8,s),r.slice(1)),o.length&&(l=l.concat(o)))),i=s;return l}},{key:"parseInitSegment",value:function(t){var r=[];return e.findBox(t,["moov","trak"]).forEach(function(t){var i=e.findBox(t,["tkhd"])[0];if(i){var a=i[0],n=0===a?12:20,s=i[n]<<24|i[n+1]<<16|i[n+2]<<8|i[n+3];s=s<0?4294967296+s:s;var o=e.findBox(t,["mdia","mdhd"])[0];if(o){a=o[0],n=0===a?12:20;var l=o[n]<<24|o[n+1]<<16|o[n+2]<<8|o[n+3],u=e.findBox(t,["mdia","hdlr"])[0];if(u){var d=e.bin2str(u.subarray(8,12)),f={soun:"audio",vide:"video"}[d];f&&(r[s]={timescale:l,type:f},r[f]={timescale:l,id:s})}}}}),r}},{key:"startDTS",value:function(t,r){var i,a,n;return i=e.findBox(r,["moof","traf"]),a=[].concat.apply([],i.map(function(r){return e.findBox(r,["tfhd"]).map(function(i){var a,n,s;return a=i[4]<<24|i[5]<<16|i[6]<<8|i[7],n=t[a].timescale||9e4,s=e.findBox(r,["tfdt"]).map(function(e){var t,r;return t=e[0],r=e[4]<<24|e[5]<<16|e[6]<<8|e[7],1===t&&(r*=Math.pow(2,32),r+=e[8]<<24|e[9]<<16|e[10]<<8|e[11]),r})[0],(s=s||1/0)/n})})),n=Math.min.apply(null,a),isFinite(n)?n:0}}]),e}();r.default=o},{35:35}],30:[function(e,t,r){"use strict";var i=e(53),a={onFrame:function(e,t,r,i,a,n,s){var o=10368e4/i,l=s+n*o;e.config=[],e.channelCount=a,e.samplerate=i,e.samples.push({unit:t,pts:l,dts:l}),e.len+=t.length},onNoise:function(e){i.logger.warn("mpeg audio has noise: "+e.length+" bytes")},parseFrames:function(e,t,r,i,a,n){var s=[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],o=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3];if(r+2>i)return-1;if(255===t[r]||224==(224&t[r+1])){if(r+24>i)return-1;var l=t[r+1]>>3&3,u=t[r+1]>>1&3,d=t[r+2]>>4&15,f=t[r+2]>>2&3,c=!!(2&t[r+2]);if(1!==l&&0!==d&&15!==d&&3!==f){var h=3===l?3-u:3===u?3:4,g=1e3*s[14*h+d-1],v=3===l?0:2===l?1:2,p=o[3*v+f],y=c?1:0,m=t[r+3]>>6==3?1:2,E=3===u?(3===l?12:6)*g/p+y<<2:(3===l?144:72)*g/p+y|0;return r+E>i?-1:(this.onFrame(e,t.subarray(r,r+E),g,p,m,a,n),E)}}for(var b=r+2;b0;)r+=a}};t.exports=a},{53:53}],31:[function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r=e.length)return void r();if(!(e[t].unit.length<32)){var i=this.decrypter.isSync();if(this.decryptAacSample(e,t,r,i),!i)return}}}},{key:"getAvcEncryptedData",value:function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,a=32;a<=e.length-16;a+=160,i+=16)r.set(e.subarray(a,a+16),i);return r}},{key:"getAvcDecryptedUnit",value:function(e,t){t=new Uint8Array(t);for(var r=0,i=32;i<=e.length-16;i+=160,r+=16)e.set(t.subarray(r,r+16),i);return e}},{key:"decryptAvcSample",value:function(e,t,r,i,a,n){var s=this.discardEPB(a.data),o=this.getAvcEncryptedData(s),l=this;this.decryptBuffer(o.buffer,function(o){a.data=l.getAvcDecryptedUnit(s,o),n||l.decryptAvcSamples(e,t,r+1,i)})}},{key:"decryptAvcSamples",value:function(e,t,r,i){for(;;t++,r=0){if(t>=e.length)return void i();for(var a=e[t].units;!(r>=a.length);r++){var n=a[r];if(!(n.length<=48||1!==n.type&&5!==n.type)){var s=this.decrypter.isSync();if(this.decryptAvcSample(e,t,r,i,n,s),!s)return}}}}}]),e}();r.default=o},{19:19}],32:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r>4>1){if((o=a+5+e[a+4])===a+188)continue}else o=a+4;switch(s){case m:n&&(k&&(l=L(k))&&w(l,!1),k={data:[],size:0}),k&&(k.data.push(e.subarray(o,a+188)),k.size+=a+188-o);break;case E:n&&(_&&(l=L(_))&&(g.isAAC?D(l):O(l)),_={data:[],size:0}),_&&(_.data.push(e.subarray(o,a+188)),_.size+=a+188-o);break;case b:n&&(R&&(l=L(R))&&I(l),R={data:[],size:0}),R&&(R.data.push(e.subarray(o,a+188)),R.size+=a+188-o);break;case 0:n&&(o+=e[o]+1),T=this._pmtId=A(e,o);break;case T:n&&(o+=e[o]+1);var P=S(e,o,this.typeSupported.mpeg===!0||this.typeSupported.mp3===!0,null!=this.sampleAes);m=P.avc,m>0&&(h.id=m),E=P.audio,E>0&&(g.id=E,g.isAAC=P.isAAC),b=P.id3,b>0&&(v.id=b),d&&!c&&(p.logger.log("reparse from beginning"),d=!1,a=-188),c=this.pmtParsed=!0;break;case 17:case 8191:break;default:d=!0}}else this.observer.trigger(f.default.ERROR,{type:y.ErrorTypes.MEDIA_ERROR,details:y.ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,reason:"TS packet did not start with 0x47"});k&&(l=L(k))?(w(l,!0),h.pesData=null):h.pesData=k,_&&(l=L(_))?(g.isAAC?D(l):O(l),g.pesData=null):(_&&_.size&&p.logger.log("last AAC PES packet truncated,might overlap between fragments"),g.pesData=_),R&&(l=L(R))?(I(l),v.pesData=null):v.pesData=R,null==this.sampleAes?this.remuxer.remux(g,h,v,this._txtTrack,t,r,i):this.decryptAndRemux(g,h,v,this._txtTrack,t,r,i)}},{key:"decryptAndRemux",value:function(e,t,r,i,a,n,s){if(e.samples&&e.isAAC){var o=this;this.sampleAes.decryptAacSamples(e.samples,0,function(){o.decryptAndRemuxAvc(e,t,r,i,a,n,s)})}else this.decryptAndRemuxAvc(e,t,r,i,a,n,s)}},{key:"decryptAndRemuxAvc",value:function(e,t,r,i,a,n,s){if(t.samples){var o=this;this.sampleAes.decryptAvcSamples(t.samples,0,0,function(){o.remuxer.remux(e,t,r,i,a,n,s)})}else this.remuxer.remux(e,t,r,i,a,n,s)}},{key:"destroy",value:function(){this._initPTS=this._initDTS=void 0,this._duration=0}},{key:"_parsePAT",value:function(e,t){return(31&e[t+10])<<8|e[t+11]}},{key:"_parsePMT",value:function(e,t,r,i){var a,n,s,o,l={audio:-1,avc:-1,id3:-1,isAAC:!0};for(a=(15&e[t+1])<<8|e[t+2],n=t+3+a-4,s=(15&e[t+10])<<8|e[t+11],t+=12+s;t1;){var f=new Uint8Array(d[0].length+d[1].length);f.set(d[0]),f.set(d[1],d[0].length),d[0]=f,d.splice(1,1)}if(t=d[0],1===(t[0]<<16)+(t[1]<<8)+t[2]){if((i=(t[4]<<8)+t[5])&&i>e.size-6)return null;r=t[7],192&r&&(s=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,s>4294967295&&(s-=8589934592),64&r?(o=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2,o>4294967295&&(o-=8589934592),s-o>54e5&&(p.logger.warn(Math.round((s-o)/9e4)+"s delta between PTS and DTS, align them"),s=o)):o=s),a=t[8],l=a+9,e.size-=l,n=new Uint8Array(e.size);for(var c=0,h=d.length;cg){l-=g;continue}t=t.subarray(l),g-=l,l=0}n.set(t,u),u+=g}return i&&(i-=a+3),{data:n,pts:s,dts:o,len:i}}return null}},{key:"pushAccesUnit",value:function(e,t){if(e.units.length&&e.frame){var r=t.samples,i=r.length;!this.config.forceKeyFrameOnDiscontinuity||e.key===!0||t.sps&&(i||this.contiguous)?(e.id=i,r.push(e)):t.dropped++}e.debug.length&&p.logger.log(e.pts+"/"+e.dts+":"+e.debug)}},{key:"_parseAVCPES",value:function(e,t){var r,i,a,n=this,s=this._avcTrack,o=this._parseAVCNALu(e.data),l=this.avcSample;e.data=null,o.forEach(function(t){switch(t.type){case 1:i=!0,l.frame=!0;var o=t.data;if(o.length>4){var u=new h.default(o).readSliceType();2!==u&&4!==u&&7!==u&&9!==u||(l.key=!0)}break;case 5:i=!0,l||(l=n.avcSample=n._createAVCSample(!0,e.pts,e.dts,"")),l.key=!0,l.frame=!0;break;case 6:i=!0,r=new h.default(n.discardEPB(t.data)),r.readUByte();for(var d=0,f=0,c=!1,g=0;!c&&r.bytesAvailable>1;){d=0;do{g=r.readUByte(),d+=g}while(255===g);f=0;do{g=r.readUByte(),f+=g}while(255===g);if(4===d&&0!==r.bytesAvailable){c=!0;if(181===r.readUByte()){if(49===r.readUShort()){if(1195456820===r.readUInt()){if(3===r.readUByte()){var v=r.readUByte(),p=r.readUByte(),y=31&v,m=[v,p];for(a=0;a0){if(t.pts>=e[r-1].pts)e.push(t);else for(var i=r-1;i>=0;i--)if(t.pts=0)i={data:e.subarray(c,s-u-1),type:n},f.push(i);else{var h=this._getLastNalUnit();if(h&&(d&&s<=4-d&&h.state&&(h.data=h.data.subarray(0,h.data.byteLength-d)),(r=s-u-1)>0)){var g=new Uint8Array(h.data.byteLength+r);g.set(h.data,0),g.set(e.subarray(0,r),h.data.byteLength),h.data=g}}s=0&&u>=0&&(i={data:e.subarray(c,o),type:n,state:u},f.push(i)),0===f.length){var v=this._getLastNalUnit();if(v){var p=new Uint8Array(v.data.byteLength+e.byteLength);p.set(v.data,0),p.set(e,v.data.byteLength),v.data=p}}return l.naluState=u,f}},{key:"discardEPB",value:function(e){for(var t,r,i=e.byteLength,a=[],n=1;n1&&(p.logger.log("AAC: align PTS for overlapping frames by "+Math.round((_-g)/90)),g=_)}for(;n+5>>5,(r-=s)>0&&n+s+r<=u);)for(l=g+a*i,d={unit:h.subarray(n+s,n+s+r),pts:l,dts:l},c.samples.push(d),c.len+=r,n+=r+s,a++;n=564&&71===e[0]&&71===e[188]&&71===e[376]}}]),e}();r.default=m},{22:22,26:26,30:30,31:31,33:33,35:35,53:53}],33:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});r.ErrorTypes={NETWORK_ERROR:"networkError",MEDIA_ERROR:"mediaError",MUX_ERROR:"muxError",OTHER_ERROR:"otherError"},r.ErrorDetails={MANIFEST_LOAD_ERROR:"manifestLoadError",MANIFEST_LOAD_TIMEOUT:"manifestLoadTimeOut",MANIFEST_PARSING_ERROR:"manifestParsingError",MANIFEST_INCOMPATIBLE_CODECS_ERROR:"manifestIncompatibleCodecsError",LEVEL_LOAD_ERROR:"levelLoadError",LEVEL_LOAD_TIMEOUT:"levelLoadTimeOut",LEVEL_SWITCH_ERROR:"levelSwitchError",AUDIO_TRACK_LOAD_ERROR:"audioTrackLoadError",AUDIO_TRACK_LOAD_TIMEOUT:"audioTrackLoadTimeOut",FRAG_LOAD_ERROR:"fragLoadError",FRAG_LOOP_LOADING_ERROR:"fragLoopLoadingError",FRAG_LOAD_TIMEOUT:"fragLoadTimeOut",FRAG_DECRYPT_ERROR:"fragDecryptError",FRAG_PARSING_ERROR:"fragParsingError",REMUX_ALLOC_ERROR:"remuxAllocError",KEY_LOAD_ERROR:"keyLoadError",KEY_LOAD_TIMEOUT:"keyLoadTimeOut",BUFFER_ADD_CODEC_ERROR:"bufferAddCodecError",BUFFER_APPEND_ERROR:"bufferAppendError",BUFFER_APPENDING_ERROR:"bufferAppendingError",BUFFER_STALLED_ERROR:"bufferStalledError",BUFFER_FULL_ERROR:"bufferFullError",BUFFER_SEEK_OVER_HOLE:"bufferSeekOverHole",BUFFER_NUDGE_ON_STALL:"bufferNudgeOnStall",INTERNAL_EXCEPTION:"internalException",WEBVTT_EXCEPTION:"webVTTException"}},{}],34:[function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n=function(){function e(e,t){for(var r=0;r1?r-1:0),n=1;n=r.start(i)&&t<=r.end(i))return!0;return!1},bufferInfo:function(e,t,r){if(e){var i,a=e.buffered,n=[];for(i=0;id&&(l[u-1].end=e[o].end):l.push(e[o])}else l.push(e[o])}for(o=0,i=0,a=n=t;o=f&&t=0&&oe.endSN)return 0;var d,f,c;for(d=u-e.startSN,f=e.fragments,t=f[d],c=d;c>0;c--)a.updatePTS(f,c,c-1);for(c=d;ct?a.start+a.duration:Math.max(a.start-n.duration,0):r>t?(a.duration=s-a.start,a.duration<0&&i.logger.warn("negative duration computed for frag "+a.sn+",level "+a.level+", there should be some duration drift between playlist and fragment!")):(n.duration=a.start-s,n.duration<0&&i.logger.warn("negative duration computed for frag "+n.sn+",level "+n.level+", there should be some duration drift between playlist and fragment!"))}};t.exports=a},{53:53}],39:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{};a(this,e);var i=e.DefaultConfig;if((r.liveSyncDurationCount||r.liveMaxLatencyDurationCount)&&(r.liveSyncDuration||r.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");for(var n in i)n in r||(r[n]=i[n]);if(void 0!==r.liveMaxLatencyDurationCount&&r.liveMaxLatencyDurationCount<=r.liveSyncDurationCount)throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');if(void 0!==r.liveMaxLatencyDuration&&(r.liveMaxLatencyDuration<=r.liveSyncDuration||void 0===r.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');(0,_.enableLogs)(r.debug),this.config=r,this._autoLevelCapping=-1;var s=this.observer=new A.default;s.trigger=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i1?t-1:0),i=1;i0&&void 0!==arguments[0]?arguments[0]:-1;_.logger.log("startLoad("+e+")"),this.networkControllers.forEach(function(t){t.startLoad(e)})}},{key:"stopLoad",value:function(){_.logger.log("stopLoad"),this.networkControllers.forEach(function(e){e.stopLoad()})}},{key:"swapAudioCodec",value:function(){_.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}},{key:"recoverMediaError",value:function(){_.logger.log("recoverMediaError");var e=this.media;this.detachMedia(),this.attachMedia(e)}},{key:"levels",get:function(){return this.levelController.levels}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){_.logger.log("set currentLevel:"+e),this.loadLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){_.logger.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){_.logger.log("set loadLevel:"+e),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){_.logger.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){return this.levelController.startLevel},set:function(e){_.logger.log("set startLevel:"+e);var t=this;e!==-1&&(e=Math.max(e,t.minAutoLevel)),t.levelController.startLevel=e}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){_.logger.log("set autoLevelCapping:"+e),this._autoLevelCapping=e}},{key:"autoLevelEnabled",get:function(){return this.levelController.manualLevel===-1}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){for(var e=this,t=e.levels,r=e.config.minAutoBitrate,i=t?t.length:0,a=0;ar)return a}return 0}},{key:"maxAutoLevel",get:function(){var e=this,t=e.levels,r=e.autoLevelCapping;return r===-1&&t&&t.length?t.length-1:r}},{key:"nextAutoLevel",get:function(){var e=this;return Math.min(Math.max(e.abrController.nextAutoLevel,e.minAutoLevel),e.maxAutoLevel)},set:function(e){var t=this;t.abrController.nextAutoLevel=Math.max(t.minAutoLevel,e)}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"liveSyncPosition",get:function(){return this.streamController.liveSyncPosition}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}}]),e}();r.default=L},{1:1,11:11,12:12,13:13,2:2,33:33,35:35,4:4,41:41,42:42,43:43,53:53}],40:[function(e,t,r){"use strict";t.exports=e(39).default},{39:39}],41:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(r,"__esModule",{value:!0});var o=function(){function e(e,t){for(var r=0;r>8*(15-r)&255;return t}},{key:"fragmentDecryptdataFromLevelkey",value:function(e,t){var r=e;return e&&e.method&&e.uri&&!e.iv&&(r=new T,r.method=e.method,r.baseuri=e.baseuri,r.reluri=e.reluri,r.iv=this.createInitializationVector(t)),r}},{key:"cloneObj",value:function(e){return JSON.parse(JSON.stringify(e))}},{key:"url",get:function(){return!this._url&&this.relurl&&(this._url=u.default.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url},set:function(e){this._url=e}},{key:"programDateTime",get:function(){return!this._programDateTime&&this.rawProgramDateTime&&(this._programDateTime=new Date(Date.parse(this.rawProgramDateTime))),this._programDateTime}},{key:"byteRange",get:function(){if(!this._byteRange){var e=this._byteRange=[];if(this.rawByteRange){var t=this.rawByteRange.split("@",2);if(1===t.length){var r=this.lastByteRangeEndOffset;e[0]=r?r:0}else e[0]=parseInt(t[1]);e[1]=parseInt(t[0])+e[0]}}return this._byteRange}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"decryptdata",get:function(){return this._decryptdata||(this._decryptdata=this.fragmentDecryptdataFromLevelkey(this.levelkey,this.sn)),this._decryptdata}}]),e}(),_=function(e){function t(e){s(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,f.default.MANIFEST_LOADING,f.default.LEVEL_LOADING,f.default.AUDIO_TRACK_LOADING,f.default.SUBTITLE_TRACK_LOADING));return r.loaders={},r}return n(t,e),o(t,[{key:"destroy",value:function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy()}this.loaders={},h.default.prototype.destroy.call(this)}},{key:"onManifestLoading",value:function(e){this.load(e.url,{type:"manifest"})}},{key:"onLevelLoading",value:function(e){this.load(e.url,{type:"level",level:e.level,id:e.id})}},{key:"onAudioTrackLoading",value:function(e){this.load(e.url,{type:"audioTrack",id:e.id})}},{key:"onSubtitleTrackLoading",value:function(e){this.load(e.url,{type:"subtitleTrack",id:e.id})}},{key:"load",value:function(e,t){var r=this.loaders[t.type];if(r){var i=r.context;if(i&&i.url===e)return void y.logger.trace("playlist request ongoing");y.logger.warn("abort previous loader for type:"+t.type),r.abort()}var a=this.hls.config,n=void 0,s=void 0,o=void 0,l=void 0;"manifest"===t.type?(n=a.manifestLoadingMaxRetry,s=a.manifestLoadingTimeOut,o=a.manifestLoadingRetryDelay,l=a.manifestLoadingMaxRetryTimeout):(n=a.levelLoadingMaxRetry,s=a.levelLoadingTimeOut,o=a.levelLoadingRetryDelay,l=a.levelLoadingMaxRetryTimeout,y.logger.log("loading playlist for "+t.type+" "+(t.level||t.id))),r=this.loaders[t.type]=t.loader=void 0!==a.pLoader?new a.pLoader(a):new a.loader(a),t.url=e,t.responseType="";var u=void 0,d=void 0;u={timeout:s,maxRetry:n,retryDelay:o,maxRetryDelay:l},d={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)},r.load(t,u,d)}},{key:"resolve",value:function(e,t){return u.default.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}},{key:"parseMasterPlaylist",value:function(e,t){var r=[],i=void 0;for(m.lastIndex=0;null!=(i=m.exec(e));){var a={},n=a.attrs=new p.default(i[1]);a.url=this.resolve(i[2],t);var s=n.decimalResolution("RESOLUTION");s&&(a.width=s.width,a.height=s.height),a.bitrate=n.decimalInteger("AVERAGE-BANDWIDTH")||n.decimalInteger("BANDWIDTH"),a.name=n.NAME;var o=n.CODECS;if(o){o=o.split(/[ ,]+/);for(var l=0;l2?(t=r.shift()+".",t+=parseInt(r.shift()).toString(16),t+=("000"+parseInt(r.shift()).toString(16)).substr(-4)):t=e,t}},{key:"parseLevelPlaylist",value:function(e,t,r,i){var a,n,s=0,o=0,l={type:null,version:null,url:t,fragments:[],live:!0,startSN:0},u=new T,d=0,f=null,c=new k;for(b.lastIndex=0;null!==(a=b.exec(e));){var h=a[1];if(h){c.duration=parseFloat(h);var g=(" "+a[2]).slice(1);c.title=g?g:null,c.tagList.push(g?["INF",h,g]:["INF",h])}else if(a[3]){if(!isNaN(c.duration)){var v=s++;c.type=i,c.start=o,c.levelkey=u,c.sn=v,c.level=r,c.cc=d,c.baseurl=t,c.relurl=(" "+a[3]).slice(1),l.fragments.push(c),f=c,o+=c.duration,c=new k}}else if(a[4]){if(c.rawByteRange=(" "+a[4]).slice(1),f){var m=f.byteRangeEndOffset;m&&(c.lastByteRangeEndOffset=m)}}else if(a[5])c.rawProgramDateTime=(" "+a[5]).slice(1),c.tagList.push(["PROGRAM-DATE-TIME",c.rawProgramDateTime]);else{for(a=a[0].match(/(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)(.*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/),n=1;n=0&&(u.method=S,u.baseuri=t,u.reluri=L,u.key=null,u.iv=w));break;case"START":var D=E,O=new p.default(D),I=O.decimalFloatingPoint("TIME-OFFSET");isNaN(I)||(l.startTimeOffset=I);break;case"MAP":var P=new p.default(E);c.relurl=P.URI,c.rawByteRange=P.BYTERANGE,c.baseurl=t,c.level=r,c.type=i,c.sn="initSegment",l.initSegment=c,c=new k;break;default:y.logger.warn("line parsed but not handled: "+a)}}}return c=f,c&&!c.relurl&&(l.fragments.pop(),o-=c.duration),l.totalduration=o,l.averagetargetduration=o/l.fragments.length,l.endSN=s-1,l}},{key:"loadsuccess",value:function(e,t,r){var i=e.data,a=e.url,n=r.type,s=r.id,o=r.level,l=this.hls;if(this.loaders[n]=void 0,void 0!==a&&0!==a.indexOf("data:")||(a=r.url),t.tload=performance.now(),0===i.indexOf("#EXTM3U"))if(i.indexOf("#EXTINF:")>0){var u="audioTrack"!==n&&"subtitleTrack"!==n,d=isNaN(o)?isNaN(s)?0:s:o,c=this.parseLevelPlaylist(i,a,d,"audioTrack"===n?"audio":"subtitleTrack"===n?"subtitle":"main");c.tload=t.tload,"manifest"===n&&l.trigger(f.default.MANIFEST_LOADED,{levels:[{url:a,details:c}],audioTracks:[],url:a,stats:t}),t.tparsed=performance.now(),c.targetduration?u?l.trigger(f.default.LEVEL_LOADED,{details:c,level:o||0,id:s||0,stats:t}):"audioTrack"===n?l.trigger(f.default.AUDIO_TRACK_LOADED,{details:c,id:s,stats:t}):"subtitleTrack"===n&&l.trigger(f.default.SUBTITLE_TRACK_LOADED,{details:c,id:s,stats:t}):l.trigger(f.default.ERROR,{type:g.ErrorTypes.NETWORK_ERROR,details:g.ErrorDetails.MANIFEST_PARSING_ERROR,fatal:!0,url:a,reason:"invalid targetduration"})}else{var h=this.parseMasterPlaylist(i,a);if(h.length){var v=this.parseMasterPlaylistMedia(i,a,"AUDIO"),p=this.parseMasterPlaylistMedia(i,a,"SUBTITLES");if(v.length){var m=!1;v.forEach(function(e){e.url||(m=!0)}),m===!1&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(y.logger.log("audio codec signaled in quality level, but no embedded audio track signaled, create one"),v.unshift({type:"main",name:"main"}))}l.trigger(f.default.MANIFEST_LOADED,{levels:h,audioTracks:v,subtitles:p,url:a,stats:t})}else l.trigger(f.default.ERROR,{type:g.ErrorTypes.NETWORK_ERROR,details:g.ErrorDetails.MANIFEST_PARSING_ERROR,fatal:!0,url:a,reason:"no level found in manifest"})}else l.trigger(f.default.ERROR,{type:g.ErrorTypes.NETWORK_ERROR,details:g.ErrorDetails.MANIFEST_PARSING_ERROR,fatal:!0,url:a,reason:"no EXTM3U delimiter"})}},{key:"loaderror",value:function(e,t){var r,i,a=t.loader;switch(t.type){case"manifest":r=g.ErrorDetails.MANIFEST_LOAD_ERROR,i=!0;break;case"level":r=g.ErrorDetails.LEVEL_LOAD_ERROR,i=!1;break;case"audioTrack":r=g.ErrorDetails.AUDIO_TRACK_LOAD_ERROR,i=!1}a&&(a.abort(),this.loaders[t.type]=void 0),this.hls.trigger(f.default.ERROR,{type:g.ErrorTypes.NETWORK_ERROR,details:r,fatal:i,url:a.url,loader:a,response:e,context:t})}},{key:"loadtimeout",value:function(e,t){var r,i,a=t.loader;switch(t.type){case"manifest":r=g.ErrorDetails.MANIFEST_LOAD_TIMEOUT,i=!0;break;case"level":r=g.ErrorDetails.LEVEL_LOAD_TIMEOUT,i=!1;break;case"audioTrack":r=g.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT,i=!1}a&&(a.abort(),this.loaders[t.type]=void 0),this.hls.trigger(f.default.ERROR,{type:g.ErrorTypes.NETWORK_ERROR,details:r,fatal:i,url:a.url,loader:a,context:t})}}]),t}(h.default);r.default=_},{2:2,33:33,34:34,35:35,47:47,53:53}],44:[function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r>24&255,t[1]=i>>16&255,t[2]=i>>8&255,t[3]=255&i,t.set(e,4),a=0,i=8;a>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,85,196,0,0]))}},{key:"mdia",value:function(t){return e.box(e.types.mdia,e.mdhd(t.timescale,t.duration),e.hdlr(t.type),e.minf(t))}},{key:"mfhd",value:function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}},{key:"minf",value:function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))}},{key:"moof",value:function(t,r,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))}},{key:"moov",value:function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(e.mvex(t)))}},{key:"mvex",value:function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(i))}},{key:"mvhd",value:function(t,r){r*=t;var i=Math.floor(r/(n+1)),a=Math.floor(r%(n+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,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 e.box(e.types.mvhd,s)}},{key:"sdtp",value:function(t){var r,i,a=t.samples||[],n=new Uint8Array(4+a.length);for(i=0;i>>8&255),n.push(255&a),n=n.concat(Array.prototype.slice.call(i));for(r=0;r>>8&255),s.push(255&a),s=s.concat(Array.prototype.slice.call(i));var o=e.box(e.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(s))),l=t.width,u=t.height,d=t.pixelRatio[0],f=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,f>>24,f>>16&255,f>>8&255,255&f])))}},{key:"esds",value:function(e){var t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}},{key:"mp4a",value:function(t){var r=t.samplerate;return e.box(e.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),e.box(e.types.esds,e.esds(t)))}},{key:"mp3",value:function(t){var r=t.samplerate;return e.box(e.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))}},{key:"stsd",value:function(t){return"audio"===t.type?t.isAAC||"mp3"!==t.codec?e.box(e.types.stsd,e.STSD,e.mp4a(t)):e.box(e.types.stsd,e.STSD,e.mp3(t)):e.box(e.types.stsd,e.STSD,e.avc1(t))}},{key:"tkhd",value:function(t){var r=t.id,i=t.duration*t.timescale,a=t.width,s=t.height,o=Math.floor(i/(n+1)),l=Math.floor(i%(n+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,o>>24,o>>16&255,o>>8&255,255&o,l>>24,l>>16&255,l>>8&255,255&l,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,a>>8&255,255&a,0,0,s>>8&255,255&s,0,0]))}},{key:"traf",value:function(t,r){var i=e.sdtp(t),a=t.id,s=Math.floor(r/(n+1)),o=Math.floor(r%(n+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o])),e.trun(t,i.length+16+20+8+16+8+8),i)}},{key:"trak",value:function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))}},{key:"trex",value:function(t){var r=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}},{key:"trun",value:function(t,r){var i,a,n,s,o,l,u=t.samples||[],d=u.length,f=12+16*d,c=new Uint8Array(f);for(r+=8+f,c.set([0,0,15,1,d>>>24&255,d>>>16&255,d>>>8&255,255&d,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i>>24&255,n>>>16&255,n>>>8&255,255&n,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return e.box(e.types.trun,c)}},{key:"initSegment",value:function(t){e.types||e.init();var r,i=e.moov(t);return r=new Uint8Array(e.FTYP.byteLength+i.byteLength),r.set(e.FTYP),r.set(i,e.FTYP.byteLength),r}}]),e}();r.default=s},{}],45:[function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r-1&&s&&!s.match("CriOS"),this.ISGenerated=!1}return n(e,[{key:"destroy",value:function(){}},{key:"resetTimeStamp",value:function(e){this._initPTS=this._initDTS=e}},{key:"resetInitSegment",value:function(){this.ISGenerated=!1}},{key:"remux",value:function(e,t,r,i,a,n,s){if(this.ISGenerated||this.generateIS(e,t,a),this.ISGenerated)if(e.samples.length){e.timescale||(d.logger.warn("regenerate InitSegment as audio detected"),this.generateIS(e,t,a));var o=this.remuxAudio(e,a,n,s);if(t.samples.length){var l=void 0;o&&(l=o.endPTS-o.startPTS),t.timescale||(d.logger.warn("regenerate InitSegment as video detected"),this.generateIS(e,t,a)),this.remuxVideo(t,a,n,l)}}else{var f=void 0;t.samples.length&&(f=this.remuxVideo(t,a,n)),f&&e.codec&&this.remuxEmptyAudio(e,a,n,f)}r.samples.length&&this.remuxID3(r,a),i.samples.length&&this.remuxText(i,a),this.observer.trigger(u.default.FRAG_PARSED)}},{key:"generateIS",value:function(e,t,r){var i,a,n=this.observer,s=e.samples,o=t.samples,l=this.typeSupported,f="audio/mp4",g={},v={tracks:g},p=void 0===this._initPTS;if(p&&(i=a=1/0),e.config&&s.length&&(e.timescale=e.samplerate,d.logger.log("audio sampling rate : "+e.samplerate),e.isAAC||(l.mpeg?(f="audio/mpeg",e.codec=""):l.mp3&&(e.codec="mp3")),g.audio={container:f,codec:e.codec,initSegment:!e.isAAC&&l.mpeg?new Uint8Array:c.default.initSegment([e]),metadata:{channelCount:e.channelCount}},p&&(i=a=s[0].pts-e.inputTimeScale*r)),t.sps&&t.pps&&o.length){var y=t.inputTimeScale;t.timescale=y,g.video={container:"video/mp4",codec:t.codec,initSegment:c.default.initSegment([t]),metadata:{width:t.width,height:t.height}},p&&(i=Math.min(i,o[0].pts-y*r),a=Math.min(a,o[0].dts-y*r),this.observer.trigger(u.default.INIT_PTS_FOUND,{initPTS:i}))}Object.keys(g).length?(n.trigger(u.default.FRAG_PARSING_INIT_SEGMENT,v),this.ISGenerated=!0,p&&(this._initPTS=i,this._initDTS=a)):n.trigger(u.default.ERROR,{type:h.ErrorTypes.MEDIA_ERROR,details:h.ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,reason:"no audio/video samples found"})}},{key:"remuxVideo",value:function(e,t,r,i){var a,n,s,o,l,f,g,v=8,p=e.timescale,y=e.samples,m=[],E=y.length,b=this._PTSNormalize,T=this._initDTS;y.sort(function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r?r:i?i:e.id-t.id});var k=y.reduce(function(e,t){return Math.max(Math.min(e,t.pts-t.dts),-18e3)},0);if(k<0){d.logger.warn("PTS < DTS detected in video samples, shifting DTS by "+Math.round(k/90)+" ms to overcome this issue");for(var _=0;_1?d.logger.log("AVC:"+S+" ms hole between fragments detected,filling it"):S<-1&&d.logger.log("AVC:"+-S+" ms overlapping between fragments detected"),l=R,y[0].dts=l+T,o=Math.max(o-S,R),y[0].pts=o+T,d.logger.log("Video/PTS/DTS adjusted: "+Math.round(o/90)+"/"+Math.round(l/90)+",delta:"+S+" ms")),A=y[y.length-1],g=Math.max(b(A.dts-T,R),0),f=Math.max(b(A.pts-T,R),0),f=Math.max(f,g);var L=this.isSafari;L&&(a=Math.round((g-l)/(y.length-1)));for(var w=0,D=0,O=0;O0?U-1:U].dts;if(q.stretchShortVideoTrack){var Q=q.maxBufferHole,J=q.maxSeekHole,Z=Math.floor(Math.min(Q,J)*p),$=(i?o+i*p:this.nextAudioPts)-B.pts;$>Z?(a=$-z,a<0&&(a=z),d.logger.log("It is approximately "+$/90+" ms to the next segment; using duration "+a/90+" ms for the last video frame.")):a=z}else a=z}K=Math.round(B.pts-B.dts)}m.push({size:j,duration:a,cts:K,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:B.key?2:1,isNonSync:B.key?0:1}})}this.nextAvcDts=g+a;var ee=e.dropped;if(e.len=0,e.nbNalu=0,e.dropped=0,m.length&&navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var te=m[0].flags;te.dependsOn=2,te.isNonSync=0}e.samples=m,s=c.default.moof(e.sequenceNumber++,l,e),e.samples=[];var re={data1:s,data2:n,startPTS:o/p,endPTS:(f+a)/p,startDTS:l/p,endDTS:this.nextAvcDts/p,type:"video",nb:m.length,dropped:ee};return this.observer.trigger(u.default.FRAG_PARSING_DATA,re),re}},{key:"remuxAudio",value:function(e,t,r,i){var a,n,s,l,f,g,v,p,y,m,E,b,T,k,_,R,A=e.inputTimeScale,S=e.timescale,L=A/S,w=e.isAAC?1024:1152,D=w*L,O=this._PTSNormalize,I=this._initDTS,P=!e.isAAC&&this.typeSupported.mpeg,C=P?0:8,x=[],F=[];if(e.samples.sort(function(e,t){return e.pts-t.pts}),F=e.samples,R=this.nextAudioPts,r|=F.length&&R&&(i&&Math.abs(t-R/A)<.1||Math.abs(F[0].pts-R-I)<20*D),r||(R=t*A),i&&e.isAAC)for(var M=0,N=R;M=D&&N){var j=Math.round(G/D);d.logger.warn("Injecting "+j+" audio frame @ "+(N/A).toFixed(3)+"s due to "+Math.round(1e3*G/A)+" ms gap.");for(var K=0;K0)Y=Math.round((b-R)/D),d.logger.log(V+" ms hole between AAC samples detected,filling it"),Y>0&&(k=o.default.getSilentFrame(e.manifestCodec||e.codec,e.channelCount),k||(k=l.subarray()),e.len+=Y*k.length);else if(V<-12){d.logger.log("drop overlapping AAC sample, expected/parsed/delta:"+(R/A).toFixed(3)+"s/"+(b/A).toFixed(3)+"s/"+-V+"ms"),e.len-=l.byteLength;continue}b=T=R}if(v=Math.max(0,b),p=Math.max(0,T),!(e.len>0))return;var X=P?e.len:e.len+8;try{f=new Uint8Array(X)}catch(e){return void this.observer.trigger(u.default.ERROR,{type:h.ErrorTypes.MUX_ERROR,details:h.ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,bytes:X,reason:"fail allocating audio mdat "+X})}P||(a=new DataView(f.buffer),a.setUint32(0,X),f.set(c.default.types.mdat,4));for(var q=0;q=2&&(Q=x[J-2].duration,s.duration=Q),J){this.nextAudioPts=b+L*Q,e.len=0,e.samples=x,g=P?new Uint8Array:c.default.moof(e.sequenceNumber++,p/L,e),e.samples=[];var Z={data1:g,data2:f,startPTS:v/A,endPTS:this.nextAudioPts/A,startDTS:p/A,endDTS:(T+L*Q)/A,type:"audio",nb:J};return this.observer.trigger(u.default.FRAG_PARSING_DATA,Z),Z}return null}},{key:"remuxEmptyAudio",value:function(e,t,r,i){var a=e.inputTimeScale,n=e.samplerate?e.samplerate:a,s=a/n,l=this.nextAudioPts,u=(void 0!==l?l:i.startDTS*a)+this._initDTS,f=i.endDTS*a+this._initDTS,c=1024*s,h=Math.ceil((f-u)/c),g=o.default.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(d.logger.warn("remux empty Audio"),!g)return void d.logger.trace("Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!");for(var v=[],p=0;p4294967296;)e+=r;return e}}]),e}();r.default=g},{33:33,35:35,36:36,44:44,53:53}],46:[function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;rNumber.MAX_SAFE_INTEGER?1/0:t}},{key:"hexadecimalInteger",value:function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),i=0;iNumber.MAX_SAFE_INTEGER?1/0:t}},{key:"decimalFloatingPoint",value:function(e){return parseFloat(this[e])}},{key:"enumeratedString",value:function(e){return this[e]}},{key:"decimalResolution",value:function(e){var t=n.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}}],[{key:"parseAttrList",value:function(e){var t,r={};for(s.lastIndex=0;null!==(t=s.exec(e));){var i=t[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[t[1]]=i}return r}}]),e}();r.default=o},{}],48:[function(e,t,r){"use strict";var i={search:function(e,t){for(var r=0,i=e.length-1,a=null,n=null;r<=i;){a=(r+i)/2|0,n=e[a];var s=t(n);if(s>0)r=a+1;else{if(!(s<0))return n;i=a-1}}return null}};t.exports=i},{}],49:[function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;rl&&(g.log("ERROR","Too large cursor position "+this.pos),this.pos=l)}},{key:"moveCursor",value:function(e){var t=this.pos+e;if(e>1)for(var r=this.pos+1;r=144&&this.backSpace();var t=s(e);if(this.pos>=l)return void g.log("ERROR","Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}},{key:"clearFromPos",value:function(e){var t;for(t=e;t0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r}},{key:"getTextAndFormat",value:function(){return this.rows}}]),e}(),b=function(){function e(t,r){i(this,e),this.chNr=t,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new E,this.nonDisplayedMemory=new E,this.lastOutputScreen=new E,this.currRollUpRow=this.displayedMemory.rows[o-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}return a(e,[{key:"reset",value:function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.currRollUpRow=this.displayedMemory.rows[o-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.lastCueEndTime=null}},{key:"getHandler",value:function(){return this.outputFilter}},{key:"setHandler",value:function(e){this.outputFilter=e}},{key:"setPAC",value:function(e){this.writeScreen.setPAC(e)}},{key:"setBkgData",value:function(e){this.writeScreen.setBkgData(e)}},{key:"setMode",value:function(e){e!==this.mode&&(this.mode=e,g.log("INFO","MODE="+e),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}},{key:"insertChars",value:function(e){for(var t=0;t=46,t.italics)t.foreground="white";else{var r=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[r]}g.log("INFO","MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}},{key:"outputDataUpdate",value:function(){var e=g.time;null!==e&&this.outputFilter&&(this.outputFilter.updateData&&this.outputFilter.updateData(e,this.displayedMemory),null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}},{key:"cueSplitAtTime",value:function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}]),e}(),T=function(){function e(t,r,a){i(this,e),this.field=t||1,this.outputs=[r,a],this.channels=[new b(1,r),new b(2,a)],this.currChNr=-1,this.lastCmdA=null,this.lastCmdB=null,this.bufferedData=[],this.startTime=null,this.lastTime=null,this.dataCounters={padding:0,char:0,cmd:0,other:0}}return a(e,[{key:"getHandler",value:function(e){return this.channels[e].getHandler()}},{key:"setHandler",value:function(e,t){this.channels[e].setHandler(t)}},{key:"addData",value:function(e,t){var r,i,a,n=!1;this.lastTime=e,g.setTime(e);for(var s=0;s ("+v([i,a])+")"),r=this.parseCmd(i,a),r||(r=this.parseMidrow(i,a)),r||(r=this.parsePAC(i,a)),r||(r=this.parseBackgroundAttributes(i,a)),!r&&(n=this.parseChars(i,a)))if(this.currChNr&&this.currChNr>=0){var o=this.channels[this.currChNr-1];o.insertChars(n)}else g.log("WARNING","No channel found yet. TEXT-MODE?");r?this.dataCounters.cmd+=2:n?this.dataCounters.char+=2:(this.dataCounters.other+=2,g.log("WARNING","Couldn't parse cleaned data "+v([i,a])+" orig: "+v([t[s],t[s+1]])))}else this.dataCounters.padding+=2}},{key:"parseCmd",value:function(e,t){var r=null,i=(20===e||28===e)&&32<=t&&t<=47,a=(23===e||31===e)&&33<=t&&t<=35;if(!i&&!a)return!1;if(e===this.lastCmdA&&t===this.lastCmdB)return this.lastCmdA=null,this.lastCmdB=null,g.log("DEBUG","Repeated command ("+v([e,t])+") is dropped"),!0;r=20===e||23===e?1:2;var n=this.channels[r-1];return 20===e||28===e?32===t?n.ccRCL():33===t?n.ccBS():34===t?n.ccAOF():35===t?n.ccAON():36===t?n.ccDER():37===t?n.ccRU(2):38===t?n.ccRU(3):39===t?n.ccRU(4):40===t?n.ccFON():41===t?n.ccRDC():42===t?n.ccTR():43===t?n.ccRTD():44===t?n.ccEDM():45===t?n.ccCR():46===t?n.ccENM():47===t&&n.ccEOC():n.ccTO(t-32),this.lastCmdA=e,this.lastCmdB=t,this.currChNr=r,!0}},{key:"parseMidrow",value:function(e,t){var r=null;if((17===e||25===e)&&32<=t&&t<=47){if((r=17===e?1:2)!==this.currChNr)return g.log("ERROR","Mismatch channel in midrow parsing"),!1;return this.channels[r-1].ccMIDROW(t),g.log("DEBUG","MIDROW ("+v([e,t])+")"),!0}return!1}},{key:"parsePAC",value:function(e,t){var r=null,i=null,a=(17<=e&&e<=23||25<=e&&e<=31)&&64<=t&&t<=127,n=(16===e||24===e)&&64<=t&&t<=95;if(!a&&!n)return!1;if(e===this.lastCmdA&&t===this.lastCmdB)return this.lastCmdA=null,this.lastCmdB=null,!0;r=e<=23?1:2,i=64<=t&&t<=95?1===r?u[e]:f[e]:1===r?d[e]:c[e];var s=this.interpretPAC(i,t);return this.channels[r-1].setPAC(s),this.lastCmdA=e,this.lastCmdB=t,this.currChNr=r,!0}},{key:"interpretPAC",value:function(e,t){var r=t,i={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,i.underline=1==(1&r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i}},{key:"parseChars",value:function(e,t){var r=null,i=null,a=null;if(e>=25?(r=2,a=e-8):(r=1,a=e),17<=a&&a<=19){var n=t;n=17===a?t+80:18===a?t+112:t+144,g.log("INFO","Special char '"+s(n)+"' in channel "+r),i=[n]}else 32<=e&&e<=127&&(i=0===t?[e]:[e,t]);if(i){var o=v(i);g.log("DEBUG","Char codes = "+o.join(",")),this.lastCmdA=null,this.lastCmdB=null}return i}},{key:"parseBackgroundAttributes",value:function(e,t){var r,i,a,n,s=(16===e||24===e)&&32<=t&&t<=47,o=(23===e||31===e)&&45<=t&&t<=47;return!(!s&&!o)&&(r={},16===e||24===e?(i=Math.floor((t-32)/2),r.background=h[i],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0)),a=e<24?1:2,n=this.channels[a-1],n.setBkgData(r),this.lastCmdA=null,this.lastCmdB=null,!0)}},{key:"reset",value:function(){for(var e=0;e=16?l--:l++,navigator.userAgent.match(/Firefox\//)?s.line=f+1:s.line=f>7?f-2:f+1,s.align="left",s.position=Math.max(0,Math.min(100,l/32*100+(navigator.userAgent.match(/Firefox\//)?50:0))),e.addCue(s)}}};t.exports=a},{56:56}],51:[function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r=this.minWeight_}},{key:"getEstimate",value:function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}},{key:"destroy",value:function(){}}]),e}();r.default=o},{52:52}],52:[function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r "+t}function n(e){var t=self.console[e];return t?function(){for(var r=arguments.length,i=Array(r),n=0;n1?t-1:0),i=1;i100)throw new Error("Position must be between 0 and 100.");b=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},u,{get:function(){return T},set:function(e){var r=t(e);if(!r)throw new SyntaxError("An invalid or illegal string was specified.");T=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},u,{get:function(){return k},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");k=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},u,{get:function(){return _},set:function(e){var r=t(e);if(!r)throw new SyntaxError("An invalid or illegal string was specified.");_=r,this.hasBeenReset=!0}})),o.displayState=void 0,l)return o}if("undefined"!=typeof window&&window.VTTCue)return window.VTTCue;var a="auto",n={"":!0,lr:!0,rl:!0},s={start:!0,middle:!0,end:!0,left:!0,right:!0};return i.prototype.getCueAsHTML=function(){return window.WebVTT.convertCueToDOMTree(window,this.text)},i}()},{}],56:[function(e,t,r){"use strict";function i(){this.window=window,this.state="INITIAL",this.buffer="",this.decoder=new f,this.regionList=[]}function a(e){function t(e,t,r,i){return 3600*(0|e)+60*(0|t)+(0|r)+(0|i)/1e3}var r=e.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);return r?r[3]?t(r[1],r[2],r[3].replace(":",""),r[4]):r[1]>59?t(r[1],r[2],0,r[4]):t(0,r[1],r[2],r[4]):null}function n(){this.values=Object.create(null)}function s(e,t,r,i){var a=i?e.split(i):[e];for(var n in a)if("string"==typeof a[n]){var s=a[n].split(r);if(2===s.length){var o=s[0],l=s[1];t(o,l)}}}function o(e,t,r){function i(){var t=a(e);if(null===t)throw new Error("Malformed timestamp: "+l);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function o(){e=e.replace(/^\s+/,"")}var l=e;if(o(),t.startTime=i(),o(),"-->"!==e.substr(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+l);e=e.substr(3),o(),t.endTime=i(),o(),function(e,t){var i=new n;s(e,function(e,t){switch(e){case"region":for(var a=r.length-1;a>=0;a--)if(r[a].id===t){i.set(e,r[a].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":var n=t.split(","),s=n[0];i.integer(e,s),i.percent(e,s)&&i.set("snapToLines",!1),i.alt(e,s,["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",h,"end"]);break;case"position":n=t.split(","),i.percent(e,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",h,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",h,"end","left","right"])}},/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");var a=i.get("line","auto");"auto"===a&&c.line===-1&&(a=-1),t.line=a,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",h);var o=i.get("position","auto");"auto"===o&&50===c.position&&(o="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=o}(e,t)}function l(e){return e.replace(//gi,"\n")}Object.defineProperty(r,"__esModule",{value:!0}),r.fixLineBreaks=void 0;var u=e(55),d=function(e){return e&&e.__esModule?e:{default:e}}(u),f=function(){return{decode:function(e){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}};n.prototype={set:function(e,t){this.get(e)||""===t||(this.values[e]=t)},get:function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t},has:function(e){return e in this.values},alt:function(e,t,r){for(var i=0;i=0&&t<=100)&&(this.set(e,t),!0)}};var c=new d.default(0,0,0),h="middle"===c.align?"middle":"center";i.prototype={parse:function(e){function t(){var e=r.buffer,t=0;for(e=l(e);t")===-1){r.cue.id=i;continue}case"CUE":try{o(i,r.cue,r.regionList)}catch(e){r.cue=null,r.state="BADCUE";continue}r.state="CUETEXT";continue;case"CUETEXT":var u=i.indexOf("-->")!==-1;if(!i||u&&(n=!0)){r.oncue&&r.oncue(r.cue),r.cue=null,r.state="ID";continue}r.cue.text&&(r.cue.text+="\n"),r.cue.text+=i;continue;case"BADCUE":i||(r.state="ID");continue}}}catch(e){"CUETEXT"===r.state&&r.cue&&r.oncue&&r.oncue(r.cue),r.cue=null,r.state="INITIAL"===r.state?"BADWEBVTT":"BADCUE"}return this},flush:function(){var e=this;try{if(e.buffer+=e.decoder.decode(),(e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state)throw new Error("Malformed WebVTT signature.")}catch(e){throw e}return e.onflush&&e.onflush(),this}},r.fixLineBreaks=l,r.default=i},{55:55}],57:[function(e,t,r){"use strict";var i=e(56),a=function(e){return e&&e.__esModule?e:{default:e}}(i),n=function(e){var t=parseInt(e.substr(-3)),r=parseInt(e.substr(-6,2)),i=parseInt(e.substr(-9,2)),a=e.length>9?parseInt(e.substr(0,e.indexOf(":"))):0;return isNaN(t)||isNaN(r)||isNaN(i)||isNaN(a)?-1:(t+=1e3*r,t+=6e4*i,t+=36e5*a)},s=function e(t){for(var e=5381,r=t.length;r;)e=33*e^t.charCodeAt(--r);return(e>>>0).toString()},o=function(e,t,r){var i=e[t],a=e[i.prevCC];if(!a||!a.new&&i.new)return e.ccOffset=e.presentationOffset=i.start,void(i.new=!1);for(;a&&a.new;)e.ccOffset+=i.start-a.start,i.new=!1,i=a,a=e[i.prevCC];e.presentationOffset=r},l={parse:function(e,t,r,i,l,u){var d=String.fromCharCode.apply(null,new Uint8Array(e)).trim().replace(/\r\n|\n\r|\n|\r/g,"\n").split("\n"),f="00:00.000",c=0,h=0,g=0,v=[],p=void 0,y=!0,m=new a.default;m.oncue=function(e){var t=r[i],a=r.ccOffset;t&&t.new&&(h?a=r.ccOffset=t.start:o(r,i,g)),g&&!h&&(a=g+r.ccOffset-r.presentationOffset),e.startTime+=a-h,e.endTime+=a-h,e.id=s(e.startTime)+s(e.endTime)+s(e.text),e.text=decodeURIComponent(escape(e.text)),e.endTime>0&&v.push(e)},m.onparsingerror=function(e){p=e},m.onflush=function(){if(p&&u)return void u(p);l(v)},d.forEach(function(e){if(y){if(e.startsWith("X-TIMESTAMP-MAP=")){y=!1,e.substr(16).split(",").forEach(function(e){e.startsWith("LOCAL:")?f=e.substr(6):e.startsWith("MPEGTS:")&&(c=parseInt(e.substr(7)))});try{t=t<0?t+8589934592:t,c-=t,h=n(f)/1e3,g=c/9e4,h===-1&&(p=new Error("Malformed X-TIMESTAMP-MAP: "+e))}catch(t){p=new Error("Malformed X-TIMESTAMP-MAP: "+e)}return}""===e&&(y=!1)}m.parse(e+"\n")}),m.flush()}};t.exports=l},{56:56}],58:[function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(r,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r=2)if(window.clearTimeout(this.requestTimeout),0===i.tfirst&&(i.tfirst=Math.max(performance.now(),i.trequest)),4===r){var o=t.status;if(o>=200&&o<300){i.tload=Math.max(i.tfirst,performance.now());var l=void 0,u=void 0;"arraybuffer"===a.responseType?(l=t.response,u=l.byteLength):(l=t.responseText,u=l.length),i.loaded=i.total=u;var d={url:t.responseURL,data:l};this.callbacks.onSuccess(d,i,a)}else i.retry>=s.maxRetry||o>=400&&o<499?(n.logger.error(o+" while loading "+a.url),this.callbacks.onError({code:o,text:t.statusText},a)):(n.logger.warn(o+" while loading "+a.url+", retrying in "+this.retryDelay+"..."),this.destroy(),this.retryTimeout=window.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,s.maxRetryDelay),i.retry++)}else this.requestTimeout=window.setTimeout(this.loadtimeout.bind(this),s.timeout)}},{key:"loadtimeout",value:function(){n.logger.warn("timeout while loading "+this.context.url),this.callbacks.onTimeout(this.stats,this.context)}},{key:"loadprogress",value:function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total);var r=this.callbacks.onProgress;r&&r(t,this.context,null)}}]),e}();r.default=s},{53:53}]},{},[40])(40)});