PageSourceSearch

https://www.cdn.tv2.no/s/aws/15/video-gate/production/tv2no-video-gate.umd.js?v=4.0.770

js tv2.no collected 2026-10-01 08:39:44 UTC 697,763 bytes, 23 lines download raw bytes

1!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TV2VideoGate={})}(this,function(t){"use strict";function e(t,e,i,s){return new(i||(i=Promise))(function(r,n){function a(t){try{l(s.next(t))}catch(t){n(t)}}function o(t){try{l(s.throw(t))}catch(t){n(t)}}function l(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(a,o)}l((s=s.apply(t,e||[])).next())})}function i(t,e,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(t):s?s.value:e.get(t)}function s(t,e,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const r={prod:"https://www.tv2.no",stage:"https://www.stage.tv2.no",dev:"https://www.stage.tv2.no",local:"https://www.stage.tv2.no"},n="application/x-mpegurl",a=({imageUrl:t,compression:e,width:i,height:s})=>t?`https://www.cdn.tv2.no/images/?imageUrl=${encodeURIComponent(t)}${void 0!==i?"&width="+i:""}${void 0!==s?"&height="+s:""}${void 0!==e?"&compression="+e:""}`:void 0,o=()=>600,l="undefined"!=typeof document&&"undefined"!=typeof window&&"undefined"!=typeof HTMLElement,d=t=>{var e;return(null===(e=null==t?void 0:t.images)||void 0===e?void 0:e.defaultUrl)?a({imageUrl:`${t.images.defaultUrl}?location=frontbilde`,width:600}):void 0},c=(t,e)=>t>0?Math.min(100,Math.max(0,100*e/t)):0;var u,h;const f=["ERROR","WARN","INFO","LOG","DEBUG"];let g=class{static setLogLevel(t="ERROR"){s(u,u,t,"f",h),"DEBUG"===i(u,u,"f",h)&&u.special("=== Logger debug mode enabled ===")}static getColorScheme(){var t;return l&&(null===(t=window.matchMedia)||void 0===t?void 0:t.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"}static getColorByLevel(t){const e=u.getColorScheme();switch(t){case"LOG":case"DEBUG":return"dark"===e?"#B0BEC5":"#37474F";case"INFO":return"dark"===e?"#82B1FF":"#0D47A1";case"WARN":return"dark"===e?"#FFD54F":"#FF6F00";case"ERROR":return"dark"===e?"#FF8A80":"#D32F2F";default:return"dark"===e?"white":"black"}}static logMessage(t,e,...s){if(!(f.indexOf(t)<=f.indexOf(i(u,u,"f",h))))return;const r=`%c[${t}]${e}`,n=`color: ${u.getColorByLevel(t)};`,a=`font-size: 32px;color: ${u.getColorByLevel("SPECIAL")}; font-weight: bold;`,o=`%c${e}`;switch(t){case"LOG":console.log(`${r}`,n,...s);break;case"INFO":console.info(`${r}`,n,...s);break;case"WARN":console.warn(`${r}`,n,...s);break;case"ERROR":console.error(`${r}`,n,...s);break;case"DEBUG":console.debug(`${r}`,n,...s);break;default:console.log(`${o}`,a,...s)}}static log(t,...e){u.logMessage("LOG",t,...e)}static info(t,...e){u.logMessage("INFO",t,...e)}static warn(t,...e){u.logMessage("WARN",t,...e)}static error(t,...e){u.logMessage("ERROR",t,...e)}static debug(t,...e){u.logMessage("DEBUG",t,...e)}static special(t,...e){u.logMessage("SPECIAL",t,...e)}};var m,p,v;u=g,h={value:"ERROR"};class y{constructor(t,n){m.set(this,void 0),p.set(this,void 0),this.fetchAsset=(t,s)=>e(this,void 0,void 0,function*(){try{const e=yield i(this,m,"f").assetService.fetchAssetByAssetIdOrLegacyAssetId(t,!0);return e?Object.assign(Object.assign({},e),{href:this.getAssetUrl(e,s)}):void 0}catch(t){return void g.error("Failed to fetch asset:",t)}}),this.getAssetUrl=(t,e)=>(null==e?void 0:e.videoReelUrl)?e.videoReelUrl:`${r[i(this,p,"f")]}${i(this,m,"f").urlService.getAssetUrl(t,null==e?void 0:e.playlistId)}`,s(this,m,t,"f"),s(this,p,n,"f")}getPlayRequest(t,s){return e(this,void 0,void 0,function*(){try{return yield i(this,m,"f").playService.createPlayRequest(t,s)}catch(t){return void g.error("Failed to fetch play request:",t)}})}}m=new WeakMap,p=new WeakMap,function(t){t.News="nyheter",t.Sport="sport",t.Entertainment="underholdning",t.Serier="serier",t.Broom="broom",t.Live="live"}(v||(v={}));var E={nyheter:v.News,underholdning:v.Entertainment,serier:v.Serier,sport:v.Sport,broom:v.Broom,live:v.Live},T=function(){return T=Object.assign||function(t){for(var e,i=1,s=arguments.length;i<s;i++)for(var r in e=arguments[i])Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t},T.apply(this,arguments)};
1function S(t,e,i,s){return new(i||(i=Promise))(function(r,n){function a(t){try{l(s.next(t))}catch(t){n(t)}}function o(t){try{l(s.throw(t))}catch(t){n(t)}}function l(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(a,o)}l((s=s.apply(t,e||[])).next())})}function b(t,e){var i,s,r,n={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;a&&(a=0,o[0]&&(n=0)),n;)try{if(i=1,s&&(r=2&o[0]?s.return:o[0]?s.throw||((r=s.return)&&r.call(s),0):s.next)&&!(r=r.call(s,o[1])).done)return r;switch(s=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return n.label++,{value:o[1],done:!1};case 5:n.label++,s=o[1],o=[0];continue;case 7:o=n.ops.pop(),n.trys.pop();continue;default:if(!((r=(r=n.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){n=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){n.label=o[1];break}if(6===o[0]&&n.label<r[1]){n.label=r[1],r=o;break}if(r&&n.label<r[2]){n.label=r[2],n.ops.push(o);break}r[2]&&n.ops.pop(),n.trys.pop();continue}o=e.call(t,n)}catch(t){o=[6,t],s=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}function A(t,e,i){for(var s,r=0,n=e.length;r<n;r++)!s&&r in e||(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))}"function"==typeof SuppressedError&&SuppressedError;var k="9:16",L="main",I=function(t){var e,i,s=E.live,r=E.sport;if(t.isLive)return s;var n=null!==(i=null===(e=t["type-of-action"])||void 0===e?void 0:e.toLowerCase())&&void 0!==i?i:"";for(var a in E)if(n.includes(a))return E[a];return r},w=function(t){return t===k?L:k},R=function(t){return null==t?void 0:t["cop-asset-id"]},_=function(){function t(){}return t.mapToAsset=function(e){var i,s,r;return{id:e.id,title:e.title,noindex:e.noindex,timestamp:e.timestamp,createTime:e.createTime,images:{defaultUrl:null===(i=e.images)||void 0===i?void 0:i.defaultUrl},category:{path:null===(s=e.category)||void 0===s?void 0:s.path,id:null===(r=e.category)||void 0===r?void 0:r.id},duration:e.duration||0,assetType:e.assetType,description:e.description,"description-short":e["description-short"],"ad-path":e["ad-path"],"external-asset-id":e["external-asset-id"],keywords:e.keywords,"tv2-gpid":e["tv2-gpid"],"loop-url":e["loop-url"],sportType:e.sportType,"home-team":e["home-team"],"away-team":e["away-team"],"game-score":e["game-score"],"match-name":e["match-name"],"player-name":e["player-name"],tournamentTitle:e.tournamentTitle,"players-team-name":e["players-team-name"],"type-of-action":e["type-of-action"],"event-occurrence-time":e["event-occurrence-time"],"video-type":e["video-type"],"seo-title":e["seo-title"],"ingress-url":e["ingress-url"],"ingress-url-text":e["ingress-url-text"],"tv2-bug":e["tv2-bug"],"engagement-refs":e["engagement-refs"],"tv2-player-id":e["tv2-player-id"],"tv2-player-team-id":e["tv2-player-team-id"],"team-id-home":e["team-id-home"],"team-id-away":e["team-id-away"],incidentType:e.incidentType,isLive:e.isLive,assetLists:e.assetLists,bylines:e.bylines,linkedVersion:e.linkedVersion?t.mapToAsset(e.linkedVersion):void 0}},t}(),D=function(){function t(t){var e=this;this.apiUrl=t,this._queryParts=[],this.useDefaultSort=!0,this.request=function(t){return!t.skipDefaultAssetType&&!t.assetType&&!t.query&&e.assetType(k),t.typeOfAction&&e.typeOfAction(t.typeOfAction),t.clipType&&e.clipType(t.clipType),t.sportType&&e.sportType(t.sportType),t.incidentType&&e.incidentType(t.incidentType),t.tournamentId&&e.tournamentId(t.tournamentId),t.eventId&&e.eventId(t.eventId),t.teamId&&e.teamId(t.teamId),t.playerTeamId&&e.playerTeamId(t.playerTeamId),t.headToHead&&e.headToHead(t.headToHead),t.playerId&&e.playerId(t.playerId),t.teamName&&e.teamName(t.teamName),t.homeTeam&&e.homeTeam(t.homeTeam),t.awayTeam&&e.awayTeam(t.awayTeam),(t.fromDate||t.toDate)&&e.datePeriod(t.fromDate,t.toDate),t.assetType&&e.assetType(t.assetType),t.videoType&&e.videoType(t.videoType),t.tag&&e.tag(t.tag),t.tagAnd&&e.tagAnd(t.tagAnd),t.tagNot&&e.tagNot(t.tagNot),t.legacyAssetId&&e.legacyAssetId(t.legacyAssetId),t.title&&e.title(t.title),t.description&&e.description(t.description),t.titleOrDescription&&e.titleOrDescription(t.titleOrDescription),t.isLive&&e.isLive(),t.query&&e.query(t.query),t.categoryId&&e.categoryId(t.categoryId),t.sort&&e.sort(t.sort),t.fields&&e.fields(t.fields),t.pageSize&&e.pageSize(t.pageSize),t.pageNumber&&e.pageNumber(t.pageNumber),t.id&&t.id&&e.id(t.id),t.copAssetId&&t.copAssetId&&e.copAssetId(t.copAssetId),e},this.typeOfAction=function(t){var i=Array.isArray(t)?t:[t];return e._queryParts.push(i.map(function(t){return"type-of-action:".concat(t)}).join(" OR ")),e},this.clipType=function(t){var i=Array.isArray(t)?t:[t];return e._queryParts.push(i.map(function(t){return"clipType:".concat(t)}).join(" OR ")),e},this.sportType=function(t){return e._queryParts.push("sportType:".concat(t)),e},this.incidentType=function(t){var i=Array.isArray(t)?t:[t];return e._queryParts.push(i.map(function(t){return"incidentType:".concat(t)}).join(" OR ")),e},this.tournamentId=function(t){var i=Array.isArray(t)?t:[t];return e._queryParts.push(i.map(function(t){return'tv2-tournament-id:"'.concat(t,'"')}).join(" OR ")),e},this.eventId=function(t){var i=Array.isArray(t)?t:[t];return e._queryParts.push(i.map(function(t){return'tv2-match-id:"'.concat(t,'"')}).join(" OR ")),e},this.teamId=function(t){var i=Array.isArray(t)?t:[t];return e._queryParts.push(i.map(function(t){return'team-id-home:"'.concat(t,'" OR team-id-away:"').concat(t,'"')}).join(" OR ")),e},this.playerTeamId=function(t){return e._queryParts.push('tv2-player-team-id:"'.concat(t,'"')),e},this.headToHead=function(t){if(2!==t.length)throw new Error("headToHead: requires two team ids");return e._queryParts.push('(team-id-home:"'.concat(t[0],'" AND team-id-away:"').concat(t[1],'") OR (team-id-home:"').concat(t[1],'" AND team-id-away:"').concat(t[0],'")')),e},this.playerId=function(t){var i=Array.isArray(t)?t:[t];return e._queryParts.push(i.map(function(t){return'tv2-player-id:"'.concat(t,'"')}).join(" OR ")),e},this.teamName=function(t){return e._queryParts.push('(home-team:"'.concat(t,'" OR away-team:"').concat(t,'")')),e},this.homeTeam=function(t){return e._queryParts.push('home-team:"'.concat(t,'"')),e},this.awayTeam=function(t){return e._queryParts.push('away-team:"'.concat(t,'"')),e},this.datePeriod=function(t,i,s){var r,n;return e._queryParts.push("event-occurrence-time:[".concat(null!==(r=null==t?void 0:t.toISOString())&&void 0!==r?r:"now-20y","+TO+").concat(null!==(n=null==i?void 0:i.toISOString())&&void 0!==n?n:"now+1y","]")),e},this.assetType=function(t){var i=Array.isArray(t)?t:[t];return e._queryParts.push(i.map(function(t){return'assetType:"'.concat(t,'"')}).join(" OR ")),e},this.videoType=function(t){return e._queryParts.push('video-type:"'.concat(t,'"')),e},this.tag=function(t){var i=Array.isArray(t)?t:[t];return e._queryParts.push(i.map(function(t){return'(keywords:"'.concat(t,'" OR keywords:" ').concat(t,'")')}).join(" OR ")),e},this.tagAnd=function(t){var i=Array.isArray(t)?t:[t];return e._queryParts.push(i.map(function(t){return'(keywords:"'.concat(t,'" OR keywords:" ').concat(t,'")')}).join(" AND ")),e},this.tagNot=function(t){var i=Array.isArray(t)?t:[t];return e._queryParts.push(i.map(function(t){return'-keywords:"'.concat(t,'" AND -keywords:" ').concat(t,'"')}).join(" AND ")),e},this.legacyAssetId=function(t){return e._queryParts.push("legacyAssetId:".concat(t)),e},this.assetIdOrlegacyAssetId=function(t){return e._queryParts.push("id:".concat(t," OR legacyAssetId:").concat(t)),e.useDefaultSort=!1,e},this.isLive=function(){return e._queryParts.push("isLive:true"),e},this.query=function(t){return e._url.searchParams.set("query",t),e},this.title=function(t){return e._queryParts.push('title:"'.concat(t,'"~')),e.useDefaultSort=!1,e},this.description=function(t){return e._queryParts.push('description-short:"'.concat(t,'"~')),e.useDefaultSort=!1,e},this.titleOrDescription=function(t){return e._queryParts.push('title:"'.concat(t,'" OR description-short:"').concat(t,'"')),e.useDefaultSort=!1,e},this.id=function(t){var i=Array.isArray(t)?t:[t];return e._queryParts.push(i.map(function(t){return'id:"'.concat(t,'"')}).join(" OR ")),e},this.categoryId=function(t){return e._queryParts.push("category.id:".concat(t)),e},this.externalAssetId=function(t){return e._queryParts.push('external-asset-id:"'.concat(t.startsWith("2_")?t:"2_".concat(t),'"')),e},this.copAssetId=function(t){var i=Array.isArray(t)?t:[t];return e._queryParts.push(i.map(function(t){return'cop-asset-id:"'.concat(t,'"')}).join(" OR ")),e},this.fields=function(t){return e._url.searchParams.set("fields",t.join(",")),e},this.sort=function(t){return e._url.searchParams.set("sort",t),e.useDefaultSort=!1,e},this.pageSize=function(t){return e._url.searchParams.set("page[size]","".concat(t)),e},this.pageNumber=function(t){return e._url.searchParams.set("page[number]","".concat(t)),e},this.all=function(){return e._url.search="".concat(e._url.search,"&query=createTime:[now-20y+TO+now%2B1y]"),e},this.allNotLowRated=function(){return e._url.search="".concat(e._url.search,"&query=(createTime:[now-20y+TO+now%2B1y]%20AND%20(-poi-rating:1)%20AND%20(-poi-rating:2))"),e},this.buildQuery=function(){e._queryParts.length>0&&e._url.searchParams.set("query",e._queryParts.map(function(t){return"(".concat(t,")")}).join(" AND "));var t=e._url.search;t=(t=(t=t.replace(/%2BTO%2B/g,"+TO+")).replace(/%5B/g,"[")).replace(/%5D/g,"]"),e._url.search=t},this._url=new URL("/api/v1/assets",this.apiUrl),this._url.searchParams.set("platform","web")}return t.prototype.build=function(){if(this.buildQuery(),!this._url.searchParams.has("query"))throw new Error("AssetQueryBuilder: query not set");return this.useDefaultSort&&this.sort("-event-occurrence-time"),this._url.toString()},t}(),P={prod:"https://tv2no-via-video-api.public.tv2.no",stage:"https://tv2no-via-video-api.stage.public.tv2.no",dev:"https://tv2no-via-video-api.stage.public.tv2.no",local:"https://tv2no-via-video-api.stage.public.tv2.no"},x={prod:"https://tv2news.content-discovery.cf.eu-north-1-prod.vmnd.tv",stage:"https://tv2news.content-discovery.cf.eu-north-1-preprod.vmnd.tv",dev:"https://tv2news.content-discovery.cf.eu-north-1-preprod.vmnd.tv",local:"https://tv2news.content-discovery.cf.eu-north-1-preprod.vmnd.tv"},C={prod:"https://tv2news.play.cf.eu-north-1-prod.vmnd.tv",stage:"https://tv2news.play.cf.eu-north-1-preprod.vmnd.tv",dev:"https://tv2news.play.cf.eu-north-1-preprod.vmnd.tv",local:"https://tv2news.play.cf.eu-north-1-preprod.vmnd.tv"},O={prod:"df2bryDgJD",stage:"aqN13ZiaRT",dev:"aqN13ZiaRT",local:"aqN13ZiaRT"},M=function(){function t(t){var e=this;this.apiUrl=t,this._queryParts=[],this._listId="",this.request=function(t){return e.depth(1),e.includeNotPublished(!1),t.query&&e.query(t.query),t.listId&&e.listId(t.listId),t.fields&&e.fieldsAsset(t.fields),t.pageSize&&e.pageSize(t.pageSize),t.pageNumber&&e.pageNumber(t.pageNumber),e},this.fromRequest=function(t){return e.depth(t.depth),e.includeNotPublished(t.includeNotPublished),t.query&&e.query(t.query),t.listId&&e.listId(t.listId),t.fieldsAsset&&e.fieldsAsset(t.fieldsAsset),t.fields&&e.fields(t.fields),t.pageSize&&e.pageSize(t.pageSize),t.pageNumber&&e.pageNumber(t.pageNumber),e},this.query=function(t){return e._queryParts.push(t),e},this.listId=function(t){return e._listId=t,e},this.keywords=function(t){return e._queryParts.push('keywords:"'.concat(t,'"')),e},this.fields=function(t){return t&&0!==t.length?(e._url.searchParams.set("fields",t.join(",")),e):e},this.fieldsAsset=function(t){return t&&0!==t.length?(e._url.searchParams.set("fields[asset]",t.join(",")),e):e},this.fieldsCategory=function(t){return t&&0!==t.length?(e._url.searchParams.set("fields[category]",t.join(",")),e):e},this.depth=function(t){return e._url.searchParams.set("depth",t),e},this.includeNotPublished=function(t){return e._url.searchParams.set("includeNotPublished",t),e},this.pageSize=function(t){return e._url.searchParams.set("childrenPage[size]","".concat(t)),e},this.pageNumber=function(t){return e._url.searchParams.set("childrenPage[number]","".concat(t)),e},this.buildQuery=function(){""!==e._listId&&(e._url.pathname="".concat(e._url.pathname,"/").concat(e._listId)),e._queryParts.length>0&&e._url.searchParams.set("query",e._queryParts.map(function(t){return"(".concat(t,")")}).join(" AND "))},this._url=new URL("/api/v1/lists",this.apiUrl)}return t.prototype.build=function(){if(this.buildQuery(),!this._url.searchParams.has("query")&&""===this._listId)throw new Error("ListQueryBuilder: you need to provide either query parameters or listId");return this._url.toString()},t}(),F=function(){function t(t,e){var i=this;this.apiUrl=t,this.videoUrl=e,this.getVideoSectionByAsset=function(t){return I(t)},this.fetchAssetsQuery=function(t){return t.listId?new M(i.apiUrl).request(t).build():new D(i.apiUrl).request(t).build()},this.fetchAssets=function(t){return S(i,void 0,void 0,function(){var e,i,s,r,n,a,o,l,d,c,u,h,f,g,m,p,v,y,E;return b(this,function(T){switch(T.label){case 0:return e=t.assetId,i=t.listId,s=t.mapToAsset,r=t.includeLinkedVersion,n=t.preferLinkedVersion,a=t.includeLinkedVersionForTourn
1ament,o=t.pageSize,l=this.fetchAssetsQuery(t),[4,this.fetchData(l)];case 1:return d=T.sent(),c=d.data[0],u=null==c?void 0:c.title,h=[],f={},i&&this.isKilkayaTopList(d)?[4,this.handleKilkayaTopList(t,d)]:[3,3];case 2:return(g=T.sent())&&(h=g.data,f=g.meta),[3,4];case 3:h=null===(v=null==c?void 0:c.elements)||void 0===v?void 0:v.map(function(t){return t.content}),f=null==c?void 0:c.meta,T.label=4;case 4:return m=i?this.mapListResponse(i,u,h,f):d,r&&(null===(y=null==m?void 0:m.data)||void 0===y?void 0:y.length)?(p=m,[4,this.enrichWithHorizontalVersion(m.data,k,n,a,o)]):[3,6];case 5:p.data=T.sent(),T.label=6;case 6:return s&&(m.data=null===(E=m.data)||void 0===E?void 0:E.map(_.mapToAsset)),e&&this.locateAsset(t,m),[2,m]}})})},this.fetchAssetById=function(t,e){return S(i,void 0,void 0,function(){var i,s,r;return b(this,function(n){switch(n.label){case 0:return i=new URL("/api/v1/assets/".concat(t),this.apiUrl),[4,this.fetchAsset(i.toString())];case 1:if(!(s=n.sent()))throw new Error("Asset not found: ".concat(t));return r=s[0],[2,e?_.mapToAsset(r):r]}})})},this.fetchAssetByExternalAssetId=function(t,e){return S(i,void 0,void 0,function(){var i,s,r,n;return b(this,function(a){switch(a.label){case 0:return i=new D(this.apiUrl).externalAssetId(t).build(),[4,this.fetchAsset(i)];case 1:if(s=a.sent(),r=s.filter(function(e){return e["external-asset-id"].includes(t)}),!r.length)throw new Error("Asset not found: ".concat(t));return n=r[0],[2,e?_.mapToAsset(n):n]}})})},this.fetchAssetByLegacyAssetId=function(t,e){return S(i,void 0,void 0,function(){var i,s,r,n;return b(this,function(a){switch(a.label){case 0:return i=new D(this.apiUrl).legacyAssetId(t).build(),[4,this.fetchAsset(i)];case 1:if(s=a.sent(),r=s.filter(function(e){var i;return null===(i=e.legacyAssetId)||void 0===i?void 0:i.includes(t)}),!r.length)throw new Error("Asset with legacy asset id not found: ".concat(t));return n=r[0],[2,e?_.mapToAsset(n):n]}})})},this.fetchAssetByAssetIdOrLegacyAssetId=function(t,e,s,r,n,a){return S(i,void 0,void 0,function(){var i,o,l,d,c,u,h;return b(this,function(f){switch(f.label){case 0:return i=this.createAssetIdSearchUrl(t),[4,this.fetchAsset(i)];case 1:if(!(null==(o=f.sent())?void 0:o.length))throw new Error("Asset with asset id or legacy asset id is not found: ".concat(t));return r?(l=o[0].assetType===L?L:k,d=n&&l===k,[4,this.enrichWithHorizontalVersion(o,l,d,a)]):[3,3];case 2:o=f.sent(),f.label=3;case 3:return c=o[0],u=e?_.mapToAsset(c):c,s?(h=u,[4,this.fetchListsByAssetId(u.id)]):[3,5];case 4:h.assetLists=f.sent(),f.label=5;case 5:return[2,u]}})})},this.fetchListsByAssetId=function(t){return S(i,void 0,void 0,function(){var e,i;return b(this,function(s){switch(s.label){case 0:return e=new URL("/api/v1/lists/asset/".concat(t),this.videoUrl),[4,fetch(e.toString())];case 1:if(!(i=s.sent()).ok)throw new Error("Unexpected response from Video API: ".concat(i.status));return[4,i.json()];case 2:return[2,s.sent()]}})})},this.createAssetIdSearchUrl=function(t){return t.includes("cop_version_")?new D(i.apiUrl).externalAssetId(t).build():t.startsWith("cop_asset_")?new D(i.apiUrl).copAssetId(t).build():new D(i.apiUrl).assetIdOrlegacyAssetId(t).build()},this.handleKilkayaTopList=function(t,e){return S(i,void 0,void 0,function(){var i,s,r,n,a;return b(this,function(o){switch(o.label){case 0:return i=null===(a=null===(n=null===(r=e.data[0])||void 0===r?void 0:r.smartList)||void 0===n?void 0:n.requestMap)||void 0===a?void 0:a.url,[4,this.fetchData(this.buildKilkayaUrl(i,t))];case 1:return s=o.sent(),[2,this.verifyKilkayaAssets(t,s)]}})})},this.isKilkayaTopList=function(t){var e;return"kilkaya"===(null===(e=t.data[0])||void 0===e?void 0:e.keywords)},this.fetchLinkedVersion=function(t,e,s){return S(i,void 0,void 0,function(){var i,r;return b(this,function(n){switch(n.label){case 0:return i={copAssetId:t,assetType:e,pageSize:s},r=this.fetchAssetsQuery(i),[4,this.fetchData(r)];case 1:return[2,n.sent().data]}})})},this.enrichWithHorizontalVersion=function(t,e,s,r,n){return S(i,void 0,void 0,function(){var i,a,o,l;return b(this,function(d){switch(d.label){case 0:return d.trys.push([0,2,,3]),i=r?Array.isArray(r)?r:[r]:[],0===(a=t.filter(function(t){var s;return t.assetType===e&&("SportAutomatic"===t["video-type"]||t.isLive)&&(!i.length||i.includes(null!==(s=t["tv2-tournament-id"])&&void 0!==s?s:""))}).map(R).filter(function(t){return!!t})).length?[2,t]:[4,this.fetchLinkedVersion(a,w(e),n)];case 1:return o=d.sent(),l=new Map(o.map(function(t){return[R(t),t]})),t.forEach(function(e,i){var r=l.get(R(e));if(r)if(s){var n=e;t[i]=r,t[i].linkedVersion=n}else t[i].linkedVersion=r}),[2,t];case 2:return d.sent(),[2,t];case 3:return[2]}})})},this.extractIds=function(t){var e;return(null===(e=null==t?void 0:t.data)||void 0===e?void 0:e.map(function(t){return t.id}))||[]},this.verifyKilkayaAssets=function(t,e){return S(i,void 0,void 0,function(){var i,s,r,n,a;return b(this,function(o){switch(o.label){case 0:return(null==(i=this.extractIds(e))?void 0:i.length)?(s=this.fetchAssetsQuery({id:i,pageSize:t.pageSize,fields:["id"]}),[4,this.fetchData(s)]):[3,2];case 1:if(r=o.sent(),(n=this.extractIds(r)).length&&n.length<i.length)return[2,{data:a=e.data.filter(function(t){return n.includes(t.id)}),meta:{totalPages:e.meta.totalPages,numberOfHits:a.length,pageSize:a.length}}];o.label=2;case 2:return[2,e]}})})}
1,this.mapListResponse=function(t,e,i,s){return{title:e,data:null==i?void 0:i.map(function(i){return T(T({},i),{assetLists:[{id:t,title:e}]})}),meta:null!=s?s:{}}},this.fetchData=function(t){for(var e=[],s=1;s<arguments.length;s++)e[s-1]=arguments[s];return S(i,A([t],e),void 0,function(t,e){var i,s;return void 0===e&&(e="Vimond API"),b(this,function(r){switch(r.label){case 0:return[4,fetch(t,{headers:{"Accept-Language":"en-US"}})];case 1:if(!(i=r.sent()).ok)throw new Error("Unexpected response from ".concat(e,": ").concat(i.status,", ").concat(i.statusText,", ").concat(t));return[4,i.json()];case 2:if(!(s=r.sent()).data)throw new Error("Unexpected response from ".concat(e,": ").concat(i.status));return[2,s]}})})},this.fetchAsset=function(t){return S(i,void 0,void 0,function(){return b(this,function(e){switch(e.label){case 0:return[4,this.fetchData(t)];case 1:return[2,e.sent().data]}})})},this.locateAsset=function(t,e){var i,s=null===(i=e.data)||void 0===i?void 0:i.findIndex(function(e){var i;return e.id===t.assetId||(null===(i=e.linkedVersion)||void 0===i?void 0:i.id)===t.assetId});return s>-1&&(e.asset=e.data[s],e.assetIndex=s),e}}return t.prototype.buildKilkayaUrl=function(t,e){var i=new URL(t);return e.pageSize&&i.searchParams.set("size",e.pageSize.toString()),e.pageNumber&&i.searchParams.set("page",e.pageNumber.toString()),i.toString()},t}(),N=function(t){return t?t.toString().toLowerCase().replace(/æ/g,"ae").replace(/ø/g,"o").replace(/å/g,"a").normalize("NFD").replace(/[^a-z0-9- ]/g,"").replace(/ +/g," ").trim().replace(/ - /g,"-").replace(/ /g,"-"):""},U=function(t){return t?t.split(",").map(function(t){return t.trim().toLowerCase()}).filter(Boolean):[]},B=function(){function t(t,e){this.env=t,this.categoryTtlMs=e,this._cachedCategories={categories:void 0,response:void 0,validUntil:0}}return t.prototype.initialize=function(t){t&&(this._cachedCategories={categories:this.createCateoriesMap(t),response:t,validUntil:Date.now()+this.categoryTtlMs})},t.prototype.getAdPath=function(t){var e,i,s;return null!==(s=null===(i=null===(e=this._cachedCategories.categories)||void 0===e?void 0:e.get(t))||void 0===i?void 0:i.navigationPath)&&void 0!==s?s:""},t.prototype.getCategoryTitle=function(t){var e,i,s;return null!==(s=null===(i=null===(e=this._cachedCategories.categories)||void 0===e?void 0:e.get(t))||void 0===i?void 0:i.title)&&void 0!==s?s:""},t.prototype.getCategoryKeywords=function(t){var e,i,s;return null!==(s=null===(i=null===(e=this._cachedCategories.categories)||void 0===e?void 0:e.get(t))||void 0===i?void 0:i.code)&&void 0!==s?s:""},t.prototype.hasKeyword=function(t,e){return U(this.getCategoryKeywords(t)).includes(e)},t.prototype.getCategories=function(){return S(this,void 0,void 0,function(){var t,e,i;return b(this,function(s){switch(s.label){case 0:if("undefined"!=typeof window)return[2,null!==(e=this._cachedCategories.response)&&void 0!==e?e:null];if(this._cachedCategories.categories&&!(this._cachedCategories.validUntil<=Date.now()))return[3,4];s.label=1;case 1:return s.trys.push([1,3,,4]),[4,this.refreshCategories()];case 2:return s.sent(),[3,4];case 3:if(t=s.sent(),!this._cachedCategories.response)throw t;return[3,4];case 4:return[2,null!==(i=this._cachedCategories.response)&&void 0!==i?i:null]}})})},t.prototype.refreshCategories=function(){var t=this;return this._pendingFetch||(this._pendingFetch=this.fetchCategories().then(function(e){return t.initialize(e)}).finally(function(){t._pendingFetch=void 0})),this._pendingFetch},t.prototype.fetchCategoryImageUrl=function(t){return S(this,void 0,void 0,function(){var e,i,s,r,n,a;return b(this,function(o){switch(o.label){case 0:return[4,fetch("".concat(x[this.env],"/api/v1/categories/").concat(t))];case 1:if(!(e=o.sent()).ok)throw new Error("Failed to fetch category image for ".concat(t," from content discovery API: ").concat(e.status));return[4,e.json()];case 2:return i=o.sent(),[2,null!==(a=null===(n=null===(r=null===(s=null==i?void 0:i.data)||void 0===s?void 0:s[0])||void 0===r?void 0:r.images)||void 0===n?void 0:n.defaultUrl)&&void 0!==a?a:null]}})})},t.prototype.fetchCategories=function(){return S(this,void 0,void 0,function(){var t,e;return b(this,function(i){switch(i.label){case 0:return[4,fetch("".concat(P[this.env],"/api/v1/categories?includeAIClips=true"),{signal:null===(e=AbortSignal.timeout)||void 0===e?void 0:e.call(AbortSignal,5e3)})];case 1:if(!(t=i.sent()).ok)throw new Error("Failed to fetch categories from video API: ".concat(t.status));return[4,t.json()];case 2:return[2,i.sent()]}})})},t.prototype.createCateoriesMap=function(t){var e=new Map,i=function(t){t.navigationPath&&e.set(t.i
1d,t),t.children&&t.children.length>0&&t.children.forEach(function(t){return i(t)})};return i(t),e},t}(),$=function(t){return S(void 0,void 0,void 0,function(){return b(this,function(e){return[2,new Promise(function(e,i){fetch(t,{headers:{"Accept-Language":"en-US"}}).then(function(t){t.ok?t.json().then(function(t){e(t)}).catch(function(t){i(t)}):i("Unexpected response from Vimond API: ".concat(t.status))}).catch(function(t){i(t)})})]})})},G=function(t){var e=this;this.apiUrl=t,this.fetchListsById=function(t){for(var i=[],s=1;s<arguments.length;s++)i[s-1]=arguments[s];return S(e,A([t],i),void 0,function(t,e,i,s,r){var n;return void 0===e&&(e=10),void 0===i&&(i=!1),void 0===s&&(s=[]),void 0===r&&(r=[]),b(this,function(a){return n=new M(this.apiUrl).listId(t).depth(e).includeNotPublished(i).fields(s).fieldsAsset(r).build(),[2,$(n.toString())]})})},this.fetchListIdByKeyword=function(t){return S(e,void 0,void 0,function(){var e,i,s,r;return b(this,function(n){switch(n.label){case 0:return e=new M(this.apiUrl).keywords(t).depth(1).includeNotPublished(!1).fields(["id"]).build(),[4,$(e.toString())];case 1:return i=n.sent(),[2,null===(r=null===(s=null==i?void 0:i.data)||void 0===s?void 0:s[0])||void 0===r?void 0:r.id]}})})},this.fetchLists=function(t){return S(e,void 0,void 0,function(){var e,i,s;return b(this,function(r){switch(r.label){case 0:return e=new M(this.apiUrl).fromRequest(t).build(),[4,fetch(e,{headers:{"Accept-Language":"en-US"}})];case 1:if(!(i=r.sent()).ok)throw new Error("Unexpected response from Vimond API: ".concat(i.status,", ").concat(i.statusText,", ").concat(e));return[4,i.json()];case 2:if(!(s=r.sent()).data)throw new Error("Unexpected response from Vimond API: ".concat(i.status));return[2,s.data]}})})},this.hasKeyword=function(t,i){return S(e,void 0,void 0,function(){var e,s,r;return b(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,this.fetchListsById(t,1,!1,["keywords"],[])];case 1:return e=n.sent(),(s=null===(r=null==e?void 0:e.data[0])||void 0===r?void 0:r.keywords)?[2,U(s).includes(i)]:[2,!1];case 2:return n.sent(),[2,!1];case 3:return[2]}})})}},V=function(t,e,i,s){var r=this;this.rootListId=t,this.listService=e,this.urlService=i,this.navigationTtlMs=s,this.getNavigationById=function(t){return S(r,void 0,void 0,function(){function e(i){return i.id===t?(s=i,!0):Array.isArray(i.children)&&i.children.some(e)}var i,s,r;return b(this,function(t){switch(t.label){case 0:return[4,this.getNavigation()];case 1:return i=t.sent(),null===(r=i.children)||void 0===r||r.some(e),[2,s||i]}})})},this.getNavigation=function(){return S(r,void 0,void 0,function(){var t;return b(this,function(e){switch(e.label){case 0:return"undefined"!=typeof window?[2,this._cachedNavigation.navigationTree]:!this._cachedNavigation.navigationTree||this._cachedNavigation.validUntil<=Date.now()?[4,this.fetchNavigation()]:[3,2];case 1:t=e.sent(),this._cachedNavigation={navigationTree:t,validUntil:Date.now()+this.navigationTtlMs},e.label=2;case 2:return[2,this._cachedNavigation.navigationTree]}})})},this.fetchNavigation=function(){return S(r,void 0,void 0,function(){var t=this;return b(this,function(e){return[2,new Promise(function(e,i){var s=t.buildMenu(t.rootListId,"Main menu",void 0,[]);try{t.listService.fetchListsById(t.rootListId,10,!1,["id","title"],["id"]).then(function(i){var r,n=i.data,a=null==n?void 0:n.filter(function t(e){var i;return(null===(i=e.elements)||void 0===i?void 0:i.length)?e.elements=e.elements.filter(t):"asset"!==e.contentType}),o=null===(r=a[0])||void 0===r?void 0:r.elements.map(function t(e){var i,s={id:e.id,title:e.title};return(null===(i=e.elements)||void 0===i?void 0:i.length)?T(T({},s),{submeny:e.elements.map(t)}):s});null==o||o.forEach(function(e){var i=t.buildDynamicMenu(e,s);i.urlPath=t.urlService.slugify(i.title),s.children.push(i)}),e(s)}).catch(function(t){return i(t)})}catch(t){i(t)}})]})})},this.buildDynamicMenu=function(t,e){var i;if(!t.submeny)return r.parseMenuItem(t,e.urlPath);var s=r.buildMenu(t.id,t.title,e.id,[]);return s.urlPath=(null==e?void 0:e.urlPath)?e.urlPath+"/"+r.urlService.slugify(t.title):r.urlService.slugify(t.title),null===(i=t.submeny)||void 0===i||i.forEac
1h(function(e){var i,n;if(e.submeny){var a=r.buildMenu(e.id,e.title,s.id,[]);a.urlPath=r.urlService.slugify(t.title)+"/"+r.urlService.slugify(e.title),e.submeny.forEach(function(t){a.children.push(r.buildDynamicMenu(t,a))}),null===(i=s.children)||void 0===i||i.push(a)}else{var o=r.parseMenuItem(e,s.urlPath||r.urlService.slugify(t.title));null===(n=s.children)||void 0===n||n.push(o)}}),s},this.parseMenuItem=function(t,e){return{id:t.id,title:t.title,urlPath:"".concat(e,"/").concat(r.urlService.slugify(t.title))}},this.buildMenu=function(t,e,i,s){return{id:t,title:e,prevMenuId:i,children:s,urlPath:""}},this.initialize=function(t){t&&(r._cachedNavigation={navigationTree:t,validUntil:Date.now()+r.navigationTtlMs})},this._cachedNavigation={navigationTree:void 0,validUntil:0}},K=function(t){var e=this;this.playApiUrl=t,this.createPlayRequest=function(t,i){return S(e,void 0,void 0,function(){var e,s,r;return b(this,function(n){switch(n.label){case 0:return e=new URL("/api/v2/asset/".concat(t,"/play"),this.playApiUrl),i&&e.searchParams.append("contentType",i),[4,fetch(e.toString(),{method:"POST"})];case 1:if(!(s=n.sent()).ok)throw new Error("Unexpected response from Vimond API: ".concat(s.status));return[4,s.json()];case 2:if(!(r=n.sent()).data||r.data.length<1)throw new Error("Unexpected response from Vimond API: ".concat(s.status));return[2,r.data[0]]}})})}},H=function(t){var e;if(!t)return"/slug";var i=(null===(e=t.title)||void 0===e?void 0:e.substring(0,50))||"";return i?"/".concat(N(i)):""},j=function(){var t=this;this.getAssetUrl=function(t,e){return"/video/".concat(I(t)).concat(H(t),"/").concat(e?"".concat(e,"-").concat(t.id):t.id)},this.getSportAssetUrl=function(e,i,s){return"/video/sportauto/".concat(e,"/").concat(t.mapToGroup(i)).concat(H(s),"/").concat(t.mapToGroupId(i),"/").concat(t.mapToTypeFilter(i)).concat(s?"/"+s.id:"")},this.slugify=function(t){return N(t)},this.mapToGroup=function(t){if(t.tournamentId)return"turnering";if(t.eventId)return"kamp";if(t.teamId)return"lag";if(t.playerId)return"spiller";throw new Error("Invalid request: missing group")},this.mapToGroupId=function(t){if(t.tournamentId)return Array.isArray(t.tournamentId)?t.tournamentId[0]:t.tournamentId;if(t.eventId)return Array.isArray(t.eventId)?t.eventId[0]:t.eventId;if(t.teamId)return Array.isArray(t.teamId)?t.teamId[0]:t.teamId;if(t.playerId)return Array.isArray(t.playerId)?t.playerId[0]:t.playerId;throw new Error("Invalid request: missing group id")},this.mapToTypeFilter=function(t){var e=t.typeOfAction,i=t.incidentType;return"string"==typeof e&&"highlight"===e.toLowerCase()?"highlight":(Array.isArray(i)?i.map(function(t){return t.toLowerCase()}).join("-"):null==i?void 0:i.toLowerCase())||"all"}},q=function(t){var e,i,s=this;this.options=t,this.contentDiscoveryAPIURL=function(){return x[s.options.env]},this.videoAPIURL=function(){return P[s.options.env]},this.playApiUrl=function(){return C[s.options.env]},this.rootListId=function(){return O[s.options.env]},this.initialize=function(t){var e;t&&(s.navigationService.initialize(t.menuStructure),s.categoryService.initialize(null!==(e=t.categories)&&void 0!==e?e:null))},this.urlService=new j,this.assetService=new F(this.contentDiscoveryAPIURL(),this.videoAPIURL()),this.listService=new G(this.contentDiscoveryAPIURL()),this.playService=new K(this.playApiUrl()),this.navigationService=new V(this.rootListId(),this.listService,this.urlService,null!==(e=t.navigationTtlMs)&&void 0!==e?e:36e5),this.categoryService=new B(this.options.env,null!==(i=this.options.categoryTtlMs)&&void 0!==i?i:18e5)};const Y=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},W=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=z},z=Number.MAX_SAFE_INTEGER||9007199254740991;let X=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),Q=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ER
1ROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.UNKNOWN="unknown",t}({}),J=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",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.BUFFERED_TO_END="hlsBufferedToEnd",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.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",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_TRACK_UPDATED="hlsSubtitleTrackUpdated",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.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",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",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});var Z="manifest",tt="level",et="audioTrack",it="subtitleTrack",st="main",rt="audio",nt="subtitle";class at{constructor(t,e=0,i=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_=i}sample(t,e){const i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t}
vendor: 3,732 bytes, line 1
1getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class ot{constructor(t,e,i,s=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new at(t),this.fast_=new at(e),this.defaultTTFB_=s,this.ttfb_=new at(t)}update(t,e){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==t&&(this.slow_=new at(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.fast_=new at(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new at(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){const i=(t=Math.max(t,this.minDelayMs_))/1e3,s=8*e/i;this.fast_.sample(i,s),this.slow_.sample(i,s)}sampleTTFB(t){const e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function lt(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var s=i.call(t,e);if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function dt(){return dt=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var s in i)({}).hasOwnProperty.call(i,s)&&(t[s]=i[s])}return t},dt.apply(null,arguments)}function ct(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),i.push.apply(i,s)}return i}function ut(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?ct(Object(i),!0).forEach(function(e){lt(t,e,i[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):ct(Object(i)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))})}return t}class ht{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${t}]:`;this.trace=ft,this.debug=e.debug.bind(null,i),this.log=e.log.bind(null,i),this.warn=e.warn.bind(null,i),this.info=e.info.bind(null,i),this.error=e.error.bind(null,i)}}const ft=function(){},gt={trace:ft,debug:ft,log:ft,warn:ft,info:ft,error:ft};function mt(){return dt({},gt)}function pt(t,e,i){return e[t]?e[t].bind(e):function(t,e){const i=self.console[t];return i?i.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):ft}(t,i)}const vt=mt();const yt=vt;function Et(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Tt(t,e){const i=Object.keys(t),s=Object.keys(e),r=i.length,n=s.length;return!r||!n||r===n&&!i.some(t=>-1===s.indexOf(t))}function St(t,e=!1){if("undefined"!=typeof TextDecoder){const i=new TextDecoder("utf-8").decode(t);if(e){const t=i.indexOf("\0");return-1!==t?i.substring(0,t):i}return i.replace(/\0/g,"")}const i=t.length;let s,r,n,a="",o=0;for(;o<i;){if(s=t[o++],0===s&&e)return a;
vendor: 5,477 bytes, line 1
1if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:r=t[o++],a+=String.fromCharCode((31&s)<<6|63&r);break;case 14:r=t[o++],n=t[o++],a+=String.fromCharCode((15&s)<<12|(63&r)<<6|63&n)}}return a}function bt(t){let e="";for(let i=0;i<t.length;i++){let s=t[i].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function At(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function kt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Lt,It={exports:{}};var wt=(Lt||(Lt=1,function(t){var e,i,s,r,n;e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,n={buildAbsoluteURL:function(t,e,s){if(s=s||{},t=t.trim(),!(e=e.trim())){if(!s.alwaysNormalize)return t;var r=n.parseURL(t);if(!r)throw new Error("Error trying to parse base URL.");return r.path=n.normalizePath(r.path),n.buildURLFromParts(r)}var a=n.parseURL(e);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return s.alwaysNormalize?(a.path=n.normalizePath(a.path),n.buildURLFromParts(a)):e;var o=n.parseURL(t);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var d={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(d.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var c=o.path,u=c.substring(0,c.lastIndexOf("/")+1)+a.path;d.path=n.normalizePath(u)}else d.path=o.path,a.params||(d.params=o.params,a.query||(d.query=o.query));return null===d.path&&(d.path=s.alwaysNormalize?n.normalizePath(a.path):a.path),n.buildURLFromParts(d)},parseURL:function(t){var i=e.exec(t);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(s,"");t.length!==(t=t.replace(r,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=n}(It)),It.exports);class Rt{constructor(){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}}}var _t="audio",Dt="video",Pt="audiovideo";class xt{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,function(t,e){const i=Ft(t,e);i&&(i.enumerable=!0,Object.defineProperty(t,e,i))}(this,"stats")}setByteRange(t,e){const i=t.split("@",2);let s;s=1===i.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[_t]:null,[Dt]:null,[Pt]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new Rt),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=wt.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[_t]=null,t[Dt]=null,t[Pt]=null}}function Ct(t){return"initSegment"!==t.sn}class Ot extends xt{constructor(t,e){super(e),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}get byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange.length){const t=this.byteRange[0],e=this.byteRange[1];if(Y(t)&&Y(e))return e-t}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(null==(t=this._decryptdata)||!t.keyId){const t=Object.keys(e);if(1===t.length){const i=this._decryptdata=e[t[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const t=Y(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;
vendor: 59,335 bytes, line 1
1if(this.levelkeys){var e;const t=Object.keys(this.levelkeys),i=t.length;if(i>1||1===i&&null!=(e=this.levelkeys[t[0]])&&e.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){Y(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}get ref(){return Ct(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const e=this.levelkeys;if(e){var i;const s=e[t];!s||null!=(i=this._decryptdata)&&i.keyId||(this._decryptdata=s.getDecryptData(this.sn,e))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,i,s,r,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,s),o.endDTS=Math.max(o.endDTS,r)):a[t]={startPTS:e,endPTS:i,startDTS:s,endDTS:r,partial:n}}}class Mt extends xt{constructor(t,e,i,s,r){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=s;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}function Ft(t,e){const i=Object.getPrototypeOf(t);if(i){const t=Object.getOwnPropertyDescriptor(i,e);return t||Ft(i,e)}}const Nt=Math.pow(2,32)-1,Ut=[].push,Bt={video:1,audio:2,id3:3,text:4};function $t(t){return String.fromCharCode.apply(null,t)}function Gt(t,e){const i=t[e]<<8|t[e+1];return i<0?65536+i:i}function Vt(t,e){const i=Ht(t,e);return i<0?4294967296+i:i}function Kt(t,e){let i=Vt(t,e);return i*=Math.pow(2,32),i+=Vt(t,e+4),i}function Ht(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function jt(t,e){const i=[];if(!e.length)return i;const s=t.byteLength;for(let r=0;r<s;){const n=Vt(t,r),a=n>1?r+n:s;if($t(t.subarray(r+4,r+8))===e[0])if(1===e.length)i.push(t.subarray(r+8,a));else{const s=jt(t.subarray(r+8,a),e.slice(1));s.length&&Ut.apply(i,s)}r=a}return i}function qt(t){const e=[],i=t[0];let s=8;const r=Vt(t,s);s+=4;let n=0,a=0;0===i?(n=Vt(t,s),a=Vt(t,s+4),s+=8):(n=Kt(t,s),a=Kt(t,s+8),s+=16),s+=2;let o=t.length+a;const l=Gt(t,s);s+=2;for(let i=0;i<l;i++){let i=s;const n=Vt(t,i);i+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return yt.warn("SIDX has hierarchical references (not supported)"),null;const l=Vt(t,i);i+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,i+=4,s=i}return{earliestPresentationTime:n,timescale:r,version:i,referencesCount:l,references:e}}function Yt(t){const e=[],i=jt(t,["moov","trak"]);for(let t=0;t<i.length;t++){const s=i[t],r=jt(s,["tkhd"])[0];if(r){let t=r[0];const i=Vt(r,0===t?12:20),n=jt(s,["mdia","mdhd"])[0];if(n){t=n[0];const r=Vt(n,0===t?12:20),a=jt(s,["mdia","hdlr"])[0];if(a){const t=$t(a.subarray(8,12)),n={soun:_t,vide:Dt}[t],o=Wt(jt(s,["mdia","minf","stbl","stsd"])[0]);n?(e[i]={timescale:r,type:n,stsd:o},e[n]=ut({timescale:r,id:i},o)):e[i]={timescale:r,type:t,stsd:o}}}}}return jt(t,["moov","mvex","trex"]).forEach(t=>{const i=Vt(t,4),s=e[i];s&&(s.default={duration:Vt(t,12),flags:Vt(t,20)})}),e}function Wt(t){const e=t.subarray(8),i=e.subarray(86),s=$t(e.subarray(4,8));let r,n=s;const a="enca"===s||"encv"===s;if(a){const t=jt(e,[s])[0];jt(t.subarray("enca"===s?28:78),["sinf"]).forEach(t=>{const e=jt(t,["schm"])[0];if(e){const i=$t(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=jt(t,["frma"])[0];e&&(n=$t(e))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=jt(i,["avcC"])[0];t&&t.length>3&&(n+="."+Qt(t[1])+Qt(t[2])+Qt(t[3]),r=zt("avc1"===o?"dva1":"dvav",i));break}case"mp4a":{const t=jt(e,[s])[0],i=jt(t.subarray(28),["esds"])[0];if(i&&i.length>7){let t=4;if(3!==i[t++])break;t=Xt(i,t),t+=2;const e=i[t++];if(128&e&&(t+=2),64&e&&(t+=i[t++]),4!==i[t++])break;t=Xt(i,t);const s=i[t++];if(64!==s)break;if(n+="."+Qt(s),t+=12,5!==i[t++])break;t=Xt(i,t);const r=i[t++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&i[t])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const t=jt(i,["hvcC"])[0];if(t&&t.length>12){const e=t[1],i=["","A","B","C"][e>>6],s=31&e,r=Vt(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);n+="."+i+s,n+="."+function(t){let e=0;for(let i=0;i<32;i++)e|=(t>>i&1)<<31-i;return e>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let d="";for(let t=l.length;t--;){const e=l[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}n+=d}r=zt("hev1"==o?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=zt(n,i)||n;break;case"vp09":{const t=jt(i,["vpcC"])[0];if(t&&t.length>6){const e=t[4],i=t[5],s=t[6]>>4&15;n+="."+Jt(e)+"."+Jt(i)+"."+Jt(s)}break}case"av01":{const t=jt(i,["av1C"])[0];if(t&&t.length>2){const e=t[1]>>>5,s=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,d=2===e&&o?l?12:10:o?10:8,c=(16&t[2])>>4,u=(8&t[2])>>3,h=(4&t[2])>>2,f=3&t[2],g=1,m=1,p=1,v=0;n+="."+e+"."+Jt(s)+a+"."+Jt(d)+"."+c+"."+u+h+f+"."+Jt(g)+"."+Jt(m)+"."+Jt(p)+"."+v,r=zt("dav1",i)}break}}return{codec:n,encrypted:a,supplemental:r}}function zt(t,e){const i=jt(e,["dvvC"]),s=i.length?i[0]:jt(e,["dvcC"])[0];if(s){const e=s[2]>>1&127,i=s[2]<<5&32|s[3]>>3&31;return t+"."+Jt(e)+"."+Jt(i)}}function Xt(t,e){const i=e+5;for(;128&t[e++]&&e<i;);return e}function Qt(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function Jt(t){return(t<10?"0":"")+t}function Zt(t,e){jt(t,["moov","trak"]).forEach(t=>{const i=jt(t,["mdia","minf","stbl","stsd"])[0];if(!i)return;const s=i.subarray(8);let r=jt(s,["enca"]);const n=r.length>0;n||(r=jt(s,["encv"])),r.forEach(t=>{jt(n?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const i=te(t);i&&e(i,n)})})})}function te(t){const e=jt(t,["schm"])[0];if(e){const i=$t(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=jt(t,["schi","tenc"])[0];if(e)return e}}}function ee(t,e){const i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function ie(t,e){const i=[],s=e.samples,r=e.timescale,n=e.id;let a=!1;return jt(s,["moof"]).map(o=>{const l=o.byteOffset-8;jt(o,["traf"]).map(o=>{const d=jt(o,["tfdt"]).map(t=>{const e=t[0];let i=Vt(t,4);return 1===e&&(i*=Math.pow(2,32),i+=Vt(t,8)),i/r})[0];return void 0!==d&&(t=d),jt(o,["tfhd"]).map(d=>{const c=Vt(d,4),u=16777215&Vt(d,0);let h=0;const f=!!(16&u);let g=0;const m=!!(32&u);let p=8;c===n&&(!!(1&u)&&(p+=8),!!(2&u)&&(p+=4),!!(8&u)&&(h=Vt(d,p),p+=4),f&&(g=Vt(d,p),p+=4),m&&(p+=4),"video"===e.type&&(a=se(e.codec)),jt(o,["trun"]).map(n=>{const o=n[0],d=16777215&Vt(n,0),c=!!(1&d);let u=0;const f=!!(4&d),m=!!(256&d);let p=0;const v=!!(512&d);let y=0;const E=!!(1024&d),T=!!(2048&d);let S=0;const b=Vt(n,4);let A=8;c&&(u=Vt(n,A),A+=4),f&&(A+=4);let k=u+l;for(let l=0;l<b;l++){if(m?(p=Vt(n,A),A+=4):p=h,v?(y=Vt(n,A),A+=4):y=g,E&&(A+=4),T&&(S=0===o?Vt(n,A):Ht(n,A),A+=4),e.type===Dt){let e=0;for(;e<y;){const n=Vt(s,k);if(k+=4,re(a,s[k])){ne(s.subarray(k,k+n),a?2:1,t+S/r,i)}k+=n,e+=n+4}}t+=p/r}}))})})}),i}function se(t){if(!t)return!1;const e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function re(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function ne(t,e,i,s){const r=ae(t);let n=0;n+=e;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const t=r.length-n;let e=n;if(o<t)n+=o;else if(o>t){yt.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===r[e++]){const t=Gt(r,e);if(e+=2,49===t){const t=Vt(r,e);if(e+=4,1195456820===t){const t=r[e++];if(3===t){const n=r[e++],o=64&n,l=o?2+3*(31&n):0,d=new Uint8Array(l);if(o){d[0]=n;for(let t=1;t<l;t++)d[t]=r[e++]}s.push({type:t,payloadType:a,pts:i,bytes:d})}}}}}else if(5===a&&o>16){const t=[];for(let i=0;i<16;i++){const s=r[e++].toString(16);t.push(1==s.length?"0"+s:s),3!==i&&5!==i&&7!==i&&9!==i||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t<n;t++)l[t]=r[e++];s.push({payloadType:a,pts:i,uuid:t.join(""),userData:St(l),userDataBytes:l})}}}function ae(t){const e=t.byteLength,i=[];let s=1;for(;s<e-2;)0===t[s]&&0===t[s+1]&&3===t[s+2]?(i.push(s+2),s+=2):s++;if(0===i.length)return t;const r=e-i.length,n=new Uint8Array(r);let a=0;for(s=0;s<r;a++,s++)a===i[0]&&(a++,i.shift()),n[s]=t[a];return n}function oe(t,e,i){if(16!==t.byteLength)throw new RangeError("Invalid system id");let s,r,n;s=0,r=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(t,...e){const i=e.length;let s=8,r=i;for(;r--;)s+=e[r].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(t,4),r=0,s=8;r<i;r++)n.set(e[r],s),s+=e[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),t,n,r,a,i)}function le(t){const e=t.getUint32(0),i=t.byteOffset,s=t.byteLength;if(s<e)return{offset:i,size:s};if(1886614376!==t.getUint32(4))return{offset:i,size:e};const r=t.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:i,size:e};const n=t.buffer,a=bt(new Uint8Array(n,i+12,16));let o=null,l=null,d=0;if(0===r)d=28;else{const r=t.getUint32(28);if(!r||s<32+16*r)return{offset:i,size:e};o=[];for(let t=0;t<r;t++)o.push(new Uint8Array(n,i+32+16*t,16));d=32+16*r}if(!d)return{offset:i,size:e};const c=t.getUint32(d);return e-32<c?{offset:i,size:e}:(l=new Uint8Array(n,i+d+4,c),{version:r,systemId:a,kids:o,data:l,offset:i,size:e})}const de=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),ce={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function ue(t,e){const i=ce[e];return!!i&&!!i[t.slice(0,4)]}function he(t,e,i=!0){return!t.split(",").some(t=>!fe(t,e,i))}function fe(t,e,i=!0){var s;const r=Et(i);return null!=(s=null==r?void 0:r.isTypeSupported(ge(t,e)))&&s}function ge(t,e){return`${e}/mp4;codecs=${t}`}function me(t){if(t){const e=t.substring(0,4);return ce.video[e]}return 2}function pe(t){const e=de();return t.split(",").reduce((t,i)=>{const s=e&&se(i)?9:ce.video[i];return s?(2*s+t)/(t?3:2):(ce.audio[i]+t)/(t?2:1)},0)}const ve={};const ye=/flac|opus|mp4a\.40\.34/i;function Ee(t,e=!0){return t.replace(ye,t=>function(t,e=!0){if(ve[t])return ve[t];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let r=0;r<i.length;r++){var s;if(fe(i[r],"audio",e))return ve[t]=i[r],i[r];if("mp3"===i[r]&&null!=(s=Et(e))&&s.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),e))}function Te(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(Se(t,"audio")||Se(t,"video")))return t;if(e){const i=e.split(",");if(i.length>1){if(t)for(let e=i.length;e--;)if(i[e].substring(0,4)===t.substring(0,4))return i[e];return i[0]}}return e||t}function Se(t,e){return ue(t,e)&&fe(t,e)}function be(t){if(t.startsWith("av01.")){const e=t.split("."),i=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=i[t-4];return e.join(".")}return t}function Ae(t){const e=Et(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function ke(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Le={supported:!1,smooth:!1,powerEfficient:!1},Ie={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function we(t,e){return{supported:!1,configurations:e,decodingInfoResults:[Le],error:t}}function Re(t,e,i,s,r,n){const a=t.videoCodec,o=t.audioCodec?t.audioGroups:null,l=null==n?void 0:n.audioCodec,d=null==n?void 0:n.channels,c=d?parseInt(d):l?1/0:2;let u=null;if(null!=o&&o.length)try{u=1===o.length&&o[0]?e.groups[o[0]].channels:o.reduce((t,i)=>{if(i){const s=e.groups[i];if(!s)throw new Error(`Audio track group ${i} not found`);Object.keys(s.channels).forEach(e=>{t[e]=(t[e]||0)+s.channels[e]})}return t},{2:0})}catch(t){return!0}return void 0!==a&&(a.split(",").some(t=>se(t))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(s,30)||"SDR"!==t.videoRange&&t.videoRange!==i||t.bitrate>Math.max(r,8e6))||!!u&&Y(c)&&Object.keys(u).some(t=>parseInt(t)>c)}function _e(t,e,i,s={}){const r=t.videoCodec;if(!r&&!t.audioCodec||!i)return Promise.resolve(Ie);const n=[],a=function(t){var e;const i=null==(e=t.videoCodec)?void 0:e.split(","),s=Pe(t),r=t.width||640,n=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return i?i.map(t=>{const e={contentType:ge(be(t),"video"),width:r,height:n,bitrate:s,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e}):[]}(t),o=a.length,l=function(t,e,i){var s;const r=null==(s=t.audioCodec)?void 0:s.split(","),n=Pe(t);if(r&&t.audioGroups)return t.audioGroups.reduce((t,s)=>{var a;const o=s?null==(a=e.groups[s])?void 0:a.tracks:null;return o?o.reduce((t,e)=>{if(e.groupId===s){const s=parseFloat(e.channels||"");r.forEach(e=>{const r={contentType:ge(e,"audio"),bitrate:i?De(e,n):n};s&&(r.channels=""+s),t.push(r)})}return t},t):t},[]);return[]}(t,e,o>0),d=l.length;for(let t=o||1*d||1;t--;){const e={type:"media-source"};if(o&&(e.video=a[t%o]),d){e.audio=l[t%d];const i=e.audio.bitrate;e.video&&i&&(e.video.bitrate-=i)}n.push(e)}if(r){const t=navigator.userAgent;if(r.split(",").some(t=>se(t))&&de())return Promise.resolve(we(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),n))}return Promise.all(n.map(t=>{const e=function(t){let e="";const{audio:i,video:s}=t;if(s){e+=`${ke(s.contentType)}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(i){e+=`${s?"_":""}${ke(i.contentType)}_c${i.channels}`}return e}(t);return s[e]||(s[e]=i.decodingInfo(t))})).then(t=>({supported:!t.some(t=>!t.supported),configurations:n,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:n,decodingInfoResults:[],error:t}))}function De(t,e){if(e<=1)return 1;let i=128e3;return"ec-3"===t?i=768e3:"ac-3"===t&&(i=64e4),Math.min(e/2,i)}function Pe(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}const xe=["NONE","TYPE-0","TYPE-1",null];const Ce=["SDR","PQ","HLG"];var Oe="",Me="YES",Fe="v2";function Ne(t){const{canSkipUntil:e,canSkipDateRanges:i,age:s}=t;return e&&s<e/2?i?Fe:Me:Oe}class Ue{constructor(t,e,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=i}addDirectives(t){const e=new self.URL(t);return void 0!==this.msn&&e.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}}class Be{constructor(t){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const i=null==(e=t.supplemental)?void 0:e.videoCodec;i&&i!==t.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return $e(this._audioGroups,t)}hasSubtitleGroup(t){return $e(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function $e(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function Ge(t,e){let i=!1,s=[];if(t&&(i="SDR"!==t,s=[t]),e){s=e.allowedVideoRanges||Ce.slice(0);const t="SDR"!==s.join("")&&!e.videoCodec;i=void 0!==e.preferHDR?e.preferHDR:t&&function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),i||(s=["SDR"])}return{preferHDR:i,allowedVideoRanges:s}}const Ve=(t,e)=>JSON.stringify(t,(t=>{const e=new WeakSet;return(i,s)=>{if(t&&(s=t(i,s)),"object"==typeof s&&null!==s){if(e.has(s))return;e.add(s)}return s}})(e));function Ke(t,e){yt.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function He(t){return t.reduce((t,e)=>{let i=t.groups[e.groupId];i||(i=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(e);const s=e.channels||"2";return i.channels[s]=(i.channels[s]||0)+1,i.hasDefault=i.hasDefault||e.default,i.hasAutoSelect=i.hasAutoSelect||e.autoselect,i.hasDefault&&(t.hasDefaultAudio=!0),i.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function je(t){if(!t)return t;const{lang:e,assocLang:i,characteristics:s,channels:r,audioCodec:n}=t;return{lang:e,assocLang:i,characteristics:s,channels:r,audioCodec:n}}function qe(t,e,i){if("attrs"in t){const i=e.indexOf(t);if(-1!==i)return i}for(let s=0;s<e.length;s++){if(Ye(t,e[s],i))return s}return-1}function Ye(t,e,i){const{groupId:s,name:r,lang:n,assocLang:a,default:o}=t,l=t.forced;return(void 0===s||e.groupId===s)&&(void 0===r||e.name===r)&&(void 0===n||function(t,e="--"){if(t.length===e.length)return t===e;return t.startsWith(e)||e.startsWith(t)}(n,e.lang))&&(void 0===n||e.assocLang===a)&&(void 0===o||e.default===o)&&(void 0===l||e.forced===l)&&(!("characteristics"in t)||function(t,e=""){const i=t.split(","),s=e.split(",");return i.length===s.length&&!i.some(t=>-1===s.indexOf(t))}(t.characteristics||"",e.characteristics))&&(void 0===i||i(t,e))}function We(t,e){const{audioCodec:i,channels:s}=t;return!(void 0!==i&&(e.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==s&&s!==(e.channels||"2"))}function ze(t,e,i){for(let s=e;s>-1;s--)if(i(t[s]))return s;for(let s=e+1;s<t.length;s++)if(i(t[s]))return s;return-1}function Xe(t,e){var i;return!!t&&t!==(null==(i=e.loadLevelObj)?void 0:i.uri)}const Qe=function(t,e){let i=0,s=t.length-1,r=null,n=null;for(;i<=s;){r=(i+s)/2|0,n=t[r];const a=e(n);if(a>0)i=r+1;else{if(!(a<0))return n;s=r-1}}return null};function Je(t,e,i=0,s=0,r=.005){let n=null;if(t){n=e[1+t.sn-e[0].sn]||null;const s=t.endDTS-i;s>0&&s<15e-7&&(i+=15e-7),n&&t.level!==n.level&&n.end<=t.end&&(n=e[2+t.sn-e[0].sn]||null)}else 0===i&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===Ze(i,s,n)||function(t,e,i){if(e&&0===e.start&&e.level<t.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t),i);return t.start<=s}return!1}(n,t,Math.min(r,s))))return n;const a=Qe(e,Ze.bind(null,i,s));return!a||a===t&&n?n:a}function Ze(t=0,e=0,i){if(i.start<=t&&i.start+i.duration>t)return 0;const s=Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-s<=t?1:i.start-s>t&&i.start?-1:0}function ti(t,e,i){const s=1e3*Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-s>t}function ei(t,e,i){if(t&&t.startCC<=e&&t.endCC>=e){let s=t.fragments;const{fragmentHint:r}=t;let n;return r&&(s=s.concat(r)),Qe(s,t=>t.cc<e?1:t.cc>e?-1:(n=t,t.end<=i?1:t.start>i?-1:0)),n||null}return null}function ii(t){switch(t.details){case Q.FRAG_LOAD_TIMEOUT:case Q.KEY_LOAD_TIMEOUT:case Q.LEVEL_LOAD_TIMEOUT:case Q.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function si(t){return t.details.startsWith("key")}function ri(t){return si(t)&&!!t.frag&&!t.frag.decryptdata}function ni(t,e){const i=ii(e);return t.default[(i?"timeout":"error")+"Retry"]}function ai(t,e){const i="linear"===t.backoff?1:Math.pow(2,e);return Math.min(i*t.retryDelayMs,t.maxRetryDelayMs)}function oi(t){return ut(ut({},t),{errorRetry:null,timeoutRetry:null})}function li(t,e,i,s){if(!t)return!1;const r=null==s?void 0:s.code,n=e<t.maxNumRetry&&(function(t){return di(t)||!!t&&(t<400||t>499)}(r)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,s,n):n}function di(t){return 0===t&&!1===navigator.onLine}var ci=0,ui=2,hi=3,fi=5,gi=0,mi=1,pi=2,vi=4;function yi(t){const e={action:ci,flags:gi};return t&&(e.resolved=!0),e}var Ei="NOT_LOADED",Ti="APPENDING",Si="PARTIAL",bi="OK";class Ai{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t&&(t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.BUFFER_APPENDED,this.onBufferAppended,this),t.on(J.FRAG_BUFFERED,this.onFragBuffered,this),t.on(J.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.BUFFER_APPENDED,this.onBufferAppended,this),t.off(J.FRAG_BUFFERED,this.onFragBuffered,this),t.off(J.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const i=this.activePartLists[e];if(i)for(let e=i.length;e--;){const s=i[e];if(!s)break;if(s.start<=t&&t<=s.end&&s.loaded)return s}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,i){const{fragments:s}=this,r=Object.keys(s);for(let n=r.length;n--;){const a=s[r[n]];if((null==a?void 0:a.body.type)===e&&(!i||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,i,s,r){this.timeRanges&&(this.timeRanges[t]=e);const n=(null==s?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach(s=>{const a=this.fragments[s];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||r))return void(a.body.type===i&&this.removeFragment(a.body));const o=a.range[t];o&&(0!==o.time.length?o.time.some(t=>{const i=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&this.removeFragment(a.body),i}):this.removeFragment(a.body))})}detectPartialFragments(t){const e=this.timeRanges;if(!e||"initSegment"===t.frag.sn)return;const i=t.frag,s=Li(i),r=this.fragments[s];if(!r||r.buffered&&i.gap)return;const n=!i.relurl;Object.keys(e).forEach(s=>{const a=i.elementaryStreams[s];if(!a)return;const o=e[s],l=n||!0===a.partial;r.range[s]=this.getBufferedTimes(i,t.part,l,o)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,i),ki(r)||this.removeParts(i.sn-1,i.type)):this.removeFragment(r.body)}bufferedEnd(t,e){t.buffered=!0;(t.body.endList=e.endList||t.body.endList)&&(this.endListFragments[t.body.type]=t)}removeParts(t,e){const i=this.activePartLists[e];i&&(this.activePartLists[e]=Ii(i,e=>e.fragment.sn>=t))}fragBuffered(t,e){const i=Li(t);let s=this.fragments[i];!s&&e&&(s=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,this.bufferedEnd(s,t))}getBufferedTimes(t,e,i,s){const r={time:[],partial:i},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<s.length;t++){const e=s.start(t)-this.bufferPadding,i=s.end(t)+this.bufferPadding;if(l>=e&&o<=i){r.time.push({startPTS:Math.max(n,s.start(t)),endPTS:Math.min(a,s.end(t))});break}if(n<i&&a>e){const e=Math.max(n,s.start(t)),i=Math.min(a,s.end(t));i>e&&(r.partial=!0,r.time.push({startPTS:e,endPTS:i}))}else if(a<=e)break}return r}getPartialFragment(t){let e,i,s,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&ki(d)&&(i=d.body.start-a,s=d.body.end+a,t>=i&&t<=s&&(e=Math.min(t-i,s-t),n<=e&&(r=d.body,n=e)))}),r}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||ki(e))}getState(t){const e=Li(t),i=this.fragments[e];return i?i.buffered?ki(i)?Si:bi:Ti:Ei}isTimeBuffered(t,e,i){let s,r;for(let n=0;n<i.length;n++){if(s=i.start(n)-this.bufferPadding,r=i.end(n)+this.bufferPadding,t>=s&&e<=r)return!0;if(e<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if("initSegment"===e.frag.sn||e.frag.bitrateTest)return;const i=e.frag,s=e.part?null:e,r=Li(i);this.fragments[r]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:s,timeRanges:r,type:n}=e;if("initSegment"===i.sn)return;const a=i.type;if(s){let t=this.activePartLists[a];t||(this.activePartLists[a]=t=[]),t.push(s)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,s)}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=Li(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,i=Object.keys(e);if(!t)return i.length>0;for(let s=i.length;s--;){const r=e[i[s]];if((null==r?void 0:r.body.type)===t)return!0}return!1}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,i,s,r){s&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==i||s&&!o.gap||o.start<e&&o.end>t&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(t){const e=Li(t);t.clearElementaryStreamInfo();const i=this.activePartLists[t.type];if(i){const e=t.sn;this.activePartLists[t.type]=Ii(i,t=>t.fragment.sn!==e)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const e=null==(t=this.hls)||null==(t=t.latestLevelDetails)?void 0:t.partList;e&&e.forEach(t=>t.clearElementaryStreamInfo())}}function ki(t){var e,i,s;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(i=t.range.audio)&&i.partial||null!=(s=t.range.audiovideo)&&s.partial)}function Li(t){return`${t.type}_${t.level}_${t.sn}`}function Ii(t,e){return t.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var wi=0,Ri=1;class _i{constructor(t,e,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=i}decrypt(t,e){switch(this.aesMode){case wi:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case Ri:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class Di{constructor(){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()}uint8ArrayToUint32Array_(t){const e=new DataView(t),i=new Uint32Array(4);for(let t=0;t<4;t++)i[t]=e.getUint32(4*t);return i}initTable(){const t=this.sBox,e=this.invSBox,i=this.subMix,s=i[0],r=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],d=o[1],c=o[2],u=o[3],h=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)h[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,t[f]=i,e[i]=f;const o=h[f],m=h[o],p=h[m];let v=257*h[i]^16843008*i;s[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[i]=v<<24|v>>>8,d[i]=v<<16|v>>>16,c[i]=v<<8|v>>>24,u[i]=v,f?(f=o^h[h[h[p^o]]],g^=h[h[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let i=!0,s=0;for(;s<e.length&&i;)i=e[s]===this.key[s],s++;if(i)return;this.key=e;const r=this.keySize=e.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),c=this.sBox,u=this.rcon,h=this.invSubMix,f=h[0],g=h[1],m=h[2],p=h[3];let v,y;for(a=0;a<n;a++)a<r?v=l[a]=e[a]:(y=v,a%r===0?(y=y<<8|y>>>24,y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y],y^=u[a/r|0]<<24):r>6&&a%r===4&&(y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?y:f[c[y>>>24]]^g[c[y>>>16&255]]^m[c[y>>>8&255]]^p[c[255&y]],d[o]=d[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,i){const s=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],c=a[3],u=this.uint8ArrayToUint32Array_(i);let h=u[0],f=u[1],g=u[2],m=u[3];const p=new Int32Array(t),v=new Int32Array(p.length);let y,E,T,S,b,A,k,L,I,w,R,_,D,P;const x=this.networkToHostOrderSwap;for(;e<p.length;){for(I=x(p[e]),w=x(p[e+1]),R=x(p[e+2]),_=x(p[e+3]),b=I^r[0],A=_^r[1],k=R^r[2],L=w^r[3],D=4,P=1;P<s;P++)y=o[b>>>24]^l[A>>16&255]^d[k>>8&255]^c[255&L]^r[D],E=o[A>>>24]^l[k>>16&255]^d[L>>8&255]^c[255&b]^r[D+1],T=o[k>>>24]^l[L>>16&255]^d[b>>8&255]^c[255&A]^r[D+2],S=o[L>>>24]^l[b>>16&255]^d[A>>8&255]^c[255&k]^r[D+3],b=y,A=E,k=T,L=S,D+=4;y=n[b>>>24]<<24^n[A>>16&255]<<16^n[k>>8&255]<<8^n[255&L]^r[D],E=n[A>>>24]<<24^n[k>>16&255]<<16^n[L>>8&255]<<8^n[255&b]^r[D+1],T=n[k>>>24]<<24^n[L>>16&255]<<16^n[b>>8&255]<<8^n[255&A]^r[D+2],S=n[L>>>24]<<24^n[b>>16&255]<<16^n[A>>8&255]<<8^n[255&k]^r[D+3],v[e]=x(y^h),v[e+1]=x(S^f),v[e+2]=x(T^g),v[e+3]=x(E^m),h=I,f=w,g=R,m=_,e+=4}return v.buffer}}class Pi{constructor(t,e,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=i}expandKey(){const t=function(t){switch(t){case wi:return"AES-CBC";case Ri:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}class xi{constructor(t,{removePKCS7Padding:e=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=t.enableSoftwareAES,this.removePKCS7Padding=e,e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const i=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const e=t.byteLength,i=e&&new DataView(t.buffer).getUint8(e-1);return i?t.slice(0,e-i):t}(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,i,s){return this.useSoftware?new Promise((r,n)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,i,s);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,i,s)}softwareDecrypt(t,e,i,s){const{currentIV:r,currentResult:n,remainderData:a}=this;if(s!==wi||16!==e.byteLength)return yt.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=ee(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;r&&(i=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Di),l.expandKey(e);const d=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,d||null}webCryptoDecrypt(t,e,i,s){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i,s));this.key=e,this.fastAesKey=new Pi(this.subtle,e,s)}return this.fastAesKey.expandKey().then(e=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new _i(this.subtle,new Uint8Array(i),s).decrypt(t.buffer,e)}).catch(r=>(yt.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,i,s)))}onWebCryptoError(t,e,i,s){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i,s);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const i=t.length-t.length%16;return i!==t.length&&(e=t.slice(0,i),this.remainderData=t.slice(i)),e}logOnce(t){this.logEnabled&&(yt.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const Ci=Math.pow(2,17);class Oi{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){const i=t.url;if(!i)return Promise.reject(new Ni({type:X.NETWORK_ERROR,details:Q.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(i?"part list":"url")),networkDetails:null}));this.abort();const s=this.config,r=s.fLoader,n=s.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some(t=>"GAP"===t[0]))return void o(Fi(t));t.gap=!1}const l=this.loader=r?new r(s):new n(s),d=Mi(t);t.loader=l;const c=oi(s.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:Ci};t.stats=l.stats;const h={onSuccess:(e,i,s,r)=>{this.resetLoader(t,l);let n=e.data;s.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:t,part:null,payload:n,networkDetails:r})},onError:(e,s,r,n)=>{this.resetLoader(t,l),o(new Ni({type:X.NETWORK_ERROR,details:Q.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:ut({url:i,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:r,stats:n}))},onAbort:(e,i,s)=>{this.resetLoader(t,l),o(new Ni({type:X.NETWORK_ERROR,details:Q.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:s,stats:e}))},onTimeout:(e,i,s)=>{this.resetLoader(t,l),o(new Ni({type:X.NETWORK_ERROR,details:Q.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:s,stats:e}))}};e&&(h.onProgress=(i,s,r,n)=>e({frag:t,part:null,payload:r,networkDetails:n})),l.load(d,u,h)})}loadPart(t,e,i){this.abort();const s=this.config,r=s.fLoader,n=s.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(Fi(t,e));const l=this.loader=r?new r(s):new n(s),d=Mi(t,e);t.loader=l;const c=oi(s.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ci};e.stats=l.stats,l.load(d,u,{onSuccess:(s,r,n,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const d={frag:t,part:e,payload:s.data,networkDetails:o};i(d),a(d)},onError:(i,s,r,n)=>{this.resetLoader(t,l),o(new Ni({type:X.NETWORK_ERROR,details:Q.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:ut({url:d.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:r,stats:n}))},onAbort:(i,s,r)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new Ni({type:X.NETWORK_ERROR,details:Q.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:r,stats:i}))},onTimeout:(i,s,r)=>{this.resetLoader(t,l),o(new Ni({type:X.NETWORK_ERROR,details:Q.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:r,stats:i}))}})})}updateStatsFromPart(t,e){const i=t.stats,s=e.stats,r=s.total;if(i.loaded+=s.loaded,r){const s=Math.round(t.duration/e.duration),n=Math.min(Math.round(i.loaded/r),s),a=(s-n)*Math.round(i.loaded/n);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const n=i.loading,a=s.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function Mi(t,e=null){const i=e||t,s={frag:t,part:e,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},r=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(Y(r)&&Y(n)){var a;let e=r,i=n;if("initSegment"===t.sn&&("AES-128"===(o=null==(a=t.decryptdata)?void 0:a.method)||"AES-256"===o)){const t=n-r;t%16&&(i=n+(16-t%16)),0!==r&&(s.resetIV=!0,e=r-16)}s.rangeStart=e,s.rangeEnd=i}var o;return s}function Fi(t,e){const i=new Error(`GAP ${t.gap?"tag":"attribute"} found`),s={type:X.MEDIA_ERROR,details:Q.FRAG_GAP,fatal:!1,frag:t,error:i,networkDetails:null};return e&&(s.part=e),(e||t).stats.aborted=!0,new Ni(s)}class Ni extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Ui extends ht{constructor(t,e){super(t,e),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Bi{constructor(t,e,i,s=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=e,this.id=i,this.size=s,this.part=r,this.partial=n}}const $i={length:0,start:()=>0,end:()=>0};class Gi{static isBuffered(t,e){if(t){const i=Gi.getBuffered(t);for(let t=i.length;t--;)if(e>=i.start(t)&&e<=i.end(t))return!0}return!1}static bufferedRanges(t){if(t){const e=Gi.getBuffered(t);return Gi.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let i=0;i<t.length;i++)e.push({start:t.start(i),end:t.end(i)});return e}static bufferInfo(t,e,i){if(t){const s=Gi.bufferedRanges(t);if(s.length)return Gi.bufferedInfo(s,e,i)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,i){e=Math.max(0,e),t.length>1&&t.sort((t,e)=>t.start-e.start||e.end-t.end);let s=-1,r=[];if(i)for(let n=0;n<t.length;n++){e>=t[n].start&&e<=t[n].end&&(s=n);const a=r.length;if(a){const e=r[a-1].end;t[n].start-e<i?t[n].end>e&&(r[a-1].end=t[n].end):r.push(t[n])}else r.push(t[n])}else r=t;let n,a=0,o=e,l=e;for(let t=0;t<r.length;t++){const d=r[t].start,c=r[t].end;if(-1===s&&e>=d&&e<=c&&(s=t),e+i>=d&&e<c)o=d,l=c,a=l-e;else if(e+i<d){n=d;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:t,bufferedIndex:s}}static getBuffered(t){try{return t.buffered||$i}catch(t){return yt.log("failed to get media.buffered",t),$i}}}const Vi=/\{\$([a-zA-Z0-9-_]+)\}/g;function Ki(t){return Vi.test(t)}function Hi(t,e){if(null!==t.variableList||t.hasVariableRefs){const i=t.variableList;return e.replace(Vi,e=>{const s=e.substring(2,e.length-1),r=null==i?void 0:i[s];return void 0===r?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),e):r})}return e}function ji(t,e,i){let s,r,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){s=e.QUERYPARAM;try{const t=new self.URL(i).searchParams;if(!t.has(s))throw new Error(`"${s}" does not match any query parameter in URI: "${i}"`);r=t.get(s)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else s=e.NAME,r=e.VALUE;s in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):n[s]=r||""}function qi(t,e,i){const s=e.IMPORT;if(i&&s in i){let e=t.variableList;e||(t.variableList=e={}),e[s]=i[s]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const Yi=/^(\d+)x(\d+)$/,Wi=/(.+?)=(".*?"|.*?)(?:,|$)/g;class zi{constructor(t,e){"string"==typeof t&&(t=zi.parseAttrList(t,e)),dt(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>"X-"===t.substring(0,2))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const i=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)i[t]=parseInt(e.slice(2*t,2*t+2),16);return i}return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const i=this[t];return i?parseFloat(i):e}enumeratedString(t){return this[t]}enumeratedStringList(t,e){const i=this[t];return(i?i.split(/[ ,]+/):[]).reduce((t,e)=>(t[e.toLowerCase()]=!0,t),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=Yi.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let i;const s={};for(Wi.lastIndex=0;null!==(i=Wi.exec(t));){const r=i[1].trim();let n=i[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(e&&(a||o))n=Hi(e,n);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":yt.warn(`${t}: attribute ${r} is missing quotes`)}s[r]=n}return s}}function Xi(t){return"ID"!==t&&"CLASS"!==t&&"CUE"!==t&&"START-DATE"!==t&&"DURATION"!==t&&"END-DATE"!==t&&"END-ON-NEXT"!==t}function Qi(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class Ji{constructor(t,e,i=0){var s;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==e?void 0:e.tagAnchor)||null,this.tagOrder=null!=(s=null==e?void 0:e.tagOrder)?s:i,e){const i=e.attr;for(const e in i)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==i[e]){yt.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=dt(new zi({}),i,t)}if(this.attr=t,e?(this._startDate=e._startDate,this._cue=e._cue,this._endDate=e._endDate,this._dateAtEnd=e._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=(null==e?void 0:e.endDate)||new Date(this.attr["END-DATE"]);Y(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(yt.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(Y(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&Y(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}class Zi{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,i=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!i||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(e=>{let i=e.decryptdata;return i||(e.setKeyFormat(t.keyFormat),i=e.decryptdata),!!i&&t.matches(i)})}get hasProgramDateTime(){return!!this.fragments.length&&Y(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(-1!==e){for(let i=t.length;i--;)if(t[i].index>e)return t[i].index;return e}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function ts(t,e){return t.length===e.length&&!t.some((t,i)=>t!==e[i])}function es(t,e){return!t&&!e||!(!t||!e)&&ts(t,e)}function is(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function ss(t){switch(t){case"AES-128":case"AES-256":return wi;case"AES-256-CTR":return Ri;default:throw new Error(`invalid full segment method ${t}`)}}function rs(t){return Uint8Array.from(atob(t),t=>t.charCodeAt(0))}function ns(t){return Uint8Array.from(unescape(encodeURIComponent(t)),t=>t.charCodeAt(0))}function as(t){const e=function(t,e,i){const s=t[e];t[e]=t[i],t[i]=s};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function os(t){const e=t.split(":");let i=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),s=t[t.length-1].split(",");if(2===s.length){const e="base64"===s[0],r=s[1];e?(t.splice(-1,1),i=rs(r)):i=function(t){const e=ns(t).subarray(0,16),i=new Uint8Array(16);return i.set(e,16-e.length),i}(r)}}return i}const ls="undefined"!=typeof self?self:void 0;var ds={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},cs="org.w3.clearkey",us="com.apple.streamingkeydelivery",hs="com.microsoft.playready",fs="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function gs(t){switch(t){case us:return ds.FAIRPLAY;case hs:return ds.PLAYREADY;case fs:return ds.WIDEVINE;case cs:return ds.CLEARKEY}}function ms(t){switch(t){case ds.FAIRPLAY:return us;case ds.PLAYREADY:return hs;case ds.WIDEVINE:return fs;case ds.CLEARKEY:return cs}}function ps(t){const{drmSystems:e,widevineLicenseUrl:i}=t,s=e?[ds.FAIRPLAY,ds.WIDEVINE,ds.PLAYREADY,ds.CLEARKEY].filter(t=>!!e[t]):[];return!s[ds.WIDEVINE]&&i&&s.push(ds.WIDEVINE),s}const vs=null!=ls&&null!=(ys=ls.navigator)&&ys.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var ys;function Es(t){const e=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),i=String.fromCharCode.apply(null,Array.from(e)),s=i.substring(i.indexOf("<"),i.length),r=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(r){const t=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(t){const e=rs(t).subarray(0,16);return as(e),e}}return null}let Ts={};class Ss{static clearKeyUriToKeyIdMap(){Ts={}}static setKeyIdForUri(t,e){Ts[t]=e}static addKeyIdForUri(t){const e=Object.keys(Ts).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,e),Ts[t]=i,i}constructor(t,e,i,s=[1],r=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=e,this.keyFormat=i,this.keyFormatVersions=s,this.iv=r,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!is(t),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(At(n)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&ts(t.keyFormatVersions,this.keyFormatVersions)&&es(t.iv,this.iv)&&es(t.keyId,this.keyId)}isSupported(){if(this.method){if(is(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case us:case fs:case hs:case cs:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t,e){if(!this.encrypted||!this.uri)return null;if(is(this.method)){let e=this.iv;e||("number"!=typeof t&&(yt.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),e=function(t){const e=new Uint8Array(16);for(let i=12;i<16;i++)e[i]=t>>8*(15-i)&255;return e}(t));return new Ss(this.method,this.uri,"identity",this.keyFormatVersions,e)}if(this.keyId){const t=Ts[this.uri];if(t&&!ts(this.keyId,t)&&Ss.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=os(this.uri);if(i)switch(this.keyFormat){case fs:if(this.pssh=i,!this.keyId){const t=function(t){const e=[];if(t instanceof ArrayBuffer){const i=t.byteLength;let s=0;for(;s+32<i;){const i=le(new DataView(t,s));e.push(i),s+=i.size}}return e}(i.buffer);if(t.length){var s;const e=t[0];this.keyId=null!=(s=e.kids)&&s.length?e.kids[0]:null}}this.keyId||(this.keyId=bs(e));break;case hs:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=oe(t,0,i),this.keyId=Es(i);break}default:{let t=i.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let t;t=function(t){const e=null==t?void 0:t[fs];if(e)return e.keyId;return null}(e),t||(t=bs(e),t||(t=Ts[this.uri])),t&&(this.keyId=t,Ss.setKeyIdForUri(this.uri,t))}return this}}function bs(t){const e=null==t?void 0:t[hs];if(e){const t=os(e.uri);if(t)return Es(t)}return null}const As=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,ks=/#EXT-X-MEDIA:(.*)/g,Ls=/^#EXT(?:INF|-X-TARGETDURATION):/m,Is=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),ws=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|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|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Rs{static findGroup(t,e){for(let i=0;i<t.length;i++){const s=t[i];if(s.id===e)return s}}static resolve(t,e){return wt.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Ls.test(t)}static parseMasterPlaylist(t,e){const i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Ki(t)},s=[];if(As.lastIndex=0,!t.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let r;for(;null!=(r=As.exec(t));)if(r[1]){var n;const t=new zi(r[1],i),a=Hi(i,r[2]),o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:Rs.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Cs(t.CODECS,o);const d=t["SUPPLEMENTAL-CODECS"];d&&(o.supplemental={},Cs(d,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||s.push(o),i.levels.push(o)}else if(r[3]){const t=r[3],s=r[4];switch(t){case"SESSION-DATA":{const t=new zi(s,i),e=t["DATA-ID"];e&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[e]=t);break}case"SESSION-KEY":{const t=Ps(s,e,i);t.encrypted&&t.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(t)):yt.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${s}"`);break}case"DEFINE":ji(i,new zi(s,i),e);break;case"CONTENT-STEERING":{const t=new zi(s,i);i.contentSteering={uri:Rs.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=xs(s)}}const a=s.length>0&&s.length<i.levels.length;return i.levels=a?s:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(t,e,i){let s;const r={},n=i.levels,a={AUDIO:n.map(t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec})),SUBTITLES:n.map(t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec})),"CLOSED-CAPTIONS":[]};let o=0;for(ks.lastIndex=0;null!==(s=ks.exec(t));){const t=new zi(s[1],i),n=t.TYPE;if(n){const i=a[n],s=r[n]||[];r[n]=s;const l=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],c=t.CHANNELS,u=t.CHARACTERISTICS,h=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?Rs.resolve(t.URI,e):""};if(d&&(f.assocLang=d),c&&(f.channels=c),u&&(f.characteristics=u),h&&(f.instreamId=h),null!=i&&i.length){const t=Rs.findGroup(i,f.groupId)||i[0];Os(f,t,"audioCodec"),Os(f,t,"textCodec")}s.push(f)}}return r}static parseLevelPlaylist(t,e,i,s,r,n){var a;const o={url:e},l=new Zi(e),d=l.fragments,c=[];let u,h,f,g,m=null,p=0,v=0,y=0,E=0,T=0,S=null,b=new Ot(s,o),A=-1,k=!1,L=null;if(Is.lastIndex=0,l.m3u8=t,l.hasVariableRefs=Ki(t),"#EXTM3U"!==(null==(a=Is.exec(t))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(u=Is.exec(t));){k&&(k=!1,b=new Ot(s,o),b.playlistOffset=y,b.setStart(y),b.sn=p,b.cc=E,T&&(b.bitrate=T),b.level=i,m&&(b.initSegment=m,m.rawProgramDateTime&&(b.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),L&&(b.setByteRange(L),L=null)));const t=u[1];if(t){b.duration=parseFloat(t);const e=(" "+u[2]).slice(1);b.title=e||null,b.tagList.push(e?["INF",t,e]:["INF",t])}else if(u[3]){if(Y(b.duration)){b.playlistOffset=y,b.setStart(y),f&&Ns(b,f,l),b.sn=p,b.level=i,b.cc=E,d.push(b);const t=(" "+u[3]).slice(1);b.relurl=Hi(l,t),Ms(b,S,c),S=b,y+=b.duration,p++,v=0,k=!0}}
vendor: 4,438 bytes, line 1
1else{if(u=u[0].match(ws),!u){yt.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h<u.length&&void 0===u[h];h++);const t=(" "+u[h]).slice(1),r=(" "+u[h+1]).slice(1),a=u[h+2]?(" "+u[h+2]).slice(1):null;switch(t){case"BYTERANGE":S?b.setByteRange(r,S):b.setByteRange(r);break;case"PROGRAM-DATE-TIME":b.rawProgramDateTime=r,b.tagList.push(["PROGRAM-DATE-TIME",r]),-1===A&&(A=d.length);break;case"PLAYLIST-TYPE":l.type&&Us(l,t,u),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?Us(l,t,u):d.length>0&&Bs(l,t,u),p=l.startSN=parseInt(r);break;case"SKIP":{l.skippedSegments&&Us(l,t,u);const e=new zi(r,l),i=e.decimalInteger("SKIPPED-SEGMENTS");if(Y(i)){l.skippedSegments+=i;for(let t=i;t--;)d.push(null);p+=i}const s=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(s.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&Us(l,t,u),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&Us(l,t,u),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Us(l,t,u),l.live=!1;break;case"#":(r||a)&&b.tagList.push(a?[r,a]:[r]);break;case"DISCONTINUITY":E++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([t]);break;case"BITRATE":b.tagList.push([t,r]),T=1e3*parseInt(r),Y(T)?b.bitrate=T:T=0;break;case"DATERANGE":{const t=new zi(r,l),e=new Ji(t,l.dateRanges[t.ID],l.dateRangeTagCount);l.dateRangeTagCount++,e.isValid||l.skippedSegments?l.dateRanges[e.id]=e:yt.warn(`Ignoring invalid DATERANGE tag: "${r}"`),b.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const t=new zi(r,l);"IMPORT"in t?qi(l,t,n):ji(l,t,e)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC?Us(l,t,u):d.length>0&&Bs(l,t,u),l.startCC=E=parseInt(r);break;case"KEY":{const t=Ps(r,e,l);if(t.isSupported()){if("NONE"===t.method){f=void 0;break}f||(f={});const e=f[t.keyFormat];null!=e&&e.matches(t)||(e&&(f=dt({},f)),f[t.keyFormat]=t)}else yt.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}"`);break}case"START":l.startTimeOffset=xs(r);break;case"MAP":{const t=new zi(r,l);if(b.duration){const e=new Ot(s,o);Fs(e,t,i,f),m=e,b.initSegment=m,m.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=m.rawProgramDateTime)}else{const e=b.byteRangeEndOffset;if(e){const t=b.byteRangeStartOffset;L=`${e-t}@${t}`}else L=null;Fs(b,t,i,f),m=b,k=!0}m.cc=E;break}case"SERVER-CONTROL":g&&Us(l,t,u),g=new zi(r),l.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),l.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&Us(l,t,u);const e=new zi(r);l.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=l.partList;t||(t=l.partList=[]);const e=v>0?t[t.length-1]:void 0,i=v++,s=new zi(r,l),n=new Mt(s,b,o,i,e);t.push(n),b.duration+=n.duration;break}case"PRELOAD-HINT":{const t=new zi(r,l);l.preloadHint=t;break}case"RENDITION-REPORT":{const t=new zi(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(t);break}default:yt.warn(`line parsed but not handled: ${u}`)}}}S&&!S.relurl?(d.pop(),y-=S.duration,l.partList&&(l.fragmentHint=S)):l.partList&&(Ms(b,S,c),b.cc=E,l.fragmentHint=b,f&&Ns(b,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const I=d.length,w=d[0],R=d[I-1];if(y+=l.skippedSegments*l.targetduration,y>0&&I&&R){l.averagetargetduration=y/I;const t=R.sn;l.endSN="initSegment"!==t?t:0,l.live||(R.endList=!0),A>0&&(!function(t,e){let i=t[e];for(let s=e;s--;){const e=t[s];if(!e)return;e.programDateTime=i.programDateTime-1e3*e.duration,i=e}}(d,A),w&&c.unshift(w))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,c.length&&l.dateRangeTagCount&&w&&_s(c,l),l.endCC=E,l}}function _s(t,e){let i=t.length;if(!i){if(!e.hasProgramDateTime)return;{const s=e.fragments[e.fragments.length-1];t.push(s),i++}}const s=t[i-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=s.ref;for(let s=i;s--;){var a;if((null==(a=t[s])?void 0:a.sn)<e.startSN)break;const i=Ds(e,d,t,s,r);if(-1!==i){l.tagAnchor=e.fragments[i].ref;break}}}}function Ds(t,e,i,s,r){const n=i[s];if(n){const o=n.programDateTime;if(e>=o||0===s){var a;
vendor: 4,162 bytes, line 1
1if(e<=o+1e3*(((null==(a=i[s+1])?void 0:a.start)||r)-n.start)){const r=i[s].sn-t.startSN;if(r<0)return-1;const n=t.fragments;if(n.length>i.length){for(let a=(i[s+1]||n[n.length-1]).sn-t.startSN;a>r;a--){const t=n[a].programDateTime;if(e>=t&&e<t+1e3*n[a].duration)return a}}return r}}}return-1}function Ps(t,e,i){var s,r;const n=new zi(t,i),a=null!=(s=n.METHOD)?s:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,c=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&yt.error(`Invalid IV: ${n.IV}`);const u=o?Rs.resolve(o,e):"",h=(d||"1").split("/").map(Number).filter(Number.isFinite);return new Ss(a,u,c,h,l,n.KEYID)}function xs(t){const e=new zi(t).decimalFloatingPoint("TIME-OFFSET");return Y(e)?e:null}function Cs(t,e){let i=(t||"").split(/[ ,]+/).filter(t=>t);["video","audio","text"].forEach(t=>{const s=i.filter(e=>ue(e,t));s.length&&(e[`${t}Codec`]=s.map(t=>t.split("/")[0]).join(","),i=i.filter(t=>-1===s.indexOf(t)))}),e.unknownCodecs=i}function Os(t,e,i){const s=e[i];s&&(t[i]=s)}function Ms(t,e,i){t.rawProgramDateTime?i.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function Fs(t,e,i,s){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=i,t.sn="initSegment",s&&(t.levelkeys=s),t.initSegment=null}function Ns(t,e,i){t.levelkeys=e;const{encryptedFragments:s}=i;s.length&&s[s.length-1].levelkeys===e||!Object.keys(e).some(t=>e[t].isCommonEncryption)||s.push(t)}function Us(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${i[0]})`)}function Bs(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${i[0]})`)}function $s(t,e){const i=e.startPTS;if(Y(i)){let s,r=0;e.sn>t.sn?(r=i-t.start,s=t):(r=t.start-i,s=e),s.duration!==r&&s.setDuration(r)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.setStart(t.start+(t.minEndPTS-t.start)):e.setStart(t.start+t.duration)}else e.setStart(Math.max(t.start-e.duration,0))}function Gs(t,e,i,s,r,n,a){s-i<=0&&(a.warn("Fragment should have a positive duration",e),s=i+e.duration,n=r+e.duration);let o=i,l=s;const d=e.startPTS,c=e.endPTS;if(Y(d)){const u=Math.abs(d-i);t&&u>t.totalduration?a.warn(`media timestamps and playlist times differ by ${u}s for level ${e.level} ${t.url}`):Y(e.deltaPTS)?e.deltaPTS=Math.max(u,e.deltaPTS):e.deltaPTS=u,o=Math.max(i,d),i=Math.min(i,d),r=void 0!==e.startDTS?Math.min(r,e.startDTS):r,l=Math.min(s,c),s=Math.max(s,c),n=void 0!==e.endDTS?Math.max(n,e.endDTS):n}const u=i-e.start;0!==e.start&&e.setStart(i),e.setDuration(s-e.start),e.startPTS=i,e.maxStartPTS=o,e.startDTS=r,e.endPTS=s,e.minEndPTS=l,e.endDTS=n;const h=e.sn;if(!t||h<t.startSN||h>t.endSN)return 0;let f;const g=h-t.startSN,m=t.fragments;for(m[g]=e,f=g;f>0;f--)$s(m[f],m[f-1]);for(f=g;f<m.length-1;f++)$s(m[f],m[f+1]);return t.fragmentHint&&$s(m[m.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,u}function Vs(t,e,i){if(t===e)return;let s=null;const r=t.fragments;for(let t=r.length-1;t>=0;t--){const e=r[t].initSegment;if(e){s=e;break}}let n;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,i){var s;const r=e.skippedSegments,n=Math.max(t.startSN,e.startSN)-e.startSN,a=(t.fragmentHint?1:0)+(r?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,o=e.startSN-t.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,d=null!=(s=t.fragmentHint)&&s.duration?t.fragments.concat(t.fragmentHint):t.fragments;for(let s=n;s<=a;s++){const n=d[o+s];let a=l[s];if(r&&!a&&n&&(a=e.fragments[s]=n),n&&a){i(n,a,s,l);const r=n.relurl,o=a.relurl;if(r&&Qs(r,o))return void(e.playlistParsingError=Ks(`media sequence mismatch ${a.sn}:`,t,e,n,a));if(n.cc!==a.cc)return void(e.playlistParsingError=Ks(`discontinuity sequence mismatch (${n.cc}!=${a.cc})`,t,e,n,a))}}}(t,e,(t,i,r,a)=>{if((!e.startCC||e.skippedSegments)&&i.cc!==t.cc){const s=t.cc-i.cc;for(let t=r;t<a.length;t++)a[t].cc+=s;e.endCC=a[a.length-1].cc}Y(t.startPTS)&&Y(t.endPTS)&&(i.setStart(i.startPTS=t.startPTS),i.startDTS=t.startDTS,i.maxStartPTS=t.maxStartPTS,i.endPTS=t.endPTS,i.endDTS=t.endDTS,i.minEndPTS=t.minEndPTS,i.setDuration(t.endPTS-t.startPTS),i.duration&&(n=i),e.PTSKnown=e.alignedSliding=!0),t.hasStream
vendor: 17,197 bytes, line 1
1s&&(i.elementaryStreams=t.elementaryStreams),i.loader=t.loader,t.hasStats&&(i.stats=t.stats),t.initSegment&&(i.initSegment=t.initSegment,s=t.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(s&&o.forEach(t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=s)?void 0:e.relurl)||(t.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(t=>!t),e.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=function(t,e,i){const{dateRanges:s,recentlyRemovedDateranges:r}=e,n=dt({},t);r&&r.forEach(t=>{delete n[t]});const a=Object.keys(n).length;if(!a)return s;return Object.keys(s).forEach(t=>{const e=n[t],r=new Ji(s[t].attr,e);r.isValid?(n[t]=r,e||(r.tagOrder+=a)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Ve(s[t].attr)}"`)}),n}(t.dateRanges,e,i));const s=t.fragments.filter(t=>t.rawProgramDateTime);if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let t=1;t<o.length;t++)null===o[t].programDateTime&&Ms(o[t],o[t-1],s);_s(s,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const i=Ys(t,e.startSN-1);e.startCC=null!=(l=null==i?void 0:i.cc)?l:a[0].cc}!function(t,e,i){if(t&&e){let s=0;for(let r=0,n=t.length;r<n;r++){const n=t[r],a=e[r+s];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?i(n,a):s--}}}(t.partList,e.partList,(t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats}),n?Gs(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,i):Hs(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const d=e.advancedDateTime;if(e.advanced&&d){const t=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=t),e.driftEndTime=d,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;-1===e.requestScheduled&&(e.requestScheduled=t.requestScheduled)}function Ks(t,e,i,s,r){return new Error(`${t} ${r.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${i.startSN}\n${i.m3u8}`)}function Hs(t,e,i=!0){const s=e.startSN+e.skippedSegments-t.startSN,r=t.fragments,n=s>=0;let a=0;if(n&&s<r.length)a=r[s].start;else if(n&&e.startSN===t.endSN+1)a=t.fragmentEnd;else if(n&&i)a=t.fragmentStart+s*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return;a=t.fragmentStart}js(e,a)}function js(t,e){if(e){const i=t.fragments;for(let s=t.skippedSegments;s<i.length;s++)i[s].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}function qs(t,e=1/0){let i=1e3*t.targetduration;if(t.updated){const s=t.fragments,r=4;if(s.length&&i*r>e){const t=1e3*s[s.length-1].duration;t<i&&(i=t)}}else i/=2;return Math.round(i)}function Ys(t,e,i){if(!t)return null;let s=t.fragments[e-t.startSN];return s||(s=t.fragmentHint,s&&s.sn===e?s:e<t.startSN&&i&&i.sn===e?i:null)}function Ws(t,e,i){return t?zs(t.partList,e,i):null}function zs(t,e,i){if(t)for(let s=t.length;s--;){const r=t[s];if(r.index===i&&r.fragment.sn===e)return r}return null}function Xs(t){t.forEach((t,e)=>{var i;null==(i=t.details)||i.fragments.forEach(t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)})})}function Qs(t,e){return!(t===e||!e)&&Js(t)!==Js(e)}function Js(t){return t.replace(/\?[^?]*$/,"")}function Zs(t,e){for(let s=0,r=t.length;s<r;s++){var i;if((null==(i=t[s])?void 0:i.cc)===e)return t[s]}return null}function tr(t,e){const i=t.start+e;t.startPTS=i,t.setStart(i),t.endPTS=i+t.duration}function er(t,e){const i=e.fragments;for(let e=0,s=i.length;e<s;e++)tr(i[e],t);e.fragmentHint&&tr(e.fragmentHint,t),e.alignedSliding=!0}function ir(t,e){if(!function(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}(e,t))return;const i=Math.min(e.endCC,t.endCC),s=Zs(e.fragments,i),r=Zs(t.fragments,i);if(!s||!r)return;yt.log(`Aligning playlist at start of dicontinuity sequence ${i}`);er(s.start-r.start,t)}function sr(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const i=t.fragments,s=e.fragments;if(!i.length||!s.length)return;let r,n;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(r=Zs(s,a),n=Zs(i,a)),r&&n||(r=s[Math.floor(s.length/2)],n=Zs(i,r.cc)||i[Math.floor(i.length/2)]);const o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;er((l-o)/1e3-(n.start-r.start),t)}function rr(t,e,i){nr(t,e,i),t.addEventListener(e,i)}function nr(t,e,i){t.removeEventListener(e,i)}const ar=function(t){let e="";const i=t.length;for(let s=0;s<i;s++)e+=`[${t.start(s).toFixed(3)}-${t.end(s).toFixed(3)}]`;return e},or="STOPPED",lr="IDLE",dr="KEY_LOADING",cr="FRAG_LOADING",ur="FRAG_LOADING_WAITING_RETRY",hr="WAITING_TRACK",fr="PARSING",gr="PARSED",mr="ENDED",pr="ERROR",vr="WAITING_INIT_PTS",yr="WAITING_LEVEL";class Er extends Ui{constructor(t,e,i,s,r){super(s,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=or,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:t,fragCurrent:e,media:i,mediaBuffer:s,state:r}=this,n=i?i.currentTime:0,a=Gi.bufferInfo(s||i,n,t.maxBufferHole),o=!a.len;if(this.log(`Media seeking to ${Y(n)?n.toFixed(3):n}, state: ${r}, ${o?"out of":"in"} buffer`),this.state===mr)this.resetLoadingState();else if(e){const i=t.maxFragLookUpTolerance,s=e.start-i,r=e.start+e.duration+i;if(o||r<a.start||s>a.end){const t=n>r;(n<s||t)&&(t&&e.loader&&(this.log(`Cancelling fragment load for seek (sn: ${e.sn})`),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(i){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const t=Math.max(a.end,n),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${t.toFixed(2)}`),this.loadingParts=e)}}this.hls.hasEnoughToStart||(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,o&&(this.startPosition=n)),o&&this.state===lr&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=t,this.fragmentLoader=new Oi(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new xi(t.config)}registerListeners(){const{hls:t}=this;t.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(J.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(J.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===or)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=or}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;return-1===e&&t?t:e}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const i=t.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;const r=t.buffered;this.config.maxBufferHole&&r&&r.length>1&&(t=Gi.bufferedInfo(r,t.start,0));const n=t.nextStart;if(n&&n>s&&n<e.edge)return!1;if(this.media.currentTime<t.start)return!1;const a=e.partList;if(null!=a&&a.length){const t=a[a.length-1];return Gi.isBuffered(this.media,t.start+t.duration/2)}const o=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;var e;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}onMediaAttached(t,e){const i=this.media=this.mediaBuffer=e.media;rr(i,"seeking",this.onMediaSeeking),rr(i,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===or&&this.startLoad(s.startPosition)}onMediaDetaching(t,e){const i=!!e.transferMedia,s=this.media;if(null!==s){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),nr(s,"seeking",this.onMediaSeeking),nr(s,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=or,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,i){this.startFragRequested=!0,this._loadFragForPlayback(t,e,i)}_loadFragForPlayback(t,e,i){this._doFragLoad(t,e,i,t=>{const e=t.frag;if(this.fragContextChanged(e))return this.warn(`${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)}).then(t=>{if(!t)return;const e=this.state,i=t.frag;this.fragContextChanged(i)?(e===cr||!this.fragCurrent&&e===fr)&&(this.fragmentTracker.removeFragment(i),this.state=lr):("payload"in t&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level}`),this.hls.trigger(J.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))}).catch(e=>{this.state!==or&&this.state!==pr&&(this.warn(`Frag error: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:i}=this;if(i.getState(t)===Ti){const e=t.type,s=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,s?s.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(r,t.duration))&&i.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===Si&&i.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&(this.levelLastLoaded!==t||e.expired)}flushMainBuffer(t,e,i=null){if(!(t-e))return;const s={startOffset:t,endOffset:e,type:i};this.hls.trigger(J.BUFFER_FLUSHING,s)}_loadInitSegment(t,e){this._doFragLoad(t,e).then(t=>{const e=null==t?void 0:t.frag;if(!e||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t}).then(t=>{const{hls:e}=this,{frag:i,payload:s}=t,r=i.decryptdata;if(s&&s.byteLength>0&&null!=r&&r.key&&r.iv&&is(r.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(s),r.key.buffer,r.iv.buffer,ss(r.method)).catch(t=>{throw e.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),t}).then(s=>{const r=self.performance.now();return e.trigger(J.FRAG_DECRYPTED,{frag:i,payload:s,stats:{tstart:n,tdecrypt:r}}),t.payload=s,this.completeInitSegmentLoad(t)})}return this.completeInitSegmentLoad(t)}).catch(e=>{this.state!==or&&this.state!==pr&&(this.warn(e),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const i=t.frag.stats;this.state!==or&&(this.state=lr),t.frag.data=new Uint8Array(t.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(t,e){var i,s;const r=t.tracks;if(r&&!e.encrypted&&(null!=(i=r.audio)&&i.encrypted||null!=(s=r.video)&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const t=this.media,i=new Error(`Encrypted track with no key in ${this.fragInfo(e)} (media ${t?"attached mediaKeys: "+t.mediaKeys:"detached"})`);return this.warn(i.message),!t||t.mediaKeys?!1:(this.hls.trigger(J.ERROR,{type:X.KEY_SYSTEM_ERROR,details:Q.KEY_SYSTEM_NO_KEYS,fatal:!1,error:i,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${i?ar(Gi.getBuffered(i)):"(detached)"})`),Ct(t)){var s;if(t.type!==nt){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return void(this.state=lr)}const e=null==(s=this.levels)?void 0:s[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=lr}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:i,part:s,partsLoaded:r}=t,n=!r||0===r.length||r.some(t=>!t),a=new Bi(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,i=null,s){var r;this.fragCurrent=t;const n=e.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!t.encrypted||null!=(r=t.decryptdata)&&r.key)t.encrypted||(a=this.keyLoader.loadClear(t,n.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${t.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=dr,this.fragCurrent=t,a=this.keyLoader.load(t).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(J.KEY_LOADED,t),this.state===dr&&(this.state=lr),t}),this.hls.trigger(J.KEY_LOADING,{frag:t}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const o=this.fragPrevious;if(Ct(t)&&(!o||t.sn!==o.sn)){const i=this.shouldLoadParts(e.details,t.end);i!==this.loadingParts&&(this.log(`LL-Part loading ${i?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${t.sn}`),this.loadingParts=i)}if(i=Math.max(t.start,i||0),this.loadingParts&&Ct(t)){const r=n.partList;if(r&&s){i>n.fragmentEnd&&n.fragmentHint&&(t=n.fragmentHint);const o=this.getNextPart(r,t,i);if(o>-1){const l=r[o];let d;return t=this.fragCurrent=l.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${l.index} (${o}/${r.length-1}) of ${this.fragInfo(t,!1,l)}) cc: ${t.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=cr,d=a?a.then(i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(t,l,e,s)).catch(t=>this.handleFragLoadError(t)):this.doFragPartsLoad(t,l,e,s).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(J.FRAG_LOADING,{frag:t,part:l,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!t.url||this.loadedEndOfParts(r,i))return Promise.resolve(null)}}var l;if(Ct(t)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${null==(l=n.partList)?void 0:l.filter(t=>t.loaded).map(t=>`[${t.start}-${t.end}]`)}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),Y(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=cr;const d=this.config.progressive&&t.type!==nt;
vendor: 13,236 bytes, line 1
1let c;return c=d&&a?a.then(e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,s)).catch(t=>this.handleFragLoadError(t)):Promise.all([this.fragmentLoader.load(t,d?s:void 0),a]).then(([t])=>(!d&&s&&s(t),t)).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(J.FRAG_LOADING,{frag:t,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(t,e,i,s){return new Promise((r,n)=>{var a;const o=[],l=null==(a=i.details)?void 0:a.partList,d=e=>{this.fragmentLoader.loadPart(t,e,s).then(s=>{o[e.index]=s;const n=s.part;this.hls.trigger(J.FRAG_LOADED,s);const a=Ws(i.details,t.sn,e.index+1)||zs(l,t.sn,e.index+1);if(!a)return r({frag:t,part:n,partsLoaded:o});d(a)}).catch(n)};d(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;e.frag&&e.details===Q.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):e.frag&&e.type===X.KEY_SYSTEM_ERROR?(e.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e.frag)):this.hls.trigger(J.ERROR,e)}else this.hls.trigger(J.ERROR,{type:X.OTHER_ERROR,details:Q.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==fr)return void(this.fragCurrent||this.state===or||this.state===pr||(this.state=lr));const{frag:i,part:s,level:r}=e,n=self.performance.now();i.stats.parsing.end=n,s&&(s.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(i,s,r,t.partial)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var i;const r=t.partList[0];if(r.fragment.type===nt)return!1;if(e>=r.end+((null==(i=t.fragmentHint)?void 0:i.duration)||0)){var s;if((this.hls.hasEnoughToStart?(null==(s=this.media)?void 0:s.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:i}=this,{level:s,sn:r,part:n}=t;if(null==e||!e[s])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const a=e[s],o=a.details,l=n>-1?Ws(o,r,n):null,d=l?l.fragment:Ys(o,r,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(t,e,i,s,r){if(this.state!==fr)return;const{data1:n,data2:a}=t;let o=n;if(a&&(o=ee(n,a)),!o.length)return;const l=this.initPTS[e.cc],d=l?-l.baseTime/l.timescale:void 0,c={type:t.type,frag:e,part:i,chunkMeta:s,offset:d,parent:e.type,data:o};if(this.hls.trigger(J.BUFFER_APPENDING,c),t.dropped&&t.independent&&!i){if(r)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!Gi.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const i=e.currentTime,s=Gi.bufferInfo(e,i,0),r=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(t.start-n,s.end-n),i+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var i;const s=this.getLoadPosition();if(!Y(s))return null;const r=this.lastCurrentTime>s||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,s,e,r)}getFwdBufferInfoAtPos(t,e,i,s){const r=Gi.bufferInfo(t,e,s);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,i);if(n&&(r.nextStart<=n.end||n.gap)){const i=Math.max(Math.min(r.nextStart,n.end)-e,s);return Gi.bufferInfo(t,e,i)}}return r}getMaxBufferLength(t){const{config:e}=this;let i;return i=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(i,e.maxMaxBufferLength)}exceedsMaxBuffer(t,e,i){const s=t.nextStart;if(s&&i.start>s){const s=t.buffered;if(s){let r=t.len;const n=t.bufferedIndex;for(let t=s.length-1;t>n;t--)s[t].start<i.start&&(r+=s[t].end-s[t].start);return r>=e}}return!1}reduceMaxBufferLength(t,e){const i=this.config,s=Math.max(Math.min(t-e,i.maxBufferLength),e),r=Math.max(t-3*e,i.maxMaxBufferLength/2,s);return r>=s&&(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(t,e=st){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,e):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(t,e){const i=e.fragments,s=i.length;if(!s)return null;const{config:r}=this,n=e.fragmentStart,a=r.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const i=r.initialLiveManifestSize;if(s<i)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${i})`),null;if(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(e);const i=this.config.startPosition,s=this.hls.startPosition,r=this.hls.liveSyncPosition,d=(null==(l=o)?void 0:l.start)||0;let c,u;-1!==s&&s>=n?(c=s,u=s===i?"config":"next load start"):null!==r?(c=r,u="live edge"):(c=t,u="buffer pos"),c<d&&(c=d,u="live frag start"),c<n&&(c=n,u="playlist start"),this.startPosition==c&&this.nextLoadPosition==c||(this.log(`Setting startPosition to ${c.toFixed(3)} ${-1===s?"":`(from ${i}) `}based on ${u}. live edge: ${r} live frag start: ${d.toFixed(3)} playlist start: ${n.toFixed(3)} buffer pos: ${t}`),this.startPosition=this.nextLoadPosition=c)}}else t<=n&&(o=i[0]);if(!o){const i=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,i,e)}let d=this.filterReplacedPrimary(o,e);if(!d&&o){const t=o.sn-e.startSN;d=this.filterReplacedPrimary(i[t+1]||null,e)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(t,e){if(this.nextLoadPosition<=e)return!1;const i=this.fragmentTracker.getState(t);return i===bi||i===Si&&!!t.gap}getNextFragmentLoopLoading(t,e,i,s,r){let n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&i.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(null!==t&&i.len+t.len>=r){const t=n.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(Tr(this.config)){var t;if(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,e){if(!t)return t;if(Tr(this.config)&&t.type!==nt){const i=this.hls.interstitialsManager,s=null==i?void 0:i.bufferingItem;if(s){const i=s.event;if(i){if(i.appendInPlace||Math.abs(t.start-s.start)>1||0===s.start)return null}else{if(t.end<=s.start&&!1===(null==e?void 0:e.live))return null;if(t.start>s.end&&s.nextEvent&&(s.nextEvent.appendInPlace||t.start-s.end>1))return null}}const r=null==i?void 0:i.playerQueue;if(r)for(let e=r.length;e--;){const i=r[e].interstitial;if(i.appendInPlace&&t.start>=i.startTime&&t.end<=i.resumeTime)return null}}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,i){let s=-1,r=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,s>-1&&i<o.start)break;const l=o.loaded;l?s=-1:(r||(o.independent||n)&&o.fragment===e)&&(o.fragment!==e&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${o.start}`),s=a),r=l}return s}loadedEndOfParts(t,e){let i;for(let s=t.length;s--;){if(i=t[s],!i.loaded)return!1;if(e>i.start)return!0}return!1}getInitialLiveFragment(t){const e=t.fragments,i=this.fragPrevious;let s=null;if(i){if(t.hasProgramDateTime&&(s=function(t,e,i){if(null===e||!Array.isArray(t)||!t.length||!Y(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;for(let s=0;s<t.length;++s){const r=t[s];if(ti(e,i,r))return r}return null}(e,i.endProgramDateTime,this.config.maxFragLookUpTolerance),s&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`)),!s){const r=i.sn+1;if(r>=t.startSN&&r<=t.endSN){const n=e[r-t.startSN];i.cc===n.cc&&(s=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=ei(t,i.cc,i.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(s=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return s}getFragmentAtPosition(t,e,i){const{config:s}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=s,d=i.partList,c=!!(this.loadingParts&&null!=d&&d.length&&o);let u;if(c&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),t<e){var h;u=Je(r,n,t,t<this.lastCurrentTime||t>e-l||null!=(h=this.media)&&h.paused||!this.startFragRequested?0:l)}else u=n[n.length-1];if(u){const t=u.sn-i.startSN,e=this.fragmentTracker.getState(u);if((e===bi||e===Si&&u.gap)&&(r=u),r&&u.sn===r.sn&&(!c||d[0].fragment.sn>u.sn||!i.live)){if(u.level===r.level){const e=n[t+1];u=u.sn<a&&this.fragmentTracker.getState(e)!==bi?e:null}}}return u}alignPlaylists(t,e,i){const s=t.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const r=t.fragmentStart,n=!e,a=t.alignedSliding&&Y(r);if(n||!a&&!r){!function(t,e){t&&(ir(e,t),e.alignedSliding||sr(e,t),e.alignedSliding||e.skippedSegments||Hs(t,e,!1))}(i,t);const r=t.fragmentStart;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${s}`),r}return r}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let i=this.startPosition;i<e&&(i=-1);const s=this.timelineOffset;if(-1===i){const r=null!==this.startTimeOffset,n=r?this.startTimeOffset:t.startTimeOffset;null!==n&&Y(n)?(i=e+n,n<0&&(i+=t.edge),i=Math.min(Math.max(e,i),e+t.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=i):t.live?(i=this.hls.liveSyncPosition||e,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+s}this.nextLoadPosition=i+s}getLoadPosition(){var t;const{media:e}=this;let i=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e?i=e.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&Ct(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===ur)||(this.state=lr)}onFragmentOrKeyLoadError(t,e){var i;if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const s=e.frag;if(!s||s.type!==t||!this.levels)return;var r;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const n=e.details===Q.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(s,!0);const a=e.errorAction;if(!a)return void(this.state=pr);const{action:o,flags:l,retryCount:d=0,retryConfig:c}=a,u=!!c,h=u&&o===fi,f=u&&!a.resolved&&l===mi,g=null==(i=this.hls.latestLevelDetails)?void 0:i.live;if(!h&&f&&Ct(s)&&!s.endList&&g&&!ri(e))this.resetFragmentErrors(t),this.treatAsGap(s),a.resolved=!0;else if((h||f)&&d<c.maxNumRetry){var m;const i=di(null==(m=e.response)?void 0:m.code),r=ai(c,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=ur,a.resolved=!0,i)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(e.reason="offline");this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${d+1}/${c.maxNumRetry} in ${r}ms`)}else if(c){if(this.resetFragmentErrors(t),!(d<c.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${d})`);n||o===hi||(a.resolved=!0)}else this.state=o===ui?yr:pr;this.tickImmediate()}checkRetryDate(){const t=self.performance.now(),e=this.retryDate,i=e===1/0;(!e||t>=e||i&&!di(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=lr)}reduceLengthAndFlushBuffer(t){if(this.state===fr||this.state===gr){const e=t.frag,i=t.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len,(null==e?void 0:e.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===rt&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==or&&(this.state=lr)}afterBufferFlushed(t,e,i){if(!t)return;const s=Gi.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,s,i),this.state===mr&&this.resetLoadingState()}
vendor: 29,830 bytes, line 1
1resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==or&&(this.state=lr)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.levelLastLoaded,e=t?t.details:null;null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${-1===t.level?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,s){const r=i.details;if(!r)return void this.warn("level.details undefined");if(!Object.keys(t.elementaryStreams).reduce((e,n)=>{const a=t.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${n} duration reliably (${o})`),e||!1;const l=s?0:Gs(r,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger(J.LEVEL_PTS_UPDATED,{details:r,level:i,drift:l,type:n,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e},!1)){var n;const e=null===(null==(n=this.transmuxer)?void 0:n.error);if((0===i.fragmentError||e&&(i.fragmentError<2||t.endList))&&this.treatAsGap(t,i),e){const e=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(e.message),this.hls.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=gr,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)})`),this.hls.trigger(J.FRAG_PARSED,{frag:t,part:e})}playlistLabel(){return this.playlistType===st?"level":"track"}fragInfo(t,e=!0,i){var s,r;return`${this.playlistLabel()} ${t.level} (${i?"part":"frag"}:[${(null!=(s=e&&!i?t.startPTS:(i||t).start)?s:NaN).toFixed(3)}-${(null!=(r=e&&!i?t.endPTS:(i||t).end)?r:NaN).toFixed(3)}]${i&&"main"===t.type?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(t,e){e&&e.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}function Tr(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}class Sr{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let i;return t.length?(i=1===t.length?t[0]:function(t,e){const i=new Uint8Array(e);let s=0;for(let e=0;e<t.length;e++){const r=t[e];i.set(r,s),s+=r.length}return i}(t,e),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var br,Ar={exports:{}};var kr=(br||(br=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function s(){}function r(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function n(t,e,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||t,a),l=i?i+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0===--t._eventsCount?t._events=new s:delete t._events[e]}function o(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(i=!1)),o.prototype.eventNames=function(){var t,s,r=[];if(0===this._eventsCount)return r;for(s in t=this._events)e.call(t,s)&&r.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=i?i+t:t,s=this._events[e];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,n=s.length,a=new Array(n);r<n;r++)a[r]=s[r].fn;return a},o.prototype.listenerCount=function(t){var e=i?i+t:t,s=this._events[e];return s?s.fn?1:s.length:0},o.prototype.emit=function(t,e,s,r,n,a){var o=i?i+t:t;if(!this._events[o])return!1;var l,d,c=this._events[o],u=arguments.length;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,s),!0;case 4:return c.fn.call(c.context,e,s,r),!0;case 5:return c.fn.call(c.context,e,s,r,n),!0;case 6:return c.fn.call(c.context,e,s,r,n,a),!0}for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];c.fn.apply(c.context,l)}else{var h,f=c.length;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(t,c[d].fn,void 0,!0),u){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,e);break;case 3:c[d].fn.call(c[d].context,e,s);break;case 4:c[d].fn.call(c[d].context,e,s,r);break;default:if(!l)for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];c[d].fn.apply(c[d].context,l)}}return!0},o.prototype.on=function(t,e,i){return n(this,t,e,i,!1)},o.prototype.once=function(t,e,i){return n(this,t,e,i,!0)},o.prototype.removeListener=function(t,e,s,r){var n=i?i+t:t;if(!this._events[n])return this;if(!e)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==e||r&&!o.once||s&&o.context!==s||a(this,n);else{for(var l=0,d=[],c=o.length;l<c;l++)(o[l].fn!==e||r&&!o[l].once||s&&o[l].context!==s)&&d.push(o[l]);d.length?this._events[n]=1===d.length?d[0]:d:a(this,n)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=i?i+t:t,this._events[e]&&a(this,e)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,t.exports=o}(Ar)),Ar.exports),Lr=kt(kr);const Ir="1.6.18",wr={};function Rr(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function _r(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function Dr(t,e){let i=0;return i=(127&t[e])<<21,i|=(127&t[e+1])<<14,i|=(127&t[e+2])<<7,i|=127&t[e+3],i}function Pr(t,e){const i=e;let s=0;for(;_r(t,e);){s+=10;s+=Dr(t,e+6),Rr(t,e+10)&&(s+=10),e+=s}if(s>0)return t.subarray(i,i+s)}function xr(t,e){return 255===t[e]&&240==(246&t[e+1])}function Cr(t,e){return 1&t[e+1]?7:9}function Or(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Mr(t,e){return e+1<t.length&&xr(t,e)}function Fr(t,e){if(Mr(t,e)){const i=Cr(t,e);if(e+i>=t.length)return!1;const s=Or(t,e);if(s<=i)return!1;const r=e+s;return r===t.length||Mr(t,r)}return!1}function Nr(t,e,i,s,r){if(!t.samplerate){const n=function(t,e,i,s){const r=e[i+2],n=r>>2&15;if(n>12){const e=new Error(`invalid ADTS sampling index:${n}`);return void t.emit(J.ERROR,J.ERROR,{type:X.MEDIA_ERROR,details:Q.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const a=1+(r>>6&3),o=e[i+3]>>6&3|(1&r)<<2,l="mp4a.40."+a,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let c=n;5!==a&&29!==a||(c-=3);const u=[a<<3|(14&c)>>1,(1&c)<<7|o<<3];return yt.log(`manifest codec:${s}, parsed codec:${l}, channels:${o}, rate:${d} (ADTS object type:${a} sampling index:${n})`),{config:u,samplerate:d,channelCount:o,codec:l,parsedCodec:l,manifestCodec:s}}(e,i,s,r);if(!n)return;dt(t,n)}}function Ur(t){return 9216e4/t}function Br(t,e,i,s,r){const n=s+r*Ur(t.samplerate),a=function(t,e){const i=Cr(t,e);if(e+i<=t.length){const s=Or(t,e)-i;if(s>0)return{headerLength:i,frameLength:s}}}(e,i);let o;if(a){const{frameLength:s,headerLength:r}=a,l=r+s,d=Math.max(0,i+l-e.length);d?(o=new Uint8Array(l-r),o.set(e.subarray(i+r,e.length),0)):o=e.subarray(i+r,i+l);const c={unit:o,pts:n};return d||t.samples.push(c),{sample:c,length:l,missing:d}}const l=e.length-i;o=new Uint8Array(l),o.set(e.subarray(i,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function $r(t,e){return _r(t,e)&&Dr(t,e+6)+10<=t.length-e}function Gr(t,e=0,i=1/0){return function(t,e,i,s){const r=function(t){return t instanceof ArrayBuffer?t:t.buffer}(t);let n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);const a=(u=t,u&&u.buffer instanceof ArrayBuffer&&void 0!==u.byteLength&&void 0!==u.byteOffset?t.byteOffset:0),o=(a+t.byteLength)/n,l=(a+e)/n,d=Math.floor(Math.max(0,Math.min(l,o))),c=Math.floor(Math.min(d+Math.max(i,0),o));var u;return new s(r,d,c-d)}(t,e,i,Uint8Array)}function Vr(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const i=t.data.subarray(1).indexOf(0);if(-1===i)return;const s=St(Gr(t.data,1,i)),r=t.data[2+i],n=t.data.subarray(3+i).indexOf(0);if(-1===n)return;const a=St(Gr(t.data,3+i,n));let o;return o="--\x3e"===s?St(Gr(t.data,4+i+n)):function(t){return t instanceof ArrayBuffer?t:0==t.byteOffset&&t.byteLength==t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}(t.data.subarray(4+i+n)),e.mimeType=s,e.pictureType=r,e.description=a,e.data=o,e}function Kr(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=St(t.data,!0),i=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:i.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const i=St(t.data.subarray(e),!0);e+=i.length+1;const s=St(t.data.subarray(e));return{key:t.type,info:i,data:s}}const e=St(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?Vr(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const i=St(t.data.subarray(e),!0);e+=i.length+1;const s=St(t.data.subarray(e));return{key:t.type,info:i,data:s}}const e=St(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function Hr(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),i=Dr(t,4);return{type:e,size:i,data:t.subarray(10,10+i)}}function jr(t){let e=0;const i=[];for(;_r(t,e);){const s=Dr(t,e+6);t[e+5]>>6&1&&(e+=10),e+=10;const r=e+s;for(;e+10<r;){const s=Hr(t.subarray(e)),r=Kr(s);r&&i.push(r),e+=s.size+10}Rr(t,e)&&(e+=10)}return i}function qr(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function Yr(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),i=1&e[3];let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,i&&(s+=47721858.84),Math.round(s)}}function Wr(t){const e=jr(t);for(let t=0;t<e.length;t++){const i=e[t];if(qr(i))return Yr(i)}}let zr=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function Xr(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Qr{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(t,e,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,i){}demux(t,e){this.cachedData&&(t=ee(this.cachedData,t),this.cachedData=null);let i,s=Pr(t,0),r=s?s.length:0;const n=this._audioTrack,a=this._id3Track,o=s?Wr(s):void 0,l=t.length;for((null===this.basePTS||0===this.frameIndex&&Y(o))&&(this.basePTS=Jr(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),s&&s.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:zr.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(t,r)){const e=this.appendFrame(n,t,r);e?(this.frameIndex++,this.lastPTS=e.sample.pts,r+=e.length,i=r):r=l}else $r(t,r)?(s=Pr(t,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:zr.audioId3,duration:Number.POSITIVE_INFINITY}),r+=s.length,i=r):r++;if(r===l&&i!==l){const e=t.slice(i);this.cachedData?this.cachedData=ee(this.cachedData,e):this.cachedData=e}}return{audioTrack:n,videoTrack:Xr(),id3Track:a,textTrack:Xr()}}demuxSampleAes(t,e,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:Xr(),id3Track:this._id3Track,textTrack:Xr()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Jr=(t,e,i)=>{if(Y(t))return 90*t;return 9e4*e+(i?9e4*i.baseTime/i.timescale:0)};let Zr=null;const tn=[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],en=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],sn=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],rn=[0,1,1,4];function nn(t,e,i,s,r){if(i+24>e.length)return;const n=an(e,i);if(n&&i+n.frameLength<=e.length){const a=s+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(i,i+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function an(t,e){const i=t[e+1]>>3&3,s=t[e+1]>>1&3,r=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==i&&0!==r&&15!==r&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*tn[14*(3===i?3-s:3===s?3:4)+r-1],d=en[3*(3===i?0:2===i?1:2)+n],c=3===o?1:2,u=sn[i][s],h=rn[s],f=8*u*h,g=Math.floor(u*l/d+a)*h;if(null===Zr){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Zr=t?parseInt(t[1]):0}return!!Zr&&Zr<=87&&2===s&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:d,channelCount:c,frameLength:g,samplesPerFrame:f}}}function on(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function ln(t,e){return e+1<t.length&&on(t,e)}function dn(t,e){if(e+1<t.length&&on(t,e)){const i=4,s=an(t,e);let r=i;null!=s&&s.frameLength&&(r=s.frameLength);const n=e+r;return n===t.length||ln(t,n)}return!1}const cn=(t,e)=>{let i=0,s=5;e+=s;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=t[e];const o=Math.min(s,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,i=i?i<<o|r[0]:r[0],e+=1,s-=o}return i};class un extends Qr{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,i){const s=hn(t,e,i,this.basePTS,this.frameIndex);if(-1!==s){return{sample:t.samples[t.samples.length-1],length:s,missing:0}}}static probe(t){if(!t)return!1;const e=Pr(t,0);if(!e)return!1;const i=e.length;return 11===t[i]&&119===t[i+1]&&void 0!==Wr(e)&&cn(t,i)<16}}function hn(t,e,i,s,r){if(i+8>e.length)return-1;if(11!==e[i]||119!==e[i+1])return-1;const n=e[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(i+l>e.length)return-1;const d=e[i+6]>>5;let c=0;2===d?c+=2:(1&d&&1!==d&&(c+=2),4&d&&(c+=2));const u=(e[i+6]<<8|e[i+7])>>12-c&1,h=[2,1,2,3,3,4,4,5][d]+u,f=e[i+5]>>3,g=7&e[i+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|d<<3|u<<2|o>>4,o<<4&224]),p=s+r*(1536/a*9e4),v=e.subarray(i,i+l);return t.config=m,t.channelCount=h,t.samplerate=a,t.samples.push({unit:v,pts:p}),l}const fn=/\/emsg[-/]ID3/i;function gn(t,e){return Y(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}class mn{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new xi(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,wi)}decryptAacSample(t,e,i){const s=t[e].unit;if(s.length<=16)return;const r=s.subarray(16,s.length-s.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(r=>{const n=new Uint8Array(r);s.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,i)}).catch(i)}decryptAacSamples(t,e,i){for(;;e++){if(e>=t.length)return void i();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,i=new Int8Array(e);let s=0;for(let e=32;e<t.length-16;e+=160,s+=16)i.set(t.subarray(e,e+16),s);return i}getAvcDecryptedUnit(t,e){const i=new Uint8Array(e);let s=0;for(let e=32;e<t.length-16;e+=160,s+=16)t.set(i.subarray(s,s+16),e);return t}decryptAvcSample(t,e,i,s,r){const n=ae(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,i+1,s)}).catch(s)}decryptAvcSamples(t,e,i,s){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length)return void s();const r=t[e].units;for(;!(i>=r.length);i++){const n=r[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,i,s,n),this.decrypter.isSync())))return}}}}class pn{constructor(){this.VideoSample=null}createVideoSample(t,e,i){return{key:t,frame:!1,pts:e,dts:i,units:[],length:0}}getLastNalUnit(t){var e;let i,s=this.VideoSample;if(s&&0!==s.units.length||(s=t[t.length-1]),null!=(e=s)&&e.units){const t=s.units;i=t[t.length-1]}return i}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const i=e.samples,s=i.length;if(!s)return void e.dropped++;{const e=i[s-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,i){const s=e.byteLength;let r=t.naluState||0;const n=r,a=[];let o,l,d,c=0,u=-1,h=0;for(-1===r&&(u=0,h=this.getNALuType(e,0),r=0,c=1);c<s;)if(o=e[c++],r)if(1!==r)if(o)if(1===o){if(l=c-r-1,u>=0){const t={data:e.subarray(u,l),type:h};a.push(t)}else{const i=this.getLastNalUnit(t.samples);i&&(n&&c<=4-n&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-n)),l>0&&(i.data=ee(i.data,e.subarray(0,l)),i.state=0))}c<s?(d=this.getNALuType(e,c),u=c,h=d,r=0):r=-1}else r=0;else r=3;else r=o?0:2;else r=o?0:1;if(u>=0&&r>=0){const t={data:e.subarray(u,s),type:h,state:r};a.push(t)}if(0===a.length){const i=this.getLastNalUnit(t.samples);i&&(i.data=ee(i.data,e))}return t.naluState=r,a}}class vn{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,i=t.byteLength-e,s=new Uint8Array(4),r=Math.min(4,e);if(0===r)throw new Error("no bytes available");s.set(t.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const i=this.word>>>32-e;if(t>32&&yt.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?i<<e|this.readBits(e):i}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class yn extends pn{parsePES(t,e,i,s){const r=this.parseNALu(t,i.data,s);let n,a=this.VideoSample,o=!1;i.data=null,a&&r.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(s=>{var r,l;switch(s.type){case 1:{let e=!1;n=!0;const r=s.data;if(o&&r.length>4){const t=this.readSliceType(r);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var d;if(e)null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=e;break}case 5:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,ne(s.data,1,i.pts,e.samples);break;case 7:{var c,u;n=!0,o=!0;const e=s.data,i=this.readSPS(e);if(!t.sps||t.width!==i.width||t.height!==i.height||(null==(c=t.pixelRatio)?void 0:c[0])!==i.pixelRatio[0]||(null==(u=t.pixelRatio)?void 0:u[1])!==i.pixelRatio[1]){t.width=i.width,t.height=i.height,t.pixelRatio=i.pixelRatio,t.sps=[e];const s=e.subarray(1,4);let r="avc1.";for(let t=0;t<3;t++){let e=s[t].toString(16);e.length<2&&(e="0"+e),r+=e}t.codec=r}break}case 8:n=!0,t.pps=[s.data];break;case 9:n=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(s)}}),s&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new vn(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let i,s=8,r=8;for(let n=0;n<t;n++)0!==r&&(i=e.readEG(),r=(s+i+256)%256),s=0===r?s:r}readSPS(t){const e=new vn(t);let i,s,r,n=0,a=0,o=0,l=0;const d=e.readUByte.bind(e),c=e.readBits.bind(e),u=e.readUEG.bind(e),h=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),m=e.skipUEG.bind(e),p=this.skipScalingList.bind(this);d();const v=d();if(c(5),f(3),d(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const t=u();if(3===t&&f(1),m(),m(),f(1),h())for(s=3!==t?8:12,r=0;r<s;r++)h()&&p(r<6?16:64,e)}m();const y=u();if(0===y)u();else if(1===y)for(f(1),g(),g(),i=u(),r=0;r<i;r++)g();m(),f(1);const E=u(),T=u(),S=c(1);0===S&&f(1),f(1),h()&&(n=u(),a=u(),o=u(),l=u());let b=[1,1];if(h()&&h()){switch(d()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:b=[d()<<8|d(),d()<<8|d()]}}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:b}}}class En extends pn{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,i,s){const r=this.parseNALu(t,i.data,s);let n,a=this.VideoSample,o=!1;i.data=null,a&&r.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(s=>{var r,l;switch(s.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var d;if(n=!0,o)null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:n=!0,ne(s.data,2,i.pts,e.samples);break;case 32:n=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=dt(t.params,this.readVPS(s.data)),this.initVPS=s.data),t.vps=[s.data];break;case 33:if(n=!0,o=!0,void 0===t.vps||t.vps[0]===this.initVPS||void 0===t.sps||this.matchSPS(t.sps[0],s.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const e=this.readSPS(s.data);t.width=e.width,t.height=e.height,t.pixelRatio=e.pixelRatio,t.codec=e.codecString,t.sps=[],"object"!=typeof t.params&&(t.params={});for(const i in e.params)t.params[i]=e.params[i]}this.pushParameterSet(t.sps,s.data,t.vps),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];const e=this.readPPS(s.data);for(const i in e)t.params[i]=e[i]}this.pushParameterSet(t.pps,s.data,t.vps)}break;case 35:n=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:n=!1}if(a&&n){a.units.push(s)}}),s&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}pushParameterSet(t,e,i){(i&&i[0]===this.initVPS||!i&&!t.length)&&t.push(e)}getNALuType(t,e){return(126&t[e])>>>1}ebsp2rbsp(t){const e=new Uint8Array(t.byteLength);let i=0;for(let s=0;s<t.byteLength;s++)s>=2&&3===t[s]&&0===t[s-1]&&0===t[s-2]||(e[i]=t[s],i++);return new Uint8Array(e.buffer,0,i)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){const e=new vn(t);e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6);return{numTemporalLayers:e.readBits(3)+1,temporalIdNested:e.readBoolean()}}readSPS(t){const e=new vn(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const i=e.readBits(3);e.readBoolean();const s=e.readBits(2),r=e.readBoolean(),n=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),d=e.readUByte(),c=e.readUByte(),u=e.readUByte(),h=e.readUByte(),f=e.readUByte(),g=e.readUByte(),m=e.readUByte(),p=e.readUByte(),v=[],y=[];for(let t=0;t<i;t++)v.push(e.readBoolean()),y.push(e.readBoolean());if(i>0)for(let t=i;t<8;t++)e.readBits(2);for(let t=0;t<i;t++)v[t]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),y[t]&&e.readUByte();e.readUEG();const E=e.readUEG();3==E&&e.skipBits(1);const T=e.readUEG(),S=e.readUEG(),b=e.readBoolean();let A=0,k=0,L=0,I=0;b&&(A+=e.readUEG(),k+=e.readUEG(),L+=e.readUEG(),I+=e.readUEG());const w=e.readUEG(),R=e.readUEG(),_=e.readUEG();for(let t=e.readBoolean()?0:i;t<=i;t++)e.skipUEG(),e.skipUEG(),e.skipUEG();e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG();if(e.readBoolean()){if(e.readBoolean())for(let t=0;t<4;t++)for(let i=0;i<(3===t?2:6);i++){if(e.readBoolean()){const i=Math.min(64,1<<4+(t<<1));t>1&&e.readEG();for(let t=0;t<i;t++)e.readEG()}else e.readUEG()}}e.readBoolean(),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());const D=e.readUEG();let P=0;for(let t=0;t<D;t++){let i=!1;if(0!==t&&(i=e.readBoolean()),i){t===D&&e.readUEG(),e.readBoolean(),e.readUEG();let i=0;for(let t=0;t<=P;t++){const t=e.readBoolean();let s=!1;t||(s=e.readBoolean()),(t||s)&&i++}P=i}else{const t=e.readUEG(),i=e.readUEG();P=t+i;for(let i=0;i<t;i++)e.readUEG(),e.readBoolean();for(let t=0;t<i;t++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){const t=e.readUEG();for(let i=0;i<t;i++){for(let t=0;t<_+4;t++)e.readBits(1);e.readBits(1)}}let x=0,C=1,O=1,M=!0,F=1,N=0;e.readBoolean(),e.readBoolean();let U=!1;if(e.readBoolean()){if(e.readBoolean()){const t=e.readUByte();t>0&&t<16?(C=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],O=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(C=e.readBits(16),O=e.readBits(16))}e.readBoolean()&&e.readBoolean();if(e.readBoolean()){e.readBits(3),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.readUByte(),e.readUByte())}e.readBoolean()&&(e.readUEG(),e.readUEG()),e.readBoolean(),e.readBoolean(),e.readBoolean(),U=e.readBoolean(),U&&(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG());if(e.readBoolean()){F=e.readBits(32),N=e.readBits(32);e.readBoolean()&&e.readUEG();if(e.readBoolean()){const t=e.readBoolean(),s=e.readBoolean();let r=!1;(t||s)&&(r=e.readBoolean(),r&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),r&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=i;n++){M=e.readBoolean();let i=!1;M||e.readBoolean()?e.readEG():i=e.readBoolean();const n=i?1:e.readUEG()+1;if(t)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(s)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),x=e.readUEG())}let B=T,$=S;if(b){let t=1,e=1;1===E?t=e=2:2==E&&(t=2),B=T-t*k-t*A,$=S-e*I-e*L}const G=s?["A","B","C"][s]:"",V=a<<24|o<<16|l<<8|d;let K=0;for(let t=0;t<32;t++)K=(K|(V>>t&1)<<31-t)>>>0;let H=K.toString(16);1===n&&"2"===H&&(H="6");return{codecString:`hvc1.${G}${n}.${H}.${r?"H":"L"}${p}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:s,general_profile_compatibility_flags:[a,o,l,d],general_constraint_indicator_flags:[c,u,h,f,g,m],general_level_idc:
vendor: 4,468 bytes, line 1
1p,bit_depth:w+8,bit_depth_luma_minus8:w,bit_depth_chroma_minus8:R,min_spatial_segmentation_idc:x,chroma_format_idc:E,frame_rate:{fixed:M,fps:N/F}},width:B,height:$,pixelRatio:[C,O]}}readPPS(t){const e=new vn(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.skipUEG(),e.skipUEG(),e.skipBits(2),e.skipBits(3),e.skipBits(2),e.skipUEG(),e.skipUEG(),e.skipEG(),e.skipBits(2);e.readBoolean()&&e.skipUEG(),e.skipEG(),e.skipEG(),e.skipBits(4);const i=e.readBoolean(),s=e.readBoolean();let r=1;return s&&i?r=0:s?r=3:i&&(r=2),{parallelismType:r}}matchSPS(t,e){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,e).substr(3)}}const Tn=188;class Sn{constructor(t,e,i,s){this.logger=void 0,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._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=e,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(t,e){const i=Sn.syncOffset(t);return i>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(t){const e=t.length;let i=Math.min(940,e-Tn)+1,s=0;for(;s<i;){let r=!1,n=-1,a=0;for(let o=s;o<e;o+=Tn){if(71!==t[o]||e-o!==Tn&&71!==t[o+Tn]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(i=Math.min(n+18612,t.length-Tn)+1)),r||(r=0===bn(t,o)),r&&a>1&&(0===n&&a>2||o+Tn>i))return n}s++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:Bt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,i,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Sn.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=Sn.createTrack("audio",s),this._id3Track=Sn.createTrack("id3"),this._txtTrack=Sn.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:i}=this;t&&(t.pesData=null),e&&(e.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,i=!1,s=!1){let r;i||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let d=n.pid,c=n.pesData,u=a.pid,h=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,v=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=ee(this.remainderData,t)).length,this.remainderData=null),y<Tn&&!s)return this.remainderData=t,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const E=Math.max(0,Sn.syncOffset(t));y-=(y-E)%Tn,y<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let T=0;for(let e=E;e<y;e+=Tn)if(71===t[e]){const s=!!(64&t[e+1]),y=bn(t,e);let T;if((48&t[e+3])>>4>1){if(T=e+5+t[e+4],T===e+Tn)continue}else T=e+4;switch(y){case d:s&&(c&&(r=wn(c,this.logger))&&(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(n,l,r,!1)),c={data:[],size:0}),c&&(c.data.push(t.subarray(T,e+Tn)),c.size+=e+Tn-T);break;case u:if(s){if(f&&(r=wn(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,r);break;case"mp3":this.parseMPEGPES(a,r);break;case"ac3":this.parseAC3PES(a,r)}f={data:[],size:0}}f&&(f.data.push(t.subarray(T,e+Tn)),f.size+=e+Tn-T);break;case h:s&&(g&&(r=wn(g,this.logger))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(t.subarray(T,e+Tn)),g.size+=e+Tn-T);break;case 0:s&&(T+=t[T]+1),v=this._pmtId=An(t,T);break;case v:{s&&(T+=t[T]+1);const r=kn(t,T,this.typeSupported,i,this.observer,this.logger);d=r.videoPid,d>0&&(n.pid=d,n.segmentCodec=r.segmentVideoCodec),u=r.audioPid,u>0&&(a.pid=u,a.segmentCodec=r.segmentAudioCodec),h=r.id3Pid,h>0&&(o.pid=h),null===m||p||(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${m}'. Backtracking to sync byte @${E} to parse all TS packets.`),m=null,e=E-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=y}}else T++;T>0&&Ln(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=c,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return s&&this.extractRemainingSamples(S),S}flush(){const{remainderData:t}=this;let e;
vendor: 4,380 bytes, line 1
1return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:i,id3Track:s,textTrack:r}=t,n=i.pesData,a=e.pesData,o=s.pesData;let l;if(n&&(l=wn(n,this.logger))?(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,r,l,!0),i.pesData=null)):i.pesData=n,a&&(l=wn(a,this.logger))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l);break;case"ac3":this.parseAC3PES(e,l)}e.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=wn(o,this.logger))?(this.parseID3PES(s,l),s.pesData=null):s.pesData=o}demuxSampleAes(t,e,i){const s=this.demux(t,i,!0,!this.config.progressive),r=this.sampleAes=new mn(this.observer,this.config,e);return this.decrypt(s,r)}readyVideoParser(t){null===this.videoParser&&("avc"===t?this.videoParser=new yn:"hevc"===t&&(this.videoParser=new En))}decrypt(t,e){return new Promise(i=>{const{audioTrack:s,videoTrack:r}=t;s.samples&&"aac"===s.segmentCodec?e.decryptAacSamples(s.samples,0,()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,()=>{i(t)}):i(t)}):r.samples&&e.decryptAvcSamples(r.samples,0,0,()=>{i(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,e){let i=0;const s=this.aacOverFlow;let r,n,a,o=e.data;if(s){this.aacOverFlow=null;const e=s.missing,r=s.sample.unit.byteLength;if(-1===e)o=ee(s.sample.unit,o);else{const n=r-e;s.sample.unit.set(o.subarray(0,e),n),t.samples.push(s.sample),i=s.missing}}for(r=i,n=o.length;r<n-1&&!Mr(o,r);r++);if(r!==i){let t;const e=r<n-1;if(t=e?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",Ln(this.observer,new Error(t),e,this.logger),!e)return}if(Nr(t,this.observer,o,r,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!s)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Ur(t.samplerate);a=s.sample.pts+e}}let l,d=0;for(;r<n;){if(l=Br(t,o,r,a,d),r+=l.length,l.missing){this.aacOverFlow=l;break}for(d++;r<n-1&&!Mr(o,r);r++);}}parseMPEGPES(t,e){const i=e.data,s=i.length;let r=0,n=0;const a=e.pts;if(void 0!==a)for(;n<s;)if(ln(i,n)){const e=nn(t,i,n,a,r);if(!e)break;n+=e.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const i=e.data,s=e.pts;if(void 0===s)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=i.length;let n,a=0,o=0;for(;o<r&&(n=hn(t,i,o,s,a++))>0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=dt({},e,{type:this._videoTrack?zr.emsg:zr.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}}function bn(t,e){return((31&t[e+1])<<8)+t[e+2]}function An(t,e){return(31&t[e+10])<<8|t[e+11]}function kn(t,e,i,s,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<o;){const o=bn(t,e),l=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!s){In("ADTS AAC",n);break}case 15:-1===a.audioPid&&(a.audioPid=o);break;case 21:-1===a.id3Pid&&(a.id3Pid=o);break;case 219:if(!s){In("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:i.mpeg||i.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!s){In("AC-3",n);break}case 129:i.ac3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&l>0){let s=e+5,r=l;for(;r>2;){if(106===t[s])!0!==i.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const e=t[s+1]+2;s+=e,r-=e}}break;case 194:case 135:return Ln(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:-1===a.videoPid&&(a.videoPid=o,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}e+=l+5}return a}
vendor: 4,798 bytes, line 1
1function Ln(t,e,i,s){s.warn(`parsing error: ${e.message}`),t.emit(J.ERROR,J.ERROR,{type:X.MEDIA_ERROR,details:Q.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:e,reason:e.message})}function In(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function wn(t,e){let i,s,r,n,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=ee(l[0],l[1]),l.splice(1,1);i=l[0];if(1===(i[0]<<16)+(i[1]<<8)+i[2]){if(s=(i[4]<<8)+i[5],s&&s>t.size-6)return null;const d=i[7];192&d&&(n=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&d?(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2,n-a>54e5&&(e.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=i[8];let c=r+9;if(t.size<=c)return null;t.size-=c;const u=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){i=l[t];let e=i.byteLength;if(c){if(c>e){c-=e;continue}i=i.subarray(c),e-=c,c=0}u.set(i,o),o+=e}return s&&(s-=r+3),{data:u,pts:n,dts:a,len:s}}return null}class Rn{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===e)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const _n=Math.pow(2,32)-1;class Dn{static init(){let t;for(t in Dn.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},Dn.types)Dn.types.hasOwnProperty(t)&&(Dn.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);Dn.HDLR_TYPES={video:e,audio:i};const s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);Dn.STTS=Dn.STSC=Dn.STCO=r,Dn.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Dn.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Dn.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Dn.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Dn.FTYP=Dn.box(Dn.types.ftyp,n,o,n,a),Dn.DINF=Dn.box(Dn.types.dinf,Dn.box(Dn.types.dref,s))}static box(t,...e){let i=8,s=e.length;const r=s;for(;s--;)i+=e[s].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(t,4),s=0,i=8;s<r;s++)n.set(e[s],i),i+=e[s].byteLength;return n}static hdlr(t){return Dn.box(Dn.types.hdlr,Dn.HDLR_TYPES[t])}static mdat(t){return Dn.box(Dn.types.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(_n+1)),s=Math.floor(e%(_n+1));return Dn.box(Dn.types.mdhd,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,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))}static mdia(t){return Dn.box(Dn.types.mdia,Dn.mdhd(t.timescale||0,t.duration||0),Dn.hdlr(t.type),Dn.minf(t))}static mfhd(t){return Dn.box(Dn.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?Dn.box(Dn.types.minf,Dn.box(Dn.types.smhd,Dn.SMHD),Dn.DINF,Dn.stbl(t)):Dn.box(Dn.types.minf,Dn.box(Dn.types.vmhd,Dn.VMHD),Dn.DINF,Dn.stbl(t))}static moof(t,e,i){return Dn.box(Dn.types.moof,Dn.mfhd(t),Dn.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=Dn.trak(t[e]);return Dn.box.apply(null,[Dn.types.moov,Dn.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).c
vendor: 4,563 bytes, line 1
1oncat(Dn.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=Dn.trex(t[e]);return Dn.box.apply(null,[Dn.types.mvex,...i])}static mvhd(t,e){e*=t;const i=Math.floor(e/(_n+1)),s=Math.floor(e%(_n+1)),r=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,s>>24,s>>16&255,s>>8&255,255&s,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 Dn.box(Dn.types.mvhd,r)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let s,r;for(s=0;s<e.length;s++)r=e[s].flags,i[s+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return Dn.box(Dn.types.sdtp,i)}static stbl(t){return Dn.box(Dn.types.stbl,Dn.stsd(t),Dn.box(Dn.types.stts,Dn.STTS),Dn.box(Dn.types.stsc,Dn.STSC),Dn.box(Dn.types.stsz,Dn.STSZ),Dn.box(Dn.types.stco,Dn.STCO))}static avc1(t){let e,i,s,r=[],n=[];for(e=0;e<t.sps.length;e++)i=t.sps[e],s=i.byteLength,r.push(s>>>8&255),r.push(255&s),r=r.concat(Array.prototype.slice.call(i));for(e=0;e<t.pps.length;e++)i=t.pps[e],s=i.byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(i));const a=Dn.box(Dn.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,d=t.pixelRatio[0],c=t.pixelRatio[1];return Dn.box(Dn.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,o>>8&255,255&o,l>>8&255,255&l,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]),a,Dn.box(Dn.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Dn.box(Dn.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(t){const e=t.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return Dn.box(Dn.types.mp4a,Dn.audioStsd(t),Dn.box(Dn.types.esds,Dn.esds(t)))}static mp3(t){return Dn.box(Dn.types[".mp3"],Dn.audioStsd(t))}static ac3(t){return Dn.box(Dn.types["ac-3"],Dn.audioStsd(t),Dn.box(Dn.types.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return Dn.box(Dn.types.stsd,Dn.STSD,Dn.mp4a(t));if("ac3"===e&&t.config)return Dn.box(Dn.types.stsd,Dn.STSD,Dn.ac3(t));if("mp3"===e&&"mp3"===t.codec)return Dn.box(Dn.types.stsd,Dn.STSD,Dn.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return Dn.box(Dn.types.stsd,Dn.STSD,Dn.avc1(t));if("hevc"===e&&t.vps)return Dn.box(Dn.types.stsd,Dn.STSD,Dn.hvc1(t))}throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,i=(t.duration||0)*(t.timescale||0),s=t.width||0,r=t.height||0,n=Math.floor(i/(_n+1)),a=Math.floor(i%(_n+1));return Dn.box(Dn.types.tkhd,new Uint8Array([1,0,0,7,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,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,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,s>>8&255,255&s,0,0,r>>8&255,255&r,0,0]))}static traf(t,e){const i=Dn.sdtp(t),s=t.id,r=Math.floor(e/(_n+1)),n=Math.floor(e%(_n+1));return Dn.box(Dn.types.traf,Dn.box(Dn.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),Dn.box(Dn.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n])),Dn.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,Dn.box(Dn.types.trak,Dn.tkhd(t),Dn.mdia(t))}static trex(t){const e=t.id;return Dn.box(Dn.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const i=t.samples||[],s=i.length,r=12+16*s,n=new Uint8Array(r);let a,o,l,d,c,u;for(e+=8+r,n.set(["video"===t.type?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,255&s,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<s;a++)o=i[a],l=o.duration,d=o.size,c=o.flags,u=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,d>>>24&255,d>>>16&255,d>>>8&255,255&d,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*a);return Dn.box(Dn.types.trun,n)}
vendor: 4,393 bytes, line 1
1static initSegment(t){Dn.types||Dn.init();const e=Dn.moov(t);return ee(Dn.FTYP,e)}static hvc1(t){const e=t.params,i=[t.vps,t.sps,t.pps],s=new Uint8Array([1,e.general_profile_space<<6|(e.general_tier_flag?32:0)|e.general_profile_idc,e.general_profile_compatibility_flags[0],e.general_profile_compatibility_flags[1],e.general_profile_compatibility_flags[2],e.general_profile_compatibility_flags[3],e.general_constraint_indicator_flags[0],e.general_constraint_indicator_flags[1],e.general_constraint_indicator_flags[2],e.general_constraint_indicator_flags[3],e.general_constraint_indicator_flags[4],e.general_constraint_indicator_flags[5],e.general_level_idc,240|e.min_spatial_segmentation_idc>>8,255&e.min_spatial_segmentation_idc,252|e.parallelismType,252|e.chroma_format_idc,248|e.bit_depth_luma_minus8,248|e.bit_depth_chroma_minus8,0,parseInt(e.frame_rate.fps),3|e.temporal_id_nested<<2|e.num_temporal_layers<<3|(e.frame_rate.fixed?64:0),i.length]);let r=s.length;for(let t=0;t<i.length;t+=1){r+=3;for(let e=0;e<i[t].length;e+=1)r+=2+i[t][e].length}const n=new Uint8Array(r);n.set(s,0),r=s.length;const a=i.length-1;for(let t=0;t<i.length;t+=1){n.set(new Uint8Array([32+t|(t===a?128:0),0,i[t].length]),r),r+=3;for(let e=0;e<i[t].length;e+=1)n.set(new Uint8Array([i[t][e].length>>8,255&i[t][e].length]),r),r+=2,n.set(i[t][e],r),r+=i[t][e].length}const o=Dn.box(Dn.types.hvcC,n),l=t.width,d=t.height,c=t.pixelRatio[0],u=t.pixelRatio[1];return Dn.box(Dn.types.hvc1,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,d>>8&255,255&d,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,Dn.box(Dn.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Dn.box(Dn.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,u>>24,u>>16&255,u>>8&255,255&u])))}}Dn.types=void 0,Dn.HDLR_TYPES=void 0,Dn.STTS=void 0,Dn.STSC=void 0,Dn.STCO=void 0,Dn.STSZ=void 0,Dn.VMHD=void 0,Dn.SMHD=void 0,Dn.STSD=void 0,Dn.FTYP=void 0,Dn.DINF=void 0;function Pn(t,e,i=1,s=!1){const r=t*e*i;return s?Math.round(r):r}function xn(t,e=!1){return Pn(t,1e3,1/9e4,e)}function Cn(t){const{baseTime:e,timescale:i,trackId:s}=t;return`${e/i} (${e}/${i}) trackId: ${s}`}const On=8589934592;let Mn,Fn=null,Nn=null;function Un(t,e,i,s){return{duration:e,size:i,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}class Bn extends ht{constructor(t,e,i,s){if(super("mp4-remuxer",s),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=i,this.ISGenerated=!1,null===Fn){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Fn=t?parseInt(t[1]):0}if(null===Nn){const t=navigator.userAgent.match(/Safari\/(\d+)/i);Nn=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const e=this._initPTS;e&&t&&t.trackId===e.trackId&&t.baseTime===e.baseTime&&t.timescale===e.timescale||this.log(`Reset initPTS: ${e?Cn(e):e} > ${t?Cn(t):t}`),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const i=t[0].pts,s=t.reduce((t,s)=>{let r=s.pts,n=r-t;return n<-4294967296&&(e=!0,r=$n(r,i),n=r-t),n>0?t:r},i);return e&&this.debug("PTS rollover detected"),s}remux(t,e,i,s,r,n,a,o){let l,d,c,u,h,f,g=r,m=r;const p=t.pid>-1,v=e.pid>-1,y=e.samples.length,E=t.samples.length>0,T=a&&y>0||y>1;if((!p||E)&&(!v||T)||this.ISGenerated||a){if(this.ISGenerated){var S,b,A,k;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(S=e.pixelRatio)?void 0:S[0])!==(null==(b=t.pixelRatio)?void 0:b[0])||(null==(A=e.pixelRatio)?void 0:A[1])!==(null==(k=t.pixelRatio)?void 0:k[1]))||!t&&T||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(t,e,r,n));const i=this.isVideoContiguous;let s,a=-1;if(T&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}
vendor: 3,761 bytes, line 1
1(e.samples),!i&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.warn(`Dropped ${a} out of ${y} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,m+=(e.samples[0].pts-t)/e.inputTimeScale,s=m}else-1===a&&(this.warn(`No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(E&&T&&r){const i=this.getVideoStartPts(e.samples),s=($n(t.samples[0].pts,i)-i)/e.inputTimeScale;g+=Math.max(0,s),m+=Math.max(0,-s)}if(E){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(t,e,r,n)),d=this.remuxAudio(t,g,this.isAudioContiguous,n,v||T||o===rt?m:void 0),T){const s=d?d.endPTS-d.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(t,e,r,n)),l=this.remuxVideo(e,m,i,s)}}else T&&(l=this.remuxVideo(e,m,i,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=s)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(h=Gn(i,r,this._initPTS,this._initDTS)),s.samples.length&&(u=Vn(s,r,this._initPTS))),{audio:d,video:l,initSegment:c,independent:f,text:u,id3:h}}computeInitPts(t,e,i,s){const r=Math.round(i*e);let n=$n(t,r);if(n<r)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/e} ${s}`);n<r;)n+=On;return n-r}generateIS(t,e,i,s){const r=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS,d=!l||s;let c,u,h,f="audio/mp4",g=-1;if(d&&(c=u=1/0),t.config&&r.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}if(o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):Dn.initSegment([t]),metadata:{channelCount:t.channelCount}},d){g=t.id,h=t.inputTimeScale;const e=this.computeInitPts(r[0].pts,h,i,"audio");(!l||h!==l.timescale||0===i&&e<l.baseTime)&&(c=u=e)}}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:Dn.initSegment([e]),metadata:{width:e.width,height:e.height}},d){g=e.id,h=e.inputTimeScale;const t=this.getVideoStartPts(n),s=$n(n[0].dts,t),r=this.computeInitPts(s,h,i,"video"),a=this.computeInitPts(t,h,i,"video");(!l||h!==l.timescale||Y(c)||0===i&&a<l.baseTime)&&(u=Math.min(u,r),c=Math.min(c,r))}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,d&&Y(c)?(l&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${i} ${c/h} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${c/h} (${c}/${h}) trackId: ${g}`),this._initPTS={baseTime:c,timescale:h,trackId:g},this._initDTS={baseTime:u,timescale:h,trackId:g}):c=h=void 0,{tracks:o,initPTS:c,timescale:h,trackId:g}}remuxVideo(t,e,i,s){const r=t.inputTimeScale,n=t.samples,a=[],o=n.length,l=this._initPTS,d=l.baseTime*r/l.timescale;let c,u,h=this.nextVideoTs,f=8,g=this.videoSampleDuration,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!i||null===h){const t=d+e*r,s=n[0].pts-$n(n[0].dts,n[0].pts);Fn&&null!==h&&Math.abs(t-s-(h+d))<15e3?i=!0:h=t-s-d}const y=h+d;for(let t=0;t<o;t++){const e=n[t];e.pts=$n(e.pts,y),e.dts=$n(e.dts,y),e.dts<n[t>0?t-1:t].dts&&(v=!0)}v&&n.sort(function(t,e){const i=t.dts-e.dts,s=t.pts-e.pts;return i||s}),c=n[0].dts,u=n[n.length-1].dts;const E=u-c,T=E?Math.round(E/(o-1)):g||t.inputTimeScale/30;if(i){const i=c-y,s=i>T,r=i<-1;if((s||r)&&(s?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${xn(i,!0)} ms (${i}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}
vendor: 21,831 bytes, line 1
1: ${xn(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!r||y>=n[0].pts||Fn)){c=y;const t=n[0].pts-i;if(s)n[0].dts=c,n[0].pts=t;else{let e=!0;for(let s=0;s<n.length&&!(n[s].dts>t&&e);s++){const t=n[s].pts;if(n[s].dts-=i,n[s].pts-=i,s<n.length-1){const i=n[s+1].pts;e=i<=n[s].pts==i<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${xn(t,!0)}/${xn(c,!0)}, delta: ${xn(i,!0)} ms`)}}c=Math.max(0,c);let S=0,b=0,A=c;for(let t=0;t<o;t++){const e=n[t],i=e.units,s=i.length;let r=0;for(let t=0;t<s;t++)r+=i[t].data.length;b+=r,S+=s,e.length=r,e.dts<A?(e.dts=A,A+=T/4|0||1):A=e.dts,m=Math.min(e.pts,m),p=Math.max(e.pts,p)}u=n[o-1].dts;const k=b+4*S+8;let L;try{L=new Uint8Array(k)}catch(t){return void this.observer.emit(J.ERROR,J.ERROR,{type:X.MUX_ERROR,details:Q.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:k,reason:`fail allocating video mdat ${k}`})}const I=new DataView(L.buffer);I.setUint32(0,k),L.set(Dn.types.mdat,4);let w=!1,R=Number.POSITIVE_INFINITY,_=Number.POSITIVE_INFINITY,D=Number.NEGATIVE_INFINITY,P=Number.NEGATIVE_INFINITY;for(let t=0;t<o;t++){const e=n[t],i=e.units;let l,c=0;for(let t=0,e=i.length;t<e;t++){const e=i[t],s=e.data,r=e.data.byteLength;I.setUint32(f,r),f+=4,L.set(s,f),f+=r,c+=4+r}if(t<o-1)g=n[t+1].dts-e.dts,l=n[t+1].pts-e.pts;else{const i=this.config,a=t>0?e.dts-n[t-1].dts:T;if(l=t>0?e.pts-n[t-1].pts:T,i.stretchShortVideoTrack&&null!==this.nextAudioTs){const t=Math.floor(i.maxBufferHole*r),n=(s?m+s*r:this.nextAudioTs+d)-e.pts;n>t?(g=n-a,g<0?g=a:w=!0,this.log(`It is approximately ${n/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=a}else g=a}const u=Math.round(e.pts-e.dts);R=Math.min(R,g),D=Math.max(D,g),_=Math.min(_,l),P=Math.max(P,l),a.push(Un(e.key,g,c,u))}if(a.length)if(Fn){if(Fn<70){const t=a[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(Nn&&P-_<D-R&&T/D<.025&&0===a[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=c;for(let e=0,i=a.length;e<i;e++){const s=t+a[e].duration,r=t+a[e].cts;if(e<i-1){const t=s+a[e+1].cts;a[e].duration=t-r}else a[e].duration=e?a[e-1].duration:T;a[e].cts=0,t=s}}g=w||!g?T:g;const x=u+g;this.nextVideoTs=h=x-d,this.videoSampleDuration=g,this.isVideoContiguous=!0;const C={data1:Dn.moof(t.sequenceNumber++,c,dt(t,{samples:a})),data2:L,startPTS:(m-d)/r,endPTS:(p+g-d)/r,startDTS:(c-d)/r,endDTS:h/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:t.dropped};return t.samples=[],t.dropped=0,C}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,i,s,r){const n=t.inputTimeScale,a=n/(t.samplerate?t.samplerate:n),o=this.getSamplesPerFrame(t),l=o*a,d=this._initPTS,c="mp3"===t.segmentCodec&&this.typeSupported.mpeg,u=[],h=void 0!==r;let f=t.samples,g=c?0:8,m=this.nextAudioTs||-1;const p=d.baseTime*n/d.timescale,v=p+e*n;if(this.isAudioContiguous=i=i||f.length&&m>0&&(s&&Math.abs(v-(m+p))<9e3||Math.abs($n(f[0].pts,v)-(m+p))<20*l),f.forEach(function(t){t.pts=$n(t.pts,v)}),!i||m<0){const t=f.length;if(f=f.filter(t=>t.pts>=0),t!==f.length&&this.warn(`Removed ${f.length-t} of ${t} samples (initPTS ${p} / ${n})`),!f.length)return;m=0===r?0:s&&!h?Math.max(0,v-p):f[0].pts-p}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let i=0,s=m+p;i<f.length;i++){const r=f[i],a=r.pts,o=a-s,d=Math.abs(1e3*o/n);if(o<=-e*l&&h)0===i&&(this.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/n)} ms.`),this.nextAudioTs=m=a-p,s=a);else if(o>=e*l&&d<1e4&&h){let e=Math.round(o/l);for(s=a-e*l;s<0&&e&&l;)e--,s+=l;0===i&&(this.nextAudioTs=m=s-p),this.warn(`Injecting ${e} audio frames @ ${((s-p)/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<e;n++){let e=Rn.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);e||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),e=r.unit.subarray()),f.splice(i,0,{unit:e,pts:s}),s+=l,i++}}r.pts=s,s+=l}}let y,E=null,T=null,S=0,b=f.length;for(;b--;)S+=f[b].unit.byteLength;for(let e=0,s=f.length;e<s;e++){const s=f[e],r=s.unit;let n=s.pts;if(null!==T){u[e-1].duration=Math.round((n-T)/a)}else{if(i&&"aac"===t.segmentCodec&&(n=m+p),E=n,!(S>0))return;S+=g;try{y=new Uint8Array(S)}catch(t){return void this.observer.emit(J.ERROR,J.ERROR,{type:X.MUX_ERROR,details:Q.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:S,reason:`fail allocating audio mdat ${S}`})}if(!c){new DataView(y.buffer).setUint32(0,S),y.set(Dn.types.mdat,4)}}y.set(r,g);const l=r.byteLength;g+=l,u.push(Un(!0,o,l,0)),T=n}const A=u.length;if(!A)return;const k=u[u.length-1];m=T-p,this.nextAudioTs=m+a*k.duration;const L=c?new Uint8Array(0):Dn.moof(t.sequenceNumber++,E/a,dt({},t,{samples:u}));t.samples=[];const I=(E-p)/n,w=this.nextAudioTs/n,R={data1:L,data2:y,startPTS:I,endPTS:w,startDTS:I,endDTS:w,type:"audio",hasAudio:!0,hasVideo:!1,nb:A};return this.isAudioContiguous=!0,R}}function $n(t,e){let i;if(null===e)return t;for(i=e<t?-8589934592:On;Math.abs(t-e)>4294967296;)t+=i;return t}function Gn(t,e,i,s){const r=t.samples.length;if(!r)return;const n=t.inputTimeScale;for(let a=0;a<r;a++){const r=t.samples[a];r.pts=$n(r.pts-i.baseTime*n/i.timescale,e*n)/n,r.dts=$n(r.dts-s.baseTime*n/s.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function Vn(t,e,i){const s=t.samples.length;if(!s)return;const r=t.inputTimeScale;for(let n=0;n<s;n++){const s=t.samples[n];s.pts=$n(s.pts-i.baseTime*r/i.timescale,e*r)/r}t.samples.sort((t,e)=>t.pts-e.pts);const n=t.samples;return t.samples=[],{samples:n}}function Kn(t,e,i=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(i?t.duration:0))/t.timescale:e}function Hn(t,e,i){const s=t.codec;if(s&&s.length>4)return s;if(e===_t){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s){return Ee(s,!1)}return i.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"}return i.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1"}try{Mn=self.performance.now.bind(self.performance)}catch(t){Mn=Date.now}const jn=[{demux:class{constructor(t,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}resetTimeStamp(){}resetInitSegment(t,e,i,s){const r=this.videoTrack=Xr("video",1),n=this.audioTrack=Xr("audio",1),a=this.txtTrack=Xr("text",1);if(this.id3Track=Xr("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=Yt(t);if(o.video){const{id:t,timescale:e,codec:i,supplemental:s}=o.video;r.id=t,r.timescale=a.timescale=e,r.codec=i,r.supplemental=s}if(o.audio){const{id:t,timescale:e,codec:i}=o.audio;n.id=t,n.timescale=e,n.codec=i}a.id=Bt.text,r.sampleDuration=0,r.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let i=0;i<e;){const s=Vt(t,i);if(s>8&&109===t[i+4]&&111===t[i+5]&&111===t[i+6]&&102===t[i+7])return!0;i=s>1?i+s:e}return!1}(t)}demux(t,e){this.timeOffset=e;let i=t;const s=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=ee(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},i=jt(t,["moof"]);if(i.length<2)return e.remainder=t,e;const s=i[i.length-1];return e.valid=t.slice(0,s.byteOffset-8),e.remainder=t.slice(s.byteOffset-8),e}(i);this.remainderData=e.remainder,s.samples=e.valid||new Uint8Array}else s.samples=i;const n=this.extractID3Track(s,e);return r.samples=ie(e,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,i=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(e,this.timeOffset);return i.samples=ie(t,e),{videoTrack:e,audioTrack:Xr(),id3Track:s,textTrack:Xr()}}extractID3Track(t,e){const i=this.id3Track;if(t.samples.length){const s=jt(t.samples,["emsg"]);s&&s.forEach(t=>{const s=function(t){const e=t[0];let i="",s="",r=0,n=0,a=0,o=0,l=0,d=0;if(0===e){for(;"\0"!==$t(t.subarray(d,d+1));)i+=$t(t.subarray(d,d+1)),d+=1;for(i+=$t(t.subarray(d,d+1)),d+=1;"\0"!==$t(t.subarray(d,d+1));)s+=$t(t.subarray(d,d+1)),d+=1;s+=$t(t.subarray(d,d+1)),d+=1,r=Vt(t,12),n=Vt(t,16),o=Vt(t,20),l=Vt(t,24),d=28}else if(1===e){d+=4,r=Vt(t,d),d+=4;const e=Vt(t,d);d+=4;const n=Vt(t,d);for(d+=4,a=2**32*e+n,W(a)||(a=Number.MAX_SAFE_INTEGER,yt.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Vt(t,d),d+=4,l=Vt(t,d),d+=4;"\0"!==$t(t.subarray(d,d+1));)i+=$t(t.subarray(d,d+1)),d+=1;for(i+=$t(t.subarray(d,d+1)),d+=1;"\0"!==$t(t.subarray(d,d+1));)s+=$t(t.subarray(d,d+1)),d+=1;s+=$t(t.subarray(d,d+1)),d+=1}return{schemeIdUri:i,value:s,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(d,t.byteLength)}}(t);if(fn.test(s.schemeIdUri)){const t=gn(s,e);let r=4294967295===s.eventDuration?Number.POSITIVE_INFINITY:s.eventDuration/s.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=s.payload;i.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:zr.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata&&s.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const t=gn(s,e);i.samples.push({data:s.payload,len:s.payload.byteLength,dts:t,pts:t,type:zr.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(t,e,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class extends ht{constructor(t,e,i,s){super("passthrough-remuxer",s),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(t){this.lastEndTime=null;const e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,i,s){this.audioCodec=e,this.videoCodec=i,this.generateInitSegment(t,s),this.emitInitSegment=!0}generateInitSegment(t,e){let{audioCodec:i,videoCodec:s}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:r,video:n}=this.initData=Yt(t);if(e)!function(t,e){if(!t||!e)return;const i=e.keyId;i&&e.isCommonEncryption&&Zt(t,(t,e)=>{const s=t.subarray(8,24);s.some(t=>0!==t)||(yt.log(`[eme] Patching keyId in 'enc${e?"a":"v"}>sinf>>tenc' box: ${bt(s)} -> ${bt(i)}`),t.set(i,8))})}(t,e);else{const t=r||n;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}r&&(i=Hn(r,_t,this)),n&&(s=Hn(n,Dt,this));const a={};r&&n?a.audiovideo={container:"video/mp4",codec:i+","+s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:t,id:"main"}:r?a.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:t,id:"audio"}:n?a.video={container:"video/mp4",codec:s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(t,e,i,s,r,n){var a,o;let{initPTS:l,lastEndTime:d}=this;const c={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};Y(d)||(d=this.lastEndTime=r||0);const u=e.samples;if(!u.length)return c;const h={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(t,e,i){const s={},r=jt(t,["moof","traf"]);for(let t=0;t<r.length;t++){const n=r[t],a=jt(n,["tfhd"])[0],o=Vt(a,4),l=e[o];if(!l)continue;s[o]||(s[o]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const d=s[o],c=jt(n,["tfdt"])[0];if(c){const t=c[0];let e=Vt(c,4);1===t&&(e===Nt?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(e*=Nt+1,e+=Vt(c,8))),Y(e)&&(!Y(d.start)||e<d.start)&&(d.start=e)}const u=l.default,h=Vt(a,0)|(null==u?void 0:u.flags);let f=(null==u?void 0:u.duration)||0;8&h&&(f=Vt(a,2&h?12:8));const g=jt(n,["trun"]);let m=d.start||0,p=0,v=f;for(let t=0;t<g.length;t++){const e=g[t],i=Vt(e,4),s=d.sampleCount;d.sampleCount+=i;const r=1&e[3],n=4&e[3],a=1&e[2],o=2&e[2],l=4&e[2],c=8&e[2];let u=8,h=i;for(r&&(u+=4),n&&i&&(1&e[u+1]||void 0!==d.keyFrameIndex||(d.keyFrameIndex=s),u+=4,a?(v=Vt(e,u),u+=4):v=f,o&&(u+=4),c&&(u+=4),m+=v,p+=v,h--);h--;)a?(v=Vt(e,u),u+=4):v=f,o&&(u+=4),l&&(1&e[u+1]||void 0===d.keyFrameIndex&&(d.keyFrameIndex=d.sampleCount-(h+1),d.keyFrameStart=m),u+=4),c&&(u+=4),m+=v,p+=v;!p&&f&&(p+=f*i)}d.duration+=p}if(!Object.keys(s).some(t=>s[t].duration)){let e=1/0,i=0;const r=jt(t,["sidx"]);for(let t=0;t<r.length;t++){const s=qt(r[t]);if(null!=s&&s.references){e=Math.min(e,s.earliestPresentationTime/s.timescale);const t=s.references.reduce((t,e)=>t+e.info.duration||0,0);i=Math.max(i,t+s.earliestPresentationTime/s.timescale)}}i&&Y(i)&&Object.keys(s).forEach(t=>{s[t].duration||(s[t].duration=i*s[t].timescale-s[t].start)})}return s}(u,f,this),m=f.audio?g[f.audio.id]:null,p=f.video?g[f.video.id]:null,v=Kn(p,1/0),y=Kn(m,1/0),E=Kn(p,0,!0),T=Kn(m,0,!0);let S=r,b=0;const A=m&&(!p||!l&&y<v||l&&l.trackId===f.audio.id),k=A?m:p;if(k){const t=k.timescale,e=k.start-r*t,i=A?f.audio.id:f.video.id;S=k.start/t,b=A?T-y:E-v,!n&&l||!function(t,e,i,s){if(null===t)return!0;const r=Math.max(s,1),n=e-t.baseTime/t.timescale;return Math.abs(n-i)>r}(l,S,r,b)&&t===l.timescale||(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${e/t} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${S-r} (${e}/${t}) trackId: ${i}`),l=null,h.initPTS=e,h.timescale=t,h.trackId=i)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(h.initPTS=l.baseTime,h.timescale=l.timescale,h.trackId=l.trackId):(h.timescale&&void 0!==h.trackId&&void 0!==h.initPTS||(this.warn("Could not set initPTS"),h.initPTS=S,h.timescale=1,h.trackId=-1),this.initPTS=l={baseTime:h.initPTS,timescale:h.timescale,trackId:h.trackId});const L=S-l.baseTime/l.timescale,I=L+b;b>0?this.lastEndTime=I:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const w=!!f.audio,R=!!f.video;let _="";w&&(_+="audio"),R&&(_+="video");const D={data1:u,startPTS:L,startDTS:L,endPTS:I,endDTS:I,type:_,hasAudio:w,hasVideo:R,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};c.audio=w&&!R?D:void 0,c.video=R?D:void 0;const P=null==p?void 0:p.sampleCount;if(P){const t=p.keyFrameIndex,e=-1!==t;D.nb=P,D.dropped=0===t||this.isVideoContiguous?0:e?t:P,D.independent=e,D.firstKeyFrame=t,e&&p.keyFrameStart&&(D.firstKeyFramePTS=(p.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(c.independent=e),this.isVideoContiguous||(this.isVideoContiguous=e),D.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${P} dropped: ${D.dropped} start: ${D.firstKeyFramePTS||"NA"}`)}return c.initSegment=h,c.id3=Gn(i,r,l,l),s.samples.length&&(c.text=Vn(s,r,l)),c}}},{demux:Sn,remux:Bn},{demux:class extends Qr{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const i=Pr(t,0);let s=(null==i?void 0:i.length)||0;if(dn(t,s))return!1;for(let i=t.length;s<i;s++)if(Fr(t,s))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return function(t,e){return e+5<t.length}(t,e)&&xr(t,e)&&Or(t,e)<=t.length-e}(t,e)}appendFrame(t,e,i){Nr(t,this.observer,e,i,t.manifestCodec);const s=Br(t,e,i,this.basePTS,this.frameIndex);if(s&&0===s.missing)return s}},remux:Bn},{demux:class extends Qr{resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=Pr(t,0);let i=(null==e?void 0:e.length)||0;if(e&&11===t[i]&&119===t[i+1]&&void 0!==Wr(e)&&cn(t,i)<=16)return!1;for(let e=t.length;i<e;i++)if(dn(t,i))return yt.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return on(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,i){if(null!==this.basePTS)return nn(t,e,i,this.basePTS,this.frameIndex)}},remux:Bn}];jn.splice(2,0,{demux:un,remux:Bn});class qn{constructor(t,e,i,s,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=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=t,this.typeSupported=e,this.config=i,this.id=r,this.logger=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,s){const r=i.transmuxing;r.executeStart=Mn();let n=new Uint8Array(t);const{currentTransmuxState:a,transmuxConfig:o}=this;s&&(this.currentTransmuxState=s);const{contiguous:l,discontinuity:d,trackSwitch:c,accurateTimeOffset:u,timeOffset:h,initSegmentChange:f}=s||a,{audioCodec:g,videoCodec:m,defaultInitPts:p,duration:v,initSegmentData:y}=o,E=function(t,e){let i=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(i=e);return i}(n,e);if(E&&is(E.method)){const t=this.getDecrypter(),e=ss(E.method);if(!t.isSync())return this.asyncResult=!0,this.decryptionPromise=t.webCryptoDecrypt(n,E.key.buffer,E.iv.buffer,e).then(t=>{const e=this.push(t,null,i);return this.decryptionPromise=null,e}),this.decryptionPromise;{let s=t.softwareDecrypt(n,E.key.buffer,E.iv.buffer,e);if(i.part>-1){const e=t.flush();s=e?e.buffer:e}if(!s)return r.executeEnd=Mn(),Yn(i);n=new Uint8Array(s)}}const T=this.needsProbing(d,c);if(T){const t=this.configureTransmuxer(n);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit(J.ERROR,J.ERROR,{type:X.MEDIA_ERROR,details:Q.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),r.executeEnd=Mn(),Yn(i)}(d||c||f||T)&&this.resetInitSegment(y,g,m,v,e),(d||f||T)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const S=this.transmux(n,E,h,u,i);this.asyncResult=Wn(S);const b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,r.executeEnd=Mn(),S}flush(t){const e=t.transmuxing;e.executeStart=Mn();const{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(t));const n=[],{timeOffset:a}=s;if(i){const e=i.flush();e&&n.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=Mn();const i=[Yn(t)];return this.asyncResult?Promise.resolve(i):i}const d=o.flush(a);return Wn(d)?(this.asyncResult=!0,d.then(e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,d,t),this.asyncResult?Promise.resolve(n):n)}flushRemux(t,e,i){const{audioTrack:s,videoTrack:r,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===st?"level":"track"} ${i.level}`);const d=this.remuxer.remux(s,r,n,a,l,o,!0,this.id);t.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=Mn()}resetInitialTimestamp(t){const{demuxer:e,remuxer:i}=this;e&&i&&(e.resetTimeStamp(t),i.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,i,s,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,i,s),a.resetInitSegment(t,e,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,i,s,r){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,i,s,r):this.transmuxUnencrypted(t,i,s,r),n}transmuxUnencrypted(t,e,i,s){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,e,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(t,e,i,s,r){return this.demuxer.demuxSampleAes(t,e,i).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,i,s,!1,this.id),chunkMeta:r}))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:s}=this;let r;for(let e=0,i=jn.length;e<i;e++){var n;if(null!=(n=jn[e].demux)&&n.probe(t,this.logger)){r=jn[e];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.remux,d=r.demux;o&&o instanceof l||(this.remuxer=new l(i,e,s,this.logger)),a&&a instanceof d||(this.demuxer=new d(i,e,s,this.logger),this.probe=d.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new xi(this.config)),t}}const Yn=t=>({remuxResult:{},chunkMeta:t});function Wn(t){return"then"in t&&t.then instanceof Function}class zn{constructor(t,e,i,s,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}}class Xn{constructor(t,e,i,s,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOff
vendor: 3,298 bytes, line 1
1set=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=n}}let Qn=0;class Jn{constructor(t,e,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Qn++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=t=>{const e=t.data,i=this.hls;if(i&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var s;const t=null==(s=this.workerContext)?void 0:s.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":i.logger[e.data.logType]&&i.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.part=this.part,e.data.id=this.id,i.trigger(e.event,e.data)}},this.onWorkerError=t=>{if(!this.hls)return;const e=new Error(`${t.message}  (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(J.ERROR,{type:X.OTHER_ERROR,details:Q.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const r=t.config;this.hls=t,this.id=e,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const n=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===J.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new Lr,this.observer.on(J.FRAG_DECRYPTED,n),this.observer.on(J.ERROR,n);const a=Ae(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const i=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(i.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=function(t){const e=wr[t];if(e)return e.clientCount++,e;const i=new self.URL(t,self.location.href).href,s={worker:new self.Worker(i),scriptURL:i,clientCount:1};return wr[t]=s,s}(r.workerPath)):(i.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=wr[Ir];if(t)return t.clientCount++,t;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(e),s={worker:new self.Worker(i),objectURL:i,clientCount:1};return wr[Ir]=s,s}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:e,config:Ve(r)})}catch(s){i.warn(`Error setting up "${e}" Web Worker, fallback to inline`,s),this.terminateWorker(),this.error=null,this.transmuxer=new qn(this.observer,a,r,"",e,t.logger)}return}}this.transmuxer=new qn(this.observer,a,r,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=Qn++;const e=this.hls.config,i=Ae(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:i,id:this.id,c
vendor: 18,912 bytes, line 1
1onfig:Ve(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const e=wr[t||Ir];if(e&&1===e.clientCount--){const{worker:i,objectURL:s}=e;delete wr[t||Ir],s&&self.URL.revokeObjectURL(s),i.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,i,s,r,n,a,o,l,d){var c,u;l.transmuxing.start=self.performance.now();const{instanceNo:h,transmuxer:f}=this,g=n?n.start:r.start,m=r.decryptdata,p=this.frag,v=!(p&&r.cc===p.cc),y=!(p&&l.level===p.level),E=p?l.sn-p.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===E&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),b=!y&&(1===E||0===E&&(1===T||S&&T<=0)),A=self.performance.now();(y||E||0===r.stats.parsing.start)&&(r.stats.parsing.start=A),!n||!T&&b||(n.stats.parsing.start=A);const k=!(p&&(null==(c=r.initSegment)?void 0:c.url)===(null==(u=p.initSegment)?void 0:u.url)),L=new Xn(v,b,o,y,g,k);if(!b||v||k){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===st?"level":"track"}: ${l.level} id: ${l.id}\n        discontinuity: ${v}\n        trackSwitch: ${y}\n        contiguous: ${b}\n        accurateTimeOffset: ${o}\n        timeOffset: ${g}\n        initSegmentChange: ${k}`);const t=new zn(i,s,e,a,d);this.configureTransmuxer(t)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:h,cmd:"demux",data:t,decryptdata:m,chunkMeta:l,state:L},t instanceof ArrayBuffer?[t]:[]);else if(f){const e=f.push(t,m,l,L);Wn(e)?e.then(t=>{this.handleTransmuxComplete(t)}).catch(t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(e)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(i){const e=i.flush(t);Wn(e)?e.then(e=>{this.handleFlushResult(e,t)}).catch(e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}):this.handleFlushResult(e,t)}}transmuxerError(t,e,i){this.hls&&(this.error=t,this.hls.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:i}))}handleFlushResult(t,e){t.forEach(t=>{this.handleTransmuxComplete(t)}),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):i&&i.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}class Zn extends ht{constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,i){const s=null==e?void 0:e.renditionReports;if(s){let r=-1;for(let i=0;i<s.length;i++){const n=s[i];let a;try{a=new self.URL(n.URI,e.url).href}catch(t){this.warn(`Could not construct new URL for Rendition Report: ${t}`),a=n.URI||""}if(a===t){r=i;break}a===t.substring(0,a.length)&&(r=i)}if(-1!==r){const t=s[r],n=parseInt(t["LAST-MSN"])||e.lastPartSn;let a=parseInt(t["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);a>=0&&t>e.partTarget&&(a+=1)}const o=i&&Ne(i);return new Ue(n,a>=0?a:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}return t}playlistLoaded(t,e,i){const{details:s,stats:r}=e,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;s.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==s.appliedTimelineOffset){const t=Math.max(o||0,0);s.appliedTimelineOffset=t,s.fragments.forEach(e=>{e.setStart(e.playlistOffset+t)})}if(s.live||null!=i&&i.live){const o="levelInfo"in e?e.levelInfo:e.track;if(s.reloaded(i),i&&s.fragments.length>0){Vs(i,s,this);const t=s.playlistParsingError;if(t){this.warn(t);const i=this.hls;if(!i.config.ignorePlaylistParsingErrors){var l;const{networkDetails:n}=e;return void i.trigger(J.ERROR,{type:X.NETWORK_ERROR,details:Q.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:t,reason:t.message,level:e.level||void 0,parent:null==(l=s.fragments[0])?void 0:l.type,networkDetails:n,stats:r})}s.playlistParsingError=null}}-1===s.requestScheduled&&(s.requestScheduled=r.loading.start);const d=this.hls.mainForwardBufferInfo,c=d?d.end-d.len:0,u=qs(s,1e3*(s.edge-c));if(s.requestScheduled+u<n?s.requestScheduled=n:s.requestScheduled<=n&&(s.requestScheduled+=u),this.log(`live playlist ${t} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),!this.canLoad||!s.live)return;let h,f,g;if(s.canBlockReload&&s.endSN&&s.advanced){const t=this.hls.config.lowLatencyMode,r=s.lastPartSn,a=s.endSN,l=s.lastPartIndex,d=r===a;-1!==l?d?(f=a+1,g=t?0:l):(f=r,g=t?l+1:s.maxPartIndex):f=a+1;const c=s.age,u=c+s.ageHeader;let m=Math.min(u-s.partTarget,1.5*s.targetduration);if(m>0){if(u>3*s.targetduration)this.log(`Playlist last advanced ${c.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,g=void 0;else if(null!=i&&i.tuneInGoal&&u-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${m} with playlist age: ${s.age}`),m=0;else{const t=Math.floor(m/s.targetduration);if(f+=t,void 0!==g){g+=Math.round(m%s.targetduration/s.partTarget)}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${c.toFixed(2)}s goal: ${m} skip sn ${t} to part ${g}`)}s.tuneInGoal=m}if(h=this.getDeliveryDirectives(s,e.deliveryDirectives,f,g),t||!d)return s.requestScheduled=n,void this.loadingPlaylist(o,h)}else(s.canBlockReload||s.canSkipUntil)&&(h=this.getDeliveryDirectives(s,e.deliveryDirectives,f,g));h&&void 0!==f&&s.canBlockReload&&(s.requestScheduled=r.loading.first+Math.max(u-2*a,u/2)),this.scheduleLoading(o,h,s)}else this.clearTimer()}scheduleLoading(t,e,i){const s=i||t.details;if(!s)return void this.loadingPlaylist(t,e);const r=self.performance.now(),n=s.requestScheduled;if(r>=n)return void this.loadingPlaylist(t,e);const a=n-r;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),a)}getDeliveryDirectives(t,e,i,s){let r=Ne(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,s=e.part,r=Oe),new Ue(i,s,r)}checkRetry(t){const e=t.details,i=ii(t),s=t.errorAction,{action:r,retryCount:n=0,retryConfig:a}=s||{},o=!!s&&!!a&&(r===fi||!s.resolved&&r===ui);if(o){var l;if(n>=a.maxNumRetry)return!1;if(i&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const t=ai(a,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),t),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,s.resolved=!0}return o}}function ta(t,e){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!ea(t[i].attrs,e[i].attrs))return!1;return!0}function ea(t,e,i){const s=t["STABLE-RENDITION-ID"];return s&&!i?s===e["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>t[i]!==e[i])}function ia(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class sa{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,i){if(null===this.queues||null===this.tracks)return;const s=this.queues[e];s.push(t),1!==s.length||i||this.executeNext(e)}appendBlocker(t){return new Promise(e=>{const i={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,t)})}prependBlocker(t){return new Promise(e=>{if(this.queues){const i={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(i)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;const i=null==(e=t[0])?void 0:e.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(t[0].execute(),t.splice(0,1))})}unblockAudio(t){if(null===this.queues)return;this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(null===this.queues||null===this.tracks)return;const e=this.queues[t];if(e.length){const s=e[0];try{s.execute()}catch(e){var i;if(s.onError(e),null===this.queues||null===this.tracks)return;const r=null==(i=this.tracks[t])?void 0:i.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return null===t||null===e?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var e,i;return null!=(e=this.queues)&&e[t]||null!=(i=this.tracks)&&i[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const i=null==(e=this.tracks)?void 0:e[t],s=null==i?void 0:i.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map(t=>t.label).join(", "))||""}}const ra=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,na="HlsJsTrackRemovedError";class aa extends Error{constructor(t){super(t),this.name=na}}function oa(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}function la(t){return"audio"===t?1:0}class da{constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(J.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(J.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(J.MANIFEST_PARSED,this.onManifestParsed,this),t.on(J.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(J.BUFFER_CODECS,this.onBufferCodecs,this),t.on(J.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(J.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(J.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(J.MANIFEST_PARSED,this.onManifestParsed,this),t.off(J.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(J.BUFFER_CODECS,this.onBufferCodecs,this),t.off(J.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const i=this.hls.levels[e.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){const i=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,i.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&Y(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const t=this.hls.levels;if(t.length){const e=this.hls,i=this.getMaxLevel(t.length-1);i!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${i}: ${t[i].height}p@${t[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=i,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const i=e.filter((e,i)=>this.isLevelAllowed(e)&&i<=t);return this.clientRect=null,da.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const i=t.getBoundingClientRect();e.width=i.width,e.height=i.height,e.width||e.height||(e.width=i.right-i.left||t.width||0,e.height=i.bottom-i.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height)}static getMaxLevelByMediaSize(t,e,i){if(null==t||!t.length)return-1;const s=(t,e)=>!e||(t.width!==e.width||t.height!==e.height);let r=t.length-1;const n=Math.max(e,i);for(let e=0;e<t.length;e+=1){const i=t[e];if((i.width>=n||i.height>=n)&&s(i,t[e+1])){r=e;break}}return r}}const ca={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},ua={HLS:"h"};class ha{constructor(t,e){Array.isArray(t)&&(t=t.map(t=>t instanceof ha?t:new ha(t))),this.value=t,this.params=e}}function fa(t,e,i,s){return new Error(`failed to ${t} "${r=e,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${i}`,{cause:s});var r}function ga(t,e,i){return fa("serialize",t,e,i)}class ma{constructor(t){this.description=t}}const pa="Bare Item";function va(t){if(!1===ArrayBuffer.isView(t))throw ga(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function ya(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw ga(t,"Integer");return t.toString()}function Ea(t,e){if(t<0)return-Ea(-t,e);const i=Math.pow(10,e);if(Math.abs(t*i%1-.5)<Number.EPSILON){const e=Math.floor(t*i);return(e%2==0?e:e+1)/i}return Math.round(t*i)/i}function Ta(t){const e=Ea(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw ga(t,"Decimal");const i=e.toString();return i.includes(".")?i:`${i}.0`}const Sa=/[\x00-\x1f\x7f]+/;function ba(t){const e=(i=t).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw ga(e,"Token");return e}function Aa(t){switch(typeof t){case"number":if(!Y(t))throw ga(t,pa);return Number.isInteger(t)?ya(t):Ta(t);case"string":return function(t){if(Sa.test(t))throw ga(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return ba(t);case"boolean":return function(t){if("boolean"!=typeof t)throw ga(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${ya(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return va(t);if(t instanceof ma)return ba(t);default:throw ga(t,pa)}}function ka(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw ga(t,"Key");return t}function La(t){return null==t?"":Object.entries(t).map(([t,e])=>!0===e?`;${ka(t)}`:`;${ka(t)}=${Aa(e)}`).join("")}function Ia(t){return t instanceof ha?`${Aa(t.value)}${La(t.params)}`:Aa(t)}function wa(t,e={whitespace:!0}){if("object"!=typeof t||null==t)throw ga(t,"Dict");const i=t instanceof Map?t.entries():Object.entries(t),s=(null==e?void 0:e.whitespace)?" ":"";return Array.from(i).map(([t,e])=>{e instanceof ha==!1&&(e=new ha(e));let i=ka(t);var s;return!0===e.value?i+=La(e.params):(i+="=",Array.isArray(e.value)?i+=`(${(s=e).value.map(Ia).join(" ")})${La(s.params)}`:i+=Ia(e)),i}).join(`,${s}`)}function Ra(t,e){return wa(t,e)}const _a="CMCD-Object",Da="CMCD-Request",Pa="CMCD-Session",xa="CMCD-Status",Ca={br:_a,ab:_a,d:_a,ot:_a,tb:_a,tpb:_a,lb:_a,tab:_a,lab:_a,url:_a,pb:Da,bl:Da,tbl:Da,dl:Da,ltc:Da,mtp:Da,nor:Da,nrr:Da,rc:Da,sn:Da,sta:Da,su:Da,ttfb:Da,ttfbb:Da,ttlb:Da,cmsdd:Da,cmsds:Da,smrt:Da,df:Da,cs:Da,ts:Da,cid:Pa,pr:Pa,sf:Pa,sid:Pa,st:Pa,v:Pa,msd:Pa,bs:xa,bsd:xa,cdn:xa,rtp:xa,bg:xa,pt:xa,ec:xa,e:xa},Oa=Da;function Ma(t,e){const i={};if(!t)return i;const s=Object.keys(t),r=e?(n=e,Object.keys(n).reduce((t,e)=>{var i;return null===(i=n[e])||void 0===i||i.forEach(i=>t[i]=e),t},{})):{};var n;return s.reduce((e,i)=>{var s;const n=Ca[i]||r[i]||Oa;return(null!==(s=e[n])&&void 0!==s?s:e[n]={})[i]=t[i],e},i)}const Fa="event";const Na=t=>Math.round(t),Ua=(t,e)=>Array.isArray(t)?t.map(t=>Ua(t,e)):t instanceof ha&&"string"==typeof t.value?new ha(Ua(t.value,e),t.params):(e.baseUrl&&(t=function(t,e){const i=new URL(t),s=new URL(e);if(i.origin!==s.origin)return t;const r=i.pathname.split("/").slice(1),n=s.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+i.search+i.hash}(t,e.baseUrl)),1===e.version?encodeURIComponent(t):t),Ba=t=>100*Na(t/100),$a={br:Na,d:Na,bl:Ba,dl:Ba,mtp:Ba,nor:(t,e)=>{let i=t;return e.version>=2&&(t instanceof ha&&"string"==typeof t.value?i=new ha([t]):"string"==typeof t&&(i=[t])),Ua(i,e)},rtp:Ba,tb:Na},Ga="request",Va="response",Ka=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],Ha=["e"],ja=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function qa(t){return ja.test(t)}
1const Ya=["d","dl","nor","ot","rtp","su"];const Wa=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];const za=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Xa(t){return za.includes(t)||qa(t)}const Qa={[Va]:function(t){return Ka.includes(t)||Ya.includes(t)||Wa.includes(t)||qa(t)},[Fa]:function(t){return Ka.includes(t)||Ha.includes(t)||qa(t)},[Ga]:function(t){return Ka.includes(t)||Ya.includes(t)||qa(t)}};function Ja(t,e={}){const i={};if(null==t||"object"!=typeof t)return i;const s=e.version||t.v||1,r=e.reportingMode||Ga,n=1===s?Xa:Qa[r];let a=Object.keys(t).filter(n);const o=e.filter;"function"==typeof o&&(a=a.filter(o));const l=r===Va||r===Fa;l&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");const d=dt({},$a,e.formatters),c={version:s,reportingMode:r,baseUrl:e.baseUrl};return a.sort().forEach(e=>{let r=t[e];const n=d[e];if("function"==typeof n&&(r=n(r,c)),"v"===e){if(1===s)return;r=s}"pr"==e&&1===r||(l&&"ts"===e&&!Y(r)&&(r=Date.now()),function(t){return"number"==typeof t?Y(t):null!=t&&""!==t&&!1!==t}(r)&&(function(t){return["ot","sf","st","e","sta"].includes(t)}(e)&&"string"==typeof r&&(r=new ma(r)),i[e]=r))}),i}function Za(t,e,i){return dt(t,function(t,e={}){const i={};if(!t)return i;const s=Ma(Ja(t,e),null==e?void 0:e.customHeaderMap);return Object.entries(s).reduce((t,[e,i])=>{const s=Ra(i,{whitespace:!1});return s&&(t[e]=s),t},i)}(e,i))}function to(t,e={}){if(!t)return"";const i=function(t,e={}){return t?Ra(Ja(t,e),{whitespace:!1}):""}(t,e);return encodeURIComponent(i)}const eo=/CMCD=[^&#]+/;function io(t,e,i){const s=function(t,e={}){return t?`CMCD=${to(t,e)}`:""}(e,i);if(!s)return t;if(eo.test(t))return t.replace(eo,s);const r=t.includes("?")?"&":"?";return`${t}${r}${s}`}function so(t,e,i,s){t&&Object.keys(e).forEach(r=>{const n=t.filter(t=>t.groupId===r).map(t=>{const n=dt({},t);return n.details=void 0,n.attrs=new zi(n.attrs),n.url=n.attrs.URI=ro(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=e[r],n.attrs["PATHWAY-ID"]=s,n});t.push(...n)})}function ro(t,e,i,s){const{HOST:r,PARAMS:n,[i]:a}=s;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(t=>{t&&l.searchParams.set(t,n[t])}),l.href}class no extends ht{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=no.CDMCleanupPromise?[no.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:e,initData:i}=t,s=`"${t.type}" event: init data type: "${e}"`;if(this.debug(s),null!==i){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=ps(this.config));const e=t.map(ms).filter(t=>!!t);this.keyFormatPromise=this.getKeyFormatPromise(e)}this.keyFormatPromise.then(r=>{const n=gs(r);if("sinf"!==e||n!==ds.FAIRPLAY)return void this.log(`Ignoring "${t.type}" event with init data type: "${e}" for selected key-system ${n}`);let a;try{const t=$t(new Uint8Array(i)),e=te(rs(JSON.parse(t).sinf));if(!e)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(e.subarray(8,24))}catch(t){return void this.warn(`${s} Failed to parse sinf: ${t}`)}const o=bt(a),{keyIdToKeySessionPromise:l,mediaKeySessions:d}=this;let c=l[o];for(let t=0;t<d.length;t++){const s=d[t],r=s.decryptdata;if(!r.keyId)continue;const n=bt(r.keyId);if(ts(a,r.keyId)||-1!==r.uri.replace(/-/g,"").indexOf(o)){if(c=l[n],!c)continue;if(r.pssh)break;delete l[n],r.pssh=new Uint8Array(i),r.keyId=a,c=l[o]=c.then(()=>this.generateRequestWithPreferredKeySession(s,e,i,"encrypted-event-key-match")),c.catch(t=>this.handleError(t));break}}c||this.handleError(new Error(`Key ID ${o} not encountered in playlist. Key-system sessions ${d.length}.`))}).catch(t=>this.handleError(t))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}
1registerListeners(){this.hls.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(J.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(J.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(J.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(J.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(J.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(J.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(J.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(J.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:i}=this.config,s=null==e?void 0:e[t];return s?s.licenseUrl:t===ds.WIDEVINE&&i?i:void 0}getLicenseServerUrlOrThrow(t){const e=this.getLicenseServerUrl(t);if(void 0===e)throw new Error(`no license server URL configured for key-system "${t}"`);return e}getServerCertificateUrl(t){const{drmSystems:e}=this.config,i=null==e?void 0:e[t];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,i=(t,e,i)=>!!t&&i.indexOf(t)===e,s=e.map(t=>t.audioCodec).filter(i),r=e.map(t=>t.videoCodec).filter(i);return s.length+r.length===0&&r.push("avc1.42e01e"),new Promise((e,i)=>{const n=t=>{const a=t.shift();this.getMediaKeysPromise(a,s,r).then(t=>e({keySystem:a,mediaKeys:t})).catch(e=>{t.length?n(t):i(e instanceof lo?e:new lo({type:X.KEY_SYSTEM_ERROR,details:Q.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))})};n(t)})}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let t=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===vs&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return i(t,e)}getMediaKeysPromise(t,e,i){var s;const r=function(t,e,i,s){let r;switch(t){case ds.FAIRPLAY:r=["cenc","sinf"];break;case ds.WIDEVINE:case ds.PLAYREADY:r=["cenc"];break;case ds.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,i,s){return[{initDataTypes:t,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(t=>({contentType:`audio/mp4; codecs=${t}
vendor: 4,483 bytes, line 1
1`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:i.map(t=>({contentType:`video/mp4; codecs=${t}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}(r,e,i,s)}(t,e,i,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[t],a=null==(s=n)?void 0:s.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${t}" key-system access with config: ${Ve(r)}`),a=this.requestMediaKeySystemAccess(t,r);const e=n=this.keySystemAccessPromises[t]={keySystemAccess:a};return a.catch(e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)}),a.then(i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const s=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const r=e.mediaKeys=i.createMediaKeys().then(i=>(this.log(`Media-keys created for "${t}"`),e.hasMediaKeys=!0,s.then(e=>e?this.setMediaKeysServerCertificate(i,t,e):i)));return r.catch(e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)}),r})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:i}){this.log(`Creating key-system session "${e}" keyId: ${bt(t.keyId||[])} keyUri: ${t.uri}`);const s=i.createSession(),r={decryptdata:t,keySystem:e,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const i=this.createMediaKeySessionContext(t),s=ao(e),r="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,r,e.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,e){const i=t.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${bt(t.decryptdata.keyId||[])}\n      } (data length: ${e.byteLength})`),i.update(e)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>ms(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:t,mediaKeys:e})=>this.attemptSetMediaKeys(t,e))}selectKeySystem(t){return new Promise((e,i)=>{this.getKeySystemSelectionPromise(t).then(({keySystem:t})=>{const s=ms(t);s?e(s):i(new Error(`Unable to find format for key-system "${t}"`))}).catch(i)})}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){const e=ps(this.config),i=t.map(gs).filter(t=>!!t&&-1!==e.indexOf(t));return this.selectKeySystem(i)}getKeyStatus(t){const{mediaKeySessions:e}=this;for(let i=0;i<e.length;i++){const s=oo(t,e[i]);if(s)return s}}loadKey(t){const e=t.keyInfo.decryptdata,i=ao(e),s=this.bannedKeyIds[i];if(s||"internal-error"===this.getKeyStatus(e)){const i=co(s||"internal-error",e);return this.handleError(i,t.frag),Promise.reject(i)}const r=`(keyId: ${i} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${r}`);const n=this.keyIdToKeySessionPromise[i];if(!n){const s=this.getKeySystemForKeyPromise(e).then(({keySystem:i,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${r}`),this.attemptSetMediaKeys(i,s).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:i,mediaKeys:s,decryptdata:e}))))).then(t=>{const i=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(t,"cenc",i,"playlist-key")});return s.catch(e=>this.handleError(e,t.frag)),this.keyIdToKeySessionPromise[i]=s,s}return n.catch(i=>{if(i instanceof lo){const s=ut({},i.data);"internal-error"===this.getKeyStatus(e)&&(s.decryptdata=e);const r=new lo(s,i.message);this.handleError(r,t.frag)}}),n}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,e){if(this.hls)if(t instanceof lo){e&&(t.data.frag=e);const i=t.data.decryptdata;this.error(`${t.message}${i?` (${bt(i.keyId||[])})`:""}`),this.hls.trigger(J.ERROR,t.data)}else this.error(t.message),this.hls.trigger(J.ERROR,{type:X.KEY_SYSTEM_ERROR,details:Q.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}
1getKeySystemForKeyPromise(t){const e=ao(t),i=this.keyIdToKeySessionPromise[e];if(!i){const e=gs(t.keyFormat),i=e?[e]:ps(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=ps(this.config)),0===t.length)throw new lo({type:X.KEY_SYSTEM_ERROR,details:Q.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Ve({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,e){if(this.mediaResolved=void 0,this.mediaKeys===e)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const s=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(e):new Promise((t,i)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return i(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=e,this.media.setMediaKeys(e).then(t).catch(i)}}));return this.mediaKeys=e,this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${t}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(t=>-1===i.indexOf(t))})}generateRequestWithPreferredKeySession(t,e,i,s){var r;const n=null==(r=this.config.drmSystems)||null==(r=r[t.keySystem])?void 0:r.generateRequest;if(n)try{const s=n.call(this.hls,e,i,t);if(!s)throw new Error("Invalid response from configured generateRequest filter");e=s.initDataType,i=s.initData?s.initData:null,t.decryptdata.pssh=i?new Uint8Array(i):null}catch(t){if(this.warn(t.message),this.hls&&this.hls.config.debug)throw t}if(null===i)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(t);const a=ao(t.decryptdata),o=t.decryptdata.uri;this.log(`Generating key-session request for "${s}" keyId: ${a} URI: ${o} (init data type: ${e} length: ${i.byteLength})`);const l=new Lr,d=t._onmessage=e=>{const i=t.mediaKeysSession;if(!i)return void l.emit("error",new Error("invalid state"));const{messageType:s,message:r}=e;this.log(`"${s}" message event for session "${i.sessionId}" message size: ${r.byteLength}`),"license-request"===s||"license-renewal"===s?this.renewLicense(t,r).catch(t=>{l.eventNames().length?l.emit("error",t):this.handleError(t)}):"license-release"===s?t.keySystem===ds.FAIRPLAY&&this.updateKeySession(t,ns("acknowledged")).then(()=>this.removeSession(t)).catch(t=>this.handleError(t)):this.warn(`unhandled media key message type "${s}"`)},c=(t,e)=>{let i;e.keyStatus=t,t.startsWith("usable")?l.emit("resolved"):"internal-error"===t||"output-restricted"===t||"output-downscaled"===t?i=co(t,e.decryptdata):"expired"===t?i=new Error(`key expired (keyId: ${a})`):"released"===t?i=new Error("key released"):"status-pending"===t||this.warn(`unhandled key status change "${t}" (keyId: ${a})`),i&&(l.eventNames().length?l.emit("error",i):this.handleError(i))},u=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void l.emit("error",new Error("invalid state"));const i=this.getKeyStatuses(t);if(!Object.keys(i).some(t=>"status-pending"!==i[t]))return;if("expired"===i[a])return this.log(`Expired key ${Ve(i)} in key-session "${t.mediaKeysSession.sessionId}"`),void this.renewKeySession(t);let s=i[a];if(s)c(s,t);else{var r;const e=1e3;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(r=t.keyStatusTimeouts)[a]||(r[a]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const i=this.getKeyStatus(t.decryptdata);if(i&&"status-pending"!==i)return this.log(`No status for keyId ${a} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${i} from other session.`),c(i,t);this.log(`key status for ${a} in key-session "${t.mediaKeysSession.sessionId}" timed out after ${e}ms`),s="internal-error",c(s,t)},e)),this.log(`No status for keyId ${a} (${Ve(i)}).`)}};rr(t.mediaKeysSession,"message",d),rr(t.mediaKeysSession,"keystatuseschange",u);const h=new Promise((t,e)=>{l.on("error",e),l.on("resolved",t)});return t.mediaKeysSession.generateRequest(e,i).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${a} URI: ${o}`)}).catch(e=>{throw new lo({type:X.KEY_SYSTEM_ERROR,details:Q.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${e}`)}).then(()=>h).catch(e=>(l.removeAllListeners(),this.removeSession(t).then(()=>{throw e}))).then(()=>(l.removeAllListeners(),t))}getKeyStatuses(t){const e={};
1return t.mediaKeysSession.keyStatuses.forEach((i,s)=>{if("string"==typeof s&&"object"==typeof i){const t=s;s=i,i=t}const r="buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s);if(t.keySystem===ds.PLAYREADY&&16===r.length){const t=bt(r);e[t]=i,as(r)}const n=bt(r);"internal-error"===i&&(this.bannedKeyIds[n]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${n} key-session "${t.mediaKeysSession.sessionId}"`),e[n]=i}),e}fetchServerCertificate(t){const e=this.config,i=new(0,e.loader)(e),s=this.getServerCertificateUrl(t);return s?(this.log(`Fetching server certificate for "${t}"`),new Promise((r,n)=>{const a={responseType:"arraybuffer",url:s},o=e.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,e,i,s)=>{r(t.data)},onError:(e,i,r,o)=>{n(new lo({type:X.KEY_SYSTEM_ERROR,details:Q.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:ut({url:a.url,data:void 0},e)},`"${t}" certificate request failed (${s}). Status: ${e.code} (${e.text})`))},onTimeout:(e,i,r)=>{n(new lo({type:X.KEY_SYSTEM_ERROR,details:Q.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${t}" certificate request timed out (${s})`))},onAbort:(t,e,i)=>{n(new Error("aborted"))}};i.load(a,l,d)})):Promise.resolve()}setMediaKeysServerCertificate(t,e,i){return new Promise((s,r)=>{t.setServerCertificate(i).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${i.byteLength}) on "${e}"`),s(t)}
1).catch(t=>{r(new lo({type:X.KEY_SYSTEM_ERROR,details:Q.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))})})}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then(e=>this.updateKeySession(t,new Uint8Array(e)).catch(e=>{throw new lo({type:X.KEY_SYSTEM_ERROR,details:Q.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:e,fatal:!1},e.message)}))}unpackPlayReadyKeyMessage(t,e){const i=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!i.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const s=(new DOMParser).parseFromString(i,"application/xml"),r=s.querySelectorAll("HttpHeader");if(r.length>0){let e;for(let i=0,s=r.length;i<s;i++){var n,a;e=r[i];const s=null==(n=e.querySelector("name"))?void 0:n.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;s&&o&&t.setRequestHeader(s,o)}}const o=s.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return ns(atob(l))}setupLicenseXHR(t,e,i,s){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return r.call(this.hls,t,e,i,s)}).catch(n=>{if(!i.decryptdata)throw n;return t.open("POST",e,!0),r.call(this.hls,t,e,i,s)}).then(i=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:i||s}}):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:s}))}requestLicense(t,e){const i=this.config.keyLoadPolicy.default;return new Promise((s,r)=>{const n=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return r(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let e=a.response;this.log(`License received ${e instanceof ArrayBuffer?e.byteLength:e}`);const i=this.config.licenseResponseCallback;if(i)try{e=i.call(this.hls,a,n,t)}catch(t){this.error(t)}s(e)}else{const o=i.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)r(new lo({type:X.KEY_SYSTEM_ERROR,details:Q.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const i=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(t,e).then(s,r)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=a,this.setupLicenseXHR(a,n,t,e).then(({xhr:e,licenseChallenge:i})=>{t.keySystem==ds.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(e,i)),e.send(i)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const i=e.media;this.media=i,rr(i,"encrypted",this.onMediaEncrypted),rr(i,"waitingforkey",this.onWaitingForKey);const s=this.mediaResolved;s?s():this.mediaKeys=i.mediaKeys}onMediaDetached(){const t=this.media;t&&(nr(t,"encrypted",this.onMediaEncrypted),nr(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const e=this.mediaResolved;if(e&&e(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Ss.clearKeyUriToKeyIdMap();const r=s.length;no.CDMCleanupPromise=Promise.all(s.map(t=>this.removeSession(t)).concat((null==i||null==(t=i.setMediaKeys(null))?void 0:t.catch(t=>{this.log(`Could not clear media keys: ${t}`),this.hls&&this.hls.trigger(J.ERROR,{type:X.OTHER_ERROR,details:Q.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${t}`)})}))||Promise.resolve())).catch(t=>
1{this.log(`Could not close sessions and clear media keys: ${t}`),this.hls&&this.hls.trigger(J.ERROR,{type:X.OTHER_ERROR,details:Q.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${t}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:i,decryptdata:s}=t;if(e){this.log(`Remove licenses and keys and close session "${e.sessionId}" keyId: ${bt((null==s?void 0:s.keyId)||[])}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(t);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:n}=t;n&&Object.keys(n).forEach(t=>self.clearTimeout(n[t]));const{drmSystemOptions:a}=this.config,o=function(t){var e;return!(!t||"persistent-license"!==t.sessionType&&(null==(e=t.sessionTypes)||!e.some(t=>"persistent-license"===t)))}(a)?new Promise((t,i)=>{self.setTimeout(()=>i(new Error("MediaKeySession.remove() timeout")),8e3),e.remove().then(t).catch(i)}):Promise.resolve();return o.catch(t=>{this.log(`Could not remove session: ${t}`),this.hls&&this.hls.trigger(J.ERROR,{type:X.OTHER_ERROR,details:Q.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${t}`)})}).then(()=>e.close()).catch(t=>{this.log(`Could not close session: ${t}`),this.hls&&this.hls.trigger(J.ERROR,{type:X.OTHER_ERROR,details:Q.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})})}return Promise.resolve()}}function ao(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return bt(t.keyId)}function oo(t,e){return t.keyId&&e.mediaKeysSession.keyStatuses.has(t.keyId)?e.mediaKeysSession.keyStatuses.get(t.keyId):t.matches(e.decryptdata)?e.keyStatus:void 0}no.CDMCleanupPromise=void 0;
1class lo extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}function co(t,e){const i="output-restricted"===t,s=i?Q.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Q.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new lo({type:X.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},i?"HDCP level output restricted":`key status changed to "${t}"`)}function uo(t,e){let i;try{i=new Event("addtrack")}catch(t){i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=t,e.dispatchEvent(i)}function ho(t,e){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){yt.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(t){yt.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===i&&(t.mode=i)}function fo(t,e){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues)for(let i=t.cues.length;i--;)e&&t.cues[i].removeEventListener("enter",e),t.removeCue(t.cues[i]);"disabled"===i&&(t.mode=i)}function go(t,e,i,s){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=function(t,e,i){const s=[],r=function(t,e){if(e<=t[0].startTime)return 0;const i=t.length-1;if(e>t[i].endTime)return-1;let s,r=0,n=i;for(;r<=n;)if(s=Math.floor((n+r)/2),e<t[s].startTime)n=s-1;else{if(!(e>t[s].startTime&&r<i))return s;r=s+1}return t[r].startTime-e<e-t[n].startTime?r:n}(t,e);if(r>-1)for(let n=r,a=t.length;n<a;n++){const r=t[n];if(r.startTime>=e&&r.endTime<=i)s.push(r);else if(r.startTime>i)return s}return s}(t.cues,e,i);for(let e=0;e<r.length;e++)s&&!s(r[e])||t.removeCue(r[e])}"disabled"===r&&(t.mode=r)}function mo(t){const e=[];for(let i=0;i<t.length;i++){const s=t[i];"subtitles"!==s.kind&&"captions"!==s.kind||!s.label||e.push(t[i])}return e}function po(t){let e=5381,i=t.length;for(;i;)e=33*e^t.charCodeAt(--i);return(e>>>0).toString()}const vo=.025;let yo=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function Eo(t,e,i){return`${t.identifier}-${i+1}-${po(e)}`}class To{constructor(t,e){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=e,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,null==(t=this.assetListLoader)||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var e;if(t>0&&t>=this.assetList.length)return!0;const i=this.playoutLimit;if(t<=0||isNaN(i))return!1;if(0===i)return!0;return((null==(e=this.assetList[t])?void 0:e.startOffset)||0)>i}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const e=this.dateRange.tagAnchor;if(e)return So(t,e)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const e=this.dateRange.startTime;return e-So(e,t)<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,e=Y(t)?t:this.duration;return this.cumulativeDuration+e}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const e=this.resumeAnchor;if(e)return So(t,e)}return t}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<vo))}set appendInPlace(t){this.appendInPlaceStarted?this.resetOnResume=!t:this.appendInPlaceDisabled=!t}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){const t=this.playoutLimit;let e;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e}set duration(t){this._duration=t}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?yo.Range:yo.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(t=this).identifier}" ${t.cue.pre?"<pre>":t.cue.post?"<post>":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`;var t}}
1function So(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<vo)?e.start:e.start+e.duration}function bo(t,e,i){const s=new self.URL(t,i);return"data:"!==s.protocol&&s.searchParams.set("_HLS_primary_id",e),s}function Ao(t,e){for(;null!=(i=t.assetList[++e])&&i.error;)var i;return e}function ko(t){const e=t.timelineStart,i=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+i).toFixed(2)}]`}class Lo{constructor(t,e,i,s){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(J.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new t(e);this.interstitial=i,this.assetItem=s;const n=()=>{this.hasDetails=!0};r.once(J.LEVEL_LOADED,n),r.once(J.AUDIO_TRACK_LOADED,n),r.once(J.SUBTITLE_TRACK_LOADED,n),r.on(J.MEDIA_ATTACHING,(t,{media:e})=>{this.removeMediaListeners(),this.mediaAttached=e;this.interstitial.playoutLimit&&(e.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(J.BUFFER_APPENDED,()=>{const t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,r.trigger(J.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let e=this.assetItem.uri;try{e=bo(e,t.config.primarySessionId||"").href}catch(t){}t.loadSource(e)}}bufferedInPlaceToEnd(t){var e;if(!this.appendInPlace)return!1;if(null!=(e=this.hls)&&e.bufferedToEnd)return!0;if(!t)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),s=this.timelineOffset,r=Gi.bufferInfo(t,s,0);return this.getAssetTime(r.end)>=i-.02}reachedPlayout(t){const e=this.interstitial.playoutLimit;return this.startOffset+t>=e}get destroyed(){var t;return!(null!=(t=this.hls)&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return(null==(t=this.hls)?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const e=Gi.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(e.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const e=this.interstitial.playoutLimit;if(e){const i=e-this.startOffset;if(i>0&&i<t)return i}return t}get remaining(){const t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return(null==(t=this.hls)?void 0:t.config.timelineOffset)||0}set timelineOffset(t){const e=this.timelineOffset;if(t!==e){const i=t-e;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const e=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,t-e),i)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var t;this.mediaAttached&&(null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var e;this.loadSource(),null==(e=this.hls)||e.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,null==(t=this.hls)||t.detachMedia()}resumeBuffering(){var t;null==(t=this.hls)||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.hls)||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),(null==(t=this.hls)?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const e=t=>delete t.details;
1t.levels.forEach(e),t.allAudioTracks.forEach(e),t.allSubtitleTracks.forEach(e),this.hasDetails=!1}}on(t,e,i){var s;null==(s=this.hls)||s.on(t,e)}once(t,e,i){var s;null==(s=this.hls)||s.once(t,e)}off(t,e,i){var s;null==(s=this.hls)||s.off(t,e)}toString(){var t;return`HlsAssetPlayer: ${ko(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class Io extends ht{constructor(t,e){super("interstitials-sched",e),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,e){return this.events?this.events.reduce((i,s)=>t<=s.startOffset&&e>s.startOffset?(delete s.error,i+1):i,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,e){if(t.event)return this.findEventIndex(t.event.identifier);let i=-1;t.nextEvent?i=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(i=this.findEventIndex(t.previousEvent.identifier)+1);const s=this.items;if(s)for(s[i]||(void 0===e&&(e=t.start),i=this.findItemIndexAtTime(e));i>=0&&null!=(r=s[i])&&r.event;){var r;i--}return i}findItemIndexAtTime(t,e){const i=this.items;if(i)for(let s=0;s<i.length;s++){let r=i[s];if(e&&"primary"!==e&&(r=r[e]),t===r.start||t>r.start&&t<r.end)return s}return-1}findJumpRestrictedIndex(t,e){const i=this.items;if(i)for(let s=t;s<=e&&i[s];s++){const t=i[s].event;if(null!=t&&t.restrictions.jump&&!t.appendInPlace)return s}return-1}findEventIndex(t){const e=this.items;if(e)for(let s=e.length;s--;){var i;if((null==(i=e[s].event)?void 0:i.identifier)===t)return s}return-1}findAssetIndex(t,e){const i=t.assetList,s=i.length;if(s>1)for(let t=0;t<s;t++){const r=i[t];if(!r.error){const i=r.timelineStart;if(e===i||e>i&&(e<i+(r.duration||0)||t===s-1))return t}}return 0}get assetIdAtEnd(){var t;const e=null==(t=this.items)||null==(t=t[this.length-1])?void 0:t.event;if(e){const t=e.assetList,i=t[t.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(t,e){const i=t.main.details,{dateRanges:s}=i,r=this.events,n=this.parseDateRanges(s,{url:i.url},e),a=Object.keys(s),o=r?r.filter(t=>!a.includes(t.identifier)):[];n.length&&n.sort((t,e)=>{const i=t.cue.pre,s=t.cue.post,r=e.cue.pre,n=e.cue.post;if(i&&!r)return-1;if(r&&!i)return 1;if(s&&!n)return 1;if(n&&!s)return-1;if(!(i||r||s||n)){const i=t.startTime,s=e.startTime;if(i!==s)return i-s}return t.dateRange.tagOrder-e.dateRange.tagOrder}),this.events=n,o.forEach(t=>{this.removeEvent(t)}),this.updateSchedule(t,o)}updateSchedule(t,e=[],i=!1){const s=this.events||[];
1if(s.length||e.length||this.length<2){const r=this.items,n=this.parseSchedule(s,t),a=i||e.length||(null==r?void 0:r.length)!==n.length||n.some((t,e)=>Math.abs(t.playout.start-r[e].playout.start)>.005||Math.abs(t.playout.end-r[e].playout.end)>.005);a&&(this.items=n,this.onScheduleUpdate(e,r))}}parseDateRanges(t,e,i){const s=[],r=Object.keys(t);for(let n=0;n<r.length;n++){const a=r[n],o=t[a];if(o.isInterstitial){let t=this.eventMap[a];t?t.setDateRange(o):(t=new To(o,e),this.eventMap[a]=t,!1===i&&(t.appendInPlace=i)),s.push(t)}}return s}parseSchedule(t,e){const i=[],s=e.main.details,r=s.live?1/0:s.edge;let n=0;if((t=t.filter(t=>!(t.error||t.cue.once&&t.hasPlayed))).length){this.resolveOffsets(t,e);let s=0,o=0;if(t.forEach((e,a)=>{const l=e.cue.pre,d=e.cue.post,c=t[a-1]||null,u=e.appendInPlace,h=d?r:e.startOffset,f=e.duration,g=e.timelineOccupancy===yo.Range?f:0,m=e.resumptionOffset,p=(null==c?void 0:c.startTime)===h,v=h+e.cumulativeDuration;let y=u?v+f:h+m;if(l||!d&&h<=0){const t=o;o+=g,e.timelineStart=v;const s=n;n+=f,i.push({event:e,start:v,end:y,playout:{start:s,end:n},integrated:{start:t,end:o}})}else{if(!(h<=r))return;{if(!p){const r=h-s;if(r>.033){const l=s,d=o;o+=r;const c=n;n+=r;const u={previousEvent:t[a-1]||null,nextEvent:e,start:l,end:l+r,playout:{start:c,end:n},integrated:{start:d,end:o}};i.push(u)}else r>0&&c&&(c.cumulativeDuration+=r,i[i.length-1].end=h)}d&&(y=v),e.timelineStart=v;const r=o;o+=g;const l=n;n+=f,i.push({event:e,start:v,end:y,playout:{start:l,end:n},integrated:{start:r,end:o}})}}const E=e.resumeTime;s=d||E>r?r:E}),s<r){var a;const t=s,e=o,l=r-s;o+=l;const d=n;n+=l,i.push({previousEvent:(null==(a=i[i.length-1])?void 0:a.event)||null,nextEvent:null,start:s,end:t+l,playout:{start:d,end:n},integrated:{start:e,end:o}})}this.setDurations(r,n,o)}else{const t=0;i.push({previousEvent:null,nextEvent:null,start:t,end:r,playout:{start:t,end:r},integrated:{start:t,end:r}}),this.setDurations(r,r,r)}return i}setDurations(t,e,i){this.durations={primary:t,playout:e,integrated:i}}resolveOffsets(t,e){const i=e.main.details,s=i.live?1/0:i.edge;let r=0,n=-1;t.forEach((a,o)=>{const l=a.cue.pre,d=a.cue.post,c=l?0:d?s:a.startTime;this.updateAssetDurations(a);if(n===c?a.cumulativeDuration=r:(r=0,n=c),!d&&a.snapOptions.in&&(a.resumeAnchor=Je(null,i.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,e)||(a.appendInPlace=!1)}if(!a.appendInPlace&&o+1<t.length){t[o+1].startTime-t[o].resumeTime<.033&&(t[o+1].appendInPlace=!1,t[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`))}const u=Y(a.resumeOffset)?a.resumeOffset:a.duration;r+=u})}primaryCanResumeInPlaceAt(t,e){const i=t.resumeTime,s=t.startTime+t.resumptionOffset;if(Math.abs(i-s)>vo)return this.log(`"${t.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1;return!Object.keys(e).some(s=>{const r=e[s].details,n=r.edge;if(i>=n)return this.log(`"${t.identifier}" resumption ${i} past ${s} playlist end ${n}`),!1;const a=Je(null,r.fragments,i);if(!a)return this.log(`"${t.identifier}" resumption ${i} does not align with any fragments in ${s} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===s?.175:0;return!(Math.abs(a.start-i)<vo+o||Math.abs(a.end-i)<vo+o)&&(this.log(`"${t.identifier}" resumption ${i} not aligned with ${s} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)})}updateAssetDurations(t){if(!t.assetListLoaded)return;const e=t.timelineStart;let i=0,s=!1,r=!1;for(let n=0;n<t.assetList.length;n++){const a=t.assetList[n],o=e+i;a.startOffset=i,a.timelineStart=o,s||(s=null===a.duration),r||(r=!!a.error);i+=a.error?0:a.duration||0}t.duration=s&&!r?Math.max(i,t.duration):i}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function wo(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class Ro{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const i=t.assetListUrl;let s;try{s=bo(i,this.hls.sessionId,t.baseUrl)}catch(e){const s=this.assignAssetListError(t,Q.ASSET_LIST_LOAD_ERROR,e,i);return void this.hls.trigger(J.ERROR,s)}e&&"data:"!==s.protocol&&s.searchParams.set("_HLS_start_offset",""+e);const r=this.hls.config,n=new(0,r.loader)(r),a={responseType:"json",url:s.href},o=r.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,i,s,r)=>{const n=e.data,a=null==n?void 0:n.ASSETS;if(!Array.isArray(a)){const e=this.assignAssetListError(t,Q.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),s.url,i,r);return void this.hls.trigger(J.ERROR,e)}t.assetListResponse=n,this.hls.trigger(J.ASSET_LIST_LOADED,{event:t,assetListResponse:n,networkDetails:r})},onError:(e,i,s,r)=>{const n=this.assignAssetListError(t,Q.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${e.code} ${e.text} (${i.url})`),i.url,r,s);this.hls.trigger(J.ERROR,n)},onTimeout:(e,i,s)=>{const r=this.assignAssetListError(t,Q.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,e,s);this.hls.trigger(J.ERROR,r)}};return n.load(a,l,d),this.hls.trigger(J.ASSET_LIST_LOADING,{event:t}),n}assignAssetListError(t,e,i,s,r,n){return t.error=i,{type:X.NETWORK_E
vendor: 18,294 bytes, line 1
1RROR,details:e,fatal:!1,interstitial:t,url:s,error:i,networkDetails:n,stats:r}}}function _o(t){var e;null==t||null==(e=t.play())||e.catch(()=>{})}function Do(t,e){return`[${t}] Advancing timeline position to ${e}`}class Po{constructor(t){this.buffered=void 0;const e=(e,i,s)=>{if((i>>>=0)>s-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${s})`);return t[i][e]};this.buffered={get length(){return t.length},end:i=>e("end",i,t.length),start:i=>e("start",i,t.length)}}}const xo={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Co=t=>String.fromCharCode(xo[t]||t),Oo=15,Mo=100,Fo={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},No={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Uo={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Bo={25:2,26:4,29:6,30:8,31:10,27:13,28:15},$o=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Go{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i="function"==typeof e?e():e;yt.log(`${this.time} [${t}] ${i}`)}}}const Vo=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].toString(16));return e};class Ko{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(t){const e=["foreground","underline","italics","background","flash"];for(let i=0;i<e.length;i++){const s=e[i];t.hasOwnProperty(s)&&(this[s]=t[s])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Ho{constructor(){this.uchar=" ",this.penState=new Ko}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.copy(e)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class jo{constructor(t){this.chars=[],this.pos=0,this.currPenState=new Ko,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Mo;t++)this.chars.push(new Ho);this.logger=t}equals(t){for(let e=0;e<Mo;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<Mo;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<Mo;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Mo&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Mo)}moveCursor(t){const e=this.pos+t;if(t>1)for(let t=this.pos+1;t<e+1;t++)this.chars[t].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=Co(t);this.pos>=Mo?this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e<Mo;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let i=0;i<Mo;i++){const s=this.chars[i].uchar;" "!==s&&(e=!1),t.push(s)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class qo{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<Oo;e++)this.rows.push(new jo(t));this.logger=t}reset(){for(let t=0;t<Oo;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let i=0;i<Oo;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<Oo;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<Oo;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t);this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,()=>"pacData = "+Ve(t));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let t=0;t<Oo;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const s=i.rows[t].cueStartTime,r=this.logger.time;if(null!==s&&null!==r&&s<r)for(let s=0;s<this.nrRollUpRows;s++)this.rows[e-this.nrRollUpRows+s+1].copy(i.rows[t+s])}}this.currRow=e;const i=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,s=Math.max(e-1,0);i.setCursor(t.indent),t.color=i.chars[s].penState.foreground}const s={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+Ve(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let i="",s=-1;for(let i=0;i<Oo;i++){const r=this.rows[i].getTextString();r&&(s=i+1,t?e.push("Row "+s+": '"+r+"'"):e.push(r.trim()))}return e.length>0&&(i=t?"["+e.join(" | ")+"]":e.join("\n")),i}getTextAndFormat(){return this.rows}}class Yo{constructor(t,e,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new qo(i),this.nonDisplayedMemory=new qo(i),this.lastOutputScreen=new qo(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let e=0;e<t.length;e++)this.writeScreen.insertChar(t[e]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>e+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const i=Math.floor(t/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=s[i]}this.logger.log(2,"MIDROW: "+Ve(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class Wo{constructor(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const s=this.logger=new Go;this.channels=[null,new Yo(t,e,s),new Yo(t+1,i,s)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){this.logger.time=t;for(let t=0;t<e.length;t+=2){const i=127&e[t],s=127&e[t+1];let r=!1,n=null;if(0===i&&0===s)continue;this.logger.log(3,()=>"["+Vo([e[t],e[t+1]])+"] -> ("+Vo([i,s])+")");const a=this.cmdHistory;if(i>=16&&i<=31){if(Xo(i,s,a)){zo(null,null,a),this.logger.log(3,()=>"Repeated command ("+Vo([i,s])+") is dropped");continue}zo(i,s,this.cmdHistory),r=this.parseCmd(i,s),r||(r=this.parseMidrow(i,s)),r||(r=this.parsePAC(i,s)),r||(r=this.parseBackgroundAttributes(i,s))}else zo(null,null,a);if(!r&&(n=this.parseChars(i,s),n)){const t=this.currentChannel;if(t&&t>0){this.channels[t].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+Vo([i,s])+" orig: "+Vo([e[t],e[t+1]]))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;const i=20===t||21===t||23===t?1:2,s=this.channels[i];return 20===t||21===t||28===t||29===t?32===e?s.ccRCL():33===e?s.ccBS():34===e?s.ccAOF():35===e?s.ccAON():36===e?s.ccDER():37===e?s.ccRU(2):38===e?s.ccRU(3):39===e?s.ccRU(4):40===e?s.ccFON():41===e?s.ccRDC():42===e?s.ccTR():43===e?s.ccRTD():44===e?s.ccEDM():45===e?s.ccCR():46===e?s.ccENM():47===e&&s.ccEOC():s.ccTO(e-32),this.currentChannel=i,!0}parseMidrow(t,e){let i=0;if((17===t||25===t)&&e>=32&&e<=47){if(i=17===t?1:2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const s=this.channels[i];return!!s&&(s.ccMIDROW(e),this.logger.log(3,()=>"MIDROW ("+Vo([t,e])+")"),!0)}return!1}parsePAC(t,e){let i;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;const s=t<=23?1:2;i=e>=64&&e<=95?1===s?Fo[t]:Uo[t]:1===s?No[t]:Bo[t];const r=this.channels[s];return!!r&&(r.setPAC(this.interpretPAC(i,e)),this.currentChannel=s,!0)}interpretPAC(t,e){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:t};return i=e>95?e-96:e-64,s.underline=!(1&~i),i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=4*Math.floor((i-16)/2),s}parseChars(t,e){let i,s=null,r=null;if(t>=25?(i=2,r=t-8):(i=1,r=t),r>=17&&r<=19){let t;t=17===r?e+80:18===r?e+112:e+144,this.logger.log(2,()=>"Special char '"+Co(t)+"' in channel "+i),s=[t]}else t>=32&&t<=127&&(s=0===e?[t]:[t,e]);return s&&this.logger.log(3,()=>"Char codes =  "+Vo(s).join(",")),s}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let i;const s={};16===t||24===t?(i=Math.floor((e-32)/2),s.background=$o[i],e%2==1&&(s.background=s.background+"_semi")):45===e?s.background="transparent":(s.foreground="black",47===e&&(s.underline=!0));const r=t<=23?1:2;return this.channels[r].setBkgData(s),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}zo(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const i=this.channels[e];i&&i.cueSplitAtTime(t)}}}function zo(t,e,i){i.a=t,i.b=e}function Xo(t,e,i){return i.a===t&&i.b===e}var Qo=function(){if(null!=ls&&ls.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function i(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const i=e.toLowerCase();return!!~t.indexOf(i)&&i}function s(t){return i(e,t)}function r(t,...e){let i=1;for(;i<arguments.length;i++){const e=arguments[i];for(const i in e)t[i]=e[i]}return t}function n(e,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let d="",c=!1,u=e,h=n,f=a,g=null,m="",p=!0,v="auto",y="start",E=50,T="middle",S=50,b="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return d},set:function(t){d=""+t}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return c},set:function(t){c=!!t}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},l,{get:function(){return h},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");h=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",r({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return m},set:function(e){const s=function(e){return i(t,e)}(e);if(!1===s)throw new SyntaxError("An invalid or illegal string was specified.");m=s,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return p},set:function(t){p=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return v},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return y},set:function(t){const e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},l,{get:function(){return E},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return T},set:function(t){const e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return b},set:function(t){const e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");b=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class Jo{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function Zo(t){function e(t,e,i,s){return 3600*(0|t)+60*(0|e)+(0|i)+parseFloat(s||0)}const i=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?e(i[2],i[3],0,i[4]):e(i[1],i[2],i[3],i[4]):null}class tl{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,i){return i?this.has(t)?this.values[t]:e[i]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,i){for(let s=0;s<i.length;++s)if(e===i[s]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const i=parseFloat(e);
vendor: 4,556 bytes, line 1
1if(i>=0&&i<=100)return this.set(t,i),!0}return!1}}function el(t,e,i,s){const r=s?t.split(s):[t];for(const t in r){if("string"!=typeof r[t])continue;const s=r[t].split(i);if(2!==s.length)continue;e(s[0],s[1])}}const il=new Qo(0,0,""),sl="middle"===il.align?"middle":"center";function rl(t,e,i){const s=t;function r(){const e=Zo(t);if(null===e)throw new Error("Malformed timestamp: "+s);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=r(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+s);t=t.slice(3),n(),e.endTime=r(),n(),function(t,e){const s=new tl;el(t,function(t,e){let r;switch(t){case"region":for(let r=i.length-1;r>=0;r--)if(i[r].id===e){s.set(t,i[r].region);break}break;case"vertical":s.alt(t,e,["rl","lr"]);break;case"line":r=e.split(","),s.integer(t,r[0]),s.percent(t,r[0])&&s.set("snapToLines",!1),s.alt(t,r[0],["auto"]),2===r.length&&s.alt("lineAlign",r[1],["start",sl,"end"]);break;case"position":r=e.split(","),s.percent(t,r[0]),2===r.length&&s.alt("positionAlign",r[1],["start",sl,"end","line-left","line-right","auto"]);break;case"size":s.percent(t,e);break;case"align":s.alt(t,e,["start",sl,"end","left","right"])}},/:/,/\s/),e.region=s.get("region",null),e.vertical=s.get("vertical","");let r=s.get("line","auto");"auto"===r&&-1===il.line&&(r=-1),e.line=r,e.lineAlign=s.get("lineAlign","start"),e.snapToLines=s.get("snapToLines",!0),e.size=s.get("size",100),e.align=s.get("align",sl);let n=s.get("position","auto");"auto"===n&&50===il.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function nl(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class al{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Jo,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function i(){let t=e.buffer,i=0;for(t=nl(t);i<t.length&&"\r"!==t[i]&&"\n"!==t[i];)++i;const s=t.slice(0,i);return"\r"===t[i]&&++i,"\n"===t[i]&&++i,e.buffer=t.slice(i),s}function s(t){el(t,function(t,e){},/:/)}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{let t="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;t=i();const s=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==s||!s[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let r=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(r?r=!1:t=i(),e.state){case"HEADER":/:/.test(t)?s(t):t||(e.state="ID");continue;case"NOTE":t||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){e.state="NOTE";break}if(!t)continue;if(e.cue=new Qo(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{rl(t,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const i=-1!==t.indexOf("--\x3e");if(!t||i&&(r=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(null===e.cue)continue;e.cue.text&&(e.cue.text+="\n"),e.cue.text+=t}continue;case"BADCUE":t||(e.state="ID")}}}catch(t){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}}const ol=/\r\n|\n\r|\n|\r/g,ll=function(t,e,i=0){return t.slice(i,i+e.length)===e};function dl(t,e,i){return po(t.toString())+po(e.toString())+po(i)}function cl(t,e,i,s,r,n,a){const o=new al,l=St(new Uint8Array(t)).trim().replace(ol,"\n").split("\n"),d=[],c=e?function(t,e=1){return Pn(t,9e4,1/e)}(e.baseTime,e.timescale):0;let u,h="00:00.000",f=0,g=0,m=!0;o.oncue=function(t){const n=i[s];let a=i.ccOffset;const o=(f-c)/9e4;if(null!=n&&n.new&&(void 0!==g?a=i.ccOffset=n.start:function(t,e,i){let s=t[e],r=t[s.prevCC];if(!r||!r.new&&s.new)return t.ccOffset=t.presentationOffset=s.start,void(s.new=!1);for(;null!=(n=r)&&n.new;){var n;t.ccOffset+=s.start-r.start,s.new=!1,s=r,r=t[s.prevCC]}t.presentationOffset=i}(i,s,o)),o){if(!e)return void(u=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}const l=t.endTime-t.startTime,h=$n(9e4*(t.startTime+a-g),9e4*r)/9e4;t.startTime=Math.max(h,0),t.endTime=Math.max(h+l,0);const m=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(m)),t.id||(t.id=dl(t.
1startTime,t.endTime,m)),t.endTime>0&&d.push(t)},o.onparsingerror=function(t){u=t},o.onflush=function(){u?a(u):n(d)},l.forEach(t=>{if(m){if(ll(t,"X-TIMESTAMP-MAP=")){m=!1,t.slice(16).split(",").forEach(t=>{ll(t,"LOCAL:")?h=t.slice(6):ll(t,"MPEGTS:")&&(f=parseInt(t.slice(7)))});try{g=function(t){let e=parseInt(t.slice(-3));const i=parseInt(t.slice(-6,-4)),s=parseInt(t.slice(-9,-7)),r=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(Y(e)&&Y(i)&&Y(s)&&Y(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*i,e+=6e4*s,e+=36e5*r,e}(h)/1e3}catch(t){u=t}return}""===t&&(m=!1)}o.parse(t+"\n")}),o.flush()}const ul="stpp.ttml.im1t",hl=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,fl=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,gl={left:"start",center:"center",right:"end",start:"start",end:"end"};function ml(t,e,i,s){const r=jt(new Uint8Array(t),["mdat"]);if(0===r.length)return void s(new Error("Could not parse IMSC1 mdat"));const n=r.map(t=>St(t)),a=function(t,e,i=1,s=!1){return Pn(t,e,1/i,s)}(e.baseTime,1,e.timescale);try{n.forEach(t=>i(function(t,e){const i=(new DOMParser).parseFromString(t,"text/xml"),s=i.getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce((t,e)=>(t[e]=s.getAttribute(`ttp:${e}`)||r[e],t),{}),a="preserve"!==s.getAttribute("xml:space"),o=vl(pl(s,"styling","style")),l=vl(pl(s,"layout","region")),d=pl(s,"body","[begin]");return[].map.call(d,t=>{const i=yl(t,a);if(!i||!t.hasAttribute("begin"))return null;const s=Sl(t.getAttribute("begin"),n),r=Sl(t.getAttribute("dur"),n);let d=Sl(t.getAttribute("end"),n);if(null===s)throw Tl(t);if(null===d){if(null===r)throw Tl(t);d=s+r}const c=new Qo(s-e,d-e,i);c.id=dl(c.startTime,c.endTime,c.text);const u=function(t,e,i){const s="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(r=i[a]);return n.reduce((i,n)=>{const a=El(e,s,n)||El(t,s,n)||El(r,s,n);return a&&(i[n]=a),i},{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:h}=u;if(h){const t=gl[h];t&&(c.lineAlign=t),c.align=h}return dt(c,u),c}).filter(t=>null!==t)}(t,a)))}catch(t){s(t)}}function pl(t,e,i){const s=t.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(i)):[]}function vl(t){return t.reduce((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t},{})}function yl(t,e){return[].slice.call(t.childNodes).reduce((t,i,s)=>{var r;return"br"===i.nodeName&&s?t+"\n":null!=(r=i.childNodes)&&r.length?yl(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function El(t,e,i){return t&&t.hasAttributeNS(e,i)?t.getAttributeNS(e,i):null}function Tl(t){return new Error(`Could not parse ttml timestamp ${t}`)}function Sl(t,e){if(!t)return null;let i=Zo(t);return null===i&&(hl.test(t)?i=function(t,e){const i=hl.exec(t),s=(0|i[4])+(0|i[5])/e.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+s/e.frameRate}(t,e):fl.test(t)&&(i=function(t,e){const i=fl.exec(t),s=Number(i[1]);switch(i[2]){case"h":return 3600*s;case"m":return 60*s;case"ms":return 1e3*s;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}(t,e))),i}class bl{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,i){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function Al(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function kl(t,e){return!!t&&t.kind===Al(e)&&ia(e,t)}function Ll(t,e,i,s){return Math.min(e,s)-Math.max(t,i)}const Il=/\s/,wl={newCue(t,e,i,s){const r=[];let n,a,o,l,d;const c=self.VTTCue||self.TextTrackCue;for(let h=0;h<s.rows.length;h++)if(n=s.rows[h],o=!0,l=0,d="",!n.isEmpty()){var u;for(let t=0;t<n.chars.length;t++)Il.test(n.chars[t].uchar)&&o?l++:(d+=n.chars[t].uchar,o=!1);n.cueStartTime=e,e===i&&(i+=1e-4),l>=16?l--:l++;const s=nl(d.trim()),f=dl(e,i,s);null!=t&&null!=(u=t.cues)&&u.getCueById(f)||(a=new c(e,i,s),a.id=f,a.line=h+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return t&&r.length&&(r.sort((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>
18?e.line-t.line:t.line-e.line),r.forEach(e=>ho(t,e))),r}};const Rl=/(\d+)-(\d+)\/(\d+)/;class _l{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||Dl,this.controller=new self.AbortController,this.stats=new Rt}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,i){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const r=function(t,e){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(dt({},t.headers))};t.rangeEnd&&i.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return i}(t,this.controller.signal),n="arraybuffer"===t.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=i,this.request=this.fetchSetup(t,r),self.clearTimeout(this.requestTimeout),e.timeout=o&&Y(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,t,this.response))},e.timeout);(Wn(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(i=>{var r;this.response=this.loader=i;const a=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,t,this.response))},l-(a-s.loading.start)),!i.ok){const{status:t,statusText:e}=i;throw new Pl(e||"fetch, bad network response",t,i)}s.loading.first=a,s.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=Rl.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(Y(t))return t}const i=t.get("Content-Length");if(i)return parseInt(i)}(i.headers)||s.total;const o=null==(r=this.callbacks)?void 0:r.onProgress;return o&&Y(e.highWaterMark)?this.loadProgressively(i,s,t,e.highWaterMark,o):n?i.arrayBuffer():"json"===t.responseType?i.json():i.text()}).then(i=>{var r,n;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const l=i[a];l&&(s.loaded=s.total=l);const d={url:o.url,data:i,code:o.status},c=null==(r=this.callbacks)?void 0:r.onProgress;c&&!Y(e.highWaterMark)&&c(s,t,i,o),null==(n=this.callbacks)||n.onSuccess(d,s,t,o)}).catch(e=>{var i;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const r=e&&e.code||0,n=e?e.message:null;null==(i=this.callbacks)||i.onError({code:r,text:n},t,e?e.details:null,s)})}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,i,s=0,r){const n=new Sr,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&r(e,i,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return e.loaded+=d,d<s||n.dataLength?(n.push(l),n.dataLength>=s&&r(e,i,n.flush().buffer,t)):r(e,i,l.buffer,t),o()}).catch(()=>Promise.reject());return o()}}function Dl(t,e){return new self.Request(t.url,e)}class Pl extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const xl=/^age:\s*[\d.]+\s*$/im;class Cl{constructor(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=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new Rt,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const 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()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,i){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=i,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>
vendor: 12,684 bytes, line 1
1{if(this.loader===i&&!this.stats.aborted)return r(i,e.url)}).catch(t=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",e.url,!0),r(i,e.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,e,t)}).catch(t=>{var r;null==(r=this.callbacks)||r.onError({code:i.status,text:t.message},e,i,s)}):this.openAndSendXhr(i,e,t)}openAndSendXhr(t,e,i){t.readyState||t.open("GET",e.url,!0);const s=e.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=i.loadPolicy;if(s)for(const e in s)t.setRequestHeader(e,s[e]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),i.timeout=r&&Y(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:i}=this;if(!t||!e)return;const s=e.readyState,r=this.config;if(!i.aborted&&s>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===s)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const s=e.status,l="text"===e.responseType?e.responseText:null;if(s>=200&&s<300){const r=null!=l?l:e.response;if(null!=r){var n,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);const o="arraybuffer"===e.responseType?r.byteLength:r.length;i.loaded=i.total=o,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(i,t,r,e);const d={url:e.responseURL,data:r,code:s};return void(null==(a=this.callbacks)||a.onSuccess(d,i,t,e))}}const d=r.loadPolicy.errorRetry;var o;if(li(d,i.retry,!1,{url:t.url,data:void 0,code:s}))this.retry(d);else yt.error(`${s} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:s,text:e.statusText},t,e,i)}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(li(t,this.stats.retry,!0))this.retry(t);else{var e;yt.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:i}=this;this.retryDelay=ai(t,i.retry),i.retry++,yt.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${i.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&xl.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const Ol=ut(ut({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Cl,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends ht{constructor(t){super("abr",t.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var e;const{fragCurrent:i,partCurrent:s,hls:r}=this,{autoLevelEnabled:n,media:a}=r;if(!i||!a)return;const o=performance.now(),l=s?s.stats:i.stats,d=s?s.duration:i.duration,c=o-l.loading.start,u=r.minAutoLevel,h=i.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||h<=u)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const g=f>-1&&f!==h,m=!!t||g;if(!m&&(a.paused||!a.playbackRate||!a.readyState))return;const p=r.mainForwardBufferInfo;if(!m&&null===p)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(c<=Math.max(v,d/(2*y)*1e3))return;const E=p?p.len/y:0,T=l.loading.first?l.loading.first-l.loading.start:-1,S=l.loaded&&T>-1,b=this.getBwEstimate(),A=r.levels,k=A[h],L=Math.max(l.loaded,Math.round(d*(i.bitrate||k.averageBitrate)/8));let I=S?c-T:c;I<1&&S&&(I=Math.min(c,8*l.loaded/b));const w=S?1e3*l.loaded/I:0,R=v/1e3,_=w?(L-l.loaded)/w:8*L/b+R;if(_<=E)return;const D=w?8*w:b,P=!0===(null==(e=(null==t?void 0:t.details)||this.hls.latestLevelDetails)?void 0:e.live),x=this.hls.config.abrBandWidthUpFactor;let C,O=Number.POSITIVE_INFINITY;for(C=h-1;C>u;C--){const t=A[C].maxBitrate,e=!A[C].details||P;if(O=this.getTimeToLoadFrag(R,D,d*t,e),O<Math.min(E,d+R))break}if(O>=_)return;if(O>10*d)return;S?this.bwEstimator.sample(c-Math.min(v,T),l.loaded):this.bwEstimator.sampleTTFB(c);const M=A[C].maxBitrate;this.getBwEstimate()*x>M&&this.resetEstimator(M);const F=this.findBestLevel(M,u,C,0,E,1,1);F>-1&&(C=F),this.warn(`Fragment ${i.sn}${s?" part "+s.index:""} of level ${h} is loading too slowly;\n      Fragment duration: ${i.duration.toFixed(3)}\n      Time to underbuffer: ${E.toFixed(3)} s\n      Estimated load time for current fragment: ${_.toFixed(3)} s\n      Estimated load time for down switch fragment: ${O.toFixed(3)} s\n      TTFB estimate: ${0|T} ms\n      Current BW estimate: ${Y(b)?0|b:"Unknown"} bps\n      New BW estimate: ${0|this.getBwEstimate()} bps\n      Switching to level ${C} @ ${0|M} bps`),r.nextLoadLevel=r.nextAutoLevel=C,this.clearTimer();const N=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===C&&C>0){const t=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${C>0?"and switching down":""}\n      Fragment duration: ${i.duration.toFixed(3)} s\n      Time to underbuffer: ${t.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,C>u){let e=this.findBestLevel(this.hls.levels[u].bitrate,u,C,0,t,1,1);-1===e&&(e=u),this.hls.nextLoadLevel=this.hls.nextAutoLevel=e,this.resetEstimator(this.hls.levels[e].bitrate)}}};g||_>2*O?N():this.timer=self.setInterval(N,1e3*O),r.trigger(J.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:s,stats:l})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new ot(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.FRAG_LOADING,this.onFragLoading,this),t.on(J.FRAG_LOADED,this.onFragLoaded,this),t.on(J.FRAG_BUFFERED,this.onFragBuffered,this),t.on(J.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(J.LEVEL_LOADED,this.onLevelLoaded,this),t.on(J.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(J.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(J.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.FRAG_LOADING,this.onFragLoading,this),t.off(J.FRAG_LOADED,this.onFragLoaded,this),t.off(J.FRAG_BUFFERED,this.onFragBuffered,this),t.off(J.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(J.LEVEL_LOADED,this.onLevelLoaded,this),t.off(J.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(J.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(J.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const i=e.frag;if(!this.ignoreFragment(i)){var s;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(s=e.part)?s:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case Q.BUFFER_ADD_CODEC_ERROR:case Q.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Q.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:i,partCurrent:s}=this;if(t&&i&&t.sn===i.sn&&t.level===i.level){const e=performance.now(),i=s?s.stats:t.stats,r=e-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(t,n),i.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(t,e,i,s){return t+i/e+(s?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const i=this.hls.config,{loading:s}=e.stats,r=s.end-s.first;Y(r)&&(this.lastLevelLoadSec=r/1e3),e.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,{frag:e,part:i}){const s=i?i.stats:e.stats;if(e.type===st&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=i?i.duration:e.duration,r=this.hls.levels[e.level],n=(r.loaded?r.loaded.bytes:0)+s.loaded,a=(r.loaded?r.loaded.duration:0)+t;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(e.bitrateTest){const t={stats:s,frag:e,part:i,id:e.type};this.onFragBuffered(J.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:i,part:s}=e,r=null!=s&&s.stats.loaded?s.stats:i.stats;if(r.aborted)return;if(this.ignoreFragment(i))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==st||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,e,t,0,s,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),t);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const s=e&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,s)&&e[t].loadError<=e[s].loadError)return t}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}
1_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:s,config:r,minAutoLevel:n}=i,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=r.abrBandWidthFactor,c=r.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,s,l,0,d,c);if(t>=0)return this.rebufferNotice=-1,t}let u=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){u=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),d=c=1}}const h=this.findBestLevel(o,n,s,l,u,d,c);if(this.rebufferNotice!==h&&(this.rebufferNotice=h,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${h}`)),h>-1)return h;const f=i.levels[n],g=i.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:i.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const i=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,s=t.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,i,s,r,n,a){var o;const l=s+r,d=this.lastLoadedFragLevel,c=-1===d?this.hls.firstLevel:d,{fragCurrent:u,partCurrent:h}=this,{levels:f,allAudioTracks:g,loadLevel:m,config:p}=this.hls;if(1===f.length)return 0;const v=f[c],y=!(null==(o=this.hls.latestLevelDetails)||!o.live),E=-1===m||-1===d;let T,S="SDR",b=(null==v?void 0:v.frameRate)||0;const{audioPreference:A,videoPreference:k}=p,L=this.audioTracksByGroup||(this.audioTracksByGroup=He(g));let I=-1;if(E){if(-1!==this.firstSelection)return this.firstSelection;const s=this.codecTiers||(this.codecTiers=function(t,e,i,s){return t.slice(i,s+1).reduce((t,i,s)=>{if(!i.codecSet)return t;const r=i.audioGroups;let n=t[i.codecSet];n||(t[i.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:s,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,i.bitrate);const a=Math.min(i.height,i.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,i.frameRate),n.minIndex=Math.min(n.minIndex,s),n.maxScore=Math.max(n.maxScore,i.score),n.fragmentError+=i.fragmentError,n.videoRanges[i.videoRange]=(n.videoRanges[i.videoRange]||0)+1,r&&r.forEach(t=>{if(!t)return;const i=e.groups[t];i&&(n.hasDefaultAudio=n.hasDefaultAudio||e.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(i.channels).forEach(t=>{n.channels[t]=(n.channels[t]||0)+i.channels[t]}))}),t},{})}(f,L,e,i)),r=function(t,e,i,s,r){const n=Object.keys(t),a=null==s?void 0:s.channels,o=null==s?void 0:s.audioCodec,l=null==r?void 0:r.videoCodec,d=a&&2===parseInt(a);let c=!1,u=!1,h=1/0,f=1/0,g=1/0,m=1/0,p=0,v=[];const{preferHDR:y,allowedVideoRanges:E}=Ge(e,r);for(let e=n.length;e--;){const i=t[n[e]];c||(c=i.channels[2]>0),h=Math.min(h,i.minHeight),f=Math.min(f,i.minFramerate),g=Math.min(g,i.minBitrate),E.filter(t=>i.videoRanges[t]>0).length>0&&(u=!0)}h=Y(h)?h:0,f=Y(f)?f:0;const T=Math.max(1080,h),S=Math.max(30,f);g=Y(g)?g:i,i=Math.max(g,i),u||(e=void 0);const b=n.length>1;return{codecSet:n.reduce((e,s)=>{const r=t[s];if(s===e)return e;if(v=u?E.filter(t=>r.videoRanges[t]>0):[],b){if(r.minBitrate>i)return Ke(s,`min bitrate of ${r.minBitrate} > current estimate of ${i}`),e;if(!r.hasDefaultAudio)return Ke(s,"no renditions with default or auto-select sound found"),e;if(o&&s.indexOf(o.substring(0,4))%5!=0)return Ke(s,`audio codec preference "${o}" not found`),e;if(a&&!d){if(!r.channels[a])return Ke(s,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),e}else if((!o||d)&&c&&0===r.channels[2])return Ke(s,"no renditions with stereo sound found"),e;if(r.minHeight>T)return Ke(s,`min resolution of ${r.minHeight} > maximum of ${T}`),e;if(r.minFramerate>S)return Ke(s,`min framerate of ${r.minFramerate} > maximum of ${S}`),e;if(!v.some(t=>r.videoRanges[t]>0))return Ke(s,`no variants with VIDEO-RANGE of ${Ve(v)} found`),e;if(l&&s.indexOf(l.substring(0,4))%5!=0)return Ke(s,`video codec preference "${l}" not found`),e;if(r.maxScore<p)return Ke(s,`max score of ${r.maxScore} < selected max of ${p}`),e}return e&&(pe(s)>=pe(e)||r.fragmentError>t[e].fragmentError)?e:(m=r.minIndex,p=r.maxScore,s)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:m}}(s,S,t,A,k),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:d,preferHDR:c}=r;I=d,T=n,S=c?a[a.length-1]:a[0],b=o,t=Math.max(t,l),this.log(`picked start tier ${Ve(r)}`)}else T=null==v?void 0:v.codecSet,S=null==v?void 0:v.videoRange;const w=h?h.duration:u?u.duration:0,R=this.bwEstimator.getEstimateTTFB()/1e3,_=[];for(let o=i;o>=e;o--){var D;const e=f[o],u=o>c;if(!e)continue;if(p.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const i=navigator.mediaCapabilities;"function"==typeof(null==i?void 0:i.decodingInfo)&&Re(e,L,S,b,t,A)?(e.supportedPromise=_e(e,L,i,this.supportedCache),e.supportedPromise.then(t=>{if(!this.hls)return;
1e.supportedResult=t;const i=this.hls.levels,s=i.indexOf(e);t.error?this.warn(`MediaCapabilities decodingInfo error: "${t.error}" for level ${s} ${Ve(t)}`):t.supported?t.decodingInfoResults.some(t=>!1===t.smooth||!1===t.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${s} not smooth or powerEfficient: ${Ve(t)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${s} ${Ve(t)}`),s>-1&&i.length>1&&(this.log(`Removing unsupported level ${s}`),this.hls.removeLevel(s),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(t=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${t}`)})):e.supportedResult=Ie}if((T&&e.codecSet!==T||S&&e.videoRange!==S||u&&b>e.frameRate||!u&&b>0&&b<e.frameRate||null!=(D=e.supportedResult)&&null!=(D=D.decodingInfoResults)&&D.some(t=>!1===t.smooth))&&(!E||o!==I)){_.push(o);continue}const g=e.details,v=(h?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||w;let k;k=u?a*t:n*t;const P=w&&s>=2*w&&0===r?e.averageBitrate:e.maxBitrate,x=this.getTimeToLoadFrag(R,k,P*v,void 0===g);if(k>=P&&(o===d||0===e.loadError&&0===e.fragmentError)&&(x<=R||!Y(x)||y&&!this.bitrateTestDelay||x<l)){const t=this.forcedAutoLevel;return o===m||-1!==t&&t===m||(_.length&&this.trace(`Skipped level(s) ${_.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[_[0]].codecs}" ${f[_[0]].videoRange}; not compatible with "${T}" ${S}`),this.info(`switch candidate:${c}->${o} adjustedbw(${Math.round(k)})-bitrate=${Math.round(k-P)} ttfb:${R.toFixed(1)} avgDuration:${v.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${x.toFixed(1)} firstSelection:${E} codecSet:${e.codecSet} videoRange:${e.videoRange} hls.loadLevel:${m}`)),E&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:i}=this.hls;return Math.min(Math.max(t,i),e)}},bufferController:class extends ht{constructor(t,e){var i;super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=t=>{var e;this.hls&&"open"===(null==(e=this.mediaSource)?void 0:e.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:e,mediaSource:i}=this;t&&this.log("Media source opened"),e&&i&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(J.MEDIA_ATTA
vendor: 1,041 bytes, line 1
1CHED,{media:e,mediaSource:i}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&this.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t,this.fragmentTracker=e,this.appendSource=(i=Et(t.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:t}=this;
vendor: 11,353 bytes, line 1
1t.on(J.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.MANIFEST_PARSED,this.onManifestParsed,this),t.on(J.BUFFER_RESET,this.onBufferReset,this),t.on(J.BUFFER_APPENDING,this.onBufferAppending,this),t.on(J.BUFFER_CODECS,this.onBufferCodecs,this),t.on(J.BUFFER_EOS,this.onBufferEos,this),t.on(J.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(J.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(J.FRAG_PARSED,this.onFragParsed,this),t.on(J.FRAG_CHANGED,this.onFragChanged,this),t.on(J.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(J.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.MANIFEST_PARSED,this.onManifestParsed,this),t.off(J.BUFFER_RESET,this.onBufferReset,this),t.off(J.BUFFER_APPENDING,this.onBufferAppending,this),t.off(J.BUFFER_CODECS,this.onBufferCodecs,this),t.off(J.BUFFER_EOS,this.onBufferEos,this),t.off(J.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(J.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(J.FRAG_PARSED,this.onFragParsed,this),t.off(J.FRAG_CHANGED,this.onFragChanged,this),t.off(J.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const i={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const e=this.isQueued();(t||e)&&this.warn(`Transfering MediaSource with${e?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===e?dt(i,s.tracks):this.sourceBuffers.forEach(t=>{const[e]=t;e&&(i[e]=dt({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null}),{media:t,mediaSource:e,tracks:i}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){var i;let s=2;(e.audio&&!e.video||!e.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(t,e){const i=this.media=e.media;this.transferData=this.overrides=void 0;const s=Et(this.appendSource);if(s){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const r=this.mediaSource=e.mediaSource||new s;if(this.assignMediaSource(r),t)this._objectUrl=i.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{i.removeAttribute("src");const e=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||e&&r instanceof e,oa(i),function(t,e){const i=self.document.createElement("source");i.type="video/mp4",i.src=e,t.appendChild(i)}(i,t),i.load()}catch(e){i.src=t}else i.src=t}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var e,i;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(i=t.constructor)?void 0:i.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const i=this.tracks,s=e.tracks,r=s?Object.keys(s):null,n=r?r.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&r&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${Ve(i,(t,e)=>"initSegment"===t?void 0:e)};\ntransfer tracks: ${Ve(s,(t,e)=>"initSegment"===t?void 0:e)}}`),!Tt(s,i)){e.mediaSource=null,e.tracks=void 0;const r=t.currentTime,n=this.details,a=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching(J.MEDIA_DETACHING,{}),this.onMediaAttaching(J.MEDIA_ATTACHING,e),void(t.currentTime=a))}this.transferData=void 0,r.forEach(t=>{const e=t,i=s[e];if(i){const t=i.buffer;if(t){const s=this.fragmentTracker,r=i.id;if(s.hasFragments(r)||s.hasParts(r)){const i=Gi.getBuffered(t);s.detectEvictedFragments(e,i,r,null,!0)}const n=la(e),a=[e,t];this.sourceBuffers[n]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,i)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var t;const e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){const i=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:s,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach(([t])=>{t&&this.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===r.readyState;try{const e=r.sourceBuffers;for(let i=e.length;i--;)t&&e[i].abort(),r.removeSourceBuffer(e[i]);t&&r.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),i||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(s.removeAttribute("src"),this.appendSource&&oa(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(J.MEDIA_DETACHED,e)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),i)try{var s;null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(e){this.warn(`onBufferReset ${t}`,e)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[la(t)]=[null,null];const e=this.tracks[t];e&&(e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new sa(this.tracks)}onBufferCodecs(t,e){var i;const s=this.tracks,r=Object.keys(e);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in e&&(s.audio||s.video)||s.audiovideo&&("audio"in e||"video"in e),a=!n&&this.sourceBufferCount&&this.media&&r.some(t=>!s[t]);n||a?this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`):(r.forEach(t=>{var i,r;const n=e[t],{id:a,codec:o,levelCodec:l,container:d,metadata:c,supplemental:u}=n;let h=s[t];const f=null==(i=this.transferData)||null==(i=i.tracks)?void 0:i[t],g=null!=f&&f.buffer?f:h,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=null==g?void 0:g.levelCodec;h||(h=s[t]={buffer:void 0,listeners:[],codec:o,supplemental:u,container:d,levelCodec:l,metadata:c,id:a});const v=Te(m,p),y=null==v?void 0:v.replace(ra,"$1");let E=Te(o,l);const T=null==(r=E)?void 0:r.replace(ra,"$1");E&&v&&y!==T&&("audio"===t.slice(0,5)&&(E=Ee(E,this.appendSource)),this.log(`switching codec ${m} to ${E}`),E!==(h.pendingCodec||h.codec)&&(h.pendingCodec=E),h.container=d,this.appendChangeType(t,d,E))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&"main"===(null==(i=e.audio)?void 0:i.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,e)=>{const i=this.tracks[e];return t[e]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t},{})}appendChangeType(t,e,i){const s=`${e};codecs=${i}`,r={label:`change-type=${s}`,execute:()=>{const r=this.tracks[t];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${t} sourceBuffer type to ${s}`),n.changeType(s),r.codec=i,r.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(r,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const i=t.start,s=i+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(i,st))?void 0:e.gap))return;const r={label:"block-audio",execute:()=>{var t;const e=this.tracks.video;(this.lastVideoAppendEnd>s||null!=e&&e.buffer&&Gi.isBuffered(e.buffer,s)||!0===(null==(t=this.fragmentTracker.getAppendedFrag(s,st))?void 0:t.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.blockedAudioAppend={op:r,frag:t},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:e}=this;t&&e&&(this.blockedAudioAppend=null,e.unblockAudio(t.op))}onBufferAppending(t,e){const{tracks:i}=this,{data:s,type:r,parent:n,frag:a,part:o,chunkMeta:l,offset:d}=e,c=l.buffering[r],{sn:u,cc:h}=a,f=self.performance.now();c.start=f;const g=a.stats.buffering,m=o?o.stats.buffering:null;0===g.start&&(g.start=f),m&&0===m.start&&(m.start=f);const p=i.audio;let v=!1;"audio"===r&&"audio/mpeg"===(null==p?void 0:p.container)&&(v=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const y=i.video,E=null==y?void 0:y.buffer;if(E&&"initSegment"!==u){const t=o||a,e=this.blockedAudioAppend;if("audio"!==r||"main"===n||this.blockedAudioAppend||y.ending||y.ended){if("video"===r){const i=t.end;if(e){const t=e.frag.start;(i>t||i<this.lastVideoAppendEnd||Gi.isBuffered(E,t))&&this.unblockAudio()}this.lastVideoAppendEnd=i}}else{const e=t.start+.05*t.duration,i=E.buffered,s=this.currentOp("video");i.length||s?!s&&!Gi.isBuffered(E,e)&&this.lastVideoAppendEnd<e&&this.blockAudio(t):this.blockAudio(t)}}const T=(o||a).start,S={label:`append-${r}`,execute:()=>{var t;c.executeStart=self.performance.now();const e=null==(t=this.tracks[r])?void 0:t.buffer;e&&(v?this.updateTimestampOffset(e,T,.1,r,u,h):void 0!==d&&Y(d)&&this.updateTimestampOffset(e,d,1e-6,r,u,h)),this.appendExecutor(s,r)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();c.executeEnd=c.end=t,0===g.first&&(g.first=t),m&&0===m.first&&(m.first=t);const e={};
1this.sourceBuffers.forEach(([t,i])=>{t&&(e[t]=Gi.getBuffered(i))}),this.appendErrors[r]=0,"audio"===r||"video"===r?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(J.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:e})},onError:t=>{var e;const i={type:X.MEDIA_ERROR,parent:a.type,details:Q.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:t,err:t,fatal:!1},s=null==(e=this.media)?void 0:e.error;if(t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t)i.details=Q.BUFFER_FULL_ERROR;else if(t.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!s)i.errorAction=yi(!0);else if(t.name===na&&0===this.sourceBufferCount)i.errorAction=yi(!0);else{const t=++this.appendErrors[r];this.warn(`Failed ${t}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${s||"no media error"})`),(t>=this.hls.config.appendErrorMaxRetry||s)&&(i.fatal=!0)}this.hls.trigger(J.ERROR,i)}};this.log(`queuing "${r}" append sn: ${u}${o?" p: "+o.index:""} of ${a.type===st?"level":"track"} ${a.level} cc: ${h}`),this.append(S,r,this.isPending(this.tracks[r]))}getFlushOp(t,e,i){return this.log(`queuing "${t}" remove ${e}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(J.BUFFER_FLUSHED,{type:t})},onError:s=>{this.warn(`Failed to remove ${e}-${i} from "${t}" SourceBuffer`,s)}}}onBufferFlushing(t,e){const{type:i,startOffset:s,endOffset:r}=e;i?this.append(this.getFlushOp(i,s,r),i):this.sourceBuffers.forEach(([t])=>{t&&this.append(this.getFlushOp(t,s,r),t)})}onFragParsed(t,e){const{frag:i,part:s}=e,r=[],n=s?s.elementaryStreams:i.elementaryStreams;n[Pt]?r.push("audiovideo"):(n[_t]&&r.push("audio"),n[Dt]&&r.push("video"));0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(()=>{const t=self.performance.now();i.stats.buffering.end=t,s&&(s.stats.buffering.end=t);const e=s?s.stats:i.stats;this.hls.trigger(J.FRAG_BUFFERED,{frag:i,part:s,stats:e,id:i.type})},r).catch(t=>{this.warn(`Fragment buffered callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const e=this.tracks[t];if(e)return!e.ended||e.ending}return!1})}onBufferEos(t,e){var i;this.sourceBuffers.forEach(([t])=>{if(t){const i=this.tracks[t];e.type&&e.type!==t||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${t} buffer reached EOS`)))}});const s=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)})?s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger(J.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})):(this.tracksEnded(),this.hls.trigger(J.BUFFERED_TO_END,void 0)):"video"===e.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(null!==t){const e=this.tracks[t];e&&(e.ending=!1)}})}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,e){if(e.details===Q.BUFFER_APPEND_ERROR&&e.frag){var i;const t=null==(i=e.errorAction)?void 0:i.nextAutoLevel;Y(t)&&t!==e.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:e,media:i}=this;if(!i||null===e)return;if(!this.sourceBufferCount)return;const s=t.config,r=i.currentTime,n=e.levelTargetDuration,a=e.live&&null!==s.liveBackBufferLength?s.liveBackBufferLength:s.backBufferLength;if(Y(a)&&a>=0){const t=Math.max(a,n),e=Math.floor(r/n)*n-t;this.flushBackBuffer(r,n,e)}const o=s.frontBufferFlushThreshold;if(Y(o)&&o>0){const t=Math.max(s.maxBufferLength,o),e=Math.max(t,n),i=Math.floor(r/n)*n+e;this.flushFrontBuffer(r,n,i)}}
vendor: 4,832 bytes, line 1
1flushBackBuffer(t,e,i){this.sourceBuffers.forEach(([t,e])=>{if(e){const r=Gi.getBuffered(e);if(r.length>0&&i>r.start(0)){var s;this.hls.trigger(J.BACK_BUFFER_REACHED,{bufferEnd:i});const e=this.tracks[t];if(null!=(s=this.details)&&s.live)this.hls.trigger(J.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=e&&e.ended)return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(J.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:t})}}})}flushFrontBuffer(t,e,i){this.sourceBuffers.forEach(([e,s])=>{if(s){const r=Gi.getBuffered(s),n=r.length;if(n<2)return;const a=r.start(n-1),o=r.end(n-1);if(i>a||t>=a&&t<=o)return;this.hls.trigger(J.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:e})}})}getDurationAndRange(){var t;const{details:e,mediaSource:i}=this;if(!e||!this.media||"open"!==(null==i?void 0:i.readyState))return null;const s=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&i.setLiveSeekableRange){const t=Math.max(0,e.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,s)}}return{duration:1/0}}const r=null==(t=this.overrides)?void 0:t.duration;if(r)return Y(r)?{duration:r}:null;const n=this.media.duration;return s>(Y(i.duration)?i.duration:0)&&s>n||!Y(n)?{duration:s}:null}updateMediaSource({duration:t,start:e,end:i}){const s=this.mediaSource;this.media&&s&&"open"===s.readyState&&(s.duration!==t&&(Y(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),s.duration=t),void 0!==e&&void 0!==i&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${e}-${i}.`),s.setLiveSeekableRange(e,i)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${Ve(i)}`),this.tracksReady){var s;const t=null==(s=this.transferData)?void 0:s.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([e,i])=>{if(e){const s=this.tracks[e];t[e]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(J.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in t){const n=r,a=t[n];if(this.isPending(a)){const t=this.getTrackCodec(a,n),r=`${a.container};codecs=${t}`;a.codec=t,this.log(`creating sourceBuffer(${r})${this.currentOp(n)?" Queued":""} ${Ve(a)}`);try{const t=i.addSourceBuffer(r),s=la(n),o=[n,t];e[s]=o,a.buffer=t}catch(t){var s;return this.error(`error while trying to add sourceBuffer: ${t.message}`),this.shiftAndExecuteNext(n),null==(s=this.operationQueue)||s.removeBlockers(),delete this.tracks[n],void this.hls.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:n,mimeType:r,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}getTrackCodec(t,e){const i=t.supplemental;let s=t.codec;i&&("video"===e||"audiovideo"===e)&&he(i,"video")&&(s=function(t,e){const i=[];if(t){const e=t.split(",");for(let t=0;t<e.length;t++)ue(e[t],"video")||i.push(e[t])}return e&&i.push(e),i.join(",")}(s,i));const r=Te(s,t.levelCodec);return r?"audio"===e.slice(0,5)?Ee(r,this.appendSource):r:""}trackSourceBuffer(t,e){const i=e.buffer;if(!i)return;const s=this.getTrackCodec(e,t);this.tracks[t]={buffer:i,codec:s,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(t,e)=>{const i=e.removedRanges;null!=i&&i.length&&this.hls.trigger(J.BUFFER_FLUSHED,{type:t})})}get mediaSrc(){var t,e;const i=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==i?void 0:i.src}onSBUpdateStart(t){const e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const i=this.currentOp(t);
1i&&(i.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,e){var i;const s=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${s}`,e),this.hls.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:s,fatal:!1});const r=this.currentOp(t);r&&r.onError(s)}updateTimestampOffset(t,e,i,s,r,n){const a=e-t.timestampOffset;Math.abs(a)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${e} (sn: ${r} cc: ${n})`),t.timestampOffset=e)}removeExecutor(t,e,i){const{media:s,mediaSource:r}=this,n=this.tracks[t],a=null==n?void 0:n.buffer;if(!s||!r||!a)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(t);const o=Y(s.duration)?s.duration:1/0,l=Y(r.duration)?r.duration:1/0,d=Math.max(0,e),c=Math.min(i,o,l);c>d&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${d},${c}] from the ${t} SourceBuffer`),a.remove(d,c)):this.shiftAndExecuteNext(t)}appendExecutor(t,e){const i=this.tracks[e],s=null==i?void 0:i.buffer;if(!s)throw new aa(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,s.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([t,e])=>t&&e.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:i}=this,s=e.map(t=>this.appendBlocker(t));return e.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then(e=>{i===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(t=>{var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;i&&!i.updating&&this.shiftAndExecuteNext(t)})}append(t,e,i){this.operationQueue&&this.operationQueue.append(t,e,i)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,e)=>t+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[e])=>t+(e?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,e,i){const s=this.tracks[t];if(!s)return;const r=s.buffer;if(!r)return;const n=i.bind(this,t);s.listeners.push({event:e,listener:n}),r.addEventListener(e,n)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const i=e.buffer;i&&(e.listeners.forEach(t=>{i.removeEventListener(t.event,t.listener)}),e.listeners.length=0)}},capLevelController:da,errorController:class extends ht{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(J.ERROR,this.onError,this),t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(J.ERROR,this.onError,this),t.off(J.ERROR,this.onErrorOut,this),t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===st?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,i=e.currentLevel;return null!=(t=e.loadLevelObj)&&t.details||-1===i?e.loadLevel:i}variantHasKey(t,e){if(t){var i;if(null!=(i=t.details)&&i.hasKey(e))return!0;const s=t.audioGroups;if(s){return this.hls.allAudioTracks.filter(t=>s.indexOf(t.groupId)>=0).some(t=>{var i;return null==(i=t.details)?void 0:i.hasKey(e)})}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var i;if(e.fatal)return;const s=this.hls,r=e.context;switch(e.details){case Q.FRAG_LOAD_ERROR:case Q.FRAG_LOAD_TIMEOUT:case Q.KEY_LOAD_ERROR:case Q.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case Q.FRAG_PARSING_ERROR:if(null!=(i=e.frag)&&i.gap)return void(e.errorAction=yi());case Q.FRAG_GAP:case Q.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=ui);case Q.LEVEL_EMPTY_ERROR:case Q.LEVEL_PARSING_ERROR:{var n;const t=e.parent===st?e.level:s.loadLevel;e.details===Q.LEVEL_EMPTY_ERROR&&null!=(n=e.context)&&null!=(n=n.levelDetails)&&n.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case Q.LEVEL_LOAD_ERROR:case Q.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.level)));case Q.AUDIO_TRACK_LOAD_ERROR:case Q.AUDIO_TRACK_LOAD_TIMEOUT:case Q.SUBTITLE_LOAD_ERROR:case Q.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const t=s.loadLevelObj;if(t&&(r.type===et&&t.hasAudioGroup(r.groupId)||r.type===it&&t.hasSubtitleGroup(r.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.loadLevel),e.errorAction.action=ui,void(e.errorAction.flags=mi)}return;case Q.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:ui,flags:pi});case Q.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Q.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Q.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:ui,flags:vi});
vendor: 9,549 bytes, line 1
1case Q.BUFFER_ADD_CODEC_ERROR:case Q.REMUX_ALLOC_ERROR:case Q.BUFFER_APPEND_ERROR:var a;if(!e.errorAction)e.errorAction=this.getLevelSwitchAction(e,null!=(a=e.level)?a:s.loadLevel);return;case Q.INTERNAL_EXCEPTION:case Q.BUFFER_APPENDING_ERROR:case Q.BUFFER_FULL_ERROR:case Q.LEVEL_SWITCH_ERROR:case Q.BUFFER_STALLED_ERROR:case Q.BUFFER_SEEK_OVER_HOLE:case Q.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=yi())}e.type===X.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=yi())}getPlaylistRetryOrSwitchAction(t,e){const i=ni(this.hls.config.playlistLoadPolicy,t),s=this.playlistError++;if(li(i,s,ii(t),t.response))return{action:fi,flags:gi,retryConfig:i,retryCount:s};const r=this.getLevelSwitchAction(t,e);return i&&(r.retryConfig=i,r.retryCount=s),r}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),s=e.levels[i],{fragLoadPolicy:r,keyLoadPolicy:n}=e.config,a=ni(si(t)?n:r,t),o=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(s&&(t.details!==Q.FRAG_GAP&&s.fragmentError++,!ri(t))){if(li(a,o,ii(t),t.response))return{action:fi,flags:gi,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(t,i);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(t,e){const i=this.hls;null==e&&(e=i.loadLevel);const s=this.hls.levels[e];if(s){var r,n;const e=t.details;s.loadError++,e===Q.BUFFER_APPEND_ERROR&&s.fragmentError++;let l=-1;const{levels:d,loadLevel:c,minAutoLevel:u,maxAutoLevel:h}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);const f=null==(r=t.frag)?void 0:r.type,g=(f===rt&&e===Q.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===Q.BUFFER_ADD_CODEC_ERROR||e===Q.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:t})=>s.audioCodec!==t),m="video"===t.sourceBufferName&&(e===Q.BUFFER_ADD_CODEC_ERROR||e===Q.BUFFER_APPEND_ERROR)&&d.some(({codecSet:t,audioCodec:e})=>s.codecSet!==t&&s.audioCodec===e),{type:p,groupId:v}=null!=(n=t.context)?n:{};for(let i=d.length;i--;){const r=(i+c)%d.length;if(r!==c&&r>=u&&r<=h&&0===d[r].loadError){var a,o;const i=d[r];if(e===Q.FRAG_GAP&&f===st&&t.frag){const e=d[r].details;if(e){const i=Je(t.frag,e.fragments,t.frag.start);if(null!=i&&i.gap)continue}}else{if(p===et&&i.hasAudioGroup(v)||p===it&&i.hasSubtitleGroup(v))continue;if(f===rt&&null!=(a=s.audioGroups)&&a.some(t=>i.hasAudioGroup(t))||f===nt&&null!=(o=s.subtitleGroups)&&o.some(t=>i.hasSubtitleGroup(t))||g&&s.audioCodec===i.audioCodec||m&&s.codecSet===i.codecSet||!g&&s.codecSet!==i.codecSet)continue}l=r;break}}if(l>-1&&i.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:ui,flags:gi,nextAutoLevel:l}}return{action:ui,flags:mi}}onErrorOut(t,e){var i;switch(null==(i=e.errorAction)?void 0:i.action){case ci:break;case ui:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===Q.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,i=t.errorAction;if(!i)return;const{flags:s}=i,r=i.nextAutoLevel;switch(s){case gi:this.switchLevel(t,r);break;case pi:{const s=this.getVariantLevelIndex(t.frag),r=e.levels[s],n=null==r?void 0:r.attrs["HDCP-LEVEL"];if(i.hdcpLevel=n,"NONE"===n)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(n){e.maxHdcpLevel=xe[xe.indexOf(n)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);break}}case vi:{const e=t.decryptdata;if(e){const s=this.hls.levels,r=s.length;for(let i=r;i--;){var n,a;if(this.variantHasKey(s[i],e))this.log(`Banned key found in level ${i} (${s[i].bitrate}bps) or audio group "${null==(n=s[i].audioGroups)?void 0:n.join(",")}" (${null==(a=t.frag)?void 0:a.type} fragment) ${bt(e.keyId||[])}`),s[i].fragmentError++,s[i].loadError++,this.log(`Removing level ${i} with key error (${t.error})`),this.hls.removeLevel(i)}const o=t.frag;if(this.hls.levels.length<r)i.resolved=!0;else if(o&&o.type!==st){const t=o.decryptdata;t&&!e.matches(t)&&(i.resolved=!0)}}break}}i.resolved||this.switchLevel(t,r)}switchLevel(t,e){if(void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,t.details===Q.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=ke(t.mimeType),i=this.hls.levels;for(let s=i.length;s--;)i[s][`${t.sourceBufferName}Codec`]===e&&(this.log(`Removing level ${s} for ${t.details} ("${e}" not supported)`),this.hls.removeLevel(s))}}},fpsController:class{constructor(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()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(J.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(J.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(J.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(J.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const i=this.hls.config;if(i.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,e,i){const s=performance.now();if(e){if(this.lastTime){const t=s-this.lastTime,r=i-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*r/t,o=this.hls;if(o.trigger(J.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:i}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(J.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:vs,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:wl,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{}
1,{subtitleStreamController:class extends Er{constructor(t,e,i){super(t,e,i,"subtitle-stream-controller",nt),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(J.LEVEL_LOADED,this.onLevelLoaded,this),t.on(J.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(J.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(J.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(J.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(J.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(J.LEVEL_LOADED,this.onLevelLoaded,this),t.off(J.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(J.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(J.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(J.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(J.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,e){this.stopLoad(),this.state=lr,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,e){this.tracksBuffered=[],super.onMediaDetaching(t,e)}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:i,success:s}=e;if(this.fragContextChanged(i)||(Ct(i)&&(this.fragPrevious=i),this.state=lr),!s)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=i.start;for(let t=0;t<r.length;t++)if(a>=r[t].start&&a<=r[t].end){n=r[t];break}const o=i.start+i.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(t,e){const{startOffset:i,endOffset:s}=e;if(0===i&&s!==Number.POSITIVE_INFINITY){const t=s-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach(e=>{for(let i=0;i<e.length;)if(e[i].end<=t)e.shift();else{if(!(e[i].start<t))break;e[i].start=t,i++}}),this.fragmentTracker.removeFragmentsInRange(i,t,nt)}}onError(t,e){const i=e.frag;(null==i?void 0:i.type)===nt&&(e.details===Q.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==or&&(this.state=lr))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&ta(this.levels,e)?this.levels=e.map(t=>new Be(t)):(this.tracksBuffered=[],this.levels=e.map(t=>{const e=new Be(t);return this.tracksBuffered[e.id]=[],e}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,nt),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var i;if(this.currentTrackId=e.id,null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();const s=this.levels[this.currentTrackId];null!=s&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.state!==or&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var i;const{currentTrackId:s,levels:r}=this,{details:n,id:a}=e;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(i=o.details)&&i.live){if(n.deltaUpdateFailed)return;const t=this.mainDetails;if(!t)return void(this.startFragRequested=!1);const e=t.fragments[0];var d;if(o.details)l=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details),0===l&&e&&(l=e.start,js(n,l));else n.hasProgramDateTime&&t.hasProgramDateTime?(sr(n,t),l=n.fragmentStart):e&&(l=e.start,js(n,l));t&&!this.startFragRequested&&this.setStartPosition(t,l)}if(o.details=n,this.levelLastLoaded=o,a===s&&(this.hls.trigger(J.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:e.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===lr)){Je(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(t){const{frag:e,payload:i}=t,s=e.decryptdata,r=this.hls;if(!this.fragContextChanged(e)&&i&&i.byteLength>0&&null!=s&&s.key&&s.iv&&is(s.method)){const t=performance.now();
1this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,ss(s.method)).catch(t=>{throw r.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t}).then(i=>{const s=performance.now();r.trigger(J.FRAG_DECRYPTED,{frag:e,payload:i,stats:{tstart:t,tdecrypt:s}})}).catch(t=>{this.warn(`${t.name}: ${t.message}`),this.state=lr})}}doTick(){if(this.media){if(this.state===lr){const{currentTrackId:t,levels:e}=this,i=null==e?void 0:e[t];if(!i||!e.length||!i.details)return;if(this.waitForLive(i))return;const{config:s}=this,r=this.getLoadPosition(),n=Gi.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,s.maxBufferHole),{end:a,len:o}=n,l=i.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;const d=l.fragments,c=d.length,u=l.edge;let h=null;const f=this.fragPrevious;if(a<u){const t=s.maxFragLookUpTolerance,e=a>u-t?0:t;h=Je(f,d,Math.max(d[0].start,a),e),!h&&f&&f.start<d[0].start&&(h=d[0])}else h=d[c-1];if(h=this.filterReplacedPrimary(h,i.details),!h)return;const g=d[h.sn-l.startSN-1];if(g&&g.cc===h.cc&&this.fragmentTracker.getState(g)===Ei&&(h=g),this.fragmentTracker.getState(h)===Ei){const t=this.mapToInitFragWhenRequired(h);t&&this.loadFragment(t,i,a)}}}else this.state=lr}loadFragment(t,e,i){Ct(t)?super.loadFragment(t,e,i):this._loadInitSegment(t,e)}get mediaBufferTimeRanges(){return new Po(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Zn{constructor(t){super(t,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const e=mo(this.media.textTracks);for(let i=0;i<e.length;i++)if("hidden"===e[i].mode)t=e[i];else if("showing"===e[i].mode){t=e[i];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;
vendor: 1,678 bytes, line 1
1t.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.MANIFEST_PARSED,this.onManifestParsed,this),t.on(J.LEVEL_LOADING,this.onLevelLoading,this),t.on(J.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(J.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(J.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.MANIFEST_PARSED,this.onManifestParsed,this),t.off(J.LEVEL_LOADING,this.onLevelLoading,this),t.off(J.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(J.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(J.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,e){const i=this.media;if(!i)return;const s=!!e.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,s)return;
1mo(i.textTracks).forEach(t=>{fo(t)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:i,groupId:s,details:r}=e,n=this.tracksInGroup[i];if(!n||n.groupId!==s)return void this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.subtitleGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some(t=>-1===(null==s?void 0:s.indexOf(t)))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>!i||-1!==i.indexOf(t.groupId));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.subtitlePreference;if(!r&&e){this.selectDefaultTrack=!1;const i=qe(e,t);if(i>-1)r=t[i];else{const t=qe(e,this.tracks);r=this.tracks[t]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(J.SUBTITLE_TRACKS_UPDATED,n),-1!==s&&-1===this.trackId&&this.setSubtitleTrack(s)}}findTrackId(t){const e=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<e.length;s++){const r=e[s];if((!i||r.default)&&(i||t)&&(!t||Ye(r,t)))return s}if(t){for(let i=0;i<e.length;i++){const s=e[i];if(ea(t.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const s=e[i];if(ea(t.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(t){if(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){if(ia(e[i],t))return i}}return-1}onError(t,e){!e.fatal&&e.context&&(e.context.type!==it||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){if(-1===t.id)return this.setSubtitleTrack(-1),null;const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const i=this.currentTrack;if(i&&Ye(t,i))return i;const s=qe(t,this.tracksInGroup);if(s>-1){const t=this.tracksInGroup[s];return this.setSubtitleTrack(s),t}if(i)return null;{const i=qe(t,e);if(i>-1)return e[i]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,s=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${i} "${t.name}" lang:${t.lang} group:${s}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(J.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:e||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=mo(t.textTracks),i=this.currentTrack;let s;if(i&&(s=e.filter(t=>ia(i,t))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(e).forEach(t=>{"disabled"!==t.mode&&t!==s&&(t.mode="disabled")}),s){const t=this.subtitleDisplay?"showing":"hidden";s.mode!==t&&(s.mode=t)}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=e.length||!Y(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.selectDefaultTrack=!1;const i=this.currentTrack,s=e[t]||null;if(this.trackId=t,this.currentTrack=s,this.toggleTrackModes(),!s)return void this.hls.trigger(J.SUBTITLE_TRACK_SWITCH,{id:t});const r=!!s.details&&!s.details.live;if(t===this.trackId&&s===i&&r)return;this.log(`Switching to subtitle-track ${t}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:d}=s;this.hls.trigger(J.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:d});const c=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(c)}},timelineController:class{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}}
vendor: 4,142 bytes, line 1
1,t.on(J.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(J.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(J.FRAG_LOADING,this.onFragLoading,this),t.on(J.FRAG_LOADED,this.onFragLoaded,this),t.on(J.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(J.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(J.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(J.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(J.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(J.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(J.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(J.FRAG_LOADING,this.onFragLoading,this),t.off(J.FRAG_LOADED,this.onFragLoaded,this),t.off(J.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(J.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(J.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(J.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(J.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new bl(this,"textTrack1"),e=new bl(this,"textTrack2"),i=new bl(this,"textTrack3"),s=new bl(this,"textTrack4");this.cea608Parser1=new Wo(1,t,e),this.cea608Parser2=new Wo(3,i,s)}addCues(t,e,i,s,r){let n=!1;for(let t=r.length;t--;){const s=r[t],a=Ll(s[0],s[1],e,i);if(a>=0&&(s[0]=Math.min(s[0],e),s[1]=Math.max(s[1],i),n=!0,a/(i-e)>.5))return}if(n||r.push([e,i]),this.config.renderTextTracksNatively){const r=this.captionsTracks[t];this.Cues.newCue(r,e,i,s)}else{const r=this.Cues.newCue(null,e,i,s);this.hls.trigger(J.CUES_PARSED,{type:"captions",cues:r,track:t})}}onInitPtsFound(t,{frag:e,id:i,initPTS:s,timescale:r,trackId:n}){const{unparsedVttFrags:a}=this;i===st&&(this.initPTS[e.cc]={baseTime:s,timescale:r,trackId:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(t=>{this.initPTS[t.frag.cc]?this.onFragLoaded(J.FRAG_LOADED,t):this.hls.trigger(J.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(t,e){const{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){const r=i.textTracks[s];if(kl(r,{name:t,lang:e,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:i,media:s}=this,{label:r,languageCode:n}=e[t],a=this.getExistingTrack(r,n);if(a)i[t]=a,fo(i[t]),uo(i[t],s);else{const e=this.createTextTrack("captions",r,n);e&&(e[t]=!0,i[t]=e)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const i={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=i,this.hls.trigger(J.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(t,e,i){const s=this.media;if(s)return s.addTextTrack(t,e,i)}onMediaAttaching(t,e){this.media=e.media,e.mediaSource||this._cleanTracks()}onMediaDetaching(t,e){const i=!!e.transferMedia;if(this.media=null,i)return;const{captionsTracks:s}=this;Object.keys(s).forEach(t=>{fo(s[t]),delete s[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const e=t.textTracks;
1if(e)for(let t=0;t<e.length;t++)fo(e[t])}onSubtitleTracksUpdated(t,e){const i=e.subtitleTracks||[],s=i.some(t=>t.textCodec===ul);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(ta(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const t=this.media,e=t?mo(t.textTracks):null;if(this.tracks.forEach((t,i)=>{let s;if(e){let i=null;for(let s=0;s<e.length;s++)if(e[s]&&kl(e[s],t)){i=e[s],e[s]=null;break}i&&(s=i)}if(s)fo(s);else{const e=Al(t);s=this.createTextTrack(e,t.name,t.lang),s&&(s.mode="disabled")}s&&this.textTracks.push(s)}),null!=e&&e.length){const t=e.filter(t=>null!==t).map(t=>t.label);t.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${t.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const t=this.tracks.map(t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t}));this.hls.trigger(J.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach(t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const i=`textTrack${e[1]}`,s=this.captionsProperties[i];s&&(s.label=t.name,t.lang&&(s.languageCode=t.lang),s.media=t)})}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===st){var i,s;const{cea608Parser1:t,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=e.frag,l=null!=(i=null==(s=e.part)?void 0:s.index)?i:-1;t&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:i,payload:s}=e;if(i.type===nt)if(s.byteLength){const t=i.decryptdata,r="stats"in e;if(null==t||!t.encrypted||r){const t=this.tracks[i.level],r=this.vttCCs;r[i.cc]||(r[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),t&&t.textCodec===ul?this._parseIMSC1(i,s):this._parseVTTs(e)}}else this.hls.trigger(J.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const i=this.hls;ml(e,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),i.trigger(J.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},e=>{i.logger.log(`Failed to parse IMSC1: ${e}`),i.trigger(J.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})})}_parseVTTs(t){var e;const{frag:i,payload:s}=t,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[i.cc]&&-1===a)return void n.push(t);const o=this.hls;cl(null!=(e=i.initSegment)&&e.data?ee(i.initSegment.data,new Uint8Array(s)).buffer:s,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,t=>{this._appendCues(t,i.level),o.trigger(J.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},e=>{const r="Missing initPTS for VTT MPEGTS"===e.message;r?n.push(t):this._fallbackToIMSC1(i,s),o.logger.log(`Failed to parse VTT cue: ${e}`),r&&a>i.cc||o.trigger(J.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:e})})}_fallbackToIMSC1(t,e){const i=this.tracks[t.level];i.textCodec||ml(e,this.initPTS[t.cc],()=>{i.textCodec=ul,this._parseIMSC1(t,e)},()=>{i.textCodec="wvtt"})}_appendCues(t,e){const i=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[e];if(!i||"disabled"===i.mode)return;t.forEach(t=>ho(i,t))}else{const s=this.tracks[e];if(!s)return;const r=s.default?"default":"subtitles"+e;i.trigger(J.CUES_PARSED,{type:"subtitles",cues:t,track:r})}}onFragDecrypted(t,e){const{frag:i}=e;i.type===nt&&this.onFragLoaded(J.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:s}=e;if(i.type!==st||"NONE"!==this.closedCaptionsForLevel(i))for(let t=0;t<s.length;t++){const e=s[t].bytes;if(e){this.cea608Parser1||this.initCea608Parsers();const i=this.extractCea608Data(e);this.cea608Parser1.addData(s[t].pts,i[0]),this.cea608Parser2.addData(s[t].pts,i[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:i,endOffsetSubtitles:s,type:r}){const{media:n}=this;
1if(n&&!(n.currentTime<i)){if(!r||"video"===r){const{captionsTracks:t}=this;Object.keys(t).forEach(s=>go(t[s],e,i))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==s){const{textTracks:t}=this;Object.keys(t).forEach(i=>go(t[i],e,s))}}}extractCea608Data(t){const e=[[],[]],i=31&t[0];let s=2;for(let r=0;r<i;r++){const i=t[s++],r=127&t[s++],n=127&t[s++];if(0===r&&0===n)continue;if(!!(4&i)){const t=3&i;0!==t&&1!==t||(e[t].push(r),e[t].push(n))}}return e}},audioStreamController:class extends Er{constructor(t,e,i){super(t,e,i,"audio-stream-controller",rt),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(J.LEVEL_LOADED,this.onLevelLoaded,this),t.on(J.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(J.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(J.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(J.BUFFER_RESET,this.onBufferReset,this),t.on(J.BUFFER_CREATED,this.onBufferCreated,this),t.on(J.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(J.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(J.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(J.FRAG_LOADING,this.onFragLoading,this),t.on(J.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(J.LEVEL_LOADED,this.onLevelLoaded,this),t.off(J.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(J.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(J.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(J.BUFFER_RESET,this.onBufferReset,this),t.off(J.BUFFER_CREATED,this.onBufferCreated,this),t.off(J.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(J.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(J.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(J.FRAG_LOADING,this.onFragLoading,this),t.off(J.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:e,id:i,initPTS:s,timescale:r,trackId:n}){if(i===st){const t=e.cc,i=this.fragCurrent;if(this.initPTS[t]={baseTime:s,timescale:r,trackId:n},this.log(`InitPTS for cc: ${t} found from main: ${s/r} (${s}/${r}) trackId: ${n}`),this.mainAnchor=e,this.state===vr){const i=this.waitingData;(!i&&!this.loadingParts||i&&i.frag.cc!==t)&&this.syncWithAnchor(e,null==i?void 0:i.frag)}else!this.hls.hasEnoughToStart&&i&&i.cc!==t?(i.abortRequests(),this.syncWithAnchor(e,i)):this.state===lr&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,e){var i;const s=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(e&&(null==s?void 0:s.cc)===e.cc)return;const r=(s||t).cc,n=ei(this.getLevelDetails(),r,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===lr&&this.doTickIdle())}startLoad(t,e){if(!this.levels)return this.startPosition=t,void(this.state=or);const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i,this.state=lr):this.state=hr,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}doTick(){switch(this.state){case lr:this.doTickIdle();break;case hr:{const{levels:t,trackId:e}=this,i=null==t?void 0:t[e],s=null==i?void 0:i.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=vr}break}case ur:this.checkRetryDate();break;case vr:{const t=this.waitingData;if(t){const{frag:e,part:i,cache:s,complete:r}=t,n=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=cr;const t={frag:e,part:i,payload:s.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),r&&super._handleFragmentLoadComplete(t)}else n&&n.cc!==t.frag.cc&&this.syncWithAnchor(n,t.frag)}else this.state=lr}}this.onTickEnd()}
1resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls:e,levels:i,media:s,trackId:r}=this,n=e.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==i||!i[r])return;const a=i[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=hr,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,_t,rt));const d=this.getFwdBufferInfo(l,rt);if(null===d)return;if(!this.switchingTrack&&this._streamEnded(d,o))return e.trigger(J.BUFFER_EOS,{type:"audio"}),void(this.state=mr);const c=d.len,u=e.maxBufferLength,h=o.fragments,f=h[0].start,g=this.getLoadPosition(),m=this.flushing?g:d.end;if(this.switchingTrack&&s){const t=g;o.PTSKnown&&t<f&&(d.end>f||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=f+.05)}if(c>=u&&!this.switchingTrack&&m<h[h.length-1].start)return;let p=this.getNextFragment(m,o);if(p&&this.isLoopLoading(p,m)&&(p=this.getNextFragmentLoopLoading(p,o,d,st,u)),!p)return void(this.bufferFlushed=!0);if(this.exceedsMaxBuffer(d,u,p))return;let v=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&Ct(p)&&!p.endList&&(!o.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===bi&&(this.mainFragLoading=v=null),v&&Ct(v))){if(p.start>v.end){const t=this.fragmentTracker.getFragAtPos(m,st);t&&t.end>v.end&&(v=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(p.start>v.end)return}this.loadFragment(p,a,m)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(t=>new Be(t))}onAudioTrackSwitching(t,e){const i=!!e.url;this.trackId=e.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?(this.switchingTrack=e,this.flushAudioIfNeeded(e),this.state!==or&&(this.setInterval(100),this.state=lr,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=e,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,e){this.mainDetails=e.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(J.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(t,e){var i;const{levels:s}=this,{details:r,id:n,groupId:a,track:o}=e;if(!s)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=e,void(this.state!==or&&(this.state=hr));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const d=s[n];let c=0;if(r.live||null!=(i=d.details)&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var u;if(d.details)c=this.alignPlaylists(r,d.details,null==(u=this.levelLastLoaded)?void 0:u.details);r.alignedSliding||(ir(r,l),r.alignedSliding||sr(r,l),c=r.fragmentStart)}d.details=r,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(J.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:e.groupId}),this.state!==hr||this.waitForCdnTuneIn(r)||(this.state=lr),this.tick()}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:r}=t,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const d=l.details;if(!d)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const c=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new Jn(this.hls,rt,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const h=this.initPTS[i.cc],f=null==(e=i.initSegment)?void 0:e.data;if(void 0!==h){const t=!1,e=s?s.index:-1,n=-1!==e,a=new Bi(i.level,i.sn,i.stats.chunkCount,r.byteLength,e,n);u.push(r,f,c,"",i,s,d.totalduration,t,a,h)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Sr,complete:!1};t.push(new Uint8Array(r)),this.state!==or&&(this.state=vr)}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,e){this.bufferFlushed=this.flushing=!1;const i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===st&&Ct(e.frag)&&(this.mainFragLoading=e,this.state===lr&&this.tick())}onFragBuffered(t,e){const{frag:i,part:s}=e;if(i.type===rt)if(this.fragContextChanged(i))this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(Ct(i)){this.fragPrevious=i;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(J.AUDIO_TRACK_SWITCHED,ut({},t)))}this.fragBufferedComplete(i,s),this.media&&this.tick()}else this.audioOnly||i.type!==st||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(t,e){var i;if(e.fatal)this.state=pr;else switch(e.details){case Q.FRAG_GAP:case Q.FRAG_PARSING_ERROR:case Q.FRAG_DECRYPT_ERROR:case Q.FRAG_LOAD_ERROR:case Q.FRAG_LOAD_TIMEOUT:case Q.KEY_LOAD_ERROR:case Q.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(rt,e);break;case Q.AUDIO_TRACK_LOAD_ERROR:case Q.AUDIO_TRACK_LOAD_TIMEOUT:case Q.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==hr||(null==(i=e.context)?void 0:i.type)!==et||(this.state=lr);break;case Q.BUFFER_ADD_CODEC_ERROR:case Q.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case Q.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Q.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==Dt&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==Dt){this.flushing=!1,this.bufferFlushed=!0,this.state===mr&&(this.state=lr);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,rt),this.tick())}}_handleTransmuxComplete(t){var e;const i="audio",{hls:s}=this,{remuxResult:r,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:d}=a,{details:c}=d,{audio:u,text:h,id3:f,initSegment:g}=r;if(!this.fragContextChanged(o)&&c){if(this.state=fr,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const t=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(d,g.tracks,t,n),s.trigger(J.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:i,tracks:g.tracks})}if(u){const{startPTS:t,endPTS:e,startDTS:i,endDTS:s}=u;l&&(l.elementaryStreams[_t]={startPTS:t,endPTS:e,startDTS:i,endDTS:s}),o.setElementaryStreamInfo(_t,t,e,i,s),this.bufferFragmentData(u,o,l,n)}if(null!=f&&null!=(e=f.samples)&&e.length){const t=dt({id:i,frag:o,details:c},f);s.trigger(J.FRAG_PARSING_METADATA,t)}if(h){const t=dt({id:i,frag:o,details:c},h);s.trigger(J.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,e,i,s){if(this.state!==fr)return;if(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio)return;const r=e.audio;r.id=rt;const n=t.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&1===n.split(",").length&&(r.levelCodec=n),this.hls.trigger(J.BUFFER_CODECS,e);const a=r.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:a};this.hls.trigger(J.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);var r;if(this.switchingTrack||s===Ei||s===Si)if(Ct(t))if(null!=(r=e.details)&&r.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=vr;const i=this.mainDetails;i&&i.fragmentStart!==e.details.fragmentStart&&sr(e.details,i)}else super.loadFragment(t,e,i);else this._loadInitSegment(t,e);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:e,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;Ye({name:e,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a},t,We)||(Xe(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(J.AUDIO_TRACK_SWITCHED,ut({},t))}},audioTrackController:class extends Zn{constructor(t){super(t,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.MANIFEST_PARSED,this.onManifestParsed,this),t.on(J.LEVEL_LOADING,this.onLevelLoading,this),t.on(J.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(J.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(J.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.MANIFEST_PARSED,this.onManifestParsed,this),t.off(J.LEVEL_LOADING,this.onLevelLoading,this),t.off(J.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(J.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(J.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:i,groupId:s,details:r}=e,n=this.tracksInGroup[i];if(!n||n.groupId!==s)return void this.warn(`Audio track with id:${i} and group:${s} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.audioGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some(t=>-1===(null==s?void 0:s.indexOf(t)))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>!i||-1!==i.indexOf(t.groupId));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!r&&e){const i=qe(e,t,We);if(i>-1)r=t[i];else{const t=qe(e,this.tracks);r=this.tracks[t]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null));const a={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(J.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==s&&-1===o)this.setAudioTrack(s);else if(t.length&&-1===o){var n;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}}onError(t,e){!e.fatal&&e.context&&(e.context.type!==et||e.context.
1id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&Ye(t,s,We))return s;const r=qe(t,this.tracksInGroup,We);if(r>-1){const t=this.tracksInGroup[r];return this.setAudioTrack(r),t}if(s){let s=e.loadLevel;-1===s&&(s=e.firstAutoLevel);const r=function(t,e,i,s,r){const n=e[s],a=e.reduce((t,e,i)=>{const s=e.uri;return(t[s]||(t[s]=[])).push(i),t},{})[n.uri];a.length>1&&(s=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,d=n.codecSet.substring(0,4),c=ze(e,s,e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==d)return!1;const s=e.audioGroups,n=i.filter(t=>!s||-1!==s.indexOf(t.groupId));return qe(t,n,r)>-1});return c>-1?c:ze(e,s,e=>{const s=e.audioGroups,n=i.filter(t=>!s||-1!==s.indexOf(t.groupId));return qe(t,n,r)>-1})}(t,e.levels,i,s,We);if(-1===r)return null;e.nextLoadLevel=r}if(t.channels||t.audioCodec){const e=qe(t,i);if(e>-1)return i[e]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn(`Invalid audio track id: ${t}`);this.selectDefaultTrack=!1;const i=this.currentTrack,s=e[t],r=s.details&&!s.details.live;if(t===this.trackId&&s===i&&r)return;if(this.log(`Switching to audio-track ${t} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=t,this.currentTrack=s,this.hls.trigger(J.AUDIO_TRACK_SWITCHING,ut({},s)),r)return;const n=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(n)}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const s=e[i];if((!this.selectDefaultTrack||s.default)&&(!t||Ye(t,s,We)))return i}if(t){const{name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(Ye({name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},e[t],We))return t}for(let i=0;i<e.length;i++){const s=e[i];if(ea(t.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const s=e[i];if(ea(t.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&Xe(e.url,this.hls)&&this.scheduleLoading(e,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,s=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${i} "${t.name}" lang:${t.lang} group:${s}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(J.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:e||null,track:t})}},emeController:no,cmcdController:class{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=t=>{try{this.apply(t,{ot:ca.MANIFEST,su:!this.initialized})}catch(t){this.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const{frag:e,part:i}=t,s=this.hls.levels[e.level],r=this.getObjectType(e),n={d:1e3*(i||e).duration,ot:r};r!==ca.VIDEO&&r!==ca.AUDIO&&r!=ca.MUXED||(n.br=s.bitrate/1e3,n.tb=this.getTopBandwidth(r)/1e3,n.bl=this.getBufferLength(r));const a=i?this.getNextPart(i):this.getNextFrag(e);null!=a&&a.url&&a.url!==e.url&&(n.nor=a.url),this.apply(t,n)}catch(t){this.hls.logger.warn("Could not generate segment CMCD data.",t)}},this.hls=t;const e=this.config=t.config,{cmcd:i}=e;null!=i&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||t.sessionId,this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;
1t.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(J.MEDIA_DETACHED,this.onMediaDetached,this),t.on(J.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(J.MEDIA_DETACHED,this.onMediaDetached,this),t.off(J.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,e){var i,s;this.audioBuffer=null==(i=e.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(s=e.tracks.video)?void 0:s.buffer}createData(){var t;return{v:1,sf:ua.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){dt(e,this.createData());const i=e.ot===ca.INIT||e.ot===ca.VIDEO||e.ot===ca.MUXED;this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:s}=this;s&&(e=Object.keys(e).reduce((t,i)=>(s.includes(i)&&(t[i]=e[i]),t),{}));const r={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),Za(t.headers,e,r)):t.url=io(t.url,e,r)}getNextFrag(t){var e;const i=null==(e=this.hls.levels[t.level])?void 0:e.details;if(i){const e=t.sn-i.startSN;return i.fragments[e+1]}}getNextPart(t){var e;const{index:i,fragment:s}=t,r=null==(e=this.hls.levels[s.level])||null==(e=e.details)?void 0:e.partList;if(r){const{sn:t}=s;for(let e=r.length-1;e>=0;e--){const s=r[e];if(s.index===i&&s.fragment.sn===t)return r[e+1]}}}getObjectType(t){const{type:e}=t;return"subtitle"===e?ca.TIMED_TEXT:"initSegment"===t.sn?ca.INIT:"audio"===e?ca.AUDIO:"main"===e?this.hls.audioTracks.length?ca.VIDEO:ca.MUXED:void 0}getTopBandwidth(t){let e,i=0;const s=this.hls;if(t===ca.AUDIO)e=s.audioTracks;else{const t=s.maxAutoLevel,i=t>-1?t+1:s.levels.length;e=s.levels.slice(0,i)}return e.forEach(t=>{t.bitrate>i&&(i=t.bitrate)}),i>0?i:NaN}getBufferLength(t){const e=this.media,i=t===ca.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!e)return NaN;return 1e3*Gi.bufferInfo(i,e.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,s){e(t),this.loader.load(t,i,s)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,s){e(t),this.loader.load(t,i,s)}}}},contentSteeringController:class extends ht{constructor(t){super("content-steering",t.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(J.MANIFEST_PARSED,this.onManifestParsed,this),t.on(J.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(J.MANIFEST_PARSED,this.onManifestParsed,this),t.off(J.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}
vendor: 2,299 bytes, line 1
1startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter(e=>e!==t))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:i}=e;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:i}=e;if((null==i?void 0:i.action)===ui&&i.flags===mi){const t=this.levels;let s=this._pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:i,pathwayId:s,type:n}=e.context;i&&t?r=this.getPathwayForGroupId(i,n,r):s&&(r=s)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!s&&t&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==r),e.details!==Q.BUFFER_APPEND_ERROR||e.fatal?i.resolved||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${t?t.length:t} priorities: ${Ve(s)} penalized: ${Ve(this.penalizedPathways)}`):i.resolved=!0}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const i=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),e=this.getLevelsForPathway(i),this.pathwayId=i}return e.length!==t.length&&this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){let e;this._pathwayPriority=t;const i=this.penalizedPathways,s=performance.now();
1Object.keys(i).forEach(t=>{s-i[t]>3e5&&delete i[t]});for(let s=0;s<t.length;s++){const r=t[s];if(r in i)continue;if(r===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(e=this.getLevelsForPathway(r),e.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,Xs(e),this.hls.trigger(J.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];a&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<s.length;i++)if(e===et&&s[i].hasAudioGroup(t)||e===it&&s[i].hasSubtitleGroup(t))return s[i].pathwayId;return i}clonePathways(t){const e=this.levels;if(!e)return;const i={},s={};t.forEach(t=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some(t=>t.pathwayId===r))return;const o=this.getLevelsForPathway(n).map(t=>{const e=new zi(t.attrs);e["PATHWAY-ID"]=r;const n=e.AUDIO&&`${e.AUDIO}_clone_${r}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${r}`;n&&(i[e.AUDIO]=n,e.AUDIO=n),o&&(s[e.SUBTITLES]=o,e.SUBTITLES=o);const l=ro(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new Be({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e<t.audioGroups.length;e++)d.addGroupId("audio",`${t.audioGroups[e]}_clone_${r}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)d.addGroupId("text",`${t.subtitleGroups[e]}_clone_${r}`);return d});e.push(...o),so(this.audioTracks,i,a,r),so(this.subtitleTracks,s,a,r)})}loadSteeringManifest(t){const e=this.hls.config,i=e.loader;let s;this.loader&&this.loader.destroy(),this.loader=new i(e);try{s=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==s.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+t)}const r={responseType:"json",url:s.href},n=e.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(t,e,i,r)=>{this.log(`Loaded steering manifest: "${s}"`);const n=t.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,s).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||i.url),o&&this.clonePathways(o);const d={steeringManifest:n,url:s.toString()};this.hls.trigger(J.STEERING_MANIFEST_LOADED,d),l&&this.updatePathwayPriority(l)},onError:(t,e,i,s)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let r=1e3*this.timeToLoad;if(429===t.code){const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(r=1e3*parseFloat(e))}return void this.log(`Steering manifest ${e.url} rate limited`)}this.scheduleRefresh(this.uri||e.url,r)},onTimeout:(t,e,i)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var e;const i=null==(e=this.hls)?void 0:e.media;!i||i.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)},e)}},interstitialsController:class extends ht{constructor(t,e){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1}
1,this.onSeeking=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled||!this.schedule)return;const e=t-this.timelinePos;if(Math.abs(e)<1/7056e5)return;const i=e<=-.01;-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),this.timelinePos=t,this.bufferedPos=t;const s=this.playingItem;if(!s)return void this.checkBuffer();if(i){this.schedule.resetErrorsInRange(t,t-e)&&this.updateSchedule(!0)}if(this.checkBuffer(),i&&t<s.start||t>=s.end){var r;const e=this.findItemIndex(s);let n=this.schedule.findItemIndexAtTime(t);if(-1===n&&(n=e+(i?-1:1),this.log(`seeked ${i?"back ":""}to position not covered by schedule ${t} (resolving from ${e} to ${n})`)),!this.isInterstitial(s)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!i&&n>e){const t=this.schedule.findJumpRestrictedIndex(e+1,n);if(t>e)return void this.setSchedulePosition(t)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(s)){const e=s.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(t,e))}return}const a=n.timelineStart,o=n.duration||0;var l;(i&&t<a||t>=a+o)&&(null!=(l=s.event)&&l.appendInPlace&&(this.clearAssetPlayers(s.event,s),this.flushFrontBuffer(t)),this.setScheduleToAssetAtTime(t,n))},this.onTimeupdate=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;if(-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),!(t>this.timelinePos))return;this.timelinePos=t,t>this.bufferedPos&&this.checkBuffer();const e=this.playingItem;if(!e||this.playingLastItem)return;if(t>=e.end){this.timelinePos=e.end;const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}const i=this.playingAsset;if(!i)return;t>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(t,i)},this.onScheduleUpdate=(t,e)=>{const i=this.schedule;if(!i)return;const s=this.playingItem,r=i.events||[],n=i.items||[],a=i.durations,o=t.map(t=>t.identifier),l=!(!r.length&&!o.length);(l||e)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map(t=>wo(t))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let d=null,c=null;s&&(d=this.updateItem(s,this.timelinePos),this.itemsMatch(s,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const u=this.bufferingItem;if(u&&(c=this.updateItem(u,this.bufferedPos),this.itemsMatch(u,c)?this.bufferingItem=c:u.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(u.event,null))),t.forEach(t=>{t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,null)})}),this.playerQueue.forEach(t=>{if(t.interstitial.appendInPlace){const e=t.assetItem.timelineStart,i=t.timelineOffset-e;if(i)try{t.timelineOffset=e}catch(s){Math.abs(i)>vo&&this.warn(`${s} ("${t.assetId}" ${t.timelineOffset}->${e})`)}}}),l||e){if(this.hls.trigger(J.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(s)&&o.includes(s.event.identifier))return this.warn(`Interstitial "${s.event.identifier}" removed while playing`),void this.primaryFallback(s.event);s&&this.trimInPlace(d,s),u&&c!==d&&this.trimInPlace(c,u),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new Ro(t),this.schedule=new Io(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;
1t&&(t.on(J.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(J.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(J.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(J.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(J.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(J.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(J.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(J.BUFFER_APPENDED,this.onBufferAppended,this),t.on(J.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(J.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(J.MEDIA_ENDED,this.onMediaEnded,this),t.on(J.ERROR,this.onError,this),t.on(J.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(J.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(J.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(J.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(J.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(J.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(J.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(J.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(J.BUFFER_CODECS,this.onBufferCodecs,this),t.off(J.BUFFER_APPENDED,this.onBufferAppended,this),t.off(J.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(J.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(J.MEDIA_ENDED,this.onMediaEnded,this),t.off(J.ERROR,this.onError,this),t.off(J.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;null==(t=this.getBufferingPlayer())||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.getBufferingPlayer())||t.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){nr(t,"play",this.onPlay),nr(t,"pause",this.onPause),nr(t,"seeking",this.onSeeking),nr(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const i=this.media=e.media;rr(i,"seeking",this.onSeeking),rr(i,"timeupdate",this.onTimeupdate),rr(i,"play",this.onPlay),rr(i,"pause",this.onPause)}onMediaAttached(t,e){const i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!s){this.clearScheduleState();const t=this.findItemIndex(i);this.setSchedulePosition(t)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){const i=!!e.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){const t=this.getBufferingPlayer();t&&(this.log(`Removing schedule state for detachedData and ${t}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,e=()=>t.bufferingItem||t.waitingItem,i=e=>e?t.getAssetPlayer(e.identifier):e,s=(e,s,n,a,o)=>{if(e){let l=e[s].start;const d=e.event;if(d){if("playout"===s||d.timelineOccupancy!==yo.Point){const t=i(n);(null==t?void 0:t.interstitial)===d&&(l+=t.assetItem.startOffset+t[o])}}else{l+=("bufferedPos"===a?r():t[a])-e.start}return l}return 0},r=()=>{const e=t.bufferedPos;return e===Number.MAX_VALUE?n("primary"):Math.max(e,0)},n=e=>{var i,s;return null!=(i=t.primaryDetails)&&i.live?t.primaryDetails.edge:(null==(s=t.schedule)?void 0:s.durations[e])||0},a=(e,r)=>{var n,a;const o=t.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!t.schedule)return;t.log(`seek to ${e} "${r}"`);const l=t.effectivePlayingItem,d=t.schedule.findItemIndexAtTime(e,r),c=null==(a=t.schedule.items)?void 0:a[d],u=t.getBuffer
1ingPlayer(),h=null==u?void 0:u.interstitial,f=null==h?void 0:h.appendInPlace,g=l&&t.itemsMatch(l,c);if(l&&(f||g)){const n=i(t.playingAsset),a=(null==n?void 0:n.media)||t.primaryMedia;if(a){const i="primary"===r?a.currentTime:s(l,r,t.playingAsset,"timelinePos","currentTime"),o=e-i,d=(f?i:a.currentTime)+o;if(d>=0&&(!n||f||d<=n.duration))return void(a.currentTime=d)}}if(c){let i=e;if("primary"!==r){const t=e-c[r].start;i=c.start+t}const s=!t.isInterstitial(c);if(t.isInterstitial(l)&&!l.event.appendInPlace||!s&&!c.event.appendInPlace){if(l){const n=t.findItemIndex(l);if(d>n){const e=t.schedule.findJumpRestrictedIndex(n+1,d);if(e>n)return void t.setSchedulePosition(e)}let a=0;if(s)t.timelinePos=i,t.checkBuffer();else{const t=c.event.assetList,i=e-(c[r]||c).start;for(let e=t.length;e--;){const s=t[e];if(s.duration&&i>=s.startOffset&&i<s.startOffset+s.duration){a=e;break}}}t.setSchedulePosition(d,a)}}else{const e=t.media||(f?null==u?void 0:u.media:null);e&&(e.currentTime=i)}}},o=()=>{const i=t.effectivePlayingItem;if(t.isInterstitial(i))return i;const s=e();return t.isInterstitial(s)?s:null},l={get bufferedEnd(){const i=e(),r=t.bufferingItem;var n;return r&&r===i&&(s(r,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(n=t.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const e=o(),i=t.effectivePlayingItem;return i&&i===e?s(i,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(e){const i=o(),s=t.effectivePlayingItem;s&&s===i&&a(e+s.playout.start,"playout")},get duration(){const t=o();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var e;const i=null==(e=o())?void 0:e.event.assetList;return i?i.map(e=>t.getAssetPlayer(e.identifier)):[]},get playingIndex(){var e;const i=null==(e=o())?void 0:e.event;return i&&t.effectivePlayingAsset?i.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var e;return(null==(e=t.schedule)||null==(e=e.events)?void 0:e.slice(0))||[]},get schedule(){var e;return(null==(e=t.schedule)||null==(e=e.items)?void 0:e.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const i=e();return t.findItemIndex(i)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const e=t.effectivePlayingItem;return t.findItemIndex(e)},primary:{get bufferedEnd(){return r()},get currentTime(){const e=t.timelinePos;return e>0?e:0},set currentTime(t){a(t,"primary")},get duration(){return n("primary")},get seekableStart(){var e;return(null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0}},integrated:{get bufferedEnd(){return s(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){a(t,"integrated")},get duration(){return n("integrated")},get seekableStart(){var e;return((e,i)=>{var s;if(0!==e&&"primary"!==i&&null!=(s=t.schedule)&&s.length){var r;const s=t.schedule.findItemIndexAtTime(e),n=null==(r=t.schedule.items)?void 0:r[s];if(n)return e+(n[i].start-n.start)}return e})((null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0,"integrated")}},skip:()=>{const e=t.effectivePlayingItem,i=null==e?void 0:e.event;if(i&&!i.restrictions.skip){const s=t.findItemIndex(e);if(i.appendInPlace){const t=e.playout.start+e.event.duration;a(t+.001,"playout")}else t.advanceAfterAssetEnded(i,s,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const e=this.playingItem,i=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&e&&i)&&this.findItemIndex(e)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,e;if(null===this.mediaSelection)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let s=this.media;!s&&null!=(t=this.bufferingItem)&&null!=(t=t.event)&&t.appendInPlace&&(s=this.primaryMedia);const r=null==(e=s)?void 0:e.currentTime;
1return void 0!==r&&Y(r)?r:void 0}get primaryMedia(){var t;return this.media||(null==(t=this.detachedData)?void 0:t.media)||null}isInterstitial(t){return!(null==t||!t.event)}retreiveMediaSource(t,e){const i=this.getAssetPlayer(t);i&&this.transferMediaFromPlayer(i,e)}transferMediaFromPlayer(t,e){const i=t.interstitial.appendInPlace,s=t.media;if(i&&s===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&s)return void(this.detachedData={media:s});const i=t.transferMedia();this.log(`transfer MediaSource from ${t} ${Ve(i)}`),this.detachedData=i}else e&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(t,e){var i,s;if(t.media===e)return;let r=null;const n=this.hls,a=t!==n,o=a&&t.interstitial.appendInPlace,l=null==(i=this.detachedData)?void 0:i.mediaSource;let d;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),d="Primary";else if(l){const t=this.getBufferingPlayer();t?(r=t.transferMedia(),d=`${t}`):d="detached MediaSource"}else d="detached media";if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${Ve(r)}`);else if(!this.detachedData||n.media===e){const t=this.playerQueue;t.length>1&&t.forEach(t=>{if(a&&t.interstitial.appendInPlace!==o){const e=t.interstitial;this.clearInterstitial(t.interstitial,null),e.appendInPlace=!1,e.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${e}`)}}),this.hls.detachMedia(),this.detachedData={media:e}}const c=r&&"mediaSource"in r&&"closed"!==(null==(s=r.mediaSource)?void 0:s.readyState),u=c&&r?r:e;this.log(`${c?"transfering MediaSource":"attaching media"} to ${a?t:"Primary"} from ${d} (media.currentTime: ${e.currentTime})`);const h=this.schedule;if(u===r&&h){const e=a&&t.assetId===h.assetIdAtEnd;u.overrides={duration:h.duration,endOfStream:!a||e,cueRemoval:!a}}t.attachMedia(u)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,e=null==t?void 0:t.events;if(!e||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const i=this.timelinePos,s=this.effectivePlayingItem;if(-1===i){const i=this.hls.startPosition;if(this.timelinePos=i,0===e.length)this.setSchedulePosition(0);else if(e[0].cue.pre){this.log(Do("checkStart (preroll)",i));const s=t.findEventIndex(e[0].identifier);this.setSchedulePosition(s)}else if(i>=0||!this.primaryLive){this.log(Do("checkStart",i));const e=this.timelinePos=i>0?i:0,s=t.findItemIndexAtTime(e);this.setSchedulePosition(s)}else 0===this.hls.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(s&&!this.playingItem){this.log(Do("checkStart (playing item)",s.start));const e=t.findItemIndex(s);this.setSchedulePosition(e)}}advanceAssetBuffering(t,e){const i=t.event,s=i.findAssetIndex(e),r=Ao(i,s);if(i.isAssetPastPlayoutLimit(r)){if(this.schedule){var n;const e=null==(n=this.schedule.items)?void 0:n[this.findItemIndex(t)+1];e&&this.bufferedToItem(e)}}else this.bufferedToEvent(t,r)}advanceAfterAssetEnded(t,e,i){const s=Ao(t,i);if(t.isAssetPastPlayoutLimit(s)){if(this.schedule){const i=this.schedule.items;if(i){const s=e+1;if(s>=i.length)return void this.setSchedulePosition(-1);const r=t.resumeTime;this.timelinePos<r&&(this.log(Do("advanceAfterAssetEnded",r)),this.timelinePos=r,t.appendInPlace&&this.advanceInPlace(r),this.checkBuffer(this.bufferedPos<r)),this.setSchedulePosition(s)}}}else{if(t.appendInPlace){const e=t.assetList[s];e&&this.advanceInPlace(e.timelineStart)}this.setSchedulePosition(e,s)}}setScheduleToAssetAtTime(t,e){const i=this.schedule;if(!i)return;const s=e.parentIdentifier,r=i.getEvent(s);if(r){const e=i.findEventIndex(s),n=i.findAssetIndex(r,t);this.advanceAfterAssetEnded(r,e,n-1)}}setSchedulePosition(t,e){var i;const s=null==(i=this.schedule)?void 0:i.items;if(!s||this.playbackDisabled)return;const r=t>=0?s[t]:null;this.log(`setSchedulePosition ${t}, ${e} (${r?wo(r):r}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const i=n.event,d=this.playingAsset,c=null==d?void 0:d.identifier,u=c?this.getAssetPlayer(c):null;if(u&&c&&(!this.eventItemsMatch(n,r)||void 0!==e&&c!==i.assetList[e].identifier)){var o;const e=i.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${e+1}/${i.assetList.length} ${ko(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(J.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:e,event:i,schedule:s.slice(0),scheduleIndex:t,player:u}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),e));this.retreiveMediaSource(c,r),!u.media||null!=(o=this.detachedData)&&o.mediaSource||u.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${wo(n)}`),i.hasPlayed=!0,this.hls.trigger(J.INTERSTITIAL_ENDED,{event:i,schedule:s.slice(0),scheduleIndex:t}),i.cue.once)){var l;this.updateSchedule();const t=null==(l=this.schedule)?void 0:l.items;if(r&&t){const i=this.findItemIndex(r);this.advanceSchedule(i,t,e,n,a)}return}}this.advanceSchedule(t,s,e,n,a)}advanceSchedule(t,e,i,s,r){const n=this.schedule;if(!n)return;const a=e[t]||null,o=this.primaryMedia,l=this.playerQueue;
1if(l.length&&l.forEach(e=>{const i=e.interstitial,s=n.findEventIndex(i.identifier);(s<t||s>t+1)&&this.clearInterstitial(i,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const r=a.event;if(void 0===i){const e=Ao(r,(i=n.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(e)||r.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(r,t,i);i=e}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let d=this.preloadAssets(r,i);if(this.eventItemsMatch(a,l||s)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${wo(a)} ${r.appendInPlace?"append in place":""}`),this.hls.trigger(J.INTERSTITIAL_STARTED,{event:r,schedule:e.slice(0),scheduleIndex:t})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const c=r.assetList[i];if(!c)return void this.advanceAfterAssetEnded(r,t,i||0);if(d||(d=this.getAssetPlayer(c.identifier)),null===d||d.destroyed){const t=r.assetList.length;this.warn(`asset ${i+1}/${t} player destroyed ${r}`),d=this.createAssetPlayer(r,c,i),d.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(d,i,e,t,o),this.shouldPlay&&_o(d.media)}else a?(this.resumePrimary(a,t,s),this.shouldPlay&&_o(this.hls.media)):r&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var t;return null==(t=this.mediaSelection)?void 0:t.main.details}get primaryLive(){var t;return!(null==(t=this.primaryDetails)||!t.live)}resumePrimary(t,e,i){var s,r;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${wo(t)}`),null==(s=this.detachedData)||!s.mediaSource){let i=this.timelinePos;(i<t.start||i>=t.end)&&(i=this.getPrimaryResumption(t,e),this.log(Do("resumePrimary",i)),this.timelinePos=i),this.attachPrimary(i,t)}if(!i)return;const n=null==(r=this.schedule)?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${wo(t)}`),this.hls.trigger(J.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:e}),this.checkBuffer())}getPrimaryResumption(t,e){const i=t.start;if(this.primaryLive){const t=this.primaryDetails;if(0===e)return this.hls.startPosition;if(t&&(i<t.fragmentStart||i>t.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(t){const e=this.getAssetPlayer(t.identifier);if(null!=e&&e.hls)return e.hls.bufferedToEnd;return Gi.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,i){e?this.setBufferingItem(e):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const s=this.primaryMedia;if(!s)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,s),i&&this.startLoadingPrimaryAt(t,i)),i||(this.log(Do("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,i))}startLoadingPrimaryAt(t,e){var i;const s=this.hls;!s.loadingEnabled||!s.media||Math.abs(((null==(i=s.mainForwardBufferInfo)?void 0:i.start)||s.media.currentTime)-t)>.5?s.startLoad(t,e):s.bufferingEnabled||s.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),null==(t=this.schedule)||t.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(J.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(J.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(-1===e.level||!this.schedule)return;const i=this.hls.levels[e.level];if(!i.details)return;const s=ut(ut({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s,this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(t,e){const i=this.hls.audioTracks[e.id],s=this.mediaSelection;if(!s)return void(this.altSelection=ut(ut({},this.altSelection),{},{audio:i}));const r=ut(ut({},s),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(t,e){const i=this.hls.subtitleTracks[e.id],s=this.mediaSelection;if(!s)return void(this.altSelection=ut(ut({},this.altSelection),{},{subtitles:i}));const r=ut(ut({},s),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(t,e){const i=je(e);this.playerQueue.forEach(({hls:t})=>
1t&&(t.setAudioOption(e)||t.setAudioOption(i)))}onSubtitleTrackSwitch(t,e){const i=je(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setSubtitleOption(e)||-1!==e.id&&t.setSubtitleOption(i)))}onBufferCodecs(t,e){const i=e.tracks;i&&(this.requiredTracks=i)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const t=this.timelinePos;this.bufferedPos=t,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;const e=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&e){for(let t=0;t<e.length;t++){const s=e[t];if(s.cue.post){var i;const t=this.schedule.findEventIndex(s.identifier),e=null==(i=this.schedule.items)?void 0:i[t];this.isInterstitial(e)&&this.eventItemsMatch(e,this.bufferingItem)&&this.bufferedToItem(e,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(t){const e=this.playingItem;if(!this.playingLastItem&&e){const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}else this.shouldPlay=!1}updateItem(t,e){var i;const s=null==(i=this.schedule)?void 0:i.items;if(t&&s){return s[this.findItemIndex(t,e)]||null}return null}trimInPlace(t,e){if(this.isInterstitial(t)&&t.event.appendInPlace&&e.end-t.end>.25){t.event.assetList.forEach((e,i)=>{t.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(e.identifier,null)});const i=t.end+.25,s=Gi.bufferInfo(this.primaryMedia,i,0);if(s.end>i||(s.nextStart||0)>i){this.log(`trim buffered interstitial ${wo(t)} (was ${wo(e)})`);const s=!0;this.attachPrimary(i,null,s),this.flushFrontBuffer(i)}}}itemsMatch(t,e){return!!e&&(t===e||t.event&&e.event&&this.eventItemsMatch(t,e)||!t.event&&!e.event&&this.findItemIndex(t)===this.findItemIndex(e))}eventItemsMatch(t,e){var i;return!!e&&(t===e||t.event.identifier===(null==(i=e.event)?void 0:i.identifier))}findItemIndex(t,e){return t&&this.schedule?this.schedule.findItemIndex(t,e):-1}updateSchedule(t=!1){var e;const i=this.mediaSelection;i&&(null==(e=this.schedule)||e.updateSchedule(i,[],t))}checkBuffer(t){var e;const i=null==(e=this.schedule)?void 0:e.items;if(!i)return;const s=Gi.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=s.len<1),this.updateBufferedPos(s.end,i,t)}updateBufferedPos(t,e,i){const s=this.schedule,r=this.bufferingItem;if(this.bufferedPos>t||!s)return;if(1===e.length&&this.itemsMatch(e[0],r))return void(this.bufferedPos=t);const n=this.playingItem,a=this.findItemIndex(n);let o=s.findItemIndexAtTime(t);if(this.bufferedPos<t){var l;const i=this.findItemIndex(r),s=Math.min(i+1,e.length-1),n=e[s];if((-1===o&&r&&t>=r.end||null!=(l=n.event)&&l.appendInPlace&&t+.01>=n.start)&&(o=s),this.isInterstitial(r)){const t=r.event;if(s-a>1&&!1===t.appendInPlace)return;if(0===t.assetList.length&&t.assetListLoader)return}if(this.bufferedPos=t,o>i&&o>a)this.bufferedToItem(n);else{const e=this.primaryDetails;this.primaryLive&&e&&t>e.edge-e.targetduration&&n.start<e.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else i&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(e[o]))}assetsBuffered(t,e){return 0!==t.event.assetList.length&&!t.event.assetList.some(t=>{const i=this.getAssetPlayer(t.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(e))})}setBufferingItem(t){const e=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(t,e)&&i){const{items:s,events:r}=i;if(!s||!r)return e;const n=this.isInterstitial(t),a=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const o=a?a.remaining:e?e.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${wo(t)}`+(e?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const e=i.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((t,i)=>{const s=this.getAssetPlayer(t.identifier);s&&(i===e&&s.loadSource(),s.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(t=>t.pauseBuffering());this.hls.trigger(J.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return e}bufferedToItem(t,e=0){const i=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(null!==i){this.bufferingAsset=null;const e=this.detachedData;if(e)if(e.mediaSource){const e=!0;this.attachPrimary(t.start,t,e)}else this.preloadPrimary(t);else this.preloadPrimary(t)}}preloadPrimary(t){const e=this.findItemIndex(t),i=this.getPrimaryResumption(t,e);this.startLoadingPrimaryAt(i)}bufferedToEvent(t,e){const i=t.event,s=0===i.assetList.length&&!i.assetListLoader,r=i.cue.once;if(s||!r){const t=this.preloadAssets(i,e);if(null!=t&&t.interstitial.appendInPlace){const e=this.primaryMedia;e&&this.bufferAssetPlayer(t,e)}}}preloadAssets(t,e){const i=t.assetUrl,s=t.assetList.length,r=0===s&&!t.assetListLoader,n=t.cue.once;if(r){const r=t.timelineStart;if(t.appendInPlace){var a;const e=this.playingItem;this.isInterstitial(e)||(null==e||null==(a=e.nextEvent)?void 0:a.identifier)!==t.identifier||this.flushFrontBuffer(r+.25)}let n,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!t.cue.pre&&!t.cue.post){const t=o-r;t>0&&(n=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${i?1:s} ${t}${n?` live-start: ${o} start-offset: ${n}`:""}`),i)return this.createAsset(t,0,0,r,t.duration,i);const l=this.assetListLoader.loadAssetList(t,n);l&&(t.assetListLoader=l)}else if(!n&&s){for(let i=e;i<s;i++){const e=t.assetList[i],s=this.getAssetPlayerQueueIndex(e.identifier);-1!==s&&!this.playerQueue[s].destroyed||e.error||this.createAssetPlayer(t,e,i)}const i=t.assetList[e];if(i){const t=this.getAssetPlayer(i.identifier);return t&&t.loadSource(),t}}return null}flushFrontBuffer(t){const e=this.requiredTracks;
1if(!e)return;this.log(`Removing front buffer starting at ${t}`);Object.keys(e).forEach(e=>{this.hls.trigger(J.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:e})})}getAssetPlayerQueueIndex(t){const e=this.playerQueue;for(let i=0;i<e.length;i++)if(t===e[i].assetId)return i;return-1}getAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);return this.playerQueue[e]||null}getBufferingPlayer(){const{playerQueue:t,primaryMedia:e}=this;if(e)for(let i=0;i<t.length;i++)if(t[i].media===e)return t[i];return null}createAsset(t,e,i,s,r,n){const a={parentIdentifier:t.identifier,identifier:Eo(t,n,e),duration:r,startOffset:i,timelineStart:s,uri:n};return this.createAssetPlayer(t,a,e)}createAssetPlayer(t,e,i){const s=this.hls,r=s.userConfig;let n=r.videoPreference;const a=s.loadLevelObj||s.levels[s.currentLevel];(n||a)&&(n=dt({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=s.audioTracks[s.audioTrack],l=s.subtitleTracks[s.subtitleTrack];let d=0;if(this.primaryLive||t.appendInPlace){const t=this.timelinePos-e.timelineStart;if(t>1){const i=e.duration;i&&t<i&&(d=t)}}const c=e.identifier,u=ut(ut({},r),{},{maxMaxBufferLength:Math.min(180,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||r.audioPreference,subtitlePreference:l||r.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(u.timelineOffset=e.timelineStart));const h=u.cmcd;null!=h&&h.sessionId&&h.contentId&&(u.cmcd=dt({},h,{contentId:po(e.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${t} and asset ${c}`);const f=new Lo(this.HlsPlayerClass,u,t,e);this.playerQueue.push(f),t.assetList[i]=e;let g=!0;const m=s=>{if(s.live){var r;const e=new Error(`Interstitials MUST be VOD assets ${t}`),s={fatal:!0,type:X.OTHER_ERROR,details:Q.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},n=(null==(r=this.schedule)?void 0:r.findEventIndex(t.identifier))||-1;return void this.handleAssetItemError(s,t,n,i,e.message)}const n=s.edge-s.fragmentStart,a=e.duration;(g||null===a||n>a)&&(g=!1,this.log(`Interstitial asset "${c}" duration change ${a} > ${n}`),e.duration=n,this.updateSchedule())};f.on(J.LEVEL_UPDATED,(t,{details:e})=>m(e)),f.on(J.LEVEL_PTS_UPDATED,(t,{details:e})=>m(e)),f.on(J.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const p=(t,e)=>{const i=this.getAssetPlayer(c);if(i&&e.tracks){i.off(J.BUFFER_CODECS,p),i.tracks=e.tracks;const t=this.primaryMedia;this.bufferingAsset===i.assetItem&&t&&!i.media&&this.bufferAssetPlayer(i,t)}};f.on(J.BUFFER_CODECS,p);f.on(J.BUFFERED_TO_END,()=>{var i;const s=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${s}`),!s||!this.schedule)return;const r=this.schedule.findEventIndex(t.identifier),n=null==(i=this.schedule.items)?void 0:i[r];this.isInterstitial(n)&&this.advanceAssetBuffering(n,e)});const v=e=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;const i=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,e)};return f.once(J.MEDIA_ENDED,v(i)),f.once(J.PLAYOUT_LIMIT_REACHED,v(1/0)),f.on(J.ERROR,(e,s)=>{if(!this.schedule)return;const r=this.getAssetPlayer(c);if(s.details===Q.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(t):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(s,t,this.schedule.findEventIndex(t.identifier),i,`Asset player error ${s.error} ${t}`)}),f.on(J.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;const e=new Error(`Asset player destroyed unexpectedly ${c}`),s={fatal:!0,type:X.OTHER_ERROR,details:Q.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(s,t,this.schedule.findEventIndex(t.identifier),i,e.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${ko(e)}`),this.hls.trigger(J.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:i,event:t,player:f}),f}clearInterstitial(t,e){this.clearAssetPlayers(t,e),t.reset()}clearAssetPlayers(t,e){t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,e)})}resetAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);if(-1!==e){this.log(`reset asset player "${t}" after error`);const i=this.playerQueue[e];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(t,e){const i=this.getAssetPlayerQueueIndex(t);if(-1!==i){const t=this.playerQueue[i];this.log(`clear ${t} toSegment: ${e?wo(e):e}`),this.transferMediaFromPlayer(t,e),this.playerQueue.splice(i,1),t.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,e,i,s,r){const{interstitial:n,assetItem:a,assetId:o}=t,l=n.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=a,d&&d.identifier===o||(d&&(this.clearAssetPlayer(d.identifier,i[s]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${l} ${ko(a)}`),this.hls.trigger(J.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:e,event:n,schedule:i.slice(0),scheduleIndex:s,player:t})),this.bufferAssetPlayer(t,r)}bufferAssetPlayer(t,e){var i,s;if(!this.schedule)return;const{interstitial:r,assetItem:n}=t,a=this.schedule.findEventIndex(r.identifier),o=null==(i=this.schedule.items)?void 0:i[a];if(!o)return;t.loadSource(),this.setBufferingItem(o),this.bufferingAsset=n;
1const l=this.getBufferingPlayer();if(l===t)return;const d=r.appendInPlace;if(d&&!1===(null==l?void 0:l.interstitial.appendInPlace))return;const c=(null==l?void 0:l.tracks)||(null==(s=this.detachedData)?void 0:s.tracks)||this.requiredTracks;if(d&&n!==this.playingAsset){if(!t.tracks)return void this.log(`Waiting for track info before buffering ${t}`);if(c&&!Tt(c,t.tracks)){const e=new Error(`Asset ${ko(n)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),i={fatal:!0,type:X.OTHER_ERROR,details:Q.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},s=r.findAssetIndex(n);return void this.handleAssetItemError(i,r,a,s,e.message)}}this.transferMediaTo(t,e)}handleInPlaceStall(t){const e=this.schedule,i=this.primaryMedia;if(!e||!i)return;const s=i.currentTime,r=e.findAssetIndex(t,s),n=t.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||s-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${t} (media.currentTime: ${s})`),o&&(l/i.playbackRate<.5||a.bufferedInPlaceToEnd(i))&&a.hls){const i=e.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,r)}}}}advanceInPlace(t){const e=this.primaryMedia;e&&e.currentTime<t&&(e.currentTime=t)}handleAssetItemError(t,e,i,s,r){if(t.details===Q.BUFFER_STALLED_ERROR)return;const n=e.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n?ko(n):n} ${t.error}`),!this.schedule)return;const a=(null==n?void 0:n.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,d=this.schedule.items,c=dt({},t,{fatal:!1,errorAction:yi(!0),asset:n,assetListIndex:s,event:e,schedule:d,scheduleIndex:i,player:l});if(this.hls.trigger(J.INTERSTITIAL_ASSET_ERROR,c),!t.fatal)return;const u=this.playingAsset,h=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(a,null),n.error=f),e.assetList.some(t=>!t.error))for(let t=s;t<e.assetList.length;t++)this.resetAssetPlayer(e.assetList[t].identifier);else e.error=f;this.updateSchedule(!0),e.error?this.primaryFallback(e):u&&u.identifier===a?this.advanceAfterAssetEnded(e,i,s):h&&h.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,h)}primaryFallback(t){const e=t.timelineStart,i=this.effectivePlayingItem;let s=this.timelinePos;if(i){this.log(`Fallback to primary from event "${t.identifier}" start: ${e} pos: ${s} playing: ${wo(i)} error: ${t.error}`),-1===s&&(s=this.hls.startPosition);const r=this.updateItem(i,s);this.itemsMatch(i,r)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e))}else if(-1===s)return void this.checkStart();if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(r)}onAssetListLoaded(t,e){var i,s;const r=e.event,n=r.identifier,a=e.assetListResponse.ASSETS;if(null==(i=this.schedule)||!i.hasEvent(n))return;const o=r.timelineStart,l=r.duration;let d=0;a.forEach((t,e)=>{const i=parseFloat(t.DURATION);this.createAsset(r,e,d,o+d,i,t.URI),d+=i}),r.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${l}) ${r}`);const c=this.waitingItem,u=(null==c?void 0:c.event.identifier)===n;this.updateSchedule();const h=null==(s=this.bufferingItem)?void 0:s.event;if(u){var f;const t=this.schedule.findEventIndex(n),e=null==(f=this.schedule.items)?void 0:f[t];if(e){if(!this.playingItem&&this.timelinePos>e.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),void this.primaryFallback(r)}this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==h?void 0:h.identifier)===n){const t=r.assetList[0];if(t){const e=this.getAssetPlayer(t.identifier);if(h.appendInPlace){const t=this.primaryMedia;e&&t&&this.bufferAssetPlayer(e,t)}else e&&e.loadSource()}}}onError(t,e){if(this.schedule)switch(e.details){case Q.ASSET_LIST_PARSING_ERROR:case Q.ASSET_LIST_LOAD_ERROR:case Q.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&(this.updateSchedule(!0),this.primaryFallback(t));break}case Q.BUFFER_STALLED_ERROR:{const t=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&t.event.appendInPlace)return void this.handleInPlaceStall(t.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function Ml(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Ml):Object.keys(t).reduce((e,i)=>(e[i]=Ml(t[i]),e),{}):t}function Fl(t,e){const i=t.loader;if(i!==_l&&i!==Cl)e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}
vendor: 8,749 bytes, line 1
1)()&&(t.loader=_l,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Nl extends Ui{constructor(t,e){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger(J.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(J.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(J.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(100),this.mediaSource=e.mediaSource;const i=this.media=e.media;rr(i,"playing",this.onMediaPlaying),rr(i,"waiting",this.onMediaWaiting),rr(i,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:i}=this;i&&(nr(i,"playing",this.onMediaPlaying),nr(i,"waiting",this.onMediaWaiting),nr(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const e=this.media.currentTime;this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e}poll(t,e){var i,s;const r=null==(i=this.hls)?void 0:i.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,d=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,t!==e)return e&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!d&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(l||o)return void(o&&this.stallResolved(t));if(d)return this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(J.MEDIA_ENDED,{stalled:!1})));if(!Gi.getBuffered(n).length)return void(this.nudgeRetry=0);const c=Gi.bufferInfo(n,t,0),u=c.nextStart||0,h=this.fragmentTracker;if(a&&h&&this.hls){const e=Ul(this.hls.inFlightFragments,t),i=c.len>2,s=!u||e||u-t>2&&!h.getPartialFragment(t);if(i||s)return;this.moved=!1}const f=null==(s=this.hls)?void 0:s.latestLevelDetails;if(!this.moved&&null!==this.stalled&&h){if(!(c.len>0)&&!u)return;const e=Math.max(u,c.start||0)-t,i=!(null==f||!f.live)?2*f.targetduration:2,s=$l(t,h);if(e>0&&(e<=i||s))return void(n.paused||this._trySkipBufferHole(s))}const g=r.detectStallWithCurrentTimeMs,m=self.performance.now(),p=this.waiting;let v=this.stalled;if(null===v){if(!(p>0&&m-p<g))return void(this.stalled=m);v=this.stalled=p}const y=m-v;if(!a&&(y>=g||p)&&this.hls){var E;if("ended"===(null==(E=this.mediaSource)?void 0:E.readyState)&&(null==f||!f.live)&&Math.abs(t-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(J.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return}const T=Gi.bufferInfo(n,t,r.maxBufferHole);this._tryFixBufferStall(T,y,t)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(J.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var i;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&s&&s.length>1&&t>s.end(0)){const i=Gi.bufferedInfo(Gi.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&e>=i.start){const i=Gi.timeRangesToArray(s),r=Gi.bufferedInfo(i,e,0).bufferedIndex;if(r>-1&&r<i.length-1){const e=Gi.bufferedInfo(i,t,0).bufferedIndex,s=i[r].end,n=i[r+1].start;if((-1===e||e>r)&&n-s<1&&t-s<2){const i=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${s} -> ${n} buffered index: ${e}`);this.warn(i.message),this.media.currentTime+=1e-6;let r=$l(t,this.fragmentTracker);r&&"fragment"in r?r=r.fragment:r||(r=void 0);const a=Gi.bufferInfo(this.media,t,0);this.hls.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(t,e,i){var s,r;const{fragmentTracker:n,media:a}=this,o=null==(s=this.hls)?void 0:s.config;if(!a||!n||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,d=$l(i,n);if(d||null!=l&&l.live&&i<l.fragmentStart){if(this._trySkipBufferHole(d)||!this.media)return}const c=t.buffered,u=this.adjacentTraversal(t,i);(c&&c.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-i<o.maxBufferHole||u))&&(e>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const i=this.fragmentTracker,s=t.nextStart;if(i&&s){const t=i.getFragAtPos(e,st),r=i.getFragAtPos(s,st);if(t&&r)return r.sn-t.sn<2}return!1}_reportStall(t){const{hls:e,media:i,stallReported:s,stalled:r}=this;if(!s&&null!==r&&i&&e){this.stallReported=!0;const s=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Ve(t)})`);this.warn(s.message),e.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.BUFFER_STALLED_ERROR,fatal:!1,error:s,buffer:t.len,bufferInfo:t,stalled:{start:r}})}}_trySkipBufferHole(t){var e;const{fragmentTracker:i,media:s}=this,r=null==(e=this.hls)?void 0:e.config;if(!s||!i||!r)return 0;const n=s.currentTime,a=Gi.bufferInfo(s,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const e=a.len<=r.maxBufferHole,d=a.len>0&&a.len<1&&s.readyState<3,c=o-n;if(c>0&&(e||d)){if(c>r.maxBufferHole){let e=!1;if(0===n){const t=i.getAppendedFrag(0,st);t&&o<t.end&&(e=!0)}if(!e&&t){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(Ul(this.hls.inFlightFragments,o))return 0;let e=!1,s=t.end;for(;s<o;){const t=$l(s,i);if(!t){e=!0;break}s+=t.duration}if(e)return 0}}const e=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${e}`),this.moved=!0,s.currentTime=e,null==t||!t.gap){const i=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${e}`),s={type:X.MEDIA_ERROR,details:Q.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,buffer:a.len,bufferInfo:a};t&&("fragment"in t?s.part=t:s.frag=t),this.hls.trigger(J.ERROR,s)}return e}}return 0}_tryNudgeBuffer(t){const{hls:e,media:i,nudgeRetry:s}=this,r=null==e?void 0:e.config;if(!i||!r)return 0;const n=i.currentTime;if(this.nudgeRetry++,s<r.nudgeMaxRetry){const a=n+(s+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),i.currentTime=a,e.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:t.len,bufferInfo:t})}else{const i=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(i.message),e.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:t.len,bufferInfo:t})}}}function Ul(t,e){const i=Bl(t.main);if(i&&i.start<=e)return i;const s=Bl(t.audio);return s&&s.start<=e?s:null}function Bl(t){if(!t)return null;switch(t.state){case lr:case or:case mr:case pr:return null}return t.frag}function $l(t,e){return e.getAppendedFrag(t,st)||e.getPartialFragment(t)}function Gl(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Vl(t,e,i,s,r){let n=new t(e,i,"");try{n.value=s,r&&(n.type=r)}catch(a){n=new t(e,i,Ve(r?ut({type:r},s):s))}return n}const Kl=(()=>{const t=Gl();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Hl{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(J.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;
1t&&(t.on(J.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(J.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(J.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(J.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(J.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(J.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(J.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(J.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){var i;this.media=e.media,!1===(null==(i=e.overrides)?void 0:i.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var t;const e=null==(t=this.hls)?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null;!!e.transferMedia||(this.id3Track&&(this.removeCues&&fo(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;e<t.length;e++){const i=t[e];if("metadata"===i.kind&&"id3"===i.label)return uo(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;const{samples:r}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Gl();if(n)for(let t=0;t<r.length;t++){const e=r[t].type;if(e===zr.emsg&&!i||!s)continue;const a=jr(r[t].data),o=r[t].pts;let l=o+r[t].duration;l>Kl&&(l=Kl);l-o<=0&&(l=o+.25);for(let t=0;t<a.length;t++){const i=a[t];if(!qr(i)){this.updateId3CueEnds(o,e);const t=Vl(n,o,l,i,e);t&&this.id3Track.addCue(t)}}}}updateId3CueEnds(t,e){var i;const s=null==(i=this.id3Track)?void 0:i.cues;if(s)for(let i=s.length;i--;){const r=s[i];r.type===e&&r.startTime<t&&r.endTime===Kl&&(r.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:s}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let t;t="audio"===s?t=>t.type===zr.audioId3&&o:"video"===s?t=>t.type===zr.emsg&&a:t=>t.type===zr.audioId3&&o||t.type===zr.emsg&&a,go(r,e,i,t)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,e){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:s,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const a=Gl();if(i&&s&&!n){const{fragmentStart:e,fragmentEnd:s}=t;let r=this.assetCue;r?(r.startTime=e,r.endTime=s):a&&(r=this.assetCue=Vl(a,e,s,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=t,d=Object.keys(l);let c=this.dateRangeCuesAppended;var u;if(o&&e)if(null!=(u=o.cues)&&u.length){const t=Object.keys(c).filter(t=>!d.includes(t));for(let e=t.length;e--;){var h;const i=t[e],s=null==(h=c[i])?void 0:h.cues;delete c[i],s&&Object.keys(s).forEach(t=>{const e=s[t];if(e){e.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(e)}catch(t){}}})}}else c=this.dateRangeCuesAppended={};const f=t.fragments[t.fragments.length-1];if(0!==d.length&&Y(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<d.length;t++){const e=d[t],i=l[e],s=i.startTime,r=c[e],o=(null==r?void 0:r.cues)||{};
vendor: 19,358 bytes, line 1
1let u=(null==r?void 0:r.durationKnown)||!1,h=Kl;const{duration:f,endDate:g}=i;if(g&&null!==f)h=s+f,u=!0;else if(i.endOnNext&&!u){const t=d.reduce((t,e)=>{if(e!==i.id){const s=l[e];if(s.class===i.class&&s.startDate>i.startDate&&(!t||i.startDate<t.startDate))return s}return t},null);t&&(h=t.startTime,u=!0)}const m=Object.keys(i.attr);for(let t=0;t<m.length;t++){const l=m[t];if(!Xi(l))continue;const d=o[l];if(d)!u||null!=r&&r.durationKnown?Math.abs(d.startTime-s)>.01&&(d.startTime=s,d.endTime=h):d.endTime=h;else if(a){let t=i.attr[l];Qi(l)&&(t=At(t));const r=Vl(a,s,h,{key:l,data:t},zr.dateRange);r&&(r.id=e,this.id3Track.addCue(r),o[l]=r,n&&("X-ASSET-LIST"!==l&&"X-ASSET-URL"!==l||r.addEventListener("enter",this.onEventCueEnter)))}}c[e]={cues:o,dateRange:i,durationKnown:u}}}}}class jl{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,e=this.levelDetails;if(!t||!e)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:r}=this.config;if(!s||1===r||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=i-n;if(a<Math.min(this.maxLatency,n+e.targetduration)&&a>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,r)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,s=Math.min(e,Math.max(1,i));this.changeMediaPlaybackRate(t,s)}else 1!==t.playbackRate&&0!==t.playbackRate&&this.changeMediaPlaybackRate(t,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;const e=this.levelDetails;return e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||null===this.hls)return null;const{holdBack:e,partHoldBack:i,targetduration:s}=t,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||e;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*s);const d=s;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e)return null;const i=this.levelDetails;if(null===i)return null;const s=i.edge,r=t-e-this.edgeStalled,n=s-i.totalduration,a=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(null===t)return 0;const e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t}=this,e=this.levelDetails;if(!t||!e)return 0;const i=t.buffered.length;return(i?t.buffered.end(i-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(J.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(J.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(J.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(J.ERROR,this.onError,this))}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,e){var i;e.details===Q.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var i,s;t.playbackRate!==e&&(null==(i=this.hls)||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(s=this.targetLatency)?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}class ql extends Zn{constructor(t,e){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(J.LEVEL_LOADED,this.onLevelLoaded,this),t.on(J.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(J.FRAG_BUFFERED,this.onFragBuffered,this),t.on(J.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(J.LEVEL_LOADED,this.onLevelLoaded,this),t.off(J.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(J.FRAG_BUFFERED,this.onFragBuffered,this),t.off(J.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const i=this.hls.config.preferManagedMediaSource,s=[],r={},n={};let a=!1,o=!1,l=!1;e.levels.forEach(t=>{const e=t.attrs;let{audioCodec:d,videoCodec:c}=t;d&&(t.audioCodec=d=Ee(d,i)||void 0),c&&(c=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t<e.length;t++){const i=e[t].split(".");i.length>2&&"avc1"===i[0]&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}(c));const{width:u,height:h,unknownCodecs:f}=t,g=(null==f?void 0:f.length)||0;if(a||(a=!(!u||!h)),o||(o=!!c),l||(l=!!d),g||d&&!this.isAudioSupported(d)||c&&!this.isVideoSupported(c))return void this.log(`Some or all CODECS not supported "${e.CODECS}"`);const{CODECS:m,"FRAME-RATE":p,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:E,"VIDEO-RANGE":T}=e,S=`${`${y||"."}-`}${t.bitrate}-${E}-${p}-${m}-${T}-${v}`;if(r[S])if(r[S].uri===t.url||t.attrs["PATHWAY-ID"])r[S].addGroupId("audio",e.AUDIO),r[S].addGroupId("text",e.SUBTITLES);else{const e=n[S]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const i=this.createLevel(t);r[S]=i,s.push(i)}else{const e=this.createLevel(t);r[S]=e,n[S]=1,s.push(e)}}),this.filterAndSortMediaOptions(s,e,a,o,l)}createLevel(t){const e=new Be(t),i=t.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(t.message),e.supportedResult=we(t,[])}return e}isAudioSupported(t){return he(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return he(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,e,i,s,r){var n;let a=[],o=[],l=t;const d=(null==(n=e.stats)?void 0:n.parsing)||{};if((i||s)&&r&&(l=l.filter(({videoCodec:t,videoRange:e,width:i,height:s})=>{return(!!t||!(!i||!s))&&(!!(r=e)&&Ce.indexOf(r)>-1);var r})),0===l.length)return Promise.resolve().then(()=>{if(this.hls){let t="no level with compatible codecs found in manifest",i=t;e.levels.length&&(i=`one or more CODECS in variant not supported: ${Ve(e.levels.map(t=>t.attrs.CODECS).filter((t,e,i)=>i.indexOf(t)===e))}`,this.warn(i),t+=` (${i})`);const s=new Error(t);this.hls.trigger(J.ERROR,{type:X.MEDIA_ERROR,details:Q.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:s,reason:i})}}),void(d.end=performance.now());e.audioTracks&&(a=e.audioTracks.filter(t=>!t.audioCodec||this.isAudioSupported(t.audioCodec)),Yl(a)),e.subtitles&&(o=e.subtitles,Yl(o));const c=l.slice(0);l.sort((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return Ce.indexOf(t.videoRange)-Ce.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const i=me(t.videoCodec),s=me(e.videoCodec);if(i!==s)return s-i}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const i=pe(t.codecSet),s=pe(e.codecSet);if(i!==s)return s-i}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0});let u=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length))for(let t=0;t<c.length;t++)if(c[t].pathwayId===l[0].pathwayId){u=c[t];break}this._levels=l;for(let t=0;t<l.length;t++)if(l[t]===u){var h;this._firstLevel=t;const e=u.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${e}`),void 0===(null==(h=this.hls.userConfig)?void 0:h.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const f=r&&!s,g=this.hls.config,m=!(!g.audioStreamController||!g.audioTrackController),p={levels:l,audioTracks:a,subtitleTracks:o,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:s,altAudio:m&&!f&&a.some(t=>!!t.url)};d.end=performance.now(),this.hls.trigger(J.MANIFEST_PARSED,p)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const i=new Error("invalid level idx"),s=t<0;if(this.hls.trigger(J.ERROR,{type:X.OTHER_ERROR,details:Q.LEVEL_SWITCH_ERROR,level:t,fatal:s,error:i,reason:i.message}),s)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,r=s?s.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,i===t&&s&&r===a)return;this.log(`Switching to level ${t} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${i}${r?" with Pathway "+r:""}`);const o={level:t,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(J.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const t=this.switchParams(n.uri,null==s?void 0:s.details,l);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),i=t.filter(t=>-1!==e.indexOf(t));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);this.steering.pathwayPriority=i}}onError(t,e){!e.fatal&&e.context&&e.context.type===tt&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===st){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return;const i=this._levels[e.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(t,e){var i;const{level:s,details:r}=e,n=e.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${s}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||e.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let t=n.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(s,e,t)}else null!=(i=e.deliveryDirectives)&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=this.getUrlWithDirectives(t.uri,e),s=this.currentLevelIndex,r=t.attrs["PATHWAY-ID"],n=t.details,a=null==n?void 0:n.age;this.log(`Loading level index ${s}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${i}`),this.hls.trigger(J.LEVEL_LOADING,{url:i,level:s,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(1===this._levels.length)return;const i=this._levels.filter((e,i)=>i!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach(t=>t.level=-1)),!1));Xs(i),this._levels=i,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(J.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(J.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Yl(t){const e={};t.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function Wl(){return self.SourceBuffer||self.WebKitSourceBuffer}function zl(){if(!Et())return!1;const t=Wl();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class Xl extends Er{constructor(t,e,i){super(t,e,i,"stream-controller",st),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const t=this.media,e=t?t.currentTime:null;if(null===e||!Y(e))return;if(this.log(`Media seeked to ${e.toFixed(3)}`),!this.getBufferedFrag(e))return;const i=this.getFwdBufferInfoAtPos(t,e,st,0);null!==i&&0!==i.len?this.tick():this.warn(`Main forward buffer length at ${e} on "seeked" event ${i?i.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(J.MANIFEST_PARSED,this.onManifestParsed,this),t.on(J.LEVEL_LOADING,this.onLevelLoading,this),t.on(J.LEVEL_LOADED,this.onLevelLoaded,this),t.on(J.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(J.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(J.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(J.BUFFER_CREATED,this.onBufferCreated,this),t.on(J.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(J.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(J.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(J.MANIFEST_PARSED,this.onManifestParsed,this),t.off(J.LEVEL_LOADED,this.onLevelLoaded,this),t.off(J.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(J.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(J.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(J.BUFFER_CREATED,this.onBufferCreated,this),t.off(J.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(J.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(J.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=s.startLevel;-1===t&&(s.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=s.firstAutoLevel),s.nextLoadLevel=t,this.level=s.loadLevel,this._hasEnoughToStart=!!e}i>0&&-1===t&&!e&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i),this.state=lr,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=or}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case yr:{const{levels:t,level:e}=this,i=null==t?void 0:t[e],s=null==i?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=lr;break}if(this.hls.nextLoadLevel!==this.level){this.state=lr;break}break}case ur:this.checkRetryDate()}this.state===lr&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:i,media:s}=this;if(null===e||!s&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==i||!i[r])return;const n=i[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={};return 2===this.altAudio&&(t.type="video"),this.hls.trigger(J.BUFFER_EOS,t),void(this.state=mr)}if(!this.buffering)return;t.loadLevel!==r&&-1===t.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}
1`),this.level=t.nextLoadLevel=r;const l=n.details;if(!l||this.state===yr||this.waitForLive(n))return this.level=r,this.state=yr,void(this.startFragRequested=!1);const d=a.len,c=this.getMaxBufferLength(n.maxBitrate);if(d>=c)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:a.end;let h=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&h&&Ct(h)&&this.fragmentTracker.getState(h)!==bi){var f;const t=(null!=(f=this.backtrackFragment)?f:h).sn-l.startSN,e=l.fragments[t-1];e&&h.cc===e.cc&&(h=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(h&&this.isLoopLoading(h,u)){if(!h.gap){const t=this.audioOnly&&!this.altAudio?_t:Dt,e=(t===Dt?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,st)}h=this.getNextFragmentLoopLoading(h,l,a,st,c)}h&&(this.exceedsMaxBuffer(a,c,h)||(!h.initSegment||h.initSegment.data||this.bitrateTest||(h=h.initSegment),this.loadFragment(h,n,u)))}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);s===Ei||s===Si?Ct(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,e)):super.loadFragment(t,e,i):this._loadInitSegment(t,e):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,st)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),0!==this.altAudio){var t;((null==(t=this.getLevelDetails())?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let i;const s=this.getAppendedFrag(e.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*r.targetduration)return}if(!e.paused&&t){const e=t[this.hls.nextLoadLevel],s=this.fragLastKbps;i=s&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*s)+1:0}else i=0;const n=this.getBufferedFrag(e.currentTime+i);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,i=t.duration,s=Math.max(n.end,e+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(s,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case dr:case cr:case ur:case fr:case gr:this.state=lr}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,2===this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;rr(i,"playing",this.onMediaPlaying),rr(i,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:i}=this;i&&(nr(i,"playing",this.onMediaPlaying),nr(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(t,e);!!e.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(J.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(t,e){let i=!1,s=!1;for(let t=0;t<e.levels.length;t++){const r=e.levels[t].audioCodec;r&&(i=i||-1!==r.indexOf("mp4a.40.2"),s=s||-1!==r.indexOf("mp4a.40.5"))}this.audioCodecSwitch=i&&s&&!function(){var t;const e=Wl();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.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}onLevelLoading(t,e){const{levels:i}=this;if(!i||this.state!==lr)return;const s=e.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=yr)}onLevelLoaded(t,e){var i;const{levels:s,startFragRequested:r}=this,n=e.level,a=e.details,o=a.totalduration;if(!s)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=e.levelInfo,d=this.fragCurrent;!d||this.state!==cr&&this.state!==ur||d.level!==e.level&&d.loader&&this.abortCurrentFrag();let c=0;if(a.live||null!=(i=l.details)&&i.live){var u;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,c),this.hls.trigger(J.LEVEL_UPDATED,{details:a,level:n}),this.state===yr){if(this.waitForCdnTuneIn(a))return;this.state=lr}r&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=t.fragmentStart,a=t.edge,o=r>=n-e.maxFragLookUpTolerance&&r<=a;if(null!==s&&i.duration>s&&(r<s||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!o&&i.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${s.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var l;const t=Gi.bufferInfo(i,s,0);if(null==(l=t.buffered)||!l.length)return void(i.currentTime=s);if(t.start<=r)return void(i.currentTime=s);const{nextStart:e}=Gi.bufferedInfo(t.buffered,r,0);e&&(i.currentTime=e)}else i.currentTime=s}}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:r}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const a=n[i.level];if(!a)return void this.warn(`Level ${i.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),void this.fragmentTracker.removeFragment(i);const l=a.videoCodec,d=o.PTSKnown||!o.live,c=null==(e=i.initSegment)?void 0:e.data,u=this._getAudioCodec(a),h=this.transmuxer=this.transmuxer||new Jn(this.hls,st,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=s?s.index:-1,g=-1!==f,m=new Bi(i.level,i.sn,i.stats.chunkCount,r.byteLength,f,g),p=this.initPTS[i.cc];
vendor: 9,550 bytes, line 1
1h.push(r,c,u,l,i,s,o.totalduration,d,m,p)}onAudioTrackSwitching(t,e){const i=this.hls,s=0!==this.altAudio;if(Xe(e.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s)return this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(J.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(J.AUDIO_TRACK_SWITCHED,e)}),void i.trigger(J.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(J.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=Xe(e.url,this.hls);if(i){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=i?2:0,this.tick()}onBufferCreated(t,e){const i=e.tracks;let s,r,n=!1;for(const t in i){const e=i[t];if("main"===e.id){if(r=t,s=e,"video"===t){const e=i[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&s?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:i,part:s}=e,r=i.type===st;if(r){if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===gr&&(this.state=lr));const t=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*t.total/(t.buffering.end-t.loading.first)),Ct(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}const n=this.media;n&&(!this._hasEnoughToStart&&Gi.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var i;if(e.fatal)this.state=pr;else switch(e.details){case Q.FRAG_GAP:case Q.FRAG_PARSING_ERROR:case Q.FRAG_DECRYPT_ERROR:case Q.FRAG_LOAD_ERROR:case Q.FRAG_LOAD_TIMEOUT:case Q.KEY_LOAD_ERROR:case Q.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(st,e);break;case Q.LEVEL_LOAD_ERROR:case Q.LEVEL_LOAD_TIMEOUT:case Q.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==yr||(null==(i=e.context)?void 0:i.type)!==tt||(this.state=lr);break;case Q.BUFFER_ADD_CODEC_ERROR:case Q.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case Q.BUFFER_FULL_ERROR:if("main"!==e.parent)return;if(this.reduceLengthAndFlushBuffer(e)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case Q.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=lr,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==_t||!this.altAudio){const t=(e===Dt?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e,st),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let i=this.startPosition;if(i>=0&&e<i){if(t.seeking)return void this.log(`could not seek to ${i}, already seeking at ${e}`);const s=this.timelineOffset;s&&i&&(i+=s);const r=this.getLevelDetails(),n=Gi.getBuffered(t),a=n.length?n.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),e<i&&(this.log(`seek to target start position ${i} from current time ${e} buffer start ${a}`),t.currentTime=i)}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then(t=>{const{hls:i}=this,s=null==t?void 0:t.frag;if(!s||this.fragContextChanged(s))return;e.fragmentError=0,this.state=lr,this.startFragRequested=!1,this.bitrateTest=!1;const r=s.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(J.FRAG_LOADED,t),s.bitrateTest=!1}).catch(e=>{this.state!==or&&this.state!==pr&&(this.warn(e),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const e=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:r}=t,n=this.getCurrentContext(r);if(!n)return void this.resetWhenMissingContext(r);const{frag:a,part:o,level:l}=n,{video:d,text:c,id3:u,initSegment:h}=s,{details:f}=l,g=this.altAudio?void 0:s.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=fr,h){const t=h.tracks;if(t){const s=a.initSegment||a;if(this.unhandledEncryptionError(h,a))return;this._bufferInitSegment(l,t,s,r),i.trigger(J.FRAG_PARSING_INIT_SEGMENT,{frag:s,id:e,tracks:t})}const s=h.initPTS,n=h.timescale,o=this.initPTS[a.cc];if(Y(s)&&(!o||o.baseTime!==s||o.timescale!==n)){const t=h.trackId;this.initPTS[a.cc]={baseTime:s,timescale:n,trackId:t},i.trigger(J.INIT_PTS_FOUND,{frag:a,id:e,initPTS:s,timescale:n,trackId:t})}}if(d&&f){g&&"audiovideo"===d.type&&this.logMuxedErr(a);const t=f.fragments[a.sn-1-f.startSN],e=a.sn===f.startSN,i=!t||a.cc>t.cc;if(!1!==s.independent){const{startPTS:t,endPTS:s,startDTS:n,endDTS:l}=d;if(o)o.elementaryStreams[d.type]={startPTS:t,endPTS:s,startDTS:n,endDTS:l};else if(d.firstKeyFrame&&d.independent&&1===r.id&&!i&&(this.couldBacktrack=!0),d.dropped&&d.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=d.firstKeyFramePTS?d.firstKeyFramePTS:t;if(!e&&n<o-this.config.maxBufferHole&&!i)return void this.backtrack(a);i&&(a.gap=!0),a.setElementaryStreamInfo(d.type,a.start,s,a.start,l,!0)}else e&&t-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(d.type,t,s,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(d,a,o,r,e||i)}else{if(!e&&!i)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:t,endPTS:e,startDTS:i,endDTS:s}=g;o&&(o.elementaryStreams[_t]={startPTS:t,endPTS:e,startDTS:i,endDTS:s}),a.setElementaryStreamInfo(_t,t,e,i,s),this.bufferFragmentData(g,a,o,r)}if(f&&null!=u&&u.samples.length){const t={id:e,frag:a,details:f,samples:u.samples};i.trigger(J.FRAG_PARSING_METADATA,t)}if(f&&c){const t={id:e,frag:a,details:f,samples:c.samples};i.trigger(J.FRAG_PARSING_USERDATA,t)}}}logMuxedErr(t){this.warn(`${Ct(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,i,s){if(this.state!==fr)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(i));const{audio:r,video:n,audiovideo:a}=e;if(r){const i=t.audioCodec;let s=Te(r.codec,i);"mp4a"===s&&(s="mp4a.40.5");const n=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){s&&(s=-1!==s.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=r.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&-1===n.indexOf("firefox")&&(s="mp4a.40.5")}s&&-1!==s.indexOf("mp4a.40.5")&&-1!==n.indexOf("android")&&"audio/mpeg"!==r.container&&(s="mp4a.40.2",this.log(`Android: force audio codec to ${s}`)),i&&i!==s&&this.log(`Swapping manifest audio codec "${i}" for "${s}"`),r.levelCodec=s,r.id=st,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${s||""}/${i||""}/${r.codec}]`),delete e.audiovideo}if(n){n.levelCodec=t.videoCodec,n.id=st;const i=n.codec;if(4===(null==i?void 0:i.length))switch(i){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${i}]${n.codec!==i?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete e.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),delete e.video,delete e.audio);const o=Object.keys(e);if(o.length){if(this.hls.trigger(J.BUFFER_CODECS,e),!this.hls)return;o.forEach(t=>{const r=e[t].initSegment;null!=r&&r.byteLength&&this.hls.trigger(J.BUFFER_APPENDING,{type:t,data:r,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,st)}get maxBufferLength(){const{levels:t,level:e}=this,i=null==t?void 0:t[e];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=lr}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const i=t.currentTime;if(Gi.isBuffered(t,i)?e=this.getAppendedFrag(i):Gi.isBuffered(t,i+.1)&&
1(e=this.getAppendedFrag(i+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,i=e.level;t&&e.sn===t.sn&&t.level===i||(this.fragPlaying=e,this.hls.trigger(J.FRAG_CHANGED,{frag:e}),t&&t.level===i||this.hls.trigger(J.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return Y(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(Y(e)){const t=this.getLevelDetails(),i=this.currentFrag||(t?Je(null,t.fragments,e):null);if(i){const t=i.programDateTime;if(null!==t){const s=t+1e3*(e-i.start);return new Date(s)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class Ql extends ht{constructor(t,e){super("key-loader",e),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const i in this.keyIdToKeyInfo){const s=this.keyIdToKeyInfo[i].loader;if(s){var e;if(t&&t!==(null==(e=s.context)?void 0:e.frag.type))return;s.abort()}}}detach(){for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t].loader;e&&e.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(t,e=Q.KEY_LOAD_ERROR,i,s,r){return new Ni({type:X.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:r,error:i,networkDetails:s})}loadClear(t,e,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(e.length)for(let s=0,r=e.length;s<r;s++){const n=e[s];if(t.cc<=n.cc&&(!Ct(t)||!Ct(n)||t.sn<n.sn)||!i&&s==r-1)return this.emeController.selectKeySystemFormat(n).then(t=>{if(!this.emeController)return;n.setKeyFormat(t);const e=gs(t);return e?this.emeController.getKeySystemAccess([e]):void 0})}if(this.config.requireKeySystemAccessOnStart){const t=ps(this.config);if(t.length)return this.emeController.getKeySystemAccess(t)}}return null}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(e=>this.loadInternal(t,e)):this.loadInternal(t)}loadInternal(t,e){var i,s;e&&t.setKeyFormat(e);const r=t.decryptdata;if(!r){const i=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(t,Q.KEY_LOAD_ERROR,i))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,Q.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=Jl(r);let o=this.keyIdToKeyInfo[a];if(null!=(i=o)&&i.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:t,keyInfo:o});if(this.emeController&&null!=(s=o)&&s.keyLoadPromise){switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then(e=>{const{keyInfo:i}=e;return r.key=i.decryptdata.key,{frag:t,keyInfo:i}})}}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${r.keyId?" keyId: "+bt(r.keyId):""} URI: ${r.uri} from ${t.type} ${t.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(o,t):this.loadKeyEME(o,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,t);default:return Promise.reject(this.createKeyLoadError(t,Q.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(t,e){const i={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var s;if(!t.decryptdata.keyId&&null!=(s=e.initSegment)&&s.data){const i=function(t){const e=[];return Zt(t,t=>
1e.push(t.subarray(8,24))),e}(e.initSegment.data);if(i.length){let e=i[0];e.some(t=>0!==t)?(this.log(`Using keyId found in init segment ${bt(e)}`),Ss.setKeyIdForUri(t.decryptdata.uri,e)):(e=Ss.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${bt(e)}`)),t.decryptdata.keyId=e}}if(!t.decryptdata.keyId&&!Ct(e))return Promise.resolve(i);const r=this.emeController.loadKey(i);return(t.keyLoadPromise=r.then(e=>(t.mediaKeySessionContext=e,i))).catch(i=>{throw t.keyLoadPromise=null,"data"in i&&(i.data.frag=e),i})}return Promise.resolve(i)}loadKeyHTTP(t,e){const i=this.config,s=new(0,i.loader)(i);return e.keyLoader=t.loader=s,t.keyLoadPromise=new Promise((r,n)=>{const a={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},o=i.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,e,i,s)=>{const{frag:a,keyInfo:o}=i,l=Jl(o.decryptdata);if(!a.decryptdata||o!==this.keyIdToKeyInfo[l])return n(this.createKeyLoadError(a,Q.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,o.loader=null,r({frag:a,keyInfo:o})},onError:(t,i,s,r)=>{this.resetLoader(i),n(this.createKeyLoadError(e,Q.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),s,ut({url:a.url,data:void 0},t)))},onTimeout:(t,i,s)=>{this.resetLoader(i),n(this.createKeyLoadError(e,Q.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),s))},onAbort:(t,i,s)=>
vendor: 9,074 bytes, line 1
1{this.resetLoader(i),n(this.createKeyLoadError(e,Q.INTERNAL_ABORTED,new Error("key loading aborted"),s))}};s.load(a,l,d)})}resetLoader(t){const{frag:e,keyInfo:i,url:s}=t,r=i.loader;e.keyLoader===r&&(e.keyLoader=null,i.loader=null);const n=Jl(i.decryptdata)||s;delete this.keyIdToKeyInfo[n],r&&r.destroy()}}function Jl(t){if(t.keyFormat!==us){const e=t.keyId;if(e)return bt(e)}return t.uri}function Zl(t){const{type:e}=t;switch(e){case et:return rt;case it:return nt;default:return st}}function td(t,e){let i=t.url;return void 0!==i&&0!==i.indexOf("data:")||(i=e.url),i}class ed{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(J.MANIFEST_LOADING,this.onManifestLoading,this),t.on(J.LEVEL_LOADING,this.onLevelLoading,this),t.on(J.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(J.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(J.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(J.MANIFEST_LOADING,this.onManifestLoading,this),t.off(J.LEVEL_LOADING,this.onLevelLoading,this),t.off(J.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(J.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(J.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,i=e.pLoader,s=e.loader,r=new(i||s)(e);return this.loaders[t.type]=r,r}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:i}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Z,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:i,level:s,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=e;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:tt,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:et,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:it,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(t,e){const i=this.loaders[tt];if(i){const t=i.context;t&&!e.levels.some(e=>e===t.levelOrTrack)&&(i.abort(),delete this.loaders[tt])}}load(t){var e;const i=this.hls.config;let s,r=this.getInternalLoader(t);if(r){const e=this.hls.logger,i=r.context;if(i&&i.levelOrTrack===t.levelOrTrack&&(i.url===t.url||i.deliveryDirectives&&!t.deliveryDirectives))return void(i.url===t.url?e.log(`[playlist-loader]: ignore ${t.url} ongoing request`):e.log(`[playlist-loader]: ignore ${t.url} in favor of ${i.url}`));e.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),r.abort()}if(s=t.type===Z?i.manifestLoadPolicy.default:dt({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(t),Y(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===tt&&null!==t.level?e=this.hls.levels[t.level].details:t.type===et&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===it&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,i=e.targetduration;if(t&&i){const e=1e3*Math.max(3*t,.8*i);s=dt({},s,{maxTimeToFirstByteMs:Math.min(e,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,s.maxTimeToFirstByteMs)})}}}const n=s.errorRetry||s.timeoutRetry||{},a={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(t,e,i,s)=>{const r=this.getInternalLoader(i);this.resetInternalLoader(i.type);const n=t.data;e.parsing.start=performance.now(),Rs.isMediaPlaylist(n)||i.type!==Z?this.handleTrackOrLevelPlaylist(t,e,i,s||null,r):this.handleMasterPlaylist(t,e,i,s)},onError:(t,e,i,s)=>{this.handleNetworkError(e,i,!1,t,s)},onTimeout:(t,e,i)=>{this.handleNetworkError(e,i,!0,void 0,t)}};r.load(t,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:i}=this.hls;(t||i)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,i,s){const r=this.hls,n=t.data,a=td(t,i),o=Rs.parseMasterPlaylist(n,a);if(o.playlistParsingError)return e.parsing.end=performance.now(),void this.handleManifestParsingError(t,i,o.playlistParsingError,s,e);const{contentSteering:l,levels:d,sessionData:c,sessionKeys:u,startTimeOffset:h,variableList:f}=o;this.variableList=f,d.forEach(t=>{const{unknownCodecs:e}=t;if(e){const{preferManagedMediaSource:i}=this.hls.config;let{audioCodec:s,videoCodec:r}=t;for(let n=e.length;n--;){const a=e[n];he(a,"audio",i)?(t.audioCodec=s=s?`${s},${a}`:a,ce.audio[s.substring(0,4)]=2,e.splice(n,1)):he(a,"video",i)&&(t.videoCodec=r=r?`${r},${a}`:a,ce.video[r.substring(0,4)]=2,e.splice(n,1))}}});const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=Rs.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some(t=>!t.url)||!d[0].audioCodec||d[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new zi({}),bitrate:0,url:""}))}r.trigger(J.MANIFEST_LOADED,{levels:d,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:e,networkDetails:s,sessionData:c,sessionKeys:u,startTimeOffset:h,variableList:f})}handleTrackOrLevelPlaylist(t,e,i,s,r){const n=this.hls,{id:a,level:o,type:l}=i,d=td(t,i),c=Y(o)?o:Y(a)?a:0,u=Zl(i),h=Rs.parseLevelPlaylist(t.data,d,c,u,0,this.variableList);if(l===Z){const t={attrs:new zi({}),bitrate:0,details:h,name:"",url:d};h.requestScheduled=e.loading.start+qs(h,0),n.trigger(J.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:d,stats:e,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=h,this.handlePlaylistLoaded(h,t,e,i,s,r)}handleManifestParsingError(t,e,i,s,r){this.hls.trigger(J.ERROR,{type:X.NETWORK_ERROR,details:Q.MANIFEST_PARSING_ERROR,fatal:e.type===Z,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:s,stats:r})}handleNetworkError(t,e,i=!1,s,r){let n=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${t.type}`;t.type===tt?n+=`: ${t.level} id: ${t.id}`:t.type!==et&&t.type!==it||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=Q.UNKNOWN,l=!1;const d=this.getInternalLoader(t);switch(t.type){case Z:o=i?Q.MANIFEST_LOAD_TIMEOUT:Q.MANIFEST_LOAD_ERROR,l=!0;break;case tt:o=i?Q.LEVEL_LOAD_TIMEOUT:Q.LEVEL_LOAD_ERROR,l=!1;break;case et:o=i?Q.AUDIO_TRACK_LOAD_TIMEOUT:Q.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case it:o=i?Q.SUBTITLE_TRACK_LOAD_TIMEOUT:Q.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(t.type);const c={type:X.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:d,context:t,error:a,networkDetails:e,stats:r};if(s){const i=(null==e?void 0:e.url)||t.url;c.response=ut({url:i,data:void 0},s)}this.hls.trigger(J.ERROR,c)}handlePlaylistLoaded(t,e,i,s,r,n){const a=this.hls,{type:o,level:l,levelOrTrack:d,id:c,groupId:u,deliveryDirectives:h}=s,f=td(e,s),g=Zl(s);let m="number"==typeof s.level&&g===st?l:void 0;const p=t.playlistParsingError;if(p){if(this.hls.logger.warn(`${p} ${t.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(J.ERROR,{type:X.NETWORK_ERROR,details:Q.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:e,context:s,level:m,parent:g,networkDetails:r,stats:i});t.playlistParsingError=null}if(!t.fragments.length){const n=t.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(J.ERROR,{type:X.NETWORK_ERROR,details:Q.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:n,reason:n.message,response:e,context:s,level:m,parent:g,networkDetails:r,stats:i})}switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case Z:case tt:if(m)if(d){if(d!==a.levels[m]){const t=a.levels.indexOf(d);t>-1&&(m=t)}}else m=0;a.trigger(J.LEVEL_LOADED,{details:t,levelInfo:d||a.levels[0],level:m||0,id:c||0,stats:i,networkDetails:r,deliveryDirectives:h,withoutMultiVariant:o===Z});break;case et:a.trigger(J.AUDIO_TRACK_LOADED,{details:t,track:d,id:c||0,groupId:u||"",stats:i,networkDetails:r,deliveryDirectives:h});break;case it:a.trigger(J.SUBTITLE_TRACK_LOADED,{details:t,track:d,id:c||0,groupId:u||"",stats:i,networkDetails:r,deliveryDirectives:h})}}}
1class id{static get version(){return Ir}static isMSESupported(){return zl()}static isSupported(){return function(){if(!zl())return!1;const t=Et();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>t.isTypeSupported(ge(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(ge(e,"audio"))))}()}static getMediaSource(){return Et()}static get Events(){return J}static get MetadataSchema(){return zr}static get ErrorTypes(){return X}static get ErrorDetails(){return Q}static get DefaultConfig(){return id.defaultConfig?id.defaultConfig:Ol}static set DefaultConfig(t){id.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Lr,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const e=this.logger=function(t,e,i){const s=mt();if("object"==typeof console&&!0===t||"object"==typeof t){const r=["debug","log","info","warn","error"];r.forEach(e=>{s[e]=pt(e,t,i)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.18`)}catch(t){return mt()}r.forEach(e=>{vt[e]=pt(e,t)})}else dt(vt,s);return s}(t.debug||!1,"Hls instance",t.assetPlayerId),i=this.config=function(t,e,i){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=Ml(t),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const n=`${"level"===t?"playlist":t}LoadPolicy`,a=void 0===e[n],o=[];r.forEach(i=>{const r=`${t}Loading${i}`,l=e[r];if(void 0!==l&&a){o.push(r);const t=s[n].default;switch(e[n]={default:t},i){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&i.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${Ve(e[n])}`)}),ut(ut({},s),e)}(id.DefaultConfig,t,e);this.userConfig=t,i.progressive&&Fl(i,e);const{abrController:s,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=i,l=new a(this),d=this.abrController=new s(this),c=new Ai(this),u=i.interstitialsController,h=u?this.interstitialsController=new u(this,id):null,f=this.bufferController=new r(this,c),g=this.capLevelController=new n(this),m=new o(this),p=new ed(this),v=i.contentSteeringController,y=v?new v(this):null,E=this.levelController=new ql(this,y),T=new Hl(this),S=new Ql(this.config,this.logger),b=this.streamController=new Xl(this,c,S),A=this.gapController=new Nl(this,c);g.setStreamController(b),m.setStreamController(b);const k=[p,E,b];h&&k.splice(1,0,h),y&&k.splice(1,0,y),this.networkControllers=k;const L=[d,f,A,g,m,T,c];this.audioTrackController=this.createController(i.audioTrackController,k);const I=i.audioStreamController;I&&k.push(this.audioStreamController=new I(this,c,S)),this.subtitleTrackController=this.createController(i.subtitleTrackController,k);const w=i.subtitleStreamController;w&&k.push(this.subtititleStreamController=new w(this,c,S)),this.createController(i.timelineController,L),S.emeController=this.emeController=this.createController(i.emeController,L),this.cmcdController=this.createController(i.cmcdController,L),this.latencyController=this.createController(jl,L),this.coreComponents=L,k.push(l);const R=l.onErrorOut;"function"==typeof R&&this.on(J.ERROR,R,l),this.on(J.MANIFEST_LOADED,p.onManifestLoaded,p)}createController(t,e){if(t){const i=new t(this);return e&&e.push(i),i}return null}on(t,e,i=this){this._emitter.on(t,e,i)}once(t,e,i=this){this._emitter.once(t,e,i)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,i=this,s){this._emitter.off(t,e,i,s)}listeners(t){return this._emitter.listeners(t)}emit(t,e,i){return this._emitter.emit(t,e,i)}
vendor: 3,489 bytes, line 1
1trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const i=t===J.ERROR;this.trigger(J.ERROR,{type:X.OTHER_ERROR,details:Q.INTERNAL_EXCEPTION,fatal:i,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(J.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const e=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger(J.ERROR,{type:X.OTHER_ERROR,details:Q.ATTACH_MEDIA_ERROR,fatal:!0,error:e})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,i=e?t.media:t,s=e?t:{media:i};this._media=i,this.trigger(J.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(J.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(J.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const e=this.media,i=this._url,s=this._url=wt.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),e&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(J.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(t,e),this.started&&this.networkControllers);i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[st]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[rt]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[nt]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&this.startLoad(e))}removeLevel(t){this.levelController.removeLevel(t)}
1get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();const i="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|8).toString(16)});return i}}}()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return xe.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const i=t.length;for(let s=0;s<i;s++)if(t[s].maxBitrate>=e)return s;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:i}=this;let s;if(s=-1===e&&null!=t&&t.length?t.length-1:e,i)for(let e=s;e--;){const s=t[e].attrs["HDCP-LEVEL"];if(s&&s<=i)return e}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return(null==(e=this.subtitleTrackController)?void 0:e.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){var t;return(null==(t=this.interstitialsController)?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,e=this.allAudioTracks){return _e(t,He(e),navigator.mediaCapabilities)}}id.defaultConfig=void 0;class sd{constructor(){this._isLoaded=!1,this._player=new id({capLevelToPlayerSize:!0,startLevel:-1})}init(t){this._player.attachMedia(t)}get source(){return this._source}set source(t){this._source=t}load(){this._isLoaded||(this._player.loadSource(this._source),this._isLoaded=!0)}onPlay(){this._isLoaded||this.load(),this._player.startLoad()}onPause(){this._player.stopLoad()}}"function"==typeof SuppressedError&&SuppressedError;const rd=["ERROR","WARN","INFO","LOG","DEBUG"];class nd{static setLogLevel(t){nd.currentLogLevel=t}static getColorScheme(){return"undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dar
1k":"light"}static getColorByLevel(t){const e=nd.getColorScheme();switch(t){case"LOG":case"DEBUG":return"dark"===e?"#B0BEC5":"#37474F";case"INFO":return"dark"===e?"#82B1FF":"#0D47A1";case"WARN":return"dark"===e?"#FFD54F":"#FF6F00";case"ERROR":return"dark"===e?"#FF8A80":"#D32F2F";default:return"dark"===e?"white":"black"}}static logMessage(t,e,...i){if(!(rd.indexOf(t)<=rd.indexOf(nd.currentLogLevel)))return;const s=`%c[${t}] Tracker: ${e}`,r=`color: ${nd.getColorByLevel(t)};`;switch(t){case"LOG":default:console.log(`${s}`,r,...i);break;case"INFO":console.info(`${s}`,r,...i);break;case"WARN":console.warn(`${s}`,r,...i);break;case"ERROR":console.error(`${s}`,r,...i);break;case"DEBUG":console.debug(`${s}`,r,...i)}}static log(t,...e){nd.logMessage("LOG",t,...e)}static info(t,...e){nd.logMessage("INFO",t,...e)}static warn(t,...e){nd.logMessage("WARN",t,...e)}static error(t,...e){nd.logMessage("ERROR",t,...e)}static debug(t,...e){nd.logMessage("DEBUG",t,...e)}}nd.currentLogLevel="WARN";var ad=function(){return ad=Object.assign||function(t){for(var e,i=1,s=arguments.length;i<s;i++)for(var r in e=arguments[i])Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t},ad.apply(this,arguments)};function od(t,e){var i={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(i[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(s=Object.getOwnPropertySymbols(t);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(t,s[r])&&(i[s[r]]=t[s[r]])}return i}function ld(t,e,i,s){return new(i||(i=Promise))(function(e,r){function n(t){try{o(s.next(t))}catch(t){r(t)}}function a(t){try{o(s.throw(t))}catch(t){r(t)}}function o(t){var s;t.done?e(t.value):(s=t.value,s instanceof i?s:new i(function(t){t(s)})).then(n,a)}o((s=s.apply(t,[])).next())})}function dd(t,e){var i,s,r,n={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;a&&(a=0,o[0]&&(n=0)),n;)try{if(i=1,s&&(r=2&o[0]?s.return:o[0]?s.throw||((r=s.return)&&r.call(s),0):s.next)&&!(r=r.call(s,o[1])).done)return r;switch(s=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return n.label++,{value:o[1],done:!1};case 5:n.label++,s=o[1],o=[0];continue;case 7:o=n.ops.pop(),n.trys.pop();continue;default:if(!((r=(r=n.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){n=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){n.label=o[1];break}if(6===o[0]&&n.label<r[1]){n.label=r[1],r=o;break}if(r&&n.label<r[2]){n.label=r[2],n.ops.push(o);break}r[2]&&n.ops.pop(),n.trys.pop();continue}o=e.call(t,n)}catch(t){o=[6,t],s=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}function cd(t,e,i){if(i||2===arguments.length)for(var s,r=0,n=e.length;r<n;r++)!s&&r in e||(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))}"function"==typeof SuppressedError&&SuppressedError;var ud=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;for(var hd,fd=[],gd=0;gd<256;++gd)fd.push((gd+256).toString(16).slice(1));function md(t,e=0){return(fd[t[e+0]]+fd[t[e+1]]+fd[t[e+2]]+fd[t[e+3]]+"-"+fd[t[e+4]]+fd[t[e+5]]+"-"+fd[t[e+6]]+fd[t[e+7]]+"-"+fd[t[e+8]]+fd[t[e+9]]+"-"+fd[t[e+10]]+fd[t[e+11]]+fd[t[e+12]]+fd[t[e+13]]+fd[t[e+14]]+fd[t[e+15]]).toLowerCase()}var pd=new Uint8Array(16);function vd(){if(!hd&&!(hd="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return hd(pd)}function yd(t,e,i){function s(t,s,r,n){var a;if("string"==typeof t&&(t=function(t){t=unescape(encodeURIComponent(t));for(var e=[],i=0;i<t.length;++i)e.push(t.charCodeAt(i));return e}(t)),"string"==typeof s&&(s=function(t){if(!function(t){return"string"==typeof t&&ud.test(t)}(t))throw TypeError("Invalid UUID");var e,i=new Uint8Array(16);return i[0]=(e=parseInt(t.slice(0,8),16))>>>24,i[1]=e>>>16&255,i[2]=e>>>8&255,i[3]=255&e,i[4]=(e=parseInt(t.slice(9,13),16))>>>8,i[5]=255&e,i[6]=(e=parseInt(t.slice(14,18),16))>>>8,i[7]=255&e,i[8]=(e=parseInt(t.slice(19,23),16))>>>8,i[9]=255&e,i[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,i[11]=e/4294967296&255,i[12]=e>>>24&255,i[13]=e>>>16&255,i[14]=e>>>8&255,i[15]=255&e,i}(s)),16!==(null===(a=s)||void 0===a?void 0:a.length))throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var o=new Uint8Array(16+t.length);if(o.set(s),o.set(t,s.length),(o=i(o))[6]=15&o[6]|e,o[8]=63&o[8]|128,r){n=n||0;for(var l=0;l<16;++l)r[n+l]=o[l];return r}return md(o)}try{s.name=t}catch(t){}return s.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",s.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",s}function Ed(t){return 14+(t+64>>>9<<4)+1}function Td(t,e){var i=(65535&t)+(65535&e);return(t>>16)+(e>>16)+(i>>16)<<16|65535&i}function Sd(t,e,i,s,r,n){return Td((a=Td(Td(e,t),Td(s,n)))<<(o=r)|a>>>32-o,i);var a,o}function bd(t,e,i,s,r,n,a){return Sd(e&i|~e&s,t,e,r,n,a)}
vendor: 4,350 bytes, line 1
1function Ad(t,e,i,s,r,n,a){return Sd(e&s|i&~s,t,e,r,n,a)}function kd(t,e,i,s,r,n,a){return Sd(e^i^s,t,e,r,n,a)}function Ld(t,e,i,s,r,n,a){return Sd(i^(e|~s),t,e,r,n,a)}yd("v3",48,function(t){if("string"==typeof t){var e=unescape(encodeURIComponent(t));t=new Uint8Array(e.length);for(var i=0;i<e.length;++i)t[i]=e.charCodeAt(i)}return function(t){for(var e=[],i=32*t.length,s="0123456789abcdef",r=0;r<i;r+=8){var n=t[r>>5]>>>r%32&255,a=parseInt(s.charAt(n>>>4&15)+s.charAt(15&n),16);e.push(a)}return e}(function(t,e){t[e>>5]|=128<<e%32,t[Ed(e)-1]=e;for(var i=1732584193,s=-271733879,r=-1732584194,n=271733878,a=0;a<t.length;a+=16){var o=i,l=s,d=r,c=n;i=bd(i,s,r,n,t[a],7,-680876936),n=bd(n,i,s,r,t[a+1],12,-389564586),r=bd(r,n,i,s,t[a+2],17,606105819),s=bd(s,r,n,i,t[a+3],22,-1044525330),i=bd(i,s,r,n,t[a+4],7,-176418897),n=bd(n,i,s,r,t[a+5],12,1200080426),r=bd(r,n,i,s,t[a+6],17,-1473231341),s=bd(s,r,n,i,t[a+7],22,-45705983),i=bd(i,s,r,n,t[a+8],7,1770035416),n=bd(n,i,s,r,t[a+9],12,-1958414417),r=bd(r,n,i,s,t[a+10],17,-42063),s=bd(s,r,n,i,t[a+11],22,-1990404162),i=bd(i,s,r,n,t[a+12],7,1804603682),n=bd(n,i,s,r,t[a+13],12,-40341101),r=bd(r,n,i,s,t[a+14],17,-1502002290),i=Ad(i,s=bd(s,r,n,i,t[a+15],22,1236535329),r,n,t[a+1],5,-165796510),n=Ad(n,i,s,r,t[a+6],9,-1069501632),r=Ad(r,n,i,s,t[a+11],14,643717713),s=Ad(s,r,n,i,t[a],20,-373897302),i=Ad(i,s,r,n,t[a+5],5,-701558691),n=Ad(n,i,s,r,t[a+10],9,38016083),r=Ad(r,n,i,s,t[a+15],14,-660478335),s=Ad(s,r,n,i,t[a+4],20,-405537848),i=Ad(i,s,r,n,t[a+9],5,568446438),n=Ad(n,i,s,r,t[a+14],9,-1019803690),r=Ad(r,n,i,s,t[a+3],14,-187363961),s=Ad(s,r,n,i,t[a+8],20,1163531501),i=Ad(i,s,r,n,t[a+13],5,-1444681467),n=Ad(n,i,s,r,t[a+2],9,-51403784),r=Ad(r,n,i,s,t[a+7],14,1735328473),i=kd(i,s=Ad(s,r,n,i,t[a+12],20,-1926607734),r,n,t[a+5],4,-378558),n=kd(n,i,s,r,t[a+8],11,-2022574463),r=kd(r,n,i,s,t[a+11],16,1839030562),s=kd(s,r,n,i,t[a+14],23,-35309556),i=kd(i,s,r,n,t[a+1],4,-1530992060),n=kd(n,i,s,r,t[a+4],11,1272893353),r=kd(r,n,i,s,t[a+7],16,-155497632),s=kd(s,r,n,i,t[a+10],23,-1094730640),i=kd(i,s,r,n,t[a+13],4,681279174),n=kd(n,i,s,r,t[a],11,-358537222),r=kd(r,n,i,s,t[a+3],16,-722521979),s=kd(s,r,n,i,t[a+6],23,76029189),i=kd(i,s,r,n,t[a+9],4,-640364487),n=kd(n,i,s,r,t[a+12],11,-421815835),r=kd(r,n,i,s,t[a+15],16,530742520),i=Ld(i,s=kd(s,r,n,i,t[a+2],23,-995338651),r,n,t[a],6,-198630844),n=Ld(n,i,s,r,t[a+7],10,1126891415),r=Ld(r,n,i,s,t[a+14],15,-1416354905),s=Ld(s,r,n,i,t[a+5],21,-57434055),i=Ld(i,s,r,n,t[a+12],6,1700485571),n=Ld(n,i,s,r,t[a+3],10,-1894986606),r=Ld(r,n,i,s,t[a+10],15,-1051523),s=Ld(s,r,n,i,t[a+1],21,-2054922799),i=Ld(i,s,r,n,t[a+8],6,1873313359),n=Ld(n,i,s,r,t[a+15],10,-30611744),r=Ld(r,n,i,s,t[a+6],15,-1560198380),s=Ld(s,r,n,i,t[a+13],21,1309151649),i=Ld(i,s,r,n,t[a+4],6,-145523070),n=Ld(n,i,s,r,t[a+11],10,-1120210379),r=Ld(r,n,i,s,t[a+2],15,718787259),s=Ld(s,r,n,i,t[a+9],21,-343485551),i=Td(i,o),s=Td(s,l),r=Td(r,d),n=Td(n,c)}return[i,s,r,n]}(function(t){if(0===t.length)return[];for(var e=8*t.length,i=new Uint32Array(Ed(e)),s=0;s<e;s+=8)i[s>>5]|=(255&t[s/8])<<s%32;return i}(t),8*t.length))});var Id={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function wd(t,e,i){if(Id.randomUUID&&!t)return Id.randomUUID();var s=(t=t||{}).random||(t.rng||vd)();return s[6]=15&s[6]|64,s[8]=63&s[8]|128,md(s)}function Rd(t,e,i,s){switch(t){case 0:return e&i^~e&s;case 1:case 3:return e^i^s;case 2:return e&i^e&s^i&s}}function _d(t,e){return t<<e|t>>>32-e}yd("v5",80,function(t){var e=[1518500249,1859775393,2400959708,3395469782],i=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof t){var s=unescape(encodeURIComponent(t));t=[];for(var r=0;r<s.length;++r)t.push(s.charCodeAt(r))}else Array.isArray(t)||(t=Array.prototype.slice.call(t));t.push(128);for(var n=t.length/4+2,a=Math.ceil(n/16),o=new Array(a),l=0;l<a;++l){for(var d=new Uint32Array(16),c=0;c<16;++c)d[c]=t[64*l+4*c]<<24|t[64*l+4*c+1]<<16|t[64*l+4*c+2]<<8|t[64*l+4*c+3];o[l]=d}o[a-1][14]=8*(t.length-1)/Math.pow(2,32),o[a-1][14]=Math.floor(o[a-1][14]),o[a-1][15]=8*(t.length-1)&4294967295;for(var u=0;u<a;++u){for(var h=new Uint32Array(80),f=0;f<16;++f)h[f]=o[u][f];for(var g=16;g<80;++g)h[g]=_d(h[g-3]^h[g-8]^h[g-14]^h[g-16],1);for(var m=i[0],p=i[1],v=i[2],y=i[3],E=i[4],T=0;T<80;++T){var S=Math.floor(T/20),b=_d(m,5)+Rd(S,p,v,y)+E+e[S]+h[T]>>>0;
1E=y,y=v,v=_d(p,30)>>>0,p=m,m=b}i[0]=i[0]+m>>>0,i[1]=i[1]+p>>>0,i[2]=i[2]+v>>>0,i[3]=i[3]+y>>>0,i[4]=i[4]+E>>>0}return[i[0]>>24&255,i[0]>>16&255,i[0]>>8&255,255&i[0],i[1]>>24&255,i[1]>>16&255,i[1]>>8&255,255&i[1],i[2]>>24&255,i[2]>>16&255,i[2]>>8&255,255&i[2],i[3]>>24&255,i[3]>>16&255,i[3]>>8&255,255&i[3],i[4]>>24&255,i[4]>>16&255,i[4]>>8&255,255&i[4]]});var Dd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function Pd(){var t,e={},i=[],s=[],r=[],n=function(t,i){null!=i&&""!==i&&(e[t]=i)};return{add:n,addDict:function(t){for(var e in t)Object.prototype.hasOwnProperty.call(t,e)&&n(e,t[e])},addJson:function(t,e,r){if(r&&Cd(r)){var n={keyIfEncoded:t,keyIfNotEncoded:e,json:r};s.push(n),i.push(n)}},addContextEntity:function(t){r.push(t)},getPayload:function(){return e},getJson:function(){return i},withJsonProcessor:function(e){t=e},build:function(){return null==t||t(this,s,r),e}}}function xd(t){return function(e,i,s){for(var r=function(i,s,r){var n=JSON.stringify(i);t?e.add(s,function(t){if(!t)return t;var e=function(t){var e,i,s,r,n,a=0,o=0,l=[];if(!t)return t;t=unescape(encodeURIComponent(t));do{e=(n=t.charCodeAt(a++)<<16|t.charCodeAt(a++)<<8|t.charCodeAt(a++))>>18&63,i=n>>12&63,s=n>>6&63,r=63&n,l[o++]=Dd.charAt(e)+Dd.charAt(i)+Dd.charAt(s)+Dd.charAt(r)}while(a<t.length);var d=l.join(""),c=t.length%3;return(c?d.slice(0,c-3):d)+"===".slice(c||3)}(t);return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(n)):e.add(r,n)},n=function(i,s){var r=i||function(){var i=e.getPayload();if(t?i.cx:i.co)return JSON.parse(t?function(t){if(!t)return t;switch(4-t.length%4){case 2:t+="==";break;case 3:t+="="}return function(t){var e,i,s,r,n,a,o=0,l=0,d=[];if(!t)return t;t+="";do{e=(a=Dd.indexOf(t.charAt(o++))<<18|Dd.indexOf(t.charAt(o++))<<12|(r=Dd.indexOf(t.charAt(o++)))<<6|(n=Dd.indexOf(t.charAt(o++))))>>16&255,i=a>>8&255,s=255&a,d[l++]=64===r?String.fromCharCode(e):64===n?String.fromCharCode(e,i):String.fromCharCode(e,i,s)}while(o<t.length);return function(t){return decodeURIComponent(t.split("").map(function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)}).join(""))}(d.join("").replace(/\0+$/,""))}(t.replace(/-/g,"+").replace(/_/g,"/"))}(i.cx):i.co)}();return r?r.data=r.data.concat(s.data):r=s,r},a=void 0,o=0,l=i;o<l.length;o++){var d=l[o];"cx"===d.keyIfEncoded?a=n(a,d.json):r(d.json,d.keyIfEncoded,d.keyIfNotEncoded)}i.length=0,s.length&&(a=n(a,{schema:"iglu:com.snowplowanalytics.snowplow/contexts/jsonschema/1-0-0",data:cd([],s,!0)}),s.length=0),a&&r(a,"cx","co")}}function Cd(t){if(!Od(t))return!1;for(var e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!0;return!1}function Od(t){return null!=t&&(t.constructor==={}.constructor||t.constructor===[].constructor)}var Md,Fd="Snowplow: ";!function(t){t[t.none=0]="none",t[t.error=1]="error",t[t.warn=2]="warn",t[t.debug=3]="debug",t[t.info=4]="info"}(Md||(Md={}));var Nd=function(t){return void 0===t&&(t=Md.warn),{setLogLevel:function(e){t=Md[e]?e:Md.warn},warn:function(e,i){for(var s=[],r=2;r<arguments.length;r++)s[r-2]=arguments[r];if(t>=Md.warn&&"undefined"!=typeof console){var n=Fd+e;i?console.warn.apply(console,cd([n+"\n",i],s,!1)):console.warn.apply(console,cd([n],s,!1))}},error:function(e,i){for(var s=[],r=2;r<arguments.length;r++)s[r-2]=arguments[r];if(t>=Md.error&&"undefined"!=typeof console){var n=Fd+e+"\n";i?console.error.apply(console,cd([n+"\n",i],s,!1)):console.error.apply(console,cd([n],s,!1))}},debug:function(e){for(var i=[],s=1;s<arguments.length;s++)i[s-1]=arguments[s];t>=Md.debug&&"undefined"!=typeof console&&console.debug.apply(console,cd([Fd+e],i,!1))},info:function(e){for(var i=[],s=1;s<arguments.length;s++)i[s-1]=arguments[s];t>=Md.info&&"undefined"!=typeof console&&console.info.apply(console,cd([Fd+e],i,!1))}}}();function Ud(t){for(var e,i=[],s=1;s<arguments.length;s++)i[s-1]=arguments[s];return null!==(e=null==t?void 0:t.map(function(t){if("function"!=typeof t)return t;try{return t.apply(void 0,i)}catch(t){return}}).filter(Boolean))&&void 0!==e?e:[]}function Bd(t){var e=t.split(".");return!!(e&&e.length>1)&&function(t){if("*"===t[0]||"*"===t[1])return!1;if(t.slice(2).length>0){for(var e=!1,i=0,s=t.slice(2);i<s.length;i++)if("*"===s[i])e=!0;else if(e)return!1;return!0}return 2==t.length}(e)}function $d(t){var e=new RegExp("^iglu:((?:(?:[a-zA-Z0-9-_]+|\\*).)+(?:[a-zA-Z0-9-_]+|\\*))/([a-zA-Z0-9-_.]+|\\*)/jsonschema/([1-9][0-9]*|\\*)-(0|[1-9][0-9]*|\\*)-(0|[1-9][0-9]*|\\*)$").exec(t);if(null!==e&&Bd(e[1]))return e.slice(1,6)}function Gd(t){var e=$d(t);if(e){var i=e[0];return 5===e.length&&Bd(i)}return!1}function Vd(t){return function(t){return Array.isArray(t)&&t.every(function(t){return"string"==typeof t})}(t)?t.every(function(t){return Gd(t)}):"string"==typeof t&&Gd(t)}function Kd(t){var e=t;return!!(Cd(e)&&"schema"in e&&"data"in e)&&"string"==typeof e.schema&&"object"==typeof e.data}function Hd(t){return"function"==typeof t&&t.length<=1}
1function jd(t){return Hd(t)||Kd(t)}function qd(t){return!(!Array.isArray(t)||2!==t.length)&&(Array.isArray(t[1])?Hd(t[0])&&t[1].every(jd):Hd(t[0])&&jd(t[1]))}function Yd(t){return!(!Array.isArray(t)||2!==t.length)&&!!function(t){var e=t,i=0;if(null!=t&&"object"==typeof t&&!Array.isArray(t)){if(Object.prototype.hasOwnProperty.call(e,"accept")){if(!Vd(e.accept))return!1;i+=1}if(Object.prototype.hasOwnProperty.call(e,"reject")){if(!Vd(e.reject))return!1;i+=1}return i>0&&i<=2}return!1}(t[0])&&(Array.isArray(t[1])?t[1].every(jd):jd(t[1]))}function Wd(t){return qd(t)||Yd(t)}function zd(t,e){if(!Gd(t))return!1;var i=$d(t),s=function(t){var e=new RegExp("^iglu:([a-zA-Z0-9-_.]+)/([a-zA-Z0-9-_]+)/jsonschema/([1-9][0-9]*)-(0|[1-9][0-9]*)-(0|[1-9][0-9]*)$").exec(t);if(null!==e)return e.slice(1,6)}(e);if(i&&s){if(!function(t,e){var i=e.split("."),s=t.split(".");if(i&&s){if(i.length!==s.length)return!1;for(var r=0;r<s.length;r++)if(!Xd(i[r],s[r]))return!1;return!0}return!1}(i[0],s[0]))return!1;for(var r=1;r<5;r++)if(!Xd(i[r],s[r]))return!1;return!0}return!1}function Xd(t,e){return t&&e&&"*"===t||t===e}function Qd(t){return Array.isArray(t)?t:Array.of(t)}function Jd(t,e,i,s){var r,n=Qd(t).map(function(t){var r=function(t,e,i,s){if(Kd(t))return[t];if(Hd(t)){var r=function(t,e,i,s){var r=void 0;try{return r=t({event:e.getPayload(),eventType:i,eventSchema:s}),Array.isArray(r)&&r.every(Kd)||Kd(r)?r:void 0}catch(t){r=void 0}return r}(t,e,i,s);if(Kd(r))return[r];if(Array.isArray(r))return r}}(t,e,i,s);if(r&&0!==r.length)return r});return(r=[]).concat.apply(r,n.filter(function(t){return null!=t&&t.filter(Boolean)}))}function Zd(t,e){return"function"==typeof t?t===e:JSON.stringify(t)===JSON.stringify(e)}function tc(t,e){if(Wd(t)){if(!Wd(e))return!1;var i=t[0],s=t[1],r=e[0],n=e[1];return!!Zd(i,r)&&(Array.isArray(s)?!!Array.isArray(n)&&s.length===n.length&&s.reduce(function(t,e,i){return t&&Zd(e,n[i])},!0):!Array.isArray(n)&&Zd(s,n))}return!!jd(t)&&!!jd(e)&&Zd(t,e)}function ec(t){void 0===t&&(t={});var e=!0,i=t.base64,s=t.corePlugins,r=t.callback,n=null!=s?s:[],a=function(t,i,s){var r=function(t){return{addPluginContexts:function(e){var i=e?cd([],e,!0):[];return t.forEach(function(t){try{t.contexts&&i.push.apply(i,t.contexts())}catch(t){Nd.error("Error adding plugin contexts",t)}}),i}}}(i),n=function(){var t=[],e=[],i={},s={},r=function(r){var n=function(t){for(var e=0,i=t.getJson();e<i.length;e++){var s=i[e];if("ue_px"===s.keyIfEncoded&&"object"==typeof s.json.data){var r=s.json.data.schema;if("string"==typeof r)return r}}return""}(r),a=function(t){var e=t.getPayload().e;return"string"==typeof e?e:""}(r),o=[],l=Jd(t.concat(Object.values(i)),r,a,n);o.push.apply(o,l);var d=function(t,e,i,s){var r,n=Qd(t).map(function(t){var r=function(t,e,i,s){if(qd(t)){var r=t[0],n=!1;try{n=r({event:e.getPayload(),eventType:i,eventSchema:s})}catch(t){n=!1}if(!0===n)return Jd(t[1],e,i,s)}else if(Yd(t)&&function(t,e){var i=0,s=0,r=t.accept;Array.isArray(r)?t.accept.some(function(t){return zd(t,e)})&&s++:"string"==typeof r&&zd(r,e)&&s++;var n=t.reject;return Array.isArray(n)?t.reject.some(function(t){return zd(t,e)})&&i++:"string"==typeof n&&zd(n,e)&&i++,s>0&&0===i}(t[0],s))return Jd(t[1],e,i,s);return[]}(t,e,i,s);if(r&&0!==r.length)return r});return(r=[]).concat.apply(r,n.filter(function(t){return null!=t&&t.filter(Boolean)}))}(e.concat(Object.values(s)),r,a,n);return o.push.apply(o,d),o};return{getGlobalPrimitives:function(){return t.concat(Object.values(i))},getConditionalProviders:function(){return e.concat(Object.values(s))},addGlobalContexts:function(r){if(Array.isArray(r)){for(var n=[],a=[],o=0,l=r;o<l.length;o++)Wd(u=l[o])?n.push(u):jd(u)&&a.push(u);t=t.concat(a),e=e.concat(n)}else for(var d=0,c=Object.entries(r);d<c.length;d++){var u,h=c[d],f=h[0];Wd(u=h[1])?s[f]=u:jd(u)&&(i[f]=u)}},clearGlobalContexts:function(){e=[],t=[],s={},i={}},removeGlobalContexts:function(r){for(var n=function(r){"string"==typeof r?(delete s[r],delete i[r]):Wd(r)?e=e.filter(function(t){return!tc(r,t)}):jd(r)&&(t=t.filter(function(t){return!tc(r,t)}))},a=0,o=r;a<o.length;a++)n(o[a])},getApplicableContexts:function(t){return r(t)}}}(),a=t,o={};function l(t,e){o[t]=e}var d={track:function(t,l,d){if(e){t.withJsonProcessor(xd(a)),t.add("eid",wd()),t.addDict(o);var c=function(t){return null==t?{type:"dtm",value:(new Date).getTime()}:"number"==typeof t?{type:"dtm",value:t}:"ttm"===t.type?{type:"ttm",value:t.value}:{type:"dtm",value:t.value||(new Date).getTime()}}(d);t.add(c.type,c.value.toString());var u=function(t,e){var i=n.getApplicableContexts(t),s=[];return e&&e.length&&s.push.apply(s,e),i&&i.length&&s.push.apply(s,i),s}(t,r.addPluginContexts(l)),h=function(t){if(t&&t.length)return{schema:"iglu:com.snowplowanalytics.snowplow/contexts/jsonschema/1-0-0",data:t}}(u);
1if(void 0!==h&&t.addJson("cx","co",h),i.forEach(function(e){try{e.beforeTrack&&e.beforeTrack(t)}catch(t){Nd.error("Plugin beforeTrack",t)}}),!i.find(function(e){try{return e.filter&&!1===e.filter(t.build())}catch(t){return Nd.error("Plugin filter",t),!1}})){"function"==typeof s&&s(t);var f=t.build();return i.forEach(function(t){try{t.afterTrack&&t.afterTrack(f)}catch(t){Nd.error("Plugin afterTrack",t)}}),f}}else Nd.error("Track called on deactivated tracker")},addPayloadPair:l,getBase64Encoding:function(){return a},setBase64Encoding:function(t){a=t},addPayloadDict:function(t){for(var e in t)Object.prototype.hasOwnProperty.call(t,e)&&(o[e]=t[e])},resetPayloadPairs:function(t){o=Od(t)?t:{}},setTrackerVersion:function(t){l("tv",t)},setTrackerNamespace:function(t){l("tna",t)},setAppId:function(t){l("aid",t)},setPlatform:function(t){l("p",t)},setUserId:function(t){l("uid",t)},setScreenResolution:function(t,e){l("res",t+"x"+e)},setViewport:function(t,e){l("vp",t+"x"+e)},setColorDepth:function(t){l("cd",t)},setTimezone:function(t){l("tz",t)},setLang:function(t){l("lang",t)},setIpAddress:function(t){l("ip",t)},setUseragent:function(t){l("ua",t)},addGlobalContexts:function(t){n.addGlobalContexts(t)},clearGlobalContexts:function(){n.clearGlobalContexts()},removeGlobalContexts:function(t){n.removeGlobalContexts(t)}};return d}(null==i||i,n,r),o=ad(ad({},a),{addPlugin:function(t){var e,i,s=t.plugin;n.push(s),null===(e=s.logger)||void 0===e||e.call(s,Nd),null===(i=s.activateCorePlugin)||void 0===i||i.call(s,o)},deactivate:function(){n.forEach(function(t){var e;null===(e=t.deactivatePlugin)||void 0===e||e.call(t,o)}),n.length=0,e=!1}});return null==n||n.forEach(function(t){var e,i;null===(e=t.logger)||void 0===e||e.call(t,Nd),null===(i=t.activateCorePlugin)||void 0===i||i.call(t,o)}),o}function ic(t){var e=t.event,i=e.schema,s=e.data,r=Pd(),n={schema:"iglu:com.snowplowanalytics.snowplow/unstruct_event/jsonschema/1-0-0",data:{schema:i,data:s}};return r.add("e","ue"),r.addJson("ue_px","ue_pr",n),r}function sc(t){return ic({event:{schema:"iglu:com.snowplowanalytics.snowplow/link_click/jsonschema/1-0-1",data:rc({targetUrl:t.targetUrl,elementId:t.elementId,elementClasses:t.elementClasses,elementTarget:t.elementTarget,elementContent:t.elementContent})}})}function rc(t,e){void 0===e&&(e={});var i={};for(var s in t)(e[s]||null!==t[s]&&void 0!==t[s])&&(i[s]=t[s]);return i}function nc(t){var e=t.maxSize,i=void 0===e?1e3:e,s=t.events,r=cd([],void 0===s?[]:s,!0),n=function(){return Promise.resolve(r.length)};return{count:n,add:function(t){for(r.push(t);r.length>i;)r.shift();return n()},removeHead:function(t){for(var e=0;e<t;e++)r.shift();return Promise.resolve()},iterator:function(){var t=0,e=cd([],r,!0);return{next:function(){return t<e.length?Promise.resolve({value:e[t++],done:!1}):Promise.resolve({value:void 0,done:!0})}}},getAll:function(){return Promise.resolve(cd([],r,!0))},getAllPayloads:function(){return Promise.resolve(r.map(function(t){return t.payload}))}}}function ac(t){return JSON.stringify({schema:"iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4",data:t})}function oc(t){var e,i,s=t.endpoint,r=t.protocol,n=void 0===r?"https":r,a=t.port,o=t.eventMethod,l=void 0===o?"post":o,d=t.customHeaders,c=t.connectionTimeout,u=t.keepalive,h=void 0!==u&&u,f=t.postPath,g=void 0===f?"/com.snowplowanalytics.snowplow/tp2":f,m=t.useStm,p=void 0===m||m,v=t.maxPostBytes,y=void 0===v?4e4:v,E=t.credentials,T=void 0===E?"include":E,S=[],b="post"===l.toLowerCase();function A(){var t=S.reduce(function(t,e){return t+(b?e.getPOSTRequestBytesCount():e.getGETRequestBytesCount())},0);return b&&(t+=88),t}function k(){return S.length>0?S[0].getServerAnonymization():void 0}function L(){var t=s;return s.includes("://")||(t="".concat(n,"://").concat(s)),a&&(t="".concat(t,":").concat(a)),t+(b?g:"/i")}function I(t,s){w(!1),i=new AbortController,e=setTimeout(function(){var t="Request timed out";console.error(t),e=void 0,w(!1,t)},null!=c?c:5e3);var r,n=ad({headers:(r=new Headers,b&&r.append("Content-Type","application/json;
1 charset=UTF-8"),d&&Object.keys(d).forEach(function(t){r.append(t,d[t])}),k()&&r.append("SP-Anonymous","*"),r),signal:i.signal,keepalive:h,credentials:T},s);return new Request(t,n)}function w(t,s){if(void 0!==e&&(clearTimeout(e),e=void 0),void 0!==i){var r=i;i=void 0,t||r.abort(s)}}return{addEvent:function(t){return!(S.length>0&&k()!==t.getServerAnonymization()||(S.push(t),0))},getEvents:function(){return S},toRequest:function(){if(0!==S.length)return b?function(){var t=function(t){for(var e=(new Date).getTime().toString(),i=0;i<t.length;i++)t[i].stm=e;return t}(S.map(function(t){return t.getPOSTRequestBody()}));return I(L(),{method:"POST",body:ac(t)})}():function(){if(1!==S.length)throw new Error("Only one event can be sent in a GET request");return I(S[0].getGETRequestURL(L(),p),{method:"GET"})}()},countBytes:A,countEvents:function(){return S.length},isFull:function(){return b?A()>=y:S.length>=1},closeRequest:w}}function lc(t){for(var e=0,i=0;i<t.length;i++){var s=t.charCodeAt(i);s<=127?e+=1:s<=2047?e+=2:s>=55296&&s<=57343?(e+=4,i++):e+=s<65535?3:4}return e}function dc(t){var e=null,i=null,s=null,r=null;function n(){return t.payload}function a(t){return null===e&&(e=function(t){var e={co:!0,cx:!0},i=[];for(var s in t)t.hasOwnProperty(s)&&!e[s]&&i.push(s+"="+encodeURIComponent(t[s]));for(var r in e)t.hasOwnProperty(r)&&e[r]&&i.push(r+"="+encodeURIComponent(t[r]));return"?"+i.join("&")}(t)),e}function o(){var t,e;return null===i&&(t=n(),e=Object.keys(t).map(function(e){return[e,t[e]]}).reduce(function(t,e){var i=e[0],s=e[1];return t[i]=s.toString(),t},{}),i=e),i}return{getPayload:n,getServerAnonymization:function(){var e;return null!==(e=t.svrAnon)&&void 0!==e&&e},getGETRequestURL:function(t,e){var i=a(n());return e?t+i.replace("?","?stm="+(new Date).getTime()+"&"):t+i},getGETRequestBytesCount:function(){if(null===s){var t=a(n());s=lc(t)}return s},getPOSTRequestBody:o,getPOSTRequestBytesCount:function(){return null===r&&(r=lc(JSON.stringify(o()))),r}}}var cc,uc,hc={exports:{}},fc={exports:{}};cc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",uc={rotl:function(t,e){return t<<e|t>>>32-e},rotr:function(t,e){return t<<32-e|t>>>e},endian:function(t){if(t.constructor==Number)return 16711935&uc.rotl(t,8)|4278255360&uc.rotl(t,24);for(var e=0;e<t.length;e++)t[e]=uc.endian(t[e]);return t},randomBytes:function(t){for(var e=[];t>0;t--)e.push(Math.floor(256*Math.random()));return e},bytesToWords:function(t){for(var e=[],i=0,s=0;i<t.length;i++,s+=8)e[s>>>5]|=t[i]<<24-s%32;return e},wordsToBytes:function(t){for(var e=[],i=0;i<32*t.length;i+=8)e.push(t[i>>>5]>>>24-i%32&255);return e},bytesToHex:function(t){for(var e=[],i=0;i<t.length;i++)e.push((t[i]>>>4).toString(16)),e.push((15&t[i]).toString(16));return e.join("")},hexToBytes:function(t){for(var e=[],i=0;i<t.length;i+=2)e.push(parseInt(t.substr(i,2),16));return e},bytesToBase64:function(t){for(var e=[],i=0;i<t.length;i+=3)for(var s=t[i]<<16|t[i+1]<<8|t[i+2],r=0;r<4;r++)8*i+6*r<=8*t.length?e.push(cc.charAt(s>>>6*(3-r)&63)):e.push("=");return e.join("")},base64ToBytes:function(t){t=t.replace(/[^A-Z0-9+\/]/gi,"");for(var e=[],i=0,s=0;i<t.length;s=++i%4)0!=s&&e.push((cc.indexOf(t.charAt(i-1))&Math.pow(2,-2*s+8)-1)<<2*s|cc.indexOf(t.charAt(i))>>>6-2*s);return e}},fc.exports=uc;var gc=fc.exports,mc={utf8:{stringToBytes:function(t){return mc.bin.stringToBytes(unescape(encodeURIComponent(t)))},bytesToString:function(t){return decodeURIComponent(escape(mc.bin.bytesToString(t)))}},bin:{stringToBytes:function(t){for(var e=[],i=0;i<t.length;i++)e.push(255&t.charCodeAt(i));return e},bytesToString:function(t){for(var e=[],i=0;i<t.length;i++)e.push(String.fromCharCode(t[i]));return e.join("")}}},pc=mc;!function(){var t=gc,e=pc.utf8,i=pc.bin,s=function(s,r){var n=t.wordsToBytes(function(i){i.constructor==String?i=e.stringToBytes(i):"undefined"!=typeof Buffer&&"function"==typeof Buffer.isBuffer&&Buffer.isBuffer(i)?i=Array.prototype.slice.call(i,0):Array.isArray(i)||(i=i.toString());var s=t.bytesToWords(i),r=8*i.length,n=[],a=1732584193,o=-271733879,l=-1732584194,d=271733878,c=-1009589776;s[r>>5]|=128<<24-r%32,s[15+(r+64>>>9<<4)]=r;for(var u=0;u<s.length;u+=16){for(var h=a,f=o,g=l,m=d,p=c,v=0;v<80;v++){if(v<16)n[v]=s[u+v];else{var y=n[v-3]^n[v-8]^n[v-14]^n[v-16];n[v]=y<<1|y>>>31}var E=(a<<5|a>>>27)+c+(n[v]>>>0)+(v<20?1518500249+(o&l|~o&d):v<40?1859775393+(o^l^d):v<60?(o&l|o&d|l&d)-1894007588:(o^l^d)-899497514);c=d,d=l,l=o<<30|o>>>2,o=a,a=E}a+=h,o+=f,l+=g,d+=m,c+=p}return[a,o,l,d,c]}(s));return r&&r.asBytes?n:r&&r.asString?i.bytesToString(n):t.bytesToHex(n)};s._blocksize=16,s._digestsize=20,hc.exports=s}();var vc=function(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}
1(hc.exports);function yc(t){try{var e=window.localStorage;return e.removeItem(t),e.removeItem(t+".expires"),!0}catch(t){return!1}}function Ec(t){try{return window.sessionStorage.getItem(t)}catch(t){return}}var Tc={sessionId:!0,sourceId:!0,sourcePlatform:!1,userId:!1,reason:!1};function Sc(t){return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,"")}function bc(t){return Number.isInteger&&Number.isInteger(t)||"number"==typeof t&&isFinite(t)&&Math.floor(t)===t}function Ac(t){if(!(i=t)||"string"!=typeof i.valueOf()){t=t.text||"";var e=document.getElementsByTagName("title");e&&null!=e[0]&&(t=e[0].text)}var i;return t}function kc(t){var e=new RegExp("^(?:(?:https?|ftp):)/*(?:[^@]+@)?([^:/#]+)").exec(t);return e?e[1]:t}function Lc(t){var e=t.length;return"."===t.charAt(--e)&&(t=t.slice(0,e)),"*."===t.slice(0,2)&&(t=t.slice(1)),t}function Ic(t){var e=window,i=Rc("referrer",e.location.href)||Rc("referer",e.location.href);if(i)return i;if(t)return t;try{if(e.top)return e.top.document.referrer;if(e.parent)return e.parent.document.referrer}catch(t){}return document.referrer}function wc(t,e,i,s){return t.addEventListener?(t.addEventListener(e,i,s),!0):t.attachEvent?t.attachEvent("on"+e,i):void(t["on"+e]=i)}function Rc(t,e){var i=new RegExp("^[^#]*[?&]"+t+"=([^&#]*)").exec(e);return i?decodeURIComponent(i[1].replace(/\+/g," ")):null}function _c(t,e,i,s,r){Pc(t,"",-1,e,i,s,r)}function Dc(t){for(var e=document.cookie.split("; "),i=[],s=0;s<e.length;s++)e[s].substring(0,t.length)===t&&i.push(e[s]);return i}function Pc(t,e,i,s,r,n,a){return arguments.length>1?document.cookie=t+"="+encodeURIComponent(null!=e?e:"")+(i?"; Expires="+new Date(+new Date+1e3*i).toUTCString():"")+(s?"; Path="+s:"")+(r?"; Domain="+r:"")+(n?"; SameSite="+n:"")+(a?"; Secure":""):decodeURIComponent((("; "+document.cookie).split("; "+t+"=")[1]||"").split(";")[0])}function xc(t){if(null==t||"object"!=typeof t||Array.isArray(t))return function(){return!0};var e=Object.prototype.hasOwnProperty.call(t,"allowlist"),i=function(t){var e={},i=t.allowlist||t.denylist;if(i){Array.isArray(i)||(i=[i]);for(var s=0;s<i.length;s++)e[i[s]]=!0}return e}(t);return function(t,e){return t.hasOwnProperty("filter")&&t.filter?t.filter:e}(t,function(t){return function(t,e){for(var i=0,s=Cc(t);i<s.length;i++)if(e[s[i]])return!0;return!1}(t,i)===e})}function Cc(t){return t.className.match(/\S+/g)||[]}function Oc(t,e){var i,s=null!==(i=t.eventStore)&&void 0!==i?i:function(t){var e=t.trackerId,i=t.maxLocalStorageQueueSize,s=void 0===i?1e3:i,r=t.useLocalStorage,n=void 0===r||r,a="snowplowOutQueue_".concat(e),o=function(){if(!n)return nc({maxSize:s});try{var t=window.localStorage.getItem(a),e=t?JSON.parse(t):[];return nc({maxSize:s,events:e})}catch(t){return console.error("Failed to access localStorage when initializing event store:",t),nc({maxSize:s})}}(),l=o.getAll,d=o.getAllPayloads,c=o.add,u=o.count,h=o.iterator,f=o.removeHead;function g(){return n?l().then(function(t){try{window.localStorage.setItem(a,JSON.stringify(t))}catch(t){console.error("Failed to persist events to localStorage:",t)}}):Promise.resolve()}return{count:u,add:function(t){return c(t),g().then(u)},removeHead:function(t){return f(t),g()},iterator:h,getAll:l,getAllPayloads:d,setUseLocalStorage:function(t){n=t}}}(t);t.eventStore=s;var r=function(t){var e=t.endpoint,i=t.eventMethod,s=void 0===i?"post":i,r=t.postPath,n=t.protocol,a=t.port,o=t.maxPostBytes,l=void 0===o?4e4:o,d=t.maxGetBytes,c=t.bufferSize,u=void 0===c?1:c,h=t.customHeaders,f=t.serverAnonymization,g=t.connectionTimeout,m=t.keepalive,p=t.cookieExtensionService,v=t.idService,y=t.dontRetryStatusCodes,E=void 0===y?[]:y,T=t.retryStatusCodes,S=void 0===T?[]:T,b=t.retryFailedRequests,A=void 0===b||b,k=t.onRequestFailure,L=t.onRequestSuccess,I=t.customFetch,w=void 0===I?fetch:I,R=t.useStm,_=t.eventStore,D=void 0===_?nc({}):_,P=t.credentials;p=p||v;var x=!1,C=!1,O="post"===s.toLowerCase();function M(t,e){void 0!==k&&setTimeout(function(){try{null==k||k(t,e)}catch(t){Nd.error("Error in onRequestFailure",t)}},0)}function F(t){return ld(this,0,void 0,function(){var e,i,s,r,n,a;return dd(this,function(o){switch(o.label){case 0:if(void 0===(e=t.toRequest()))throw new Error("Empty batch");i=t.getEvents().map(function(t){return t.getPayload()}),o.label=1;case 1:return o.trys.push([1,4,,5]),[4,w(e)];case 2:return[4,(s=o.sent()).text()];
1case 3:return o.sent(),t.closeRequest(!0),s.ok?(function(t,e){void 0!==L&&setTimeout(function(){try{null==L||L(t,e)}catch(t){Nd.error("Error in onRequestSuccess",t)}},0)}(i,s),[2,{success:!0,retry:!1,status:s.status}]):(l=s.status,r=!(l>=200&&l<300||!A||!S.includes(l)&&E.includes(l)),M({events:i,status:s.status,message:s.statusText,willRetry:r},s),[2,{success:!1,retry:r,status:s.status}]);case 4:return n=o.sent(),t.closeRequest(!1),a="string"==typeof n?n:n?n.message:"Unknown error",M({events:i,message:a,willRetry:!0}),[2,{success:!1,retry:!0}];case 5:return[2]}var l})})}function N(){return oc({endpoint:e,protocol:n,port:a,eventMethod:s,customHeaders:h,connectionTimeout:g,keepalive:m,maxPostBytes:l,useStm:R,credentials:P,postPath:r})}function U(){return ld(this,0,void 0,function(){var t;return dd(this,function(e){switch(e.label){case 0:return!p||x?[3,2]:(x=!0,t=new Request(p,{method:"GET"}),[4,w(t)]);case 1:e.sent(),e.label=2;case 2:return[2]}})})}function B(){return ld(this,0,void 0,function(){var t;return dd(this,function(e){switch(e.label){case 0:if(C)return[3,5];C=!0,e.label=1;case 1:return e.trys.push([1,3,4,5]),[4,$()];case 2:return e.sent(),[3,5];case 3:return t=e.sent(),Nd.error("Error sending events",t),[3,5];case 4:return C=!1,[7];case 5:return[2]}})})}function $(){return ld(this,0,void 0,function(){var t,e,i,s,r,n,a,o,l;return dd(this,function(d){switch(d.label){case 0:return[4,U()];case 1:d.sent(),t=N(),e=D.iterator(),d.label=2;case 2:return t.isFull()?[3,4]:[4,e.next()];case 3:return i=d.sent(),s=i.value,i.done||void 0===s?[3,4]:(r=dc(s),t.addEvent(r)?[3,2]:[3,4]);case 4:return 0===t.countEvents()?[2]:[4,F(t)];case 5:return n=d.sent(),a=n.success,o=n.retry,l=n.status,!a&&o?[3,7]:(a||Nd.error("Status ".concat(l,", will not retry.")),[4,D.removeHead(t.countEvents())]);case 6:d.sent(),d.label=7;case 7:return a?[4,$()]:[3,9];case 8:d.sent(),d.label=9;case 9:return[2]}})})}return E=E.concat([400,401,403,410,422]),{flush:B,input:function(t){return ld(this,0,void 0,function(){var e,i,s;return dd(this,function(r){switch(r.label){case 0:return e=function(t){var e=t.svrAnon;return{payload:t.payload,svrAnon:void 0!==e&&e}}({payload:t,svrAnon:f}),n=i=dc(e),c=function(t,e){return Nd.warn("Event ("+t+"B) too big, max is "+e)},(O?((o=(a=n.getPOSTRequestBytesCount()+88)>l)&&c(a,l),o):void 0!==d&&((o=(a=n.getGETRequestBytesCount())>d)&&c(a,d),o))?((s=N()).addEvent(i),[4,F(s)]):[3,2];case 1:return r.sent(),[3,5];case 2:return[4,D.add(e)];case 3:return r.sent()>=u?[4,B()]:[3,5];case 4:r.sent(),r.label=5;case 5:return[2]}var n,a,o,c})})},setCollectorUrl:function(t){e=t},setAnonymousTracking:function(t){f=t},setBufferSize:function(t){u=t}}}(t);return e.bufferFlushers.push(r.flush),{enqueueRequest:r.input,executeQueue:r.flush,setAnonymousTracking:r.setAnonymousTracking,setCollectorUrl:r.setCollectorUrl,setBufferSize:r.setBufferSize,setUseLocalStorage:function(t){s.hasOwnProperty("setUseLocalStorage")&&s.setUseLocalStorage(t)}}}function Mc(t,e,i){var s,r,n;return"translate.googleusercontent.com"===t?(""===i&&(i=e),t=kc(e=null!==(r=e,s=(n=new RegExp("^(?:https?|ftp)(?::/*(?:[^?]+))([?][^#]+)").exec(r))&&(null==n?void 0:n.length)>1?Rc("u",n[1]):null)&&void 0!==s?s:"")):"cc.bingj.com"!==t&&"webcache.googleusercontent.com"!==t||(t=kc(e=document.links[0].href)),[t,e,i]}function Fc(t,e){void 0===e&&(e={memorizedVisitCount:1});var i=e.memorizedVisitCount;Gc(t)?(t[7]=t[6],t[5]=t[4],t[3]++):t[3]=i;var s=wd();return t[6]=s,t[10]=0,t[8]="",t[9]=void 0,s}function Nc(t){t[4]=Math.round((new Date).getTime()/1e3)}function Uc(t,e,i){var s=t[9];return{userId:i?"00000000-0000-0000-0000-000000000000":t[1],sessionId:t[6],eventIndex:t[10],sessionIndex:t[3],previousSessionId:i?null:t[7]||null,storageMechanism:"localStorage"==e?"LOCAL_STORAGE":"COOKIE_1",firstEventId:t[8]||null,firstEventTimestamp:s?new Date(s).toISOString():null}}function Bc(t){return t[6]}function $c(t){return t[3]}function Gc(t){return"0"===t[0]}function Vc(t){return t[10]}var Kc,Hc=!1,jc=null;function qc(){return"ResizeObserver"in window?(Kc||(Kc=Yc()),function(){if(!Hc&&document&&document.body&&document.documentElement){Hc=!0;var t=new ResizeObserver(function(){jc||(jc=requestAnimationFrame(function(){jc=null,Kc=Yc()}))});t.observe(document.body),t.observe(document.documentElement)}}(),Kc):Yc()}function Yc(){return{viewport:Wc(),documentSize:(t=document.documentElement,e=document.body,i=e?Math.max(e.offsetHeight,e.scrollHeight):0,zc(Math.max(t.clientWidth,t.offsetWidth,t.scrollWidth),Math.max(t.clientHeight,t.offsetHeight,t.scrollHeight,i))),resolution:zc(screen.width,screen.height),colorDepth:screen.colorDepth,devicePixelRatio:window.devicePixelRatio,cookiesEnabled:window.navigator.cookieEnabled,online:window.navigator.onLine,browserLanguage:window.navigator.language||window.navigator.userLanguage,documentLanguage:document.documentElement.lang,webdriver:window.navigator.webdriver,deviceMemory:window.navigator.deviceMemory,hardwareConcurrency:Math.floor(window.navigator.hardwareConcurrency)||void 0};var t,e,i}function Wc(){var t,e;if("innerWidth"in window)t=window.innerWidth,e=window.innerHeight;else{var i=document.documentElement||document.body;t=i.clientWidth,e=i.clientHeight}return zc(Math.max(0,t),Math.max(0,e))}function zc(t,e){return isNaN(t)||isNaN(e)?null:Math.floor(t)+"x"+Math.floor(e)}var Xc=function(){var t={};function e(e){return t[e]||(t[e]=function(t){var e,i,s,r=!0;function n(){if(void 0!==e&&(clearTimeout(e),e=void 0),!r&&(r=!0,void 0!==i)){var s=i[0],n=i[1],a=i[2],o=i[3],l=i[4],d=i[5];Pc(t,s,n,a,o,l,d)}}return{getValue:function(){var e;return i&&(!s||s>new Date)&&null!==(e=i[0])&&void 0!==e?e:Pc(t)},setValue:function(t,a,o,l,d,c){return i=[t,a,o,l,d,c],r=!1,void 0===e&&(e=setTimeout(function(){e=void 0,n()},10)),s=new Date(Date.now()+1e3*Math.min(.05,null!=a?a:.05)),!0},deleteValue:function(s,n,a,o){i=void 0,r=!0,void 0!==e&&(clearTimeout(e),e=void 0),_c(t,s,n,a,o)},flush:n}}(e)),t[e]}return{getCookie:function(t){return e(t).getValue()}
vendor: 9,179 bytes, lines 1-7
1,setCookie:function(t,i,s,r,n,a,o){return e(t).setValue(i,s,r,n,a,o)},deleteCookie:function(t,i,s,r,n){e(t).deleteValue(i,s,r,n)},clearCache:function(){t={}},flush:function(){for(var e=0,i=Object.values(t);e<i.length;e++)i[e].flush()}}}(),Qc={getCookie:Pc,setCookie:function(t,e,i,s,r,n,a){return Pc(t,e,i,s,r,n,a),-1!==document.cookie.indexOf("".concat(t,"="))},deleteCookie:_c,flush:function(){}};function Jc(t,e,i,s,r,n){void 0===n&&(n={});var a=[],o=function(t,e,i,s,r,n){var o,l,d,c,u,h,f,g,m,p,v,y,E,T,S,b,A,k,L,I;n.eventMethod=null!==(o=n.eventMethod)&&void 0!==o?o:"post";var w,R,_=function(t){var e;return null!==(e=t.stateStorageStrategy)&&void 0!==e?e:"cookieAndLocalStorage"},D=function(t){var e;return"boolean"!=typeof t.anonymousTracking&&!0===(null===(e=t.anonymousTracking)||void 0===e?void 0:e.withSessionTracking)},P=function(t){var e;return"boolean"!=typeof t.anonymousTracking&&!0===(null===(e=t.anonymousTracking)||void 0===e?void 0:e.withServerAnonymisation)},x=function(t){return!!t.anonymousTracking},C=null!==(d=null===(l=null==n?void 0:n.contexts)||void 0===l?void 0:l.browser)&&void 0!==d&&d,O=null===(u=null===(c=null==n?void 0:n.contexts)||void 0===c?void 0:c.webPage)||void 0===u||u,M=n.synchronousCookieWrite?Qc:Xc;a.push((w=function(t){return At?null:t},R=function(t){return St?t:w(t)},{beforeTrack:function(t){var e=zt("ses"),i=le(),s=0===Vc(i);if(Q=!!G&&!!M.getCookie(G),yt||Q)ne();else{Gc(i)?(z=e||"none"==kt?Bc(i):Fc(i),It=$c(i)):(new Date).getTime()-Lt>1e3*Tt&&(It++,z=Fc(i,{memorizedVisitCount:It})),Nc(i),function(t,e){if(0===t[10]){var i=e.build();t[8]=i.eid;var s=i.dtm||i.ttm;t[9]=s?parseInt(s):void 0}}(i,t),function(t){t[10]+=1}(i);var r=qc(),n=r.viewport,a=r.documentSize;t.add("vp",n),t.add("ds",a),t.add("vid",R(It)),t.add("sid",R(z)),t.add("duid",w(function(t){return t[1]}(i))),t.add("uid",w(X)),Ht(),t.add("refr",qt(F||rt)),t.add("url",qt(N||st));var o=Uc(i,kt,At);if(!xt||At&&!St||function(t,e){var i={schema:"iglu:com.snowplowanalytics.snowplow/client_session/jsonschema/1-0-2",data:e};t.addContextEntity(i)}(t,o),"none"!=kt){se(i);var l=ie();e&&!s||!l||!Ct||Ot||(M.flush(),Ct(o),Ot=!1)}Lt=(new Date).getTime()}}})),O&&a.push({contexts:function(){return[{schema:"iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0",data:{id:ue()}}]}}),C&&a.push({contexts:function(){return[{schema:"iglu:com.snowplowanalytics.snowplow/browser_context/jsonschema/2-0-0",data:ad(ad({},qc()),{tabId:he()})}]}}),a.push.apply(a,null!==(h=n.plugins)&&void 0!==h?h:[]);var F,N,U,B,$,G,V,K,H,j,q,Y,W,z,X,Q,J,Z=ec({base64:null!==(f=n.encodeBase64)&&void 0!==f?f:"post"!==n.eventMethod,corePlugins:a,callback:function(t){yt||Q||wt.enqueueRequest(t.build())}}),tt=document.characterSet||document.charset,et=Mc(window.location.hostname,window.location.href,Ic()),it=Lc(et[0]),st=et[1],rt=et[2],nt=null!==(g=n.platform)&&void 0!==g?g:"web",at=null!==(m=n.appId)&&void 0!==m?m:"",ot=n.appVersion,lt=document.title,dt=!1,ct=null===(p=n.resetActivityTrackingOnPageView)||void 0===p||p,ut=null!==(v=n.cookieName)&&void 0!==v?v:"_sp_",ht=null!==(y=n.cookieDomain)&&void 0!==y?y:void 0,ft=null!==(E=n.discoverRootDomain)&&void 0!==E?E:void 0===ht,gt="/",mt=null!==(T=n.cookieSameSite)&&void 0!==T?T:"Lax",pt=null===(S=n.cookieSecure)||void 0===S||S,vt=window.navigator.doNotTrack||window.navigator.msDoNotTrack||window.doNotTrack,yt=void 0!==n.respectDoNotTrack&&n.respectDoNotTrack&&("yes"===vt||"1"===vt),Et=null!==(b=n.cookieLifetime)&&void 0!==b?b:63072e3,Tt=null!==(A=n.sessionCookieTimeout)&&void 0!==A?A:1800,St=D(n),bt=P(n),At=x(n),kt=_(n),Lt=(new Date).getTime(),It=1,wt=Oc(ad({trackerId:t,endpoint:de(s),serverAnonymization:bt,useLocalStorage:"localStorage"==kt||"cookieAndLocalStorage"==kt},n),r),Rt=!1,_t=null!==(k=n.preservePageViewIdForUrl)&&void 0!==k&&k,Dt=void 0,Pt={enabled:!1,installed:!1,configurations:{}},xt=null!==(I=null===(L=n.contexts)||void 0===L?void 0:L.session)&&void 0!==I&&I,Ct=n.onSessionUpdateCallback,Ot=!1,Mt="boolean"==typeof(J=n.useExtendedCrossDomainLinker||!1)?{useExtendedCrossDomainLinker:J}:{useExtendedCrossDomainLinker:!0,collectCrossDomainAttributes:J},Ft=Mt.useExtendedCrossDomainLinker,Nt=Mt.collectCrossDomainAttributes;ft&&!ht&&(ht=function(t,e){for(var i=window.location.hostname,s="_sp_root_domain_test_",r=s+(new Date).getTime(),n="_test_value_"+(new Date).getTime(),a=i.split("."),o=a.length-2;o>=0;o--){var l=a.slice(o).join(".");if(Pc(r,n,0,"/",l,t,e),Pc(r)===n){_c(r,"/",l,t,e);for(var d=Dc(s),c=0;c<d.length;c++)_c(d[c],"/",l,t,e);return l}}return i}(mt,pt));var Ut=qc(),Bt=Ut.browserLanguage,$t=Ut.resolution,Gt=Ut.colorDepth,Vt=Ut.cookiesEnabled,Kt=function(){if("object"==typeof Intl&&"function"==typeof Intl.DateTimeFormat)return(new Intl.DateTimeFormat).resolvedOptions().timeZone}();function Ht(){(et=Mc(window.location.hostname,window.location.href,Ic()))[1]!==st&&(rt=Ic(st)),it=Lc(et[0]),st=et[1]}function jt(t){for(var e=function(t){return function(e){var i=e.currentTarget,s=function(t,e,i){var s,r=(new Date).getTime(),n=ad(ad({},Tc),e),a=i.domainUserId,o=i.userId,l=i.sessionId,d=i.sourceId,c=i.sourcePlatform,u=i.event,h=u.currentTarget,f="function"==typeof n.reason?n.reason(u):null===(s=null==h?void 0:h.textContent)||void 0===s?void 0:s.trim();return t?[a,r,n.sessionId&&l,n.userId&&Sc(o||""),n.sourceId&&Sc(d||""),n.sourcePlatform&&c,n.reason&&Sc(f||"")].map(function(t){return t||""}).join(".").replace(/([.]*$)/,""):i.domainUserId+"."+r}(t,Nt,{domainUserId:W,userId:X||void 0,sessionId:z,sourceId:at,sourcePlatform:nt,event:e});(null==i?void 0:i.href)&&(i.href=function(t,e,i){var s="_sp="+i,r=t.split("#"),n=r[0].split("?"),a=n.shift(),o=n.join("?");if(o){for(var l=!0,d=o.split("&"),c=0;c<d.length;c++)if("_sp="===d[c].substr(0,4)){l=!1,d[c]=s,o=d.join("&");break}l&&(o=s+"&"+o)}else o=s;return r[0]=a+"?"+o,r.join("#")}(i.href,0,s))}}(Ft),i=0;i<document.links.length;i++){var s=document.links[i];!s.spDecorationEnabled&&t(s)&&(s.addEventListener("click",e,!0),s.addEventListener("mousedown",e,!0),s.spDecorationEnabled=!0)}}function qt(t){var e;return B&&(e=new RegExp("#.*"),t=t.replace(e,"")),$&&(e=new RegExp("[{}]","g"),t=t.replace(e,"")),t}function Yt(t){var e=new RegExp("^([a-z]+):").exec(t);return e?e[1]:null}function Wt(t){return ut+t+"."+Y}function zt(t){var e=Wt(t);return"localStorage"==kt?
2/*!
3     * Core functionality for Snowplow Browser trackers v4.6.9 (http://bit.ly/sp-js)
4     * Copyright 2022 Snowplow Analytics Ltd, 2010 Anthon Pang
5     * Licensed under BSD-3-Clause
6     */
7function(t){try{var e=window.localStorage,i=e.getItem(t+".expires");return null===i||+i>Date.now()?e.getItem(t):(e.removeItem(t),void e.removeItem(t+".expires"))}catch(t){return}}(e):"cookie"==kt||"cookieAndLocalStorage"==kt?M.getCookie(e):void 0}function Xt(){Ht(),Y=vc((ht||it)+(gt||"/")).slice(0,4)}function Qt(){var t=new Date;V=t.getTime()}function Jt(){!function(){var t=Zt(),e=t[0];e<K?K=e:e>H&&(H=e);var i=t[1];i<j?j=i:i>q&&(q=i)}(),Qt()}function Zt(){var t=document.documentElement;return t?[t.scrollLeft||window.pageXOffset,t.scrollTop||window.pageYOffset]:[0,0]}function te(){var t=Zt(),e=t[0];K=e,H=e;var i=t[1];j=i,q=i}function ee(t){return Math.round(t)}function ie(){return re(Wt("ses"),"*",Tt)}function se(t){var e=Wt("id"),i=function(t,e){var i=cd([],t,!0);return e&&(i[1]="",i[7]=""),i.shift(),i.join(".")}(t,At);return re(e,i,Et)}function re(t,e,i){return!(At&&!St)&&("localStorage"==kt?function(t,e,i){void 0===i&&(i=63072e3);try{var s=window.localStorage,r=Date.now()+1e3*i;return s.setItem("".concat(t,".expires"),r.toString()),s.setItem(t,e),!0}catch(t){return!1}}(t,e,i):("cookie"==kt||"cookieAndLocalStorage"==kt)&&M.setCookie(t,e,i,gt,ht,mt,pt))}function ne(t){var e=Wt("id"),i=Wt("ses");yc(e),yc(i),M.deleteCookie(e,gt,ht,mt,pt),M.deleteCookie(i,gt,ht,mt,pt),(null==t?void 0:t.preserveSession)||(z=wd(),It=1),(null==t?void 0:t.preserveUser)||(W=At?"":wd(),X=null)}function ae(t){t&&t.stateStorageStrategy&&(n.stateStorageStrategy=t.stateStorageStrategy,kt=_(n)),At=x(n),St=D(n),bt=P(n),wt.setUseLocalStorage("localStorage"==kt||"cookieAndLocalStorage"==kt),wt.setAnonymousTracking(bt)}function oe(){if(!At||St){var t="none"!=kt&&!!zt("ses"),e=le();W=function(t,e){var i;return t[1]?i=t[1]:e?(i="",t[1]=i):(i=wd(),t[1]=i),i}(e,At),z=t?Bc(e):Fc(e),It=$c(e),"none"!=kt&&(ie(),Nc(e),se(e),Vc(e)||M.flush())}}function le(){return"none"==kt?["1","",0,0,0,void 0,"","","",void 0,0]:function(t,e,i,s){var r,n=new Date,a=Math.round(n.getTime()/1e3);t?(r=t.split(".")).unshift("0"):r=["1",e,a,s,a,"",i],r[6]&&"undefined"!==r[6]||(r[6]=wd()),r[7]&&"undefined"!==r[7]||(r[7]=""),r[8]&&"undefined"!==r[8]||(r[8]=""),r[9]&&"undefined"!==r[9]||(r[9]=""),r[10]&&"undefined"!==r[10]||(r[10]=0);var o=function(t,e){var i=parseInt(t);return isNaN(i)?e:i},l=function(t){return t?o(t,void 0):void 0};return[r[0],r[1],o(r[2],a),o(r[3],s),o(r[4],a),l(r[5]),r[6],r[7],r[8],l(r[9]),o(r[10],0)]}(zt("id")||void 0,W,z,It)}function de(t){return 0===t.indexOf("http")?t:("https:"===document.location.protocol?"https":"http")+"://"+t}function ce(){Rt&&null!=r.pageViewId||(r.pageViewId=wd(),r.pageViewUrl=N||st)}function ue(){return function(){if(null==r.pageViewId)return!0;
7if(Rt||!_t)return!1;if(void 0===r.pageViewUrl)return!0;var t=N||st;if(!0===_t||"full"==_t||!("URL"in window))return r.pageViewUrl!=t;var e=new URL(t),i=new URL(r.pageViewUrl);return"pathname"==_t?e.pathname!=i.pathname:"pathnameAndSearch"==_t&&(e.pathname!=i.pathname||e.search!=i.search)}()&&(r.pageViewId=wd(),r.pageViewUrl=N||st),r.pageViewId}function he(){if("none"===kt||At||!O)return null;var t="_sp_tab_id",e=Ec(t);return e||(function(t,e){try{return window.sessionStorage.setItem(t,e),!0}catch(t){return!1}}(t,wd()),e=Ec(t)),e||null}function fe(t,e){return(t||[]).concat(e?e():[])}function ge(t,e,i){var s=function(t,e){Ht(),t({context:e,pageViewId:ue(),minXOffset:K,minYOffset:j,maxXOffset:H,maxYOffset:q}),te()},r=function(){var r=new Date;V+t.configHeartBeatTimer>r.getTime()&&s(t.callback,fe(e,i))};0===t.configMinimumVisitLength?t.activityInterval=window.setInterval(r,t.configHeartBeatTimer):t.activityInterval=window.setTimeout(function(){var n=new Date;V+t.configMinimumVisitLength>n.getTime()&&s(t.callback,fe(e,i)),t.activityInterval=window.setInterval(r,t.configHeartBeatTimer)},t.configMinimumVisitLength)}function me(t){var e=t.minimumVisitLength,i=t.heartbeatDelay,s=t.callback;if(bc(e)&&bc(i))return{configMinimumVisitLength:1e3*e,configHeartBeatTimer:1e3*i,callback:s};Nd.error("Activity tracking minimumVisitLength & heartbeatDelay must be integers")}function pe(t){var e=t.context,i=t.minXOffset,s=t.minYOffset,r=t.maxXOffset,n=t.maxYOffset,a=document.title;a!==lt&&(lt=a,U=void 0),Z.track(function(t){var e=t.pageUrl,i=t.pageTitle,s=t.referrer,r=t.minXOffset,n=t.maxXOffset,a=t.minYOffset,o=t.maxYOffset,l=Pd();return l.add("e","pp"),l.add("url",e),l.add("page",i),l.add("refr",s),r&&!isNaN(Number(r))&&l.add("pp_mix",r.toString()),n&&!isNaN(Number(n))&&l.add("pp_max",n.toString()),a&&!isNaN(Number(a))&&l.add("pp_miy",a.toString()),o&&!isNaN(Number(o))&&l.add("pp_may",o.toString()),l}({pageUrl:qt(N||st),pageTitle:Ac(U||lt),referrer:qt(F||rt),minXOffset:ee(i),maxXOffset:ee(r),minYOffset:ee(s),maxYOffset:ee(n)}),e)}function ve(t){var e=Pt.configurations[t];0===(null==e?void 0:e.configMinimumVisitLength)?window.clearTimeout(null==e?void 0:e.activityInterval):window.clearInterval(null==e?void 0:e.activityInterval),Pt.configurations[t]=void 0}Z.setTrackerVersion(i),Z.setTrackerNamespace(e),Z.setAppId(at),Z.setPlatform(nt),Z.addPayloadPair("cookie",Vt?"1":"0"),Z.addPayloadPair("cs",tt),Z.addPayloadPair("lang",Bt),Z.addPayloadPair("res",$t),Z.addPayloadPair("cd",Gt),Kt&&Z.addPayloadPair("tz",Kt),ot&&Z.addPlugin({plugin:{contexts:function(){return[{schema:"iglu:com.snowplowanalytics.snowplow/application/jsonschema/1-0-0",data:{version:ot}}]}}}),Xt(),oe(),n.crossDomainLinker&&jt(n.crossDomainLinker);var ye={getDomainSessionIndex:function(){return It},getPageViewId:ue,getTabId:he,newSession:function(){var t=le();if(Gc(t)?(z="none"!=kt?Fc(t):Bc(t),It=$c(t)):(It++,z=Fc(t,{memorizedVisitCount:It})),Nc(t),"none"!=kt){var e=Uc(t,kt,At);se(t);var i=ie();M.flush(),i&&Ct&&(Ot=!0,Ct(e))}Lt=(new Date).getTime()},getCookieName:function(t){return Wt(t)},getUserId:function(){return X},getDomainUserId:function(){return le()[1]},getDomainUserInfo:function(){return le()},setReferrerUrl:function(t){F=t},setCustomUrl:function(t){Ht(),N=function(t,e){var i;return Yt(e)?e:"/"===e.slice(0,1)?Yt(t)+"://"+kc(t)+e:((i=(t=qt(t)).indexOf("?"))>=0&&(t=t.slice(0,i)),(i=t.lastIndexOf("/"))!==t.length-1&&(t=t.slice(0,i+1)),t+e)}(st,t)},setDocumentTitle:function(t){lt=document.title,U=t,dt=!1},discardHashTag:function(t){B=t},discardBrace:function(t){$=t},setCookiePath:function(t){gt=t,Xt()},setVisitorCookieTimeout:function(t){Et=t},crossDomainLinker:function(t){jt(t)},enableActivityTracking:function(t){Pt.configurations.pagePing||(Pt.enabled=!0,Pt.configurations.pagePing=me(ad(ad({},t),{callback:pe})))},enableActivityTrackingCallback:function(t){Pt.configurations.callback||(Pt.enabled=!0,Pt.configurations.callback=me(t))},disableActivityTracking:function(){ve("pagePing")},disableActivityTrackingCallback:function(){ve("callback")},updatePageActivity:function(){Qt()},setOptOutCookie:function(t){G=t},setUserId:function(t){X=t},setUserIdFromLocation:function(t){Ht(),X=Rc(t,st)},setUserIdFromReferrer:function(t){Ht(),X=Rc(t,rt)},setUserIdFromCookie:function(t){X=M.getCookie(t)},setCollectorUrl:function(t){wt.setCollectorUrl(de(t))},setBufferSize:function(t){wt.setBufferSize(t)}
7,flushBuffer:function(t){void 0===t&&(t={}),wt.executeQueue(),t.newBufferSize&&wt.setBufferSize(t.newBufferSize)},trackPageView:function(t){void 0===t&&(t={}),function(t){var e=t.title,i=t.context,s=t.timestamp,r=t.contextCallback;Ht(),Dt&&Dt==ue()&&ce(),Dt=ue(),lt=document.title,e?(U=e,dt=!0):dt&&(U=null);var n=Ac(U||lt);Z.track(function(t){var e=t.pageUrl,i=t.pageTitle,s=t.referrer,r=Pd();return r.add("e","pv"),r.add("url",e),r.add("page",i),r.add("refr",s),r}({pageUrl:qt(N||st),pageTitle:n,referrer:qt(F||rt)}),fe(i,r),s);var a=new Date,o=!1;if(Pt.enabled&&!Pt.installed){Pt.installed=!0,o=!0;var l={update:function(){if("undefined"!=typeof window&&"function"==typeof window.addEventListener){var t=!1,e=Object.defineProperty({},"passive",{get:function(){t=!0},set:function(){}}),i=function(){};window.addEventListener("testPassiveEventSupport",i,e),window.removeEventListener("testPassiveEventSupport",i,e),l.hasSupport=t}}};l.update();var d="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";Object.prototype.hasOwnProperty.call(l,"hasSupport")?wc(document,d,Qt,{passive:!0}):wc(document,d,Qt),te();var c=function(t,e){return void 0===e&&(e=Qt),function(t){return wc(document,t,e)}};["click","mouseup","mousedown","mousemove","keypress","keydown","keyup","touchend","touchstart"].forEach(c(document)),["resize","focus","blur"].forEach(c(window)),c(window,Jt)("scroll")}if(Pt.enabled&&(ct||o)){V=a.getTime();var u=void 0;for(u in Pt.configurations){var h=Pt.configurations[u];h&&(window.clearInterval(h.activityInterval),ge(h,i,r))}}}(t)},preservePageViewId:function(){Rt=!0},preservePageViewIdForUrl:function(t){_t=t},disableAnonymousTracking:function(t){var e=(null==t?void 0:t.stateStorageStrategy)&&t.stateStorageStrategy!==kt&&(!At||St)&&zt("ses");n.anonymousTracking=!1,ae(t),e&&ie(),oe(),wt.executeQueue()},enableAnonymousTracking:function(t){var e;n.anonymousTracking=null===(e=t&&(null==t?void 0:t.options))||void 0===e||e,ae(t),St||ce()},clearUserData:ne};return ad(ad({},ye),{id:t,namespace:e,core:Z,sharedState:r})}(t,e,i,s,r,n),l=ad(ad({},o),{addPlugin:function(t){var e,i;l.core.addPlugin(t),null===(i=(e=t.plugin).activateBrowserPlugin)||void 0===i||i.call(e,l)}});return a.forEach(function(t){var e;null===(e=t.activateBrowserPlugin)||void 0===e||e.call(t,l)}),l}var Zc={};function tu(t,e){try{(i=null!=t?t:Object.keys(Zc),iu(i,Zc)).forEach(e)}catch(t){Nd.error("Function failed",t)}var i}function eu(t,e,i){try{iu(null!=t?t:Object.keys(e),e).forEach(i)}catch(t){Nd.error("Function failed",t)}}function iu(t,e){for(var i=[],s=0,r=t;s<r.length;s++){var n=r[s];e.hasOwnProperty(n)?i.push(e[n]):Nd.warn(n+" not configured")}return i}var su=function(){this.bufferFlushers=[],this.hasLoaded=!1,this.registeredOnLoadHandlers=[]};function ru(t,e){tu(e,function(e){e.trackPageView(t)})}function nu(t,e){tu(e,function(e){e.core.track(ic({event:t.event}),t.context,t.timestamp)})}function au(t,e){tu(e,function(e){e.core.addGlobalContexts(t)})}function ou(t,e){tu(e,function(e){e.core.removeGlobalContexts(t)})}var lu="undefined"!=typeof window?function(){var t=new su,e=document,i=window;function s(){var e;if(!t.hasLoaded)for(t.hasLoaded=!0,e=0;e<t.registeredOnLoadHandlers.length;e++)t.registeredOnLoadHandlers[e]();return!0}return e.visibilityState&&wc(e,"visibilitychange",function(){"hidden"==e.visibilityState&&t.bufferFlushers.forEach(function(t){t(!1)})},!1),wc(i,"beforeunload",function(){t.bufferFlushers.forEach(function(t){t(!1)})},!1),"loading"===document.readyState?(e.addEventListener?e.addEventListener("DOMContentLoaded",function t(){e.removeEventListener("DOMContentLoaded",t,!1),s()}):e.attachEvent&&e.attachEvent("onreadystatechange",function t(){"complete"===e.readyState&&(e.detachEvent("onreadystatechange",t),s())}),wc(i,"load",s,!1)):s(),t}
8/*!
9     * Browser tracker for Snowplow v4.6.9 (http://bit.ly/sp-js)
10     * Copyright 2022 Snowplow Analytics Ltd, 2010 Anthon Pang
11     * Licensed under BSD-3-Clause
12     */():void 0;function du(t){return{schema:"iglu:com.snowplowanalytics.snowplow/event_specification/jsonschema/1-0-2",data:t}}function cu(t){return{schema:"iglu:no.tv2/tv2no_ad/jsonschema/1-0-1",data:t}}function uu(t){return{schema:"iglu:no.tv2/tv2_user/jsonschema/1-0-2",data:t}}function hu(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2no_user_action/jsonschema/1-0-1",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}
12function fu(t){return{schema:"iglu:no.tv2/tv2_component/jsonschema/1-0-0",data:t}}function gu(t){return{schema:"iglu:no.tv2/tv2_login_reason/jsonschema/1-0-0",data:t}}function mu(t,e){const i=du({id:"0de4c612-2975-45a1-b7a1-cf930f7c001e",name:"User Action",data_product_id:"5acd0a88-158f-4f62-8af4-56ea346043ca",data_product_name:"TV2.NO BITS Component Tracker"}),s=Array.isArray(t.context)?[...t.context,i]:[i];hu(Object.assign(Object.assign({},t),{context:s}),e)}function pu(t,e){const i=du({id:"bcde6c9e-9475-45ed-9890-df3d9e46b262",name:"Paywall Impression",data_product_id:"097df141-f8fb-4a82-b099-89adeef86573",data_product_name:"TV2.NO Labrador/Global Tracking"}),s=Array.isArray(t.context)?[...t.context,i]:[i];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2no_paywall_impression/jsonschema/1-0-0",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:s}),e)}function vu(t,e){const i=du({id:"e3e8ca0c-faa0-4763-9016-32e4a813e4d5",name:"User login",data_product_id:"097df141-f8fb-4a82-b099-89adeef86573",data_product_name:"TV2.NO Labrador/Global Tracking"}),s=Array.isArray(t.context)?[...t.context,i]:[i];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2no_user_login/jsonschema/1-0-0",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:s}),e)}const yu=["ERROR","WARN","INFO","LOG","DEBUG"];class Eu{static setLogLevel(t){Eu.currentLogLevel=t}static getColorScheme(){return"undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}static getColorByLevel(t){const e=Eu.getColorScheme();switch(t){case"LOG":case"DEBUG":return"dark"===e?"#B0BEC5":"#37474F";case"INFO":return"dark"===e?"#82B1FF":"#0D47A1";case"WARN":return"dark"===e?"#FFD54F":"#FF6F00";case"ERROR":return"dark"===e?"#FF8A80":"#D32F2F";default:return"dark"===e?"white":"black"}}static logMessage(t,e,...i){if(!(yu.indexOf(t)<=yu.indexOf(Eu.currentLogLevel)))return;const s=`%c[${t}] Tracker: ${e}`,r=`color: ${Eu.getColorByLevel(t)};`;switch(t){case"LOG":default:console.log(`${s}`,r,...i);break;case"INFO":console.info(`${s}`,r,...i);break;case"WARN":console.warn(`${s}`,r,...i);break;case"ERROR":console.error(`${s}`,r,...i);break;case"DEBUG":console.debug(`${s}`,r,...i)}}static log(t,...e){Eu.logMessage("LOG",t,...e)}static info(t,...e){Eu.logMessage("INFO",t,...e)}static warn(t,...e){Eu.logMessage("WARN",t,...e)}static error(t,...e){Eu.logMessage("ERROR",t,...e)}static debug(t,...e){Eu.logMessage("DEBUG",t,...e)}}Eu.currentLogLevel="WARN";const Tu="articleHistory";function Su(t){return t.includes("/video/")}function bu(t){return void 0!==t.path&&Su(t.path)}function Au(t){return function(t){return t.filter(t=>{const e=new Date(t.timestamp).getTime();return!isNaN(e)&&e>=Date.now()-5184e6})}(t).filter(t=>!bu(t))}function ku(){if("undefined"==typeof window)return null;if(Su(window.location.pathname))return null;if(window.lab_metadata&&window.lab_metadata.articleId)return String(window.lab_metadata.articleId);const t=window.location.pathname.match(/\/(\d{5,})(?:\/|$)/);return t?t[1]:null}function Lu(){if("undefined"==typeof localStorage)return[];try{const t=localStorage.getItem(Tu);return Au(t?JSON.parse(t):[])}catch(t){return[]}}function Iu(t){if("undefined"!=typeof localStorage)try{localStorage.setItem(Tu,JSON.stringify(Au(t)))}catch(t){Eu.warn("Could not save article history",t)}}function wu(){if("undefined"!=typeof localStorage)try{localStorage.removeItem(Tu)}catch(t){Eu.warn("Could not clear article history",t)}}function Ru(){if("undefined"==typeof document)return!1;const t=document.cookie.split("; ").find(t=>t.startsWith("tv2_personalisation_consent_cookie="));if(t)try{const e=JSON.parse(decodeURIComponent(t.split("=")[1]));if(e&&e.consentedToAll)return!0}catch(t){}if("undefined"==typeof localStorage)return!1;const e=localStorage.getItem("tv2_personalisation_consent_data");if(e)try{const t=JSON.parse(e);if(t&&t.consentedToAll)return!0}catch(t){return!1}return!1}class _u{constructor(){this.tracking=!1,this.readIntervalId=null,this.session=null,this.updateScrollDepth=()=>
12{if(!this.session)return;const t=function(){const t=document.documentElement,e=document.body,i=window.pageYOffset||t.scrollTop||e&&e.scrollTop||0,s=Math.max(e?e.scrollHeight:0,t.scrollHeight,e?e.offsetHeight:0,t.offsetHeight),r=t.clientHeight||window.innerHeight;return s<=r?100:Math.min(100,Math.round(i/(s-r)*100))}();t>this.session.maxScrollDepth&&(this.session.maxScrollDepth=t)},this.tickReadTime=()=>{if(!this.session)return;const t=Date.now();this.session.pageVisible&&(this.session.readSeconds+=(t-this.session.lastTick)/1e3),this.session.lastTick=t},this.saveCurrentSession=()=>{if(!this.session||this.session.saved)return;if(Su(window.location.pathname))return;this.tickReadTime(),this.updateScrollDepth(),this.session.saved=!0;const t={id:this.session.articleId,timestamp:this.session.visitTimestamp,scroll_depth:this.session.maxScrollDepth,read_seconds:Math.round(this.session.readSeconds),path:window.location.pathname},e=function(t,e){var i;if(bu(e))return t;const s=t.findIndex(t=>t.id===e.id);if(-1===s)return[...t,e];const r=t[s],n=e.scroll_depth>r.scroll_depth,a=e.read_seconds>r.read_seconds;if(!n&&!a)return t;const o=[...t];return o[s]={id:e.id,timestamp:e.timestamp,scroll_depth:n?e.scroll_depth:r.scroll_depth,read_seconds:a?e.read_seconds:r.read_seconds,path:null!==(i=e.path)&&void 0!==i?i:r.path},o}(Lu(),t);Iu(e),Eu.info("Article visit saved",t)},this.handleScroll=()=>{this.updateScrollDepth()},this.handleVisibilityChange=()=>{this.session&&(this.tickReadTime(),this.session.pageVisible="hidden"!==document.visibilityState,this.session.lastTick=Date.now())},this.handlePageHide=t=>{t.persisted?this.pauseTracking():(this.saveCurrentSession(),this.teardown())},this.handlePageShow=t=>{if(t.persisted&&this.session){if(!Ru())return this.teardown(),void wu();this.session.lastTick=Date.now(),this.session.pageVisible="hidden"!==document.visibilityState,this.attachTrackingListeners(),Eu.info("Resumed article visit tracking after bfcache restore",{articleId:this.session.articleId})}},this.handleBeforeUnload=()=>{this.saveCurrentSession(),this.teardown()}}trackArticleVisit(){var t;if("undefined"==typeof window)return;if(!Ru())return this.teardown(),void wu();const e=ku();if(!e)return this.teardown(),void this.cleanup();this.tracking||((null===(t=this.session)||void 0===t?void 0:t.articleId)!==e?(this.session&&!this.session.saved&&this.saveCurrentSession(),this.teardown(),this.startSession(e)):this.attachTrackingListeners())}cleanup(){Ru()&&Iu(Lu())}startSession(t){this.session={articleId:t,visitTimestamp:(new Date).toISOString(),maxScrollDepth:0,readSeconds:0,lastTick:Date.now(),pageVisible:"hidden"!==document.visibilityState,saved:!1},this.updateScrollDepth(),window.addEventListener("pageshow",this.handlePageShow),this.attachTrackingListeners(),Eu.info("Tracking article visit",{articleId:t})}attachTrackingListeners(){!this.tracking&&this.session&&(window.addEventListener("scroll",this.handleScroll,{passive:!0}),document.addEventListener("visibilitychange",this.handleVisibilityChange),window.addEventListener("pagehide",this.handlePageHide),window.addEventListener("beforeunload",this.handleBeforeUnload),this.readIntervalId=setInterval(this.tickReadTime,1e3),this.tracking=!0)}pauseTracking(){this.detachTrackingListeners(),this.tracking=!1}teardown(){this.detachTrackingListeners(),window.removeEventListener("pageshow",this.handlePageShow),this.session=null,this.tracking=!1}detachTrackingListeners(){null!==this.readIntervalId&&(clearInterval(this.readIntervalId),this.readIntervalId=null),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("visibilitychange",this.handleVisibilityChange),window.removeEventListener("pagehide",this.handlePageHide),window.removeEventListener("beforeunload",this.handleBeforeUnload)}}class Du{trackUserAction(t,e){try{const i=fu(e);mu(Object.assign(Object.assign({},t),{context:[i]})),Eu.debug(`User action tracked: ${t.actionType}`)}catch(t){Eu.error("Error tracking user action:",t)}}}
13/*!
14     * Link Click tracking for Snowplow v4.6.9 (http://bit.ly/sp-js)
15     * Copyright 2022 Snowplow Analytics Ltd, 2010 Anthon Pang
16     * Licensed under BSD-3-Clause
17     */var Pu,xu,Cu,Ou,Mu=["a","area"],Fu=Mu.join(", "),Nu=/^(javascript|vbscript|jscript|mocha|livescript|ecmascript):/i,Uu={},Bu={},$u={},Gu=void 0;function Vu(t,e){void 0===t&&(t={}),void 0===e&&(e=Object.keys(Uu)),function(t){void 0===t&&(t=Object.keys(Uu)),t.forEach(function(t){Uu[t]&&Bu[t]&&(window.removeEventListener("click",Bu[t],!0),window.removeEventListener("mouseup",Bu[t],!0),window.removeEventListener("mousedown",Bu[t],!0))})}(e),e.forEach(function(e){var i;
18/*!
19     * Snowplow element tracking v4.6.9 (https://github.com/snowplow/snowplow-javascript-tracker)
20     * Copyright 2022 Snowplow Analytics Ltd, 2010 Anthon Pang
21     * Licensed under BSD-3-Clause
22     */Uu[e]&&(function(t,e){var i=void 0===t?{}:t,s=i.options,r=i.pseudoClicks,n=i.trackContent,a=i.context;$u[e]={linkTrackingContent:n,linkTrackingContext:a,linkTrackingPseudoClicks:r,linkTrackingFilter:xc(s)}}(t,e),Bu[i=e]=Bu[i]||Hu.bind(null,i),$u[i].linkTrackingPseudoClicks?(wc(window,"mouseup",Bu[i],!0),wc(window,"mousedown",Bu[i],!0)):wc(window,"click",Bu[i],!0))})}function Ku(t,e){void 0===e&&(e=Object.keys(Uu)),eu(e,Uu,function(e){var i,s,r,n;if("element"in t){var a=null!==(r=null!==(i=t.trackContent)&&void 0!==i?i:null===(s=$u[e.id])||void 0===s?void 0:s.linkTrackingContent)&&void 0!==r&&r;n=function(t,e){void 0===e&&(e=!1);var i,s,r,n,a=t,o=a.hostname||kc(a.href),l=a.href.replace(o,function(t){return t.toLowerCase()});if(!Nu.test(l))return i=a.id,s=Cc(a),r=a.target,n=e?a.innerHTML:void 0,l||null==Gu||Gu.warn("Link click target URL empty",a),sc({targetUrl:l||"about:invalid",elementId:i,elementClasses:s,elementTarget:r,elementContent:n})}(t.element,a)}else n=sc(t);n&&e.core.track(n,t.context,t.timestamp)}),Xc.flush()}function Hu(t,e){var i=$u[t].linkTrackingContext,s=$u[t].linkTrackingFilter,r=e||window.event,n=r.which||r.button,a=function(t){if(t instanceof Element){if("function"==typeof t.closest)return t.closest(Fu);for(var e=t;e;){var i=e.tagName.toLowerCase();if(-1!==Mu.indexOf(i))return e;e=e.parentElement}}return null}(r.composed?r.composedPath()[0]:r.target||r.srcElement);a&&null!=a.href&&(s&&!s(a)||("click"===r.type?Ku({element:a,context:Ud(i,a)},[t]):"mousedown"===r.type?1===n||2===n?($u[t].lastButton=n,$u[t].lastTarget=a):delete $u[t].lastButton:"mouseup"===r.type&&(n===$u[t].lastButton&&a===$u[t].lastTarget&&Ku({element:a,context:Ud(i,a)},[t]),delete $u[t].lastButton,delete $u[t].lastTarget)))}!function(t){t.ELEMENT_CREATE="iglu:com.snowplowanalytics.snowplow/create_element/jsonschema/1-0-0",t.ELEMENT_DESTROY="iglu:com.snowplowanalytics.snowplow/destroy_element/jsonschema/1-0-0",t.ELEMENT_EXPOSE="iglu:com.snowplowanalytics.snowplow/expose_element/jsonschema/1-0-0",t.ELEMENT_OBSCURE="iglu:com.snowplowanalytics.snowplow/obscure_element/jsonschema/1-0-0"}(Pu||(Pu={})),function(t){t.ELEMENT_DETAILS="iglu:com.snowplowanalytics.snowplow/element/jsonschema/1-0-0",t.ELEMENT_CONTENT="iglu:com.snowplowanalytics.snowplow/element_content/jsonschema/1-0-0",t.ELEMENT_STATISTICS="iglu:com.snowplowanalytics.snowplow/element_statistics/jsonschema/1-0-0",t.COMPONENT_PARENTS="iglu:com.snowplowanalytics.snowplow/component_parents/jsonschema/1-0-0"}(xu||(xu={})),function(t){t[t.INITIAL=0]="INITIAL",t[t.CREATED=1]="CREATED",t[t.DESTROYED=2]="DESTROYED",t[t.EXPOSED=3]="EXPOSED",t[t.PENDING=4]="PENDING",t[t.OBSCURED=5]="OBSCURED"}(Ou||(Ou={}));var ju="undefined"!=typeof WeakMap?new WeakMap:new Map;function qu(t,e){if(void 0===e&&(e={}),ju.has(t))return ju.get(t);var i=performance.now(),s=ad({state:Ou.INITIAL,matches:new Set,originalPageViewId:"",createdTs:i+performance.timeOrigin,lastPosition:-1,lastObservationTs:i,elapsedVisibleMs:0,views:0},e);return ju.set(t,s),s}var Yu,Wu=((Cu={})[Ou.CREATED]="exists",Cu[Ou.DESTROYED]="destroyed",Cu[Ou.EXPOSED]="on screen",Cu[Ou.INITIAL]="unknown",Cu[Ou.OBSCURED]="off screen",Cu[Ou.PENDING]="awaiting time criteria",Cu),zu=function(t,e){return void 0===e?0:t[0]*t[1]-e[0]*e[1]};function Xu(t,e){void 0===e&&(e=document);var i=t.selector,s=t.shadowOnly,r=t.shadowSelector,n=s?[]:Array.from(e.querySelectorAll(i));return r&&Array.from(e.querySelectorAll(r),function(e){e.shadowRoot&&(s&&n.push.apply(n,Array.from(e.shadowRoot.querySelectorAll(i))),n.push.apply(n,Xu(t,e.
22shadowRoot)))}),n}function Qu(t){return t.nodeType===Node.ELEMENT_NODE}function Ju(t){return null!=t&&("function"==typeof t||"object"==typeof t&&["match","content","selector","dataset","attributes","properties","child_text"].some(function(e){return e in t}))}function Zu(t,e,i){return i.reduce(function(i,s){var r=th(t,e,s);return r.length?i.concat(r):"match"in s?[]:i},[])}function th(t,e,i){var s=[],r="callback";if("function"==typeof i){try{var n=i(t);for(var a in n)if("string"==typeof a&&n.hasOwnProperty(a)){var o="object"==typeof n[a]?JSON.stringify(n[a]):String(n[a]);s.push({source:r,attribute:a,value:o})}}catch(t){o=t instanceof Error?t.message||t.name:String(t),s.push({source:"error",attribute:"message",value:o})}return s}if((r="attributes")in i&&Array.isArray(i[r])&&i[r].forEach(function(e){var i=t.getAttribute(e);null!==i&&s.push({source:r,attribute:e,value:i})}),(r="properties")in i&&Array.isArray(i[r])&&i[r].forEach(function(e){var i=t[e];"object"!=typeof i&&void 0!==i&&s.push({source:r,attribute:e,value:String(i)})}),(r="dataset")in i&&Array.isArray(i[r])&&i[r].forEach(function(e){if("dataset"in t){var i=t.dataset[e];void 0!==i&&s.push({source:r,attribute:e,value:String(i)})}}),(r="child_text")in i&&"object"==typeof i[r]&&i[r]&&Object.entries(i[r]).forEach(function(e){var i,n=e[0],a=e[1];try{var o=t.querySelector(a)||(null===(i=t.shadowRoot)||void 0===i?void 0:i.querySelector(a));o&&o.textContent&&s.push({source:r,attribute:n,value:o.textContent})}catch(t){}}),(r="content")in i&&"object"==typeof i[r]&&i[r]&&Object.entries(i[r]).forEach(function(e){var i,n=e[0],a=e[1];if(!(a instanceof RegExp))try{a=new RegExp(a)}catch(t){return}var o=t.textContent||(null===(i=t.shadowRoot)||void 0===i?void 0:i.textContent);if(o)try{var l=a.exec(o);l&&s.push({source:r,attribute:n,value:l.length>1?l[1]:l[0]})}catch(t){console.error(t)}}),(r="selector")in i&&i[r]&&s.push({source:r,attribute:r,value:e}),(r="match")in i&&i[r])for(var l=i[r],d=function(t,e){if(!s.some(function(i){return i.attribute===t&&("function"==typeof e?e(i.value):i.value===e)}))return{value:[]}},c=0,u=Object.entries(l);c<u.length;c++){var h=u[c],f=d(a=h[0],o=h[1]);if("object"==typeof f)return f.value}return s}function eh(t,e,i){void 0===i&&(i=1);var s=[];return e&&t.contents.length&&t.contents.forEach(function(r){Xu(r,e).forEach(function(e,n){var a={schema:xu.ELEMENT_CONTENT,data:{parent_name:t.name,parent_index:i,element_name:r.name,element_index:n+1,attributes:Zu(e,r.selector,r.details)}};s.push(a),s.push.apply(s,r.context(e,r)),s.push.apply(s,eh(r,e,n+1))})}),s}function ih(t,e,i,s,r,n){void 0===i&&(i=e.getBoundingClientRect()),void 0===n&&(n=!1);var a=qu(e);return n&&a.lastKnownSize&&(0===i.height||0===i.width)&&(i=a.lastKnownSize),a.lastKnownSize=i,{schema:xu.ELEMENT_DETAILS,data:{element_name:t.name,width:i.width,height:i.height,position_x:i.x,position_y:i.y,doc_position_x:i.x+window.scrollX,doc_position_y:i.y+window.scrollY,element_index:s,element_matches:r,originating_page_view:a.originalPageViewId,attributes:Zu(e,t.selector,t.details)}}}!function(t){t.ALWAYS="always",t.ELEMENT="element",t.ONCE="once",t.NEVER="never",t.PAGEVIEW="pageview"}(Yu||(Yu={}));var sh,rh=function(t,e){for(var i=[],s=2;s<arguments.length;s++)i[s-2]=arguments[s];var r=i.filter(function(t){return t instanceof Node&&Qu(t)}),n=i.find(function(t){return"string"==typeof t});if(!r.length)return null;var a=[],o=[];r.forEach(function(i){e.forEach(function(e){if(e.component){var s=i.closest(e.selector);null!==s&&(a.push(e.name),t&&e.details&&o.push(ih(e,s)))}})});var l={schema:xu.COMPONENT_PARENTS,data:{element_name:n,component_list:a}};return a.length?t?cd([l],o,!0):l:null};!function(t){t[t.INITIAL=0]="INITIAL",t[t.CONFIGURED=1]="CONFIGURED"}(sh||(sh={}));var nh,ah,oh,lh={when:"always"},dh=function(){return[]};function ch(t,e,i,s,r,n){var a=t.selector,o=t.name,l=void 0===o?a:o,d=t.shadowSelector,c=t.shadowOnly,u=void 0!==c&&c,h=t.id,f=t.component,g=void 0!==f&&f;if("string"!=typeof l||!l)throw new Error("Invalid element name value: ".concat(l));if("string"!=typeof a||!a)throw new Error("Invalid element selector value: ".concat(a));document.querySelector(a),d&&document.querySelector(d);var m=t.create,p=void 0!==m&&m,v=t.destroy,y=void 0!==v&&v,E=t.expose,T=void 0===E||E,S=t.obscure,b=[p,y,void 0!==S&&S].map(function(t){if(!t)return{when:Yu.NEVER};if("object"==typeof t){var e=t.when,i=void 0===e?"always":e,s=t.condition;if(s&&!Ju(s))throw new Error("Invalid data selector provided for c
22ondition");if(i.toUpperCase()in Yu)return{when:i.toLowerCase(),condition:s};throw new Error("Unknown tracking frequency: ".concat(i))}return lh}),A=b[0],k=b[1],L=b[2];A.when===Yu.NEVER&&k.when===Yu.NEVER||s||null==r||r.warn("MutationObserver API unavailable but required for events in configuration:",t);var I=null;if(T&&"object"==typeof T){var w=T.when,R=void 0===w?"always":w,_=T.condition,D=T.boundaryPixels,P=void 0===D?0:D,x=T.minPercentage,C=void 0===x?0:x,O=T.minSize,M=void 0===O?0:O,F=T.minTimeMillis,N=void 0===F?0:F;if(_&&!Ju(_))throw new Error("Invalid data selector provided for condition");if("number"!=typeof P&&!Array.isArray(P)||"number"!=typeof C||"number"!=typeof M||"number"!=typeof N)throw new Error("Invalid expose options provided");if(!(R.toUpperCase()in Yu))throw new Error("Unknown tracking frequency: ".concat(R));I={when:R.toLowerCase(),condition:_,boundaryPixels:P,minPercentage:C,minSize:M,minTimeMillis:N}}else I=T?ad(ad({},lh),{boundaryPixels:0,minPercentage:0,minSize:0,minTimeMillis:0}):{when:Yu.NEVER,boundaryPixels:0,minPercentage:0,minSize:0,minTimeMillis:0};I.when===Yu.NEVER&&L.when===Yu.NEVER||i||null==r||r.warn("IntersectionObserver API unavailable but required for events in configuration:",t);var U=t.details,B=void 0===U?[]:U,$=t.contents,G=void 0===$?[]:$,V=t.includeStats,K=void 0===V?[]:V;if(Array.isArray(B)||(B=null==B?[]:[B]),Array.isArray(G)||(G=null==G?[]:[G]),Array.isArray(K)||(K=null==K?[]:[K]),B.length!==B.filter(Ju).length)throw new Error("Invalid DataSelector given for details");return{name:l,selector:a,id:h,shadowSelector:d,shadowOnly:u,create:A,destroy:k,expose:I,obscure:L,component:!!g,details:B,includeStats:K,contents:G.map(function(t){var e;return ch(t,null!==(e=t.context)&&void 0!==e?e:dh,i,s,r,n)}),context:"function"==typeof e?e:function(){return e},trackers:n,state:sh.INITIAL}}var uh={},hh=[],fh="undefined"==typeof WeakSet?Set:WeakSet,gh=((nh={})[Pu.ELEMENT_CREATE]=new Set,nh[Pu.ELEMENT_DESTROY]=new Set,nh[Pu.ELEMENT_EXPOSE]=new Set,nh[Pu.ELEMENT_OBSCURE]=new Set,nh),mh=((ah={})[Pu.ELEMENT_CREATE]=new fh,ah[Pu.ELEMENT_DESTROY]=new fh,ah[Pu.ELEMENT_EXPOSE]=new fh,ah[Pu.ELEMENT_OBSCURE]=new fh,ah),ph=((oh={})[Pu.ELEMENT_CREATE]=new fh,oh[Pu.ELEMENT_DESTROY]=new fh,oh[Pu.ELEMENT_EXPOSE]=new fh,oh[Pu.ELEMENT_OBSCURE]=new fh,oh),vh=void 0,yh=!1,Eh=!1,Th="";function Sh(t){var e={}.ignoreNextPageView;return(void 0===e||e)&&Object.values(gh).forEach(function(t){t.add("initial")}),{activateBrowserPlugin:function(t){uh[t.id]=t,Th=t.getPageViewId(),bh()},afterTrack:function(t){if("pv"===t.e){var e=t.tna;"string"==typeof e&&e in uh&&(Th=uh[e].getPageViewId()),Object.values(gh).forEach(function(t){t.has("initial")?t.delete("initial"):t.clear()})}},beforeTrack:function(t){var e,i=t.getPayload().e;if("pv"===i)e="page_view";else if("pp"===i)e="page_ping";else if("se"===i)e="event";else if("tr"===i)e="transaction";else if("ti"===i)e="transaction_item";else{if("ue"!==i)return;for(var s=0,r=t.getJson();s<r.length;s++){var n=r[s];if("ue_px"===n.keyIfEncoded){var a=n.json.data.schema;e=a.split("/")[1]}}}
22hh.forEach(function(i){(i.includeStats.includes(e)||i.includeStats.includes("*"))&&Xu(i).forEach(function(e,s,r){t.addContextEntity(function(t,e,i,s){var r=qu(e),n=Wu[r.state],a=e.getBoundingClientRect(),o=[a.width,a.height],l=zu(o,r.minSize)<=0?o:r.minSize,d=zu(o,r.maxSize)<0?r.maxSize:o,c=window.visualViewport?window.visualViewport.height+window.visualViewport.pageTop:window.innerHeight+window.scrollY,u=[Math.min(c,a.top+a.height)-a.top,a.height],h=void 0===r.maxDepth||0===r.maxDepth[1]?u:0===u[1]?r.maxDepth:u[0]/u[1]>r.maxDepth[0]/r.maxDepth[1]?u:r.maxDepth;return Object.assign(r,{minSize:l,maxSize:d,maxDepth:h}),{schema:xu.ELEMENT_STATISTICS,data:{element_name:t,element_index:i,element_matches:s,current_state:n,min_size:l.join("x"),current_size:o.join("x"),max_size:d.join("x"),y_depth_ratio:0===u[1]?null:u[0]/u[1],max_y_depth_ratio:0===h[1]?null:h[0]/h[1],max_y_depth:h.join("/"),element_age_ms:Math.floor(performance.now()-(r.createdTs-performance.timeOrigin)),times_in_view:r.views,total_time_visible_ms:Math.floor(r.elapsedVisibleMs)}}}(i.name,e,s+1,r.length))})})},logger:function(t){vh=t}}}function bh(){yh||(yh="function"==typeof MutationObserver&&new MutationObserver(wh))&&yh.observe(document.documentElement,{attributes:!0,childList:!0,subtree:!0}),Eh=Eh||"function"==typeof IntersectionObserver&&new IntersectionObserver(Rh)}rh.bind(null,!1,hh);var Ah,kh=rh.bind(null,!0,hh);function Lh(t,e,i,s){var r,n,a=null!=s?s:{},o=a.boundingRect,l=a.position,d=a.matches,c={schema:t,data:{element_name:e.name}},u=((r={})[Pu.ELEMENT_CREATE]=e.create.condition,r[Pu.ELEMENT_DESTROY]=e.destroy.condition,r[Pu.ELEMENT_EXPOSE]=e.expose.condition,r[Pu.ELEMENT_OBSCURE]=e.obscure.condition,r);if(!u[t]||th(i,e.selector,u[t]).length){switch(((n={})[Pu.ELEMENT_CREATE]=e.create.when,n[Pu.ELEMENT_DESTROY]=e.destroy.when,n[Pu.ELEMENT_EXPOSE]=e.expose.when,n[Pu.ELEMENT_OBSCURE]=e.obscure.when,n)[t]){case Yu.NEVER:return;case Yu.ALWAYS:break;case Yu.ONCE:if(ph[t].has(e))return;ph[t].add(e);break;case Yu.ELEMENT:if(mh[t].has(i))return;mh[t].add(i);break;case Yu.PAGEVIEW:if(gh[t].has(i))return;gh[t].add(i)}var h=[];h.push.apply(h,e.context(i,e)),e.details&&h.push(ih(e,i,o,l,d,t===Pu.ELEMENT_DESTROY||t===Pu.ELEMENT_OBSCURE)),e.contents.length&&h.push.apply(h,eh(e,i,l));var f=kh(e.name,i);f&&h.push.apply(h,f),setTimeout(eu,0,e.trackers,uh,function(t){var e=ic({event:c});t.core.track(e,h)})}}function Ih(t,e,i){if(Qu(i)&&i.matches(e.selector)){var s=qu(i,{originalPageViewId:Th});s.state=Ou.CREATED,s.createdTs=t,s.matches.add(e),Lh(Pu.ELEMENT_CREATE,e,i),e.expose.when!==Yu.NEVER&&Eh&&Eh.observe(i)}}function wh(t){var e=performance.now()+performance.timeOrigin;t.forEach(function(t){hh.forEach(function(i){var s=Ih.bind(null,e,i);if("attributes"===t.type){if(Qu(t.target)){var r=t.target,n=qu(r,{originalPageViewId:Th});n.state!==Ou.INITIAL?r.matches(i.selector)?n.matches.has(i)||s(r):n.matches.has(i)&&(n.state===Ou.EXPOSED&&Lh(Pu.ELEMENT_OBSCURE,i,r),Lh(Pu.ELEMENT_DESTROY,i,r),n.matches.delete(i),Eh&&Eh.unobserve(r),n.state=Ou.DESTROYED):s(r)}}else if("childList"===t.type){var a=Xu(i);t.addedNodes.forEach(function(t){a.filter(function(e){return t.contains(e)}).forEach(s)}),t.removedNodes.forEach(function(t){if(Qu(t)){var e=t.matches(i.selector)?[t]:[];e.push.apply(e,Xu(i,t)),e.forEach(function(t){var e=qu(t,{originalPageViewId:Th});e.state===Ou.EXPOSED&&Lh(Pu.ELEMENT_OBSCURE,i,t),Lh(Pu.ELEMENT_DESTROY,i,t),Eh&&Eh.unobserve(t),e.state=Ou.DESTROYED})}})}})})}function Rh(t,e){t.forEach(function(t){var i=void 0,s=qu(t.target,{lastObservationTs:t.time,originalPageViewId:Th});hh.forEach(function(r){if(t.target.matches(r.selector)){var n=Xu(r),a=n.findIndex(function(e){return e.isSameNode(t.target)})+1;if(t.isIntersecting){if(s.state!==Ou.EXPOSED&&s.state!==Ou.PENDING&&Object.assign(s,{state:Ou.PENDING,lastObservationTs:t.time,views:s.views+1}),s.state===Ou.PENDING&&function(t,e){if(t.expose.when===Yu.NEVER)return!1;if(!e.isIntersecting)return!1;var i=t.expose,s=i.boundaryPixels,r=i.minPercentage,n=i.minSize,a=function(t){var e,i,s,r;return"number"==typeof t?e=i=s=r=t:Array.isArray(t)?2===t.length?(e=s=t[0],i=r=t[1]):4===t.length?(e=t[0],i=t[1],s=t[2],r=t[3]):e=i=s=r=0:e=i=s=r=0,{boundTop:e,boundRight:i,boundBottom:s,boundLeft:r}}(s),o=a.boundTop,l=a.boundRight,d=a.boundBottom,c=a.boundLeft,u=e.boundingClientRect;return!(u.height*u.width<n||r>e.intersectionRect.height*e.intersectionRect.width/((e.boundingClientRect.height+o+d)*(e.boundingClientRect.width+c+l)))}(r,t)&&r.expose.minTimeMillis<=s.elapsedVisibleMs&&(s.state=Ou.EXPOSED,Lh(Pu.ELEMENT_EXPOSE,r,t.target,{boundingRect:t.boundingClientRect,position:a,matches:n.length})),s.state===Ou.PENDING||s.state===Ou.EXPOSED){var o=s.elapsedVisibleMs+(t.time-s.lastObservationTs);Object.assign(s,{lastObservationTs:t.time,elapsedVisibleMs:o}),i||(i=requestAnimationFrame(function(){e.unobserve(t.target),e.observe(t.target)}))}}
22else s.state===Ou.EXPOSED&&Lh(Pu.ELEMENT_OBSCURE,r,t.target,{boundingRect:t.boundingClientRect,position:a,matches:n.length}),Object.assign(s,{state:s.state===Ou.DESTROYED?Ou.DESTROYED:Ou.OBSCURED,lastObservationTs:t.time})}})})}class _h{constructor(t){this.storageKey=t}bufferEvent(t){const e=this.getBufferedEvents();e.push(t),localStorage.setItem(this.storageKey,JSON.stringify(e))}getBufferedEvents(){var t;return JSON.parse(null!==(t=localStorage.getItem(this.storageKey))&&void 0!==t?t:"[]")}clearBufferedEvents(){localStorage.removeItem(this.storageKey)}processBufferedEvents(t){this.getBufferedEvents().forEach(e=>t(e)),this.clearBufferedEvents()}}function Dh(){var t,e;return!!(null===(e=null===(t=null===window||void 0===window?void 0:window.webkit)||void 0===t?void 0:t.messageHandlers)||void 0===e?void 0:e.getAppId)}function Ph(){var t;return void 0!==window.TV2JSBridge&&"function"==typeof(null===(t=window.TV2JSBridge)||void 0===t?void 0:t.getAppId)}class xh{constructor(t={},e="snowplowBufferedEvents"){this.snowplowTrackingOptions=t,this.bufferManager=new _h(e)}initializeTracker(){return ld(this,0,void 0,function*(){try{const{platform:t="web",appId:e="tv2no",environment:i="development"}=this.snowplowTrackingOptions,s=function(t){return Dh()||Ph()?"app":t}(t),r=yield function(t){return ld(this,0,void 0,function*(){return Dh()?(yield function(){return ld(this,0,void 0,function*(){var t,e;if(null===(e=null===(t=window.webkit)||void 0===t?void 0:t.messageHandlers)||void 0===e?void 0:e.getAppId){const t=yield window.webkit.messageHandlers.getAppId.postMessage("getAppId");return""!==t?t:null}return null})}())||t:Ph()&&(yield function(){return ld(this,0,void 0,function*(){var t;return(null===(t=window.TV2JSBridge)||void 0===t?void 0:t.getAppId)?window.TV2JSBridge.getAppId():null})}())||t})}(e);this.setupTracker(r,s,i)}catch(t){Eu.error("Error during tracker initialization:",t)}})}shouldDecorateLink(t){return!!t.hostname&&!["javascript:","mailto:","tel:","data:","file:"].some(e=>t.href.startsWith(e))&&t.hostname!==window.location.hostname&&["play.tv2.no","id.tv2.no"].includes(t.hostname)}getCrossDomainLinkReason(t){var e;const i=t.currentTarget;return(null==i?void 0:i.getAttribute("data-tracking-reason"))||(null===(e=null==i?void 0:i.textContent)||void 0===e?void 0:e.trim())||"unknown"}setupTracker(t,e,i){const s=function(t){switch(t){case"local":return"http://localhost:9090";case"test":case"dev":case"development":default:return"https://06a9d123-d3f4-4383-86e6-8793c221d241.apps.snowplowanalytics.com";case"qa":case"stage":case"staging":return"https://no-tv2-qa1.collector.snplow.net";case"prod":case"production":return"https://t.tv2.no"}}(i);(function(t,e,i){lu&&function(t,e,i,s,r,n){Zc.hasOwnProperty(t)||(Zc[t]=Jc(t,e,i,s,r,n),Zc[t])}("sp","sp","js-".concat("4.6.9"),e,lu,i)})(0,s,{appId:t,platform:e,discoverRootDomain:!0,cookieSameSite:"Lax",plugins:[{activateBrowserPlugin:function(t){Uu[t.id]=t},logger:function(t){Gu=t}},Sh()],crossDomainLinker:t=>this.shouldDecorateLink(t),useExtendedCrossDomainLinker:{sessionId:!0,userId:!0,reason:t=>this.getCrossDomainLinkReason(t)}}),Eu.info(`Snowplow tracker initialized with appId: ${t}, platform: ${e}, collectorUrl: ${s}`)}setupUserContext(){Eu.info("Setting up user context");let t=!1;const e=e=>{t||(au([uu({user_id:e})]),t=!0,Eu.info("User context set",{userId:e}))},i=()=>ld(this,0,void 0,function*(){if(window.TV2&&"function"==typeof window.TV2.getLoggedInUser)try{const t=yield window.TV2.getLoggedInUser();if(t&&t.id)return e(t.id),!0}catch(t){Eu.error("Error calling getLoggedInUser",t)}return!1}),s=t=>{(t=>{if(void 0===t.detail.isAuthenticated||void 0===t.detail.userId)return Eu.info("Received Auth0 event without required properties, waiting for valid data"),!1;const i=t.detail.userId;return e(i),!0})(t)&&document.removeEventListener("tv2-menu:auth0-ready",s)};document.addEventListener("tv2-menu:auth0-ready",s),i().then(e=>{e||setTimeout(()=>ld(this,0,void 0,function*(){t||(Eu.info("Performing fallback check"),yield i())}),2e3)})}setGlobalContexts(t){try{au(t),Eu.info("Global contexts added.")}catch(t){Eu.error("Error adding global contexts:",t)}}enableActivityTracking(t=5,e=15){try{!function(t){tu(void 0,function(e){e.enableActivityTracking(t)})}({minimumVisitLength:t,heartbeatDelay:e}),Eu.info(`Activity tracking enabled: minimum visit length = ${t}
22s, heartbeat delay = ${e}s`)}catch(t){Eu.error("Error enabling activity tracking:",t)}}trackEvent(t,e){try{t(Object.assign({},e)),Eu.debug(`${t.name} tracked.`)}catch(e){Eu.error(`Error tracking with ${t.name}:`,e)}}trackUserAction(t){this.trackEvent(mu,t)}trackUserLogin(t){this.trackEvent(vu,t)}trackPaywallImpression(t){this.trackEvent(pu,t)}trackLoginSuccess(t){try{(function(t){const e=du({id:"ef7ff526-5457-4c21-a80f-169db255f600",name:"TV2 login success",data_product_id:"41cff7e9-1323-4281-b799-b035e15333a0",data_product_name:"TV2.NO Login"}),i=Array.isArray(t.context)?[...t.context,e]:[e];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2_login_success/jsonschema/1-0-0",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:i}),void 0)})({context:[gu(t)]}),Eu.debug("trackTv2LoginSuccessSpec tracked.")}catch(t){Eu.error("Error tracking with trackTv2LoginSuccessSpec:",t)}}trackLoginImpression(t){try{(function(t){const e=du({id:"2ea387fc-ca09-47c2-8f5b-706a04515c2c",name:"TV2 login impression",data_product_id:"41cff7e9-1323-4281-b799-b035e15333a0",data_product_name:"TV2.NO Login"}),i=Array.isArray(t.context)?[...t.context,e]:[e];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2_login_impression/jsonschema/1-0-0",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:i}),void 0)})({context:[gu(t)]}),Eu.debug("trackTv2LoginImpressionSpec tracked.")}catch(t){Eu.error("Error tracking with trackTv2LoginImpressionSpec:",t)}}trackPageView(t){try{const e=Object.assign(Object.assign({},(null==t?void 0:t.pageTitle)&&{title:t.pageTitle}),{context:(null==t?void 0:t.contexts)||[],timestamp:{type:"dtm",value:Date.now()}});if(null==t?void 0:t.shouldBuffer){const t={type:"page_view",data:e};this.bufferManager.bufferEvent(t),Eu.info("Page view event buffered.")}else ru(e),Eu.info("Track pageview")}catch(t){Eu.error("Error tracking page view:",t)}}processBufferedEvents(){this.bufferManager.processBufferedEvents(t=>{const{type:e,data:i}=t;switch(e){case"page_view":ru(i);break;case"self_describing":break;default:Eu.warn(`Unknown buffered event type: ${e}`)}})}startElementImpressionTracking(t){try{(function(t){var e=t.elements,i=void 0===e?[]:e,s=t.context,r=Array.isArray(i)?i:[i];r.length&&bh(),r.forEach(function(t){try{var e=function(t,e){return function i(s,r){for(var n=[],a=0,o=[t,e];a<o.length;a++){var l=o[a];l&&("function"==typeof l?l!==i&&n.push.apply(n,l(s,r)):n.push.apply(n,l))}return n}}(s,t.context),i=ch(t,e,!!Eh,!!yh,vh,void 0);if(i.id){var r=hh.findIndex(function(t){return t.id===i.id});r>-1?hh[r]=i:hh.push(i)}else hh.push(i)}catch(e){null==vh||vh.error("Failed to process Element Tracking configuration",e,t)}}),hh.forEach(function(t){var e=t.expose,i=t.obscure;if(t.state===sh.INITIAL){t.state=sh.CONFIGURED;var s=Xu(t);s.forEach(function(r,n){var a=qu(r,{originalPageViewId:Th});a.lastPosition=n,a.matches.add(t),Lh(Pu.ELEMENT_CREATE,t,r,{position:n+1,matches:s.length}),!Eh||e.when===Yu.NEVER&&i.when===Yu.NEVER||Eh.observe(r)})}})})(t),Eu.info("Element impression tracking started")}catch(t){Eu.error("Error starting element impression tracking:",t)}}endElementImpressionTracking(t){try{!function(t){if(t){if("elementIds"in t){var e=t.elementIds,i=Array.isArray(e)?e:[e],s=hh.filter(function(t){var e=t.id;return!("string"==typeof e&&i.includes(e))});hh.splice.apply(hh,cd([0,hh.length],s,!1))}if("elements"in t){var r=t.elements,n=Array.isArray(r)?r:[r];s=hh.filter(function(t){var e=t.name;return n.includes(e)}),hh.splice.apply(hh,cd([0,hh.length],s,!1))}"filter"in t&&"function"==typeof t.filter&&(s=hh.filter(function(e){try{return!0!==t.filter(e)}catch(t){return!0}}),hh.splice.apply(hh,cd([0,hh.length],s,!1)))}else hh.length=0;hh.length||(Eh&&Eh.disconnect(),yh&&yh.disconnect(),yh=Eh=!1)}(t),Eu.info("Element impression tracking ended")}catch(t){Eu.error("Error ending element impression tracking:",t)}}enableLinkClickTracking(){try{Vu(),Eu.info("Link click tracking enabled.")}catch(t){Eu.error("Error enabling link click tracking:",t)}}}class Ch{constructor(){this.currentContexts=[]}setContext(t,e){try{this.currentContexts.length>0&&ou(this.currentContexts),this.currentContexts=[uu(t),...e?[(i=e,{schema:"iglu:no.tv2/tv2no_livesport/jsonschema/4-1-0",data:i})]:[]],au(this.currentContexts)}catch(t){Eu.error("Failed to set global contexts in LivesportTracker:",t)}var i}trackFollowAction(t){const{intention:e}=t;try{(function(t,e){const i=du({id:"130251dd-3107-4be6-a851-ba27c5373cd8",name:"Follow Favourite Action",data_product_id:"31f57dca-da9d-4b60-a74f-01d7379d2520",data_product_name:"TV2.NO Livesport Tracking"}),s=Array.isArray(t.context)?[...t.context,i]:[i];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2no_livesport_follow/jsonschema/3-0-0",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:s}),e)})(t),Eu.debug(`Livesport ${e} event tracked`)}catch(t){Eu.error(`Error tracking livesport ${e} event:`,t)}}trackUserAction(t,e){try{!function(t){const e=du({id:"aaf1256e-f0e7-4455-9b03-7e0a7f24af8a",
22name:"Livesport User Action",data_product_id:"31f57dca-da9d-4b60-a74f-01d7379d2520",data_product_name:"TV2.NO Livesport Tracking"}),i=Array.isArray(t.context)?[...t.context,e]:[e];hu(Object.assign(Object.assign({},t),{context:i}),void 0)}(Object.assign(Object.assign({},t),e?{context:[fu(e)]}:{})),Eu.debug("Livesport user action event tracked")}catch(t){Eu.error("Error tracking livesport user action event:",t)}}}class Oh{constructor(){this.videoSessionId=wd(),this.videoPulses=void 0,this.currentVideoContexts=[],this.videoProgress=(t,e,i)=>{this.videoPulses||(this.videoPulses={firstQuartileFired:!1,secondQuartileFired:!1,thirdQuartileFired:!1});const s=t=>{const s=Math.round(e);!function(t,e){const i=du({id:"eb568b7e-a559-41c6-b1fd-4d25c047d4ba",name:"Video quartile",data_product_id:"4e9792d1-a590-4f18-bab6-c2b3b953e981",data_product_name:"TV2.NO Video Reels Tracking"}),s=Array.isArray(t.context)?[...t.context,i]:[i];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2no_video_quartile/jsonschema/1-0-0",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:s}),e)}({pulsePercent:`${t}%`,position:`${s}`,percentageComplete:`${i>0?Math.round(s/i*100):0}%`})};t>=25&&!this.videoPulses.firstQuartileFired&&(this.videoPulses.firstQuartileFired=!0,s(25)),t>=50&&!this.videoPulses.secondQuartileFired&&(this.videoPulses.secondQuartileFired=!0,s(50)),t>=75&&!this.videoPulses.thirdQuartileFired&&(this.videoPulses.thirdQuartileFired=!0,s(75))}}setAsset(t){this.videoPulses={firstQuartileFired:!1,secondQuartileFired:!1,thirdQuartileFired:!1},Eu.log("Setting asset for video tracking:",t.asset),this.updateVideoContexts(t)}updateVideoContexts({asset:t,category:e,numberOfVideosWatched:i}){this.currentVideoContexts.length>0&&ou(this.currentVideoContexts);const s=(r=(({asset:t,category:e,videoSessionId:i,numberOfVideosWatched:s})=>({assetId:t.id,assetName:t.title,videoCategory:e,categoryTypeOfAction:t.categoryTypeOfAction,videoLive:t.isLive,videoName:t.title,videoTags:t.tags,publishedDate:t.publishedDate,numberOfVideosWatched:s,videoSessionId:i}))({asset:t,category:e,numberOfVideosWatched:i,videoSessionId:this.videoSessionId}),{schema:"iglu:no.tv2/tv2no_video/jsonschema/5-1-0",data:r});var r;this.currentVideoContexts=[s,{schema:"iglu:no.tv2/tv2no_video_player/jsonschema/1-0-0",data:{videoPlayerName:"TV 2 Klipp",videoPlayerVersion:"latest"}}],au(this.currentVideoContexts)}videoStart(t){try{(function(t,e){const i=du({id:"bca75448-3c30-44b1-b81f-43010b50c40d",name:"Video start",data_product_id:"4e9792d1-a590-4f18-bab6-c2b3b953e981",data_product_name:"TV2.NO Video Reels Tracking"}),s=Array.isArray(t.context)?[...t.context,i]:[i];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2no_video_start/jsonschema/2-0-0",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:s}),e)})({context:t?[(e=t,{schema:"iglu:no.tv2/tv2no_video_orientation_metadata/jsonschema/2-0-0",data:e})]:[]}),Eu.debug("Logging video start event")}catch(t){Eu.error("Error tracking video start event:",t)}var e}trackVideoOrientation(t){try{!function(t){const e=du({id:"49c64686-cd59-4165-b4f2-654ebc25a372",name:"Video orientation",data_product_id:"4e9792d1-a590-4f18-bab6-c2b3b953e981",data_product_name:"TV2.NO Video Reels Tracking"}),i=Array.isArray(t.context)?[...t.context,e]:[e];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2no_video_orientation/jsonschema/2-0-0",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:i}),void 0)}(t)}catch(t){Eu.error("Error tracking video orientation event:",t)}}adStart(t){try{(function(t){const e=du({id:"4bee41fc-9407-465e-b25e-ea2805f1b951",name:"Ad start",data_product_id:"4e9792d1-a590-4f18-bab6-c2b3b953e981",data_product_name:"TV2.NO Video Reels Tracking"}),i=Array.isArray(t.context)?[...t.context,e]:[e];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2no_ad_start/jsonschema/2-0-0",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:i}),void 0)})({adUnitPath:t}),Eu.debug("Logging ad start event")}catch(t){Eu.error("Error tracking ad start event:",t)}}videoInteraction(t){try{this.trackVideoInteraction(t)}catch(e){Eu.error(`Error tracking video ${t.interactionType} event:`,e)}}videoMute(t){const{muted:e,actionLabel:i}=t;try{(function(t,e){const i=du({id:"b70d86c7-9a21-4e87-aa6c-1f3ba7aea709",name:"Video mute",data_product_id:"4e9792d1-a590-4f18-bab6-c2b3b953e981",data_product_name:"TV2.NO Video Reels Tracking"}),s=Array.isArray(t.context)?[...t.context,i]:[i];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2no_video_mute/jsonschema/1-1-0",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:s}),e)})(t),Eu.debug(`Video ${i} event tracked`,t)}catch(t){Eu.error(`Error tracking video ${e?"mute":"unmute"} event:`,t)}}videoEnd(){try{(function(t){const e=du({id:"1454ac78-8aae-416a-bb3e-d58bbf01e8b9",name:"Video end",data_product_id:"4e9792d1-a590-4f18-bab6-c2b3b953e981",data_product_name:"TV2.NO Video Reels Tracking"}),i=Array.isArray(t.context)?[...t.context,e]:[e];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2no_video_end/jsonschema/1-0-0",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:i}),void 0)})({}),Eu.debug("Video end event tracked")}catch(t){Eu.error("Error tracking video end event:",t)}}videoPlaybackEndedOrSkipped(t){try{(function(t){const e=du({id:"8bb96e05-60ec-4f01-a9db-55aef75c1b81",name:"Video playback ended or skipped",data_product_id:"4e9792d1-a590-4f18-bab6-c2b3b953e981",data_product_name:"TV2.NO Video Reels Tracking"}),i=Array.isArray(t.context)?[...t.context,e]:[e];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2no_video_playback_ended_or_skipped/jsonschema/1-0-0",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:i}),void 0)})(t),Eu.debug("Video playback ended or skipped event tracked:",t)}catch(t){Eu.error("Error tracking video playback ended or skipped event:",t)}}navigateBetweenVideos(t){try{(function(t){const e=du({id:"07c87493-46fb-441c-b259-4603c71b30bc",name:"Video navigation event",data_product_id:"4e9792d1-a590-4f18-bab6-c2b3b953e981",data_product_name:"TV2.NO Video Reels Tracking"}),i=Array.isArray(t.context)?[...t.context,e]:[e];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2no_video_navigation_event/jsonschema/1-0-0",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:i}),void 0)})({videoLabel:t}),Eu.debug("Navigating between videos")}catch(t){Eu.error("Error navigating between videos:",t)}}closeButtonClickedOrTapped(t,e){try{(function(t,e){const i=du({id:"2c295eee-f3c5-41b0-b9d4-3ebab1dc7fe6",name:"Video close button event",data_product_id:"4e9792d1-a590-4f18-bab6-c2b3b953e981",data_product_name:"TV2.NO Video Reels Tracking"}),s=Array.isArray(t.context)?[...t.context,i]:[i];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2no_video_close_button_event/jsonschema/3-1-0",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:s}),e)})({percentageOfVideoWatched:t,durationWatchedVideo:e}),Eu.debug("Close navigation button clicked or tapped")}catch(t){Eu.error("Error tracking close category button:",t)}}shareButtonClickedOrTapped(){try{(function(t){const e=du({id:"02533083-594b-4ea0-8abe-e07b4055b7f5",name:"Video share button event",data_product_id:"4e9792d1-a590-4f18-bab6-c2b3b953e981",data_product_name:"TV2.NO Video Reels Tracking"}),i=Array.isArray(t.context)?[...t.context,e]:[e];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2no_video_share_event/jsonschema/2-0-0",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:i}),void 0)})({}),Eu.debug("Share button clicked or tapped")}catch(t){Eu.error("Error tracking Share button:",t)}}linkButtonClickedOrTapped(t,e,i,s,r){try{(function(t,e){const i=du({id:"4e105226-ed9b-479e-a403-183d6f15a5d2",name:"Video link button event",data_product_id:"4e9792d1-a590-4f18-bab6-c2b3b953e981",data_product_name:"TV2.NO Video Reels Tracking"}),s=Array.isArray(t.context)?[...t.context,i]:[i];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2no_video_link_navigation_event/jsonschema/3-2-0",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:s}),e)})({linkType:t,href:e,title:i,percentageOfVideoWatched:s,durationWatchedVideo:r}),Eu.debug("Link button clicked or tapped")}catch(t){Eu.error("Error tracking link button:",t)}}menuNavigation(t){try{(function(t){const e=du({id:"c0dea4b6-5336-4672-bdc8-cb6ad9614749",name:"Video menu navigation",data_product_id:"4e9792d1-a590-4f18-bab6-c2b3b953e981",data_product_name:"TV2.NO Video Reels Tracking"}),i=Array.isArray(t.context)?[...t.context,e]:[e];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2no_video_menu_navigation/jsonschema/1-0-0",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:i}),void 0)})(t),Eu.debug("Menu navigation event tracked:",t)}catch(t){Eu.error("Error tracking menu navigation event:",t)}}trackVideoInteraction(t){try{(function(t){const e=du({id:"40bce21e-2270-44d8-9c0f-d3f445cc9351",name:"Video interaction",data_product_id:"4e9792d1-a590-4f18-bab6-c2b3b953e981",data_product_name:"TV2.NO Video Reels Tracking"}),i=Array.isArray(t.context)?[...t.context,e]:[e];!function(t,e){const{context:i,timestamp:s}=t;nu({event:{schema:"iglu:no.tv2/tv2no_video_interaction/jsonschema/1-0-1",data:od(t,["context","timestamp"])},context:i,timestamp:s},e)}(Object.assign(Object.assign({},t),{context:i}),void 0)})(t),Eu.debug(`Video ${t.interactionType} event tracked:`,t)}catch(t){Eu.error("Error tracking video ${interactionType} event:",t)}}}class Mh{constructor(t={appId:"tv2no",cookieDomain:"tv2.no"}){this.initializedPromise=null;const{logLevel:e="WARN"}=t;Eu.setLogLevel(e),this.coreTracker=new xh(t),this.videoTracker=new Oh,this.livesportTracker=new Ch,this.componentTracker=new Du,this.articleTracker=new _u}static getInstance(t={}){return"undefined"!=typeof window&&window.snowplowTracker?(Eu.debug("Snowplow tracker already initialized"),window.snowplowTracker):(Mh.instance||(Mh.instance=new Mh(t),"undefined"!=typeof window&&(Eu.info("Snowplow tracker initialized"),window.snowplowTracker=Mh.instance)),Mh.instance)}initialize(){return this.initializedPromise||(this.initializedPromise=this.initializeInternal()),this.initializedPromise}trackAndProcessPageview(t){const e=(null==t?void 0:t.adUnitPath)?cu({adUnitPath:t.adUnitPath}):this.getAdUnitPathContext();this.coreTracker.trackPageView({pageTitle:null==t?void 0:t.pageTitle,contexts:e?[e]:[]})}initializeInternal(){return ld(this,0,void 0,function*(){try{yield this.coreTracker.initializeTracker(),this.coreTracker.setupUserContext(),this.coreTracker.enableActivityTracking(),this.coreTracker.enableLinkClickTracking();const t=this.getMetadataContext();t&&this.coreTracker.setGlobalContexts([t]),this.initializeArticleTracking(),Eu.info("Snowplow tracker fully initialized")}catch(t){throw Eu.error("Error during Snowplow tracker initialization",t),t}})}initializeArticleTracking(){"undefined"!=typeof window&&(Ru()?ku()?this.articleTracker.trackArticleVisit():this.articleTracker.cleanup():wu())}getAdUnitPathContext(){var t;return"undefined"!=typeof window&&(null===(t=window.gptSetup)||void 0===t?void 0:t.adUnitPath)?cu({adUnitPath:window.gptSetup.adUnitPath}):null}getMetadataContext(){return"undefined"!=typeof window&&window.lab_metadata?{schema:"iglu:no.tv2/tv2no_labrador_metadata/jsonschema/1-0-4",data:((t=window.lab_metadata).tags&&Array.isArray(t.tags.sectionPath)&&(0===t.tags.sectionPath.length?t.tags.sectionPath="":t.tags.sectionPath=t.tags.sectionPath.join(",")),t.assetId&&(Array.isArray(t.assetId)||(t.assetId=[t.assetId]),t.assetId=t.assetId.map(t=>Math.floor(t))),t)}:null;var t}}!function(t){t.FORWARD="FORWARD",t.BACK="BACK"}(Ah||(Ah={}));const Fh="undefined"!=typeof window,Nh=(t,e="")=>{try{return t()}catch(t){nd.warn(e,t)}},Uh=t=>{var e;if(!t)return;(null===(e=null===window||void 0===window?void 0:window.playerDebugger)||void 0===e?void 0:e.logs)||(()=>{var t;Fh&&!(null===(t=null===window||void 0===window?void 0:window.playerDebugger)||void 0===t?void 0:t.logs)&&(window.playerDebugger={logs:[]})})(),window.playerDebugger.logs.push(t);const i=new Event("playerDebuggerLogs");window.dispatchEvent(i)},Bh=t=>{var e;return null===(e=(()=>{try{return"undefined"!=typeof window&&window.localStorage?JSON.parse(localStorage.getItem("debugger")):null}catch(t){return null}})())||void 0===e?void 0:e[t]},$h="tv2klipp";class Gh{constructor(){this._kilkayaVideo=null,this.setAsset=(t,e,i)=>{if(!(null===window||void 0===window?void 0:window.kilkaya))return;const s=`${window.location.origin}/video/asset/${t.id}`;this._kilkayaVideo=Nh(()=>{var t;return null===(t=null===window||void 0===window?void 0:window.kilkaya)||void 0===t?void 0:t.getVideo(s,!1)}),Bh("kilkayaTracking")&&Uh(`Kilkaya --init video: ${s}, ${t.title} setField -> title, image, duration, contenttag)`),nd.debug("kilkaya",`Kilkaya --init video: ${s}, ${t.title} setField -> title, image, duration, contenttag)`),Bh("kilkayaTracking")&&Uh(`Kilkaya --contenttag: ${$h}`),nd.debug("kilkaya",`Kilkaya --contenttag: ${$h}`),this.setField("title",t.title),this.setField("image",t.image),this.setField("duration",t.duration),this.setField("contenttag",$h);for(const e of t.tags){const t=this.slugifyForTag(e);this.setField("tag",t),nd.debug("kilkaya",`Kilkaya --tag: "${t}"`)}this.setField("section",t.section),nd.debug("kilkaya",`Kilkaya --section: ${t.section}`),this.setField("subsection",e),nd.debug("kilkaya",`Kilkaya --subsection: ${e}`),this.setField("published",t.publishedDate),this.setField("modified",t.modifiedDate),i&&this.setField("contenttag",`pl_${i}`),"SportAutomatic"===t.videoType&&this.setField("contenttag","ai")},this.videoLoad=()=>{this._kilkayaVideo?(Nh(()=>{var t;return null===(t=this._kilkayaVideo)||void 0===t?void 0:t.load()}),Bh("kilkayaTracking")&&Uh("Kilkaya --log load (load)"),nd.debug("kilkaya","Kilkaya --log load (load)")):(Bh("kilkayaTracking")&&Uh("Kilkaya --log load: setAsset has not been called"),nd.info("kilkaya","load: setAsset has not been called"))},this.videoStart=(t,e)=>{this._kilkayaVideo?(t>=1&&t<=100&&this.setField("countabletag",`viewed_${t}`),Nh(()=>{var t;return null===(t=this._kilkayaVideo)||void 0===t?void 0:t.restart(null!=e?e:"manual")}),Bh("kilkayaTracking")&&Uh(`Kilkaya --log start video ${e||"auto"} (start)`),nd.debug("kilkaya",`Kilkaya --log start video ${e||"auto"} (start)`)):(Bh("kilkayaTracking")&&Uh("Kilkaya --log start video: setAsset has not been called"),nd.info("kilkaya","start video: setAsset has not been called"))},this.videoPause=()=>{this._kilkayaVideo&&(Nh(()=>{var t;return null===(t=this._kilkayaVideo)||void 0===t?void 0:t.pause()}),Bh("kilkayaTracking")&&Uh("Kilkaya --log pause video (pause)"),nd.debug("kilkaya","Kilkaya --log pause video (pause)"))},this.videoResume=()=>{this._kilkayaVideo&&(Nh(()=>{var t;return null===(t=this._kilkayaVideo)||void 0===t?void 0:t.resume()}),Bh("kilkayaTracking")&&Uh("Kilkaya --log resume video (resume)"),nd.debug("kilkaya","Kilkaya --log resume video (resume)"))},this.videoStop=()=>{this._kilkayaVideo&&(Nh(()=>{var t;return null===(t=this._kilkayaVideo)||void 0===t?void 0:t.stop()}),Bh("kilkayaTracking")&&Uh("Kilkaya --log stop video (stop)"),nd.debug("kilkaya","Kilkaya --log stop video (stop)"))},this.videoEnd=()=>{this._kilkayaVideo&&(Nh(()=>{var t;return null===(t=null===window||void 0===window?void 0:window.kilkaya)||void 0===t?void 0:t.finishVideo(this._kilkayaVideo)}),this._kilkayaVideo=null,Bh("kilkayaTracking")&&Uh("Kilkaya --log finish video (finishVideo)"),nd.debug("kilkaya","Kilkaya --log finish video (finishVideo)"))},this.videoRestar
22t=()=>{this._kilkayaVideo&&(Nh(()=>{var t;return null===(t=this._kilkayaVideo)||void 0===t?void 0:t.restart("restart")}),Bh("kilkayaTracking")&&Uh("Kilkaya --log restart video (restart)"),nd.debug("kilkaya","Kilkaya --log restart video (restart)"))},this.setField=(t,e)=>{this._kilkayaVideo&&null!=e&&Nh(()=>{var i;return null===(i=this._kilkayaVideo)||void 0===i?void 0:i.setField(t,e)})},this.slugifyForTag=t=>t.toString().trim().toLowerCase().replace(/æ/g,"ae").replace(/ø/g,"o").replace(/å/g,"a").normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9_]/g,"_").replace(/_{2,}/g,"_").replace(/^_+|_+$/g,"").substring(0,32)}}const Vh={nyheter:"nyheter",underholdning:"underholdning",sport:"sport",broom:"broom",serier:"serier"},Kh={UnderholdningGodMorgenNorge:"godmorgennorge"};var Hh;!function(t){t.FORWARD="FORWARD",t.BACK="BACK"}(Hh||(Hh={}));class jh{constructor(t){var e;this._options=t,this._asset=null,this.setAsset=({asset:t,category:e,numberOfVideosWatchedInSession:i,playlistId:s})=>{var r,n;this._asset=this.mapToAsset(t),nd.debug("setAsset",t,this._asset),null===(r=this._sp)||void 0===r||r.videoTracker.setAsset({asset:this._asset,category:e,numberOfVideosWatched:i}),null===(n=this._kilkaya)||void 0===n||n.setAsset(this._asset,e,s)},this.mapToAsset=t=>{var e,i;return{id:t.id,gpid:t["tv2-gpid"]||"",title:t.title,categoryTypeOfAction:t["type-of-action"]||"",image:(null===(e=t.images)||void 0===e?void 0:e.defaultUrl)||"",url:t.url,duration:Math.floor(t.duration),categoryId:(null===(i=t.category)||void 0===i?void 0:i.id)||"",publishedDate:t["event-occurrence-time"],modifiedDate:t.timestamp,isLive:t.isLive||void 0,tags:t.keywords?t.keywords.split(",").map(t=>t.trim()):[],section:this.mapToSection(t["type-of-action"]||""),videoType:t["video-type"]||""}},this.mapToSection=t=>{var e;if(t&&Kh[t])return Kh[t];const i=null!==(e=null==t?void 0:t.toLowerCase())&&void 0!==e?e:"";for(const t in Vh)if(i.includes(t))return Vh[t];return Vh.sport},this.videoStart=(t,e)=>{var i,s,r;null===(i=this._sp)||void 0===i||i.videoTracker.videoStart(e),null===(s=this._kilkaya)||void 0===s||s.videoLoad(),null===(r=this._kilkaya)||void 0===r||r.videoStart(t)},this.adStart=t=>{var e;null===(e=this._sp)||void 0===e||e.videoTracker.adStart(t)},this.videoProgress=(t,e,i)=>{var s;this._asset&&(null===(s=this._sp)||void 0===s||s.videoTracker.videoProgress(t,e,i))},this.videoPause=()=>{var t,e;this._asset&&(null===(t=this._sp)||void 0===t||t.videoTracker.videoInteraction({assetId:this._asset.id,assetName:this._asset.title,categoryTypeOfAction:this._asset.categoryTypeOfAction,interactionType:"pause"}),null===(e=this._kilkaya)||void 0===e||e.videoPause())},this.videoResume=()=>{var t,e;this._asset&&(null===(t=this._sp)||void 0===t||t.videoTracker.videoInteraction({assetId:this._asset.id,assetName:this._asset.title,categoryTypeOfAction:this._asset.categoryTypeOfAction,interactionType:"resume"}),null===(e=this._kilkaya)||void 0===e||e.videoResume())},this.videoMute=t=>{var e;this._asset&&(null===(e=this._sp)||void 0===e||e.videoTracker.videoMute(Object.assign(Object.assign({},t),{actionLabel:t.muted?"mute":"unmute"})))},this.videoEnd=()=>{var t,e;this._asset&&(null===(t=this._sp)||void 0===t||t.videoTracker.videoEnd(),null===(e=this._kilkaya)||void 0===e||e.videoEnd())},this.videoStop=()=>{var t;this._asset&&(null===(t=this._kilkaya)||void 0===t||t.videoStop())},this.videoPlaybackEndedOrSkipped=(t,e,i,s,r)=>{var n;this._asset&&(null===(n=this._sp)||void 0===n||n.videoTracker.videoPlaybackEndedOrSkipped({assetId:this._asset.id,assetName:this._asset.title,categoryTypeOfAction:this._asset.categoryTypeOfAction,direction:t,percentWatched:e,durationSec:i,watchedSec:s,numberOfVideosWatchedInSession:r}))},this.trackVideoOrientation=t=>{var e;return null===(e=this._sp)||void 0===e?void 0:e.videoTracker.trackVideoOrientation(t)},this.closeButtonClickedOrTapped=(t,e)=>{var i;null===(i=this._sp)||void 0===i||i.videoTracker.closeButtonClickedOrTapped(t,e)},this.navigateBetweenVideos=t=>{var e;null===(e=this._sp)||void 0===e||e.videoTracker.navigateBetweenVideos(t)},this.videoRestart=()=>{var t;this._asset&&(null===(t=this._kilkaya)||void 0===t||t.videoRestart())},this.videoFailure=t=>{this._asset},this.newCategoryButtonClickedOrTapped=(t,e)=>{},this.shareButtonClickedOrTapped=()=>{var t;null===(t=this._sp)||void 0===t||t.videoTracker.shareButtonClickedOrTapped()},this.copyLinkClicked=()=>{this._asset},this.reachedEndOfList=t=>{},this.entranceFromLivesportClickedOrTapped=t=>{},this.trackAndProcessPageview=t=>{var e;null===(e=this._sp)||void 0===e||e.trackAndProcessPageview(t)}
22,nd.setLogLevel(null!==(e=t.logLevel)&&void 0!==e?e:"WARN"),this._options.sp&&(this._sp=Mh.getInstance({logLevel:t.logLevel,environment:t.environment,cookieDomain:t.cookieDomain}),this._sp.initialize()),this._options.kilkaya&&((null===window||void 0===window?void 0:window.kilkaya)||nd.info("Ensure that kilkaya is loaded."),this._kilkaya=new Gh)}videoMenuNavigation(t,e){var i;null===(i=this._sp)||void 0===i||i.videoTracker.menuNavigation({category_title:t,menu_path:e})}linkButtonClickedOrTapped(t,e,i,s,r){var n;null===(n=this._sp)||void 0===n||n.videoTracker.linkButtonClickedOrTapped(t,e,i,s,r)}}const qh=t=>{if("number"!=typeof t||isNaN(t))return;const e=Math.round(t),i=Math.floor(e/3600),s=Math.floor(e%3600/60),r=e%60;return(i>0?String(i).padStart(2,"0")+":":"")+String(s).padStart(2,"0")+":"+String(r).padStart(2,"0")},Yh=(t,e)=>{const{id:i,title:s,href:r,duration:n,"loop-url":a,isLive:o}=t,{posterUrl:l,title:c,disableLoop:u,disableLink:h,hideDuration:f,useVideoPlayer:g,autoPlay:m}=e||{},p=i,v=t.assetType,y=null!=g&&g;return{assetId:p,title:null!=c?c:s,href:r,posterUrl:null!=l?l:d(t),duration:n?qh(n):void 0,loopUrl:u?void 0:a,isLive:o,useVideoPlayer:y,autoPlay:null!=m&&m,assetType:v,disableLink:!y&&null!=h&&h,hideDuration:null!=f&&f}};var Wh;class zh{constructor(t){Wh.set(this,void 0),this.lastTickTime=null,this.secondsWatched=0,s(this,Wh,new y(new q({env:t}),t),"f");const e="prod"===t;this.tracker=new jh({environment:t,logLevel:e?"WARN":"DEBUG",sp:!0,cookieDomain:e?"tv2.no":"test.tv2.no",kilkaya:e})}setAsset(t){return e(this,void 0,void 0,function*(){this.lastTickTime=null,this.secondsWatched=0,this.asset=yield i(this,Wh,"f").fetchAsset(t),this.asset&&this.tracker.setAsset({asset:this.asset,category:this.asset.isLive?"livestrommer":"",numberOfVideosWatchedInSession:0})})}videoStart(){this.asset&&this.tracker.videoStart(0)}videoPlaybackEnd(t){if(this.asset&&this.secondsWatched>0){const e=this.asset.isLive?0:c(t,this.secondsWatched);this.tracker.videoPlaybackEndedOrSkipped(Hh.FORWARD,e,this.asset.isLive?0:t,this.secondsWatched,1),this.tracker.closeButtonClickedOrTapped(Math.round(e),Math.round(this.secondsWatched))}this.lastTickTime=null}videoProgress(){if(this.asset){const t=performance.now();if(null!==this.lastTickTime){const e=(t-this.lastTickTime)/1e3;e<=2&&(this.secondsWatched+=e)}this.lastTickTime=t}}}Wh=new WeakMap;const Xh=(t=20)=>`\n  <svg width="${t}" height="${t}" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n    <path d="M14 5V7.5C16.5 7.5 18.5 9.5 18.5 12C18.5 14.5 16.5 16.5 14 16.5V19C17.85 19 21 15.85 21 12C21 8.15 17.85 5 14 5Z" fill="#FAFAFA"/>\n    <path d="M16.5 12C16.5 10.6 15.4 9.5 14 9.5V14.5C15.4 14.5 16.5 13.4 16.5 12Z" fill="#FAFAFA"/>\n    <path d="M5.5 9.5H3V14.5H5.5L9.5 20H12V4H9.5L5.5 9.5Z" fill="#FAFAFA"/>\n  </svg>\n`,Qh=(t=20)=>`\n  <svg width="${t}" height="${t}" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n    <path d="M4.04999 5.75549L6.45001 8.16301L5.5 9.46708H3V14.4828H5.5L9.5 20H12V13.7304L18.2 19.9498L19.95 18.1944L5.79999 4L4.04999 5.75549Z" fill="#FAFAFA"/>\n    <path d="M14 4.95298V7.46081C16.5 7.46081 18.5 9.46708 18.5 11.9749C18.5 12.5266 18.4 13.0784 18.2 13.5799L20.05 15.4357C20.65 14.3824 21 13.2288 21 11.9248C21 8.11285 17.85 4.95298 14 4.95298Z" fill="#FAFAFA"/>\n  </svg>\n`,Jh=(t=18)=>`\n  <svg width="${t}" height="${t}" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n    <path d="M8 4.5V19.5L19 12L8 4.5Z" fill="#FAFAFA"/>\n  </svg>\n`,Zh=()=>"\n  <style>\n    .video-gate {\n      color: #fafafa;\n      border-radius: 12px;\n      overflow: hidden;\n      height: auto;\n      width: auto;\n      aspect-ratio: var(--video-gate-aspect-ratio, 2/3);\n      position: relative;\n      display: block;\n      container: video-gate / size;\n      font-family: var(--font-tv2-display), sans-serif;\n    }\n\n    .video-gate .video-gate-link {\n      cursor: pointer;\n    }\n\n    .video-gate:has(.video-gate-link):focus-within {\n      outline: 2px solid #2684ff;\n      outline-offset: 2px;\n    }\n\n    .video-gate button:focus-visible {\n      outline: 2px solid #2684ff;\n    }\n  \n    .video-gate--wide {\n      --video-gate-aspect-ratio: 16/9;\n    }\n\n    .video-gate .container {\n      height: 100%;\n      width: 100%;\n      display: flex;\n      object-fit: cover;\n      object-position: top;\n    }\n\n    .video-gate .gradient-overlay {\n      position: absolute;\n      top: 0;\n      left: 0;\n      right: 0;\n      bottom: 0;\n      background: linear-gradient(17deg, rgba(0, 0, 0, 0.70) 0%, rgba(0, 0, 0, 0) 50%);\n      pointer-events: none;\n    }\n\n    .video-gate .gradient-inline-overlay {\n      position: absolute;\n      top: 0;\n      left: 0;\n      right: 0;\n      bottom: 0;\n      border-radius: 12px;\n      background: linear-gradient(180deg, rgba(0, 0, 0, 0.50) 0%, rgba(0, 0, 0, 0.00) 20%, rgba(0, 0, 0, 0.00) 60%, rgba(0, 0, 0, 0.50) 100%);\n      pointer-events: none;\n    }\n\n    .video-gate .ingress-overlay {\n      /* Fallback font-size */\n      font-size: 32px;\n      /* This will only apply if the browser supports container queries */\n      font-size: 10cqw;\n      line-height: 1.2;\n      font-weight: 600;\n      font-family: var(--font-tv2-display);\n      position: absolute;\n      bottom: 0;\n      left: 0; \n      color: #fff; \n      text-align: left;\n      padding: 0 16px;\n      margin-bottom: 14px;\n      display: -webkit-box; \n      -webkit-box-orient: vertical; \n      -webkit-line-clamp: 3; \n      overflow: hidden; \n      text-overflow: ellipsis;\n    }\n\n    .video-gate .inline-video-ingress {   \n      font-size: 16px;\n      font-weight: 600;\n      font-family: var(--font-tv2-text);\n    }\n\n    .video-gate .banner {\n      display: flex;\n      gap: 6px;\n      font-family: var(--font-tv2-text);\n      align-items: center;\n      justify-content: center;\n      border-radius: 6px;\n      background: #1F1031CC;\n      color: #fafafa;\n      font-size: 16px;\n      line-height: 120%;\n      font-weight: 600;\n      padding: 6px 8px;\n      max-width: max-content;\n    }\n\n    .video-gate .banner.banner-live {\n      background-color: #dc0e2a;\n      color: #fff;\n    }\n\n    .video-gate .banner.banner-duration {\n      padding: 4px 10px 4px 6px;\n      font-size: 16px;\n    }\n\n    .video-gate .banner-top-left {\n      position: absolute;\n      top: 0;\n      left: 0;\n      display: flex;\n      align-items: center;\n      justify-content: center;\n      border-radius: 12px 0 12px 0;\n    }\n\n    .video-gate .banner-bottom-left {\n      position: absolute;\n      bottom: 0;\n      left: 0;\n      margin: 16px;\n      display: flex;\n      flex-direction: column;\n      gap: 8px;\n    }\n\n    .video-gate .banner-bottom-left .banner {\n      font-size: 12px;\n    }\n\n    .video-gate .outdated {\n      background-color: rgba(0, 0, 0, 0.20) !important;\n    }\n\n    .video-gate .entrance-link {\n      position: absolute;\n      top: 0;\n      right: 0;\n      display: flex;\n      gap: 4px;\n      align-items: center;\n      justify-content: center;\n      color: #fafafa;\n      font-size: 12px;\n      padding: 6px 8px 7px;\n      max-width: max-content;\n      text-decoration: none;\n      font-family: var(--font-tv2-text);\n      outline: none;\n    }\n\n    .video-gate .with-text-shadow {\n      text-shadow: 0px 0px 4px rgba(0, 0, 0, 0.4);    \n    }\n\n    .video-gate .with-filter-shadow > svg {\n      filter: drop-shadow(0px 0px 10px rgba(0, 0, 0, 0.1));    \n    }\n\n\n    .video-gate .center-overlay {\n      visibility: hidden;\n      position: absolute;\n      top: 50%; \n      left: 50%;\n      transform: translate(-50%, -50%);\n      display: flex;\n      flex-direction: column;\n      gap: 8px;\n      justify-content: center;\n      align-items: center;\n    }
22\n\n    .video-gate .player-controls {\n      visibility: hidden;\n      position: absolute;\n      bottom: 0;\n      right: 0;\n      display: flex;\n      justify-content: center;\n      align-items: center;\n      gap: 16px;\n      padding: 16px;\n    }\n\n    .video-gate button {\n      background: none;\n      border: none;\n      cursor: pointer;\n      padding: 0; \n    }\n\n    .video-gate .round-play-button {\n      border-radius: 40px;\n      padding: 12px;\n      background: rgba(0, 0, 0, 0.60); \n      display: flex;\n      align-items: center;\n      justify-content: center;\n    }\n\n    .video-gate .round-play-button > div {\n      display: flex;\n      align-items: center;\n      justify-content: center;\n    }\n\n    .video-gate .fade-out {\n      animation: fade-out 1s ease-in-out forwards;\n    }\n\n    @keyframes fade-out {\n      from {\n        opacity: 1;\n      }\n      to {\n        opacity: 0;\n      }\n    }\n\n    .video-gate:hover .fade-out {\n      animation: none;\n      opacity: 1;\n    }\n\n    .video-gate .watch-live-button,\n    .video-gate .continue-watching-button {\n      color: #fff;\n      border-radius: 48px;\n      padding: 7px 14px;\n      line-height: 18px;\n      font-size: 12px;\n      font-weight: 600;\n      font-family: var(--font-tv2-text);\n      border: none;\n      cursor: pointer;\n    }\n\n    .video-gate .watch-live-button {\n      display: flex;\n      gap: 6px;\n      align-items: center;\n      justify-content: center;\n      background-color: #dc0e2a;\n      color: #fff;\n      width: 100%;\n      max-width: max-content;\n    }\n\n    .video-gate .watch-live-button > div {\n      height: 16px;\n      width: 16px;\n      display: flex;\n      align-items: center;\n      justify-content: center;\n    }\n\n    .video-gate .continue-watching-button {\n      background-color: #1F1031CC;\n    }\n\n  </style>\n",tf=t=>{const{href:e,isLive:i,useVideoPlayer:s,autoPlay:r,assetType:n,disableLink:a}=t,o=`\n    ${af(s)}\n    ${df(t)}\n    ${sf(i)}\n    ${nf(r)}\n    ${of(t)}\n    ${lf(t)}\n    ${hf(s,e)}\n  `;return`\n    <div class="video-gate ${"main"===n&&s?"video-gate--wide":""}">\n      ${s?o:ef(o,e,a)}\n    </div>\n  `},ef=(t,e,i=!1)=>i?`<div class="video-gate-link">${t}</div>`:`<a class="video-gate-link" href="${e}">${t}</a>`,sf=t=>`\n  <div id="pause-overlay" class="center-overlay">\n    <button id="round-play-button" class="round-play-button">\n      ${Jh(29)}\n    </button>\n  </div>\n  ${t?rf():""}\n`,rf=()=>`\n  <div id="pause-live-overlay" class="center-overlay">\n    <button id="watch-live-button" class="watch-live-button">\n        ${Jh()}\n      Se direkte\n    </button>\n    <button id="continue-watching-live-button" class="continue-watching-button">Fortsett å se</button>\n  </div>\n`,nf=t=>`\n  <div id="player-controls" class="player-controls">\n    <button id="mute-button" class="mute-button with-filter-shadow">\n        ${t?Qh():Xh()}\n    </button>\n    <button id="pause-button" class="pause-button with-filter-shadow">\n        ${((t=20)=>`\n  <svg width="${t}" height="${t}" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n    <path d="M10 5.5H5.5V18.5H10V5.5Z" fill="#FAFAFA"/>\n    <path d="M18.5 5.5H14V18.5H18.5V5.5Z" fill="#FAFAFA"/>\n  </svg>\n`)()}\n    </button>\n  </div>\n`,af=t=>`<div id="gradient-overlay" class=${t?"gradient-inline-overlay":"gradient-overlay"}></div>`,of=({isLive:t,useVideoPlayer:e,duration:i,title:s,hideDuration:r})=>t?uf(e,s):r?"":cf(i),lf=({useVideoPlayer:t,title:e})=>t?"":`<div class="ingress-overlay with-text-shadow">${e}</div>`,df=({assetId:t,autoPlay:e,loopUrl:i,posterUrl:s,useVideoPlayer:r})=>`\n  <video \n    id="video-gate-video-player-${t}" \n    class="container" \n    ${!r&&i?`muted loop autoplay src="${i}"`:""} \n    ${e?"muted autoplay":""}\n    controlslist="nodownload nofullscreen noremoteplayback"\n    playsinline\n    disablepictureinpicture \n    preload="auto" \n    poster="${s||""}">\n    Beklager, din nettleser støtter ikke avspilling av videoklipp\n  </video>\n  <img src="${s}" class="container" alt="Bilde for video" onerror="this.style.display='none'"/>
22\n`,cf=t=>t?`\n    <div id="duration-banner" class="banner banner-duration banner-top-left">\n        ${Jh()}\n      <div>${t}</div>\n    </div>\n  `:"",uf=(t,e)=>t?`\n      <div class="banner-bottom-left">\n        <button id="live-banner" class="banner banner-live">Direkte</button>\n        <div class="inline-video-ingress with-text-shadow" id="live-video-title">${e}</div>\n      </div>\n    `:`\n    <div class="banner banner-live banner-top-left">\n      ${Jh(19)}\n      <div>Direkte</div>\n    </div>\n  `,hf=(t,e)=>t?`\n    <a id="entrance-link" class="entrance-link with-filter-shadow" href="${e}">\n      <div class="entrance-link-text with-text-shadow" id="entrance-link-text">\n        GÃ¥ til fullskjerm\n      </div>\n      ${((t=20)=>`\n  <svg width="${t}" height="${t}" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n    <path d="M18.5 8.48661C18.5 7.82712 18.2382 7.19464 17.7722 6.72831C17.3063 6.26198 16.6743 6 16.0153 6L7.5 6V9H13.5L5.5 16.8914L7.60703 19L15.5 11V17H18.5V8.48661Z" fill="#FAFAFA"/>\n  </svg>\n`)()}\n  </a>\n`:"";l&&(function(){if(l){class t extends HTMLElement{constructor(){super(),this.hasTrackedPlaybackEnd=!1,this.useVideoPlayer=!1,this.observer=t.observerEnabled?new IntersectionObserver(t=>{t.forEach(t=>{t.isIntersecting||t.target.pause()})}):void 0,this.trackPlaybackEnd=()=>{var t,e,i;return null===(t=this.trackingService)||void 0===t?void 0:t.videoPlaybackEnd(null!==(i=null===(e=this.videoElement)||void 0===e?void 0:e.duration)&&void 0!==i?i:0)},this.trackPlaybackEndOnce=()=>{this.hasTrackedPlaybackEnd||(this.hasTrackedPlaybackEnd=!0,this.trackPlaybackEnd())},this.handleVisibilityChange=()=>{"hidden"===document.visibilityState?this.trackPlaybackEndOnce():"visible"===document.visibilityState&&(this.hasTrackedPlaybackEnd=!1)},this.handlePageHide=()=>this.trackPlaybackEndOnce(),this.handleBeforeUnload=()=>this.trackPlaybackEndOnce(),this.shadow=this.attachShadow({mode:"open"}),this.videoService=new sd}connectedCallback(){var o,l,d;const c=this.getAttribute("env"),u=this.getAttribute("title"),h=this.getAttribute("href"),f="true"===this.getAttribute("islive"),g=this.getAttribute("src"),m=null!==(o=this.getAttribute("posterurl"))&&void 0!==o?o:void 0,p=null!==(l=this.getAttribute("duration"))&&void 0!==l?l:void 0,v=null!==(d=this.getAttribute("loopurl"))&&void 0!==d?d:void 0,y="true"===this.getAttribute("autoplay");this.useVideoPlayer="true"===this.getAttribute("usevideoplayer");const E=this.getAttribute("data-asset-type"),T=this.getAttribute("assetId"),S="true"===this.getAttribute("disablelink"),b="true"===this.getAttribute("hideDuration");this.shadow.innerHTML=`${Zh()}${tf({assetId:T,title:u,href:h,posterUrl:m,duration:p,isLive:f,loopUrl:v,useVideoPlayer:this.useVideoPlayer,autoPlay:y,assetType:E,disableLink:S,hideDuration:b})}`,this.videoElement=this.shadow.getElementById(`video-gate-video-player-${T}`);const A=()=>{var t;null===(t=this.videoElement)||void 0===t||t.play().catch(()=>{this.videoElement&&(this.videoElement.style.display="none")})};if(!this.useVideoPlayer&&v&&this.videoElement.addEventListener("canplay",A),this.useVideoPlayer){this.trackingService=new zh(c),this.trackingService.setAsset(T);const o=this.shadow.getElementById("pause-overlay"),l=this.shadow.getElementById("pause-live-overlay"),d=this.shadow.getElementById("player-controls"),u=this.shadow.getElementById("mute-button"),h=this.shadow.getElementById("pause-button"),m=this.shadow.getElementById("live-video-title"),p=this.shadow.getElementById("entrance-link"),v=this.shadow.getElementById("duration-banner"),E=this.shadow.getElementById("live-banner"),S=this.shadow.getElementById("gradient-overlay"),b=this.shadow.getElementById("round-play-button"),A=this.shadow.getElementById("watch-live-button"),k=this.shadow.getElementById("continue-watching-live-button");let L,I=!1,w=!1;if(!this.videoElement)return;this.videoService.source=g,this.videoService.init(this.videoElement),y?this.videoService.load():(s(o),s(m));const R=()=>{I=!0,_()},_=()=>{this.videoElement&&(this.videoElement.paused?this.videoElement.play():this.videoElement.pause())},D=()=>{var t;if(this.videoElement){const e=(null!==(t=this.videoElement.duration)&&void 0!==t?t:0)-5;this.videoElement.currentTime=e,a(E,"outdated"),I=!1}},P=t=>{var e,i,s;const r=t.target;r&&(null===(e=this.trackingService)||void 0===e||e.videoProgress(),f&&(null!==(i=r.duration)&&void 0!==i?i:0)-(null!==(s=r.currentTime)&&void 0!==s?s:0)>60&&n(E,"outdated"))},x=()=>{clearTimeout(L),this.videoService.onPause(),s(f?l:o),i(E),i(d),r(m),t.observerEnabled&&this.observer&&this.observer.disconnect(),M(!1)},C=()=>{clearTimeout(L),this.videoService.onPlay(),this.trackingService&&!w&&(w=!0,this.trackingService.videoStart()),s(E),s(d),i(o),i(l),e(m),L=setTimeout(()=>{M(!0)},1e4),t.observerEnabled&&this.observer&&this.observer.observe(this.videoElement),document.addEventListener("visibilitychange",()=>{var t;document.hidden&&(null===(t=this.videoElement)||void 0===t||t.pause()),s(d)},{once:!0})},O=()=>{I&&D()},M=t=>
22{[S,m,d,o,u,h,v,E,p].forEach(e=>{t?n(e,"fade-out"):a(e,"fade-out")})},F=()=>{this.videoElement.muted?(this.videoElement.muted=!1,u.innerHTML=Xh()):(this.videoElement.muted=!0,u.innerHTML=Qh())},N=()=>this.trackPlaybackEndOnce();this.videoElement.addEventListener("timeupdate",P),this.videoElement.addEventListener("playing",O),this.videoElement.addEventListener("click",_),this.videoElement.addEventListener("pause",x),this.videoElement.addEventListener("play",C),this.videoElement.addEventListener("ended",N),null==A||A.addEventListener("click",R),null==k||k.addEventListener("click",_),null==b||b.addEventListener("click",_),null==u||u.addEventListener("click",F),null==h||h.addEventListener("click",_),null==E||E.addEventListener("click",D),document.addEventListener("visibilitychange",this.handleVisibilityChange,{capture:!0}),window.addEventListener("pagehide",this.handlePageHide,{capture:!0}),window.addEventListener("beforeunload",this.handleBeforeUnload,{capture:!0})}}disconnectedCallback(){this.useVideoPlayer&&(this.trackPlaybackEndOnce(),document.removeEventListener("visibilitychange",this.handleVisibilityChange,{capture:!0}),window.removeEventListener("pagehide",this.handlePageHide,{capture:!0}),window.removeEventListener("beforeunload",this.handleBeforeUnload,{capture:!0}))}static get tag(){return"video-gate"}}t.observerEnabled=!1;const e=t=>{t&&(t.style.display="none")},i=t=>{t&&(t.style.visibility="hidden")},s=t=>{t&&(t.style.visibility="visible")},r=t=>{t&&(t.style.display="block")},n=(t,e)=>{t&&t.classList.add(e)},a=(t,e)=>{t&&t.classList.remove(e)};customElements.get(t.tag)||customElements.define(t.tag,t)}}(),function(){if(l){class t extends HTMLElement{constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.videoService=new sd}connectedCallback(){var t;const e=this.getAttribute("env"),i=this.getAttribute("src"),s=null!==(t=this.getAttribute("posterurl"))&&void 0!==t?t:void 0,r="true"===this.getAttribute("autoplay"),n="true"===this.getAttribute("muted"),a="true"===this.getAttribute("loop"),o=this.getAttribute("assetId");this.shadow.innerHTML=`\n  <style>\n    .clean-video-player {\n      width: 100%;\n      height: 100%;\n      position: relative;\n      display: block;\n      overflow: hidden;\n      border-radius: 12px;\n    }\n\n    .clean-video-player video {\n      width: 100%;\n      height: 100%;\n      display: block;\n      object-fit: cover;\n    }\n  </style>\n${(t=>{const{assetId:e,posterUrl:i,autoPlay:s,muted:r,loop:n}=t;return`\n    <div class="clean-video-player">\n      <video\n        id="clean-video-player-${e}"\n        controls\n        playsinline\n        ${s?"autoplay":""}\n        ${r?"muted":""}\n        ${n?"loop":""}\n        ${i?`poster="${i}"`:""}\n      ></video>\n    </div>\n  `})({assetId:o,posterUrl:s,autoPlay:r,muted:n,loop:a})}`,this.videoElement=this.shadow.getElementById(`clean-video-player-${o}`),this.videoElement&&(this.videoService.source=i,this.videoService.init(this.videoElement),this.videoService.load(),e&&(this.trackingService=new zh(e),this.trackingService.setAsset(o),this.videoElement.addEventListener("play",()=>{var t;null===(t=this.trackingService)||void 0===t||t.videoStart()},{once:!0})),document.addEventListener("visibilitychange",()=>{document.hidden&&this.videoElement&&this.videoElement.pause()}))}static get tag(){return"clean-video-player"}}customElements.get(t.tag)||customElements.define(t.tag,t),t.tag}}(),function(){if(l){class t extends HTMLElement{constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){const t=document.createElement("template");t.innerHTML='\n  <style>\n    .video-unavailable-container {\n      color: #fafafa;\n      border-radius: 12px;\n      overflow: hidden;\n      height: auto;\n      width: auto;\n      aspect-ratio: 2 / 3;\n      position: relative;\n      display: block;\n      container: video-unavailable / inline-size;\n      background-color: #100118;\n    }\n\n    .video-unavailable-container .content {\n      height: 100%;\n      flex-direction: column;\n      justify-content: center;\n      align-items: center;\n      display: flex;\n    }\n\n    .video-unavailable-container .error-text {\n      color: #fafafa;\n      text-align: center;\n      padding: 0 32px;\n      font-family: "TV 2 Sans Display", sans-serif;\n      font-size: 32px;\n      font-weight: 600;\n      line-height: 110%;\n    }\n      \n    .video-unavailable-container .main-text {\n      color: #fafafa;\n      padding: 0 16px;\n      text-align: center;\n      margin-top: 30px;\n      font-size: 18px;\n      font-weight: 300;\n      line-height: 150%;\n      font-family: "TV 2 Sans Condensed", sans-serif;\n      @container video-unavailable (min-width: 350px) { padding: 0 32px; }\n      @container video-unavailable (min-width: 370px) { padding: 0 42px; }\n    }\n    \n    .main-text a {\n      color: #fafafa;\n      border-bottom: 1px solid #b2aeff;\n      text-decoration: none;\n    }\n  </style>\n\n  <div class="video-unavailable-container">\n    <div class="content">\n      <h2 class="error-text">Videoen er ikke tilgjengelig</h2>\n      <div class="main-text">Dersom problemet vedvarer kan du ta kontakt med\n        <a href="https://hjelp.play.tv2.no/" target="_blank" rel="noopener noreferrer">kundesenteret</a>\n        eller finne flere videoer\n        <a href="https://www.tv2.no/video">her</a>\n      </div>\n    </div>\n  </div>\n';const e=t.content.cloneNode(!0);this.shadow.appendChild(e)}static get tag(){return"video-gate-unavailable"}}customElements.get(t.tag)||customElements.define(t.tag,t)}}());class ff{constructor(t){this.generateStyles=()=>`\n    ${Zh()}\n    \n  <style>\n    .video-unavailable-container {\n      color: #fafafa;\n      border-radius: 12px;\n      overflow: hidden;\n      height: auto;\n      width: auto;\n      aspect-ratio: 2 / 3;\n      position: relative;\n      display: block;\n      container: video-unavailable / inline-size;\n      background-color: #100118;\n    }\n\n    .video-unavailable-container .content {\n      height: 100%;\n      flex-direction: column;\n      justify-content: center;\n      align-items: center;\n      display: flex;\n    }\n\n    .video-unavailable-container .error-text {\n      color: #fafafa;\n      text-align: center;\n      padding: 0 32px;\n      font-family: "TV 2 Sans Display", sans-serif;\n      font-size: 32px;\n      font-weight: 600;\n      line-height: 110%;\n    }\n      \n    .video-unavailable-container .main-text {\n      color: #fafafa;\n      padding: 0 16px;\n      text-align: center;\n      margin-top: 30px;\n      font-size: 18px;\n      font-weight: 300;\n      line-height: 150%;\n      font-family: "TV 2 Sans Condensed", sans-serif;\n      @container video-unavailable (min-width: 350px) { padding: 0 32px; }\n      @container video-unavailable (min-width: 370px) { padding: 0 42px; }\n    }\n    \n    .main-text a {\n      color: #fafafa;\n      border-bottom: 1px solid #b2aeff;\n      text-decoration: none;\n    }\n  </style>\n\n    \n  <style>\n    .clean-video-player {\n      width: 100%;\n      height: 100%;\n      position: relative;\n      display: block;\n      overflow: hidden;\n      border-radius: 12px;\n    }\n\n    .clean-video-player video {\n      width: 100%;\n      height: 100%;\n      display: block;\n      object-fit: cover;\n    }\n  </style>\n\n  `,this.generateMarkup=(t,e)=>t?((t,e)=>{const{assetId:i,title:s,href:r,posterUrl:n,duration:a,isLive:o,loopUrl:l,useVideoPlayer:d,assetType:c,disableLink:u,hideDuration:h}=Yh(t,e);return{styles:Zh(),markup:tf({assetId:i,title:s,href:r,posterUrl:n,duration:a,isLive:o,loopUrl:l,useVideoPlayer:d,assetType:c,disableLink:u,hideDuration:h})}})(t,e):{styles:'\n  <style>\n    .video-unavailable-container {\n      color: #fafafa;\n      border-radius: 12px;\n      overflow: hidden;\n      height: auto;\n      width: auto;\n      aspect-ratio: 2 / 3;\n      position: relative;\n      display: block;\n      container: video-unavailable / inline-size;\n      background-color: #100118;\n    }\n\n    .video-unavailable-container .content {\n      height: 100%;\n      flex-direction: column;\n      justify-content: center;\n      align-items: center;\n      display: flex;\n    }\n\n    .video-unavailable-container .error-text {\n      color: #fafafa;\n      text-align: center;\n      padding: 0 32px;\n      font-family: "TV 2 Sans Display", sans-serif;\n      font-size: 32px;\n      font-weight: 600;\n      line-height: 110%;\n    }\n      \n    .video-unavailable-container .main-text {\n      color: #fafafa;\n      padding: 0 16px;\n      text-align: center;\n      margin-top: 30px;\n      font-size: 18px;\n      font-weight: 300;\n      line-height: 150%;\n      font-family: "TV 2 Sans Condensed", sans-serif;\n      @container video-unavailable (min-width: 350px) { padding: 0 32px; }\n      @container video-unavailable (min-width: 370px) { padding: 0 42px; }\n    }\n    \n    .main-text a {\n      color: #fafafa;\n      border-bottom: 1px solid #b2aeff;\n      text-decoration: none;\n    }\n  </style>\n',markup:'\n  <div class="video-unavailable-container">\n    <div class="content">\n      <h2 class="error-text">Videoen er ikke tilgjengelig</h2>\n      <div class="main-text">Dersom problemet vedvarer kan du ta kontakt med\n        <a href="https://hjelp.play.tv2.no/" target="_blank" rel="noopener noreferrer">kundesenteret</a>\n        eller finne flere videoer\n        <a href="https://www.tv2.no/video">her</a>\n      </div>\n    </div>\n  </div>\n'},this.mountToElement=(t,i,s,r)=>e(this,void 0,void 0,function*(){let e;t.innerHTML="",e=s?(null==r?void 0:r.useVideoPlayer)&&(null==r?void 0:r.useCleanPlayer)?yield this.createCleanPlayerElement(s,i,r):yield this.createVideoGateElement(s,i,r):document.createElement("video-gate-unavailable"),t.appendChild(e)}),this.createVideoGateElement=(t,i,s)=>e(this,void 0,void 0,function*(){var e;const{title:r,href:a,posterUrl:o,duration:l,isLive:d,loopUrl:c,useVideoPlayer:u,autoPlay:h,disableLink:f,hideDuration:g}=Yh(t,s),m=document.createElement("video-gate");if(m.setAttribute("title",r),m.setAttribute("href",a),m.setAttribute("islive",`${d}`),c&&m.setAttribute("loopurl",c),o&&m.setAttribute("posterurl",o),l&&m.setAttribute("duration",l),f&&m.setAttribute("disablelink",`${f}`),g&&m.setAttribute("hideDuration",`${g}`),u){const e=yield this.dataService.getPlayRequest(null==t?void 0:t.id,n),i=null==e?void 0:e.recommendedStream.manifest.uri;i&&m.setAttribute("src",i)}return m.setAttribute("assetId",null!==(e=null==t?void 0:t.id)&&void 0!==e?e:""),m.setAttribute("usevideoplayer",`${u}`),m.setAttribute("data-asset-type",t.assetType),m.setAttribute("autoplay",`${h}`),m.setAttribute("env",i),m}),this.createCleanPlayerElement=(t,i,s)=>e(this,void 0,void 0,function*(){var e;const{posterUrl:r,autoPlay:a}=Yh(t,s),o=document.createElement("clean-video-player");r&&o.setAttribute("posterurl",r);const l=yield this.dataService.getPlayRequest(null==t?void 0:t.id,n),d=null==l?void 0:l.recommendedStream.manifest.uri;return d&&o.setAttribute("src",d),o.setAttribute("assetId",null!==(e=null==t?void 0:t.id)&&void 0!==e?e:""),o.setAttribute("autoplay",`${a}`),o.setAttribute("muted",`${Boolean(a)}`),o.setAttribute("loop","false"),o.setAttribute("env",i),o}),this.dataService=t}}var gf,mf;gf=new WeakMap,mf=new WeakMap,t.DataFetchingService=y,t.Logger=g,t.MarkupService=ff,t.StreamService=sd,t.VideoGateService=class{constructor(t){this.options=t,gf.set(this,void 0),mf.set(this,void 0),this.generateStyles=()=>i(this,mf,"f").generateStyles(),this.generateMarkup=(t,s,r)=>e(this,void 0,void 0,function*(){const e=yield i(this,gf,"f").fetchAsset(t,s),{markup:n,styles:a}=i(this,mf,"f").generateMarkup(e,s);return r?`${n}`:`${a}${n}`}),this.mountToDom=(t,s,r)=>e(this,void 0,void 0,function*(){const e=this.getHtmlElement(t);if(!e)return void g.error("Container element is not defined");const n=yield i(this,gf,"f").fetchAsset(s,r);i(this,mf,"f").mountToElement(e,this.options.env,n,r)}),this.getHtmlElement=t=>"string"==typeof t?document.getElementById(t):t;const{logLevel:r,env:n}=this.options;s(this,gf,new y(new q({env:n}),n),"f"),s(this,mf,new ff(i(this,gf,"f")),"f"),g.setLogLevel(r)}},t.calculatePercentWatched=c,t.formatTime=qh,t.getDefaultImageWidth=o,t.getOptimizedImageUrl=a,t.getPosterUrl=d,t.getVideoGateMarkupOptions=Yh,t.isCSR=l});
23//# sourceMappingURL=tv2no-video-gate.umd.js.map

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.