diff --git a/dashboard-ui/bower_components/emby-webcomponents/htmlaudioplayer/plugin.js b/dashboard-ui/bower_components/emby-webcomponents/htmlaudioplayer/plugin.js index 7e68d180d4..517af9a9de 100644 --- a/dashboard-ui/bower_components/emby-webcomponents/htmlaudioplayer/plugin.js +++ b/dashboard-ui/bower_components/emby-webcomponents/htmlaudioplayer/plugin.js @@ -1 +1 @@ -define(["events","browser","pluginManager","apphost","appSettings","itemHelper"],function(events,browser,pluginManager,appHost,appSettings,itemHelper){"use strict";return function(){function getSavedVolume(){return appSettings.get("volume")||1}function saveVolume(value){value&&appSettings.set("volume",value)}function getDefaultProfile(){return new Promise(function(resolve,reject){require(["browserdeviceprofile"],function(profileBuilder){resolve(profileBuilder({}))})})}function playUwp(options,elem){return Windows.Storage.StorageFile.getFileFromPathAsync(options.url).then(function(file){var playlist=new Windows.Media.Playback.MediaPlaybackList,source1=Windows.Media.Core.MediaSource.createFromStorageFile(file),startTime=(options.playerStartPositionTicks||0)/1e4,winJsPlaybackItem=new Windows.Media.Playback.MediaPlaybackItem(source1,startTime);return playlist.items.append(winJsPlaybackItem),elem.src=URL.createObjectURL(playlist,{oneTimeOnly:!0}),currentSrc=elem.src,currentPlayOptions=options,playWithPromise(elem)})}function playWithPromise(elem){try{var promise=elem.play();return promise&&promise.then?promise.catch(function(e){var errorName=(e.name||"").toLowerCase();return"notallowederror"===errorName||"aborterror"===errorName?Promise.resolve():Promise.reject()}):Promise.resolve()}catch(err){return console.log("error calling audio.play: "+err),Promise.reject()}}function getCrossOriginValue(mediaSource){return mediaSource.IsRemote?null:"anonymous"}function supportsFade(){return!browser.tv}function fade(elem,startingVolume){var newVolume=Math.max(0,startingVolume-.15);return console.log("fading volume to "+newVolume),elem.volume=newVolume,newVolume<=0?Promise.resolve():new Promise(function(resolve,reject){cancelFadeTimeout(),fadeTimeout=setTimeout(function(){fade(elem,newVolume).then(resolve,reject)},100)})}function cancelFadeTimeout(){var timeout=fadeTimeout;timeout&&(clearTimeout(timeout),fadeTimeout=null)}function onEnded(){var stopInfo={src:currentSrc};events.trigger(self,"stopped",[stopInfo]),_currentTime=null,currentSrc=null,currentPlayOptions=null}function onTimeUpdate(){var time=this.currentTime;_currentTime=time,events.trigger(self,"timeupdate")}function onVolumeChange(){fadeTimeout||(saveVolume(this.volume),events.trigger(self,"volumechange"))}function onPlaying(e){started||(started=!0,this.removeAttribute("controls"),seekOnPlaybackStart(e.target)),events.trigger(self,"playing")}function seekOnPlaybackStart(element){var seconds=(currentPlayOptions.playerStartPositionTicks||0)/1e7;if(seconds){var src=(self.currentSrc()||"").toLowerCase();if(!browser.chrome||src.indexOf(".m3u8")!==-1){var delay=browser.safari?2500:0;delay?setTimeout(function(){element.currentTime=seconds},delay):element.currentTime=seconds}}}function onPause(){events.trigger(self,"pause")}function onError(){var errorCode=this.error?this.error.code:"";errorCode=(errorCode||"").toString(),console.log("Media element error code: "+errorCode);var type;switch(errorCode){case 1:return;case 2:type="network";break;case 3:type="mediadecodeerror";break;case 4:type="medianotsupported";break;default:return}onErrorInternal(type)}function onErrorInternal(type){events.trigger(self,"error",[{type:type}])}function createMediaElement(){var elem=document.querySelector(".mediaPlayerAudio");return elem||(elem=document.createElement("audio"),elem.classList.add("mediaPlayerAudio"),elem.classList.add("hide"),document.body.appendChild(elem),elem.volume=getSavedVolume(),elem.addEventListener("timeupdate",onTimeUpdate),elem.addEventListener("ended",onEnded),elem.addEventListener("volumechange",onVolumeChange),elem.addEventListener("pause",onPause),elem.addEventListener("playing",onPlaying),elem.addEventListener("error",onError)),mediaElement=elem,elem}function onDocumentClick(){document.removeEventListener("click",onDocumentClick);var elem=document.createElement("audio");elem.classList.add("mediaPlayerAudio"),elem.classList.add("hide"),document.body.appendChild(elem),elem.src=pluginManager.mapPath(self,"blank.mp3"),elem.play(),setTimeout(function(){elem.src="",elem.removeAttribute("src")},1e3)}var self=this;self.name="Html Audio Player",self.type="mediaplayer",self.id="htmlaudioplayer",self.priority=1;var mediaElement,currentSrc,currentPlayOptions,started,_currentTime;self.canPlayMediaType=function(mediaType){return"audio"===(mediaType||"").toLowerCase()},self.getDeviceProfile=function(item){return appHost.getDeviceProfile?appHost.getDeviceProfile(item):getDefaultProfile()},self.currentSrc=function(){return currentSrc},self.play=function(options){_currentTime=null,started=!1;var elem=createMediaElement(),val=options.url,seconds=(options.playerStartPositionTicks||0)/1e7;seconds&&(val+="#t="+seconds);var crossOrigin=getCrossOriginValue(options.mediaSource);if(crossOrigin&&(elem.crossOrigin=crossOrigin),elem.title=options.title,options.mimeType&&browser.operaTv)elem.currentSrc&&(elem.src="",elem.removeAttribute("src")),elem.innerHTML='';else{if(window.Windows&&options.mediaSource&&options.mediaSource.IsLocal)return playUwp(options,elem);elem.src=val}return currentSrc=val,currentPlayOptions=options,playWithPromise(elem)},self.currentTime=function(val){if(mediaElement)return null!=val?void(mediaElement.currentTime=val/1e3):_currentTime?1e3*_currentTime:1e3*(mediaElement.currentTime||0)},self.duration=function(val){if(mediaElement){var duration=mediaElement.duration;if(duration&&!isNaN(duration)&&duration!==Number.POSITIVE_INFINITY&&duration!==Number.NEGATIVE_INFINITY)return 1e3*duration}return null},self.stop=function(destroyPlayer){cancelFadeTimeout();var elem=mediaElement,src=currentSrc;if(elem&&src){if(!destroyPlayer||!supportsFade())return elem.paused||elem.pause(),elem.src="",elem.innerHTML="",elem.removeAttribute("src"),onEnded(),Promise.resolve();var originalVolume=elem.volume;return fade(elem,elem.volume).then(function(){elem.paused||elem.pause(),elem.src="",elem.innerHTML="",elem.removeAttribute("src"),elem.volume=originalVolume,onEnded()})}return Promise.resolve()},self.destroy=function(){};var fadeTimeout;self.pause=function(){mediaElement&&mediaElement.pause()},self.resume=function(){mediaElement&&mediaElement.play()},self.unpause=function(){mediaElement&&mediaElement.play()},self.paused=function(){return!!mediaElement&&mediaElement.paused},self.setVolume=function(val){mediaElement&&(mediaElement.volume=val/100)},self.getVolume=function(){if(mediaElement)return 100*mediaElement.volume},self.volumeUp=function(){self.setVolume(Math.min(self.getVolume()+2,100))},self.volumeDown=function(){self.setVolume(Math.max(self.getVolume()-2,0))},self.setMute=function(mute){mediaElement&&(mediaElement.muted=mute)},self.isMuted=function(){return!!mediaElement&&mediaElement.muted},appHost.supports("htmlaudioautoplay")||document.addEventListener("click",onDocumentClick)}}); \ No newline at end of file +define(["events","browser","pluginManager","apphost","appSettings","itemHelper"],function(events,browser,pluginManager,appHost,appSettings,itemHelper){"use strict";return function(){function getSavedVolume(){return appSettings.get("volume")||1}function saveVolume(value){value&&appSettings.set("volume",value)}function getDefaultProfile(){return new Promise(function(resolve,reject){require(["browserdeviceprofile"],function(profileBuilder){resolve(profileBuilder({}))})})}function playUwp(options,elem){return Windows.Storage.StorageFile.getFileFromPathAsync(options.url).then(function(file){var playlist=new Windows.Media.Playback.MediaPlaybackList,source1=Windows.Media.Core.MediaSource.createFromStorageFile(file),startTime=(options.playerStartPositionTicks||0)/1e4,winJsPlaybackItem=new Windows.Media.Playback.MediaPlaybackItem(source1,startTime);return playlist.items.append(winJsPlaybackItem),elem.src=URL.createObjectURL(playlist,{oneTimeOnly:!0}),currentSrc=elem.src,currentPlayOptions=options,playWithPromise(elem)})}function playWithPromise(elem){try{var promise=elem.play();return promise&&promise.then?promise.catch(function(e){var errorName=(e.name||"").toLowerCase();return"notallowederror"===errorName||"aborterror"===errorName?Promise.resolve():Promise.reject()}):Promise.resolve()}catch(err){return console.log("error calling audio.play: "+err),Promise.reject()}}function getCrossOriginValue(mediaSource){return mediaSource.IsRemote?null:"anonymous"}function supportsFade(){return!browser.tv}function fade(elem,startingVolume){var newVolume=Math.max(0,startingVolume-.15);return console.log("fading volume to "+newVolume),elem.volume=newVolume,newVolume<=0?Promise.resolve():new Promise(function(resolve,reject){cancelFadeTimeout(),fadeTimeout=setTimeout(function(){fade(elem,newVolume).then(resolve,reject)},100)})}function cancelFadeTimeout(){var timeout=fadeTimeout;timeout&&(clearTimeout(timeout),fadeTimeout=null)}function onEnded(){var stopInfo={src:currentSrc};events.trigger(self,"stopped",[stopInfo]),_currentTime=null,currentSrc=null,currentPlayOptions=null}function onTimeUpdate(){var time=this.currentTime;_currentTime=time,events.trigger(self,"timeupdate")}function onVolumeChange(){fadeTimeout||(saveVolume(this.volume),events.trigger(self,"volumechange"))}function onPlaying(e){started?events.trigger(self,"unpause"):(started=!0,this.removeAttribute("controls"),seekOnPlaybackStart(e.target)),events.trigger(self,"playing")}function seekOnPlaybackStart(element){var seconds=(currentPlayOptions.playerStartPositionTicks||0)/1e7;if(seconds){var src=(self.currentSrc()||"").toLowerCase();if(!browser.chrome||src.indexOf(".m3u8")!==-1){var delay=browser.safari?2500:0;delay?setTimeout(function(){element.currentTime=seconds},delay):element.currentTime=seconds}}}function onPause(){events.trigger(self,"pause")}function onError(){var errorCode=this.error?this.error.code:"";errorCode=(errorCode||"").toString(),console.log("Media element error code: "+errorCode);var type;switch(errorCode){case 1:return;case 2:type="network";break;case 3:type="mediadecodeerror";break;case 4:type="medianotsupported";break;default:return}onErrorInternal(type)}function onErrorInternal(type){events.trigger(self,"error",[{type:type}])}function createMediaElement(){var elem=document.querySelector(".mediaPlayerAudio");return elem||(elem=document.createElement("audio"),elem.classList.add("mediaPlayerAudio"),elem.classList.add("hide"),document.body.appendChild(elem),elem.volume=getSavedVolume(),elem.addEventListener("timeupdate",onTimeUpdate),elem.addEventListener("ended",onEnded),elem.addEventListener("volumechange",onVolumeChange),elem.addEventListener("pause",onPause),elem.addEventListener("playing",onPlaying),elem.addEventListener("error",onError)),mediaElement=elem,elem}function onDocumentClick(){document.removeEventListener("click",onDocumentClick);var elem=document.createElement("audio");elem.classList.add("mediaPlayerAudio"),elem.classList.add("hide"),document.body.appendChild(elem),elem.src=pluginManager.mapPath(self,"blank.mp3"),elem.play(),setTimeout(function(){elem.src="",elem.removeAttribute("src")},1e3)}var self=this;self.name="Html Audio Player",self.type="mediaplayer",self.id="htmlaudioplayer",self.priority=1;var mediaElement,currentSrc,currentPlayOptions,started,_currentTime;self.canPlayMediaType=function(mediaType){return"audio"===(mediaType||"").toLowerCase()},self.getDeviceProfile=function(item){return appHost.getDeviceProfile?appHost.getDeviceProfile(item):getDefaultProfile()},self.currentSrc=function(){return currentSrc},self.play=function(options){_currentTime=null,started=!1;var elem=createMediaElement(),val=options.url,seconds=(options.playerStartPositionTicks||0)/1e7;seconds&&(val+="#t="+seconds);var crossOrigin=getCrossOriginValue(options.mediaSource);if(crossOrigin&&(elem.crossOrigin=crossOrigin),elem.title=options.title,options.mimeType&&browser.operaTv)elem.currentSrc&&(elem.src="",elem.removeAttribute("src")),elem.innerHTML='';else{if(window.Windows&&options.mediaSource&&options.mediaSource.IsLocal)return playUwp(options,elem);elem.src=val}return currentSrc=val,currentPlayOptions=options,playWithPromise(elem)},self.currentTime=function(val){if(mediaElement)return null!=val?void(mediaElement.currentTime=val/1e3):_currentTime?1e3*_currentTime:1e3*(mediaElement.currentTime||0)},self.duration=function(val){if(mediaElement){var duration=mediaElement.duration;if(duration&&!isNaN(duration)&&duration!==Number.POSITIVE_INFINITY&&duration!==Number.NEGATIVE_INFINITY)return 1e3*duration}return null},self.stop=function(destroyPlayer){cancelFadeTimeout();var elem=mediaElement,src=currentSrc;if(elem&&src){if(!destroyPlayer||!supportsFade())return elem.paused||elem.pause(),elem.src="",elem.innerHTML="",elem.removeAttribute("src"),onEnded(),Promise.resolve();var originalVolume=elem.volume;return fade(elem,elem.volume).then(function(){elem.paused||elem.pause(),elem.src="",elem.innerHTML="",elem.removeAttribute("src"),elem.volume=originalVolume,onEnded()})}return Promise.resolve()},self.destroy=function(){};var fadeTimeout;self.pause=function(){mediaElement&&mediaElement.pause()},self.resume=function(){mediaElement&&mediaElement.play()},self.unpause=function(){mediaElement&&mediaElement.play()},self.paused=function(){return!!mediaElement&&mediaElement.paused},self.setVolume=function(val){mediaElement&&(mediaElement.volume=val/100)},self.getVolume=function(){if(mediaElement)return 100*mediaElement.volume},self.volumeUp=function(){self.setVolume(Math.min(self.getVolume()+2,100))},self.volumeDown=function(){self.setVolume(Math.max(self.getVolume()-2,0))},self.setMute=function(mute){mediaElement&&(mediaElement.muted=mute)},self.isMuted=function(){return!!mediaElement&&mediaElement.muted},appHost.supports("htmlaudioautoplay")||document.addEventListener("click",onDocumentClick)}}); \ No newline at end of file diff --git a/dashboard-ui/bower_components/emby-webcomponents/htmlvideoplayer/plugin.js b/dashboard-ui/bower_components/emby-webcomponents/htmlvideoplayer/plugin.js index 92d0a44df0..686a5a79ff 100644 --- a/dashboard-ui/bower_components/emby-webcomponents/htmlvideoplayer/plugin.js +++ b/dashboard-ui/bower_components/emby-webcomponents/htmlvideoplayer/plugin.js @@ -1 +1 @@ -define(["browser","pluginManager","events","apphost","loading","playbackManager","embyRouter","appSettings","connectionManager","itemHelper"],function(browser,pluginManager,events,appHost,loading,playbackManager,embyRouter,appSettings,connectionManager,itemHelper){"use strict";return function(){function getSavedVolume(){return appSettings.get("volume")||1}function saveVolume(value){value&&appSettings.set("volume",value)}function getDefaultProfile(){return new Promise(function(resolve,reject){require(["browserdeviceprofile"],function(profileBuilder){resolve(profileBuilder({}))})})}function updateVideoUrl(streamInfo){var isHls=streamInfo.url.toLowerCase().indexOf(".m3u8")!==-1,mediaSource=streamInfo.mediaSource,item=streamInfo.item;if(mediaSource&&item&&!mediaSource.RunTimeTicks&&isHls&&"Transcode"===streamInfo.playMethod&&(browser.iOS||browser.osx)){var hlsPlaylistUrl=streamInfo.url.replace("master.m3u8","live.m3u8");return loading.show(),console.log("prefetching hls playlist: "+hlsPlaylistUrl),connectionManager.getApiClient(item.ServerId).ajax({type:"GET",url:hlsPlaylistUrl}).then(function(){return console.log("completed prefetching hls playlist: "+hlsPlaylistUrl),loading.hide(),streamInfo.url=hlsPlaylistUrl,Promise.resolve()},function(){return console.log("error prefetching hls playlist: "+hlsPlaylistUrl),loading.hide(),Promise.resolve()})}return Promise.resolve()}function getSupportedFeatures(){var list=[],video=document.createElement("video");return browser.ipad&&navigator.userAgent.toLowerCase().indexOf("os 9")===-1&&video.webkitSupportsPresentationMode&&video.webkitSupportsPresentationMode&&"function"==typeof video.webkitSetPresentationMode&&list.push("PictureInPicture"),list.push("SetBrightness"),list}function getCrossOriginValue(mediaSource){return mediaSource.IsRemote?null:"anonymous"}function requireHlsPlayer(callback){require(["hlsjs"],function(hls){window.Hls=hls,callback()})}function bindEventsToHlsPlayer(hls,elem,resolve,reject){hls.on(Hls.Events.MANIFEST_PARSED,function(){playWithPromise(elem).then(resolve,function(){reject&&(reject(),reject=null)})}),hls.on(Hls.Events.ERROR,function(event,data){if(console.log("HLS Error: Type: "+data.type+" Details: "+(data.details||"")+" Fatal: "+(data.fatal||!1)),data.fatal)switch(data.type){case Hls.ErrorTypes.NETWORK_ERROR:data.response&&data.response.code&&data.response.code>=400&&data.response.code<500?(console.log("hls.js response error code: "+data.response.code),reject?(reject(),reject=null):onErrorInternal("network")):(console.log("fatal network error encountered, try to recover"),hls.startLoad());break;case Hls.ErrorTypes.MEDIA_ERROR:console.log("fatal media error encountered, try to recover");var currentReject=reject;reject=null,handleMediaError(currentReject);break;default:hls.destroy(),reject?(reject(),reject=null):onErrorInternal("mediadecodeerror")}})}function setCurrentSrc(elem,options){elem.removeEventListener("error",onError);var val=options.url;console.log("playing url: "+val);var seconds=(options.playerStartPositionTicks||0)/1e7;seconds&&(val+="#t="+seconds),destroyHlsPlayer();for(var tracks=getMediaStreamTextTracks(options.mediaSource),currentTrackIndex=-1,i=0,length=tracks.length;i'+getTracksHtml(tracks,options.mediaSource,options.item.ServerId),elem.addEventListener("loadedmetadata",onLoadedMetadata),currentSrc=val,setCurrentTrackElement(currentTrackIndex),playWithPromise(elem)):applySrc(elem,val,options).then(function(){return setTracks(elem,tracks,options.mediaSource,options.item.ServerId),currentSrc=val,setCurrentTrackElement(currentTrackIndex),playWithPromise(elem)})}function handleMediaError(reject){if(hlsPlayer){var now=Date.now();window.performance&&window.performance.now&&(now=performance.now()),!recoverDecodingErrorDate||now-recoverDecodingErrorDate>3e3?(recoverDecodingErrorDate=now,console.log("try to recover media Error ..."),hlsPlayer.recoverMediaError()):!recoverSwapAudioCodecDate||now-recoverSwapAudioCodecDate>3e3?(recoverSwapAudioCodecDate=now,console.log("try to swap Audio Codec and recover media Error ..."),hlsPlayer.swapAudioCodec(),hlsPlayer.recoverMediaError()):(console.error("cannot recover, last media error recovery failed ..."),reject?reject():onErrorInternal("mediadecodeerror"))}}function applySrc(elem,src,options){return window.Windows&&options.mediaSource&&options.mediaSource.IsLocal?Windows.Storage.StorageFile.getFileFromPathAsync(options.url).then(function(file){var playlist=new Windows.Media.Playback.MediaPlaybackList,source1=Windows.Media.Core.MediaSource.createFromStorageFile(file),startTime=(options.playerStartPositionTicks||0)/1e4;return playlist.items.append(new Windows.Media.Playback.MediaPlaybackItem(source1,startTime)),elem.src=URL.createObjectURL(playlist,{oneTimeOnly:!0}),Promise.resolve()}):(elem.src=src,Promise.resolve())}function onSuccessfulPlay(elem){elem.addEventListener("error",onError)}function playWithPromise(elem){try{var promise=elem.play();return promise&&promise.then?promise.catch(function(e){var errorName=(e.name||"").toLowerCase();return"notallowederror"===errorName||"aborterror"===errorName?(onSuccessfulPlay(elem),Promise.resolve()):Promise.reject()}):(onSuccessfulPlay(elem),Promise.resolve())}catch(err){return console.log("error calling video.play: "+err),Promise.reject()}}function destroyHlsPlayer(){var player=hlsPlayer;if(player){try{player.destroy()}catch(err){console.log(err)}hlsPlayer=null}}function onEnded(){destroyCustomTrack(this),onEndedInternal(!0,this)}function onEndedInternal(triggerEnded,elem){if(elem.removeEventListener("error",onError),elem.src="",elem.innerHTML="",elem.removeAttribute("src"),destroyHlsPlayer(),self.originalDocumentTitle&&(document.title=self.originalDocumentTitle,self.originalDocumentTitle=null),triggerEnded){var stopInfo={src:currentSrc};events.trigger(self,"stopped",[stopInfo]),_currentTime=null}currentSrc=null}function onTimeUpdate(e){var time=this.currentTime;_currentTime=time;var timeMs=1e3*time;timeMs+=(currentPlayOptions.transcodingOffsetTicks||0)/1e4,updateSubtitleText(timeMs),events.trigger(self,"timeupdate")}function onVolumeChange(){saveVolume(this.volume),events.trigger(self,"volumechange")}function onNavigatedToOsd(){videoDialog.classList.remove("videoPlayerContainer-withBackdrop"),videoDialog.classList.remove("videoPlayerContainer-onTop")}function onPlaying(e){started||(started=!0,this.removeAttribute("controls"),currentPlayOptions.title?(self.originalDocumentTitle=document.title,document.title=currentPlayOptions.title):self.originalDocumentTitle=null,setCurrentTrackElement(subtitleTrackIndexToSetOnPlaying),seekOnPlaybackStart(e.target),currentPlayOptions.fullscreen?embyRouter.showVideoOsd().then(onNavigatedToOsd):(embyRouter.setTransparency("backdrop"),videoDialog.classList.remove("videoPlayerContainer-withBackdrop"),videoDialog.classList.remove("videoPlayerContainer-onTop")),loading.hide(),ensureValidVideo(this)),events.trigger(self,"playing")}function ensureValidVideo(elem){setTimeout(function(){if(elem===mediaElement)return 0===elem.videoWidth&&0===elem.videoHeight?void onErrorInternal("mediadecodeerror"):void 0},100)}function seekOnPlaybackStart(element){var seconds=(currentPlayOptions.playerStartPositionTicks||0)/1e7;if(seconds){var src=(self.currentSrc()||"").toLowerCase();if(!browser.chrome||src.indexOf(".m3u8")!==-1){var delay=browser.safari?2500:0;delay?setTimeout(function(){element.currentTime=seconds},delay):element.currentTime=seconds}}}function onClick(){events.trigger(self,"click")}function onDblClick(){events.trigger(self,"dblclick")}function onPause(){events.trigger(self,"pause")}function onError(){var errorCode=this.error?this.error.code||0:0;console.log("Media element error code: "+errorCode.toString());var type;switch(errorCode){case 1:return;case 2:type="network";break;case 3:if(hlsPlayer)return void handleMediaError();type="mediadecodeerror";break;case 4:type="medianotsupported";break;default:return}onErrorInternal(type)}function onErrorInternal(type){destroyCustomTrack(mediaElement),events.trigger(self,"error",[{type:type}])}function onLoadedMetadata(e){var mediaElem=e.target;if(mediaElem.removeEventListener("loadedmetadata",onLoadedMetadata),!hlsPlayer)try{mediaElem.play()}catch(err){console.log("error calling mediaElement.play: "+err)}}function enableHlsPlayer(src,item,mediaSource){if(src&&src.indexOf(".m3u8")===-1)return!1;if(null==window.MediaSource)return!1;if(canPlayNativeHls()){if(browser.edge)return!0;if(mediaSource.RunTimeTicks)return!1}return!(browser.safari&&!browser.osx)}function canPlayNativeHls(){var media=document.createElement("video");return!(!media.canPlayType("application/x-mpegURL").replace(/no/,"")&&!media.canPlayType("application/vnd.apple.mpegURL").replace(/no/,""))}function setTracks(elem,tracks,mediaSource,serverId){elem.innerHTML=getTracksHtml(tracks,mediaSource,serverId)}function getTextTrackUrl(track,serverId){return playbackManager.getSubtitleUrl(track,serverId)}function getTracksHtml(tracks,mediaSource,serverId){return tracks.map(function(t){var defaultAttribute=mediaSource.DefaultSubtitleStreamIndex===t.Index?" default":"",language=t.Language||"und",label=t.Language||"und";return'"}).join("")}function enableNativeTrackSupport(track){if(browser.firefox&&(currentSrc||"").toLowerCase().indexOf(".m3u8")!==-1)return!1;if(browser.ps4)return!1;if(browser.edge)return!1;if(track){var format=(track.Codec||"").toLowerCase();if("ssa"===format||"ass"===format)return!1}return!0}function destroyCustomTrack(videoElement){if(window.removeEventListener("resize",onVideoResize),window.removeEventListener("orientationchange",onVideoResize),videoSubtitlesElem){var subtitlesContainer=videoSubtitlesElem.parentNode;subtitlesContainer.parentNode.removeChild(subtitlesContainer),videoSubtitlesElem=null}if(currentTrackEvents=null,videoElement)for(var allTracks=videoElement.textTracks||[],i=0;i',videoSubtitlesElem=subtitlesContainer.querySelector(".videoSubtitlesInner"),videoElement.parentNode.appendChild(subtitlesContainer),currentTrackEvents=data.TrackEvents}})}function renderTracksEvents(videoElement,track,serverId){var format=(track.Codec||"").toLowerCase();if("ssa"===format||"ass"===format)return void renderWithLibjass(videoElement,track,serverId);if(requiresCustomSubtitlesElement())return void renderSubtitlesWithCustomElement(videoElement,track,serverId);for(var trackElement=null,expectedId="manualTrack"+track.Index,allTracks=videoElement.textTracks,i=0;i=ticks){selectedTrackEvent=currentTrackEvent;break}}selectedTrackEvent?(videoSubtitlesElem.innerHTML=normalizeTrackEventText(selectedTrackEvent.Text),videoSubtitlesElem.classList.remove("hide")):(videoSubtitlesElem.innerHTML="",videoSubtitlesElem.classList.add("hide"))}}function getMediaStreamAudioTracks(mediaSource){return mediaSource.MediaStreams.filter(function(s){return"Audio"===s.Type})}function getMediaStreamTextTracks(mediaSource){return mediaSource.MediaStreams.filter(function(s){return"Subtitle"===s.Type&&"External"===s.DeliveryMethod})}function setCurrentTrackElement(streamIndex){console.log("Setting new text track index to: "+streamIndex);var mediaStreamTextTracks=getMediaStreamTextTracks(currentPlayOptions.mediaSource),track=streamIndex===-1?null:mediaStreamTextTracks.filter(function(t){return t.Index===streamIndex})[0];enableNativeTrackSupport(track)?setTrackForCustomDisplay(mediaElement,null):(setTrackForCustomDisplay(mediaElement,track),streamIndex=-1,track=null);for(var expectedId="textTrack"+streamIndex,trackIndex=streamIndex!==-1&&track?mediaStreamTextTracks.indexOf(track):-1,modes=["disabled","showing","hidden"],allTracks=mediaElement.textTracks,i=0;i':'",dlg.innerHTML=html;var videoElement=dlg.querySelector("video");videoElement.volume=getSavedVolume(),videoElement.addEventListener("timeupdate",onTimeUpdate),videoElement.addEventListener("ended",onEnded),videoElement.addEventListener("volumechange",onVolumeChange),videoElement.addEventListener("pause",onPause),videoElement.addEventListener("playing",onPlaying),videoElement.addEventListener("click",onClick),videoElement.addEventListener("dblclick",onDblClick),document.body.insertBefore(dlg,document.body.firstChild),videoDialog=dlg,mediaElement=videoElement,options.fullscreen&&browser.supportsCssAnimation()&&!browser.slow?zoomIn(dlg).then(function(){resolve(videoElement)}):resolve(videoElement)})})}var self=this;self.name="Html Video Player",self.type="mediaplayer",self.id="htmlvideoplayer",self.priority=1;var mediaElement,videoDialog,currentSrc,hlsPlayer,currentPlayOptions,subtitleTrackIndexToSetOnPlaying,currentClock,currentAssRenderer,currentAspectRatio,videoSubtitlesElem,currentTrackEvents,started=!1,lastCustomTrackMs=0,customTrackIndex=-1;self.canPlayMediaType=function(mediaType){return"video"===(mediaType||"").toLowerCase()},self.getDeviceProfile=function(item){return appHost.getDeviceProfile?appHost.getDeviceProfile(item):getDefaultProfile()},self.currentSrc=function(){return currentSrc},self.play=function(options){return browser.msie&&"Transcode"===options.playMethod&&!window.MediaSource?(alert("Playback of this content is not supported in Internet Explorer. For a better experience, try a modern browser such as Microsoft Edge, Google Chrome, Firefox or Opera."),Promise.reject()):(started=!1,_currentTime=null,createMediaElement(options).then(function(elem){return updateVideoUrl(options,options.mediaSource).then(function(){return setCurrentSrc(elem,options)})}))};var supportedFeatures;self.supports=function(feature){return supportedFeatures||(supportedFeatures=getSupportedFeatures()),supportedFeatures.indexOf(feature)!==-1},self.setAspectRatio=function(val){var video=mediaElement;video&&(currentAspectRatio=val)},self.getAspectRatio=function(){return currentAspectRatio},self.getSupportedAspectRatios=function(){return[]},self.togglePictureInPicture=function(){return self.setPictureInPictureEnabled(!self.isPictureInPictureEnabled())},self.setPictureInPictureEnabled=function(isEnabled){var video=mediaElement;video&&video.webkitSupportsPresentationMode&&"function"==typeof video.webkitSetPresentationMode&&video.webkitSetPresentationMode(isEnabled?"picture-in-picture":"inline")},self.isPictureInPictureEnabled=function(isEnabled){var video=mediaElement;return!!video&&"picture-in-picture"===video.webkitPresentationMode};var recoverDecodingErrorDate,recoverSwapAudioCodecDate;self.setSubtitleStreamIndex=function(index){setCurrentTrackElement(index)},self.canSetAudioStreamIndex=function(){return!(!browser.edge&&!browser.msie)},self.setAudioStreamIndex=function(index){var i,length,audioStreams=getMediaStreamAudioTracks(currentPlayOptions.mediaSource),audioTrackOffset=-1;for(i=0,length=audioStreams.length;i=100?"none":rawValue/100;elem.style["-webkit-filter"]="brightness("+cssValue+");",elem.style.filter="brightness("+cssValue+")",elem.brightnessValue=val,events.trigger(self,"brightnesschange")}},self.getBrightness=function(){if(mediaElement){var val=mediaElement.brightnessValue;return null==val?100:val}},self.setVolume=function(val){mediaElement&&(mediaElement.volume=val/100)},self.getVolume=function(){if(mediaElement)return 100*mediaElement.volume},self.volumeUp=function(){self.setVolume(Math.min(self.getVolume()+2,100))},self.volumeDown=function(){self.setVolume(Math.max(self.getVolume()-2,0))},self.setMute=function(mute){mediaElement&&(mediaElement.muted=mute)},self.isMuted=function(){return!!mediaElement&&mediaElement.muted}}}); \ No newline at end of file +define(["browser","pluginManager","events","apphost","loading","playbackManager","embyRouter","appSettings","connectionManager","itemHelper"],function(browser,pluginManager,events,appHost,loading,playbackManager,embyRouter,appSettings,connectionManager,itemHelper){"use strict";return function(){function getSavedVolume(){return appSettings.get("volume")||1}function saveVolume(value){value&&appSettings.set("volume",value)}function getDefaultProfile(){return new Promise(function(resolve,reject){require(["browserdeviceprofile"],function(profileBuilder){resolve(profileBuilder({}))})})}function updateVideoUrl(streamInfo){var isHls=streamInfo.url.toLowerCase().indexOf(".m3u8")!==-1,mediaSource=streamInfo.mediaSource,item=streamInfo.item;if(mediaSource&&item&&!mediaSource.RunTimeTicks&&isHls&&"Transcode"===streamInfo.playMethod&&(browser.iOS||browser.osx)){var hlsPlaylistUrl=streamInfo.url.replace("master.m3u8","live.m3u8");return loading.show(),console.log("prefetching hls playlist: "+hlsPlaylistUrl),connectionManager.getApiClient(item.ServerId).ajax({type:"GET",url:hlsPlaylistUrl}).then(function(){return console.log("completed prefetching hls playlist: "+hlsPlaylistUrl),loading.hide(),streamInfo.url=hlsPlaylistUrl,Promise.resolve()},function(){return console.log("error prefetching hls playlist: "+hlsPlaylistUrl),loading.hide(),Promise.resolve()})}return Promise.resolve()}function getSupportedFeatures(){var list=[],video=document.createElement("video");return browser.ipad&&navigator.userAgent.toLowerCase().indexOf("os 9")===-1&&video.webkitSupportsPresentationMode&&video.webkitSupportsPresentationMode&&"function"==typeof video.webkitSetPresentationMode&&list.push("PictureInPicture"),list.push("SetBrightness"),list}function getCrossOriginValue(mediaSource){return mediaSource.IsRemote?null:"anonymous"}function requireHlsPlayer(callback){require(["hlsjs"],function(hls){window.Hls=hls,callback()})}function bindEventsToHlsPlayer(hls,elem,resolve,reject){hls.on(Hls.Events.MANIFEST_PARSED,function(){playWithPromise(elem).then(resolve,function(){reject&&(reject(),reject=null)})}),hls.on(Hls.Events.ERROR,function(event,data){if(console.log("HLS Error: Type: "+data.type+" Details: "+(data.details||"")+" Fatal: "+(data.fatal||!1)),data.fatal)switch(data.type){case Hls.ErrorTypes.NETWORK_ERROR:data.response&&data.response.code&&data.response.code>=400&&data.response.code<500?(console.log("hls.js response error code: "+data.response.code),reject?(reject(),reject=null):onErrorInternal("network")):(console.log("fatal network error encountered, try to recover"),hls.startLoad());break;case Hls.ErrorTypes.MEDIA_ERROR:console.log("fatal media error encountered, try to recover");var currentReject=reject;reject=null,handleMediaError(currentReject);break;default:hls.destroy(),reject?(reject(),reject=null):onErrorInternal("mediadecodeerror")}})}function setCurrentSrc(elem,options){elem.removeEventListener("error",onError);var val=options.url;console.log("playing url: "+val);var seconds=(options.playerStartPositionTicks||0)/1e7;seconds&&(val+="#t="+seconds),destroyHlsPlayer();for(var tracks=getMediaStreamTextTracks(options.mediaSource),currentTrackIndex=-1,i=0,length=tracks.length;i'+getTracksHtml(tracks,options.mediaSource,options.item.ServerId),elem.addEventListener("loadedmetadata",onLoadedMetadata),currentSrc=val,setCurrentTrackElement(currentTrackIndex),playWithPromise(elem)):applySrc(elem,val,options).then(function(){return setTracks(elem,tracks,options.mediaSource,options.item.ServerId),currentSrc=val,setCurrentTrackElement(currentTrackIndex),playWithPromise(elem)})}function handleMediaError(reject){if(hlsPlayer){var now=Date.now();window.performance&&window.performance.now&&(now=performance.now()),!recoverDecodingErrorDate||now-recoverDecodingErrorDate>3e3?(recoverDecodingErrorDate=now,console.log("try to recover media Error ..."),hlsPlayer.recoverMediaError()):!recoverSwapAudioCodecDate||now-recoverSwapAudioCodecDate>3e3?(recoverSwapAudioCodecDate=now,console.log("try to swap Audio Codec and recover media Error ..."),hlsPlayer.swapAudioCodec(),hlsPlayer.recoverMediaError()):(console.error("cannot recover, last media error recovery failed ..."),reject?reject():onErrorInternal("mediadecodeerror"))}}function applySrc(elem,src,options){return window.Windows&&options.mediaSource&&options.mediaSource.IsLocal?Windows.Storage.StorageFile.getFileFromPathAsync(options.url).then(function(file){var playlist=new Windows.Media.Playback.MediaPlaybackList,source1=Windows.Media.Core.MediaSource.createFromStorageFile(file),startTime=(options.playerStartPositionTicks||0)/1e4;return playlist.items.append(new Windows.Media.Playback.MediaPlaybackItem(source1,startTime)),elem.src=URL.createObjectURL(playlist,{oneTimeOnly:!0}),Promise.resolve()}):(elem.src=src,Promise.resolve())}function onSuccessfulPlay(elem){elem.addEventListener("error",onError)}function playWithPromise(elem){try{var promise=elem.play();return promise&&promise.then?promise.catch(function(e){var errorName=(e.name||"").toLowerCase();return"notallowederror"===errorName||"aborterror"===errorName?(onSuccessfulPlay(elem),Promise.resolve()):Promise.reject()}):(onSuccessfulPlay(elem),Promise.resolve())}catch(err){return console.log("error calling video.play: "+err),Promise.reject()}}function destroyHlsPlayer(){var player=hlsPlayer;if(player){try{player.destroy()}catch(err){console.log(err)}hlsPlayer=null}}function onEnded(){destroyCustomTrack(this),onEndedInternal(!0,this)}function onEndedInternal(triggerEnded,elem){if(elem.removeEventListener("error",onError),elem.src="",elem.innerHTML="",elem.removeAttribute("src"),destroyHlsPlayer(),self.originalDocumentTitle&&(document.title=self.originalDocumentTitle,self.originalDocumentTitle=null),triggerEnded){var stopInfo={src:currentSrc};events.trigger(self,"stopped",[stopInfo]),_currentTime=null}currentSrc=null}function onTimeUpdate(e){var time=this.currentTime;_currentTime=time;var timeMs=1e3*time;timeMs+=(currentPlayOptions.transcodingOffsetTicks||0)/1e4,updateSubtitleText(timeMs),events.trigger(self,"timeupdate")}function onVolumeChange(){saveVolume(this.volume),events.trigger(self,"volumechange")}function onNavigatedToOsd(){videoDialog.classList.remove("videoPlayerContainer-withBackdrop"),videoDialog.classList.remove("videoPlayerContainer-onTop")}function onPlaying(e){started?events.trigger(self,"unpause"):(started=!0,this.removeAttribute("controls"),currentPlayOptions.title?(self.originalDocumentTitle=document.title,document.title=currentPlayOptions.title):self.originalDocumentTitle=null,setCurrentTrackElement(subtitleTrackIndexToSetOnPlaying),seekOnPlaybackStart(e.target),currentPlayOptions.fullscreen?embyRouter.showVideoOsd().then(onNavigatedToOsd):(embyRouter.setTransparency("backdrop"),videoDialog.classList.remove("videoPlayerContainer-withBackdrop"),videoDialog.classList.remove("videoPlayerContainer-onTop")),loading.hide(),ensureValidVideo(this)),events.trigger(self,"playing")}function ensureValidVideo(elem){setTimeout(function(){if(elem===mediaElement)return 0===elem.videoWidth&&0===elem.videoHeight?void onErrorInternal("mediadecodeerror"):void 0},100)}function seekOnPlaybackStart(element){var seconds=(currentPlayOptions.playerStartPositionTicks||0)/1e7;if(seconds){var src=(self.currentSrc()||"").toLowerCase();if(!browser.chrome||src.indexOf(".m3u8")!==-1){var delay=browser.safari?2500:0;delay?setTimeout(function(){element.currentTime=seconds},delay):element.currentTime=seconds}}}function onClick(){events.trigger(self,"click")}function onDblClick(){events.trigger(self,"dblclick")}function onPause(){events.trigger(self,"pause")}function onError(){var errorCode=this.error?this.error.code||0:0;console.log("Media element error code: "+errorCode.toString());var type;switch(errorCode){case 1:return;case 2:type="network";break;case 3:if(hlsPlayer)return void handleMediaError();type="mediadecodeerror";break;case 4:type="medianotsupported";break;default:return}onErrorInternal(type)}function onErrorInternal(type){destroyCustomTrack(mediaElement),events.trigger(self,"error",[{type:type}])}function onLoadedMetadata(e){var mediaElem=e.target;if(mediaElem.removeEventListener("loadedmetadata",onLoadedMetadata),!hlsPlayer)try{mediaElem.play()}catch(err){console.log("error calling mediaElement.play: "+err)}}function enableHlsPlayer(src,item,mediaSource){if(src&&src.indexOf(".m3u8")===-1)return!1;if(null==window.MediaSource)return!1;if(canPlayNativeHls()){if(browser.edge)return!0;if(mediaSource.RunTimeTicks)return!1}return!(browser.safari&&!browser.osx)}function canPlayNativeHls(){var media=document.createElement("video");return!(!media.canPlayType("application/x-mpegURL").replace(/no/,"")&&!media.canPlayType("application/vnd.apple.mpegURL").replace(/no/,""))}function setTracks(elem,tracks,mediaSource,serverId){elem.innerHTML=getTracksHtml(tracks,mediaSource,serverId)}function getTextTrackUrl(track,serverId){return playbackManager.getSubtitleUrl(track,serverId)}function getTracksHtml(tracks,mediaSource,serverId){return tracks.map(function(t){var defaultAttribute=mediaSource.DefaultSubtitleStreamIndex===t.Index?" default":"",language=t.Language||"und",label=t.Language||"und";return'"}).join("")}function enableNativeTrackSupport(track){if(browser.firefox&&(currentSrc||"").toLowerCase().indexOf(".m3u8")!==-1)return!1;if(browser.ps4)return!1;if(browser.edge)return!1;if(track){var format=(track.Codec||"").toLowerCase();if("ssa"===format||"ass"===format)return!1}return!0}function destroyCustomTrack(videoElement){if(window.removeEventListener("resize",onVideoResize),window.removeEventListener("orientationchange",onVideoResize),videoSubtitlesElem){var subtitlesContainer=videoSubtitlesElem.parentNode;subtitlesContainer.parentNode.removeChild(subtitlesContainer),videoSubtitlesElem=null}if(currentTrackEvents=null,videoElement)for(var allTracks=videoElement.textTracks||[],i=0;i',videoSubtitlesElem=subtitlesContainer.querySelector(".videoSubtitlesInner"),videoElement.parentNode.appendChild(subtitlesContainer),currentTrackEvents=data.TrackEvents}})}function renderTracksEvents(videoElement,track,serverId){var format=(track.Codec||"").toLowerCase();if("ssa"===format||"ass"===format)return void renderWithLibjass(videoElement,track,serverId);if(requiresCustomSubtitlesElement())return void renderSubtitlesWithCustomElement(videoElement,track,serverId);for(var trackElement=null,expectedId="manualTrack"+track.Index,allTracks=videoElement.textTracks,i=0;i=ticks){selectedTrackEvent=currentTrackEvent;break}}selectedTrackEvent?(videoSubtitlesElem.innerHTML=normalizeTrackEventText(selectedTrackEvent.Text),videoSubtitlesElem.classList.remove("hide")):(videoSubtitlesElem.innerHTML="",videoSubtitlesElem.classList.add("hide"))}}function getMediaStreamAudioTracks(mediaSource){return mediaSource.MediaStreams.filter(function(s){return"Audio"===s.Type})}function getMediaStreamTextTracks(mediaSource){return mediaSource.MediaStreams.filter(function(s){return"Subtitle"===s.Type&&"External"===s.DeliveryMethod})}function setCurrentTrackElement(streamIndex){console.log("Setting new text track index to: "+streamIndex);var mediaStreamTextTracks=getMediaStreamTextTracks(currentPlayOptions.mediaSource),track=streamIndex===-1?null:mediaStreamTextTracks.filter(function(t){return t.Index===streamIndex})[0];enableNativeTrackSupport(track)?setTrackForCustomDisplay(mediaElement,null):(setTrackForCustomDisplay(mediaElement,track),streamIndex=-1,track=null);for(var expectedId="textTrack"+streamIndex,trackIndex=streamIndex!==-1&&track?mediaStreamTextTracks.indexOf(track):-1,modes=["disabled","showing","hidden"],allTracks=mediaElement.textTracks,i=0;i':'",dlg.innerHTML=html;var videoElement=dlg.querySelector("video");videoElement.volume=getSavedVolume(),videoElement.addEventListener("timeupdate",onTimeUpdate),videoElement.addEventListener("ended",onEnded),videoElement.addEventListener("volumechange",onVolumeChange),videoElement.addEventListener("pause",onPause),videoElement.addEventListener("playing",onPlaying),videoElement.addEventListener("click",onClick),videoElement.addEventListener("dblclick",onDblClick),document.body.insertBefore(dlg,document.body.firstChild),videoDialog=dlg,mediaElement=videoElement,options.fullscreen&&browser.supportsCssAnimation()&&!browser.slow?zoomIn(dlg).then(function(){resolve(videoElement)}):resolve(videoElement)})})}var self=this;self.name="Html Video Player",self.type="mediaplayer",self.id="htmlvideoplayer",self.priority=1;var mediaElement,videoDialog,currentSrc,hlsPlayer,currentPlayOptions,subtitleTrackIndexToSetOnPlaying,currentClock,currentAssRenderer,currentAspectRatio,videoSubtitlesElem,currentTrackEvents,started=!1,lastCustomTrackMs=0,customTrackIndex=-1;self.canPlayMediaType=function(mediaType){return"video"===(mediaType||"").toLowerCase()},self.getDeviceProfile=function(item){return appHost.getDeviceProfile?appHost.getDeviceProfile(item):getDefaultProfile()},self.currentSrc=function(){return currentSrc},self.play=function(options){return browser.msie&&"Transcode"===options.playMethod&&!window.MediaSource?(alert("Playback of this content is not supported in Internet Explorer. For a better experience, try a modern browser such as Microsoft Edge, Google Chrome, Firefox or Opera."),Promise.reject()):(started=!1,_currentTime=null,createMediaElement(options).then(function(elem){return updateVideoUrl(options,options.mediaSource).then(function(){return setCurrentSrc(elem,options)})}))};var supportedFeatures;self.supports=function(feature){return supportedFeatures||(supportedFeatures=getSupportedFeatures()),supportedFeatures.indexOf(feature)!==-1},self.setAspectRatio=function(val){var video=mediaElement;video&&(currentAspectRatio=val)},self.getAspectRatio=function(){return currentAspectRatio},self.getSupportedAspectRatios=function(){return[]},self.togglePictureInPicture=function(){return self.setPictureInPictureEnabled(!self.isPictureInPictureEnabled())},self.setPictureInPictureEnabled=function(isEnabled){var video=mediaElement;video&&video.webkitSupportsPresentationMode&&"function"==typeof video.webkitSetPresentationMode&&video.webkitSetPresentationMode(isEnabled?"picture-in-picture":"inline")},self.isPictureInPictureEnabled=function(isEnabled){var video=mediaElement;return!!video&&"picture-in-picture"===video.webkitPresentationMode};var recoverDecodingErrorDate,recoverSwapAudioCodecDate;self.setSubtitleStreamIndex=function(index){setCurrentTrackElement(index)},self.canSetAudioStreamIndex=function(){return!(!browser.edge&&!browser.msie)},self.setAudioStreamIndex=function(index){var i,length,audioStreams=getMediaStreamAudioTracks(currentPlayOptions.mediaSource),audioTrackOffset=-1;for(i=0,length=audioStreams.length;i=100?"none":rawValue/100;elem.style["-webkit-filter"]="brightness("+cssValue+");",elem.style.filter="brightness("+cssValue+")",elem.brightnessValue=val,events.trigger(self,"brightnesschange")}},self.getBrightness=function(){if(mediaElement){var val=mediaElement.brightnessValue;return null==val?100:val}},self.setVolume=function(val){mediaElement&&(mediaElement.volume=val/100)},self.getVolume=function(){if(mediaElement)return 100*mediaElement.volume},self.volumeUp=function(){self.setVolume(Math.min(self.getVolume()+2,100))},self.volumeDown=function(){self.setVolume(Math.max(self.getVolume()-2,0))},self.setMute=function(mute){mediaElement&&(mediaElement.muted=mute)},self.isMuted=function(){return!!mediaElement&&mediaElement.muted}}}); \ No newline at end of file diff --git a/dashboard-ui/bower_components/emby-webcomponents/playback/playbackmanager.js b/dashboard-ui/bower_components/emby-webcomponents/playback/playbackmanager.js index f762d922b5..82348ba46f 100644 --- a/dashboard-ui/bower_components/emby-webcomponents/playback/playbackmanager.js +++ b/dashboard-ui/bower_components/emby-webcomponents/playback/playbackmanager.js @@ -1,2 +1,2 @@ -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 PlaybackManager(){function triggerPlayerChange(newPlayer,newTarget,previousPlayer,previousTargetInfo){(newPlayer||previousPlayer)&&(newTarget&&previousTargetInfo&&newTarget.id===previousTargetInfo.id||events.trigger(self,"playerchange",[newPlayer,newTarget,previousPlayer]))}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(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).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){clearProgressInterval(player);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,startProgressInterval(player),sendProgressUpdate(player)},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;iintervalTime&&sendProgressUpdate(player)},500)}function sendProgressUpdate(player){if(!player)throw new Error("player cannot be null");player.lastProgressReport=(new Date).getTime(),self.getPlayerState(player).then(function(state){var currentItem=getPlayerData(player).streamInfo.item;reportPlayback(state,currentItem.ServerId,"reportPlaybackProgress")})}function reportPlayback(state,serverId,method){if(serverId){var info={QueueableMediaTypes:state.NowPlayingItem.MediaType,ItemId:state.NowPlayingItem.Id};for(var i in state.PlayState)info[i]=state.PlayState[i];var apiClient=connectionManager.getApiClient(serverId);apiClient[method](info)}}function clearProgressInterval(player){if(!player)throw new Error("player cannot be null");var playerData=getPlayerData(player);playerData.currentProgressInterval&&(clearTimeout(playerData.currentProgressInterval),playerData.currentProgressInterval=null)}var currentPlayer,currentTargetInfo,lastLocalPlayer,currentPlaylistIndex,currentPlaylistItemId,currentPlayOptions,self=this,players=[],currentPairingId=null,repeatMode="RepeatNone",playlist=[],playNextAfterEnded=!0,playerStates={};self.currentItem=function(player){if(!player)throw new Error("player cannot be null");var data=getPlayerData(player);return data.streamInfo?data.streamInfo.item:null},self.currentMediaSource=function(player){if(!player)throw new Error("player cannot be null");var data=getPlayerData(player);return data.streamInfo?data.streamInfo.mediaSource:null; -},self.beginPlayerUpdates=function(player){player.beginPlayerUpdates&&player.beginPlayerUpdates()},self.endPlayerUpdates=function(player){player.endPlayerUpdates&&player.endPlayerUpdates()},self.getPlayerInfo=function(){var player=currentPlayer;if(!player)return null;var target=currentTargetInfo||{};return{name:player.name,isLocalPlayer:player.isLocalPlayer,id:target.id,deviceName:target.deviceName,playableMediaTypes:target.playableMediaTypes,supportedCommands:target.supportedCommands}},self.setActivePlayer=function(player,targetInfo){if("localplayer"===player||"localplayer"===player.name){if(currentPlayer&¤tPlayer.isLocalPlayer)return;return void setCurrentPlayerInternal(null,null)}if("string"==typeof player&&(player=players.filter(function(p){return p.name===player})[0]),!player)throw new Error("null player");setCurrentPlayerInternal(player,targetInfo)},self.trySetActivePlayer=function(player,targetInfo){if("localplayer"===player||"localplayer"===player.name)return void(currentPlayer&¤tPlayer.isLocalPlayer);if("string"==typeof player&&(player=players.filter(function(p){return p.name===player})[0]),!player)throw new Error("null player");if(currentPairingId!==targetInfo.id){currentPairingId=targetInfo.id;var promise=player.tryPair?player.tryPair(targetInfo):Promise.resolve();promise.then(function(){setCurrentPlayerInternal(player,targetInfo)},function(){currentPairingId===targetInfo.id&&(currentPairingId=null)})}},self.trySetActiveDeviceName=function(name){function normalizeName(t){return t.toLowerCase().replace(" ","")}name=normalizeName(name),self.getTargets().then(function(result){var target=result.filter(function(p){return normalizeName(p.name)===name})[0];target&&self.trySetActivePlayer(target.playerName,target)})},self.setDefaultPlayerActive=function(){self.setActivePlayer("localplayer")},self.removeActivePlayer=function(name){var playerInfo=self.getPlayerInfo();playerInfo&&playerInfo.name===name&&self.setDefaultPlayerActive()},self.removeActiveTarget=function(id){var playerInfo=self.getPlayerInfo();playerInfo&&playerInfo.id===id&&self.setDefaultPlayerActive()},self.disconnectFromPlayer=function(){var playerInfo=self.getPlayerInfo();playerInfo&&(playerInfo.supportedCommands.indexOf("EndSession")!==-1?require(["dialog"],function(dialog){var menuItems=[];menuItems.push({name:globalize.translate("ButtonYes"),id:"yes"}),menuItems.push({name:globalize.translate("ButtonNo"),id:"no"}),dialog({buttons:menuItems,text:globalize.translate("ConfirmEndPlayerSession")}).then(function(id){switch(id){case"yes":self.getCurrentPlayer().endSession(),self.setDefaultPlayerActive();break;case"no":self.setDefaultPlayerActive()}})}):self.setDefaultPlayerActive())},self.getTargets=function(){var promises=players.filter(function(p){return!displayPlayerInLocalGroup(p)}).map(getPlayerTargets);return Promise.all(promises).then(function(responses){var targets=[];targets.push({name:globalize.translate("sharedcomponents#HeaderMyDevice"),id:"localplayer",playerName:"localplayer",playableMediaTypes:["Audio","Video","Game"],isLocalPlayer:!0,supportedCommands:getSupportedCommands({isLocalPlayer:!0})});for(var i=0;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.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&&getPlayerData(player).currentProgressInterval&&(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 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 PlaybackManager(){function triggerPlayerChange(newPlayer,newTarget,previousPlayer,previousTargetInfo){(newPlayer||previousPlayer)&&(newTarget&&previousTargetInfo&&newTarget.id===previousTargetInfo.id||events.trigger(self,"playerchange",[newPlayer,newTarget,previousPlayer]))}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(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).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){clearProgressInterval(player);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,startProgressInterval(player),sendProgressUpdate(player)},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;i1e4&&sendProgressUpdate(player)},500)}function sendProgressUpdate(player){if(!player)throw new Error("player cannot be null");player.lastProgressReport=(new Date).getTime(),self.getPlayerState(player).then(function(state){var currentItem=getPlayerData(player).streamInfo.item;reportPlayback(state,currentItem.ServerId,"reportPlaybackProgress")})}function reportPlayback(state,serverId,method){if(serverId){var info=Object.assign({},state.PlayState);info.ItemId=state.NowPlayingItem.Id;var apiClient=connectionManager.getApiClient(serverId);apiClient[method](info)}}function clearProgressInterval(player){if(!player)throw new Error("player cannot be null");var playerData=getPlayerData(player);playerData.currentProgressInterval&&(clearTimeout(playerData.currentProgressInterval),playerData.currentProgressInterval=null)}var currentPlayer,currentTargetInfo,lastLocalPlayer,currentPlaylistIndex,currentPlaylistItemId,currentPlayOptions,self=this,players=[],currentPairingId=null,repeatMode="RepeatNone",playlist=[],playNextAfterEnded=!0,playerStates={};self.currentItem=function(player){if(!player)throw new Error("player cannot be null");var data=getPlayerData(player);return data.streamInfo?data.streamInfo.item:null},self.currentMediaSource=function(player){ +if(!player)throw new Error("player cannot be null");var data=getPlayerData(player);return data.streamInfo?data.streamInfo.mediaSource:null},self.beginPlayerUpdates=function(player){player.beginPlayerUpdates&&player.beginPlayerUpdates()},self.endPlayerUpdates=function(player){player.endPlayerUpdates&&player.endPlayerUpdates()},self.getPlayerInfo=function(){var player=currentPlayer;if(!player)return null;var target=currentTargetInfo||{};return{name:player.name,isLocalPlayer:player.isLocalPlayer,id:target.id,deviceName:target.deviceName,playableMediaTypes:target.playableMediaTypes,supportedCommands:target.supportedCommands}},self.setActivePlayer=function(player,targetInfo){if("localplayer"===player||"localplayer"===player.name){if(currentPlayer&¤tPlayer.isLocalPlayer)return;return void setCurrentPlayerInternal(null,null)}if("string"==typeof player&&(player=players.filter(function(p){return p.name===player})[0]),!player)throw new Error("null player");setCurrentPlayerInternal(player,targetInfo)},self.trySetActivePlayer=function(player,targetInfo){if("localplayer"===player||"localplayer"===player.name)return void(currentPlayer&¤tPlayer.isLocalPlayer);if("string"==typeof player&&(player=players.filter(function(p){return p.name===player})[0]),!player)throw new Error("null player");if(currentPairingId!==targetInfo.id){currentPairingId=targetInfo.id;var promise=player.tryPair?player.tryPair(targetInfo):Promise.resolve();promise.then(function(){setCurrentPlayerInternal(player,targetInfo)},function(){currentPairingId===targetInfo.id&&(currentPairingId=null)})}},self.trySetActiveDeviceName=function(name){function normalizeName(t){return t.toLowerCase().replace(" ","")}name=normalizeName(name),self.getTargets().then(function(result){var target=result.filter(function(p){return normalizeName(p.name)===name})[0];target&&self.trySetActivePlayer(target.playerName,target)})},self.setDefaultPlayerActive=function(){self.setActivePlayer("localplayer")},self.removeActivePlayer=function(name){var playerInfo=self.getPlayerInfo();playerInfo&&playerInfo.name===name&&self.setDefaultPlayerActive()},self.removeActiveTarget=function(id){var playerInfo=self.getPlayerInfo();playerInfo&&playerInfo.id===id&&self.setDefaultPlayerActive()},self.disconnectFromPlayer=function(){var playerInfo=self.getPlayerInfo();playerInfo&&(playerInfo.supportedCommands.indexOf("EndSession")!==-1?require(["dialog"],function(dialog){var menuItems=[];menuItems.push({name:globalize.translate("ButtonYes"),id:"yes"}),menuItems.push({name:globalize.translate("ButtonNo"),id:"no"}),dialog({buttons:menuItems,text:globalize.translate("ConfirmEndPlayerSession")}).then(function(id){switch(id){case"yes":self.getCurrentPlayer().endSession(),self.setDefaultPlayerActive();break;case"no":self.setDefaultPlayerActive()}})}):self.setDefaultPlayerActive())},self.getTargets=function(){var promises=players.filter(function(p){return!displayPlayerInLocalGroup(p)}).map(getPlayerTargets);return Promise.all(promises).then(function(responses){var targets=[];targets.push({name:globalize.translate("sharedcomponents#HeaderMyDevice"),id:"localplayer",playerName:"localplayer",playableMediaTypes:["Audio","Video","Game"],isLocalPlayer:!0,supportedCommands:getSupportedCommands({isLocalPlayer:!0})});for(var i=0;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.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&&getPlayerData(player).currentProgressInterval&&(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 new PlaybackManager}); \ No newline at end of file diff --git a/dashboard-ui/mypreferenceshome.html b/dashboard-ui/mypreferenceshome.html index 54ed0bf65e..7ba5112ff4 100644 --- a/dashboard-ui/mypreferenceshome.html +++ b/dashboard-ui/mypreferenceshome.html @@ -1,5 +1,5 @@ 
-
+
\ No newline at end of file diff --git a/dashboard-ui/scripts/indexpage.js b/dashboard-ui/scripts/indexpage.js index f08f7c8a4a..4e5bd8dcc6 100644 --- a/dashboard-ui/scripts/indexpage.js +++ b/dashboard-ui/scripts/indexpage.js @@ -1 +1 @@ -define(["loading","libraryBrowser","libraryMenu","playbackManager","mainTabsManager","homeSections","emby-button"],function(loading,libraryBrowser,libraryMenu,playbackManager,mainTabsManager,homeSections){"use strict";function loadSections(page,user,userSettings){var i,length,sectionCount=7,elem=page.querySelector(".sections"),html="";for(i=0,length=sectionCount;i
';elem.innerHTML=html;var promises=[];for(i=0,length=sectionCount;i';elem.innerHTML=html;var promises=[];for(i=0,length=sectionCount;i1?view.querySelector(".btnAudio").classList.remove("hide"):view.querySelector(".btnAudio").classList.add("hide"))):(setPoster(null),Emby.Page.setTitle(""),nowPlayingVolumeSlider.disabled=!0,nowPlayingPositionSlider.disabled=!0,btnFastForward.disabled=!0,btnRewind.disabled=!0,view.querySelector(".btnSubtitles").classList.add("hide"),view.querySelector(".btnAudio").classList.add("hide"),view.querySelector(".osdTitle").innerHTML="",view.querySelector(".osdTitleSmall").innerHTML="",void(view.querySelector(".osdMediaInfo").innerHTML=""))}function setTitle(item){var url=logoImageUrl(item,connectionManager.getApiClient(item.ServerId),{});url||Emby.Page.setTitle("")}function setPoster(item,secondaryItem){var osdPoster=view.querySelector(".osdPoster");if(item){var imgUrl=seriesImageUrl(item,{type:"Primary"})||seriesImageUrl(item,{type:"Thumb"})||imageUrl(item,{type:"Primary"});if(!imgUrl&&secondaryItem&&(imgUrl=seriesImageUrl(secondaryItem,{type:"Primary"})||seriesImageUrl(secondaryItem,{type:"Thumb"})||imageUrl(secondaryItem,{type:"Primary"})),imgUrl)return void(osdPoster.innerHTML='')}osdPoster.innerHTML=""}function isOsdOpen(){return _osdOpen}function showOsd(){slideDownToShow(headerElement),slideUpToShow(osdBottomElement),startHideTimer()}function hideOsd(){slideUpToHide(headerElement),slideDownToHide(osdBottomElement)}function startHideTimer(){stopHideTimer(),hideTimeout=setTimeout(hideOsd,5e3)}function stopHideTimer(){hideTimeout&&(clearTimeout(hideTimeout),hideTimeout=null)}function slideDownToShow(elem){elem.classList.remove("osdHeader-hidden")}function slideUpToHide(elem){elem.classList.add("osdHeader-hidden")}function clearBottomPanelAnimationEventListeners(elem){dom.removeEventListener(elem,transitionEndEventName,onSlideDownComplete,{once:!0})}function slideUpToShow(elem){_osdOpen||(_osdOpen=!0,clearBottomPanelAnimationEventListeners(elem),elem.classList.remove("hide"),void elem.offsetWidth,elem.classList.remove("videoOsdBottom-hidden"),setTimeout(function(){focusManager.focus(elem.querySelector(".btnPause"))},50),view.dispatchEvent(new CustomEvent("video-osd-show",{bubbles:!0,cancelable:!1})))}function onSlideDownComplete(e){var elem=e.target;elem.classList.add("hide"),dom.removeEventListener(elem,transitionEndEventName,onSlideDownComplete,{once:!0}),view.dispatchEvent(new CustomEvent("video-osd-hide",{bubbles:!0,cancelable:!1}))}function slideDownToHide(elem){_osdOpen&&(clearBottomPanelAnimationEventListeners(elem),void elem.offsetWidth,elem.classList.add("videoOsdBottom-hidden"),dom.addEventListener(elem,transitionEndEventName,onSlideDownComplete,{once:!0}),_osdOpen=!1)}function onMouseMove(e){var eventX=e.screenX||0,eventY=e.screenY||0,obj=lastMouseMoveData;return obj?void(Math.abs(eventX-obj.x)<10&&Math.abs(eventY-obj.y)<10||(obj.x=eventX,obj.y=eventY,showOsd())):void(lastMouseMoveData={x:eventX,y:eventY})}function onInputCommand(e){switch(e.detail.command){case"left":isOsdOpen()?showOsd():(e.preventDefault(),playbackManager.rewind());break;case"right":isOsdOpen()?showOsd():(e.preventDefault(),playbackManager.fastForward());break;case"up":case"down":case"select":case"menu":case"info":case"play":case"playpause":case"pause":case"fastforward":case"rewind":case"next":case"previous":showOsd();break;case"record":onRecordingCommand(),showOsd()}}function onRecordingCommand(){var btnRecord=view.querySelector(".btnRecord");btnRecord.classList.contains("hide")||btnRecord.click()}function updateFullscreenIcon(){playbackManager.isFullscreen(currentPlayer)?(view.querySelector(".btnFullscreen").setAttribute("title",globalize.translate("ExitFullscreen")),view.querySelector(".btnFullscreen i").innerHTML=""):(view.querySelector(".btnFullscreen").setAttribute("title",globalize.translate("Fullscreen")),view.querySelector(".btnFullscreen i").innerHTML="")}function onPlayerChange(){var player=playbackManager.getCurrentPlayer();player&&!player.isLocalPlayer?view.querySelector(".btnCast i").innerHTML="":view.querySelector(".btnCast i").innerHTML="",bindToPlayer(player)}function onStateChanged(event,state){var player=this;state.NowPlayingItem&&(isEnabled=!0,updatePlayerStateInternal(event,state),updatePlaylist(player),enableStopOnBack(!0))}function onPlayPauseStateChanged(e){if(isEnabled){var player=this;updatePlayPauseState(player.paused())}}function onVolumeChanged(e){if(isEnabled){var player=this;updatePlayerVolumeState(player.isMuted(),player.getVolume())}}function onPlaybackStart(e,state){console.log("nowplaying event: "+e.type);var player=this;onStateChanged.call(player,e,state)}function onPlaybackStopped(e,state){currentRuntimeTicks=null,console.log("nowplaying event: "+e.type),"Video"!==state.NextMediaType&&(view.removeEventListener("viewbeforehide",onViewHideStopPlayback),Emby.Page.back())}function bindToPlayer(player){player!==currentPlayer&&(releaseCurrentPlayer(),currentPlayer=player,player&&(playbackManager.getPlayerState(player).then(function(state){onStateChanged.call(player,{type:"init"},state)}),events.on(player,"playbackstart",onPlaybackStart),events.on(player,"playbackstop",onPlaybackStopped),events.on(player,"volumechange",onVolumeChanged),events.on(player,"pause",onPlayPauseStateChanged),events.on(player,"playing",onPlayPauseStateChanged),events.on(player,"timeupdate",onTimeUpdate),events.on(player,"fullscreenchange",updateFullscreenIcon)))}function releaseCurrentPlayer(){var player=currentPlayer;player&&(events.off(player,"playbackstart",onPlaybackStart),events.off(player,"playbackstop",onPlaybackStopped),events.off(player,"volumechange",onVolumeChanged),events.off(player,"pause",onPlayPauseStateChanged),events.off(player,"playing",onPlayPauseStateChanged),events.off(player,"timeupdate",onTimeUpdate),events.off(player,"fullscreenchange",updateFullscreenIcon),currentPlayer=null)}function onTimeUpdate(e){if(isEnabled){var now=(new Date).getTime();if(!(now-lastUpdateTime<700)){lastUpdateTime=now;var player=this;currentRuntimeTicks=playbackManager.duration(player),updateTimeDisplay(playbackManager.currentTime(player),currentRuntimeTicks),refreshProgramInfoIfNeeded(player)}}}function refreshProgramInfoIfNeeded(player){var item=currentItem;if("TvChannel"===item.Type){var program=item.CurrentProgram;if(program&&program.EndDate)try{var endDate=datetime.parseISO8601Date(program.EndDate);(new Date).getTime()>=endDate.getTime()&&(console.log("program info needs to be refreshed"),playbackManager.getPlayerState(player).then(function(state){onStateChanged.call(player,{type:"init"},state)}))}catch(e){console.log("Error parsing date: "+program.EndDate)}}}function updatePlayPauseState(isPaused){isPaused?view.querySelector(".btnPause i").innerHTML="":view.querySelector(".btnPause i").innerHTML=""}function updatePlayerStateInternal(event,state){var playerInfo=playbackManager.getPlayerInfo(),playState=state.PlayState||{};updatePlayPauseState(playState.IsPaused);var supportedCommands=playerInfo.supportedCommands;currentPlayerSupportedCommands=supportedCommands,supportsBrightnessChange=supportedCommands.indexOf("SetBrightness")!==-1,updatePlayerVolumeState(playState.IsMuted,playState.VolumeLevel),nowPlayingPositionSlider&&!nowPlayingPositionSlider.dragging&&(nowPlayingPositionSlider.disabled=!playState.CanSeek),btnFastForward.disabled=!playState.CanSeek,btnRewind.disabled=!playState.CanSeek;var nowPlayingItem=state.NowPlayingItem||{};updateTimeDisplay(playState.PositionTicks,nowPlayingItem.RunTimeTicks),updateNowPlayingInfo(state),state.MediaSource&&state.MediaSource.SupportsTranscoding&&supportedCommands.indexOf("SetMaxStreamingBitrate")!==-1?view.querySelector(".btnVideoOsdSettings").classList.remove("hide"):view.querySelector(".btnVideoOsdSettings").classList.add("hide"),supportedCommands.indexOf("ToggleFullscreen")===-1?view.querySelector(".btnFullscreen").classList.add("hide"):view.querySelector(".btnFullscreen").classList.remove("hide"),supportedCommands.indexOf("PictureInPicture")===-1?view.querySelector(".btnPip").classList.add("hide"):view.querySelector(".btnPip").classList.remove("hide"),updateFullscreenIcon()}function updateTimeDisplay(positionTicks,runtimeTicks){if(nowPlayingPositionSlider&&!nowPlayingPositionSlider.dragging){if(runtimeTicks){var pct=positionTicks/runtimeTicks;pct*=100,nowPlayingPositionSlider.value=pct}else nowPlayingPositionSlider.value=0;runtimeTicks&&null!=positionTicks?endsAtText.innerHTML="  -  "+mediaInfo.getEndsAtFromPosition(runtimeTicks,positionTicks,!0):endsAtText.innerHTML=""}updateTimeText(nowPlayingPositionText,positionTicks),updateTimeText(nowPlayingDurationText,runtimeTicks,!0)}function updatePlayerVolumeState(isMuted,volumeLevel){var supportedCommands=currentPlayerSupportedCommands,showMuteButton=!0,showVolumeSlider=!0;supportedCommands.indexOf("Mute")===-1&&(showMuteButton=!1),supportedCommands.indexOf("SetVolume")===-1&&(showVolumeSlider=!1),currentPlayer.isLocalPlayer&&appHost.supports("physicalvolumecontrol")&&(showMuteButton=!1,showVolumeSlider=!1),isMuted?(view.querySelector(".buttonMute").setAttribute("title",globalize.translate("Unmute")),view.querySelector(".buttonMute i").innerHTML=""):(view.querySelector(".buttonMute").setAttribute("title",globalize.translate("Mute")),view.querySelector(".buttonMute i").innerHTML=""),showMuteButton?view.querySelector(".buttonMute").classList.remove("hide"):view.querySelector(".buttonMute").classList.add("hide"),nowPlayingVolumeSlider&&(showVolumeSlider?nowPlayingVolumeSliderContainer.classList.remove("hide"):nowPlayingVolumeSliderContainer.classList.add("hide"),nowPlayingVolumeSlider.dragging||(nowPlayingVolumeSlider.value=volumeLevel||0))}function updatePlaylist(player){var btnPreviousTrack=view.querySelector(".btnPreviousTrack"),btnNextTrack=view.querySelector(".btnNextTrack");btnPreviousTrack.classList.remove("hide"),btnNextTrack.classList.remove("hide"),btnNextTrack.disabled=!1,btnPreviousTrack.disabled=!1}function updateTimeText(elem,ticks,divider){if(null==ticks)return void(elem.innerHTML="");var html=datetime.getDisplayRunningTime(ticks);divider&&(html=" / "+html),elem.innerHTML=html}function onSettingsButtonClick(e){var btn=this;require(["playerSettingsMenu"],function(playerSettingsMenu){playerSettingsMenu.show({mediaType:"Video",player:currentPlayer,positionTo:btn})})}function showAudioTrackSelection(){var player=currentPlayer,audioTracks=playbackManager.audioTracks(player),currentIndex=playbackManager.getAudioStreamIndex(player),menuItems=audioTracks.map(function(stream){var opt={name:stream.DisplayTitle,id:stream.Index};return stream.Index===currentIndex&&(opt.selected=!0),opt}),positionTo=this;require(["actionsheet"],function(actionsheet){actionsheet.show({items:menuItems,title:globalize.translate("Audio"),positionTo:positionTo}).then(function(id){var index=parseInt(id);index!==currentIndex&&playbackManager.setAudioStreamIndex(index,currentPlayer)})})}function showSubtitleTrackSelection(){var player=currentPlayer,streams=playbackManager.subtitleTracks(player),currentIndex=playbackManager.getSubtitleStreamIndex(player);null==currentIndex&&(currentIndex=-1),streams.unshift({Index:-1,DisplayTitle:globalize.translate("Off")});var menuItems=streams.map(function(stream){var opt={name:stream.DisplayTitle,id:stream.Index};return stream.Index===currentIndex&&(opt.selected=!0),opt}),positionTo=this;require(["actionsheet"],function(actionsheet){actionsheet.show({title:globalize.translate("Subtitles"),items:menuItems,positionTo:positionTo}).then(function(id){var index=parseInt(id);index!==currentIndex&&playbackManager.setSubtitleStreamIndex(index,currentPlayer)})})}function onWindowKeyDown(e){32!==e.keyCode||isOsdOpen()||(playbackManager.playPause(currentPlayer),showOsd())}function getImgUrl(item,chapter,index,maxWidth,apiClient){return chapter.ImageTag?apiClient.getScaledImageUrl(item.Id,{maxWidth:maxWidth,tag:chapter.ImageTag,type:"Chapter",index:index}):null}function getChapterBubbleHtml(apiClient,item,chapters,positionTicks){for(var chapter,index=-1,i=0,length=chapters.length;i=currentChapter.StartPositionTicks&&(chapter=currentChapter,index=i)}if(!chapter)return null;var src=getImgUrl(item,chapter,index,400,apiClient);if(src){var html='
';return html+='',html+='
',html+='
',html+=chapter.Name,html+="
",html+='

',html+=datetime.getDisplayRunningTime(positionTicks),html+="

",html+="
",html+="
"}return null}function onViewHideStopPlayback(){if(playbackManager.isPlayingVideo()){var player=currentPlayer;view.removeEventListener("viewbeforehide",onViewHideStopPlayback),releaseCurrentPlayer(),playbackManager.stop(player)}}function enableStopOnBack(enabled){view.removeEventListener("viewbeforehide",onViewHideStopPlayback),enabled&&playbackManager.isPlayingVideo(currentPlayer)&&view.addEventListener("viewbeforehide",onViewHideStopPlayback)}var currentPlayer,isEnabled,currentItem,recordingButtonManager,supportsBrightnessChange,hideTimeout,lastMouseMoveData,self=this,currentPlayerSupportedCommands=[],currentRuntimeTicks=0,lastUpdateTime=0,nowPlayingVolumeSlider=view.querySelector(".osdVolumeSlider"),nowPlayingVolumeSliderContainer=view.querySelector(".osdVolumeSliderContainer"),nowPlayingPositionSlider=view.querySelector(".osdPositionSlider"),nowPlayingPositionText=view.querySelector(".osdPositionText"),nowPlayingDurationText=view.querySelector(".osdDurationText"),endsAtText=view.querySelector(".endsAtText"),btnRewind=view.querySelector(".btnRewind"),btnFastForward=view.querySelector(".btnFastForward"),transitionEndEventName=dom.whichTransitionEvent(),headerElement=document.querySelector(".skinHeader"),osdBottomElement=document.querySelector(".videoOsdBottom"),_osdOpen=!0;view.addEventListener("viewbeforeshow",function(e){headerElement.classList.add("osdHeader"),Emby.Page.setTransparency("full")}),view.addEventListener("viewshow",function(e){events.on(playbackManager,"playerchange",onPlayerChange),bindToPlayer(playbackManager.getCurrentPlayer()),dom.addEventListener(document,"mousemove",onMouseMove,{passive:!0}),document.body.classList.add("autoScrollY"),showOsd(),inputManager.on(window,onInputCommand),dom.addEventListener(window,"keydown",onWindowKeyDown,{passive:!0})}),view.addEventListener("viewbeforehide",function(){dom.removeEventListener(window,"keydown",onWindowKeyDown,{passive:!0}),stopHideTimer(),headerElement.classList.remove("osdHeader"),headerElement.classList.remove("osdHeader-hidden"),dom.removeEventListener(document,"mousemove",onMouseMove,{passive:!0}),document.body.classList.remove("autoScrollY"),inputManager.off(window,onInputCommand),events.off(playbackManager,"playerchange",onPlayerChange),releaseCurrentPlayer()}),appHost.supports("remotecontrol")&&!layoutManager.tv&&view.querySelector(".btnCast").classList.remove("hide"),view.querySelector(".btnCast").addEventListener("click",function(){var btn=this;require(["playerSelectionMenu"],function(playerSelectionMenu){playerSelectionMenu.show(btn)})}),view.querySelector(".btnFullscreen").addEventListener("click",function(){playbackManager.toggleFullscreen(currentPlayer)}),view.querySelector(".btnPip").addEventListener("click",function(){playbackManager.togglePictureInPicture(currentPlayer)}),view.querySelector(".btnVideoOsdSettings").addEventListener("click",onSettingsButtonClick),view.addEventListener("viewhide",function(){headerElement.classList.remove("hide")}),view.addEventListener("viewhide",function(){self.touchHelper&&(self.touchHelper.destroy(),self.touchHelper=null)}),view.addEventListener("viewdestroy",function(){recordingButtonManager&&(recordingButtonManager.destroy(),recordingButtonManager=null)}),view.querySelector(".pageContainer").addEventListener("click",function(){layoutManager.mobile||playbackManager.playPause(currentPlayer),showOsd()}),view.querySelector(".buttonMute").addEventListener("click",function(){playbackManager.toggleMute(currentPlayer)}),nowPlayingVolumeSlider.addEventListener("change",function(){playbackManager.setVolume(this.value,currentPlayer)}),nowPlayingPositionSlider.addEventListener("change",function(){if(currentPlayer){var newPercent=parseFloat(this.value);playbackManager.seekPercent(newPercent,currentPlayer)}}),nowPlayingPositionSlider.getBubbleHtml=function(value){if(showOsd(),!currentRuntimeTicks)return"--:--";var ticks=currentRuntimeTicks;ticks/=100,ticks*=value;var item=currentItem;if(item&&item.Chapters&&item.Chapters.length&&item.Chapters[0].ImageTag){var html=getChapterBubbleHtml(connectionManager.getApiClient(item.ServerId),item,item.Chapters,ticks);if(html)return html}return'

'+datetime.getDisplayRunningTime(ticks)+"

"},view.querySelector(".btnPreviousTrack").addEventListener("click",function(){playbackManager.previousChapter(currentPlayer)}),view.querySelector(".btnPause").addEventListener("click",function(){playbackManager.playPause(currentPlayer)}),view.querySelector(".btnNextTrack").addEventListener("click",function(){playbackManager.nextChapter(currentPlayer)}),btnRewind.addEventListener("click",function(){playbackManager.rewind(currentPlayer)}),btnFastForward.addEventListener("click",function(){playbackManager.fastForward(currentPlayer)}),view.querySelector(".btnAudio").addEventListener("click",showAudioTrackSelection),view.querySelector(".btnSubtitles").addEventListener("click",showSubtitleTrackSelection),browser.touch&&initSwipeEvents()}}); \ No newline at end of file +define(["playbackManager","dom","inputmanager","datetime","itemHelper","mediaInfo","focusManager","imageLoader","scrollHelper","events","connectionManager","browser","globalize","apphost","layoutManager","scrollStyles","emby-slider","paper-icon-button-light","css!css/videoosd"],function(playbackManager,dom,inputManager,datetime,itemHelper,mediaInfo,focusManager,imageLoader,scrollHelper,events,connectionManager,browser,globalize,appHost,layoutManager){"use strict";function seriesImageUrl(item,options){if("Episode"!==item.Type)return null;if(options=options||{},options.type=options.type||"Primary","Primary"===options.type&&item.SeriesPrimaryImageTag)return options.tag=item.SeriesPrimaryImageTag,connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.SeriesId,options);if("Thumb"===options.type){if(item.SeriesThumbImageTag)return options.tag=item.SeriesThumbImageTag,connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.SeriesId,options);if(item.ParentThumbImageTag)return options.tag=item.ParentThumbImageTag,connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.ParentThumbItemId,options)}return null}function imageUrl(item,options){return options=options||{},options.type=options.type||"Primary",item.ImageTags&&item.ImageTags[options.type]?(options.tag=item.ImageTags[options.type],connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.PrimaryImageItemId||item.Id,options)):"Primary"===options.type&&item.AlbumId&&item.AlbumPrimaryImageTag?(options.tag=item.AlbumPrimaryImageTag,connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.AlbumId,options)):null}function logoImageUrl(item,apiClient,options){return options=options||{},options.type="Logo",item.ImageTags&&item.ImageTags.Logo?(options.tag=item.ImageTags.Logo,apiClient.getScaledImageUrl(item.Id,options)):item.ParentLogoImageTag?(options.tag=item.ParentLogoImageTag,apiClient.getScaledImageUrl(item.ParentLogoItemId,options)):null}return function(view,params){function onVerticalSwipe(e,elem,data){var player=currentPlayer;if(player){var windowSize=dom.getWindowSize();if(supportsBrightnessChange&&data.clientX1?view.querySelector(".btnAudio").classList.remove("hide"):view.querySelector(".btnAudio").classList.add("hide"))):(setPoster(null),Emby.Page.setTitle(""),nowPlayingVolumeSlider.disabled=!0,nowPlayingPositionSlider.disabled=!0,btnFastForward.disabled=!0,btnRewind.disabled=!0,view.querySelector(".btnSubtitles").classList.add("hide"),view.querySelector(".btnAudio").classList.add("hide"),view.querySelector(".osdTitle").innerHTML="",view.querySelector(".osdTitleSmall").innerHTML="",void(view.querySelector(".osdMediaInfo").innerHTML=""))}function setTitle(item){var url=logoImageUrl(item,connectionManager.getApiClient(item.ServerId),{});url||Emby.Page.setTitle("")}function setPoster(item,secondaryItem){var osdPoster=view.querySelector(".osdPoster");if(item){var imgUrl=seriesImageUrl(item,{type:"Primary"})||seriesImageUrl(item,{type:"Thumb"})||imageUrl(item,{type:"Primary"});if(!imgUrl&&secondaryItem&&(imgUrl=seriesImageUrl(secondaryItem,{type:"Primary"})||seriesImageUrl(secondaryItem,{type:"Thumb"})||imageUrl(secondaryItem,{type:"Primary"})),imgUrl)return void(osdPoster.innerHTML='')}osdPoster.innerHTML=""}function isOsdOpen(){return _osdOpen}function showOsd(){slideDownToShow(headerElement),slideUpToShow(osdBottomElement),startHideTimer()}function hideOsd(){slideUpToHide(headerElement),slideDownToHide(osdBottomElement)}function startHideTimer(){stopHideTimer(),hideTimeout=setTimeout(hideOsd,5e3)}function stopHideTimer(){hideTimeout&&(clearTimeout(hideTimeout),hideTimeout=null)}function slideDownToShow(elem){elem.classList.remove("osdHeader-hidden")}function slideUpToHide(elem){elem.classList.add("osdHeader-hidden")}function clearBottomPanelAnimationEventListeners(elem){dom.removeEventListener(elem,transitionEndEventName,onSlideDownComplete,{once:!0})}function slideUpToShow(elem){_osdOpen||(_osdOpen=!0,clearBottomPanelAnimationEventListeners(elem),elem.classList.remove("hide"),void elem.offsetWidth,elem.classList.remove("videoOsdBottom-hidden"),setTimeout(function(){focusManager.focus(elem.querySelector(".btnPause"))},50),view.dispatchEvent(new CustomEvent("video-osd-show",{bubbles:!0,cancelable:!1})))}function onSlideDownComplete(e){var elem=e.target;elem.classList.add("hide"),dom.removeEventListener(elem,transitionEndEventName,onSlideDownComplete,{once:!0}),view.dispatchEvent(new CustomEvent("video-osd-hide",{bubbles:!0,cancelable:!1}))}function slideDownToHide(elem){_osdOpen&&(clearBottomPanelAnimationEventListeners(elem),void elem.offsetWidth,elem.classList.add("videoOsdBottom-hidden"),dom.addEventListener(elem,transitionEndEventName,onSlideDownComplete,{once:!0}),_osdOpen=!1)}function onMouseMove(e){var eventX=e.screenX||0,eventY=e.screenY||0,obj=lastMouseMoveData;return obj?void(Math.abs(eventX-obj.x)<10&&Math.abs(eventY-obj.y)<10||(obj.x=eventX,obj.y=eventY,showOsd())):void(lastMouseMoveData={x:eventX,y:eventY})}function onInputCommand(e){switch(e.detail.command){case"left":isOsdOpen()?showOsd():(e.preventDefault(),playbackManager.rewind());break;case"right":isOsdOpen()?showOsd():(e.preventDefault(),playbackManager.fastForward());break;case"up":case"down":case"select":case"menu":case"info":case"play":case"playpause":case"pause":case"fastforward":case"rewind":case"next":case"previous":showOsd();break;case"record":onRecordingCommand(),showOsd()}}function onRecordingCommand(){var btnRecord=view.querySelector(".btnRecord");btnRecord.classList.contains("hide")||btnRecord.click()}function updateFullscreenIcon(){playbackManager.isFullscreen(currentPlayer)?(view.querySelector(".btnFullscreen").setAttribute("title",globalize.translate("ExitFullscreen")),view.querySelector(".btnFullscreen i").innerHTML=""):(view.querySelector(".btnFullscreen").setAttribute("title",globalize.translate("Fullscreen")),view.querySelector(".btnFullscreen i").innerHTML="")}function onPlayerChange(){var player=playbackManager.getCurrentPlayer();player&&!player.isLocalPlayer?view.querySelector(".btnCast i").innerHTML="":view.querySelector(".btnCast i").innerHTML="",bindToPlayer(player)}function onStateChanged(event,state){var player=this;state.NowPlayingItem&&(isEnabled=!0,updatePlayerStateInternal(event,state),updatePlaylist(player),enableStopOnBack(!0))}function onPlayPauseStateChanged(e){if(isEnabled){var player=this;updatePlayPauseState(player.paused())}}function onVolumeChanged(e){if(isEnabled){var player=this;updatePlayerVolumeState(player.isMuted(),player.getVolume())}}function onPlaybackStart(e,state){console.log("nowplaying event: "+e.type);var player=this;onStateChanged.call(player,e,state)}function onPlaybackStopped(e,state){currentRuntimeTicks=null,comingUpNextDisplayed=!1,hideComingUpNext(),console.log("nowplaying event: "+e.type),"Video"!==state.NextMediaType&&(view.removeEventListener("viewbeforehide",onViewHideStopPlayback),Emby.Page.back())}function bindToPlayer(player){player!==currentPlayer&&(releaseCurrentPlayer(),currentPlayer=player,player&&(playbackManager.getPlayerState(player).then(function(state){onStateChanged.call(player,{type:"init"},state)}),events.on(player,"playbackstart",onPlaybackStart),events.on(player,"playbackstop",onPlaybackStopped),events.on(player,"volumechange",onVolumeChanged),events.on(player,"pause",onPlayPauseStateChanged),events.on(player,"playing",onPlayPauseStateChanged),events.on(player,"timeupdate",onTimeUpdate),events.on(player,"fullscreenchange",updateFullscreenIcon),hideComingUpNext()))}function releaseCurrentPlayer(){var player=currentPlayer;player&&(events.off(player,"playbackstart",onPlaybackStart),events.off(player,"playbackstop",onPlaybackStopped),events.off(player,"volumechange",onVolumeChanged),events.off(player,"pause",onPlayPauseStateChanged),events.off(player,"playing",onPlayPauseStateChanged),events.off(player,"timeupdate",onTimeUpdate),events.off(player,"fullscreenchange",updateFullscreenIcon),currentPlayer=null),hideComingUpNext()}function onTimeUpdate(e){if(isEnabled){var now=(new Date).getTime();if(!(now-lastUpdateTime<700)){lastUpdateTime=now;var player=this;currentRuntimeTicks=playbackManager.duration(player);var currentTime=playbackManager.currentTime(player);updateTimeDisplay(currentTime,currentRuntimeTicks),refreshProgramInfoIfNeeded(player),showComingUpNextIfNeeded(player,currentTime,currentRuntimeTicks)}}}function showComingUpNextIfNeeded(player,currentTimeTicks,runtimeTicks){if(runtimeTicks&¤tTimeTicks){var showAtSecondsLeft=45,showAtTicks=runtimeTicks-1e3*showAtSecondsLeft*1e4;currentTimeTicks>=showAtTicks&&showComingUpNext(player,currentTimeTicks,runtimeTicks)}}function showComingUpNext(player,currentTimeTicks,runtimeTicks){comingUpNextDisplayed||(comingUpNextDisplayed=!0)}function hideComingUpNext(){}function refreshProgramInfoIfNeeded(player){var item=currentItem;if("TvChannel"===item.Type){var program=item.CurrentProgram;if(program&&program.EndDate)try{var endDate=datetime.parseISO8601Date(program.EndDate);(new Date).getTime()>=endDate.getTime()&&(console.log("program info needs to be refreshed"),playbackManager.getPlayerState(player).then(function(state){onStateChanged.call(player,{type:"init"},state)}))}catch(e){console.log("Error parsing date: "+program.EndDate)}}}function updatePlayPauseState(isPaused){isPaused?view.querySelector(".btnPause i").innerHTML="":view.querySelector(".btnPause i").innerHTML=""}function updatePlayerStateInternal(event,state){var playerInfo=playbackManager.getPlayerInfo(),playState=state.PlayState||{};updatePlayPauseState(playState.IsPaused);var supportedCommands=playerInfo.supportedCommands;currentPlayerSupportedCommands=supportedCommands,supportsBrightnessChange=supportedCommands.indexOf("SetBrightness")!==-1,updatePlayerVolumeState(playState.IsMuted,playState.VolumeLevel),nowPlayingPositionSlider&&!nowPlayingPositionSlider.dragging&&(nowPlayingPositionSlider.disabled=!playState.CanSeek),btnFastForward.disabled=!playState.CanSeek,btnRewind.disabled=!playState.CanSeek;var nowPlayingItem=state.NowPlayingItem||{};updateTimeDisplay(playState.PositionTicks,nowPlayingItem.RunTimeTicks),updateNowPlayingInfo(state),state.MediaSource&&state.MediaSource.SupportsTranscoding&&supportedCommands.indexOf("SetMaxStreamingBitrate")!==-1?view.querySelector(".btnVideoOsdSettings").classList.remove("hide"):view.querySelector(".btnVideoOsdSettings").classList.add("hide"),supportedCommands.indexOf("ToggleFullscreen")===-1?view.querySelector(".btnFullscreen").classList.add("hide"):view.querySelector(".btnFullscreen").classList.remove("hide"),supportedCommands.indexOf("PictureInPicture")===-1?view.querySelector(".btnPip").classList.add("hide"):view.querySelector(".btnPip").classList.remove("hide"),updateFullscreenIcon()}function updateTimeDisplay(positionTicks,runtimeTicks){if(nowPlayingPositionSlider&&!nowPlayingPositionSlider.dragging){if(runtimeTicks){var pct=positionTicks/runtimeTicks;pct*=100,nowPlayingPositionSlider.value=pct}else nowPlayingPositionSlider.value=0;runtimeTicks&&null!=positionTicks?endsAtText.innerHTML="  -  "+mediaInfo.getEndsAtFromPosition(runtimeTicks,positionTicks,!0):endsAtText.innerHTML=""}updateTimeText(nowPlayingPositionText,positionTicks),updateTimeText(nowPlayingDurationText,runtimeTicks,!0)}function updatePlayerVolumeState(isMuted,volumeLevel){var supportedCommands=currentPlayerSupportedCommands,showMuteButton=!0,showVolumeSlider=!0;supportedCommands.indexOf("Mute")===-1&&(showMuteButton=!1),supportedCommands.indexOf("SetVolume")===-1&&(showVolumeSlider=!1),currentPlayer.isLocalPlayer&&appHost.supports("physicalvolumecontrol")&&(showMuteButton=!1,showVolumeSlider=!1),isMuted?(view.querySelector(".buttonMute").setAttribute("title",globalize.translate("Unmute")),view.querySelector(".buttonMute i").innerHTML=""):(view.querySelector(".buttonMute").setAttribute("title",globalize.translate("Mute")),view.querySelector(".buttonMute i").innerHTML=""),showMuteButton?view.querySelector(".buttonMute").classList.remove("hide"):view.querySelector(".buttonMute").classList.add("hide"),nowPlayingVolumeSlider&&(showVolumeSlider?nowPlayingVolumeSliderContainer.classList.remove("hide"):nowPlayingVolumeSliderContainer.classList.add("hide"),nowPlayingVolumeSlider.dragging||(nowPlayingVolumeSlider.value=volumeLevel||0))}function updatePlaylist(player){var btnPreviousTrack=view.querySelector(".btnPreviousTrack"),btnNextTrack=view.querySelector(".btnNextTrack");btnPreviousTrack.classList.remove("hide"),btnNextTrack.classList.remove("hide"),btnNextTrack.disabled=!1,btnPreviousTrack.disabled=!1}function updateTimeText(elem,ticks,divider){if(null==ticks)return void(elem.innerHTML="");var html=datetime.getDisplayRunningTime(ticks);divider&&(html=" / "+html),elem.innerHTML=html}function onSettingsButtonClick(e){var btn=this;require(["playerSettingsMenu"],function(playerSettingsMenu){playerSettingsMenu.show({mediaType:"Video",player:currentPlayer,positionTo:btn})})}function showAudioTrackSelection(){var player=currentPlayer,audioTracks=playbackManager.audioTracks(player),currentIndex=playbackManager.getAudioStreamIndex(player),menuItems=audioTracks.map(function(stream){var opt={name:stream.DisplayTitle,id:stream.Index};return stream.Index===currentIndex&&(opt.selected=!0),opt}),positionTo=this;require(["actionsheet"],function(actionsheet){actionsheet.show({items:menuItems,title:globalize.translate("Audio"),positionTo:positionTo}).then(function(id){var index=parseInt(id);index!==currentIndex&&playbackManager.setAudioStreamIndex(index,currentPlayer)})})}function showSubtitleTrackSelection(){var player=currentPlayer,streams=playbackManager.subtitleTracks(player),currentIndex=playbackManager.getSubtitleStreamIndex(player);null==currentIndex&&(currentIndex=-1),streams.unshift({Index:-1,DisplayTitle:globalize.translate("Off")});var menuItems=streams.map(function(stream){var opt={name:stream.DisplayTitle,id:stream.Index};return stream.Index===currentIndex&&(opt.selected=!0),opt}),positionTo=this;require(["actionsheet"],function(actionsheet){actionsheet.show({title:globalize.translate("Subtitles"),items:menuItems,positionTo:positionTo}).then(function(id){var index=parseInt(id);index!==currentIndex&&playbackManager.setSubtitleStreamIndex(index,currentPlayer)})})}function onWindowKeyDown(e){32!==e.keyCode||isOsdOpen()||(playbackManager.playPause(currentPlayer),showOsd())}function getImgUrl(item,chapter,index,maxWidth,apiClient){return chapter.ImageTag?apiClient.getScaledImageUrl(item.Id,{maxWidth:maxWidth,tag:chapter.ImageTag,type:"Chapter",index:index}):null}function getChapterBubbleHtml(apiClient,item,chapters,positionTicks){for(var chapter,index=-1,i=0,length=chapters.length;i=currentChapter.StartPositionTicks&&(chapter=currentChapter,index=i)}if(!chapter)return null;var src=getImgUrl(item,chapter,index,400,apiClient);if(src){var html='
';return html+='',html+='
',html+='
',html+=chapter.Name,html+="
",html+='

',html+=datetime.getDisplayRunningTime(positionTicks),html+="

",html+="
",html+="
"}return null}function onViewHideStopPlayback(){if(playbackManager.isPlayingVideo()){var player=currentPlayer;view.removeEventListener("viewbeforehide",onViewHideStopPlayback),releaseCurrentPlayer(),playbackManager.stop(player)}}function enableStopOnBack(enabled){view.removeEventListener("viewbeforehide",onViewHideStopPlayback),enabled&&playbackManager.isPlayingVideo(currentPlayer)&&view.addEventListener("viewbeforehide",onViewHideStopPlayback)}var currentPlayer,comingUpNextDisplayed,isEnabled,currentItem,recordingButtonManager,supportsBrightnessChange,hideTimeout,lastMouseMoveData,self=this,currentPlayerSupportedCommands=[],currentRuntimeTicks=0,lastUpdateTime=0,nowPlayingVolumeSlider=view.querySelector(".osdVolumeSlider"),nowPlayingVolumeSliderContainer=view.querySelector(".osdVolumeSliderContainer"),nowPlayingPositionSlider=view.querySelector(".osdPositionSlider"),nowPlayingPositionText=view.querySelector(".osdPositionText"),nowPlayingDurationText=view.querySelector(".osdDurationText"),endsAtText=view.querySelector(".endsAtText"),btnRewind=view.querySelector(".btnRewind"),btnFastForward=view.querySelector(".btnFastForward"),transitionEndEventName=dom.whichTransitionEvent(),headerElement=document.querySelector(".skinHeader"),osdBottomElement=document.querySelector(".videoOsdBottom"),_osdOpen=!0;view.addEventListener("viewbeforeshow",function(e){headerElement.classList.add("osdHeader"),Emby.Page.setTransparency("full")}),view.addEventListener("viewshow",function(e){events.on(playbackManager,"playerchange",onPlayerChange),bindToPlayer(playbackManager.getCurrentPlayer()),dom.addEventListener(document,"mousemove",onMouseMove,{passive:!0}),document.body.classList.add("autoScrollY"),showOsd(),inputManager.on(window,onInputCommand),dom.addEventListener(window,"keydown",onWindowKeyDown,{passive:!0})}),view.addEventListener("viewbeforehide",function(){dom.removeEventListener(window,"keydown",onWindowKeyDown,{passive:!0}),stopHideTimer(),headerElement.classList.remove("osdHeader"),headerElement.classList.remove("osdHeader-hidden"),dom.removeEventListener(document,"mousemove",onMouseMove,{passive:!0}),document.body.classList.remove("autoScrollY"),inputManager.off(window,onInputCommand),events.off(playbackManager,"playerchange",onPlayerChange),releaseCurrentPlayer()}),appHost.supports("remotecontrol")&&!layoutManager.tv&&view.querySelector(".btnCast").classList.remove("hide"),view.querySelector(".btnCast").addEventListener("click",function(){var btn=this;require(["playerSelectionMenu"],function(playerSelectionMenu){playerSelectionMenu.show(btn)})}),view.querySelector(".btnFullscreen").addEventListener("click",function(){playbackManager.toggleFullscreen(currentPlayer)}),view.querySelector(".btnPip").addEventListener("click",function(){playbackManager.togglePictureInPicture(currentPlayer)}),view.querySelector(".btnVideoOsdSettings").addEventListener("click",onSettingsButtonClick),view.addEventListener("viewhide",function(){headerElement.classList.remove("hide")}),view.addEventListener("viewhide",function(){self.touchHelper&&(self.touchHelper.destroy(),self.touchHelper=null)}),view.addEventListener("viewdestroy",function(){recordingButtonManager&&(recordingButtonManager.destroy(),recordingButtonManager=null)}),view.querySelector(".pageContainer").addEventListener("click",function(){layoutManager.mobile||playbackManager.playPause(currentPlayer),showOsd()}),view.querySelector(".buttonMute").addEventListener("click",function(){playbackManager.toggleMute(currentPlayer)}),nowPlayingVolumeSlider.addEventListener("change",function(){playbackManager.setVolume(this.value,currentPlayer)}),nowPlayingPositionSlider.addEventListener("change",function(){if(currentPlayer){var newPercent=parseFloat(this.value);playbackManager.seekPercent(newPercent,currentPlayer)}}),nowPlayingPositionSlider.getBubbleHtml=function(value){if(showOsd(),!currentRuntimeTicks)return"--:--";var ticks=currentRuntimeTicks;ticks/=100,ticks*=value;var item=currentItem;if(item&&item.Chapters&&item.Chapters.length&&item.Chapters[0].ImageTag){var html=getChapterBubbleHtml(connectionManager.getApiClient(item.ServerId),item,item.Chapters,ticks);if(html)return html}return'

'+datetime.getDisplayRunningTime(ticks)+"

"},view.querySelector(".btnPreviousTrack").addEventListener("click",function(){playbackManager.previousChapter(currentPlayer)}),view.querySelector(".btnPause").addEventListener("click",function(){playbackManager.playPause(currentPlayer)}),view.querySelector(".btnNextTrack").addEventListener("click",function(){playbackManager.nextChapter(currentPlayer)}),btnRewind.addEventListener("click",function(){playbackManager.rewind(currentPlayer)}),btnFastForward.addEventListener("click",function(){playbackManager.fastForward(currentPlayer)}),view.querySelector(".btnAudio").addEventListener("click",showAudioTrackSelection),view.querySelector(".btnSubtitles").addEventListener("click",showSubtitleTrackSelection),browser.touch&&initSwipeEvents()}}); \ No newline at end of file