mirror of
https://github.com/jellyfin/jellyfin-web.git
synced 2024-11-18 11:28:23 -07:00
3 lines
64 KiB
JavaScript
3 lines
64 KiB
JavaScript
define(["events","datetime","appSettings","itemHelper","pluginManager","playQueueManager","userSettings","globalize","connectionManager","loading","serverNotifications","apphost","fullscreenManager","layoutManager"],function(events,datetime,appSettings,itemHelper,pluginManager,PlayQueueManager,userSettings,globalize,connectionManager,loading,serverNotifications,apphost,fullscreenManager,layoutManager){"use strict";function enableLocalPlaylistManagement(player){return!player.getPlaylist&&!!player.isLocalPlayer}function bindToFullscreenChange(player){events.on(fullscreenManager,"fullscreenchange",function(){events.trigger(player,"fullscreenchange")})}function triggerPlayerChange(playbackManagerInstance,newPlayer,newTarget,previousPlayer,previousTargetInfo){(newPlayer||previousPlayer)&&(newTarget&&previousTargetInfo&&newTarget.id===previousTargetInfo.id||events.trigger(playbackManagerInstance,"playerchange",[newPlayer,newTarget,previousPlayer]))}function reportPlayback(state,serverId,method,progressEventName){if(serverId){var info=Object.assign({},state.PlayState);info.ItemId=state.NowPlayingItem.Id,progressEventName&&(info.EventName=progressEventName);var apiClient=connectionManager.getApiClient(serverId);apiClient[method](info)}}function normalizeName(t){return t.toLowerCase().replace(" ","")}function getItemsForPlayback(serverId,query){var apiClient=connectionManager.getApiClient(serverId);if(query.Ids&&1===query.Ids.split(",").length){var itemId=query.Ids.split(",");return apiClient.getItem(apiClient.getCurrentUserId(),itemId).then(function(item){return{Items:[item],TotalRecordCount:1}})}return query.Limit=query.Limit||200,query.Fields="MediaSources,Chapters",query.ExcludeLocationTypes="Virtual",query.EnableTotalRecordCount=!1,apiClient.getItems(apiClient.getCurrentUserId(),query)}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 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 isAutomaticPlayer(player){return!!player.isLocalPlayer}function getAutomaticPlayers(instance){var player=instance._currentPlayer;return player&&!isAutomaticPlayer(player)?[player]:instance.getPlayers().filter(isAutomaticPlayer)}function isServerItem(item){return!!item.Id}function enableIntros(item){return"Video"===item.MediaType&&("TvChannel"!==item.Type&&("InProgress"!==item.Status&&isServerItem(item)))}function getIntros(firstItem,apiClient,options){return!options.startPositionTicks&&options.fullscreen!==!1&&enableIntros(firstItem)&&userSettings.enableCinemaMode()?apiClient.getIntros(firstItem.Id):Promise.resolve({Items:[]})}function getAudioMaxValues(deviceProfile){var maxAudioSampleRate=null,maxAudioBitDepth=null;return deviceProfile.CodecProfiles.map(function(codecProfile){"Audio"===codecProfile.Type&&(codecProfile.Conditions||[]).map(function(condition){"LessThanEqual"===condition.Condition&&"AudioBitDepth"===condition.Property&&(maxAudioBitDepth=condition.Value),"LessThanEqual"===condition.Condition&&"AudioSampleRate"===condition.Property&&(maxAudioSampleRate=condition.Value)})}),{maxAudioSampleRate:maxAudioSampleRate,maxAudioBitDepth:maxAudioBitDepth}}function getAudioStreamUrl(item,transcodingProfile,directPlayContainers,maxBitrate,apiClient,maxAudioSampleRate,maxAudioBitDepth,startPosition){var url="Audio/"+item.Id+"/universal";return startingPlaySession++,apiClient.getUrl(url,{UserId:apiClient.getCurrentUserId(),DeviceId:apiClient.deviceId(),MaxStreamingBitrate:maxBitrate||appSettings.maxStreamingBitrate(),Container:directPlayContainers,TranscodingContainer:transcodingProfile.Container||null,TranscodingProtocol:transcodingProfile.Protocol||null,AudioCodec:transcodingProfile.AudioCodec,MaxAudioSampleRate:maxAudioSampleRate,MaxAudioBitDepth:maxAudioBitDepth,api_key:apiClient.accessToken(),PlaySessionId:startingPlaySession,StartTimeTicks:startPosition||0,EnableRedirection:!0,EnableRemoteMedia:apphost.supports("remotemedia")})}function getAudioStreamUrlFromDeviceProfile(item,deviceProfile,maxBitrate,apiClient,startPosition){var transcodingProfile=deviceProfile.TranscodingProfiles.filter(function(p){return"Audio"===p.Type&&"Streaming"===p.Context})[0],directPlayContainers="";deviceProfile.DirectPlayProfiles.map(function(p){"Audio"===p.Type&&(directPlayContainers?directPlayContainers+=","+p.Container:directPlayContainers=p.Container)});var maxValues=getAudioMaxValues(deviceProfile);return getAudioStreamUrl(item,transcodingProfile,directPlayContainers,maxBitrate,apiClient,maxValues.maxAudioSampleRate,maxValues.maxAudioBitDepth,startPosition)}function getStreamUrls(items,deviceProfile,maxBitrate,apiClient,startPosition){var audioTranscodingProfile=deviceProfile.TranscodingProfiles.filter(function(p){return"Audio"===p.Type&&"Streaming"===p.Context})[0],audioDirectPlayContainers="";deviceProfile.DirectPlayProfiles.map(function(p){"Audio"===p.Type&&(audioDirectPlayContainers?audioDirectPlayContainers+=","+p.Container:audioDirectPlayContainers=p.Container)});for(var maxValues=getAudioMaxValues(deviceProfile),supportsUniversalAudio=apiClient.isMinServerVersion("3.2.17.5"),streamUrls=[],i=0,length=items.length;i<length;i++){var streamUrl,item=items[i];supportsUniversalAudio&&"Audio"===item.MediaType&&(streamUrl=getAudioStreamUrl(item,audioTranscodingProfile,audioDirectPlayContainers,maxBitrate,apiClient,maxValues.maxAudioSampleRate,maxValues.maxAudioBitDepth,startPosition)),streamUrls.push(streamUrl||""),0===i&&(startPosition=0)}return Promise.resolve(streamUrls)}function setStreamUrls(items,deviceProfile,maxBitrate,apiClient,startPosition){return getStreamUrls(items,deviceProfile,maxBitrate,apiClient,startPosition).then(function(streamUrls){for(var i=0,length=items.length;i<length;i++){var item=items[i],streamUrl=streamUrls[i];streamUrl&&(item.PresetMediaSource={StreamUrl:streamUrl,Id:item.Id,MediaStreams:[],RunTimeTicks:item.RunTimeTicks})}})}function getPlaybackInfo(player,apiClient,item,deviceProfile,maxBitrate,startPosition,mediaSource,audioStreamIndex,subtitleStreamIndex,liveStreamId,enableDirectPlay,enableDirectStream,allowVideoStreamCopy,allowAudioStreamCopy){if(!itemHelper.isLocalItem(item)&&"Audio"===item.MediaType&&apiClient.isMinServerVersion("3.2.17.5"))return Promise.resolve({MediaSources:[{StreamUrl:getAudioStreamUrlFromDeviceProfile(item,deviceProfile,maxBitrate,apiClient,startPosition),Id:item.Id,MediaStreams:[],RunTimeTicks:item.RunTimeTicks}]});var itemId=item.Id,query={UserId:apiClient.getCurrentUserId(),StartTimeTicks:startPosition||0,AutoOpenLiveStream:!0};return null!=audioStreamIndex&&(query.AudioStreamIndex=audioStreamIndex),null!=subtitleStreamIndex&&(query.SubtitleStreamIndex=subtitleStreamIndex),null!=enableDirectPlay&&(query.EnableDirectPlay=enableDirectPlay),null!=enableDirectStream&&(query.EnableDirectStream=enableDirectStream),null!=allowVideoStreamCopy&&(query.AllowVideoStreamCopy=allowVideoStreamCopy),null!=allowAudioStreamCopy&&(query.AllowAudioStreamCopy=allowAudioStreamCopy),mediaSource&&(query.MediaSourceId=mediaSource.Id),liveStreamId&&(query.LiveStreamId=liveStreamId),maxBitrate&&(query.MaxStreamingBitrate=maxBitrate),player.enableMediaProbe&&!player.enableMediaProbe(item)&&(query.EnableMediaProbe=!1),query.EnableDirectStream!==!1&&player.supportsPlayMethod&&!player.supportsPlayMethod("DirectStream",item)&&(query.EnableDirectStream=!1),apiClient.getPlaybackInfo(itemId,query,deviceProfile)}function getOptimalMediaSource(apiClient,item,versions){var promises=versions.map(function(v){return supportsDirectPlay(apiClient,item,v)});return promises.length?Promise.all(promises).then(function(results){for(var i=0,length=versions.length;i<length;i++)versions[i].enableDirectPlay=results[i]||!1;var optimalVersion=versions.filter(function(v){return v.enableDirectPlay})[0];return optimalVersion||(optimalVersion=versions.filter(function(v){return v.SupportsDirectStream})[0]),optimalVersion=optimalVersion||versions.filter(function(s){return s.SupportsTranscoding})[0],optimalVersion||versions[0]}):Promise.reject()}function getLiveStream(player,apiClient,item,playSessionId,deviceProfile,maxBitrate,startPosition,mediaSource,audioStreamIndex,subtitleStreamIndex){var postData={DeviceProfile:deviceProfile,OpenToken:mediaSource.OpenToken},query={UserId:apiClient.getCurrentUserId(),StartTimeTicks:startPosition||0,ItemId:item.Id,PlaySessionId:playSessionId};return maxBitrate&&(query.MaxStreamingBitrate=maxBitrate),null!=audioStreamIndex&&(query.AudioStreamIndex=audioStreamIndex),null!=subtitleStreamIndex&&(query.SubtitleStreamIndex=subtitleStreamIndex),query.EnableDirectStream!==!1&&player.supportsPlayMethod&&!player.supportsPlayMethod("DirectStream",item)&&(query.EnableDirectStream=!1),apiClient.ajax({url:apiClient.getUrl("LiveStreams/Open",query),type:"POST",data:JSON.stringify(postData),contentType:"application/json",dataType:"json"})}function isHostReachable(mediaSource,apiClient){var url=mediaSource.Path,isServerAddress=0===url.toLowerCase().replace("https:","http").indexOf(apiClient.serverAddress().toLowerCase().replace("https:","http").substring(0,14));return isServerAddress?Promise.resolve(!0):mediaSource.IsRemote?Promise.resolve(!0):Promise.resolve(!1)}function supportsDirectPlay(apiClient,item,mediaSource){var isFolderRip="BluRay"===mediaSource.VideoType||"Dvd"===mediaSource.VideoType||"HdDvd"===mediaSource.VideoType;if(mediaSource.SupportsDirectPlay||isFolderRip){if(mediaSource.IsRemote&&("TvChannel"===item.Type||"Trailer"===item.Type)&&!apphost.supports("remotemedia"))return Promise.resolve(!1);if("Http"===mediaSource.Protocol&&!mediaSource.RequiredHttpHeaders.length)return mediaSource.SupportsDirectStream||mediaSource.SupportsTranscoding?isHostReachable(mediaSource,apiClient):Promise.resolve(!0);if("File"===mediaSource.Protocol)return new Promise(function(resolve,reject){require(["filesystem"],function(filesystem){var method=isFolderRip?"directoryExists":"fileExists";filesystem[method](mediaSource.Path).then(function(){resolve(!0)},function(){resolve(!1)})})})}return Promise.resolve(!1)}function validatePlaybackInfoResult(instance,result){return!result.ErrorCode||(showPlaybackInfoErrorMessage(instance,result.ErrorCode),!1)}function showPlaybackInfoErrorMessage(instance,errorCode,playNextTrack){require(["alert"],function(alert){alert({text:globalize.translate("sharedcomponents#PlaybackError"+errorCode),title:globalize.translate("sharedcomponents#HeaderPlaybackError")}).then(function(){playNextTrack&&instance.nextTrack()})})}function normalizePlayOptions(playOptions){playOptions.fullscreen=playOptions.fullscreen!==!1}function getNowPlayingItemForReporting(player,item,mediaSource){var nowPlayingItem=Object.assign({},item);return mediaSource&&(nowPlayingItem.RunTimeTicks=mediaSource.RunTimeTicks,nowPlayingItem.MediaStreams=mediaSource.MediaStreams,nowPlayingItem.MediaSources=null),nowPlayingItem.RunTimeTicks=nowPlayingItem.RunTimeTicks||1e4*player.duration(),nowPlayingItem}function displayPlayerInLocalGroup(player){return player.isLocalPlayer}function createTarget(instance,player){return{name:player.name,id:player.id,playerName:player.name,playableMediaTypes:["Audio","Video","Game","Photo","Book"].map(player.canPlayMediaType),isLocalPlayer:player.isLocalPlayer,supportedCommands:instance.getSupportedCommands(player)}}function getPlayerTargets(player){return player.getTargets?player.getTargets():Promise.resolve([createTarget(player)])}function PlaybackManager(){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 removeCurrentPlayer(player){var previousPlayer=self._currentPlayer;previousPlayer&&player.id!==previousPlayer.id||setCurrentPlayerInternal(null)}function setCurrentPlayerInternal(player,targetInfo){var previousPlayer=self._currentPlayer,previousTargetInfo=currentTargetInfo;if(player&&!targetInfo&&player.isLocalPlayer&&(targetInfo=createTarget(self,player)),player&&!targetInfo)throw new Error("targetInfo cannot be null");currentPairingId=null,self._currentPlayer=player,currentTargetInfo=targetInfo,targetInfo&&console.log("Active player: "+JSON.stringify(targetInfo)),player&&player.isLocalPlayer&&(lastLocalPlayer=player),previousPlayer&&self.endPlayerUpdates(previousPlayer),player&&self.beginPlayerUpdates(player),triggerPlayerChange(self,player,targetInfo,previousPlayer,previousTargetInfo)}function canPlayerSeek(player){if(!player)throw new Error("player cannot be null");var playerData=getPlayerData(player),currentSrc=(playerData.streamInfo.url||"").toLowerCase();if(currentSrc.indexOf(".m3u8")!==-1)return!0;if(player.seekable)return player.seekable();var isPlayMethodTranscode="Transcode"===self.playMethod(player);return!isPlayMethodTranscode&&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=self.playSessionId(player),currentItem=self.currentItem(player);player.getDeviceProfile(currentItem,{isRetry:params.EnableDirectPlay===!1}).then(function(deviceProfile){var audioStreamIndex=null==params.AudioStreamIndex?getPlayerData(player).audioStreamIndex:params.AudioStreamIndex,subtitleStreamIndex=null==params.SubtitleStreamIndex?getPlayerData(player).subtitleStreamIndex:params.SubtitleStreamIndex,currentMediaSource=self.currentMediaSource(player),apiClient=connectionManager.getApiClient(currentItem.ServerId);ticks&&(ticks=parseInt(ticks));var maxBitrate=params.MaxStreamingBitrate||self.getMaxStreamingBitrate(player);getPlaybackInfo(player,apiClient,currentItem,deviceProfile,maxBitrate,ticks,currentMediaSource,audioStreamIndex,subtitleStreamIndex,liveStreamId,params.EnableDirectPlay,params.EnableDirectStream,params.AllowVideoStreamCopy,params.AllowAudioStreamCopy).then(function(result){if(validatePlaybackInfoResult(self,result)){currentMediaSource=result.MediaSources[0];var streamInfo=createStreamInfo(apiClient,currentItem.MediaType,currentItem,currentMediaSource,ticks);if(streamInfo.fullscreen=currentPlayOptions.fullscreen,!streamInfo.url)return showPlaybackInfoErrorMessage(self,"NoCompatibleStream"),void self.nextTrack();getPlayerData(player).subtitleStreamIndex=subtitleStreamIndex,getPlayerData(player).audioStreamIndex=audioStreamIndex,getPlayerData(player).maxStreamingBitrate=maxBitrate,changeStreamToUrl(apiClient,player,playSessionId,streamInfo)}})})}function changeStreamToUrl(apiClient,player,playSessionId,streamInfo,newPositionTicks){var playerData=getPlayerData(player);playerData.isChangingStream=!0,"Video"===playerData.MediaType?apiClient.stopActiveEncodings(playSessionId).then(function(){setSrcIntoPlayer(apiClient,player,streamInfo)}):setSrcIntoPlayer(apiClient,player,streamInfo)}function setSrcIntoPlayer(apiClient,player,streamInfo){player.play(streamInfo).then(function(){var playerData=getPlayerData(player);playerData.isChangingStream=!1,playerData.streamInfo=streamInfo,sendProgressUpdate(player,"timeupdate")},function(e){onPlaybackError.call(player,e,{type:"mediadecodeerror"})})}function 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"}):"Photo"===firstItem.MediaType?promise=getItemsForPlayback(serverId,{ParentId:firstItem.ParentId,Filters:"IsNotFolder",Recursive:!0,SortBy:"SortName",MediaTypes:"Photo,Video"}).then(function(result){var items=result.Items,index=items.map(function(i){return i.Id}).indexOf(firstItem.Id);return index===-1&&(index=0),options.playStartIndex=index,Promise.resolve(result)}):"MusicGenre"===firstItem.Type?promise=getItemsForPlayback(serverId,{GenreIds:firstItem.Id,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 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||self._currentPlayer).currentTime()),streamInfo=getPlayerData(player).streamInfo;return streamInfo&&(playerTime+=getPlayerData(player).streamInfo.transcodingOffsetTicks||0),playerTime}function playPhotos(items,options,user){var playStartIndex=options.playStartIndex||0,player=getPlayer(items[playStartIndex],options);return loading.hide(),options.items=items,player.play(options)}function playWithIntros(items,options,user){var playStartIndex=options.playStartIndex||0,firstItem=items[playStartIndex];if("Photo"===firstItem.MediaType)return playPhotos(items,options,user);var apiClient=connectionManager.getApiClient(firstItem.ServerId);return getIntros(firstItem,apiClient,options).then(function(intros){return items=intros.Items.concat(items),currentPlayOptions=options,options.items=items,playInternal(items[0],options,function(){self._playQueueManager.setPlaylist(items),setPlaylistState(items[playStartIndex].PlaylistItemId,playStartIndex),loading.hide()})})}function setPlaylistState(playlistItemId,index){isNaN(index)||self._playQueueManager.setPlaylistState(playlistItemId,index)}function playInternal(item,playOptions,onPlaybackStartedFn){return item.IsPlaceHolder?(loading.hide(),showPlaybackInfoErrorMessage(self,"PlaceHolder",!0),Promise.reject()):(normalizePlayOptions(playOptions),playOptions.isFirstItem?playOptions.isFirstItem=!1:playOptions.isFirstItem=!0,runInterceptors(item,playOptions).then(function(){if(playOptions.fullscreen&&loading.show(),"Video"===item.MediaType&&isServerItem(item)&&appSettings.enableAutomaticBitrateDetection()){var apiClient=connectionManager.getApiClient(item.ServerId);return apiClient.detectBitrate().then(function(bitrate){return appSettings.maxStreamingBitrate(bitrate),playAfterBitrateDetect(connectionManager,bitrate,item,playOptions,onPlaybackStartedFn)},function(){return playAfterBitrateDetect(connectionManager,appSettings.maxStreamingBitrate(),item,playOptions,onPlaybackStartedFn)})}return playAfterBitrateDetect(connectionManager,appSettings.maxStreamingBitrate(),item,playOptions,onPlaybackStartedFn)},function(){var player=self._currentPlayer;return player&&(destroyPlayer(player),removeCurrentPlayer(player)),events.trigger(self,"playbackcancelled"),Promise.reject()}))}function destroyPlayer(player){player.destroy(),releaseResourceLocks(player)}function runInterceptors(item,playOptions){return new Promise(function(resolve,reject){var interceptors=pluginManager.ofType("preplayintercept");if(interceptors.sort(function(a,b){return(a.order||0)-(b.order||0)}),!interceptors.length)return void resolve();loading.hide();var options=Object.assign({},playOptions);options.mediaType=item.MediaType,options.item=item,runNextPrePlay(interceptors,0,options,resolve,reject)})}function runNextPrePlay(interceptors,index,options,resolve,reject){if(index>=interceptors.length)return void resolve();var interceptor=interceptors[index];interceptor.intercept(options).then(function(){runNextPrePlay(interceptors,index+1,options,resolve,reject)},reject)}function sendPlaybackListToPlayer(player,items,deviceProfile,maxBitrate,apiClient,startPosition){return setStreamUrls(items,deviceProfile,maxBitrate,apiClient,startPosition).then(function(){return loading.hide(),player.play({items:items})})}function playAfterBitrateDetect(connectionManager,maxBitrate,item,playOptions,onPlaybackStartedFn){var promise,startPosition=playOptions.startPositionTicks,player=getPlayer(item,playOptions),activePlayer=self._currentPlayer;return activePlayer?(self._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 player&&!enableLocalPlaylistManagement(player)?sendPlaybackListToPlayer(player,playOptions.items,deviceProfile,maxBitrate,apiClient,startPosition):getPlaybackMediaSource(player,apiClient,deviceProfile,maxBitrate,item,startPosition).then(function(mediaSource){var streamInfo=createStreamInfo(apiClient,item.MediaType,item,mediaSource,startPosition);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 createStreamInfo(apiClient,type,item,mediaSource,startPosition,forceTranscoding){var mediaUrl,contentType,directOptions,transcodingOffsetTicks=0,playerStartPositionTicks=startPosition,liveStreamId=mediaSource.LiveStreamId,playMethod="Transcode",mediaSourceContainer=(mediaSource.Container||"").toLowerCase();"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)))):"Audio"===type?(contentType=getMimeType("audio",mediaSourceContainer),mediaSource.enableDirectPlay&&!forceTranscoding?(mediaUrl=mediaSource.Path,playMethod="DirectPlay"):mediaSource.StreamUrl?(playMethod="Transcode",mediaUrl=mediaSource.StreamUrl):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("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)))):"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),resultInfo}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<length;i++){var textStream=textStreams[i],textStreamUrl=textStream.IsExternalUrl?textStream.DeliveryUrl:apiClient.getUrl(textStream.DeliveryUrl);tracks.push({url:textStreamUrl,language:textStream.Language||"und",isDefault:textStream.Index===mediaSource.DefaultSubtitleStreamIndex,index:textStream.Index,format:textStream.Codec})}return tracks}function getPlaybackMediaSource(player,apiClient,deviceProfile,maxBitrate,item,startPosition,callback){return"Video"===item.MediaType,getPlaybackInfo(player,apiClient,item,deviceProfile,maxBitrate,startPosition).then(function(playbackInfoResult){return validatePlaybackInfoResult(self,playbackInfoResult)?getOptimalMediaSource(apiClient,item,playbackInfoResult.MediaSources).then(function(mediaSource){return mediaSource?mediaSource.RequiresOpening&&!mediaSource.LiveStreamId?getLiveStream(player,apiClient,item,playbackInfoResult.PlaySessionId,deviceProfile,maxBitrate,startPosition,mediaSource,null,null).then(function(openLiveStreamResult){return supportsDirectPlay(apiClient,item,openLiveStreamResult.MediaSource).then(function(result){return openLiveStreamResult.MediaSource.enableDirectPlay=result,openLiveStreamResult.MediaSource})}):mediaSource:(showPlaybackInfoErrorMessage(self,"NoCompatibleStream"),Promise.reject())}):Promise.reject()})}function getPlayer(item,playOptions){var serverItem=isServerItem(item);return getAutomaticPlayers(self).filter(function(p){if(p.canPlayMediaType(item.MediaType)){if(serverItem)return!p.canPlayItem||p.canPlayItem(item,playOptions);if(p.canPlayUrl)return p.canPlayUrl(item.Url)}return!1})[0]}function queue(options,mode,player){if(player=player||self._currentPlayer,!player)return self.play(options);if(options.items)return translateItemsForPlayback(options.items,options).then(function(items){queueAll(items,mode,player)});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,player)})})}function queueAll(items,mode,player){if(items.length){var queueDirectToPlayer=player&&!enableLocalPlaylistManagement(player);if(queueDirectToPlayer){var apiClient=connectionManager.getApiClient(items[0].ServerId);return void player.getDeviceProfile(items[0]).then(function(profile){setStreamUrls(items,profile,self.getMaxStreamingBitrate(player),apiClient,0).then(function(){"next"===mode?player.queueNext(items):player.queue(items)})})}"next"===mode?self._playQueueManager.queueNext(items):self._playQueueManager.queue(items)}}function onPlaybackStarted(player,playOptions,streamInfo,mediaSource){if(!player)throw new Error("player cannot be null");setCurrentPlayerInternal(player);var playerData=getPlayerData(player);playerData.streamInfo=streamInfo,streamInfo.playbackStartTimeTicks=1e4*(new Date).getTime(),mediaSource?(playerData.audioStreamIndex=mediaSource.DefaultAudioStreamIndex,playerData.subtitleStreamIndex=mediaSource.DefaultSubtitleStreamIndex):(playerData.audioStreamIndex=null,playerData.subtitleStreamIndex=null),self._playNextAfterEnded=!0;var isFirstItem=playOptions.isFirstItem,fullscreen=playOptions.fullscreen;self.getPlayerState(player).then(function(state){reportPlayback(state,state.NowPlayingItem.ServerId,"reportPlaybackStart"),state.IsFirstItem=isFirstItem,state.IsFullscreen=fullscreen,events.trigger(player,"playbackstart",[state]),events.trigger(self,"playbackstart",[player,state]),streamInfo.started=!0,acquireResourceLocks(player,streamInfo.mediaType)})}function onPlaybackStartedFromSelfManagingPlayer(e,item,mediaSource){var player=this;setCurrentPlayerInternal(player);var playOptions=currentPlayOptions,isFirstItem=playOptions.isFirstItem,fullscreen=playOptions.fullscreen;playOptions.isFirstItem=!1;var playerData=getPlayerData(player);playerData.streamInfo={};var streamInfo=playerData.streamInfo;streamInfo.playbackStartTimeTicks=1e4*(new Date).getTime(),self.getPlayerState(player).then(function(state){reportPlayback(state,state.NowPlayingItem.ServerId,"reportPlaybackStart"),state.IsFirstItem=isFirstItem,state.IsFullscreen=fullscreen,events.trigger(player,"playbackstart",[state]),events.trigger(self,"playbackstart",[player,state]),streamInfo.started=!0})}function onPlaybackStoppedFromSelfManagingPlayer(e,playerStopInfo){var player=this;self.getPlayerState(player).then(function(state){var nextItem=playerStopInfo.nextItem,nextMediaType=playerStopInfo.nextMediaType,playbackStopInfo={player:player,state:state,nextItem:nextItem?nextItem.item:null,nextMediaType:nextMediaType};state.NextMediaType=nextMediaType;var streamInfo=getPlayerData(player).streamInfo;streamInfo.ended=!0,isServerItem(playerStopInfo.item)&&(state.PlayState.PositionTicks=1e4*(playerStopInfo.positionMs||0),reportPlayback(state,playerStopInfo.item.ServerId,"reportPlaybackStopped")),
|
|
state.NextItem=playbackStopInfo.nextItem,events.trigger(player,"playbackstop",[state]),events.trigger(self,"playbackstop",[playbackStopInfo]);var newPlayer=nextItem?getPlayer(nextItem.item,currentPlayOptions):null;newPlayer!==player&&(destroyPlayer(player),removeCurrentPlayer(player))})}function acquireResourceLocks(player,mediaType){if(!player)throw new Error("player cannot be null");if(player.isLocalPlayer&&!player.hasResourceLocks){var playerData=getPlayerData(player);playerData.resourceLocks=playerData.resourceLocks||{};var locks=playerData.resourceLocks;ensureLock(locks,"network"),ensureLock(locks,"wake"),"Video"===mediaType&&ensureLock(locks,"screen")}}function ensureLock(locks,resourceType){var prop=resourceType+"Lock",existingLock=locks[prop];return existingLock?void existingLock.acquire():void require(["resourceLockManager"],function(resourceLockManager){resourceLockManager.request(resourceType).then(function(resourceLock){locks[prop]=resourceLock,resourceLock.acquire()},function(){})})}function releaseResourceLocks(player){if(!player)throw new Error("player cannot be null");if(player.isLocalPlayer&&!player.hasResourceLocks){var playerData=getPlayerData(player),locks=playerData.resourceLocks||{};locks.wakeLock&&locks.wakeLock.release(),locks.networkLock&&locks.networkLock.release(),locks.screenLock&&locks.screenLock.release()}}function enablePlaybackRetryWithTranscoding(streamInfo,errorType){return!!streamInfo&&(!("mediadecodeerror"!==errorType&&"medianotsupported"!==errorType||"Transcode"===streamInfo.playMethod||!streamInfo.mediaSource.SupportsTranscoding)||!("network"!==errorType||"DirectPlay"!==streamInfo.playMethod||!streamInfo.mediaSource.IsRemote||!streamInfo.mediaSource.SupportsTranscoding))}function onPlaybackError(e,error){var player=this;error=error||{};var errorType=error.type;console.log("playbackmanager playback error type: "+(errorType||""));var streamInfo=getPlayerData(player).streamInfo;if(enablePlaybackRetryWithTranscoding(streamInfo,errorType)){var startTime=getCurrentTicks(player)||streamInfo.playerStartPositionTicks;return void changeStream(player,startTime,{EnableDirectPlay:!1,EnableDirectStream:!1,AllowVideoStreamCopy:!1,AllowAudioStreamCopy:!1},!0)}onPlaybackStopped.call(player,e)}function onPlaybackStopped(e){var player=this;getPlayerData(player).isChangingStream||self.getPlayerState(player).then(function(state){var streamInfo=getPlayerData(player).streamInfo,nextItem=self._playNextAfterEnded?self._playQueueManager.getNextItemInfo():null,nextMediaType=nextItem?nextItem.item.MediaType:null,playbackStopInfo={player:player,state:state,nextItem:nextItem?nextItem.item:null,nextMediaType:nextMediaType};state.NextMediaType=nextMediaType,isServerItem(streamInfo.item)&&(player.supportsProgress===!1&&state.PlayState&&!state.PlayState.PositionTicks&&(state.PlayState.PositionTicks=streamInfo.item.RunTimeTicks),streamInfo.ended=!0,reportPlayback(state,streamInfo.item.ServerId,"reportPlaybackStopped")),state.NextItem=playbackStopInfo.nextItem,nextItem||self._playQueueManager.reset(),events.trigger(player,"playbackstop",[state]),events.trigger(self,"playbackstop",[playbackStopInfo]);var newPlayer=nextItem?getPlayer(nextItem.item,currentPlayOptions):null;newPlayer!==player&&(destroyPlayer(player),removeCurrentPlayer(player)),nextItem&&self.nextTrack()})}function onPlaybackChanging(activePlayer,newPlayer,newItem){return self.getPlayerState(activePlayer).then(function(state){var promise,serverId=self.currentItem(activePlayer).ServerId;return unbindStopped(activePlayer),promise=activePlayer===newPlayer?activePlayer.stop(!1):activePlayer.stop(!0),promise.then(function(){bindStopped(activePlayer),enableLocalPlaylistManagement(activePlayer)&&reportPlayback(state,serverId,"reportPlaybackStopped"),events.trigger(self,"playbackstop",[{player:activePlayer,state:state,nextItem:newItem,nextMediaType:newItem.MediaType}])})})}function bindStopped(player){enableLocalPlaylistManagement(player)&&(events.off(player,"stopped",onPlaybackStopped),events.on(player,"stopped",onPlaybackStopped))}function onPlaybackTimeUpdate(e){var player=this;sendProgressUpdate(player,"timeupdate")}function onPlaybackPause(e){var player=this;sendProgressUpdate(player,"pause")}function onPlaybackUnpause(e){var player=this;sendProgressUpdate(player,"unpause")}function onPlaybackVolumeChange(e){var player=this;sendProgressUpdate(player,"volumechange")}function onRepeatModeChange(e){var player=this;sendProgressUpdate(player,"repeatmodechange")}function unbindStopped(player){events.off(player,"stopped",onPlaybackStopped)}function initLegacyVolumeMethods(player){player.getVolume=function(){return player.volume()},player.setVolume=function(val){return player.volume(val)}}function initMediaPlayer(player){players.push(player),players.sort(function(a,b){return(a.priority||0)-(b.priority||0)}),player.isLocalPlayer!==!1&&(player.isLocalPlayer=!0),player.currentState={},player.getVolume&&player.setVolume||initLegacyVolumeMethods(player),enableLocalPlaylistManagement(player)?(events.on(player,"error",onPlaybackError),events.on(player,"timeupdate",onPlaybackTimeUpdate),events.on(player,"pause",onPlaybackPause),events.on(player,"unpause",onPlaybackUnpause),events.on(player,"volumechange",onPlaybackVolumeChange),events.on(player,"repeatmodechange",onRepeatModeChange)):player.isLocalPlayer&&(events.on(player,"itemstarted",onPlaybackStartedFromSelfManagingPlayer),events.on(player,"itemstopped",onPlaybackStoppedFromSelfManagingPlayer),events.on(player,"timeupdate",onPlaybackTimeUpdate),events.on(player,"pause",onPlaybackPause),events.on(player,"unpause",onPlaybackUnpause),events.on(player,"volumechange",onPlaybackVolumeChange),events.on(player,"repeatmodechange",onRepeatModeChange)),player.isLocalPlayer&&bindToFullscreenChange(player),bindStopped(player)}function sendProgressUpdate(player,progressEventName){if(!player)throw new Error("player cannot be null");self.getPlayerState(player).then(function(state){if(state.NowPlayingItem){var serverId=state.NowPlayingItem.ServerId,streamInfo=getPlayerData(player).streamInfo;streamInfo&&streamInfo.started&&!streamInfo.ended&&reportPlayback(state,serverId,"reportPlaybackProgress",progressEventName)}})}var currentTargetInfo,lastLocalPlayer,currentPlayOptions,self=this,players=[],currentPairingId=null;this._playNextAfterEnded=!0;var playerStates={};this._playQueueManager=new PlayQueueManager,self.currentItem=function(player){if(!player)throw new Error("player cannot be null");if(player.currentItem)return player.currentItem();var data=getPlayerData(player);return data.streamInfo?data.streamInfo.item:null},self.currentMediaSource=function(player){if(!player)throw new Error("player cannot be null");if(player.currentMediaSource)return player.currentMediaSource();var data=getPlayerData(player);return data.streamInfo?data.streamInfo.mediaSource:null},self.playMethod=function(player){if(!player)throw new Error("player cannot be null");if(player.playMethod)return player.playMethod();var data=getPlayerData(player);return data.streamInfo?data.streamInfo.playMethod:null},self.playSessionId=function(player){if(!player)throw new Error("player cannot be null");if(player.playSessionId)return player.playSessionId();var data=getPlayerData(player);return data.streamInfo?data.streamInfo.playSessionId:null},self.getPlayerInfo=function(){var player=self._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(self._currentPlayer&&self._currentPlayer.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(self._currentPlayer&&self._currentPlayer.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.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","Photo","Book"],isLocalPlayer:!0,supportedCommands:self.getSupportedCommands({isLocalPlayer:!0})});for(var i=0;i<responses.length;i++)for(var subTargets=responses[i],j=0;j<subTargets.length;j++)targets.push(subTargets[j]);return targets=targets.sort(function(a,b){var aVal=a.isLocalPlayer?0:1,bVal=b.isLocalPlayer?0:1;return aVal=aVal.toString()+a.name,bVal=bVal.toString()+b.name,aVal.localeCompare(bVal)})})},self.getPlaylist=function(player){return player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getPlaylist():Promise.resolve(self._playQueueManager.getPlaylist())},self.isPlaying=function(player){return player=player||self._currentPlayer,player&&player.isPlaying?player.isPlaying():null!=player&&null!=player.currentSrc()},self.isPlayingMediaType=function(mediaType,player){if(player=player||self._currentPlayer,player&&player.isPlaying)return player.isPlaying(mediaType);if(self.isPlaying(player)){var playerData=getPlayerData(player);return playerData.streamInfo.mediaType===mediaType}return!1},self.isPlayingLocally=function(mediaTypes,player){return player=player||self._currentPlayer,!(!player||!player.isLocalPlayer)&&mediaTypes.filter(function(mediaType){return self.isPlayingMediaType(mediaType,player)}).length>0},self.isPlayingVideo=function(player){return self.isPlayingMediaType("Video",player)},self.isPlayingAudio=function(player){return self.isPlayingMediaType("Audio",player)},self.getPlayers=function(){return players},self.canPlay=function(item){var itemType=item.Type,locationType=item.LocationType;if("MusicGenre"===itemType||"Season"===itemType||"Series"===itemType||"BoxSet"===itemType||"MusicAlbum"===itemType||"MusicArtist"===itemType||"Playlist"===itemType)return!0;if("Virtual"===locationType&&"Program"!==itemType)return!1;if("Program"===itemType){if(!item.EndDate||!item.StartDate)return!1;if((new Date).getTime()>datetime.parseISO8601Date(item.EndDate).getTime()||(new Date).getTime()<datetime.parseISO8601Date(item.StartDate).getTime())return!1}return null!=getPlayer(item,{})},self.toggleAspectRatio=function(player){if(player=player||self._currentPlayer){for(var current=self.getAspectRatio(player),supported=self.getSupportedAspectRatios(player),index=-1,i=0,length=supported.length;i<length;i++)if(supported[i].id===current){index=i;break}index++,index>=supported.length&&(index=0),self.setAspectRatio(supported[index].id,player)}},self.setAspectRatio=function(val,player){player=player||self._currentPlayer,player&&player.setAspectRatio&&player.setAspectRatio(val)},self.getSupportedAspectRatios=function(player){return player=player||self._currentPlayer,player&&player.getSupportedAspectRatios?player.getSupportedAspectRatios():[]},self.getAspectRatio=function(player){if(player=player||self._currentPlayer,player&&player.getAspectRatio)return player.getAspectRatio()};var brightnessOsdLoaded;self.setBrightness=function(val,player){player=player||self._currentPlayer,player&&(brightnessOsdLoaded||(brightnessOsdLoaded=!0,require(["brightnessOsd"])),player.setBrightness(val))},self.getBrightness=function(player){if(player=player||self._currentPlayer)return player.getBrightness()},self.setVolume=function(val,player){player=player||self._currentPlayer,player&&player.setVolume(val)},self.getVolume=function(player){if(player=player||self._currentPlayer)return player.getVolume()},self.volumeUp=function(player){player=player||self._currentPlayer,player&&player.volumeUp()},self.volumeDown=function(player){player=player||self._currentPlayer,player&&player.volumeDown()},self.changeAudioStreamIndex=function(player){if(player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.changeAudioStreamIndex()},self.changeSubtitleStreamIndex=function(player){if(player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.changeSubtitleStreamIndex()},self.getAudioStreamIndex=function(player){return player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getAudioStreamIndex():getPlayerData(player).audioStreamIndex},self.setAudioStreamIndex=function(index,player){return player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.setAudioStreamIndex(index):void("Transcode"!==self.playMethod(player)&&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||self._currentPlayer,player&&player.getMaxStreamingBitrate?player.getMaxStreamingBitrate():getPlayerData(player).maxStreamingBitrate||appSettings.maxStreamingBitrate()},self.enableAutomaticBitrateDetection=function(player){return player=player||self._currentPlayer,player&&player.enableAutomaticBitrateDetection?player.enableAutomaticBitrateDetection():appSettings.enableAutomaticBitrateDetection()},self.setMaxStreamingBitrate=function(options,player){if(player=player||self._currentPlayer,player&&player.setMaxStreamingBitrate)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||self._currentPlayer,!player.isLocalPlayer||player.isFullscreen?player.isFullscreen():fullscreenManager.isFullScreen()},self.toggleFullscreen=function(player){return player=player||self._currentPlayer,!player.isLocalPlayer||player.toggleFulscreen?player.toggleFulscreen():void(fullscreenManager.isFullScreen()?fullscreenManager.exitFullscreen():fullscreenManager.requestFullscreen())},self.togglePictureInPicture=function(player){return player=player||self._currentPlayer,player.togglePictureInPicture()},self.getSubtitleStreamIndex=function(player){if(player=player||self._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||self._currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.setSubtitleStreamIndex(index);var currentStream=getCurrentSubtitleStream(player),newStream=getSubtitleStream(player,index);if(currentStream||newStream){var selectedTrackElementIndex=-1,currentPlayMethod=self.playMethod(player);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.seek=function(ticks,player){return ticks=Math.max(0,ticks),player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.isLocalPlayer?player.seek((ticks||0)/1e4):player.seek(ticks):void changeStream(player,ticks)},self.play=function(options){if(normalizePlayOptions(options),self._currentPlayer){if(options.enableRemotePlayers===!1&&!self._currentPlayer.isLocalPlayer)return Promise.reject();if(!self._currentPlayer.isLocalPlayer)return self._currentPlayer.play(options)}if(options.fullscreen&&loading.show(),options.items)return translateItemsForPlayback(options.items,options).then(function(items){return playWithIntros(items,options)});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){return playWithIntros(items,options)})})},self.getPlayerState=function(player){if(player=player||self._currentPlayer,!player)throw new Error("player cannot be null");if(!enableLocalPlaylistManagement(player)&&player.getPlayerState)return player.getPlayerState();var item=player?self.currentItem(player):null,mediaSource=player?self.currentMediaSource(player):null,state={PlayState:{}};return player&&(state.PlayState.VolumeLevel=player.getVolume(),state.PlayState.IsMuted=player.isMuted(),state.PlayState.IsPaused=player.paused(),state.PlayState.RepeatMode=self.getRepeatMode(player),state.PlayState.MaxStreamingBitrate=self.getMaxStreamingBitrate(player),state.PlayState.PositionTicks=getCurrentTicks(player),state.PlayState.PlaybackStartTimeTicks=self.playbackStartTime(player),state.PlayState.SubtitleStreamIndex=self.getSubtitleStreamIndex(player),state.PlayState.AudioStreamIndex=self.getAudioStreamIndex(player),state.PlayState.PlayMethod=self.playMethod(player),mediaSource&&(state.PlayState.LiveStreamId=mediaSource.LiveStreamId),state.PlayState.PlaySessionId=self.playSessionId(player)),mediaSource&&(state.PlayState.MediaSourceId=mediaSource.Id,state.NowPlayingItem={RunTimeTicks:mediaSource.RunTimeTicks},state.PlayState.CanSeek=(mediaSource.RunTimeTicks||0)>0||canPlayerSeek(player)),item&&(state.NowPlayingItem=getNowPlayingItemForReporting(player,item,mediaSource)),state.MediaSource=mediaSource,Promise.resolve(state)},self.duration=function(player){if(player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player)&&!player.isLocalPlayer)return player.duration();if(!player)throw new Error("player cannot be null");var mediaSource=self.currentMediaSource(player);if(mediaSource&&mediaSource.RunTimeTicks)return mediaSource.RunTimeTicks;var playerDuration=player.duration();return playerDuration&&(playerDuration*=1e4),playerDuration},self.getCurrentTicks=getCurrentTicks,self.setCurrentPlaylistItem=function(playlistItemId,player){if(player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.setCurrentPlaylistItem(playlistItemId);for(var newItem,newItemIndex,playlist=self._playQueueManager.getPlaylist(),i=0,length=playlist.length;i<length;i++)if(playlist[i].PlaylistItemId===playlistItemId){newItem=playlist[i],newItemIndex=i;break}if(newItem){var playOptions=Object.assign({},currentPlayOptions,{startPositionTicks:0});playInternal(newItem,playOptions,function(){setPlaylistState(newItem.PlaylistItemId,newItemIndex)})}},self.removeFromPlaylist=function(playlistItemIds,player){if(!playlistItemIds)throw new Error("Invalid playlistItemIds");if(player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.removeFromPlaylist(playlistItemIds);var removeResult=self._playQueueManager.removeFromPlaylist(playlistItemIds);if("empty"===removeResult.result)return self.stop(player);var isCurrentIndex=removeResult.isCurrentIndex;return events.trigger(player,"playlistitemremove",[{playlistItemIds:playlistItemIds}]),isCurrentIndex?self.setCurrentPlaylistItem(self._playQueueManager.getPlaylist()[0].PlaylistItemId,player):Promise.resolve()},self.movePlaylistItem=function(playlistItemId,newIndex,player){if(player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.movePlaylistItem(playlistItemId,newIndex);var moveResult=self._playQueueManager.movePlaylistItem(playlistItemId,newIndex);"noop"!==moveResult.result&&events.trigger(player,"playlistitemmove",[{playlistItemId:moveResult.playlistItemId,newIndex:moveResult.newIndex}])},self.getCurrentPlaylistIndex=function(player){return player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getCurrentPlaylistIndex():self._playQueueManager.getCurrentPlaylistIndex()},self.getCurrentPlaylistItemId=function(player){return player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getCurrentPlaylistItemId():self._playQueueManager.getCurrentPlaylistItemId()},self.nextTrack=function(player){if(player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.nextTrack();var newItemInfo=self._playQueueManager.getNextItemInfo();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||self._currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.previousTrack();var newIndex=self.getCurrentPlaylistIndex(player)-1;if(newIndex>=0){var playlist=self._playQueueManager.getPlaylist(),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=self._currentPlayer;player&&self.isPlaying(player)&&(self._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()}),self.playbackStartTime=function(player){if(player=player||this._currentPlayer,player&&!enableLocalPlaylistManagement(player)&&!player.isLocalPlayer)return player.playbackStartTime();var streamInfo=getPlayerData(player).streamInfo;return streamInfo?streamInfo.playbackStartTimeTicks:null}}var startingPlaySession=(new Date).getTime();return PlaybackManager.prototype.getCurrentPlayer=function(){return this._currentPlayer},PlaybackManager.prototype.currentTime=function(player){return player=player||this._currentPlayer,!player||enableLocalPlaylistManagement(player)||player.isLocalPlayer?this.getCurrentTicks(player):player.currentTime()},PlaybackManager.prototype.canQueue=function(item){return"MusicAlbum"===item.Type||"MusicArtist"===item.Type||"MusicGenre"===item.Type?this.canQueueMediaType("Audio"):this.canQueueMediaType(item.MediaType)},PlaybackManager.prototype.canQueueMediaType=function(mediaType){return!!this._currentPlayer&&this._currentPlayer.canPlayMediaType(mediaType)},PlaybackManager.prototype.isMuted=function(player){return player=player||this._currentPlayer,!!player&&player.isMuted()},PlaybackManager.prototype.setMute=function(mute,player){player=player||this._currentPlayer,player&&player.setMute(mute)},PlaybackManager.prototype.toggleMute=function(mute,player){player=player||this._currentPlayer,player&&(player.toggleMute?player.toggleMute():player.setMute(!player.isMuted()))},PlaybackManager.prototype.toggleDisplayMirroring=function(){this.enableDisplayMirroring(!this.enableDisplayMirroring())},PlaybackManager.prototype.enableDisplayMirroring=function(enabled){if(null!=enabled){var val=enabled?"1":"0";return void appSettings.set("displaymirror",val)}return"0"!==(appSettings.get("displaymirror")||"")},PlaybackManager.prototype.nextChapter=function(player){player=player||this._currentPlayer;var item=this.currentItem(player),ticks=this.getCurrentTicks(player),nextChapter=(item.Chapters||[]).filter(function(i){return i.StartPositionTicks>ticks})[0];nextChapter?this.seek(nextChapter.StartPositionTicks,player):this.nextTrack(player)},PlaybackManager.prototype.previousChapter=function(player){player=player||this._currentPlayer;var item=this.currentItem(player),ticks=this.getCurrentTicks(player);ticks-=1e8,0===this.getCurrentPlaylistIndex(player)&&(ticks=Math.max(ticks,0));var previousChapters=(item.Chapters||[]).filter(function(i){return i.StartPositionTicks<=ticks});previousChapters.length?this.seek(previousChapters[previousChapters.length-1].StartPositionTicks,player):this.previousTrack(player)},PlaybackManager.prototype.fastForward=function(player){if(player=player||this._currentPlayer,null!=player.fastForward)return void player.fastForward(userSettings.skipForwardLength());var ticks=this.getCurrentTicks(player);ticks+=1e4*userSettings.skipForwardLength();var runTimeTicks=this.duration(player)||0;ticks<runTimeTicks&&this.seek(ticks)},PlaybackManager.prototype.rewind=function(player){if(player=player||this._currentPlayer,null!=player.rewind)return void player.rewind(userSettings.skipBackLength());var ticks=this.getCurrentTicks(player);ticks-=1e4*userSettings.skipBackLength(),this.seek(Math.max(0,ticks))},PlaybackManager.prototype.seekPercent=function(percent,player){player=player||this._currentPlayer;var ticks=this.duration(player)||0;percent/=100,ticks*=percent,this.seek(parseInt(ticks),player)},PlaybackManager.prototype.playTrailers=function(item){var apiClient=connectionManager.getApiClient(item.ServerId),instance=this;if(item.LocalTrailerCount)return apiClient.getLocalTrailers(apiClient.getCurrentUserId(),item.Id).then(function(result){return instance.play({items:result})});var remoteTrailers=item.RemoteTrailers||[];return remoteTrailers.length?this.play({items:remoteTrailers.map(function(t){return{Name:t.Name||item.Name+" Trailer",Url:t.Url,MediaType:"Video",Type:"Trailer",ServerId:apiClient.serverId()}})}):Promise.reject()},PlaybackManager.prototype.getSubtitleUrl=function(textStream,serverId){var apiClient=connectionManager.getApiClient(serverId),textStreamUrl=textStream.IsExternalUrl?textStream.DeliveryUrl:apiClient.getUrl(textStream.DeliveryUrl);return textStreamUrl},PlaybackManager.prototype.stop=function(player){return player=player||this._currentPlayer,player?(enableLocalPlaylistManagement(player)&&(this._playNextAfterEnded=!1),player.stop(!0,!0)):Promise.resolve()},PlaybackManager.prototype.playPause=function(player){if(player=player||this._currentPlayer)return player.playPause?player.playPause():player.paused()?this.unpause(player):this.pause(player)},PlaybackManager.prototype.paused=function(player){if(player=player||this._currentPlayer)return player.paused()},PlaybackManager.prototype.pause=function(player){player=player||this._currentPlayer,player&&player.pause()},PlaybackManager.prototype.unpause=function(player){player=player||this._currentPlayer,player&&player.unpause()},PlaybackManager.prototype.instantMix=function(item,player){if(player=player||this._currentPlayer,player&&player.instantMix)return player.instantMix(item);var apiClient=connectionManager.getApiClient(item.ServerId),options={};options.UserId=apiClient.getCurrentUserId(),options.Fields="MediaSources",options.Limit=200;var instance=this;apiClient.getInstantMixFromItem(item.Id,options).then(function(result){instance.play({items:result.Items})})},PlaybackManager.prototype.shuffle=function(shuffleItem,player){if(player=player||this._currentPlayer,player&&player.shuffle)return player.shuffle(shuffleItem);var apiClient=connectionManager.getApiClient(shuffleItem.ServerId),instance=this;apiClient.getItem(apiClient.getCurrentUserId(),shuffleItem.Id).then(function(item){var query={Fields:"MediaSources,Chapters",Limit:200,Filters:"IsNotFolder",Recursive:!0,SortBy:"Random"};if("MusicArtist"===item.Type)query.MediaTypes="Audio",query.ArtistIds=item.Id;else if("MusicGenre"===item.Type)query.MediaTypes="Audio",query.Genres=item.Name;else{if(!item.IsFolder)return;query.ParentId=item.Id}getItemsForPlayback(item.ServerId,query).then(function(result){instance.play({items:result.Items})})})},PlaybackManager.prototype.audioTracks=function(player){if(player=player||this._currentPlayer,player.audioTracks){var result=player.audioTracks();if(result)return result}var mediaSource=this.currentMediaSource(player),mediaStreams=(mediaSource||{}).MediaStreams||[];return mediaStreams.filter(function(s){return"Audio"===s.Type})},PlaybackManager.prototype.subtitleTracks=function(player){if(player=player||this._currentPlayer,player.subtitleTracks){var result=player.subtitleTracks();if(result)return result}var mediaSource=this.currentMediaSource(player),mediaStreams=(mediaSource||{}).MediaStreams||[];return mediaStreams.filter(function(s){return"Subtitle"===s.Type})},PlaybackManager.prototype.getSupportedCommands=function(player){if(player=player||this._currentPlayer,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}var info=this.getPlayerInfo();return info?info.supportedCommands:[]},PlaybackManager.prototype.setRepeatMode=function(value,player){return player=player||this._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.setRepeatMode(value):(this._playQueueManager.setRepeatMode(value),void events.trigger(player,"repeatmodechange"))},PlaybackManager.prototype.getRepeatMode=function(player){return player=player||this._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getRepeatMode():this._playQueueManager.getRepeatMode()},PlaybackManager.prototype.trySetActiveDeviceName=function(name){name=normalizeName(name);var instance=this;instance.getTargets().then(function(result){var target=result.filter(function(p){return normalizeName(p.name)===name})[0];target&&instance.trySetActivePlayer(target.playerName,target)})},PlaybackManager.prototype.displayContent=function(options,player){player=player||this._currentPlayer,player&&player.displayContent&&player.displayContent(options)},PlaybackManager.prototype.beginPlayerUpdates=function(player){player.beginPlayerUpdates&&player.beginPlayerUpdates()},PlaybackManager.prototype.endPlayerUpdates=function(player){player.endPlayerUpdates&&player.endPlayerUpdates()},PlaybackManager.prototype.setDefaultPlayerActive=function(){
|
|
this.setActivePlayer("localplayer")},PlaybackManager.prototype.removeActivePlayer=function(name){var playerInfo=this.getPlayerInfo();playerInfo&&playerInfo.name===name&&this.setDefaultPlayerActive()},PlaybackManager.prototype.removeActiveTarget=function(id){var playerInfo=this.getPlayerInfo();playerInfo&&playerInfo.id===id&&this.setDefaultPlayerActive()},PlaybackManager.prototype.sendCommand=function(cmd,player){switch(console.log("MediaController received command: "+cmd.Name),cmd.Name){case"SetRepeatMode":this.setRepeatMode(cmd.Arguments.RepeatMode,player);break;case"VolumeUp":this.volumeUp(player);break;case"VolumeDown":this.volumeDown(player);break;case"Mute":this.setMute(!0,player);break;case"Unmute":this.setMute(!1,player);break;case"ToggleMute":this.toggleMute(player);break;case"SetVolume":this.setVolume(cmd.Arguments.Volume,player);break;case"SetAspectRatio":this.setAspectRatio(cmd.Arguments.AspectRatio,player);break;case"SetBrightness":this.setBrightness(cmd.Arguments.Brightness,player);break;case"SetAudioStreamIndex":this.setAudioStreamIndex(parseInt(cmd.Arguments.Index),player);break;case"SetSubtitleStreamIndex":this.setSubtitleStreamIndex(parseInt(cmd.Arguments.Index),player);break;case"SetMaxStreamingBitrate":break;case"ToggleFullscreen":this.toggleFullscreen(player);break;default:player.sendCommand&&player.sendCommand(cmd)}},new PlaybackManager}); |