UNPKG

@flowplayer/player

Version:
2 lines (1 loc) 17.2 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):((e="undefined"!=typeof globalThis?globalThis:e||self).flowplayer=e.flowplayer||{},e.flowplayer.chromecast=t())}(this,(function(){"use strict";function e(e){const t=document.createElement("a");t.href=e;const n=t.pathname&&t.pathname.split(".");return n.length>1&&n[n.length-1]}function t(e){switch(e){case"video/mpd":return"application/dash+xml";case"video/m3u8":return"application/x-mpegurl";default:return e}}const n=n=>{var{src:o}=n,r=function(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n}(n,["src"]);return[Object.assign({src:o,type:o?t("video/"+e(o)):""},r)]};function o(e){return n({src:e})}class Pipe{static of(e){return new Pipe(e)}static maybe(e,t,...n){return null==e?e:t.apply(e,[e,...n])}constructor(e){this.data=e}tap(e,...t){return e.apply(this,[this.data,...t]),new Pipe(this.data)}fmap(e,...t){const n=e.apply(this,[this.data,...t]);return new Pipe(n)}unwrap(){return this.data}}const r="chromecast:idle";var a=Object.freeze({__proto__:null,CAST_AVAILABLE:"chromecast:available",CAST_UNAVAILABLE:"chromecast:unavailable",CAST_START_CASTING:"chromecast:start",CAST_IDLE:r,CAST_STATE_CHANGED:"chromecast:state:changed",CAST_SESSION_CHANGED:"chromecast:session:changed",CAST_FIELD_UPDATE:"chromecast:field:update",CAST_MEDIA_LOAD_REQUEST:"chromecast:media"});const s={AAC:"aac",AC3:"ac3",E_AC3:"e_ac3",FMP4:"fmp4",MP3:"mp3",TS:"ts",TS_AAC:"ts_aac"},i={FMP4:"fmp4",MPEG2_TS:"mpeg2_ts"},c=/(video\/mp4)|(application\/x-mpegurl)|(video\/mpd)|(application\/dash\+xml)/;function l(){var e;return(null===(e=g())||void 0===e?void 0:e.getCurrentSession())||null}function u(e){return h(e).unwrap().shift()}function d(e,t){const n=e.opts.chromecast;(null==n?void 0:n.hlsSegmentFormat)&&Object.values(s).includes(n.hlsSegmentFormat.toLowerCase())&&(t.hlsSegmentFormat=n.hlsSegmentFormat),(null==n?void 0:n.hlsVideoSegmentFormat)&&Object.values(i).includes(n.hlsVideoSegmentFormat.toLowerCase())&&(t.hlsVideoSegmentFormat=n.hlsVideoSegmentFormat)}function m(){var e;return(null===(e=l())||void 0===e?void 0:e.getMediaSession())||null}function p(e){var t,n;const o=h(e).unwrap().map((function(e){return null==e?void 0:e.src})),r=null===(n=null===(t=m())||void 0===t?void 0:t.media)||void 0===n?void 0:n.contentId;return!!r&&!!~o.indexOf(r)}function f(e){var t;return(null===(t=e.type)||void 0===t?void 0:t.match(c))||!1}function v(e,t){if(!t.opts.src)return e;const n=(Array.isArray(t.opts.src)?t.opts.src:[t.opts.src]).map(e=>"string"==typeof e?o(e)[0]:e);return e.map(e=>{const t=n.find(t=>t.src===e.src);return t&&t.drm?Object.assign(Object.assign({},e),{drm:t.drm}):e})}function h(e){return Pipe.of(e).fmap(()=>e.original_src||[]).fmap((function(e){return"string"==typeof e?o(e):e})).fmap(v,e).fmap((function(e){return e.filter(f)}))}function g(){var e,t,n;return null===(n=null===(t=null===(e=window.cast)||void 0===e?void 0:e.framework)||void 0===t?void 0:t.CastContext)||void 0===n?void 0:n.getInstance()}function y(e,t){var n;null===(n=w.casting_player)||void 0===n||n.emit(e,t)}function S(e,t,n){e.forEach((function(e){e!==w.casting_player&&e.emit(t,n)}))}function _(e,t,n){e.forEach((function(e){e.emit(t,n)}))}const w={remote_player:void 0,controller:void 0,listener:void 0};function E(e){w.controller&&w.listener&&w.controller.removeEventListener(cast.framework.RemotePlayerEventType.ANY_CHANGE,w.listener),w.remote_player=new cast.framework.RemotePlayer,w.controller=new cast.framework.RemotePlayerController(w.remote_player),w.listener=b.bind(null,e),w.controller.addEventListener(cast.framework.RemotePlayerEventType.ANY_CHANGE,w.listener)}function b(e,t){var n;if((null===(n=g())||void 0===n?void 0:n.getCastState())!==cast.framework.CastState.NOT_CONNECTED)return"IDLE"===t.value?S(e,r):void y("chromecast:field:update",t)}function T(e){return Array.from(e.textTracks).filter(e=>["subtitles","captions"].includes(e.kind))}function A(e){return T(e).flatMap((t,n)=>{try{const o=e.querySelector("#"+t.id);if(!(o instanceof HTMLTrackElement&&o.lang))return[];const r=new chrome.cast.media.Track(n+1e3,chrome.cast.media.TrackType.TEXT);return r.trackContentType="text/vtt",r.subtype=chrome.cast.media.TextTrackType.SUBTITLES,r.trackContentId=o.src,r.name=o.label,r.language=o.lang,r}catch(e){return[]}})}function C(e){var t;const n=new chrome.cast.media.EditTracksInfoRequest(e);null===(t=m())||void 0===t||t.editTracksInfo(n,console.debug,console.error)}var k=Object.freeze({__proto__:null,getCurrentSession:l,getMedia:u,setMediaSegmentFormat:d,getMediaSession:m,isSame:p,is_supported_media:f,injectDRMConfiguration:v,normalizeSrc:h,getCastContext:g,broadcast_to_active:y,broadcast_to_idle:S,broadcast:_,SINGLETONS:w,refresh_singletons:E,onremotechange:b,tracks:T,cast_tracks:A,editTracks:C});var O=Object.freeze({__proto__:null,STABLE:"940D4BE4",CANARY:"6F71FA7C",LOCAL:"5258CA32"});const L="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1";function P(e,t,n){if(document.querySelector("script[src='"+L+"']"))return x(n);!function(){const e=document.createElement("script");e.async=!0,e.src=L,document.head.appendChild(e)}(),window.__onGCastApiAvailable=function(){!function(e,t,n){var o;if(!I())return;const r=(null===(o=e.chromecast)||void 0===o?void 0:o.app)||"940D4BE4",a=g();if(!a)return;a.setOptions({receiverApplicationId:r,autoJoinPolicy:chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}),a.addEventListener(cast.framework.CastContextEventType.CAST_STATE_CHANGED,(function(e){_(n,"chromecast:state:changed",e)})),a.addEventListener(cast.framework.CastContextEventType.SESSION_STATE_CHANGED,(function(e){E(n),_(n,"chromecast:session:changed",e)}))}(e,0,n),x(n)}}function I(){return"object"==typeof window.cast&&"object"==typeof chrome.cast}function x(e){if(I())return _(e,"chromecast:available");_(e,"chromecast:unavailable")}const N="is-chromecast-playing";function D(e,t){const n=e.seekable;if("object"!=typeof e.opts||0==n.length)return{head:0,tail:0};const o=function(e){var t;const n=e.seekable;return n.length?e.hasState(N)||!(null===(t=e.hls)||void 0===t?void 0:t.liveSyncPosition)?n.end(n.length-1):e.hls.liveSyncPosition:0}(e),r=t||e.live_state.dvr_window;return{head:o,tail:"number"!=typeof r||o-r<0?n.start(0):o-r}}function M(e){const t=e.currentTime,n=D(e);return{progress:Math.min(100,Math.max(0,(t-n.tail)/(n.head-n.tail)*100)),is_live:t-n.head>=-10}}const j={player:void 0,listener:void 0};function F(e,t,n,o){var a,s,i,c,p;const f=l();if(!f)return;const v=u(e);if(!v||!v.src)return;w.casting_player=e;const h=new chrome.cast.media.MediaInfo(v.src,v.type||"");h.metadata=new chrome.cast.media.GenericMediaMetadata,function(e){j.player&&j.listener&&j.player.off("playing",j.listener);const t={currentTime:e.currentSessionTime,liveState:e.live_state,progress:M(e).progress};j.player=e,j.listener=()=>{setTimeout(()=>{!function(e,t){const n=m();if(!n)return;if(-1!==n.media.duration)return e.currentTime=t.currentTime;const o=n.liveSeekableRange;if(!o||"number"!=typeof o.end||"number"!=typeof o.start)return;if(void 0===t.liveState.dvr_window||!t.liveState.dvr)return;e.currentTime=(o.end-o.start)*(t.progress/100)}(e,t)},1e3)},e.once("playing",j.listener)}(e);const g={health:e.health,text_tracks:A(e),active_tracks:{active_audio:(null===(s=null===(a=null==e?void 0:e.asel)||void 0===a?void 0:a.active_track)||void 0===s?void 0:s.name)||(null===(c=null===(i=null==e?void 0:e.asel)||void 0===i?void 0:i.active_track)||void 0===c?void 0:c.lang),active_text:null===(p=T(e).find(e=>e.is_active))||void 0===p?void 0:p.label}};v.drm&&(g.drm=v.drm),localStorage.__fpChromecastDebug&&(g.debug=!0),e.opt("ads")&&(g.ads=e.opt("ads")),h.customData=g,d(e,h);const y=new chrome.cast.media.LoadRequest(h);y.customData=e.opt("chromecast",{}),y.customData.metadata=e.opt("metadata"),e.emit("chromecast:media",{request:y}),console.debug("cast:request(%o)",y),f.loadMedia(y).then(()=>{e.emit("remotesession:started"),e.setState("has-casted",!0),e.setState("is-casting",!0),E(t);const n=w.remote_player;n&&(e.volume=n.volumeLevel,e.muted=n.isMuted),S(t,r)},o)}function R(){return!!m()}function G(){return!!l()}function q(){var e;return null===(e=l())||void 0===e?void 0:e.getCastDevice().friendlyName}function H(){var e;return(null===(e=null==k?void 0:l())||void 0===e?void 0:e.getMediaSession()).getEstimatedLiveSeekableRange()}function V(){var e,t;return null===(t=null===(e=m())||void 0===e?void 0:e.media)||void 0===t?void 0:t.duration}function U(){var e;return null===(e=m())||void 0===e?void 0:e.playerState}function B(e){var t;return e?z(e):null===(t=m())||void 0===t?void 0:t.getEstimatedTime()}function z(e){const t=m();if(!t)return e;const n=new chrome.cast.media.SeekRequest;return n.currentTime=e,t.seek(n,console.debug,console.error),e}function Y(){var e;return null===(e=m())||void 0===e?void 0:e.play(new chrome.cast.media.PlayRequest,console.debug,console.error)}function J(){var e;return null===(e=m())||void 0===e?void 0:e.pause(new chrome.cast.media.PauseRequest,console.debug,console.error)}var X=Object.freeze({__proto__:null,load:F,has_media:R,exists:G,device_name:q,seekable_ranges:H,duration:V,state:U,currentTime:B,seek:z,play:Y,pause:J});function $(e,t){if(!e.root)return;const n=e.root.querySelector(".fp-chromecast p");if(!n)return;let o="";o=e.i18n("chromecast.message","{{state}} on {{device}}").replace("{{device}}",(null==t?void 0:t.device)||"chromecast"),o=o.replace("{{state}}",((null==t?void 0:t.state)||"").toLowerCase()),n.textContent=o}const Q="currentTime",K="duration",W="playerState",Z="videoInfo",ee="volumeLevel",te="isMuted",ne="liveSeekableRange",oe=(e,t)=>new(((e,t)=>{const n=e.get(t);if(!n)throw new Error(`no flowplayer component with the name ${t} exists`);const o=window.customElements.get(t);if(!o)throw new Error(`no default flowplayer component with the name ${t} exists`);const r=window.customElements.get(n);return"function"!=typeof r?o:r})(e._customElements,t))(e);class FlowplayerComponent extends HTMLElement{constructor(e){super(),this.player=e}}class FlowplayerChromecastIcon extends FlowplayerComponent{constructor(e){super(e),this.classList.add("fp-cast-button"),this.setAttribute("tabindex","-1"),this.setAttribute("role","button"),this.setAttribute("aria-hidden","true"),this.cast_launcher=document.createElement("google-cast-launcher"),this.cast_launcher.setAttribute("inert","true"),this.append(this.cast_launcher),this.addEventListener("click",t=>{const n=l();if(n)return n.endSession(!0);e.emit("chromecast:start"),t.target===this&&this.cast_launcher.click()}),e.on("chromecast:state:changed",t=>{const n=t.detail.castState;n&&(this.setAttribute("tabindex",n===cast.framework.CastState.NO_DEVICES_AVAILABLE?"-1":"0"),this.setAttribute("aria-hidden",(n===cast.framework.CastState.NO_DEVICES_AVAILABLE)+""),this.setAttribute("aria-label",n===cast.framework.CastState.NOT_CONNECTED?e.i18n("chromecast.start","start casting"):e.i18n("chromecast.stop","stop casting")))})}}function re(e,t){const n=e._customElements.get(t);return n&&e.root.querySelector(n)||void 0}class ChromecastPlugin{constructor(e){var t,n,o;this.flowplayer=e,t=e,n="flowplayer-chromecast-icon",o=FlowplayerChromecastIcon,window.customElements.get(n)||window.customElements.define(n,o),t.customElements.get(n)||t.customElements.set(n,n)}init(e,t,n){if("https:"!==location.protocol&&"localhost"!==location.hostname&&"127.0.0.1"!==location.hostname)return console.warn("Secure URL required to enable Chromecast");P(e,0,this.flowplayer.instances),n.on("mount",(function(){const t=re(n,"flowplayer-middle");t&&function(e,t){const n=document.createElement("div");n.className="fp-chromecast";const o=document.createElement("p");t.poster&&(n.style.backgroundImage=["url(",t.poster,")"].join("")),n.append(o),e.prepend(n)}(t,{poster:e.poster});const o=re(n,"flowplayer-header-right-zone");o&&o.prepend(oe(n,"flowplayer-chromecast-icon"))})),n.on("chromecast:available",()=>{n.setState("is-cast-available",!0),function(e,t){const n={play:function(){return new Promise(n=>p(e)?n(Y()):R()?n(F(e,t,console.debug,console.error)):(F(e,t,console.debug,console.error),void n()))},pause:function(){return p(e)?J():HTMLMediaElement.prototype.pause.call(e)}};n.currentTime={get:B,set:B},n.seekable={get:()=>{const e=H();return{start:()=>(null==e?void 0:e.start)||0,end:()=>(null==e?void 0:e.end)||0,length:1}}},n.duration={get:V},n.paused={get:function(){return"PAUSED"===U()}},n.playing={get:function(){return"PLAYING"===U()}},Object.keys(n).forEach((function(t){if("object"==typeof n[t])return Object.defineProperty(e,t,{get:function(){var o,r;return p(e)?n[t].get():null===(r=null===(o=Object.getOwnPropertyDescriptor(HTMLMediaElement.prototype,t))||void 0===o?void 0:o.get)||void 0===r?void 0:r.call(this)},set:function(o){var r,a;return p(e)?n[t].set(o):null===(a=null===(r=Object.getOwnPropertyDescriptor(HTMLMediaElement.prototype,t))||void 0===r?void 0:r.set)||void 0===a?void 0:a.call(this,o)}});const o=e[t];e[t]=function(){const r=[].slice.apply(arguments);return G()?n[t].apply(e,r):o.apply(e,r)}}))}(n,this.flowplayer.instances)}),n.on("chromecast:unavailable",(function(){n.setState("is-cast-available",!1)})),n.on("chromecast:start",()=>{if(w.casting_player=n,this.flowplayer.instances.forEach(e=>{e.togglePlay(!1),e.currentSessionTime=e.hasState("is-ended")?0:e.currentTime}),R())return F(n,this.flowplayer.instances,console.debug,console.error)}),n.on("volumechange",()=>{const e=w.remote_player,t=w.controller;if(!R()||!e||!t)return;const o=n.volume,r=n.muted;o!==e.volumeLevel&&(e.volumeLevel=o,t.setVolumeLevel()),r!==e.isMuted&&t.muteOrUnmute()}),n.on("tracks:text:updated",(function(e){var t,o,r;if(R())return e.data?void C((null===(r=null===(o=null===(t=m())||void 0===t?void 0:t.media)||void 0===o?void 0:o.tracks)||void 0===r?void 0:r.filter(e=>"TEXT"===e.type).filter(e=>{var t;return e.name===(null===(t=T(n).find(e=>e.is_active))||void 0===t?void 0:t.label)}).map(e=>e.trackId))||[]):C([])})),n.on("audio:update",()=>{R()&&setTimeout(()=>{var e,t,o,r,a;const s=null===(e=null==n?void 0:n.asel)||void 0===e?void 0:e.active_track,i=null===(a=null===(r=null===(o=null===(t=m())||void 0===t?void 0:t.media)||void 0===o?void 0:o.tracks)||void 0===r?void 0:r.filter(e=>"AUDIO"===e.type).find(e=>void 0!==e.name?e.name===(null==s?void 0:s.name):e.language===(null==s?void 0:s.lang)))||void 0===a?void 0:a.trackId;"number"==typeof i&&C([i])},0)}),n.on(r,()=>{if(n.setState("is-starting",!0),!n.hasState("is-casting"))return;const e=n.opt("duration");"number"==typeof e&&Math.abs(e-n.currentSessionTime)<=1&&(n.currentSessionTime=0,n.setState("is-paused",!1),n.emit("ended")),n.emit("remotesession:ended",{currentTime:n.currentSessionTime}),this.reset_state(n)}),n.on("chromecast:field:update",(function(e){if(!e.data)return;const{field:t,value:o}=e.data;switch(t){case K:return void(-1!==o||n.opts.live||n.setOpts({live:!0}));case te:return n.muted=o;case ee:return n.volume=o;case ne:return n.emit("dvr/window",o.end-o.start);case Q:return Math.abs(o-n.currentSessionTime)>=1.5&&n.emit("seeked"),n.currentSessionTime=o,n.emit("timeupdate",o);case W:return"PLAYING"==o?n.emit("playing"):"PAUSED"==o?n.emit("pause"):void 0;case Z:var r=(o||{}).fake_session||X;return $(n,{device:r.device_name(),state:r.state()}),r.hide_controls&&n.setState("no-chromecast-controls",!0),n.setState("is-starting",!1),n.hasState("is-loaded")||-1===n.duration||n.setOpts({duration:n.duration}),n.setState(N,!0)}})),n.on("chromecast:session:changed",e=>{if(e.data)switch(e.detail.sessionState){case cast.framework.SessionState.SESSION_ENDED:if(!n.hasState("is-casting"))return;return w.casting_player=void 0,n.emit("remotesession:ended",{currentTime:n.currentSessionTime}),this.reset_state(n);case cast.framework.SessionState.SESSION_RESUMED:if(!p(n))return;return w.casting_player=n,n.setState(n.paused?"is-paused":"is-playing",!0),n.setState("is-casting",!0),n.setState("has-casted",!0),n.setState(N,!0),n.emit("timeupdate"),n.currentSessionTime=n.currentTime,$(n,{device:q(),state:U()}),n.setState("is-starting",!1);case cast.framework.SessionState.SESSION_STARTED:if(n!==w.casting_player)return;F(n,this.flowplayer.instances,console.debug,console.error)}})}reset_state(e){e.setState(N,!1),e.setState("is-casting",!1),e.setState("is-playing",!1),e.setState("is-paused",!0),e.setState("is-starting",!0)}}ChromecastPlugin.pluginName="chromecast",ChromecastPlugin.apps=O,ChromecastPlugin.events=a,ChromecastPlugin.hlsSegmentFormat={audio:s,video:i};return function(e,t){if("object"==typeof exports&&"undefined"!=typeof module)return t;if(null===document.currentScript)return t;"flowplayer"in e||(e.flowplayer={extensions:[]});const n=e.flowplayer;return"function"==typeof n?(n(t),t):(Array.isArray(n.extensions)||(n.extensions=[]),~n.extensions.indexOf(t)||n.extensions.push(t),t)}(window,ChromecastPlugin)}));