From 5cceca4e9396e760517f616ae45d01ea37b704a8 Mon Sep 17 00:00:00 2001 From: zedeus Date: Thu, 9 Jun 2022 09:25:45 +0200 Subject: [PATCH 01/68] Bump zippy dependency --- nitter.nimble | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nitter.nimble b/nitter.nimble index d364562..90a7921 100644 --- a/nitter.nimble +++ b/nitter.nimble @@ -20,7 +20,7 @@ requires "packedjson#d11d167" requires "supersnappy#2.1.1" requires "redpool#8b7c1db" requires "https://github.com/zedeus/redis#d0a0e6f" -requires "zippy#0.7.3" +requires "zippy#0.9.11" requires "flatty#0.2.3" requires "jsony#d0e69bd" From 74c13b372dfe43014385e2ce165fd01d5d656fae Mon Sep 17 00:00:00 2001 From: zedeus Date: Thu, 9 Jun 2022 09:34:06 +0200 Subject: [PATCH 02/68] Format readme --- README.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 460ce21..286bea7 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ XMR: 42hKayRoEAw4D6G6t8mQHPJHQcXqofjFuVfavqKeNMNUZfeJLJAcNU19i1bGdDvcdN6romiSscW ## Resources -The wiki contains +The wiki contains [a list of instances](https://github.com/zedeus/nitter/wiki/Instances) and [browser extensions](https://github.com/zedeus/nitter/wiki/Extensions) maintained by the community. @@ -67,9 +67,10 @@ Twitter account. ## Installation ### Dependencies -* libpcre -* libsass -* redis + +- libpcre +- libsass +- redis To compile Nitter you need a Nim installation, see [nim-lang.org](https://nim-lang.org/install.html) for details. It is possible to @@ -115,18 +116,21 @@ before you can run the container. See below for how to also run Redis using Docker. To build and run Nitter in Docker: + ```bash docker build -t nitter:latest . docker run -v $(pwd)/nitter.conf:/src/nitter.conf -d --network host nitter:latest ``` A prebuilt Docker image is provided as well: + ```bash docker run -v $(pwd)/nitter.conf:/src/nitter.conf -d --network host zedeus/nitter:latest ``` Using docker-compose to run both Nitter and Redis as different containers: Change `redisHost` from `localhost` to `nitter-redis` in `nitter.conf`, then run: + ```bash docker-compose up -d ``` From b398136742f9b784b2d5c8b5baa9f25a3560b5a0 Mon Sep 17 00:00:00 2001 From: Frank Moskal Date: Sun, 12 Jun 2022 17:11:39 +0000 Subject: [PATCH 03/68] update hls.js to v1.1.5 (#636) --- public/js/hls.light.min.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/public/js/hls.light.min.js b/public/js/hls.light.min.js index af4758a..2dcaa72 100644 --- a/public/js/hls.light.min.js +++ b/public/js/hls.light.min.js @@ -1,5 +1,5 @@ // @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 // @source https://github.com/video-dev/hls.js -// @version v1.0.6 -"undefined"!=typeof window&&function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Hls=e():t.Hls=e()}(this,(function(){return function(t){var e={};function r(i){if(e[i])return e[i].exports;var a=e[i]={i:i,l:!1,exports:{}};return t[i].call(a.exports,a,a.exports,r),a.l=!0,a.exports}return r.m=t,r.c=e,r.d=function(t,e,i){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var a in t)r.d(i,a,function(e){return t[e]}.bind(null,a));return i},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="/dist/",r(r.s=19)}([function(t,e,r){"use strict";var i;r.d(e,"a",(function(){return i})),function(t){t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached"}(i||(i={}))},function(t,e,r){"use strict";r.d(e,"a",(function(){return o})),r.d(e,"b",(function(){return l}));var i=function(){},a={trace:i,debug:i,log:i,warn:i,info:i,error:i},n=a;function s(t){var e=self.console[t];return e?e.bind(self.console,"["+t+"] >"):i}function o(t){if(self.console&&!0===t||"object"==typeof t){!function(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i>8*(15-r)&255;return e},r.setDecryptDataFromLevelKey=function(t,e){var r=t;return"AES-128"===(null==t?void 0:t.method)&&t.uri&&!t.iv&&((r=o.a.fromURI(t.uri)).method=t.method,r.iv=this.createInitializationVector(e),r.keyFormat="identity"),r},r.setElementaryStreamInfo=function(t,e,r,i,a,n){void 0===n&&(n=!1);var s=this.elementaryStreams,o=s[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,a)):s[t]={startPTS:e,endPTS:r,startDTS:i,endDTS:a,partial:n}},r.clearElementaryStreamInfo=function(){var t=this.elementaryStreams;t[i.AUDIO]=null,t[i.VIDEO]=null,t[i.AUDIOVIDEO]=null},f(e,[{key:"decryptdata",get:function(){if(!this.levelkey&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkey){var t=this.sn;"number"!=typeof t&&(this.levelkey&&"AES-128"===this.levelkey.method&&!this.levelkey.iv&&s.b.warn('missing IV for initialization segment with method="'+this.levelkey.method+'" - compliance issue'),t=0),this._decryptdata=this.setDecryptDataFromLevelKey(this.levelkey,t)}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;if(!Object(a.a)(this.programDateTime))return null;var t=Object(a.a)(this.duration)?this.duration:0;return this.programDateTime+1e3*t}},{key:"encrypted",get:function(){var t;return!(null===(t=this.decryptdata)||void 0===t||!t.keyFormat||!this.decryptdata.uri)}}]),e}(c),g=function(t){function e(e,r,i,a,n){var s;(s=t.call(this,i)||this).fragOffset=0,s.duration=0,s.gap=!1,s.independent=!1,s.relurl=void 0,s.fragment=void 0,s.index=void 0,s.stats=new l.a,s.duration=e.decimalFloatingPoint("DURATION"),s.gap=e.bool("GAP"),s.independent=e.bool("INDEPENDENT"),s.relurl=e.enumeratedString("URI"),s.fragment=r,s.index=a;var o=e.enumeratedString("BYTERANGE");return o&&s.setByteRange(o,n),n&&(s.fragOffset=n.fragOffset+n.duration),s}return u(e,t),f(e,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var t=this.elementaryStreams;return!!(t.audio||t.video||t.audiovideo)}}]),e}(c)},function(t,e,r){"use strict";r.d(e,"b",(function(){return d})),r.d(e,"g",(function(){return h})),r.d(e,"f",(function(){return f})),r.d(e,"d",(function(){return c})),r.d(e,"c",(function(){return v})),r.d(e,"e",(function(){return p})),r.d(e,"h",(function(){return m})),r.d(e,"a",(function(){return y}));var i=r(8),a=r(5),n=Math.pow(2,32)-1,s=[].push;function o(t){return String.fromCharCode.apply(null,t)}function l(t,e){"data"in t&&(e+=t.start,t=t.data);var r=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3];return r<0?4294967296+r:r}function u(t,e,r){"data"in t&&(e+=t.start,t=t.data),t[e]=r>>24,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=255&r}function d(t,e){var r,i,a,n=[];if(!e.length)return n;"data"in t?(r=t.data,i=t.start,a=t.end):(i=0,a=(r=t).byteLength);for(var u=i;u1?u+h:a;if(o(r.subarray(u+4,u+8))===e[0])if(1===e.length)n.push({data:r,start:u+8,end:f});else{var c=d({data:r,start:u+8,end:f},e.slice(1));c.length&&s.apply(n,c)}u=f}return n}function h(t){var e=d(t,["moov"])[0],r=e?e.end:null,i=d(t,["sidx"]);if(!i||!i[0])return null;var a=[],n=i[0],s=n.data[0],o=0===s?8:16,u=l(n,o);o+=4;o+=0===s?8:16,o+=2;var h=n.end+0,f=function(t,e){"data"in t&&(e+=t.start,t=t.data);var r=t[e]<<8|t[e+1];return r<0?65536+r:r}(n,o);o+=2;for(var c=0;c>>31)return console.warn("SIDX has hierarchical references (not supported)"),null;var m=l(n,v);v+=4,a.push({referenceSize:p,subsegmentDuration:m,info:{duration:m/u,start:h,end:h+p-1}}),h+=p,o=v+=4}return{earliestPresentationTime:0,timescale:u,version:s,referencesCount:f,references:a,moovEndOffset:r}}function f(t){for(var e=[],r=d(t,["moov","trak"]),i=0;i0)return t.subarray(r,r+i)},o=function(t,e){var r=0;return r=(127&t[e])<<21,r|=(127&t[e+1])<<14,r|=(127&t[e+2])<<7,r|=127&t[e+3]},l=function(t,e){return a(t,e)&&o(t,e+6)+10<=t.length-e},u=function(t){for(var e=f(t),r=0;r>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:u+=String.fromCharCode(n);break;case 12:case 13:s=t[d++],u+=String.fromCharCode((31&n)<<6|63&s);break;case 14:s=t[d++],o=t[d++],u+=String.fromCharCode((15&n)<<12|(63&s)<<6|(63&o)<<0)}}return u};function b(){return i||void 0===self.TextDecoder||(i=new self.TextDecoder("utf-8")),i}},function(t,e,r){"use strict";function i(t,e,r){return Uint8Array.prototype.slice?t.slice(e,r):new Uint8Array(Array.prototype.slice.call(t,e,r))}r.d(e,"a",(function(){return i}))},function(t,e,r){"use strict";r.d(e,"c",(function(){return St})),r.d(e,"d",(function(){return At})),r.d(e,"a",(function(){return Rt})),r.d(e,"b",(function(){return Dt}));var i=r(0),a=r(2),n=r(14),s=r(3),o=r(7);var l=r(6),u=r(8),d=function(){function t(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.initPTS=null}var e=t.prototype;return e.resetInitSegment=function(t,e,r){this._id3Track={type:"id3",id:0,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},e.resetTimeStamp=function(){},e.resetContiguity=function(){},e.canParse=function(t,e){return!1},e.appendFrame=function(t,e,r){},e.demux=function(t,e){this.cachedData&&(t=Object(l.a)(this.cachedData,t),this.cachedData=null);var r,i,a=o.b(t,0),n=a?a.length:0,s=this._audioTrack,d=this._id3Track,f=a?o.d(a):void 0,c=t.length;for(0!==this.frameIndex&&null!==this.initPTS||(this.initPTS=h(f,e)),a&&a.length>0&&d.samples.push({pts:this.initPTS,dts:this.initPTS,data:a}),i=this.initPTS;n>>5}function m(t,e){return e+1=t.length)return!1;var i=p(t,e);if(i<=r)return!1;var a=e+i;return a===t.length||m(t,a)}return!1}function b(t,e,r,n,s){if(!t.samplerate){var o=function(t,e,r,n){var s,o,l,u,d=navigator.userAgent.toLowerCase(),h=n,f=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&e[r+2])>>>6);var v=(60&e[r+2])>>>2;if(!(v>f.length-1))return l=(1&e[r+2])<<2,l|=(192&e[r+3])>>>6,c.b.log("manifest codec:"+n+", ADTS type:"+s+", samplingIndex:"+v),/firefox/i.test(d)?v>=6?(s=5,u=new Array(4),o=v-3):(s=2,u=new Array(2),o=v):-1!==d.indexOf("android")?(s=2,u=new Array(2),o=v):(s=5,u=new Array(4),n&&(-1!==n.indexOf("mp4a.40.29")||-1!==n.indexOf("mp4a.40.5"))||!n&&v>=6?o=v-3:((n&&-1!==n.indexOf("mp4a.40.2")&&(v>=6&&1===l||/vivaldi/i.test(d))||!n&&1===l)&&(s=2,u=new Array(2)),o=v)),u[0]=s<<3,u[0]|=(14&v)>>1,u[1]|=(1&v)<<7,u[1]|=l<<3,5===s&&(u[1]|=(14&o)>>1,u[2]=(1&o)<<7,u[2]|=8,u[3]=0),{config:u,samplerate:f[v],channelCount:l,codec:"mp4a.40."+s,manifestCodec:h};t.trigger(i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+v})}(e,r,n,s);if(!o)return;t.config=o.config,t.samplerate=o.samplerate,t.channelCount=o.channelCount,t.codec=o.codec,t.manifestCodec=o.manifestCodec,c.b.log("parsed codec:"+t.codec+", rate:"+o.samplerate+", channels:"+o.channelCount)}}function T(t){return 9216e4/t}function E(t,e,r,i,a){var n=function(t,e,r,i,a){var n=g(t,e),s=p(t,e);if((s-=n)>0)return{headerLength:n,frameLength:s,stamp:r+i*a}}(e,r,i,a,T(t.samplerate));if(n){var s,o=n.frameLength,l=n.headerLength,u=n.stamp,d=l+o,h=Math.max(0,r+d-e.length);h?(s=new Uint8Array(d-l)).set(e.subarray(r+l,e.length),0):s=e.subarray(r+l,r+d);var f={unit:s,pts:u};return h||t.samples.push(f),{sample:f,length:d,missing:h}}}function S(t,e){return(S=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}var L=function(t){var e,r;function i(e,r){var i;return(i=t.call(this)||this).observer=void 0,i.config=void 0,i.observer=e,i.config=r,i}r=t,(e=i).prototype=Object.create(r.prototype),e.prototype.constructor=e,S(e,r);var a=i.prototype;return a.resetInitSegment=function(e,r,i){t.prototype.resetInitSegment.call(this,e,r,i),this._audioTrack={container:"audio/adts",type:"audio",id:0,pid:-1,sequenceNumber:0,isAAC:!0,samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}},i.probe=function(t){if(!t)return!1;for(var e=(o.b(t,0)||[]).length,r=t.length;e0},e.demux=function(t){var e=t,r={type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0};if(this.config.progressive){this.remainderData&&(e=Object(l.a)(this.remainderData,t));var i=Object(l.h)(e);this.remainderData=i.remainder,r.samples=i.valid||new Uint8Array}else r.samples=e;return{audioTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},avcTrack:r,id3Track:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},textTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0}}},e.flush=function(){var t={type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0};return t.samples=this.remainderData||new Uint8Array,this.remainderData=null,{audioTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},avcTrack:t,id3Track:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},textTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0}}},e.demuxSampleAes=function(t,e,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},e.destroy=function(){},t}();R.minProbeByteLength=1024;var D=R,_=null,k=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],x=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],w=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],C=[0,1,1,4];function O(t,e,r,i,a){if(!(r+24>e.length)){var n=I(e,r);if(n&&r+n.frameLength<=e.length){var s=i+a*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(r,r+n.frameLength),pts:s,dts:s};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}}function I(t,e){var r=t[e+1]>>3&3,i=t[e+1]>>1&3,a=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==r&&0!==a&&15!==a&&3!==n){var s=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*k[14*(3===r?3-i:3===i?3:4)+a-1],u=x[3*(3===r?0:2===r?1:2)+n],d=3===o?1:2,h=w[r][i],f=C[i],c=8*h*f,v=Math.floor(h*l/u+s)*f;if(null===_){var g=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);_=g?parseInt(g[1]):0}return!!_&&_<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:u,channelCount:d,frameLength:v,samplesPerFrame:c}}}function P(t,e){return 255===t[e]&&224==(224&t[e+1])&&0!=(6&t[e+1])}function F(t,e){return e+1t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,t-=(e=t>>3)>>3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)},e.readBits=function(t){var e=Math.min(this.bitsAvailable,t),r=this.word>>>32-e;return t>32&&c.b.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0?this.word<<=e:this.bytesAvailable>0&&this.loadWord(),(e=t-e)>0&&this.bitsAvailable?r<>>t))return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()},e.skipUEG=function(){this.skipBits(1+this.skipLZ())},e.skipEG=function(){this.skipBits(1+this.skipLZ())},e.readUEG=function(){var t=this.skipLZ();return this.readBits(t+1)-1},e.readEG=function(){var t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)},e.readBoolean=function(){return 1===this.readBits(1)},e.readUByte=function(){return this.readBits(8)},e.readUShort=function(){return this.readBits(16)},e.readUInt=function(){return this.readBits(32)},e.skipScalingList=function(t){for(var e=8,r=8,i=0;i=t.length)return void r();if(!(t[e].unit.length<32)){var i=this.decrypter.isSync();if(this.decryptAacSample(t,e,r,i),!i)return}}},e.getAvcEncryptedData=function(t){for(var e=16*Math.floor((t.length-48)/160)+16,r=new Int8Array(e),i=0,a=32;a<=t.length-16;a+=160,i+=16)r.set(t.subarray(a,a+16),i);return r},e.getAvcDecryptedUnit=function(t,e){for(var r=new Uint8Array(e),i=0,a=32;a<=t.length-16;a+=160,i+=16)t.set(r.subarray(i,i+16),a);return t},e.decryptAvcSample=function(t,e,r,i,a,n){var s=X(a.data),o=this.getAvcEncryptedData(s),l=this;this.decryptBuffer(o.buffer,(function(o){a.data=l.getAvcDecryptedUnit(s,o),n||l.decryptAvcSamples(t,e,r+1,i)}))},e.decryptAvcSamples=function(t,e,r,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,r=0){if(e>=t.length)return void i();for(var a=t[e].units;!(r>=a.length);r++){var n=a[r];if(!(n.data.length<=48||1!==n.type&&5!==n.type)){var s=this.decrypter.isSync();if(this.decryptAvcSample(t,e,r,i,n,s),!s)return}}}},t}(),U={video:1,audio:2,id3:3,text:4},G=function(){function t(t,e,r){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this.aacLastPTS=null,this._initPTS=null,this._initDTS=null,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=t,this.config=e,this.typeSupported=r}t.probe=function(e){var r=t.syncOffset(e);return!(r<0)&&(r&&c.b.warn("MPEG2-TS detected but first sync word found @ offset "+r+", junk ahead ?"),!0)},t.syncOffset=function(t){for(var e=Math.min(1e3,t.length-564),r=0;r>4>1){if((_=A+5+e[A+4])===A+188)continue}else _=A+4;switch(D){case f:R&&(v&&(o=V(v))&&this.parseAVCPES(o,!1),v={data:[],size:0}),v&&(v.data.push(e.subarray(_,A+188)),v.size+=A+188-_);break;case g:R&&(m&&(o=V(m))&&(d.isAAC?this.parseAACPES(o):this.parseMPEGPES(o)),m={data:[],size:0}),m&&(m.data.push(e.subarray(_,A+188)),m.size+=A+188-_);break;case p:R&&(y&&(o=V(y))&&this.parseID3PES(o),y={data:[],size:0}),y&&(y.data.push(e.subarray(_,A+188)),y.size+=A+188-_);break;case 0:R&&(_+=e[_]+1),E=this._pmtId=K(e,_);break;case E:R&&(_+=e[_]+1);var k=H(e,_,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,n);(f=k.avc)>0&&(u.pid=f),(g=k.audio)>0&&(d.pid=g,d.isAAC=k.isAAC),(p=k.id3)>0&&(h.pid=p),b&&!T&&(c.b.log("reparse from beginning"),b=!1,A=L-188),T=this.pmtParsed=!0;break;case 17:case 8191:break;default:b=!0}}else this.observer.emit(i.a.ERROR,i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!1,reason:"TS packet did not start with 0x47"});u.pesData=v,d.pesData=m,h.pesData=y;var x={audioTrack:d,avcTrack:u,id3Track:h,textTrack:this._txtTrack};return s&&this.extractRemainingSamples(x),x},e.flush=function(){var t,e=this.remainderData;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{audioTrack:this._audioTrack,avcTrack:this._avcTrack,textTrack:this._txtTrack,id3Track:this._id3Track},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t},e.extractRemainingSamples=function(t){var e,r=t.audioTrack,i=t.avcTrack,a=t.id3Track,n=i.pesData,s=r.pesData,o=a.pesData;n&&(e=V(n))?(this.parseAVCPES(e,!0),i.pesData=null):i.pesData=n,s&&(e=V(s))?(r.isAAC?this.parseAACPES(e):this.parseMPEGPES(e),r.pesData=null):(null!=s&&s.size&&c.b.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=s),o&&(e=V(o))?(this.parseID3PES(e),a.pesData=null):a.pesData=o},e.demuxSampleAes=function(t,e,r){var i=this.demux(t,r,!0,!this.config.progressive),a=this.sampleAes=new B(this.observer,this.config,e);return this.decrypt(i,a)},e.decrypt=function(t,e){return new Promise((function(r){var i=t.audioTrack,a=t.avcTrack;i.samples&&i.isAAC?e.decryptAacSamples(i.samples,0,(function(){a.samples?e.decryptAvcSamples(a.samples,0,0,(function(){r(t)})):r(t)})):a.samples&&e.decryptAvcSamples(a.samples,0,0,(function(){r(t)}))}))},e.destroy=function(){this._initPTS=this._initDTS=null,this._duration=0},e.parseAVCPES=function(t,e){var r,i=this,a=this._avcTrack,n=this.parseAVCNALu(t.data),s=this.avcSample,l=!1;t.data=null,s&&n.length&&!a.audFound&&(W(s,a),s=this.avcSample=j(!1,t.pts,t.dts,"")),n.forEach((function(e){switch(e.type){case 1:r=!0,s||(s=i.avcSample=j(!0,t.pts,t.dts,"")),s.frame=!0;var n=e.data;if(l&&n.length>4){var u=new N(n).readSliceType();2!==u&&4!==u&&7!==u&&9!==u||(s.key=!0)}break;case 5:r=!0,s||(s=i.avcSample=j(!0,t.pts,t.dts,"")),s.key=!0,s.frame=!0;break;case 6:r=!0;var d=new N(X(e.data));d.readUByte();for(var h=0,f=0,c=!1,v=0;!c&&d.bytesAvailable>1;){h=0;do{h+=v=d.readUByte()}while(255===v);f=0;do{f+=v=d.readUByte()}while(255===v);if(4===h&&0!==d.bytesAvailable){if(c=!0,181===d.readUByte())if(49===d.readUShort())if(1195456820===d.readUInt())if(3===d.readUByte()){for(var g=d.readUByte(),p=31&g,m=[g,d.readUByte()],y=0;y16){for(var b=[],T=0;T<16;T++)b.push(d.readUByte().toString(16)),3!==T&&5!==T&&7!==T&&9!==T||b.push("-");for(var E=f-16,S=new Uint8Array(E),L=0;L=0){var h={data:t.subarray(u,l-n-1),type:d};o.push(h)}else{var f=this.getLastNalUnit();if(f&&(s&&l<=4-s&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-s)),(r=l-n-1)>0)){var c=new Uint8Array(f.data.byteLength+r);c.set(f.data,0),c.set(t.subarray(0,r),f.data.byteLength),f.data=c}}l=0&&n>=0){var v={data:t.subarray(u,i),type:d,state:n};o.push(v)}if(0===o.length){var g=this.getLastNalUnit();if(g){var p=new Uint8Array(g.data.byteLength+t.byteLength);p.set(g.data,0),p.set(t,g.data.byteLength),g.data=p}}return a.naluState=n,o},e.parseAACPES=function(t){var e,r,n,s,o,l=0,u=this._audioTrack,d=this.aacOverFlow,h=t.data;if(d){this.aacOverFlow=null;var f=d.sample.unit.byteLength,v=Math.min(d.missing,f),g=f-v;d.sample.unit.set(h.subarray(0,v),g),u.samples.push(d.sample),l=d.missing}for(e=l,r=h.length;e1;){var l=new Uint8Array(o[0].length+o[1].length);l.set(o[0]),l.set(o[1],o[0].length),o[0]=l,o.splice(1,1)}if(1===((e=o[0])[0]<<16)+(e[1]<<8)+e[2]){if((r=(e[4]<<8)+e[5])&&r>t.size-6)return null;var u=e[7];192&u&&(a=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&u?a-(n=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2)>54e5&&(c.b.warn(Math.round((a-n)/9e4)+"s delta between PTS and DTS, align them"),a=n):n=a);var d=(i=e[8])+9;if(t.size<=d)return null;t.size-=d;for(var h=new Uint8Array(t.size),f=0,v=o.length;fg){d-=g;continue}e=e.subarray(d),g-=d,d=0}h.set(e,s),s+=g}return r&&(r-=i+3),{data:h,pts:a,dts:n,len:r}}return null}function W(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){var r=e.samples,i=r.length;if(!i)return void e.dropped++;var a=r[i-1];t.pts=a.pts,t.dts=a.dts}e.samples.push(t)}t.debug.length&&c.b.log(t.pts+"/"+t.dts+":"+t.debug)}function Y(t,e){var r=t.length;if(r>0){if(e.pts>=t[r-1].pts)t.push(e);else for(var i=r-1;i>=0;i--)if(e.pts1?r-1:0),a=1;a>24&255,o[1]=e>>16&255,o[2]=e>>8&255,o[3]=255&e,o.set(t,4),n=0,e=8;n>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,85,196,0,0]))},t.mdia=function(e){return t.box(t.types.mdia,t.mdhd(e.timescale,e.duration),t.hdlr(e.type),t.minf(e))},t.mfhd=function(e){return t.box(t.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))},t.minf=function(e){return"audio"===e.type?t.box(t.types.minf,t.box(t.types.smhd,t.SMHD),t.DINF,t.stbl(e)):t.box(t.types.minf,t.box(t.types.vmhd,t.VMHD),t.DINF,t.stbl(e))},t.moof=function(e,r,i){return t.box(t.types.moof,t.mfhd(e),t.traf(i,r))},t.moov=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trak(e[r]);return t.box.apply(null,[t.types.moov,t.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(t.mvex(e)))},t.mvex=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trex(e[r]);return t.box.apply(null,[t.types.mvex].concat(i))},t.mvhd=function(e,r){r*=e;var i=Math.floor(r/(J+1)),a=Math.floor(r%(J+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return t.box(t.types.mvhd,n)},t.sdtp=function(e){var r,i,a=e.samples||[],n=new Uint8Array(4+a.length);for(r=0;r>>8&255),n.push(255&a),n=n.concat(Array.prototype.slice.call(i));for(r=0;r>>8&255),s.push(255&a),s=s.concat(Array.prototype.slice.call(i));var o=t.box(t.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|e.sps.length].concat(n).concat([e.pps.length]).concat(s))),l=e.width,u=e.height,d=e.pixelRatio[0],h=e.pixelRatio[1];return t.box(t.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,t.box(t.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),t.box(t.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))},t.esds=function(t){var e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))},t.mp4a=function(e){var r=e.samplerate;return t.box(t.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),t.box(t.types.esds,t.esds(e)))},t.mp3=function(e){var r=e.samplerate;return t.box(t.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))},t.stsd=function(e){return"audio"===e.type?e.isAAC||"mp3"!==e.codec?t.box(t.types.stsd,t.STSD,t.mp4a(e)):t.box(t.types.stsd,t.STSD,t.mp3(e)):t.box(t.types.stsd,t.STSD,t.avc1(e))},t.tkhd=function(e){var r=e.id,i=e.duration*e.timescale,a=e.width,n=e.height,s=Math.floor(i/(J+1)),o=Math.floor(i%(J+1));return t.box(t.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,a>>8&255,255&a,0,0,n>>8&255,255&n,0,0]))},t.traf=function(e,r){var i=t.sdtp(e),a=e.id,n=Math.floor(r/(J+1)),s=Math.floor(r%(J+1));return t.box(t.types.traf,t.box(t.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a])),t.box(t.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,s>>24,s>>16&255,s>>8&255,255&s])),t.trun(e,i.length+16+20+8+16+8+8),i)},t.trak=function(e){return e.duration=e.duration||4294967295,t.box(t.types.trak,t.tkhd(e),t.mdia(e))},t.trex=function(e){var r=e.id;return t.box(t.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},t.trun=function(e,r){var i,a,n,s,o,l,u=e.samples||[],d=u.length,h=12+16*d,f=new Uint8Array(h);for(r+=8+h,f.set([0,0,15,1,d>>>24&255,d>>>16&255,d>>>8&255,255&d,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i>>24&255,n>>>16&255,n>>>8&255,255&n,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return t.box(t.types.trun,f)},t.initSegment=function(e){t.types||t.init();var r=t.moov(e),i=new Uint8Array(t.FTYP.byteLength+r.byteLength);return i.set(t.FTYP),i.set(r,t.FTYP.byteLength),i},t}();tt.types=void 0,tt.HDLR_TYPES=void 0,tt.STTS=void 0,tt.STSC=void 0,tt.STCO=void 0,tt.STSZ=void 0,tt.VMHD=void 0,tt.SMHD=void 0,tt.STSD=void 0,tt.FTYP=void 0,tt.DINF=void 0;var et=tt,rt=r(4);function it(t,e,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var a=t*e*r;return i?Math.round(a):a}function at(t,e){return void 0===e&&(e=!1),it(t,1e3,1/9e4,e)}function nt(){return(nt=Object.assign||function(t){for(var e=1;e0?t:r.pts}),t[0].pts);return e&&c.b.debug("PTS rollover detected"),r},e.remux=function(t,e,r,i,a,n,s,o){var l,u,d,h,f,v,g=a,p=a,m=t.pid>-1,y=e.pid>-1,b=e.samples.length,T=t.samples.length>0,E=b>1;if((!m||T)&&(!y||E)||this.ISGenerated||s){this.ISGenerated||(d=this.generateIS(t,e,a));var S=this.isVideoContiguous,L=-1;if(E&&(L=function(t){for(var e=0;e0){c.b.warn("[mp4-remuxer]: Dropped "+L+" out of "+b+" video samples due to a missing keyframe");var A=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(L),e.dropped+=L,p+=(e.samples[0].pts-A)/(e.timescale||9e4)}else-1===L&&(c.b.warn("[mp4-remuxer]: No keyframe found out of "+b+" video samples"),v=!1);if(this.ISGenerated){if(T&&E){var R=this.getVideoStartPts(e.samples),D=(dt(t.samples[0].pts,R)-R)/e.inputTimeScale;g+=Math.max(0,D),p+=Math.max(0,-D)}if(T){if(t.samplerate||(c.b.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(t,e,a)),u=this.remuxAudio(t,g,this.isAudioContiguous,n,y||E||o===rt.b.AUDIO?p:void 0),E){var _=u?u.endPTS-u.startPTS:0;e.inputTimeScale||(c.b.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(t,e,a)),l=this.remuxVideo(e,p,S,_)}}else E&&(l=this.remuxVideo(e,p,S,0));l&&(l.firstKeyFrame=L,l.independent=-1!==L)}}return this.ISGenerated&&(r.samples.length&&(f=this.remuxID3(r,a)),i.samples.length&&(h=this.remuxText(i,a))),{audio:u,video:l,initSegment:d,independent:v,text:h,id3:f}},e.generateIS=function(t,e,r){var i,a,n,o=t.samples,l=e.samples,u=this.typeSupported,d={},h=!Object(s.a)(this._initPTS),f="audio/mp4";if(h&&(i=a=1/0),t.config&&o.length&&(t.timescale=t.samplerate,t.isAAC||(u.mpeg?(f="audio/mpeg",t.codec=""):u.mp3&&(t.codec="mp3")),d.audio={id:"audio",container:f,codec:t.codec,initSegment:!t.isAAC&&u.mpeg?new Uint8Array(0):et.initSegment([t]),metadata:{channelCount:t.channelCount}},h&&(n=t.inputTimeScale,i=a=o[0].pts-Math.round(n*r))),e.sps&&e.pps&&l.length&&(e.timescale=e.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:et.initSegment([e]),metadata:{width:e.width,height:e.height}},h)){n=e.inputTimeScale;var c=this.getVideoStartPts(l),v=Math.round(n*r);a=Math.min(a,dt(l[0].dts,c)-v),i=Math.min(i,c-v)}if(Object.keys(d).length)return this.ISGenerated=!0,h&&(this._initPTS=i,this._initDTS=a),{tracks:d,initPTS:i,timescale:n}},e.remuxVideo=function(t,e,r,n){var s,o,l,u=t.inputTimeScale,d=t.samples,h=[],f=d.length,v=this._initPTS,g=this.nextAvcDts,p=8,m=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,b=0,T=!1;r&&null!==g||(g=e*u-(d[0].pts-dt(d[0].dts,d[0].pts)));for(var E=0;ES.pts){b=Math.max(Math.min(b,S.pts-S.dts),-18e3)}S.dts0?E-1:E].dts&&(T=!0)}T&&d.sort((function(t,e){var r=t.dts-e.dts,i=t.pts-e.pts;return r||i})),o=d[0].dts,l=d[d.length-1].dts;var L=Math.round((l-o)/(f-1));if(b<0){if(b<-2*L){c.b.warn("PTS < DTS detected in video samples, offsetting DTS from PTS by "+at(-L,!0)+" ms");for(var A=b,R=0;RL;if(k||_<-1){k?c.b.warn("AVC: "+at(_,!0)+" ms ("+_+"dts) hole between fragments detected, filling it"):c.b.warn("AVC: "+at(-_,!0)+" ms ("+_+"dts) overlapping between fragments detected"),o=g;var x=d[0].pts-_;d[0].dts=o,d[0].pts=x,c.b.log("Video: First PTS/DTS adjusted: "+at(x,!0)+"/"+at(o,!0)+", delta: "+at(_,!0)+" ms")}}lt&&(o=Math.max(0,o));for(var w=0,C=0,O=0;O0?j-1:j].dts;if(Q.stretchShortVideoTrack&&null!==this.nextAudioPts){var Z=Math.floor(Q.maxBufferHole*u),J=(n?m+n*u:this.nextAudioPts)-K.pts;J>Z?((s=J-$)<0&&(s=$),c.b.log("[mp4-remuxer]: It is approximately "+J/90+" ms to the next segment; using duration "+s/90+" ms for the last video frame.")):s=$}else s=$}var tt=Math.round(K.pts-K.dts);h.push(new ht(K.key,s,V,tt))}if(h.length&&st&&st<70){var rt=h[0].flags;rt.dependsOn=2,rt.isNonSync=0}this.nextAvcDts=g=l+s,this.isVideoContiguous=!0;var it={data1:et.moof(t.sequenceNumber++,o,nt({},t,{samples:h})),data2:B,startPTS:m/u,endPTS:(y+s)/u,startDTS:o/u,endDTS:g/u,type:"video",hasAudio:!1,hasVideo:!0,nb:h.length,dropped:t.dropped};return t.samples=[],t.dropped=0,it},e.remuxAudio=function(t,e,r,n,s){var o=t.inputTimeScale,l=o/(t.samplerate?t.samplerate:o),u=t.isAAC?1024:1152,d=u*l,h=this._initPTS,f=!t.isAAC&&this.typeSupported.mpeg,v=[],g=t.samples,p=f?0:8,m=this.nextAudioPts||-1,y=e*o;if(this.isAudioContiguous=r=r||g.length&&m>0&&(n&&Math.abs(y-m)<9e3||Math.abs(dt(g[0].pts-h,y)-m)<20*d),g.forEach((function(t){t.pts=dt(t.pts-h,y)})),!r||m<0){if(!(g=g.filter((function(t){return t.pts>=0}))).length)return;m=0===s?0:n?Math.max(0,y):g[0].pts}if(t.isAAC)for(var b=void 0!==s,T=this.config.maxAudioFramesDrift,E=0,S=m;E=T*d&&D<1e4&&b){var _=Math.round(R/d);(S=A-_*d)<0&&(_--,S+=d),0===E&&(this.nextAudioPts=m=S),c.b.warn("[mp4-remuxer]: Injecting "+_+" audio frame @ "+(S/o).toFixed(3)+"s due to "+Math.round(1e3*R/o)+" ms gap.");for(var k=0;k<_;k++){var x=Math.max(S,0),w=Z.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);w||(c.b.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),w=L.unit.subarray()),g.splice(E,0,{unit:w,pts:x}),S+=d,E++}}L.pts=S,S+=d}for(var C,O=null,I=null,P=0,F=g.length;F--;)P+=g[F].unit.byteLength;for(var M=0,N=g.length;M0))return;P+=p;try{C=new Uint8Array(P)}catch(t){return void this.observer.emit(i.a.ERROR,i.a.ERROR,{type:a.b.MUX_ERROR,details:a.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:P,reason:"fail allocating audio mdat "+P})}f||(new DataView(C.buffer).setUint32(0,P),C.set(et.types.mdat,4))}C.set(U,p);var j=U.byteLength;p+=j,v.push(new ht(!0,u,j,0)),I=G}var K=v.length;if(K){var H=v[v.length-1];this.nextAudioPts=m=I+l*H.duration;var V=f?new Uint8Array(0):et.moof(t.sequenceNumber++,O/l,nt({},t,{samples:v}));t.samples=[];var W=O/o,Y=m/o,X={data1:V,data2:C,startPTS:W,endPTS:Y,startDTS:W,endDTS:Y,type:"audio",hasAudio:!0,hasVideo:!1,nb:K};return this.isAudioContiguous=!0,X}},e.remuxEmptyAudio=function(t,e,r,i){var a=t.inputTimeScale,n=a/(t.samplerate?t.samplerate:a),s=this.nextAudioPts,o=(null!==s?s:i.startDTS*a)+this._initDTS,l=i.endDTS*a+this._initDTS,u=1024*n,d=Math.ceil((l-o)/u),h=Z.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(c.b.warn("[mp4-remuxer]: remux empty Audio"),h){for(var f=[],v=0;v4294967296;)t+=r;return t}var ht=function(t,e,r,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=r,this.cts=i,this.flags=new ft(t)},ft=function(t){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=t?2:1,this.isNonSync=t?0:1},ct=r(5),vt=function(){function t(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=void 0,this.initTracks=void 0,this.lastEndDTS=null}var e=t.prototype;return e.destroy=function(){},e.resetTimeStamp=function(t){this.initPTS=t,this.lastEndDTS=null},e.resetNextTimestamp=function(){this.lastEndDTS=null},e.resetInitSegment=function(t,e,r){this.audioCodec=e,this.videoCodec=r,this.generateInitSegment(t),this.emitInitSegment=!0},e.generateInitSegment=function(t){var e=this.audioCodec,r=this.videoCodec;if(!t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var i=this.initData=Object(l.f)(t);e||(e=pt(i.audio,ct.a.AUDIO)),r||(r=pt(i.video,ct.a.VIDEO));var a={};i.audio&&i.video?a.audiovideo={container:"video/mp4",codec:e+","+r,initSegment:t,id:"main"}:i.audio?a.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:i.video?a.video={container:"video/mp4",codec:r,initSegment:t,id:"main"}:c.b.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=a},e.remux=function(t,e,r,i,a){var n=this.initPTS,o=this.lastEndDTS,u={audio:void 0,video:void 0,text:i,id3:r,initSegment:void 0};Object(s.a)(o)||(o=this.lastEndDTS=a||0);var d=e.samples;if(!d||!d.length)return u;var h={initPTS:void 0,timescale:1},f=this.initData;if(f&&f.length||(this.generateInitSegment(d),f=this.initData),!f||!f.length)return c.b.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1),Object(s.a)(n)||(this.initPTS=h.initPTS=n=gt(f,d,o));var v=Object(l.c)(d,f),g=o,p=v+g;Object(l.e)(f,d,n),v>0?this.lastEndDTS=p:(c.b.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var m=!!f.audio,y=!!f.video,b="";m&&(b+="audio"),y&&(b+="video");var T={data1:d,startPTS:g,startDTS:g,endPTS:p,endDTS:p,type:b,hasAudio:m,hasVideo:y,nb:1,dropped:0};return u.audio="audio"===T.type?T:void 0,u.video="audio"!==T.type?T:void 0,u.text=i,u.id3=r,u.initSegment=h,u},t}(),gt=function(t,e,r){return Object(l.d)(t,e)-r};function pt(t,e){var r=null==t?void 0:t.codec;return r&&r.length>4?r:"hvc1"===r?"hvc1.1.c.L120.90":"av01"===r?"av01.0.04M.08":"avc1"===r||e===ct.a.VIDEO?"avc1.42e01e":"mp4a.40.5"}var mt,yt=vt,bt=r(16);try{mt=self.performance.now.bind(self.performance)}catch(t){c.b.debug("Unable to use Performance API on this environment"),mt=self.Date.now}var Tt=[{demux:q,remux:ut},{demux:D,remux:yt},{demux:A,remux:ut},{demux:$,remux:ut}],Et=1024;Tt.forEach((function(t){var e=t.demux;Et=Math.max(Et,e.minProbeByteLength)}));var St=function(){function t(t,e,r,i,a){this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.cache=new bt.a,this.observer=t,this.typeSupported=e,this.config=r,this.vendor=i,this.id=a}var e=t.prototype;return e.configure=function(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()},e.push=function(t,e,r,i){var a=this,n=r.transmuxing;n.executeStart=mt();var s=new Uint8Array(t),o=this.cache,u=this.config,d=this.currentTransmuxState,h=this.transmuxConfig;i&&(this.currentTransmuxState=i);var f=function(t,e){var r=null;t.byteLength>0&&null!=e&&null!=e.key&&null!==e.iv&&null!=e.method&&(r=e);return r}(s,e);if(f&&"AES-128"===f.method){var c=this.getDecrypter();if(!u.enableSoftwareAES)return this.decryptionPromise=c.webCryptoDecrypt(s,f.key.buffer,f.iv.buffer).then((function(t){var e=a.push(t,null,r);return a.decryptionPromise=null,e})),this.decryptionPromise;var v=c.softwareDecrypt(s,f.key.buffer,f.iv.buffer);if(!v)return n.executeEnd=mt(),Lt(r);s=new Uint8Array(v)}var g=i||d,p=g.contiguous,m=g.discontinuity,y=g.trackSwitch,b=g.accurateTimeOffset,T=g.timeOffset,E=h.audioCodec,S=h.videoCodec,L=h.defaultInitPts,A=h.duration,R=h.initSegmentData;if((m||y)&&this.resetInitSegment(R,E,S,A),m&&this.resetInitialTimestamp(L),p||this.resetContiguity(),this.needsProbing(s,m,y)){if(o.dataLength){var D=o.flush();s=Object(l.a)(D,s)}this.configureTransmuxer(s,h)}var _=this.transmux(s,f,T,b,r),k=this.currentTransmuxState;return k.contiguous=!0,k.discontinuity=!1,k.trackSwitch=!1,n.executeEnd=mt(),_},e.flush=function(t){var e=this,r=t.transmuxing;r.executeStart=mt();var n=this.decrypter,s=this.cache,o=this.currentTransmuxState,l=this.decryptionPromise;if(l)return l.then((function(){return e.flush(t)}));var u=[],d=o.timeOffset;if(n){var h=n.flush();h&&u.push(this.push(h,null,t))}var f=s.dataLength;s.reset();var c=this.demuxer,v=this.remuxer;if(!c||!v)return f>=Et&&this.observer.emit(i.a.ERROR,i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"}),r.executeEnd=mt(),[Lt(t)];var g=c.flush(d);return At(g)?g.then((function(r){return e.flushRemux(u,r,t),u})):(this.flushRemux(u,g,t),u)},e.flushRemux=function(t,e,r){var i=e.audioTrack,a=e.avcTrack,n=e.id3Track,s=e.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;c.b.log("[transmuxer.ts]: Flushed fragment "+r.sn+(r.part>-1?" p: "+r.part:"")+" of level "+r.level);var d=this.remuxer.remux(i,a,n,s,u,l,!0,this.id);t.push({remuxResult:d,chunkMeta:r}),r.transmuxing.executeEnd=mt()},e.resetInitialTimestamp=function(t){var e=this.demuxer,r=this.remuxer;e&&r&&(e.resetTimeStamp(t),r.resetTimeStamp(t))},e.resetContiguity=function(){var t=this.demuxer,e=this.remuxer;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())},e.resetInitSegment=function(t,e,r,i){var a=this.demuxer,n=this.remuxer;a&&n&&(a.resetInitSegment(e,r,i),n.resetInitSegment(t,e,r))},e.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},e.transmux=function(t,e,r,i,a){return e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,r,i,a):this.transmuxUnencrypted(t,r,i,a)},e.transmuxUnencrypted=function(t,e,r,i){var a=this.demuxer.demux(t,e,!1,!this.config.progressive),n=a.audioTrack,s=a.avcTrack,o=a.id3Track,l=a.textTrack;return{remuxResult:this.remuxer.remux(n,s,o,l,e,r,!1,this.id),chunkMeta:i}},e.transmuxSampleAes=function(t,e,r,i,a){var n=this;return this.demuxer.demuxSampleAes(t,e,r).then((function(t){return{remuxResult:n.remuxer.remux(t.audioTrack,t.avcTrack,t.id3Track,t.textTrack,r,i,!1,n.id),chunkMeta:a}}))},e.configureTransmuxer=function(t,e){for(var r,i=this.config,a=this.observer,n=this.typeSupported,s=this.vendor,o=e.audioCodec,l=e.defaultInitPts,u=e.duration,d=e.initSegmentData,h=e.videoCodec,f=0,v=Tt.length;f>>8^255&p^99,t[c]=p,e[p]=c;var m=f[c],y=f[m],b=f[y],T=257*f[p]^16843008*p;i[c]=T<<24|T>>>8,a[c]=T<<16|T>>>16,n[c]=T<<8|T>>>24,s[c]=T,T=16843009*b^65537*y^257*m^16843008*c,l[p]=T<<24|T>>>8,u[p]=T<<16|T>>>16,d[p]=T<<8|T>>>24,h[p]=T,c?(c=m^f[f[f[b^m]]],v^=f[f[v]]):c=v=1}},e.expandKey=function(t){for(var e=this.uint8ArrayToUint32Array_(t),r=!0,i=0;i0}),!1)}t.exports=function(t,e){e=e||{};var a={main:r.m},o=e.all?{main:Object.keys(a.main)}:function(t,e){for(var r={main:[e]},i={main:[]},a={main:{}};s(r);)for(var o=Object.keys(r),l=0;lt.endSN||e>0||0===e&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay},e=t,(r=[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&Object(a.a)(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var t=this.driftEndTime-this.driftStartTime;return t>0?1e3*(this.driftEnd-this.driftStart)/t:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){var t;return null!==(t=this.fragments)&&void 0!==t&&t.length?this.fragments[this.fragments.length-1].end:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].index:-1}},{key:"lastPartSn",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}])&&d(e.prototype,r),i&&d(e,i),t}(),f=r(15),c=/^(\d+)x(\d+)$/,v=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,g=function(){function t(e){for(var r in"string"==typeof e&&(e=t.parseAttrList(e)),e)e.hasOwnProperty(r)&&(this[r]=e[r])}var e=t.prototype;return e.decimalInteger=function(t){var e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e},e.hexadecimalInteger=function(t){if(this[t]){var e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;for(var r=new Uint8Array(e.length/2),i=0;iNumber.MAX_SAFE_INTEGER?1/0:e},e.decimalFloatingPoint=function(t){return parseFloat(this[t])},e.optionalFloat=function(t,e){var r=this[t];return r?parseFloat(r):e},e.enumeratedString=function(t){return this[t]},e.bool=function(t){return"YES"===this[t]},e.decimalResolution=function(t){var e=c.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}},t.parseAttrList=function(t){var e,r={};for(v.lastIndex=0;null!==(e=v.exec(t));){var i=e[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[e[1]]=i}return r},t}(),p={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dvav:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}};function m(t,e){return MediaSource.isTypeSupported((e||"video")+'/mp4;codecs="'+t+'"')}var y=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-SESSION-DATA:([^\r\n]*)[\r\n]+/g,b=/#EXT-X-MEDIA:(.*)/g,T=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),E=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(PLAYLIST-TYPE):(.+)/.source,/#EXT-X-(MEDIA-SEQUENCE): *(\d+)/.source,/#EXT-X-(SKIP):(.+)/.source,/#EXT-X-(TARGETDURATION): *(\d+)/.source,/#EXT-X-(KEY):(.+)/.source,/#EXT-X-(START):(.+)/.source,/#EXT-X-(ENDLIST)/.source,/#EXT-X-(DISCONTINUITY-SEQ)UENCE: *(\d+)/.source,/#EXT-X-(DIS)CONTINUITY/.source,/#EXT-X-(VERSION):(\d+)/.source,/#EXT-X-(MAP):(.+)/.source,/#EXT-X-(SERVER-CONTROL):(.+)/.source,/#EXT-X-(PART-INF):(.+)/.source,/#EXT-X-(GAP)/.source,/#EXT-X-(BITRATE):\s*(\d+)/.source,/#EXT-X-(PART):(.+)/.source,/#EXT-X-(PRELOAD-HINT):(.+)/.source,/#EXT-X-(RENDITION-REPORT):(.+)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),S=/\.(mp4|m4s|m4v|m4a)$/i;var L=function(){function t(){}return t.findGroup=function(t,e){for(var r=0;r2){var r=e.shift()+".";return r+=parseInt(e.shift()).toString(16),r+=("000"+parseInt(e.shift()).toString(16)).substr(-4)}return t},t.resolve=function(t,e){return i.buildAbsoluteURL(e,t,{alwaysNormalize:!0})},t.parseMasterPlaylist=function(e,r){var i,a=[],n={},s=!1;for(y.lastIndex=0;null!=(i=y.exec(e));)if(i[1]){var o=new g(i[1]),l={attrs:o,bitrate:o.decimalInteger("AVERAGE-BANDWIDTH")||o.decimalInteger("BANDWIDTH"),name:o.NAME,url:t.resolve(i[2],r)},u=o.decimalResolution("RESOLUTION");u&&(l.width=u.width,l.height=u.height),A((o.CODECS||"").split(/[ ,]+/).filter((function(t){return t})),l),l.videoCodec&&-1!==l.videoCodec.indexOf("avc1")&&(l.videoCodec=t.convertAVC1ToAVCOTI(l.videoCodec)),a.push(l)}else if(i[3]){var d=new g(i[3]);d["DATA-ID"]&&(s=!0,n[d["DATA-ID"]]=d)}return{levels:a,sessionData:s?n:null}},t.parseMasterPlaylistMedia=function(e,r,i,a){var n;void 0===a&&(a=[]);var s=[],o=0;for(b.lastIndex=0;null!==(n=b.exec(e));){var l=new g(n[1]);if(l.TYPE===i){var u={attrs:l,bitrate:0,id:o++,groupId:l["GROUP-ID"],instreamId:l["INSTREAM-ID"],name:l.NAME||l.LANGUAGE||"",type:i,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:l.LANGUAGE,url:l.URI?t.resolve(l.URI,r):""};if(a.length){var d=t.findGroup(a,u.groupId)||a[0];R(u,d,"audioCodec"),R(u,d,"textCodec")}s.push(u)}}return s},t.parseLevelPlaylist=function(t,e,r,n,s){var l,d,c,v=new h(e),p=v.fragments,m=null,y=0,b=0,L=0,A=0,R=null,_=new u.b(n,e),k=-1,x=!1;for(T.lastIndex=0,v.m3u8=t;null!==(l=T.exec(t));){x&&(x=!1,(_=new u.b(n,e)).start=L,_.sn=y,_.cc=A,_.level=r,m&&(_.initSegment=m,_.rawProgramDateTime=m.rawProgramDateTime));var w=l[1];if(w){_.duration=parseFloat(w);var C=(" "+l[2]).slice(1);_.title=C||null,_.tagList.push(C?["INF",w,C]:["INF",w])}else if(l[3])Object(a.a)(_.duration)&&(_.start=L,c&&(_.levelkey=c),_.sn=y,_.level=r,_.cc=A,_.urlId=s,p.push(_),_.relurl=(" "+l[3]).slice(1),D(_,R),R=_,L+=_.duration,y++,b=0,x=!0);else if(l[4]){var O=(" "+l[4]).slice(1);R?_.setByteRange(O,R):_.setByteRange(O)}else if(l[5])_.rawProgramDateTime=(" "+l[5]).slice(1),_.tagList.push(["PROGRAM-DATE-TIME",_.rawProgramDateTime]),-1===k&&(k=p.length);else{if(!(l=l[0].match(E))){o.b.warn("No matches on slow regex match for level playlist!");continue}for(d=1;d-1){o.b.warn("Keyformat "+X+" is not supported from the manifest");continue}if("identity"!==X)continue;K&&(c=f.a.fromURL(e,H),H&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(K)>=0&&(c.method=K,c.keyFormat=X,Y&&(c.keyID=Y),W&&(c.keyFormatVersions=W),c.iv=V));break;case"START":var q=new g(P).decimalFloatingPoint("TIME-OFFSET");Object(a.a)(q)&&(v.startTimeOffset=q);break;case"MAP":var z=new g(P);_.relurl=z.URI,z.BYTERANGE&&_.setByteRange(z.BYTERANGE),_.level=r,_.sn="initSegment",c&&(_.levelkey=c),_.initSegment=null,m=_,x=!0;break;case"SERVER-CONTROL":var Q=new g(P);v.canBlockReload=Q.bool("CAN-BLOCK-RELOAD"),v.canSkipUntil=Q.optionalFloat("CAN-SKIP-UNTIL",0),v.canSkipDateRanges=v.canSkipUntil>0&&Q.bool("CAN-SKIP-DATERANGES"),v.partHoldBack=Q.optionalFloat("PART-HOLD-BACK",0),v.holdBack=Q.optionalFloat("HOLD-BACK",0);break;case"PART-INF":var $=new g(P);v.partTarget=$.decimalFloatingPoint("PART-TARGET");break;case"PART":var Z=v.partList;Z||(Z=v.partList=[]);var J=b>0?Z[Z.length-1]:void 0,tt=b++,et=new u.c(new g(P),_,e,tt,J);Z.push(et),_.duration+=et.duration;break;case"PRELOAD-HINT":var rt=new g(P);v.preloadHint=rt;break;case"RENDITION-REPORT":var it=new g(P);v.renditionReports=v.renditionReports||[],v.renditionReports.push(it);break;default:o.b.warn("line parsed but not handled: "+l)}}}R&&!R.relurl?(p.pop(),L-=R.duration,v.partList&&(v.fragmentHint=R)):v.partList&&(D(_,R),_.cc=A,v.fragmentHint=_);var at=p.length,nt=p[0],st=p[at-1];if((L+=v.skippedSegments*v.targetduration)>0&&at&&st){v.averagetargetduration=L/at;var ot=st.sn;v.endSN="initSegment"!==ot?ot:0,nt&&(v.startCC=nt.cc,nt.initSegment||v.fragments.every((function(t){return t.relurl&&(e=t.relurl,S.test(null!=(r=null===(a=i.parseURL(e))||void 0===a?void 0:a.path)?r:""));var e,r,a}))&&(o.b.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),(_=new u.b(n,e)).relurl=st.relurl,_.level=r,_.sn="initSegment",nt.initSegment=_,v.needSidxRanges=!0))}else v.endSN=0,v.startCC=0;return v.fragmentHint&&(L+=v.fragmentHint.duration),v.totalduration=L,v.endCC=A,k>0&&function(t,e){for(var r=t[e],i=e;i--;){var a=t[i];if(!a)return;a.programDateTime=r.programDateTime-1e3*a.duration,r=a}}(p,k),v},t}();function A(t,e){["video","audio","text"].forEach((function(r){var i=t.filter((function(t){return function(t,e){var r=p[e];return!!r&&!0===r[t.slice(0,4)]}(t,r)}));if(i.length){var a=i.filter((function(t){return 0===t.lastIndexOf("avc1",0)||0===t.lastIndexOf("mp4a",0)}));e[r+"Codec"]=a.length>0?a[0]:i[0],t=t.filter((function(t){return-1===i.indexOf(t)}))}})),e.unknownCodecs=t}function R(t,e,r){var i=e[r];i&&(t[r]=i)}function D(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),Object(a.a)(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}var _=r(4);function k(t,e){var r=t.url;return void 0!==r&&0!==r.indexOf("data:")||(r=e.url),r}var x=function(){function t(t){this.hls=void 0,this.loaders=Object.create(null),this.hls=t,this.registerListeners()}var e=t.prototype;return e.registerListeners=function(){var t=this.hls;t.on(n.a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.a.LEVEL_LOADING,this.onLevelLoading,this),t.on(n.a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(n.a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.unregisterListeners=function(){var t=this.hls;t.off(n.a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.a.LEVEL_LOADING,this.onLevelLoading,this),t.off(n.a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(n.a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.createInternalLoader=function(t){var e=this.hls.config,r=e.pLoader,i=e.loader,a=new(r||i)(e);return t.loader=a,this.loaders[t.type]=a,a},e.getInternalLoader=function(t){return this.loaders[t.type]},e.resetInternalLoader=function(t){this.loaders[t]&&delete this.loaders[t]},e.destroyInternalLoaders=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}},e.destroy=function(){this.unregisterListeners(),this.destroyInternalLoaders()},e.onManifestLoading=function(t,e){var r=e.url;this.load({id:null,groupId:null,level:0,responseType:"text",type:_.a.MANIFEST,url:r,deliveryDirectives:null})},e.onLevelLoading=function(t,e){var r=e.id,i=e.level,a=e.url,n=e.deliveryDirectives;this.load({id:r,groupId:null,level:i,responseType:"text",type:_.a.LEVEL,url:a,deliveryDirectives:n})},e.onAudioTrackLoading=function(t,e){var r=e.id,i=e.groupId,a=e.url,n=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:_.a.AUDIO_TRACK,url:a,deliveryDirectives:n})},e.onSubtitleTrackLoading=function(t,e){var r=e.id,i=e.groupId,a=e.url,n=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:_.a.SUBTITLE_TRACK,url:a,deliveryDirectives:n})},e.load=function(t){var e,r,i,a,n,s,l=this.hls.config,u=this.getInternalLoader(t);if(u){var d=u.context;if(d&&d.url===t.url)return void o.b.trace("[playlist-loader]: playlist request ongoing");o.b.log("[playlist-loader]: aborting previous loader for type: "+t.type),u.abort()}switch(t.type){case _.a.MANIFEST:r=l.manifestLoadingMaxRetry,i=l.manifestLoadingTimeOut,a=l.manifestLoadingRetryDelay,n=l.manifestLoadingMaxRetryTimeout;break;case _.a.LEVEL:case _.a.AUDIO_TRACK:case _.a.SUBTITLE_TRACK:r=0,i=l.levelLoadingTimeOut;break;default:r=l.levelLoadingMaxRetry,i=l.levelLoadingTimeOut,a=l.levelLoadingRetryDelay,n=l.levelLoadingMaxRetryTimeout}if((u=this.createInternalLoader(t),null!==(e=t.deliveryDirectives)&&void 0!==e&&e.part)&&(t.type===_.a.LEVEL&&null!==t.level?s=this.hls.levels[t.level].details:t.type===_.a.AUDIO_TRACK&&null!==t.id?s=this.hls.audioTracks[t.id].details:t.type===_.a.SUBTITLE_TRACK&&null!==t.id&&(s=this.hls.subtitleTracks[t.id].details),s)){var h=s.partTarget,f=s.targetduration;h&&f&&(i=Math.min(1e3*Math.max(3*h,.8*f),i))}var c={timeout:i,maxRetry:r,retryDelay:a,maxRetryDelay:n,highWaterMark:0},v={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};u.load(t,c,v)},e.loadsuccess=function(t,e,r,i){if(void 0===i&&(i=null),r.isSidxRequest)return this.handleSidxRequest(t,r),void this.handlePlaylistLoaded(t,e,r,i);this.resetInternalLoader(r.type);var a=t.data;0===a.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),a.indexOf("#EXTINF:")>0||a.indexOf("#EXT-X-TARGETDURATION:")>0?this.handleTrackOrLevelPlaylist(t,e,r,i):this.handleMasterPlaylist(t,e,r,i)):this.handleManifestParsingError(t,r,"no EXTM3U delimiter",i)},e.loaderror=function(t,e,r){void 0===r&&(r=null),this.handleNetworkError(e,r,!1,t)},e.loadtimeout=function(t,e,r){void 0===r&&(r=null),this.handleNetworkError(e,r,!0)},e.handleMasterPlaylist=function(t,e,r,i){var a=this.hls,s=t.data,l=k(t,r),u=L.parseMasterPlaylist(s,l),d=u.levels,h=u.sessionData;if(d.length){var f=d.map((function(t){return{id:t.attrs.AUDIO,audioCodec:t.audioCodec}})),c=d.map((function(t){return{id:t.attrs.SUBTITLES,textCodec:t.textCodec}})),v=L.parseMasterPlaylistMedia(s,l,"AUDIO",f),p=L.parseMasterPlaylistMedia(s,l,"SUBTITLES",c),m=L.parseMasterPlaylistMedia(s,l,"CLOSED-CAPTIONS");if(v.length)v.some((function(t){return!t.url}))||!d[0].audioCodec||d[0].attrs.AUDIO||(o.b.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),v.unshift({type:"main",name:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new g({}),bitrate:0,url:""}));a.trigger(n.a.MANIFEST_LOADED,{levels:d,audioTracks:v,subtitles:p,captions:m,url:l,stats:e,networkDetails:i,sessionData:h})}else this.handleManifestParsingError(t,r,"no level found in manifest",i)},e.handleTrackOrLevelPlaylist=function(t,e,r,i){var o=this.hls,l=r.id,u=r.level,d=r.type,h=k(t,r),f=Object(a.a)(l)?l:0,c=Object(a.a)(u)?u:f,v=function(t){switch(t.type){case _.a.AUDIO_TRACK:return _.b.AUDIO;case _.a.SUBTITLE_TRACK:return _.b.SUBTITLE;default:return _.b.MAIN}}(r),p=L.parseLevelPlaylist(t.data,h,c,v,f);if(p.fragments.length){if(d===_.a.MANIFEST){var m={attrs:new g({}),bitrate:0,details:p,name:"",url:h};o.trigger(n.a.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:h,stats:e,networkDetails:i,sessionData:null})}if(e.parsing.end=performance.now(),p.needSidxRanges){var y,b=null===(y=p.fragments[0].initSegment)||void 0===y?void 0:y.url;this.load({url:b,isSidxRequest:!0,type:d,level:u,levelDetails:p,id:l,groupId:null,rangeStart:0,rangeEnd:2048,responseType:"arraybuffer",deliveryDirectives:null})}else r.levelDetails=p,this.handlePlaylistLoaded(t,e,r,i)}else o.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.LEVEL_EMPTY_ERROR,fatal:!1,url:h,reason:"no fragments found in level",level:"number"==typeof r.level?r.level:void 0})},e.handleSidxRequest=function(t,e){var r=Object(l.g)(new Uint8Array(t.data));if(r){var i=r.references,a=e.levelDetails;i.forEach((function(t,e){var i=t.info,n=a.fragments[e];0===n.byteRange.length&&n.setByteRange(String(1+i.end-i.start)+"@"+String(i.start)),n.initSegment&&n.initSegment.setByteRange(String(r.moovEndOffset)+"@0")}))}},e.handleManifestParsingError=function(t,e,r,i){this.hls.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.MANIFEST_PARSING_ERROR,fatal:e.type===_.a.MANIFEST,url:t.url,reason:r,response:t,context:e,networkDetails:i})},e.handleNetworkError=function(t,e,r,i){void 0===r&&(r=!1),o.b.warn("[playlist-loader]: A network "+(r?"timeout":"error")+" occurred while loading "+t.type+" level: "+t.level+" id: "+t.id+' group-id: "'+t.groupId+'"');var a=s.a.UNKNOWN,l=!1,u=this.getInternalLoader(t);switch(t.type){case _.a.MANIFEST:a=r?s.a.MANIFEST_LOAD_TIMEOUT:s.a.MANIFEST_LOAD_ERROR,l=!0;break;case _.a.LEVEL:a=r?s.a.LEVEL_LOAD_TIMEOUT:s.a.LEVEL_LOAD_ERROR,l=!1;break;case _.a.AUDIO_TRACK:a=r?s.a.AUDIO_TRACK_LOAD_TIMEOUT:s.a.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case _.a.SUBTITLE_TRACK:a=r?s.a.SUBTITLE_TRACK_LOAD_TIMEOUT:s.a.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(t.type);var d={type:s.b.NETWORK_ERROR,details:a,fatal:l,url:t.url,loader:u,context:t,networkDetails:e};i&&(d.response=i),this.hls.trigger(n.a.ERROR,d)},e.handlePlaylistLoaded=function(t,e,r,i){var a=r.type,s=r.level,o=r.id,l=r.groupId,u=r.loader,d=r.levelDetails,h=r.deliveryDirectives;if(null!=d&&d.targetduration){if(u)switch(d.live&&(u.getCacheAge&&(d.ageHeader=u.getCacheAge()||0),u.getCacheAge&&!isNaN(d.ageHeader)||(d.ageHeader=0)),a){case _.a.MANIFEST:case _.a.LEVEL:this.hls.trigger(n.a.LEVEL_LOADED,{details:d,level:s||0,id:o||0,stats:e,networkDetails:i,deliveryDirectives:h});break;case _.a.AUDIO_TRACK:this.hls.trigger(n.a.AUDIO_TRACK_LOADED,{details:d,id:o||0,groupId:l||"",stats:e,networkDetails:i,deliveryDirectives:h});break;case _.a.SUBTITLE_TRACK:this.hls.trigger(n.a.SUBTITLE_TRACK_LOADED,{details:d,id:o||0,groupId:l||"",stats:e,networkDetails:i,deliveryDirectives:h})}}else this.handleManifestParsingError(t,r,"invalid target duration",i)},t}(),w=function(){function t(t){this.hls=void 0,this.loaders={},this.decryptkey=null,this.decrypturl=null,this.hls=t,this._registerListeners()}var e=t.prototype;return e._registerListeners=function(){this.hls.on(n.a.KEY_LOADING,this.onKeyLoading,this)},e._unregisterListeners=function(){this.hls.off(n.a.KEY_LOADING,this.onKeyLoading)},e.destroy=function(){for(var t in this._unregisterListeners(),this.loaders){var e=this.loaders[t];e&&e.destroy()}this.loaders={}},e.onKeyLoading=function(t,e){var r=e.frag,i=r.type,a=this.loaders[i];if(r.decryptdata){var s=r.decryptdata.uri;if(s!==this.decrypturl||null===this.decryptkey){var l=this.hls.config;if(a&&(o.b.warn("abort previous key loader for type:"+i),a.abort()),!s)return void o.b.warn("key uri is falsy");var u=l.loader,d=r.loader=this.loaders[i]=new u(l);this.decrypturl=s,this.decryptkey=null;var h={url:s,frag:r,responseType:"arraybuffer"},f={timeout:l.fragLoadingTimeOut,maxRetry:0,retryDelay:l.fragLoadingRetryDelay,maxRetryDelay:l.fragLoadingMaxRetryTimeout,highWaterMark:0},c={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};d.load(h,f,c)}else this.decryptkey&&(r.decryptdata.key=this.decryptkey,this.hls.trigger(n.a.KEY_LOADED,{frag:r}))}else o.b.warn("Missing decryption data on fragment in onKeyLoading")},e.loadsuccess=function(t,e,r){var i=r.frag;i.decryptdata?(this.decryptkey=i.decryptdata.key=new Uint8Array(t.data),i.loader=null,delete this.loaders[i.type],this.hls.trigger(n.a.KEY_LOADED,{frag:i})):o.b.error("after key load, decryptdata unset")},e.loaderror=function(t,e){var r=e.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.KEY_LOAD_ERROR,fatal:!1,frag:r,response:t})},e.loadtimeout=function(t,e){var r=e.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},t}();function C(t,e){var r;try{r=new Event("addtrack")}catch(t){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=t,e.dispatchEvent(r)}function O(t,e,r){var i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&t.cues.length>0)for(var a=function(t,e,r){var i=[],a=function(t,e){if(et[r].endTime)return-1;var i=0,a=r;for(;i<=a;){var n=Math.floor((a+i)/2);if(et[n].startTime&&i-1)for(var n=a,s=t.length;n=e&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(t.cues,e,r),n=0;n.05&&this.forwardBufferLength>1){var u=Math.min(2,Math.max(1,n)),d=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;t.playbackRate=Math.min(u,Math.max(1,d))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}}}}},a.estimateLiveEdge=function(){var t=this.levelDetails;return null===t?null:t.edge+t.age},a.computeLatency=function(){var t=this.estimateLiveEdge();return null===t?null:t-this.currentTime},e=t,(r=[{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var t=this.config,e=this.levelDetails;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}},{key:"targetLatency",get:function(){var t=this.levelDetails;if(null===t)return null;var e=t.holdBack,r=t.partHoldBack,i=t.targetduration,a=this.config,n=a.liveSyncDuration,s=a.liveSyncDurationCount,o=a.lowLatencyMode,l=this.hls.userConfig,u=o&&r||e;(l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==n?n:s*i);var d=i;return u+Math.min(1*this.stallCount,d)}},{key:"liveSyncPosition",get:function(){var t=this.estimateLiveEdge(),e=this.targetLatency,r=this.levelDetails;if(null===t||null===e||null===r)return null;var i=r.edge,a=t-e-this.edgeStalled,n=i-r.totalduration,s=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(n,a),s)}},{key:"drift",get:function(){var t=this.levelDetails;return null===t?1:t.drift}},{key:"edgeStalled",get:function(){var t=this.levelDetails;if(null===t)return 0;var e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}},{key:"forwardBufferLength",get:function(){var t=this.media,e=this.levelDetails;if(!t||!e)return 0;var r=t.buffered.length;return r?t.buffered.end(r-1):e.edge-this.currentTime}}])&&F(e.prototype,r),i&&F(e,i),t}();function B(t,e){for(var r=0;rt.sn?(n=r-t.start,i=t):(n=t.start-r,i=e),i.duration!==n&&(i.duration=n)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration}else e.start=Math.max(t.start-e.duration,0)}function V(t,e,r,i,n,s){i-r<=0&&(o.b.warn("Fragment should have a positive duration",e),i=r+e.duration,s=n+e.duration);var l=r,u=i,d=e.startPTS,h=e.endPTS;if(Object(a.a)(d)){var f=Math.abs(d-r);Object(a.a)(e.deltaPTS)?e.deltaPTS=Math.max(f,e.deltaPTS):e.deltaPTS=f,l=Math.max(r,d),r=Math.min(r,d),n=Math.min(n,e.startDTS),u=Math.min(i,h),i=Math.max(i,h),s=Math.max(s,e.endDTS)}e.duration=i-r;var c=r-e.start;e.appendedPTS=i,e.start=e.startPTS=r,e.maxStartPTS=l,e.startDTS=n,e.endPTS=i,e.minEndPTS=u,e.endDTS=s;var v,g=e.sn;if(!t||gt.endSN)return 0;var p=g-t.startSN,m=t.fragments;for(m[p]=e,v=p;v>0;v--)H(m[v],m[v-1]);for(v=p;v=0;n--){var s=i[n].initSegment;if(s){r=s;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;var l,u=0;if(function(t,e,r){for(var i=e.skippedSegments,a=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(i?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,s=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,u=a;u<=n;u++){var d=l[s+u],h=o[u];i&&!h&&u=i.length||function(t,e){if(e){for(var r=t.fragments,i=t.skippedSegments;ie.partTarget&&(l+=1)}if(Object(a.a)(o))return new U(o,Object(a.a)(l)?l:void 0,M.No)}}},e.loadPlaylist=function(t){},e.shouldLoadTrack=function(t){return this.canLoad&&t&&!!t.url&&(!t.details||t.details.live)},e.playlistLoaded=function(t,e,r){var i=this,a=e.details,n=e.stats,s=n.loading.end?Math.max(0,self.performance.now()-n.loading.end):0;if(a.advancedDateTime=Date.now()-s,a.live||null!=r&&r.live){if(a.reloaded(r),r&&this.log("live playlist "+t+" "+(a.advanced?"REFRESHED "+a.lastPartSn+"-"+a.lastPartIndex:"MISSED")),r&&a.fragments.length>0&&W(r,a),!this.canLoad||!a.live)return;var o,l=void 0,u=void 0;if(a.canBlockReload&&a.endSN&&a.advanced){var d=this.hls.config.lowLatencyMode,h=a.lastPartSn,f=a.endSN,c=a.lastPartIndex,v=h===f;-1!==c?(l=v?f+1:h,u=v?d?0:c:c+1):l=f+1;var g=a.age,p=g+a.ageHeader,m=Math.min(p-a.partTarget,1.5*a.targetduration);if(m>0){if(r&&m>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+m+" with playlist age: "+a.age),m=0;else{var y=Math.floor(m/a.targetduration);if(l+=y,void 0!==u)u+=Math.round(m%a.targetduration/a.partTarget);this.log("CDN Tune-in age: "+a.ageHeader+"s last advanced "+g.toFixed(2)+"s goal: "+m+" skip sn "+y+" to part "+u)}a.tuneInGoal=m}if(o=this.getDeliveryDirectives(a,e.deliveryDirectives,l,u),d||!v)return void this.loadPlaylist(o)}else o=this.getDeliveryDirectives(a,e.deliveryDirectives,l,u);var b=function(t,e){var r,i=1e3*t.levelTargetDuration,a=i/2,n=t.age,s=n>0&&n<3*i,o=e.loading.end-e.loading.start,l=t.availabilityDelay;if(!1===t.updated)if(s){var u=333*t.misses;r=Math.max(Math.min(a,2*o),u),t.availabilityDelay=(t.availabilityDelay||0)+r}else r=a;else s?(l=Math.min(l||i/2,n),t.availabilityDelay=l,r=l+i-n):r=i-o;return Math.round(r)}(a,n);void 0!==l&&a.canBlockReload&&(b-=a.partTarget||1),this.log("reload live playlist "+t+" in "+Math.round(b)+" ms"),this.timer=self.setTimeout((function(){return i.loadPlaylist(o)}),b)}else this.clearTimer()},e.getDeliveryDirectives=function(t,e,r,i){var a=function(t,e){var r=t.canSkipUntil,i=t.canSkipDateRanges,a=t.endSN;return r&&(void 0!==e?e-a:0)-1&&null!==(e=t.context)&&void 0!==e&&e.deliveryDirectives)this.warn("retry playlist loading #"+this.retryCount+' after "'+t.details+'"'),this.loadPlaylist();else{var n=Math.min(Math.pow(2,this.retryCount)*i.levelLoadingRetryDelay,i.levelLoadingMaxRetryTimeout);this.timer=self.setTimeout((function(){return r.loadPlaylist()}),n),this.warn("retry playlist loading #"+this.retryCount+" in "+n+' ms after "'+t.details+'"')}else this.warn('cannot recover from error "'+t.details+'"'),this.clearTimer(),t.fatal=!0;return a},t}();function q(){return(q=Object.assign||function(t){for(var e=1;e0){r=a[0].bitrate,a.sort((function(t,e){return t.bitrate-e.bitrate})),this._levels=a;for(var c=0;cthis.hls.config.fragLoadingMaxRetry&&(n=r.frag.level)):n=r.frag.level}break;case s.a.LEVEL_LOAD_ERROR:case s.a.LEVEL_LOAD_TIMEOUT:i&&(i.deliveryDirectives&&(l=!1),n=i.level),o=!0;break;case s.a.REMUX_ALLOC_ERROR:n=r.level,o=!0}void 0!==n&&this.recoverLevel(r,n,o,l)}}},u.recoverLevel=function(t,e,r,i){var a=t.details,n=this._levels[e];if(n.loadError++,r){if(!this.retryLoadingOrFail(t))return void(this.currentLevelIndex=-1);t.levelRetry=!0}if(i){var s=n.url.length;if(s>1&&n.loadError1){var i=(e.urlId+1)%r;this.warn("Switching to redundant URL-id "+i),this._levels.forEach((function(t){t.urlId=i})),this.level=t}},u.onFragLoaded=function(t,e){var r=e.frag;if(void 0!==r&&r.type===_.b.MAIN){var i=this._levels[r.level];void 0!==i&&(i.fragmentError=0,i.loadError=0)}},u.onLevelLoaded=function(t,e){var r,i,a=e.level,n=e.details,s=this._levels[a];if(!s)return this.warn("Invalid level index "+a),void(null!==(i=e.deliveryDirectives)&&void 0!==i&&i.skip&&(n.deltaUpdateFailed=!0));a===this.currentLevelIndex?(0===s.fragmentError&&(s.loadError=0,this.retryCount=0),this.playlistLoaded(a,e,s.details)):null!==(r=e.deliveryDirectives)&&void 0!==r&&r.skip&&(n.deltaUpdateFailed=!0)},u.onAudioTrackSwitched=function(t,e){var r=this.hls.levels[this.currentLevelIndex];if(r&&r.audioGroupIds){for(var i=-1,a=this.hls.audioTracks[e.id].groupId,n=0;n0){var i=r.urlId,a=r.url[i];if(t)try{a=t.addDirectives(a)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}this.log("Attempt loading level index "+e+(t?" at sn "+t.msn+" part "+t.part:"")+" with URL-id "+i+" "+a),this.clearTimer(),this.hls.trigger(n.a.LEVEL_LOADING,{url:a,level:e,id:i,deliveryDirectives:t||null})}},u.removeLevel=function(t,e){var r=function(t,r){return r!==e},i=this._levels.filter((function(i,a){return a!==t||i.url.length>1&&void 0!==e&&(i.url=i.url.filter(r),i.audioGroupIds&&(i.audioGroupIds=i.audioGroupIds.filter(r)),i.textGroupIds&&(i.textGroupIds=i.textGroupIds.filter(r)),i.urlId=0,!0)})).map((function(t,e){var r=t.details;return null!=r&&r.fragments&&r.fragments.forEach((function(t){t.level=e})),t}));this._levels=i,this.hls.trigger(n.a.LEVELS_UPDATED,{levels:i})},a=i,(o=[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(t){var e,r=this._levels;if(0!==r.length&&(this.currentLevelIndex!==t||null===(e=r[t])||void 0===e||!e.details)){if(t<0||t>=r.length){var i=t<0;if(this.hls.trigger(n.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.LEVEL_SWITCH_ERROR,level:t,fatal:i,reason:"invalid level idx"}),i)return;t=Math.min(t,r.length-1)}this.clearTimer();var a=this.currentLevelIndex,o=r[a],l=r[t];this.log("switching to level "+t+" from "+a),this.currentLevelIndex=t;var u=q({},l,{level:t,maxBitrate:l.maxBitrate,uri:l.uri,urlId:l.urlId});delete u._urlId,this.hls.trigger(n.a.LEVEL_SWITCHING,u);var d=l.details;if(!d||d.live){var h=this.switchParams(l.uri,null==o?void 0:o.details);this.loadPlaylist(h)}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(t){this._firstLevel=t}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var t=this.hls.config.startLevel;return void 0!==t?t:this._firstLevel}return this._startLevel},set:function(t){this._startLevel=t}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}}])&&z(a.prototype,o),l&&z(a,l),i}(X);!function(t){t.NOT_LOADED="NOT_LOADED",t.BACKTRACKED="BACKTRACKED",t.APPENDING="APPENDING",t.PARTIAL="PARTIAL",t.OK="OK"}($||($={}));var tt=function(){function t(t){this.activeFragment=null,this.activeParts=null,this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hls=t,this._registerListeners()}var e=t.prototype;return e._registerListeners=function(){var t=this.hls;t.on(n.a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(n.a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(n.a.FRAG_LOADED,this.onFragLoaded,this)},e._unregisterListeners=function(){var t=this.hls;t.off(n.a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(n.a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(n.a.FRAG_LOADED,this.onFragLoaded,this)},e.destroy=function(){this._unregisterListeners(),this.fragments=this.timeRanges=null},e.getAppendedFrag=function(t,e){if(e===_.b.MAIN){var r=this.activeFragment,i=this.activeParts;if(!r)return null;if(i)for(var a=i.length;a--;){var n=i[a],s=n?n.end:r.appendedPTS;if(n.start<=t&&void 0!==s&&t<=s)return a>9&&(this.activeParts=i.slice(a-9)),n}else if(r.start<=t&&void 0!==r.appendedPTS&&t<=r.appendedPTS)return r}return this.getBufferedFrag(t,e)},e.getBufferedFrag=function(t,e){for(var r=this.fragments,i=Object.keys(r),a=i.length;a--;){var n=r[i[a]];if((null==n?void 0:n.body.type)===e&&n.buffered){var s=n.body;if(s.start<=t&&t<=s.end)return s}}return null},e.detectEvictedFragments=function(t,e,r){var i=this;Object.keys(this.fragments).forEach((function(a){var n=i.fragments[a];if(n)if(n.buffered){var s=n.range[t];s&&s.time.some((function(t){var r=!i.isTimeBuffered(t.startPTS,t.endPTS,e);return r&&i.removeFragment(n.body),r}))}else n.body.type===r&&i.removeFragment(n.body)}))},e.detectPartialFragments=function(t){var e=this,r=this.timeRanges,i=t.frag,a=t.part;if(r&&"initSegment"!==i.sn){var n=rt(i),s=this.fragments[n];s&&(Object.keys(r).forEach((function(t){var n=i.elementaryStreams[t];if(n){var o=r[t],l=null!==a||!0===n.partial;s.range[t]=e.getBufferedTimes(i,a,l,o)}})),s.backtrack=s.loaded=null,Object.keys(s.range).length?s.buffered=!0:this.removeFragment(s.body))}},e.fragBuffered=function(t){var e=rt(t),r=this.fragments[e];r&&(r.backtrack=r.loaded=null,r.buffered=!0)},e.getBufferedTimes=function(t,e,r,i){for(var a={time:[],partial:r},n=e?e.start:t.start,s=e?e.end:t.end,o=t.minEndPTS||s,l=t.maxStartPTS||n,u=0;u=d&&o<=h){a.time.push({startPTS:Math.max(n,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(nd)a.partial=!0,a.time.push({startPTS:Math.max(n,i.start(u)),endPTS:Math.min(s,i.end(u))});else if(s<=d)break}return a},e.getPartialFragment=function(t){var e,r,i,a=null,n=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var u=o[l];u&&et(u)&&(r=u.body.start-s,i=u.body.end+s,t>=r&&t<=i&&(e=Math.min(t-r,i-t),n<=e&&(a=u.body,n=e)))})),a},e.getState=function(t){var e=rt(t),r=this.fragments[e];return r?r.buffered?et(r)?$.PARTIAL:$.OK:r.backtrack?$.BACKTRACKED:$.APPENDING:$.NOT_LOADED},e.backtrack=function(t,e){var r=rt(t),i=this.fragments[r];if(!i||i.backtrack)return null;var a=i.backtrack=e||i.loaded;return i.loaded=null,a},e.getBacktrackData=function(t){var e=rt(t),r=this.fragments[e];if(r){var i,a=r.backtrack;if(null!=a&&null!==(i=a.payload)&&void 0!==i&&i.byteLength)return a;this.removeFragment(t)}return null},e.isTimeBuffered=function(t,e,r){for(var i,a,n=0;n=i&&e<=a)return!0;if(e<=i)return!1}return!1},e.onFragLoaded=function(t,e){var r=e.frag,i=e.part;if("initSegment"!==r.sn&&!r.bitrateTest&&!i){var a=rt(r);this.fragments[a]={body:r,loaded:e,backtrack:null,buffered:!1,range:Object.create(null)}}},e.onBufferAppended=function(t,e){var r=this,i=e.frag,a=e.part,n=e.timeRanges;if(i.type===_.b.MAIN)if(this.activeFragment=i,a){var s=this.activeParts;s||(this.activeParts=s=[]),s.push(a)}else this.activeParts=null;this.timeRanges=n,Object.keys(n).forEach((function(t){var e=n[t];if(r.detectEvictedFragments(t,e),!a)for(var s=0;st&&i.removeFragment(s)}}))},e.removeFragment=function(t){var e=rt(t);t.stats.loaded=0,t.clearElementaryStreamInfo(),delete this.fragments[e]},e.removeAllFragments=function(){this.fragments=Object.create(null),this.activeFragment=null,this.activeParts=null},t}();function et(t){var e,r;return t.buffered&&((null===(e=t.range.video)||void 0===e?void 0:e.partial)||(null===(r=t.range.audio)||void 0===r?void 0:r.partial))}function rt(t){return t.type+"_"+t.level+"_"+t.urlId+"_"+t.sn}var it=function(){function t(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}var e=t.prototype;return e.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},e.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},e.onHandlerDestroyed=function(){},e.hasInterval=function(){return!!this._tickInterval},e.hasNextTick=function(){return!!this._tickTimer},e.setInterval=function(t){return!this._tickInterval&&(this._tickInterval=self.setInterval(this._boundTick,t),!0)},e.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},e.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},e.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},e.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},e.doTick=function(){},t}(),at={length:0,start:function(){return 0},end:function(){return 0}},nt=function(){function t(){}return t.isBuffered=function(e,r){try{if(e)for(var i=t.getBuffered(e),a=0;a=i.start(a)&&r<=i.end(a))return!0}catch(t){}return!1},t.bufferInfo=function(e,r,i){try{if(e){var a,n=t.getBuffered(e),s=[];for(a=0;as&&(i[n-1].end=t[a].end):i.push(t[a])}else i.push(t[a])}else i=t;for(var o,l=0,u=e,d=e,h=0;h=f&&er.startCC||t&&t.cc0)r=a+1;else{if(!(s<0))return n;i=a-1}}return null}};function ht(t,e,r){void 0===t&&(t=0),void 0===e&&(e=0);var i=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=t?1:r.start-i>t&&r.start?-1:0}function ft(t,e,r){var i=1e3*Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>t}function ct(t){var e="function"==typeof Map?new Map:void 0;return(ct=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,i)}function i(){return vt(t,arguments,mt(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),pt(i,t)})(t)}function vt(t,e,r){return(vt=gt()?Reflect.construct:function(t,e,r){var i=[null];i.push.apply(i,e);var a=new(Function.bind.apply(t,i));return r&&pt(a,r.prototype),a}).apply(null,arguments)}function gt(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function pt(t,e){return(pt=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function mt(t){return(mt=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var yt=Math.pow(2,17),bt=function(){function t(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}var e=t.prototype;return e.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},e.abort=function(){this.loader&&this.loader.abort()},e.load=function(t,e){var r=this,i=t.url;if(!i)return Promise.reject(new Et({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,networkDetails:null},"Fragment does not have a "+(i?"part list":"url")));this.abort();var a=this.config,n=a.fLoader,o=a.loader;return new Promise((function(i,l){r.loader&&r.loader.destroy();var u=r.loader=t.loader=n?new n(a):new o(a),d=Tt(t),h={timeout:a.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:a.fragLoadingMaxRetryTimeout,highWaterMark:yt};t.stats=u.stats,u.load(d,h,{onSuccess:function(e,a,n,s){r.resetLoader(t,u),i({frag:t,part:null,payload:e.data,networkDetails:s})},onError:function(e,i,a){r.resetLoader(t,u),l(new Et({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:e,networkDetails:a}))},onAbort:function(e,i,a){r.resetLoader(t,u),l(new Et({type:s.b.NETWORK_ERROR,details:s.a.INTERNAL_ABORTED,fatal:!1,frag:t,networkDetails:a}))},onTimeout:function(e,i,a){r.resetLoader(t,u),l(new Et({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,networkDetails:a}))},onProgress:function(r,i,a,n){e&&e({frag:t,part:null,payload:a,networkDetails:n})}})}))},e.loadPart=function(t,e,r){var i=this;this.abort();var a=this.config,n=a.fLoader,o=a.loader;return new Promise((function(l,u){i.loader&&i.loader.destroy();var d=i.loader=t.loader=n?new n(a):new o(a),h=Tt(t,e),f={timeout:a.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:a.fragLoadingMaxRetryTimeout,highWaterMark:yt};e.stats=d.stats,d.load(h,f,{onSuccess:function(a,n,s,o){i.resetLoader(t,d),i.updateStatsFromPart(t,e);var u={frag:t,part:e,payload:a.data,networkDetails:o};r(u),l(u)},onError:function(r,a,n){i.resetLoader(t,d),u(new Et({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:r,networkDetails:n}))},onAbort:function(r,a,n){t.stats.aborted=e.stats.aborted,i.resetLoader(t,d),u(new Et({type:s.b.NETWORK_ERROR,details:s.a.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,networkDetails:n}))},onTimeout:function(r,a,n){i.resetLoader(t,d),u(new Et({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,networkDetails:n}))}})}))},e.updateStatsFromPart=function(t,e){var r=t.stats,i=e.stats,a=i.total;if(r.loaded+=i.loaded,a){var n=Math.round(t.duration/e.duration),s=Math.min(Math.round(r.loaded/a),n),o=(n-s)*Math.round(r.loaded/s);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,u=i.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end},e.resetLoader=function(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()},t}();function Tt(t,e){void 0===e&&(e=null);var r=e||t,i={frag:t,part:e,responseType:"arraybuffer",url:r.url,rangeStart:0,rangeEnd:0},n=r.byteRangeStartOffset,s=r.byteRangeEndOffset;return Object(a.a)(n)&&Object(a.a)(s)&&(i.rangeStart=n,i.rangeEnd=s),i}var Et=function(t){var e,r;function i(e){for(var r,i=arguments.length,a=new Array(i>1?i-1:0),n=1;ne.start+e.duration+l;(s0&&s&&s.key&&s.iv&&"AES-128"===s.method){var o=self.performance.now();return e.decrypter.webCryptoDecrypt(new Uint8Array(a),s.key.buffer,s.iv.buffer).then((function(e){var a=self.performance.now();return i.trigger(n.a.FRAG_DECRYPTED,{frag:t,payload:e,stats:{tstart:o,tdecrypt:a}}),r.payload=e,r}))}return r})).then((function(r){var i=e.fragCurrent,a=e.hls,s=e.levels;if(!s)throw new Error("init load aborted, missing levels");s[t.level].details;var o=t.stats;e.state=_t,e.fragLoadError=0,t.data=new Uint8Array(r.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),r.frag===i&&a.trigger(n.a.FRAG_BUFFERED,{stats:o,frag:i,part:null,id:t.type}),e.tick()})).catch((function(r){e.warn(r),e.resetFragmentLoading(t)}))},f.fragContextChanged=function(t){var e=this.fragCurrent;return!t||!e||t.level!==e.level||t.sn!==e.sn||t.urlId!==e.urlId},f.fragBufferedComplete=function(t,e){var r=this.mediaBuffer?this.mediaBuffer:this.media;this.log("Buffered "+t.type+" sn: "+t.sn+(e?" part: "+e.index:"")+" of "+("[stream-controller]"===this.logPrefix?"level":"track")+" "+t.level+" "+Lt.toString(nt.getBuffered(r))),this.state=_t,this.tick()},f._handleFragmentLoadComplete=function(t){var e=this.transmuxer;if(e){var r=t.frag,i=t.part,a=t.partsLoaded,n=!a||0===a.length||a.some((function(t){return!t})),s=new st(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!n);e.flush(s)}},f._handleFragmentLoadProgress=function(t){},f._doFragLoad=function(t,e,r,i){var s=this;if(void 0===r&&(r=null),!this.levels)throw new Error("frag load aborted, missing levels");if(r=Math.max(t.start,r||0),this.config.lowLatencyMode&&e){var o=e.partList;if(o&&i){r>t.end&&e.fragmentHint&&(t=e.fragmentHint);var l=this.getNextPart(o,t,r);if(l>-1){var u=o[l];return this.log("Loading part sn: "+t.sn+" p: "+u.index+" cc: "+t.cc+" of playlist ["+e.startSN+"-"+e.endSN+"] parts [0-"+l+"-"+(o.length-1)+"] "+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),this.nextLoadPosition=u.start+u.duration,this.state=xt,this.hls.trigger(n.a.FRAG_LOADING,{frag:t,part:o[l],targetBufferTime:r}),this.doFragPartsLoad(t,o,l,i).catch((function(t){return s.handleFragLoadError(t)}))}if(!t.url||this.loadedEndOfParts(o,r))return Promise.resolve(null)}}return this.log("Loading fragment "+t.sn+" cc: "+t.cc+" "+(e?"of ["+e.startSN+"-"+e.endSN+"] ":"")+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),Object(a.a)(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=xt,this.hls.trigger(n.a.FRAG_LOADING,{frag:t,targetBufferTime:r}),this.fragmentLoader.load(t,i).catch((function(t){return s.handleFragLoadError(t)}))},f.doFragPartsLoad=function(t,e,r,i){var a=this;return new Promise((function(s,o){var l=[];!function r(u){var d=e[u];a.fragmentLoader.loadPart(t,d,i).then((function(i){l[d.index]=i;var o=i.part;a.hls.trigger(n.a.FRAG_LOADED,i);var h=e[u+1];if(!h||h.fragment!==t)return s({frag:t,part:o,partsLoaded:l});r(u+1)})).catch(o)}(r)}))},f.handleFragLoadError=function(t){var e=t.data;return e&&e.details===s.a.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(n.a.ERROR,e),null},f._handleTransmuxerFlush=function(t){var e=this.getCurrentContext(t);if(e&&this.state===Ct){var r=e.frag,i=e.part,a=e.level,n=self.performance.now();r.stats.parsing.end=n,i&&(i.stats.parsing.end=n),this.updateLevelTiming(r,i,a,t.partial)}else this.fragCurrent||(this.state=_t)},f.getCurrentContext=function(t){var e=this.levels,r=t.level,i=t.sn,a=t.part;if(!e||!e[r])return this.warn("Levels object was unset while buffering fragment "+i+" of level "+r+". The current chunk will not be buffered."),null;var n=e[r],s=a>-1?function(t,e,r){if(!t||!t.details)return null;var i=t.details.partList;if(i)for(var a=i.length;a--;){var n=i[a];if(n.index===r&&n.fragment.sn===e)return n}return null}(n,i,a):null,o=s?s.fragment:function(t,e,r){if(!t||!t.details)return null;var i=t.details,a=i.fragments[e-i.startSN];return a||((a=i.fragmentHint)&&a.sn===e?a:en&&this.flushMainBuffer(s,t.start)}else this.flushMainBuffer(0,t.start)},f.getFwdBufferInfo=function(t,e){var r=this.config,i=this.getLoadPosition();if(!Object(a.a)(i))return null;var n=nt.bufferInfo(t,i,r.maxBufferHole);if(0===n.len&&void 0!==n.nextStart){var s=this.fragmentTracker.getBufferedFrag(i,e);if(s&&n.nextStart=r&&(e.maxMaxBufferLength/=2,this.warn("Reduce max buffer length to "+e.maxMaxBufferLength+"s"),!0)},f.getNextFragment=function(t,e){var r,i,a=e.fragments,n=a.length;if(!n)return null;var s,o=this.config,l=a[0].start;if(e.live){var u=o.initialLiveManifestSize;if(n-1&&rr.start&&r.loaded},f.getInitialLiveFragment=function(t,e){var r=this.fragPrevious,i=null;if(r){if(t.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+r.programDateTime),i=function(t,e,r){if(null===e||!Array.isArray(t)||!t.length||!Object(a.a)(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;r=r||0;for(var i=0;i=t.startSN&&n<=t.endSN){var s=e[n-t.startSN];r.cc===s.cc&&(i=s,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=function(t,e){return dt.search(t,(function(t){return t.cce?-1:0}))}(e,r.cc))&&this.log("Live playlist, switching playlist, load frag with same CC: "+i.sn)}}else{var o=this.hls.liveSyncPosition;null!==o&&(i=this.getFragmentAtPosition(o,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i},f.getFragmentAtPosition=function(t,e,r){var i,a=this.config,n=this.fragPrevious,s=r.fragments,o=r.endSN,l=r.fragmentHint,u=a.maxFragLookUpTolerance,d=!!(a.lowLatencyMode&&r.partList&&l);(d&&l&&!this.bitrateTest&&(s=s.concat(l),o=l.sn),te-u?0:u):i=s[s.length-1];if(i){var h=i.sn-r.startSN,f=n&&i.level===n.level,c=s[h+1];if(this.fragmentTracker.getState(i)===$.BACKTRACKED){i=null;for(var v=h;s[v]&&this.fragmentTracker.getState(s[v])===$.BACKTRACKED;)i=n?s[v--]:s[--v];i||(i=c)}else n&&i.sn===n.sn&&!d&&f&&(i.sn=n-e.maxFragLookUpTolerance&&a<=s;if(null!==i&&r.duration>i&&(a"+t.startSN+" prev-sn: "+(n?n.sn:"na")+" fragments: "+o),h}return l},f.waitForCdnTuneIn=function(t){return t.live&&t.canBlockReload&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)},f.setStartPosition=function(t,e){var r=this.startPosition;if(r"+t))}}])&&At(u.prototype,d),h&&At(u,h),i}(it);function Bt(){return self.MediaSource||self.WebKitMediaSource}function Ut(){return self.SourceBuffer||self.WebKitSourceBuffer}var Gt=r(17),jt=r(9),Kt=r(13),Ht=Bt()||{isTypeSupported:function(){return!1}},Vt=function(){function t(t,e,r,i){var a=this;this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.worker=void 0,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.hls=t,this.id=e,this.onTransmuxComplete=r,this.onFlush=i;var l=t.config,u=function(e,r){(r=r||{}).frag=a.frag,r.id=a.id,t.trigger(e,r)};this.observer=new Kt.EventEmitter,this.observer.on(n.a.FRAG_DECRYPTED,u),this.observer.on(n.a.ERROR,u);var d={mp4:Ht.isTypeSupported("video/mp4"),mpeg:Ht.isTypeSupported("audio/mpeg"),mp3:Ht.isTypeSupported('audio/mp4; codecs="mp3"')},h=navigator.vendor;if(l.enableWorker&&"undefined"!=typeof Worker){var f;o.b.log("demuxing in webworker");try{f=this.worker=Gt(18),this.onwmsg=this.onWorkerMessage.bind(this),f.addEventListener("message",this.onwmsg),f.onerror=function(e){t.trigger(n.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.INTERNAL_EXCEPTION,fatal:!0,event:"demuxerWorker",error:new Error(e.message+" ("+e.filename+":"+e.lineno+")")})},f.postMessage({cmd:"init",typeSupported:d,vendor:h,id:e,config:JSON.stringify(l)})}catch(t){o.b.warn("Error in worker:",t),o.b.error("Error while initializing DemuxerWorker, fallback to inline"),f&&self.URL.revokeObjectURL(f.objectURL),this.transmuxer=new jt.c(this.observer,d,l,h,e),this.worker=null}}else this.transmuxer=new jt.c(this.observer,d,l,h,e)}var e=t.prototype;return e.destroy=function(){var t=this.worker;if(t)t.removeEventListener("message",this.onwmsg),t.terminate(),this.worker=null;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var r=this.observer;r&&r.removeAllListeners(),this.observer=null},e.push=function(t,e,r,i,a,n,s,l,u,d){var h=this;u.transmuxing.start=self.performance.now();var f=this.transmuxer,c=this.worker,v=n?n.start:a.start,g=a.decryptdata,p=this.frag,m=!(p&&a.cc===p.cc),y=!(p&&u.level===p.level),b=p?u.sn-p.sn:-1,T=this.part?u.part-this.part.index:1,E=!y&&(1===b||0===b&&1===T),S=self.performance.now();(y||b||0===a.stats.parsing.start)&&(a.stats.parsing.start=S),!n||!T&&E||(n.stats.parsing.start=S);var L=new jt.b(m,E,l,y,v);if(!E||m){o.b.log("[transmuxer-interface, "+a.type+"]: Starting new transmux session for sn: "+u.sn+" p: "+u.part+" level: "+u.level+" id: "+u.id+"\n discontinuity: "+m+"\n trackSwitch: "+y+"\n contiguous: "+E+"\n accurateTimeOffset: "+l+"\n timeOffset: "+v);var A=new jt.a(r,i,e,s,d);this.configureTransmuxer(A)}if(this.frag=a,this.part=n,c)c.postMessage({cmd:"demux",data:t,decryptdata:g,chunkMeta:u,state:L},t instanceof ArrayBuffer?[t]:[]);else if(f){var R=f.push(t,g,u,L);Object(jt.d)(R)?R.then((function(t){h.handleTransmuxComplete(t)})):this.handleTransmuxComplete(R)}},e.flush=function(t){var e=this;t.transmuxing.start=self.performance.now();var r=this.transmuxer,i=this.worker;if(i)i.postMessage({cmd:"flush",chunkMeta:t});else if(r){var a=r.flush(t);Object(jt.d)(a)?a.then((function(r){e.handleFlushResult(r,t)})):this.handleFlushResult(a,t)}},e.handleFlushResult=function(t,e){var r=this;t.forEach((function(t){r.handleTransmuxComplete(t)})),this.onFlush(e)},e.onWorkerMessage=function(t){var e=t.data,r=this.hls;switch(e.event){case"init":self.URL.revokeObjectURL(this.worker.objectURL);break;case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,r.trigger(e.event,e.data)}},e.configureTransmuxer=function(t){var e=this.worker,r=this.transmuxer;e?e.postMessage({cmd:"configure",config:t}):r&&r.configure(t)},e.handleTransmuxComplete=function(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)},t}(),Wt=function(){function t(t,e,r,i){this.config=void 0,this.media=void 0,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=r,this.hls=i}var e=t.prototype;return e.destroy=function(){this.hls=this.fragmentTracker=this.media=null},e.poll=function(t){var e=this.config,r=this.media,i=this.stalled,a=r.currentTime,n=r.seeking,s=this.seeking&&!n,l=!this.seeking&&n;if(this.seeking=n,a===t){if((l||s)&&(this.stalled=null),!r.paused&&!r.ended&&0!==r.playbackRate&&nt.getBuffered(r).length){var u=nt.bufferInfo(r,a,0),d=u.len>0,h=u.nextStart||0;if(d||h){if(n){var f=u.len>2,c=!h||h-a>2&&!this.fragmentTracker.getPartialFragment(a);if(f||c)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var v,g=Math.max(h,u.start||0)-a,p=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,m=(null==p||null===(v=p.details)||void 0===v?void 0:v.live)?2*p.details.targetduration:2;if(g>0&&g<=m)return void this._trySkipBufferHole(null)}var y=self.performance.now();if(null!==i){var b=y-i;!n&&b>=250&&this._reportStall(u.len);var T=nt.bufferInfo(r,a,e.maxBufferHole);this._tryFixBufferStall(T,b)}else this.stalled=y}}}else if(this.moved=!0,null!==i){if(this.stallReported){var E=self.performance.now()-i;o.b.warn("playback not stuck anymore @"+a+", after "+Math.round(E)+"ms"),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}},e._tryFixBufferStall=function(t,e){var r=this.config,i=this.fragmentTracker,a=this.media.currentTime,n=i.getPartialFragment(a);if(n&&this._trySkipBufferHole(n))return;t.len>r.maxBufferHole&&e>1e3*r.highBufferWatchdogPeriod&&(o.b.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())},e._reportStall=function(t){var e=this.hls,r=this.media;this.stallReported||(this.stallReported=!0,o.b.warn("Playback stalling at @"+r.currentTime+" due to low buffer (buffer="+t+")"),e.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_STALLED_ERROR,fatal:!1,buffer:t}))},e._trySkipBufferHole=function(t){for(var e=this.config,r=this.hls,i=this.media,a=i.currentTime,l=0,u=nt.getBuffered(i),d=0;d=l&&a0&&-1===t&&(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e),this.state=_t,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=Dt},f.stopLoad=function(){this._forceStartLoad=!1,t.prototype.stopLoad.call(this)},f.doTick=function(){switch(this.state){case _t:this.doTickIdle();break;case Mt:var t,e=this.levels,r=this.level,i=null==e||null===(t=e[r])||void 0===t?void 0:t.details;if(i&&(!i.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(i))break;this.state=_t;break}break;case wt:var a,n=self.performance.now(),s=this.retryDate;(!s||n>=s||null!==(a=this.media)&&void 0!==a&&a.seeking)&&(this.log("retryDate reached, switch back to IDLE state"),this.state=_t)}this.onTickEnd()},f.onTickEnd=function(){t.prototype.onTickEnd.call(this),this.checkBuffer(),this.checkFragmentChanged()},f.doTickIdle=function(){var t,e,r=this.hls,i=this.levelLastLoaded,a=this.levels,s=this.media,o=r.config,l=r.nextLoadLevel;if(null!==i&&(s||!this.startFragRequested&&o.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)&&a&&a[l]){var d=a[l];this.level=r.nextLoadLevel=l;var h=d.details;if(!h||this.state===Mt||h.live&&this.levelLastLoaded!==l)this.state=Mt;else{var f=this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:s,_.b.MAIN);if(null!==f)if(!(f.len>=this.getMaxBufferLength(d.maxBitrate))){if(this._streamEnded(f,h)){var c={};return this.altAudio&&(c.type="video"),this.hls.trigger(n.a.BUFFER_EOS,c),void(this.state=Pt)}var v=f.end,g=this.getNextFragment(v,h);if(this.couldBacktrack&&!this.fragPrevious&&g&&"initSegment"!==g.sn){var p=g.sn-h.startSN;p>1&&(g=h.fragments[p-1],this.fragmentTracker.removeFragment(g))}if(g&&this.fragmentTracker.getState(g)===$.OK&&this.nextLoadPosition>v){var m=this.audioOnly&&!this.altAudio?u.a.AUDIO:u.a.VIDEO;this.afterBufferFlushed(s,m,_.b.MAIN),g=this.getNextFragment(this.nextLoadPosition,h)}g&&(!g.initSegment||g.initSegment.data||this.bitrateTest||(g=g.initSegment),"identity"!==(null===(t=g.decryptdata)||void 0===t?void 0:t.keyFormat)||null!==(e=g.decryptdata)&&void 0!==e&&e.key?this.loadFragment(g,h,v):this.loadKey(g,h))}}}},f.loadFragment=function(e,r,i){var a,n=this.fragmentTracker.getState(e);if(this.fragCurrent=e,n===$.BACKTRACKED){var s=this.fragmentTracker.getBacktrackData(e);if(s)return this._handleFragmentLoadProgress(s),void this._handleFragmentLoadComplete(s);n=$.NOT_LOADED}n===$.NOT_LOADED||n===$.PARTIAL?"initSegment"===e.sn?this._loadInitSegment(e):this.bitrateTest?(e.bitrateTest=!0,this.log("Fragment "+e.sn+" of level "+e.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(e)):(this.startFragRequested=!0,t.prototype.loadFragment.call(this,e,r,i)):n===$.APPENDING?this.reduceMaxBufferLength(e.duration)&&this.fragmentTracker.removeFragment(e):0===(null===(a=this.media)||void 0===a?void 0:a.buffered.length)&&this.fragmentTracker.removeAllFragments()},f.getAppendedFrag=function(t){var e=this.fragmentTracker.getAppendedFrag(t,_.b.MAIN);return e&&"fragment"in e?e.fragment:e},f.getBufferedFrag=function(t){return this.fragmentTracker.getBufferedFrag(t,_.b.MAIN)},f.followingBufferedFrag=function(t){return t?this.getBufferedFrag(t.end+.5):null},f.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},f.nextLevelSwitch=function(){var t=this.levels,e=this.media;if(null!=e&&e.readyState){var r,i=this.getAppendedFrag(e.currentTime);if(i&&i.start>1&&this.flushMainBuffer(0,i.start-1),!e.paused&&t){var a=t[this.hls.nextLoadLevel],n=this.fragLastKbps;r=n&&this.fragCurrent?this.fragCurrent.duration*a.maxBitrate/(1e3*n)+1:0}else r=0;var s=this.getBufferedFrag(e.currentTime+r);if(s){var o=this.followingBufferedFrag(s);if(o){this.abortCurrentFrag();var l=o.maxStartPTS?o.maxStartPTS:o.start,u=o.duration,d=Math.max(s.end,l+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,.5*u),.75*u));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}},f.abortCurrentFrag=function(){var t=this.fragCurrent;this.fragCurrent=null,null!=t&&t.loader&&t.loader.abort(),this.state===kt&&(this.state=_t),this.nextLoadPosition=this.getLoadPosition()},f.flushMainBuffer=function(e,r){t.prototype.flushMainBuffer.call(this,e,r,this.altAudio?"video":null)},f.onMediaAttached=function(e,r){t.prototype.onMediaAttached.call(this,e,r);var i=r.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Wt(this.config,i,this.fragmentTracker,this.hls)},f.onMediaDetaching=function(){var e=this.media;e&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),t.prototype.onMediaDetaching.call(this)},f.onMediaPlaying=function(){this.tick()},f.onMediaSeeked=function(){var t=this.media,e=t?t.currentTime:null;Object(a.a)(e)&&this.log("Media seeked to "+e.toFixed(3)),this.tick()},f.onManifestLoading=function(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(n.a.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=this.stalled=!1,this.startPosition=this.lastCurrentTime=0,this.fragPlaying=null},f.onManifestParsed=function(t,e){var r,i,a,n=!1,s=!1;e.levels.forEach((function(t){(r=t.audioCodec)&&(-1!==r.indexOf("mp4a.40.2")&&(n=!0),-1!==r.indexOf("mp4a.40.5")&&(s=!0))})),this.audioCodecSwitch=n&&s&&!("function"==typeof(null==(a=Ut())||null===(i=a.prototype)||void 0===i?void 0:i.changeType)),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1},f.onLevelLoading=function(t,e){var r=this.levels;if(r&&this.state===_t){var i=r[e.level];(!i.details||i.details.live&&this.levelLastLoaded!==e.level||this.waitForCdnTuneIn(i.details))&&(this.state=Mt)}},f.onLevelLoaded=function(t,e){var r,i=this.levels,a=e.level,s=e.details,o=s.totalduration;if(i){this.log("Level "+a+" loaded ["+s.startSN+","+s.endSN+"], cc ["+s.startCC+", "+s.endCC+"] duration:"+o);var l=this.fragCurrent;!l||this.state!==xt&&this.state!==wt||l.level!==e.level&&l.loader&&(this.state=_t,l.loader.abort());var u=i[a],d=0;if(s.live||null!==(r=u.details)&&void 0!==r&&r.live){if(s.fragments[0]||(s.deltaUpdateFailed=!0),s.deltaUpdateFailed)return;d=this.alignPlaylists(s,u.details)}if(u.details=s,this.levelLastLoaded=a,this.hls.trigger(n.a.LEVEL_UPDATED,{details:s,level:a}),this.state===Mt){if(this.waitForCdnTuneIn(s))return;this.state=_t}this.startFragRequested?s.live&&this.synchronizeToLiveEdge(s):this.setStartPosition(s,d),this.tick()}else this.warn("Levels were reset while loading level "+a)},f._handleFragmentLoadProgress=function(t){var e,r=t.frag,i=t.part,a=t.payload,n=this.levels;if(n){var s=n[r.level],o=s.details;if(o){var l=s.videoCodec,u=o.PTSKnown||!o.live,d=null===(e=r.initSegment)||void 0===e?void 0:e.data,h=this._getAudioCodec(s),f=this.transmuxer=this.transmuxer||new Vt(this.hls,_.b.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),c=i?i.index:-1,v=-1!==c,g=new st(r.level,r.sn,r.stats.chunkCount,a.byteLength,c,v),p=this.initPTS[r.cc];f.push(a,d,h,l,r,i,o.totalduration,u,g,p)}else this.warn("Dropping fragment "+r.sn+" of level "+r.level+" after level details were reset")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},f.onAudioTrackSwitching=function(t,e){var r=this.altAudio,i=!!e.url,a=e.id;if(!i){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var s=this.fragCurrent;null!=s&&s.loader&&(this.log("Switching to main audio track, cancel main fragment load"),s.loader.abort()),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var o=this.hls;r&&o.trigger(n.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),o.trigger(n.a.AUDIO_TRACK_SWITCHED,{id:a})}},f.onAudioTrackSwitched=function(t,e){var r=e.id,i=!!this.hls.audioTracks[r].url;if(i){var a=this.videoBuffer;a&&this.mediaBuffer!==a&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=a)}this.altAudio=i,this.tick()},f.onBufferCreated=function(t,e){var r,i,a=e.tracks,n=!1;for(var s in a){var o=a[s];if("main"===o.id){if(i=s,r=o,"video"===s){var l=a[s];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&r?(this.log("Alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},f.onFragBuffered=function(t,e){var r=e.frag,i=e.part;if(!r||r.type===_.b.MAIN){if(this.fragContextChanged(r))return this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===Ot&&(this.state=_t));var a=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}},f.onError=function(t,e){switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:case s.a.KEY_LOAD_ERROR:case s.a.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(_.b.MAIN,e);break;case s.a.LEVEL_LOAD_ERROR:case s.a.LEVEL_LOAD_TIMEOUT:this.state!==Ft&&(e.fatal?(this.warn(""+e.details),this.state=Ft):e.levelRetry||this.state!==Mt||(this.state=_t));break;case s.a.BUFFER_FULL_ERROR:if("main"===e.parent&&(this.state===Ct||this.state===Ot)){var r=!0,i=this.getFwdBufferInfo(this.media,_.b.MAIN);i&&i.len>.5&&(r=!this.reduceMaxBufferLength(i.len)),r&&(this.warn("buffer full error also media.currentTime is not buffered, flush main"),this.immediateLevelSwitch()),this.resetLoadingState()}}},f.checkBuffer=function(){var t=this.media,e=this.gapController;if(t&&e&&t.readyState){var r=nt.getBuffered(t);!this.loadedmetadata&&r.length?(this.loadedmetadata=!0,this.seekToStartPos()):e.poll(this.lastCurrentTime),this.lastCurrentTime=t.currentTime}},f.onFragLoadEmergencyAborted=function(){this.state=_t,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()},f.onBufferFlushed=function(t,e){var r=e.type;if(r!==u.a.AUDIO||this.audioOnly&&!this.altAudio){var i=(r===u.a.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,r,_.b.MAIN)}},f.onLevelsUpdated=function(t,e){this.levels=e.levels},f.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},f.seekToStartPos=function(){var t=this.media,e=t.currentTime,r=this.startPosition;if(r>=0&&e0&&a1&&!1===t.seeking){var r=t.currentTime;if(nt.isBuffered(t,r)?e=this.getAppendedFrag(r):nt.isBuffered(t,r+.1)&&(e=this.getAppendedFrag(r+.1)),e){var i=this.fragPlaying,a=e.level;i&&e.sn===i.sn&&i.level===a&&e.urlId===i.urlId||(this.hls.trigger(n.a.FRAG_CHANGED,{frag:e}),i&&i.level===a||this.hls.trigger(n.a.LEVEL_SWITCHED,{level:a}),this.fragPlaying=e)}}},l=i,(d=[{key:"nextLevel",get:function(){var t=this.nextBufferedFrag;return t?t.level:-1}},{key:"currentLevel",get:function(){var t=this.media;if(t){var e=this.getAppendedFrag(t.currentTime);if(e)return e.level}return-1}},{key:"nextBufferedFrag",get:function(){var t=this.media;if(t){var e=this.getAppendedFrag(t.currentTime);return this.followingBufferedFrag(e)}return null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])&&Yt(l.prototype,d),h&&Yt(l,h),i}(Nt),zt=function(){function t(t,e,r){void 0===e&&(e=0),void 0===r&&(r=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=r}var e=t.prototype;return e.sample=function(t,e){var r=Math.pow(this.alpha_,t);this.estimate_=e*(1-r)+r*this.estimate_,this.totalWeight_+=t},e.getTotalWeight=function(){return this.totalWeight_},e.getEstimate=function(){if(this.alpha_){var t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_},t}(),Qt=function(){function t(t,e,r){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new zt(t),this.fast_=new zt(e)}var e=t.prototype;return e.update=function(t,e){var r=this.slow_,i=this.fast_;this.slow_.halfLife!==t&&(this.slow_=new zt(t,r.getEstimate(),r.getTotalWeight())),this.fast_.halfLife!==e&&(this.fast_=new zt(e,i.getEstimate(),i.getTotalWeight()))},e.sample=function(t,e){var r=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/r;this.fast_.sample(r,i),this.slow_.sample(r,i)},e.canEstimate=function(){var t=this.fast_;return t&&t.getTotalWeight()>=this.minWeight_},e.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},e.destroy=function(){},t}();function $t(t,e){for(var r=0;r=2*d/f||y<=T)){var E,S=Number.POSITIVE_INFINITY;for(E=t.level-1;E>v;E--){if((S=d*c[E].maxBitrate/(6.4*m))=y)){var L=this.bwEstimator.getEstimate();o.b.warn("Fragment "+t.sn+(e?" part "+e.index:"")+" of level "+t.level+" is loading too slowly and will cause an underbuffer; aborting and switching to level "+E+"\n Current BW estimate: "+(Object(a.a)(L)?(L/1024).toFixed(3):"Unknown")+" Kb/s\n Estimated load time for current fragment: "+y.toFixed(3)+" s\n Estimated load time for the next fragment: "+S.toFixed(3)+" s\n Time to underbuffer: "+T.toFixed(3)+" s"),r.nextLoadLevel=E,this.bwEstimator.sample(h,u.loaded),this.clearTimer(),t.loader&&(this.fragCurrent=this.partCurrent=null,t.loader.abort()),r.trigger(n.a.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:u})}}}}}},l.onFragLoaded=function(t,e){var r=e.frag,i=e.part;if(r.type===_.b.MAIN&&Object(a.a)(r.sn)){var s=i?i.stats:r.stats,o=i?i.duration:r.duration;if(this.clearTimer(),this.lastLoadedFragLevel=r.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){var l=this.hls.levels[r.level],u=(l.loaded?l.loaded.bytes:0)+s.loaded,d=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:u,duration:d},l.realBitrate=Math.round(8*u/d)}if(r.bitrateTest){var h={stats:s,frag:r,part:i,id:r.type};this.onFragBuffered(n.a.FRAG_BUFFERED,h),r.bitrateTest=!1}}},l.onFragBuffered=function(t,e){var r=e.frag,i=e.part,a=i?i.stats:r.stats;if(!a.aborted&&r.type===_.b.MAIN&&"initSegment"!==r.sn){var n=a.parsing.end-a.loading.start;this.bwEstimator.sample(n,a.loaded),a.bwEstimate=this.bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}},l.onError=function(t,e){switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:this.clearTimer()}},l.clearTimer=function(){self.clearInterval(this.timer),this.timer=void 0},l.getNextABRAutoLevel=function(){var t=this.fragCurrent,e=this.partCurrent,r=this.hls,i=r.maxAutoLevel,a=r.config,n=r.minAutoLevel,s=r.media,l=e?e.duration:t?t.duration:0,u=s?s.currentTime:0,d=s&&0!==s.playbackRate?Math.abs(s.playbackRate):1,h=this.bwEstimator?this.bwEstimator.getEstimate():a.abrEwmaDefaultEstimate,f=(nt.bufferInfo(s,u,a.maxBufferHole).end-u)/d,c=this.findBestLevel(h,n,i,f,a.abrBandWidthFactor,a.abrBandWidthUpFactor);if(c>=0)return c;o.b.trace((f?"rebuffering expected":"buffer is empty")+", finding optimal quality level");var v=l?Math.min(l,a.maxStarvationDelay):a.maxStarvationDelay,g=a.abrBandWidthFactor,p=a.abrBandWidthUpFactor;if(!f){var m=this.bitrateTestDelay;if(m)v=(l?Math.min(l,a.maxLoadingDelay):a.maxLoadingDelay)-m,o.b.trace("bitrate test took "+Math.round(1e3*m)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*v)+" ms"),g=p=1}return c=this.findBestLevel(h,n,i,f+v,g,p),Math.max(c,0)},l.findBestLevel=function(t,e,r,i,a,n){for(var s,l=this.fragCurrent,u=this.partCurrent,d=this.lastLoadedFragLevel,h=this.hls.levels,f=h[d],c=!(null==f||null===(s=f.details)||void 0===s||!s.live),v=null==f?void 0:f.codecSet,g=u?u.duration:l?l.duration:0,p=r;p>=e;p--){var m=h[p];if(m&&(!v||m.codecSet===v)){var y=m.details,b=(u?null==y?void 0:y.partTarget:null==y?void 0:y.averagetargetduration)||g,T=void 0;T=p<=d?a*t:n*t;var E=h[p].maxBitrate,S=E*b/T;if(o.b.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+p+"/"+Math.round(T)+"/"+E+"/"+b+"/"+i+"/"+S),T>E&&(!S||c&&!this.bitrateTestDelay||S0||Object.keys(this.pendingTracks).length>0},e.destroy=function(){this.unregisterListeners(),this.details=null},e.registerListeners=function(){var t=this.hls;t.on(n.a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(n.a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(n.a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(n.a.BUFFER_RESET,this.onBufferReset,this),t.on(n.a.BUFFER_APPENDING,this.onBufferAppending,this),t.on(n.a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(n.a.BUFFER_EOS,this.onBufferEos,this),t.on(n.a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(n.a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(n.a.FRAG_PARSED,this.onFragParsed,this),t.on(n.a.FRAG_CHANGED,this.onFragChanged,this)},e.unregisterListeners=function(){var t=this.hls;t.off(n.a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(n.a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(n.a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(n.a.BUFFER_RESET,this.onBufferReset,this),t.off(n.a.BUFFER_APPENDING,this.onBufferAppending,this),t.off(n.a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(n.a.BUFFER_EOS,this.onBufferEos,this),t.off(n.a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(n.a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(n.a.FRAG_PARSED,this.onFragParsed,this),t.off(n.a.FRAG_CHANGED,this.onFragChanged,this)},e._initSourceBuffer=function(){this.sourceBuffer={},this.operationQueue=new ee(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]}},e.onManifestParsed=function(t,e){var r=2;(e.audio&&!e.video||!e.altAudio)&&(r=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,this.details=null,o.b.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},e.onMediaAttaching=function(t,e){var r=this.media=e.media;if(r&&re){var i=this.mediaSource=new re;i.addEventListener("sourceopen",this._onMediaSourceOpen),i.addEventListener("sourceended",this._onMediaSourceEnded),i.addEventListener("sourceclose",this._onMediaSourceClose),r.src=self.URL.createObjectURL(i),this._objectUrl=r.src}},e.onMediaDetaching=function(){var t=this.media,e=this.mediaSource,r=this._objectUrl;if(e){if(o.b.log("[buffer-controller]: media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){o.b.warn("[buffer-controller]: onMediaDetaching: "+t.message+" while calling endOfStream")}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),t&&(r&&self.URL.revokeObjectURL(r),t.src===r?(t.removeAttribute("src"),t.load()):o.b.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(n.a.MEDIA_DETACHED,void 0)},e.onBufferReset=function(){var t=this;this.getSourceBufferTypes().forEach((function(e){var r=t.sourceBuffer[e];try{r&&(t.removeBufferListeners(e),t.mediaSource&&t.mediaSource.removeSourceBuffer(r),t.sourceBuffer[e]=void 0)}catch(t){o.b.warn("[buffer-controller]: Failed to reset the "+e+" buffer",t)}})),this._initSourceBuffer()},e.onBufferCodecs=function(t,e){var r=this,i=this.getSourceBufferTypes().length;Object.keys(e).forEach((function(t){if(i){var a=r.tracks[t];if(a&&"function"==typeof a.buffer.changeType){var n=e[t],s=n.codec,o=n.levelCodec,l=n.container;if((a.levelCodec||a.codec).replace(ie,"$1")!==(o||s).replace(ie,"$1")){var u=l+";codecs="+(o||s);r.appendChangeType(t,u)}}}else r.pendingTracks[t]=e[t]})),i||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())},e.appendChangeType=function(t,e){var r=this,i=this.operationQueue,a={execute:function(){var a=r.sourceBuffer[t];a&&(o.b.log("[buffer-controller]: changing "+t+" sourceBuffer type to "+e),a.changeType(e)),i.shiftAndExecuteNext(t)},onStart:function(){},onComplete:function(){},onError:function(e){o.b.warn("[buffer-controller]: Failed to change "+t+" SourceBuffer type",e)}};i.append(a,t)},e.onBufferAppending=function(t,e){var r=this,i=this.hls,a=this.operationQueue,l=this.tracks,u=e.data,d=e.type,h=e.frag,f=e.part,c=e.chunkMeta,v=c.buffering[d],g=self.performance.now();v.start=g;var p=h.stats.buffering,m=f?f.stats.buffering:null;0===p.start&&(p.start=g),m&&0===m.start&&(m.start=g);var y=l.audio,b="audio"===d&&1===c.id&&"audio/mpeg"===(null==y?void 0:y.container),T={execute:function(){if(v.executeStart=self.performance.now(),b){var t=r.sourceBuffer[d];if(t){var e=h.start-t.timestampOffset;Math.abs(e)>=.1&&(o.b.log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to "+h.start+" (delta: "+e+") sn: "+h.sn+")"),t.timestampOffset=h.start)}}r.appendExecutor(u,d)},onStart:function(){},onComplete:function(){var t=self.performance.now();v.executeEnd=v.end=t,0===p.first&&(p.first=t),m&&0===m.first&&(m.first=t);var e=r.sourceBuffer,i={};for(var a in e)i[a]=nt.getBuffered(e[a]);r.appendError=0,r.hls.trigger(n.a.BUFFER_APPENDED,{type:d,frag:h,part:f,chunkMeta:c,parent:h.type,timeRanges:i})},onError:function(t){o.b.error("[buffer-controller]: Error encountered while trying to append to the "+d+" SourceBuffer",t);var e={type:s.b.MEDIA_ERROR,parent:h.type,details:s.a.BUFFER_APPEND_ERROR,err:t,fatal:!1};t.code===DOMException.QUOTA_EXCEEDED_ERR?e.details=s.a.BUFFER_FULL_ERROR:(r.appendError++,e.details=s.a.BUFFER_APPEND_ERROR,r.appendError>i.config.appendErrorMaxRetry&&(o.b.error("[buffer-controller]: Failed "+i.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),e.fatal=!0)),i.trigger(n.a.ERROR,e)}};a.append(T,d)},e.onBufferFlushing=function(t,e){var r=this,i=this.operationQueue,a=function(t){return{execute:r.removeExecutor.bind(r,t,e.startOffset,e.endOffset),onStart:function(){},onComplete:function(){r.hls.trigger(n.a.BUFFER_FLUSHED,{type:t})},onError:function(e){o.b.warn("[buffer-controller]: Failed to remove from "+t+" SourceBuffer",e)}}};e.type?i.append(a(e.type),e.type):this.getSourceBufferTypes().forEach((function(t){i.append(a(t),t)}))},e.onFragParsed=function(t,e){var r=this,i=e.frag,a=e.part,s=[],l=a?a.elementaryStreams:i.elementaryStreams;l[u.a.AUDIOVIDEO]?s.push("audiovideo"):(l[u.a.AUDIO]&&s.push("audio"),l[u.a.VIDEO]&&s.push("video"));0===s.length&&o.b.warn("Fragments must have at least one ElementaryStreamType set. type: "+i.type+" level: "+i.level+" sn: "+i.sn),this.blockBuffers((function(){var t=self.performance.now();i.stats.buffering.end=t,a&&(a.stats.buffering.end=t);var e=a?a.stats:i.stats;r.hls.trigger(n.a.FRAG_BUFFERED,{frag:i,part:a,stats:e,id:i.type})}),s)},e.onFragChanged=function(t,e){this.flushBackBuffer()},e.onBufferEos=function(t,e){var r=this;this.getSourceBufferTypes().reduce((function(t,i){var a=r.sourceBuffer[i];return e.type&&e.type!==i||a&&!a.ended&&(a.ended=!0,o.b.log("[buffer-controller]: "+i+" sourceBuffer now EOS")),t&&!(a&&!a.ended)}),!0)&&this.blockBuffers((function(){var t=r.mediaSource;t&&"open"===t.readyState&&t.endOfStream()}))},e.onLevelUpdated=function(t,e){var r=e.details;r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())},e.flushBackBuffer=function(){var t=this.hls,e=this.details,r=this.media,i=this.sourceBuffer;if(r&&null!==e){var s=this.getSourceBufferTypes();if(s.length){var o=e.live&&null!==t.config.liveBackBufferLength?t.config.liveBackBufferLength:t.config.backBufferLength;if(Object(a.a)(o)&&!(o<0)){var l=r.currentTime,u=e.levelTargetDuration,d=Math.max(o,u),h=Math.floor(l/u)*u-d;s.forEach((function(r){var a=i[r];if(a){var s=nt.getBuffered(a);s.length>0&&h>s.start(0)&&(t.trigger(n.a.BACK_BUFFER_REACHED,{bufferEnd:h}),e.live&&t.trigger(n.a.LIVE_BACK_BUFFER_REACHED,{bufferEnd:h}),t.trigger(n.a.BUFFER_FLUSHING,{startOffset:0,endOffset:h,type:r}))}}))}}}},e.updateMediaElementDuration=function(){if(this.details&&this.media&&this.mediaSource&&"open"===this.mediaSource.readyState){var t=this.details,e=this.hls,r=this.media,i=this.mediaSource,n=t.fragments[0].start+t.totalduration,s=r.duration,l=Object(a.a)(i.duration)?i.duration:0;t.live&&e.config.liveDurationInfinity?(o.b.log("[buffer-controller]: Media Source duration is set to Infinity"),i.duration=1/0,this.updateSeekableRange(t)):(n>l&&n>s||!Object(a.a)(s))&&(o.b.log("[buffer-controller]: Updating Media Source duration to "+n.toFixed(3)),i.duration=n)}},e.updateSeekableRange=function(t){var e=this.mediaSource,r=t.fragments;if(r.length&&t.live&&null!=e&&e.setLiveSeekableRange){var i=Math.max(0,r[0].start),a=Math.max(i,i+t.totalduration);e.setLiveSeekableRange(i,a)}},e.checkPendingTracks=function(){var t=this.bufferCodecEventsExpected,e=this.operationQueue,r=this.pendingTracks,i=Object.keys(r).length;if(i&&!t||2===i){this.createSourceBuffers(r),this.pendingTracks={};var a=this.getSourceBufferTypes();if(0===a.length)return void this.hls.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,reason:"could not create source buffer for media codec(s)"});a.forEach((function(t){e.executeNext(t)}))}},e.createSourceBuffers=function(t){var e=this.sourceBuffer,r=this.mediaSource;if(!r)throw Error("createSourceBuffers called when mediaSource was null");var i=0;for(var a in t)if(!e[a]){var l=t[a];if(!l)throw Error("source buffer exists for track "+a+", however track does not");var u=l.levelCodec||l.codec,d=l.container+";codecs="+u;o.b.log("[buffer-controller]: creating sourceBuffer("+d+")");try{var h=e[a]=r.addSourceBuffer(d),f=a;this.addBufferListener(f,"updatestart",this._onSBUpdateStart),this.addBufferListener(f,"updateend",this._onSBUpdateEnd),this.addBufferListener(f,"error",this._onSBUpdateError),this.tracks[a]={buffer:h,codec:u,container:l.container,levelCodec:l.levelCodec,id:l.id},i++}catch(t){o.b.error("[buffer-controller]: error while trying to add sourceBuffer: "+t.message),this.hls.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,mimeType:d})}}i&&this.hls.trigger(n.a.BUFFER_CREATED,{tracks:this.tracks})},e._onSBUpdateStart=function(t){this.operationQueue.current(t).onStart()},e._onSBUpdateEnd=function(t){var e=this.operationQueue;e.current(t).onComplete(),e.shiftAndExecuteNext(t)},e._onSBUpdateError=function(t,e){o.b.error("[buffer-controller]: "+t+" SourceBuffer error",e),this.hls.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_APPENDING_ERROR,fatal:!1});var r=this.operationQueue.current(t);r&&r.onError(e)},e.removeExecutor=function(t,e,r){var i=this.media,n=this.mediaSource,s=this.operationQueue,l=this.sourceBuffer[t];if(!i||!n||!l)return o.b.warn("[buffer-controller]: Attempting to remove from the "+t+" SourceBuffer, but it does not exist"),void s.shiftAndExecuteNext(t);var u=Object(a.a)(i.duration)?i.duration:1/0,d=Object(a.a)(n.duration)?n.duration:1/0,h=Math.max(0,e),f=Math.min(r,u,d);f>h?(o.b.log("[buffer-controller]: Removing ["+h+","+f+"] from the "+t+" SourceBuffer"),l.remove(h,f)):s.shiftAndExecuteNext(t)},e.appendExecutor=function(t,e){var r=this.operationQueue,i=this.sourceBuffer[e];if(!i)return o.b.warn("[buffer-controller]: Attempting to append to the "+e+" SourceBuffer, but it does not exist"),void r.shiftAndExecuteNext(e);i.ended=!1,i.appendBuffer(t)},e.blockBuffers=function(t,e){var r=this;if(void 0===e&&(e=this.getSourceBufferTypes()),!e.length)return o.b.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve(t);var i=this.operationQueue,a=e.map((function(t){return i.appendBlocker(t)}));Promise.all(a).then((function(){t(),e.forEach((function(t){var e=r.sourceBuffer[t];e&&e.updating||i.shiftAndExecuteNext(t)}))}))},e.getSourceBufferTypes=function(){return Object.keys(this.sourceBuffer)},e.addBufferListener=function(t,e,r){var i=this.sourceBuffer[t];if(i){var a=r.bind(this,t);this.listeners[t].push({event:e,listener:a}),i.addEventListener(e,a)}},e.removeBufferListeners=function(t){var e=this.sourceBuffer[t];e&&this.listeners[t].forEach((function(t){e.removeEventListener(t.event,t.listener)}))},t}();function ne(t,e){for(var r=0;r0&&this.mediaWidth>0){var t=this.hls.levels;if(t.length){var e=this.hls;e.autoLevelCapping=this.getMaxLevel(t.length-1),e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}},a.getMaxLevel=function(e){var r=this,i=this.hls.levels;if(!i.length)return-1;var a=i.filter((function(i,a){return t.isLevelAllowed(a,r.restrictedLevels)&&a<=e}));return this.clientRect=null,t.getMaxLevelByMediaSize(a,this.mediaWidth,this.mediaHeight)},a.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},a.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},a.getDimensions=function(){if(this.clientRect)return this.clientRect;var t=this.media,e={width:0,height:0};if(t){var r=t.getBoundingClientRect();e.width=r.width,e.height=r.height,e.width||e.height||(e.width=r.right-r.left||t.width||0,e.height=r.bottom-r.top||t.height||0)}return this.clientRect=e,e},t.isLevelAllowed=function(t,e){return void 0===e&&(e=[]),-1===e.indexOf(t)},t.getMaxLevelByMediaSize=function(t,e,r){if(!t||!t.length)return-1;for(var i,a,n=t.length-1,s=0;s=e||o.height>=r)&&(i=o,!(a=t[s+1])||i.width!==a.width||i.height!==a.height)){n=s;break}}return n},e=t,i=[{key:"contentScaleFactor",get:function(){var t=1;try{t=self.devicePixelRatio}catch(t){}return t}}],(r=[{key:"mediaWidth",get:function(){return this.getDimensions().width*t.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*t.contentScaleFactor}}])&&ne(e.prototype,r),i&&ne(e,i),t}(),oe=function(){function t(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}var e=t.prototype;return e.setStreamController=function(t){this.streamController=t},e.registerListeners=function(){this.hls.on(n.a.MEDIA_ATTACHING,this.onMediaAttaching,this)},e.unregisterListeners=function(){this.hls.off(n.a.MEDIA_ATTACHING,this.onMediaAttaching)},e.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},e.onMediaAttaching=function(t,e){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},e.checkFPS=function(t,e,r){var i=performance.now();if(e){if(this.lastTime){var a=i-this.lastTime,s=r-this.lastDroppedFrames,l=e-this.lastDecodedFrames,u=1e3*s/a,d=this.hls;if(d.trigger(n.a.FPS_DROP,{currentDropped:s,currentDecoded:l,totalDroppedFrames:r}),u>0&&s>d.config.fpsDroppedMonitoringThreshold*l){var h=d.currentLevel;o.b.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(-1===d.autoLevelCapping||d.autoLevelCapping>=h)&&(h-=1,d.trigger(n.a.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:d.currentLevel}),d.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=e}},e.checkFPSInterval=function(){var t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){var e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)},t}(),le=r(12),ue=/^age:\s*[\d.]+\s*$/m,de=function(){function t(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=t?t.xhrSetup:null,this.stats=new le.a,this.retryDelay=0}var e=t.prototype;return e.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null},e.abortInternal=function(){var t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))},e.abort=function(){var t;this.abortInternal(),null!==(t=this.callbacks)&&void 0!==t&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},e.load=function(t,e,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=r,this.retryDelay=e.retryDelay,this.loadInternal()},e.loadInternal=function(){var t=this.config,e=this.context;if(t){var r=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0;var a=this.xhrSetup;try{if(a)try{a(r,e.url)}catch(t){r.open("GET",e.url,!0),a(r,e.url)}r.readyState||r.open("GET",e.url,!0)}catch(t){return void this.callbacks.onError({code:r.status,text:t.message},e,r)}e.rangeEnd&&r.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),r.onreadystatechange=this.readystatechange.bind(this),r.onprogress=this.loadprogress.bind(this),r.responseType=e.responseType,self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),t.timeout),r.send()}},e.readystatechange=function(){var t=this.context,e=this.loader,r=this.stats;if(t&&e){var i=e.readyState,a=this.config;if(!r.aborted&&i>=2)if(self.clearTimeout(this.requestTimeout),0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start)),4===i){e.onreadystatechange=null,e.onprogress=null;var n=e.status;if(n>=200&&n<300){var s,l;if(r.loading.end=Math.max(self.performance.now(),r.loading.first),l="arraybuffer"===t.responseType?(s=e.response).byteLength:(s=e.responseText).length,r.loaded=r.total=l,!this.callbacks)return;var u=this.callbacks.onProgress;if(u&&u(r,t,s,e),!this.callbacks)return;var d={url:e.responseURL,data:s};this.callbacks.onSuccess(d,r,t,e)}else r.retry>=a.maxRetry||n>=400&&n<499?(o.b.error(n+" while loading "+t.url),this.callbacks.onError({code:n,text:e.statusText},t,e)):(o.b.warn(n+" while loading "+t.url+", retrying in "+this.retryDelay+"..."),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,a.maxRetryDelay),r.retry++)}else self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),a.timeout)}},e.loadtimeout=function(){o.b.warn("timeout while loading "+this.context.url);var t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))},e.loadprogress=function(t){var e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)},e.getCacheAge=function(){var t=null;if(this.loader&&ue.test(this.loader.getAllResponseHeaders())){var e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t},t}(),he=r(16);function fe(t){var e="function"==typeof Map?new Map:void 0;return(fe=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,i)}function i(){return ce(t,arguments,pe(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),ge(i,t)})(t)}function ce(t,e,r){return(ce=ve()?Reflect.construct:function(t,e,r){var i=[null];i.push.apply(i,e);var a=new(Function.bind.apply(t,i));return r&&ge(a,r.prototype),a}).apply(null,arguments)}function ve(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function ge(t,e){return(ge=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function pe(t){return(pe=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var me=function(){function t(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||ye,this.controller=new self.AbortController,this.stats=new le.a}var e=t.prototype;return e.destroy=function(){this.loader=this.callbacks=null,this.abortInternal()},e.abortInternal=function(){var t=this.response;t&&t.ok||(this.stats.aborted=!0,this.controller.abort())},e.abort=function(){var t;this.abortInternal(),null!==(t=this.callbacks)&&void 0!==t&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},e.load=function(t,e,r){var i=this,n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();var s=function(t,e){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:e};t.rangeEnd&&(r.headers=new self.Headers({Range:"bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)}));return r}(t,this.controller.signal),o=r.onProgress,l="arraybuffer"===t.responseType,u=l?"byteLength":"length";this.context=t,this.config=e,this.callbacks=r,this.request=this.fetchSetup(t,s),self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout((function(){i.abortInternal(),r.onTimeout(n,t,i.response)}),e.timeout),self.fetch(this.request).then((function(r){if(i.response=i.loader=r,!r.ok){var s=r.status,u=r.statusText;throw new Te(u||"fetch, bad network response",s,r)}return n.loading.first=Math.max(self.performance.now(),n.loading.start),n.total=parseInt(r.headers.get("Content-Length")||"0"),o&&Object(a.a)(e.highWaterMark)?i.loadProgressively(r,n,t,e.highWaterMark,o):l?r.arrayBuffer():r.text()})).then((function(s){var l=i.response;self.clearTimeout(i.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first),n.loaded=n.total=s[u];var d={url:l.url,data:s};o&&!Object(a.a)(e.highWaterMark)&&o(n,t,s,l),r.onSuccess(d,n,t,l)})).catch((function(e){if(self.clearTimeout(i.requestTimeout),!n.aborted){var a=e.code||0;r.onError({code:a,text:e.message},t,e.details)}}))},e.getCacheAge=function(){var t=null;if(this.response){var e=this.response.headers.get("age");t=e?parseFloat(e):null}return t},e.loadProgressively=function(t,e,r,i,a){void 0===i&&(i=0);var n=new he.a,s=t.body.getReader();return function o(){return s.read().then((function(s){if(s.done)return n.dataLength&&a(e,r,n.flush(),t),Promise.resolve(new ArrayBuffer(0));var l=s.value,u=l.length;return e.loaded+=u,u=i&&a(e,r,n.flush(),t)):a(e,r,l,t),o()})).catch((function(){return Promise.reject()}))}()},t}();function ye(t,e){return new self.Request(t.url,e)}var be,Te=function(t){var e,r;function i(e,r,i){var a;return(a=t.call(this,e)||this).code=void 0,a.details=void 0,a.code=r,a.details=i,a}return r=t,(e=i).prototype=Object.create(r.prototype),e.prototype.constructor=e,ge(e,r),i}(fe(Error)),Ee=me;!function(t){t.WIDEVINE="com.widevine.alpha",t.PLAYREADY="com.microsoft.playready"}(be||(be={}));var Se="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Le(){return(Le=Object.assign||function(t){for(var e=1;ee)return i;return 0}},{key:"maxAutoLevel",get:function(){var t=this.levels,e=this.autoLevelCapping;return-1===e&&t&&t.length?t.length-1:e}},{key:"nextAutoLevel",get:function(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)},set:function(t){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,t)}},{key:"audioTracks",get:function(){var t=this.audioTrackController;return t?t.audioTracks:[]}},{key:"audioTrack",get:function(){var t=this.audioTrackController;return t?t.audioTrack:-1},set:function(t){var e=this.audioTrackController;e&&(e.audioTrack=t)}},{key:"subtitleTracks",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTrack:-1},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var t=this.subtitleTrackController;return!!t&&t.subtitleDisplay},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(t){this.config.lowLatencyMode=t}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}}])&&xe(e.prototype,r),a&&xe(e,a),t}();we.defaultConfig=void 0}]).default})); +// @version v1.1.5 +"undefined"!=typeof window&&function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Hls=e():t.Hls=e()}(this,(function(){return function(t){var e={};function r(i){if(e[i])return e[i].exports;var a=e[i]={i:i,l:!1,exports:{}};return t[i].call(a.exports,a,a.exports,r),a.l=!0,a.exports}return r.m=t,r.c=e,r.d=function(t,e,i){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var a in t)r.d(i,a,function(e){return t[e]}.bind(null,a));return i},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="/dist/",r(r.s=19)}([function(t,e,r){"use strict";var i;r.d(e,"a",(function(){return i})),function(t){t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached"}(i||(i={}))},function(t,e,r){"use strict";r.d(e,"a",(function(){return o})),r.d(e,"b",(function(){return l}));var i=function(){},a={trace:i,debug:i,log:i,warn:i,info:i,error:i},n=a;function s(t){var e=self.console[t];return e?e.bind(self.console,"["+t+"] >"):i}function o(t){if(self.console&&!0===t||"object"==typeof t){!function(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i>8*(15-r)&255;return e},r.setDecryptDataFromLevelKey=function(t,e){var r=t;return"AES-128"===(null==t?void 0:t.method)&&t.uri&&!t.iv&&((r=o.a.fromURI(t.uri)).method=t.method,r.iv=this.createInitializationVector(e),r.keyFormat="identity"),r},r.setElementaryStreamInfo=function(t,e,r,i,a,n){void 0===n&&(n=!1);var s=this.elementaryStreams,o=s[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,a)):s[t]={startPTS:e,endPTS:r,startDTS:i,endDTS:a,partial:n}},r.clearElementaryStreamInfo=function(){var t=this.elementaryStreams;t[i.AUDIO]=null,t[i.VIDEO]=null,t[i.AUDIOVIDEO]=null},f(e,[{key:"decryptdata",get:function(){if(!this.levelkey&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkey){var t=this.sn;"number"!=typeof t&&(this.levelkey&&"AES-128"===this.levelkey.method&&!this.levelkey.iv&&s.b.warn('missing IV for initialization segment with method="'+this.levelkey.method+'" - compliance issue'),t=0),this._decryptdata=this.setDecryptDataFromLevelKey(this.levelkey,t)}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;if(!Object(a.a)(this.programDateTime))return null;var t=Object(a.a)(this.duration)?this.duration:0;return this.programDateTime+1e3*t}},{key:"encrypted",get:function(){var t;return!(null===(t=this.decryptdata)||void 0===t||!t.keyFormat||!this.decryptdata.uri)}}]),e}(c),g=function(t){function e(e,r,i,a,n){var s;(s=t.call(this,i)||this).fragOffset=0,s.duration=0,s.gap=!1,s.independent=!1,s.relurl=void 0,s.fragment=void 0,s.index=void 0,s.stats=new l.a,s.duration=e.decimalFloatingPoint("DURATION"),s.gap=e.bool("GAP"),s.independent=e.bool("INDEPENDENT"),s.relurl=e.enumeratedString("URI"),s.fragment=r,s.index=a;var o=e.enumeratedString("BYTERANGE");return o&&s.setByteRange(o,n),n&&(s.fragOffset=n.fragOffset+n.duration),s}return u(e,t),f(e,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var t=this.elementaryStreams;return!!(t.audio||t.video||t.audiovideo)}}]),e}(c)},function(t,e,r){"use strict";r.d(e,"b",(function(){return d})),r.d(e,"g",(function(){return h})),r.d(e,"f",(function(){return f})),r.d(e,"d",(function(){return c})),r.d(e,"c",(function(){return v})),r.d(e,"e",(function(){return p})),r.d(e,"h",(function(){return m})),r.d(e,"a",(function(){return y}));var i=r(8),a=r(5),n=Math.pow(2,32)-1,s=[].push;function o(t){return String.fromCharCode.apply(null,t)}function l(t,e){"data"in t&&(e+=t.start,t=t.data);var r=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3];return r<0?4294967296+r:r}function u(t,e,r){"data"in t&&(e+=t.start,t=t.data),t[e]=r>>24,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=255&r}function d(t,e){var r,i,a,n=[];if(!e.length)return n;"data"in t?(r=t.data,i=t.start,a=t.end):(i=0,a=(r=t).byteLength);for(var u=i;u1?u+h:a;if(o(r.subarray(u+4,u+8))===e[0])if(1===e.length)n.push({data:r,start:u+8,end:f});else{var c=d({data:r,start:u+8,end:f},e.slice(1));c.length&&s.apply(n,c)}u=f}return n}function h(t){var e=d(t,["moov"])[0],r=e?e.end:null,i=d(t,["sidx"]);if(!i||!i[0])return null;var a=[],n=i[0],s=n.data[0],o=0===s?8:16,u=l(n,o);o+=4;o+=0===s?8:16,o+=2;var h=n.end+0,f=function(t,e){"data"in t&&(e+=t.start,t=t.data);var r=t[e]<<8|t[e+1];return r<0?65536+r:r}(n,o);o+=2;for(var c=0;c>>31)return console.warn("SIDX has hierarchical references (not supported)"),null;var m=l(n,v);v+=4,a.push({referenceSize:p,subsegmentDuration:m,info:{duration:m/u,start:h,end:h+p-1}}),h+=p,o=v+=4}return{earliestPresentationTime:0,timescale:u,version:s,referencesCount:f,references:a,moovEndOffset:r}}function f(t){for(var e=[],r=d(t,["moov","trak"]),i=0;i0)return t.subarray(r,r+i)},o=function(t,e){var r=0;return r=(127&t[e])<<21,r|=(127&t[e+1])<<14,r|=(127&t[e+2])<<7,r|=127&t[e+3]},l=function(t,e){return a(t,e)&&o(t,e+6)+10<=t.length-e},u=function(t){for(var e=f(t),r=0;r>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:u+=String.fromCharCode(n);break;case 12:case 13:s=t[d++],u+=String.fromCharCode((31&n)<<6|63&s);break;case 14:s=t[d++],o=t[d++],u+=String.fromCharCode((15&n)<<12|(63&s)<<6|(63&o)<<0)}}return u};function b(){return i||void 0===self.TextDecoder||(i=new self.TextDecoder("utf-8")),i}},function(t,e,r){"use strict";function i(t,e,r){return Uint8Array.prototype.slice?t.slice(e,r):new Uint8Array(Array.prototype.slice.call(t,e,r))}r.d(e,"a",(function(){return i}))},function(t,e,r){"use strict";r.d(e,"c",(function(){return St})),r.d(e,"d",(function(){return At})),r.d(e,"a",(function(){return Rt})),r.d(e,"b",(function(){return Dt}));var i=r(0),a=r(2),n=r(14),s=r(3),o=r(7);var l=r(6),u=r(8),d=function(){function t(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.initPTS=null}var e=t.prototype;return e.resetInitSegment=function(t,e,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},e.resetTimeStamp=function(){},e.resetContiguity=function(){},e.canParse=function(t,e){return!1},e.appendFrame=function(t,e,r){},e.demux=function(t,e){this.cachedData&&(t=Object(l.a)(this.cachedData,t),this.cachedData=null);var r,i,a=o.b(t,0),n=a?a.length:0,s=this._audioTrack,d=this._id3Track,f=a?o.d(a):void 0,c=t.length;for(0!==this.frameIndex&&null!==this.initPTS||(this.initPTS=h(f,e)),a&&a.length>0&&d.samples.push({pts:this.initPTS,dts:this.initPTS,data:a}),i=this.initPTS;n>>5}function m(t,e){return e+1=t.length)return!1;var i=p(t,e);if(i<=r)return!1;var a=e+i;return a===t.length||m(t,a)}return!1}function b(t,e,r,n,s){if(!t.samplerate){var o=function(t,e,r,n){var s,o,l,u,d=navigator.userAgent.toLowerCase(),h=n,f=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&e[r+2])>>>6);var v=(60&e[r+2])>>>2;if(!(v>f.length-1))return l=(1&e[r+2])<<2,l|=(192&e[r+3])>>>6,c.b.log("manifest codec:"+n+", ADTS type:"+s+", samplingIndex:"+v),/firefox/i.test(d)?v>=6?(s=5,u=new Array(4),o=v-3):(s=2,u=new Array(2),o=v):-1!==d.indexOf("android")?(s=2,u=new Array(2),o=v):(s=5,u=new Array(4),n&&(-1!==n.indexOf("mp4a.40.29")||-1!==n.indexOf("mp4a.40.5"))||!n&&v>=6?o=v-3:((n&&-1!==n.indexOf("mp4a.40.2")&&(v>=6&&1===l||/vivaldi/i.test(d))||!n&&1===l)&&(s=2,u=new Array(2)),o=v)),u[0]=s<<3,u[0]|=(14&v)>>1,u[1]|=(1&v)<<7,u[1]|=l<<3,5===s&&(u[1]|=(14&o)>>1,u[2]=(1&o)<<7,u[2]|=8,u[3]=0),{config:u,samplerate:f[v],channelCount:l,codec:"mp4a.40."+s,manifestCodec:h};t.trigger(i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+v})}(e,r,n,s);if(!o)return;t.config=o.config,t.samplerate=o.samplerate,t.channelCount=o.channelCount,t.codec=o.codec,t.manifestCodec=o.manifestCodec,c.b.log("parsed codec:"+t.codec+", rate:"+o.samplerate+", channels:"+o.channelCount)}}function T(t){return 9216e4/t}function E(t,e,r,i,a){var n=function(t,e,r,i,a){var n=g(t,e),s=p(t,e);if((s-=n)>0)return{headerLength:n,frameLength:s,stamp:r+i*a}}(e,r,i,a,T(t.samplerate));if(n){var s,o=n.frameLength,l=n.headerLength,u=n.stamp,d=l+o,h=Math.max(0,r+d-e.length);h?(s=new Uint8Array(d-l)).set(e.subarray(r+l,e.length),0):s=e.subarray(r+l,r+d);var f={unit:s,pts:u};return h||t.samples.push(f),{sample:f,length:d,missing:h}}}function S(t,e){return(S=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}var L=function(t){var e,r;function i(e,r){var i;return(i=t.call(this)||this).observer=void 0,i.config=void 0,i.observer=e,i.config=r,i}r=t,(e=i).prototype=Object.create(r.prototype),e.prototype.constructor=e,S(e,r);var a=i.prototype;return a.resetInitSegment=function(e,r,i){t.prototype.resetInitSegment.call(this,e,r,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,isAAC:!0,samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}},i.probe=function(t){if(!t)return!1;for(var e=(o.b(t,0)||[]).length,r=t.length;e0},e.demux=function(t){var e=t,r={type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0};if(this.config.progressive){this.remainderData&&(e=Object(l.a)(this.remainderData,t));var i=Object(l.h)(e);this.remainderData=i.remainder,r.samples=i.valid||new Uint8Array}else r.samples=e;return{audioTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},avcTrack:r,id3Track:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},textTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0}}},e.flush=function(){var t={type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0};return t.samples=this.remainderData||new Uint8Array,this.remainderData=null,{audioTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},avcTrack:t,id3Track:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},textTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0}}},e.demuxSampleAes=function(t,e,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},e.destroy=function(){},t}();R.minProbeByteLength=1024;var D=R,_=null,k=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],x=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],C=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],w=[0,1,1,4];function O(t,e,r,i,a){if(!(r+24>e.length)){var n=I(e,r);if(n&&r+n.frameLength<=e.length){var s=i+a*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(r,r+n.frameLength),pts:s,dts:s};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}}function I(t,e){var r=t[e+1]>>3&3,i=t[e+1]>>1&3,a=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==r&&0!==a&&15!==a&&3!==n){var s=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*k[14*(3===r?3-i:3===i?3:4)+a-1],u=x[3*(3===r?0:2===r?1:2)+n],d=3===o?1:2,h=C[r][i],f=w[i],c=8*h*f,v=Math.floor(h*l/u+s)*f;if(null===_){var g=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);_=g?parseInt(g[1]):0}return!!_&&_<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:u,channelCount:d,frameLength:v,samplesPerFrame:c}}}function P(t,e){return 255===t[e]&&224==(224&t[e+1])&&0!=(6&t[e+1])}function F(t,e){return e+1t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,t-=(e=t>>3)>>3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)},e.readBits=function(t){var e=Math.min(this.bitsAvailable,t),r=this.word>>>32-e;return t>32&&c.b.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0?this.word<<=e:this.bytesAvailable>0&&this.loadWord(),(e=t-e)>0&&this.bitsAvailable?r<>>t))return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()},e.skipUEG=function(){this.skipBits(1+this.skipLZ())},e.skipEG=function(){this.skipBits(1+this.skipLZ())},e.readUEG=function(){var t=this.skipLZ();return this.readBits(t+1)-1},e.readEG=function(){var t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)},e.readBoolean=function(){return 1===this.readBits(1)},e.readUByte=function(){return this.readBits(8)},e.readUShort=function(){return this.readBits(16)},e.readUInt=function(){return this.readBits(32)},e.skipScalingList=function(t){for(var e=8,r=8,i=0;i=t.length)return void r();if(!(t[e].unit.length<32)){var i=this.decrypter.isSync();if(this.decryptAacSample(t,e,r,i),!i)return}}},e.getAvcEncryptedData=function(t){for(var e=16*Math.floor((t.length-48)/160)+16,r=new Int8Array(e),i=0,a=32;a=t.length)return void i();for(var a=t[e].units;!(r>=a.length);r++){var n=a[r];if(!(n.data.length<=48||1!==n.type&&5!==n.type)){var s=this.decrypter.isSync();if(this.decryptAvcSample(t,e,r,i,n,s),!s)return}}}},t}(),U={video:1,audio:2,id3:3,text:4},G=function(){function t(t,e,r){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this.aacLastPTS=null,this._initPTS=null,this._initDTS=null,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=t,this.config=e,this.typeSupported=r}t.probe=function(e){var r=t.syncOffset(e);return!(r<0)&&(r&&c.b.warn("MPEG2-TS detected but first sync word found @ offset "+r+", junk ahead ?"),!0)},t.syncOffset=function(t){for(var e=Math.min(1e3,t.length-564),r=0;r>4>1){if((k=R+5+e[R+4])===R+188)continue}else k=R+4;switch(_){case f:D&&(v&&(o=V(v))&&this.parseAVCPES(o,!1),v={data:[],size:0}),v&&(v.data.push(e.subarray(k,R+188)),v.size+=R+188-k);break;case g:D&&(m&&(o=V(m))&&(d.isAAC?this.parseAACPES(o):this.parseMPEGPES(o)),m={data:[],size:0}),m&&(m.data.push(e.subarray(k,R+188)),m.size+=R+188-k);break;case p:D&&(y&&(o=V(y))&&this.parseID3PES(o),y={data:[],size:0}),y&&(y.data.push(e.subarray(k,R+188)),y.size+=R+188-k);break;case 0:D&&(k+=e[k]+1),E=this._pmtId=H(e,k);break;case E:D&&(k+=e[k]+1);var x=K(e,k,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,n);(f=x.avc)>0&&(u.pid=f),(g=x.audio)>0&&(d.pid=g,d.isAAC=x.isAAC),(p=x.id3)>0&&(h.pid=p),b&&!T&&(c.b.log("reparse from beginning"),b=!1,R=L-188),T=this.pmtParsed=!0;break;case 17:case 8191:break;default:b=!0}}else A++;A>0&&this.observer.emit(i.a.ERROR,i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!1,reason:"Found "+A+" TS packet/s that do not start with 0x47"}),u.pesData=v,d.pesData=m,h.pesData=y;var C={audioTrack:d,avcTrack:u,id3Track:h,textTrack:this._txtTrack};return s&&this.extractRemainingSamples(C),C},e.flush=function(){var t,e=this.remainderData;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{audioTrack:this._audioTrack,avcTrack:this._avcTrack,textTrack:this._txtTrack,id3Track:this._id3Track},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t},e.extractRemainingSamples=function(t){var e,r=t.audioTrack,i=t.avcTrack,a=t.id3Track,n=i.pesData,s=r.pesData,o=a.pesData;n&&(e=V(n))?(this.parseAVCPES(e,!0),i.pesData=null):i.pesData=n,s&&(e=V(s))?(r.isAAC?this.parseAACPES(e):this.parseMPEGPES(e),r.pesData=null):(null!=s&&s.size&&c.b.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=s),o&&(e=V(o))?(this.parseID3PES(e),a.pesData=null):a.pesData=o},e.demuxSampleAes=function(t,e,r){var i=this.demux(t,r,!0,!this.config.progressive),a=this.sampleAes=new B(this.observer,this.config,e);return this.decrypt(i,a)},e.decrypt=function(t,e){return new Promise((function(r){var i=t.audioTrack,a=t.avcTrack;i.samples&&i.isAAC?e.decryptAacSamples(i.samples,0,(function(){a.samples?e.decryptAvcSamples(a.samples,0,0,(function(){r(t)})):r(t)})):a.samples&&e.decryptAvcSamples(a.samples,0,0,(function(){r(t)}))}))},e.destroy=function(){this._initPTS=this._initDTS=null,this._duration=0},e.parseAVCPES=function(t,e){var r,i=this,a=this._avcTrack,n=this.parseAVCNALu(t.data),s=this.avcSample,l=!1;t.data=null,s&&n.length&&!a.audFound&&(W(s,a),s=this.avcSample=j(!1,t.pts,t.dts,"")),n.forEach((function(e){switch(e.type){case 1:r=!0,s||(s=i.avcSample=j(!0,t.pts,t.dts,"")),s.frame=!0;var n=e.data;if(l&&n.length>4){var u=new N(n).readSliceType();2!==u&&4!==u&&7!==u&&9!==u||(s.key=!0)}break;case 5:r=!0,s||(s=i.avcSample=j(!0,t.pts,t.dts,"")),s.key=!0,s.frame=!0;break;case 6:r=!0;var d=new N(X(e.data));d.readUByte();for(var h=0,f=0,c=!1,v=0;!c&&d.bytesAvailable>1;){h=0;do{h+=v=d.readUByte()}while(255===v);f=0;do{f+=v=d.readUByte()}while(255===v);if(4===h&&0!==d.bytesAvailable){if(c=!0,181===d.readUByte())if(49===d.readUShort())if(1195456820===d.readUInt())if(3===d.readUByte()){for(var g=d.readUByte(),p=31&g,m=[g,d.readUByte()],y=0;y16){for(var b=[],T=0;T<16;T++)b.push(d.readUByte().toString(16)),3!==T&&5!==T&&7!==T&&9!==T||b.push("-");for(var E=f-16,S=new Uint8Array(E),L=0;L=0){var h={data:t.subarray(u,l-n-1),type:d};o.push(h)}else{var f=this.getLastNalUnit();if(f&&(s&&l<=4-s&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-s)),(r=l-n-1)>0)){var c=new Uint8Array(f.data.byteLength+r);c.set(f.data,0),c.set(t.subarray(0,r),f.data.byteLength),f.data=c,f.state=0}}l=0&&n>=0){var v={data:t.subarray(u,i),type:d,state:n};o.push(v)}if(0===o.length){var g=this.getLastNalUnit();if(g){var p=new Uint8Array(g.data.byteLength+t.byteLength);p.set(g.data,0),p.set(t,g.data.byteLength),g.data=p}}return a.naluState=n,o},e.parseAACPES=function(t){var e,r,n,s,o,l=0,u=this._audioTrack,d=this.aacOverFlow,h=t.data;if(d){this.aacOverFlow=null;var f=d.sample.unit.byteLength,v=Math.min(d.missing,f),g=f-v;d.sample.unit.set(h.subarray(0,v),g),u.samples.push(d.sample),l=d.missing}for(e=l,r=h.length;e1;){var l=new Uint8Array(o[0].length+o[1].length);l.set(o[0]),l.set(o[1],o[0].length),o[0]=l,o.splice(1,1)}if(1===((e=o[0])[0]<<16)+(e[1]<<8)+e[2]){if((r=(e[4]<<8)+e[5])&&r>t.size-6)return null;var u=e[7];192&u&&(a=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&u?a-(n=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2)>54e5&&(c.b.warn(Math.round((a-n)/9e4)+"s delta between PTS and DTS, align them"),a=n):n=a);var d=(i=e[8])+9;if(t.size<=d)return null;t.size-=d;for(var h=new Uint8Array(t.size),f=0,v=o.length;fg){d-=g;continue}e=e.subarray(d),g-=d,d=0}h.set(e,s),s+=g}return r&&(r-=i+3),{data:h,pts:a,dts:n,len:r}}return null}function W(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){var r=e.samples,i=r.length;if(!i)return void e.dropped++;var a=r[i-1];t.pts=a.pts,t.dts=a.dts}e.samples.push(t)}t.debug.length&&c.b.log(t.pts+"/"+t.dts+":"+t.debug)}function Y(t,e){var r=t.length;if(r>0){if(e.pts>=t[r-1].pts)t.push(e);else for(var i=r-1;i>=0;i--)if(e.pts1?r-1:0),a=1;a>24&255,o[1]=e>>16&255,o[2]=e>>8&255,o[3]=255&e,o.set(t,4),n=0,e=8;n>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,85,196,0,0]))},t.mdia=function(e){return t.box(t.types.mdia,t.mdhd(e.timescale,e.duration),t.hdlr(e.type),t.minf(e))},t.mfhd=function(e){return t.box(t.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))},t.minf=function(e){return"audio"===e.type?t.box(t.types.minf,t.box(t.types.smhd,t.SMHD),t.DINF,t.stbl(e)):t.box(t.types.minf,t.box(t.types.vmhd,t.VMHD),t.DINF,t.stbl(e))},t.moof=function(e,r,i){return t.box(t.types.moof,t.mfhd(e),t.traf(i,r))},t.moov=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trak(e[r]);return t.box.apply(null,[t.types.moov,t.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(t.mvex(e)))},t.mvex=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trex(e[r]);return t.box.apply(null,[t.types.mvex].concat(i))},t.mvhd=function(e,r){r*=e;var i=Math.floor(r/(J+1)),a=Math.floor(r%(J+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return t.box(t.types.mvhd,n)},t.sdtp=function(e){var r,i,a=e.samples||[],n=new Uint8Array(4+a.length);for(r=0;r>>8&255),n.push(255&a),n=n.concat(Array.prototype.slice.call(i));for(r=0;r>>8&255),s.push(255&a),s=s.concat(Array.prototype.slice.call(i));var o=t.box(t.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|e.sps.length].concat(n).concat([e.pps.length]).concat(s))),l=e.width,u=e.height,d=e.pixelRatio[0],h=e.pixelRatio[1];return t.box(t.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,t.box(t.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),t.box(t.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))},t.esds=function(t){var e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))},t.mp4a=function(e){var r=e.samplerate;return t.box(t.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),t.box(t.types.esds,t.esds(e)))},t.mp3=function(e){var r=e.samplerate;return t.box(t.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))},t.stsd=function(e){return"audio"===e.type?e.isAAC||"mp3"!==e.codec?t.box(t.types.stsd,t.STSD,t.mp4a(e)):t.box(t.types.stsd,t.STSD,t.mp3(e)):t.box(t.types.stsd,t.STSD,t.avc1(e))},t.tkhd=function(e){var r=e.id,i=e.duration*e.timescale,a=e.width,n=e.height,s=Math.floor(i/(J+1)),o=Math.floor(i%(J+1));return t.box(t.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,a>>8&255,255&a,0,0,n>>8&255,255&n,0,0]))},t.traf=function(e,r){var i=t.sdtp(e),a=e.id,n=Math.floor(r/(J+1)),s=Math.floor(r%(J+1));return t.box(t.types.traf,t.box(t.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a])),t.box(t.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,s>>24,s>>16&255,s>>8&255,255&s])),t.trun(e,i.length+16+20+8+16+8+8),i)},t.trak=function(e){return e.duration=e.duration||4294967295,t.box(t.types.trak,t.tkhd(e),t.mdia(e))},t.trex=function(e){var r=e.id;return t.box(t.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},t.trun=function(e,r){var i,a,n,s,o,l,u=e.samples||[],d=u.length,h=12+16*d,f=new Uint8Array(h);for(r+=8+h,f.set([0,0,15,1,d>>>24&255,d>>>16&255,d>>>8&255,255&d,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i>>24&255,n>>>16&255,n>>>8&255,255&n,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return t.box(t.types.trun,f)},t.initSegment=function(e){t.types||t.init();var r=t.moov(e),i=new Uint8Array(t.FTYP.byteLength+r.byteLength);return i.set(t.FTYP),i.set(r,t.FTYP.byteLength),i},t}();tt.types=void 0,tt.HDLR_TYPES=void 0,tt.STTS=void 0,tt.STSC=void 0,tt.STCO=void 0,tt.STSZ=void 0,tt.VMHD=void 0,tt.SMHD=void 0,tt.STSD=void 0,tt.FTYP=void 0,tt.DINF=void 0;var et=tt,rt=r(4);function it(t,e,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var a=t*e*r;return i?Math.round(a):a}function at(t,e){return void 0===e&&(e=!1),it(t,1e3,1/9e4,e)}function nt(){return(nt=Object.assign||function(t){for(var e=1;e0?t:r.pts}),t[0].pts);return e&&c.b.debug("PTS rollover detected"),r},e.remux=function(t,e,r,i,a,n,s,o){var l,u,d,h,f,v,g=a,p=a,m=t.pid>-1,y=e.pid>-1,b=e.samples.length,T=t.samples.length>0,E=b>1;if((!m||T)&&(!y||E)||this.ISGenerated||s){this.ISGenerated||(d=this.generateIS(t,e,a));var S=this.isVideoContiguous,L=-1;if(E&&(L=function(t){for(var e=0;e0){c.b.warn("[mp4-remuxer]: Dropped "+L+" out of "+b+" video samples due to a missing keyframe");var A=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(L),e.dropped+=L,p+=(e.samples[0].pts-A)/(e.timescale||9e4)}else-1===L&&(c.b.warn("[mp4-remuxer]: No keyframe found out of "+b+" video samples"),v=!1);if(this.ISGenerated){if(T&&E){var R=this.getVideoStartPts(e.samples),D=(dt(t.samples[0].pts,R)-R)/e.inputTimeScale;g+=Math.max(0,D),p+=Math.max(0,-D)}if(T){if(t.samplerate||(c.b.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(t,e,a)),u=this.remuxAudio(t,g,this.isAudioContiguous,n,y||E||o===rt.b.AUDIO?p:void 0),E){var _=u?u.endPTS-u.startPTS:0;e.inputTimeScale||(c.b.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(t,e,a)),l=this.remuxVideo(e,p,S,_)}}else E&&(l=this.remuxVideo(e,p,S,0));l&&(l.firstKeyFrame=L,l.independent=-1!==L)}}return this.ISGenerated&&(r.samples.length&&(f=this.remuxID3(r,a)),i.samples.length&&(h=this.remuxText(i,a))),{audio:u,video:l,initSegment:d,independent:v,text:h,id3:f}},e.generateIS=function(t,e,r){var i,a,n,o=t.samples,l=e.samples,u=this.typeSupported,d={},h=!Object(s.a)(this._initPTS),f="audio/mp4";if(h&&(i=a=1/0),t.config&&o.length&&(t.timescale=t.samplerate,t.isAAC||(u.mpeg?(f="audio/mpeg",t.codec=""):u.mp3&&(t.codec="mp3")),d.audio={id:"audio",container:f,codec:t.codec,initSegment:!t.isAAC&&u.mpeg?new Uint8Array(0):et.initSegment([t]),metadata:{channelCount:t.channelCount}},h&&(n=t.inputTimeScale,i=a=o[0].pts-Math.round(n*r))),e.sps&&e.pps&&l.length&&(e.timescale=e.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:et.initSegment([e]),metadata:{width:e.width,height:e.height}},h)){n=e.inputTimeScale;var c=this.getVideoStartPts(l),v=Math.round(n*r);a=Math.min(a,dt(l[0].dts,c)-v),i=Math.min(i,c-v)}if(Object.keys(d).length)return this.ISGenerated=!0,h&&(this._initPTS=i,this._initDTS=a),{tracks:d,initPTS:i,timescale:n}},e.remuxVideo=function(t,e,r,n){var s,o,l,u=t.inputTimeScale,d=t.samples,h=[],f=d.length,v=this._initPTS,g=this.nextAvcDts,p=8,m=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,b=0,T=!1;r&&null!==g||(g=e*u-(d[0].pts-dt(d[0].dts,d[0].pts)));for(var E=0;ES.pts){b=Math.max(Math.min(b,S.pts-S.dts),-18e3)}S.dts0?E-1:E].dts&&(T=!0)}T&&d.sort((function(t,e){var r=t.dts-e.dts,i=t.pts-e.pts;return r||i})),o=d[0].dts,l=d[d.length-1].dts;var L=Math.round((l-o)/(f-1));if(b<0){if(b<-2*L){c.b.warn("PTS < DTS detected in video samples, offsetting DTS from PTS by "+at(-L,!0)+" ms");for(var A=b,R=0;RL;if(k||_<-1){k?c.b.warn("AVC: "+at(_,!0)+" ms ("+_+"dts) hole between fragments detected, filling it"):c.b.warn("AVC: "+at(-_,!0)+" ms ("+_+"dts) overlapping between fragments detected"),o=g;var x=d[0].pts-_;d[0].dts=o,d[0].pts=x,c.b.log("Video: First PTS/DTS adjusted: "+at(x,!0)+"/"+at(o,!0)+", delta: "+at(_,!0)+" ms")}}lt&&(o=Math.max(0,o));for(var C=0,w=0,O=0;O0?j-1:j].dts;if(Q.stretchShortVideoTrack&&null!==this.nextAudioPts){var Z=Math.floor(Q.maxBufferHole*u),J=(n?m+n*u:this.nextAudioPts)-H.pts;J>Z?((s=J-$)<0&&(s=$),c.b.log("[mp4-remuxer]: It is approximately "+J/90+" ms to the next segment; using duration "+s/90+" ms for the last video frame.")):s=$}else s=$}var tt=Math.round(H.pts-H.dts);h.push(new ht(H.key,s,V,tt))}if(h.length&&st&&st<70){var rt=h[0].flags;rt.dependsOn=2,rt.isNonSync=0}this.nextAvcDts=g=l+s,this.isVideoContiguous=!0;var it={data1:et.moof(t.sequenceNumber++,o,nt({},t,{samples:h})),data2:B,startPTS:m/u,endPTS:(y+s)/u,startDTS:o/u,endDTS:g/u,type:"video",hasAudio:!1,hasVideo:!0,nb:h.length,dropped:t.dropped};return t.samples=[],t.dropped=0,it},e.remuxAudio=function(t,e,r,n,s){var o=t.inputTimeScale,l=o/(t.samplerate?t.samplerate:o),u=t.isAAC?1024:1152,d=u*l,h=this._initPTS,f=!t.isAAC&&this.typeSupported.mpeg,v=[],g=t.samples,p=f?0:8,m=this.nextAudioPts||-1,y=e*o;if(this.isAudioContiguous=r=r||g.length&&m>0&&(n&&Math.abs(y-m)<9e3||Math.abs(dt(g[0].pts-h,y)-m)<20*d),g.forEach((function(t){t.pts=dt(t.pts-h,y)})),!r||m<0){if(!(g=g.filter((function(t){return t.pts>=0}))).length)return;m=0===s?0:n?Math.max(0,y):g[0].pts}if(t.isAAC)for(var b=void 0!==s,T=this.config.maxAudioFramesDrift,E=0,S=m;E=T*d&&D<1e4&&b){var _=Math.round(R/d);(S=A-_*d)<0&&(_--,S+=d),0===E&&(this.nextAudioPts=m=S),c.b.warn("[mp4-remuxer]: Injecting "+_+" audio frame @ "+(S/o).toFixed(3)+"s due to "+Math.round(1e3*R/o)+" ms gap.");for(var k=0;k<_;k++){var x=Math.max(S,0),C=Z.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);C||(c.b.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),C=L.unit.subarray()),g.splice(E,0,{unit:C,pts:x}),S+=d,E++}}L.pts=S,S+=d}for(var w,O=null,I=null,P=0,F=g.length;F--;)P+=g[F].unit.byteLength;for(var M=0,N=g.length;M0))return;P+=p;try{w=new Uint8Array(P)}catch(t){return void this.observer.emit(i.a.ERROR,i.a.ERROR,{type:a.b.MUX_ERROR,details:a.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:P,reason:"fail allocating audio mdat "+P})}f||(new DataView(w.buffer).setUint32(0,P),w.set(et.types.mdat,4))}w.set(U,p);var j=U.byteLength;p+=j,v.push(new ht(!0,u,j,0)),I=G}var H=v.length;if(H){var K=v[v.length-1];this.nextAudioPts=m=I+l*K.duration;var V=f?new Uint8Array(0):et.moof(t.sequenceNumber++,O/l,nt({},t,{samples:v}));t.samples=[];var W=O/o,Y=m/o,X={data1:V,data2:w,startPTS:W,endPTS:Y,startDTS:W,endDTS:Y,type:"audio",hasAudio:!0,hasVideo:!1,nb:H};return this.isAudioContiguous=!0,X}},e.remuxEmptyAudio=function(t,e,r,i){var a=t.inputTimeScale,n=a/(t.samplerate?t.samplerate:a),s=this.nextAudioPts,o=(null!==s?s:i.startDTS*a)+this._initDTS,l=i.endDTS*a+this._initDTS,u=1024*n,d=Math.ceil((l-o)/u),h=Z.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(c.b.warn("[mp4-remuxer]: remux empty Audio"),h){for(var f=[],v=0;v4294967296;)t+=r;return t}var ht=function(t,e,r,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=r,this.cts=i,this.flags=new ft(t)},ft=function(t){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=t?2:1,this.isNonSync=t?0:1},ct=r(5),vt=function(){function t(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=void 0,this.initTracks=void 0,this.lastEndDTS=null}var e=t.prototype;return e.destroy=function(){},e.resetTimeStamp=function(t){this.initPTS=t,this.lastEndDTS=null},e.resetNextTimestamp=function(){this.lastEndDTS=null},e.resetInitSegment=function(t,e,r){this.audioCodec=e,this.videoCodec=r,this.generateInitSegment(t),this.emitInitSegment=!0},e.generateInitSegment=function(t){var e=this.audioCodec,r=this.videoCodec;if(!t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var i=this.initData=Object(l.f)(t);e||(e=pt(i.audio,ct.a.AUDIO)),r||(r=pt(i.video,ct.a.VIDEO));var a={};i.audio&&i.video?a.audiovideo={container:"video/mp4",codec:e+","+r,initSegment:t,id:"main"}:i.audio?a.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:i.video?a.video={container:"video/mp4",codec:r,initSegment:t,id:"main"}:c.b.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=a},e.remux=function(t,e,r,i,a){var n=this.initPTS,o=this.lastEndDTS,u={audio:void 0,video:void 0,text:i,id3:r,initSegment:void 0};Object(s.a)(o)||(o=this.lastEndDTS=a||0);var d=e.samples;if(!d||!d.length)return u;var h={initPTS:void 0,timescale:1},f=this.initData;if(f&&f.length||(this.generateInitSegment(d),f=this.initData),!f||!f.length)return c.b.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1),Object(s.a)(n)||(this.initPTS=h.initPTS=n=gt(f,d,o));var v=Object(l.c)(d,f),g=o,p=v+g;Object(l.e)(f,d,n),v>0?this.lastEndDTS=p:(c.b.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var m=!!f.audio,y=!!f.video,b="";m&&(b+="audio"),y&&(b+="video");var T={data1:d,startPTS:g,startDTS:g,endPTS:p,endDTS:p,type:b,hasAudio:m,hasVideo:y,nb:1,dropped:0};return u.audio="audio"===T.type?T:void 0,u.video="audio"!==T.type?T:void 0,u.text=i,u.id3=r,u.initSegment=h,u},t}(),gt=function(t,e,r){return Object(l.d)(t,e)-r};function pt(t,e){var r=null==t?void 0:t.codec;return r&&r.length>4?r:"hvc1"===r?"hvc1.1.c.L120.90":"av01"===r?"av01.0.04M.08":"avc1"===r||e===ct.a.VIDEO?"avc1.42e01e":"mp4a.40.5"}var mt,yt=vt,bt=r(16);try{mt=self.performance.now.bind(self.performance)}catch(t){c.b.debug("Unable to use Performance API on this environment"),mt=self.Date.now}var Tt=[{demux:q,remux:ut},{demux:D,remux:yt},{demux:A,remux:ut},{demux:$,remux:ut}],Et=1024;Tt.forEach((function(t){var e=t.demux;Et=Math.max(Et,e.minProbeByteLength)}));var St=function(){function t(t,e,r,i,a){this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.cache=new bt.a,this.observer=t,this.typeSupported=e,this.config=r,this.vendor=i,this.id=a}var e=t.prototype;return e.configure=function(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()},e.push=function(t,e,r,i){var a=this,n=r.transmuxing;n.executeStart=mt();var s=new Uint8Array(t),o=this.cache,u=this.config,d=this.currentTransmuxState,h=this.transmuxConfig;i&&(this.currentTransmuxState=i);var f=function(t,e){var r=null;t.byteLength>0&&null!=e&&null!=e.key&&null!==e.iv&&null!=e.method&&(r=e);return r}(s,e);if(f&&"AES-128"===f.method){var c=this.getDecrypter();if(!u.enableSoftwareAES)return this.decryptionPromise=c.webCryptoDecrypt(s,f.key.buffer,f.iv.buffer).then((function(t){var e=a.push(t,null,r);return a.decryptionPromise=null,e})),this.decryptionPromise;var v=c.softwareDecrypt(s,f.key.buffer,f.iv.buffer);if(!v)return n.executeEnd=mt(),Lt(r);s=new Uint8Array(v)}var g=i||d,p=g.contiguous,m=g.discontinuity,y=g.trackSwitch,b=g.accurateTimeOffset,T=g.timeOffset,E=g.initSegmentChange,S=h.audioCodec,L=h.videoCodec,A=h.defaultInitPts,R=h.duration,D=h.initSegmentData;if((m||y||E)&&this.resetInitSegment(D,S,L,R),(m||E)&&this.resetInitialTimestamp(A),p||this.resetContiguity(),this.needsProbing(s,m,y)){if(o.dataLength){var _=o.flush();s=Object(l.a)(_,s)}this.configureTransmuxer(s,h)}var k=this.transmux(s,f,T,b,r),x=this.currentTransmuxState;return x.contiguous=!0,x.discontinuity=!1,x.trackSwitch=!1,n.executeEnd=mt(),k},e.flush=function(t){var e=this,r=t.transmuxing;r.executeStart=mt();var n=this.decrypter,s=this.cache,o=this.currentTransmuxState,l=this.decryptionPromise;if(l)return l.then((function(){return e.flush(t)}));var u=[],d=o.timeOffset;if(n){var h=n.flush();h&&u.push(this.push(h,null,t))}var f=s.dataLength;s.reset();var c=this.demuxer,v=this.remuxer;if(!c||!v)return f>=Et&&this.observer.emit(i.a.ERROR,i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"}),r.executeEnd=mt(),[Lt(t)];var g=c.flush(d);return At(g)?g.then((function(r){return e.flushRemux(u,r,t),u})):(this.flushRemux(u,g,t),u)},e.flushRemux=function(t,e,r){var i=e.audioTrack,a=e.avcTrack,n=e.id3Track,s=e.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;c.b.log("[transmuxer.ts]: Flushed fragment "+r.sn+(r.part>-1?" p: "+r.part:"")+" of level "+r.level);var d=this.remuxer.remux(i,a,n,s,u,l,!0,this.id);t.push({remuxResult:d,chunkMeta:r}),r.transmuxing.executeEnd=mt()},e.resetInitialTimestamp=function(t){var e=this.demuxer,r=this.remuxer;e&&r&&(e.resetTimeStamp(t),r.resetTimeStamp(t))},e.resetContiguity=function(){var t=this.demuxer,e=this.remuxer;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())},e.resetInitSegment=function(t,e,r,i){var a=this.demuxer,n=this.remuxer;a&&n&&(a.resetInitSegment(e,r,i),n.resetInitSegment(t,e,r))},e.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},e.transmux=function(t,e,r,i,a){return e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,r,i,a):this.transmuxUnencrypted(t,r,i,a)},e.transmuxUnencrypted=function(t,e,r,i){var a=this.demuxer.demux(t,e,!1,!this.config.progressive),n=a.audioTrack,s=a.avcTrack,o=a.id3Track,l=a.textTrack;return{remuxResult:this.remuxer.remux(n,s,o,l,e,r,!1,this.id),chunkMeta:i}},e.transmuxSampleAes=function(t,e,r,i,a){var n=this;return this.demuxer.demuxSampleAes(t,e,r).then((function(t){return{remuxResult:n.remuxer.remux(t.audioTrack,t.avcTrack,t.id3Track,t.textTrack,r,i,!1,n.id),chunkMeta:a}}))},e.configureTransmuxer=function(t,e){for(var r,i=this.config,a=this.observer,n=this.typeSupported,s=this.vendor,o=e.audioCodec,l=e.defaultInitPts,u=e.duration,d=e.initSegmentData,h=e.videoCodec,f=0,v=Tt.length;f>>8^255&p^99,t[c]=p,e[p]=c;var m=f[c],y=f[m],b=f[y],T=257*f[p]^16843008*p;i[c]=T<<24|T>>>8,a[c]=T<<16|T>>>16,n[c]=T<<8|T>>>24,s[c]=T,T=16843009*b^65537*y^257*m^16843008*c,l[p]=T<<24|T>>>8,u[p]=T<<16|T>>>16,d[p]=T<<8|T>>>24,h[p]=T,c?(c=m^f[f[f[b^m]]],v^=f[f[v]]):c=v=1}},e.expandKey=function(t){for(var e=this.uint8ArrayToUint32Array_(t),r=!0,i=0;i0}),!1)}t.exports=function(t,e){e=e||{};var a={main:r.m},o=e.all?{main:Object.keys(a.main)}:function(t,e){for(var r={main:[e]},i={main:[]},a={main:{}};s(r);)for(var o=Object.keys(r),l=0;lt.endSN||e>0||0===e&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay},e=t,(r=[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&Object(a.a)(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var t=this.driftEndTime-this.driftStartTime;return t>0?1e3*(this.driftEnd-this.driftStart)/t:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){var t;return null!==(t=this.fragments)&&void 0!==t&&t.length?this.fragments[this.fragments.length-1].end:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].index:-1}},{key:"lastPartSn",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}])&&d(e.prototype,r),i&&d(e,i),t}(),f=r(15),c=/^(\d+)x(\d+)$/,v=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,g=function(){function t(e){for(var r in"string"==typeof e&&(e=t.parseAttrList(e)),e)e.hasOwnProperty(r)&&(this[r]=e[r])}var e=t.prototype;return e.decimalInteger=function(t){var e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e},e.hexadecimalInteger=function(t){if(this[t]){var e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;for(var r=new Uint8Array(e.length/2),i=0;iNumber.MAX_SAFE_INTEGER?1/0:e},e.decimalFloatingPoint=function(t){return parseFloat(this[t])},e.optionalFloat=function(t,e){var r=this[t];return r?parseFloat(r):e},e.enumeratedString=function(t){return this[t]},e.bool=function(t){return"YES"===this[t]},e.decimalResolution=function(t){var e=c.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}},t.parseAttrList=function(t){var e,r={};for(v.lastIndex=0;null!==(e=v.exec(t));){var i=e[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[e[1]]=i}return r},t}(),p={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dvav:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}};function m(t,e){return MediaSource.isTypeSupported((e||"video")+'/mp4;codecs="'+t+'"')}var y=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-SESSION-DATA:([^\r\n]*)[\r\n]+/g,b=/#EXT-X-MEDIA:(.*)/g,T=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),E=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(PLAYLIST-TYPE):(.+)/.source,/#EXT-X-(MEDIA-SEQUENCE): *(\d+)/.source,/#EXT-X-(SKIP):(.+)/.source,/#EXT-X-(TARGETDURATION): *(\d+)/.source,/#EXT-X-(KEY):(.+)/.source,/#EXT-X-(START):(.+)/.source,/#EXT-X-(ENDLIST)/.source,/#EXT-X-(DISCONTINUITY-SEQ)UENCE: *(\d+)/.source,/#EXT-X-(DIS)CONTINUITY/.source,/#EXT-X-(VERSION):(\d+)/.source,/#EXT-X-(MAP):(.+)/.source,/#EXT-X-(SERVER-CONTROL):(.+)/.source,/#EXT-X-(PART-INF):(.+)/.source,/#EXT-X-(GAP)/.source,/#EXT-X-(BITRATE):\s*(\d+)/.source,/#EXT-X-(PART):(.+)/.source,/#EXT-X-(PRELOAD-HINT):(.+)/.source,/#EXT-X-(RENDITION-REPORT):(.+)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),S=/\.(mp4|m4s|m4v|m4a)$/i;var L=function(){function t(){}return t.findGroup=function(t,e){for(var r=0;r2){var r=e.shift()+".";return r+=parseInt(e.shift()).toString(16),r+=("000"+parseInt(e.shift()).toString(16)).substr(-4)}return t},t.resolve=function(t,e){return i.buildAbsoluteURL(e,t,{alwaysNormalize:!0})},t.parseMasterPlaylist=function(e,r){var i,a=[],n={},s=!1;for(y.lastIndex=0;null!=(i=y.exec(e));)if(i[1]){var o=new g(i[1]),l={attrs:o,bitrate:o.decimalInteger("AVERAGE-BANDWIDTH")||o.decimalInteger("BANDWIDTH"),name:o.NAME,url:t.resolve(i[2],r)},u=o.decimalResolution("RESOLUTION");u&&(l.width=u.width,l.height=u.height),A((o.CODECS||"").split(/[ ,]+/).filter((function(t){return t})),l),l.videoCodec&&-1!==l.videoCodec.indexOf("avc1")&&(l.videoCodec=t.convertAVC1ToAVCOTI(l.videoCodec)),a.push(l)}else if(i[3]){var d=new g(i[3]);d["DATA-ID"]&&(s=!0,n[d["DATA-ID"]]=d)}return{levels:a,sessionData:s?n:null}},t.parseMasterPlaylistMedia=function(e,r,i,a){var n;void 0===a&&(a=[]);var s=[],o=0;for(b.lastIndex=0;null!==(n=b.exec(e));){var l=new g(n[1]);if(l.TYPE===i){var u={attrs:l,bitrate:0,id:o++,groupId:l["GROUP-ID"],instreamId:l["INSTREAM-ID"],name:l.NAME||l.LANGUAGE||"",type:i,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:l.LANGUAGE,url:l.URI?t.resolve(l.URI,r):""};if(a.length){var d=t.findGroup(a,u.groupId)||a[0];R(u,d,"audioCodec"),R(u,d,"textCodec")}s.push(u)}}return s},t.parseLevelPlaylist=function(t,e,r,n,s){var l,d,c,v=new h(e),p=v.fragments,m=null,y=0,b=0,L=0,A=0,R=null,_=new u.b(n,e),k=-1,x=!1;for(T.lastIndex=0,v.m3u8=t;null!==(l=T.exec(t));){x&&(x=!1,(_=new u.b(n,e)).start=L,_.sn=y,_.cc=A,_.level=r,m&&(_.initSegment=m,_.rawProgramDateTime=m.rawProgramDateTime));var C=l[1];if(C){_.duration=parseFloat(C);var w=(" "+l[2]).slice(1);_.title=w||null,_.tagList.push(w?["INF",C,w]:["INF",C])}else if(l[3])Object(a.a)(_.duration)&&(_.start=L,c&&(_.levelkey=c),_.sn=y,_.level=r,_.cc=A,_.urlId=s,p.push(_),_.relurl=(" "+l[3]).slice(1),D(_,R),R=_,L+=_.duration,y++,b=0,x=!0);else if(l[4]){var O=(" "+l[4]).slice(1);R?_.setByteRange(O,R):_.setByteRange(O)}else if(l[5])_.rawProgramDateTime=(" "+l[5]).slice(1),_.tagList.push(["PROGRAM-DATE-TIME",_.rawProgramDateTime]),-1===k&&(k=p.length);else{if(!(l=l[0].match(E))){o.b.warn("No matches on slow regex match for level playlist!");continue}for(d=1;d-1){o.b.warn("Keyformat "+X+" is not supported from the manifest");continue}if("identity"!==X)continue;H&&(c=f.a.fromURL(e,K),K&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(H)>=0&&(c.method=H,c.keyFormat=X,Y&&(c.keyID=Y),W&&(c.keyFormatVersions=W),c.iv=V));break;case"START":var q=new g(P).decimalFloatingPoint("TIME-OFFSET");Object(a.a)(q)&&(v.startTimeOffset=q);break;case"MAP":var z=new g(P);_.relurl=z.URI,z.BYTERANGE&&_.setByteRange(z.BYTERANGE),_.level=r,_.sn="initSegment",c&&(_.levelkey=c),_.initSegment=null,m=_,x=!0;break;case"SERVER-CONTROL":var Q=new g(P);v.canBlockReload=Q.bool("CAN-BLOCK-RELOAD"),v.canSkipUntil=Q.optionalFloat("CAN-SKIP-UNTIL",0),v.canSkipDateRanges=v.canSkipUntil>0&&Q.bool("CAN-SKIP-DATERANGES"),v.partHoldBack=Q.optionalFloat("PART-HOLD-BACK",0),v.holdBack=Q.optionalFloat("HOLD-BACK",0);break;case"PART-INF":var $=new g(P);v.partTarget=$.decimalFloatingPoint("PART-TARGET");break;case"PART":var Z=v.partList;Z||(Z=v.partList=[]);var J=b>0?Z[Z.length-1]:void 0,tt=b++,et=new u.c(new g(P),_,e,tt,J);Z.push(et),_.duration+=et.duration;break;case"PRELOAD-HINT":var rt=new g(P);v.preloadHint=rt;break;case"RENDITION-REPORT":var it=new g(P);v.renditionReports=v.renditionReports||[],v.renditionReports.push(it);break;default:o.b.warn("line parsed but not handled: "+l)}}}R&&!R.relurl?(p.pop(),L-=R.duration,v.partList&&(v.fragmentHint=R)):v.partList&&(D(_,R),_.cc=A,v.fragmentHint=_);var at=p.length,nt=p[0],st=p[at-1];if((L+=v.skippedSegments*v.targetduration)>0&&at&&st){v.averagetargetduration=L/at;var ot=st.sn;v.endSN="initSegment"!==ot?ot:0,nt&&(v.startCC=nt.cc,nt.initSegment||v.fragments.every((function(t){return t.relurl&&(e=t.relurl,S.test(null!=(r=null===(a=i.parseURL(e))||void 0===a?void 0:a.path)?r:""));var e,r,a}))&&(o.b.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),(_=new u.b(n,e)).relurl=st.relurl,_.level=r,_.sn="initSegment",nt.initSegment=_,v.needSidxRanges=!0))}else v.endSN=0,v.startCC=0;return v.fragmentHint&&(L+=v.fragmentHint.duration),v.totalduration=L,v.endCC=A,k>0&&function(t,e){for(var r=t[e],i=e;i--;){var a=t[i];if(!a)return;a.programDateTime=r.programDateTime-1e3*a.duration,r=a}}(p,k),v},t}();function A(t,e){["video","audio","text"].forEach((function(r){var i=t.filter((function(t){return function(t,e){var r=p[e];return!!r&&!0===r[t.slice(0,4)]}(t,r)}));if(i.length){var a=i.filter((function(t){return 0===t.lastIndexOf("avc1",0)||0===t.lastIndexOf("mp4a",0)}));e[r+"Codec"]=a.length>0?a[0]:i[0],t=t.filter((function(t){return-1===i.indexOf(t)}))}})),e.unknownCodecs=t}function R(t,e,r){var i=e[r];i&&(t[r]=i)}function D(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),Object(a.a)(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}var _=r(4);function k(t,e){var r=t.url;return void 0!==r&&0!==r.indexOf("data:")||(r=e.url),r}var x=function(){function t(t){this.hls=void 0,this.loaders=Object.create(null),this.hls=t,this.registerListeners()}var e=t.prototype;return e.registerListeners=function(){var t=this.hls;t.on(n.a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.a.LEVEL_LOADING,this.onLevelLoading,this),t.on(n.a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(n.a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.unregisterListeners=function(){var t=this.hls;t.off(n.a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.a.LEVEL_LOADING,this.onLevelLoading,this),t.off(n.a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(n.a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.createInternalLoader=function(t){var e=this.hls.config,r=e.pLoader,i=e.loader,a=new(r||i)(e);return t.loader=a,this.loaders[t.type]=a,a},e.getInternalLoader=function(t){return this.loaders[t.type]},e.resetInternalLoader=function(t){this.loaders[t]&&delete this.loaders[t]},e.destroyInternalLoaders=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}},e.destroy=function(){this.unregisterListeners(),this.destroyInternalLoaders()},e.onManifestLoading=function(t,e){var r=e.url;this.load({id:null,groupId:null,level:0,responseType:"text",type:_.a.MANIFEST,url:r,deliveryDirectives:null})},e.onLevelLoading=function(t,e){var r=e.id,i=e.level,a=e.url,n=e.deliveryDirectives;this.load({id:r,groupId:null,level:i,responseType:"text",type:_.a.LEVEL,url:a,deliveryDirectives:n})},e.onAudioTrackLoading=function(t,e){var r=e.id,i=e.groupId,a=e.url,n=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:_.a.AUDIO_TRACK,url:a,deliveryDirectives:n})},e.onSubtitleTrackLoading=function(t,e){var r=e.id,i=e.groupId,a=e.url,n=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:_.a.SUBTITLE_TRACK,url:a,deliveryDirectives:n})},e.load=function(t){var e,r,i,a,n,s,l=this.hls.config,u=this.getInternalLoader(t);if(u){var d=u.context;if(d&&d.url===t.url)return void o.b.trace("[playlist-loader]: playlist request ongoing");o.b.log("[playlist-loader]: aborting previous loader for type: "+t.type),u.abort()}switch(t.type){case _.a.MANIFEST:r=l.manifestLoadingMaxRetry,i=l.manifestLoadingTimeOut,a=l.manifestLoadingRetryDelay,n=l.manifestLoadingMaxRetryTimeout;break;case _.a.LEVEL:case _.a.AUDIO_TRACK:case _.a.SUBTITLE_TRACK:r=0,i=l.levelLoadingTimeOut;break;default:r=l.levelLoadingMaxRetry,i=l.levelLoadingTimeOut,a=l.levelLoadingRetryDelay,n=l.levelLoadingMaxRetryTimeout}if((u=this.createInternalLoader(t),null!==(e=t.deliveryDirectives)&&void 0!==e&&e.part)&&(t.type===_.a.LEVEL&&null!==t.level?s=this.hls.levels[t.level].details:t.type===_.a.AUDIO_TRACK&&null!==t.id?s=this.hls.audioTracks[t.id].details:t.type===_.a.SUBTITLE_TRACK&&null!==t.id&&(s=this.hls.subtitleTracks[t.id].details),s)){var h=s.partTarget,f=s.targetduration;h&&f&&(i=Math.min(1e3*Math.max(3*h,.8*f),i))}var c={timeout:i,maxRetry:r,retryDelay:a,maxRetryDelay:n,highWaterMark:0},v={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};u.load(t,c,v)},e.loadsuccess=function(t,e,r,i){if(void 0===i&&(i=null),r.isSidxRequest)return this.handleSidxRequest(t,r),void this.handlePlaylistLoaded(t,e,r,i);this.resetInternalLoader(r.type);var a=t.data;0===a.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),a.indexOf("#EXTINF:")>0||a.indexOf("#EXT-X-TARGETDURATION:")>0?this.handleTrackOrLevelPlaylist(t,e,r,i):this.handleMasterPlaylist(t,e,r,i)):this.handleManifestParsingError(t,r,"no EXTM3U delimiter",i)},e.loaderror=function(t,e,r){void 0===r&&(r=null),this.handleNetworkError(e,r,!1,t)},e.loadtimeout=function(t,e,r){void 0===r&&(r=null),this.handleNetworkError(e,r,!0)},e.handleMasterPlaylist=function(t,e,r,i){var a=this.hls,s=t.data,l=k(t,r),u=L.parseMasterPlaylist(s,l),d=u.levels,h=u.sessionData;if(d.length){var f=d.map((function(t){return{id:t.attrs.AUDIO,audioCodec:t.audioCodec}})),c=d.map((function(t){return{id:t.attrs.SUBTITLES,textCodec:t.textCodec}})),v=L.parseMasterPlaylistMedia(s,l,"AUDIO",f),p=L.parseMasterPlaylistMedia(s,l,"SUBTITLES",c),m=L.parseMasterPlaylistMedia(s,l,"CLOSED-CAPTIONS");if(v.length)v.some((function(t){return!t.url}))||!d[0].audioCodec||d[0].attrs.AUDIO||(o.b.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),v.unshift({type:"main",name:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new g({}),bitrate:0,url:""}));a.trigger(n.a.MANIFEST_LOADED,{levels:d,audioTracks:v,subtitles:p,captions:m,url:l,stats:e,networkDetails:i,sessionData:h})}else this.handleManifestParsingError(t,r,"no level found in manifest",i)},e.handleTrackOrLevelPlaylist=function(t,e,r,i){var o=this.hls,l=r.id,u=r.level,d=r.type,h=k(t,r),f=Object(a.a)(l)?l:0,c=Object(a.a)(u)?u:f,v=function(t){switch(t.type){case _.a.AUDIO_TRACK:return _.b.AUDIO;case _.a.SUBTITLE_TRACK:return _.b.SUBTITLE;default:return _.b.MAIN}}(r),p=L.parseLevelPlaylist(t.data,h,c,v,f);if(p.fragments.length){if(d===_.a.MANIFEST){var m={attrs:new g({}),bitrate:0,details:p,name:"",url:h};o.trigger(n.a.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:h,stats:e,networkDetails:i,sessionData:null})}if(e.parsing.end=performance.now(),p.needSidxRanges){var y,b=null===(y=p.fragments[0].initSegment)||void 0===y?void 0:y.url;this.load({url:b,isSidxRequest:!0,type:d,level:u,levelDetails:p,id:l,groupId:null,rangeStart:0,rangeEnd:2048,responseType:"arraybuffer",deliveryDirectives:null})}else r.levelDetails=p,this.handlePlaylistLoaded(t,e,r,i)}else o.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.LEVEL_EMPTY_ERROR,fatal:!1,url:h,reason:"no fragments found in level",level:"number"==typeof r.level?r.level:void 0})},e.handleSidxRequest=function(t,e){var r=Object(l.g)(new Uint8Array(t.data));if(r){var i=r.references,a=e.levelDetails;i.forEach((function(t,e){var i=t.info,n=a.fragments[e];0===n.byteRange.length&&n.setByteRange(String(1+i.end-i.start)+"@"+String(i.start)),n.initSegment&&n.initSegment.setByteRange(String(r.moovEndOffset)+"@0")}))}},e.handleManifestParsingError=function(t,e,r,i){this.hls.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.MANIFEST_PARSING_ERROR,fatal:e.type===_.a.MANIFEST,url:t.url,reason:r,response:t,context:e,networkDetails:i})},e.handleNetworkError=function(t,e,r,i){void 0===r&&(r=!1),o.b.warn("[playlist-loader]: A network "+(r?"timeout":"error")+" occurred while loading "+t.type+" level: "+t.level+" id: "+t.id+' group-id: "'+t.groupId+'"');var a=s.a.UNKNOWN,l=!1,u=this.getInternalLoader(t);switch(t.type){case _.a.MANIFEST:a=r?s.a.MANIFEST_LOAD_TIMEOUT:s.a.MANIFEST_LOAD_ERROR,l=!0;break;case _.a.LEVEL:a=r?s.a.LEVEL_LOAD_TIMEOUT:s.a.LEVEL_LOAD_ERROR,l=!1;break;case _.a.AUDIO_TRACK:a=r?s.a.AUDIO_TRACK_LOAD_TIMEOUT:s.a.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case _.a.SUBTITLE_TRACK:a=r?s.a.SUBTITLE_TRACK_LOAD_TIMEOUT:s.a.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(t.type);var d={type:s.b.NETWORK_ERROR,details:a,fatal:l,url:t.url,loader:u,context:t,networkDetails:e};i&&(d.response=i),this.hls.trigger(n.a.ERROR,d)},e.handlePlaylistLoaded=function(t,e,r,i){var a=r.type,s=r.level,o=r.id,l=r.groupId,u=r.loader,d=r.levelDetails,h=r.deliveryDirectives;if(null!=d&&d.targetduration){if(u)switch(d.live&&(u.getCacheAge&&(d.ageHeader=u.getCacheAge()||0),u.getCacheAge&&!isNaN(d.ageHeader)||(d.ageHeader=0)),a){case _.a.MANIFEST:case _.a.LEVEL:this.hls.trigger(n.a.LEVEL_LOADED,{details:d,level:s||0,id:o||0,stats:e,networkDetails:i,deliveryDirectives:h});break;case _.a.AUDIO_TRACK:this.hls.trigger(n.a.AUDIO_TRACK_LOADED,{details:d,id:o||0,groupId:l||"",stats:e,networkDetails:i,deliveryDirectives:h});break;case _.a.SUBTITLE_TRACK:this.hls.trigger(n.a.SUBTITLE_TRACK_LOADED,{details:d,id:o||0,groupId:l||"",stats:e,networkDetails:i,deliveryDirectives:h})}}else this.handleManifestParsingError(t,r,"invalid target duration",i)},t}(),C=function(){function t(t){this.hls=void 0,this.loaders={},this.decryptkey=null,this.decrypturl=null,this.hls=t,this._registerListeners()}var e=t.prototype;return e._registerListeners=function(){this.hls.on(n.a.KEY_LOADING,this.onKeyLoading,this)},e._unregisterListeners=function(){this.hls.off(n.a.KEY_LOADING,this.onKeyLoading)},e.destroy=function(){for(var t in this._unregisterListeners(),this.loaders){var e=this.loaders[t];e&&e.destroy()}this.loaders={}},e.onKeyLoading=function(t,e){var r=e.frag,i=r.type,a=this.loaders[i];if(r.decryptdata){var s=r.decryptdata.uri;if(s!==this.decrypturl||null===this.decryptkey){var l=this.hls.config;if(a&&(o.b.warn("abort previous key loader for type:"+i),a.abort()),!s)return void o.b.warn("key uri is falsy");var u=l.loader,d=r.loader=this.loaders[i]=new u(l);this.decrypturl=s,this.decryptkey=null;var h={url:s,frag:r,responseType:"arraybuffer"},f={timeout:l.fragLoadingTimeOut,maxRetry:0,retryDelay:l.fragLoadingRetryDelay,maxRetryDelay:l.fragLoadingMaxRetryTimeout,highWaterMark:0},c={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};d.load(h,f,c)}else this.decryptkey&&(r.decryptdata.key=this.decryptkey,this.hls.trigger(n.a.KEY_LOADED,{frag:r}))}else o.b.warn("Missing decryption data on fragment in onKeyLoading")},e.loadsuccess=function(t,e,r){var i=r.frag;i.decryptdata?(this.decryptkey=i.decryptdata.key=new Uint8Array(t.data),i.loader=null,delete this.loaders[i.type],this.hls.trigger(n.a.KEY_LOADED,{frag:i})):o.b.error("after key load, decryptdata unset")},e.loaderror=function(t,e){var r=e.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.KEY_LOAD_ERROR,fatal:!1,frag:r,response:t})},e.loadtimeout=function(t,e){var r=e.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},t}();function w(t,e){var r;try{r=new Event("addtrack")}catch(t){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=t,e.dispatchEvent(r)}function O(t,e,r){var i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&t.cues.length>0)for(var a=function(t,e,r){var i=[],a=function(t,e){if(et[r].endTime)return-1;var i=0,a=r;for(;i<=a;){var n=Math.floor((a+i)/2);if(et[n].startTime&&i-1)for(var n=a,s=t.length;n=e&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(t.cues,e,r),n=0;n.05&&this.forwardBufferLength>1){var u=Math.min(2,Math.max(1,n)),d=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;t.playbackRate=Math.min(u,Math.max(1,d))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}}}}},a.estimateLiveEdge=function(){var t=this.levelDetails;return null===t?null:t.edge+t.age},a.computeLatency=function(){var t=this.estimateLiveEdge();return null===t?null:t-this.currentTime},e=t,(r=[{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var t=this.config,e=this.levelDetails;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}},{key:"targetLatency",get:function(){var t=this.levelDetails;if(null===t)return null;var e=t.holdBack,r=t.partHoldBack,i=t.targetduration,a=this.config,n=a.liveSyncDuration,s=a.liveSyncDurationCount,o=a.lowLatencyMode,l=this.hls.userConfig,u=o&&r||e;(l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==n?n:s*i);var d=i;return u+Math.min(1*this.stallCount,d)}},{key:"liveSyncPosition",get:function(){var t=this.estimateLiveEdge(),e=this.targetLatency,r=this.levelDetails;if(null===t||null===e||null===r)return null;var i=r.edge,a=t-e-this.edgeStalled,n=i-r.totalduration,s=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(n,a),s)}},{key:"drift",get:function(){var t=this.levelDetails;return null===t?1:t.drift}},{key:"edgeStalled",get:function(){var t=this.levelDetails;if(null===t)return 0;var e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}},{key:"forwardBufferLength",get:function(){var t=this.media,e=this.levelDetails;if(!t||!e)return 0;var r=t.buffered.length;return r?t.buffered.end(r-1):e.edge-this.currentTime}}])&&F(e.prototype,r),i&&F(e,i),t}();function B(t,e){for(var r=0;rt.sn?(n=r-t.start,i=t):(n=t.start-r,i=e),i.duration!==n&&(i.duration=n)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration}else e.start=Math.max(t.start-e.duration,0)}function V(t,e,r,i,n,s){i-r<=0&&(o.b.warn("Fragment should have a positive duration",e),i=r+e.duration,s=n+e.duration);var l=r,u=i,d=e.startPTS,h=e.endPTS;if(Object(a.a)(d)){var f=Math.abs(d-r);Object(a.a)(e.deltaPTS)?e.deltaPTS=Math.max(f,e.deltaPTS):e.deltaPTS=f,l=Math.max(r,d),r=Math.min(r,d),n=Math.min(n,e.startDTS),u=Math.min(i,h),i=Math.max(i,h),s=Math.max(s,e.endDTS)}e.duration=i-r;var c=r-e.start;e.appendedPTS=i,e.start=e.startPTS=r,e.maxStartPTS=l,e.startDTS=n,e.endPTS=i,e.minEndPTS=u,e.endDTS=s;var v,g=e.sn;if(!t||gt.endSN)return 0;var p=g-t.startSN,m=t.fragments;for(m[p]=e,v=p;v>0;v--)K(m[v],m[v-1]);for(v=p;v=0;n--){var s=i[n].initSegment;if(s){r=s;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;var l,u=0;(function(t,e,r){for(var i=e.skippedSegments,a=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(i?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,s=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,u=a;u<=n;u++){var d=l[s+u],h=o[u];i&&!h&&u=i.length||function(t,e){if(e){for(var r=t.fragments,i=t.skippedSegments;ie.partTarget&&(l+=1)}if(Object(a.a)(o))return new U(o,Object(a.a)(l)?l:void 0,M.No)}}},e.loadPlaylist=function(t){},e.shouldLoadTrack=function(t){return this.canLoad&&t&&!!t.url&&(!t.details||t.details.live)},e.playlistLoaded=function(t,e,r){var i=this,a=e.details,n=e.stats,s=n.loading.end?Math.max(0,self.performance.now()-n.loading.end):0;if(a.advancedDateTime=Date.now()-s,a.live||null!=r&&r.live){if(a.reloaded(r),r&&this.log("live playlist "+t+" "+(a.advanced?"REFRESHED "+a.lastPartSn+"-"+a.lastPartIndex:"MISSED")),r&&a.fragments.length>0&&W(r,a),!this.canLoad||!a.live)return;var o,l=void 0,u=void 0;if(a.canBlockReload&&a.endSN&&a.advanced){var d=this.hls.config.lowLatencyMode,h=a.lastPartSn,f=a.endSN,c=a.lastPartIndex,v=h===f;-1!==c?(l=v?f+1:h,u=v?d?0:c:c+1):l=f+1;var g=a.age,p=g+a.ageHeader,m=Math.min(p-a.partTarget,1.5*a.targetduration);if(m>0){if(r&&m>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+m+" with playlist age: "+a.age),m=0;else{var y=Math.floor(m/a.targetduration);if(l+=y,void 0!==u)u+=Math.round(m%a.targetduration/a.partTarget);this.log("CDN Tune-in age: "+a.ageHeader+"s last advanced "+g.toFixed(2)+"s goal: "+m+" skip sn "+y+" to part "+u)}a.tuneInGoal=m}if(o=this.getDeliveryDirectives(a,e.deliveryDirectives,l,u),d||!v)return void this.loadPlaylist(o)}else o=this.getDeliveryDirectives(a,e.deliveryDirectives,l,u);var b=function(t,e){var r,i=1e3*t.levelTargetDuration,a=i/2,n=t.age,s=n>0&&n<3*i,o=e.loading.end-e.loading.start,l=t.availabilityDelay;if(!1===t.updated)if(s){var u=333*t.misses;r=Math.max(Math.min(a,2*o),u),t.availabilityDelay=(t.availabilityDelay||0)+r}else r=a;else s?(l=Math.min(l||i/2,n),t.availabilityDelay=l,r=l+i-n):r=i-o;return Math.round(r)}(a,n);void 0!==l&&a.canBlockReload&&(b-=a.partTarget||1),this.log("reload live playlist "+t+" in "+Math.round(b)+" ms"),this.timer=self.setTimeout((function(){return i.loadPlaylist(o)}),b)}else this.clearTimer()},e.getDeliveryDirectives=function(t,e,r,i){var a=function(t,e){var r=t.canSkipUntil,i=t.canSkipDateRanges,a=t.endSN;return r&&(void 0!==e?e-a:0)-1&&null!==(e=t.context)&&void 0!==e&&e.deliveryDirectives)this.warn("retry playlist loading #"+this.retryCount+' after "'+t.details+'"'),this.loadPlaylist();else{var n=Math.min(Math.pow(2,this.retryCount)*i.levelLoadingRetryDelay,i.levelLoadingMaxRetryTimeout);this.timer=self.setTimeout((function(){return r.loadPlaylist()}),n),this.warn("retry playlist loading #"+this.retryCount+" in "+n+' ms after "'+t.details+'"')}else this.warn('cannot recover from error "'+t.details+'"'),this.clearTimer(),t.fatal=!0;return a},t}();function q(){return(q=Object.assign||function(t){for(var e=1;e0){r=a[0].bitrate,a.sort((function(t,e){return t.bitrate-e.bitrate})),this._levels=a;for(var c=0;cthis.hls.config.fragLoadingMaxRetry&&(n=r.frag.level)):n=r.frag.level}break;case s.a.LEVEL_LOAD_ERROR:case s.a.LEVEL_LOAD_TIMEOUT:i&&(i.deliveryDirectives&&(l=!1),n=i.level),o=!0;break;case s.a.REMUX_ALLOC_ERROR:n=r.level,o=!0}void 0!==n&&this.recoverLevel(r,n,o,l)}}},u.recoverLevel=function(t,e,r,i){var a=t.details,n=this._levels[e];if(n.loadError++,r){if(!this.retryLoadingOrFail(t))return void(this.currentLevelIndex=-1);t.levelRetry=!0}if(i){var s=n.url.length;if(s>1&&n.loadError1){var i=(e.urlId+1)%r;this.warn("Switching to redundant URL-id "+i),this._levels.forEach((function(t){t.urlId=i})),this.level=t}},u.onFragLoaded=function(t,e){var r=e.frag;if(void 0!==r&&r.type===_.b.MAIN){var i=this._levels[r.level];void 0!==i&&(i.fragmentError=0,i.loadError=0)}},u.onLevelLoaded=function(t,e){var r,i,a=e.level,n=e.details,s=this._levels[a];if(!s)return this.warn("Invalid level index "+a),void(null!==(i=e.deliveryDirectives)&&void 0!==i&&i.skip&&(n.deltaUpdateFailed=!0));a===this.currentLevelIndex?(0===s.fragmentError&&(s.loadError=0,this.retryCount=0),this.playlistLoaded(a,e,s.details)):null!==(r=e.deliveryDirectives)&&void 0!==r&&r.skip&&(n.deltaUpdateFailed=!0)},u.onAudioTrackSwitched=function(t,e){var r=this.hls.levels[this.currentLevelIndex];if(r&&r.audioGroupIds){for(var i=-1,a=this.hls.audioTracks[e.id].groupId,n=0;n0){var i=r.urlId,a=r.url[i];if(t)try{a=t.addDirectives(a)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}this.log("Attempt loading level index "+e+(t?" at sn "+t.msn+" part "+t.part:"")+" with URL-id "+i+" "+a),this.clearTimer(),this.hls.trigger(n.a.LEVEL_LOADING,{url:a,level:e,id:i,deliveryDirectives:t||null})}},u.removeLevel=function(t,e){var r=function(t,r){return r!==e},i=this._levels.filter((function(i,a){return a!==t||i.url.length>1&&void 0!==e&&(i.url=i.url.filter(r),i.audioGroupIds&&(i.audioGroupIds=i.audioGroupIds.filter(r)),i.textGroupIds&&(i.textGroupIds=i.textGroupIds.filter(r)),i.urlId=0,!0)})).map((function(t,e){var r=t.details;return null!=r&&r.fragments&&r.fragments.forEach((function(t){t.level=e})),t}));this._levels=i,this.hls.trigger(n.a.LEVELS_UPDATED,{levels:i})},a=i,(o=[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(t){var e,r=this._levels;if(0!==r.length&&(this.currentLevelIndex!==t||null===(e=r[t])||void 0===e||!e.details)){if(t<0||t>=r.length){var i=t<0;if(this.hls.trigger(n.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.LEVEL_SWITCH_ERROR,level:t,fatal:i,reason:"invalid level idx"}),i)return;t=Math.min(t,r.length-1)}this.clearTimer();var a=this.currentLevelIndex,o=r[a],l=r[t];this.log("switching to level "+t+" from "+a),this.currentLevelIndex=t;var u=q({},l,{level:t,maxBitrate:l.maxBitrate,uri:l.uri,urlId:l.urlId});delete u._urlId,this.hls.trigger(n.a.LEVEL_SWITCHING,u);var d=l.details;if(!d||d.live){var h=this.switchParams(l.uri,null==o?void 0:o.details);this.loadPlaylist(h)}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(t){this._firstLevel=t}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var t=this.hls.config.startLevel;return void 0!==t?t:this._firstLevel}return this._startLevel},set:function(t){this._startLevel=t}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}}])&&z(a.prototype,o),l&&z(a,l),i}(X);!function(t){t.NOT_LOADED="NOT_LOADED",t.BACKTRACKED="BACKTRACKED",t.APPENDING="APPENDING",t.PARTIAL="PARTIAL",t.OK="OK"}($||($={}));var tt=function(){function t(t){this.activeFragment=null,this.activeParts=null,this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hls=t,this._registerListeners()}var e=t.prototype;return e._registerListeners=function(){var t=this.hls;t.on(n.a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(n.a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(n.a.FRAG_LOADED,this.onFragLoaded,this)},e._unregisterListeners=function(){var t=this.hls;t.off(n.a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(n.a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(n.a.FRAG_LOADED,this.onFragLoaded,this)},e.destroy=function(){this._unregisterListeners(),this.fragments=this.timeRanges=null},e.getAppendedFrag=function(t,e){if(e===_.b.MAIN){var r=this.activeFragment,i=this.activeParts;if(!r)return null;if(i)for(var a=i.length;a--;){var n=i[a],s=n?n.end:r.appendedPTS;if(n.start<=t&&void 0!==s&&t<=s)return a>9&&(this.activeParts=i.slice(a-9)),n}else if(r.start<=t&&void 0!==r.appendedPTS&&t<=r.appendedPTS)return r}return this.getBufferedFrag(t,e)},e.getBufferedFrag=function(t,e){for(var r=this.fragments,i=Object.keys(r),a=i.length;a--;){var n=r[i[a]];if((null==n?void 0:n.body.type)===e&&n.buffered){var s=n.body;if(s.start<=t&&t<=s.end)return s}}return null},e.detectEvictedFragments=function(t,e,r){var i=this;Object.keys(this.fragments).forEach((function(a){var n=i.fragments[a];if(n)if(n.buffered){var s=n.range[t];s&&s.time.some((function(t){var r=!i.isTimeBuffered(t.startPTS,t.endPTS,e);return r&&i.removeFragment(n.body),r}))}else n.body.type===r&&i.removeFragment(n.body)}))},e.detectPartialFragments=function(t){var e=this,r=this.timeRanges,i=t.frag,a=t.part;if(r&&"initSegment"!==i.sn){var n=rt(i),s=this.fragments[n];s&&(Object.keys(r).forEach((function(t){var n=i.elementaryStreams[t];if(n){var o=r[t],l=null!==a||!0===n.partial;s.range[t]=e.getBufferedTimes(i,a,l,o)}})),s.backtrack=s.loaded=null,Object.keys(s.range).length?s.buffered=!0:this.removeFragment(s.body))}},e.fragBuffered=function(t){var e=rt(t),r=this.fragments[e];r&&(r.backtrack=r.loaded=null,r.buffered=!0)},e.getBufferedTimes=function(t,e,r,i){for(var a={time:[],partial:r},n=e?e.start:t.start,s=e?e.end:t.end,o=t.minEndPTS||s,l=t.maxStartPTS||n,u=0;u=d&&o<=h){a.time.push({startPTS:Math.max(n,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(nd)a.partial=!0,a.time.push({startPTS:Math.max(n,i.start(u)),endPTS:Math.min(s,i.end(u))});else if(s<=d)break}return a},e.getPartialFragment=function(t){var e,r,i,a=null,n=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var u=o[l];u&&et(u)&&(r=u.body.start-s,i=u.body.end+s,t>=r&&t<=i&&(e=Math.min(t-r,i-t),n<=e&&(a=u.body,n=e)))})),a},e.getState=function(t){var e=rt(t),r=this.fragments[e];return r?r.buffered?et(r)?$.PARTIAL:$.OK:r.backtrack?$.BACKTRACKED:$.APPENDING:$.NOT_LOADED},e.backtrack=function(t,e){var r=rt(t),i=this.fragments[r];if(!i||i.backtrack)return null;var a=i.backtrack=e||i.loaded;return i.loaded=null,a},e.getBacktrackData=function(t){var e=rt(t),r=this.fragments[e];if(r){var i,a=r.backtrack;if(null!=a&&null!==(i=a.payload)&&void 0!==i&&i.byteLength)return a;this.removeFragment(t)}return null},e.isTimeBuffered=function(t,e,r){for(var i,a,n=0;n=i&&e<=a)return!0;if(e<=i)return!1}return!1},e.onFragLoaded=function(t,e){var r=e.frag,i=e.part;if("initSegment"!==r.sn&&!r.bitrateTest&&!i){var a=rt(r);this.fragments[a]={body:r,loaded:e,backtrack:null,buffered:!1,range:Object.create(null)}}},e.onBufferAppended=function(t,e){var r=this,i=e.frag,a=e.part,n=e.timeRanges;if(i.type===_.b.MAIN)if(this.activeFragment=i,a){var s=this.activeParts;s||(this.activeParts=s=[]),s.push(a)}else this.activeParts=null;this.timeRanges=n,Object.keys(n).forEach((function(t){var e=n[t];if(r.detectEvictedFragments(t,e),!a)for(var s=0;st&&i.removeFragment(s)}}))},e.removeFragment=function(t){var e=rt(t);t.stats.loaded=0,t.clearElementaryStreamInfo(),delete this.fragments[e]},e.removeAllFragments=function(){this.fragments=Object.create(null),this.activeFragment=null,this.activeParts=null},t}();function et(t){var e,r;return t.buffered&&((null===(e=t.range.video)||void 0===e?void 0:e.partial)||(null===(r=t.range.audio)||void 0===r?void 0:r.partial))}function rt(t){return t.type+"_"+t.level+"_"+t.urlId+"_"+t.sn}var it=function(){function t(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}var e=t.prototype;return e.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},e.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},e.onHandlerDestroyed=function(){},e.hasInterval=function(){return!!this._tickInterval},e.hasNextTick=function(){return!!this._tickTimer},e.setInterval=function(t){return!this._tickInterval&&(this._tickInterval=self.setInterval(this._boundTick,t),!0)},e.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},e.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},e.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},e.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},e.doTick=function(){},t}(),at={length:0,start:function(){return 0},end:function(){return 0}},nt=function(){function t(){}return t.isBuffered=function(e,r){try{if(e)for(var i=t.getBuffered(e),a=0;a=i.start(a)&&r<=i.end(a))return!0}catch(t){}return!1},t.bufferInfo=function(e,r,i){try{if(e){var a,n=t.getBuffered(e),s=[];for(a=0;as&&(i[n-1].end=t[a].end):i.push(t[a])}else i.push(t[a])}else i=t;for(var o,l=0,u=e,d=e,h=0;h=f&&er.startCC||t&&t.cc0)r=a+1;else{if(!(s<0))return n;i=a-1}}return null}};function ht(t,e,r){void 0===t&&(t=0),void 0===e&&(e=0);var i=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=t?1:r.start-i>t&&r.start?-1:0}function ft(t,e,r){var i=1e3*Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>t}function ct(t){var e="function"==typeof Map?new Map:void 0;return(ct=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,i)}function i(){return vt(t,arguments,mt(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),pt(i,t)})(t)}function vt(t,e,r){return(vt=gt()?Reflect.construct:function(t,e,r){var i=[null];i.push.apply(i,e);var a=new(Function.bind.apply(t,i));return r&&pt(a,r.prototype),a}).apply(null,arguments)}function gt(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function pt(t,e){return(pt=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function mt(t){return(mt=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var yt=Math.pow(2,17),bt=function(){function t(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}var e=t.prototype;return e.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},e.abort=function(){this.loader&&this.loader.abort()},e.load=function(t,e){var r=this,i=t.url;if(!i)return Promise.reject(new Et({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,networkDetails:null},"Fragment does not have a "+(i?"part list":"url")));this.abort();var a=this.config,n=a.fLoader,o=a.loader;return new Promise((function(i,l){r.loader&&r.loader.destroy();var u=r.loader=t.loader=n?new n(a):new o(a),d=Tt(t),h={timeout:a.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:a.fragLoadingMaxRetryTimeout,highWaterMark:yt};t.stats=u.stats,u.load(d,h,{onSuccess:function(e,a,n,s){r.resetLoader(t,u),i({frag:t,part:null,payload:e.data,networkDetails:s})},onError:function(e,i,a){r.resetLoader(t,u),l(new Et({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:e,networkDetails:a}))},onAbort:function(e,i,a){r.resetLoader(t,u),l(new Et({type:s.b.NETWORK_ERROR,details:s.a.INTERNAL_ABORTED,fatal:!1,frag:t,networkDetails:a}))},onTimeout:function(e,i,a){r.resetLoader(t,u),l(new Et({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,networkDetails:a}))},onProgress:function(r,i,a,n){e&&e({frag:t,part:null,payload:a,networkDetails:n})}})}))},e.loadPart=function(t,e,r){var i=this;this.abort();var a=this.config,n=a.fLoader,o=a.loader;return new Promise((function(l,u){i.loader&&i.loader.destroy();var d=i.loader=t.loader=n?new n(a):new o(a),h=Tt(t,e),f={timeout:a.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:a.fragLoadingMaxRetryTimeout,highWaterMark:yt};e.stats=d.stats,d.load(h,f,{onSuccess:function(a,n,s,o){i.resetLoader(t,d),i.updateStatsFromPart(t,e);var u={frag:t,part:e,payload:a.data,networkDetails:o};r(u),l(u)},onError:function(r,a,n){i.resetLoader(t,d),u(new Et({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:r,networkDetails:n}))},onAbort:function(r,a,n){t.stats.aborted=e.stats.aborted,i.resetLoader(t,d),u(new Et({type:s.b.NETWORK_ERROR,details:s.a.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,networkDetails:n}))},onTimeout:function(r,a,n){i.resetLoader(t,d),u(new Et({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,networkDetails:n}))}})}))},e.updateStatsFromPart=function(t,e){var r=t.stats,i=e.stats,a=i.total;if(r.loaded+=i.loaded,a){var n=Math.round(t.duration/e.duration),s=Math.min(Math.round(r.loaded/a),n),o=(n-s)*Math.round(r.loaded/s);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,u=i.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end},e.resetLoader=function(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()},t}();function Tt(t,e){void 0===e&&(e=null);var r=e||t,i={frag:t,part:e,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},n=r.byteRangeStartOffset,s=r.byteRangeEndOffset;return Object(a.a)(n)&&Object(a.a)(s)&&(i.rangeStart=n,i.rangeEnd=s),i}var Et=function(t){var e,r;function i(e){for(var r,i=arguments.length,a=new Array(i>1?i-1:0),n=1;n=e.endSN&&!t.nextStart){var a=e.partList;if(null!=a&&a.length){var n=a[a.length-1];return nt.isBuffered(this.media,n.start+n.duration/2)}var s=i.getState(r);return s===$.PARTIAL||s===$.OK}return!1},f.onMediaAttached=function(t,e){var r=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),r.addEventListener("seeking",this.onvseeking),r.addEventListener("ended",this.onvended);var i=this.config;this.levels&&i.autoStartLoad&&this.state===Dt&&this.startLoad(i.startPosition)},f.onMediaDetaching=function(){var t=this.media;null!=t&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()},f.onMediaSeeking=function(){var t=this.config,e=this.fragCurrent,r=this.media,i=this.mediaBuffer,n=this.state,s=r?r.currentTime:0,o=nt.bufferInfo(i||r,s,t.maxBufferHole);if(this.log("media seeking to "+(Object(a.a)(s)?s.toFixed(3):s)+", state: "+n),n===Pt)this.resetLoadingState();else if(e&&!o.len){var l=t.maxFragLookUpTolerance,u=e.start-l,d=s>e.start+e.duration+l;(s0&&s&&s.key&&s.iv&&"AES-128"===s.method){var o=self.performance.now();return e.decrypter.webCryptoDecrypt(new Uint8Array(a),s.key.buffer,s.iv.buffer).then((function(e){var a=self.performance.now();return i.trigger(n.a.FRAG_DECRYPTED,{frag:t,payload:e,stats:{tstart:o,tdecrypt:a}}),r.payload=e,r}))}return r})).then((function(r){var i=e.fragCurrent,a=e.hls,s=e.levels;if(!s)throw new Error("init load aborted, missing levels");s[t.level].details;var o=t.stats;e.state=_t,e.fragLoadError=0,t.data=new Uint8Array(r.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),r.frag===i&&a.trigger(n.a.FRAG_BUFFERED,{stats:o,frag:i,part:null,id:t.type}),e.tick()})).catch((function(r){e.warn(r),e.resetFragmentLoading(t)}))},f.fragContextChanged=function(t){var e=this.fragCurrent;return!t||!e||t.level!==e.level||t.sn!==e.sn||t.urlId!==e.urlId},f.fragBufferedComplete=function(t,e){var r=this.mediaBuffer?this.mediaBuffer:this.media;this.log("Buffered "+t.type+" sn: "+t.sn+(e?" part: "+e.index:"")+" of "+("[stream-controller]"===this.logPrefix?"level":"track")+" "+t.level+" "+Lt.toString(nt.getBuffered(r))),this.state=_t,this.tick()},f._handleFragmentLoadComplete=function(t){var e=this.transmuxer;if(e){var r=t.frag,i=t.part,a=t.partsLoaded,n=!a||0===a.length||a.some((function(t){return!t})),s=new st(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!n);e.flush(s)}},f._handleFragmentLoadProgress=function(t){},f._doFragLoad=function(t,e,r,i){var s=this;if(void 0===r&&(r=null),!this.levels)throw new Error("frag load aborted, missing levels");if(r=Math.max(t.start,r||0),this.config.lowLatencyMode&&e){var o=e.partList;if(o&&i){r>t.end&&e.fragmentHint&&(t=e.fragmentHint);var l=this.getNextPart(o,t,r);if(l>-1){var u=o[l];return this.log("Loading part sn: "+t.sn+" p: "+u.index+" cc: "+t.cc+" of playlist ["+e.startSN+"-"+e.endSN+"] parts [0-"+l+"-"+(o.length-1)+"] "+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),this.nextLoadPosition=u.start+u.duration,this.state=xt,this.hls.trigger(n.a.FRAG_LOADING,{frag:t,part:o[l],targetBufferTime:r}),this.doFragPartsLoad(t,o,l,i).catch((function(t){return s.handleFragLoadError(t)}))}if(!t.url||this.loadedEndOfParts(o,r))return Promise.resolve(null)}}return this.log("Loading fragment "+t.sn+" cc: "+t.cc+" "+(e?"of ["+e.startSN+"-"+e.endSN+"] ":"")+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),Object(a.a)(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=xt,this.hls.trigger(n.a.FRAG_LOADING,{frag:t,targetBufferTime:r}),this.fragmentLoader.load(t,i).catch((function(t){return s.handleFragLoadError(t)}))},f.doFragPartsLoad=function(t,e,r,i){var a=this;return new Promise((function(s,o){var l=[];!function r(u){var d=e[u];a.fragmentLoader.loadPart(t,d,i).then((function(i){l[d.index]=i;var o=i.part;a.hls.trigger(n.a.FRAG_LOADED,i);var h=e[u+1];if(!h||h.fragment!==t)return s({frag:t,part:o,partsLoaded:l});r(u+1)})).catch(o)}(r)}))},f.handleFragLoadError=function(t){var e=t.data;return e&&e.details===s.a.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(n.a.ERROR,e),null},f._handleTransmuxerFlush=function(t){var e=this.getCurrentContext(t);if(e&&this.state===wt){var r=e.frag,i=e.part,a=e.level,n=self.performance.now();r.stats.parsing.end=n,i&&(i.stats.parsing.end=n),this.updateLevelTiming(r,i,a,t.partial)}else this.fragCurrent||(this.state=_t)},f.getCurrentContext=function(t){var e=this.levels,r=t.level,i=t.sn,a=t.part;if(!e||!e[r])return this.warn("Levels object was unset while buffering fragment "+i+" of level "+r+". The current chunk will not be buffered."),null;var n=e[r],s=a>-1?function(t,e,r){if(!t||!t.details)return null;var i=t.details.partList;if(i)for(var a=i.length;a--;){var n=i[a];if(n.index===r&&n.fragment.sn===e)return n}return null}(n,i,a):null,o=s?s.fragment:function(t,e,r){if(!t||!t.details)return null;var i=t.details,a=i.fragments[e-i.startSN];return a||((a=i.fragmentHint)&&a.sn===e?a:en&&this.flushMainBuffer(s,t.start)}else this.flushMainBuffer(0,t.start)},f.getFwdBufferInfo=function(t,e){var r=this.config,i=this.getLoadPosition();if(!Object(a.a)(i))return null;var n=nt.bufferInfo(t,i,r.maxBufferHole);if(0===n.len&&void 0!==n.nextStart){var s=this.fragmentTracker.getBufferedFrag(i,e);if(s&&n.nextStart=r&&(e.maxMaxBufferLength/=2,this.warn("Reduce max buffer length to "+e.maxMaxBufferLength+"s"),!0)},f.getNextFragment=function(t,e){var r,i,a=e.fragments,n=a.length;if(!n)return null;var s,o=this.config,l=a[0].start;if(e.live){var u=o.initialLiveManifestSize;if(n-1&&rr.start&&r.loaded},f.getInitialLiveFragment=function(t,e){var r=this.fragPrevious,i=null;if(r){if(t.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+r.programDateTime),i=function(t,e,r){if(null===e||!Array.isArray(t)||!t.length||!Object(a.a)(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;r=r||0;for(var i=0;i=t.startSN&&n<=t.endSN){var s=e[n-t.startSN];r.cc===s.cc&&(i=s,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=function(t,e){return dt.search(t,(function(t){return t.cce?-1:0}))}(e,r.cc))&&this.log("Live playlist, switching playlist, load frag with same CC: "+i.sn)}}else{var o=this.hls.liveSyncPosition;null!==o&&(i=this.getFragmentAtPosition(o,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i},f.getFragmentAtPosition=function(t,e,r){var i,a=this.config,n=this.fragPrevious,s=r.fragments,o=r.endSN,l=r.fragmentHint,u=a.maxFragLookUpTolerance,d=!!(a.lowLatencyMode&&r.partList&&l);(d&&l&&!this.bitrateTest&&(s=s.concat(l),o=l.sn),te-u?0:u):i=s[s.length-1];if(i){var h=i.sn-r.startSN,f=n&&i.level===n.level,c=s[h+1];if(this.fragmentTracker.getState(i)===$.BACKTRACKED){i=null;for(var v=h;s[v]&&this.fragmentTracker.getState(s[v])===$.BACKTRACKED;)i=n?s[v--]:s[--v];i||(i=c)}else n&&i.sn===n.sn&&!d&&f&&(i.sn=n-e.maxFragLookUpTolerance&&a<=s;if(null!==i&&r.duration>i&&(a"+t.startSN+" prev-sn: "+(n?n.sn:"na")+" fragments: "+o),h}return l},f.waitForCdnTuneIn=function(t){return t.live&&t.canBlockReload&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)},f.setStartPosition=function(t,e){var r=this.startPosition;if(r"+t))}}])&&At(u.prototype,d),h&&At(u,h),i}(it);function Bt(){return self.MediaSource||self.WebKitMediaSource}function Ut(){return self.SourceBuffer||self.WebKitSourceBuffer}var Gt=r(17),jt=r(9),Ht=r(13),Kt=Bt()||{isTypeSupported:function(){return!1}},Vt=function(){function t(t,e,r,i){var a=this;this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.worker=void 0,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.hls=t,this.id=e,this.onTransmuxComplete=r,this.onFlush=i;var l=t.config,u=function(e,r){(r=r||{}).frag=a.frag,r.id=a.id,t.trigger(e,r)};this.observer=new Ht.EventEmitter,this.observer.on(n.a.FRAG_DECRYPTED,u),this.observer.on(n.a.ERROR,u);var d={mp4:Kt.isTypeSupported("video/mp4"),mpeg:Kt.isTypeSupported("audio/mpeg"),mp3:Kt.isTypeSupported('audio/mp4; codecs="mp3"')},h=navigator.vendor;if(l.enableWorker&&"undefined"!=typeof Worker){var f;o.b.log("demuxing in webworker");try{f=this.worker=Gt(18),this.onwmsg=this.onWorkerMessage.bind(this),f.addEventListener("message",this.onwmsg),f.onerror=function(e){t.trigger(n.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.INTERNAL_EXCEPTION,fatal:!0,event:"demuxerWorker",error:new Error(e.message+" ("+e.filename+":"+e.lineno+")")})},f.postMessage({cmd:"init",typeSupported:d,vendor:h,id:e,config:JSON.stringify(l)})}catch(t){o.b.warn("Error in worker:",t),o.b.error("Error while initializing DemuxerWorker, fallback to inline"),f&&self.URL.revokeObjectURL(f.objectURL),this.transmuxer=new jt.c(this.observer,d,l,h,e),this.worker=null}}else this.transmuxer=new jt.c(this.observer,d,l,h,e)}var e=t.prototype;return e.destroy=function(){var t=this.worker;if(t)t.removeEventListener("message",this.onwmsg),t.terminate(),this.worker=null;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var r=this.observer;r&&r.removeAllListeners(),this.observer=null},e.push=function(t,e,r,i,a,n,s,l,u,d){var h,f,c=this;u.transmuxing.start=self.performance.now();var v=this.transmuxer,g=this.worker,p=n?n.start:a.start,m=a.decryptdata,y=this.frag,b=!(y&&a.cc===y.cc),T=!(y&&u.level===y.level),E=y?u.sn-y.sn:-1,S=this.part?u.part-this.part.index:1,L=!T&&(1===E||0===E&&1===S),A=self.performance.now();(T||E||0===a.stats.parsing.start)&&(a.stats.parsing.start=A),!n||!S&&L||(n.stats.parsing.start=A);var R=!(y&&(null===(h=a.initSegment)||void 0===h?void 0:h.url)===(null===(f=y.initSegment)||void 0===f?void 0:f.url)),D=new jt.b(b,L,l,T,p,R);if(!L||b||R){o.b.log("[transmuxer-interface, "+a.type+"]: Starting new transmux session for sn: "+u.sn+" p: "+u.part+" level: "+u.level+" id: "+u.id+"\n discontinuity: "+b+"\n trackSwitch: "+T+"\n contiguous: "+L+"\n accurateTimeOffset: "+l+"\n timeOffset: "+p+"\n initSegmentChange: "+R);var _=new jt.a(r,i,e,s,d);this.configureTransmuxer(_)}if(this.frag=a,this.part=n,g)g.postMessage({cmd:"demux",data:t,decryptdata:m,chunkMeta:u,state:D},t instanceof ArrayBuffer?[t]:[]);else if(v){var k=v.push(t,m,u,D);Object(jt.d)(k)?k.then((function(t){c.handleTransmuxComplete(t)})):this.handleTransmuxComplete(k)}},e.flush=function(t){var e=this;t.transmuxing.start=self.performance.now();var r=this.transmuxer,i=this.worker;if(i)i.postMessage({cmd:"flush",chunkMeta:t});else if(r){var a=r.flush(t);Object(jt.d)(a)?a.then((function(r){e.handleFlushResult(r,t)})):this.handleFlushResult(a,t)}},e.handleFlushResult=function(t,e){var r=this;t.forEach((function(t){r.handleTransmuxComplete(t)})),this.onFlush(e)},e.onWorkerMessage=function(t){var e=t.data,r=this.hls;switch(e.event){case"init":self.URL.revokeObjectURL(this.worker.objectURL);break;case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,r.trigger(e.event,e.data)}},e.configureTransmuxer=function(t){var e=this.worker,r=this.transmuxer;e?e.postMessage({cmd:"configure",config:t}):r&&r.configure(t)},e.handleTransmuxComplete=function(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)},t}(),Wt=function(){function t(t,e,r,i){this.config=void 0,this.media=void 0,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=r,this.hls=i}var e=t.prototype;return e.destroy=function(){this.hls=this.fragmentTracker=this.media=null},e.poll=function(t){var e=this.config,r=this.media,i=this.stalled,a=r.currentTime,n=r.seeking,s=this.seeking&&!n,l=!this.seeking&&n;if(this.seeking=n,a===t){if((l||s)&&(this.stalled=null),!r.paused&&!r.ended&&0!==r.playbackRate&&nt.getBuffered(r).length){var u=nt.bufferInfo(r,a,0),d=u.len>0,h=u.nextStart||0;if(d||h){if(n){var f=u.len>2,c=!h||h-a>2&&!this.fragmentTracker.getPartialFragment(a);if(f||c)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var v,g=Math.max(h,u.start||0)-a,p=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,m=(null==p||null===(v=p.details)||void 0===v?void 0:v.live)?2*p.details.targetduration:2;if(g>0&&g<=m)return void this._trySkipBufferHole(null)}var y=self.performance.now();if(null!==i){var b=y-i;!n&&b>=250&&this._reportStall(u.len);var T=nt.bufferInfo(r,a,e.maxBufferHole);this._tryFixBufferStall(T,b)}else this.stalled=y}}}else if(this.moved=!0,null!==i){if(this.stallReported){var E=self.performance.now()-i;o.b.warn("playback not stuck anymore @"+a+", after "+Math.round(E)+"ms"),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}},e._tryFixBufferStall=function(t,e){var r=this.config,i=this.fragmentTracker,a=this.media.currentTime,n=i.getPartialFragment(a);if(n&&this._trySkipBufferHole(n))return;t.len>r.maxBufferHole&&e>1e3*r.highBufferWatchdogPeriod&&(o.b.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())},e._reportStall=function(t){var e=this.hls,r=this.media;this.stallReported||(this.stallReported=!0,o.b.warn("Playback stalling at @"+r.currentTime+" due to low buffer (buffer="+t+")"),e.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_STALLED_ERROR,fatal:!1,buffer:t}))},e._trySkipBufferHole=function(t){for(var e=this.config,r=this.hls,i=this.media,a=i.currentTime,l=0,u=nt.getBuffered(i),d=0;d=l&&a0&&-1===t&&(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e),this.state=_t,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=Dt},f.stopLoad=function(){this._forceStartLoad=!1,t.prototype.stopLoad.call(this)},f.doTick=function(){switch(this.state){case _t:this.doTickIdle();break;case Mt:var t,e=this.levels,r=this.level,i=null==e||null===(t=e[r])||void 0===t?void 0:t.details;if(i&&(!i.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(i))break;this.state=_t;break}break;case Ct:var a,n=self.performance.now(),s=this.retryDate;(!s||n>=s||null!==(a=this.media)&&void 0!==a&&a.seeking)&&(this.log("retryDate reached, switch back to IDLE state"),this.state=_t)}this.onTickEnd()},f.onTickEnd=function(){t.prototype.onTickEnd.call(this),this.checkBuffer(),this.checkFragmentChanged()},f.doTickIdle=function(){var t,e,r=this.hls,i=this.levelLastLoaded,a=this.levels,s=this.media,o=r.config,l=r.nextLoadLevel;if(null!==i&&(s||!this.startFragRequested&&o.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)&&a&&a[l]){var d=a[l];this.level=r.nextLoadLevel=l;var h=d.details;if(!h||this.state===Mt||h.live&&this.levelLastLoaded!==l)this.state=Mt;else{var f=this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:s,_.b.MAIN);if(null!==f)if(!(f.len>=this.getMaxBufferLength(d.maxBitrate))){if(this._streamEnded(f,h)){var c={};return this.altAudio&&(c.type="video"),this.hls.trigger(n.a.BUFFER_EOS,c),void(this.state=Pt)}var v=f.end,g=this.getNextFragment(v,h);if(this.couldBacktrack&&!this.fragPrevious&&g&&"initSegment"!==g.sn){var p=g.sn-h.startSN;p>1&&(g=h.fragments[p-1],this.fragmentTracker.removeFragment(g))}if(g&&this.fragmentTracker.getState(g)===$.OK&&this.nextLoadPosition>v){var m=this.audioOnly&&!this.altAudio?u.a.AUDIO:u.a.VIDEO;this.afterBufferFlushed(s,m,_.b.MAIN),g=this.getNextFragment(this.nextLoadPosition,h)}g&&(!g.initSegment||g.initSegment.data||this.bitrateTest||(g=g.initSegment),"identity"!==(null===(t=g.decryptdata)||void 0===t?void 0:t.keyFormat)||null!==(e=g.decryptdata)&&void 0!==e&&e.key?this.loadFragment(g,h,v):this.loadKey(g,h))}}}},f.loadFragment=function(e,r,i){var a,n=this.fragmentTracker.getState(e);if(this.fragCurrent=e,n===$.BACKTRACKED){var s=this.fragmentTracker.getBacktrackData(e);if(s)return this._handleFragmentLoadProgress(s),void this._handleFragmentLoadComplete(s);n=$.NOT_LOADED}n===$.NOT_LOADED||n===$.PARTIAL?"initSegment"===e.sn?this._loadInitSegment(e):this.bitrateTest?(e.bitrateTest=!0,this.log("Fragment "+e.sn+" of level "+e.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(e)):(this.startFragRequested=!0,t.prototype.loadFragment.call(this,e,r,i)):n===$.APPENDING?this.reduceMaxBufferLength(e.duration)&&this.fragmentTracker.removeFragment(e):0===(null===(a=this.media)||void 0===a?void 0:a.buffered.length)&&this.fragmentTracker.removeAllFragments()},f.getAppendedFrag=function(t){var e=this.fragmentTracker.getAppendedFrag(t,_.b.MAIN);return e&&"fragment"in e?e.fragment:e},f.getBufferedFrag=function(t){return this.fragmentTracker.getBufferedFrag(t,_.b.MAIN)},f.followingBufferedFrag=function(t){return t?this.getBufferedFrag(t.end+.5):null},f.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},f.nextLevelSwitch=function(){var t=this.levels,e=this.media;if(null!=e&&e.readyState){var r,i=this.getAppendedFrag(e.currentTime);if(i&&i.start>1&&this.flushMainBuffer(0,i.start-1),!e.paused&&t){var a=t[this.hls.nextLoadLevel],n=this.fragLastKbps;r=n&&this.fragCurrent?this.fragCurrent.duration*a.maxBitrate/(1e3*n)+1:0}else r=0;var s=this.getBufferedFrag(e.currentTime+r);if(s){var o=this.followingBufferedFrag(s);if(o){this.abortCurrentFrag();var l=o.maxStartPTS?o.maxStartPTS:o.start,u=o.duration,d=Math.max(s.end,l+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,.5*u),.75*u));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}},f.abortCurrentFrag=function(){var t=this.fragCurrent;this.fragCurrent=null,null!=t&&t.loader&&t.loader.abort(),this.state===kt&&(this.state=_t),this.nextLoadPosition=this.getLoadPosition()},f.flushMainBuffer=function(e,r){t.prototype.flushMainBuffer.call(this,e,r,this.altAudio?"video":null)},f.onMediaAttached=function(e,r){t.prototype.onMediaAttached.call(this,e,r);var i=r.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Wt(this.config,i,this.fragmentTracker,this.hls)},f.onMediaDetaching=function(){var e=this.media;e&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),t.prototype.onMediaDetaching.call(this)},f.onMediaPlaying=function(){this.tick()},f.onMediaSeeked=function(){var t=this.media,e=t?t.currentTime:null;Object(a.a)(e)&&this.log("Media seeked to "+e.toFixed(3)),this.tick()},f.onManifestLoading=function(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(n.a.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=this.stalled=!1,this.startPosition=this.lastCurrentTime=0,this.fragPlaying=null},f.onManifestParsed=function(t,e){var r,i,a,n=!1,s=!1;e.levels.forEach((function(t){(r=t.audioCodec)&&(-1!==r.indexOf("mp4a.40.2")&&(n=!0),-1!==r.indexOf("mp4a.40.5")&&(s=!0))})),this.audioCodecSwitch=n&&s&&!("function"==typeof(null==(a=Ut())||null===(i=a.prototype)||void 0===i?void 0:i.changeType)),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1},f.onLevelLoading=function(t,e){var r=this.levels;if(r&&this.state===_t){var i=r[e.level];(!i.details||i.details.live&&this.levelLastLoaded!==e.level||this.waitForCdnTuneIn(i.details))&&(this.state=Mt)}},f.onLevelLoaded=function(t,e){var r,i=this.levels,a=e.level,s=e.details,o=s.totalduration;if(i){this.log("Level "+a+" loaded ["+s.startSN+","+s.endSN+"], cc ["+s.startCC+", "+s.endCC+"] duration:"+o);var l=this.fragCurrent;!l||this.state!==xt&&this.state!==Ct||l.level!==e.level&&l.loader&&(this.state=_t,l.loader.abort());var u=i[a],d=0;if(s.live||null!==(r=u.details)&&void 0!==r&&r.live){if(s.fragments[0]||(s.deltaUpdateFailed=!0),s.deltaUpdateFailed)return;d=this.alignPlaylists(s,u.details)}if(u.details=s,this.levelLastLoaded=a,this.hls.trigger(n.a.LEVEL_UPDATED,{details:s,level:a}),this.state===Mt){if(this.waitForCdnTuneIn(s))return;this.state=_t}this.startFragRequested?s.live&&this.synchronizeToLiveEdge(s):this.setStartPosition(s,d),this.tick()}else this.warn("Levels were reset while loading level "+a)},f._handleFragmentLoadProgress=function(t){var e,r=t.frag,i=t.part,a=t.payload,n=this.levels;if(n){var s=n[r.level],o=s.details;if(o){var l=s.videoCodec,u=o.PTSKnown||!o.live,d=null===(e=r.initSegment)||void 0===e?void 0:e.data,h=this._getAudioCodec(s),f=this.transmuxer=this.transmuxer||new Vt(this.hls,_.b.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),c=i?i.index:-1,v=-1!==c,g=new st(r.level,r.sn,r.stats.chunkCount,a.byteLength,c,v),p=this.initPTS[r.cc];f.push(a,d,h,l,r,i,o.totalduration,u,g,p)}else this.warn("Dropping fragment "+r.sn+" of level "+r.level+" after level details were reset")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},f.onAudioTrackSwitching=function(t,e){var r=this.altAudio,i=!!e.url,a=e.id;if(!i){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var s=this.fragCurrent;null!=s&&s.loader&&(this.log("Switching to main audio track, cancel main fragment load"),s.loader.abort()),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var o=this.hls;r&&o.trigger(n.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),o.trigger(n.a.AUDIO_TRACK_SWITCHED,{id:a})}},f.onAudioTrackSwitched=function(t,e){var r=e.id,i=!!this.hls.audioTracks[r].url;if(i){var a=this.videoBuffer;a&&this.mediaBuffer!==a&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=a)}this.altAudio=i,this.tick()},f.onBufferCreated=function(t,e){var r,i,a=e.tracks,n=!1;for(var s in a){var o=a[s];if("main"===o.id){if(i=s,r=o,"video"===s){var l=a[s];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&r?(this.log("Alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},f.onFragBuffered=function(t,e){var r=e.frag,i=e.part;if(!r||r.type===_.b.MAIN){if(this.fragContextChanged(r))return this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===Ot&&(this.state=_t));var a=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}},f.onError=function(t,e){switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:case s.a.KEY_LOAD_ERROR:case s.a.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(_.b.MAIN,e);break;case s.a.LEVEL_LOAD_ERROR:case s.a.LEVEL_LOAD_TIMEOUT:this.state!==Ft&&(e.fatal?(this.warn(""+e.details),this.state=Ft):e.levelRetry||this.state!==Mt||(this.state=_t));break;case s.a.BUFFER_FULL_ERROR:if("main"===e.parent&&(this.state===wt||this.state===Ot)){var r=!0,i=this.getFwdBufferInfo(this.media,_.b.MAIN);i&&i.len>.5&&(r=!this.reduceMaxBufferLength(i.len)),r&&(this.warn("buffer full error also media.currentTime is not buffered, flush main"),this.immediateLevelSwitch()),this.resetLoadingState()}}},f.checkBuffer=function(){var t=this.media,e=this.gapController;if(t&&e&&t.readyState){var r=nt.getBuffered(t);!this.loadedmetadata&&r.length?(this.loadedmetadata=!0,this.seekToStartPos()):e.poll(this.lastCurrentTime),this.lastCurrentTime=t.currentTime}},f.onFragLoadEmergencyAborted=function(){this.state=_t,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()},f.onBufferFlushed=function(t,e){var r=e.type;if(r!==u.a.AUDIO||this.audioOnly&&!this.altAudio){var i=(r===u.a.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,r,_.b.MAIN)}},f.onLevelsUpdated=function(t,e){this.levels=e.levels},f.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},f.seekToStartPos=function(){var t=this.media,e=t.currentTime,r=this.startPosition;if(r>=0&&e0&&(a1&&!1===t.seeking){var r=t.currentTime;if(nt.isBuffered(t,r)?e=this.getAppendedFrag(r):nt.isBuffered(t,r+.1)&&(e=this.getAppendedFrag(r+.1)),e){var i=this.fragPlaying,a=e.level;i&&e.sn===i.sn&&i.level===a&&e.urlId===i.urlId||(this.hls.trigger(n.a.FRAG_CHANGED,{frag:e}),i&&i.level===a||this.hls.trigger(n.a.LEVEL_SWITCHED,{level:a}),this.fragPlaying=e)}}},l=i,(d=[{key:"nextLevel",get:function(){var t=this.nextBufferedFrag;return t?t.level:-1}},{key:"currentLevel",get:function(){var t=this.media;if(t){var e=this.getAppendedFrag(t.currentTime);if(e)return e.level}return-1}},{key:"nextBufferedFrag",get:function(){var t=this.media;if(t){var e=this.getAppendedFrag(t.currentTime);return this.followingBufferedFrag(e)}return null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])&&Yt(l.prototype,d),h&&Yt(l,h),i}(Nt),zt=function(){function t(t,e,r){void 0===e&&(e=0),void 0===r&&(r=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=r}var e=t.prototype;return e.sample=function(t,e){var r=Math.pow(this.alpha_,t);this.estimate_=e*(1-r)+r*this.estimate_,this.totalWeight_+=t},e.getTotalWeight=function(){return this.totalWeight_},e.getEstimate=function(){if(this.alpha_){var t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_},t}(),Qt=function(){function t(t,e,r){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new zt(t),this.fast_=new zt(e)}var e=t.prototype;return e.update=function(t,e){var r=this.slow_,i=this.fast_;this.slow_.halfLife!==t&&(this.slow_=new zt(t,r.getEstimate(),r.getTotalWeight())),this.fast_.halfLife!==e&&(this.fast_=new zt(e,i.getEstimate(),i.getTotalWeight()))},e.sample=function(t,e){var r=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/r;this.fast_.sample(r,i),this.slow_.sample(r,i)},e.canEstimate=function(){var t=this.fast_;return t&&t.getTotalWeight()>=this.minWeight_},e.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},e.destroy=function(){},t}();function $t(t,e){for(var r=0;r=2*d/f||y<=T)){var E,S=Number.POSITIVE_INFINITY;for(E=t.level-1;E>v;E--){if((S=d*c[E].maxBitrate/(6.4*m))=y)){var L=this.bwEstimator.getEstimate();o.b.warn("Fragment "+t.sn+(e?" part "+e.index:"")+" of level "+t.level+" is loading too slowly and will cause an underbuffer; aborting and switching to level "+E+"\n Current BW estimate: "+(Object(a.a)(L)?(L/1024).toFixed(3):"Unknown")+" Kb/s\n Estimated load time for current fragment: "+y.toFixed(3)+" s\n Estimated load time for the next fragment: "+S.toFixed(3)+" s\n Time to underbuffer: "+T.toFixed(3)+" s"),r.nextLoadLevel=E,this.bwEstimator.sample(h,u.loaded),this.clearTimer(),t.loader&&(this.fragCurrent=this.partCurrent=null,t.loader.abort()),r.trigger(n.a.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:u})}}}}}},l.onFragLoaded=function(t,e){var r=e.frag,i=e.part;if(r.type===_.b.MAIN&&Object(a.a)(r.sn)){var s=i?i.stats:r.stats,o=i?i.duration:r.duration;if(this.clearTimer(),this.lastLoadedFragLevel=r.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){var l=this.hls.levels[r.level],u=(l.loaded?l.loaded.bytes:0)+s.loaded,d=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:u,duration:d},l.realBitrate=Math.round(8*u/d)}if(r.bitrateTest){var h={stats:s,frag:r,part:i,id:r.type};this.onFragBuffered(n.a.FRAG_BUFFERED,h),r.bitrateTest=!1}}},l.onFragBuffered=function(t,e){var r=e.frag,i=e.part,a=i?i.stats:r.stats;if(!a.aborted&&r.type===_.b.MAIN&&"initSegment"!==r.sn){var n=a.parsing.end-a.loading.start;this.bwEstimator.sample(n,a.loaded),a.bwEstimate=this.bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}},l.onError=function(t,e){switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:this.clearTimer()}},l.clearTimer=function(){self.clearInterval(this.timer),this.timer=void 0},l.getNextABRAutoLevel=function(){var t=this.fragCurrent,e=this.partCurrent,r=this.hls,i=r.maxAutoLevel,a=r.config,n=r.minAutoLevel,s=r.media,l=e?e.duration:t?t.duration:0,u=s?s.currentTime:0,d=s&&0!==s.playbackRate?Math.abs(s.playbackRate):1,h=this.bwEstimator?this.bwEstimator.getEstimate():a.abrEwmaDefaultEstimate,f=(nt.bufferInfo(s,u,a.maxBufferHole).end-u)/d,c=this.findBestLevel(h,n,i,f,a.abrBandWidthFactor,a.abrBandWidthUpFactor);if(c>=0)return c;o.b.trace((f?"rebuffering expected":"buffer is empty")+", finding optimal quality level");var v=l?Math.min(l,a.maxStarvationDelay):a.maxStarvationDelay,g=a.abrBandWidthFactor,p=a.abrBandWidthUpFactor;if(!f){var m=this.bitrateTestDelay;if(m)v=(l?Math.min(l,a.maxLoadingDelay):a.maxLoadingDelay)-m,o.b.trace("bitrate test took "+Math.round(1e3*m)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*v)+" ms"),g=p=1}return c=this.findBestLevel(h,n,i,f+v,g,p),Math.max(c,0)},l.findBestLevel=function(t,e,r,i,a,n){for(var s,l=this.fragCurrent,u=this.partCurrent,d=this.lastLoadedFragLevel,h=this.hls.levels,f=h[d],c=!(null==f||null===(s=f.details)||void 0===s||!s.live),v=null==f?void 0:f.codecSet,g=u?u.duration:l?l.duration:0,p=r;p>=e;p--){var m=h[p];if(m&&(!v||m.codecSet===v)){var y=m.details,b=(u?null==y?void 0:y.partTarget:null==y?void 0:y.averagetargetduration)||g,T=void 0;T=p<=d?a*t:n*t;var E=h[p].maxBitrate,S=E*b/T;if(o.b.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+p+"/"+Math.round(T)+"/"+E+"/"+b+"/"+i+"/"+S),T>E&&(!S||c&&!this.bitrateTestDelay||S0||Object.keys(this.pendingTracks).length>0},e.destroy=function(){this.unregisterListeners(),this.details=null},e.registerListeners=function(){var t=this.hls;t.on(n.a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(n.a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(n.a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(n.a.BUFFER_RESET,this.onBufferReset,this),t.on(n.a.BUFFER_APPENDING,this.onBufferAppending,this),t.on(n.a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(n.a.BUFFER_EOS,this.onBufferEos,this),t.on(n.a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(n.a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(n.a.FRAG_PARSED,this.onFragParsed,this),t.on(n.a.FRAG_CHANGED,this.onFragChanged,this)},e.unregisterListeners=function(){var t=this.hls;t.off(n.a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(n.a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(n.a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(n.a.BUFFER_RESET,this.onBufferReset,this),t.off(n.a.BUFFER_APPENDING,this.onBufferAppending,this),t.off(n.a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(n.a.BUFFER_EOS,this.onBufferEos,this),t.off(n.a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(n.a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(n.a.FRAG_PARSED,this.onFragParsed,this),t.off(n.a.FRAG_CHANGED,this.onFragChanged,this)},e._initSourceBuffer=function(){this.sourceBuffer={},this.operationQueue=new ee(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]}},e.onManifestParsed=function(t,e){var r=2;(e.audio&&!e.video||!e.altAudio)&&(r=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,this.details=null,o.b.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},e.onMediaAttaching=function(t,e){var r=this.media=e.media;if(r&&re){var i=this.mediaSource=new re;i.addEventListener("sourceopen",this._onMediaSourceOpen),i.addEventListener("sourceended",this._onMediaSourceEnded),i.addEventListener("sourceclose",this._onMediaSourceClose),r.src=self.URL.createObjectURL(i),this._objectUrl=r.src}},e.onMediaDetaching=function(){var t=this.media,e=this.mediaSource,r=this._objectUrl;if(e){if(o.b.log("[buffer-controller]: media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){o.b.warn("[buffer-controller]: onMediaDetaching: "+t.message+" while calling endOfStream")}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),t&&(r&&self.URL.revokeObjectURL(r),t.src===r?(t.removeAttribute("src"),t.load()):o.b.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(n.a.MEDIA_DETACHED,void 0)},e.onBufferReset=function(){var t=this;this.getSourceBufferTypes().forEach((function(e){var r=t.sourceBuffer[e];try{r&&(t.removeBufferListeners(e),t.mediaSource&&t.mediaSource.removeSourceBuffer(r),t.sourceBuffer[e]=void 0)}catch(t){o.b.warn("[buffer-controller]: Failed to reset the "+e+" buffer",t)}})),this._initSourceBuffer()},e.onBufferCodecs=function(t,e){var r=this,i=this.getSourceBufferTypes().length;Object.keys(e).forEach((function(t){if(i){var a=r.tracks[t];if(a&&"function"==typeof a.buffer.changeType){var n=e[t],s=n.codec,o=n.levelCodec,l=n.container;if((a.levelCodec||a.codec).replace(ie,"$1")!==(o||s).replace(ie,"$1")){var u=l+";codecs="+(o||s);r.appendChangeType(t,u)}}}else r.pendingTracks[t]=e[t]})),i||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())},e.appendChangeType=function(t,e){var r=this,i=this.operationQueue,a={execute:function(){var a=r.sourceBuffer[t];a&&(o.b.log("[buffer-controller]: changing "+t+" sourceBuffer type to "+e),a.changeType(e)),i.shiftAndExecuteNext(t)},onStart:function(){},onComplete:function(){},onError:function(e){o.b.warn("[buffer-controller]: Failed to change "+t+" SourceBuffer type",e)}};i.append(a,t)},e.onBufferAppending=function(t,e){var r=this,i=this.hls,a=this.operationQueue,l=this.tracks,u=e.data,d=e.type,h=e.frag,f=e.part,c=e.chunkMeta,v=c.buffering[d],g=self.performance.now();v.start=g;var p=h.stats.buffering,m=f?f.stats.buffering:null;0===p.start&&(p.start=g),m&&0===m.start&&(m.start=g);var y=l.audio,b="audio"===d&&1===c.id&&"audio/mpeg"===(null==y?void 0:y.container),T={execute:function(){if(v.executeStart=self.performance.now(),b){var t=r.sourceBuffer[d];if(t){var e=h.start-t.timestampOffset;Math.abs(e)>=.1&&(o.b.log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to "+h.start+" (delta: "+e+") sn: "+h.sn+")"),t.timestampOffset=h.start)}}r.appendExecutor(u,d)},onStart:function(){},onComplete:function(){var t=self.performance.now();v.executeEnd=v.end=t,0===p.first&&(p.first=t),m&&0===m.first&&(m.first=t);var e=r.sourceBuffer,i={};for(var a in e)i[a]=nt.getBuffered(e[a]);r.appendError=0,r.hls.trigger(n.a.BUFFER_APPENDED,{type:d,frag:h,part:f,chunkMeta:c,parent:h.type,timeRanges:i})},onError:function(t){o.b.error("[buffer-controller]: Error encountered while trying to append to the "+d+" SourceBuffer",t);var e={type:s.b.MEDIA_ERROR,parent:h.type,details:s.a.BUFFER_APPEND_ERROR,err:t,fatal:!1};t.code===DOMException.QUOTA_EXCEEDED_ERR?e.details=s.a.BUFFER_FULL_ERROR:(r.appendError++,e.details=s.a.BUFFER_APPEND_ERROR,r.appendError>i.config.appendErrorMaxRetry&&(o.b.error("[buffer-controller]: Failed "+i.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),e.fatal=!0)),i.trigger(n.a.ERROR,e)}};a.append(T,d)},e.onBufferFlushing=function(t,e){var r=this,i=this.operationQueue,a=function(t){return{execute:r.removeExecutor.bind(r,t,e.startOffset,e.endOffset),onStart:function(){},onComplete:function(){r.hls.trigger(n.a.BUFFER_FLUSHED,{type:t})},onError:function(e){o.b.warn("[buffer-controller]: Failed to remove from "+t+" SourceBuffer",e)}}};e.type?i.append(a(e.type),e.type):this.getSourceBufferTypes().forEach((function(t){i.append(a(t),t)}))},e.onFragParsed=function(t,e){var r=this,i=e.frag,a=e.part,s=[],l=a?a.elementaryStreams:i.elementaryStreams;l[u.a.AUDIOVIDEO]?s.push("audiovideo"):(l[u.a.AUDIO]&&s.push("audio"),l[u.a.VIDEO]&&s.push("video"));0===s.length&&o.b.warn("Fragments must have at least one ElementaryStreamType set. type: "+i.type+" level: "+i.level+" sn: "+i.sn),this.blockBuffers((function(){var t=self.performance.now();i.stats.buffering.end=t,a&&(a.stats.buffering.end=t);var e=a?a.stats:i.stats;r.hls.trigger(n.a.FRAG_BUFFERED,{frag:i,part:a,stats:e,id:i.type})}),s)},e.onFragChanged=function(t,e){this.flushBackBuffer()},e.onBufferEos=function(t,e){var r=this;this.getSourceBufferTypes().reduce((function(t,i){var a=r.sourceBuffer[i];return e.type&&e.type!==i||a&&!a.ended&&(a.ended=!0,o.b.log("[buffer-controller]: "+i+" sourceBuffer now EOS")),t&&!(a&&!a.ended)}),!0)&&this.blockBuffers((function(){var t=r.mediaSource;t&&"open"===t.readyState&&t.endOfStream()}))},e.onLevelUpdated=function(t,e){var r=e.details;r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())},e.flushBackBuffer=function(){var t=this.hls,e=this.details,r=this.media,i=this.sourceBuffer;if(r&&null!==e){var s=this.getSourceBufferTypes();if(s.length){var o=e.live&&null!==t.config.liveBackBufferLength?t.config.liveBackBufferLength:t.config.backBufferLength;if(Object(a.a)(o)&&!(o<0)){var l=r.currentTime,u=e.levelTargetDuration,d=Math.max(o,u),h=Math.floor(l/u)*u-d;s.forEach((function(r){var a=i[r];if(a){var s=nt.getBuffered(a);s.length>0&&h>s.start(0)&&(t.trigger(n.a.BACK_BUFFER_REACHED,{bufferEnd:h}),e.live&&t.trigger(n.a.LIVE_BACK_BUFFER_REACHED,{bufferEnd:h}),t.trigger(n.a.BUFFER_FLUSHING,{startOffset:0,endOffset:h,type:r}))}}))}}}},e.updateMediaElementDuration=function(){if(this.details&&this.media&&this.mediaSource&&"open"===this.mediaSource.readyState){var t=this.details,e=this.hls,r=this.media,i=this.mediaSource,n=t.fragments[0].start+t.totalduration,s=r.duration,l=Object(a.a)(i.duration)?i.duration:0;t.live&&e.config.liveDurationInfinity?(o.b.log("[buffer-controller]: Media Source duration is set to Infinity"),i.duration=1/0,this.updateSeekableRange(t)):(n>l&&n>s||!Object(a.a)(s))&&(o.b.log("[buffer-controller]: Updating Media Source duration to "+n.toFixed(3)),i.duration=n)}},e.updateSeekableRange=function(t){var e=this.mediaSource,r=t.fragments;if(r.length&&t.live&&null!=e&&e.setLiveSeekableRange){var i=Math.max(0,r[0].start),a=Math.max(i,i+t.totalduration);e.setLiveSeekableRange(i,a)}},e.checkPendingTracks=function(){var t=this.bufferCodecEventsExpected,e=this.operationQueue,r=this.pendingTracks,i=Object.keys(r).length;if(i&&!t||2===i){this.createSourceBuffers(r),this.pendingTracks={};var a=this.getSourceBufferTypes();if(0===a.length)return void this.hls.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,reason:"could not create source buffer for media codec(s)"});a.forEach((function(t){e.executeNext(t)}))}},e.createSourceBuffers=function(t){var e=this.sourceBuffer,r=this.mediaSource;if(!r)throw Error("createSourceBuffers called when mediaSource was null");var i=0;for(var a in t)if(!e[a]){var l=t[a];if(!l)throw Error("source buffer exists for track "+a+", however track does not");var u=l.levelCodec||l.codec,d=l.container+";codecs="+u;o.b.log("[buffer-controller]: creating sourceBuffer("+d+")");try{var h=e[a]=r.addSourceBuffer(d),f=a;this.addBufferListener(f,"updatestart",this._onSBUpdateStart),this.addBufferListener(f,"updateend",this._onSBUpdateEnd),this.addBufferListener(f,"error",this._onSBUpdateError),this.tracks[a]={buffer:h,codec:u,container:l.container,levelCodec:l.levelCodec,id:l.id},i++}catch(t){o.b.error("[buffer-controller]: error while trying to add sourceBuffer: "+t.message),this.hls.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,mimeType:d})}}i&&this.hls.trigger(n.a.BUFFER_CREATED,{tracks:this.tracks})},e._onSBUpdateStart=function(t){this.operationQueue.current(t).onStart()},e._onSBUpdateEnd=function(t){var e=this.operationQueue;e.current(t).onComplete(),e.shiftAndExecuteNext(t)},e._onSBUpdateError=function(t,e){o.b.error("[buffer-controller]: "+t+" SourceBuffer error",e),this.hls.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_APPENDING_ERROR,fatal:!1});var r=this.operationQueue.current(t);r&&r.onError(e)},e.removeExecutor=function(t,e,r){var i=this.media,n=this.mediaSource,s=this.operationQueue,l=this.sourceBuffer[t];if(!i||!n||!l)return o.b.warn("[buffer-controller]: Attempting to remove from the "+t+" SourceBuffer, but it does not exist"),void s.shiftAndExecuteNext(t);var u=Object(a.a)(i.duration)?i.duration:1/0,d=Object(a.a)(n.duration)?n.duration:1/0,h=Math.max(0,e),f=Math.min(r,u,d);f>h?(o.b.log("[buffer-controller]: Removing ["+h+","+f+"] from the "+t+" SourceBuffer"),l.remove(h,f)):s.shiftAndExecuteNext(t)},e.appendExecutor=function(t,e){var r=this.operationQueue,i=this.sourceBuffer[e];if(!i)return o.b.warn("[buffer-controller]: Attempting to append to the "+e+" SourceBuffer, but it does not exist"),void r.shiftAndExecuteNext(e);i.ended=!1,i.appendBuffer(t)},e.blockBuffers=function(t,e){var r=this;if(void 0===e&&(e=this.getSourceBufferTypes()),!e.length)return o.b.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve(t);var i=this.operationQueue,a=e.map((function(t){return i.appendBlocker(t)}));Promise.all(a).then((function(){t(),e.forEach((function(t){var e=r.sourceBuffer[t];e&&e.updating||i.shiftAndExecuteNext(t)}))}))},e.getSourceBufferTypes=function(){return Object.keys(this.sourceBuffer)},e.addBufferListener=function(t,e,r){var i=this.sourceBuffer[t];if(i){var a=r.bind(this,t);this.listeners[t].push({event:e,listener:a}),i.addEventListener(e,a)}},e.removeBufferListeners=function(t){var e=this.sourceBuffer[t];e&&this.listeners[t].forEach((function(t){e.removeEventListener(t.event,t.listener)}))},t}();function ne(t,e){for(var r=0;r0&&this.mediaWidth>0){var t=this.hls.levels;if(t.length){var e=this.hls;e.autoLevelCapping=this.getMaxLevel(t.length-1),e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}},a.getMaxLevel=function(e){var r=this,i=this.hls.levels;if(!i.length)return-1;var a=i.filter((function(i,a){return t.isLevelAllowed(a,r.restrictedLevels)&&a<=e}));return this.clientRect=null,t.getMaxLevelByMediaSize(a,this.mediaWidth,this.mediaHeight)},a.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},a.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},a.getDimensions=function(){if(this.clientRect)return this.clientRect;var t=this.media,e={width:0,height:0};if(t){var r=t.getBoundingClientRect();e.width=r.width,e.height=r.height,e.width||e.height||(e.width=r.right-r.left||t.width||0,e.height=r.bottom-r.top||t.height||0)}return this.clientRect=e,e},t.isLevelAllowed=function(t,e){return void 0===e&&(e=[]),-1===e.indexOf(t)},t.getMaxLevelByMediaSize=function(t,e,r){if(!t||!t.length)return-1;for(var i,a,n=t.length-1,s=0;s=e||o.height>=r)&&(i=o,!(a=t[s+1])||i.width!==a.width||i.height!==a.height)){n=s;break}}return n},e=t,i=[{key:"contentScaleFactor",get:function(){var t=1;try{t=self.devicePixelRatio}catch(t){}return t}}],(r=[{key:"mediaWidth",get:function(){return this.getDimensions().width*t.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*t.contentScaleFactor}}])&&ne(e.prototype,r),i&&ne(e,i),t}(),oe=function(){function t(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}var e=t.prototype;return e.setStreamController=function(t){this.streamController=t},e.registerListeners=function(){this.hls.on(n.a.MEDIA_ATTACHING,this.onMediaAttaching,this)},e.unregisterListeners=function(){this.hls.off(n.a.MEDIA_ATTACHING,this.onMediaAttaching)},e.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},e.onMediaAttaching=function(t,e){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},e.checkFPS=function(t,e,r){var i=performance.now();if(e){if(this.lastTime){var a=i-this.lastTime,s=r-this.lastDroppedFrames,l=e-this.lastDecodedFrames,u=1e3*s/a,d=this.hls;if(d.trigger(n.a.FPS_DROP,{currentDropped:s,currentDecoded:l,totalDroppedFrames:r}),u>0&&s>d.config.fpsDroppedMonitoringThreshold*l){var h=d.currentLevel;o.b.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(-1===d.autoLevelCapping||d.autoLevelCapping>=h)&&(h-=1,d.trigger(n.a.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:d.currentLevel}),d.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=e}},e.checkFPSInterval=function(){var t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){var e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)},t}(),le=r(12),ue=/^age:\s*[\d.]+\s*$/m,de=function(){function t(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=t?t.xhrSetup:null,this.stats=new le.a,this.retryDelay=0}var e=t.prototype;return e.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null},e.abortInternal=function(){var t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))},e.abort=function(){var t;this.abortInternal(),null!==(t=this.callbacks)&&void 0!==t&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},e.load=function(t,e,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=r,this.retryDelay=e.retryDelay,this.loadInternal()},e.loadInternal=function(){var t=this.config,e=this.context;if(t){var r=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0;var a=this.xhrSetup;try{if(a)try{a(r,e.url)}catch(t){r.open("GET",e.url,!0),a(r,e.url)}r.readyState||r.open("GET",e.url,!0);var n=this.context.headers;if(n)for(var s in n)r.setRequestHeader(s,n[s])}catch(t){return void this.callbacks.onError({code:r.status,text:t.message},e,r)}e.rangeEnd&&r.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),r.onreadystatechange=this.readystatechange.bind(this),r.onprogress=this.loadprogress.bind(this),r.responseType=e.responseType,self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),t.timeout),r.send()}},e.readystatechange=function(){var t=this.context,e=this.loader,r=this.stats;if(t&&e){var i=e.readyState,a=this.config;if(!r.aborted&&i>=2)if(self.clearTimeout(this.requestTimeout),0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start)),4===i){e.onreadystatechange=null,e.onprogress=null;var n=e.status;if(n>=200&&n<300){var s,l;if(r.loading.end=Math.max(self.performance.now(),r.loading.first),l="arraybuffer"===t.responseType?(s=e.response).byteLength:(s=e.responseText).length,r.loaded=r.total=l,!this.callbacks)return;var u=this.callbacks.onProgress;if(u&&u(r,t,s,e),!this.callbacks)return;var d={url:e.responseURL,data:s};this.callbacks.onSuccess(d,r,t,e)}else r.retry>=a.maxRetry||n>=400&&n<499?(o.b.error(n+" while loading "+t.url),this.callbacks.onError({code:n,text:e.statusText},t,e)):(o.b.warn(n+" while loading "+t.url+", retrying in "+this.retryDelay+"..."),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,a.maxRetryDelay),r.retry++)}else self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),a.timeout)}},e.loadtimeout=function(){o.b.warn("timeout while loading "+this.context.url);var t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))},e.loadprogress=function(t){var e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)},e.getCacheAge=function(){var t=null;if(this.loader&&ue.test(this.loader.getAllResponseHeaders())){var e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t},t}(),he=r(16);function fe(t){var e="function"==typeof Map?new Map:void 0;return(fe=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,i)}function i(){return ce(t,arguments,pe(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),ge(i,t)})(t)}function ce(t,e,r){return(ce=ve()?Reflect.construct:function(t,e,r){var i=[null];i.push.apply(i,e);var a=new(Function.bind.apply(t,i));return r&&ge(a,r.prototype),a}).apply(null,arguments)}function ve(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function ge(t,e){return(ge=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function pe(t){return(pe=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function me(){return(me=Object.assign||function(t){for(var e=1;e=i&&a(e,r,n.flush(),t)):a(e,r,l,t),o()})).catch((function(){return Promise.reject()}))}()},t}();function be(t,e){return new self.Request(t.url,e)}var Te,Ee=function(t){var e,r;function i(e,r,i){var a;return(a=t.call(this,e)||this).code=void 0,a.details=void 0,a.code=r,a.details=i,a}return r=t,(e=i).prototype=Object.create(r.prototype),e.prototype.constructor=e,ge(e,r),i}(fe(Error)),Se=ye;!function(t){t.WIDEVINE="com.widevine.alpha",t.PLAYREADY="com.microsoft.playready"}(Te||(Te={}));var Le="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Ae(){return(Ae=Object.assign||function(t){for(var e=1;ee)return i;return 0}},{key:"maxAutoLevel",get:function(){var t=this.levels,e=this.autoLevelCapping;return-1===e&&t&&t.length?t.length-1:e}},{key:"nextAutoLevel",get:function(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)},set:function(t){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,t)}},{key:"audioTracks",get:function(){var t=this.audioTrackController;return t?t.audioTracks:[]}},{key:"audioTrack",get:function(){var t=this.audioTrackController;return t?t.audioTrack:-1},set:function(t){var e=this.audioTrackController;e&&(e.audioTrack=t)}},{key:"subtitleTracks",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTrack:-1},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var t=this.subtitleTrackController;return!!t&&t.subtitleDisplay},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(t){this.config.lowLatencyMode=t}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}}])&&Ce(e.prototype,r),a&&Ce(e,a),t}();we.defaultConfig=void 0}]).default})); // @license-end \ No newline at end of file From 5e827c91aa1b5f41cc03c5bb07b6fe629002430b Mon Sep 17 00:00:00 2001 From: HookedBehemoth Date: Thu, 16 Jun 2022 18:46:41 +0200 Subject: [PATCH 04/68] emit body and doctype on iframe embed endpoint (#640) --- src/routes/embed.nim | 2 +- src/views/embed.nim | 5 +++-- src/views/tweet.nim | 14 +++++++++++--- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/routes/embed.nim b/src/routes/embed.nim index 8690357..baaec68 100644 --- a/src/routes/embed.nim +++ b/src/routes/embed.nim @@ -25,7 +25,7 @@ proc createEmbedRouter*(cfg: Config) = if convo == nil or convo.tweet == nil: resp Http404 - resp $renderTweetEmbed(convo.tweet, path, prefs, cfg, request) + resp renderTweetEmbed(convo.tweet, path, prefs, cfg, request) get "/embed/Tweet.html": let id = @"id" diff --git a/src/views/embed.nim b/src/views/embed.nim index e6afffd..a884cf3 100644 --- a/src/views/embed.nim +++ b/src/views/embed.nim @@ -15,7 +15,8 @@ proc renderVideoEmbed*(tweet: Tweet; cfg: Config; req: Request): string = let node = buildHtml(html(lang="en")): renderHead(prefs, cfg, req, video=vidUrl, images=(@[thumb])) - tdiv(class="embed-video"): - renderVideo(get(tweet.video), prefs, "") + body: + tdiv(class="embed-video"): + renderVideo(get(tweet.video), prefs, "") result = doctype & $node diff --git a/src/views/tweet.nim b/src/views/tweet.nim index 5bee864..daad61a 100644 --- a/src/views/tweet.nim +++ b/src/views/tweet.nim @@ -7,6 +7,9 @@ import renderutils import ".."/[types, utils, formatters] import general +const + doctype = "\n" + proc getSmallPic(url: string): string = result = url if "?" notin url and not url.endsWith("placeholder.png"): @@ -364,7 +367,12 @@ proc renderTweet*(tweet: Tweet; prefs: Prefs; path: string; class=""; index=0; a(class="show-thread", href=("/i/status/" & $tweet.threadId)): text "Show this thread" -proc renderTweetEmbed*(tweet: Tweet; path: string; prefs: Prefs; cfg: Config; req: Request): VNode = - buildHtml(tdiv(class="tweet-embed")): +proc renderTweetEmbed*(tweet: Tweet; path: string; prefs: Prefs; cfg: Config; req: Request): string = + let node = buildHtml(html(lang="en")): renderHead(prefs, cfg, req) - renderTweet(tweet, prefs, path, mainTweet=true) + + body: + tdiv(class="tweet-embed"): + renderTweet(tweet, prefs, path, mainTweet=true) + + result = doctype & $node From 81ec41328d5684dd395f584254d723abee213ac0 Mon Sep 17 00:00:00 2001 From: Jules Bertholet Date: Thu, 23 Jun 2022 16:47:03 -0400 Subject: [PATCH 05/68] Add redirect for `thread` links (#647) --- src/routes/status.nim | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/routes/status.nim b/src/routes/status.nim index 0303152..1104282 100644 --- a/src/routes/status.nim +++ b/src/routes/status.nim @@ -72,3 +72,6 @@ proc createStatusRouter*(cfg: Config) = get "/i/web/status/@id": redirect("/i/status/" & @"id") + + get "/@name/thread/@id/?": + redirect("/$1/status/$2" % [@"name", @"id"]) From 0200cc21a32e0ed87025744066894cdc26f73ff3 Mon Sep 17 00:00:00 2001 From: flywind <43030857+xflywind@users.noreply.github.com> Date: Tue, 5 Jul 2022 15:15:38 +0800 Subject: [PATCH 06/68] add `threads:off` to config file (#662) --- config.nims | 1 + 1 file changed, 1 insertion(+) diff --git a/config.nims b/config.nims index ee77289..b7e52d0 100644 --- a/config.nims +++ b/config.nims @@ -1,5 +1,6 @@ --define:ssl --define:useStdLib +--threads:off # workaround httpbeast file upload bug --assertions:off From 17cb977e70cfefe505b3d294609aa69098e2f9e8 Mon Sep 17 00:00:00 2001 From: jackyzy823 Date: Sun, 17 Jul 2022 17:42:40 +0100 Subject: [PATCH 07/68] fix profile-website css (#669) --- src/sass/profile/card.scss | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sass/profile/card.scss b/src/sass/profile/card.scss index cc68d7d..85878e4 100644 --- a/src/sass/profile/card.scss +++ b/src/sass/profile/card.scss @@ -73,9 +73,9 @@ } } - .profile-joindate, .profile-location, profile-website { + .profile-joindate, .profile-location, .profile-website { color: var(--fg_faded); - margin: 2px 0; + margin: 1px 0; width: 100%; } } From 5f31e86e0e8578377fa7d5aeb9631bbb2d35ef1e Mon Sep 17 00:00:00 2001 From: Mico Date: Thu, 21 Jul 2022 16:04:27 +0300 Subject: [PATCH 08/68] Fixes selection issues on iOS devices (#671) --- src/sass/tweet/_base.scss | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/sass/tweet/_base.scss b/src/sass/tweet/_base.scss index b5410f5..549298a 100644 --- a/src/sass/tweet/_base.scss +++ b/src/sass/tweet/_base.scss @@ -100,6 +100,7 @@ .avatar { &.round { border-radius: 50%; + -webkit-user-select: none; } &.mini { @@ -200,6 +201,7 @@ .tweet-stats { margin-bottom: -3px; + -webkit-user-select: none; } .tweet-stat { @@ -231,6 +233,7 @@ left: 0; top: 0; position: absolute; + -webkit-user-select: none; &:hover { background-color: var(--bg_hover); From 077ebc95fa5c3e7700581f66ba19ee313edee46a Mon Sep 17 00:00:00 2001 From: jackyzy823 Date: Mon, 15 Aug 2022 00:07:40 +0100 Subject: [PATCH 09/68] make video control bar fit parent div (#683) --- src/sass/tweet/video.scss | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sass/tweet/video.scss b/src/sass/tweet/video.scss index 2dd257a..1e9096e 100644 --- a/src/sass/tweet/video.scss +++ b/src/sass/tweet/video.scss @@ -3,7 +3,7 @@ video { max-height: 100%; - max-width: 100%; + width: 100%; } .gallery-video { From 8edfda39ecb36855d66b51cd706b08c77602de28 Mon Sep 17 00:00:00 2001 From: ringabout <43030857+ringabout@users.noreply.github.com> Date: Tue, 30 Aug 2022 15:18:46 +0800 Subject: [PATCH 10/68] bump `packedjson` dependency to include a fix for ARC/ORC (#691) Hello. `shallowCopy` has been removed for ARC/ORC since it does a deep copy for strings/seqs, which breaks the semantics of `shallowCopy`. https://github.com/Araq/packedjson/pull/13 is a fix for `packedjson` to support ARC/ORC. The PR bumps `packedjson` dependency to include [a fix](https://github.com/Araq/packedjson/commit/9e6fbb63cb9e0ab8ff570c04bec28cc713ca1f7c) for ARC/ORC. --- nitter.nimble | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nitter.nimble b/nitter.nimble index 90a7921..4dcb946 100644 --- a/nitter.nimble +++ b/nitter.nimble @@ -16,7 +16,7 @@ requires "karax#5498909" requires "sass#e683aa1" requires "nimcrypto#a5742a9" requires "markdown#a661c26" -requires "packedjson#d11d167" +requires "packedjson#9e6fbb6" requires "supersnappy#2.1.1" requires "redpool#8b7c1db" requires "https://github.com/zedeus/redis#d0a0e6f" From 1cf8e6756707b9841fea39915e154bb2ef03c1c7 Mon Sep 17 00:00:00 2001 From: ringabout <43030857+ringabout@users.noreply.github.com> Date: Thu, 15 Sep 2022 20:47:02 +0800 Subject: [PATCH 11/68] bump karax version (#694) Co-authored-by: xflywind <43030857+xflywind@users.noreply.github.com> --- nitter.nimble | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nitter.nimble b/nitter.nimble index 4dcb946..72863bd 100644 --- a/nitter.nimble +++ b/nitter.nimble @@ -12,7 +12,7 @@ bin = @["nitter"] requires "nim >= 1.4.8" requires "jester >= 0.5.0" -requires "karax#5498909" +requires "karax#6abcb77" requires "sass#e683aa1" requires "nimcrypto#a5742a9" requires "markdown#a661c26" From 2ac3afa5b273a502d7632e9346c7c3bc9283fb48 Mon Sep 17 00:00:00 2001 From: Zed Date: Wed, 21 Sep 2022 05:47:16 +0200 Subject: [PATCH 12/68] Retry intermittent 401 Unauthorized requests --- src/apiutils.nim | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/apiutils.nim b/src/apiutils.nim index fd6960f..77ff368 100644 --- a/src/apiutils.nim +++ b/src/apiutils.nim @@ -61,12 +61,22 @@ template fetchImpl(result, fetchBody) {.dirty.} = try: var resp: AsyncResponse pool.use(genHeaders(token)): - resp = await c.get($url) - result = await resp.body + template getContent = + resp = await c.get($url) + result = await resp.body - if resp.status == $Http503: - badClient = true - raise newException(InternalError, result) + getContent() + + # Twitter randomly returns 401 errors with an empty body quite often. + # Retrying the request usually works. + var attempt = 0 + while resp.status == "401 Unauthorized" and result.len == 0 and attempt < 3: + inc attempt + getContent() + + if resp.status == $Http503: + badClient = true + raise newException(InternalError, result) if result.len > 0: if resp.headers.getOrDefault("content-encoding") == "gzip": From 6272297d64d4cc8f1268626bee31a0e3d5899f51 Mon Sep 17 00:00:00 2001 From: Kavin <20838718+FireMasterK@users.noreply.github.com> Date: Sat, 19 Nov 2022 02:47:29 +0000 Subject: [PATCH 13/68] Update hostname for piped (#728) --- nitter.example.conf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nitter.example.conf b/nitter.example.conf index b987cd5..cc7551a 100644 --- a/nitter.example.conf +++ b/nitter.example.conf @@ -37,7 +37,7 @@ tokenCount = 10 [Preferences] theme = "Nitter" replaceTwitter = "nitter.net" -replaceYouTube = "piped.kavin.rocks" +replaceYouTube = "piped.video" replaceReddit = "teddit.net" replaceInstagram = "" proxyVideos = true From 02557b67c39831005690118b651cc03e719d8735 Mon Sep 17 00:00:00 2001 From: Zed Date: Sun, 27 Nov 2022 00:03:11 +0100 Subject: [PATCH 14/68] Fix minor bug --- src/parserutils.nim | 8 ++++---- src/routes/rss.nim | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/parserutils.nim b/src/parserutils.nim index 51ccea5..4b89236 100644 --- a/src/parserutils.nim +++ b/src/parserutils.nim @@ -28,13 +28,13 @@ template `?`*(js: JsonNode): untyped = if j.isNull: return j -template `with`*(ident, value, body): untyped = - block: +template with*(ident, value, body): untyped = + if true: let ident {.inject.} = value if ident != nil: body -template `with`*(ident; value: JsonNode; body): untyped = - block: +template with*(ident; value: JsonNode; body): untyped = + if true: let ident {.inject.} = value if value.notNull: body diff --git a/src/routes/rss.nim b/src/routes/rss.nim index 700c215..2b23d0a 100644 --- a/src/routes/rss.nim +++ b/src/routes/rss.nim @@ -1,5 +1,5 @@ # SPDX-License-Identifier: AGPL-3.0-only -import asyncdispatch, strutils, strformat, tables, times, hashes, uri +import asyncdispatch, tables, times, hashes, uri import jester From dd184715681ff311e5cd58be25f86022a47d3644 Mon Sep 17 00:00:00 2001 From: Zed Date: Sun, 27 Nov 2022 00:28:49 +0100 Subject: [PATCH 15/68] Make YouTube regex case insensitive Fixes #726 --- src/formatters.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/formatters.nim b/src/formatters.nim index 28bfa1c..96b3612 100644 --- a/src/formatters.nim +++ b/src/formatters.nim @@ -12,7 +12,7 @@ let twRegex = re"(?<=(?twitter\.com(\S+)""" - ytRegex = re"([A-z.]+\.)?youtu(be\.com|\.be)" + ytRegex = re(r"([A-z.]+\.)?youtu(be\.com|\.be)", {reStudy, reIgnoreCase}) igRegex = re"(www\.)?instagram\.com" rdRegex = re"(? Date: Sun, 27 Nov 2022 00:40:33 +0100 Subject: [PATCH 16/68] Revert /c/ removal from YouTube replacer Fixes #724 --- src/formatters.nim | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/formatters.nim b/src/formatters.nim index 96b3612..7b939ca 100644 --- a/src/formatters.nim +++ b/src/formatters.nim @@ -56,8 +56,6 @@ proc replaceUrls*(body: string; prefs: Prefs; absolute=""): string = if prefs.replaceYouTube.len > 0 and "youtu" in result: result = result.replace(ytRegex, prefs.replaceYouTube) - if prefs.replaceYouTube in result: - result = result.replace("/c/", "/") if prefs.replaceTwitter.len > 0 and ("twitter.com" in body or tco in body): result = result.replace(tco, &"{https}{prefs.replaceTwitter}/t.co") From 9ef0f649fd575876c0abe4d35af6d2f2ca07c12e Mon Sep 17 00:00:00 2001 From: Zed Date: Sun, 27 Nov 2022 00:59:54 +0100 Subject: [PATCH 17/68] Bump dependencies --- nitter.nimble | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/nitter.nimble b/nitter.nimble index 72863bd..a4d2e87 100644 --- a/nitter.nimble +++ b/nitter.nimble @@ -11,17 +11,17 @@ bin = @["nitter"] # Dependencies requires "nim >= 1.4.8" -requires "jester >= 0.5.0" +requires "jester#baca3f" requires "karax#6abcb77" requires "sass#e683aa1" -requires "nimcrypto#a5742a9" +requires "nimcrypto#b41129f" requires "markdown#a661c26" requires "packedjson#9e6fbb6" -requires "supersnappy#2.1.1" +requires "supersnappy#6c94198" requires "redpool#8b7c1db" requires "https://github.com/zedeus/redis#d0a0e6f" -requires "zippy#0.9.11" -requires "flatty#0.2.3" +requires "zippy#61922b9" +requires "flatty#9f885d7" requires "jsony#d0e69bd" From b1ef505cffe075a4c988c9989a4e9d81e65a5266 Mon Sep 17 00:00:00 2001 From: Zed Date: Sun, 27 Nov 2022 01:57:32 +0100 Subject: [PATCH 18/68] Fix "Show this thread" for pinned threads --- src/parser.nim | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/parser.nim b/src/parser.nim index b731bdb..10186be 100644 --- a/src/parser.nim +++ b/src/parser.nim @@ -206,6 +206,10 @@ proc parseTweet(js: JsonNode): Tweet = ) ) + # fix for pinned threads + if result.hasThread and result.threadId == 0: + result.threadId = js{"self_thread", "id_str"}.getId + result.expandTweetEntities(js) if js{"is_quote_status"}.getBool: From 92a6eb0339b8288ce6af4e51c6b5198b1ce0d823 Mon Sep 17 00:00:00 2001 From: Zed Date: Sun, 27 Nov 2022 12:49:50 +0100 Subject: [PATCH 19/68] Bump Dockerfile Nim to 1.6.10 --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 52dadf6..f65c3ed 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM nimlang/nim:1.6.2-alpine-regular as nim +FROM nimlang/nim:1.6.10-alpine-regular as nim LABEL maintainer="setenforce@protonmail.com" RUN apk --no-cache add libsass-dev pcre From 85316f8f8d265ea4449e7166c1f6651fb595c41d Mon Sep 17 00:00:00 2001 From: Zed Date: Sun, 27 Nov 2022 15:50:08 +0100 Subject: [PATCH 20/68] Reduce usage of strformat, minor perf improvement --- src/formatters.nim | 4 ++-- src/routes/rss.nim | 51 ++++++++++++++++++++++------------------- src/routes/search.nim | 4 ++-- src/routes/timeline.nim | 4 ++-- src/views/general.nim | 2 +- src/views/profile.nim | 2 +- 6 files changed, 36 insertions(+), 31 deletions(-) diff --git a/src/formatters.nim b/src/formatters.nim index 7b939ca..87ff647 100644 --- a/src/formatters.nim +++ b/src/formatters.nim @@ -58,11 +58,11 @@ proc replaceUrls*(body: string; prefs: Prefs; absolute=""): string = result = result.replace(ytRegex, prefs.replaceYouTube) if prefs.replaceTwitter.len > 0 and ("twitter.com" in body or tco in body): - result = result.replace(tco, &"{https}{prefs.replaceTwitter}/t.co") + result = result.replace(tco, https & prefs.replaceTwitter & "/t.co") result = result.replace(cards, prefs.replaceTwitter & "/cards") result = result.replace(twRegex, prefs.replaceTwitter) result = result.replacef(twLinkRegex, a( - prefs.replaceTwitter & "$2", href = &"{https}{prefs.replaceTwitter}$1")) + prefs.replaceTwitter & "$2", href = https & prefs.replaceTwitter & "$1")) if prefs.replaceReddit.len > 0 and ("reddit.com" in result or "redd.it" in result): result = result.replace(rdShortRegex, prefs.replaceReddit & "/comments/") diff --git a/src/routes/rss.nim b/src/routes/rss.nim index 2b23d0a..5da29b0 100644 --- a/src/routes/rss.nim +++ b/src/routes/rss.nim @@ -10,6 +10,11 @@ include "../views/rss.nimf" export times, hashes +proc redisKey*(page, name, cursor: string): string = + result = page & ":" & name + if cursor.len > 0: + result &= ":" & cursor + proc timelineRss*(req: Request; cfg: Config; query: Query): Future[Rss] {.async.} = var profile: Profile let @@ -42,8 +47,8 @@ proc timelineRss*(req: Request; cfg: Config; query: Query): Future[Rss] {.async. template respRss*(rss, page) = if rss.cursor.len == 0: let info = case page - of "User": &""" "{@"name"}" """ - of "List": &""" "{@"id"}" """ + of "User": " \"" & @"name" & "\" " + of "List": " \"" & @"id" & "\" " else: " " resp Http404, showError(page & info & "not found", cfg) @@ -67,7 +72,7 @@ proc createRssRouter*(cfg: Config) = let cursor = getCursor() - key = &"search:{hash(genQueryUrl(query))}:cursor" + key = redisKey("search", $hash(genQueryUrl(query)), cursor) var rss = await getCachedRss(key) if rss.cursor.len > 0: @@ -84,9 +89,8 @@ proc createRssRouter*(cfg: Config) = cond cfg.enableRss cond '.' notin @"name" let - cursor = getCursor() name = @"name" - key = &"twitter:{name}:{cursor}" + key = redisKey("twitter", name, getCursor()) var rss = await getCachedRss(key) if rss.cursor.len > 0: @@ -101,18 +105,20 @@ proc createRssRouter*(cfg: Config) = cond cfg.enableRss cond '.' notin @"name" cond @"tab" in ["with_replies", "media", "search"] - let name = @"name" - let query = - case @"tab" - of "with_replies": getReplyQuery(name) - of "media": getMediaQuery(name) - of "search": initQuery(params(request), name=name) - else: Query(fromUser: @[name]) + let + name = @"name" + tab = @"tab" + query = + case tab + of "with_replies": getReplyQuery(name) + of "media": getMediaQuery(name) + of "search": initQuery(params(request), name=name) + else: Query(fromUser: @[name]) - var key = &"""{@"tab"}:{@"name"}:""" - if @"tab" == "search": - key &= $hash(genQueryUrl(query)) & ":" - key &= getCursor() + let searchKey = if tab != "search": "" + else: ":" & $hash(genQueryUrl(query)) + + let key = redisKey(tab, name & searchKey, getCursor()) var rss = await getCachedRss(key) if rss.cursor.len > 0: @@ -132,28 +138,27 @@ proc createRssRouter*(cfg: Config) = cursor = getCursor() if list.id.len == 0: - resp Http404, showError(&"""List "{@"slug"}" not found""", cfg) + resp Http404, showError("List \"" & @"slug" & "\" not found", cfg) - let url = &"/i/lists/{list.id}/rss" + let url = "/i/lists/" & list.id & "/rss" if cursor.len > 0: - redirect(&"{url}?cursor={encodeUrl(cursor, false)}") + redirect(url & "?cursor=" & encodeUrl(cursor, false)) else: redirect(url) get "/i/lists/@id/rss": cond cfg.enableRss let + id = @"id" cursor = getCursor() - key = - if cursor.len == 0: "lists:" & @"id" - else: &"""lists:{@"id"}:{cursor}""" + key = redisKey("lists", id, cursor) var rss = await getCachedRss(key) if rss.cursor.len > 0: respRss(rss, "List") let - list = await getCachedList(id=(@"id")) + list = await getCachedList(id=id) timeline = await getListTimeline(list.id, cursor) rss.cursor = timeline.bottom rss.feed = renderListRss(timeline.content, list, cfg) diff --git a/src/routes/search.nim b/src/routes/search.nim index 554f2f6..3fc44a9 100644 --- a/src/routes/search.nim +++ b/src/routes/search.nim @@ -1,5 +1,5 @@ # SPDX-License-Identifier: AGPL-3.0-only -import strutils, strformat, uri +import strutils, uri import jester @@ -37,7 +37,7 @@ proc createSearchRouter*(cfg: Config) = resp Http404, showError("Invalid search", cfg) get "/hashtag/@hash": - redirect(&"""/search?q={encodeUrl("#" & @"hash")}""") + redirect("/search?q=" & encodeUrl("#" & @"hash")) get "/opensearch": let url = getUrlPrefix(cfg) & "/search?q=" diff --git a/src/routes/timeline.nim b/src/routes/timeline.nim index 9d97c29..a0a6e21 100644 --- a/src/routes/timeline.nim +++ b/src/routes/timeline.nim @@ -1,5 +1,5 @@ # SPDX-License-Identifier: AGPL-3.0-only -import asyncdispatch, strutils, strformat, sequtils, uri, options, times +import asyncdispatch, strutils, sequtils, uri, options, times import jester, karax/vdom import router_utils @@ -102,7 +102,7 @@ proc showTimeline*(request: Request; query: Query; cfg: Config; prefs: Prefs; template respTimeline*(timeline: typed) = let t = timeline if t.len == 0: - resp Http404, showError(&"""User "{@"name"}" not found""", cfg) + resp Http404, showError("User \"" & @"name" & "\" not found", cfg) resp t template respUserId*() = diff --git a/src/views/general.nim b/src/views/general.nim index f242e66..b18dae5 100644 --- a/src/views/general.nim +++ b/src/views/general.nim @@ -81,7 +81,7 @@ proc renderHead*(prefs: Prefs; cfg: Config; req: Request; titleText=""; desc=""; title: if titleText.len > 0: - text &"{titleText}|{cfg.title}" + text titleText & " | " & cfg.title else: text cfg.title diff --git a/src/views/profile.nim b/src/views/profile.nim index 73ce59d..2a007b1 100644 --- a/src/views/profile.nim +++ b/src/views/profile.nim @@ -108,7 +108,7 @@ proc renderProfile*(profile: var Profile; prefs: Prefs; path: string): VNode = renderBanner(profile.user.banner) let sticky = if prefs.stickyProfile: " sticky" else: "" - tdiv(class=(&"profile-tab{sticky}")): + tdiv(class=("profile-tab" & sticky)): renderUserCard(profile.user, prefs) if profile.photoRail.len > 0: renderPhotoRail(profile) From 310b0ab9a1d80ff6df64232ff52f7b214d35d9f3 Mon Sep 17 00:00:00 2001 From: Zed Date: Sun, 27 Nov 2022 16:00:16 +0100 Subject: [PATCH 21/68] Update test --- tests/test_quote.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_quote.py b/tests/test_quote.py index e1ee728..1b458ea 100644 --- a/tests/test_quote.py +++ b/tests/test_quote.py @@ -3,7 +3,7 @@ from parameterized import parameterized text = [ ['elonmusk/status/1138136540096319488', - 'Trev Page', '@Model3Owners', + 'TREV PAGE', '@Model3Owners', """As of March 58.4% of new car sales in Norway are electric. What are we doing wrong? reuters.com/article/us-norwa…"""], From 096d44856fb219d467519dbfc3fc330fe49ac712 Mon Sep 17 00:00:00 2001 From: Zed Date: Sun, 27 Nov 2022 16:06:36 +0100 Subject: [PATCH 22/68] Remove Location field autofocus from search panel --- src/views/renderutils.nim | 4 ++-- src/views/search.nim | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/views/renderutils.nim b/src/views/renderutils.nim index bab01cd..8e8d530 100644 --- a/src/views/renderutils.nim +++ b/src/views/renderutils.nim @@ -55,12 +55,12 @@ proc genCheckbox*(pref, label: string; state: bool): VNode = else: input(name=pref, `type`="checkbox") span(class="checkbox") -proc genInput*(pref, label, state, placeholder: string; class=""): VNode = +proc genInput*(pref, label, state, placeholder: string; class=""; autofocus=true): VNode = let p = placeholder buildHtml(tdiv(class=("pref-group pref-input " & class))): if label.len > 0: label(`for`=pref): text label - if state.len == 0: + if autofocus and state.len == 0: input(name=pref, `type`="text", placeholder=p, value=state, autofocus="") else: input(name=pref, `type`="text", placeholder=p, value=state) diff --git a/src/views/search.nim b/src/views/search.nim index 94bbac8..77ba14f 100644 --- a/src/views/search.nim +++ b/src/views/search.nim @@ -88,7 +88,7 @@ proc renderSearchPanel*(query: Query): VNode = genDate("until", query.until) tdiv: span(class="search-title"): text "Near" - genInput("near", "", query.near, placeholder="Location...") + genInput("near", "", query.near, "Location...", autofocus=false) proc renderTweetSearch*(results: Result[Tweet]; prefs: Prefs; path: string; pinned=none(Tweet)): VNode = From 78b6877b02d1787c6c5ea07523ccb944421130fb Mon Sep 17 00:00:00 2001 From: Zed Date: Sun, 27 Nov 2022 16:19:30 +0100 Subject: [PATCH 23/68] Add "Search (...)" to tab title Fixes #247 --- src/routes/search.nim | 12 +++++++----- src/views/profile.nim | 2 +- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/routes/search.nim b/src/routes/search.nim index 3fc44a9..da1ba55 100644 --- a/src/routes/search.nim +++ b/src/routes/search.nim @@ -14,25 +14,27 @@ export search proc createSearchRouter*(cfg: Config) = router search: get "/search/?": - if @"q".len > 500: + let q = @"q" + if q.len > 500: resp Http400, showError("Search input too long.", cfg) let prefs = cookiePrefs() query = initQuery(params(request)) + title = "Search" & (if q.len > 0: " (" & q & ")" else: "") case query.kind of users: - if "," in @"q": - redirect("/" & @"q") + if "," in q: + redirect("/" & q) let users = await getSearch[User](query, getCursor()) - resp renderMain(renderUserSearch(users, prefs), request, cfg, prefs) + resp renderMain(renderUserSearch(users, prefs), request, cfg, prefs, title) of tweets: let tweets = await getSearch[Tweet](query, getCursor()) rss = "/search/rss?" & genQueryUrl(query) resp renderMain(renderTweetSearch(tweets, prefs, getPath()), - request, cfg, prefs, rss=rss) + request, cfg, prefs, title, rss=rss) else: resp Http404, showError("Invalid search", cfg) diff --git a/src/views/profile.nim b/src/views/profile.nim index 2a007b1..2b2e410 100644 --- a/src/views/profile.nim +++ b/src/views/profile.nim @@ -50,7 +50,7 @@ proc renderUserCard*(user: User; prefs: Prefs): VNode = span: let url = replaceUrls(user.website, prefs) icon "link" - a(href=url): text shortLink(url) + a(href=url): text url.shortLink tdiv(class="profile-joindate"): span(title=getJoinDateFull(user)): From 6a7e56b61366b8564defff4d8d3e58591a0ba58f Mon Sep 17 00:00:00 2001 From: Zed Date: Sun, 27 Nov 2022 16:20:53 +0100 Subject: [PATCH 24/68] Linting --- src/parser.nim | 1 - src/routes/search.nim | 2 +- src/sass/tweet/_base.scss | 1 - src/sass/tweet/thread.scss | 1 - 4 files changed, 1 insertion(+), 4 deletions(-) diff --git a/src/parser.nim b/src/parser.nim index 10186be..2b0c6a4 100644 --- a/src/parser.nim +++ b/src/parser.nim @@ -45,7 +45,6 @@ proc parseGraphList*(js: JsonNode): List = banner: list{"custom_banner_media", "media_info", "url"}.getImageStr ) - proc parsePoll(js: JsonNode): Poll = let vals = js{"binding_values"} # name format is pollNchoice_* diff --git a/src/routes/search.nim b/src/routes/search.nim index da1ba55..b2fd718 100644 --- a/src/routes/search.nim +++ b/src/routes/search.nim @@ -44,4 +44,4 @@ proc createSearchRouter*(cfg: Config) = get "/opensearch": let url = getUrlPrefix(cfg) & "/search?q=" resp Http200, {"Content-Type": "application/opensearchdescription+xml"}, - generateOpenSearchXML(cfg.title, cfg.hostname, url) + generateOpenSearchXML(cfg.title, cfg.hostname, url) diff --git a/src/sass/tweet/_base.scss b/src/sass/tweet/_base.scss index 549298a..69f51c0 100644 --- a/src/sass/tweet/_base.scss +++ b/src/sass/tweet/_base.scss @@ -138,7 +138,6 @@ } } - .attribution { display: flex; pointer-events: all; diff --git a/src/sass/tweet/thread.scss b/src/sass/tweet/thread.scss index f8ad603..5fbad21 100644 --- a/src/sass/tweet/thread.scss +++ b/src/sass/tweet/thread.scss @@ -23,7 +23,6 @@ font-size: 18px; } - @media(max-width: 600px) { .main-tweet .tweet-content { font-size: 16px; From da4d6eabddc322306b152b7d856b13c530f58e95 Mon Sep 17 00:00:00 2001 From: Zed Date: Sun, 27 Nov 2022 17:24:29 +0100 Subject: [PATCH 25/68] Add enum hooks to log parseHook jsony errors --- src/experimental/parser/unifiedcard.nim | 2 ++ src/experimental/types/unifiedcard.nim | 26 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/experimental/parser/unifiedcard.nim b/src/experimental/parser/unifiedcard.nim index 337c3b9..12689e1 100644 --- a/src/experimental/parser/unifiedcard.nim +++ b/src/experimental/parser/unifiedcard.nim @@ -82,6 +82,8 @@ proc parseUnifiedCard*(json: string): Card = component.parseMedia(card, result) of buttonGroup: discard + of unknown: + echo "ERROR: Unknown component type: ", json case component.kind of twitterListDetails: diff --git a/src/experimental/types/unifiedcard.nim b/src/experimental/types/unifiedcard.nim index 16500df..737fdd6 100644 --- a/src/experimental/types/unifiedcard.nim +++ b/src/experimental/types/unifiedcard.nim @@ -17,6 +17,7 @@ type twitterListDetails communityDetails mediaWithDetailsHorizontal + unknown Component* = object kind*: ComponentType @@ -77,3 +78,28 @@ converter fromText*(text: Text): string = text.content proc renameHook*(v: var HasTypeField; fieldName: var string) = if fieldName == "type": fieldName = "kind" + +proc enumHook*(s: string; v: var ComponentType) = + v = case s + of "details": details + of "media": media + of "swipeable_media": swipeableMedia + of "button_group": buttonGroup + of "app_store_details": appStoreDetails + of "twitter_list_details": twitterListDetails + of "community_details": communityDetails + of "media_with_details_horizontal": mediaWithDetailsHorizontal + else: echo "ERROR: Unknown enum value (ComponentType): ", s; unknown + +proc enumHook*(s: string; v: var AppType) = + v = case s + of "android_app": androidApp + of "iphone_app": iPhoneApp + of "ipad_app": iPadApp + else: echo "ERROR: Unknown enum value (AppType): ", s; androidApp + +proc enumHook*(s: string; v: var MediaType) = + v = case s + of "video": video + of "photo": photo + else: echo "ERROR: Unknown enum value (MediaType): ", s; photo From 9bae009bbc2276f4930aa5927ee6608cfe5b3bd1 Mon Sep 17 00:00:00 2001 From: Zed Date: Sun, 27 Nov 2022 17:27:07 +0100 Subject: [PATCH 26/68] Fix 'unknown' compilation error --- src/experimental/parser/unifiedcard.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/experimental/parser/unifiedcard.nim b/src/experimental/parser/unifiedcard.nim index 12689e1..a3e8111 100644 --- a/src/experimental/parser/unifiedcard.nim +++ b/src/experimental/parser/unifiedcard.nim @@ -82,7 +82,7 @@ proc parseUnifiedCard*(json: string): Card = component.parseMedia(card, result) of buttonGroup: discard - of unknown: + of ComponentType.unknown: echo "ERROR: Unknown component type: ", json case component.kind From d923c20aa6a87224343562f15b00e72e7780aa3d Mon Sep 17 00:00:00 2001 From: Zed Date: Sun, 27 Nov 2022 18:18:51 +0100 Subject: [PATCH 27/68] Explicitly don't support 'model3d' cards Fixes #597 --- src/experimental/parser/unifiedcard.nim | 2 ++ src/experimental/types/unifiedcard.nim | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/experimental/parser/unifiedcard.nim b/src/experimental/parser/unifiedcard.nim index a3e8111..3c5158a 100644 --- a/src/experimental/parser/unifiedcard.nim +++ b/src/experimental/parser/unifiedcard.nim @@ -66,6 +66,8 @@ proc parseMedia(component: Component; card: UnifiedCard; result: var Card) = durationMs: videoInfo.durationMillis, variants: videoInfo.variants ) + of model3d: + result.title = "Unsupported 3D model ad" proc parseUnifiedCard*(json: string): Card = let card = json.fromJson(UnifiedCard) diff --git a/src/experimental/types/unifiedcard.nim b/src/experimental/types/unifiedcard.nim index 737fdd6..4ec587c 100644 --- a/src/experimental/types/unifiedcard.nim +++ b/src/experimental/types/unifiedcard.nim @@ -48,7 +48,7 @@ type vanity*: string MediaType* = enum - photo, video + photo, video, model3d MediaEntity* = object kind*: MediaType @@ -102,4 +102,5 @@ proc enumHook*(s: string; v: var MediaType) = v = case s of "video": video of "photo": photo + of "model3d": model3d else: echo "ERROR: Unknown enum value (MediaType): ", s; photo From 687447cea43089e0550ed47656535e11ba8f69f8 Mon Sep 17 00:00:00 2001 From: Zed Date: Mon, 19 Dec 2022 10:07:24 +0100 Subject: [PATCH 28/68] Only retry on 401 once --- src/apiutils.nim | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/apiutils.nim b/src/apiutils.nim index 77ff368..917932a 100644 --- a/src/apiutils.nim +++ b/src/apiutils.nim @@ -23,7 +23,7 @@ proc genParams*(pars: openArray[(string, string)] = @[]; cursor=""; result &= ("count", count) if cursor.len > 0: # The raw cursor often has plus signs, which sometimes get turned into spaces, - # so we need to them back into a plus + # so we need to turn them back into a plus if " " in cursor: result &= ("cursor", cursor.replace(" ", "+")) else: @@ -69,9 +69,7 @@ template fetchImpl(result, fetchBody) {.dirty.} = # Twitter randomly returns 401 errors with an empty body quite often. # Retrying the request usually works. - var attempt = 0 - while resp.status == "401 Unauthorized" and result.len == 0 and attempt < 3: - inc attempt + if resp.status == "401 Unauthorized" and result.len == 0: getContent() if resp.status == $Http503: From d549a77ebeea7fbdd1825e38d973291f013bb40f Mon Sep 17 00:00:00 2001 From: Andrew Sun <14020276+apsun@users.noreply.github.com> Date: Sat, 31 Dec 2022 11:46:02 -0800 Subject: [PATCH 29/68] Fix arm64 build (#756) --- nitter.nimble | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nitter.nimble b/nitter.nimble index a4d2e87..6facdbd 100644 --- a/nitter.nimble +++ b/nitter.nimble @@ -20,7 +20,7 @@ requires "packedjson#9e6fbb6" requires "supersnappy#6c94198" requires "redpool#8b7c1db" requires "https://github.com/zedeus/redis#d0a0e6f" -requires "zippy#61922b9" +requires "zippy#88a5a5a" requires "flatty#9f885d7" requires "jsony#d0e69bd" From b5dee25b379c561eeb2e71a8bd08882b6b9699ff Mon Sep 17 00:00:00 2001 From: Zed Date: Mon, 9 Jan 2023 00:11:33 +0100 Subject: [PATCH 30/68] Enable SO_REUSEPORT for simplier load balancing --- src/nitter.nim | 1 + 1 file changed, 1 insertion(+) diff --git a/src/nitter.nim b/src/nitter.nim index d743599..2e868a4 100644 --- a/src/nitter.nim +++ b/src/nitter.nim @@ -56,6 +56,7 @@ settings: port = Port(cfg.port) staticDir = cfg.staticDir bindAddr = cfg.address + reusePort = true routes: get "/": From 6c4c691fe781454d1e7f271f78bc5fa7225539a8 Mon Sep 17 00:00:00 2001 From: Zed Date: Mon, 9 Jan 2023 00:12:07 +0100 Subject: [PATCH 31/68] Add Crawl-delay to robots.txt --- public/robots.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/public/robots.txt b/public/robots.txt index 7a74568..812656a 100644 --- a/public/robots.txt +++ b/public/robots.txt @@ -1,4 +1,5 @@ User-agent: * Disallow: / +Crawl-delay: 1 User-agent: Twitterbot Disallow: From 88c6135030a3f5bcd45a6b71fe2bcebc4129dc39 Mon Sep 17 00:00:00 2001 From: Zed Date: Mon, 9 Jan 2023 00:13:59 +0100 Subject: [PATCH 32/68] Bump dependencies --- nitter.nimble | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nitter.nimble b/nitter.nimble index 6facdbd..fdc1f9f 100644 --- a/nitter.nimble +++ b/nitter.nimble @@ -12,15 +12,15 @@ bin = @["nitter"] requires "nim >= 1.4.8" requires "jester#baca3f" -requires "karax#6abcb77" -requires "sass#e683aa1" +requires "karax#0af2c85" +requires "sass#7dfdd03" requires "nimcrypto#b41129f" -requires "markdown#a661c26" +requires "markdown#158efe3" requires "packedjson#9e6fbb6" requires "supersnappy#6c94198" requires "redpool#8b7c1db" requires "https://github.com/zedeus/redis#d0a0e6f" -requires "zippy#88a5a5a" +requires "zippy#123cd59" requires "flatty#9f885d7" requires "jsony#d0e69bd" From cd163b26a3f6c2751276475072406b397d8355c5 Mon Sep 17 00:00:00 2001 From: Zed Date: Mon, 9 Jan 2023 00:29:59 +0100 Subject: [PATCH 33/68] Use webp for thumbnails when available --- src/views/general.nim | 5 ++--- src/views/renderutils.nim | 8 ++++++++ src/views/tweet.nim | 14 +++----------- 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/views/general.nim b/src/views/general.nim index b18dae5..5e96d02 100644 --- a/src/views/general.nim +++ b/src/views/general.nim @@ -98,9 +98,8 @@ proc renderHead*(prefs: Prefs; cfg: Config; req: Request; titleText=""; desc=""; link(rel="preload", type="image/png", href=bannerUrl, `as`="image") for url in images: - let suffix = if "400x400" in url or url.endsWith("placeholder.png"): "" - else: "?name=small" - let preloadUrl = getPicUrl(url & suffix) + let preloadUrl = if "400x400" in url: getPicUrl(url) + else: getSmallPic(url) link(rel="preload", type="image/png", href=preloadUrl, `as`="image") let image = getUrlPrefix(cfg) & getPicUrl(url) diff --git a/src/views/renderutils.nim b/src/views/renderutils.nim index 8e8d530..cdfeb28 100644 --- a/src/views/renderutils.nim +++ b/src/views/renderutils.nim @@ -3,6 +3,14 @@ import strutils, strformat import karax/[karaxdsl, vdom, vstyles] import ".."/[types, utils] +const smallWebp* = "?name=small&format=webp" + +proc getSmallPic*(url: string): string = + result = url + if "?" notin url and not url.endsWith("placeholder.png"): + result &= smallWebp + result = getPicUrl(result) + proc icon*(icon: string; text=""; title=""; class=""; href=""): VNode = var c = "icon-" & icon if class.len > 0: c = &"{c} {class}" diff --git a/src/views/tweet.nim b/src/views/tweet.nim index daad61a..69335fa 100644 --- a/src/views/tweet.nim +++ b/src/views/tweet.nim @@ -7,14 +7,7 @@ import renderutils import ".."/[types, utils, formatters] import general -const - doctype = "\n" - -proc getSmallPic(url: string): string = - result = url - if "?" notin url and not url.endsWith("placeholder.png"): - result &= "?name=small" - result = getPicUrl(result) +const doctype = "\n" proc renderMiniAvatar(user: User; prefs: Prefs): VNode = let url = getPicUrl(user.getUserPic("_mini")) @@ -60,9 +53,8 @@ proc renderAlbum(tweet: Tweet): VNode = tdiv(class="attachment image"): let named = "name=" in photo - orig = photo - small = if named: photo else: photo & "?name=small" - a(href=getOrigPicUrl(orig), class="still-image", target="_blank"): + small = if named: photo else: photo & smallWebp + a(href=getOrigPicUrl(photo), class="still-image", target="_blank"): genImg(small) proc isPlaybackEnabled(prefs: Prefs; playbackType: VideoType): bool = From d38b63f5a9ec9206305f1bef8d15ac4e8446d489 Mon Sep 17 00:00:00 2001 From: Zed Date: Mon, 9 Jan 2023 00:37:32 +0100 Subject: [PATCH 34/68] Bump hls.js --- public/js/hls.light.min.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/public/js/hls.light.min.js b/public/js/hls.light.min.js index 2dcaa72..5a1fd1d 100644 --- a/public/js/hls.light.min.js +++ b/public/js/hls.light.min.js @@ -1,5 +1,5 @@ // @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 // @source https://github.com/video-dev/hls.js -// @version v1.1.5 -"undefined"!=typeof window&&function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Hls=e():t.Hls=e()}(this,(function(){return function(t){var e={};function r(i){if(e[i])return e[i].exports;var a=e[i]={i:i,l:!1,exports:{}};return t[i].call(a.exports,a,a.exports,r),a.l=!0,a.exports}return r.m=t,r.c=e,r.d=function(t,e,i){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var a in t)r.d(i,a,function(e){return t[e]}.bind(null,a));return i},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="/dist/",r(r.s=19)}([function(t,e,r){"use strict";var i;r.d(e,"a",(function(){return i})),function(t){t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached"}(i||(i={}))},function(t,e,r){"use strict";r.d(e,"a",(function(){return o})),r.d(e,"b",(function(){return l}));var i=function(){},a={trace:i,debug:i,log:i,warn:i,info:i,error:i},n=a;function s(t){var e=self.console[t];return e?e.bind(self.console,"["+t+"] >"):i}function o(t){if(self.console&&!0===t||"object"==typeof t){!function(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i>8*(15-r)&255;return e},r.setDecryptDataFromLevelKey=function(t,e){var r=t;return"AES-128"===(null==t?void 0:t.method)&&t.uri&&!t.iv&&((r=o.a.fromURI(t.uri)).method=t.method,r.iv=this.createInitializationVector(e),r.keyFormat="identity"),r},r.setElementaryStreamInfo=function(t,e,r,i,a,n){void 0===n&&(n=!1);var s=this.elementaryStreams,o=s[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,a)):s[t]={startPTS:e,endPTS:r,startDTS:i,endDTS:a,partial:n}},r.clearElementaryStreamInfo=function(){var t=this.elementaryStreams;t[i.AUDIO]=null,t[i.VIDEO]=null,t[i.AUDIOVIDEO]=null},f(e,[{key:"decryptdata",get:function(){if(!this.levelkey&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkey){var t=this.sn;"number"!=typeof t&&(this.levelkey&&"AES-128"===this.levelkey.method&&!this.levelkey.iv&&s.b.warn('missing IV for initialization segment with method="'+this.levelkey.method+'" - compliance issue'),t=0),this._decryptdata=this.setDecryptDataFromLevelKey(this.levelkey,t)}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;if(!Object(a.a)(this.programDateTime))return null;var t=Object(a.a)(this.duration)?this.duration:0;return this.programDateTime+1e3*t}},{key:"encrypted",get:function(){var t;return!(null===(t=this.decryptdata)||void 0===t||!t.keyFormat||!this.decryptdata.uri)}}]),e}(c),g=function(t){function e(e,r,i,a,n){var s;(s=t.call(this,i)||this).fragOffset=0,s.duration=0,s.gap=!1,s.independent=!1,s.relurl=void 0,s.fragment=void 0,s.index=void 0,s.stats=new l.a,s.duration=e.decimalFloatingPoint("DURATION"),s.gap=e.bool("GAP"),s.independent=e.bool("INDEPENDENT"),s.relurl=e.enumeratedString("URI"),s.fragment=r,s.index=a;var o=e.enumeratedString("BYTERANGE");return o&&s.setByteRange(o,n),n&&(s.fragOffset=n.fragOffset+n.duration),s}return u(e,t),f(e,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var t=this.elementaryStreams;return!!(t.audio||t.video||t.audiovideo)}}]),e}(c)},function(t,e,r){"use strict";r.d(e,"b",(function(){return d})),r.d(e,"g",(function(){return h})),r.d(e,"f",(function(){return f})),r.d(e,"d",(function(){return c})),r.d(e,"c",(function(){return v})),r.d(e,"e",(function(){return p})),r.d(e,"h",(function(){return m})),r.d(e,"a",(function(){return y}));var i=r(8),a=r(5),n=Math.pow(2,32)-1,s=[].push;function o(t){return String.fromCharCode.apply(null,t)}function l(t,e){"data"in t&&(e+=t.start,t=t.data);var r=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3];return r<0?4294967296+r:r}function u(t,e,r){"data"in t&&(e+=t.start,t=t.data),t[e]=r>>24,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=255&r}function d(t,e){var r,i,a,n=[];if(!e.length)return n;"data"in t?(r=t.data,i=t.start,a=t.end):(i=0,a=(r=t).byteLength);for(var u=i;u1?u+h:a;if(o(r.subarray(u+4,u+8))===e[0])if(1===e.length)n.push({data:r,start:u+8,end:f});else{var c=d({data:r,start:u+8,end:f},e.slice(1));c.length&&s.apply(n,c)}u=f}return n}function h(t){var e=d(t,["moov"])[0],r=e?e.end:null,i=d(t,["sidx"]);if(!i||!i[0])return null;var a=[],n=i[0],s=n.data[0],o=0===s?8:16,u=l(n,o);o+=4;o+=0===s?8:16,o+=2;var h=n.end+0,f=function(t,e){"data"in t&&(e+=t.start,t=t.data);var r=t[e]<<8|t[e+1];return r<0?65536+r:r}(n,o);o+=2;for(var c=0;c>>31)return console.warn("SIDX has hierarchical references (not supported)"),null;var m=l(n,v);v+=4,a.push({referenceSize:p,subsegmentDuration:m,info:{duration:m/u,start:h,end:h+p-1}}),h+=p,o=v+=4}return{earliestPresentationTime:0,timescale:u,version:s,referencesCount:f,references:a,moovEndOffset:r}}function f(t){for(var e=[],r=d(t,["moov","trak"]),i=0;i0)return t.subarray(r,r+i)},o=function(t,e){var r=0;return r=(127&t[e])<<21,r|=(127&t[e+1])<<14,r|=(127&t[e+2])<<7,r|=127&t[e+3]},l=function(t,e){return a(t,e)&&o(t,e+6)+10<=t.length-e},u=function(t){for(var e=f(t),r=0;r>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:u+=String.fromCharCode(n);break;case 12:case 13:s=t[d++],u+=String.fromCharCode((31&n)<<6|63&s);break;case 14:s=t[d++],o=t[d++],u+=String.fromCharCode((15&n)<<12|(63&s)<<6|(63&o)<<0)}}return u};function b(){return i||void 0===self.TextDecoder||(i=new self.TextDecoder("utf-8")),i}},function(t,e,r){"use strict";function i(t,e,r){return Uint8Array.prototype.slice?t.slice(e,r):new Uint8Array(Array.prototype.slice.call(t,e,r))}r.d(e,"a",(function(){return i}))},function(t,e,r){"use strict";r.d(e,"c",(function(){return St})),r.d(e,"d",(function(){return At})),r.d(e,"a",(function(){return Rt})),r.d(e,"b",(function(){return Dt}));var i=r(0),a=r(2),n=r(14),s=r(3),o=r(7);var l=r(6),u=r(8),d=function(){function t(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.initPTS=null}var e=t.prototype;return e.resetInitSegment=function(t,e,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},e.resetTimeStamp=function(){},e.resetContiguity=function(){},e.canParse=function(t,e){return!1},e.appendFrame=function(t,e,r){},e.demux=function(t,e){this.cachedData&&(t=Object(l.a)(this.cachedData,t),this.cachedData=null);var r,i,a=o.b(t,0),n=a?a.length:0,s=this._audioTrack,d=this._id3Track,f=a?o.d(a):void 0,c=t.length;for(0!==this.frameIndex&&null!==this.initPTS||(this.initPTS=h(f,e)),a&&a.length>0&&d.samples.push({pts:this.initPTS,dts:this.initPTS,data:a}),i=this.initPTS;n>>5}function m(t,e){return e+1=t.length)return!1;var i=p(t,e);if(i<=r)return!1;var a=e+i;return a===t.length||m(t,a)}return!1}function b(t,e,r,n,s){if(!t.samplerate){var o=function(t,e,r,n){var s,o,l,u,d=navigator.userAgent.toLowerCase(),h=n,f=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&e[r+2])>>>6);var v=(60&e[r+2])>>>2;if(!(v>f.length-1))return l=(1&e[r+2])<<2,l|=(192&e[r+3])>>>6,c.b.log("manifest codec:"+n+", ADTS type:"+s+", samplingIndex:"+v),/firefox/i.test(d)?v>=6?(s=5,u=new Array(4),o=v-3):(s=2,u=new Array(2),o=v):-1!==d.indexOf("android")?(s=2,u=new Array(2),o=v):(s=5,u=new Array(4),n&&(-1!==n.indexOf("mp4a.40.29")||-1!==n.indexOf("mp4a.40.5"))||!n&&v>=6?o=v-3:((n&&-1!==n.indexOf("mp4a.40.2")&&(v>=6&&1===l||/vivaldi/i.test(d))||!n&&1===l)&&(s=2,u=new Array(2)),o=v)),u[0]=s<<3,u[0]|=(14&v)>>1,u[1]|=(1&v)<<7,u[1]|=l<<3,5===s&&(u[1]|=(14&o)>>1,u[2]=(1&o)<<7,u[2]|=8,u[3]=0),{config:u,samplerate:f[v],channelCount:l,codec:"mp4a.40."+s,manifestCodec:h};t.trigger(i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+v})}(e,r,n,s);if(!o)return;t.config=o.config,t.samplerate=o.samplerate,t.channelCount=o.channelCount,t.codec=o.codec,t.manifestCodec=o.manifestCodec,c.b.log("parsed codec:"+t.codec+", rate:"+o.samplerate+", channels:"+o.channelCount)}}function T(t){return 9216e4/t}function E(t,e,r,i,a){var n=function(t,e,r,i,a){var n=g(t,e),s=p(t,e);if((s-=n)>0)return{headerLength:n,frameLength:s,stamp:r+i*a}}(e,r,i,a,T(t.samplerate));if(n){var s,o=n.frameLength,l=n.headerLength,u=n.stamp,d=l+o,h=Math.max(0,r+d-e.length);h?(s=new Uint8Array(d-l)).set(e.subarray(r+l,e.length),0):s=e.subarray(r+l,r+d);var f={unit:s,pts:u};return h||t.samples.push(f),{sample:f,length:d,missing:h}}}function S(t,e){return(S=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}var L=function(t){var e,r;function i(e,r){var i;return(i=t.call(this)||this).observer=void 0,i.config=void 0,i.observer=e,i.config=r,i}r=t,(e=i).prototype=Object.create(r.prototype),e.prototype.constructor=e,S(e,r);var a=i.prototype;return a.resetInitSegment=function(e,r,i){t.prototype.resetInitSegment.call(this,e,r,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,isAAC:!0,samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}},i.probe=function(t){if(!t)return!1;for(var e=(o.b(t,0)||[]).length,r=t.length;e0},e.demux=function(t){var e=t,r={type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0};if(this.config.progressive){this.remainderData&&(e=Object(l.a)(this.remainderData,t));var i=Object(l.h)(e);this.remainderData=i.remainder,r.samples=i.valid||new Uint8Array}else r.samples=e;return{audioTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},avcTrack:r,id3Track:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},textTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0}}},e.flush=function(){var t={type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0};return t.samples=this.remainderData||new Uint8Array,this.remainderData=null,{audioTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},avcTrack:t,id3Track:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},textTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0}}},e.demuxSampleAes=function(t,e,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},e.destroy=function(){},t}();R.minProbeByteLength=1024;var D=R,_=null,k=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],x=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],C=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],w=[0,1,1,4];function O(t,e,r,i,a){if(!(r+24>e.length)){var n=I(e,r);if(n&&r+n.frameLength<=e.length){var s=i+a*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(r,r+n.frameLength),pts:s,dts:s};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}}function I(t,e){var r=t[e+1]>>3&3,i=t[e+1]>>1&3,a=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==r&&0!==a&&15!==a&&3!==n){var s=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*k[14*(3===r?3-i:3===i?3:4)+a-1],u=x[3*(3===r?0:2===r?1:2)+n],d=3===o?1:2,h=C[r][i],f=w[i],c=8*h*f,v=Math.floor(h*l/u+s)*f;if(null===_){var g=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);_=g?parseInt(g[1]):0}return!!_&&_<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:u,channelCount:d,frameLength:v,samplesPerFrame:c}}}function P(t,e){return 255===t[e]&&224==(224&t[e+1])&&0!=(6&t[e+1])}function F(t,e){return e+1t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,t-=(e=t>>3)>>3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)},e.readBits=function(t){var e=Math.min(this.bitsAvailable,t),r=this.word>>>32-e;return t>32&&c.b.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0?this.word<<=e:this.bytesAvailable>0&&this.loadWord(),(e=t-e)>0&&this.bitsAvailable?r<>>t))return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()},e.skipUEG=function(){this.skipBits(1+this.skipLZ())},e.skipEG=function(){this.skipBits(1+this.skipLZ())},e.readUEG=function(){var t=this.skipLZ();return this.readBits(t+1)-1},e.readEG=function(){var t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)},e.readBoolean=function(){return 1===this.readBits(1)},e.readUByte=function(){return this.readBits(8)},e.readUShort=function(){return this.readBits(16)},e.readUInt=function(){return this.readBits(32)},e.skipScalingList=function(t){for(var e=8,r=8,i=0;i=t.length)return void r();if(!(t[e].unit.length<32)){var i=this.decrypter.isSync();if(this.decryptAacSample(t,e,r,i),!i)return}}},e.getAvcEncryptedData=function(t){for(var e=16*Math.floor((t.length-48)/160)+16,r=new Int8Array(e),i=0,a=32;a=t.length)return void i();for(var a=t[e].units;!(r>=a.length);r++){var n=a[r];if(!(n.data.length<=48||1!==n.type&&5!==n.type)){var s=this.decrypter.isSync();if(this.decryptAvcSample(t,e,r,i,n,s),!s)return}}}},t}(),U={video:1,audio:2,id3:3,text:4},G=function(){function t(t,e,r){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this.aacLastPTS=null,this._initPTS=null,this._initDTS=null,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=t,this.config=e,this.typeSupported=r}t.probe=function(e){var r=t.syncOffset(e);return!(r<0)&&(r&&c.b.warn("MPEG2-TS detected but first sync word found @ offset "+r+", junk ahead ?"),!0)},t.syncOffset=function(t){for(var e=Math.min(1e3,t.length-564),r=0;r>4>1){if((k=R+5+e[R+4])===R+188)continue}else k=R+4;switch(_){case f:D&&(v&&(o=V(v))&&this.parseAVCPES(o,!1),v={data:[],size:0}),v&&(v.data.push(e.subarray(k,R+188)),v.size+=R+188-k);break;case g:D&&(m&&(o=V(m))&&(d.isAAC?this.parseAACPES(o):this.parseMPEGPES(o)),m={data:[],size:0}),m&&(m.data.push(e.subarray(k,R+188)),m.size+=R+188-k);break;case p:D&&(y&&(o=V(y))&&this.parseID3PES(o),y={data:[],size:0}),y&&(y.data.push(e.subarray(k,R+188)),y.size+=R+188-k);break;case 0:D&&(k+=e[k]+1),E=this._pmtId=H(e,k);break;case E:D&&(k+=e[k]+1);var x=K(e,k,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,n);(f=x.avc)>0&&(u.pid=f),(g=x.audio)>0&&(d.pid=g,d.isAAC=x.isAAC),(p=x.id3)>0&&(h.pid=p),b&&!T&&(c.b.log("reparse from beginning"),b=!1,R=L-188),T=this.pmtParsed=!0;break;case 17:case 8191:break;default:b=!0}}else A++;A>0&&this.observer.emit(i.a.ERROR,i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!1,reason:"Found "+A+" TS packet/s that do not start with 0x47"}),u.pesData=v,d.pesData=m,h.pesData=y;var C={audioTrack:d,avcTrack:u,id3Track:h,textTrack:this._txtTrack};return s&&this.extractRemainingSamples(C),C},e.flush=function(){var t,e=this.remainderData;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{audioTrack:this._audioTrack,avcTrack:this._avcTrack,textTrack:this._txtTrack,id3Track:this._id3Track},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t},e.extractRemainingSamples=function(t){var e,r=t.audioTrack,i=t.avcTrack,a=t.id3Track,n=i.pesData,s=r.pesData,o=a.pesData;n&&(e=V(n))?(this.parseAVCPES(e,!0),i.pesData=null):i.pesData=n,s&&(e=V(s))?(r.isAAC?this.parseAACPES(e):this.parseMPEGPES(e),r.pesData=null):(null!=s&&s.size&&c.b.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=s),o&&(e=V(o))?(this.parseID3PES(e),a.pesData=null):a.pesData=o},e.demuxSampleAes=function(t,e,r){var i=this.demux(t,r,!0,!this.config.progressive),a=this.sampleAes=new B(this.observer,this.config,e);return this.decrypt(i,a)},e.decrypt=function(t,e){return new Promise((function(r){var i=t.audioTrack,a=t.avcTrack;i.samples&&i.isAAC?e.decryptAacSamples(i.samples,0,(function(){a.samples?e.decryptAvcSamples(a.samples,0,0,(function(){r(t)})):r(t)})):a.samples&&e.decryptAvcSamples(a.samples,0,0,(function(){r(t)}))}))},e.destroy=function(){this._initPTS=this._initDTS=null,this._duration=0},e.parseAVCPES=function(t,e){var r,i=this,a=this._avcTrack,n=this.parseAVCNALu(t.data),s=this.avcSample,l=!1;t.data=null,s&&n.length&&!a.audFound&&(W(s,a),s=this.avcSample=j(!1,t.pts,t.dts,"")),n.forEach((function(e){switch(e.type){case 1:r=!0,s||(s=i.avcSample=j(!0,t.pts,t.dts,"")),s.frame=!0;var n=e.data;if(l&&n.length>4){var u=new N(n).readSliceType();2!==u&&4!==u&&7!==u&&9!==u||(s.key=!0)}break;case 5:r=!0,s||(s=i.avcSample=j(!0,t.pts,t.dts,"")),s.key=!0,s.frame=!0;break;case 6:r=!0;var d=new N(X(e.data));d.readUByte();for(var h=0,f=0,c=!1,v=0;!c&&d.bytesAvailable>1;){h=0;do{h+=v=d.readUByte()}while(255===v);f=0;do{f+=v=d.readUByte()}while(255===v);if(4===h&&0!==d.bytesAvailable){if(c=!0,181===d.readUByte())if(49===d.readUShort())if(1195456820===d.readUInt())if(3===d.readUByte()){for(var g=d.readUByte(),p=31&g,m=[g,d.readUByte()],y=0;y16){for(var b=[],T=0;T<16;T++)b.push(d.readUByte().toString(16)),3!==T&&5!==T&&7!==T&&9!==T||b.push("-");for(var E=f-16,S=new Uint8Array(E),L=0;L=0){var h={data:t.subarray(u,l-n-1),type:d};o.push(h)}else{var f=this.getLastNalUnit();if(f&&(s&&l<=4-s&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-s)),(r=l-n-1)>0)){var c=new Uint8Array(f.data.byteLength+r);c.set(f.data,0),c.set(t.subarray(0,r),f.data.byteLength),f.data=c,f.state=0}}l=0&&n>=0){var v={data:t.subarray(u,i),type:d,state:n};o.push(v)}if(0===o.length){var g=this.getLastNalUnit();if(g){var p=new Uint8Array(g.data.byteLength+t.byteLength);p.set(g.data,0),p.set(t,g.data.byteLength),g.data=p}}return a.naluState=n,o},e.parseAACPES=function(t){var e,r,n,s,o,l=0,u=this._audioTrack,d=this.aacOverFlow,h=t.data;if(d){this.aacOverFlow=null;var f=d.sample.unit.byteLength,v=Math.min(d.missing,f),g=f-v;d.sample.unit.set(h.subarray(0,v),g),u.samples.push(d.sample),l=d.missing}for(e=l,r=h.length;e1;){var l=new Uint8Array(o[0].length+o[1].length);l.set(o[0]),l.set(o[1],o[0].length),o[0]=l,o.splice(1,1)}if(1===((e=o[0])[0]<<16)+(e[1]<<8)+e[2]){if((r=(e[4]<<8)+e[5])&&r>t.size-6)return null;var u=e[7];192&u&&(a=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&u?a-(n=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2)>54e5&&(c.b.warn(Math.round((a-n)/9e4)+"s delta between PTS and DTS, align them"),a=n):n=a);var d=(i=e[8])+9;if(t.size<=d)return null;t.size-=d;for(var h=new Uint8Array(t.size),f=0,v=o.length;fg){d-=g;continue}e=e.subarray(d),g-=d,d=0}h.set(e,s),s+=g}return r&&(r-=i+3),{data:h,pts:a,dts:n,len:r}}return null}function W(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){var r=e.samples,i=r.length;if(!i)return void e.dropped++;var a=r[i-1];t.pts=a.pts,t.dts=a.dts}e.samples.push(t)}t.debug.length&&c.b.log(t.pts+"/"+t.dts+":"+t.debug)}function Y(t,e){var r=t.length;if(r>0){if(e.pts>=t[r-1].pts)t.push(e);else for(var i=r-1;i>=0;i--)if(e.pts1?r-1:0),a=1;a>24&255,o[1]=e>>16&255,o[2]=e>>8&255,o[3]=255&e,o.set(t,4),n=0,e=8;n>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,85,196,0,0]))},t.mdia=function(e){return t.box(t.types.mdia,t.mdhd(e.timescale,e.duration),t.hdlr(e.type),t.minf(e))},t.mfhd=function(e){return t.box(t.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))},t.minf=function(e){return"audio"===e.type?t.box(t.types.minf,t.box(t.types.smhd,t.SMHD),t.DINF,t.stbl(e)):t.box(t.types.minf,t.box(t.types.vmhd,t.VMHD),t.DINF,t.stbl(e))},t.moof=function(e,r,i){return t.box(t.types.moof,t.mfhd(e),t.traf(i,r))},t.moov=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trak(e[r]);return t.box.apply(null,[t.types.moov,t.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(t.mvex(e)))},t.mvex=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trex(e[r]);return t.box.apply(null,[t.types.mvex].concat(i))},t.mvhd=function(e,r){r*=e;var i=Math.floor(r/(J+1)),a=Math.floor(r%(J+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return t.box(t.types.mvhd,n)},t.sdtp=function(e){var r,i,a=e.samples||[],n=new Uint8Array(4+a.length);for(r=0;r>>8&255),n.push(255&a),n=n.concat(Array.prototype.slice.call(i));for(r=0;r>>8&255),s.push(255&a),s=s.concat(Array.prototype.slice.call(i));var o=t.box(t.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|e.sps.length].concat(n).concat([e.pps.length]).concat(s))),l=e.width,u=e.height,d=e.pixelRatio[0],h=e.pixelRatio[1];return t.box(t.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,t.box(t.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),t.box(t.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))},t.esds=function(t){var e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))},t.mp4a=function(e){var r=e.samplerate;return t.box(t.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),t.box(t.types.esds,t.esds(e)))},t.mp3=function(e){var r=e.samplerate;return t.box(t.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))},t.stsd=function(e){return"audio"===e.type?e.isAAC||"mp3"!==e.codec?t.box(t.types.stsd,t.STSD,t.mp4a(e)):t.box(t.types.stsd,t.STSD,t.mp3(e)):t.box(t.types.stsd,t.STSD,t.avc1(e))},t.tkhd=function(e){var r=e.id,i=e.duration*e.timescale,a=e.width,n=e.height,s=Math.floor(i/(J+1)),o=Math.floor(i%(J+1));return t.box(t.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,a>>8&255,255&a,0,0,n>>8&255,255&n,0,0]))},t.traf=function(e,r){var i=t.sdtp(e),a=e.id,n=Math.floor(r/(J+1)),s=Math.floor(r%(J+1));return t.box(t.types.traf,t.box(t.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a])),t.box(t.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,s>>24,s>>16&255,s>>8&255,255&s])),t.trun(e,i.length+16+20+8+16+8+8),i)},t.trak=function(e){return e.duration=e.duration||4294967295,t.box(t.types.trak,t.tkhd(e),t.mdia(e))},t.trex=function(e){var r=e.id;return t.box(t.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},t.trun=function(e,r){var i,a,n,s,o,l,u=e.samples||[],d=u.length,h=12+16*d,f=new Uint8Array(h);for(r+=8+h,f.set([0,0,15,1,d>>>24&255,d>>>16&255,d>>>8&255,255&d,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i>>24&255,n>>>16&255,n>>>8&255,255&n,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return t.box(t.types.trun,f)},t.initSegment=function(e){t.types||t.init();var r=t.moov(e),i=new Uint8Array(t.FTYP.byteLength+r.byteLength);return i.set(t.FTYP),i.set(r,t.FTYP.byteLength),i},t}();tt.types=void 0,tt.HDLR_TYPES=void 0,tt.STTS=void 0,tt.STSC=void 0,tt.STCO=void 0,tt.STSZ=void 0,tt.VMHD=void 0,tt.SMHD=void 0,tt.STSD=void 0,tt.FTYP=void 0,tt.DINF=void 0;var et=tt,rt=r(4);function it(t,e,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var a=t*e*r;return i?Math.round(a):a}function at(t,e){return void 0===e&&(e=!1),it(t,1e3,1/9e4,e)}function nt(){return(nt=Object.assign||function(t){for(var e=1;e0?t:r.pts}),t[0].pts);return e&&c.b.debug("PTS rollover detected"),r},e.remux=function(t,e,r,i,a,n,s,o){var l,u,d,h,f,v,g=a,p=a,m=t.pid>-1,y=e.pid>-1,b=e.samples.length,T=t.samples.length>0,E=b>1;if((!m||T)&&(!y||E)||this.ISGenerated||s){this.ISGenerated||(d=this.generateIS(t,e,a));var S=this.isVideoContiguous,L=-1;if(E&&(L=function(t){for(var e=0;e0){c.b.warn("[mp4-remuxer]: Dropped "+L+" out of "+b+" video samples due to a missing keyframe");var A=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(L),e.dropped+=L,p+=(e.samples[0].pts-A)/(e.timescale||9e4)}else-1===L&&(c.b.warn("[mp4-remuxer]: No keyframe found out of "+b+" video samples"),v=!1);if(this.ISGenerated){if(T&&E){var R=this.getVideoStartPts(e.samples),D=(dt(t.samples[0].pts,R)-R)/e.inputTimeScale;g+=Math.max(0,D),p+=Math.max(0,-D)}if(T){if(t.samplerate||(c.b.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(t,e,a)),u=this.remuxAudio(t,g,this.isAudioContiguous,n,y||E||o===rt.b.AUDIO?p:void 0),E){var _=u?u.endPTS-u.startPTS:0;e.inputTimeScale||(c.b.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(t,e,a)),l=this.remuxVideo(e,p,S,_)}}else E&&(l=this.remuxVideo(e,p,S,0));l&&(l.firstKeyFrame=L,l.independent=-1!==L)}}return this.ISGenerated&&(r.samples.length&&(f=this.remuxID3(r,a)),i.samples.length&&(h=this.remuxText(i,a))),{audio:u,video:l,initSegment:d,independent:v,text:h,id3:f}},e.generateIS=function(t,e,r){var i,a,n,o=t.samples,l=e.samples,u=this.typeSupported,d={},h=!Object(s.a)(this._initPTS),f="audio/mp4";if(h&&(i=a=1/0),t.config&&o.length&&(t.timescale=t.samplerate,t.isAAC||(u.mpeg?(f="audio/mpeg",t.codec=""):u.mp3&&(t.codec="mp3")),d.audio={id:"audio",container:f,codec:t.codec,initSegment:!t.isAAC&&u.mpeg?new Uint8Array(0):et.initSegment([t]),metadata:{channelCount:t.channelCount}},h&&(n=t.inputTimeScale,i=a=o[0].pts-Math.round(n*r))),e.sps&&e.pps&&l.length&&(e.timescale=e.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:et.initSegment([e]),metadata:{width:e.width,height:e.height}},h)){n=e.inputTimeScale;var c=this.getVideoStartPts(l),v=Math.round(n*r);a=Math.min(a,dt(l[0].dts,c)-v),i=Math.min(i,c-v)}if(Object.keys(d).length)return this.ISGenerated=!0,h&&(this._initPTS=i,this._initDTS=a),{tracks:d,initPTS:i,timescale:n}},e.remuxVideo=function(t,e,r,n){var s,o,l,u=t.inputTimeScale,d=t.samples,h=[],f=d.length,v=this._initPTS,g=this.nextAvcDts,p=8,m=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,b=0,T=!1;r&&null!==g||(g=e*u-(d[0].pts-dt(d[0].dts,d[0].pts)));for(var E=0;ES.pts){b=Math.max(Math.min(b,S.pts-S.dts),-18e3)}S.dts0?E-1:E].dts&&(T=!0)}T&&d.sort((function(t,e){var r=t.dts-e.dts,i=t.pts-e.pts;return r||i})),o=d[0].dts,l=d[d.length-1].dts;var L=Math.round((l-o)/(f-1));if(b<0){if(b<-2*L){c.b.warn("PTS < DTS detected in video samples, offsetting DTS from PTS by "+at(-L,!0)+" ms");for(var A=b,R=0;RL;if(k||_<-1){k?c.b.warn("AVC: "+at(_,!0)+" ms ("+_+"dts) hole between fragments detected, filling it"):c.b.warn("AVC: "+at(-_,!0)+" ms ("+_+"dts) overlapping between fragments detected"),o=g;var x=d[0].pts-_;d[0].dts=o,d[0].pts=x,c.b.log("Video: First PTS/DTS adjusted: "+at(x,!0)+"/"+at(o,!0)+", delta: "+at(_,!0)+" ms")}}lt&&(o=Math.max(0,o));for(var C=0,w=0,O=0;O0?j-1:j].dts;if(Q.stretchShortVideoTrack&&null!==this.nextAudioPts){var Z=Math.floor(Q.maxBufferHole*u),J=(n?m+n*u:this.nextAudioPts)-H.pts;J>Z?((s=J-$)<0&&(s=$),c.b.log("[mp4-remuxer]: It is approximately "+J/90+" ms to the next segment; using duration "+s/90+" ms for the last video frame.")):s=$}else s=$}var tt=Math.round(H.pts-H.dts);h.push(new ht(H.key,s,V,tt))}if(h.length&&st&&st<70){var rt=h[0].flags;rt.dependsOn=2,rt.isNonSync=0}this.nextAvcDts=g=l+s,this.isVideoContiguous=!0;var it={data1:et.moof(t.sequenceNumber++,o,nt({},t,{samples:h})),data2:B,startPTS:m/u,endPTS:(y+s)/u,startDTS:o/u,endDTS:g/u,type:"video",hasAudio:!1,hasVideo:!0,nb:h.length,dropped:t.dropped};return t.samples=[],t.dropped=0,it},e.remuxAudio=function(t,e,r,n,s){var o=t.inputTimeScale,l=o/(t.samplerate?t.samplerate:o),u=t.isAAC?1024:1152,d=u*l,h=this._initPTS,f=!t.isAAC&&this.typeSupported.mpeg,v=[],g=t.samples,p=f?0:8,m=this.nextAudioPts||-1,y=e*o;if(this.isAudioContiguous=r=r||g.length&&m>0&&(n&&Math.abs(y-m)<9e3||Math.abs(dt(g[0].pts-h,y)-m)<20*d),g.forEach((function(t){t.pts=dt(t.pts-h,y)})),!r||m<0){if(!(g=g.filter((function(t){return t.pts>=0}))).length)return;m=0===s?0:n?Math.max(0,y):g[0].pts}if(t.isAAC)for(var b=void 0!==s,T=this.config.maxAudioFramesDrift,E=0,S=m;E=T*d&&D<1e4&&b){var _=Math.round(R/d);(S=A-_*d)<0&&(_--,S+=d),0===E&&(this.nextAudioPts=m=S),c.b.warn("[mp4-remuxer]: Injecting "+_+" audio frame @ "+(S/o).toFixed(3)+"s due to "+Math.round(1e3*R/o)+" ms gap.");for(var k=0;k<_;k++){var x=Math.max(S,0),C=Z.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);C||(c.b.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),C=L.unit.subarray()),g.splice(E,0,{unit:C,pts:x}),S+=d,E++}}L.pts=S,S+=d}for(var w,O=null,I=null,P=0,F=g.length;F--;)P+=g[F].unit.byteLength;for(var M=0,N=g.length;M0))return;P+=p;try{w=new Uint8Array(P)}catch(t){return void this.observer.emit(i.a.ERROR,i.a.ERROR,{type:a.b.MUX_ERROR,details:a.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:P,reason:"fail allocating audio mdat "+P})}f||(new DataView(w.buffer).setUint32(0,P),w.set(et.types.mdat,4))}w.set(U,p);var j=U.byteLength;p+=j,v.push(new ht(!0,u,j,0)),I=G}var H=v.length;if(H){var K=v[v.length-1];this.nextAudioPts=m=I+l*K.duration;var V=f?new Uint8Array(0):et.moof(t.sequenceNumber++,O/l,nt({},t,{samples:v}));t.samples=[];var W=O/o,Y=m/o,X={data1:V,data2:w,startPTS:W,endPTS:Y,startDTS:W,endDTS:Y,type:"audio",hasAudio:!0,hasVideo:!1,nb:H};return this.isAudioContiguous=!0,X}},e.remuxEmptyAudio=function(t,e,r,i){var a=t.inputTimeScale,n=a/(t.samplerate?t.samplerate:a),s=this.nextAudioPts,o=(null!==s?s:i.startDTS*a)+this._initDTS,l=i.endDTS*a+this._initDTS,u=1024*n,d=Math.ceil((l-o)/u),h=Z.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(c.b.warn("[mp4-remuxer]: remux empty Audio"),h){for(var f=[],v=0;v4294967296;)t+=r;return t}var ht=function(t,e,r,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=r,this.cts=i,this.flags=new ft(t)},ft=function(t){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=t?2:1,this.isNonSync=t?0:1},ct=r(5),vt=function(){function t(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=void 0,this.initTracks=void 0,this.lastEndDTS=null}var e=t.prototype;return e.destroy=function(){},e.resetTimeStamp=function(t){this.initPTS=t,this.lastEndDTS=null},e.resetNextTimestamp=function(){this.lastEndDTS=null},e.resetInitSegment=function(t,e,r){this.audioCodec=e,this.videoCodec=r,this.generateInitSegment(t),this.emitInitSegment=!0},e.generateInitSegment=function(t){var e=this.audioCodec,r=this.videoCodec;if(!t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var i=this.initData=Object(l.f)(t);e||(e=pt(i.audio,ct.a.AUDIO)),r||(r=pt(i.video,ct.a.VIDEO));var a={};i.audio&&i.video?a.audiovideo={container:"video/mp4",codec:e+","+r,initSegment:t,id:"main"}:i.audio?a.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:i.video?a.video={container:"video/mp4",codec:r,initSegment:t,id:"main"}:c.b.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=a},e.remux=function(t,e,r,i,a){var n=this.initPTS,o=this.lastEndDTS,u={audio:void 0,video:void 0,text:i,id3:r,initSegment:void 0};Object(s.a)(o)||(o=this.lastEndDTS=a||0);var d=e.samples;if(!d||!d.length)return u;var h={initPTS:void 0,timescale:1},f=this.initData;if(f&&f.length||(this.generateInitSegment(d),f=this.initData),!f||!f.length)return c.b.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1),Object(s.a)(n)||(this.initPTS=h.initPTS=n=gt(f,d,o));var v=Object(l.c)(d,f),g=o,p=v+g;Object(l.e)(f,d,n),v>0?this.lastEndDTS=p:(c.b.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var m=!!f.audio,y=!!f.video,b="";m&&(b+="audio"),y&&(b+="video");var T={data1:d,startPTS:g,startDTS:g,endPTS:p,endDTS:p,type:b,hasAudio:m,hasVideo:y,nb:1,dropped:0};return u.audio="audio"===T.type?T:void 0,u.video="audio"!==T.type?T:void 0,u.text=i,u.id3=r,u.initSegment=h,u},t}(),gt=function(t,e,r){return Object(l.d)(t,e)-r};function pt(t,e){var r=null==t?void 0:t.codec;return r&&r.length>4?r:"hvc1"===r?"hvc1.1.c.L120.90":"av01"===r?"av01.0.04M.08":"avc1"===r||e===ct.a.VIDEO?"avc1.42e01e":"mp4a.40.5"}var mt,yt=vt,bt=r(16);try{mt=self.performance.now.bind(self.performance)}catch(t){c.b.debug("Unable to use Performance API on this environment"),mt=self.Date.now}var Tt=[{demux:q,remux:ut},{demux:D,remux:yt},{demux:A,remux:ut},{demux:$,remux:ut}],Et=1024;Tt.forEach((function(t){var e=t.demux;Et=Math.max(Et,e.minProbeByteLength)}));var St=function(){function t(t,e,r,i,a){this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.cache=new bt.a,this.observer=t,this.typeSupported=e,this.config=r,this.vendor=i,this.id=a}var e=t.prototype;return e.configure=function(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()},e.push=function(t,e,r,i){var a=this,n=r.transmuxing;n.executeStart=mt();var s=new Uint8Array(t),o=this.cache,u=this.config,d=this.currentTransmuxState,h=this.transmuxConfig;i&&(this.currentTransmuxState=i);var f=function(t,e){var r=null;t.byteLength>0&&null!=e&&null!=e.key&&null!==e.iv&&null!=e.method&&(r=e);return r}(s,e);if(f&&"AES-128"===f.method){var c=this.getDecrypter();if(!u.enableSoftwareAES)return this.decryptionPromise=c.webCryptoDecrypt(s,f.key.buffer,f.iv.buffer).then((function(t){var e=a.push(t,null,r);return a.decryptionPromise=null,e})),this.decryptionPromise;var v=c.softwareDecrypt(s,f.key.buffer,f.iv.buffer);if(!v)return n.executeEnd=mt(),Lt(r);s=new Uint8Array(v)}var g=i||d,p=g.contiguous,m=g.discontinuity,y=g.trackSwitch,b=g.accurateTimeOffset,T=g.timeOffset,E=g.initSegmentChange,S=h.audioCodec,L=h.videoCodec,A=h.defaultInitPts,R=h.duration,D=h.initSegmentData;if((m||y||E)&&this.resetInitSegment(D,S,L,R),(m||E)&&this.resetInitialTimestamp(A),p||this.resetContiguity(),this.needsProbing(s,m,y)){if(o.dataLength){var _=o.flush();s=Object(l.a)(_,s)}this.configureTransmuxer(s,h)}var k=this.transmux(s,f,T,b,r),x=this.currentTransmuxState;return x.contiguous=!0,x.discontinuity=!1,x.trackSwitch=!1,n.executeEnd=mt(),k},e.flush=function(t){var e=this,r=t.transmuxing;r.executeStart=mt();var n=this.decrypter,s=this.cache,o=this.currentTransmuxState,l=this.decryptionPromise;if(l)return l.then((function(){return e.flush(t)}));var u=[],d=o.timeOffset;if(n){var h=n.flush();h&&u.push(this.push(h,null,t))}var f=s.dataLength;s.reset();var c=this.demuxer,v=this.remuxer;if(!c||!v)return f>=Et&&this.observer.emit(i.a.ERROR,i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"}),r.executeEnd=mt(),[Lt(t)];var g=c.flush(d);return At(g)?g.then((function(r){return e.flushRemux(u,r,t),u})):(this.flushRemux(u,g,t),u)},e.flushRemux=function(t,e,r){var i=e.audioTrack,a=e.avcTrack,n=e.id3Track,s=e.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;c.b.log("[transmuxer.ts]: Flushed fragment "+r.sn+(r.part>-1?" p: "+r.part:"")+" of level "+r.level);var d=this.remuxer.remux(i,a,n,s,u,l,!0,this.id);t.push({remuxResult:d,chunkMeta:r}),r.transmuxing.executeEnd=mt()},e.resetInitialTimestamp=function(t){var e=this.demuxer,r=this.remuxer;e&&r&&(e.resetTimeStamp(t),r.resetTimeStamp(t))},e.resetContiguity=function(){var t=this.demuxer,e=this.remuxer;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())},e.resetInitSegment=function(t,e,r,i){var a=this.demuxer,n=this.remuxer;a&&n&&(a.resetInitSegment(e,r,i),n.resetInitSegment(t,e,r))},e.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},e.transmux=function(t,e,r,i,a){return e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,r,i,a):this.transmuxUnencrypted(t,r,i,a)},e.transmuxUnencrypted=function(t,e,r,i){var a=this.demuxer.demux(t,e,!1,!this.config.progressive),n=a.audioTrack,s=a.avcTrack,o=a.id3Track,l=a.textTrack;return{remuxResult:this.remuxer.remux(n,s,o,l,e,r,!1,this.id),chunkMeta:i}},e.transmuxSampleAes=function(t,e,r,i,a){var n=this;return this.demuxer.demuxSampleAes(t,e,r).then((function(t){return{remuxResult:n.remuxer.remux(t.audioTrack,t.avcTrack,t.id3Track,t.textTrack,r,i,!1,n.id),chunkMeta:a}}))},e.configureTransmuxer=function(t,e){for(var r,i=this.config,a=this.observer,n=this.typeSupported,s=this.vendor,o=e.audioCodec,l=e.defaultInitPts,u=e.duration,d=e.initSegmentData,h=e.videoCodec,f=0,v=Tt.length;f>>8^255&p^99,t[c]=p,e[p]=c;var m=f[c],y=f[m],b=f[y],T=257*f[p]^16843008*p;i[c]=T<<24|T>>>8,a[c]=T<<16|T>>>16,n[c]=T<<8|T>>>24,s[c]=T,T=16843009*b^65537*y^257*m^16843008*c,l[p]=T<<24|T>>>8,u[p]=T<<16|T>>>16,d[p]=T<<8|T>>>24,h[p]=T,c?(c=m^f[f[f[b^m]]],v^=f[f[v]]):c=v=1}},e.expandKey=function(t){for(var e=this.uint8ArrayToUint32Array_(t),r=!0,i=0;i0}),!1)}t.exports=function(t,e){e=e||{};var a={main:r.m},o=e.all?{main:Object.keys(a.main)}:function(t,e){for(var r={main:[e]},i={main:[]},a={main:{}};s(r);)for(var o=Object.keys(r),l=0;lt.endSN||e>0||0===e&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay},e=t,(r=[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&Object(a.a)(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var t=this.driftEndTime-this.driftStartTime;return t>0?1e3*(this.driftEnd-this.driftStart)/t:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){var t;return null!==(t=this.fragments)&&void 0!==t&&t.length?this.fragments[this.fragments.length-1].end:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].index:-1}},{key:"lastPartSn",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}])&&d(e.prototype,r),i&&d(e,i),t}(),f=r(15),c=/^(\d+)x(\d+)$/,v=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,g=function(){function t(e){for(var r in"string"==typeof e&&(e=t.parseAttrList(e)),e)e.hasOwnProperty(r)&&(this[r]=e[r])}var e=t.prototype;return e.decimalInteger=function(t){var e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e},e.hexadecimalInteger=function(t){if(this[t]){var e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;for(var r=new Uint8Array(e.length/2),i=0;iNumber.MAX_SAFE_INTEGER?1/0:e},e.decimalFloatingPoint=function(t){return parseFloat(this[t])},e.optionalFloat=function(t,e){var r=this[t];return r?parseFloat(r):e},e.enumeratedString=function(t){return this[t]},e.bool=function(t){return"YES"===this[t]},e.decimalResolution=function(t){var e=c.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}},t.parseAttrList=function(t){var e,r={};for(v.lastIndex=0;null!==(e=v.exec(t));){var i=e[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[e[1]]=i}return r},t}(),p={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dvav:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}};function m(t,e){return MediaSource.isTypeSupported((e||"video")+'/mp4;codecs="'+t+'"')}var y=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-SESSION-DATA:([^\r\n]*)[\r\n]+/g,b=/#EXT-X-MEDIA:(.*)/g,T=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),E=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(PLAYLIST-TYPE):(.+)/.source,/#EXT-X-(MEDIA-SEQUENCE): *(\d+)/.source,/#EXT-X-(SKIP):(.+)/.source,/#EXT-X-(TARGETDURATION): *(\d+)/.source,/#EXT-X-(KEY):(.+)/.source,/#EXT-X-(START):(.+)/.source,/#EXT-X-(ENDLIST)/.source,/#EXT-X-(DISCONTINUITY-SEQ)UENCE: *(\d+)/.source,/#EXT-X-(DIS)CONTINUITY/.source,/#EXT-X-(VERSION):(\d+)/.source,/#EXT-X-(MAP):(.+)/.source,/#EXT-X-(SERVER-CONTROL):(.+)/.source,/#EXT-X-(PART-INF):(.+)/.source,/#EXT-X-(GAP)/.source,/#EXT-X-(BITRATE):\s*(\d+)/.source,/#EXT-X-(PART):(.+)/.source,/#EXT-X-(PRELOAD-HINT):(.+)/.source,/#EXT-X-(RENDITION-REPORT):(.+)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),S=/\.(mp4|m4s|m4v|m4a)$/i;var L=function(){function t(){}return t.findGroup=function(t,e){for(var r=0;r2){var r=e.shift()+".";return r+=parseInt(e.shift()).toString(16),r+=("000"+parseInt(e.shift()).toString(16)).substr(-4)}return t},t.resolve=function(t,e){return i.buildAbsoluteURL(e,t,{alwaysNormalize:!0})},t.parseMasterPlaylist=function(e,r){var i,a=[],n={},s=!1;for(y.lastIndex=0;null!=(i=y.exec(e));)if(i[1]){var o=new g(i[1]),l={attrs:o,bitrate:o.decimalInteger("AVERAGE-BANDWIDTH")||o.decimalInteger("BANDWIDTH"),name:o.NAME,url:t.resolve(i[2],r)},u=o.decimalResolution("RESOLUTION");u&&(l.width=u.width,l.height=u.height),A((o.CODECS||"").split(/[ ,]+/).filter((function(t){return t})),l),l.videoCodec&&-1!==l.videoCodec.indexOf("avc1")&&(l.videoCodec=t.convertAVC1ToAVCOTI(l.videoCodec)),a.push(l)}else if(i[3]){var d=new g(i[3]);d["DATA-ID"]&&(s=!0,n[d["DATA-ID"]]=d)}return{levels:a,sessionData:s?n:null}},t.parseMasterPlaylistMedia=function(e,r,i,a){var n;void 0===a&&(a=[]);var s=[],o=0;for(b.lastIndex=0;null!==(n=b.exec(e));){var l=new g(n[1]);if(l.TYPE===i){var u={attrs:l,bitrate:0,id:o++,groupId:l["GROUP-ID"],instreamId:l["INSTREAM-ID"],name:l.NAME||l.LANGUAGE||"",type:i,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:l.LANGUAGE,url:l.URI?t.resolve(l.URI,r):""};if(a.length){var d=t.findGroup(a,u.groupId)||a[0];R(u,d,"audioCodec"),R(u,d,"textCodec")}s.push(u)}}return s},t.parseLevelPlaylist=function(t,e,r,n,s){var l,d,c,v=new h(e),p=v.fragments,m=null,y=0,b=0,L=0,A=0,R=null,_=new u.b(n,e),k=-1,x=!1;for(T.lastIndex=0,v.m3u8=t;null!==(l=T.exec(t));){x&&(x=!1,(_=new u.b(n,e)).start=L,_.sn=y,_.cc=A,_.level=r,m&&(_.initSegment=m,_.rawProgramDateTime=m.rawProgramDateTime));var C=l[1];if(C){_.duration=parseFloat(C);var w=(" "+l[2]).slice(1);_.title=w||null,_.tagList.push(w?["INF",C,w]:["INF",C])}else if(l[3])Object(a.a)(_.duration)&&(_.start=L,c&&(_.levelkey=c),_.sn=y,_.level=r,_.cc=A,_.urlId=s,p.push(_),_.relurl=(" "+l[3]).slice(1),D(_,R),R=_,L+=_.duration,y++,b=0,x=!0);else if(l[4]){var O=(" "+l[4]).slice(1);R?_.setByteRange(O,R):_.setByteRange(O)}else if(l[5])_.rawProgramDateTime=(" "+l[5]).slice(1),_.tagList.push(["PROGRAM-DATE-TIME",_.rawProgramDateTime]),-1===k&&(k=p.length);else{if(!(l=l[0].match(E))){o.b.warn("No matches on slow regex match for level playlist!");continue}for(d=1;d-1){o.b.warn("Keyformat "+X+" is not supported from the manifest");continue}if("identity"!==X)continue;H&&(c=f.a.fromURL(e,K),K&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(H)>=0&&(c.method=H,c.keyFormat=X,Y&&(c.keyID=Y),W&&(c.keyFormatVersions=W),c.iv=V));break;case"START":var q=new g(P).decimalFloatingPoint("TIME-OFFSET");Object(a.a)(q)&&(v.startTimeOffset=q);break;case"MAP":var z=new g(P);_.relurl=z.URI,z.BYTERANGE&&_.setByteRange(z.BYTERANGE),_.level=r,_.sn="initSegment",c&&(_.levelkey=c),_.initSegment=null,m=_,x=!0;break;case"SERVER-CONTROL":var Q=new g(P);v.canBlockReload=Q.bool("CAN-BLOCK-RELOAD"),v.canSkipUntil=Q.optionalFloat("CAN-SKIP-UNTIL",0),v.canSkipDateRanges=v.canSkipUntil>0&&Q.bool("CAN-SKIP-DATERANGES"),v.partHoldBack=Q.optionalFloat("PART-HOLD-BACK",0),v.holdBack=Q.optionalFloat("HOLD-BACK",0);break;case"PART-INF":var $=new g(P);v.partTarget=$.decimalFloatingPoint("PART-TARGET");break;case"PART":var Z=v.partList;Z||(Z=v.partList=[]);var J=b>0?Z[Z.length-1]:void 0,tt=b++,et=new u.c(new g(P),_,e,tt,J);Z.push(et),_.duration+=et.duration;break;case"PRELOAD-HINT":var rt=new g(P);v.preloadHint=rt;break;case"RENDITION-REPORT":var it=new g(P);v.renditionReports=v.renditionReports||[],v.renditionReports.push(it);break;default:o.b.warn("line parsed but not handled: "+l)}}}R&&!R.relurl?(p.pop(),L-=R.duration,v.partList&&(v.fragmentHint=R)):v.partList&&(D(_,R),_.cc=A,v.fragmentHint=_);var at=p.length,nt=p[0],st=p[at-1];if((L+=v.skippedSegments*v.targetduration)>0&&at&&st){v.averagetargetduration=L/at;var ot=st.sn;v.endSN="initSegment"!==ot?ot:0,nt&&(v.startCC=nt.cc,nt.initSegment||v.fragments.every((function(t){return t.relurl&&(e=t.relurl,S.test(null!=(r=null===(a=i.parseURL(e))||void 0===a?void 0:a.path)?r:""));var e,r,a}))&&(o.b.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),(_=new u.b(n,e)).relurl=st.relurl,_.level=r,_.sn="initSegment",nt.initSegment=_,v.needSidxRanges=!0))}else v.endSN=0,v.startCC=0;return v.fragmentHint&&(L+=v.fragmentHint.duration),v.totalduration=L,v.endCC=A,k>0&&function(t,e){for(var r=t[e],i=e;i--;){var a=t[i];if(!a)return;a.programDateTime=r.programDateTime-1e3*a.duration,r=a}}(p,k),v},t}();function A(t,e){["video","audio","text"].forEach((function(r){var i=t.filter((function(t){return function(t,e){var r=p[e];return!!r&&!0===r[t.slice(0,4)]}(t,r)}));if(i.length){var a=i.filter((function(t){return 0===t.lastIndexOf("avc1",0)||0===t.lastIndexOf("mp4a",0)}));e[r+"Codec"]=a.length>0?a[0]:i[0],t=t.filter((function(t){return-1===i.indexOf(t)}))}})),e.unknownCodecs=t}function R(t,e,r){var i=e[r];i&&(t[r]=i)}function D(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),Object(a.a)(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}var _=r(4);function k(t,e){var r=t.url;return void 0!==r&&0!==r.indexOf("data:")||(r=e.url),r}var x=function(){function t(t){this.hls=void 0,this.loaders=Object.create(null),this.hls=t,this.registerListeners()}var e=t.prototype;return e.registerListeners=function(){var t=this.hls;t.on(n.a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.a.LEVEL_LOADING,this.onLevelLoading,this),t.on(n.a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(n.a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.unregisterListeners=function(){var t=this.hls;t.off(n.a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.a.LEVEL_LOADING,this.onLevelLoading,this),t.off(n.a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(n.a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.createInternalLoader=function(t){var e=this.hls.config,r=e.pLoader,i=e.loader,a=new(r||i)(e);return t.loader=a,this.loaders[t.type]=a,a},e.getInternalLoader=function(t){return this.loaders[t.type]},e.resetInternalLoader=function(t){this.loaders[t]&&delete this.loaders[t]},e.destroyInternalLoaders=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}},e.destroy=function(){this.unregisterListeners(),this.destroyInternalLoaders()},e.onManifestLoading=function(t,e){var r=e.url;this.load({id:null,groupId:null,level:0,responseType:"text",type:_.a.MANIFEST,url:r,deliveryDirectives:null})},e.onLevelLoading=function(t,e){var r=e.id,i=e.level,a=e.url,n=e.deliveryDirectives;this.load({id:r,groupId:null,level:i,responseType:"text",type:_.a.LEVEL,url:a,deliveryDirectives:n})},e.onAudioTrackLoading=function(t,e){var r=e.id,i=e.groupId,a=e.url,n=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:_.a.AUDIO_TRACK,url:a,deliveryDirectives:n})},e.onSubtitleTrackLoading=function(t,e){var r=e.id,i=e.groupId,a=e.url,n=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:_.a.SUBTITLE_TRACK,url:a,deliveryDirectives:n})},e.load=function(t){var e,r,i,a,n,s,l=this.hls.config,u=this.getInternalLoader(t);if(u){var d=u.context;if(d&&d.url===t.url)return void o.b.trace("[playlist-loader]: playlist request ongoing");o.b.log("[playlist-loader]: aborting previous loader for type: "+t.type),u.abort()}switch(t.type){case _.a.MANIFEST:r=l.manifestLoadingMaxRetry,i=l.manifestLoadingTimeOut,a=l.manifestLoadingRetryDelay,n=l.manifestLoadingMaxRetryTimeout;break;case _.a.LEVEL:case _.a.AUDIO_TRACK:case _.a.SUBTITLE_TRACK:r=0,i=l.levelLoadingTimeOut;break;default:r=l.levelLoadingMaxRetry,i=l.levelLoadingTimeOut,a=l.levelLoadingRetryDelay,n=l.levelLoadingMaxRetryTimeout}if((u=this.createInternalLoader(t),null!==(e=t.deliveryDirectives)&&void 0!==e&&e.part)&&(t.type===_.a.LEVEL&&null!==t.level?s=this.hls.levels[t.level].details:t.type===_.a.AUDIO_TRACK&&null!==t.id?s=this.hls.audioTracks[t.id].details:t.type===_.a.SUBTITLE_TRACK&&null!==t.id&&(s=this.hls.subtitleTracks[t.id].details),s)){var h=s.partTarget,f=s.targetduration;h&&f&&(i=Math.min(1e3*Math.max(3*h,.8*f),i))}var c={timeout:i,maxRetry:r,retryDelay:a,maxRetryDelay:n,highWaterMark:0},v={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};u.load(t,c,v)},e.loadsuccess=function(t,e,r,i){if(void 0===i&&(i=null),r.isSidxRequest)return this.handleSidxRequest(t,r),void this.handlePlaylistLoaded(t,e,r,i);this.resetInternalLoader(r.type);var a=t.data;0===a.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),a.indexOf("#EXTINF:")>0||a.indexOf("#EXT-X-TARGETDURATION:")>0?this.handleTrackOrLevelPlaylist(t,e,r,i):this.handleMasterPlaylist(t,e,r,i)):this.handleManifestParsingError(t,r,"no EXTM3U delimiter",i)},e.loaderror=function(t,e,r){void 0===r&&(r=null),this.handleNetworkError(e,r,!1,t)},e.loadtimeout=function(t,e,r){void 0===r&&(r=null),this.handleNetworkError(e,r,!0)},e.handleMasterPlaylist=function(t,e,r,i){var a=this.hls,s=t.data,l=k(t,r),u=L.parseMasterPlaylist(s,l),d=u.levels,h=u.sessionData;if(d.length){var f=d.map((function(t){return{id:t.attrs.AUDIO,audioCodec:t.audioCodec}})),c=d.map((function(t){return{id:t.attrs.SUBTITLES,textCodec:t.textCodec}})),v=L.parseMasterPlaylistMedia(s,l,"AUDIO",f),p=L.parseMasterPlaylistMedia(s,l,"SUBTITLES",c),m=L.parseMasterPlaylistMedia(s,l,"CLOSED-CAPTIONS");if(v.length)v.some((function(t){return!t.url}))||!d[0].audioCodec||d[0].attrs.AUDIO||(o.b.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),v.unshift({type:"main",name:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new g({}),bitrate:0,url:""}));a.trigger(n.a.MANIFEST_LOADED,{levels:d,audioTracks:v,subtitles:p,captions:m,url:l,stats:e,networkDetails:i,sessionData:h})}else this.handleManifestParsingError(t,r,"no level found in manifest",i)},e.handleTrackOrLevelPlaylist=function(t,e,r,i){var o=this.hls,l=r.id,u=r.level,d=r.type,h=k(t,r),f=Object(a.a)(l)?l:0,c=Object(a.a)(u)?u:f,v=function(t){switch(t.type){case _.a.AUDIO_TRACK:return _.b.AUDIO;case _.a.SUBTITLE_TRACK:return _.b.SUBTITLE;default:return _.b.MAIN}}(r),p=L.parseLevelPlaylist(t.data,h,c,v,f);if(p.fragments.length){if(d===_.a.MANIFEST){var m={attrs:new g({}),bitrate:0,details:p,name:"",url:h};o.trigger(n.a.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:h,stats:e,networkDetails:i,sessionData:null})}if(e.parsing.end=performance.now(),p.needSidxRanges){var y,b=null===(y=p.fragments[0].initSegment)||void 0===y?void 0:y.url;this.load({url:b,isSidxRequest:!0,type:d,level:u,levelDetails:p,id:l,groupId:null,rangeStart:0,rangeEnd:2048,responseType:"arraybuffer",deliveryDirectives:null})}else r.levelDetails=p,this.handlePlaylistLoaded(t,e,r,i)}else o.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.LEVEL_EMPTY_ERROR,fatal:!1,url:h,reason:"no fragments found in level",level:"number"==typeof r.level?r.level:void 0})},e.handleSidxRequest=function(t,e){var r=Object(l.g)(new Uint8Array(t.data));if(r){var i=r.references,a=e.levelDetails;i.forEach((function(t,e){var i=t.info,n=a.fragments[e];0===n.byteRange.length&&n.setByteRange(String(1+i.end-i.start)+"@"+String(i.start)),n.initSegment&&n.initSegment.setByteRange(String(r.moovEndOffset)+"@0")}))}},e.handleManifestParsingError=function(t,e,r,i){this.hls.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.MANIFEST_PARSING_ERROR,fatal:e.type===_.a.MANIFEST,url:t.url,reason:r,response:t,context:e,networkDetails:i})},e.handleNetworkError=function(t,e,r,i){void 0===r&&(r=!1),o.b.warn("[playlist-loader]: A network "+(r?"timeout":"error")+" occurred while loading "+t.type+" level: "+t.level+" id: "+t.id+' group-id: "'+t.groupId+'"');var a=s.a.UNKNOWN,l=!1,u=this.getInternalLoader(t);switch(t.type){case _.a.MANIFEST:a=r?s.a.MANIFEST_LOAD_TIMEOUT:s.a.MANIFEST_LOAD_ERROR,l=!0;break;case _.a.LEVEL:a=r?s.a.LEVEL_LOAD_TIMEOUT:s.a.LEVEL_LOAD_ERROR,l=!1;break;case _.a.AUDIO_TRACK:a=r?s.a.AUDIO_TRACK_LOAD_TIMEOUT:s.a.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case _.a.SUBTITLE_TRACK:a=r?s.a.SUBTITLE_TRACK_LOAD_TIMEOUT:s.a.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(t.type);var d={type:s.b.NETWORK_ERROR,details:a,fatal:l,url:t.url,loader:u,context:t,networkDetails:e};i&&(d.response=i),this.hls.trigger(n.a.ERROR,d)},e.handlePlaylistLoaded=function(t,e,r,i){var a=r.type,s=r.level,o=r.id,l=r.groupId,u=r.loader,d=r.levelDetails,h=r.deliveryDirectives;if(null!=d&&d.targetduration){if(u)switch(d.live&&(u.getCacheAge&&(d.ageHeader=u.getCacheAge()||0),u.getCacheAge&&!isNaN(d.ageHeader)||(d.ageHeader=0)),a){case _.a.MANIFEST:case _.a.LEVEL:this.hls.trigger(n.a.LEVEL_LOADED,{details:d,level:s||0,id:o||0,stats:e,networkDetails:i,deliveryDirectives:h});break;case _.a.AUDIO_TRACK:this.hls.trigger(n.a.AUDIO_TRACK_LOADED,{details:d,id:o||0,groupId:l||"",stats:e,networkDetails:i,deliveryDirectives:h});break;case _.a.SUBTITLE_TRACK:this.hls.trigger(n.a.SUBTITLE_TRACK_LOADED,{details:d,id:o||0,groupId:l||"",stats:e,networkDetails:i,deliveryDirectives:h})}}else this.handleManifestParsingError(t,r,"invalid target duration",i)},t}(),C=function(){function t(t){this.hls=void 0,this.loaders={},this.decryptkey=null,this.decrypturl=null,this.hls=t,this._registerListeners()}var e=t.prototype;return e._registerListeners=function(){this.hls.on(n.a.KEY_LOADING,this.onKeyLoading,this)},e._unregisterListeners=function(){this.hls.off(n.a.KEY_LOADING,this.onKeyLoading)},e.destroy=function(){for(var t in this._unregisterListeners(),this.loaders){var e=this.loaders[t];e&&e.destroy()}this.loaders={}},e.onKeyLoading=function(t,e){var r=e.frag,i=r.type,a=this.loaders[i];if(r.decryptdata){var s=r.decryptdata.uri;if(s!==this.decrypturl||null===this.decryptkey){var l=this.hls.config;if(a&&(o.b.warn("abort previous key loader for type:"+i),a.abort()),!s)return void o.b.warn("key uri is falsy");var u=l.loader,d=r.loader=this.loaders[i]=new u(l);this.decrypturl=s,this.decryptkey=null;var h={url:s,frag:r,responseType:"arraybuffer"},f={timeout:l.fragLoadingTimeOut,maxRetry:0,retryDelay:l.fragLoadingRetryDelay,maxRetryDelay:l.fragLoadingMaxRetryTimeout,highWaterMark:0},c={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};d.load(h,f,c)}else this.decryptkey&&(r.decryptdata.key=this.decryptkey,this.hls.trigger(n.a.KEY_LOADED,{frag:r}))}else o.b.warn("Missing decryption data on fragment in onKeyLoading")},e.loadsuccess=function(t,e,r){var i=r.frag;i.decryptdata?(this.decryptkey=i.decryptdata.key=new Uint8Array(t.data),i.loader=null,delete this.loaders[i.type],this.hls.trigger(n.a.KEY_LOADED,{frag:i})):o.b.error("after key load, decryptdata unset")},e.loaderror=function(t,e){var r=e.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.KEY_LOAD_ERROR,fatal:!1,frag:r,response:t})},e.loadtimeout=function(t,e){var r=e.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},t}();function w(t,e){var r;try{r=new Event("addtrack")}catch(t){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=t,e.dispatchEvent(r)}function O(t,e,r){var i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&t.cues.length>0)for(var a=function(t,e,r){var i=[],a=function(t,e){if(et[r].endTime)return-1;var i=0,a=r;for(;i<=a;){var n=Math.floor((a+i)/2);if(et[n].startTime&&i-1)for(var n=a,s=t.length;n=e&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(t.cues,e,r),n=0;n.05&&this.forwardBufferLength>1){var u=Math.min(2,Math.max(1,n)),d=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;t.playbackRate=Math.min(u,Math.max(1,d))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}}}}},a.estimateLiveEdge=function(){var t=this.levelDetails;return null===t?null:t.edge+t.age},a.computeLatency=function(){var t=this.estimateLiveEdge();return null===t?null:t-this.currentTime},e=t,(r=[{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var t=this.config,e=this.levelDetails;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}},{key:"targetLatency",get:function(){var t=this.levelDetails;if(null===t)return null;var e=t.holdBack,r=t.partHoldBack,i=t.targetduration,a=this.config,n=a.liveSyncDuration,s=a.liveSyncDurationCount,o=a.lowLatencyMode,l=this.hls.userConfig,u=o&&r||e;(l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==n?n:s*i);var d=i;return u+Math.min(1*this.stallCount,d)}},{key:"liveSyncPosition",get:function(){var t=this.estimateLiveEdge(),e=this.targetLatency,r=this.levelDetails;if(null===t||null===e||null===r)return null;var i=r.edge,a=t-e-this.edgeStalled,n=i-r.totalduration,s=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(n,a),s)}},{key:"drift",get:function(){var t=this.levelDetails;return null===t?1:t.drift}},{key:"edgeStalled",get:function(){var t=this.levelDetails;if(null===t)return 0;var e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}},{key:"forwardBufferLength",get:function(){var t=this.media,e=this.levelDetails;if(!t||!e)return 0;var r=t.buffered.length;return r?t.buffered.end(r-1):e.edge-this.currentTime}}])&&F(e.prototype,r),i&&F(e,i),t}();function B(t,e){for(var r=0;rt.sn?(n=r-t.start,i=t):(n=t.start-r,i=e),i.duration!==n&&(i.duration=n)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration}else e.start=Math.max(t.start-e.duration,0)}function V(t,e,r,i,n,s){i-r<=0&&(o.b.warn("Fragment should have a positive duration",e),i=r+e.duration,s=n+e.duration);var l=r,u=i,d=e.startPTS,h=e.endPTS;if(Object(a.a)(d)){var f=Math.abs(d-r);Object(a.a)(e.deltaPTS)?e.deltaPTS=Math.max(f,e.deltaPTS):e.deltaPTS=f,l=Math.max(r,d),r=Math.min(r,d),n=Math.min(n,e.startDTS),u=Math.min(i,h),i=Math.max(i,h),s=Math.max(s,e.endDTS)}e.duration=i-r;var c=r-e.start;e.appendedPTS=i,e.start=e.startPTS=r,e.maxStartPTS=l,e.startDTS=n,e.endPTS=i,e.minEndPTS=u,e.endDTS=s;var v,g=e.sn;if(!t||gt.endSN)return 0;var p=g-t.startSN,m=t.fragments;for(m[p]=e,v=p;v>0;v--)K(m[v],m[v-1]);for(v=p;v=0;n--){var s=i[n].initSegment;if(s){r=s;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;var l,u=0;(function(t,e,r){for(var i=e.skippedSegments,a=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(i?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,s=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,u=a;u<=n;u++){var d=l[s+u],h=o[u];i&&!h&&u=i.length||function(t,e){if(e){for(var r=t.fragments,i=t.skippedSegments;ie.partTarget&&(l+=1)}if(Object(a.a)(o))return new U(o,Object(a.a)(l)?l:void 0,M.No)}}},e.loadPlaylist=function(t){},e.shouldLoadTrack=function(t){return this.canLoad&&t&&!!t.url&&(!t.details||t.details.live)},e.playlistLoaded=function(t,e,r){var i=this,a=e.details,n=e.stats,s=n.loading.end?Math.max(0,self.performance.now()-n.loading.end):0;if(a.advancedDateTime=Date.now()-s,a.live||null!=r&&r.live){if(a.reloaded(r),r&&this.log("live playlist "+t+" "+(a.advanced?"REFRESHED "+a.lastPartSn+"-"+a.lastPartIndex:"MISSED")),r&&a.fragments.length>0&&W(r,a),!this.canLoad||!a.live)return;var o,l=void 0,u=void 0;if(a.canBlockReload&&a.endSN&&a.advanced){var d=this.hls.config.lowLatencyMode,h=a.lastPartSn,f=a.endSN,c=a.lastPartIndex,v=h===f;-1!==c?(l=v?f+1:h,u=v?d?0:c:c+1):l=f+1;var g=a.age,p=g+a.ageHeader,m=Math.min(p-a.partTarget,1.5*a.targetduration);if(m>0){if(r&&m>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+m+" with playlist age: "+a.age),m=0;else{var y=Math.floor(m/a.targetduration);if(l+=y,void 0!==u)u+=Math.round(m%a.targetduration/a.partTarget);this.log("CDN Tune-in age: "+a.ageHeader+"s last advanced "+g.toFixed(2)+"s goal: "+m+" skip sn "+y+" to part "+u)}a.tuneInGoal=m}if(o=this.getDeliveryDirectives(a,e.deliveryDirectives,l,u),d||!v)return void this.loadPlaylist(o)}else o=this.getDeliveryDirectives(a,e.deliveryDirectives,l,u);var b=function(t,e){var r,i=1e3*t.levelTargetDuration,a=i/2,n=t.age,s=n>0&&n<3*i,o=e.loading.end-e.loading.start,l=t.availabilityDelay;if(!1===t.updated)if(s){var u=333*t.misses;r=Math.max(Math.min(a,2*o),u),t.availabilityDelay=(t.availabilityDelay||0)+r}else r=a;else s?(l=Math.min(l||i/2,n),t.availabilityDelay=l,r=l+i-n):r=i-o;return Math.round(r)}(a,n);void 0!==l&&a.canBlockReload&&(b-=a.partTarget||1),this.log("reload live playlist "+t+" in "+Math.round(b)+" ms"),this.timer=self.setTimeout((function(){return i.loadPlaylist(o)}),b)}else this.clearTimer()},e.getDeliveryDirectives=function(t,e,r,i){var a=function(t,e){var r=t.canSkipUntil,i=t.canSkipDateRanges,a=t.endSN;return r&&(void 0!==e?e-a:0)-1&&null!==(e=t.context)&&void 0!==e&&e.deliveryDirectives)this.warn("retry playlist loading #"+this.retryCount+' after "'+t.details+'"'),this.loadPlaylist();else{var n=Math.min(Math.pow(2,this.retryCount)*i.levelLoadingRetryDelay,i.levelLoadingMaxRetryTimeout);this.timer=self.setTimeout((function(){return r.loadPlaylist()}),n),this.warn("retry playlist loading #"+this.retryCount+" in "+n+' ms after "'+t.details+'"')}else this.warn('cannot recover from error "'+t.details+'"'),this.clearTimer(),t.fatal=!0;return a},t}();function q(){return(q=Object.assign||function(t){for(var e=1;e0){r=a[0].bitrate,a.sort((function(t,e){return t.bitrate-e.bitrate})),this._levels=a;for(var c=0;cthis.hls.config.fragLoadingMaxRetry&&(n=r.frag.level)):n=r.frag.level}break;case s.a.LEVEL_LOAD_ERROR:case s.a.LEVEL_LOAD_TIMEOUT:i&&(i.deliveryDirectives&&(l=!1),n=i.level),o=!0;break;case s.a.REMUX_ALLOC_ERROR:n=r.level,o=!0}void 0!==n&&this.recoverLevel(r,n,o,l)}}},u.recoverLevel=function(t,e,r,i){var a=t.details,n=this._levels[e];if(n.loadError++,r){if(!this.retryLoadingOrFail(t))return void(this.currentLevelIndex=-1);t.levelRetry=!0}if(i){var s=n.url.length;if(s>1&&n.loadError1){var i=(e.urlId+1)%r;this.warn("Switching to redundant URL-id "+i),this._levels.forEach((function(t){t.urlId=i})),this.level=t}},u.onFragLoaded=function(t,e){var r=e.frag;if(void 0!==r&&r.type===_.b.MAIN){var i=this._levels[r.level];void 0!==i&&(i.fragmentError=0,i.loadError=0)}},u.onLevelLoaded=function(t,e){var r,i,a=e.level,n=e.details,s=this._levels[a];if(!s)return this.warn("Invalid level index "+a),void(null!==(i=e.deliveryDirectives)&&void 0!==i&&i.skip&&(n.deltaUpdateFailed=!0));a===this.currentLevelIndex?(0===s.fragmentError&&(s.loadError=0,this.retryCount=0),this.playlistLoaded(a,e,s.details)):null!==(r=e.deliveryDirectives)&&void 0!==r&&r.skip&&(n.deltaUpdateFailed=!0)},u.onAudioTrackSwitched=function(t,e){var r=this.hls.levels[this.currentLevelIndex];if(r&&r.audioGroupIds){for(var i=-1,a=this.hls.audioTracks[e.id].groupId,n=0;n0){var i=r.urlId,a=r.url[i];if(t)try{a=t.addDirectives(a)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}this.log("Attempt loading level index "+e+(t?" at sn "+t.msn+" part "+t.part:"")+" with URL-id "+i+" "+a),this.clearTimer(),this.hls.trigger(n.a.LEVEL_LOADING,{url:a,level:e,id:i,deliveryDirectives:t||null})}},u.removeLevel=function(t,e){var r=function(t,r){return r!==e},i=this._levels.filter((function(i,a){return a!==t||i.url.length>1&&void 0!==e&&(i.url=i.url.filter(r),i.audioGroupIds&&(i.audioGroupIds=i.audioGroupIds.filter(r)),i.textGroupIds&&(i.textGroupIds=i.textGroupIds.filter(r)),i.urlId=0,!0)})).map((function(t,e){var r=t.details;return null!=r&&r.fragments&&r.fragments.forEach((function(t){t.level=e})),t}));this._levels=i,this.hls.trigger(n.a.LEVELS_UPDATED,{levels:i})},a=i,(o=[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(t){var e,r=this._levels;if(0!==r.length&&(this.currentLevelIndex!==t||null===(e=r[t])||void 0===e||!e.details)){if(t<0||t>=r.length){var i=t<0;if(this.hls.trigger(n.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.LEVEL_SWITCH_ERROR,level:t,fatal:i,reason:"invalid level idx"}),i)return;t=Math.min(t,r.length-1)}this.clearTimer();var a=this.currentLevelIndex,o=r[a],l=r[t];this.log("switching to level "+t+" from "+a),this.currentLevelIndex=t;var u=q({},l,{level:t,maxBitrate:l.maxBitrate,uri:l.uri,urlId:l.urlId});delete u._urlId,this.hls.trigger(n.a.LEVEL_SWITCHING,u);var d=l.details;if(!d||d.live){var h=this.switchParams(l.uri,null==o?void 0:o.details);this.loadPlaylist(h)}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(t){this._firstLevel=t}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var t=this.hls.config.startLevel;return void 0!==t?t:this._firstLevel}return this._startLevel},set:function(t){this._startLevel=t}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}}])&&z(a.prototype,o),l&&z(a,l),i}(X);!function(t){t.NOT_LOADED="NOT_LOADED",t.BACKTRACKED="BACKTRACKED",t.APPENDING="APPENDING",t.PARTIAL="PARTIAL",t.OK="OK"}($||($={}));var tt=function(){function t(t){this.activeFragment=null,this.activeParts=null,this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hls=t,this._registerListeners()}var e=t.prototype;return e._registerListeners=function(){var t=this.hls;t.on(n.a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(n.a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(n.a.FRAG_LOADED,this.onFragLoaded,this)},e._unregisterListeners=function(){var t=this.hls;t.off(n.a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(n.a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(n.a.FRAG_LOADED,this.onFragLoaded,this)},e.destroy=function(){this._unregisterListeners(),this.fragments=this.timeRanges=null},e.getAppendedFrag=function(t,e){if(e===_.b.MAIN){var r=this.activeFragment,i=this.activeParts;if(!r)return null;if(i)for(var a=i.length;a--;){var n=i[a],s=n?n.end:r.appendedPTS;if(n.start<=t&&void 0!==s&&t<=s)return a>9&&(this.activeParts=i.slice(a-9)),n}else if(r.start<=t&&void 0!==r.appendedPTS&&t<=r.appendedPTS)return r}return this.getBufferedFrag(t,e)},e.getBufferedFrag=function(t,e){for(var r=this.fragments,i=Object.keys(r),a=i.length;a--;){var n=r[i[a]];if((null==n?void 0:n.body.type)===e&&n.buffered){var s=n.body;if(s.start<=t&&t<=s.end)return s}}return null},e.detectEvictedFragments=function(t,e,r){var i=this;Object.keys(this.fragments).forEach((function(a){var n=i.fragments[a];if(n)if(n.buffered){var s=n.range[t];s&&s.time.some((function(t){var r=!i.isTimeBuffered(t.startPTS,t.endPTS,e);return r&&i.removeFragment(n.body),r}))}else n.body.type===r&&i.removeFragment(n.body)}))},e.detectPartialFragments=function(t){var e=this,r=this.timeRanges,i=t.frag,a=t.part;if(r&&"initSegment"!==i.sn){var n=rt(i),s=this.fragments[n];s&&(Object.keys(r).forEach((function(t){var n=i.elementaryStreams[t];if(n){var o=r[t],l=null!==a||!0===n.partial;s.range[t]=e.getBufferedTimes(i,a,l,o)}})),s.backtrack=s.loaded=null,Object.keys(s.range).length?s.buffered=!0:this.removeFragment(s.body))}},e.fragBuffered=function(t){var e=rt(t),r=this.fragments[e];r&&(r.backtrack=r.loaded=null,r.buffered=!0)},e.getBufferedTimes=function(t,e,r,i){for(var a={time:[],partial:r},n=e?e.start:t.start,s=e?e.end:t.end,o=t.minEndPTS||s,l=t.maxStartPTS||n,u=0;u=d&&o<=h){a.time.push({startPTS:Math.max(n,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(nd)a.partial=!0,a.time.push({startPTS:Math.max(n,i.start(u)),endPTS:Math.min(s,i.end(u))});else if(s<=d)break}return a},e.getPartialFragment=function(t){var e,r,i,a=null,n=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var u=o[l];u&&et(u)&&(r=u.body.start-s,i=u.body.end+s,t>=r&&t<=i&&(e=Math.min(t-r,i-t),n<=e&&(a=u.body,n=e)))})),a},e.getState=function(t){var e=rt(t),r=this.fragments[e];return r?r.buffered?et(r)?$.PARTIAL:$.OK:r.backtrack?$.BACKTRACKED:$.APPENDING:$.NOT_LOADED},e.backtrack=function(t,e){var r=rt(t),i=this.fragments[r];if(!i||i.backtrack)return null;var a=i.backtrack=e||i.loaded;return i.loaded=null,a},e.getBacktrackData=function(t){var e=rt(t),r=this.fragments[e];if(r){var i,a=r.backtrack;if(null!=a&&null!==(i=a.payload)&&void 0!==i&&i.byteLength)return a;this.removeFragment(t)}return null},e.isTimeBuffered=function(t,e,r){for(var i,a,n=0;n=i&&e<=a)return!0;if(e<=i)return!1}return!1},e.onFragLoaded=function(t,e){var r=e.frag,i=e.part;if("initSegment"!==r.sn&&!r.bitrateTest&&!i){var a=rt(r);this.fragments[a]={body:r,loaded:e,backtrack:null,buffered:!1,range:Object.create(null)}}},e.onBufferAppended=function(t,e){var r=this,i=e.frag,a=e.part,n=e.timeRanges;if(i.type===_.b.MAIN)if(this.activeFragment=i,a){var s=this.activeParts;s||(this.activeParts=s=[]),s.push(a)}else this.activeParts=null;this.timeRanges=n,Object.keys(n).forEach((function(t){var e=n[t];if(r.detectEvictedFragments(t,e),!a)for(var s=0;st&&i.removeFragment(s)}}))},e.removeFragment=function(t){var e=rt(t);t.stats.loaded=0,t.clearElementaryStreamInfo(),delete this.fragments[e]},e.removeAllFragments=function(){this.fragments=Object.create(null),this.activeFragment=null,this.activeParts=null},t}();function et(t){var e,r;return t.buffered&&((null===(e=t.range.video)||void 0===e?void 0:e.partial)||(null===(r=t.range.audio)||void 0===r?void 0:r.partial))}function rt(t){return t.type+"_"+t.level+"_"+t.urlId+"_"+t.sn}var it=function(){function t(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}var e=t.prototype;return e.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},e.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},e.onHandlerDestroyed=function(){},e.hasInterval=function(){return!!this._tickInterval},e.hasNextTick=function(){return!!this._tickTimer},e.setInterval=function(t){return!this._tickInterval&&(this._tickInterval=self.setInterval(this._boundTick,t),!0)},e.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},e.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},e.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},e.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},e.doTick=function(){},t}(),at={length:0,start:function(){return 0},end:function(){return 0}},nt=function(){function t(){}return t.isBuffered=function(e,r){try{if(e)for(var i=t.getBuffered(e),a=0;a=i.start(a)&&r<=i.end(a))return!0}catch(t){}return!1},t.bufferInfo=function(e,r,i){try{if(e){var a,n=t.getBuffered(e),s=[];for(a=0;as&&(i[n-1].end=t[a].end):i.push(t[a])}else i.push(t[a])}else i=t;for(var o,l=0,u=e,d=e,h=0;h=f&&er.startCC||t&&t.cc0)r=a+1;else{if(!(s<0))return n;i=a-1}}return null}};function ht(t,e,r){void 0===t&&(t=0),void 0===e&&(e=0);var i=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=t?1:r.start-i>t&&r.start?-1:0}function ft(t,e,r){var i=1e3*Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>t}function ct(t){var e="function"==typeof Map?new Map:void 0;return(ct=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,i)}function i(){return vt(t,arguments,mt(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),pt(i,t)})(t)}function vt(t,e,r){return(vt=gt()?Reflect.construct:function(t,e,r){var i=[null];i.push.apply(i,e);var a=new(Function.bind.apply(t,i));return r&&pt(a,r.prototype),a}).apply(null,arguments)}function gt(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function pt(t,e){return(pt=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function mt(t){return(mt=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var yt=Math.pow(2,17),bt=function(){function t(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}var e=t.prototype;return e.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},e.abort=function(){this.loader&&this.loader.abort()},e.load=function(t,e){var r=this,i=t.url;if(!i)return Promise.reject(new Et({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,networkDetails:null},"Fragment does not have a "+(i?"part list":"url")));this.abort();var a=this.config,n=a.fLoader,o=a.loader;return new Promise((function(i,l){r.loader&&r.loader.destroy();var u=r.loader=t.loader=n?new n(a):new o(a),d=Tt(t),h={timeout:a.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:a.fragLoadingMaxRetryTimeout,highWaterMark:yt};t.stats=u.stats,u.load(d,h,{onSuccess:function(e,a,n,s){r.resetLoader(t,u),i({frag:t,part:null,payload:e.data,networkDetails:s})},onError:function(e,i,a){r.resetLoader(t,u),l(new Et({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:e,networkDetails:a}))},onAbort:function(e,i,a){r.resetLoader(t,u),l(new Et({type:s.b.NETWORK_ERROR,details:s.a.INTERNAL_ABORTED,fatal:!1,frag:t,networkDetails:a}))},onTimeout:function(e,i,a){r.resetLoader(t,u),l(new Et({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,networkDetails:a}))},onProgress:function(r,i,a,n){e&&e({frag:t,part:null,payload:a,networkDetails:n})}})}))},e.loadPart=function(t,e,r){var i=this;this.abort();var a=this.config,n=a.fLoader,o=a.loader;return new Promise((function(l,u){i.loader&&i.loader.destroy();var d=i.loader=t.loader=n?new n(a):new o(a),h=Tt(t,e),f={timeout:a.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:a.fragLoadingMaxRetryTimeout,highWaterMark:yt};e.stats=d.stats,d.load(h,f,{onSuccess:function(a,n,s,o){i.resetLoader(t,d),i.updateStatsFromPart(t,e);var u={frag:t,part:e,payload:a.data,networkDetails:o};r(u),l(u)},onError:function(r,a,n){i.resetLoader(t,d),u(new Et({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:r,networkDetails:n}))},onAbort:function(r,a,n){t.stats.aborted=e.stats.aborted,i.resetLoader(t,d),u(new Et({type:s.b.NETWORK_ERROR,details:s.a.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,networkDetails:n}))},onTimeout:function(r,a,n){i.resetLoader(t,d),u(new Et({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,networkDetails:n}))}})}))},e.updateStatsFromPart=function(t,e){var r=t.stats,i=e.stats,a=i.total;if(r.loaded+=i.loaded,a){var n=Math.round(t.duration/e.duration),s=Math.min(Math.round(r.loaded/a),n),o=(n-s)*Math.round(r.loaded/s);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,u=i.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end},e.resetLoader=function(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()},t}();function Tt(t,e){void 0===e&&(e=null);var r=e||t,i={frag:t,part:e,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},n=r.byteRangeStartOffset,s=r.byteRangeEndOffset;return Object(a.a)(n)&&Object(a.a)(s)&&(i.rangeStart=n,i.rangeEnd=s),i}var Et=function(t){var e,r;function i(e){for(var r,i=arguments.length,a=new Array(i>1?i-1:0),n=1;n=e.endSN&&!t.nextStart){var a=e.partList;if(null!=a&&a.length){var n=a[a.length-1];return nt.isBuffered(this.media,n.start+n.duration/2)}var s=i.getState(r);return s===$.PARTIAL||s===$.OK}return!1},f.onMediaAttached=function(t,e){var r=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),r.addEventListener("seeking",this.onvseeking),r.addEventListener("ended",this.onvended);var i=this.config;this.levels&&i.autoStartLoad&&this.state===Dt&&this.startLoad(i.startPosition)},f.onMediaDetaching=function(){var t=this.media;null!=t&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()},f.onMediaSeeking=function(){var t=this.config,e=this.fragCurrent,r=this.media,i=this.mediaBuffer,n=this.state,s=r?r.currentTime:0,o=nt.bufferInfo(i||r,s,t.maxBufferHole);if(this.log("media seeking to "+(Object(a.a)(s)?s.toFixed(3):s)+", state: "+n),n===Pt)this.resetLoadingState();else if(e&&!o.len){var l=t.maxFragLookUpTolerance,u=e.start-l,d=s>e.start+e.duration+l;(s0&&s&&s.key&&s.iv&&"AES-128"===s.method){var o=self.performance.now();return e.decrypter.webCryptoDecrypt(new Uint8Array(a),s.key.buffer,s.iv.buffer).then((function(e){var a=self.performance.now();return i.trigger(n.a.FRAG_DECRYPTED,{frag:t,payload:e,stats:{tstart:o,tdecrypt:a}}),r.payload=e,r}))}return r})).then((function(r){var i=e.fragCurrent,a=e.hls,s=e.levels;if(!s)throw new Error("init load aborted, missing levels");s[t.level].details;var o=t.stats;e.state=_t,e.fragLoadError=0,t.data=new Uint8Array(r.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),r.frag===i&&a.trigger(n.a.FRAG_BUFFERED,{stats:o,frag:i,part:null,id:t.type}),e.tick()})).catch((function(r){e.warn(r),e.resetFragmentLoading(t)}))},f.fragContextChanged=function(t){var e=this.fragCurrent;return!t||!e||t.level!==e.level||t.sn!==e.sn||t.urlId!==e.urlId},f.fragBufferedComplete=function(t,e){var r=this.mediaBuffer?this.mediaBuffer:this.media;this.log("Buffered "+t.type+" sn: "+t.sn+(e?" part: "+e.index:"")+" of "+("[stream-controller]"===this.logPrefix?"level":"track")+" "+t.level+" "+Lt.toString(nt.getBuffered(r))),this.state=_t,this.tick()},f._handleFragmentLoadComplete=function(t){var e=this.transmuxer;if(e){var r=t.frag,i=t.part,a=t.partsLoaded,n=!a||0===a.length||a.some((function(t){return!t})),s=new st(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!n);e.flush(s)}},f._handleFragmentLoadProgress=function(t){},f._doFragLoad=function(t,e,r,i){var s=this;if(void 0===r&&(r=null),!this.levels)throw new Error("frag load aborted, missing levels");if(r=Math.max(t.start,r||0),this.config.lowLatencyMode&&e){var o=e.partList;if(o&&i){r>t.end&&e.fragmentHint&&(t=e.fragmentHint);var l=this.getNextPart(o,t,r);if(l>-1){var u=o[l];return this.log("Loading part sn: "+t.sn+" p: "+u.index+" cc: "+t.cc+" of playlist ["+e.startSN+"-"+e.endSN+"] parts [0-"+l+"-"+(o.length-1)+"] "+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),this.nextLoadPosition=u.start+u.duration,this.state=xt,this.hls.trigger(n.a.FRAG_LOADING,{frag:t,part:o[l],targetBufferTime:r}),this.doFragPartsLoad(t,o,l,i).catch((function(t){return s.handleFragLoadError(t)}))}if(!t.url||this.loadedEndOfParts(o,r))return Promise.resolve(null)}}return this.log("Loading fragment "+t.sn+" cc: "+t.cc+" "+(e?"of ["+e.startSN+"-"+e.endSN+"] ":"")+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),Object(a.a)(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=xt,this.hls.trigger(n.a.FRAG_LOADING,{frag:t,targetBufferTime:r}),this.fragmentLoader.load(t,i).catch((function(t){return s.handleFragLoadError(t)}))},f.doFragPartsLoad=function(t,e,r,i){var a=this;return new Promise((function(s,o){var l=[];!function r(u){var d=e[u];a.fragmentLoader.loadPart(t,d,i).then((function(i){l[d.index]=i;var o=i.part;a.hls.trigger(n.a.FRAG_LOADED,i);var h=e[u+1];if(!h||h.fragment!==t)return s({frag:t,part:o,partsLoaded:l});r(u+1)})).catch(o)}(r)}))},f.handleFragLoadError=function(t){var e=t.data;return e&&e.details===s.a.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(n.a.ERROR,e),null},f._handleTransmuxerFlush=function(t){var e=this.getCurrentContext(t);if(e&&this.state===wt){var r=e.frag,i=e.part,a=e.level,n=self.performance.now();r.stats.parsing.end=n,i&&(i.stats.parsing.end=n),this.updateLevelTiming(r,i,a,t.partial)}else this.fragCurrent||(this.state=_t)},f.getCurrentContext=function(t){var e=this.levels,r=t.level,i=t.sn,a=t.part;if(!e||!e[r])return this.warn("Levels object was unset while buffering fragment "+i+" of level "+r+". The current chunk will not be buffered."),null;var n=e[r],s=a>-1?function(t,e,r){if(!t||!t.details)return null;var i=t.details.partList;if(i)for(var a=i.length;a--;){var n=i[a];if(n.index===r&&n.fragment.sn===e)return n}return null}(n,i,a):null,o=s?s.fragment:function(t,e,r){if(!t||!t.details)return null;var i=t.details,a=i.fragments[e-i.startSN];return a||((a=i.fragmentHint)&&a.sn===e?a:en&&this.flushMainBuffer(s,t.start)}else this.flushMainBuffer(0,t.start)},f.getFwdBufferInfo=function(t,e){var r=this.config,i=this.getLoadPosition();if(!Object(a.a)(i))return null;var n=nt.bufferInfo(t,i,r.maxBufferHole);if(0===n.len&&void 0!==n.nextStart){var s=this.fragmentTracker.getBufferedFrag(i,e);if(s&&n.nextStart=r&&(e.maxMaxBufferLength/=2,this.warn("Reduce max buffer length to "+e.maxMaxBufferLength+"s"),!0)},f.getNextFragment=function(t,e){var r,i,a=e.fragments,n=a.length;if(!n)return null;var s,o=this.config,l=a[0].start;if(e.live){var u=o.initialLiveManifestSize;if(n-1&&rr.start&&r.loaded},f.getInitialLiveFragment=function(t,e){var r=this.fragPrevious,i=null;if(r){if(t.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+r.programDateTime),i=function(t,e,r){if(null===e||!Array.isArray(t)||!t.length||!Object(a.a)(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;r=r||0;for(var i=0;i=t.startSN&&n<=t.endSN){var s=e[n-t.startSN];r.cc===s.cc&&(i=s,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=function(t,e){return dt.search(t,(function(t){return t.cce?-1:0}))}(e,r.cc))&&this.log("Live playlist, switching playlist, load frag with same CC: "+i.sn)}}else{var o=this.hls.liveSyncPosition;null!==o&&(i=this.getFragmentAtPosition(o,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i},f.getFragmentAtPosition=function(t,e,r){var i,a=this.config,n=this.fragPrevious,s=r.fragments,o=r.endSN,l=r.fragmentHint,u=a.maxFragLookUpTolerance,d=!!(a.lowLatencyMode&&r.partList&&l);(d&&l&&!this.bitrateTest&&(s=s.concat(l),o=l.sn),te-u?0:u):i=s[s.length-1];if(i){var h=i.sn-r.startSN,f=n&&i.level===n.level,c=s[h+1];if(this.fragmentTracker.getState(i)===$.BACKTRACKED){i=null;for(var v=h;s[v]&&this.fragmentTracker.getState(s[v])===$.BACKTRACKED;)i=n?s[v--]:s[--v];i||(i=c)}else n&&i.sn===n.sn&&!d&&f&&(i.sn=n-e.maxFragLookUpTolerance&&a<=s;if(null!==i&&r.duration>i&&(a"+t.startSN+" prev-sn: "+(n?n.sn:"na")+" fragments: "+o),h}return l},f.waitForCdnTuneIn=function(t){return t.live&&t.canBlockReload&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)},f.setStartPosition=function(t,e){var r=this.startPosition;if(r"+t))}}])&&At(u.prototype,d),h&&At(u,h),i}(it);function Bt(){return self.MediaSource||self.WebKitMediaSource}function Ut(){return self.SourceBuffer||self.WebKitSourceBuffer}var Gt=r(17),jt=r(9),Ht=r(13),Kt=Bt()||{isTypeSupported:function(){return!1}},Vt=function(){function t(t,e,r,i){var a=this;this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.worker=void 0,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.hls=t,this.id=e,this.onTransmuxComplete=r,this.onFlush=i;var l=t.config,u=function(e,r){(r=r||{}).frag=a.frag,r.id=a.id,t.trigger(e,r)};this.observer=new Ht.EventEmitter,this.observer.on(n.a.FRAG_DECRYPTED,u),this.observer.on(n.a.ERROR,u);var d={mp4:Kt.isTypeSupported("video/mp4"),mpeg:Kt.isTypeSupported("audio/mpeg"),mp3:Kt.isTypeSupported('audio/mp4; codecs="mp3"')},h=navigator.vendor;if(l.enableWorker&&"undefined"!=typeof Worker){var f;o.b.log("demuxing in webworker");try{f=this.worker=Gt(18),this.onwmsg=this.onWorkerMessage.bind(this),f.addEventListener("message",this.onwmsg),f.onerror=function(e){t.trigger(n.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.INTERNAL_EXCEPTION,fatal:!0,event:"demuxerWorker",error:new Error(e.message+" ("+e.filename+":"+e.lineno+")")})},f.postMessage({cmd:"init",typeSupported:d,vendor:h,id:e,config:JSON.stringify(l)})}catch(t){o.b.warn("Error in worker:",t),o.b.error("Error while initializing DemuxerWorker, fallback to inline"),f&&self.URL.revokeObjectURL(f.objectURL),this.transmuxer=new jt.c(this.observer,d,l,h,e),this.worker=null}}else this.transmuxer=new jt.c(this.observer,d,l,h,e)}var e=t.prototype;return e.destroy=function(){var t=this.worker;if(t)t.removeEventListener("message",this.onwmsg),t.terminate(),this.worker=null;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var r=this.observer;r&&r.removeAllListeners(),this.observer=null},e.push=function(t,e,r,i,a,n,s,l,u,d){var h,f,c=this;u.transmuxing.start=self.performance.now();var v=this.transmuxer,g=this.worker,p=n?n.start:a.start,m=a.decryptdata,y=this.frag,b=!(y&&a.cc===y.cc),T=!(y&&u.level===y.level),E=y?u.sn-y.sn:-1,S=this.part?u.part-this.part.index:1,L=!T&&(1===E||0===E&&1===S),A=self.performance.now();(T||E||0===a.stats.parsing.start)&&(a.stats.parsing.start=A),!n||!S&&L||(n.stats.parsing.start=A);var R=!(y&&(null===(h=a.initSegment)||void 0===h?void 0:h.url)===(null===(f=y.initSegment)||void 0===f?void 0:f.url)),D=new jt.b(b,L,l,T,p,R);if(!L||b||R){o.b.log("[transmuxer-interface, "+a.type+"]: Starting new transmux session for sn: "+u.sn+" p: "+u.part+" level: "+u.level+" id: "+u.id+"\n discontinuity: "+b+"\n trackSwitch: "+T+"\n contiguous: "+L+"\n accurateTimeOffset: "+l+"\n timeOffset: "+p+"\n initSegmentChange: "+R);var _=new jt.a(r,i,e,s,d);this.configureTransmuxer(_)}if(this.frag=a,this.part=n,g)g.postMessage({cmd:"demux",data:t,decryptdata:m,chunkMeta:u,state:D},t instanceof ArrayBuffer?[t]:[]);else if(v){var k=v.push(t,m,u,D);Object(jt.d)(k)?k.then((function(t){c.handleTransmuxComplete(t)})):this.handleTransmuxComplete(k)}},e.flush=function(t){var e=this;t.transmuxing.start=self.performance.now();var r=this.transmuxer,i=this.worker;if(i)i.postMessage({cmd:"flush",chunkMeta:t});else if(r){var a=r.flush(t);Object(jt.d)(a)?a.then((function(r){e.handleFlushResult(r,t)})):this.handleFlushResult(a,t)}},e.handleFlushResult=function(t,e){var r=this;t.forEach((function(t){r.handleTransmuxComplete(t)})),this.onFlush(e)},e.onWorkerMessage=function(t){var e=t.data,r=this.hls;switch(e.event){case"init":self.URL.revokeObjectURL(this.worker.objectURL);break;case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,r.trigger(e.event,e.data)}},e.configureTransmuxer=function(t){var e=this.worker,r=this.transmuxer;e?e.postMessage({cmd:"configure",config:t}):r&&r.configure(t)},e.handleTransmuxComplete=function(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)},t}(),Wt=function(){function t(t,e,r,i){this.config=void 0,this.media=void 0,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=r,this.hls=i}var e=t.prototype;return e.destroy=function(){this.hls=this.fragmentTracker=this.media=null},e.poll=function(t){var e=this.config,r=this.media,i=this.stalled,a=r.currentTime,n=r.seeking,s=this.seeking&&!n,l=!this.seeking&&n;if(this.seeking=n,a===t){if((l||s)&&(this.stalled=null),!r.paused&&!r.ended&&0!==r.playbackRate&&nt.getBuffered(r).length){var u=nt.bufferInfo(r,a,0),d=u.len>0,h=u.nextStart||0;if(d||h){if(n){var f=u.len>2,c=!h||h-a>2&&!this.fragmentTracker.getPartialFragment(a);if(f||c)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var v,g=Math.max(h,u.start||0)-a,p=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,m=(null==p||null===(v=p.details)||void 0===v?void 0:v.live)?2*p.details.targetduration:2;if(g>0&&g<=m)return void this._trySkipBufferHole(null)}var y=self.performance.now();if(null!==i){var b=y-i;!n&&b>=250&&this._reportStall(u.len);var T=nt.bufferInfo(r,a,e.maxBufferHole);this._tryFixBufferStall(T,b)}else this.stalled=y}}}else if(this.moved=!0,null!==i){if(this.stallReported){var E=self.performance.now()-i;o.b.warn("playback not stuck anymore @"+a+", after "+Math.round(E)+"ms"),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}},e._tryFixBufferStall=function(t,e){var r=this.config,i=this.fragmentTracker,a=this.media.currentTime,n=i.getPartialFragment(a);if(n&&this._trySkipBufferHole(n))return;t.len>r.maxBufferHole&&e>1e3*r.highBufferWatchdogPeriod&&(o.b.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())},e._reportStall=function(t){var e=this.hls,r=this.media;this.stallReported||(this.stallReported=!0,o.b.warn("Playback stalling at @"+r.currentTime+" due to low buffer (buffer="+t+")"),e.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_STALLED_ERROR,fatal:!1,buffer:t}))},e._trySkipBufferHole=function(t){for(var e=this.config,r=this.hls,i=this.media,a=i.currentTime,l=0,u=nt.getBuffered(i),d=0;d=l&&a0&&-1===t&&(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e),this.state=_t,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=Dt},f.stopLoad=function(){this._forceStartLoad=!1,t.prototype.stopLoad.call(this)},f.doTick=function(){switch(this.state){case _t:this.doTickIdle();break;case Mt:var t,e=this.levels,r=this.level,i=null==e||null===(t=e[r])||void 0===t?void 0:t.details;if(i&&(!i.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(i))break;this.state=_t;break}break;case Ct:var a,n=self.performance.now(),s=this.retryDate;(!s||n>=s||null!==(a=this.media)&&void 0!==a&&a.seeking)&&(this.log("retryDate reached, switch back to IDLE state"),this.state=_t)}this.onTickEnd()},f.onTickEnd=function(){t.prototype.onTickEnd.call(this),this.checkBuffer(),this.checkFragmentChanged()},f.doTickIdle=function(){var t,e,r=this.hls,i=this.levelLastLoaded,a=this.levels,s=this.media,o=r.config,l=r.nextLoadLevel;if(null!==i&&(s||!this.startFragRequested&&o.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)&&a&&a[l]){var d=a[l];this.level=r.nextLoadLevel=l;var h=d.details;if(!h||this.state===Mt||h.live&&this.levelLastLoaded!==l)this.state=Mt;else{var f=this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:s,_.b.MAIN);if(null!==f)if(!(f.len>=this.getMaxBufferLength(d.maxBitrate))){if(this._streamEnded(f,h)){var c={};return this.altAudio&&(c.type="video"),this.hls.trigger(n.a.BUFFER_EOS,c),void(this.state=Pt)}var v=f.end,g=this.getNextFragment(v,h);if(this.couldBacktrack&&!this.fragPrevious&&g&&"initSegment"!==g.sn){var p=g.sn-h.startSN;p>1&&(g=h.fragments[p-1],this.fragmentTracker.removeFragment(g))}if(g&&this.fragmentTracker.getState(g)===$.OK&&this.nextLoadPosition>v){var m=this.audioOnly&&!this.altAudio?u.a.AUDIO:u.a.VIDEO;this.afterBufferFlushed(s,m,_.b.MAIN),g=this.getNextFragment(this.nextLoadPosition,h)}g&&(!g.initSegment||g.initSegment.data||this.bitrateTest||(g=g.initSegment),"identity"!==(null===(t=g.decryptdata)||void 0===t?void 0:t.keyFormat)||null!==(e=g.decryptdata)&&void 0!==e&&e.key?this.loadFragment(g,h,v):this.loadKey(g,h))}}}},f.loadFragment=function(e,r,i){var a,n=this.fragmentTracker.getState(e);if(this.fragCurrent=e,n===$.BACKTRACKED){var s=this.fragmentTracker.getBacktrackData(e);if(s)return this._handleFragmentLoadProgress(s),void this._handleFragmentLoadComplete(s);n=$.NOT_LOADED}n===$.NOT_LOADED||n===$.PARTIAL?"initSegment"===e.sn?this._loadInitSegment(e):this.bitrateTest?(e.bitrateTest=!0,this.log("Fragment "+e.sn+" of level "+e.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(e)):(this.startFragRequested=!0,t.prototype.loadFragment.call(this,e,r,i)):n===$.APPENDING?this.reduceMaxBufferLength(e.duration)&&this.fragmentTracker.removeFragment(e):0===(null===(a=this.media)||void 0===a?void 0:a.buffered.length)&&this.fragmentTracker.removeAllFragments()},f.getAppendedFrag=function(t){var e=this.fragmentTracker.getAppendedFrag(t,_.b.MAIN);return e&&"fragment"in e?e.fragment:e},f.getBufferedFrag=function(t){return this.fragmentTracker.getBufferedFrag(t,_.b.MAIN)},f.followingBufferedFrag=function(t){return t?this.getBufferedFrag(t.end+.5):null},f.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},f.nextLevelSwitch=function(){var t=this.levels,e=this.media;if(null!=e&&e.readyState){var r,i=this.getAppendedFrag(e.currentTime);if(i&&i.start>1&&this.flushMainBuffer(0,i.start-1),!e.paused&&t){var a=t[this.hls.nextLoadLevel],n=this.fragLastKbps;r=n&&this.fragCurrent?this.fragCurrent.duration*a.maxBitrate/(1e3*n)+1:0}else r=0;var s=this.getBufferedFrag(e.currentTime+r);if(s){var o=this.followingBufferedFrag(s);if(o){this.abortCurrentFrag();var l=o.maxStartPTS?o.maxStartPTS:o.start,u=o.duration,d=Math.max(s.end,l+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,.5*u),.75*u));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}},f.abortCurrentFrag=function(){var t=this.fragCurrent;this.fragCurrent=null,null!=t&&t.loader&&t.loader.abort(),this.state===kt&&(this.state=_t),this.nextLoadPosition=this.getLoadPosition()},f.flushMainBuffer=function(e,r){t.prototype.flushMainBuffer.call(this,e,r,this.altAudio?"video":null)},f.onMediaAttached=function(e,r){t.prototype.onMediaAttached.call(this,e,r);var i=r.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Wt(this.config,i,this.fragmentTracker,this.hls)},f.onMediaDetaching=function(){var e=this.media;e&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),t.prototype.onMediaDetaching.call(this)},f.onMediaPlaying=function(){this.tick()},f.onMediaSeeked=function(){var t=this.media,e=t?t.currentTime:null;Object(a.a)(e)&&this.log("Media seeked to "+e.toFixed(3)),this.tick()},f.onManifestLoading=function(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(n.a.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=this.stalled=!1,this.startPosition=this.lastCurrentTime=0,this.fragPlaying=null},f.onManifestParsed=function(t,e){var r,i,a,n=!1,s=!1;e.levels.forEach((function(t){(r=t.audioCodec)&&(-1!==r.indexOf("mp4a.40.2")&&(n=!0),-1!==r.indexOf("mp4a.40.5")&&(s=!0))})),this.audioCodecSwitch=n&&s&&!("function"==typeof(null==(a=Ut())||null===(i=a.prototype)||void 0===i?void 0:i.changeType)),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1},f.onLevelLoading=function(t,e){var r=this.levels;if(r&&this.state===_t){var i=r[e.level];(!i.details||i.details.live&&this.levelLastLoaded!==e.level||this.waitForCdnTuneIn(i.details))&&(this.state=Mt)}},f.onLevelLoaded=function(t,e){var r,i=this.levels,a=e.level,s=e.details,o=s.totalduration;if(i){this.log("Level "+a+" loaded ["+s.startSN+","+s.endSN+"], cc ["+s.startCC+", "+s.endCC+"] duration:"+o);var l=this.fragCurrent;!l||this.state!==xt&&this.state!==Ct||l.level!==e.level&&l.loader&&(this.state=_t,l.loader.abort());var u=i[a],d=0;if(s.live||null!==(r=u.details)&&void 0!==r&&r.live){if(s.fragments[0]||(s.deltaUpdateFailed=!0),s.deltaUpdateFailed)return;d=this.alignPlaylists(s,u.details)}if(u.details=s,this.levelLastLoaded=a,this.hls.trigger(n.a.LEVEL_UPDATED,{details:s,level:a}),this.state===Mt){if(this.waitForCdnTuneIn(s))return;this.state=_t}this.startFragRequested?s.live&&this.synchronizeToLiveEdge(s):this.setStartPosition(s,d),this.tick()}else this.warn("Levels were reset while loading level "+a)},f._handleFragmentLoadProgress=function(t){var e,r=t.frag,i=t.part,a=t.payload,n=this.levels;if(n){var s=n[r.level],o=s.details;if(o){var l=s.videoCodec,u=o.PTSKnown||!o.live,d=null===(e=r.initSegment)||void 0===e?void 0:e.data,h=this._getAudioCodec(s),f=this.transmuxer=this.transmuxer||new Vt(this.hls,_.b.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),c=i?i.index:-1,v=-1!==c,g=new st(r.level,r.sn,r.stats.chunkCount,a.byteLength,c,v),p=this.initPTS[r.cc];f.push(a,d,h,l,r,i,o.totalduration,u,g,p)}else this.warn("Dropping fragment "+r.sn+" of level "+r.level+" after level details were reset")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},f.onAudioTrackSwitching=function(t,e){var r=this.altAudio,i=!!e.url,a=e.id;if(!i){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var s=this.fragCurrent;null!=s&&s.loader&&(this.log("Switching to main audio track, cancel main fragment load"),s.loader.abort()),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var o=this.hls;r&&o.trigger(n.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),o.trigger(n.a.AUDIO_TRACK_SWITCHED,{id:a})}},f.onAudioTrackSwitched=function(t,e){var r=e.id,i=!!this.hls.audioTracks[r].url;if(i){var a=this.videoBuffer;a&&this.mediaBuffer!==a&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=a)}this.altAudio=i,this.tick()},f.onBufferCreated=function(t,e){var r,i,a=e.tracks,n=!1;for(var s in a){var o=a[s];if("main"===o.id){if(i=s,r=o,"video"===s){var l=a[s];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&r?(this.log("Alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},f.onFragBuffered=function(t,e){var r=e.frag,i=e.part;if(!r||r.type===_.b.MAIN){if(this.fragContextChanged(r))return this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===Ot&&(this.state=_t));var a=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}},f.onError=function(t,e){switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:case s.a.KEY_LOAD_ERROR:case s.a.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(_.b.MAIN,e);break;case s.a.LEVEL_LOAD_ERROR:case s.a.LEVEL_LOAD_TIMEOUT:this.state!==Ft&&(e.fatal?(this.warn(""+e.details),this.state=Ft):e.levelRetry||this.state!==Mt||(this.state=_t));break;case s.a.BUFFER_FULL_ERROR:if("main"===e.parent&&(this.state===wt||this.state===Ot)){var r=!0,i=this.getFwdBufferInfo(this.media,_.b.MAIN);i&&i.len>.5&&(r=!this.reduceMaxBufferLength(i.len)),r&&(this.warn("buffer full error also media.currentTime is not buffered, flush main"),this.immediateLevelSwitch()),this.resetLoadingState()}}},f.checkBuffer=function(){var t=this.media,e=this.gapController;if(t&&e&&t.readyState){var r=nt.getBuffered(t);!this.loadedmetadata&&r.length?(this.loadedmetadata=!0,this.seekToStartPos()):e.poll(this.lastCurrentTime),this.lastCurrentTime=t.currentTime}},f.onFragLoadEmergencyAborted=function(){this.state=_t,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()},f.onBufferFlushed=function(t,e){var r=e.type;if(r!==u.a.AUDIO||this.audioOnly&&!this.altAudio){var i=(r===u.a.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,r,_.b.MAIN)}},f.onLevelsUpdated=function(t,e){this.levels=e.levels},f.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},f.seekToStartPos=function(){var t=this.media,e=t.currentTime,r=this.startPosition;if(r>=0&&e0&&(a1&&!1===t.seeking){var r=t.currentTime;if(nt.isBuffered(t,r)?e=this.getAppendedFrag(r):nt.isBuffered(t,r+.1)&&(e=this.getAppendedFrag(r+.1)),e){var i=this.fragPlaying,a=e.level;i&&e.sn===i.sn&&i.level===a&&e.urlId===i.urlId||(this.hls.trigger(n.a.FRAG_CHANGED,{frag:e}),i&&i.level===a||this.hls.trigger(n.a.LEVEL_SWITCHED,{level:a}),this.fragPlaying=e)}}},l=i,(d=[{key:"nextLevel",get:function(){var t=this.nextBufferedFrag;return t?t.level:-1}},{key:"currentLevel",get:function(){var t=this.media;if(t){var e=this.getAppendedFrag(t.currentTime);if(e)return e.level}return-1}},{key:"nextBufferedFrag",get:function(){var t=this.media;if(t){var e=this.getAppendedFrag(t.currentTime);return this.followingBufferedFrag(e)}return null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])&&Yt(l.prototype,d),h&&Yt(l,h),i}(Nt),zt=function(){function t(t,e,r){void 0===e&&(e=0),void 0===r&&(r=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=r}var e=t.prototype;return e.sample=function(t,e){var r=Math.pow(this.alpha_,t);this.estimate_=e*(1-r)+r*this.estimate_,this.totalWeight_+=t},e.getTotalWeight=function(){return this.totalWeight_},e.getEstimate=function(){if(this.alpha_){var t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_},t}(),Qt=function(){function t(t,e,r){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new zt(t),this.fast_=new zt(e)}var e=t.prototype;return e.update=function(t,e){var r=this.slow_,i=this.fast_;this.slow_.halfLife!==t&&(this.slow_=new zt(t,r.getEstimate(),r.getTotalWeight())),this.fast_.halfLife!==e&&(this.fast_=new zt(e,i.getEstimate(),i.getTotalWeight()))},e.sample=function(t,e){var r=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/r;this.fast_.sample(r,i),this.slow_.sample(r,i)},e.canEstimate=function(){var t=this.fast_;return t&&t.getTotalWeight()>=this.minWeight_},e.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},e.destroy=function(){},t}();function $t(t,e){for(var r=0;r=2*d/f||y<=T)){var E,S=Number.POSITIVE_INFINITY;for(E=t.level-1;E>v;E--){if((S=d*c[E].maxBitrate/(6.4*m))=y)){var L=this.bwEstimator.getEstimate();o.b.warn("Fragment "+t.sn+(e?" part "+e.index:"")+" of level "+t.level+" is loading too slowly and will cause an underbuffer; aborting and switching to level "+E+"\n Current BW estimate: "+(Object(a.a)(L)?(L/1024).toFixed(3):"Unknown")+" Kb/s\n Estimated load time for current fragment: "+y.toFixed(3)+" s\n Estimated load time for the next fragment: "+S.toFixed(3)+" s\n Time to underbuffer: "+T.toFixed(3)+" s"),r.nextLoadLevel=E,this.bwEstimator.sample(h,u.loaded),this.clearTimer(),t.loader&&(this.fragCurrent=this.partCurrent=null,t.loader.abort()),r.trigger(n.a.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:u})}}}}}},l.onFragLoaded=function(t,e){var r=e.frag,i=e.part;if(r.type===_.b.MAIN&&Object(a.a)(r.sn)){var s=i?i.stats:r.stats,o=i?i.duration:r.duration;if(this.clearTimer(),this.lastLoadedFragLevel=r.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){var l=this.hls.levels[r.level],u=(l.loaded?l.loaded.bytes:0)+s.loaded,d=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:u,duration:d},l.realBitrate=Math.round(8*u/d)}if(r.bitrateTest){var h={stats:s,frag:r,part:i,id:r.type};this.onFragBuffered(n.a.FRAG_BUFFERED,h),r.bitrateTest=!1}}},l.onFragBuffered=function(t,e){var r=e.frag,i=e.part,a=i?i.stats:r.stats;if(!a.aborted&&r.type===_.b.MAIN&&"initSegment"!==r.sn){var n=a.parsing.end-a.loading.start;this.bwEstimator.sample(n,a.loaded),a.bwEstimate=this.bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}},l.onError=function(t,e){switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:this.clearTimer()}},l.clearTimer=function(){self.clearInterval(this.timer),this.timer=void 0},l.getNextABRAutoLevel=function(){var t=this.fragCurrent,e=this.partCurrent,r=this.hls,i=r.maxAutoLevel,a=r.config,n=r.minAutoLevel,s=r.media,l=e?e.duration:t?t.duration:0,u=s?s.currentTime:0,d=s&&0!==s.playbackRate?Math.abs(s.playbackRate):1,h=this.bwEstimator?this.bwEstimator.getEstimate():a.abrEwmaDefaultEstimate,f=(nt.bufferInfo(s,u,a.maxBufferHole).end-u)/d,c=this.findBestLevel(h,n,i,f,a.abrBandWidthFactor,a.abrBandWidthUpFactor);if(c>=0)return c;o.b.trace((f?"rebuffering expected":"buffer is empty")+", finding optimal quality level");var v=l?Math.min(l,a.maxStarvationDelay):a.maxStarvationDelay,g=a.abrBandWidthFactor,p=a.abrBandWidthUpFactor;if(!f){var m=this.bitrateTestDelay;if(m)v=(l?Math.min(l,a.maxLoadingDelay):a.maxLoadingDelay)-m,o.b.trace("bitrate test took "+Math.round(1e3*m)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*v)+" ms"),g=p=1}return c=this.findBestLevel(h,n,i,f+v,g,p),Math.max(c,0)},l.findBestLevel=function(t,e,r,i,a,n){for(var s,l=this.fragCurrent,u=this.partCurrent,d=this.lastLoadedFragLevel,h=this.hls.levels,f=h[d],c=!(null==f||null===(s=f.details)||void 0===s||!s.live),v=null==f?void 0:f.codecSet,g=u?u.duration:l?l.duration:0,p=r;p>=e;p--){var m=h[p];if(m&&(!v||m.codecSet===v)){var y=m.details,b=(u?null==y?void 0:y.partTarget:null==y?void 0:y.averagetargetduration)||g,T=void 0;T=p<=d?a*t:n*t;var E=h[p].maxBitrate,S=E*b/T;if(o.b.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+p+"/"+Math.round(T)+"/"+E+"/"+b+"/"+i+"/"+S),T>E&&(!S||c&&!this.bitrateTestDelay||S0||Object.keys(this.pendingTracks).length>0},e.destroy=function(){this.unregisterListeners(),this.details=null},e.registerListeners=function(){var t=this.hls;t.on(n.a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(n.a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(n.a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(n.a.BUFFER_RESET,this.onBufferReset,this),t.on(n.a.BUFFER_APPENDING,this.onBufferAppending,this),t.on(n.a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(n.a.BUFFER_EOS,this.onBufferEos,this),t.on(n.a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(n.a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(n.a.FRAG_PARSED,this.onFragParsed,this),t.on(n.a.FRAG_CHANGED,this.onFragChanged,this)},e.unregisterListeners=function(){var t=this.hls;t.off(n.a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(n.a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(n.a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(n.a.BUFFER_RESET,this.onBufferReset,this),t.off(n.a.BUFFER_APPENDING,this.onBufferAppending,this),t.off(n.a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(n.a.BUFFER_EOS,this.onBufferEos,this),t.off(n.a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(n.a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(n.a.FRAG_PARSED,this.onFragParsed,this),t.off(n.a.FRAG_CHANGED,this.onFragChanged,this)},e._initSourceBuffer=function(){this.sourceBuffer={},this.operationQueue=new ee(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]}},e.onManifestParsed=function(t,e){var r=2;(e.audio&&!e.video||!e.altAudio)&&(r=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,this.details=null,o.b.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},e.onMediaAttaching=function(t,e){var r=this.media=e.media;if(r&&re){var i=this.mediaSource=new re;i.addEventListener("sourceopen",this._onMediaSourceOpen),i.addEventListener("sourceended",this._onMediaSourceEnded),i.addEventListener("sourceclose",this._onMediaSourceClose),r.src=self.URL.createObjectURL(i),this._objectUrl=r.src}},e.onMediaDetaching=function(){var t=this.media,e=this.mediaSource,r=this._objectUrl;if(e){if(o.b.log("[buffer-controller]: media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){o.b.warn("[buffer-controller]: onMediaDetaching: "+t.message+" while calling endOfStream")}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),t&&(r&&self.URL.revokeObjectURL(r),t.src===r?(t.removeAttribute("src"),t.load()):o.b.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(n.a.MEDIA_DETACHED,void 0)},e.onBufferReset=function(){var t=this;this.getSourceBufferTypes().forEach((function(e){var r=t.sourceBuffer[e];try{r&&(t.removeBufferListeners(e),t.mediaSource&&t.mediaSource.removeSourceBuffer(r),t.sourceBuffer[e]=void 0)}catch(t){o.b.warn("[buffer-controller]: Failed to reset the "+e+" buffer",t)}})),this._initSourceBuffer()},e.onBufferCodecs=function(t,e){var r=this,i=this.getSourceBufferTypes().length;Object.keys(e).forEach((function(t){if(i){var a=r.tracks[t];if(a&&"function"==typeof a.buffer.changeType){var n=e[t],s=n.codec,o=n.levelCodec,l=n.container;if((a.levelCodec||a.codec).replace(ie,"$1")!==(o||s).replace(ie,"$1")){var u=l+";codecs="+(o||s);r.appendChangeType(t,u)}}}else r.pendingTracks[t]=e[t]})),i||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())},e.appendChangeType=function(t,e){var r=this,i=this.operationQueue,a={execute:function(){var a=r.sourceBuffer[t];a&&(o.b.log("[buffer-controller]: changing "+t+" sourceBuffer type to "+e),a.changeType(e)),i.shiftAndExecuteNext(t)},onStart:function(){},onComplete:function(){},onError:function(e){o.b.warn("[buffer-controller]: Failed to change "+t+" SourceBuffer type",e)}};i.append(a,t)},e.onBufferAppending=function(t,e){var r=this,i=this.hls,a=this.operationQueue,l=this.tracks,u=e.data,d=e.type,h=e.frag,f=e.part,c=e.chunkMeta,v=c.buffering[d],g=self.performance.now();v.start=g;var p=h.stats.buffering,m=f?f.stats.buffering:null;0===p.start&&(p.start=g),m&&0===m.start&&(m.start=g);var y=l.audio,b="audio"===d&&1===c.id&&"audio/mpeg"===(null==y?void 0:y.container),T={execute:function(){if(v.executeStart=self.performance.now(),b){var t=r.sourceBuffer[d];if(t){var e=h.start-t.timestampOffset;Math.abs(e)>=.1&&(o.b.log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to "+h.start+" (delta: "+e+") sn: "+h.sn+")"),t.timestampOffset=h.start)}}r.appendExecutor(u,d)},onStart:function(){},onComplete:function(){var t=self.performance.now();v.executeEnd=v.end=t,0===p.first&&(p.first=t),m&&0===m.first&&(m.first=t);var e=r.sourceBuffer,i={};for(var a in e)i[a]=nt.getBuffered(e[a]);r.appendError=0,r.hls.trigger(n.a.BUFFER_APPENDED,{type:d,frag:h,part:f,chunkMeta:c,parent:h.type,timeRanges:i})},onError:function(t){o.b.error("[buffer-controller]: Error encountered while trying to append to the "+d+" SourceBuffer",t);var e={type:s.b.MEDIA_ERROR,parent:h.type,details:s.a.BUFFER_APPEND_ERROR,err:t,fatal:!1};t.code===DOMException.QUOTA_EXCEEDED_ERR?e.details=s.a.BUFFER_FULL_ERROR:(r.appendError++,e.details=s.a.BUFFER_APPEND_ERROR,r.appendError>i.config.appendErrorMaxRetry&&(o.b.error("[buffer-controller]: Failed "+i.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),e.fatal=!0)),i.trigger(n.a.ERROR,e)}};a.append(T,d)},e.onBufferFlushing=function(t,e){var r=this,i=this.operationQueue,a=function(t){return{execute:r.removeExecutor.bind(r,t,e.startOffset,e.endOffset),onStart:function(){},onComplete:function(){r.hls.trigger(n.a.BUFFER_FLUSHED,{type:t})},onError:function(e){o.b.warn("[buffer-controller]: Failed to remove from "+t+" SourceBuffer",e)}}};e.type?i.append(a(e.type),e.type):this.getSourceBufferTypes().forEach((function(t){i.append(a(t),t)}))},e.onFragParsed=function(t,e){var r=this,i=e.frag,a=e.part,s=[],l=a?a.elementaryStreams:i.elementaryStreams;l[u.a.AUDIOVIDEO]?s.push("audiovideo"):(l[u.a.AUDIO]&&s.push("audio"),l[u.a.VIDEO]&&s.push("video"));0===s.length&&o.b.warn("Fragments must have at least one ElementaryStreamType set. type: "+i.type+" level: "+i.level+" sn: "+i.sn),this.blockBuffers((function(){var t=self.performance.now();i.stats.buffering.end=t,a&&(a.stats.buffering.end=t);var e=a?a.stats:i.stats;r.hls.trigger(n.a.FRAG_BUFFERED,{frag:i,part:a,stats:e,id:i.type})}),s)},e.onFragChanged=function(t,e){this.flushBackBuffer()},e.onBufferEos=function(t,e){var r=this;this.getSourceBufferTypes().reduce((function(t,i){var a=r.sourceBuffer[i];return e.type&&e.type!==i||a&&!a.ended&&(a.ended=!0,o.b.log("[buffer-controller]: "+i+" sourceBuffer now EOS")),t&&!(a&&!a.ended)}),!0)&&this.blockBuffers((function(){var t=r.mediaSource;t&&"open"===t.readyState&&t.endOfStream()}))},e.onLevelUpdated=function(t,e){var r=e.details;r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())},e.flushBackBuffer=function(){var t=this.hls,e=this.details,r=this.media,i=this.sourceBuffer;if(r&&null!==e){var s=this.getSourceBufferTypes();if(s.length){var o=e.live&&null!==t.config.liveBackBufferLength?t.config.liveBackBufferLength:t.config.backBufferLength;if(Object(a.a)(o)&&!(o<0)){var l=r.currentTime,u=e.levelTargetDuration,d=Math.max(o,u),h=Math.floor(l/u)*u-d;s.forEach((function(r){var a=i[r];if(a){var s=nt.getBuffered(a);s.length>0&&h>s.start(0)&&(t.trigger(n.a.BACK_BUFFER_REACHED,{bufferEnd:h}),e.live&&t.trigger(n.a.LIVE_BACK_BUFFER_REACHED,{bufferEnd:h}),t.trigger(n.a.BUFFER_FLUSHING,{startOffset:0,endOffset:h,type:r}))}}))}}}},e.updateMediaElementDuration=function(){if(this.details&&this.media&&this.mediaSource&&"open"===this.mediaSource.readyState){var t=this.details,e=this.hls,r=this.media,i=this.mediaSource,n=t.fragments[0].start+t.totalduration,s=r.duration,l=Object(a.a)(i.duration)?i.duration:0;t.live&&e.config.liveDurationInfinity?(o.b.log("[buffer-controller]: Media Source duration is set to Infinity"),i.duration=1/0,this.updateSeekableRange(t)):(n>l&&n>s||!Object(a.a)(s))&&(o.b.log("[buffer-controller]: Updating Media Source duration to "+n.toFixed(3)),i.duration=n)}},e.updateSeekableRange=function(t){var e=this.mediaSource,r=t.fragments;if(r.length&&t.live&&null!=e&&e.setLiveSeekableRange){var i=Math.max(0,r[0].start),a=Math.max(i,i+t.totalduration);e.setLiveSeekableRange(i,a)}},e.checkPendingTracks=function(){var t=this.bufferCodecEventsExpected,e=this.operationQueue,r=this.pendingTracks,i=Object.keys(r).length;if(i&&!t||2===i){this.createSourceBuffers(r),this.pendingTracks={};var a=this.getSourceBufferTypes();if(0===a.length)return void this.hls.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,reason:"could not create source buffer for media codec(s)"});a.forEach((function(t){e.executeNext(t)}))}},e.createSourceBuffers=function(t){var e=this.sourceBuffer,r=this.mediaSource;if(!r)throw Error("createSourceBuffers called when mediaSource was null");var i=0;for(var a in t)if(!e[a]){var l=t[a];if(!l)throw Error("source buffer exists for track "+a+", however track does not");var u=l.levelCodec||l.codec,d=l.container+";codecs="+u;o.b.log("[buffer-controller]: creating sourceBuffer("+d+")");try{var h=e[a]=r.addSourceBuffer(d),f=a;this.addBufferListener(f,"updatestart",this._onSBUpdateStart),this.addBufferListener(f,"updateend",this._onSBUpdateEnd),this.addBufferListener(f,"error",this._onSBUpdateError),this.tracks[a]={buffer:h,codec:u,container:l.container,levelCodec:l.levelCodec,id:l.id},i++}catch(t){o.b.error("[buffer-controller]: error while trying to add sourceBuffer: "+t.message),this.hls.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,mimeType:d})}}i&&this.hls.trigger(n.a.BUFFER_CREATED,{tracks:this.tracks})},e._onSBUpdateStart=function(t){this.operationQueue.current(t).onStart()},e._onSBUpdateEnd=function(t){var e=this.operationQueue;e.current(t).onComplete(),e.shiftAndExecuteNext(t)},e._onSBUpdateError=function(t,e){o.b.error("[buffer-controller]: "+t+" SourceBuffer error",e),this.hls.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_APPENDING_ERROR,fatal:!1});var r=this.operationQueue.current(t);r&&r.onError(e)},e.removeExecutor=function(t,e,r){var i=this.media,n=this.mediaSource,s=this.operationQueue,l=this.sourceBuffer[t];if(!i||!n||!l)return o.b.warn("[buffer-controller]: Attempting to remove from the "+t+" SourceBuffer, but it does not exist"),void s.shiftAndExecuteNext(t);var u=Object(a.a)(i.duration)?i.duration:1/0,d=Object(a.a)(n.duration)?n.duration:1/0,h=Math.max(0,e),f=Math.min(r,u,d);f>h?(o.b.log("[buffer-controller]: Removing ["+h+","+f+"] from the "+t+" SourceBuffer"),l.remove(h,f)):s.shiftAndExecuteNext(t)},e.appendExecutor=function(t,e){var r=this.operationQueue,i=this.sourceBuffer[e];if(!i)return o.b.warn("[buffer-controller]: Attempting to append to the "+e+" SourceBuffer, but it does not exist"),void r.shiftAndExecuteNext(e);i.ended=!1,i.appendBuffer(t)},e.blockBuffers=function(t,e){var r=this;if(void 0===e&&(e=this.getSourceBufferTypes()),!e.length)return o.b.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve(t);var i=this.operationQueue,a=e.map((function(t){return i.appendBlocker(t)}));Promise.all(a).then((function(){t(),e.forEach((function(t){var e=r.sourceBuffer[t];e&&e.updating||i.shiftAndExecuteNext(t)}))}))},e.getSourceBufferTypes=function(){return Object.keys(this.sourceBuffer)},e.addBufferListener=function(t,e,r){var i=this.sourceBuffer[t];if(i){var a=r.bind(this,t);this.listeners[t].push({event:e,listener:a}),i.addEventListener(e,a)}},e.removeBufferListeners=function(t){var e=this.sourceBuffer[t];e&&this.listeners[t].forEach((function(t){e.removeEventListener(t.event,t.listener)}))},t}();function ne(t,e){for(var r=0;r0&&this.mediaWidth>0){var t=this.hls.levels;if(t.length){var e=this.hls;e.autoLevelCapping=this.getMaxLevel(t.length-1),e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}},a.getMaxLevel=function(e){var r=this,i=this.hls.levels;if(!i.length)return-1;var a=i.filter((function(i,a){return t.isLevelAllowed(a,r.restrictedLevels)&&a<=e}));return this.clientRect=null,t.getMaxLevelByMediaSize(a,this.mediaWidth,this.mediaHeight)},a.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},a.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},a.getDimensions=function(){if(this.clientRect)return this.clientRect;var t=this.media,e={width:0,height:0};if(t){var r=t.getBoundingClientRect();e.width=r.width,e.height=r.height,e.width||e.height||(e.width=r.right-r.left||t.width||0,e.height=r.bottom-r.top||t.height||0)}return this.clientRect=e,e},t.isLevelAllowed=function(t,e){return void 0===e&&(e=[]),-1===e.indexOf(t)},t.getMaxLevelByMediaSize=function(t,e,r){if(!t||!t.length)return-1;for(var i,a,n=t.length-1,s=0;s=e||o.height>=r)&&(i=o,!(a=t[s+1])||i.width!==a.width||i.height!==a.height)){n=s;break}}return n},e=t,i=[{key:"contentScaleFactor",get:function(){var t=1;try{t=self.devicePixelRatio}catch(t){}return t}}],(r=[{key:"mediaWidth",get:function(){return this.getDimensions().width*t.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*t.contentScaleFactor}}])&&ne(e.prototype,r),i&&ne(e,i),t}(),oe=function(){function t(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}var e=t.prototype;return e.setStreamController=function(t){this.streamController=t},e.registerListeners=function(){this.hls.on(n.a.MEDIA_ATTACHING,this.onMediaAttaching,this)},e.unregisterListeners=function(){this.hls.off(n.a.MEDIA_ATTACHING,this.onMediaAttaching)},e.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},e.onMediaAttaching=function(t,e){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},e.checkFPS=function(t,e,r){var i=performance.now();if(e){if(this.lastTime){var a=i-this.lastTime,s=r-this.lastDroppedFrames,l=e-this.lastDecodedFrames,u=1e3*s/a,d=this.hls;if(d.trigger(n.a.FPS_DROP,{currentDropped:s,currentDecoded:l,totalDroppedFrames:r}),u>0&&s>d.config.fpsDroppedMonitoringThreshold*l){var h=d.currentLevel;o.b.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(-1===d.autoLevelCapping||d.autoLevelCapping>=h)&&(h-=1,d.trigger(n.a.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:d.currentLevel}),d.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=e}},e.checkFPSInterval=function(){var t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){var e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)},t}(),le=r(12),ue=/^age:\s*[\d.]+\s*$/m,de=function(){function t(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=t?t.xhrSetup:null,this.stats=new le.a,this.retryDelay=0}var e=t.prototype;return e.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null},e.abortInternal=function(){var t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))},e.abort=function(){var t;this.abortInternal(),null!==(t=this.callbacks)&&void 0!==t&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},e.load=function(t,e,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=r,this.retryDelay=e.retryDelay,this.loadInternal()},e.loadInternal=function(){var t=this.config,e=this.context;if(t){var r=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0;var a=this.xhrSetup;try{if(a)try{a(r,e.url)}catch(t){r.open("GET",e.url,!0),a(r,e.url)}r.readyState||r.open("GET",e.url,!0);var n=this.context.headers;if(n)for(var s in n)r.setRequestHeader(s,n[s])}catch(t){return void this.callbacks.onError({code:r.status,text:t.message},e,r)}e.rangeEnd&&r.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),r.onreadystatechange=this.readystatechange.bind(this),r.onprogress=this.loadprogress.bind(this),r.responseType=e.responseType,self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),t.timeout),r.send()}},e.readystatechange=function(){var t=this.context,e=this.loader,r=this.stats;if(t&&e){var i=e.readyState,a=this.config;if(!r.aborted&&i>=2)if(self.clearTimeout(this.requestTimeout),0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start)),4===i){e.onreadystatechange=null,e.onprogress=null;var n=e.status;if(n>=200&&n<300){var s,l;if(r.loading.end=Math.max(self.performance.now(),r.loading.first),l="arraybuffer"===t.responseType?(s=e.response).byteLength:(s=e.responseText).length,r.loaded=r.total=l,!this.callbacks)return;var u=this.callbacks.onProgress;if(u&&u(r,t,s,e),!this.callbacks)return;var d={url:e.responseURL,data:s};this.callbacks.onSuccess(d,r,t,e)}else r.retry>=a.maxRetry||n>=400&&n<499?(o.b.error(n+" while loading "+t.url),this.callbacks.onError({code:n,text:e.statusText},t,e)):(o.b.warn(n+" while loading "+t.url+", retrying in "+this.retryDelay+"..."),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,a.maxRetryDelay),r.retry++)}else self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),a.timeout)}},e.loadtimeout=function(){o.b.warn("timeout while loading "+this.context.url);var t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))},e.loadprogress=function(t){var e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)},e.getCacheAge=function(){var t=null;if(this.loader&&ue.test(this.loader.getAllResponseHeaders())){var e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t},t}(),he=r(16);function fe(t){var e="function"==typeof Map?new Map:void 0;return(fe=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,i)}function i(){return ce(t,arguments,pe(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),ge(i,t)})(t)}function ce(t,e,r){return(ce=ve()?Reflect.construct:function(t,e,r){var i=[null];i.push.apply(i,e);var a=new(Function.bind.apply(t,i));return r&&ge(a,r.prototype),a}).apply(null,arguments)}function ve(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function ge(t,e){return(ge=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function pe(t){return(pe=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function me(){return(me=Object.assign||function(t){for(var e=1;e=i&&a(e,r,n.flush(),t)):a(e,r,l,t),o()})).catch((function(){return Promise.reject()}))}()},t}();function be(t,e){return new self.Request(t.url,e)}var Te,Ee=function(t){var e,r;function i(e,r,i){var a;return(a=t.call(this,e)||this).code=void 0,a.details=void 0,a.code=r,a.details=i,a}return r=t,(e=i).prototype=Object.create(r.prototype),e.prototype.constructor=e,ge(e,r),i}(fe(Error)),Se=ye;!function(t){t.WIDEVINE="com.widevine.alpha",t.PLAYREADY="com.microsoft.playready"}(Te||(Te={}));var Le="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Ae(){return(Ae=Object.assign||function(t){for(var e=1;ee)return i;return 0}},{key:"maxAutoLevel",get:function(){var t=this.levels,e=this.autoLevelCapping;return-1===e&&t&&t.length?t.length-1:e}},{key:"nextAutoLevel",get:function(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)},set:function(t){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,t)}},{key:"audioTracks",get:function(){var t=this.audioTrackController;return t?t.audioTracks:[]}},{key:"audioTrack",get:function(){var t=this.audioTrackController;return t?t.audioTrack:-1},set:function(t){var e=this.audioTrackController;e&&(e.audioTrack=t)}},{key:"subtitleTracks",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTrack:-1},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var t=this.subtitleTrackController;return!!t&&t.subtitleDisplay},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(t){this.config.lowLatencyMode=t}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}}])&&Ce(e.prototype,r),a&&Ce(e,a),t}();we.defaultConfig=void 0}]).default})); -// @license-end \ No newline at end of file +// @version v1.2.9 +"undefined"!=typeof window&&function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Hls=t():e.Hls=t()}(this,(()=>(()=>{var e={21:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>u});var i=function(){function e(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}return e.prototype.decrypt=function(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)},e}(),n=function(){function e(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}return e.prototype.expandKey=function(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])},e}(),a=r(145),s=function(){function e(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}var t=e.prototype;return t.uint8ArrayToUint32Array_=function(e){for(var t=new DataView(e),r=new Uint32Array(4),i=0;i<4;i++)r[i]=t.getUint32(4*i);return r},t.initTable=function(){var e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],n=r[1],a=r[2],s=r[3],o=this.invSubMix,l=o[0],u=o[1],d=o[2],h=o[3],f=new Uint32Array(256),c=0,v=0,g=0;for(g=0;g<256;g++)f[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){var p=v^v<<1^v<<2^v<<3^v<<4;p=p>>>8^255&p^99,e[c]=p,t[p]=c;var m=f[c],y=f[m],E=f[y],T=257*f[p]^16843008*p;i[c]=T<<24|T>>>8,n[c]=T<<16|T>>>16,a[c]=T<<8|T>>>24,s[c]=T,T=16843009*E^65537*y^257*m^16843008*c,l[p]=T<<24|T>>>8,u[p]=T<<16|T>>>16,d[p]=T<<8|T>>>24,h[p]=T,c?(c=m^f[f[f[E^m]]],v^=f[f[v]]):c=v=1}},t.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i{"use strict";r.r(t),r.d(t,{canParse:()=>l,decodeFrame:()=>c,getID3Data:()=>s,getID3Frames:()=>f,getTimeStamp:()=>u,isFooter:()=>a,isHeader:()=>n,isTimeStampFrame:()=>d,testables:()=>E,utf8ArrayToStr:()=>y});var i,n=function(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128},a=function(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128},s=function(e,t){for(var r=t,i=0;n(e,t);)i+=10,i+=o(e,t+6),a(e,t+10)&&(i+=10),t+=i;if(i>0)return e.subarray(r,r+i)},o=function(e,t){var r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,(r|=(127&e[t+2])<<7)|127&e[t+3]},l=function(e,t){return n(e,t)&&o(e,t+6)+10<=e.length-t},u=function(e){for(var t=f(e),r=0;r>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:u+=String.fromCharCode(a);break;case 12:case 13:s=e[d++],u+=String.fromCharCode((31&a)<<6|63&s);break;case 14:s=e[d++],o=e[d++],u+=String.fromCharCode((15&a)<<12|(63&s)<<6|(63&o)<<0)}}return u},E={decodeTextFrame:g};function T(){return i||void 0===self.TextDecoder||(i=new self.TextDecoder("utf-8")),i}},182:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>o});var i=r(764),n=r(851),a=r(93),s=r(729);function o(e){var t=new s.EventEmitter,r=function(t,r){e.postMessage({event:t,data:r})};t.on(n.Events.FRAG_DECRYPTED,r),t.on(n.Events.ERROR,r),e.addEventListener("message",(function(n){var s=n.data;switch(s.cmd){case"init":var o=JSON.parse(s.config);e.transmuxer=new i.default(t,s.typeSupported,o,s.vendor,s.id),(0,a.enableLogs)(o.debug,s.id),function(){var e=function(e){a.logger[e]=function(t){r("workerLog",{logType:e,message:t})}};for(var t in a.logger)e(t)}(),r("init",null);break;case"configure":e.transmuxer.configure(s.config);break;case"demux":var u=e.transmuxer.push(s.data,s.decryptdata,s.chunkMeta,s.state);(0,i.isPromise)(u)?u.then((function(t){l(e,t)})):l(e,u);break;case"flush":var h=s.chunkMeta,f=e.transmuxer.flush(h);(0,i.isPromise)(f)?f.then((function(t){d(e,t,h)})):d(e,f,h)}}))}function l(e,t){if(!((r=t.remuxResult).audio||r.video||r.text||r.id3||r.initSegment))return!1;var r,i=[],n=t.remuxResult,a=n.audio,s=n.video;return a&&u(i,a),s&&u(i,s),e.postMessage({event:"transmuxComplete",data:t},i),!0}function u(e,t){t.data1&&e.push(t.data1.buffer),t.data2&&e.push(t.data2.buffer)}function d(e,t,r){t.reduce((function(t,r){return l(e,r)||t}),!1)||e.postMessage({event:"transmuxComplete",data:t[0]}),e.postMessage({event:"flush",data:r})}},764:(e,t,r)=>{"use strict";r.r(t),r.d(t,{TransmuxConfig:()=>Ee,TransmuxState:()=>Te,default:()=>pe,isPromise:()=>ye});var i=r(851),n=r(973),a=r(21),s=r(965),o=r(181),l=r(856);function u(e,t){return void 0===e&&(e=""),void 0===t&&(t=9e4),{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}var d=r(63),h=r(145),f=function(){function e(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}var t=e.prototype;return t.resetInitSegment=function(e,t,r,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},t.resetTimeStamp=function(e){this.initPTS=e,this.resetContiguity()},t.resetContiguity=function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0},t.canParse=function(e,t){return!1},t.appendFrame=function(e,t,r){},t.demux=function(e,t){this.cachedData&&(e=(0,d.appendUint8Array)(this.cachedData,e),this.cachedData=null);var r,i=o.getID3Data(e,0),n=i?i.length:0,a=this._audioTrack,f=this._id3Track,v=i?o.getTimeStamp(i):void 0,g=e.length;for((null===this.basePTS||0===this.frameIndex&&(0,s.isFiniteNumber)(v))&&(this.basePTS=c(v,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&f.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:l.MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY});n>>5}function E(e,t){return t+1=e.length)return!1;var i=y(e,t);if(i<=r)return!1;var n=t+i;return n===e.length||E(e,n)}return!1}function S(e,t,r,a,s){if(!e.samplerate){var o=function(e,t,r,a){var s,o,l,u,d=navigator.userAgent.toLowerCase(),h=a,f=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&t[r+2])>>>6);var c=(60&t[r+2])>>>2;if(!(c>f.length-1))return l=(1&t[r+2])<<2,l|=(192&t[r+3])>>>6,g.logger.log("manifest codec:"+a+", ADTS type:"+s+", samplingIndex:"+c),/firefox/i.test(d)?c>=6?(s=5,u=new Array(4),o=c-3):(s=2,u=new Array(2),o=c):-1!==d.indexOf("android")?(s=2,u=new Array(2),o=c):(s=5,u=new Array(4),a&&(-1!==a.indexOf("mp4a.40.29")||-1!==a.indexOf("mp4a.40.5"))||!a&&c>=6?o=c-3:((a&&-1!==a.indexOf("mp4a.40.2")&&(c>=6&&1===l||/vivaldi/i.test(d))||!a&&1===l)&&(s=2,u=new Array(2)),o=c)),u[0]=s<<3,u[0]|=(14&c)>>1,u[1]|=(1&c)<<7,u[1]|=l<<3,5===s&&(u[1]|=(14&o)>>1,u[2]=(1&o)<<7,u[2]|=8,u[3]=0),{config:u,samplerate:f[c],channelCount:l,codec:"mp4a.40."+s,manifestCodec:h};e.trigger(i.Events.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+c})}(t,r,a,s);if(!o)return;e.config=o.config,e.samplerate=o.samplerate,e.channelCount=o.channelCount,e.codec=o.codec,e.manifestCodec=o.manifestCodec,g.logger.log("parsed codec:"+e.codec+", rate:"+o.samplerate+", channels:"+o.channelCount)}}function b(e){return 9216e4/e}function L(e,t,r,i,n){var a,s=i+n*b(e.samplerate),o=function(e,t){var r=m(e,t);if(t+r<=e.length){var i=y(e,t)-r;if(i>0)return{headerLength:r,frameLength:i}}}(t,r);if(o){var l=o.frameLength,u=o.headerLength,d=u+l,h=Math.max(0,r+d-t.length);h?(a=new Uint8Array(d-u)).set(t.subarray(r+u,t.length),0):a=t.subarray(r+u,r+d);var f={unit:a,pts:s};return h||e.samples.push(f),{sample:f,length:d,missing:h}}var c=t.length-r;return(a=new Uint8Array(c)).set(t.subarray(r,t.length),0),{sample:{unit:a,pts:s},length:c,missing:-1}}function A(e,t){return A=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},A(e,t)}const D=function(e){var t,r;function i(t,r){var i;return(i=e.call(this)||this).observer=void 0,i.config=void 0,i.observer=t,i.config=r,i}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,A(t,r);var n=i.prototype;return n.resetInitSegment=function(t,r,i,n){e.prototype.resetInitSegment.call(this,t,r,i,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}},i.probe=function(e){if(!e)return!1;for(var t=(o.getID3Data(e,0)||[]).length,r=e.length;t16384?e.subarray(0,16384):e,(0,d.findBox)(e,["moof"]).length>0},t.demux=function(e,t){this.timeOffset=t;var r=e,i=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=(0,d.appendUint8Array)(this.remainderData,e));var a=(0,d.segmentValidRange)(r);this.remainderData=a.remainder,i.samples=a.valid||new Uint8Array}else i.samples=r;var s=this.extractID3Track(i,t);return n.samples=(0,d.parseSamples)(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:s,textTrack:this.txtTrack}},t.flush=function(){var e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;var i=this.extractID3Track(t,this.timeOffset);return r.samples=(0,d.parseSamples)(e,t),{videoTrack:t,audioTrack:u(),id3Track:i,textTrack:u()}},t.extractID3Track=function(e,t){var r=this.id3Track;if(e.samples.length){var i=(0,d.findBox)(e.samples,["emsg"]);i&&i.forEach((function(e){var i=(0,d.parseEmsg)(e);if(R.test(i.schemeIdUri)){var n=(0,s.isFiniteNumber)(i.presentationTime)?i.presentationTime/i.timeScale:t+i.presentationTimeDelta/i.timeScale,a=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;a<=.001&&(a=Number.POSITIVE_INFINITY);var o=i.payload;r.samples.push({data:o,len:o.byteLength,dts:n,pts:n,type:l.MetadataSchema.emsg,duration:a})}}))}return r},t.demuxSampleAes=function(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},t.destroy=function(){},e}();var _=null,x=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],I=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],w=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],C=[0,1,1,4];function P(e,t,r,i,n){if(!(r+24>t.length)){var a=O(t,r);if(a&&r+a.frameLength<=t.length){var s=i+n*(9e4*a.samplesPerFrame/a.sampleRate),o={unit:t.subarray(r,r+a.frameLength),pts:s,dts:s};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(o),{sample:o,length:a.frameLength,missing:0}}}}function O(e,t){var r=e[t+1]>>3&3,i=e[t+1]>>1&3,n=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==r&&0!==n&&15!==n&&3!==a){var s=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*x[14*(3===r?3-i:3===i?3:4)+n-1],u=I[3*(3===r?0:2===r?1:2)+a],d=3===o?1:2,h=w[r][i],f=C[i],c=8*h*f,v=Math.floor(h*l/u+s)*f;if(null===_){var g=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);_=g?parseInt(g[1]):0}return!!_&&_<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:u,channelCount:d,frameLength:v,samplesPerFrame:c}}}function F(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])}function M(e,t){return t+1e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)>>3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)},t.readBits=function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;return e>32&&g.logger.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0?this.word<<=t:this.bytesAvailable>0&&this.loadWord(),(t=e-t)>0&&this.bitsAvailable?r<>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()},t.skipUEG=function(){this.skipBits(1+this.skipLZ())},t.skipEG=function(){this.skipBits(1+this.skipLZ())},t.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},t.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},t.readBoolean=function(){return 1===this.readBits(1)},t.readUByte=function(){return this.readBits(8)},t.readUShort=function(){return this.readBits(16)},t.readUInt=function(){return this.readBits(32)},t.skipScalingList=function(e){for(var t=8,r=8,i=0;i=e.length)return void r();if(!(e[t].unit.length<32)){var i=this.decrypter.isSync();if(this.decryptAacSample(e,t,r,i),!i)return}}},t.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,n=32;n=e.length)return void i();for(var n=e[t].units;!(r>=n.length);r++){var a=n[r];if(!(a.data.length<=48||1!==a.type&&5!==a.type)){var s=this.decrypter.isSync();if(this.decryptAvcSample(e,t,r,i,a,s),!s)return}}}},e}();function G(){return G=Object.assign?Object.assign.bind():function(e){for(var t=1;t1;){var l=new Uint8Array(o[0].length+o[1].length);l.set(o[0]),l.set(o[1],o[0].length),o[0]=l,o.splice(1,1)}if(1===((t=o[0])[0]<<16)+(t[1]<<8)+t[2]){if((r=(t[4]<<8)+t[5])&&r>e.size-6)return null;var u=t[7];192&u&&(n=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&u?n-(a=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2)>54e5&&(g.logger.warn(Math.round((n-a)/9e4)+"s delta between PTS and DTS, align them"),n=a):a=n);var d=(i=t[8])+9;if(e.size<=d)return null;e.size-=d;for(var h=new Uint8Array(e.size),f=0,c=o.length;fv){d-=v;continue}t=t.subarray(d),v-=d,d=0}h.set(t,s),s+=v}return r&&(r-=i+3),{data:h,pts:n,dts:a,len:r}}return null}function Y(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var r=t.samples,i=r.length;if(!i)return void t.dropped++;var n=r[i-1];e.pts=n.pts,e.dts=n.dts}t.samples.push(e)}e.debug.length&&g.logger.log(e.pts+"/"+e.dts+":"+e.debug)}const q=function(){function e(e,t,r){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=e,this.config=t,this.typeSupported=r}e.probe=function(t){var r=e.syncOffset(t);return r>0&&g.logger.warn("MPEG2-TS detected but first sync word found @ offset "+r),-1!==r},e.syncOffset=function(e){for(var t=Math.min(940,e.length-376)+1,r=0;r>4>1){if((x=R+5+t[R+4])===R+V)continue}else x=R+4;switch(_){case c:k&&(v&&(o=W(v))&&this.parseAVCPES(l,f,o,!1),v={data:[],size:0}),v&&(v.data.push(t.subarray(x,R+V)),v.size+=R+V-x);break;case p:if(k){if(y&&(o=W(y)))switch(u.segmentCodec){case"aac":this.parseAACPES(u,o);break;case"mp3":this.parseMPEGPES(u,o)}y={data:[],size:0}}y&&(y.data.push(t.subarray(x,R+V)),y.size+=R+V-x);break;case m:k&&(E&&(o=W(E))&&this.parseID3PES(h,o),E={data:[],size:0}),E&&(E.data.push(t.subarray(x,R+V)),E.size+=R+V-x);break;case 0:k&&(x+=t[x]+1),b=this._pmtId=j(t,x);break;case b:k&&(x+=t[x]+1);var I=K(t,x,this.typeSupported,a);(c=I.avc)>0&&(l.pid=c),(p=I.audio)>0&&(u.pid=p,u.segmentCodec=I.segmentCodec),(m=I.id3)>0&&(h.pid=m),null===T||S||(g.logger.log("unknown PID '"+T+"' in TS found"),T=null,R=A-188),S=this.pmtParsed=!0;break;case 17:case 8191:break;default:T=_}}else D++;D>0&&this.observer.emit(i.Events.ERROR,i.Events.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,reason:"Found "+D+" TS packet/s that do not start with 0x47"}),l.pesData=v,u.pesData=y,h.pesData=E;var w={audioTrack:u,videoTrack:l,id3Track:h,textTrack:f};return s&&this.extractRemainingSamples(w),w},t.flush=function(){var e,t=this.remainderData;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._avcTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e},t.extractRemainingSamples=function(e){var t,r=e.audioTrack,i=e.videoTrack,n=e.id3Track,a=e.textTrack,s=i.pesData,o=r.pesData,l=n.pesData;if(s&&(t=W(s))?(this.parseAVCPES(i,a,t,!0),i.pesData=null):i.pesData=s,o&&(t=W(o))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,t);break;case"mp3":this.parseMPEGPES(r,t)}r.pesData=null}else null!=o&&o.size&&g.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;l&&(t=W(l))?(this.parseID3PES(n,t),n.pesData=null):n.pesData=l},t.demuxSampleAes=function(e,t,r){var i=this.demux(e,r,!0,!this.config.progressive),n=this.sampleAes=new B(this.observer,this.config,t);return this.decrypt(i,n)},t.decrypt=function(e,t){return new Promise((function(r){var i=e.audioTrack,n=e.videoTrack;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,(function(){n.samples?t.decryptAvcSamples(n.samples,0,0,(function(){r(e)})):r(e)})):n.samples&&t.decryptAvcSamples(n.samples,0,0,(function(){r(e)}))}))},t.destroy=function(){this._duration=0},t.parseAVCPES=function(e,t,r,i){var n,a=this,s=this.parseAVCNALu(e,r.data),o=this.avcSample,l=!1;r.data=null,o&&s.length&&!e.audFound&&(Y(o,e),o=this.avcSample=H(!1,r.pts,r.dts,"")),s.forEach((function(i){switch(i.type){case 1:n=!0,o||(o=a.avcSample=H(!0,r.pts,r.dts,"")),o.frame=!0;var s=i.data;if(l&&s.length>4){var u=new U(s).readSliceType();2!==u&&4!==u&&7!==u&&9!==u||(o.key=!0)}break;case 5:n=!0,o||(o=a.avcSample=H(!0,r.pts,r.dts,"")),o.key=!0,o.frame=!0;break;case 6:n=!0,(0,d.parseSEIMessageFromNALu)(i.data,1,r.pts,t.samples);break;case 7:if(n=!0,l=!0,!e.sps){var h=new U(i.data).readSPS();e.width=h.width,e.height=h.height,e.pixelRatio=h.pixelRatio,e.sps=[i.data],e.duration=a._duration;for(var f=i.data.subarray(1,4),c="avc1.",v=0;v<3;v++){var g=f[v].toString(16);g.length<2&&(g="0"+g),c+=g}e.codec=c}break;case 8:n=!0,e.pps||(e.pps=[i.data]);break;case 9:n=!1,e.audFound=!0,o&&Y(o,e),o=a.avcSample=H(!1,r.pts,r.dts,"");break;case 12:n=!0;break;default:n=!1,o&&(o.debug+="unknown NAL "+i.type+" ")}o&&n&&o.units.push(i)})),i&&o&&(Y(o,e),this.avcSample=null)},t.getLastNalUnit=function(e){var t,r,i=this.avcSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!==(t=i)&&void 0!==t&&t.units){var n=i.units;r=n[n.length-1]}return r},t.parseAVCNALu=function(e,t){var r,i,n=t.byteLength,a=e.naluState||0,s=a,o=[],l=0,u=-1,d=0;for(-1===a&&(u=0,d=31&t[0],a=0,l=1);l=0){var h={data:t.subarray(u,l-a-1),type:d};o.push(h)}else{var f=this.getLastNalUnit(e.samples);if(f&&(s&&l<=4-s&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-s)),(i=l-a-1)>0)){var c=new Uint8Array(f.data.byteLength+i);c.set(f.data,0),c.set(t.subarray(0,i),f.data.byteLength),f.data=c,f.state=0}}l=0&&a>=0){var v={data:t.subarray(u,n),type:d,state:a};o.push(v)}if(0===o.length){var g=this.getLastNalUnit(e.samples);if(g){var p=new Uint8Array(g.data.byteLength+t.byteLength);p.set(g.data,0),p.set(t,g.data.byteLength),g.data=p}}return e.naluState=a,o},t.parseAACPES=function(e,t){var r,a,s,o,l,u=0,d=this.aacOverFlow,h=t.data;if(d){this.aacOverFlow=null;var f=d.missing,c=d.sample.unit.byteLength;if(-1===f){var v=new Uint8Array(c+h.byteLength);v.set(d.sample.unit,0),v.set(h,c),h=v}else{var p=c-f;d.sample.unit.set(h.subarray(0,f),p),e.samples.push(d.sample),u=d.missing}}for(r=u,a=h.length;r1?r-1:0),n=1;n>24&255,o[1]=t>>16&255,o[2]=t>>8&255,o[3]=255&t,o.set(e,4),a=0,t=8;a>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))},e.mdia=function(t){return e.box(e.types.mdia,e.mdhd(t.timescale,t.duration),e.hdlr(t.type),e.minf(t))},e.mfhd=function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))},e.minf=function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))},e.moof=function(t,r,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))},e.moov=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(e.mvex(t)))},e.mvex=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(i))},e.mvhd=function(t,r){r*=t;var i=Math.floor(r/($+1)),n=Math.floor(r%($+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(e.types.mvhd,a)},e.sdtp=function(t){var r,i,n=t.samples||[],a=new Uint8Array(4+n.length);for(r=0;r>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));for(r=0;r>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(i));var o=e.box(e.types.avcC,new Uint8Array([1,a[3],a[4],a[5],255,224|t.sps.length].concat(a).concat([t.pps.length]).concat(s))),l=t.width,u=t.height,d=t.pixelRatio[0],h=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))},e.esds=function(e){var t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))},e.mp4a=function(t){var r=t.samplerate;return e.box(e.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),e.box(e.types.esds,e.esds(t)))},e.mp3=function(t){var r=t.samplerate;return e.box(e.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))},e.stsd=function(t){return"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?e.box(e.types.stsd,e.STSD,e.mp3(t)):e.box(e.types.stsd,e.STSD,e.mp4a(t)):e.box(e.types.stsd,e.STSD,e.avc1(t))},e.tkhd=function(t){var r=t.id,i=t.duration*t.timescale,n=t.width,a=t.height,s=Math.floor(i/($+1)),o=Math.floor(i%($+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,255&n,0,0,a>>8&255,255&a,0,0]))},e.traf=function(t,r){var i=e.sdtp(t),n=t.id,a=Math.floor(r/($+1)),s=Math.floor(r%($+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,s>>24,s>>16&255,s>>8&255,255&s])),e.trun(t,i.length+16+20+8+16+8+8),i)},e.trak=function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))},e.trex=function(t){var r=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},e.trun=function(t,r){var i,n,a,s,o,l,u=t.samples||[],d=u.length,h=12+16*d,f=new Uint8Array(h);for(r+=8+h,f.set(["video"===t.type?1:0,0,15,1,d>>>24&255,d>>>16&255,d>>>8&255,255&d,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i>>24&255,a>>>16&255,a>>>8&255,255&a,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return e.box(e.types.trun,f)},e.initSegment=function(t){e.types||e.init();var r=e.moov(t),i=new Uint8Array(e.FTYP.byteLength+r.byteLength);return i.set(e.FTYP),i.set(r,e.FTYP.byteLength),i},e}();Z.types=void 0,Z.HDLR_TYPES=void 0,Z.STTS=void 0,Z.STSC=void 0,Z.STCO=void 0,Z.STSZ=void 0,Z.VMHD=void 0,Z.SMHD=void 0,Z.STSD=void 0,Z.FTYP=void 0,Z.DINF=void 0;const J=Z;var ee=r(308);function te(e,t){return void 0===t&&(t=!1),function(e,t,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var n=e*t*r;return i?Math.round(n):n}(e,1e3,1/9e4,t)}function re(){return re=Object.assign?Object.assign.bind():function(e){for(var t=1;t0?e:r.pts}),e[0].pts);return t&&g.logger.debug("PTS rollover detected"),r},t.remux=function(e,t,r,i,n,a,s,o){var l,u,d,h,f,c,v=n,p=n,m=e.pid>-1,y=t.pid>-1,E=t.samples.length,T=e.samples.length>0,S=s&&E>0||E>1;if((!m||T)&&(!y||S)||this.ISGenerated||s){this.ISGenerated||(d=this.generateIS(e,t,n));var b,L=this.isVideoContiguous,A=-1;if(S&&(A=function(e){for(var t=0;t0){g.logger.warn("[mp4-remuxer]: Dropped "+A+" out of "+E+" video samples due to a missing keyframe");var D=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(A),t.dropped+=A,b=p+=(t.samples[0].pts-D)/t.inputTimeScale}else-1===A&&(g.logger.warn("[mp4-remuxer]: No keyframe found out of "+E+" video samples"),c=!1);if(this.ISGenerated){if(T&&S){var R=this.getVideoStartPts(t.samples),k=(se(e.samples[0].pts,R)-R)/t.inputTimeScale;v+=Math.max(0,k),p+=Math.max(0,-k)}if(T){if(e.samplerate||(g.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(e,t,n)),u=this.remuxAudio(e,v,this.isAudioContiguous,a,y||S||o===ee.PlaylistLevelType.AUDIO?p:void 0),S){var _=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(g.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(e,t,n)),l=this.remuxVideo(t,p,L,_)}}else S&&(l=this.remuxVideo(t,p,L,0));l&&(l.firstKeyFrame=A,l.independent=-1!==A,l.firstKeyFramePTS=b)}}return this.ISGenerated&&(r.samples.length&&(f=oe(r,n,this._initPTS,this._initDTS)),i.samples.length&&(h=le(i,n,this._initPTS))),{audio:u,video:l,initSegment:d,independent:c,text:h,id3:f}},t.generateIS=function(e,t,r){var i,n,a,o=e.samples,l=t.samples,u=this.typeSupported,d={},h=!(0,s.isFiniteNumber)(this._initPTS),f="audio/mp4";if(h&&(i=n=1/0),e.config&&o.length&&(e.timescale=e.samplerate,"mp3"===e.segmentCodec&&(u.mpeg?(f="audio/mpeg",e.codec=""):u.mp3&&(e.codec="mp3")),d.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&u.mpeg?new Uint8Array(0):J.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(a=e.inputTimeScale,i=n=o[0].pts-Math.round(a*r))),t.sps&&t.pps&&l.length&&(t.timescale=t.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:J.initSegment([t]),metadata:{width:t.width,height:t.height}},h)){a=t.inputTimeScale;var c=this.getVideoStartPts(l),v=Math.round(a*r);n=Math.min(n,se(l[0].dts,c)-v),i=Math.min(i,c-v)}if(Object.keys(d).length)return this.ISGenerated=!0,h&&(this._initPTS=i,this._initDTS=n),{tracks:d,initPTS:i,timescale:a}},t.remuxVideo=function(e,t,r,a){var s,o,l=e.inputTimeScale,u=e.samples,d=[],h=u.length,f=this._initPTS,c=this.nextAvcDts,v=8,p=this.videoSampleDuration,m=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,E=!1;r&&null!==c||(c=t*l-(u[0].pts-se(u[0].dts,u[0].pts)));for(var T=0;T0?T-1:T].dts&&(E=!0)}E&&u.sort((function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i})),s=u[0].dts;var b=u[u.length-1].dts-s,L=b?Math.round(b/(h-1)):p||e.inputTimeScale/30;if(r){var A=s-c,D=A>L,R=A<-1;if((D||R)&&(D?g.logger.warn("AVC: "+te(A,!0)+" ms ("+A+"dts) hole between fragments detected, filling it"):g.logger.warn("AVC: "+te(-A,!0)+" ms ("+A+"dts) overlapping between fragments detected"),!R||c>u[0].pts)){s=c;var k=u[0].pts-A;u[0].dts=s,u[0].pts=k,g.logger.log("Video: First PTS/DTS adjusted: "+te(k,!0)+"/"+te(s,!0)+", delta: "+te(A,!0)+" ms")}}s=Math.max(0,s);for(var _=0,x=0,I=0;I0?W.dts-u[K-1].dts:L;if(ee=K>0?W.pts-u[K-1].pts:L,ae.stretchShortVideoTrack&&null!==this.nextAudioPts){var le=Math.floor(ae.maxBufferHole*l),de=(a?m+a*l:this.nextAudioPts)-W.pts;de>le?((p=de-oe)<0?p=oe:B=!0,g.logger.log("[mp4-remuxer]: It is approximately "+de/90+" ms to the next segment; using duration "+p/90+" ms for the last video frame.")):p=oe}else p=oe}var he=Math.round(W.pts-W.dts);G=Math.min(G,p),H=Math.max(H,p),V=Math.min(V,ee),j=Math.max(j,ee),d.push(new ue(W.key,p,q,he))}if(d.length)if(ie){if(ie<70){var fe=d[0].flags;fe.dependsOn=2,fe.isNonSync=0}}else if(ne&&j-V0&&(a&&Math.abs(E-y)<9e3||Math.abs(se(p[0].pts-h,E)-y)<20*d),p.forEach((function(e){e.pts=se(e.pts-h,E)})),!r||y<0){if(p=p.filter((function(e){return e.pts>=0})),!p.length)return;y=0===s?0:a&&!v?Math.max(0,E):p[0].pts}if("aac"===e.segmentCodec)for(var T=this.config.maxAudioFramesDrift,S=0,b=y;S=T*d&&R<1e4&&v){var k=Math.round(D/d);(b=A-k*d)<0&&(k--,b+=d),0===S&&(this.nextAudioPts=y=b),g.logger.warn("[mp4-remuxer]: Injecting "+k+" audio frame @ "+(b/o).toFixed(3)+"s due to "+Math.round(1e3*D/o)+" ms gap.");for(var _=0;_0))return;O+=m;try{w=new Uint8Array(O)}catch(e){return void this.observer.emit(i.Events.ERROR,i.Events.ERROR,{type:n.ErrorTypes.MUX_ERROR,details:n.ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,bytes:O,reason:"fail allocating audio mdat "+O})}f||(new DataView(w.buffer).setUint32(0,O),w.set(J.types.mdat,4))}w.set(B,m);var V=B.byteLength;m+=V,c.push(new ue(!0,u,V,0)),P=G}var H=c.length;if(H){var j=c[c.length-1];this.nextAudioPts=y=P+l*j.duration;var K=f?new Uint8Array(0):J.moof(e.sequenceNumber++,C/l,re({},e,{samples:c}));e.samples=[];var W=C/o,Y=y/o,q={data1:K,data2:w,startPTS:W,endPTS:Y,startDTS:W,endDTS:Y,type:"audio",hasAudio:!0,hasVideo:!1,nb:H};return this.isAudioContiguous=!0,q}},t.remuxEmptyAudio=function(e,t,r,i){var n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),s=this.nextAudioPts,o=(null!==s?s:i.startDTS*n)+this._initDTS,l=i.endDTS*n+this._initDTS,u=1024*a,d=Math.ceil((l-o)/u),h=Q.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(g.logger.warn("[mp4-remuxer]: remux empty Audio"),h){for(var f=[],c=0;c4294967296;)e+=r;return e}function oe(e,t,r,i){var n=e.samples.length;if(n){for(var a=e.inputTimeScale,s=0;s4?r:"hvc1"===r||"hev1"===r?"hvc1.1.c.L120.90":"av01"===r?"av01.0.04M.08":"avc1"===r||t===he.ElementaryStreamTypes.VIDEO?"avc1.42e01e":"mp4a.40.5"}const ce=function(){function e(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=void 0,this.initTracks=void 0,this.lastEndTime=null}var t=e.prototype;return t.destroy=function(){},t.resetTimeStamp=function(e){this.initPTS=e,this.lastEndTime=null},t.resetNextTimestamp=function(){this.lastEndTime=null},t.resetInitSegment=function(e,t,r){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(e),this.emitInitSegment=!0},t.generateInitSegment=function(e){var t=this.audioCodec,r=this.videoCodec;if(!e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var i=this.initData=(0,d.parseInitSegment)(e);t||(t=fe(i.audio,he.ElementaryStreamTypes.AUDIO)),r||(r=fe(i.video,he.ElementaryStreamTypes.VIDEO));var n={};i.audio&&i.video?n.audiovideo={container:"video/mp4",codec:t+","+r,initSegment:e,id:"main"}:i.audio?n.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:i.video?n.video={container:"video/mp4",codec:r,initSegment:e,id:"main"}:g.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n},t.remux=function(e,t,r,i,n){var a,o=this.initPTS,l=this.lastEndTime,u={audio:void 0,video:void 0,text:i,id3:r,initSegment:void 0};(0,s.isFiniteNumber)(l)||(l=this.lastEndTime=n||0);var h=t.samples;if(!h||!h.length)return u;var f={initPTS:void 0,timescale:1},c=this.initData;if(c&&c.length||(this.generateInitSegment(h),c=this.initData),!c||!c.length)return g.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);var v=(0,d.getStartDTS)(c,h);(0,s.isFiniteNumber)(o)||(this.initPTS=f.initPTS=o=v-n);var p=(0,d.getDuration)(h,c),m=e?v-o:l,y=m+p;(0,d.offsetStartDTS)(c,h,o),p>0?this.lastEndTime=y:(g.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var E=!!c.audio,T=!!c.video,S="";E&&(S+="audio"),T&&(S+="video");var b={data1:h,startPTS:m,startDTS:m,endPTS:y,endDTS:y,type:S,hasAudio:E,hasVideo:T,nb:1,dropped:0};u.audio="audio"===b.type?b:void 0,u.video="audio"!==b.type?b:void 0,u.initSegment=f;var L=null!=(a=this.initPTS)?a:0;return u.id3=oe(r,n,L,L),i.samples.length&&(u.text=le(i,n,L)),u},e}();var ve;try{ve=self.performance.now.bind(self.performance)}catch(e){g.logger.debug("Unable to use Performance API on this environment"),ve=self.Date.now}var ge=[{demux:q,remux:ae},{demux:k,remux:ce},{demux:D,remux:ae},{demux:X,remux:ae}],pe=function(){function e(e,t,r,i,n){this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=r,this.vendor=i,this.id=n}var t=e.prototype;return t.configure=function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()},t.push=function(e,t,r,i){var n=this,a=r.transmuxing;a.executeStart=ve();var s=new Uint8Array(e),o=this.config,l=this.currentTransmuxState,u=this.transmuxConfig;i&&(this.currentTransmuxState=i);var d=i||l,h=d.contiguous,f=d.discontinuity,c=d.trackSwitch,v=d.accurateTimeOffset,g=d.timeOffset,p=d.initSegmentChange,m=u.audioCodec,y=u.videoCodec,E=u.defaultInitPts,T=u.duration,S=u.initSegmentData;(f||c||p)&&this.resetInitSegment(S,m,y,T),(f||p)&&this.resetInitialTimestamp(E),h||this.resetContiguity();var b=function(e,t){var r=null;return e.byteLength>0&&null!=t&&null!=t.key&&null!==t.iv&&null!=t.method&&(r=t),r}(s,t);if(b&&"AES-128"===b.method){var L=this.getDecrypter();if(!o.enableSoftwareAES)return this.decryptionPromise=L.webCryptoDecrypt(s,b.key.buffer,b.iv.buffer).then((function(e){var t=n.push(e,null,r);return n.decryptionPromise=null,t})),this.decryptionPromise;var A=L.softwareDecrypt(s,b.key.buffer,b.iv.buffer);if(!A)return a.executeEnd=ve(),me(r);s=new Uint8Array(A)}this.needsProbing(s,f,c)&&this.configureTransmuxer(s,u);var D=this.transmux(s,b,g,v,r),R=this.currentTransmuxState;return R.contiguous=!0,R.discontinuity=!1,R.trackSwitch=!1,a.executeEnd=ve(),D},t.flush=function(e){var t=this,r=e.transmuxing;r.executeStart=ve();var a=this.decrypter,s=this.currentTransmuxState,o=this.decryptionPromise;if(o)return o.then((function(){return t.flush(e)}));var l=[],u=s.timeOffset;if(a){var d=a.flush();d&&l.push(this.push(d,null,e))}var h=this.demuxer,f=this.remuxer;if(!h||!f)return this.observer.emit(i.Events.ERROR,i.Events.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"}),r.executeEnd=ve(),[me(e)];var c=h.flush(u);return ye(c)?c.then((function(r){return t.flushRemux(l,r,e),l})):(this.flushRemux(l,c,e),l)},t.flushRemux=function(e,t,r){var i=t.audioTrack,n=t.videoTrack,a=t.id3Track,s=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;g.logger.log("[transmuxer.ts]: Flushed fragment "+r.sn+(r.part>-1?" p: "+r.part:"")+" of level "+r.level);var d=this.remuxer.remux(i,n,a,s,u,l,!0,this.id);e.push({remuxResult:d,chunkMeta:r}),r.transmuxing.executeEnd=ve()},t.resetInitialTimestamp=function(e){var t=this.demuxer,r=this.remuxer;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))},t.resetContiguity=function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())},t.resetInitSegment=function(e,t,r,i){var n=this.demuxer,a=this.remuxer;n&&a&&(n.resetInitSegment(e,t,r,i),a.resetInitSegment(e,t,r))},t.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},t.transmux=function(e,t,r,i,n){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,r,i,n):this.transmuxUnencrypted(e,r,i,n)},t.transmuxUnencrypted=function(e,t,r,i){var n=this.demuxer.demux(e,t,!1,!this.config.progressive),a=n.audioTrack,s=n.videoTrack,o=n.id3Track,l=n.textTrack;return{remuxResult:this.remuxer.remux(a,s,o,l,t,r,!1,this.id),chunkMeta:i}},t.transmuxSampleAes=function(e,t,r,i,n){var a=this;return this.demuxer.demuxSampleAes(e,t,r).then((function(e){return{remuxResult:a.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,i,!1,a.id),chunkMeta:n}}))},t.configureTransmuxer=function(e,t){for(var r,i=this.config,n=this.observer,a=this.typeSupported,s=this.vendor,o=t.audioCodec,l=t.defaultInitPts,u=t.duration,d=t.initSegmentData,h=t.videoCodec,f=0,c=ge.length;f{e.exports=void 0},973:(e,t,r)=>{"use strict";var i,n;r.r(t),r.d(t,{ErrorDetails:()=>n,ErrorTypes:()=>i}),function(e){e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError"}(i||(i={})),function(e){e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_NO_INIT_DATA="keySystemNoInitData",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.UNKNOWN="unknown"}(n||(n={}))},851:(e,t,r)=>{"use strict";var i;r.r(t),r.d(t,{Events:()=>i}),function(e){e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached"}(i||(i={}))},392:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>Ht});var i,n=r(945),a=r(965),s=r(851),o=r(973),l=r(93),u=r(63),d=/^(\d+)x(\d+)$/,h=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,f=function(){function e(t){for(var r in"string"==typeof t&&(t=e.parseAttrList(t)),t)t.hasOwnProperty(r)&&(this[r]=t[r])}var t=e.prototype;return t.decimalInteger=function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.hexadecimalInteger=function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),i=0;iNumber.MAX_SAFE_INTEGER?1/0:t},t.decimalFloatingPoint=function(e){return parseFloat(this[e])},t.optionalFloat=function(e,t){var r=this[e];return r?parseFloat(r):t},t.enumeratedString=function(e){return this[e]},t.bool=function(e){return"YES"===this[e]},t.decimalResolution=function(e){var t=d.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e){var t,r={};for(h.lastIndex=0;null!==(t=h.exec(e));){var i=t[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[t[1]]=i}return r},e}();function c(){return c=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&(!this.endOnNext||!!this.class)}}])&&v(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}(),p=r(923);function m(e,t){for(var r=0;re.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay},t=e,(r=[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&(0,a.isFiniteNumber)(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var e;return null!==(e=this.partList)&&void 0!==e&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){var e;return null!==(e=this.fragments)&&void 0!==e&&e.length?this.fragments[this.fragments.length-1].end:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var e;return null!==(e=this.partList)&&void 0!==e&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"lastPartSn",get:function(){var e;return null!==(e=this.partList)&&void 0!==e&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}])&&m(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}(),E=r(960),T={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dva1:!0,dvav:!0,dvh1:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}};function S(e,t){return MediaSource.isTypeSupported((t||"video")+'/mp4;codecs="'+e+'"')}var b=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-SESSION-DATA:([^\r\n]*)[\r\n]+/g,L=/#EXT-X-MEDIA:(.*)/g,A=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),D=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),R=/\.(mp4|m4s|m4v|m4a)$/i,k=function(){function e(){}return e.findGroup=function(e,t){for(var r=0;r2){var r=t.shift()+".";return(r+=parseInt(t.shift()).toString(16))+("000"+parseInt(t.shift()).toString(16)).slice(-4)}return e},e.resolve=function(e,t){return n.buildAbsoluteURL(t,e,{alwaysNormalize:!0})},e.parseMasterPlaylist=function(t,r){var i,n=[],a=[],s={},o=!1;for(b.lastIndex=0;null!=(i=b.exec(t));)if(i[1]){var l,u=new f(i[1]),d={attrs:u,bitrate:u.decimalInteger("AVERAGE-BANDWIDTH")||u.decimalInteger("BANDWIDTH"),name:u.NAME,url:e.resolve(i[2],r)},h=u.decimalResolution("RESOLUTION");h&&(d.width=h.width,d.height=h.height),_((u.CODECS||"").split(/[ ,]+/).filter((function(e){return e})),d),d.videoCodec&&-1!==d.videoCodec.indexOf("avc1")&&(d.videoCodec=e.convertAVC1ToAVCOTI(d.videoCodec)),null!==(l=d.unknownCodecs)&&void 0!==l&&l.length||a.push(d),n.push(d)}else if(i[3]){var c=new f(i[3]);c["DATA-ID"]&&(o=!0,s[c["DATA-ID"]]=c)}return{levels:a.length>0&&a.length-1){l.logger.warn("Keyformat "+$+" is not supported from the manifest");continue}if("identity"!==$)continue;Y&&(d=E.LevelKey.fromURL(t,q),q&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(Y)>=0&&(d.method=Y,d.keyFormat=$,Q&&(d.keyID=Q),X&&(d.keyFormatVersions=X),d.iv=z));break;case"START":var Z=new f(M).decimalFloatingPoint("TIME-OFFSET");(0,a.isFiniteNumber)(Z)&&(h.startTimeOffset=Z);break;case"MAP":var J=new f(M);if(k.duration){var ee=new p.Fragment(i,t);w(ee,J,r,d),v=ee,k.initSegment=v,v.rawProgramDateTime&&!k.rawProgramDateTime&&(k.rawProgramDateTime=v.rawProgramDateTime)}else w(k,J,r,d),v=k,x=!0;break;case"SERVER-CONTROL":var te=new f(M);h.canBlockReload=te.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=te.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&te.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=te.optionalFloat("PART-HOLD-BACK",0),h.holdBack=te.optionalFloat("HOLD-BACK",0);break;case"PART-INF":var re=new f(M);h.partTarget=re.decimalFloatingPoint("PART-TARGET");break;case"PART":var ie=h.partList;ie||(ie=h.partList=[]);var ne=T>0?ie[ie.length-1]:void 0,ae=T++,se=new p.Part(new f(M),k,t,ae,ne);ie.push(se),k.duration+=se.duration;break;case"PRELOAD-HINT":var oe=new f(M);h.preloadHint=oe;break;case"RENDITION-REPORT":var le=new f(M);h.renditionReports=h.renditionReports||[],h.renditionReports.push(le);break;default:l.logger.warn("line parsed but not handled: "+o)}}}L&&!L.relurl?(c.pop(),S-=L.duration,h.partList&&(h.fragmentHint=L)):h.partList&&(I(k,L),k.cc=b,h.fragmentHint=k);var ue=c.length,de=c[0],he=c[ue-1];if((S+=h.skippedSegments*h.targetduration)>0&&ue&&he){h.averagetargetduration=S/ue;var fe=he.sn;h.endSN="initSegment"!==fe?fe:0,de&&(h.startCC=de.cc,de.initSegment||h.fragments.every((function(e){return e.relurl&&(t=e.relurl,R.test(null!=(r=null===(i=n.parseURL(t))||void 0===i?void 0:i.path)?r:""));var t,r,i}))&&(l.logger.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),(k=new p.Fragment(i,t)).relurl=he.relurl,k.level=r,k.sn="initSegment",de.initSegment=k,h.needSidxRanges=!0))}else h.endSN=0,h.startCC=0;return h.fragmentHint&&(S+=h.fragmentHint.duration),h.totalduration=S,h.endCC=b,_>0&&function(e,t){for(var r=e[t],i=t;i--;){var n=e[i];if(!n)return;n.programDateTime=r.programDateTime-1e3*n.duration,r=n}}(c,_),h},e}();function _(e,t){["video","audio","text"].forEach((function(r){var i=e.filter((function(e){return function(e,t){var r=T[t];return!!r&&!0===r[e.slice(0,4)]}(e,r)}));if(i.length){var n=i.filter((function(e){return 0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)}));t[r+"Codec"]=n.length>0?n[0]:i[0],e=e.filter((function(e){return-1===i.indexOf(e)}))}})),t.unknownCodecs=e}function x(e,t,r){var i=t[r];i&&(e[r]=i)}function I(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),(0,a.isFiniteNumber)(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function w(e,t,r,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",i&&(e.levelkey=i),e.initSegment=null}var C=r(308);function P(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}const O=function(){function e(e){this.hls=void 0,this.loaders=Object.create(null),this.hls=e,this.registerListeners()}var t=e.prototype;return t.startLoad=function(e){},t.stopLoad=function(){this.destroyInternalLoaders()},t.registerListeners=function(){var e=this.hls;e.on(s.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(s.Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(s.Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(s.Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},t.unregisterListeners=function(){var e=this.hls;e.off(s.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(s.Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(s.Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(s.Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},t.createInternalLoader=function(e){var t=this.hls.config,r=t.pLoader,i=t.loader,n=new(r||i)(t);return e.loader=n,this.loaders[e.type]=n,n},t.getInternalLoader=function(e){return this.loaders[e.type]},t.resetInternalLoader=function(e){this.loaders[e]&&delete this.loaders[e]},t.destroyInternalLoaders=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}},t.destroy=function(){this.unregisterListeners(),this.destroyInternalLoaders()},t.onManifestLoading=function(e,t){var r=t.url;this.load({id:null,groupId:null,level:0,responseType:"text",type:C.PlaylistContextType.MANIFEST,url:r,deliveryDirectives:null})},t.onLevelLoading=function(e,t){var r=t.id,i=t.level,n=t.url,a=t.deliveryDirectives;this.load({id:r,groupId:null,level:i,responseType:"text",type:C.PlaylistContextType.LEVEL,url:n,deliveryDirectives:a})},t.onAudioTrackLoading=function(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:C.PlaylistContextType.AUDIO_TRACK,url:n,deliveryDirectives:a})},t.onSubtitleTrackLoading=function(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:C.PlaylistContextType.SUBTITLE_TRACK,url:n,deliveryDirectives:a})},t.load=function(e){var t,r,i,n,a,s,o=this.hls.config,u=this.getInternalLoader(e);if(u){var d=u.context;if(d&&d.url===e.url)return void l.logger.trace("[playlist-loader]: playlist request ongoing");l.logger.log("[playlist-loader]: aborting previous loader for type: "+e.type),u.abort()}switch(e.type){case C.PlaylistContextType.MANIFEST:r=o.manifestLoadingMaxRetry,i=o.manifestLoadingTimeOut,n=o.manifestLoadingRetryDelay,a=o.manifestLoadingMaxRetryTimeout;break;case C.PlaylistContextType.LEVEL:case C.PlaylistContextType.AUDIO_TRACK:case C.PlaylistContextType.SUBTITLE_TRACK:r=0,i=o.levelLoadingTimeOut;break;default:r=o.levelLoadingMaxRetry,i=o.levelLoadingTimeOut,n=o.levelLoadingRetryDelay,a=o.levelLoadingMaxRetryTimeout}if(u=this.createInternalLoader(e),null!==(t=e.deliveryDirectives)&&void 0!==t&&t.part&&(e.type===C.PlaylistContextType.LEVEL&&null!==e.level?s=this.hls.levels[e.level].details:e.type===C.PlaylistContextType.AUDIO_TRACK&&null!==e.id?s=this.hls.audioTracks[e.id].details:e.type===C.PlaylistContextType.SUBTITLE_TRACK&&null!==e.id&&(s=this.hls.subtitleTracks[e.id].details),s)){var h=s.partTarget,f=s.targetduration;h&&f&&(i=Math.min(1e3*Math.max(3*h,.8*f),i))}var c={timeout:i,maxRetry:r,retryDelay:n,maxRetryDelay:a,highWaterMark:0},v={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};u.load(e,c,v)},t.loadsuccess=function(e,t,r,i){if(void 0===i&&(i=null),r.isSidxRequest)return this.handleSidxRequest(e,r),void this.handlePlaylistLoaded(e,t,r,i);this.resetInternalLoader(r.type);var n=e.data;0===n.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),n.indexOf("#EXTINF:")>0||n.indexOf("#EXT-X-TARGETDURATION:")>0?this.handleTrackOrLevelPlaylist(e,t,r,i):this.handleMasterPlaylist(e,t,r,i)):this.handleManifestParsingError(e,r,"no EXTM3U delimiter",i)},t.loaderror=function(e,t,r){void 0===r&&(r=null),this.handleNetworkError(t,r,!1,e)},t.loadtimeout=function(e,t,r){void 0===r&&(r=null),this.handleNetworkError(t,r,!0)},t.handleMasterPlaylist=function(e,t,r,i){var n=this.hls,a=e.data,o=P(e,r),u=k.parseMasterPlaylist(a,o),d=u.levels,h=u.sessionData;if(d.length){var c=d.map((function(e){return{id:e.attrs.AUDIO,audioCodec:e.audioCodec}})),v=d.map((function(e){return{id:e.attrs.SUBTITLES,textCodec:e.textCodec}})),g=k.parseMasterPlaylistMedia(a,o,"AUDIO",c),p=k.parseMasterPlaylistMedia(a,o,"SUBTITLES",v),m=k.parseMasterPlaylistMedia(a,o,"CLOSED-CAPTIONS");g.length&&(g.some((function(e){return!e.url}))||!d[0].audioCodec||d[0].attrs.AUDIO||(l.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new f({}),bitrate:0,url:""}))),n.trigger(s.Events.MANIFEST_LOADED,{levels:d,audioTracks:g,subtitles:p,captions:m,url:o,stats:t,networkDetails:i,sessionData:h})}else this.handleManifestParsingError(e,r,"no level found in manifest",i)},t.handleTrackOrLevelPlaylist=function(e,t,r,i){var n=this.hls,l=r.id,u=r.level,d=r.type,h=P(e,r),c=(0,a.isFiniteNumber)(l)?l:0,v=(0,a.isFiniteNumber)(u)?u:c,g=function(e){switch(e.type){case C.PlaylistContextType.AUDIO_TRACK:return C.PlaylistLevelType.AUDIO;case C.PlaylistContextType.SUBTITLE_TRACK:return C.PlaylistLevelType.SUBTITLE;default:return C.PlaylistLevelType.MAIN}}(r),p=k.parseLevelPlaylist(e.data,h,v,g,c);if(p.fragments.length){if(d===C.PlaylistContextType.MANIFEST){var m={attrs:new f({}),bitrate:0,details:p,name:"",url:h};n.trigger(s.Events.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null})}if(t.parsing.end=performance.now(),p.needSidxRanges){var y,E=null===(y=p.fragments[0].initSegment)||void 0===y?void 0:y.url;this.load({url:E,isSidxRequest:!0,type:d,level:u,levelDetails:p,id:l,groupId:null,rangeStart:0,rangeEnd:2048,responseType:"arraybuffer",deliveryDirectives:null})}else r.levelDetails=p,this.handlePlaylistLoaded(e,t,r,i)}else n.trigger(s.Events.ERROR,{type:o.ErrorTypes.NETWORK_ERROR,details:o.ErrorDetails.LEVEL_EMPTY_ERROR,fatal:!1,url:h,reason:"no fragments found in level",level:"number"==typeof r.level?r.level:void 0})},t.handleSidxRequest=function(e,t){var r=new Uint8Array(e.data),i=(0,u.findBox)(r,["sidx"])[0];if(i){var n=(0,u.parseSegmentIndex)(i);if(n){var a=n.references,s=t.levelDetails;a.forEach((function(e,t){var i=e.info,n=s.fragments[t];if(0===n.byteRange.length&&n.setByteRange(String(1+i.end-i.start)+"@"+String(i.start)),n.initSegment){var a=(0,u.findBox)(r,["moov"])[0],o=a?a.length:null;n.initSegment.setByteRange(String(o)+"@0")}}))}}},t.handleManifestParsingError=function(e,t,r,i){this.hls.trigger(s.Events.ERROR,{type:o.ErrorTypes.NETWORK_ERROR,details:o.ErrorDetails.MANIFEST_PARSING_ERROR,fatal:t.type===C.PlaylistContextType.MANIFEST,url:e.url,reason:r,response:e,context:t,networkDetails:i})},t.handleNetworkError=function(e,t,r,i){void 0===r&&(r=!1),l.logger.warn("[playlist-loader]: A network "+(r?"timeout":"error")+" occurred while loading "+e.type+" level: "+e.level+" id: "+e.id+' group-id: "'+e.groupId+'"');var n=o.ErrorDetails.UNKNOWN,a=!1,u=this.getInternalLoader(e);switch(e.type){case C.PlaylistContextType.MANIFEST:n=r?o.ErrorDetails.MANIFEST_LOAD_TIMEOUT:o.ErrorDetails.MANIFEST_LOAD_ERROR,a=!0;break;case C.PlaylistContextType.LEVEL:n=r?o.ErrorDetails.LEVEL_LOAD_TIMEOUT:o.ErrorDetails.LEVEL_LOAD_ERROR,a=!1;break;case C.PlaylistContextType.AUDIO_TRACK:n=r?o.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:o.ErrorDetails.AUDIO_TRACK_LOAD_ERROR,a=!1;break;case C.PlaylistContextType.SUBTITLE_TRACK:n=r?o.ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:o.ErrorDetails.SUBTITLE_LOAD_ERROR,a=!1}u&&this.resetInternalLoader(e.type);var d={type:o.ErrorTypes.NETWORK_ERROR,details:n,fatal:a,url:e.url,loader:u,context:e,networkDetails:t};i&&(d.response=i),this.hls.trigger(s.Events.ERROR,d)},t.handlePlaylistLoaded=function(e,t,r,i){var n=r.type,a=r.level,o=r.id,l=r.groupId,u=r.loader,d=r.levelDetails,h=r.deliveryDirectives;if(null!=d&&d.targetduration){if(u)switch(d.live&&(u.getCacheAge&&(d.ageHeader=u.getCacheAge()||0),u.getCacheAge&&!isNaN(d.ageHeader)||(d.ageHeader=0)),n){case C.PlaylistContextType.MANIFEST:case C.PlaylistContextType.LEVEL:this.hls.trigger(s.Events.LEVEL_LOADED,{details:d,level:a||0,id:o||0,stats:t,networkDetails:i,deliveryDirectives:h});break;case C.PlaylistContextType.AUDIO_TRACK:this.hls.trigger(s.Events.AUDIO_TRACK_LOADED,{details:d,id:o||0,groupId:l||"",stats:t,networkDetails:i,deliveryDirectives:h});break;case C.PlaylistContextType.SUBTITLE_TRACK:this.hls.trigger(s.Events.SUBTITLE_TRACK_LOADED,{details:d,id:o||0,groupId:l||"",stats:t,networkDetails:i,deliveryDirectives:h})}}else this.handleManifestParsingError(e,r,"invalid target duration",i)},e}();var F=function(){function e(e){this.hls=void 0,this.loaders={},this.decryptkey=null,this.decrypturl=null,this.hls=e,this.registerListeners()}var t=e.prototype;return t.startLoad=function(e){},t.stopLoad=function(){this.destroyInternalLoaders()},t.registerListeners=function(){this.hls.on(s.Events.KEY_LOADING,this.onKeyLoading,this)},t.unregisterListeners=function(){this.hls.off(s.Events.KEY_LOADING,this.onKeyLoading)},t.destroyInternalLoaders=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy()}this.loaders={}},t.destroy=function(){this.unregisterListeners(),this.destroyInternalLoaders()},t.onKeyLoading=function(e,t){var r=t.frag,i=r.type,n=this.loaders[i];if(r.decryptdata){var a=r.decryptdata.uri;if(a!==this.decrypturl||null===this.decryptkey){var o=this.hls.config;if(n&&(l.logger.warn("abort previous key loader for type:"+i),n.abort()),!a)return void l.logger.warn("key uri is falsy");var u=o.loader,d=r.loader=this.loaders[i]=new u(o);this.decrypturl=a,this.decryptkey=null;var h={url:a,frag:r,responseType:"arraybuffer"},f={timeout:o.fragLoadingTimeOut,maxRetry:0,retryDelay:o.fragLoadingRetryDelay,maxRetryDelay:o.fragLoadingMaxRetryTimeout,highWaterMark:0},c={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};d.load(h,f,c)}else this.decryptkey&&(r.decryptdata.key=this.decryptkey,this.hls.trigger(s.Events.KEY_LOADED,{frag:r}))}else l.logger.warn("Missing decryption data on fragment in onKeyLoading")},t.loadsuccess=function(e,t,r){var i=r.frag;i.decryptdata?(this.decryptkey=i.decryptdata.key=new Uint8Array(e.data),i.loader=null,delete this.loaders[i.type],this.hls.trigger(s.Events.KEY_LOADED,{frag:i})):l.logger.error("after key load, decryptdata unset")},t.loaderror=function(e,t){var r=t.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(s.Events.ERROR,{type:o.ErrorTypes.NETWORK_ERROR,details:o.ErrorDetails.KEY_LOAD_ERROR,fatal:!1,frag:r,response:e})},t.loadtimeout=function(e,t){var r=t.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(s.Events.ERROR,{type:o.ErrorTypes.NETWORK_ERROR,details:o.ErrorDetails.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},e}();function M(e,t){var r;try{r=new Event("addtrack")}catch(e){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}var N=r(181),U=r(856);function B(){return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}var G=function(){var e=B();try{new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}();function V(e,t){return e.getTime()/1e3-t}const H=function(){function e(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}var t=e.prototype;return t.destroy=function(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null},t._registerListeners=function(){var e=this.hls;e.on(s.Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(s.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(s.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(s.Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(s.Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(s.Events.LEVEL_UPDATED,this.onLevelUpdated,this)},t._unregisterListeners=function(){var e=this.hls;e.off(s.Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(s.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(s.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(s.Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(s.Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(s.Events.LEVEL_UPDATED,this.onLevelUpdated,this)},t.onMediaAttached=function(e,t){this.media=t.media},t.onMediaDetaching=function(){this.id3Track&&(function(e){var t=e.mode;if("disabled"===t&&(e.mode="hidden"),e.cues)for(var r=e.cues.length;r--;)e.removeCue(e.cues[r]);"disabled"===t&&(e.mode=t)}(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})},t.onManifestLoading=function(){this.dateRangeCuesAppended={}},t.createTrack=function(e){var t=this.getID3Track(e.textTracks);return t.mode="hidden",t},t.getID3Track=function(e){if(this.media){for(var t=0;tG&&(h=G),h-d<=0&&(h=d+.25);for(var f=0;f0)for(var a=function(e,t,r){var i=[],n=function(e,t){if(te[r].endTime)return-1;for(var i=0,n=r;i<=n;){var a=Math.floor((n+i)/2);if(te[a].startTime&&i-1)for(var a=n,s=e.length;a=t&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(e.cues,t,r),s=0;sn.startDate&&e.push(r),e}),[]).sort((function(e,t){return e.startDate.getTime()-t.startDate.getTime()}))[0];p&&(f=V(p.startDate,v),d=!0)}for(var m,y=Object.keys(n.attr),E=0;E.05&&this.forwardBufferLength>1){var u=Math.min(2,Math.max(1,a)),d=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(u,Math.max(1,d))}else 1!==e.playbackRate&&0!==e.playbackRate&&(e.playbackRate=1)}}}}},i.estimateLiveEdge=function(){var e=this.levelDetails;return null===e?null:e.edge+e.age},i.computeLatency=function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime},t=e,(r=[{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e=this.config,t=this.levelDetails;return void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e)return null;var t=e.holdBack,r=e.partHoldBack,i=e.targetduration,n=this.config,a=n.liveSyncDuration,s=n.liveSyncDurationCount,o=n.lowLatencyMode,l=this.hls.userConfig,u=o&&r||t;(l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==a?a:s*i);var d=i;return u+Math.min(1*this.stallCount,d)}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency,r=this.levelDetails;if(null===e||null===t||null===r)return null;var i=r.edge,n=e-t-this.edgeStalled,a=i-r.totalduration,s=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,n),s)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e)return 0;var t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}}])&&j(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();function Y(e,t){for(var r=0;re.sn?(n=r-e.start,i=e):(n=e.start-r,i=t),i.duration!==n&&(i.duration=n)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.start=e.start+(e.minEndPTS-e.start):t.start=e.start+e.duration:t.start=Math.max(e.start-t.duration,0)}function J(e,t,r,i,n,s){i-r<=0&&(l.logger.warn("Fragment should have a positive duration",t),i=r+t.duration,s=n+t.duration);var o=r,u=i,d=t.startPTS,h=t.endPTS;if((0,a.isFiniteNumber)(d)){var f=Math.abs(d-r);(0,a.isFiniteNumber)(t.deltaPTS)?t.deltaPTS=Math.max(f,t.deltaPTS):t.deltaPTS=f,o=Math.max(r,d),r=Math.min(r,d),n=Math.min(n,t.startDTS),u=Math.min(i,h),i=Math.max(i,h),s=Math.max(s,t.endDTS)}t.duration=i-r;var c=r-t.start;t.appendedPTS=i,t.start=t.startPTS=r,t.maxStartPTS=o,t.startDTS=n,t.endPTS=i,t.minEndPTS=u,t.endDTS=s;var v,g=t.sn;if(!e||ge.endSN)return 0;var p=g-e.startSN,m=e.fragments;for(m[p]=t,v=p;v>0;v--)Z(m[v],m[v-1]);for(v=p;v=i.length||function(e,t){if(t){for(var r=e.fragments,i=e.skippedSegments;it.partTarget&&(l+=1)}if((0,a.isFiniteNumber)(o))return new q(o,(0,a.isFiniteNumber)(l)?l:void 0,K.No)}}},t.loadPlaylist=function(e){},t.shouldLoadTrack=function(e){return this.canLoad&&e&&!!e.url&&(!e.details||e.details.live)},t.playlistLoaded=function(e,t,r){var i=this,n=t.details,s=t.stats,o=s.loading.end?Math.max(0,self.performance.now()-s.loading.end):0;if(n.advancedDateTime=Date.now()-o,n.live||null!=r&&r.live){if(n.reloaded(r),r&&this.log("live playlist "+e+" "+(n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:"MISSED")),r&&n.fragments.length>0&&function(e,t){for(var r=null,i=e.fragments,n=i.length-1;n>=0;n--){var s=i[n].initSegment;if(s){r=s;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;var o,u,d,h,f,c=0;if(function(e,t,r){for(var i=t.skippedSegments,n=Math.max(e.startSN,t.startSN)-t.startSN,a=(e.fragmentHint?1:0)+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,s=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,u=n;u<=a;u++){var d=l[s+u],h=o[u];i&&!h&&u0){if(r&&T>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+T+" with playlist age: "+n.age),T=0;else{var S=Math.floor(T/n.targetduration);d+=S,void 0!==h&&(h+=Math.round(T%n.targetduration/n.partTarget)),this.log("CDN Tune-in age: "+n.ageHeader+"s last advanced "+y.toFixed(2)+"s goal: "+T+" skip sn "+S+" to part "+h)}n.tuneInGoal=T}if(u=this.getDeliveryDirectives(n,t.deliveryDirectives,d,h),f||!m)return void this.loadPlaylist(u)}else u=this.getDeliveryDirectives(n,t.deliveryDirectives,d,h);var b=function(e,t){var r,i=1e3*e.levelTargetDuration,n=i/2,a=e.age,s=a>0&&a<3*i,o=t.loading.end-t.loading.start,l=e.availabilityDelay;if(!1===e.updated)if(s){var u=333*e.misses;r=Math.max(Math.min(n,2*o),u),e.availabilityDelay=(e.availabilityDelay||0)+r}else r=n;else s?(l=Math.min(l||i/2,a),e.availabilityDelay=l,r=l+i-a):r=i-o;return Math.round(r)}(n,s);void 0!==d&&n.canBlockReload&&(b-=n.partTarget||1),this.log("reload live playlist "+e+" in "+Math.round(b)+" ms"),this.timer=self.setTimeout((function(){return i.loadPlaylist(u)}),b)}else this.clearTimer()},t.getDeliveryDirectives=function(e,t,r,i){var n=function(e,t){var r=e.canSkipUntil,i=e.canSkipDateRanges,n=e.endSN;return r&&(void 0!==t?t-n:0)-1&&null!==(t=e.context)&&void 0!==t&&t.deliveryDirectives)this.warn("retry playlist loading #"+this.retryCount+' after "'+e.details+'"'),this.loadPlaylist();else{var a=Math.min(Math.pow(2,this.retryCount)*i.levelLoadingRetryDelay,i.levelLoadingMaxRetryTimeout);this.timer=self.setTimeout((function(){return r.loadPlaylist()}),a),this.warn("retry playlist loading #"+this.retryCount+" in "+a+' ms after "'+e.details+'"')}else this.warn('cannot recover from error "'+e.details+'"'),this.clearTimer(),e.fatal=!0;return n},e}();function re(){return re=Object.assign?Object.assign.bind():function(e){for(var t=1;t0){r=n[0].bitrate,n.sort((function(e,t){return e.bitrate-t.bitrate})),this._levels=n;for(var c=0;cthis.hls.config.fragLoadingMaxRetry&&(s=d)):s=d}break;case o.ErrorDetails.LEVEL_LOAD_ERROR:case o.ErrorDetails.LEVEL_LOAD_TIMEOUT:n&&(n.deliveryDirectives&&(u=!1),s=n.level),l=!0;break;case o.ErrorDetails.REMUX_ALLOC_ERROR:s=null!=(i=r.level)?i:this.currentLevelIndex,l=!0}void 0!==s&&this.recoverLevel(r,s,l,u)}}},l.recoverLevel=function(e,t,r,i){var n=e.details,a=this._levels[t];if(a.loadError++,r){if(!this.retryLoadingOrFail(e))return void(this.currentLevelIndex=-1);e.levelRetry=!0}if(i){var s=a.url.length;if(s>1&&a.loadError-1&&this.currentLevelIndex!==o&&(this.warn(n+": switch to "+o),e.levelRetry=!0,this.hls.nextAutoLevel=o)}}},l.redundantFailover=function(e){var t=this._levels[e],r=t.url.length;if(r>1){var i=(t.urlId+1)%r;this.warn("Switching to redundant URL-id "+i),this._levels.forEach((function(e){e.urlId=i})),this.level=e}},l.onFragLoaded=function(e,t){var r=t.frag;if(void 0!==r&&r.type===C.PlaylistLevelType.MAIN){var i=this._levels[r.level];void 0!==i&&(i.fragmentError=0,i.loadError=0)}},l.onLevelLoaded=function(e,t){var r,i,n=t.level,a=t.details,s=this._levels[n];if(!s)return this.warn("Invalid level index "+n),void(null!==(i=t.deliveryDirectives)&&void 0!==i&&i.skip&&(a.deltaUpdateFailed=!0));n===this.currentLevelIndex?(0===s.fragmentError&&(s.loadError=0,this.retryCount=0),this.playlistLoaded(n,t,s.details)):null!==(r=t.deliveryDirectives)&&void 0!==r&&r.skip&&(a.deltaUpdateFailed=!0)},l.onAudioTrackSwitched=function(e,t){var r=this.hls.levels[this.currentLevelIndex];if(r&&r.audioGroupIds){for(var i=-1,n=this.hls.audioTracks[t.id].groupId,a=0;a0){var i=r.urlId,n=r.url[i];if(e)try{n=e.addDirectives(n)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: "+e)}this.log("Attempt loading level index "+t+(e?" at sn "+e.msn+" part "+e.part:"")+" with URL-id "+i+" "+n),this.clearTimer(),this.hls.trigger(s.Events.LEVEL_LOADING,{url:n,level:t,id:i,deliveryDirectives:e||null})}},l.removeLevel=function(e,t){var r=function(e,r){return r!==t},i=this._levels.filter((function(i,n){return n!==e||i.url.length>1&&void 0!==t&&(i.url=i.url.filter(r),i.audioGroupIds&&(i.audioGroupIds=i.audioGroupIds.filter(r)),i.textGroupIds&&(i.textGroupIds=i.textGroupIds.filter(r)),i.urlId=0,!0)})).map((function(e,t){var r=e.details;return null!=r&&r.fragments&&r.fragments.forEach((function(e){e.level=t})),e}));this._levels=i,this.hls.trigger(s.Events.LEVELS_UPDATED,{levels:i})},n=i,(a=[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t,r=this._levels;if(0!==r.length&&(this.currentLevelIndex!==e||null===(t=r[e])||void 0===t||!t.details)){if(e<0||e>=r.length){var i=e<0;if(this.hls.trigger(s.Events.ERROR,{type:o.ErrorTypes.OTHER_ERROR,details:o.ErrorDetails.LEVEL_SWITCH_ERROR,level:e,fatal:i,reason:"invalid level idx"}),i)return;e=Math.min(e,r.length-1)}this.clearTimer();var n=this.currentLevelIndex,a=r[n],l=r[e];this.log("switching to level "+e+" from "+n),this.currentLevelIndex=e;var u=re({},l,{level:e,maxBitrate:l.maxBitrate,uri:l.uri,urlId:l.urlId});delete u._urlId,this.hls.trigger(s.Events.LEVEL_SWITCHING,u);var d=l.details;if(!d||d.live){var h=this.switchParams(l.uri,null==a?void 0:a.details);this.loadPlaylist(h)}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this._firstLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}}])&&ie(n.prototype,a),Object.defineProperty(n,"prototype",{writable:!1}),i}(te);!function(e){e.NOT_LOADED="NOT_LOADED",e.APPENDING="APPENDING",e.PARTIAL="PARTIAL",e.OK="OK"}(ae||(ae={}));var le=function(){function e(e){this.activeFragment=null,this.activeParts=null,this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hls=e,this._registerListeners()}var t=e.prototype;return t._registerListeners=function(){var e=this.hls;e.on(s.Events.BUFFER_APPENDED,this.onBufferAppended,this),e.on(s.Events.FRAG_BUFFERED,this.onFragBuffered,this),e.on(s.Events.FRAG_LOADED,this.onFragLoaded,this)},t._unregisterListeners=function(){var e=this.hls;e.off(s.Events.BUFFER_APPENDED,this.onBufferAppended,this),e.off(s.Events.FRAG_BUFFERED,this.onFragBuffered,this),e.off(s.Events.FRAG_LOADED,this.onFragLoaded,this)},t.destroy=function(){this._unregisterListeners(),this.fragments=this.timeRanges=null},t.getAppendedFrag=function(e,t){if(t===C.PlaylistLevelType.MAIN){var r=this.activeFragment,i=this.activeParts;if(!r)return null;if(i)for(var n=i.length;n--;){var a=i[n],s=a?a.end:r.appendedPTS;if(a.start<=e&&void 0!==s&&e<=s)return n>9&&(this.activeParts=i.slice(n-9)),a}else if(r.start<=e&&void 0!==r.appendedPTS&&e<=r.appendedPTS)return r}return this.getBufferedFrag(e,t)},t.getBufferedFrag=function(e,t){for(var r=this.fragments,i=Object.keys(r),n=i.length;n--;){var a=r[i[n]];if((null==a?void 0:a.body.type)===t&&a.buffered){var s=a.body;if(s.start<=e&&e<=s.end)return s}}return null},t.detectEvictedFragments=function(e,t,r){var i=this;Object.keys(this.fragments).forEach((function(n){var a=i.fragments[n];if(a)if(a.buffered){var s=a.range[e];s&&s.time.some((function(e){var r=!i.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&i.removeFragment(a.body),r}))}else a.body.type===r&&i.removeFragment(a.body)}))},t.detectPartialFragments=function(e){var t=this,r=this.timeRanges,i=e.frag,n=e.part;if(r&&"initSegment"!==i.sn){var a=de(i),s=this.fragments[a];s&&(Object.keys(r).forEach((function(e){var a=i.elementaryStreams[e];if(a){var o=r[e],l=null!==n||!0===a.partial;s.range[e]=t.getBufferedTimes(i,n,l,o)}})),s.loaded=null,Object.keys(s.range).length?s.buffered=!0:this.removeFragment(s.body))}},t.fragBuffered=function(e){var t=de(e),r=this.fragments[t];r&&(r.loaded=null,r.buffered=!0)},t.getBufferedTimes=function(e,t,r,i){for(var n={time:[],partial:r},a=t?t.start:e.start,s=t?t.end:e.end,o=e.minEndPTS||s,l=e.maxStartPTS||a,u=0;u=d&&o<=h){n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(ad)n.partial=!0,n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(s,i.end(u))});else if(s<=d)break}return n},t.getPartialFragment=function(e){var t,r,i,n=null,a=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var u=o[l];u&&ue(u)&&(r=u.body.start-s,i=u.body.end+s,e>=r&&e<=i&&(t=Math.min(e-r,i-e),a<=t&&(n=u.body,a=t)))})),n},t.getState=function(e){var t=de(e),r=this.fragments[t];return r?r.buffered?ue(r)?ae.PARTIAL:ae.OK:ae.APPENDING:ae.NOT_LOADED},t.isTimeBuffered=function(e,t,r){for(var i,n,a=0;a=i&&t<=n)return!0;if(t<=i)return!1}return!1},t.onFragLoaded=function(e,t){var r=t.frag,i=t.part;if("initSegment"!==r.sn&&!r.bitrateTest&&!i){var n=de(r);this.fragments[n]={body:r,loaded:t,buffered:!1,range:Object.create(null)}}},t.onBufferAppended=function(e,t){var r=this,i=t.frag,n=t.part,a=t.timeRanges;if(i.type===C.PlaylistLevelType.MAIN)if(this.activeFragment=i,n){var s=this.activeParts;s||(this.activeParts=s=[]),s.push(n)}else this.activeParts=null;this.timeRanges=a,Object.keys(a).forEach((function(e){var t=a[e];if(r.detectEvictedFragments(e,t),!n)for(var s=0;se&&i.removeFragment(s)}}))},t.removeFragment=function(e){var t=de(e);e.stats.loaded=0,e.clearElementaryStreamInfo(),delete this.fragments[t]},t.removeAllFragments=function(){this.fragments=Object.create(null),this.activeFragment=null,this.activeParts=null},e}();function ue(e){var t,r;return e.buffered&&((null===(t=e.range.video)||void 0===t?void 0:t.partial)||(null===(r=e.range.audio)||void 0===r?void 0:r.partial))}function de(e){return e.type+"_"+e.level+"_"+e.urlId+"_"+e.sn}var he=function(){function e(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}var t=e.prototype;return t.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},t.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},t.onHandlerDestroyed=function(){},t.hasInterval=function(){return!!this._tickInterval},t.hasNextTick=function(){return!!this._tickTimer},t.setInterval=function(e){return!this._tickInterval&&(this._tickInterval=self.setInterval(this._boundTick,e),!0)},t.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},t.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},t.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},t.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},t.doTick=function(){},e}(),fe={length:0,start:function(){return 0},end:function(){return 0}},ce=function(){function e(){}return e.isBuffered=function(t,r){try{if(t)for(var i=e.getBuffered(t),n=0;n=i.start(n)&&r<=i.end(n))return!0}catch(e){}return!1},e.bufferInfo=function(t,r,i){try{if(t){var n,a=e.getBuffered(t),s=[];for(n=0;ns&&(i[a-1].end=e[n].end):i.push(e[n])}else i.push(e[n])}else i=e;for(var o,l=0,u=t,d=t,h=0;h=f&&t0)r=n+1;else{if(!(s<0))return a;i=n-1}}return null};function ye(e,t,r){void 0===e&&(e=0),void 0===t&&(t=0);var i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function Ee(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}function Te(e){var t="function"==typeof Map?new Map:void 0;return Te=function(e){if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;var r;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,i)}function i(){return Se(e,arguments,Ae(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),Le(i,e)},Te(e)}function Se(e,t,r){return Se=be()?Reflect.construct.bind():function(e,t,r){var i=[null];i.push.apply(i,t);var n=new(Function.bind.apply(e,i));return r&&Le(n,r.prototype),n},Se.apply(null,arguments)}function be(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function Le(e,t){return Le=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Le(e,t)}function Ae(e){return Ae=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Ae(e)}var De=Math.pow(2,17),Re=function(){function e(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}var t=e.prototype;return t.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},t.abort=function(){this.loader&&this.loader.abort()},t.load=function(e,t){var r=this,i=e.url;if(!i)return Promise.reject(new _e({type:o.ErrorTypes.NETWORK_ERROR,details:o.ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,networkDetails:null},"Fragment does not have a "+(i?"part list":"url")));this.abort();var n=this.config,a=n.fLoader,s=n.loader;return new Promise((function(i,l){r.loader&&r.loader.destroy();var u=r.loader=e.loader=a?new a(n):new s(n),d=ke(e),h={timeout:n.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:n.fragLoadingMaxRetryTimeout,highWaterMark:"initSegment"===e.sn?1/0:De};e.stats=u.stats,u.load(d,h,{onSuccess:function(t,n,a,s){r.resetLoader(e,u),i({frag:e,part:null,payload:t.data,networkDetails:s})},onError:function(t,i,n){r.resetLoader(e,u),l(new _e({type:o.ErrorTypes.NETWORK_ERROR,details:o.ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:t,networkDetails:n}))},onAbort:function(t,i,n){r.resetLoader(e,u),l(new _e({type:o.ErrorTypes.NETWORK_ERROR,details:o.ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:e,networkDetails:n}))},onTimeout:function(t,i,n){r.resetLoader(e,u),l(new _e({type:o.ErrorTypes.NETWORK_ERROR,details:o.ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,networkDetails:n}))},onProgress:function(r,i,n,a){t&&t({frag:e,part:null,payload:n,networkDetails:a})}})}))},t.loadPart=function(e,t,r){var i=this;this.abort();var n=this.config,a=n.fLoader,s=n.loader;return new Promise((function(l,u){i.loader&&i.loader.destroy();var d=i.loader=e.loader=a?new a(n):new s(n),h=ke(e,t),f={timeout:n.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:n.fragLoadingMaxRetryTimeout,highWaterMark:De};t.stats=d.stats,d.load(h,f,{onSuccess:function(n,a,s,o){i.resetLoader(e,d),i.updateStatsFromPart(e,t);var u={frag:e,part:t,payload:n.data,networkDetails:o};r(u),l(u)},onError:function(r,n,a){i.resetLoader(e,d),u(new _e({type:o.ErrorTypes.NETWORK_ERROR,details:o.ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:r,networkDetails:a}))},onAbort:function(r,n,a){e.stats.aborted=t.stats.aborted,i.resetLoader(e,d),u(new _e({type:o.ErrorTypes.NETWORK_ERROR,details:o.ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,networkDetails:a}))},onTimeout:function(r,n,a){i.resetLoader(e,d),u(new _e({type:o.ErrorTypes.NETWORK_ERROR,details:o.ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,networkDetails:a}))}})}))},t.updateStatsFromPart=function(e,t){var r=e.stats,i=t.stats,n=i.total;if(r.loaded+=i.loaded,n){var a=Math.round(e.duration/t.duration),s=Math.min(Math.round(r.loaded/n),a),o=(a-s)*Math.round(r.loaded/s);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,u=i.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end},t.resetLoader=function(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()},e}();function ke(e,t){void 0===t&&(t=null);var r=t||e,i={frag:e,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},n=r.byteRangeStartOffset,s=r.byteRangeEndOffset;return(0,a.isFiniteNumber)(n)&&(0,a.isFiniteNumber)(s)&&(i.rangeStart=n,i.rangeEnd=s),i}var _e=function(e){var t,r;function i(t){for(var r,i=arguments.length,n=new Array(i>1?i-1:0),a=1;a=t.endSN&&!e.nextStart){var n=t.partList;if(null!=n&&n.length){var a=n[n.length-1];return ce.isBuffered(this.media,a.start+a.duration/2)}var s=i.getState(r);return s===ae.PARTIAL||s===ae.OK}return!1},h.onMediaAttached=function(e,t){var r=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),r.addEventListener("seeking",this.onvseeking),r.addEventListener("ended",this.onvended);var i=this.config;this.levels&&i.autoStartLoad&&this.state===Oe&&this.startLoad(i.startPosition)},h.onMediaDetaching=function(){var e=this.media;null!=e&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()},h.onMediaSeeking=function(){var e=this.config,t=this.fragCurrent,r=this.media,i=this.mediaBuffer,n=this.state,s=r?r.currentTime:0,o=ce.bufferInfo(i||r,s,e.maxBufferHole);if(this.log("media seeking to "+((0,a.isFiniteNumber)(s)?s.toFixed(3):s)+", state: "+n),n===Ve)this.resetLoadingState();else if(t){var l=e.maxFragLookUpTolerance,u=t.start-l,d=t.start+t.duration+l;if(!o.len||do.end){var h=s>d;(s0&&a&&a.key&&a.iv&&"AES-128"===a.method){var o=self.performance.now();return t.decrypter.webCryptoDecrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer).then((function(t){var n=self.performance.now();return i.trigger(s.Events.FRAG_DECRYPTED,{frag:e,payload:t,stats:{tstart:o,tdecrypt:n}}),r.payload=t,r}))}return r})).then((function(r){var i=t.fragCurrent,n=t.hls,a=t.levels;if(!a)throw new Error("init load aborted, missing levels");a[e.level].details;var o=e.stats;t.state=Fe,t.fragLoadError=0,e.data=new Uint8Array(r.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),r.frag===i&&n.trigger(s.Events.FRAG_BUFFERED,{stats:o,frag:i,part:null,id:e.type}),t.tick()})).catch((function(r){t.state!==Oe&&t.state!==He&&(t.warn(r),t.resetFragmentLoading(e))}))},h.fragContextChanged=function(e){var t=this.fragCurrent;return!e||!t||e.level!==t.level||e.sn!==t.sn||e.urlId!==t.urlId},h.fragBufferedComplete=function(e,t){var r,i,n=this.mediaBuffer?this.mediaBuffer:this.media;this.log("Buffered "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+("[stream-controller]"===this.logPrefix?"level":"track")+" "+e.level+" "+(n?Ie(ce.getBuffered(n)):"(detached)")),this.state=Fe,n&&(!this.loadedmetadata&&e.type==C.PlaylistLevelType.MAIN&&n.buffered.length&&(null===(r=this.fragCurrent)||void 0===r?void 0:r.sn)===(null===(i=this.fragPrevious)||void 0===i?void 0:i.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())},h.seekToStartPos=function(){},h._handleFragmentLoadComplete=function(e){var t=this.transmuxer;if(t){var r=e.frag,i=e.part,n=e.partsLoaded,a=!n||0===n.length||n.some((function(e){return!e})),s=new ve(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!a);t.flush(s)}},h._handleFragmentLoadProgress=function(e){},h._doFragLoad=function(e,t,r,i){var n=this;if(void 0===r&&(r=null),!this.levels)throw new Error("frag load aborted, missing levels");if(r=Math.max(e.start,r||0),this.config.lowLatencyMode&&t){var o=t.partList;if(o&&i){r>e.end&&t.fragmentHint&&(e=t.fragmentHint);var l=this.getNextPart(o,e,r);if(l>-1){var u=o[l];return this.log("Loading part sn: "+e.sn+" p: "+u.index+" cc: "+e.cc+" of playlist ["+t.startSN+"-"+t.endSN+"] parts [0-"+l+"-"+(o.length-1)+"] "+("[stream-controller]"===this.logPrefix?"level":"track")+": "+e.level+", target: "+parseFloat(r.toFixed(3))),this.nextLoadPosition=u.start+u.duration,this.state=Ne,this.hls.trigger(s.Events.FRAG_LOADING,{frag:e,part:o[l],targetBufferTime:r}),this.doFragPartsLoad(e,o,l,i).catch((function(e){return n.handleFragLoadError(e)}))}if(!e.url||this.loadedEndOfParts(o,r))return Promise.resolve(null)}}return this.log("Loading fragment "+e.sn+" cc: "+e.cc+" "+(t?"of ["+t.startSN+"-"+t.endSN+"] ":"")+("[stream-controller]"===this.logPrefix?"level":"track")+": "+e.level+", target: "+parseFloat(r.toFixed(3))),(0,a.isFiniteNumber)(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Ne,this.hls.trigger(s.Events.FRAG_LOADING,{frag:e,targetBufferTime:r}),this.fragmentLoader.load(e,i).catch((function(e){return n.handleFragLoadError(e)}))},h.doFragPartsLoad=function(e,t,r,i){var n=this;return new Promise((function(a,o){var l=[];!function r(u){var d=t[u];n.fragmentLoader.loadPart(e,d,i).then((function(i){l[d.index]=i;var o=i.part;n.hls.trigger(s.Events.FRAG_LOADED,i);var h=t[u+1];if(!h||h.fragment!==e)return a({frag:e,part:o,partsLoaded:l});r(u+1)})).catch(o)}(r)}))},h.handleFragLoadError=function(e){var t=e.data;return t&&t.details===o.ErrorDetails.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(s.Events.ERROR,t),null},h._handleTransmuxerFlush=function(e){var t=this.getCurrentContext(e);if(t&&this.state===Be){var r=t.frag,i=t.part,n=t.level,a=self.performance.now();r.stats.parsing.end=a,i&&(i.stats.parsing.end=a),this.updateLevelTiming(r,i,n,e.partial)}else this.fragCurrent||(this.state=Fe)},h.getCurrentContext=function(e){var t=this.levels,r=e.level,i=e.sn,n=e.part;if(!t||!t[r])return this.warn("Levels object was unset while buffering fragment "+i+" of level "+r+". The current chunk will not be buffered."),null;var a=t[r],s=n>-1?function(e,t,r){if(!e||!e.details)return null;var i=e.details.partList;if(i)for(var n=i.length;n--;){var a=i[n];if(a.index===r&&a.fragment.sn===t)return a}return null}(a,i,n):null,o=s?s.fragment:function(e,t,r){if(!e||!e.details)return null;var i=e.details,n=i.fragments[t-i.startSN];return n||((n=i.fragmentHint)&&n.sn===t?n:ta&&this.flushMainBuffer(s,e.start)}else this.flushMainBuffer(0,e.start)},h.getFwdBufferInfo=function(e,t){var r=this.config,i=this.getLoadPosition();if(!(0,a.isFiniteNumber)(i))return null;var n=ce.bufferInfo(e,i,r.maxBufferHole);if(0===n.len&&void 0!==n.nextStart){var s=this.fragmentTracker.getBufferedFrag(i,t);if(s&&n.nextStart=r&&(t.maxMaxBufferLength/=2,this.warn("Reduce max buffer length to "+t.maxMaxBufferLength+"s"),!0)},h.getNextFragment=function(e,t){var r=t.fragments,i=r.length;if(!i)return null;var n,a=this.config,s=r[0].start;if(t.live){var o=a.initialLiveManifestSize;if(i-1&&rr.start&&r.loaded},h.getInitialLiveFragment=function(e,t){var r=this.fragPrevious,i=null;if(r){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+r.programDateTime),i=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!(0,a.isFiniteNumber)(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;r=r||0;for(var i=0;i=e.startSN&&n<=e.endSN){var s=t[n-e.startSN];r.cc===s.cc&&(i=s,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=function(e,t){return me(e,(function(e){return e.cct?-1:0}))}(t,r.cc),i&&this.log("Live playlist, switching playlist, load frag with same CC: "+i.sn))}}else{var o=this.hls.liveSyncPosition;null!==o&&(i=this.getFragmentAtPosition(o,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i},h.getFragmentAtPosition=function(e,t,r){var i,n=this.config,a=this.fragPrevious,s=r.fragments,o=r.endSN,l=r.fragmentHint,u=n.maxFragLookUpTolerance,d=!!(n.lowLatencyMode&&r.partList&&l);if(d&&l&&!this.bitrateTest&&(s=s.concat(l),o=l.sn),i=et-u?0:u):s[s.length-1],i){var h=i.sn-r.startSN;if(this.fragmentTracker.getState(i)===ae.OK&&(a=i),a&&i.sn===a.sn&&!d&&a&&i.level===a.level){var f=s[h+1];i.sn=a-t.maxFragLookUpTolerance&&n<=s;if(null!==i&&r.duration>i&&(nr.startCC||e&&e.cc"+e.startSN+" prev-sn: "+(n?n.sn:"na")+" fragments: "+o),f}return u},h.waitForCdnTuneIn=function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)},h.setStartPosition=function(e,t){var r=this.startPosition;if(r"+e))}}])&&we(n.prototype,d),Object.defineProperty(n,"prototype",{writable:!1}),i}(he);function We(){return self.MediaSource||self.WebKitMediaSource}function Ye(){return self.SourceBuffer||self.WebKitSourceBuffer}var qe=function(){var e=ENTRY_MODULE,t={},r=function r(i){var n=t[i];if(void 0!==n)return n.exports;var a=t[i]={exports:{}};return e[i].call(a.exports,a,a.exports,r),a.exports};r.m=e,r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,{a:t}),t},r.d=function(e,t){for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i=r(ENTRY_MODULE);return i.default||i}.toString().split("ENTRY_MODULE"),ze="\\(\\s*(/\\*.*?\\*/)?\\s*.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)";function Xe(e){return(e+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function Qe(e,t,i){var n={};n[i]=[];var a=t.toString().replace(/^"[^"]+"/,"function"),s=a.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/)||a.match(/^\(\w+,\s*\w+,\s*(\w+)\)\s?\=\s?\>/);if(!s)return n;for(var o,l=s[1],u=new RegExp("(\\\\n|\\W)"+Xe(l)+ze,"g");o=u.exec(a);)"dll-reference"!==o[3]&&n[i].push(o[3]);for(u=new RegExp("\\("+Xe(l)+'\\("(dll-reference\\s([\\.|\\-|\\+|\\w|/|@]+))"\\)\\)'+ze,"g");o=u.exec(a);)e[o[2]]||(n[i].push(o[1]),e[o[2]]=r(o[1]).m),n[o[2]]=n[o[2]]||[],n[o[2]].push(o[4]);for(var d,h=Object.keys(n),f=0;f0}),!1)}function Ze(e,t,r,i){var n=e[i].map((function(e){return'"'+e+'": '+t[i][e].toString().replace(/^"[^"]+"/,"function")})).join(",");return qe[0]+"{"+n+"}"+qe[1]+'"'+r+'"'+qe[2]}var Je=r(764),et=r(729),tt=We()||{isTypeSupported:function(){return!1}},rt=function(){function e(e,t,i,n){var a=this;this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.worker=void 0,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;var u=e.config;this.hls=e,this.id=t,this.useWorker=!!u.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;var d=function(e,t){(t=t||{}).frag=a.frag,t.id=a.id,a.hls.trigger(e,t)};this.observer=new et.EventEmitter,this.observer.on(s.Events.FRAG_DECRYPTED,d),this.observer.on(s.Events.ERROR,d);var h={mp4:tt.isTypeSupported("video/mp4"),mpeg:tt.isTypeSupported("audio/mpeg"),mp3:tt.isTypeSupported('audio/mp4; codecs="mp3"')},f=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){var c;l.logger.log("demuxing in webworker");try{c=this.worker=function(e,t){t=t||{};var i={main:r.m},n=t.all?{main:Object.keys(i.main)}:function(e,t){for(var r={main:[t]},i={main:[]},n={main:{}};$e(r);)for(var a=Object.keys(r),s=0;s1&&u.id===(null==y?void 0:y.stats.chunkCount),A=!T&&(1===S||0===S&&(1===b||L&&b<=0)),D=self.performance.now();(T||S||0===n.stats.parsing.start)&&(n.stats.parsing.start=D),!a||!b&&A||(a.stats.parsing.start=D);var R=!(y&&(null===(h=n.initSegment)||void 0===h?void 0:h.url)===(null===(f=y.initSegment)||void 0===f?void 0:f.url)),k=new Je.TransmuxState(E,A,o,T,p,R);if(!A||E||R){l.logger.log("[transmuxer-interface, "+n.type+"]: Starting new transmux session for sn: "+u.sn+" p: "+u.part+" level: "+u.level+" id: "+u.id+"\n discontinuity: "+E+"\n trackSwitch: "+T+"\n contiguous: "+A+"\n accurateTimeOffset: "+o+"\n timeOffset: "+p+"\n initSegmentChange: "+R);var _=new Je.TransmuxConfig(r,i,t,s,d);this.configureTransmuxer(_)}if(this.frag=n,this.part=a,g)g.postMessage({cmd:"demux",data:e,decryptdata:m,chunkMeta:u,state:k},e instanceof ArrayBuffer?[e]:[]);else if(v){var x=v.push(e,m,u,k);(0,Je.isPromise)(x)?x.then((function(e){c.handleTransmuxComplete(e)})):this.handleTransmuxComplete(x)}},t.flush=function(e){var t=this;e.transmuxing.start=self.performance.now();var r=this.transmuxer,i=this.worker;if(i)i.postMessage({cmd:"flush",chunkMeta:e});else if(r){var n=r.flush(e);(0,Je.isPromise)(n)?n.then((function(r){t.handleFlushResult(r,e)})):this.handleFlushResult(n,e)}},t.handleFlushResult=function(e,t){var r=this;e.forEach((function(e){r.handleTransmuxComplete(e)})),this.onFlush(t)},t.onWorkerMessage=function(e){var t=e.data,r=this.hls;switch(t.event){case"init":self.URL.revokeObjectURL(this.worker.objectURL);break;case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":l.logger[t.data.logType]&&l.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,r.trigger(t.event,t.data)}},t.configureTransmuxer=function(e){var t=this.worker,r=this.transmuxer;t?t.postMessage({cmd:"configure",config:e}):r&&r.configure(e)},t.handleTransmuxComplete=function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)},e}(),it=function(){function e(e,t,r,i){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=r,this.hls=i}var t=e.prototype;return t.destroy=function(){this.media=null,this.hls=this.fragmentTracker=null},t.poll=function(e,t){var r=this.config,i=this.media,n=this.stalled;if(null!==i){var a=i.currentTime,s=i.seeking,o=this.seeking&&!s,u=!this.seeking&&s;if(this.seeking=s,a===e){if((u||o)&&(this.stalled=null),!(i.paused&&!s||i.ended||0===i.playbackRate)&&ce.getBuffered(i).length){var d=ce.bufferInfo(i,a,0),h=d.len>0,f=d.nextStart||0;if(h||f){if(s){var c=d.len>2,v=!f||t&&t.start<=a||f-a>2&&!this.fragmentTracker.getPartialFragment(a);if(c||v)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var g,p=Math.max(f,d.start||0)-a,m=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,y=(null==m||null===(g=m.details)||void 0===g?void 0:g.live)?2*m.details.targetduration:2;if(p>0&&p<=y)return void this._trySkipBufferHole(null)}var E=self.performance.now();if(null!==n){var T=E-n;if(s||!(T>=250)||(this._reportStall(d),this.media)){var S=ce.bufferInfo(i,a,r.maxBufferHole);this._tryFixBufferStall(S,T)}}else this.stalled=E}}}else if(this.moved=!0,null!==n){if(this.stallReported){var b=self.performance.now()-n;l.logger.warn("playback not stuck anymore @"+a+", after "+Math.round(b)+"ms"),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}}},t._tryFixBufferStall=function(e,t){var r=this.config,i=this.fragmentTracker,n=this.media;if(null!==n){var a=n.currentTime,s=i.getPartialFragment(a);if(s&&(this._trySkipBufferHole(s)||!this.media))return;e.len>r.maxBufferHole&&t>1e3*r.highBufferWatchdogPeriod&&(l.logger.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}},t._reportStall=function(e){var t=this.hls,r=this.media;!this.stallReported&&r&&(this.stallReported=!0,l.logger.warn("Playback stalling at @"+r.currentTime+" due to low buffer ("+JSON.stringify(e)+")"),t.trigger(s.Events.ERROR,{type:o.ErrorTypes.MEDIA_ERROR,details:o.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,buffer:e.len}))},t._trySkipBufferHole=function(e){var t=this.config,r=this.hls,i=this.media;if(null===i)return 0;for(var n=i.currentTime,a=0,u=ce.getBuffered(i),d=0;d=a&&n1?(i=0,this.bitrateTest=!0):i=r.nextAutoLevel),this.level=r.nextLoadLevel=i,this.loadedmetadata=!1}t>0&&-1===e&&(this.log("Override startPosition with lastCurrentTime @"+t.toFixed(3)),e=t),this.state=Fe,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=Oe},u.stopLoad=function(){this._forceStartLoad=!1,e.prototype.stopLoad.call(this)},u.doTick=function(){switch(this.state){case Fe:this.doTickIdle();break;case je:var e,t=this.levels,r=this.level,i=null==t||null===(e=t[r])||void 0===e?void 0:e.details;if(i&&(!i.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(i))break;this.state=Fe;break}break;case Ue:var n,a=self.performance.now(),s=this.retryDate;(!s||a>=s||null!==(n=this.media)&&void 0!==n&&n.seeking)&&(this.log("retryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.level),this.state=Fe)}this.onTickEnd()},u.onTickEnd=function(){e.prototype.onTickEnd.call(this),this.checkBuffer(),this.checkFragmentChanged()},u.doTickIdle=function(){var e,t,r=this.hls,i=this.levelLastLoaded,n=this.levels,a=this.media,o=r.config,l=r.nextLoadLevel;if(null!==i&&(a||!this.startFragRequested&&o.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)&&n&&n[l]){var u=n[l];this.level=r.nextLoadLevel=l;var d=u.details;if(!d||this.state===je||d.live&&this.levelLastLoaded!==l)this.state=je;else{var h=this.getMainFwdBufferInfo();if(null!==h&&!(h.len>=this.getMaxBufferLength(u.maxBitrate))){if(this._streamEnded(h,d)){var f={};return this.altAudio&&(f.type="video"),this.hls.trigger(s.Events.BUFFER_EOS,f),void(this.state=Ve)}this.backtrackFragment&&this.backtrackFragment.start>h.end&&(this.backtrackFragment=null);var c=this.backtrackFragment?this.backtrackFragment.start:h.end,v=this.getNextFragment(c,d);if(this.couldBacktrack&&!this.fragPrevious&&v&&"initSegment"!==v.sn&&this.fragmentTracker.getState(v)!==ae.OK){var g,m=(null!=(g=this.backtrackFragment)?g:v).sn-d.startSN,y=d.fragments[m-1];y&&v.cc===y.cc&&(v=y,this.fragmentTracker.removeFragment(y))}else this.backtrackFragment&&h.len&&(this.backtrackFragment=null);if(v&&this.fragmentTracker.getState(v)===ae.OK&&this.nextLoadPosition>c){var E=this.audioOnly&&!this.altAudio?p.ElementaryStreamTypes.AUDIO:p.ElementaryStreamTypes.VIDEO;a&&this.afterBufferFlushed(a,E,C.PlaylistLevelType.MAIN),v=this.getNextFragment(this.nextLoadPosition,d)}v&&(!v.initSegment||v.initSegment.data||this.bitrateTest||(v=v.initSegment),"identity"!==(null===(e=v.decryptdata)||void 0===e?void 0:e.keyFormat)||null!==(t=v.decryptdata)&&void 0!==t&&t.key?this.loadFragment(v,d,c):this.loadKey(v,d))}}}},u.loadFragment=function(t,r,i){var n,a=this.fragmentTracker.getState(t);this.fragCurrent=t,a===ae.NOT_LOADED?"initSegment"===t.sn?this._loadInitSegment(t):this.bitrateTest?(this.log("Fragment "+t.sn+" of level "+t.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(t)):(this.startFragRequested=!0,e.prototype.loadFragment.call(this,t,r,i)):a===ae.APPENDING?this.reduceMaxBufferLength(t.duration)&&this.fragmentTracker.removeFragment(t):0===(null===(n=this.media)||void 0===n?void 0:n.buffered.length)&&this.fragmentTracker.removeAllFragments()},u.getAppendedFrag=function(e){var t=this.fragmentTracker.getAppendedFrag(e,C.PlaylistLevelType.MAIN);return t&&"fragment"in t?t.fragment:t},u.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,C.PlaylistLevelType.MAIN)},u.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.end+.5):null},u.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},u.nextLevelSwitch=function(){var e=this.levels,t=this.media;if(null!=t&&t.readyState){var r,i=this.getAppendedFrag(t.currentTime);if(i&&i.start>1&&this.flushMainBuffer(0,i.start-1),!t.paused&&e){var n=e[this.hls.nextLoadLevel],a=this.fragLastKbps;r=a&&this.fragCurrent?this.fragCurrent.duration*n.maxBitrate/(1e3*a)+1:0}else r=0;var s=this.getBufferedFrag(t.currentTime+r);if(s){var o=this.followingBufferedFrag(s);if(o){this.abortCurrentFrag();var l=o.maxStartPTS?o.maxStartPTS:o.start,u=o.duration,d=Math.max(s.end,l+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,.5*u),.75*u));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}},u.abortCurrentFrag=function(){var e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,null!=e&&e.loader&&e.loader.abort(),this.state){case Me:case Ne:case Ue:case Be:case Ge:this.state=Fe}this.nextLoadPosition=this.getLoadPosition()},u.flushMainBuffer=function(t,r){e.prototype.flushMainBuffer.call(this,t,r,this.altAudio?"video":null)},u.onMediaAttached=function(t,r){e.prototype.onMediaAttached.call(this,t,r);var i=r.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new it(this.config,i,this.fragmentTracker,this.hls)},u.onMediaDetaching=function(){var t=this.media;t&&this.onvplaying&&this.onvseeked&&(t.removeEventListener("playing",this.onvplaying),t.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),e.prototype.onMediaDetaching.call(this)},u.onMediaPlaying=function(){this.tick()},u.onMediaSeeked=function(){var e=this.media,t=e?e.currentTime:null;(0,a.isFiniteNumber)(t)&&this.log("Media seeked to "+t.toFixed(3)),this.tick()},u.onManifestLoading=function(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(s.Events.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.fragPlaying=null,this.backtrackFragment=null},u.onManifestParsed=function(e,t){var r,i,n,a=!1,s=!1;t.levels.forEach((function(e){(r=e.audioCodec)&&(-1!==r.indexOf("mp4a.40.2")&&(a=!0),-1!==r.indexOf("mp4a.40.5")&&(s=!0))})),this.audioCodecSwitch=a&&s&&!("function"==typeof(null==(n=Ye())||null===(i=n.prototype)||void 0===i?void 0:i.changeType)),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1},u.onLevelLoading=function(e,t){var r=this.levels;if(r&&this.state===Fe){var i=r[t.level];(!i.details||i.details.live&&this.levelLastLoaded!==t.level||this.waitForCdnTuneIn(i.details))&&(this.state=je)}},u.onLevelLoaded=function(e,t){var r,i=this.levels,n=t.level,a=t.details,o=a.totalduration;if(i){this.log("Level "+n+" loaded ["+a.startSN+","+a.endSN+"], cc ["+a.startCC+", "+a.endCC+"] duration:"+o);var l=this.fragCurrent;!l||this.state!==Ne&&this.state!==Ue||l.level!==t.level&&l.loader&&(this.state=Fe,this.backtrackFragment=null,l.loader.abort());var u=i[n],d=0;if(a.live||null!==(r=u.details)&&void 0!==r&&r.live){if(a.fragments[0]||(a.deltaUpdateFailed=!0),a.deltaUpdateFailed)return;d=this.alignPlaylists(a,u.details)}if(u.details=a,this.levelLastLoaded=n,this.hls.trigger(s.Events.LEVEL_UPDATED,{details:a,level:n}),this.state===je){if(this.waitForCdnTuneIn(a))return;this.state=Fe}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,d),this.tick()}else this.warn("Levels were reset while loading level "+n)},u._handleFragmentLoadProgress=function(e){var t,r=e.frag,i=e.part,n=e.payload,a=this.levels;if(a){var s=a[r.level],o=s.details;if(o){var l=s.videoCodec,u=o.PTSKnown||!o.live,d=null===(t=r.initSegment)||void 0===t?void 0:t.data,h=this._getAudioCodec(s),f=this.transmuxer=this.transmuxer||new rt(this.hls,C.PlaylistLevelType.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),c=i?i.index:-1,v=-1!==c,g=new ve(r.level,r.sn,r.stats.chunkCount,n.byteLength,c,v),p=this.initPTS[r.cc];f.push(n,d,h,l,r,i,o.totalduration,u,g,p)}else this.warn("Dropping fragment "+r.sn+" of level "+r.level+" after level details were reset")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},u.onAudioTrackSwitching=function(e,t){var r=this.altAudio,i=!!t.url,n=t.id;if(!i){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var a=this.fragCurrent;null!=a&&a.loader&&(this.log("Switching to main audio track, cancel main fragment load"),a.loader.abort()),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var o=this.hls;r&&o.trigger(s.Events.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),o.trigger(s.Events.AUDIO_TRACK_SWITCHED,{id:n})}},u.onAudioTrackSwitched=function(e,t){var r=t.id,i=!!this.hls.audioTracks[r].url;if(i){var n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=i,this.tick()},u.onBufferCreated=function(e,t){var r,i,n=t.tracks,a=!1;for(var s in n){var o=n[s];if("main"===o.id){if(i=s,r=o,"video"===s){var l=n[s];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&r?(this.log("Alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},u.onFragBuffered=function(e,t){var r=t.frag,i=t.part;if(!r||r.type===C.PlaylistLevelType.MAIN){if(this.fragContextChanged(r))return this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===Ge&&(this.state=Fe));var n=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}},u.onError=function(e,t){switch(t.details){case o.ErrorDetails.FRAG_LOAD_ERROR:case o.ErrorDetails.FRAG_LOAD_TIMEOUT:case o.ErrorDetails.KEY_LOAD_ERROR:case o.ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(C.PlaylistLevelType.MAIN,t);break;case o.ErrorDetails.LEVEL_LOAD_ERROR:case o.ErrorDetails.LEVEL_LOAD_TIMEOUT:this.state!==He&&(t.fatal?(this.warn(""+t.details),this.state=He):t.levelRetry||this.state!==je||(this.state=Fe));break;case o.ErrorDetails.BUFFER_FULL_ERROR:if("main"===t.parent&&(this.state===Be||this.state===Ge)){var r=!0,i=this.getFwdBufferInfo(this.media,C.PlaylistLevelType.MAIN);i&&i.len>.5&&(r=!this.reduceMaxBufferLength(i.len)),r&&(this.warn("buffer full error also media.currentTime is not buffered, flush main"),this.immediateLevelSwitch()),this.resetLoadingState()}}},u.checkBuffer=function(){var e=this.media,t=this.gapController;if(e&&t&&e.readyState){if(this.loadedmetadata||!ce.getBuffered(e).length){var r=this.state!==Fe?this.fragCurrent:null;t.poll(this.lastCurrentTime,r)}this.lastCurrentTime=e.currentTime}},u.onFragLoadEmergencyAborted=function(){this.state=Fe,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()},u.onBufferFlushed=function(e,t){var r=t.type;if(r!==p.ElementaryStreamTypes.AUDIO||this.audioOnly&&!this.altAudio){var i=(r===p.ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,r,C.PlaylistLevelType.MAIN)}},u.onLevelsUpdated=function(e,t){this.levels=t.levels},u.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},u.seekToStartPos=function(){var e=this.media;if(e){var t=e.currentTime,r=this.startPosition;if(r>=0&&t0&&(n1&&!1===e.seeking){var r=e.currentTime;if(ce.isBuffered(e,r)?t=this.getAppendedFrag(r):ce.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;var i=this.fragPlaying,n=t.level;i&&t.sn===i.sn&&i.level===n&&t.urlId===i.urlId||(this.hls.trigger(s.Events.FRAG_CHANGED,{frag:t}),i&&i.level===n||this.hls.trigger(s.Events.LEVEL_SWITCHED,{level:n}),this.fragPlaying=t)}}},n=i,(l=[{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"currentFrag",get:function(){var e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}},{key:"currentProgramDateTime",get:function(){var e=this.media;if(e){var t=e.currentTime,r=this.currentFrag;if(r&&(0,a.isFiniteNumber)(t)&&(0,a.isFiniteNumber)(r.programDateTime)){var i=r.programDateTime+1e3*(t-r.start);return new Date(i)}}return null}},{key:"currentLevel",get:function(){var e=this.currentFrag;return e?e.level:-1}},{key:"nextBufferedFrag",get:function(){var e=this.currentFrag;return e?this.followingBufferedFrag(e):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])&&nt(n.prototype,l),Object.defineProperty(n,"prototype",{writable:!1}),i}(Ke);const ot=function(){function e(e,t,r){void 0===t&&(t=0),void 0===r&&(r=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=r}var t=e.prototype;return t.sample=function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e},t.getTotalWeight=function(){return this.totalWeight_},t.getEstimate=function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_},e}(),lt=function(){function e(e,t,r){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new ot(e),this.fast_=new ot(t)}var t=e.prototype;return t.update=function(e,t){var r=this.slow_,i=this.fast_;this.slow_.halfLife!==e&&(this.slow_=new ot(e,r.getEstimate(),r.getTotalWeight())),this.fast_.halfLife!==t&&(this.fast_=new ot(t,i.getEstimate(),i.getTotalWeight()))},t.sample=function(e,t){var r=(e=Math.max(e,this.minDelayMs_))/1e3,i=8*t/r;this.fast_.sample(r,i),this.slow_.sample(r,i)},t.canEstimate=function(){var e=this.fast_;return e&&e.getTotalWeight()>=this.minWeight_},t.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},t.destroy=function(){},e}();function ut(e,t){for(var r=0;rp;b--){var A=g[b].maxBitrate;if((L=E?u*A/(6.4*E):u*A/v)=T||(l.logger.warn("Fragment "+e.sn+(t?" part "+t.index:"")+" of level "+e.level+" is loading too slowly and will cause an underbuffer; aborting and switching to level "+b+"\n Current BW estimate: "+((0,a.isFiniteNumber)(v)?(v/1024).toFixed(3):"Unknown")+" Kb/s\n Estimated load time for current fragment: "+T.toFixed(3)+" s\n Estimated load time for the next fragment: "+L.toFixed(3)+" s\n Time to underbuffer: "+S.toFixed(3)+" s"),r.nextLoadLevel=b,c&&this.bwEstimator.sample(h,o.loaded),this.clearTimer(),e.loader&&(this.fragCurrent=this.partCurrent=null,e.loader.abort()),r.trigger(s.Events.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:o}))}}}}}},i.onFragLoaded=function(e,t){var r=t.frag,i=t.part;if(r.type===C.PlaylistLevelType.MAIN&&(0,a.isFiniteNumber)(r.sn)){var n=i?i.stats:r.stats,o=i?i.duration:r.duration;if(this.clearTimer(),this.lastLoadedFragLevel=r.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){var l=this.hls.levels[r.level],u=(l.loaded?l.loaded.bytes:0)+n.loaded,d=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:u,duration:d},l.realBitrate=Math.round(8*u/d)}if(r.bitrateTest){var h={stats:n,frag:r,part:i,id:r.type};this.onFragBuffered(s.Events.FRAG_BUFFERED,h)}}},i.onFragBuffered=function(e,t){var r=t.frag,i=t.part,n=i?i.stats:r.stats;if(!n.aborted&&r.type===C.PlaylistLevelType.MAIN&&"initSegment"!==r.sn){var a=n.parsing.end-n.loading.start;this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}},i.onError=function(e,t){switch(t.details){case o.ErrorDetails.FRAG_LOAD_ERROR:case o.ErrorDetails.FRAG_LOAD_TIMEOUT:this.clearTimer()}},i.clearTimer=function(){self.clearInterval(this.timer),this.timer=void 0},i.getNextABRAutoLevel=function(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls,i=r.maxAutoLevel,n=r.config,a=r.minAutoLevel,s=r.media,o=t?t.duration:e?e.duration:0,u=(s&&s.currentTime,s&&0!==s.playbackRate?Math.abs(s.playbackRate):1),d=this.bwEstimator?this.bwEstimator.getEstimate():n.abrEwmaDefaultEstimate,h=r.mainForwardBufferInfo,f=(h?h.len:0)/u,c=this.findBestLevel(d,a,i,f,n.abrBandWidthFactor,n.abrBandWidthUpFactor);if(c>=0)return c;l.logger.trace((f?"rebuffering expected":"buffer is empty")+", finding optimal quality level");var v=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay,g=n.abrBandWidthFactor,p=n.abrBandWidthUpFactor;if(!f){var m=this.bitrateTestDelay;m&&(v=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-m,l.logger.trace("bitrate test took "+Math.round(1e3*m)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*v)+" ms"),g=p=1)}return c=this.findBestLevel(d,a,i,f+v,g,p),Math.max(c,0)},i.findBestLevel=function(e,t,r,i,n,s){for(var o,u=this.fragCurrent,d=this.partCurrent,h=this.lastLoadedFragLevel,f=this.hls.levels,c=f[h],v=!(null==c||null===(o=c.details)||void 0===o||!o.live),g=null==c?void 0:c.codecSet,p=d?d.duration:u?u.duration:0,m=r;m>=t;m--){var y=f[m];if(y&&(!g||y.codecSet===g)){var E,T=y.details,S=(d?null==T?void 0:T.partTarget:null==T?void 0:T.averagetargetduration)||p;E=m<=h?n*e:s*e;var b=f[m].maxBitrate,L=b*S/E;if(l.logger.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+m+"/"+Math.round(E)+"/"+b+"/"+S+"/"+i+"/"+L),E>b&&(0===L||!(0,a.isFiniteNumber)(L)||v&&!this.bitrateTestDelay||L0||Object.keys(this.pendingTracks).length>0},t.destroy=function(){this.unregisterListeners(),this.details=null},t.registerListeners=function(){var e=this.hls;e.on(s.Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(s.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(s.Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(s.Events.BUFFER_RESET,this.onBufferReset,this),e.on(s.Events.BUFFER_APPENDING,this.onBufferAppending,this),e.on(s.Events.BUFFER_CODECS,this.onBufferCodecs,this),e.on(s.Events.BUFFER_EOS,this.onBufferEos,this),e.on(s.Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(s.Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(s.Events.FRAG_PARSED,this.onFragParsed,this),e.on(s.Events.FRAG_CHANGED,this.onFragChanged,this)},t.unregisterListeners=function(){var e=this.hls;e.off(s.Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(s.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(s.Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(s.Events.BUFFER_RESET,this.onBufferReset,this),e.off(s.Events.BUFFER_APPENDING,this.onBufferAppending,this),e.off(s.Events.BUFFER_CODECS,this.onBufferCodecs,this),e.off(s.Events.BUFFER_EOS,this.onBufferEos,this),e.off(s.Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(s.Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(s.Events.FRAG_PARSED,this.onFragParsed,this),e.off(s.Events.FRAG_CHANGED,this.onFragChanged,this)},t._initSourceBuffer=function(){this.sourceBuffer={},this.operationQueue=new ct(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]}},t.onManifestParsed=function(e,t){var r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,this.details=null,l.logger.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},t.onMediaAttaching=function(e,t){var r=this.media=t.media;if(r&&vt){var i=this.mediaSource=new vt;i.addEventListener("sourceopen",this._onMediaSourceOpen),i.addEventListener("sourceended",this._onMediaSourceEnded),i.addEventListener("sourceclose",this._onMediaSourceClose),r.src=self.URL.createObjectURL(i),this._objectUrl=r.src}},t.onMediaDetaching=function(){var e=this.media,t=this.mediaSource,r=this._objectUrl;if(t){if(l.logger.log("[buffer-controller]: media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(e){l.logger.warn("[buffer-controller]: onMediaDetaching: "+e.message+" while calling endOfStream")}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),e&&(r&&self.URL.revokeObjectURL(r),e.src===r?(e.removeAttribute("src"),e.load()):l.logger.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(s.Events.MEDIA_DETACHED,void 0)},t.onBufferReset=function(){var e=this;this.getSourceBufferTypes().forEach((function(t){var r=e.sourceBuffer[t];try{r&&(e.removeBufferListeners(t),e.mediaSource&&e.mediaSource.removeSourceBuffer(r),e.sourceBuffer[t]=void 0)}catch(e){l.logger.warn("[buffer-controller]: Failed to reset the "+t+" buffer",e)}})),this._initSourceBuffer()},t.onBufferCodecs=function(e,t){var r=this,i=this.getSourceBufferTypes().length;Object.keys(t).forEach((function(e){if(i){var n=r.tracks[e];if(n&&"function"==typeof n.buffer.changeType){var a=t[e],s=a.id,o=a.codec,u=a.levelCodec,d=a.container,h=a.metadata,f=(n.levelCodec||n.codec).replace(gt,"$1"),c=(u||o).replace(gt,"$1");if(f!==c){var v=d+";codecs="+(u||o);r.appendChangeType(e,v),l.logger.log("[buffer-controller]: switching codec "+f+" to "+c),r.tracks[e]={buffer:n.buffer,codec:o,container:d,levelCodec:u,metadata:h,id:s}}}}else r.pendingTracks[e]=t[e]})),i||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())},t.appendChangeType=function(e,t){var r=this,i=this.operationQueue,n={execute:function(){var n=r.sourceBuffer[e];n&&(l.logger.log("[buffer-controller]: changing "+e+" sourceBuffer type to "+t),n.changeType(t)),i.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){l.logger.warn("[buffer-controller]: Failed to change "+e+" SourceBuffer type",t)}};i.append(n,e)},t.onBufferAppending=function(e,t){var r=this,i=this.hls,n=this.operationQueue,a=this.tracks,u=t.data,d=t.type,h=t.frag,f=t.part,c=t.chunkMeta,v=c.buffering[d],g=self.performance.now();v.start=g;var p=h.stats.buffering,m=f?f.stats.buffering:null;0===p.start&&(p.start=g),m&&0===m.start&&(m.start=g);var y=a.audio,E="audio"===d&&1===c.id&&"audio/mpeg"===(null==y?void 0:y.container),T={execute:function(){if(v.executeStart=self.performance.now(),E){var e=r.sourceBuffer[d];if(e){var t=h.start-e.timestampOffset;Math.abs(t)>=.1&&(l.logger.log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to "+h.start+" (delta: "+t+") sn: "+h.sn+")"),e.timestampOffset=h.start)}}r.appendExecutor(u,d)},onStart:function(){},onComplete:function(){var e=self.performance.now();v.executeEnd=v.end=e,0===p.first&&(p.first=e),m&&0===m.first&&(m.first=e);var t=r.sourceBuffer,i={};for(var n in t)i[n]=ce.getBuffered(t[n]);r.appendError=0,r.hls.trigger(s.Events.BUFFER_APPENDED,{type:d,frag:h,part:f,chunkMeta:c,parent:h.type,timeRanges:i})},onError:function(e){l.logger.error("[buffer-controller]: Error encountered while trying to append to the "+d+" SourceBuffer",e);var t={type:o.ErrorTypes.MEDIA_ERROR,parent:h.type,details:o.ErrorDetails.BUFFER_APPEND_ERROR,err:e,fatal:!1};e.code===DOMException.QUOTA_EXCEEDED_ERR?t.details=o.ErrorDetails.BUFFER_FULL_ERROR:(r.appendError++,t.details=o.ErrorDetails.BUFFER_APPEND_ERROR,r.appendError>i.config.appendErrorMaxRetry&&(l.logger.error("[buffer-controller]: Failed "+i.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),t.fatal=!0,i.stopLoad())),i.trigger(s.Events.ERROR,t)}};n.append(T,d)},t.onBufferFlushing=function(e,t){var r=this,i=this.operationQueue,n=function(e){return{execute:r.removeExecutor.bind(r,e,t.startOffset,t.endOffset),onStart:function(){},onComplete:function(){r.hls.trigger(s.Events.BUFFER_FLUSHED,{type:e})},onError:function(t){l.logger.warn("[buffer-controller]: Failed to remove from "+e+" SourceBuffer",t)}}};t.type?i.append(n(t.type),t.type):this.getSourceBufferTypes().forEach((function(e){i.append(n(e),e)}))},t.onFragParsed=function(e,t){var r=this,i=t.frag,n=t.part,a=[],o=n?n.elementaryStreams:i.elementaryStreams;o[p.ElementaryStreamTypes.AUDIOVIDEO]?a.push("audiovideo"):(o[p.ElementaryStreamTypes.AUDIO]&&a.push("audio"),o[p.ElementaryStreamTypes.VIDEO]&&a.push("video")),0===a.length&&l.logger.warn("Fragments must have at least one ElementaryStreamType set. type: "+i.type+" level: "+i.level+" sn: "+i.sn),this.blockBuffers((function(){var e=self.performance.now();i.stats.buffering.end=e,n&&(n.stats.buffering.end=e);var t=n?n.stats:i.stats;r.hls.trigger(s.Events.FRAG_BUFFERED,{frag:i,part:n,stats:t,id:i.type})}),a)},t.onFragChanged=function(e,t){this.flushBackBuffer()},t.onBufferEos=function(e,t){var r=this;this.getSourceBufferTypes().reduce((function(e,i){var n=r.sourceBuffer[i];return t.type&&t.type!==i||n&&!n.ended&&(n.ended=!0,l.logger.log("[buffer-controller]: "+i+" sourceBuffer now EOS")),e&&!(n&&!n.ended)}),!0)&&this.blockBuffers((function(){var e=r.mediaSource;e&&"open"===e.readyState&&e.endOfStream()}))},t.onLevelUpdated=function(e,t){var r=t.details;r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())},t.flushBackBuffer=function(){var e=this.hls,t=this.details,r=this.media,i=this.sourceBuffer;if(r&&null!==t){var n=this.getSourceBufferTypes();if(n.length){var o=t.live&&null!==e.config.liveBackBufferLength?e.config.liveBackBufferLength:e.config.backBufferLength;if((0,a.isFiniteNumber)(o)&&!(o<0)){var l=r.currentTime,u=t.levelTargetDuration,d=Math.max(o,u),h=Math.floor(l/u)*u-d;n.forEach((function(r){var n=i[r];if(n){var a=ce.getBuffered(n);a.length>0&&h>a.start(0)&&(e.trigger(s.Events.BACK_BUFFER_REACHED,{bufferEnd:h}),t.live&&e.trigger(s.Events.LIVE_BACK_BUFFER_REACHED,{bufferEnd:h}),e.trigger(s.Events.BUFFER_FLUSHING,{startOffset:0,endOffset:h,type:r}))}}))}}}},t.updateMediaElementDuration=function(){if(this.details&&this.media&&this.mediaSource&&"open"===this.mediaSource.readyState){var e=this.details,t=this.hls,r=this.media,i=this.mediaSource,n=e.fragments[0].start+e.totalduration,s=r.duration,o=(0,a.isFiniteNumber)(i.duration)?i.duration:0;e.live&&t.config.liveDurationInfinity?(l.logger.log("[buffer-controller]: Media Source duration is set to Infinity"),i.duration=1/0,this.updateSeekableRange(e)):(n>o&&n>s||!(0,a.isFiniteNumber)(s))&&(l.logger.log("[buffer-controller]: Updating Media Source duration to "+n.toFixed(3)),i.duration=n)}},t.updateSeekableRange=function(e){var t=this.mediaSource,r=e.fragments;if(r.length&&e.live&&null!=t&&t.setLiveSeekableRange){var i=Math.max(0,r[0].start),n=Math.max(i,i+e.totalduration);t.setLiveSeekableRange(i,n)}},t.checkPendingTracks=function(){var e=this.bufferCodecEventsExpected,t=this.operationQueue,r=this.pendingTracks,i=Object.keys(r).length;if(i&&!e||2===i){this.createSourceBuffers(r),this.pendingTracks={};var n=this.getSourceBufferTypes();if(0===n.length)return void this.hls.trigger(s.Events.ERROR,{type:o.ErrorTypes.MEDIA_ERROR,details:o.ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,reason:"could not create source buffer for media codec(s)"});n.forEach((function(e){t.executeNext(e)}))}},t.createSourceBuffers=function(e){var t=this.sourceBuffer,r=this.mediaSource;if(!r)throw Error("createSourceBuffers called when mediaSource was null");var i=0;for(var n in e)if(!t[n]){var a=e[n];if(!a)throw Error("source buffer exists for track "+n+", however track does not");var u=a.levelCodec||a.codec,d=a.container+";codecs="+u;l.logger.log("[buffer-controller]: creating sourceBuffer("+d+")");try{var h=t[n]=r.addSourceBuffer(d),f=n;this.addBufferListener(f,"updatestart",this._onSBUpdateStart),this.addBufferListener(f,"updateend",this._onSBUpdateEnd),this.addBufferListener(f,"error",this._onSBUpdateError),this.tracks[n]={buffer:h,codec:u,container:a.container,levelCodec:a.levelCodec,metadata:a.metadata,id:a.id},i++}catch(e){l.logger.error("[buffer-controller]: error while trying to add sourceBuffer: "+e.message),this.hls.trigger(s.Events.ERROR,{type:o.ErrorTypes.MEDIA_ERROR,details:o.ErrorDetails.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,mimeType:d})}}i&&this.hls.trigger(s.Events.BUFFER_CREATED,{tracks:this.tracks})},t._onSBUpdateStart=function(e){this.operationQueue.current(e).onStart()},t._onSBUpdateEnd=function(e){var t=this.operationQueue;t.current(e).onComplete(),t.shiftAndExecuteNext(e)},t._onSBUpdateError=function(e,t){l.logger.error("[buffer-controller]: "+e+" SourceBuffer error",t),this.hls.trigger(s.Events.ERROR,{type:o.ErrorTypes.MEDIA_ERROR,details:o.ErrorDetails.BUFFER_APPENDING_ERROR,fatal:!1});var r=this.operationQueue.current(e);r&&r.onError(t)},t.removeExecutor=function(e,t,r){var i=this.media,n=this.mediaSource,s=this.operationQueue,o=this.sourceBuffer[e];if(!i||!n||!o)return l.logger.warn("[buffer-controller]: Attempting to remove from the "+e+" SourceBuffer, but it does not exist"),void s.shiftAndExecuteNext(e);var u=(0,a.isFiniteNumber)(i.duration)?i.duration:1/0,d=(0,a.isFiniteNumber)(n.duration)?n.duration:1/0,h=Math.max(0,t),f=Math.min(r,u,d);f>h?(l.logger.log("[buffer-controller]: Removing ["+h+","+f+"] from the "+e+" SourceBuffer"),o.remove(h,f)):s.shiftAndExecuteNext(e)},t.appendExecutor=function(e,t){var r=this.operationQueue,i=this.sourceBuffer[t];if(!i)return l.logger.warn("[buffer-controller]: Attempting to append to the "+t+" SourceBuffer, but it does not exist"),void r.shiftAndExecuteNext(t);i.ended=!1,i.appendBuffer(e)},t.blockBuffers=function(e,t){var r=this;if(void 0===t&&(t=this.getSourceBufferTypes()),!t.length)return l.logger.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(e);var i=this.operationQueue,n=t.map((function(e){return i.appendBlocker(e)}));Promise.all(n).then((function(){e(),t.forEach((function(e){var t=r.sourceBuffer[e];t&&t.updating||i.shiftAndExecuteNext(e)}))}))},t.getSourceBufferTypes=function(){return Object.keys(this.sourceBuffer)},t.addBufferListener=function(e,t,r){var i=this.sourceBuffer[e];if(i){var n=r.bind(this,e);this.listeners[e].push({event:t,listener:n}),i.addEventListener(t,n)}},t.removeBufferListeners=function(e){var t=this.sourceBuffer[e];t&&this.listeners[e].forEach((function(e){t.removeEventListener(e.event,e.listener)}))},e}();function mt(e,t){for(var r=0;r0&&this.mediaWidth>0){var e=this.hls.levels;if(e.length){var t=this.hls;t.autoLevelCapping=this.getMaxLevel(e.length-1),t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},i.getMaxLevel=function(t){var r=this,i=this.hls.levels;if(!i.length)return-1;var n=i.filter((function(i,n){return e.isLevelAllowed(n,r.restrictedLevels)&&n<=t}));return this.clientRect=null,e.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)},i.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},i.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},i.getDimensions=function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t},e.isLevelAllowed=function(e,t){return void 0===t&&(t=[]),-1===t.indexOf(e)},e.getMaxLevelByMediaSize=function(e,t,r){if(!e||!e.length)return-1;for(var i,n,a=e.length-1,s=0;s=t||o.height>=r)&&(i=o,!(n=e[s+1])||i.width!==n.width||i.height!==n.height)){a=s;break}}return a},t=e,(r=[{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return e}}])&&mt(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}(),Et=function(){function e(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}var t=e.prototype;return t.setStreamController=function(e){this.streamController=e},t.registerListeners=function(){this.hls.on(s.Events.MEDIA_ATTACHING,this.onMediaAttaching,this)},t.unregisterListeners=function(){this.hls.off(s.Events.MEDIA_ATTACHING,this.onMediaAttaching)},t.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},t.onMediaAttaching=function(e,t){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},t.checkFPS=function(e,t,r){var i=performance.now();if(t){if(this.lastTime){var n=i-this.lastTime,a=r-this.lastDroppedFrames,o=t-this.lastDecodedFrames,u=1e3*a/n,d=this.hls;if(d.trigger(s.Events.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:r}),u>0&&a>d.config.fpsDroppedMonitoringThreshold*o){var h=d.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(-1===d.autoLevelCapping||d.autoLevelCapping>=h)&&(h-=1,d.trigger(s.Events.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:d.currentLevel}),d.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}},t.checkFPSInterval=function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)},e}();var Tt=r(408),St=/^age:\s*[\d.]+\s*$/m;const bt=function(){function e(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=e?e.xhrSetup:null,this.stats=new Tt.LoadStats,this.retryDelay=0}var t=e.prototype;return t.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null},t.abortInternal=function(){var e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))},t.abort=function(){var e;this.abortInternal(),null!==(e=this.callbacks)&&void 0!==e&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},t.load=function(e,t,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.retryDelay=t.retryDelay,this.loadInternal()},t.loadInternal=function(){var e=this.config,t=this.context;if(e){var r=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0;var n=this.xhrSetup;try{if(n)try{n(r,t.url)}catch(e){r.open("GET",t.url,!0),n(r,t.url)}r.readyState||r.open("GET",t.url,!0);var a=this.context.headers;if(a)for(var s in a)r.setRequestHeader(s,a[s])}catch(e){return void this.callbacks.onError({code:r.status,text:e.message},t,r)}t.rangeEnd&&r.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),r.onreadystatechange=this.readystatechange.bind(this),r.onprogress=this.loadprogress.bind(this),r.responseType=t.responseType,self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),e.timeout),r.send()}},t.readystatechange=function(){var e=this.context,t=this.loader,r=this.stats;if(e&&t){var i=t.readyState,n=this.config;if(!r.aborted&&i>=2)if(self.clearTimeout(this.requestTimeout),0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start)),4===i){t.onreadystatechange=null,t.onprogress=null;var a=t.status,s="arraybuffer"===t.responseType;if(a>=200&&a<300&&(s&&t.response||null!==t.responseText)){var o,u;if(r.loading.end=Math.max(self.performance.now(),r.loading.first),u=s?(o=t.response).byteLength:(o=t.responseText).length,r.loaded=r.total=u,!this.callbacks)return;var d=this.callbacks.onProgress;if(d&&d(r,e,o,t),!this.callbacks)return;var h={url:t.responseURL,data:o};this.callbacks.onSuccess(h,r,e,t)}else r.retry>=n.maxRetry||a>=400&&a<499?(l.logger.error(a+" while loading "+e.url),this.callbacks.onError({code:a,text:t.statusText},e,t)):(l.logger.warn(a+" while loading "+e.url+", retrying in "+this.retryDelay+"..."),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,n.maxRetryDelay),r.retry++)}else self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout)}},t.loadtimeout=function(){l.logger.warn("timeout while loading "+this.context.url);var e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))},t.loadprogress=function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)},t.getCacheAge=function(){var e=null;if(this.loader&&St.test(this.loader.getAllResponseHeaders())){var t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e},e}();var Lt=function(){function e(){this.chunks=[],this.dataLength=0}var t=e.prototype;return t.push=function(e){this.chunks.push(e),this.dataLength+=e.length},t.flush=function(){var e,t=this.chunks,r=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var r=new Uint8Array(t),i=0,n=0;n=i&&n(t,r,a.flush(),e)):n(t,r,l,e),o()})).catch((function(){return Promise.reject()}))}()},e}();function wt(e,t){return new self.Request(e.url,t)}var Ct=function(e){var t,r;function i(t,r,i){var n;return(n=e.call(this,t)||this).code=void 0,n.details=void 0,n.code=r,n.details=i,n}return r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,kt(t,r),i}(At(Error));const Pt=It;var Ot;!function(e){e.WIDEVINE="com.widevine.alpha",e.PLAYREADY="com.microsoft.playready"}(Ot||(Ot={}));var Ft="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Mt(){return Mt=Object.assign?Object.assign.bind():function(e){for(var t=1;t=t)return i;return 0}},{key:"maxAutoLevel",get:function(){var e=this.levels,t=this.autoLevelCapping;return-1===t&&e&&e.length?e.length-1:t}},{key:"nextAutoLevel",get:function(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)},set:function(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(e){this.config.lowLatencyMode=e}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}}])&&Vt(t.prototype,r),i&&Vt(t,i),Object.defineProperty(t,"prototype",{writable:!1}),e}();Ht.defaultConfig=void 0},923:(e,t,r)=>{"use strict";r.r(t),r.d(t,{BaseSegment:()=>c,ElementaryStreamTypes:()=>i,Fragment:()=>v,Part:()=>g});var i,n=r(965),a=r(945),s=r(93),o=r(960),l=r(408);function u(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,d(e,t)}function d(e,t){return d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},d(e,t)}function h(e,t){for(var r=0;r>8*(15-r)&255;return t},r.setDecryptDataFromLevelKey=function(e,t){var r=e;return"AES-128"===(null==e?void 0:e.method)&&e.uri&&!e.iv&&((r=o.LevelKey.fromURI(e.uri)).method=e.method,r.iv=this.createInitializationVector(t),r.keyFormat="identity"),r},r.setElementaryStreamInfo=function(e,t,r,i,n,a){void 0===a&&(a=!1);var s=this.elementaryStreams,o=s[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,n)):s[e]={startPTS:t,endPTS:r,startDTS:i,endDTS:n,partial:a}},r.clearElementaryStreamInfo=function(){var e=this.elementaryStreams;e[i.AUDIO]=null,e[i.VIDEO]=null,e[i.AUDIOVIDEO]=null},f(t,[{key:"decryptdata",get:function(){if(!this.levelkey&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkey){var e=this.sn;"number"!=typeof e&&(this.levelkey&&"AES-128"===this.levelkey.method&&!this.levelkey.iv&&s.logger.warn('missing IV for initialization segment with method="'+this.levelkey.method+'" - compliance issue'),e=0),this._decryptdata=this.setDecryptDataFromLevelKey(this.levelkey,e)}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;if(!(0,n.isFiniteNumber)(this.programDateTime))return null;var e=(0,n.isFiniteNumber)(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function(){var e;return!(null===(e=this.decryptdata)||void 0===e||!e.keyFormat||!this.decryptdata.uri)}}]),t}(c),g=function(e){function t(t,r,i,n,a){var s;(s=e.call(this,i)||this).fragOffset=0,s.duration=0,s.gap=!1,s.independent=!1,s.relurl=void 0,s.fragment=void 0,s.index=void 0,s.stats=new l.LoadStats,s.duration=t.decimalFloatingPoint("DURATION"),s.gap=t.bool("GAP"),s.independent=t.bool("INDEPENDENT"),s.relurl=t.enumeratedString("URI"),s.fragment=r,s.index=n;var o=t.enumeratedString("BYTERANGE");return o&&s.setByteRange(o,a),a&&(s.fragOffset=a.fragOffset+a.duration),s}return u(t,e),f(t,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var e=this.elementaryStreams;return!!(e.audio||e.video||e.audiovideo)}}]),t}(c)},960:(e,t,r)=>{"use strict";r.r(t),r.d(t,{LevelKey:()=>a});var i=r(945);function n(e,t){for(var r=0;r{"use strict";r.r(t),r.d(t,{LoadStats:()=>i});var i=function(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}},965:(e,t,r)=>{"use strict";r.r(t),r.d(t,{MAX_SAFE_INTEGER:()=>n,isFiniteNumber:()=>i});var i=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},n=Number.MAX_SAFE_INTEGER||9007199254740991},856:(e,t,r)=>{"use strict";var i;r.r(t),r.d(t,{MetadataSchema:()=>i}),function(e){e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3"}(i||(i={}))},308:(e,t,r)=>{"use strict";var i,n;r.r(t),r.d(t,{PlaylistContextType:()=>i,PlaylistLevelType:()=>n}),function(e){e.MANIFEST="manifest",e.LEVEL="level",e.AUDIO_TRACK="audioTrack",e.SUBTITLE_TRACK="subtitleTrack"}(i||(i={})),function(e){e.MAIN="main",e.AUDIO="audio",e.SUBTITLE="subtitle"}(n||(n={}))},93:(e,t,r)=>{"use strict";r.r(t),r.d(t,{enableLogs:()=>o,logger:()=>l});var i=function(){},n={trace:i,debug:i,log:i,warn:i,info:i,error:i},a=n;function s(e){var t=self.console[e];return t?t.bind(self.console,"["+e+"] >"):i}function o(e,t){if(self.console&&!0===e||"object"==typeof e){!function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i{"use strict";r.r(t),r.d(t,{RemuxerTrackIdConfig:()=>l,appendUint8Array:()=>b,bin2str:()=>u,computeRawDurationFromSamples:()=>E,discardEPB:()=>R,findBox:()=>v,getDuration:()=>y,getStartDTS:()=>m,offsetStartDTS:()=>T,parseEmsg:()=>k,parseInitSegment:()=>p,parseSEIMessageFromNALu:()=>D,parseSamples:()=>L,parseSegmentIndex:()=>g,readSint32:()=>f,readUint16:()=>d,readUint32:()=>h,segmentValidRange:()=>S,writeUint32:()=>c});var i=r(145),n=r(923),a=r(181),s=Math.pow(2,32)-1,o=[].push,l={video:1,audio:2,id3:3,text:4};function u(e){return String.fromCharCode.apply(null,e)}function d(e,t){var r=e[t]<<8|e[t+1];return r<0?65536+r:r}function h(e,t){var r=f(e,t);return r<0?4294967296+r:r}function f(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function c(e,t,r){e[t]=r>>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r}function v(e,t){var r=[];if(!t.length)return r;for(var i=e.byteLength,n=0;n1?n+a:i;if(u(e.subarray(n+4,n+8))===t[0])if(1===t.length)r.push(e.subarray(n+8,s));else{var l=v(e.subarray(n+8,s),t.slice(1));l.length&&o.apply(r,l)}n=s}return r}function g(e){var t=[],r=e[0],i=8,n=h(e,i);i+=4,i+=0===r?8:16,i+=2;var a=e.length+0,s=d(e,i);i+=2;for(var o=0;o>>31)return console.warn("SIDX has hierarchical references (not supported)"),null;var c=h(e,l);l+=4,t.push({referenceSize:f,subsegmentDuration:c,info:{duration:c/n,start:a,end:a+f-1}}),a+=f,i=l+=4}return{earliestPresentationTime:0,timescale:n,version:r,referencesCount:s,references:t}}function p(e){for(var t=[],r=v(e,["moov","trak"]),i=0;i>1&63;return 39===r||40===r}return 6==(31&t)}function D(e,t,r,i){var n=R(e),s=0;s+=t;for(var o=0,l=0,u=!1,f=0;s=n.length)break;o+=f=n[s++]}while(255===f);l=0;do{if(s>=n.length)break;l+=f=n[s++]}while(255===f);var c=n.length-s;if(!u&&4===o&&s16){for(var b=[],L=0;L<16;L++){var A=n[s++].toString(16);b.push(1==A.length?"0"+A:A),3!==L&&5!==L&&7!==L&&9!==L||b.push("-")}for(var D=l-16,k=new Uint8Array(D),_=0;_c)break}}function R(e){for(var t=e.byteLength,r=[],i=1;i{"use strict";function i(e,t,r){return Uint8Array.prototype.slice?e.slice(t,r):new Uint8Array(Array.prototype.slice.call(e,t,r))}r.r(t),r.d(t,{sliceUint8:()=>i})},729:e=>{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function i(){}function n(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function a(e,t,i,a,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new n(i,a||e,s),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function s(e,t){0==--e._eventsCount?e._events=new i:delete e._events[t]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,i,n=[];if(0===this._eventsCount)return n;for(i in e=this._events)t.call(e,i)&&n.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},o.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,a=i.length,s=new Array(a);n{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i=r(392);return i.default})())); +// @license-end From ff61d97a1dc37ffc4f65a0dbfabf54952a83e01f Mon Sep 17 00:00:00 2001 From: Zed Date: Fri, 20 Jan 2023 04:54:19 +0100 Subject: [PATCH 35/68] Optimize profile fetching and caching --- src/api.nim | 31 +++++++++++++--------------- src/consts.nim | 3 ++- src/experimental/parser/graphql.nim | 5 +++++ src/experimental/types/graphuser.nim | 2 ++ src/redis_cache.nim | 11 +++++----- src/tokens.nim | 2 +- src/types.nim | 1 + 7 files changed, 31 insertions(+), 24 deletions(-) diff --git a/src/api.nim b/src/api.nim index 392795c..dd94b69 100644 --- a/src/api.nim +++ b/src/api.nim @@ -4,11 +4,22 @@ import packedjson import types, query, formatters, consts, apiutils, parser import experimental/parser as newParser -proc getGraphUser*(id: string): Future[User] {.async.} = +proc getGraphUser*(username: string): Future[User] {.async.} = + if username.len == 0: return + let + variables = """{ + "screen_name": "$1", + "withSafetyModeUserFields": false, + "withSuperFollowsUserFields": false + }""" % [username] + js = await fetchRaw(graphUser ? {"variables": variables}, Api.userScreenName) + result = parseGraphUser(js) + +proc getGraphUserById*(id: string): Future[User] {.async.} = if id.len == 0 or id.any(c => not c.isDigit): return let - variables = %*{"userId": id, "withSuperFollowsUserFields": true} - js = await fetchRaw(graphUser ? {"variables": $variables}, Api.userRestId) + variables = """{"userId": "$1", "withSuperFollowsUserFields": true}""" % [id] + js = await fetchRaw(graphUserById ? {"variables": variables}, Api.userRestId) result = parseGraphUser(js) proc getGraphListBySlug*(name, list: string): Future[List] {.async.} = @@ -47,20 +58,6 @@ proc getListTimeline*(id: string; after=""): Future[Timeline] {.async.} = url = listTimeline ? ps result = parseTimeline(await fetch(url, Api.timeline), after) -proc getUser*(username: string): Future[User] {.async.} = - if username.len == 0: return - let - ps = genParams({"screen_name": username}) - json = await fetchRaw(userShow ? ps, Api.userShow) - result = parseUser(json, username) - -proc getUserById*(userId: string): Future[User] {.async.} = - if userId.len == 0: return - let - ps = genParams({"user_id": userId}) - json = await fetchRaw(userShow ? ps, Api.userShow) - result = parseUser(json) - proc getTimeline*(id: string; after=""; replies=false): Future[Timeline] {.async.} = if id.len == 0: return let diff --git a/src/consts.nim b/src/consts.nim index 3687a54..2d3ea56 100644 --- a/src/consts.nim +++ b/src/consts.nim @@ -19,7 +19,8 @@ const tweet* = timelineApi / "conversation" graphql = api / "graphql" - graphUser* = graphql / "I5nvpI91ljifos1Y3Lltyg/UserByRestId" + graphUser* = graphql / "7mjxD3-C6BxitPMVQ6w0-Q/UserByScreenName" + graphUserById* = graphql / "I5nvpI91ljifos1Y3Lltyg/UserByRestId" graphList* = graphql / "JADTh6cjebfgetzvF3tQvQ/List" graphListBySlug* = graphql / "ErWsz9cObLel1BF-HjuBlA/ListBySlug" graphListMembers* = graphql / "Ke6urWMeCV2UlKXGRy4sow/ListMembers" diff --git a/src/experimental/parser/graphql.nim b/src/experimental/parser/graphql.nim index b00ab24..4431db3 100644 --- a/src/experimental/parser/graphql.nim +++ b/src/experimental/parser/graphql.nim @@ -1,9 +1,14 @@ +import options import jsony import user, ../types/[graphuser, graphlistmembers] from ../../types import User, Result, Query, QueryKind proc parseGraphUser*(json: string): User = let raw = json.fromJson(GraphUser) + + if raw.data.user.result.reason.get("") == "Suspended": + return User(suspended: true) + result = toUser raw.data.user.result.legacy result.id = raw.data.user.result.restId diff --git a/src/experimental/types/graphuser.nim b/src/experimental/types/graphuser.nim index dded4eb..e13383a 100644 --- a/src/experimental/types/graphuser.nim +++ b/src/experimental/types/graphuser.nim @@ -1,3 +1,4 @@ +import options import user type @@ -10,3 +11,4 @@ type UserResult = object legacy*: RawUser restId*: string + reason*: Option[string] diff --git a/src/redis_cache.nim b/src/redis_cache.nim index 469157a..b91d153 100644 --- a/src/redis_cache.nim +++ b/src/redis_cache.nim @@ -118,11 +118,11 @@ proc getUserId*(username: string): Future[string] {.async.} = pool.withAcquire(r): result = await r.hGet(name.uidKey, name) if result == redisNil: - let user = await getUser(username) + let user = await getGraphUser(username) if user.suspended: return "suspended" else: - await cacheUserId(name, user.id) + await all(cacheUserId(name, user.id), cache(user)) return user.id proc getCachedUser*(username: string; fetch=true): Future[User] {.async.} = @@ -130,8 +130,7 @@ proc getCachedUser*(username: string; fetch=true): Future[User] {.async.} = if prof != redisNil: prof.deserialize(User) elif fetch: - let userId = await getUserId(username) - result = await getGraphUser(userId) + result = await getGraphUser(username) await cache(result) proc getCachedUsername*(userId: string): Future[string] {.async.} = @@ -142,9 +141,11 @@ proc getCachedUsername*(userId: string): Future[string] {.async.} = if username != redisNil: result = username else: - let user = await getUserById(userId) + let user = await getGraphUserById(userId) result = user.username await setEx(key, baseCacheTime, result) + if result.len > 0 and user.id.len > 0: + await all(cacheUserId(result, user.id), cache(user)) proc getCachedTweet*(id: int64): Future[Tweet] {.async.} = if id == 0: return diff --git a/src/tokens.nim b/src/tokens.nim index 4bbcd81..e3b916a 100644 --- a/src/tokens.nim +++ b/src/tokens.nim @@ -41,7 +41,7 @@ proc getPoolJson*(): JsonNode = let maxReqs = case api - of Api.listMembers, Api.listBySlug, Api.list, Api.userRestId: 500 + of Api.listMembers, Api.listBySlug, Api.list, Api.userRestId, Api.userScreenName: 500 of Api.timeline: 187 else: 180 reqs = maxReqs - token.apis[api].remaining diff --git a/src/types.nim b/src/types.nim index 061ec8a..07f9bf7 100644 --- a/src/types.nim +++ b/src/types.nim @@ -17,6 +17,7 @@ type listBySlug listMembers userRestId + userScreenName status RateLimit* = object From 22b51b414b62620633de8ba456eaebdd2de54934 Mon Sep 17 00:00:00 2001 From: Zed Date: Fri, 20 Jan 2023 04:55:56 +0100 Subject: [PATCH 36/68] Fix typo to actually cache pinned tweets --- src/redis_cache.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/redis_cache.nim b/src/redis_cache.nim index b91d153..742b7ae 100644 --- a/src/redis_cache.nim +++ b/src/redis_cache.nim @@ -154,7 +154,7 @@ proc getCachedTweet*(id: int64): Future[Tweet] {.async.} = tweet.deserialize(Tweet) else: result = await getStatus($id) - if result.isNil: + if not result.isNil: await cache(result) proc getCachedPhotoRail*(name: string): Future[PhotoRail] {.async.} = From 19adc658c317c71e671201385350343add6275c8 Mon Sep 17 00:00:00 2001 From: Zed Date: Thu, 2 Feb 2023 12:31:49 +0100 Subject: [PATCH 37/68] Replace tweet endpoint with GraphQL --- src/api.nim | 15 ++++-- src/consts.nim | 32 ++++++++++++ src/parser.nim | 120 ++++++++++++++++++++++++-------------------- src/parserutils.nim | 4 -- src/tokens.nim | 3 +- src/types.nim | 2 +- src/views/tweet.nim | 2 +- 7 files changed, 111 insertions(+), 67 deletions(-) diff --git a/src/api.nim b/src/api.nim index dd94b69..dfcf413 100644 --- a/src/api.nim +++ b/src/api.nim @@ -101,16 +101,21 @@ proc getSearch*[T](query: Query; after=""): Future[Result[T]] {.async.} = except InternalError: return Result[T](beginning: true, query: query) -proc getTweetImpl(id: string; after=""): Future[Conversation] {.async.} = - let url = tweet / (id & ".json") ? genParams(cursor=after) - result = parseConversation(await fetch(url, Api.tweet), id) +proc getGraphTweet(id: string; after=""): Future[Conversation] {.async.} = + if id.len == 0: return + let + cursor = if after.len > 0: "\"cursor\":\"$1\"," % after else: "" + variables = tweetVariables % [id, cursor] + params = {"variables": variables, "features": tweetFeatures} + js = await fetch(graphTweet ? params, Api.tweetDetail) + result = parseGraphConversation(js, id) proc getReplies*(id, after: string): Future[Result[Chain]] {.async.} = - result = (await getTweetImpl(id, after)).replies + result = (await getGraphTweet(id, after)).replies result.beginning = after.len == 0 proc getTweet*(id: string; after=""): Future[Conversation] {.async.} = - result = await getTweetImpl(id) + result = await getGraphTweet(id) if after.len > 0: result.replies = await getReplies(id, after) diff --git a/src/consts.nim b/src/consts.nim index 2d3ea56..18ecb2c 100644 --- a/src/consts.nim +++ b/src/consts.nim @@ -19,6 +19,7 @@ const tweet* = timelineApi / "conversation" graphql = api / "graphql" + graphTweet* = graphql / "6lWNh96EXDJCXl05SAtn_g/TweetDetail" graphUser* = graphql / "7mjxD3-C6BxitPMVQ6w0-Q/UserByScreenName" graphUserById* = graphql / "I5nvpI91ljifos1Y3Lltyg/UserByRestId" graphList* = graphql / "JADTh6cjebfgetzvF3tQvQ/List" @@ -58,3 +59,34 @@ const ## user: "result_filter: user" ## photos: "result_filter: photos" ## videos: "result_filter: videos" + + tweetVariables* = """{ + "focalTweetId": "$1", + $2 + "includePromotedContent": false, + "withBirdwatchNotes": false, + "withDownvotePerspective": false, + "withReactionsMetadata": false, + "withReactionsPerspective": false, + "withSuperFollowsTweetFields": false, + "withSuperFollowsUserFields": false, + "withVoice": false, + "withV2Timeline": true +}""" + + tweetFeatures* = """{ + "graphql_is_translatable_rweb_tweet_is_translatable_enabled": false, + "responsive_web_graphql_timeline_navigation_enabled": false, + "standardized_nudges_misinfo": false, + "verified_phone_label_enabled": false, + "responsive_web_twitter_blue_verified_badge_is_enabled": false, + "tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled": false, + "view_counts_everywhere_api_enabled": false, + "responsive_web_edit_tweet_api_enabled": false, + "tweetypie_unmention_optimization_enabled": false, + "vibe_api_enabled": false, + "longform_notetweets_consumption_enabled": false, + "responsive_web_text_conversations_enabled": false, + "responsive_web_enhance_cards_enabled": false, + "interactive_text_enabled": false +}""" diff --git a/src/parser.nim b/src/parser.nim index 2b0c6a4..544f943 100644 --- a/src/parser.nim +++ b/src/parser.nim @@ -72,8 +72,8 @@ proc parseGif(js: JsonNode): Gif = proc parseVideo(js: JsonNode): Video = result = Video( thumb: js{"media_url_https"}.getImageStr, - views: js{"ext", "mediaStats", "r", "ok", "viewCount"}.getStr, - available: js{"ext_media_availability", "status"}.getStr == "available", + views: js{"ext", "mediaStats", "r", "ok", "viewCount"}.getStr($js{"mediaStats", "viewCount"}.getInt), + available: js{"ext_media_availability", "status"}.getStr.toLowerAscii == "available", title: js{"ext_alt_text"}.getStr, durationMs: js{"video_info", "duration_millis"}.getInt # playbackType: mp4 @@ -185,7 +185,7 @@ proc parseCard(js: JsonNode; urls: JsonNode): Card = result.url.len == 0 or result.url.startsWith("card://"): result.url = getPicUrl(result.image) -proc parseTweet(js: JsonNode): Tweet = +proc parseTweet(js: JsonNode; jsCard: JsonNode = newJNull()): Tweet = if js.isNull: return result = Tweet( id: js{"id_str"}.getId, @@ -193,7 +193,6 @@ proc parseTweet(js: JsonNode): Tweet = replyId: js{"in_reply_to_status_id_str"}.getId, text: js{"full_text"}.getStr, time: js{"created_at"}.getTime, - source: getSource(js), hasThread: js{"self_thread"}.notNull, available: true, user: User(id: js{"user_id_str"}.getStr), @@ -218,7 +217,7 @@ proc parseTweet(js: JsonNode): Tweet = result.retweet = some Tweet(id: rt.getId) return - with jsCard, js{"card"}: + if jsCard.kind != JNull: let name = jsCard{"name"}.getStr if "poll" in name: if "image" in name: @@ -295,64 +294,17 @@ proc parseGlobalObjects(js: JsonNode): GlobalObjects = result.users[k] = parseUser(v, k) for k, v in tweets: - var tweet = parseTweet(v) + var tweet = parseTweet(v, v{"card"}) if tweet.user.id in result.users: tweet.user = result.users[tweet.user.id] result.tweets[k] = tweet -proc parseThread(js: JsonNode; global: GlobalObjects): tuple[thread: Chain, self: bool] = - result.thread = Chain() - - let thread = js{"content", "item", "content", "conversationThread"} - with cursor, thread{"showMoreCursor"}: - result.thread.cursor = cursor{"value"}.getStr - result.thread.hasMore = true - - for t in thread{"conversationComponents"}: - let content = t{"conversationTweetComponent", "tweet"} - - if content{"displayType"}.getStr == "SelfThread": - result.self = true - - var tweet = finalizeTweet(global, content{"id"}.getStr) - if not tweet.available: - tweet.tombstone = getTombstone(content{"tombstone"}) - result.thread.content.add tweet - -proc parseConversation*(js: JsonNode; tweetId: string): Conversation = - result = Conversation(replies: Result[Chain](beginning: true)) - let global = parseGlobalObjects(? js) - - let instructions = ? js{"timeline", "instructions"} - if instructions.len == 0: - return - - for e in instructions[0]{"addEntries", "entries"}: - let entry = e{"entryId"}.getStr - if "tweet" in entry or "tombstone" in entry: - let tweet = finalizeTweet(global, e.getEntryId) - if $tweet.id != tweetId: - result.before.content.add tweet - else: - result.tweet = tweet - elif "conversationThread" in entry: - let (thread, self) = parseThread(e, global) - if thread.content.len > 0: - if self: - result.after = thread - else: - result.replies.content.add thread - elif "cursor-showMore" in entry: - result.replies.bottom = e.getCursor - elif "cursor-bottom" in entry: - result.replies.bottom = e.getCursor - proc parseStatus*(js: JsonNode): Tweet = with e, js{"errors"}: if e.getError == tweetNotFound: return - result = parseTweet(js) + result = parseTweet(js, js{"card"}) if not result.isNil: result.user = parseUser(js{"user"}) @@ -409,7 +361,7 @@ proc parseTimeline*(js: JsonNode; after=""): Timeline = proc parsePhotoRail*(js: JsonNode): PhotoRail = for tweet in js: let - t = parseTweet(tweet) + t = parseTweet(tweet, js{"card"}) url = if t.photos.len > 0: t.photos[0] elif t.video.isSome: get(t.video).thumb elif t.gif.isSome: get(t.gif).thumb @@ -418,3 +370,61 @@ proc parsePhotoRail*(js: JsonNode): PhotoRail = if url.len == 0: continue result.add GalleryPhoto(url: url, tweetId: $t.id) + +proc parseGraphTweet(js: JsonNode): Tweet = + if js.kind == JNull: + return Tweet(available: false) + + var jsCard = copy(js{"card", "legacy"}) + if jsCard.kind != JNull: + var values = newJObject() + for val in jsCard["binding_values"]: + values[val["key"].getStr] = val["value"] + jsCard["binding_values"] = values + + result = parseTweet(js{"legacy"}, jsCard) + result.user = parseUser(js{"core", "user_results", "result", "legacy"}) + + if result.quote.isSome: + result.quote = some(parseGraphTweet(js{"quoted_status_result", "result"})) + +proc parseGraphThread(js: JsonNode): tuple[thread: Chain; self: bool] = + let thread = js{"content", "items"} + for t in js{"content", "items"}: + let entryId = t{"entryId"}.getStr + if "cursor-showmore" in entryId: + let cursor = t{"item", "itemContent", "value"} + result.thread.cursor = cursor.getStr + result.thread.hasMore = true + elif "tweet" in entryId: + let tweet = parseGraphTweet(t{"item", "itemContent", "tweet_results", "result"}) + result.thread.content.add tweet + + if t{"item", "itemContent", "tweetDisplayType"}.getStr == "SelfThread": + result.self = true + +proc parseGraphConversation*(js: JsonNode; tweetId: string): Conversation = + result = Conversation(replies: Result[Chain](beginning: true)) + + let instructions = ? js{"data", "threaded_conversation_with_injections_v2", "instructions"} + if instructions.len == 0: + return + + for e in instructions[0]{"entries"}: + let entryId = e{"entryId"}.getStr + # echo entryId + if entryId.startsWith("tweet"): + let tweet = parseGraphTweet(e{"content", "itemContent", "tweet_results", "result"}) + + if $tweet.id == tweetId: + result.tweet = tweet + else: + result.before.content.add tweet + elif entryId.startsWith("conversationthread"): + let (thread, self) = parseGraphThread(e) + if self: + result.after = thread + else: + result.replies.content.add thread + elif entryId.startsWith("cursor-bottom"): + result.replies.bottom = e{"content", "itemContent", "value"}.getStr diff --git a/src/parserutils.nim b/src/parserutils.nim index 4b89236..af4d062 100644 --- a/src/parserutils.nim +++ b/src/parserutils.nim @@ -133,10 +133,6 @@ proc getTombstone*(js: JsonNode): string = result = js{"tombstoneInfo", "richText", "text"}.getStr result.removeSuffix(" Learn more") -proc getSource*(js: JsonNode): string = - let src = js{"source"}.getStr - result = src.substr(src.find('>') + 1, src.rfind('<') - 1) - proc getMp4Resolution*(url: string): int = # parses the height out of a URL like this one: # https://video.twimg.com/ext_tw_video//pu/vid/720x1280/.mp4 diff --git a/src/tokens.nim b/src/tokens.nim index e3b916a..e6a4449 100644 --- a/src/tokens.nim +++ b/src/tokens.nim @@ -41,7 +41,8 @@ proc getPoolJson*(): JsonNode = let maxReqs = case api - of Api.listMembers, Api.listBySlug, Api.list, Api.userRestId, Api.userScreenName: 500 + of Api.listMembers, Api.listBySlug, Api.list, + Api.userRestId, Api.userScreenName, Api.tweetDetail: 500 of Api.timeline: 187 else: 180 reqs = maxReqs - token.apis[api].remaining diff --git a/src/types.nim b/src/types.nim index 07f9bf7..087acb2 100644 --- a/src/types.nim +++ b/src/types.nim @@ -9,6 +9,7 @@ type InternalError* = object of CatchableError Api* {.pure.} = enum + tweetDetail userShow timeline search @@ -176,7 +177,6 @@ type available*: bool tombstone*: string location*: string - source*: string stats*: TweetStats retweet*: Option[Tweet] attribution*: Option[User] diff --git a/src/views/tweet.nim b/src/views/tweet.nim index 69335fa..ea94e28 100644 --- a/src/views/tweet.nim +++ b/src/views/tweet.nim @@ -347,7 +347,7 @@ proc renderTweet*(tweet: Tweet; prefs: Prefs; path: string; class=""; index=0; renderQuote(tweet.quote.get(), prefs, path) if mainTweet: - p(class="tweet-published"): text &"{getTime(tweet)} · {tweet.source}" + p(class="tweet-published"): text &"{getTime(tweet)}" if tweet.mediaTags.len > 0: renderMediaTags(tweet.mediaTags) From 36c72f98603e6387431224b3fb65ada765e9ab65 Mon Sep 17 00:00:00 2001 From: Zed Date: Thu, 2 Feb 2023 12:38:58 +0100 Subject: [PATCH 38/68] Revert "Replace tweet endpoint with GraphQL" This reverts commit 19adc658c317c71e671201385350343add6275c8. --- src/api.nim | 15 ++---- src/consts.nim | 32 ------------ src/parser.nim | 120 ++++++++++++++++++++------------------------ src/parserutils.nim | 4 ++ src/tokens.nim | 3 +- src/types.nim | 2 +- src/views/tweet.nim | 2 +- 7 files changed, 67 insertions(+), 111 deletions(-) diff --git a/src/api.nim b/src/api.nim index dfcf413..dd94b69 100644 --- a/src/api.nim +++ b/src/api.nim @@ -101,21 +101,16 @@ proc getSearch*[T](query: Query; after=""): Future[Result[T]] {.async.} = except InternalError: return Result[T](beginning: true, query: query) -proc getGraphTweet(id: string; after=""): Future[Conversation] {.async.} = - if id.len == 0: return - let - cursor = if after.len > 0: "\"cursor\":\"$1\"," % after else: "" - variables = tweetVariables % [id, cursor] - params = {"variables": variables, "features": tweetFeatures} - js = await fetch(graphTweet ? params, Api.tweetDetail) - result = parseGraphConversation(js, id) +proc getTweetImpl(id: string; after=""): Future[Conversation] {.async.} = + let url = tweet / (id & ".json") ? genParams(cursor=after) + result = parseConversation(await fetch(url, Api.tweet), id) proc getReplies*(id, after: string): Future[Result[Chain]] {.async.} = - result = (await getGraphTweet(id, after)).replies + result = (await getTweetImpl(id, after)).replies result.beginning = after.len == 0 proc getTweet*(id: string; after=""): Future[Conversation] {.async.} = - result = await getGraphTweet(id) + result = await getTweetImpl(id) if after.len > 0: result.replies = await getReplies(id, after) diff --git a/src/consts.nim b/src/consts.nim index 18ecb2c..2d3ea56 100644 --- a/src/consts.nim +++ b/src/consts.nim @@ -19,7 +19,6 @@ const tweet* = timelineApi / "conversation" graphql = api / "graphql" - graphTweet* = graphql / "6lWNh96EXDJCXl05SAtn_g/TweetDetail" graphUser* = graphql / "7mjxD3-C6BxitPMVQ6w0-Q/UserByScreenName" graphUserById* = graphql / "I5nvpI91ljifos1Y3Lltyg/UserByRestId" graphList* = graphql / "JADTh6cjebfgetzvF3tQvQ/List" @@ -59,34 +58,3 @@ const ## user: "result_filter: user" ## photos: "result_filter: photos" ## videos: "result_filter: videos" - - tweetVariables* = """{ - "focalTweetId": "$1", - $2 - "includePromotedContent": false, - "withBirdwatchNotes": false, - "withDownvotePerspective": false, - "withReactionsMetadata": false, - "withReactionsPerspective": false, - "withSuperFollowsTweetFields": false, - "withSuperFollowsUserFields": false, - "withVoice": false, - "withV2Timeline": true -}""" - - tweetFeatures* = """{ - "graphql_is_translatable_rweb_tweet_is_translatable_enabled": false, - "responsive_web_graphql_timeline_navigation_enabled": false, - "standardized_nudges_misinfo": false, - "verified_phone_label_enabled": false, - "responsive_web_twitter_blue_verified_badge_is_enabled": false, - "tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled": false, - "view_counts_everywhere_api_enabled": false, - "responsive_web_edit_tweet_api_enabled": false, - "tweetypie_unmention_optimization_enabled": false, - "vibe_api_enabled": false, - "longform_notetweets_consumption_enabled": false, - "responsive_web_text_conversations_enabled": false, - "responsive_web_enhance_cards_enabled": false, - "interactive_text_enabled": false -}""" diff --git a/src/parser.nim b/src/parser.nim index 544f943..2b0c6a4 100644 --- a/src/parser.nim +++ b/src/parser.nim @@ -72,8 +72,8 @@ proc parseGif(js: JsonNode): Gif = proc parseVideo(js: JsonNode): Video = result = Video( thumb: js{"media_url_https"}.getImageStr, - views: js{"ext", "mediaStats", "r", "ok", "viewCount"}.getStr($js{"mediaStats", "viewCount"}.getInt), - available: js{"ext_media_availability", "status"}.getStr.toLowerAscii == "available", + views: js{"ext", "mediaStats", "r", "ok", "viewCount"}.getStr, + available: js{"ext_media_availability", "status"}.getStr == "available", title: js{"ext_alt_text"}.getStr, durationMs: js{"video_info", "duration_millis"}.getInt # playbackType: mp4 @@ -185,7 +185,7 @@ proc parseCard(js: JsonNode; urls: JsonNode): Card = result.url.len == 0 or result.url.startsWith("card://"): result.url = getPicUrl(result.image) -proc parseTweet(js: JsonNode; jsCard: JsonNode = newJNull()): Tweet = +proc parseTweet(js: JsonNode): Tweet = if js.isNull: return result = Tweet( id: js{"id_str"}.getId, @@ -193,6 +193,7 @@ proc parseTweet(js: JsonNode; jsCard: JsonNode = newJNull()): Tweet = replyId: js{"in_reply_to_status_id_str"}.getId, text: js{"full_text"}.getStr, time: js{"created_at"}.getTime, + source: getSource(js), hasThread: js{"self_thread"}.notNull, available: true, user: User(id: js{"user_id_str"}.getStr), @@ -217,7 +218,7 @@ proc parseTweet(js: JsonNode; jsCard: JsonNode = newJNull()): Tweet = result.retweet = some Tweet(id: rt.getId) return - if jsCard.kind != JNull: + with jsCard, js{"card"}: let name = jsCard{"name"}.getStr if "poll" in name: if "image" in name: @@ -294,17 +295,64 @@ proc parseGlobalObjects(js: JsonNode): GlobalObjects = result.users[k] = parseUser(v, k) for k, v in tweets: - var tweet = parseTweet(v, v{"card"}) + var tweet = parseTweet(v) if tweet.user.id in result.users: tweet.user = result.users[tweet.user.id] result.tweets[k] = tweet +proc parseThread(js: JsonNode; global: GlobalObjects): tuple[thread: Chain, self: bool] = + result.thread = Chain() + + let thread = js{"content", "item", "content", "conversationThread"} + with cursor, thread{"showMoreCursor"}: + result.thread.cursor = cursor{"value"}.getStr + result.thread.hasMore = true + + for t in thread{"conversationComponents"}: + let content = t{"conversationTweetComponent", "tweet"} + + if content{"displayType"}.getStr == "SelfThread": + result.self = true + + var tweet = finalizeTweet(global, content{"id"}.getStr) + if not tweet.available: + tweet.tombstone = getTombstone(content{"tombstone"}) + result.thread.content.add tweet + +proc parseConversation*(js: JsonNode; tweetId: string): Conversation = + result = Conversation(replies: Result[Chain](beginning: true)) + let global = parseGlobalObjects(? js) + + let instructions = ? js{"timeline", "instructions"} + if instructions.len == 0: + return + + for e in instructions[0]{"addEntries", "entries"}: + let entry = e{"entryId"}.getStr + if "tweet" in entry or "tombstone" in entry: + let tweet = finalizeTweet(global, e.getEntryId) + if $tweet.id != tweetId: + result.before.content.add tweet + else: + result.tweet = tweet + elif "conversationThread" in entry: + let (thread, self) = parseThread(e, global) + if thread.content.len > 0: + if self: + result.after = thread + else: + result.replies.content.add thread + elif "cursor-showMore" in entry: + result.replies.bottom = e.getCursor + elif "cursor-bottom" in entry: + result.replies.bottom = e.getCursor + proc parseStatus*(js: JsonNode): Tweet = with e, js{"errors"}: if e.getError == tweetNotFound: return - result = parseTweet(js, js{"card"}) + result = parseTweet(js) if not result.isNil: result.user = parseUser(js{"user"}) @@ -361,7 +409,7 @@ proc parseTimeline*(js: JsonNode; after=""): Timeline = proc parsePhotoRail*(js: JsonNode): PhotoRail = for tweet in js: let - t = parseTweet(tweet, js{"card"}) + t = parseTweet(tweet) url = if t.photos.len > 0: t.photos[0] elif t.video.isSome: get(t.video).thumb elif t.gif.isSome: get(t.gif).thumb @@ -370,61 +418,3 @@ proc parsePhotoRail*(js: JsonNode): PhotoRail = if url.len == 0: continue result.add GalleryPhoto(url: url, tweetId: $t.id) - -proc parseGraphTweet(js: JsonNode): Tweet = - if js.kind == JNull: - return Tweet(available: false) - - var jsCard = copy(js{"card", "legacy"}) - if jsCard.kind != JNull: - var values = newJObject() - for val in jsCard["binding_values"]: - values[val["key"].getStr] = val["value"] - jsCard["binding_values"] = values - - result = parseTweet(js{"legacy"}, jsCard) - result.user = parseUser(js{"core", "user_results", "result", "legacy"}) - - if result.quote.isSome: - result.quote = some(parseGraphTweet(js{"quoted_status_result", "result"})) - -proc parseGraphThread(js: JsonNode): tuple[thread: Chain; self: bool] = - let thread = js{"content", "items"} - for t in js{"content", "items"}: - let entryId = t{"entryId"}.getStr - if "cursor-showmore" in entryId: - let cursor = t{"item", "itemContent", "value"} - result.thread.cursor = cursor.getStr - result.thread.hasMore = true - elif "tweet" in entryId: - let tweet = parseGraphTweet(t{"item", "itemContent", "tweet_results", "result"}) - result.thread.content.add tweet - - if t{"item", "itemContent", "tweetDisplayType"}.getStr == "SelfThread": - result.self = true - -proc parseGraphConversation*(js: JsonNode; tweetId: string): Conversation = - result = Conversation(replies: Result[Chain](beginning: true)) - - let instructions = ? js{"data", "threaded_conversation_with_injections_v2", "instructions"} - if instructions.len == 0: - return - - for e in instructions[0]{"entries"}: - let entryId = e{"entryId"}.getStr - # echo entryId - if entryId.startsWith("tweet"): - let tweet = parseGraphTweet(e{"content", "itemContent", "tweet_results", "result"}) - - if $tweet.id == tweetId: - result.tweet = tweet - else: - result.before.content.add tweet - elif entryId.startsWith("conversationthread"): - let (thread, self) = parseGraphThread(e) - if self: - result.after = thread - else: - result.replies.content.add thread - elif entryId.startsWith("cursor-bottom"): - result.replies.bottom = e{"content", "itemContent", "value"}.getStr diff --git a/src/parserutils.nim b/src/parserutils.nim index af4d062..4b89236 100644 --- a/src/parserutils.nim +++ b/src/parserutils.nim @@ -133,6 +133,10 @@ proc getTombstone*(js: JsonNode): string = result = js{"tombstoneInfo", "richText", "text"}.getStr result.removeSuffix(" Learn more") +proc getSource*(js: JsonNode): string = + let src = js{"source"}.getStr + result = src.substr(src.find('>') + 1, src.rfind('<') - 1) + proc getMp4Resolution*(url: string): int = # parses the height out of a URL like this one: # https://video.twimg.com/ext_tw_video//pu/vid/720x1280/.mp4 diff --git a/src/tokens.nim b/src/tokens.nim index e6a4449..e3b916a 100644 --- a/src/tokens.nim +++ b/src/tokens.nim @@ -41,8 +41,7 @@ proc getPoolJson*(): JsonNode = let maxReqs = case api - of Api.listMembers, Api.listBySlug, Api.list, - Api.userRestId, Api.userScreenName, Api.tweetDetail: 500 + of Api.listMembers, Api.listBySlug, Api.list, Api.userRestId, Api.userScreenName: 500 of Api.timeline: 187 else: 180 reqs = maxReqs - token.apis[api].remaining diff --git a/src/types.nim b/src/types.nim index 087acb2..07f9bf7 100644 --- a/src/types.nim +++ b/src/types.nim @@ -9,7 +9,6 @@ type InternalError* = object of CatchableError Api* {.pure.} = enum - tweetDetail userShow timeline search @@ -177,6 +176,7 @@ type available*: bool tombstone*: string location*: string + source*: string stats*: TweetStats retweet*: Option[Tweet] attribution*: Option[User] diff --git a/src/views/tweet.nim b/src/views/tweet.nim index ea94e28..69335fa 100644 --- a/src/views/tweet.nim +++ b/src/views/tweet.nim @@ -347,7 +347,7 @@ proc renderTweet*(tweet: Tweet; prefs: Prefs; path: string; class=""; index=0; renderQuote(tweet.quote.get(), prefs, path) if mainTweet: - p(class="tweet-published"): text &"{getTime(tweet)}" + p(class="tweet-published"): text &"{getTime(tweet)} · {tweet.source}" if tweet.mediaTags.len > 0: renderMediaTags(tweet.mediaTags) From 670a3bca6ea8d20761adc36799bb68d614b34a28 Mon Sep 17 00:00:00 2001 From: Zed Date: Fri, 24 Feb 2023 01:01:22 +0100 Subject: [PATCH 39/68] Revert "Revert "Replace tweet endpoint with GraphQL"" This reverts commit 36c72f98603e6387431224b3fb65ada765e9ab65. --- src/api.nim | 15 ++++-- src/consts.nim | 32 ++++++++++++ src/parser.nim | 120 ++++++++++++++++++++++++-------------------- src/parserutils.nim | 4 -- src/tokens.nim | 3 +- src/types.nim | 2 +- src/views/tweet.nim | 2 +- 7 files changed, 111 insertions(+), 67 deletions(-) diff --git a/src/api.nim b/src/api.nim index dd94b69..dfcf413 100644 --- a/src/api.nim +++ b/src/api.nim @@ -101,16 +101,21 @@ proc getSearch*[T](query: Query; after=""): Future[Result[T]] {.async.} = except InternalError: return Result[T](beginning: true, query: query) -proc getTweetImpl(id: string; after=""): Future[Conversation] {.async.} = - let url = tweet / (id & ".json") ? genParams(cursor=after) - result = parseConversation(await fetch(url, Api.tweet), id) +proc getGraphTweet(id: string; after=""): Future[Conversation] {.async.} = + if id.len == 0: return + let + cursor = if after.len > 0: "\"cursor\":\"$1\"," % after else: "" + variables = tweetVariables % [id, cursor] + params = {"variables": variables, "features": tweetFeatures} + js = await fetch(graphTweet ? params, Api.tweetDetail) + result = parseGraphConversation(js, id) proc getReplies*(id, after: string): Future[Result[Chain]] {.async.} = - result = (await getTweetImpl(id, after)).replies + result = (await getGraphTweet(id, after)).replies result.beginning = after.len == 0 proc getTweet*(id: string; after=""): Future[Conversation] {.async.} = - result = await getTweetImpl(id) + result = await getGraphTweet(id) if after.len > 0: result.replies = await getReplies(id, after) diff --git a/src/consts.nim b/src/consts.nim index 2d3ea56..18ecb2c 100644 --- a/src/consts.nim +++ b/src/consts.nim @@ -19,6 +19,7 @@ const tweet* = timelineApi / "conversation" graphql = api / "graphql" + graphTweet* = graphql / "6lWNh96EXDJCXl05SAtn_g/TweetDetail" graphUser* = graphql / "7mjxD3-C6BxitPMVQ6w0-Q/UserByScreenName" graphUserById* = graphql / "I5nvpI91ljifos1Y3Lltyg/UserByRestId" graphList* = graphql / "JADTh6cjebfgetzvF3tQvQ/List" @@ -58,3 +59,34 @@ const ## user: "result_filter: user" ## photos: "result_filter: photos" ## videos: "result_filter: videos" + + tweetVariables* = """{ + "focalTweetId": "$1", + $2 + "includePromotedContent": false, + "withBirdwatchNotes": false, + "withDownvotePerspective": false, + "withReactionsMetadata": false, + "withReactionsPerspective": false, + "withSuperFollowsTweetFields": false, + "withSuperFollowsUserFields": false, + "withVoice": false, + "withV2Timeline": true +}""" + + tweetFeatures* = """{ + "graphql_is_translatable_rweb_tweet_is_translatable_enabled": false, + "responsive_web_graphql_timeline_navigation_enabled": false, + "standardized_nudges_misinfo": false, + "verified_phone_label_enabled": false, + "responsive_web_twitter_blue_verified_badge_is_enabled": false, + "tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled": false, + "view_counts_everywhere_api_enabled": false, + "responsive_web_edit_tweet_api_enabled": false, + "tweetypie_unmention_optimization_enabled": false, + "vibe_api_enabled": false, + "longform_notetweets_consumption_enabled": false, + "responsive_web_text_conversations_enabled": false, + "responsive_web_enhance_cards_enabled": false, + "interactive_text_enabled": false +}""" diff --git a/src/parser.nim b/src/parser.nim index 2b0c6a4..544f943 100644 --- a/src/parser.nim +++ b/src/parser.nim @@ -72,8 +72,8 @@ proc parseGif(js: JsonNode): Gif = proc parseVideo(js: JsonNode): Video = result = Video( thumb: js{"media_url_https"}.getImageStr, - views: js{"ext", "mediaStats", "r", "ok", "viewCount"}.getStr, - available: js{"ext_media_availability", "status"}.getStr == "available", + views: js{"ext", "mediaStats", "r", "ok", "viewCount"}.getStr($js{"mediaStats", "viewCount"}.getInt), + available: js{"ext_media_availability", "status"}.getStr.toLowerAscii == "available", title: js{"ext_alt_text"}.getStr, durationMs: js{"video_info", "duration_millis"}.getInt # playbackType: mp4 @@ -185,7 +185,7 @@ proc parseCard(js: JsonNode; urls: JsonNode): Card = result.url.len == 0 or result.url.startsWith("card://"): result.url = getPicUrl(result.image) -proc parseTweet(js: JsonNode): Tweet = +proc parseTweet(js: JsonNode; jsCard: JsonNode = newJNull()): Tweet = if js.isNull: return result = Tweet( id: js{"id_str"}.getId, @@ -193,7 +193,6 @@ proc parseTweet(js: JsonNode): Tweet = replyId: js{"in_reply_to_status_id_str"}.getId, text: js{"full_text"}.getStr, time: js{"created_at"}.getTime, - source: getSource(js), hasThread: js{"self_thread"}.notNull, available: true, user: User(id: js{"user_id_str"}.getStr), @@ -218,7 +217,7 @@ proc parseTweet(js: JsonNode): Tweet = result.retweet = some Tweet(id: rt.getId) return - with jsCard, js{"card"}: + if jsCard.kind != JNull: let name = jsCard{"name"}.getStr if "poll" in name: if "image" in name: @@ -295,64 +294,17 @@ proc parseGlobalObjects(js: JsonNode): GlobalObjects = result.users[k] = parseUser(v, k) for k, v in tweets: - var tweet = parseTweet(v) + var tweet = parseTweet(v, v{"card"}) if tweet.user.id in result.users: tweet.user = result.users[tweet.user.id] result.tweets[k] = tweet -proc parseThread(js: JsonNode; global: GlobalObjects): tuple[thread: Chain, self: bool] = - result.thread = Chain() - - let thread = js{"content", "item", "content", "conversationThread"} - with cursor, thread{"showMoreCursor"}: - result.thread.cursor = cursor{"value"}.getStr - result.thread.hasMore = true - - for t in thread{"conversationComponents"}: - let content = t{"conversationTweetComponent", "tweet"} - - if content{"displayType"}.getStr == "SelfThread": - result.self = true - - var tweet = finalizeTweet(global, content{"id"}.getStr) - if not tweet.available: - tweet.tombstone = getTombstone(content{"tombstone"}) - result.thread.content.add tweet - -proc parseConversation*(js: JsonNode; tweetId: string): Conversation = - result = Conversation(replies: Result[Chain](beginning: true)) - let global = parseGlobalObjects(? js) - - let instructions = ? js{"timeline", "instructions"} - if instructions.len == 0: - return - - for e in instructions[0]{"addEntries", "entries"}: - let entry = e{"entryId"}.getStr - if "tweet" in entry or "tombstone" in entry: - let tweet = finalizeTweet(global, e.getEntryId) - if $tweet.id != tweetId: - result.before.content.add tweet - else: - result.tweet = tweet - elif "conversationThread" in entry: - let (thread, self) = parseThread(e, global) - if thread.content.len > 0: - if self: - result.after = thread - else: - result.replies.content.add thread - elif "cursor-showMore" in entry: - result.replies.bottom = e.getCursor - elif "cursor-bottom" in entry: - result.replies.bottom = e.getCursor - proc parseStatus*(js: JsonNode): Tweet = with e, js{"errors"}: if e.getError == tweetNotFound: return - result = parseTweet(js) + result = parseTweet(js, js{"card"}) if not result.isNil: result.user = parseUser(js{"user"}) @@ -409,7 +361,7 @@ proc parseTimeline*(js: JsonNode; after=""): Timeline = proc parsePhotoRail*(js: JsonNode): PhotoRail = for tweet in js: let - t = parseTweet(tweet) + t = parseTweet(tweet, js{"card"}) url = if t.photos.len > 0: t.photos[0] elif t.video.isSome: get(t.video).thumb elif t.gif.isSome: get(t.gif).thumb @@ -418,3 +370,61 @@ proc parsePhotoRail*(js: JsonNode): PhotoRail = if url.len == 0: continue result.add GalleryPhoto(url: url, tweetId: $t.id) + +proc parseGraphTweet(js: JsonNode): Tweet = + if js.kind == JNull: + return Tweet(available: false) + + var jsCard = copy(js{"card", "legacy"}) + if jsCard.kind != JNull: + var values = newJObject() + for val in jsCard["binding_values"]: + values[val["key"].getStr] = val["value"] + jsCard["binding_values"] = values + + result = parseTweet(js{"legacy"}, jsCard) + result.user = parseUser(js{"core", "user_results", "result", "legacy"}) + + if result.quote.isSome: + result.quote = some(parseGraphTweet(js{"quoted_status_result", "result"})) + +proc parseGraphThread(js: JsonNode): tuple[thread: Chain; self: bool] = + let thread = js{"content", "items"} + for t in js{"content", "items"}: + let entryId = t{"entryId"}.getStr + if "cursor-showmore" in entryId: + let cursor = t{"item", "itemContent", "value"} + result.thread.cursor = cursor.getStr + result.thread.hasMore = true + elif "tweet" in entryId: + let tweet = parseGraphTweet(t{"item", "itemContent", "tweet_results", "result"}) + result.thread.content.add tweet + + if t{"item", "itemContent", "tweetDisplayType"}.getStr == "SelfThread": + result.self = true + +proc parseGraphConversation*(js: JsonNode; tweetId: string): Conversation = + result = Conversation(replies: Result[Chain](beginning: true)) + + let instructions = ? js{"data", "threaded_conversation_with_injections_v2", "instructions"} + if instructions.len == 0: + return + + for e in instructions[0]{"entries"}: + let entryId = e{"entryId"}.getStr + # echo entryId + if entryId.startsWith("tweet"): + let tweet = parseGraphTweet(e{"content", "itemContent", "tweet_results", "result"}) + + if $tweet.id == tweetId: + result.tweet = tweet + else: + result.before.content.add tweet + elif entryId.startsWith("conversationthread"): + let (thread, self) = parseGraphThread(e) + if self: + result.after = thread + else: + result.replies.content.add thread + elif entryId.startsWith("cursor-bottom"): + result.replies.bottom = e{"content", "itemContent", "value"}.getStr diff --git a/src/parserutils.nim b/src/parserutils.nim index 4b89236..af4d062 100644 --- a/src/parserutils.nim +++ b/src/parserutils.nim @@ -133,10 +133,6 @@ proc getTombstone*(js: JsonNode): string = result = js{"tombstoneInfo", "richText", "text"}.getStr result.removeSuffix(" Learn more") -proc getSource*(js: JsonNode): string = - let src = js{"source"}.getStr - result = src.substr(src.find('>') + 1, src.rfind('<') - 1) - proc getMp4Resolution*(url: string): int = # parses the height out of a URL like this one: # https://video.twimg.com/ext_tw_video//pu/vid/720x1280/.mp4 diff --git a/src/tokens.nim b/src/tokens.nim index e3b916a..e6a4449 100644 --- a/src/tokens.nim +++ b/src/tokens.nim @@ -41,7 +41,8 @@ proc getPoolJson*(): JsonNode = let maxReqs = case api - of Api.listMembers, Api.listBySlug, Api.list, Api.userRestId, Api.userScreenName: 500 + of Api.listMembers, Api.listBySlug, Api.list, + Api.userRestId, Api.userScreenName, Api.tweetDetail: 500 of Api.timeline: 187 else: 180 reqs = maxReqs - token.apis[api].remaining diff --git a/src/types.nim b/src/types.nim index 07f9bf7..087acb2 100644 --- a/src/types.nim +++ b/src/types.nim @@ -9,6 +9,7 @@ type InternalError* = object of CatchableError Api* {.pure.} = enum + tweetDetail userShow timeline search @@ -176,7 +177,6 @@ type available*: bool tombstone*: string location*: string - source*: string stats*: TweetStats retweet*: Option[Tweet] attribution*: Option[User] diff --git a/src/views/tweet.nim b/src/views/tweet.nim index 69335fa..ea94e28 100644 --- a/src/views/tweet.nim +++ b/src/views/tweet.nim @@ -347,7 +347,7 @@ proc renderTweet*(tweet: Tweet; prefs: Prefs; path: string; class=""; index=0; renderQuote(tweet.quote.get(), prefs, path) if mainTweet: - p(class="tweet-published"): text &"{getTime(tweet)} · {tweet.source}" + p(class="tweet-published"): text &"{getTime(tweet)}" if tweet.mediaTags.len > 0: renderMediaTags(tweet.mediaTags) From 85f14c9a64d70ebed0ed2f203e9e682d3e415d0b Mon Sep 17 00:00:00 2001 From: Zed Date: Fri, 24 Feb 2023 01:02:28 +0100 Subject: [PATCH 40/68] Fix crash when parsing non-GraphQL cached tweets --- src/types.nim | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/types.nim b/src/types.nim index 087acb2..b5353b5 100644 --- a/src/types.nim +++ b/src/types.nim @@ -177,6 +177,8 @@ type available*: bool tombstone*: string location*: string + ## Unused, needed for backwards compat + source*: string stats*: TweetStats retweet*: Option[Tweet] attribution*: Option[User] From 2751504d2f41d2fba8d4ef74a5ac413833750c00 Mon Sep 17 00:00:00 2001 From: Zed Date: Sat, 25 Feb 2023 18:25:02 +0100 Subject: [PATCH 41/68] Fix crash on unavailable tweets --- src/parser.nim | 5 ++++- src/types.nim | 2 +- tests/test_card.py | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/parser.nim b/src/parser.nim index 544f943..6a77a5f 100644 --- a/src/parser.nim +++ b/src/parser.nim @@ -372,7 +372,7 @@ proc parsePhotoRail*(js: JsonNode): PhotoRail = result.add GalleryPhoto(url: url, tweetId: $t.id) proc parseGraphTweet(js: JsonNode): Tweet = - if js.kind == JNull: + if js.kind == JNull or js{"__typename"}.getStr == "TweetUnavailable": return Tweet(available: false) var jsCard = copy(js{"card", "legacy"}) @@ -416,6 +416,9 @@ proc parseGraphConversation*(js: JsonNode; tweetId: string): Conversation = if entryId.startsWith("tweet"): let tweet = parseGraphTweet(e{"content", "itemContent", "tweet_results", "result"}) + if not tweet.available: + tweet.id = parseBiggestInt(entryId.getId()) + if $tweet.id == tweetId: result.tweet = tweet else: diff --git a/src/types.nim b/src/types.nim index b5353b5..625dcb0 100644 --- a/src/types.nim +++ b/src/types.nim @@ -177,7 +177,7 @@ type available*: bool tombstone*: string location*: string - ## Unused, needed for backwards compat + # Unused, needed for backwards compat source*: string stats*: TweetStats retweet*: Option[Tweet] diff --git a/tests/test_card.py b/tests/test_card.py index ab79e9c..77e44e1 100644 --- a/tests/test_card.py +++ b/tests/test_card.py @@ -42,7 +42,7 @@ no_thumb = [ ['nim_lang/status/1082989146040340480', 'Nim in 2018: A short recap', - 'Posted in r/programming by u/miran1', + '36 votes and 46 comments so far on Reddit', 'reddit.com'] ] From 54cc790bdb3e3f2757f37c74c28ce634fa445752 Mon Sep 17 00:00:00 2001 From: Peter Dave Hello Date: Sun, 26 Feb 2023 07:39:08 +0800 Subject: [PATCH 42/68] Remove Instagram -> Bibliogram replacement as it's discontinued (#772) Close #761 Reference: https://cadence.moe/blog/2022-09-01-discontinuing-bibliogram --- nitter.example.conf | 1 - src/formatters.nim | 4 ---- src/prefs_impl.nim | 4 ---- 3 files changed, 9 deletions(-) diff --git a/nitter.example.conf b/nitter.example.conf index cc7551a..a7abea8 100644 --- a/nitter.example.conf +++ b/nitter.example.conf @@ -39,7 +39,6 @@ theme = "Nitter" replaceTwitter = "nitter.net" replaceYouTube = "piped.video" replaceReddit = "teddit.net" -replaceInstagram = "" proxyVideos = true hlsPlayback = false infiniteScroll = false diff --git a/src/formatters.nim b/src/formatters.nim index 87ff647..3630917 100644 --- a/src/formatters.nim +++ b/src/formatters.nim @@ -13,7 +13,6 @@ let twLinkRegex = re"""twitter\.com(\S+)""" ytRegex = re(r"([A-z.]+\.)?youtu(be\.com|\.be)", {reStudy, reIgnoreCase}) - igRegex = re"(www\.)?instagram\.com" rdRegex = re"(? 0 and "instagram.com" in result: - result = result.replace(igRegex, prefs.replaceInstagram) - if absolute.len > 0 and "href" in result: result = result.replace("href=\"/", &"href=\"{absolute}/") diff --git a/src/prefs_impl.nim b/src/prefs_impl.nim index 0223c82..87de88d 100644 --- a/src/prefs_impl.nim +++ b/src/prefs_impl.nim @@ -107,10 +107,6 @@ genPrefs: "Reddit -> Teddit/Libreddit" placeholder: "Teddit hostname" - replaceInstagram(input, ""): - "Instagram -> Bibliogram" - placeholder: "Bibliogram hostname" - iterator allPrefs*(): Pref = for k, v in prefList: for pref in v: From c21511037efc45988b6aa415f86d91fc4a912aed Mon Sep 17 00:00:00 2001 From: Zed Date: Sun, 26 Feb 2023 00:43:11 +0100 Subject: [PATCH 43/68] Uppercase HLS in preference description --- src/prefs_impl.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/prefs_impl.nim b/src/prefs_impl.nim index 87de88d..8e2ac8f 100644 --- a/src/prefs_impl.nim +++ b/src/prefs_impl.nim @@ -83,7 +83,7 @@ genPrefs: "Enable mp4 video playback (only for gifs)" hlsPlayback(checkbox, false): - "Enable hls video streaming (requires JavaScript)" + "Enable HLS video streaming (requires JavaScript)" proxyVideos(checkbox, true): "Proxy video streaming through the server (might be slow)" From f4c20a48a0eb9b615959ff692f80e5fc9f9052d3 Mon Sep 17 00:00:00 2001 From: Whizanth <107213432+Whizanth@users.noreply.github.com> Date: Sun, 26 Feb 2023 14:59:06 +0100 Subject: [PATCH 44/68] Add Dockerfile for arm64 (#762) --- Dockerfile.arm64 | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Dockerfile.arm64 diff --git a/Dockerfile.arm64 b/Dockerfile.arm64 new file mode 100644 index 0000000..899a430 --- /dev/null +++ b/Dockerfile.arm64 @@ -0,0 +1,23 @@ +FROM alpine:3.17 as nim +LABEL maintainer="setenforce@protonmail.com" + +RUN apk --no-cache add gcc git libc-dev libsass-dev "nim=1.6.8-r0" nimble pcre + +WORKDIR /src/nitter + +COPY nitter.nimble . +RUN nimble install -y --depsOnly + +COPY . . +RUN nimble build -d:danger -d:lto -d:strip \ + && nimble scss \ + && nimble md + +FROM alpine:3.17 +WORKDIR /src/ +RUN apk --no-cache add pcre ca-certificates +COPY --from=nim /src/nitter/nitter ./ +COPY --from=nim /src/nitter/nitter.example.conf ./nitter.conf +COPY --from=nim /src/nitter/public ./public +EXPOSE 8080 +CMD ./nitter From 514b16c417557880987fe1d25011919a79d3cc5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89milien=20Devos=20=28perso=29?= Date: Sun, 26 Feb 2023 15:06:52 +0100 Subject: [PATCH 45/68] Build and push ARM64 docker image (#798) --- .github/workflows/build-docker.yml | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build-docker.yml b/.github/workflows/build-docker.yml index 30a209b..81d547a 100644 --- a/.github/workflows/build-docker.yml +++ b/.github/workflows/build-docker.yml @@ -28,7 +28,7 @@ jobs: with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} - - name: Build and push + - name: Build and push AMD64 Docker image uses: docker/build-push-action@v2 with: context: . @@ -36,3 +36,11 @@ jobs: platforms: linux/amd64 push: true tags: zedeus/nitter:latest,zedeus/nitter:${{ github.sha }} + - name: Build and push ARM64 Docker image + uses: docker/build-push-action@v2 + with: + context: . + file: ./Dockerfile.arm64 + platforms: linux/arm64 + push: true + tags: zedeus/nitter:latest-arm64,zedeus/nitter:${{ github.sha }}-arm64 From 33e34c2d17de95458e9b9624f625aea7502d4088 Mon Sep 17 00:00:00 2001 From: Whizanth <107213432+Whizanth@users.noreply.github.com> Date: Sun, 26 Feb 2023 17:47:36 +0100 Subject: [PATCH 46/68] Add openssl1.1-compat to Dockerfile.arm64 (#800) --- Dockerfile.arm64 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile.arm64 b/Dockerfile.arm64 index 899a430..6cd6744 100644 --- a/Dockerfile.arm64 +++ b/Dockerfile.arm64 @@ -15,7 +15,7 @@ RUN nimble build -d:danger -d:lto -d:strip \ FROM alpine:3.17 WORKDIR /src/ -RUN apk --no-cache add pcre ca-certificates +RUN apk --no-cache add ca-certificates pcre openssl1.1-compat COPY --from=nim /src/nitter/nitter ./ COPY --from=nim /src/nitter/nitter.example.conf ./nitter.conf COPY --from=nim /src/nitter/public ./public From 756a39bdd2b69b1faadba6d996ed58ac01699a9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89milien=20Devos=20=28perso=29?= Date: Sun, 26 Feb 2023 18:24:31 +0100 Subject: [PATCH 47/68] Update note about ARM64 docker image + add docker hub links (#799) --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 286bea7..5ca2ee6 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,9 @@ performance reasons. ### Docker -#### NOTE: For ARM64/ARM support, please use [unixfox's image](https://quay.io/repository/unixfox/nitter?tab=tags), more info [here](https://github.com/zedeus/nitter/issues/399#issuecomment-997263495) +Page for the Docker image: https://hub.docker.com/r/zedeus/nitter + +#### NOTE: For ARM64 support, please use the separate ARM64 docker image: [`zedeus/nitter:latest-arm64`](https://hub.docker.com/r/zedeus/nitter/tags). To run Nitter with Docker, you'll need to install and run Redis separately before you can run the container. See below for how to also run Redis using @@ -122,6 +124,8 @@ docker build -t nitter:latest . docker run -v $(pwd)/nitter.conf:/src/nitter.conf -d --network host nitter:latest ``` +Note: For ARM64, use this Dockerfile: [`Dockerfile.arm64`](https://github.com/zedeus/nitter/blob/master/Dockerfile.arm64). + A prebuilt Docker image is provided as well: ```bash From 3a5faded86755f5cefd179375deb34fc93e704ab Mon Sep 17 00:00:00 2001 From: HookedBehemoth Date: Wed, 1 Mar 2023 00:53:44 +0100 Subject: [PATCH 48/68] parse recently added long tweets --- src/consts.nim | 2 +- src/parser.nim | 4 ++++ src/parserutils.nim | 42 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/consts.nim b/src/consts.nim index 18ecb2c..bb4e1a3 100644 --- a/src/consts.nim +++ b/src/consts.nim @@ -85,7 +85,7 @@ const "responsive_web_edit_tweet_api_enabled": false, "tweetypie_unmention_optimization_enabled": false, "vibe_api_enabled": false, - "longform_notetweets_consumption_enabled": false, + "longform_notetweets_consumption_enabled": true, "responsive_web_text_conversations_enabled": false, "responsive_web_enhance_cards_enabled": false, "interactive_text_enabled": false diff --git a/src/parser.nim b/src/parser.nim index 6a77a5f..f55f116 100644 --- a/src/parser.nim +++ b/src/parser.nim @@ -385,6 +385,10 @@ proc parseGraphTweet(js: JsonNode): Tweet = result = parseTweet(js{"legacy"}, jsCard) result.user = parseUser(js{"core", "user_results", "result", "legacy"}) + var note_tweet = js{"note_tweet", "note_tweet_results", "result"} + if note_tweet.kind != JNull: + result.expandNoteTweetEntities(note_tweet) + if result.quote.isSome: result.quote = some(parseGraphTweet(js{"quoted_status_result", "result"})) diff --git a/src/parserutils.nim b/src/parserutils.nim index af4d062..22c3d86 100644 --- a/src/parserutils.nim +++ b/src/parserutils.nim @@ -289,3 +289,45 @@ proc expandTweetEntities*(tweet: Tweet; js: JsonNode) = tweet.text = orig.replacedWith(replacements, textSlice) .strip(leading=false) + +proc expandNoteTweetEntities*(tweet: Tweet; noteTweet: JsonNode) = + let + text = noteTweet{"text"}.getStr + orig = text.toRunes + ent = ? noteTweet{"entity_set"} + hasCard = tweet.card.isSome + + var replacements = newSeq[ReplaceSlice]() + + with urls, ent{"urls"}: + for u in urls: + let urlStr = u["url"].getStr + if urlStr.len == 0 or urlStr notin text: + continue + replacements.extractUrls(u, orig.len, hideTwitter = false) + if hasCard and u{"url"}.getStr == get(tweet.card).url: + get(tweet.card).url = u{"expanded_url"}.getStr + + if "hashtags" in ent: + for hashtag in ent["hashtags"]: + replacements.extractHashtags(hashtag) + + if "symbols" in ent: + for symbol in ent["symbols"]: + replacements.extractHashtags(symbol) + + if "user_mentions" in ent: + for mention in ent["user_mentions"]: + let + name = mention{"screen_name"}.getStr + slice = mention.extractSlice + idx = tweet.reply.find(name) + + replacements.add ReplaceSlice(kind: rkMention, slice: slice, + url: "/" & name, display: mention["name"].getStr) + + replacements.deduplicate + replacements.sort(cmp) + + tweet.text = orig.replacedWith(replacements, 0..orig.len) + .strip(leading=false) From 368974c803858a88c4a327b2ad6ae5966cc3e239 Mon Sep 17 00:00:00 2001 From: HookedBehemoth Date: Wed, 1 Mar 2023 16:13:36 +0100 Subject: [PATCH 49/68] Update src/parser.nim Co-authored-by: Zed --- src/parser.nim | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/parser.nim b/src/parser.nim index f55f116..3858956 100644 --- a/src/parser.nim +++ b/src/parser.nim @@ -385,9 +385,8 @@ proc parseGraphTweet(js: JsonNode): Tweet = result = parseTweet(js{"legacy"}, jsCard) result.user = parseUser(js{"core", "user_results", "result", "legacy"}) - var note_tweet = js{"note_tweet", "note_tweet_results", "result"} - if note_tweet.kind != JNull: - result.expandNoteTweetEntities(note_tweet) + with noteTweet, js{"note_tweet", "note_tweet_results", "result"}: + result.expandNoteTweetEntities(noteTweet) if result.quote.isSome: result.quote = some(parseGraphTweet(js{"quoted_status_result", "result"})) From aea884c48ef1a429790e8c401e98548d2d6de841 Mon Sep 17 00:00:00 2001 From: Zed Date: Fri, 3 Mar 2023 21:19:21 +0100 Subject: [PATCH 50/68] Deduplicate note tweet parsing --- src/parser.nim | 4 +- src/parserutils.nim | 94 +++++++++++++++------------------------------ tests/test_card.py | 2 +- 3 files changed, 35 insertions(+), 65 deletions(-) diff --git a/src/parser.nim b/src/parser.nim index 3858956..a491cea 100644 --- a/src/parser.nim +++ b/src/parser.nim @@ -204,12 +204,12 @@ proc parseTweet(js: JsonNode; jsCard: JsonNode = newJNull()): Tweet = ) ) + result.expandTweetEntities(js) + # fix for pinned threads if result.hasThread and result.threadId == 0: result.threadId = js{"self_thread", "id_str"}.getId - result.expandTweetEntities(js) - if js{"is_quote_status"}.getBool: result.quote = some Tweet(id: js{"quoted_status_id_str"}.getId) diff --git a/src/parserutils.nim b/src/parserutils.nim index 22c3d86..8ae9cd0 100644 --- a/src/parserutils.nim +++ b/src/parserutils.nim @@ -230,47 +230,37 @@ proc expandUserEntities*(user: var User; js: JsonNode) = user.bio = user.bio.replacef(unRegex, unReplace) .replacef(htRegex, htReplace) -proc expandTweetEntities*(tweet: Tweet; js: JsonNode) = - let - orig = tweet.text.toRunes - textRange = js{"display_text_range"} - textSlice = textRange{0}.getInt .. textRange{1}.getInt - hasQuote = js{"is_quote_status"}.getBool - hasCard = tweet.card.isSome - - var replyTo = "" - if tweet.replyId != 0: - with reply, js{"in_reply_to_screen_name"}: - tweet.reply.add reply.getStr - replyTo = reply.getStr - - let ent = ? js{"entities"} +proc expandTextEntities(tweet: Tweet; entities: JsonNode; text: string; textSlice: Slice[int]; + replyTo=""; hasQuote=false) = + let hasCard = tweet.card.isSome var replacements = newSeq[ReplaceSlice]() - with urls, ent{"urls"}: + with urls, entities{"urls"}: for u in urls: let urlStr = u["url"].getStr - if urlStr.len == 0 or urlStr notin tweet.text: + if urlStr.len == 0 or urlStr notin text: continue + replacements.extractUrls(u, textSlice.b, hideTwitter = hasQuote) + if hasCard and u{"url"}.getStr == get(tweet.card).url: get(tweet.card).url = u{"expanded_url"}.getStr - with media, ent{"media"}: + with media, entities{"media"}: for m in media: replacements.extractUrls(m, textSlice.b, hideTwitter = true) - if "hashtags" in ent: - for hashtag in ent["hashtags"]: + if "hashtags" in entities: + for hashtag in entities["hashtags"]: replacements.extractHashtags(hashtag) - if "symbols" in ent: - for symbol in ent["symbols"]: + if "symbols" in entities: + for symbol in entities["symbols"]: replacements.extractHashtags(symbol) - if "user_mentions" in ent: - for mention in ent["user_mentions"]: + if "user_mentions" in entities: + for mention in entities["user_mentions"]: let name = mention{"screen_name"}.getStr slice = mention.extractSlice @@ -287,47 +277,27 @@ proc expandTweetEntities*(tweet: Tweet; js: JsonNode) = replacements.deduplicate replacements.sort(cmp) - tweet.text = orig.replacedWith(replacements, textSlice) - .strip(leading=false) + tweet.text = text.toRunes.replacedWith(replacements, textSlice).strip(leading=false) -proc expandNoteTweetEntities*(tweet: Tweet; noteTweet: JsonNode) = +proc expandTweetEntities*(tweet: Tweet; js: JsonNode) = let - text = noteTweet{"text"}.getStr - orig = text.toRunes - ent = ? noteTweet{"entity_set"} - hasCard = tweet.card.isSome + entities = ? js{"entities"} + hasQuote = js{"is_quote_status"}.getBool + textRange = js{"display_text_range"} + textSlice = textRange{0}.getInt .. textRange{1}.getInt - var replacements = newSeq[ReplaceSlice]() + var replyTo = "" + if tweet.replyId != 0: + with reply, js{"in_reply_to_screen_name"}: + replyTo = reply.getStr + tweet.reply.add replyTo - with urls, ent{"urls"}: - for u in urls: - let urlStr = u["url"].getStr - if urlStr.len == 0 or urlStr notin text: - continue - replacements.extractUrls(u, orig.len, hideTwitter = false) - if hasCard and u{"url"}.getStr == get(tweet.card).url: - get(tweet.card).url = u{"expanded_url"}.getStr + tweet.expandTextEntities(entities, tweet.text, textSlice, replyTo, hasQuote) - if "hashtags" in ent: - for hashtag in ent["hashtags"]: - replacements.extractHashtags(hashtag) +proc expandNoteTweetEntities*(tweet: Tweet; js: JsonNode) = + let + entities = ? js{"entity_set"} + text = js{"text"}.getStr + textSlice = 0..text.runeLen - if "symbols" in ent: - for symbol in ent["symbols"]: - replacements.extractHashtags(symbol) - - if "user_mentions" in ent: - for mention in ent["user_mentions"]: - let - name = mention{"screen_name"}.getStr - slice = mention.extractSlice - idx = tweet.reply.find(name) - - replacements.add ReplaceSlice(kind: rkMention, slice: slice, - url: "/" & name, display: mention["name"].getStr) - - replacements.deduplicate - replacements.sort(cmp) - - tweet.text = orig.replacedWith(replacements, 0..orig.len) - .strip(leading=false) + tweet.expandTextEntities(entities, text, textSlice) diff --git a/tests/test_card.py b/tests/test_card.py index 77e44e1..51945d6 100644 --- a/tests/test_card.py +++ b/tests/test_card.py @@ -42,7 +42,7 @@ no_thumb = [ ['nim_lang/status/1082989146040340480', 'Nim in 2018: A short recap', - '36 votes and 46 comments so far on Reddit', + 'Posted by u/miran1 - 36 votes and 46 comments', 'reddit.com'] ] From 725f601c9b006cd774024464caf4529068eb17a9 Mon Sep 17 00:00:00 2001 From: Zed Date: Sat, 4 Mar 2023 00:46:44 +0100 Subject: [PATCH 51/68] Add missing error codes for unavailable tweets --- src/parser.nim | 2 +- src/types.nim | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/parser.nim b/src/parser.nim index a491cea..977d579 100644 --- a/src/parser.nim +++ b/src/parser.nim @@ -301,7 +301,7 @@ proc parseGlobalObjects(js: JsonNode): GlobalObjects = proc parseStatus*(js: JsonNode): Tweet = with e, js{"errors"}: - if e.getError == tweetNotFound: + if e.getError in {tweetNotFound, tweetUnavailable, tweetCensored}: return result = parseTweet(js, js{"card"}) diff --git a/src/types.nim b/src/types.nim index 625dcb0..573fe8c 100644 --- a/src/types.nim +++ b/src/types.nim @@ -47,6 +47,8 @@ type forbidden = 200 badToken = 239 noCsrf = 353 + tweetUnavailable = 421 + tweetCensored = 422 User* = object id*: string From 56420a28bda8e8cbcef9c65e31cdb4d71c29bd15 Mon Sep 17 00:00:00 2001 From: Zed Date: Mon, 6 Mar 2023 00:22:27 +0100 Subject: [PATCH 52/68] Add another error code to parseStatus --- src/parser.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/parser.nim b/src/parser.nim index 977d579..daf7aea 100644 --- a/src/parser.nim +++ b/src/parser.nim @@ -301,7 +301,7 @@ proc parseGlobalObjects(js: JsonNode): GlobalObjects = proc parseStatus*(js: JsonNode): Tweet = with e, js{"errors"}: - if e.getError in {tweetNotFound, tweetUnavailable, tweetCensored}: + if e.getError in {tweetNotFound, tweetUnavailable, tweetCensored, doesntExist}: return result = parseTweet(js, js{"card"}) From ad9083149c75f7bf0cf20e3433a272ef3ff55c24 Mon Sep 17 00:00:00 2001 From: Zed Date: Mon, 6 Mar 2023 11:00:27 +0100 Subject: [PATCH 53/68] Add yet another status error code --- src/parser.nim | 2 +- src/types.nim | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/parser.nim b/src/parser.nim index daf7aea..3f39c3f 100644 --- a/src/parser.nim +++ b/src/parser.nim @@ -301,7 +301,7 @@ proc parseGlobalObjects(js: JsonNode): GlobalObjects = proc parseStatus*(js: JsonNode): Tweet = with e, js{"errors"}: - if e.getError in {tweetNotFound, tweetUnavailable, tweetCensored, doesntExist}: + if e.getError in {tweetNotFound, tweetUnavailable, tweetCensored, doesntExist, tweetNotAuthorized}: return result = parseTweet(js, js{"card"}) diff --git a/src/types.nim b/src/types.nim index 573fe8c..6f742d1 100644 --- a/src/types.nim +++ b/src/types.nim @@ -44,6 +44,7 @@ type invalidToken = 89 listIdOrSlug = 112 tweetNotFound = 144 + tweetNotAuthorized = 179 forbidden = 200 badToken = 239 noCsrf = 353 From 7edc5646fee5ad5171e9f3fd0c8d7d1b79bbfbcd Mon Sep 17 00:00:00 2001 From: Zed Date: Mon, 6 Mar 2023 11:06:27 +0100 Subject: [PATCH 54/68] And another one --- src/parser.nim | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/parser.nim b/src/parser.nim index 3f39c3f..fa877f9 100644 --- a/src/parser.nim +++ b/src/parser.nim @@ -301,7 +301,8 @@ proc parseGlobalObjects(js: JsonNode): GlobalObjects = proc parseStatus*(js: JsonNode): Tweet = with e, js{"errors"}: - if e.getError in {tweetNotFound, tweetUnavailable, tweetCensored, doesntExist, tweetNotAuthorized}: + if e.getError in {tweetNotFound, tweetUnavailable, tweetCensored, doesntExist, + tweetNotAuthorized, suspended}: return result = parseTweet(js, js{"card"}) From bc219aa792cc0e4117888b2036a969559f4f2689 Mon Sep 17 00:00:00 2001 From: Tommy Date: Mon, 6 Mar 2023 17:40:01 -0500 Subject: [PATCH 55/68] Change :ro to :Z (#735) * Change :ro to :Z * Update docker-compose.yml Co-authored-by: Mark Vainomaa --------- Co-authored-by: Mark Vainomaa --- docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-compose.yml b/docker-compose.yml index 50ae752..1cf4e09 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,7 +8,7 @@ services: ports: - "127.0.0.1:8080:8080" # Replace with "8080:8080" if you don't use a reverse proxy volumes: - - ./nitter.conf:/src/nitter.conf:ro + - ./nitter.conf:/src/nitter.conf:Z,ro depends_on: - nitter-redis restart: unless-stopped From e93de591181f1a796da869014891f226c6125a83 Mon Sep 17 00:00:00 2001 From: Jonas Chopin-Revel <45389356+JChopinRevel@users.noreply.github.com> Date: Tue, 28 Mar 2023 15:18:16 +0200 Subject: [PATCH 56/68] Edit Dockerfile (#763) Co-authored-by: Jonas Chopin-Revel --- Dockerfile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Dockerfile b/Dockerfile index f65c3ed..c100394 100644 --- a/Dockerfile +++ b/Dockerfile @@ -20,4 +20,6 @@ COPY --from=nim /src/nitter/nitter ./ COPY --from=nim /src/nitter/nitter.example.conf ./nitter.conf COPY --from=nim /src/nitter/public ./public EXPOSE 8080 +RUN adduser -h /src/ -D -s /bin/sh nitter +USER nitter CMD ./nitter From 23f4c6114c2b790405a9cefef1a7979655de44d4 Mon Sep 17 00:00:00 2001 From: Zed Date: Tue, 28 Mar 2023 16:03:15 +0200 Subject: [PATCH 57/68] Switch to BuildJet runners (#817) * Update deps * Use BuildJet runners to speed up arm64 --- .github/workflows/build-docker.yml | 34 ++++++++++++++++++++---------- nitter.nimble | 10 ++++----- 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/.github/workflows/build-docker.yml b/.github/workflows/build-docker.yml index 81d547a..c0c105e 100644 --- a/.github/workflows/build-docker.yml +++ b/.github/workflows/build-docker.yml @@ -8,36 +8,48 @@ on: - master jobs: - build-docker: - runs-on: ubuntu-latest + build-docker-amd64: + runs-on: buildjet-2vcpu-ubuntu-2204 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 with: fetch-depth: 0 - - name: Set up QEMU - uses: docker/setup-qemu-action@v1 - with: - platforms: all - name: Set up Docker Buildx id: buildx - uses: docker/setup-buildx-action@v1 + uses: docker/setup-buildx-action@v2 with: version: latest - name: Login to DockerHub - uses: docker/login-action@v1 + uses: docker/login-action@v2 with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} - name: Build and push AMD64 Docker image - uses: docker/build-push-action@v2 + uses: docker/build-push-action@v3 with: context: . file: ./Dockerfile platforms: linux/amd64 push: true tags: zedeus/nitter:latest,zedeus/nitter:${{ github.sha }} + build-docker-arm64: + runs-on: buildjet-2vcpu-ubuntu-2204-arm + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: Set up Docker Buildx + id: buildx + uses: docker/setup-buildx-action@v2 + with: + version: latest + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} - name: Build and push ARM64 Docker image - uses: docker/build-push-action@v2 + uses: docker/build-push-action@v3 with: context: . file: ./Dockerfile.arm64 diff --git a/nitter.nimble b/nitter.nimble index fdc1f9f..f9aa72a 100644 --- a/nitter.nimble +++ b/nitter.nimble @@ -12,17 +12,17 @@ bin = @["nitter"] requires "nim >= 1.4.8" requires "jester#baca3f" -requires "karax#0af2c85" +requires "karax#9ee695b" requires "sass#7dfdd03" -requires "nimcrypto#b41129f" +requires "nimcrypto#4014ef9" requires "markdown#158efe3" requires "packedjson#9e6fbb6" requires "supersnappy#6c94198" requires "redpool#8b7c1db" requires "https://github.com/zedeus/redis#d0a0e6f" -requires "zippy#123cd59" -requires "flatty#9f885d7" -requires "jsony#d0e69bd" +requires "zippy#ca5989a" +requires "flatty#e668085" +requires "jsony#ea811be" # Tasks From 78cb405acd192ee9391c2739f9edeab49c3ce797 Mon Sep 17 00:00:00 2001 From: Tommy Date: Tue, 28 Mar 2023 10:20:07 -0400 Subject: [PATCH 58/68] Additional hardening for Docker-Compose (#734) --- docker-compose.yml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docker-compose.yml b/docker-compose.yml index 1cf4e09..ec8ade5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -17,6 +17,12 @@ services: interval: 30s timeout: 5s retries: 2 + user: "998:998" + read_only: true + security_opt: + - no-new-privileges:true + cap_drop: + - ALL nitter-redis: image: redis:6-alpine @@ -30,6 +36,12 @@ services: interval: 30s timeout: 5s retries: 2 + user: "999:1000" + read_only: true + security_opt: + - no-new-privileges:true + cap_drop: + - ALL volumes: nitter-redis: From 95893eedaa2fb0ca0a0a15257d81b720f7f3eb67 Mon Sep 17 00:00:00 2001 From: Zed Date: Tue, 28 Mar 2023 17:36:48 +0200 Subject: [PATCH 59/68] Add actions workflow to run Selenium tests (#818) --- .github/workflows/build-docker.yml | 2 +- .github/workflows/run-tests.yml | 42 ++++++++++++++++++++++++++++++ tests/requirements.txt | 1 + 3 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/run-tests.yml create mode 100644 tests/requirements.txt diff --git a/.github/workflows/build-docker.yml b/.github/workflows/build-docker.yml index c0c105e..754f080 100644 --- a/.github/workflows/build-docker.yml +++ b/.github/workflows/build-docker.yml @@ -1,4 +1,4 @@ -name: CI/CD +name: Docker on: push: diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml new file mode 100644 index 0000000..d6315b3 --- /dev/null +++ b/.github/workflows/run-tests.yml @@ -0,0 +1,42 @@ +name: Run tests + +on: + push: + paths-ignore: + - "*.md" + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: Cache nimble + id: cache-nimble + uses: actions/cache@v3 + with: + path: ~/.nimble + key: nimble-${{ hashFiles('*.nimble') }} + restore-keys: "nimble-" + - uses: actions/setup-python@v4 + with: + python-version: "3.10" + cache: "pip" + - uses: jiro4989/setup-nim-action@v1 + with: + nim-version: "1.x" + - run: nimble build -d:release -Y + - run: pip install seleniumbase + - run: seleniumbase install chromedriver + - uses: supercharge/redis-github-action@1.5.0 + - name: Prepare Nitter + run: | + sudo apt install libsass-dev -y + cp nitter.example.conf nitter.conf + nimble md + nimble scss + - name: Run tests + run: | + ./nitter & + pytest -n4 tests diff --git a/tests/requirements.txt b/tests/requirements.txt new file mode 100644 index 0000000..56ea4c0 --- /dev/null +++ b/tests/requirements.txt @@ -0,0 +1 @@ +seleniumbase From e2560dc1f14173049ea80f7b8e2d69405dfc047d Mon Sep 17 00:00:00 2001 From: Zed Date: Fri, 21 Apr 2023 01:01:18 +0200 Subject: [PATCH 60/68] Prevent search endpoint from discarding tokens --- src/apiutils.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/apiutils.nim b/src/apiutils.nim index 917932a..96ace0c 100644 --- a/src/apiutils.nim +++ b/src/apiutils.nim @@ -108,7 +108,7 @@ proc fetch*(url: Uri; api: Api): Future[JsonNode] {.async.} = updateToken() let error = result.getError - if error in {invalidToken, forbidden, badToken}: + if error in {invalidToken, badToken}: echo "fetch error: ", result.getError release(token, invalid=true) raise rateLimitError() @@ -123,7 +123,7 @@ proc fetchRaw*(url: Uri; api: Api): Future[string] {.async.} = if result.startsWith("{\"errors"): let errors = result.fromJson(Errors) - if errors in {invalidToken, forbidden, badToken}: + if errors in {invalidToken, badToken}: echo "fetch error: ", errors release(token, invalid=true) raise rateLimitError() From 1ac389e7c75ced1762aa9c698ca2899cde668424 Mon Sep 17 00:00:00 2001 From: Zed Date: Fri, 21 Apr 2023 12:41:30 +0000 Subject: [PATCH 61/68] GraphQL timeline (#812) * Update deps * Replace profile timeline with GraphQL endpoint * Update GraphQL endpoint versions * Use GraphQL for profile media tab * Fix UserByRestId request * Improve routing, fixes #814 * Fix token pool JSON * Deduplicate GraphQL timeline endpoints * Update list endpoints * Use GraphQL for list tweets * Remove debug leftover * Replace old pinned tweet endpoint with GraphQL * Validate tweet ID * Minor token handling fix * Hide US-only commerce cards * Update config example * Remove http pool and gzip from token pool * Support tombstoned tweets in threads * Retry GraphQL timeout errors * Remove unnecessary 401 retry * Remove broken timeout retry * Update karax, use new bool attribute feature * Update card test * Fix odd edgecase with broken retweets * Replace search endpoints, switch Bearer token * Only parse user search if it's a list * Fix quoted tweet crash * Fix empty search query handling * Fix invalid user search errors again --- nitter.example.conf | 18 +-- nitter.nimble | 2 +- src/api.nim | 156 +++++++++++++----------- src/apiutils.nim | 20 ++- src/consts.nim | 129 ++++++++++++-------- src/experimental/parser.nim | 4 +- src/experimental/parser/graphql.nim | 1 + src/experimental/parser/timeline.nim | 30 ----- src/experimental/parser/unifiedcard.nim | 2 + src/experimental/parser/user.nim | 11 +- src/experimental/types/graphuser.nim | 1 + src/experimental/types/unifiedcard.nim | 6 +- src/http_pool.nim | 6 + src/nitter.nim | 14 ++- src/parser.nim | 134 ++++++++++++++++---- src/parserutils.nim | 2 +- src/redis_cache.nim | 2 +- src/routes/list.nim | 3 +- src/routes/rss.nim | 6 +- src/routes/search.nim | 8 +- src/routes/status.nim | 10 +- src/routes/timeline.nim | 15 +-- src/tokens.nim | 29 ++--- src/types.nim | 18 ++- src/views/renderutils.nim | 25 ++-- src/views/search.nim | 10 +- src/views/tweet.nim | 23 ++-- tests/test_card.py | 10 +- tests/test_profile.py | 11 -- 29 files changed, 405 insertions(+), 301 deletions(-) delete mode 100644 src/experimental/parser/timeline.nim diff --git a/nitter.example.conf b/nitter.example.conf index a7abea8..0d4deb7 100644 --- a/nitter.example.conf +++ b/nitter.example.conf @@ -1,11 +1,11 @@ [Server] +hostname = "nitter.net" # for generating links, change this to your own domain/ip +title = "nitter" address = "0.0.0.0" port = 8080 https = false # disable to enable cookies when not using https httpMaxConnections = 100 staticDir = "./public" -title = "nitter" -hostname = "nitter.net" [Cache] listMinutes = 240 # how long to cache list info (not the tweets, so keep it high) @@ -13,9 +13,9 @@ rssMinutes = 10 # how long to cache rss queries redisHost = "localhost" # Change to "nitter-redis" if using docker-compose redisPort = 6379 redisPassword = "" -redisConnections = 20 # connection pool size +redisConnections = 20 # minimum open connections in pool redisMaxConnections = 30 -# max, new connections are opened when none are available, but if the pool size +# new connections are opened when none are available, but if the pool size # goes above this, they're closed when released. don't worry about this unless # you receive tons of requests per second @@ -23,15 +23,15 @@ redisMaxConnections = 30 hmacKey = "secretkey" # random key for cryptographic signing of video urls base64Media = false # use base64 encoding for proxied media urls enableRSS = true # set this to false to disable RSS feeds -enableDebug = false # enable request logs and debug endpoints +enableDebug = false # enable request logs and debug endpoints (/.tokens) proxy = "" # http/https url, SOCKS proxies are not supported proxyAuth = "" tokenCount = 10 # minimum amount of usable tokens. tokens are used to authorize API requests, -# but they expire after ~1 hour, and have a limit of 187 requests. -# the limit gets reset every 15 minutes, and the pool is filled up so there's -# always at least $tokenCount usable tokens. again, only increase this if -# you receive major bursts all the time +# but they expire after ~1 hour, and have a limit of 500 requests per endpoint. +# the limits reset every 15 minutes, and the pool is filled up so there's +# always at least `tokenCount` usable tokens. only increase this if you receive +# major bursts all the time and don't have a rate limiting setup via e.g. nginx # Change default preferences here, see src/prefs_impl.nim for a complete list [Preferences] diff --git a/nitter.nimble b/nitter.nimble index f9aa72a..7771b31 100644 --- a/nitter.nimble +++ b/nitter.nimble @@ -12,7 +12,7 @@ bin = @["nitter"] requires "nim >= 1.4.8" requires "jester#baca3f" -requires "karax#9ee695b" +requires "karax#5cf360c" requires "sass#7dfdd03" requires "nimcrypto#4014ef9" requires "markdown#158efe3" diff --git a/src/api.nim b/src/api.nim index dfcf413..b23aa87 100644 --- a/src/api.nim +++ b/src/api.nim @@ -7,106 +7,82 @@ import experimental/parser as newParser proc getGraphUser*(username: string): Future[User] {.async.} = if username.len == 0: return let - variables = """{ - "screen_name": "$1", - "withSafetyModeUserFields": false, - "withSuperFollowsUserFields": false - }""" % [username] - js = await fetchRaw(graphUser ? {"variables": variables}, Api.userScreenName) + variables = %*{"screen_name": username} + params = {"variables": $variables, "features": gqlFeatures} + js = await fetchRaw(graphUser ? params, Api.userScreenName) result = parseGraphUser(js) proc getGraphUserById*(id: string): Future[User] {.async.} = if id.len == 0 or id.any(c => not c.isDigit): return let - variables = """{"userId": "$1", "withSuperFollowsUserFields": true}""" % [id] - js = await fetchRaw(graphUserById ? {"variables": variables}, Api.userRestId) + variables = %*{"userId": id} + params = {"variables": $variables, "features": gqlFeatures} + js = await fetchRaw(graphUserById ? params, Api.userRestId) result = parseGraphUser(js) +proc getGraphUserTweets*(id: string; kind: TimelineKind; after=""): Future[Timeline] {.async.} = + if id.len == 0: return + let + cursor = if after.len > 0: "\"cursor\":\"$1\"," % after else: "" + variables = userTweetsVariables % [id, cursor] + params = {"variables": variables, "features": gqlFeatures} + (url, apiId) = case kind + of TimelineKind.tweets: (graphUserTweets, Api.userTweets) + of TimelineKind.replies: (graphUserTweetsAndReplies, Api.userTweetsAndReplies) + of TimelineKind.media: (graphUserMedia, Api.userMedia) + js = await fetch(url ? params, apiId) + result = parseGraphTimeline(js, "user", after) + +proc getGraphListTweets*(id: string; after=""): Future[Timeline] {.async.} = + if id.len == 0: return + let + cursor = if after.len > 0: "\"cursor\":\"$1\"," % after else: "" + variables = listTweetsVariables % [id, cursor] + params = {"variables": variables, "features": gqlFeatures} + js = await fetch(graphListTweets ? params, Api.listTweets) + result = parseGraphTimeline(js, "list", after) + proc getGraphListBySlug*(name, list: string): Future[List] {.async.} = let - variables = %*{"screenName": name, "listSlug": list, "withHighlightedLabel": false} - url = graphListBySlug ? {"variables": $variables} - result = parseGraphList(await fetch(url, Api.listBySlug)) + variables = %*{"screenName": name, "listSlug": list} + params = {"variables": $variables, "features": gqlFeatures} + result = parseGraphList(await fetch(graphListBySlug ? params, Api.listBySlug)) proc getGraphList*(id: string): Future[List] {.async.} = let - variables = %*{"listId": id, "withHighlightedLabel": false} - url = graphList ? {"variables": $variables} - result = parseGraphList(await fetch(url, Api.list)) + variables = %*{"listId": id} + params = {"variables": $variables, "features": gqlFeatures} + result = parseGraphList(await fetch(graphListById ? params, Api.list)) proc getGraphListMembers*(list: List; after=""): Future[Result[User]] {.async.} = if list.id.len == 0: return var variables = %*{ "listId": list.id, - "withSuperFollowsUserFields": false, "withBirdwatchPivots": false, "withDownvotePerspective": false, "withReactionsMetadata": false, - "withReactionsPerspective": false, - "withSuperFollowsTweetFields": false + "withReactionsPerspective": false } if after.len > 0: variables["cursor"] = % after - let url = graphListMembers ? {"variables": $variables} + let url = graphListMembers ? {"variables": $variables, "features": gqlFeatures} result = parseGraphListMembers(await fetchRaw(url, Api.listMembers), after) -proc getListTimeline*(id: string; after=""): Future[Timeline] {.async.} = +proc getGraphTweetResult*(id: string): Future[Tweet] {.async.} = if id.len == 0: return let - ps = genParams({"list_id": id, "ranking_mode": "reverse_chronological"}, after) - url = listTimeline ? ps - result = parseTimeline(await fetch(url, Api.timeline), after) - -proc getTimeline*(id: string; after=""; replies=false): Future[Timeline] {.async.} = - if id.len == 0: return - let - ps = genParams({"userId": id, "include_tweet_replies": $replies}, after) - url = timeline / (id & ".json") ? ps - result = parseTimeline(await fetch(url, Api.timeline), after) - -proc getMediaTimeline*(id: string; after=""): Future[Timeline] {.async.} = - if id.len == 0: return - let url = mediaTimeline / (id & ".json") ? genParams(cursor=after) - result = parseTimeline(await fetch(url, Api.timeline), after) - -proc getPhotoRail*(name: string): Future[PhotoRail] {.async.} = - if name.len == 0: return - let - ps = genParams({"screen_name": name, "trim_user": "true"}, - count="18", ext=false) - url = photoRail ? ps - result = parsePhotoRail(await fetch(url, Api.timeline)) - -proc getSearch*[T](query: Query; after=""): Future[Result[T]] {.async.} = - when T is User: - const - searchMode = ("result_filter", "user") - parse = parseUsers - fetchFunc = fetchRaw - else: - const - searchMode = ("tweet_search_mode", "live") - parse = parseTimeline - fetchFunc = fetch - - let q = genQueryParam(query) - if q.len == 0 or q == emptyQuery: - return Result[T](beginning: true, query: query) - - let url = search ? genParams(searchParams & @[("q", q), searchMode], after) - try: - result = parse(await fetchFunc(url, Api.search), after) - result.query = query - except InternalError: - return Result[T](beginning: true, query: query) + variables = tweetResultVariables % id + params = {"variables": variables, "features": gqlFeatures} + js = await fetch(graphTweetResult ? params, Api.tweetResult) + result = parseGraphTweetResult(js) proc getGraphTweet(id: string; after=""): Future[Conversation] {.async.} = if id.len == 0: return let cursor = if after.len > 0: "\"cursor\":\"$1\"," % after else: "" variables = tweetVariables % [id, cursor] - params = {"variables": variables, "features": tweetFeatures} + params = {"variables": variables, "features": gqlFeatures} js = await fetch(graphTweet ? params, Api.tweetDetail) result = parseGraphConversation(js, id) @@ -119,9 +95,51 @@ proc getTweet*(id: string; after=""): Future[Conversation] {.async.} = if after.len > 0: result.replies = await getReplies(id, after) -proc getStatus*(id: string): Future[Tweet] {.async.} = - let url = status / (id & ".json") ? genParams() - result = parseStatus(await fetch(url, Api.status)) +proc getGraphSearch*(query: Query; after=""): Future[Result[Tweet]] {.async.} = + let q = genQueryParam(query) + if q.len == 0 or q == emptyQuery: + return Result[Tweet](query: query, beginning: true) + + var + variables = %*{ + "rawQuery": q, + "count": 20, + "product": "Latest", + "withDownvotePerspective": false, + "withReactionsMetadata": false, + "withReactionsPerspective": false + } + if after.len > 0: + variables["cursor"] = % after + let url = graphSearchTimeline ? {"variables": $variables, "features": gqlFeatures} + result = parseGraphSearch(await fetch(url, Api.search), after) + result.query = query + +proc getUserSearch*(query: Query; page="1"): Future[Result[User]] {.async.} = + if query.text.len == 0: + return Result[User](query: query, beginning: true) + + var url = userSearch ? { + "q": query.text, + "skip_status": "1", + "count": "20", + "page": page + } + + result = parseUsers(await fetchRaw(url, Api.userSearch)) + result.query = query + if page.len == 0: + result.bottom = "2" + elif page.allCharsInSet(Digits): + result.bottom = $(parseInt(page) + 1) + +proc getPhotoRail*(name: string): Future[PhotoRail] {.async.} = + if name.len == 0: return + let + ps = genParams({"screen_name": name, "trim_user": "true"}, + count="18", ext=false) + url = photoRail ? ps + result = parsePhotoRail(await fetch(url, Api.timeline)) proc resolve*(url: string; prefs: Prefs): Future[string] {.async.} = let client = newAsyncHttpClient(maxRedirects=0) diff --git a/src/apiutils.nim b/src/apiutils.nim index 96ace0c..dbc6cca 100644 --- a/src/apiutils.nim +++ b/src/apiutils.nim @@ -17,8 +17,8 @@ proc genParams*(pars: openArray[(string, string)] = @[]; cursor=""; result &= p if ext: result &= ("ext", "mediaStats") - result &= ("include_ext_alt_text", "true") - result &= ("include_ext_media_availability", "true") + result &= ("include_ext_alt_text", "1") + result &= ("include_ext_media_availability", "1") if count.len > 0: result &= ("count", count) if cursor.len > 0: @@ -44,7 +44,7 @@ proc genHeaders*(token: Token = nil): HttpHeaders = }) template updateToken() = - if api != Api.search and resp.headers.hasKey(rlRemaining): + if resp.headers.hasKey(rlRemaining): let remaining = parseInt(resp.headers[rlRemaining]) reset = parseInt(resp.headers[rlReset]) @@ -67,14 +67,9 @@ template fetchImpl(result, fetchBody) {.dirty.} = getContent() - # Twitter randomly returns 401 errors with an empty body quite often. - # Retrying the request usually works. - if resp.status == "401 Unauthorized" and result.len == 0: - getContent() - - if resp.status == $Http503: - badClient = true - raise newException(InternalError, result) + if resp.status == $Http503: + badClient = true + raise newException(BadClientError, "Bad client") if result.len > 0: if resp.headers.getOrDefault("content-encoding") == "gzip": @@ -90,6 +85,9 @@ template fetchImpl(result, fetchBody) {.dirty.} = raise newException(InternalError, $url) except InternalError as e: raise e + except BadClientError as e: + release(token, used=true) + raise e except Exception as e: echo "error: ", e.name, ", msg: ", e.msg, ", token: ", token[], ", url: ", url if "length" notin e.msg and "descriptor" notin e.msg: diff --git a/src/consts.nim b/src/consts.nim index bb4e1a3..27e82f9 100644 --- a/src/consts.nim +++ b/src/consts.nim @@ -1,30 +1,28 @@ # SPDX-License-Identifier: AGPL-3.0-only -import uri, sequtils +import uri, sequtils, strutils const - auth* = "Bearer AAAAAAAAAAAAAAAAAAAAAPYXBAAAAAAACLXUNDekMxqa8h%2F40K4moUkGsoc%3DTYfbDKbT3jJPCEVnMYqilB28NHfOPqkca3qaAxGfsyKCs0wRbw" + auth* = "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA" api = parseUri("https://api.twitter.com") activate* = $(api / "1.1/guest/activate.json") - userShow* = api / "1.1/users/show.json" photoRail* = api / "1.1/statuses/media_timeline.json" - status* = api / "1.1/statuses/show" - search* = api / "2/search/adaptive.json" - - timelineApi = api / "2/timeline" - timeline* = timelineApi / "profile" - mediaTimeline* = timelineApi / "media" - listTimeline* = timelineApi / "list.json" - tweet* = timelineApi / "conversation" + userSearch* = api / "1.1/users/search.json" graphql = api / "graphql" - graphTweet* = graphql / "6lWNh96EXDJCXl05SAtn_g/TweetDetail" - graphUser* = graphql / "7mjxD3-C6BxitPMVQ6w0-Q/UserByScreenName" - graphUserById* = graphql / "I5nvpI91ljifos1Y3Lltyg/UserByRestId" - graphList* = graphql / "JADTh6cjebfgetzvF3tQvQ/List" - graphListBySlug* = graphql / "ErWsz9cObLel1BF-HjuBlA/ListBySlug" - graphListMembers* = graphql / "Ke6urWMeCV2UlKXGRy4sow/ListMembers" + graphUser* = graphql / "8mPfHBetXOg-EHAyeVxUoA/UserByScreenName" + graphUserById* = graphql / "nI8WydSd-X-lQIVo6bdktQ/UserByRestId" + graphUserTweets* = graphql / "9rys0A7w1EyqVd2ME0QCJg/UserTweets" + graphUserTweetsAndReplies* = graphql / "ehMCHF3Mkgjsfz_aImqOsg/UserTweetsAndReplies" + graphUserMedia* = graphql / "MA_EP2a21zpzNWKRkaPBMg/UserMedia" + graphTweet* = graphql / "6I7Hm635Q6ftv69L8VrSeQ/TweetDetail" + graphTweetResult* = graphql / "rt-rHeSJ-2H9O9gxWQcPcg/TweetResultByRestId" + graphSearchTimeline* = graphql / "gkjsKepM6gl_HmFWoWKfgg/SearchTimeline" + graphListById* = graphql / "iTpgCtbdxrsJfyx0cFjHqg/ListByRestId" + graphListBySlug* = graphql / "-kmqNvm5Y-cVrfvBy6docg/ListBySlug" + graphListMembers* = graphql / "P4NpVZDqUD_7MEM84L-8nw/ListMembers" + graphListTweets* = graphql / "jZntL0oVJSdjhmPcdbw_eA/ListLatestTweetsTimeline" timelineParams* = { "include_profile_interstitial_type": "0", @@ -35,58 +33,85 @@ const "include_mute_edge": "0", "include_can_dm": "0", "include_can_media_tag": "1", + "include_ext_is_blue_verified": "1", "skip_status": "1", "cards_platform": "Web-12", "include_cards": "1", - "include_composer_source": "false", + "include_composer_source": "0", "include_reply_count": "1", "tweet_mode": "extended", - "include_entities": "true", - "include_user_entities": "true", - "include_ext_media_color": "false", - "send_error_codes": "true", - "simple_quoted_tweet": "true", - "include_quote_count": "true" + "include_entities": "1", + "include_user_entities": "1", + "include_ext_media_color": "0", + "send_error_codes": "1", + "simple_quoted_tweet": "1", + "include_quote_count": "1" }.toSeq - searchParams* = { - "query_source": "typed_query", - "pc": "1", - "spelling_corrections": "1" - }.toSeq - ## top: nothing - ## latest: "tweet_search_mode: live" - ## user: "result_filter: user" - ## photos: "result_filter: photos" - ## videos: "result_filter: videos" + gqlFeatures* = """{ + "blue_business_profile_image_shape_enabled": false, + "freedom_of_speech_not_reach_fetch_enabled": false, + "graphql_is_translatable_rweb_tweet_is_translatable_enabled": false, + "interactive_text_enabled": false, + "longform_notetweets_consumption_enabled": true, + "longform_notetweets_richtext_consumption_enabled": true, + "longform_notetweets_rich_text_read_enabled": false, + "responsive_web_edit_tweet_api_enabled": false, + "responsive_web_enhance_cards_enabled": false, + "responsive_web_graphql_exclude_directive_enabled": true, + "responsive_web_graphql_skip_user_profile_image_extensions_enabled": false, + "responsive_web_graphql_timeline_navigation_enabled": false, + "responsive_web_text_conversations_enabled": false, + "responsive_web_twitter_blue_verified_badge_is_enabled": true, + "spaces_2022_h2_clipping": true, + "spaces_2022_h2_spaces_communities": true, + "standardized_nudges_misinfo": false, + "tweet_awards_web_tipping_enabled": false, + "tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled": false, + "tweetypie_unmention_optimization_enabled": false, + "verified_phone_label_enabled": false, + "vibe_api_enabled": false, + "view_counts_everywhere_api_enabled": false +}""".replace(" ", "").replace("\n", "") tweetVariables* = """{ "focalTweetId": "$1", $2 - "includePromotedContent": false, "withBirdwatchNotes": false, + "includePromotedContent": false, + "withDownvotePerspective": false, + "withReactionsMetadata": false, + "withReactionsPerspective": false, + "withVoice": false +}""" + + tweetResultVariables* = """{ + "tweetId": "$1", + "includePromotedContent": false, + "withDownvotePerspective": false, + "withReactionsMetadata": false, + "withReactionsPerspective": false, + "withVoice": false, + "withCommunity": false +}""" + + userTweetsVariables* = """{ + "userId": "$1", $2 + "count": 20, + "includePromotedContent": false, "withDownvotePerspective": false, "withReactionsMetadata": false, "withReactionsPerspective": false, - "withSuperFollowsTweetFields": false, - "withSuperFollowsUserFields": false, "withVoice": false, "withV2Timeline": true }""" - tweetFeatures* = """{ - "graphql_is_translatable_rweb_tweet_is_translatable_enabled": false, - "responsive_web_graphql_timeline_navigation_enabled": false, - "standardized_nudges_misinfo": false, - "verified_phone_label_enabled": false, - "responsive_web_twitter_blue_verified_badge_is_enabled": false, - "tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled": false, - "view_counts_everywhere_api_enabled": false, - "responsive_web_edit_tweet_api_enabled": false, - "tweetypie_unmention_optimization_enabled": false, - "vibe_api_enabled": false, - "longform_notetweets_consumption_enabled": true, - "responsive_web_text_conversations_enabled": false, - "responsive_web_enhance_cards_enabled": false, - "interactive_text_enabled": false + listTweetsVariables* = """{ + "listId": "$1", $2 + "count": 20, + "includePromotedContent": false, + "withDownvotePerspective": false, + "withReactionsMetadata": false, + "withReactionsPerspective": false, + "withVoice": false }""" diff --git a/src/experimental/parser.nim b/src/experimental/parser.nim index 98ce7df..40986f5 100644 --- a/src/experimental/parser.nim +++ b/src/experimental/parser.nim @@ -1,2 +1,2 @@ -import parser/[user, graphql, timeline] -export user, graphql, timeline +import parser/[user, graphql] +export user, graphql diff --git a/src/experimental/parser/graphql.nim b/src/experimental/parser/graphql.nim index 4431db3..36014e3 100644 --- a/src/experimental/parser/graphql.nim +++ b/src/experimental/parser/graphql.nim @@ -11,6 +11,7 @@ proc parseGraphUser*(json: string): User = result = toUser raw.data.user.result.legacy result.id = raw.data.user.result.restId + result.verified = result.verified or raw.data.user.result.isBlueVerified proc parseGraphListMembers*(json, cursor: string): Result[User] = result = Result[User]( diff --git a/src/experimental/parser/timeline.nim b/src/experimental/parser/timeline.nim deleted file mode 100644 index 4663d00..0000000 --- a/src/experimental/parser/timeline.nim +++ /dev/null @@ -1,30 +0,0 @@ -import std/[strutils, tables] -import jsony -import user, ../types/timeline -from ../../types import Result, User - -proc getId(id: string): string {.inline.} = - let start = id.rfind("-") - if start < 0: return id - id[start + 1 ..< id.len] - -proc parseUsers*(json: string; after=""): Result[User] = - result = Result[User](beginning: after.len == 0) - - let raw = json.fromJson(Search) - if raw.timeline.instructions.len == 0: - return - - for i in raw.timeline.instructions: - if i.addEntries.entries.len > 0: - for e in i.addEntries.entries: - let id = e.entryId.getId - if e.entryId.startsWith("user"): - if id in raw.globalObjects.users: - result.content.add toUser raw.globalObjects.users[id] - elif e.entryId.startsWith("cursor"): - let cursor = e.content.operation.cursor - if cursor.cursorType == "Top": - result.top = cursor.value - elif cursor.cursorType == "Bottom": - result.bottom = cursor.value diff --git a/src/experimental/parser/unifiedcard.nim b/src/experimental/parser/unifiedcard.nim index 3c5158a..c9af437 100644 --- a/src/experimental/parser/unifiedcard.nim +++ b/src/experimental/parser/unifiedcard.nim @@ -84,6 +84,8 @@ proc parseUnifiedCard*(json: string): Card = component.parseMedia(card, result) of buttonGroup: discard + of ComponentType.hidden: + result.kind = CardKind.hidden of ComponentType.unknown: echo "ERROR: Unknown component type: ", json diff --git a/src/experimental/parser/user.nim b/src/experimental/parser/user.nim index 715c9a9..b4d710f 100644 --- a/src/experimental/parser/user.nim +++ b/src/experimental/parser/user.nim @@ -2,7 +2,7 @@ import std/[algorithm, unicode, re, strutils, strformat, options, nre] import jsony import utils, slices import ../types/user as userType -from ../../types import User, Error +from ../../types import Result, User, Error let unRegex = re.re"(^|[^A-z0-9-_./?])@([A-z0-9_]{1,15})" @@ -76,3 +76,12 @@ proc parseUser*(json: string; username=""): User = else: echo "[error - parseUser]: ", error result = toUser json.fromJson(RawUser) + +proc parseUsers*(json: string; after=""): Result[User] = + result = Result[User](beginning: after.len == 0) + + # starting with '{' means it's an error + if json[0] == '[': + let raw = json.fromJson(seq[RawUser]) + for user in raw: + result.content.add user.toUser diff --git a/src/experimental/types/graphuser.nim b/src/experimental/types/graphuser.nim index e13383a..478e7f3 100644 --- a/src/experimental/types/graphuser.nim +++ b/src/experimental/types/graphuser.nim @@ -11,4 +11,5 @@ type UserResult = object legacy*: RawUser restId*: string + isBlueVerified*: bool reason*: Option[string] diff --git a/src/experimental/types/unifiedcard.nim b/src/experimental/types/unifiedcard.nim index 4ec587c..6e83cad 100644 --- a/src/experimental/types/unifiedcard.nim +++ b/src/experimental/types/unifiedcard.nim @@ -17,6 +17,7 @@ type twitterListDetails communityDetails mediaWithDetailsHorizontal + hidden unknown Component* = object @@ -71,11 +72,11 @@ type Text = object content: string - HasTypeField = Component | Destination | MediaEntity | AppStoreData + TypeField = Component | Destination | MediaEntity | AppStoreData converter fromText*(text: Text): string = text.content -proc renameHook*(v: var HasTypeField; fieldName: var string) = +proc renameHook*(v: var TypeField; fieldName: var string) = if fieldName == "type": fieldName = "kind" @@ -89,6 +90,7 @@ proc enumHook*(s: string; v: var ComponentType) = of "twitter_list_details": twitterListDetails of "community_details": communityDetails of "media_with_details_horizontal": mediaWithDetailsHorizontal + of "commerce_drop_details": hidden else: echo "ERROR: Unknown enum value (ComponentType): ", s; unknown proc enumHook*(s: string; v: var AppType) = diff --git a/src/http_pool.nim b/src/http_pool.nim index 2037520..b4e3cee 100644 --- a/src/http_pool.nim +++ b/src/http_pool.nim @@ -42,5 +42,11 @@ template use*(pool: HttpPool; heads: HttpHeaders; body: untyped): untyped = except ProtocolError: # Twitter closed the connection, retry body + except BadClientError: + # Twitter returned 503, we need a new client + pool.release(c, true) + badClient = false + c = pool.acquire(heads) + body finally: pool.release(c, badClient) diff --git a/src/nitter.nim b/src/nitter.nim index 2e868a4..627af75 100644 --- a/src/nitter.nim +++ b/src/nitter.nim @@ -85,19 +85,23 @@ routes: resp Http500, showError( &"An error occurred, please {link} with the URL you tried to visit.", cfg) + error BadClientError: + echo error.exc.name, ": ", error.exc.msg + resp Http500, showError("Network error occured, please try again.", cfg) + error RateLimitError: const link = a("another instance", href = instancesUrl) resp Http429, showError( &"Instance has been rate limited.
Use {link} or try again later.", cfg) - extend unsupported, "" - extend preferences, "" - extend resolver, "" extend rss, "" + extend status, "" extend search, "" extend timeline, "" - extend list, "" - extend status, "" extend media, "" + extend list, "" + extend preferences, "" + extend resolver, "" extend embed, "" extend debug, "" + extend unsupported, "" diff --git a/src/parser.nim b/src/parser.nim index fa877f9..fe2fe5b 100644 --- a/src/parser.nim +++ b/src/parser.nim @@ -4,6 +4,8 @@ import packedjson, packedjson/deserialiser import types, parserutils, utils import experimental/parser/unifiedcard +proc parseGraphTweet(js: JsonNode): Tweet + proc parseUser(js: JsonNode; id=""): User = if js.isNull: return result = User( @@ -19,13 +21,20 @@ proc parseUser(js: JsonNode; id=""): User = tweets: js{"statuses_count"}.getInt, likes: js{"favourites_count"}.getInt, media: js{"media_count"}.getInt, - verified: js{"verified"}.getBool, + verified: js{"verified"}.getBool or js{"ext_is_blue_verified"}.getBool, protected: js{"protected"}.getBool, joinDate: js{"created_at"}.getTime ) result.expandUserEntities(js) +proc parseGraphUser(js: JsonNode): User = + let user = ? js{"user_results", "result"} + result = parseUser(user{"legacy"}) + + if "is_blue_verified" in user: + result.verified = true + proc parseGraphList*(js: JsonNode): List = if js.isNull: return @@ -38,11 +47,11 @@ proc parseGraphList*(js: JsonNode): List = result = List( id: list{"id_str"}.getStr, name: list{"name"}.getStr, - username: list{"user", "legacy", "screen_name"}.getStr, - userId: list{"user", "rest_id"}.getStr, + username: list{"user_results", "result", "legacy", "screen_name"}.getStr, + userId: list{"user_results", "result", "rest_id"}.getStr, description: list{"description"}.getStr, members: list{"member_count"}.getInt, - banner: list{"custom_banner_media", "media_info", "url"}.getImageStr + banner: list{"custom_banner_media", "media_info", "original_img_url"}.getImageStr ) proc parsePoll(js: JsonNode): Poll = @@ -213,10 +222,18 @@ proc parseTweet(js: JsonNode; jsCard: JsonNode = newJNull()): Tweet = if js{"is_quote_status"}.getBool: result.quote = some Tweet(id: js{"quoted_status_id_str"}.getId) + # legacy with rt, js{"retweeted_status_id_str"}: result.retweet = some Tweet(id: rt.getId) return + # graphql + with rt, js{"retweeted_status_result", "result"}: + # needed due to weird edgecase where the actual tweet data isn't included + if "legacy" in rt: + result.retweet = some parseGraphTweet(rt) + return + if jsCard.kind != JNull: let name = jsCard{"name"}.getStr if "poll" in name: @@ -237,7 +254,10 @@ proc parseTweet(js: JsonNode; jsCard: JsonNode = newJNull()): Tweet = of "video": result.video = some(parseVideo(m)) with user, m{"additional_media_info", "source_user"}: - result.attribution = some(parseUser(user)) + if user{"id"}.getInt > 0: + result.attribution = some(parseUser(user)) + else: + result.attribution = some(parseGraphUser(user)) of "animated_gif": result.gif = some(parseGif(m)) else: discard @@ -299,19 +319,6 @@ proc parseGlobalObjects(js: JsonNode): GlobalObjects = tweet.user = result.users[tweet.user.id] result.tweets[k] = tweet -proc parseStatus*(js: JsonNode): Tweet = - with e, js{"errors"}: - if e.getError in {tweetNotFound, tweetUnavailable, tweetCensored, doesntExist, - tweetNotAuthorized, suspended}: - return - - result = parseTweet(js, js{"card"}) - if not result.isNil: - result.user = parseUser(js{"user"}) - - with quote, js{"quoted_status"}: - result.quote = some parseStatus(js{"quoted_status"}) - proc parseInstructions[T](res: var Result[T]; global: GlobalObjects; js: JsonNode) = if js.kind != JArray or js.len == 0: return @@ -352,7 +359,7 @@ proc parseTimeline*(js: JsonNode; after=""): Timeline = result.top = e.getCursor elif "cursor-bottom" in entry: result.bottom = e.getCursor - elif entry.startsWith("sq-C"): + elif entry.startsWith("sq-cursor"): with cursor, e{"content", "operation", "cursor"}: if cursor{"cursorType"}.getStr == "Bottom": result.bottom = cursor{"value"}.getStr @@ -373,9 +380,20 @@ proc parsePhotoRail*(js: JsonNode): PhotoRail = result.add GalleryPhoto(url: url, tweetId: $t.id) proc parseGraphTweet(js: JsonNode): Tweet = - if js.kind == JNull or js{"__typename"}.getStr == "TweetUnavailable": + if js.kind == JNull: return Tweet(available: false) + case js{"__typename"}.getStr + of "TweetUnavailable": + return Tweet(available: false) + of "TweetTombstone": + return Tweet( + available: false, + text: js{"tombstone", "text"}.getTombstone + ) + of "TweetWithVisibilityResults": + return parseGraphTweet(js{"tweet"}) + var jsCard = copy(js{"card", "legacy"}) if jsCard.kind != JNull: var values = newJObject() @@ -384,7 +402,7 @@ proc parseGraphTweet(js: JsonNode): Tweet = jsCard["binding_values"] = values result = parseTweet(js{"legacy"}, jsCard) - result.user = parseUser(js{"core", "user_results", "result", "legacy"}) + result.user = parseGraphUser(js{"core"}) with noteTweet, js{"note_tweet", "note_tweet_results", "result"}: result.expandNoteTweetEntities(noteTweet) @@ -407,10 +425,14 @@ proc parseGraphThread(js: JsonNode): tuple[thread: Chain; self: bool] = if t{"item", "itemContent", "tweetDisplayType"}.getStr == "SelfThread": result.self = true +proc parseGraphTweetResult*(js: JsonNode): Tweet = + with tweet, js{"data", "tweetResult", "result"}: + result = parseGraphTweet(tweet) + proc parseGraphConversation*(js: JsonNode; tweetId: string): Conversation = result = Conversation(replies: Result[Chain](beginning: true)) - let instructions = ? js{"data", "threaded_conversation_with_injections_v2", "instructions"} + let instructions = ? js{"data", "threaded_conversation_with_injections", "instructions"} if instructions.len == 0: return @@ -418,12 +440,25 @@ proc parseGraphConversation*(js: JsonNode; tweetId: string): Conversation = let entryId = e{"entryId"}.getStr # echo entryId if entryId.startsWith("tweet"): - let tweet = parseGraphTweet(e{"content", "itemContent", "tweet_results", "result"}) + with tweetResult, e{"content", "itemContent", "tweet_results", "result"}: + let tweet = parseGraphTweet(tweetResult) - if not tweet.available: - tweet.id = parseBiggestInt(entryId.getId()) + if not tweet.available: + tweet.id = parseBiggestInt(entryId.getId()) - if $tweet.id == tweetId: + if $tweet.id == tweetId: + result.tweet = tweet + else: + result.before.content.add tweet + elif entryId.startsWith("tombstone"): + let id = entryId.getId() + let tweet = Tweet( + id: parseBiggestInt(id), + available: false, + text: e{"content", "itemContent", "tombstoneInfo", "richText"}.getTombstone + ) + + if id == tweetId: result.tweet = tweet else: result.before.content.add tweet @@ -435,3 +470,50 @@ proc parseGraphConversation*(js: JsonNode; tweetId: string): Conversation = result.replies.content.add thread elif entryId.startsWith("cursor-bottom"): result.replies.bottom = e{"content", "itemContent", "value"}.getStr + +proc parseGraphTimeline*(js: JsonNode; root: string; after=""): Timeline = + result = Timeline(beginning: after.len == 0) + + let instructions = + if root == "list": ? js{"data", "list", "tweets_timeline", "timeline", "instructions"} + else: ? js{"data", "user", "result", "timeline_v2", "timeline", "instructions"} + + if instructions.len == 0: + return + + for i in instructions: + if i{"type"}.getStr == "TimelineAddEntries": + for e in i{"entries"}: + let entryId = e{"entryId"}.getStr + if entryId.startsWith("tweet"): + with tweetResult, e{"content", "itemContent", "tweet_results", "result"}: + let tweet = parseGraphTweet(tweetResult) + if not tweet.available: + tweet.id = parseBiggestInt(entryId.getId()) + result.content.add tweet + elif entryId.startsWith("cursor-bottom"): + result.bottom = e{"content", "value"}.getStr + +proc parseGraphSearch*(js: JsonNode; after=""): Timeline = + result = Timeline(beginning: after.len == 0) + + let instructions = js{"data", "search_by_raw_query", "search_timeline", "timeline", "instructions"} + if instructions.len == 0: + return + + for instruction in instructions: + let typ = instruction{"type"}.getStr + if typ == "TimelineAddEntries": + for e in instructions[0]{"entries"}: + let entryId = e{"entryId"}.getStr + if entryId.startsWith("tweet"): + with tweetResult, e{"content", "itemContent", "tweet_results", "result"}: + let tweet = parseGraphTweet(tweetResult) + if not tweet.available: + tweet.id = parseBiggestInt(entryId.getId()) + result.content.add tweet + elif entryId.startsWith("cursor-bottom"): + result.bottom = e{"content", "value"}.getStr + elif typ == "TimelineReplaceEntry": + if instruction{"entry_id_to_replace"}.getStr.startsWith("cursor-bottom"): + result.bottom = instruction{"entry", "content", "value"}.getStr diff --git a/src/parserutils.nim b/src/parserutils.nim index 8ae9cd0..f28bd52 100644 --- a/src/parserutils.nim +++ b/src/parserutils.nim @@ -130,7 +130,7 @@ proc getBanner*(js: JsonNode): string = return proc getTombstone*(js: JsonNode): string = - result = js{"tombstoneInfo", "richText", "text"}.getStr + result = js{"text"}.getStr result.removeSuffix(" Learn more") proc getMp4Resolution*(url: string): int = diff --git a/src/redis_cache.nim b/src/redis_cache.nim index 742b7ae..89161be 100644 --- a/src/redis_cache.nim +++ b/src/redis_cache.nim @@ -153,7 +153,7 @@ proc getCachedTweet*(id: int64): Future[Tweet] {.async.} = if tweet != redisNil: tweet.deserialize(Tweet) else: - result = await getStatus($id) + result = await getGraphTweetResult($id) if not result.isNil: await cache(result) diff --git a/src/routes/list.nim b/src/routes/list.nim index c97b1c1..ac3e97e 100644 --- a/src/routes/list.nim +++ b/src/routes/list.nim @@ -6,7 +6,6 @@ import jester import router_utils import ".."/[types, redis_cache, api] import ../views/[general, timeline, list] -export getListTimeline, getGraphList template respList*(list, timeline, title, vnode: typed) = if list.id.len == 0 or list.name.len == 0: @@ -39,7 +38,7 @@ proc createListRouter*(cfg: Config) = let prefs = cookiePrefs() list = await getCachedList(id=(@"id")) - timeline = await getListTimeline(list.id, getCursor()) + timeline = await getGraphListTweets(list.id, getCursor()) vnode = renderTimelineTweets(timeline, prefs, request.path) respList(list, timeline, list.title, vnode) diff --git a/src/routes/rss.nim b/src/routes/rss.nim index 5da29b0..1323ed3 100644 --- a/src/routes/rss.nim +++ b/src/routes/rss.nim @@ -28,7 +28,7 @@ proc timelineRss*(req: Request; cfg: Config; query: Query): Future[Rss] {.async. var q = query q.fromUser = names profile = Profile( - tweets: await getSearch[Tweet](q, after), + tweets: await getGraphSearch(q, after), # this is kinda dumb user: User( username: name, @@ -78,7 +78,7 @@ proc createRssRouter*(cfg: Config) = if rss.cursor.len > 0: respRss(rss, "Search") - let tweets = await getSearch[Tweet](query, cursor) + let tweets = await getGraphSearch(query, cursor) rss.cursor = tweets.bottom rss.feed = renderSearchRss(tweets.content, query.text, genQueryUrl(query), cfg) @@ -159,7 +159,7 @@ proc createRssRouter*(cfg: Config) = let list = await getCachedList(id=id) - timeline = await getListTimeline(list.id, cursor) + timeline = await getGraphListTweets(list.id, cursor) rss.cursor = timeline.bottom rss.feed = renderListRss(timeline.content, list, cfg) diff --git a/src/routes/search.nim b/src/routes/search.nim index b2fd718..02c14e3 100644 --- a/src/routes/search.nim +++ b/src/routes/search.nim @@ -27,11 +27,15 @@ proc createSearchRouter*(cfg: Config) = of users: if "," in q: redirect("/" & q) - let users = await getSearch[User](query, getCursor()) + var users: Result[User] + try: + users = await getUserSearch(query, getCursor()) + except InternalError: + users = Result[User](beginning: true, query: query) resp renderMain(renderUserSearch(users, prefs), request, cfg, prefs, title) of tweets: let - tweets = await getSearch[Tweet](query, getCursor()) + tweets = await getGraphSearch(query, getCursor()) rss = "/search/rss?" & genQueryUrl(query) resp renderMain(renderTweetSearch(tweets, prefs, getPath()), request, cfg, prefs, title, rss=rss) diff --git a/src/routes/status.nim b/src/routes/status.nim index 1104282..7e89220 100644 --- a/src/routes/status.nim +++ b/src/routes/status.nim @@ -16,17 +16,21 @@ proc createStatusRouter*(cfg: Config) = router status: get "/@name/status/@id/?": cond '.' notin @"name" - cond not @"id".any(c => not c.isDigit) + let id = @"id" + + if id.len > 19 or id.any(c => not c.isDigit): + resp Http404, showError("Invalid tweet ID", cfg) + let prefs = cookiePrefs() # used for the infinite scroll feature if @"scroll".len > 0: - let replies = await getReplies(@"id", getCursor()) + let replies = await getReplies(id, getCursor()) if replies.content.len == 0: resp Http404, "" resp $renderReplies(replies, prefs, getPath()) - let conv = await getTweet(@"id", getCursor()) + let conv = await getTweet(id, getCursor()) if conv == nil: echo "nil conv" diff --git a/src/routes/timeline.nim b/src/routes/timeline.nim index a0a6e21..331b8ae 100644 --- a/src/routes/timeline.nim +++ b/src/routes/timeline.nim @@ -47,10 +47,10 @@ proc fetchProfile*(after: string; query: Query; skipRail=false; let timeline = case query.kind - of posts: getTimeline(userId, after) - of replies: getTimeline(userId, after, replies=true) - of media: getMediaTimeline(userId, after) - else: getSearch[Tweet](query, after) + of posts: getGraphUserTweets(userId, TimelineKind.tweets, after) + of replies: getGraphUserTweets(userId, TimelineKind.replies, after) + of media: getGraphUserTweets(userId, TimelineKind.media, after) + else: getGraphSearch(query, after) rail = skipIf(skipRail or query.kind == media, @[]): @@ -64,6 +64,7 @@ proc fetchProfile*(after: string; query: Query; skipRail=false; let tweet = await getCachedTweet(user.pinnedTweet) if not tweet.isNil: tweet.pinned = true + tweet.user = user pinned = some tweet result = Profile( @@ -82,7 +83,7 @@ proc showTimeline*(request: Request; query: Query; cfg: Config; prefs: Prefs; rss, after: string): Future[string] {.async.} = if query.fromUser.len != 1: let - timeline = await getSearch[Tweet](query, after) + timeline = await getGraphSearch(query, after) html = renderTweetSearch(timeline, prefs, getPath()) return renderMain(html, request, cfg, prefs, "Multi", rss=rss) @@ -123,7 +124,7 @@ proc createTimelineRouter*(cfg: Config) = get "/@name/?@tab?/?": cond '.' notin @"name" - cond @"name" notin ["pic", "gif", "video"] + cond @"name" notin ["pic", "gif", "video", "search", "settings", "login", "intent", "i"] cond @"tab" in ["with_replies", "media", "search", ""] let prefs = cookiePrefs() @@ -137,7 +138,7 @@ proc createTimelineRouter*(cfg: Config) = # used for the infinite scroll feature if @"scroll".len > 0: if query.fromUser.len != 1: - var timeline = await getSearch[Tweet](query, after) + var timeline = await getGraphSearch(query, after) if timeline.content.len == 0: resp Http404 timeline.beginning = true resp $renderTweetSearch(timeline, prefs, getPath()) diff --git a/src/tokens.nim b/src/tokens.nim index e6a4449..6ef81f5 100644 --- a/src/tokens.nim +++ b/src/tokens.nim @@ -1,8 +1,7 @@ # SPDX-License-Identifier: AGPL-3.0-only import asyncdispatch, httpclient, times, sequtils, json, random import strutils, tables -import zippy -import types, consts, http_pool +import types, consts const maxConcurrentReqs = 5 # max requests at a time per token, to avoid race conditions @@ -11,11 +10,12 @@ const failDelay = initDuration(minutes=30) var - clientPool: HttpPool tokenPool: seq[Token] lastFailed: Time enableLogging = false +let headers = newHttpHeaders({"authorization": auth}) + template log(str) = if enableLogging: echo "[tokens] ", str @@ -41,10 +41,12 @@ proc getPoolJson*(): JsonNode = let maxReqs = case api - of Api.listMembers, Api.listBySlug, Api.list, - Api.userRestId, Api.userScreenName, Api.tweetDetail: 500 of Api.timeline: 187 - else: 180 + of Api.listMembers, Api.listBySlug, Api.list, Api.listTweets, + Api.userTweets, Api.userTweetsAndReplies, Api.userMedia, + Api.userRestId, Api.userScreenName, + Api.tweetDetail, Api.tweetResult, Api.search: 500 + of Api.userSearch: 900 reqs = maxReqs - token.apis[api].remaining reqsPerApi[$api] = reqsPerApi.getOrDefault($api, 0) + reqs @@ -65,18 +67,12 @@ proc fetchToken(): Future[Token] {.async.} = if getTime() - lastFailed < failDelay: raise rateLimitError() - let headers = newHttpHeaders({ - "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", - "accept-encoding": "gzip", - "accept-language": "en-US,en;q=0.5", - "connection": "keep-alive", - "authorization": auth - }) + let client = newAsyncHttpClient(headers=headers) try: let - resp = clientPool.use(headers): await c.postContent(activate) - tokNode = parseJson(uncompress(resp))["guest_token"] + resp = await client.postContent(activate) + tokNode = parseJson(resp)["guest_token"] tok = tokNode.getStr($(tokNode.getInt)) time = getTime() @@ -86,6 +82,8 @@ proc fetchToken(): Future[Token] {.async.} = if "Try again" notin e.msg: echo "[tokens] fetching tokens paused, resuming in 30 minutes" lastFailed = getTime() + finally: + client.close() proc expired(token: Token): bool = let time = getTime() @@ -158,7 +156,6 @@ proc poolTokens*(amount: int) {.async.} = tokenPool.add newToken proc initTokenPool*(cfg: Config) {.async.} = - clientPool = HttpPool() enableLogging = cfg.enableDebug while true: diff --git a/src/types.nim b/src/types.nim index 6f742d1..4dca5f0 100644 --- a/src/types.nim +++ b/src/types.nim @@ -7,19 +7,28 @@ genPrefsType() type RateLimitError* = object of CatchableError InternalError* = object of CatchableError + BadClientError* = object of CatchableError + + TimelineKind* {.pure.} = enum + tweets + replies + media Api* {.pure.} = enum tweetDetail - userShow + tweetResult timeline search - tweet + userSearch list listBySlug listMembers + listTweets userRestId userScreenName - status + userTweets + userTweetsAndReplies + userMedia RateLimit* = object remaining*: int @@ -36,8 +45,10 @@ type null = 0 noUserMatches = 17 protectedUser = 22 + missingParams = 25 couldntAuth = 32 doesntExist = 34 + invalidParam = 47 userNotFound = 50 suspended = 63 rateLimited = 88 @@ -150,6 +161,7 @@ type imageDirectMessage = "image_direct_message" audiospace = "audiospace" newsletterPublication = "newsletter_publication" + hidden unknown Card* = object diff --git a/src/views/renderutils.nim b/src/views/renderutils.nim index cdfeb28..9dffdcb 100644 --- a/src/views/renderutils.nim +++ b/src/views/renderutils.nim @@ -59,8 +59,7 @@ proc buttonReferer*(action, text, path: string; class=""; `method`="post"): VNod proc genCheckbox*(pref, label: string; state: bool): VNode = buildHtml(label(class="pref-group checkbox-container")): text label - if state: input(name=pref, `type`="checkbox", checked="") - else: input(name=pref, `type`="checkbox") + input(name=pref, `type`="checkbox", checked=state) span(class="checkbox") proc genInput*(pref, label, state, placeholder: string; class=""; autofocus=true): VNode = @@ -68,20 +67,15 @@ proc genInput*(pref, label, state, placeholder: string; class=""; autofocus=true buildHtml(tdiv(class=("pref-group pref-input " & class))): if label.len > 0: label(`for`=pref): text label - if autofocus and state.len == 0: - input(name=pref, `type`="text", placeholder=p, value=state, autofocus="") - else: - input(name=pref, `type`="text", placeholder=p, value=state) + input(name=pref, `type`="text", placeholder=p, value=state, autofocus=(autofocus and state.len == 0)) proc genSelect*(pref, label, state: string; options: seq[string]): VNode = buildHtml(tdiv(class="pref-group pref-input")): label(`for`=pref): text label select(name=pref): for opt in options: - if opt == state: - option(value=opt, selected=""): text opt - else: - option(value=opt): text opt + option(value=opt, selected=(opt == state)): + text opt proc genDate*(pref, state: string): VNode = buildHtml(span(class="date-input")): @@ -93,12 +87,9 @@ proc genImg*(url: string; class=""): VNode = img(src=getPicUrl(url), class=class, alt="") proc getTabClass*(query: Query; tab: QueryKind): string = - result = "tab-item" - if query.kind == tab: - result &= " active" + if query.kind == tab: "tab-item active" + else: "tab-item" proc getAvatarClass*(prefs: Prefs): string = - if prefs.squareAvatars: - "avatar" - else: - "avatar round" + if prefs.squareAvatars: "avatar" + else: "avatar round" diff --git a/src/views/search.nim b/src/views/search.nim index 77ba14f..72c59f5 100644 --- a/src/views/search.nim +++ b/src/views/search.nim @@ -63,12 +63,10 @@ proc renderSearchPanel*(query: Query): VNode = hiddenField("f", "tweets") genInput("q", "", query.text, "Enter search...", class="pref-inline") button(`type`="submit"): icon "search" - if isPanelOpen(query): - input(id="search-panel-toggle", `type`="checkbox", checked="") - else: - input(id="search-panel-toggle", `type`="checkbox") - label(`for`="search-panel-toggle"): - icon "down" + + input(id="search-panel-toggle", `type`="checkbox", checked=isPanelOpen(query)) + label(`for`="search-panel-toggle"): icon "down" + tdiv(class="search-panel"): for f in @["filter", "exclude"]: span(class="search-title"): text capitalize(f) diff --git a/src/views/tweet.nim b/src/views/tweet.nim index ea94e28..3338b71 100644 --- a/src/views/tweet.nim +++ b/src/views/tweet.nim @@ -106,14 +106,10 @@ proc renderVideo*(video: Video; prefs: Prefs; path: string): VNode = else: vidUrl case playbackType of mp4: - if prefs.muteVideos: - video(poster=thumb, controls="", muted=""): - source(src=source, `type`="video/mp4") - else: - video(poster=thumb, controls=""): - source(src=source, `type`="video/mp4") + video(poster=thumb, controls="", muted=prefs.muteVideos): + source(src=source, `type`="video/mp4") of m3u8, vmap: - video(poster=thumb, data-url=source, data-autoload="false") + video(poster=thumb, data-url=source, data-autoload="false", muted=prefs.muteVideos) verbatim "
" tdiv(class="overlay-circle"): span(class="overlay-triangle") verbatim "
" @@ -127,14 +123,9 @@ proc renderGif(gif: Gif; prefs: Prefs): VNode = buildHtml(tdiv(class="attachments media-gif")): tdiv(class="gallery-gif", style={maxHeight: "unset"}): tdiv(class="attachment"): - let thumb = getSmallPic(gif.thumb) - let url = getPicUrl(gif.url) - if prefs.autoplayGifs: - video(class="gif", poster=thumb, controls="", autoplay="", muted="", loop=""): - source(src=url, `type`="video/mp4") - else: - video(class="gif", poster=thumb, controls="", muted="", loop=""): - source(src=url, `type`="video/mp4") + video(class="gif", poster=getSmallPic(gif.thumb), autoplay=prefs.autoplayGifs, + controls="", muted="", loop=""): + source(src=getPicUrl(gif.url), `type`="video/mp4") proc renderPoll(poll: Poll): VNode = buildHtml(tdiv(class="poll")): @@ -328,7 +319,7 @@ proc renderTweet*(tweet: Tweet; prefs: Prefs; path: string; class=""; index=0; if tweet.attribution.isSome: renderAttribution(tweet.attribution.get(), prefs) - if tweet.card.isSome: + if tweet.card.isSome and tweet.card.get().kind != hidden: renderCard(tweet.card.get(), prefs, path) if tweet.photos.len > 0: diff --git a/tests/test_card.py b/tests/test_card.py index 51945d6..da6ffde 100644 --- a/tests/test_card.py +++ b/tests/test_card.py @@ -3,11 +3,6 @@ from parameterized import parameterized card = [ - ['Thom_Wolf/status/1122466524860702729', - 'facebookresearch/fairseq', - 'Facebook AI Research Sequence-to-Sequence Toolkit written in Python. - GitHub - facebookresearch/fairseq: Facebook AI Research Sequence-to-Sequence Toolkit written in Python.', - 'github.com', True], - ['nim_lang/status/1136652293510717440', 'Version 0.20.0 released', 'We are very proud to announce Nim version 0.20. This is a massive release, both literally and figuratively. It contains more than 1,000 commits and it marks our release candidate for version 1.0!', @@ -25,6 +20,11 @@ card = [ ] no_thumb = [ + ['Thom_Wolf/status/1122466524860702729', + 'facebookresearch/fairseq', + 'Facebook AI Research Sequence-to-Sequence Toolkit written in Python. - GitHub - facebookresearch/fairseq: Facebook AI Research Sequence-to-Sequence Toolkit written in Python.', + 'github.com'], + ['brent_p/status/1088857328680488961', 'Hts Nim Sugar', 'hts-nim is a library that allows one to use htslib via the nim programming language. Nim is a garbage-collected language that compiles to C and often has similar performance. I have become very...', diff --git a/tests/test_profile.py b/tests/test_profile.py index e62f7b9..f9b5047 100644 --- a/tests/test_profile.py +++ b/tests/test_profile.py @@ -17,11 +17,6 @@ protected = [ invalid = [['thisprofiledoesntexist'], ['%']] -banner_color = [ - ['nim_lang', '22, 25, 32'], - ['rustlang', '35, 31, 32'] -] - banner_image = [ ['mobile_test', 'profile_banners%2F82135242%2F1384108037%2F1500x500'] ] @@ -74,12 +69,6 @@ class ProfileTest(BaseTestCase): self.open_nitter('user') self.assert_text('User "user" has been suspended') - @parameterized.expand(banner_color) - def test_banner_color(self, username, color): - self.open_nitter(username) - banner = self.find_element(Profile.banner + ' a') - self.assertIn(color, banner.value_of_css_property('background-color')) - @parameterized.expand(banner_image) def test_banner_image(self, username, url): self.open_nitter(username) From a64e2286d592b907eba6706ba0a8615b8161c4f1 Mon Sep 17 00:00:00 2001 From: Zed Date: Fri, 21 Apr 2023 17:41:48 +0200 Subject: [PATCH 62/68] Update badges --- .github/workflows/run-tests.yml | 2 +- README.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index d6315b3..ca93f30 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -1,4 +1,4 @@ -name: Run tests +name: Tests on: push: diff --git a/README.md b/README.md index 5ca2ee6..4f8235d 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # Nitter -[![Test Matrix](https://github.com/zedeus/nitter/workflows/CI/CD/badge.svg)](https://github.com/zedeus/nitter/actions?query=workflow%3ACI/CD) +[![Test Matrix](https://github.com/zedeus/nitter/workflows/Tests/badge.svg)](https://github.com/zedeus/nitter/actions/workflows/run-tests.yml) +[![Test Matrix](https://github.com/zedeus/nitter/workflows/Docker/badge.svg)](https://github.com/zedeus/nitter/actions/workflows/build-docker.yml) [![License](https://img.shields.io/github/license/zedeus/nitter?style=flat)](#license) A free and open source alternative Twitter front-end focused on privacy and From b67f3062fed36f78a827be4b31340ca79a6da4cf Mon Sep 17 00:00:00 2001 From: Zed Date: Fri, 21 Apr 2023 23:33:52 +0200 Subject: [PATCH 63/68] Fix card tests --- tests/test_card.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_card.py b/tests/test_card.py index da6ffde..78fe79c 100644 --- a/tests/test_card.py +++ b/tests/test_card.py @@ -76,7 +76,7 @@ class CardTest(BaseTestCase): c = Card(Conversation.main + " ") self.assert_text(title, c.title) self.assert_text(destination, c.destination) - self.assertIn('_img', self.get_image_url(c.image + ' img')) + self.assertIn('/pic/', self.get_image_url(c.image + ' img')) if len(description) > 0: self.assert_text(description, c.description) if large: @@ -99,7 +99,7 @@ class CardTest(BaseTestCase): c = Card(Conversation.main + " ") self.assert_text(title, c.title) self.assert_text(destination, c.destination) - self.assertIn('_img', self.get_image_url(c.image + ' img')) + self.assertIn('/pic/', self.get_image_url(c.image + ' img')) self.assert_element_visible('.card-overlay') if len(description) > 0: self.assert_text(description, c.description) From fe22a45c7e3221f9abd7106b304f1309c904b967 Mon Sep 17 00:00:00 2001 From: Zed Date: Fri, 21 Apr 2023 23:43:46 +0200 Subject: [PATCH 64/68] Make Docker workflow depend on tests --- .github/workflows/build-docker.yml | 4 ++++ .github/workflows/run-tests.yml | 3 +++ 2 files changed, 7 insertions(+) diff --git a/.github/workflows/build-docker.yml b/.github/workflows/build-docker.yml index 754f080..1250195 100644 --- a/.github/workflows/build-docker.yml +++ b/.github/workflows/build-docker.yml @@ -8,7 +8,10 @@ on: - master jobs: + tests: + uses: ./.github/workflows/run-tests.yml build-docker-amd64: + depends: [tests] runs-on: buildjet-2vcpu-ubuntu-2204 steps: - uses: actions/checkout@v3 @@ -33,6 +36,7 @@ jobs: push: true tags: zedeus/nitter:latest,zedeus/nitter:${{ github.sha }} build-docker-arm64: + depends: [tests] runs-on: buildjet-2vcpu-ubuntu-2204-arm steps: - uses: actions/checkout@v3 diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index ca93f30..140b6bf 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -4,6 +4,9 @@ on: push: paths-ignore: - "*.md" + branches-ignore: + - master + workflow_call: jobs: test: From 2254a0728c587ebcec51ff08da0bf145606a629e Mon Sep 17 00:00:00 2001 From: Zed Date: Fri, 21 Apr 2023 23:52:14 +0200 Subject: [PATCH 65/68] depends -> needs --- .github/workflows/build-docker.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build-docker.yml b/.github/workflows/build-docker.yml index 1250195..765e7a0 100644 --- a/.github/workflows/build-docker.yml +++ b/.github/workflows/build-docker.yml @@ -11,7 +11,7 @@ jobs: tests: uses: ./.github/workflows/run-tests.yml build-docker-amd64: - depends: [tests] + needs: [tests] runs-on: buildjet-2vcpu-ubuntu-2204 steps: - uses: actions/checkout@v3 @@ -36,7 +36,7 @@ jobs: push: true tags: zedeus/nitter:latest,zedeus/nitter:${{ github.sha }} build-docker-arm64: - depends: [tests] + needs: [tests] runs-on: buildjet-2vcpu-ubuntu-2204-arm steps: - uses: actions/checkout@v3 From 774063fb5a46633a1984900734b7300ecb1bfb4f Mon Sep 17 00:00:00 2001 From: Zed Date: Sat, 20 May 2023 00:52:55 +0200 Subject: [PATCH 66/68] Fix pinned "TweetPreviewDisplay" crash --- src/parser.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/parser.nim b/src/parser.nim index fe2fe5b..78f9bca 100644 --- a/src/parser.nim +++ b/src/parser.nim @@ -384,7 +384,7 @@ proc parseGraphTweet(js: JsonNode): Tweet = return Tweet(available: false) case js{"__typename"}.getStr - of "TweetUnavailable": + of "TweetUnavailable", "TweetPreviewDisplay": return Tweet(available: false) of "TweetTombstone": return Tweet( From b516ec367b41fad1185e3e408230cd61e24e2ea2 Mon Sep 17 00:00:00 2001 From: Zed Date: Sat, 20 May 2023 00:59:34 +0200 Subject: [PATCH 67/68] Remove outdated tweet from card test --- tests/test_card.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/tests/test_card.py b/tests/test_card.py index 78fe79c..696b9d5 100644 --- a/tests/test_card.py +++ b/tests/test_card.py @@ -35,11 +35,6 @@ no_thumb = [ 'A sample of a Qt app written using mostly nim. Contribute to sinkingsugar/nimqt-example development by creating an account on GitHub.', 'github.com'], - ['mobile_test/status/490378953744318464', - 'Nantasket Beach', - 'Explore this photo titled Nantasket Beach by Ben Sandofsky (@sandofsky) on 500px', - '500px.com'], - ['nim_lang/status/1082989146040340480', 'Nim in 2018: A short recap', 'Posted by u/miran1 - 36 votes and 46 comments', From e3b3b38a2d43a83b5fc2239ab41e864ee686fb2f Mon Sep 17 00:00:00 2001 From: Zed Date: Sat, 20 May 2023 02:10:37 +0200 Subject: [PATCH 68/68] Add proper tombstone for subscriber tweets --- src/consts.nim | 18 +++++++++++------- src/parser.nim | 13 ++++++------- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/src/consts.nim b/src/consts.nim index 27e82f9..f22581f 100644 --- a/src/consts.nim +++ b/src/consts.nim @@ -11,13 +11,13 @@ const userSearch* = api / "1.1/users/search.json" graphql = api / "graphql" - graphUser* = graphql / "8mPfHBetXOg-EHAyeVxUoA/UserByScreenName" - graphUserById* = graphql / "nI8WydSd-X-lQIVo6bdktQ/UserByRestId" - graphUserTweets* = graphql / "9rys0A7w1EyqVd2ME0QCJg/UserTweets" - graphUserTweetsAndReplies* = graphql / "ehMCHF3Mkgjsfz_aImqOsg/UserTweetsAndReplies" - graphUserMedia* = graphql / "MA_EP2a21zpzNWKRkaPBMg/UserMedia" - graphTweet* = graphql / "6I7Hm635Q6ftv69L8VrSeQ/TweetDetail" - graphTweetResult* = graphql / "rt-rHeSJ-2H9O9gxWQcPcg/TweetResultByRestId" + graphUser* = graphql / "pVrmNaXcxPjisIvKtLDMEA/UserByScreenName" + graphUserById* = graphql / "1YAM811Q8Ry4XyPpJclURQ/UserByRestId" + graphUserTweets* = graphql / "WzJjibAcDa-oCjCcLOotcg/UserTweets" + graphUserTweetsAndReplies* = graphql / "fn9oRltM1N4thkh5CVusPg/UserTweetsAndReplies" + graphUserMedia* = graphql / "qQoeS7szGavsi8-ehD2AWg/UserMedia" + graphTweet* = graphql / "miKSMGb2R1SewIJv2-ablQ/TweetDetail" + graphTweetResult* = graphql / "0kc0a_7TTr3dvweZlMslsQ/TweetResultByRestId" graphSearchTimeline* = graphql / "gkjsKepM6gl_HmFWoWKfgg/SearchTimeline" graphListById* = graphql / "iTpgCtbdxrsJfyx0cFjHqg/ListByRestId" graphListBySlug* = graphql / "-kmqNvm5Y-cVrfvBy6docg/ListBySlug" @@ -50,10 +50,13 @@ const gqlFeatures* = """{ "blue_business_profile_image_shape_enabled": false, + "creator_subscriptions_tweet_preview_api_enabled": true, "freedom_of_speech_not_reach_fetch_enabled": false, "graphql_is_translatable_rweb_tweet_is_translatable_enabled": false, + "highlights_tweets_tab_ui_enabled": false, "interactive_text_enabled": false, "longform_notetweets_consumption_enabled": true, + "longform_notetweets_inline_media_enabled": false, "longform_notetweets_richtext_consumption_enabled": true, "longform_notetweets_rich_text_read_enabled": false, "responsive_web_edit_tweet_api_enabled": false, @@ -63,6 +66,7 @@ const "responsive_web_graphql_timeline_navigation_enabled": false, "responsive_web_text_conversations_enabled": false, "responsive_web_twitter_blue_verified_badge_is_enabled": true, + "rweb_lists_timeline_redesign_enabled": true, "spaces_2022_h2_clipping": true, "spaces_2022_h2_spaces_communities": true, "standardized_nudges_misinfo": false, diff --git a/src/parser.nim b/src/parser.nim index 78f9bca..5ec21e4 100644 --- a/src/parser.nim +++ b/src/parser.nim @@ -381,16 +381,15 @@ proc parsePhotoRail*(js: JsonNode): PhotoRail = proc parseGraphTweet(js: JsonNode): Tweet = if js.kind == JNull: - return Tweet(available: false) + return Tweet() case js{"__typename"}.getStr - of "TweetUnavailable", "TweetPreviewDisplay": - return Tweet(available: false) + of "TweetUnavailable": + return Tweet() of "TweetTombstone": - return Tweet( - available: false, - text: js{"tombstone", "text"}.getTombstone - ) + return Tweet(text: js{"tombstone", "text"}.getTombstone) + of "TweetPreviewDisplay": + return Tweet(text: "You're unable to view this Tweet because it's only available to the Subscribers of the account owner.") of "TweetWithVisibilityResults": return parseGraphTweet(js{"tweet"})