UNPKG

@100mslive/hls-player

Version:

HLS client library which uses HTML5 Video element and Media Source Extension for playback

9 lines (8 loc) 12.1 kB
"use strict";var g=Object.create;var v=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var N=Object.getPrototypeOf,C=Object.prototype.hasOwnProperty;var F=(r,e)=>{for(var t in e)v(r,t,{get:e[t],enumerable:!0})},R=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of I(e))!C.call(r,s)&&s!==t&&v(r,s,{get:()=>e[s],enumerable:!(i=x(e,s))||i.enumerable});return r};var T=(r,e,t)=>(t=r!=null?g(N(r)):{},R(e||!r||!r.__esModule?v(t,"default",{value:r,enumerable:!0}):t,r)),U=r=>R(v({},"__esModule",{value:!0}),r);var H=(r,e,t)=>new Promise((i,s)=>{var o=L=>{try{a(t.next(L))}catch(S){s(S)}},m=L=>{try{a(t.throw(L))}catch(S){s(S)}},a=L=>L.done?i(L.value):Promise.resolve(L.value).then(o,m);a((t=t.apply(r,e)).next())});var k={};F(k,{HLSPlaybackState:()=>p,HMSHLSPlayer:()=>y,HMSHLSPlayerEvents:()=>h});module.exports=U(k);var O=require("@100mslive/hls-stats"),n=T(require("hls.js"));var u=T(require("hls.js"));var E=class r extends Error{constructor(t,i,s,o=!1){super(i);this.name=t;this.message=i;this.description=s;this.isTerminal=o;Object.setPrototypeOf(this,r.prototype)}toAnalyticsProperties(){return{error_name:this.name,error_message:this.message,error_description:this.description,is_terminal:this.isTerminal}}addNativeError(t){this.nativeError=t}toString(){var t;return`{ name: ${this.name}; message: ${this.message}; description: ${this.description}; isTerminal: ${this.isTerminal}; nativeError: ${(t=this.nativeError)==null?void 0:t.message}; }`}};var h=(l=>(l.TIMED_METADATA_LOADED="timed-metadata",l.SEEK_POS_BEHIND_LIVE_EDGE="seek-pos-behind-live-edge",l.CURRENT_TIME="current-time",l.AUTOPLAY_BLOCKED="autoplay-blocked",l.MANIFEST_LOADED="manifest-loaded",l.LAYER_UPDATED="layer-updated",l.CAPTION_ENABLED="caption-enabled",l.ERROR="error",l.PLAYBACK_STATE="playback-state",l.STATS="stats",l))(h||{});var p=(t=>(t[t.playing=0]="playing",t[t.paused=1]="paused",t))(p||{});var d={HLSNetworkError:{manifestLoadError(r){return new E("manifest-load-error",r.details,"Unable to load manifest file",r.fatal)},manifestParsingError(r){return new E("manifest-parsing-error",r.details,"Unable to parse manifest file",r.fatal)},layerLoadError(r){return new E("layer-load-error",r.details,"Unable to load quality layers",r.fatal)}},HLSMediaError:{manifestIncompatibleCodecsError(r){return new E("manifest-incompatible-codecs-error",r.details,"Incompatible manifest codecs",r.fatal)},fragDecryptError(r){return new E("frag-decrypt-error",r.details,"Unable to decrypt fragment",r.fatal)},bufferIncompatibleCodecsError(r){return new E("buffer-incompatible-codecs-error",r.details,"Incompatible buffer codecs",r.fatal)},videoElementNotFound(){return new E("video-element-not-found","Video element not found","Video element not found",!1)},autoplayFailed(){return new E("hls-autoplay-failed","Failed to autoplay","Failed to autoplay",!1)},hlsURLNotFound(r){return new E("hls-url-not-found",r||"hls url not found",r||"hls url not found",!0)}},HLSError:(r,e="hls-error",t="Hls error")=>new E(e,r.details,t,r.fatal)};var D=r=>{try{let e=window==null?void 0:window.atob(r);return JSON.parse(e)}catch(e){return{payload:r}}},A=r=>r.map(e=>_(e)),_=r=>{var e;return{resolution:(e=r.attrs)==null?void 0:e.RESOLUTION,bitrate:r.bitrate,height:r.height,id:r.id,url:r.url[0],width:r.width}};var c=class{constructor(e,t,i){this.videoEl=t;this.emitEvent=i;this.extractMetaTextTrack=()=>{let e=this.videoEl.textTracks.length||0;for(let t=0;t<e;t++){let i=this.videoEl.textTracks[t];if((i==null?void 0:i.kind)==="metadata")return i.mode="showing",i}return null};this.fireCues=(e,t)=>{var m;let i=(m=this.extractMetaTextTrack())==null?void 0:m.cues;if(!i)return;let s=i.length,o=0;for(;o<s;){let a=i[o];if(a.queued){o++;continue}let L=D(a.value.data),S=L.start_date,l=L.end_date,M=new Date(S).getTime()-e,b=new Date(l).getTime()-new Date(S).getTime();M<=t&&(setTimeout(()=>{this.emitEvent("timed-metadata",{id:a==null?void 0:a.id,payload:L.payload,duration:b,startDate:new Date(S),endDate:new Date(l)})},M),a.queued=!0),o++}};this.handleTimeUpdateListener=()=>{var s;let e=this.extractMetaTextTrack();if(!e||!e.cues)return;let t=((s=this.videoEl)==null?void 0:s.getStartDate())||0,i=new Date(t).getTime()+(this.videoEl.currentTime||0)*1e3;this.fireCues(i,.25)};this.fragChangeHandler=(e,{frag:t})=>{if(!this.videoEl){let i=d.HLSMediaError.videoElementNotFound();this.emitEvent("error",i)}try{if(this.videoEl.textTracks.length===0)return;let i=t.programDateTime||0,s=t.end-t.start;this.fireCues(i,s)}catch(i){console.error("FRAG_CHANGED event error",i)}};this.registerListner=()=>{u.default.isSupported()?this.hls.on(u.default.Events.FRAG_CHANGED,this.fragChangeHandler):this.videoEl.canPlayType("application/vnd.apple.mpegurl")&&this.videoEl.addEventListener("timeupdate",this.handleTimeUpdateListener)};this.unregisterListener=()=>{this.hls.off(u.default.Events.FRAG_CHANGED,this.fragChangeHandler),this.videoEl.removeEventListener("timeupdate",this.handleTimeUpdateListener)};this.hls=e,this.registerListner()}};var P=require("eventemitter2"),f=class{constructor(){this.eventEmitter=new P.EventEmitter2}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}emitEvent(e,t){return this.eventEmitter.emit(e,t,e)}removeAllListeners(e){this.eventEmitter.removeAllListeners(e)}};var y=class{constructor(e,t){this._subscribeHlsStats=null;this.TAG="[HMSHLSPlayer]";this.subscribeStats=(e=2e3)=>{this._subscribeHlsStats=this._hlsStats.subscribe(t=>{this.emitEvent("stats",t)},e)};this.unsubscribeStats=()=>{this._subscribeHlsStats&&this._subscribeHlsStats()};this.on=(e,t)=>{this._emitter.on(e,t)};this.off=(e,t)=>{this._emitter.off(e,t)};this.emitEvent=(e,t)=>{var i,s;if(e==="error"){let o=t;o!=null&&o.isTerminal&&((s=(i=window==null?void 0:window.__hms)==null?void 0:i.sdk)==null||s.sendHLSAnalytics(o))}return this._emitter.emitEvent(e,t)};this.removeAllListeners=e=>{this._emitter.removeAllListeners(e)};this.play=()=>H(this,null,function*(){yield this.playVideo()});this.pause=()=>{this.pauseVideo()};this.seekTo=e=>{this._videoEl.currentTime=e};this.hasCaptions=()=>this._hls.subtitleTracks.length>0;this.toggleCaption=()=>{this.hasCaptions()&&(this._hls.subtitleDisplay=!this._hls.subtitleDisplay,this.emitEvent("caption-enabled",this._hls.subtitleDisplay))};this.playVideo=()=>H(this,null,function*(){try{this._videoEl.paused&&(yield this._videoEl.play())}catch(e){console.debug(this.TAG,"Play failed with error",e.message),e.name==="NotAllowedError"&&this.emitEvent("autoplay-blocked",d.HLSMediaError.autoplayFailed())}});this.pauseVideo=()=>{this._videoEl.paused||this._videoEl.pause()};this.playEventHandler=()=>{this.emitEvent("playback-state",{state:0})};this.pauseEventHandler=()=>{this.emitEvent("playback-state",{state:1})};this.volumeEventHandler=()=>{this._volume=Math.round(this._videoEl.volume*100)};this.reConnectToStream=()=>{window.addEventListener("online",()=>{this._hls.startLoad()},{once:!0})};this.handleHLSException=(e,t)=>{var o,m;console.error(this.TAG,`error type ${t.type} with details ${t.details} is fatal ${t.fatal}`);let s={details:((o=t.error)==null?void 0:o.message)||((m=t.err)==null?void 0:m.message)||"",fatal:t.fatal};if(s.fatal)switch(t.details){case n.default.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR:{let a=d.HLSMediaError.manifestIncompatibleCodecsError(s);this.emitEvent("error",a);break}case n.default.ErrorDetails.FRAG_DECRYPT_ERROR:{let a=d.HLSMediaError.fragDecryptError(s);this.emitEvent("error",a);break}case n.default.ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR:{let a=d.HLSMediaError.bufferIncompatibleCodecsError(s);this.emitEvent("error",a);break}case n.default.ErrorDetails.MANIFEST_LOAD_ERROR:{let a=d.HLSNetworkError.manifestLoadError(s);this.emitEvent("error",a);break}case n.default.ErrorDetails.MANIFEST_PARSING_ERROR:{let a=d.HLSNetworkError.manifestParsingError(s);this.emitEvent("error",a);break}case n.default.ErrorDetails.LEVEL_LOAD_ERROR:{let a=d.HLSNetworkError.layerLoadError(s);navigator.onLine?this.emitEvent("error",a):this.reConnectToStream();break}default:{let a=d.HLSError(s,t.type,t.details);this.emitEvent("error",a);break}}};this.manifestLoadedHandler=(e,{levels:t})=>{let i=A(this.removeAudioLevels(t));this.emitEvent("manifest-loaded",{layers:i})};this.levelUpdatedHandler=(e,{level:t})=>{let i=_(this._hls.levels[t]);this.emitEvent("layer-updated",{layer:i})};this.handleTimeUpdateListener=e=>{this.emitEvent("current-time",this._videoEl.currentTime);let t=this._hls.liveSyncPosition?this._hls.liveSyncPosition-this._videoEl.currentTime<=5:!1;this._isLive!==t&&(this._isLive=t,this.emitEvent("seek-pos-behind-live-edge",{isLive:this._isLive}))};if(this._hls=new n.default(this.getPlayerConfig()),this._emitter=new f,this._hlsUrl=e,this._videoEl=t||this.createVideoElement(),e){if(!e.endsWith("m3u8"))throw d.HLSMediaError.hlsURLNotFound("Invalid URL, pass m3u8 url")}else throw d.HLSMediaError.hlsURLNotFound();this._hls.loadSource(e),this._hls.attachMedia(this._videoEl),this._isLive=!0,this._volume=this._videoEl.volume*100,this._hlsStats=new O.HlsStats(this._hls,this._videoEl),this.listenHLSEvent(),this._metaData=new c(this._hls,this._videoEl,this.emitEvent),this.seekToLivePosition()}createVideoElement(){if(this._videoEl)return this._videoEl;let e=document.createElement("video");return e.playsInline=!0,e.controls=!1,e.autoplay=!0,e}getVideoElement(){return this._videoEl}reset(){this._hls&&this._hls.media&&(this._hls.detachMedia(),this.unsubscribeStats()),this._metaData&&this._metaData.unregisterListener(),n.default.isSupported()&&(this._hls.off(n.default.Events.MANIFEST_LOADED,this.manifestLoadedHandler),this._hls.off(n.default.Events.LEVEL_UPDATED,this.levelUpdatedHandler),this._hls.off(n.default.Events.ERROR,this.handleHLSException)),this._videoEl&&(this._videoEl.removeEventListener("play",this.playEventHandler),this._videoEl.removeEventListener("pause",this.pauseEventHandler),this._videoEl.removeEventListener("timeupdate",this.handleTimeUpdateListener),this._videoEl.removeEventListener("volumechange",this.volumeEventHandler)),this.removeAllListeners()}get volume(){return this._volume}setVolume(e){this._videoEl.volume=e/100,this._volume=e}getLayer(){var e,t;if(this._hls&&this._hls.currentLevel!==-1){let i=(t=this._hls)==null?void 0:t.levels.at((e=this._hls)==null?void 0:e.currentLevel);return i?_(i):null}return null}setLayer(e){if(this._hls){let t=this._hls.levels.findIndex(i=>{var s;return((s=i==null?void 0:i.attrs)==null?void 0:s.RESOLUTION)===(e==null?void 0:e.resolution)});this._hls.nextLevel=t}}seekToLivePosition(){return H(this,null,function*(){let e=0;if(this._videoEl.buffered.length>0&&(e=this._videoEl.buffered.end(this._videoEl.buffered.length-1)),this._videoEl.currentTime=this._hls.liveSyncPosition||e,this._videoEl.paused)try{yield this.playVideo()}catch(t){console.error(this.TAG,"Attempt to jump to live position Failed.",t)}})}listenHLSEvent(){n.default.isSupported()?(this._hls.on(n.default.Events.MANIFEST_LOADED,this.manifestLoadedHandler),this._hls.on(n.default.Events.LEVEL_UPDATED,this.levelUpdatedHandler),this._hls.on(n.default.Events.ERROR,this.handleHLSException),this.subscribeStats()):this._videoEl.canPlayType("application/vnd.apple.mpegurl")&&(this._videoEl.src=this._hlsUrl),this._videoEl.addEventListener("timeupdate",this.handleTimeUpdateListener),this._videoEl.addEventListener("play",this.playEventHandler),this._videoEl.addEventListener("pause",this.pauseEventHandler),this._videoEl.addEventListener("volumechange",this.volumeEventHandler)}getPlayerConfig(){return{enableWorker:!0,maxBufferLength:20,backBufferLength:10,abrBandWidthUpFactor:1,playlistLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:10,retryDelayMs:1e3,maxRetryDelayMs:8e3,backoff:"exponential"},errorRetry:{maxNumRetry:10,retryDelayMs:1e3,maxRetryDelayMs:8e3,backoff:"exponential"}}}}}removeAudioLevels(e){return e.filter(({videoCodec:t,width:i,height:s})=>!!t||!!(i&&s))}static isSupported(){return n.default.isSupported()}}; //# sourceMappingURL=index.cjs.js.map