(function(ge,ye){typeof exports=="object"&&typeof module!="undefined"?ye(exports):typeof define=="function"&&define.amd?define(["exports"],ye):(ge=typeof globalThis!="undefined"?globalThis:ge||self,ye(ge.dcplayer={}))})(this,function(ge){"use strict";var yg=Object.defineProperty,vg=Object.defineProperties;var bg=Object.getOwnPropertyDescriptors;var os=Object.getOwnPropertySymbols;var fl=Object.prototype.hasOwnProperty,gl=Object.prototype.propertyIsEnumerable;var Ur=Math.pow,hl=(ge,ye,be)=>ye in ge?yg(ge,ye,{enumerable:!0,configurable:!0,writable:!0,value:be}):ge[ye]=be,wt=(ge,ye)=>{for(var be in ye||(ye={}))fl.call(ye,be)&&hl(ge,be,ye[be]);if(os)for(var be of os(ye))gl.call(ye,be)&&hl(ge,be,ye[be]);return ge},ls=(ge,ye)=>vg(ge,bg(ye));var pl=(ge,ye)=>{var be={};for(var Fe in ge)fl.call(ge,Fe)&&ye.indexOf(Fe)<0&&(be[Fe]=ge[Fe]);if(ge!=null&&os)for(var Fe of os(ge))ye.indexOf(Fe)<0&&gl.call(ge,Fe)&&(be[Fe]=ge[Fe]);return be};var $r=(ge,ye,be)=>new Promise((Fe,F)=>{var cs=je=>{try{Kt(be.next(je))}catch(Wt){F(Wt)}},ds=je=>{try{Kt(be.throw(je))}catch(Wt){F(Wt)}},Kt=je=>je.done?Fe(je.value):Promise.resolve(je.value).then(cs,ds);Kt((be=be.apply(ge,ye)).next())});const ye='@charset "UTF-8";@keyframes plyr-progress{to{background-position:25px 0;background-position:var(--plyr-progress-loading-size,25px) 0}}@keyframes plyr-popup{0%{opacity:.5;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes plyr-fade-in{0%{opacity:0}to{opacity:1}}.plyr{-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;align-items:center;direction:ltr;display:flex;flex-direction:column;font-family:inherit;font-family:var(--plyr-font-family,inherit);font-variant-numeric:tabular-nums;font-weight:400;font-weight:var(--plyr-font-weight-regular,400);line-height:1.7;line-height:var(--plyr-line-height,1.7);max-width:100%;min-width:200px;position:relative;text-shadow:none;transition:box-shadow .3s ease;z-index:0}.plyr audio,.plyr iframe,.plyr video{display:block;height:100%;width:100%}.plyr button{font:inherit;line-height:inherit;width:auto}.plyr:focus{outline:0}.plyr--full-ui{box-sizing:border-box}.plyr--full-ui *,.plyr--full-ui :after,.plyr--full-ui :before{box-sizing:inherit}.plyr--full-ui a,.plyr--full-ui button,.plyr--full-ui input,.plyr--full-ui label{touch-action:manipulation}.plyr__badge{background:#4a5464;background:var(--plyr-badge-background,#4a5464);border-radius:2px;border-radius:var(--plyr-badge-border-radius,2px);color:#fff;color:var(--plyr-badge-text-color,#fff);font-size:9px;font-size:var(--plyr-font-size-badge,9px);line-height:1;padding:3px 4px}.plyr--full-ui ::-webkit-media-text-track-container{display:none}.plyr__captions{animation:plyr-fade-in .3s ease;bottom:0;display:none;font-size:13px;font-size:var(--plyr-font-size-small,13px);left:0;padding:10px;padding:var(--plyr-control-spacing,10px);position:absolute;text-align:center;transition:transform .4s ease-in-out;width:100%}.plyr__captions span:empty{display:none}@media (min-width:480px){.plyr__captions{font-size:15px;font-size:var(--plyr-font-size-base,15px);padding:20px;padding:calc(var(--plyr-control-spacing, 10px)*2)}}@media (min-width:768px){.plyr__captions{font-size:18px;font-size:var(--plyr-font-size-large,18px)}}.plyr--captions-active .plyr__captions{display:block}.plyr:not(.plyr--hide-controls) .plyr__controls:not(:empty)~.plyr__captions{transform:translateY(-40px);transform:translateY(calc(var(--plyr-control-spacing, 10px)*-4))}.plyr__caption{background:#000c;background:var(--plyr-captions-background,#000c);border-radius:2px;-webkit-box-decoration-break:clone;box-decoration-break:clone;color:#fff;color:var(--plyr-captions-text-color,#fff);line-height:185%;padding:.2em .5em;white-space:pre-wrap}.plyr__caption div{display:inline}.plyr__control{background:#0000;border:0;border-radius:4px;border-radius:var(--plyr-control-radius,4px);color:inherit;cursor:pointer;flex-shrink:0;overflow:visible;padding:7px;padding:calc(var(--plyr-control-spacing, 10px)*.7);position:relative;transition:all .3s ease}.plyr__control svg{fill:currentColor;display:block;height:18px;height:var(--plyr-control-icon-size,18px);pointer-events:none;width:18px;width:var(--plyr-control-icon-size,18px)}.plyr__control:focus{outline:0}.plyr__control:focus-visible{outline:2px dashed #00b2ff;outline:2px dashed var(--plyr-focus-visible-color,var(--plyr-color-main,var(--plyr-color-main,#00b2ff)));outline-offset:2px}a.plyr__control{text-decoration:none}.plyr__control.plyr__control--pressed .icon--not-pressed,.plyr__control.plyr__control--pressed .label--not-pressed,.plyr__control:not(.plyr__control--pressed) .icon--pressed,.plyr__control:not(.plyr__control--pressed) .label--pressed,a.plyr__control:after,a.plyr__control:before{display:none}.plyr--full-ui ::-webkit-media-controls{display:none}.plyr__controls{align-items:center;display:flex;justify-content:flex-end;text-align:center}.plyr__controls .plyr__progress__container{flex:1;min-width:0}.plyr__controls .plyr__controls__item{margin-left:2.5px;margin-left:calc(var(--plyr-control-spacing, 10px)/4)}.plyr__controls .plyr__controls__item:first-child{margin-left:0;margin-right:auto}.plyr__controls .plyr__controls__item.plyr__progress__container{padding-left:2.5px;padding-left:calc(var(--plyr-control-spacing, 10px)/4)}.plyr__controls .plyr__controls__item.plyr__time{padding:0 5px;padding:0 calc(var(--plyr-control-spacing, 10px)/2)}.plyr__controls .plyr__controls__item.plyr__progress__container:first-child,.plyr__controls .plyr__controls__item.plyr__time+.plyr__time,.plyr__controls .plyr__controls__item.plyr__time:first-child{padding-left:0}.plyr [data-plyr=airplay],.plyr [data-plyr=captions],.plyr [data-plyr=fullscreen],.plyr [data-plyr=pip],.plyr__controls:empty{display:none}.plyr--airplay-supported [data-plyr=airplay],.plyr--captions-enabled [data-plyr=captions],.plyr--fullscreen-enabled [data-plyr=fullscreen],.plyr--pip-supported [data-plyr=pip]{display:inline-block}.plyr__menu{display:flex;position:relative}.plyr__menu .plyr__control svg{transition:transform .3s ease}.plyr__menu .plyr__control[aria-expanded=true] svg{transform:rotate(90deg)}.plyr__menu .plyr__control[aria-expanded=true] .plyr__tooltip{display:none}.plyr__menu__container{animation:plyr-popup .2s ease;background:#ffffffe6;background:var(--plyr-menu-background,#ffffffe6);border-radius:8px;border-radius:var(--plyr-menu-radius,8px);bottom:100%;box-shadow:0 1px 2px #00000026;box-shadow:var(--plyr-menu-shadow,0 1px 2px #00000026);color:#4a5464;color:var(--plyr-menu-color,#4a5464);font-size:15px;font-size:var(--plyr-font-size-base,15px);margin-bottom:10px;position:absolute;right:-3px;text-align:left;white-space:nowrap;z-index:3}.plyr__menu__container>div{overflow:hidden;transition:height .35s cubic-bezier(.4,0,.2,1),width .35s cubic-bezier(.4,0,.2,1)}.plyr__menu__container:after{border:4px solid #0000;border-top-color:#ffffffe6;border:var(--plyr-menu-arrow-size,4px) solid #0000;border-top-color:var(--plyr-menu-background,#ffffffe6);content:"";height:0;position:absolute;right:14px;right:calc(var(--plyr-control-icon-size, 18px)/2 + var(--plyr-control-spacing, 10px)*.7 - var(--plyr-menu-arrow-size, 4px)/2);top:100%;width:0}.plyr__menu__container [role=menu]{padding:7px;padding:calc(var(--plyr-control-spacing, 10px)*.7)}.plyr__menu__container [role=menuitem],.plyr__menu__container [role=menuitemradio]{margin-top:2px}.plyr__menu__container [role=menuitem]:first-child,.plyr__menu__container [role=menuitemradio]:first-child{margin-top:0}.plyr__menu__container .plyr__control{align-items:center;color:#4a5464;color:var(--plyr-menu-color,#4a5464);display:flex;font-size:13px;font-size:var(--plyr-font-size-menu,var(--plyr-font-size-small,13px));padding:4.66667px 10.5px;padding:calc(var(--plyr-control-spacing, 10px)*.7/1.5) calc(var(--plyr-control-spacing, 10px)*.7*1.5);-webkit-user-select:none;user-select:none;width:100%}.plyr__menu__container .plyr__control>span{align-items:inherit;display:flex;width:100%}.plyr__menu__container .plyr__control:after{border:4px solid #0000;border:var(--plyr-menu-item-arrow-size,4px) solid #0000;content:"";position:absolute;top:50%;transform:translateY(-50%)}.plyr__menu__container .plyr__control--forward{padding-right:28px;padding-right:calc(var(--plyr-control-spacing, 10px)*.7*4)}.plyr__menu__container .plyr__control--forward:after{border-left-color:#728197;border-left-color:var(--plyr-menu-arrow-color,#728197);right:6.5px;right:calc(var(--plyr-control-spacing, 10px)*.7*1.5 - var(--plyr-menu-item-arrow-size, 4px))}.plyr__menu__container .plyr__control--forward:focus-visible:after,.plyr__menu__container .plyr__control--forward:hover:after{border-left-color:initial}.plyr__menu__container .plyr__control--back{font-weight:400;font-weight:var(--plyr-font-weight-regular,400);margin:7px;margin:calc(var(--plyr-control-spacing, 10px)*.7);margin-bottom:3.5px;margin-bottom:calc(var(--plyr-control-spacing, 10px)*.7/2);padding-left:28px;padding-left:calc(var(--plyr-control-spacing, 10px)*.7*4);position:relative;width:calc(100% - 14px);width:calc(100% - var(--plyr-control-spacing, 10px)*.7*2)}.plyr__menu__container .plyr__control--back:after{border-right-color:#728197;border-right-color:var(--plyr-menu-arrow-color,#728197);left:6.5px;left:calc(var(--plyr-control-spacing, 10px)*.7*1.5 - var(--plyr-menu-item-arrow-size, 4px))}.plyr__menu__container .plyr__control--back:before{background:#dcdfe5;background:var(--plyr-menu-back-border-color,#dcdfe5);box-shadow:0 1px 0 #fff;box-shadow:0 1px 0 var(--plyr-menu-back-border-shadow-color,#fff);content:"";height:1px;left:0;margin-top:3.5px;margin-top:calc(var(--plyr-control-spacing, 10px)*.7/2);overflow:hidden;position:absolute;right:0;top:100%}.plyr__menu__container .plyr__control--back:focus-visible:after,.plyr__menu__container .plyr__control--back:hover:after{border-right-color:initial}.plyr__menu__container .plyr__control[role=menuitemradio]{padding-left:7px;padding-left:calc(var(--plyr-control-spacing, 10px)*.7)}.plyr__menu__container .plyr__control[role=menuitemradio]:after,.plyr__menu__container .plyr__control[role=menuitemradio]:before{border-radius:100%}.plyr__menu__container .plyr__control[role=menuitemradio]:before{background:#0000001a;content:"";display:block;flex-shrink:0;height:16px;margin-right:10px;margin-right:var(--plyr-control-spacing,10px);transition:all .3s ease;width:16px}.plyr__menu__container .plyr__control[role=menuitemradio]:after{background:#fff;border:0;height:6px;left:12px;opacity:0;top:50%;transform:translateY(-50%) scale(0);transition:transform .3s ease,opacity .3s ease;width:6px}.plyr__menu__container .plyr__control[role=menuitemradio][aria-checked=true]:before{background:#00b2ff;background:var(--plyr-control-toggle-checked-background,var(--plyr-color-main,var(--plyr-color-main,#00b2ff)))}.plyr__menu__container .plyr__control[role=menuitemradio][aria-checked=true]:after{opacity:1;transform:translateY(-50%) scale(1)}.plyr__menu__container .plyr__control[role=menuitemradio]:focus-visible:before,.plyr__menu__container .plyr__control[role=menuitemradio]:hover:before{background:#23282f1a}.plyr__menu__container .plyr__menu__value{align-items:center;display:flex;margin-left:auto;margin-right:-5px;margin-right:calc(var(--plyr-control-spacing, 10px)*.7*-1 - -2px);overflow:hidden;padding-left:24.5px;padding-left:calc(var(--plyr-control-spacing, 10px)*.7*3.5);pointer-events:none}.plyr--full-ui input[type=range]{-webkit-appearance:none;appearance:none;background:#0000;border:0;border-radius:26px;border-radius:calc(var(--plyr-range-thumb-height, 13px)*2);color:#00b2ff;color:var(--plyr-range-fill-background,var(--plyr-color-main,var(--plyr-color-main,#00b2ff)));display:block;height:19px;height:calc(var(--plyr-range-thumb-active-shadow-width, 3px)*2 + var(--plyr-range-thumb-height, 13px));margin:0;min-width:0;padding:0;transition:box-shadow .3s ease;width:100%}.plyr--full-ui input[type=range]::-webkit-slider-runnable-track{background:#0000;background-image:linear-gradient(90deg,currentColor 0,#0000 0);background-image:linear-gradient(to right,currentColor var(--value,0),#0000 var(--value,0));border:0;border-radius:2.5px;border-radius:calc(var(--plyr-range-track-height, 5px)/2);height:5px;height:var(--plyr-range-track-height,5px);-webkit-transition:box-shadow .3s ease;transition:box-shadow .3s ease;-webkit-user-select:none;user-select:none}.plyr--full-ui input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;background:#fff;background:var(--plyr-range-thumb-background,#fff);border:0;border-radius:100%;box-shadow:0 1px 1px #23282f26,0 0 0 1px #23282f33;box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px #23282f26,0 0 0 1px #23282f33);height:13px;height:var(--plyr-range-thumb-height,13px);margin-top:-4px;margin-top:calc((var(--plyr-range-thumb-height, 13px) - var(--plyr-range-track-height, 5px))/2*-1);position:relative;-webkit-transition:all .2s ease;transition:all .2s ease;width:13px;width:var(--plyr-range-thumb-height,13px)}.plyr--full-ui input[type=range]::-moz-range-track{background:#0000;border:0;border-radius:2.5px;border-radius:calc(var(--plyr-range-track-height, 5px)/2);height:5px;height:var(--plyr-range-track-height,5px);-moz-transition:box-shadow .3s ease;transition:box-shadow .3s ease;user-select:none}.plyr--full-ui input[type=range]::-moz-range-thumb{background:#fff;background:var(--plyr-range-thumb-background,#fff);border:0;border-radius:100%;box-shadow:0 1px 1px #23282f26,0 0 0 1px #23282f33;box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px #23282f26,0 0 0 1px #23282f33);height:13px;height:var(--plyr-range-thumb-height,13px);position:relative;-moz-transition:all .2s ease;transition:all .2s ease;width:13px;width:var(--plyr-range-thumb-height,13px)}.plyr--full-ui input[type=range]::-moz-range-progress{background:currentColor;border-radius:2.5px;border-radius:calc(var(--plyr-range-track-height, 5px)/2);height:5px;height:var(--plyr-range-track-height,5px)}.plyr--full-ui input[type=range]::-ms-track{color:#0000}.plyr--full-ui input[type=range]::-ms-fill-upper,.plyr--full-ui input[type=range]::-ms-track{background:#0000;border:0;border-radius:2.5px;border-radius:calc(var(--plyr-range-track-height, 5px)/2);height:5px;height:var(--plyr-range-track-height,5px);-ms-transition:box-shadow .3s ease;transition:box-shadow .3s ease;user-select:none}.plyr--full-ui input[type=range]::-ms-fill-lower{background:#0000;background:currentColor;border:0;border-radius:2.5px;border-radius:calc(var(--plyr-range-track-height, 5px)/2);height:5px;height:var(--plyr-range-track-height,5px);-ms-transition:box-shadow .3s ease;transition:box-shadow .3s ease;user-select:none}.plyr--full-ui input[type=range]::-ms-thumb{background:#fff;background:var(--plyr-range-thumb-background,#fff);border:0;border-radius:100%;box-shadow:0 1px 1px #23282f26,0 0 0 1px #23282f33;box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px #23282f26,0 0 0 1px #23282f33);height:13px;height:var(--plyr-range-thumb-height,13px);margin-top:0;position:relative;-ms-transition:all .2s ease;transition:all .2s ease;width:13px;width:var(--plyr-range-thumb-height,13px)}.plyr--full-ui input[type=range]::-ms-tooltip{display:none}.plyr--full-ui input[type=range]::-moz-focus-outer{border:0}.plyr--full-ui input[type=range]:focus{outline:0}.plyr--full-ui input[type=range]:focus-visible::-webkit-slider-runnable-track{outline:2px dashed #00b2ff;outline:2px dashed var(--plyr-focus-visible-color,var(--plyr-color-main,var(--plyr-color-main,#00b2ff)));outline-offset:2px}.plyr--full-ui input[type=range]:focus-visible::-moz-range-track{outline:2px dashed #00b2ff;outline:2px dashed var(--plyr-focus-visible-color,var(--plyr-color-main,var(--plyr-color-main,#00b2ff)));outline-offset:2px}.plyr--full-ui input[type=range]:focus-visible::-ms-track{outline:2px dashed #00b2ff;outline:2px dashed var(--plyr-focus-visible-color,var(--plyr-color-main,var(--plyr-color-main,#00b2ff)));outline-offset:2px}.plyr__poster{background-color:#000;background-color:var(--plyr-video-background,var(--plyr-video-background,#000));background-position:50% 50%;background-repeat:no-repeat;background-size:contain;height:100%;left:0;opacity:0;position:absolute;top:0;transition:opacity .2s ease;width:100%;z-index:1}.plyr--stopped.plyr__poster-enabled .plyr__poster{opacity:1}.plyr--youtube.plyr--paused.plyr__poster-enabled:not(.plyr--stopped) .plyr__poster{display:none}.plyr__time{font-size:13px;font-size:var(--plyr-font-size-time,var(--plyr-font-size-small,13px))}.plyr__time+.plyr__time:before{content:"⁄";margin-right:10px;margin-right:var(--plyr-control-spacing,10px)}@media (max-width:767px){.plyr__time+.plyr__time{display:none}}.plyr__tooltip{background:#fff;background:var(--plyr-tooltip-background,#fff);border-radius:5px;border-radius:var(--plyr-tooltip-radius,5px);bottom:100%;box-shadow:0 1px 2px #00000026;box-shadow:var(--plyr-tooltip-shadow,0 1px 2px #00000026);color:#4a5464;color:var(--plyr-tooltip-color,#4a5464);font-size:13px;font-size:var(--plyr-font-size-small,13px);font-weight:400;font-weight:var(--plyr-font-weight-regular,400);left:50%;line-height:1.3;margin-bottom:10px;margin-bottom:calc(var(--plyr-control-spacing, 10px)/2*2);opacity:0;padding:5px 7.5px;padding:calc(var(--plyr-control-spacing, 10px)/2) calc(var(--plyr-control-spacing, 10px)/2*1.5);pointer-events:none;position:absolute;transform:translate(-50%,10px) scale(.8);transform-origin:50% 100%;transition:transform .2s ease .1s,opacity .2s ease .1s;white-space:nowrap;z-index:2}.plyr__tooltip:before{border-left:4px solid #0000;border-left:var(--plyr-tooltip-arrow-size,4px) solid #0000;border-right:4px solid #0000;border-right:var(--plyr-tooltip-arrow-size,4px) solid #0000;border-top:4px solid #fff;border-top:var(--plyr-tooltip-arrow-size,4px) solid var(--plyr-tooltip-background,#fff);bottom:-4px;bottom:calc(var(--plyr-tooltip-arrow-size, 4px)*-1);content:"";height:0;left:50%;position:absolute;transform:translateX(-50%);width:0;z-index:2}.plyr .plyr__control:focus-visible .plyr__tooltip,.plyr .plyr__control:hover .plyr__tooltip,.plyr__tooltip--visible{opacity:1;transform:translate(-50%) scale(1)}.plyr .plyr__control:hover .plyr__tooltip{z-index:3}.plyr__controls>.plyr__control:first-child .plyr__tooltip,.plyr__controls>.plyr__control:first-child+.plyr__control .plyr__tooltip{left:0;transform:translateY(10px) scale(.8);transform-origin:0 100%}.plyr__controls>.plyr__control:first-child .plyr__tooltip:before,.plyr__controls>.plyr__control:first-child+.plyr__control .plyr__tooltip:before{left:16px;left:calc(var(--plyr-control-icon-size, 18px)/2 + var(--plyr-control-spacing, 10px)*.7)}.plyr__controls>.plyr__control:last-child .plyr__tooltip{left:auto;right:0;transform:translateY(10px) scale(.8);transform-origin:100% 100%}.plyr__controls>.plyr__control:last-child .plyr__tooltip:before{left:auto;right:16px;right:calc(var(--plyr-control-icon-size, 18px)/2 + var(--plyr-control-spacing, 10px)*.7);transform:translateX(50%)}.plyr__controls>.plyr__control:first-child .plyr__tooltip--visible,.plyr__controls>.plyr__control:first-child+.plyr__control .plyr__tooltip--visible,.plyr__controls>.plyr__control:first-child+.plyr__control:focus-visible .plyr__tooltip,.plyr__controls>.plyr__control:first-child+.plyr__control:hover .plyr__tooltip,.plyr__controls>.plyr__control:first-child:focus-visible .plyr__tooltip,.plyr__controls>.plyr__control:first-child:hover .plyr__tooltip,.plyr__controls>.plyr__control:last-child .plyr__tooltip--visible,.plyr__controls>.plyr__control:last-child:focus-visible .plyr__tooltip,.plyr__controls>.plyr__control:last-child:hover .plyr__tooltip{transform:translate(0) scale(1)}.plyr__progress{left:6.5px;left:calc(var(--plyr-range-thumb-height, 13px)*.5);margin-right:13px;margin-right:var(--plyr-range-thumb-height,13px);position:relative}.plyr__progress input[type=range],.plyr__progress__buffer{margin-left:-6.5px;margin-left:calc(var(--plyr-range-thumb-height, 13px)*-.5);margin-right:-6.5px;margin-right:calc(var(--plyr-range-thumb-height, 13px)*-.5);width:calc(100% + 13px);width:calc(100% + var(--plyr-range-thumb-height, 13px))}.plyr__progress input[type=range]{position:relative;z-index:2}.plyr__progress .plyr__tooltip{left:0;max-width:120px;overflow-wrap:break-word}.plyr__progress__buffer{-webkit-appearance:none;background:#0000;border:0;border-radius:100px;height:5px;height:var(--plyr-range-track-height,5px);left:0;margin-top:-2.5px;margin-top:calc((var(--plyr-range-track-height, 5px)/2)*-1);padding:0;position:absolute;top:50%}.plyr__progress__buffer::-webkit-progress-bar{background:#0000}.plyr__progress__buffer::-webkit-progress-value{background:currentColor;border-radius:100px;min-width:5px;min-width:var(--plyr-range-track-height,5px);-webkit-transition:width .2s ease;transition:width .2s ease}.plyr__progress__buffer::-moz-progress-bar{background:currentColor;border-radius:100px;min-width:5px;min-width:var(--plyr-range-track-height,5px);-moz-transition:width .2s ease;transition:width .2s ease}.plyr__progress__buffer::-ms-fill{border-radius:100px;-ms-transition:width .2s ease;transition:width .2s ease}.plyr--loading .plyr__progress__buffer{animation:plyr-progress 1s linear infinite;background-image:linear-gradient(-45deg,#23282f99 25%,#0000 0,#0000 50%,#23282f99 0,#23282f99 75%,#0000 0,#0000);background-image:linear-gradient(-45deg,var(--plyr-progress-loading-background,#23282f99) 25%,#0000 25%,#0000 50%,var(--plyr-progress-loading-background,#23282f99) 50%,var(--plyr-progress-loading-background,#23282f99) 75%,#0000 75%,#0000);background-repeat:repeat-x;background-size:25px 25px;background-size:var(--plyr-progress-loading-size,25px) var(--plyr-progress-loading-size,25px);color:#0000}.plyr--video.plyr--loading .plyr__progress__buffer{background-color:#ffffff40;background-color:var(--plyr-video-progress-buffered-background,#ffffff40)}.plyr--audio.plyr--loading .plyr__progress__buffer{background-color:#c1c8d199;background-color:var(--plyr-audio-progress-buffered-background,#c1c8d199)}.plyr__progress__marker{background-color:#fff;background-color:var(--plyr-progress-marker-background,#fff);border-radius:1px;height:5px;height:var(--plyr-range-track-height,5px);position:absolute;top:50%;transform:translate(-50%,-50%);width:3px;width:var(--plyr-progress-marker-width,3px);z-index:3}.plyr__volume{align-items:center;display:flex;position:relative}.plyr__volume input[type=range]{margin-left:5px;margin-left:calc(var(--plyr-control-spacing, 10px)/2);margin-right:5px;margin-right:calc(var(--plyr-control-spacing, 10px)/2);max-width:90px;min-width:60px;position:relative;z-index:2}.plyr--audio{display:block}.plyr--audio .plyr__controls{background:#fff;background:var(--plyr-audio-controls-background,#fff);border-radius:inherit;color:#4a5464;color:var(--plyr-audio-control-color,#4a5464);padding:10px;padding:var(--plyr-control-spacing,10px)}.plyr--audio .plyr__control:focus-visible,.plyr--audio .plyr__control:hover,.plyr--audio .plyr__control[aria-expanded=true]{background:#00b2ff;background:var(--plyr-audio-control-background-hover,var(--plyr-color-main,var(--plyr-color-main,#00b2ff)));color:#fff;color:var(--plyr-audio-control-color-hover,#fff)}.plyr--full-ui.plyr--audio input[type=range]::-webkit-slider-runnable-track{background-color:#c1c8d199;background-color:var(--plyr-audio-range-track-background,var(--plyr-audio-progress-buffered-background,#c1c8d199))}.plyr--full-ui.plyr--audio input[type=range]::-moz-range-track{background-color:#c1c8d199;background-color:var(--plyr-audio-range-track-background,var(--plyr-audio-progress-buffered-background,#c1c8d199))}.plyr--full-ui.plyr--audio input[type=range]::-ms-track{background-color:#c1c8d199;background-color:var(--plyr-audio-range-track-background,var(--plyr-audio-progress-buffered-background,#c1c8d199))}.plyr--full-ui.plyr--audio input[type=range]:active::-webkit-slider-thumb{box-shadow:0 1px 1px #23282f26,0 0 0 1px #23282f33,0 0 0 3px #23282f1a;box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px #23282f26,0 0 0 1px #23282f33),0 0 0 var(--plyr-range-thumb-active-shadow-width,3px) var(--plyr-audio-range-thumb-active-shadow-color,#23282f1a)}.plyr--full-ui.plyr--audio input[type=range]:active::-moz-range-thumb{box-shadow:0 1px 1px #23282f26,0 0 0 1px #23282f33,0 0 0 3px #23282f1a;box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px #23282f26,0 0 0 1px #23282f33),0 0 0 var(--plyr-range-thumb-active-shadow-width,3px) var(--plyr-audio-range-thumb-active-shadow-color,#23282f1a)}.plyr--full-ui.plyr--audio input[type=range]:active::-ms-thumb{box-shadow:0 1px 1px #23282f26,0 0 0 1px #23282f33,0 0 0 3px #23282f1a;box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px #23282f26,0 0 0 1px #23282f33),0 0 0 var(--plyr-range-thumb-active-shadow-width,3px) var(--plyr-audio-range-thumb-active-shadow-color,#23282f1a)}.plyr--audio .plyr__progress__buffer{color:#c1c8d199;color:var(--plyr-audio-progress-buffered-background,#c1c8d199)}.plyr--video{overflow:hidden}.plyr--video.plyr--menu-open{overflow:visible}.plyr__video-wrapper{background:#000;background:var(--plyr-video-background,var(--plyr-video-background,#000));border-radius:inherit;height:100%;margin:auto;overflow:hidden;position:relative;width:100%}.plyr__video-embed,.plyr__video-wrapper--fixed-ratio{aspect-ratio:16/9}@supports not (aspect-ratio:16/9){.plyr__video-embed,.plyr__video-wrapper--fixed-ratio{height:0;padding-bottom:56.25%;position:relative}}.plyr__video-embed iframe,.plyr__video-wrapper--fixed-ratio video{border:0;height:100%;left:0;position:absolute;top:0;width:100%}.plyr--full-ui .plyr__video-embed>.plyr__video-embed__container{padding-bottom:240%;position:relative;transform:translateY(-38.28125%)}.plyr--video .plyr__controls{background:linear-gradient(#0000,#000000bf);background:var(--plyr-video-controls-background,linear-gradient(#0000,#000000bf));border-bottom-left-radius:inherit;border-bottom-right-radius:inherit;bottom:0;color:#fff;color:var(--plyr-video-control-color,#fff);left:0;padding:5px;padding:calc(var(--plyr-control-spacing, 10px)/2);padding-top:20px;padding-top:calc(var(--plyr-control-spacing, 10px)*2);position:absolute;right:0;transition:opacity .4s ease-in-out,transform .4s ease-in-out;z-index:3}@media (min-width:480px){.plyr--video .plyr__controls{padding:10px;padding:var(--plyr-control-spacing,10px);padding-top:35px;padding-top:calc(var(--plyr-control-spacing, 10px)*3.5)}}.plyr--video.plyr--hide-controls .plyr__controls{opacity:0;pointer-events:none;transform:translateY(100%)}.plyr--video .plyr__control:focus-visible,.plyr--video .plyr__control:hover,.plyr--video .plyr__control[aria-expanded=true]{background:#00b2ff;background:var(--plyr-video-control-background-hover,var(--plyr-color-main,var(--plyr-color-main,#00b2ff)));color:#fff;color:var(--plyr-video-control-color-hover,#fff)}.plyr__control--overlaid{background:#00b2ff;background:var(--plyr-video-control-background-hover,var(--plyr-color-main,var(--plyr-color-main,#00b2ff)));border:0;border-radius:100%;color:#fff;color:var(--plyr-video-control-color,#fff);display:none;left:50%;opacity:.9;padding:15px;padding:calc(var(--plyr-control-spacing, 10px)*1.5);position:absolute;top:50%;transform:translate(-50%,-50%);transition:.3s;z-index:2}.plyr__control--overlaid svg{left:2px;position:relative}.plyr__control--overlaid:focus,.plyr__control--overlaid:hover{opacity:1}.plyr--playing .plyr__control--overlaid{opacity:0;visibility:hidden}.plyr--full-ui.plyr--video .plyr__control--overlaid{display:block}.plyr--full-ui.plyr--video input[type=range]::-webkit-slider-runnable-track{background-color:#ffffff40;background-color:var(--plyr-video-range-track-background,var(--plyr-video-progress-buffered-background,#ffffff40))}.plyr--full-ui.plyr--video input[type=range]::-moz-range-track{background-color:#ffffff40;background-color:var(--plyr-video-range-track-background,var(--plyr-video-progress-buffered-background,#ffffff40))}.plyr--full-ui.plyr--video input[type=range]::-ms-track{background-color:#ffffff40;background-color:var(--plyr-video-range-track-background,var(--plyr-video-progress-buffered-background,#ffffff40))}.plyr--full-ui.plyr--video input[type=range]:active::-webkit-slider-thumb{box-shadow:0 1px 1px #23282f26,0 0 0 1px #23282f33,0 0 0 3px #ffffff80;box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px #23282f26,0 0 0 1px #23282f33),0 0 0 var(--plyr-range-thumb-active-shadow-width,3px) var(--plyr-audio-range-thumb-active-shadow-color,#ffffff80)}.plyr--full-ui.plyr--video input[type=range]:active::-moz-range-thumb{box-shadow:0 1px 1px #23282f26,0 0 0 1px #23282f33,0 0 0 3px #ffffff80;box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px #23282f26,0 0 0 1px #23282f33),0 0 0 var(--plyr-range-thumb-active-shadow-width,3px) var(--plyr-audio-range-thumb-active-shadow-color,#ffffff80)}.plyr--full-ui.plyr--video input[type=range]:active::-ms-thumb{box-shadow:0 1px 1px #23282f26,0 0 0 1px #23282f33,0 0 0 3px #ffffff80;box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px #23282f26,0 0 0 1px #23282f33),0 0 0 var(--plyr-range-thumb-active-shadow-width,3px) var(--plyr-audio-range-thumb-active-shadow-color,#ffffff80)}.plyr--video .plyr__progress__buffer{color:#ffffff40;color:var(--plyr-video-progress-buffered-background,#ffffff40)}.plyr:fullscreen{background:#000;border-radius:0!important;height:100%;margin:0;width:100%}.plyr:fullscreen video{height:100%}.plyr:fullscreen .plyr__control .icon--exit-fullscreen{display:block}.plyr:fullscreen .plyr__control .icon--exit-fullscreen+svg{display:none}.plyr:fullscreen.plyr--hide-controls{cursor:none}@media (min-width:1024px){.plyr:fullscreen .plyr__captions{font-size:21px;font-size:var(--plyr-font-size-xlarge,21px)}}.plyr--fullscreen-fallback{background:#000;border-radius:0!important;bottom:0;height:100%;left:0;margin:0;position:fixed;right:0;top:0;width:100%;z-index:10000000}.plyr--fullscreen-fallback video{height:100%}.plyr--fullscreen-fallback .plyr__control .icon--exit-fullscreen{display:block}.plyr--fullscreen-fallback .plyr__control .icon--exit-fullscreen+svg{display:none}.plyr--fullscreen-fallback.plyr--hide-controls{cursor:none}@media (min-width:1024px){.plyr--fullscreen-fallback .plyr__captions{font-size:21px;font-size:var(--plyr-font-size-xlarge,21px)}}.plyr__ads{border-radius:inherit;bottom:0;cursor:pointer;left:0;overflow:hidden;position:absolute;right:0;top:0;z-index:-1}.plyr__ads>div,.plyr__ads>div iframe{height:100%;position:absolute;width:100%}.plyr__ads:after{background:#23282f;border-radius:2px;bottom:10px;bottom:var(--plyr-control-spacing,10px);color:#fff;content:attr(data-badge-text);font-size:11px;padding:2px 6px;pointer-events:none;position:absolute;right:10px;right:var(--plyr-control-spacing,10px);z-index:3}.plyr__ads:empty:after{display:none}.plyr__cues{background:currentColor;display:block;height:5px;height:var(--plyr-range-track-height,5px);left:0;opacity:.8;position:absolute;top:50%;transform:translateY(-50%);width:3px;z-index:3}.plyr__preview-thumb{background-color:#fff;background-color:var(--plyr-tooltip-background,#fff);border-radius:8px;border-radius:var(--plyr-menu-radius,8px);bottom:100%;box-shadow:0 1px 2px #00000026;box-shadow:var(--plyr-tooltip-shadow,0 1px 2px #00000026);margin-bottom:10px;margin-bottom:calc(var(--plyr-control-spacing, 10px)/2*2);opacity:0;padding:3px;pointer-events:none;position:absolute;transform:translateY(10px) scale(.8);transform-origin:50% 100%;transition:transform .2s ease .1s,opacity .2s ease .1s;z-index:2}.plyr__preview-thumb--is-shown{opacity:1;transform:translate(0) scale(1)}.plyr__preview-thumb:before{border-left:4px solid #0000;border-left:var(--plyr-tooltip-arrow-size,4px) solid #0000;border-right:4px solid #0000;border-right:var(--plyr-tooltip-arrow-size,4px) solid #0000;border-top:4px solid #fff;border-top:var(--plyr-tooltip-arrow-size,4px) solid var(--plyr-tooltip-background,#fff);bottom:-4px;bottom:calc(var(--plyr-tooltip-arrow-size, 4px)*-1);content:"";height:0;left:calc(50% + var(--preview-arrow-offset));position:absolute;transform:translateX(-50%);width:0;z-index:2}.plyr__preview-thumb__image-container{background:#c1c8d1;border-radius:7px;border-radius:calc(var(--plyr-menu-radius, 8px) - 1px);overflow:hidden;position:relative;z-index:0}.plyr__preview-thumb__image-container img,.plyr__preview-thumb__image-container:after{height:100%;left:0;position:absolute;top:0;width:100%}.plyr__preview-thumb__image-container:after{border-radius:inherit;box-shadow:inset 0 0 0 1px #00000026;content:"";pointer-events:none}.plyr__preview-thumb__image-container img{max-height:none;max-width:none}.plyr__preview-thumb__time-container{background:linear-gradient(#0000,#000000bf);background:var(--plyr-video-controls-background,linear-gradient(#0000,#000000bf));border-bottom-left-radius:7px;border-bottom-left-radius:calc(var(--plyr-menu-radius, 8px) - 1px);border-bottom-right-radius:7px;border-bottom-right-radius:calc(var(--plyr-menu-radius, 8px) - 1px);bottom:0;left:0;line-height:1.1;padding:20px 6px 6px;position:absolute;right:0;z-index:3}.plyr__preview-thumb__time-container span{color:#fff;font-size:13px;font-size:var(--plyr-font-size-time,var(--plyr-font-size-small,13px))}.plyr__preview-scrubbing{bottom:0;filter:blur(1px);height:100%;left:0;margin:auto;opacity:0;overflow:hidden;pointer-events:none;position:absolute;right:0;top:0;transition:opacity .3s ease;width:100%;z-index:1}.plyr__preview-scrubbing--is-shown{opacity:1}.plyr__preview-scrubbing img{height:100%;left:0;max-height:none;max-width:none;object-fit:contain;position:absolute;top:0;width:100%}.plyr--no-transition{transition:none!important}.plyr__sr-only{clip:rect(1px,1px,1px,1px);border:0!important;height:1px!important;overflow:hidden;padding:0!important;position:absolute!important;width:1px!important}.plyr [hidden]{display:none!important}',be=`#dcvideo {\r position: relative;\r }\r \r #dcvideo,\r .plyr,\r .plyr__video-wrapper,\r video {\r width: 100% !important;\r height: 100% !important;\r min-height: 100% !important;\r min-width: 100% !important;\r object-fit: cover;\r background: #000;\r display: block;\r }\r \r \r .hidden {\r display: none !important;\r }\r \r \r #dcoverlay {\r position: absolute;\r top: 0;\r left: 0;\r width: 100%;\r height: 100%;\r background: rgba(0, 0, 0, 0.6); /* полупрозрачный фон */\r color: white;\r display: flex;\r align-items: center;\r justify-content: center;\r font-size: 24px;\r z-index: 99999;\r pointer-events: auto;\r }\r \r \r .video-wrapper {\r position: relative;\r width: 100%;\r aspect-ratio: 16 / 9;\r background: black;\r }\r \r .comment {\r background: #ffffff0d;\r padding: 15px;\r border-left: 4px solid #0dcaf0;\r border-radius: 0.5rem;\r }\r \r .movie-description {\r background-color: #1c1c1e;\r padding: 20px;\r border-radius: 0.5rem;\r margin-bottom: 30px;\r }\r \r .title-row {\r display: flex;\r justify-content: space-between;\r flex-wrap: wrap;\r }\r \r .title-row h2 {\r margin-bottom: 0.5rem;\r }\r \r .plyr-spinner {\r position: absolute;\r top: 50%;\r left: 50%;\r transform: translate(-50%, -50%);\r z-index: 10;\r width: 40px;\r height: 40px;\r border: 4px solid rgba(255,255,255,0.3);\r border-top-color: white;\r border-radius: 50%;\r animation: spin 1s linear infinite;\r pointer-events: none;\r display: block;\r }\r \r \r @keyframes spin {\r to {\r transform: translate(-50%, -50%) rotate(360deg);\r }\r }\r \r `,Fe=`#before-card-form\r {\r display: flex;\r gap: 1rem;\r font-size: 0.925rem;\r justify-content: center;\r background: #e6e6e6;\r color: #007BFF;\r margin-bottom: 1rem;\r border-radius: 0.4rem;\r padding: 0.5rem 1rem;\r }\r \r .tab-heading {\r display: flex;\r gap: 1rem;\r font-size: 1.1rem;\r margin-bottom: 1rem;\r justify-content: space-between;\r }\r \r .tab {\r padding: 0.4rem 0.8rem;\r border-radius: 0.4rem;\r transition: background 0.2s, color 0.2s;\r font-size: 0.925rem;\r align-items: center;\r }\r \r .tab.active {\r background: #f5f5f5;\r cursor: default;\r color: #007BFF;\r font-weight: bold;\r }\r \r .tab:not(.active) {\r background: #e6e6e6;\r color: #333;\r cursor: pointer;\r }\r \r .tab:not(.active):hover {\r background: #dcdcdc;\r color: #007BFF;\r }\r \r \r .payment-forms {\r max-width: 600px;\r margin: 0 auto;\r /* padding: 16px; */\r border-radius: 8px;\r background-color: #f9f9f9;\r font-family: sans-serif;\r box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);\r }\r \r .payment-forms #message {\r margin: -0.5rem 0 0.7rem;\r font-size: 14px;\r color: #ff0000;\r }\r \r #sms_code_message {\r color: #aa0000;\r font-size: 14px;\r font-weight: normal;\r margin-top: -0.7em;\r display: block;\r }\r \r .payment-form h2 {\r margin-bottom: 10px;\r font-size: 20px;\r text-align: left;\r color: #333;\r }\r \r .payment-form label {\r display: block;\r margin-bottom: 6px;\r font-size: 14px;\r font-weight: 600;\r color: #333;\r }\r \r .payment-form input {\r width: 100%;\r padding: 10px 12px;\r font-size: 16px;\r border-radius: 6px;\r border: 1px solid #ccc;\r margin-bottom: 12px;\r box-sizing: border-box;\r }\r \r .payment-form input:focus {\r border: 2px solid #007bff; /* синий цвет границы */\r outline: none; /* убираем стандартный outline */\r box-shadow: 0 0 4px #007bff; /* легкое свечение */\r transition: border 0.2s, box-shadow 0.2s;\r }\r \r .payment-form .row {\r display: flex;\r gap: 12px;\r }\r \r .payment-form .row .field {\r flex: 1;\r }\r \r .payment-forms button {\r width: 100%;\r padding: 12px;\r background-color: #007bff;\r color: white;\r font-size: 16px;\r border: none;\r border-radius: 6px;\r cursor: pointer;\r }\r \r .payment-forms button:hover {\r background-color: #0056b3;\r }\r \r @media (max-width: 480px) {\r .card-form {\r padding: 12px;\r }\r }`;function F(r,e,t){return(e=ds(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function cs(r,e){if(typeof r!="object"||r===null)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var i=t.call(r,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function ds(r){var e=cs(r,"string");return typeof e=="symbol"?e:String(e)}function Kt(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function je(r,e){for(var t=0;te){var t=Ll(e);return parseFloat(r.toFixed(t))}return Math.round(r/e)*e}var Il=function(){function r(e,t){Kt(this,r),ke.element(e)?this.element=e:ke.string(e)&&(this.element=document.querySelector(e)),ke.element(this.element)&&ke.empty(this.element.rangeTouch)&&(this.config=Vr({},Hr,{},t),this.init())}return Wt(r,[{key:"init",value:function(){r.enabled&&(this.config.addCSS&&(this.element.style.userSelect="none",this.element.style.webKitUserSelect="none",this.element.style.touchAction="manipulation"),this.listeners(!0),this.element.rangeTouch=this)}},{key:"destroy",value:function(){r.enabled&&(this.config.addCSS&&(this.element.style.userSelect="",this.element.style.webKitUserSelect="",this.element.style.touchAction=""),this.listeners(!1),this.element.rangeTouch=null)}},{key:"listeners",value:function(e){var t=this,i=e?"addEventListener":"removeEventListener";["touchstart","touchmove","touchend"].forEach(function(s){t.element[i](s,function(n){return t.set(n)},!1)})}},{key:"get",value:function(e){if(!r.enabled||!ke.event(e))return null;var t,i=e.target,s=e.changedTouches[0],n=parseFloat(i.getAttribute("min"))||0,a=parseFloat(i.getAttribute("max"))||100,o=parseFloat(i.getAttribute("step"))||1,c=i.getBoundingClientRect(),l=100/c.width*(this.config.thumbWidth/2)/100;return 0>(t=100/c.width*(s.clientX-c.left))?t=0:100t?t-=(100-2*t)*l:50r!=null?r.constructor:null,rt=(r,e)=>!!(r&&e&&r instanceof e),hs=r=>r==null,zr=r=>jt(r)===Object,Rl=r=>jt(r)===Number&&!Number.isNaN(r),yi=r=>jt(r)===String,kl=r=>jt(r)===Boolean,Xr=r=>typeof r=="function",Qr=r=>Array.isArray(r),wl=r=>rt(r,WeakMap),Jr=r=>rt(r,NodeList),Cl=r=>jt(r)===Text,Dl=r=>rt(r,Event),Pl=r=>rt(r,KeyboardEvent),Ol=r=>rt(r,window.TextTrackCue)||rt(r,window.VTTCue),Ml=r=>rt(r,TextTrack)||!hs(r)&&yi(r.kind),Fl=r=>rt(r,Promise)&&Xr(r.then),Nl=r=>r!==null&&typeof r=="object"&&r.nodeType===1&&typeof r.style=="object"&&typeof r.ownerDocument=="object",Zr=r=>hs(r)||(yi(r)||Qr(r)||Jr(r))&&!r.length||zr(r)&&!Object.keys(r).length;var E={nullOrUndefined:hs,object:zr,number:Rl,string:yi,boolean:kl,function:Xr,array:Qr,weakMap:wl,nodeList:Jr,element:Nl,textNode:Cl,event:Dl,keyboardEvent:Pl,cue:Ol,track:Ml,promise:Fl,url:r=>{if(rt(r,window.URL))return!0;if(!yi(r))return!1;let e=r;r.startsWith("http://")&&r.startsWith("https://")||(e=`http://${r}`);try{return!Zr(new URL(e).hostname)}catch(t){return!1}},empty:Zr};const fs=(()=>{const r=document.createElement("span"),e={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},t=Object.keys(e).find(i=>r.style[i]!==void 0);return!!E.string(t)&&e[t]})();function en(r,e){setTimeout(()=>{try{r.hidden=!0,r.offsetHeight,r.hidden=!1}catch(t){}},e)}const Bl=!!window.document.documentMode,Ul=/Edge/g.test(navigator.userAgent),$l="WebkitAppearance"in document.documentElement.style&&!/Edge/g.test(navigator.userAgent),Gl=/iPhone|iPod/gi.test(navigator.userAgent)&&navigator.maxTouchPoints>1,Vl=navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,Hl=/iPad|iPhone|iPod/gi.test(navigator.userAgent)&&navigator.maxTouchPoints>1;var Le={isIE:Bl,isEdge:Ul,isWebKit:$l,isIPhone:Gl,isIPadOS:Vl,isIos:Hl};function Kl(r){return JSON.parse(JSON.stringify(r))}function tn(r,e){return e.split(".").reduce((t,i)=>t&&t[i],r)}function Te(r={},...e){if(!e.length)return r;const t=e.shift();return E.object(t)?(Object.keys(t).forEach(i=>{E.object(t[i])?(Object.keys(r).includes(i)||Object.assign(r,{[i]:{}}),Te(r[i],t[i])):Object.assign(r,{[i]:t[i]})}),Te(r,...e)):r}function sn(r,e){const t=r.length?r:[r];Array.from(t).reverse().forEach((i,s)=>{const n=s>0?e.cloneNode(!0):e,a=i.parentNode,o=i.nextSibling;n.appendChild(i),o?a.insertBefore(n,o):a.appendChild(n)})}function gs(r,e){E.element(r)&&!E.empty(e)&&Object.entries(e).filter(([,t])=>!E.nullOrUndefined(t)).forEach(([t,i])=>r.setAttribute(t,i))}function j(r,e,t){const i=document.createElement(r);return E.object(e)&&gs(i,e),E.string(t)&&(i.innerText=t),i}function Wl(r,e){E.element(r)&&E.element(e)&&e.parentNode.insertBefore(r,e.nextSibling)}function rn(r,e,t,i){E.element(e)&&e.appendChild(j(r,t,i))}function nt(r){E.nodeList(r)||E.array(r)?Array.from(r).forEach(nt):E.element(r)&&E.element(r.parentNode)&&r.parentNode.removeChild(r)}function vi(r){if(!E.element(r))return;let{length:e}=r.childNodes;for(;e>0;)r.removeChild(r.lastChild),e-=1}function bi(r,e){return E.element(e)&&E.element(e.parentNode)&&E.element(r)?(e.parentNode.replaceChild(r,e),r):null}function qe(r,e){if(!E.string(r)||E.empty(r))return{};const t={},i=Te({},e);return r.split(",").forEach(s=>{const n=s.trim(),a=n.replace(".",""),o=n.replace(/[[\]]/g,"").split("="),[c]=o,l=o.length>1?o[1].replace(/["']/g,""):"";switch(n.charAt(0)){case".":E.string(i.class)?t.class=`${i.class} ${a}`:t.class=a;break;case"#":t.id=n.replace("#","");break;case"[":t[c]=l}}),Te(i,t)}function xt(r,e){if(!E.element(r))return;let t=e;E.boolean(t)||(t=!r.hidden),r.hidden=t}function oe(r,e,t){if(E.nodeList(r))return Array.from(r).map(i=>oe(i,e,t));if(E.element(r)){let i="toggle";return t!==void 0&&(i=t?"add":"remove"),r.classList[i](e),r.classList.contains(e)}return!1}function Ti(r,e){return E.element(r)&&r.classList.contains(e)}function St(r,e){const{prototype:t}=Element;return(t.matches||t.webkitMatchesSelector||t.mozMatchesSelector||t.msMatchesSelector||function(){return Array.from(document.querySelectorAll(e)).includes(this)}).call(r,e)}function Yl(r,e){const{prototype:t}=Element;return(t.closest||function(){let i=this;do{if(St.matches(i,e))return i;i=i.parentElement||i.parentNode}while(i!==null&&i.nodeType===1);return null}).call(r,e)}function qt(r){return this.elements.container.querySelectorAll(r)}function xe(r){return this.elements.container.querySelector(r)}function ps(r=null,e=!1){E.element(r)&&r.focus({preventScroll:!0,focusVisible:e})}const nn={"audio/ogg":"vorbis","audio/wav":"1","video/webm":"vp8, vorbis","video/mp4":"avc1.42E01E, mp4a.40.2","video/ogg":"theora"},Ee={audio:"canPlayType"in document.createElement("audio"),video:"canPlayType"in document.createElement("video"),check(r,e){const t=Ee[r]||e!=="html5";return{api:t,ui:t&&Ee.rangeInput}},pip:!(Le.isIPhone||!E.function(j("video").webkitSetPresentationMode)&&(!document.pictureInPictureEnabled||j("video").disablePictureInPicture)),airplay:E.function(window.WebKitPlaybackTargetAvailabilityEvent),playsinline:"playsInline"in document.createElement("video"),mime(r){if(E.empty(r))return!1;const[e]=r.split("/");let t=r;if(!this.isHTML5||e!==this.type)return!1;Object.keys(nn).includes(t)&&(t+=`; codecs="${nn[r]}"`);try{return!!(t&&this.media.canPlayType(t).replace(/no/,""))}catch(i){return!1}},textTracks:"textTracks"in document.createElement("video"),rangeInput:(()=>{const r=document.createElement("input");return r.type="range",r.type==="range"})(),touch:"ontouchstart"in document.documentElement,transitions:fs!==!1,reducedMotion:"matchMedia"in window&&window.matchMedia("(prefers-reduced-motion)").matches},jl=(()=>{let r=!1;try{const e=Object.defineProperty({},"passive",{get:()=>(r=!0,null)});window.addEventListener("test",null,e),window.removeEventListener("test",null,e)}catch(e){}return r})();function zt(r,e,t,i=!1,s=!0,n=!1){if(!r||!("addEventListener"in r)||E.empty(e)||!E.function(t))return;const a=e.split(" ");let o=n;jl&&(o={passive:s,capture:n}),a.forEach(c=>{this&&this.eventListeners&&i&&this.eventListeners.push({element:r,type:c,callback:t,options:o}),r[i?"addEventListener":"removeEventListener"](c,t,o)})}function se(r,e="",t,i=!0,s=!1){zt.call(this,r,e,t,!0,i,s)}function Ei(r,e="",t,i=!0,s=!1){zt.call(this,r,e,t,!1,i,s)}function ms(r,e="",t,i=!0,s=!1){const n=(...a)=>{Ei(r,e,n,i,s),t.apply(this,a)};zt.call(this,r,e,n,!0,i,s)}function z(r,e="",t=!1,i={}){if(!E.element(r)||E.empty(e))return;const s=new CustomEvent(e,{bubbles:t,detail:ls(wt({},i),{plyr:this})});r.dispatchEvent(s)}function ql(){this&&this.eventListeners&&(this.eventListeners.forEach(r=>{const{element:e,type:t,callback:i,options:s}=r;e.removeEventListener(t,i,s)}),this.eventListeners=[])}function zl(){return new Promise(r=>this.ready?setTimeout(r,0):se.call(this,this.elements.container,"ready",r)).then(()=>{})}function ze(r){E.promise(r)&&r.then(null,()=>{})}function ys(r){return E.array(r)?r.filter((e,t)=>r.indexOf(e)===t):r}function an(r,e){return E.array(r)&&r.length?r.reduce((t,i)=>Math.abs(i-e)ls(wt({},r),{[e/t]:[e,t]}),{});function cn(r){return E.array(r)||E.string(r)&&r.includes(":")?(E.array(r)?r:r.split(":")).map(Number).every(E.number):!1}function xi(r){if(!E.array(r)||!r.every(E.number))return null;const[e,t]=r,i=(n,a)=>a===0?n:i(a,n%a),s=i(e,t);return[e/s,t/s]}function vs(r){const e=i=>cn(i)?i.split(":").map(Number):null;let t=e(r);if(t===null&&(t=e(this.config.ratio)),t===null&&!E.empty(this.embed)&&E.array(this.embed.ratio)&&({ratio:t}=this.embed),t===null&&this.isHTML5){const{videoWidth:i,videoHeight:s}=this.media;t=[i,s]}return xi(t)}function Ct(r){if(!this.isVideo)return{};const{wrapper:e}=this.elements,t=vs.call(this,r);if(!E.array(t))return{};const[i,s]=xi(t),n=100/i*s;if(on(`aspect-ratio: ${i}/${s}`)?e.style.aspectRatio=`${i}/${s}`:e.style.paddingBottom=`${n}%`,this.isVimeo&&!this.config.vimeo.premium&&this.supported.ui){const a=100/this.media.offsetWidth*parseInt(window.getComputedStyle(this.media).paddingBottom,10),o=(a-n)/(a/50);this.fullscreen.active?e.style.paddingBottom=null:this.media.style.transform=`translateY(-${o}%)`}else this.isHTML5&&e.classList.add(this.config.classNames.videoFixedRatio);return{padding:n,ratio:t}}function dn(r,e,t=.05){const i=r/e,s=an(Object.keys(ln),i);return Math.abs(s-i)<=t?ln[s]:[r,e]}function Xl(){return[Math.max(document.documentElement.clientWidth||0,window.innerWidth||0),Math.max(document.documentElement.clientHeight||0,window.innerHeight||0)]}const ht={getSources(){return this.isHTML5?Array.from(this.media.querySelectorAll("source")).filter(r=>{const e=r.getAttribute("type");return!!E.empty(e)||Ee.mime.call(this,e)}):[]},getQualityOptions(){return this.config.quality.forced?this.config.quality.options:ht.getSources.call(this).map(r=>Number(r.getAttribute("size"))).filter(Boolean)},setup(){if(!this.isHTML5)return;const r=this;r.options.speed=r.config.speed.options,E.empty(this.config.ratio)||Ct.call(r),Object.defineProperty(r.media,"quality",{get(){const e=ht.getSources.call(r).find(t=>t.getAttribute("src")===r.source);return e&&Number(e.getAttribute("size"))},set(e){if(r.quality!==e){if(r.config.quality.forced&&E.function(r.config.quality.onChange))r.config.quality.onChange(e);else{const t=ht.getSources.call(r).find(c=>Number(c.getAttribute("size"))===e);if(!t)return;const{currentTime:i,paused:s,preload:n,readyState:a,playbackRate:o}=r.media;r.media.src=t.getAttribute("src"),(n!=="none"||a)&&(r.once("loadedmetadata",()=>{r.speed=o,r.currentTime=i,s||ze(r.play())}),r.media.load())}z.call(r,r.media,"qualitychange",!1,{quality:e})}}})},cancelRequests(){this.isHTML5&&(nt(ht.getSources.call(this)),this.media.setAttribute("src",this.config.blankVideo),this.media.load(),this.debug.log("Cancelled network requests"))}};function Ql(r){return`${r}-${Math.floor(1e4*Math.random())}`}function bs(r,...e){return E.empty(r)?r:r.toString().replace(/{(\d+)}/g,(t,i)=>e[i].toString())}function Jl(r,e){return r===0||e===0||Number.isNaN(r)||Number.isNaN(e)?0:(r/e*100).toFixed(2)}const Xt=(r="",e="",t="")=>r.replace(new RegExp(e.toString().replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1"),"g"),t.toString()),un=(r="")=>r.toString().replace(/\w\S*/g,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase());function Zl(r=""){let e=r.toString();return e=Xt(e,"-"," "),e=Xt(e,"_"," "),e=un(e),Xt(e," ","")}function ec(r=""){let e=r.toString();return e=Zl(e),e.charAt(0).toLowerCase()+e.slice(1)}function tc(r){const e=document.createDocumentFragment(),t=document.createElement("div");return e.appendChild(t),t.innerHTML=r,e.firstChild.innerText}function ic(r){const e=document.createElement("div");return e.appendChild(r),e.innerHTML}const hn={pip:"PIP",airplay:"AirPlay",html5:"HTML5",vimeo:"Vimeo",youtube:"YouTube"},_e={get(r="",e={}){if(E.empty(r)||E.empty(e))return"";let t=tn(e.i18n,r);if(E.empty(t))return Object.keys(hn).includes(r)?hn[r]:"";const i={"{seektime}":e.seekTime,"{title}":e.title};return Object.entries(i).forEach(([s,n])=>{t=Xt(t,s,n)}),t}};class Qt{constructor(e){F(this,"get",t=>{if(!Qt.supported||!this.enabled)return null;const i=window.localStorage.getItem(this.key);if(E.empty(i))return null;const s=JSON.parse(i);return E.string(t)&&t.length?s[t]:s}),F(this,"set",t=>{if(!Qt.supported||!this.enabled||!E.object(t))return;let i=this.get();E.empty(i)&&(i={}),Te(i,t);try{window.localStorage.setItem(this.key,JSON.stringify(i))}catch(s){}}),this.enabled=e.config.storage.enabled,this.key=e.config.storage.key}static get supported(){try{if(!("localStorage"in window))return!1;const e="___test";return window.localStorage.setItem(e,e),window.localStorage.removeItem(e),!0}catch(e){return!1}}}function Jt(r,e="text"){return new Promise((t,i)=>{try{const s=new XMLHttpRequest;if(!("withCredentials"in s))return;s.addEventListener("load",()=>{if(e==="text")try{t(JSON.parse(s.responseText))}catch(n){t(s.responseText)}else t(s.response)}),s.addEventListener("error",()=>{throw new Error(s.status)}),s.open("GET",r,!0),s.responseType=e,s.send()}catch(s){i(s)}})}function fn(r,e){if(!E.string(r))return;const t="cache",i=E.string(e);let s=!1;const n=()=>document.getElementById(e)!==null,a=(o,c)=>{o.innerHTML=c,i&&n()||document.body.insertAdjacentElement("afterbegin",o)};if(!i||!n()){const o=Qt.supported,c=document.createElement("div");if(c.setAttribute("hidden",""),i&&c.setAttribute("id",e),o){const l=window.localStorage.getItem(`${t}-${e}`);if(s=l!==null,s){const d=JSON.parse(l);a(c,d.content)}}Jt(r).then(l=>{if(!E.empty(l)){if(o)try{window.localStorage.setItem(`${t}-${e}`,JSON.stringify({content:l}))}catch(d){}a(c,l)}}).catch(()=>{})}}const gn=r=>Math.trunc(r/60/60%60,10),sc=r=>Math.trunc(r/60%60,10),rc=r=>Math.trunc(r%60,10);function Si(r=0,e=!1,t=!1){if(!E.number(r))return Si(void 0,e,t);const i=o=>`0${o}`.slice(-2);let s=gn(r);const n=sc(r),a=rc(r);return s=e||s>0?`${s}:`:"",`${t&&r>0?"-":""}${s}${i(n)}:${i(a)}`}const N={getIconUrl(){const r=new URL(this.config.iconUrl,window.location),e=window.location.host?window.location.host:window.top.location.host,t=r.host!==e||Le.isIE&&!window.svg4everybody;return{url:this.config.iconUrl,cors:t}},findElements(){try{return this.elements.controls=xe.call(this,this.config.selectors.controls.wrapper),this.elements.buttons={play:qt.call(this,this.config.selectors.buttons.play),pause:xe.call(this,this.config.selectors.buttons.pause),restart:xe.call(this,this.config.selectors.buttons.restart),rewind:xe.call(this,this.config.selectors.buttons.rewind),fastForward:xe.call(this,this.config.selectors.buttons.fastForward),mute:xe.call(this,this.config.selectors.buttons.mute),pip:xe.call(this,this.config.selectors.buttons.pip),airplay:xe.call(this,this.config.selectors.buttons.airplay),settings:xe.call(this,this.config.selectors.buttons.settings),captions:xe.call(this,this.config.selectors.buttons.captions),fullscreen:xe.call(this,this.config.selectors.buttons.fullscreen)},this.elements.progress=xe.call(this,this.config.selectors.progress),this.elements.inputs={seek:xe.call(this,this.config.selectors.inputs.seek),volume:xe.call(this,this.config.selectors.inputs.volume)},this.elements.display={buffer:xe.call(this,this.config.selectors.display.buffer),currentTime:xe.call(this,this.config.selectors.display.currentTime),duration:xe.call(this,this.config.selectors.display.duration)},E.element(this.elements.progress)&&(this.elements.display.seekTooltip=this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`)),!0}catch(r){return this.debug.warn("It looks like there is a problem with your custom controls HTML",r),this.toggleNativeControls(!0),!1}},createIcon(r,e){const t="http://www.w3.org/2000/svg",i=N.getIconUrl.call(this),s=`${i.cors?"":i.url}#${this.config.iconPrefix}`,n=document.createElementNS(t,"svg");gs(n,Te(e,{"aria-hidden":"true",focusable:"false"}));const a=document.createElementNS(t,"use"),o=`${s}-${r}`;return"href"in a&&a.setAttributeNS("http://www.w3.org/1999/xlink","href",o),a.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",o),n.appendChild(a),n},createLabel(r,e={}){const t=_e.get(r,this.config);return j("span",ls(wt({},e),{class:[e.class,this.config.classNames.hidden].filter(Boolean).join(" ")}),t)},createBadge(r){if(E.empty(r))return null;const e=j("span",{class:this.config.classNames.menu.value});return e.appendChild(j("span",{class:this.config.classNames.menu.badge},r)),e},createButton(r,e){const t=Te({},e);let i=ec(r);const s={element:"button",toggle:!1,label:null,icon:null,labelPressed:null,iconPressed:null};switch(["element","icon","label"].forEach(a=>{Object.keys(t).includes(a)&&(s[a]=t[a],delete t[a])}),s.element!=="button"||Object.keys(t).includes("type")||(t.type="button"),Object.keys(t).includes("class")?t.class.split(" ").some(a=>a===this.config.classNames.control)||Te(t,{class:`${t.class} ${this.config.classNames.control}`}):t.class=this.config.classNames.control,r){case"play":s.toggle=!0,s.label="play",s.labelPressed="pause",s.icon="play",s.iconPressed="pause";break;case"mute":s.toggle=!0,s.label="mute",s.labelPressed="unmute",s.icon="volume",s.iconPressed="muted";break;case"captions":s.toggle=!0,s.label="enableCaptions",s.labelPressed="disableCaptions",s.icon="captions-off",s.iconPressed="captions-on";break;case"fullscreen":s.toggle=!0,s.label="enterFullscreen",s.labelPressed="exitFullscreen",s.icon="enter-fullscreen",s.iconPressed="exit-fullscreen";break;case"play-large":t.class+=` ${this.config.classNames.control}--overlaid`,i="play",s.label="play",s.icon="play";break;default:E.empty(s.label)&&(s.label=i),E.empty(s.icon)&&(s.icon=r)}const n=j(s.element);return s.toggle?(n.appendChild(N.createIcon.call(this,s.iconPressed,{class:"icon--pressed"})),n.appendChild(N.createIcon.call(this,s.icon,{class:"icon--not-pressed"})),n.appendChild(N.createLabel.call(this,s.labelPressed,{class:"label--pressed"})),n.appendChild(N.createLabel.call(this,s.label,{class:"label--not-pressed"}))):(n.appendChild(N.createIcon.call(this,s.icon)),n.appendChild(N.createLabel.call(this,s.label))),Te(t,qe(this.config.selectors.buttons[i],t)),gs(n,t),i==="play"?(E.array(this.elements.buttons[i])||(this.elements.buttons[i]=[]),this.elements.buttons[i].push(n)):this.elements.buttons[i]=n,n},createRange(r,e){const t=j("input",Te(qe(this.config.selectors.inputs[r]),{type:"range",min:0,max:100,step:.01,value:0,autocomplete:"off",role:"slider","aria-label":_e.get(r,this.config),"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":0},e));return this.elements.inputs[r]=t,N.updateRangeFill.call(this,t),Il.setup(t),t},createProgress(r,e){const t=j("progress",Te(qe(this.config.selectors.display[r]),{min:0,max:100,value:0,role:"progressbar","aria-hidden":!0},e));if(r!=="volume"){t.appendChild(j("span",null,"0"));const i={played:"played",buffer:"buffered"}[r],s=i?_e.get(i,this.config):"";t.innerText=`% ${s.toLowerCase()}`}return this.elements.display[r]=t,t},createTime(r,e){const t=qe(this.config.selectors.display[r],e),i=j("div",Te(t,{class:`${t.class?t.class:""} ${this.config.classNames.display.time} `.trim(),"aria-label":_e.get(r,this.config),role:"timer"}),"00:00");return this.elements.display[r]=i,i},bindMenuItemShortcuts(r,e){se.call(this,r,"keydown keyup",t=>{if(![" ","ArrowUp","ArrowDown","ArrowRight"].includes(t.key)||(t.preventDefault(),t.stopPropagation(),t.type==="keydown"))return;const i=St(r,'[role="menuitemradio"]');if(!i&&[" ","ArrowRight"].includes(t.key))N.showMenuPanel.call(this,e,!0);else{let s;t.key!==" "&&(t.key==="ArrowDown"||i&&t.key==="ArrowRight"?(s=r.nextElementSibling,E.element(s)||(s=r.parentNode.firstElementChild)):(s=r.previousElementSibling,E.element(s)||(s=r.parentNode.lastElementChild)),ps.call(this,s,!0))}},!1),se.call(this,r,"keyup",t=>{t.key==="Return"&&N.focusFirstMenuItem.call(this,null,!0)})},createMenuItem({value:r,list:e,type:t,title:i,badge:s=null,checked:n=!1}){const a=qe(this.config.selectors.inputs[t]),o=j("button",Te(a,{type:"button",role:"menuitemradio",class:`${this.config.classNames.control} ${a.class?a.class:""}`.trim(),"aria-checked":n,value:r})),c=j("span");c.innerHTML=i,E.element(s)&&c.appendChild(s),o.appendChild(c),Object.defineProperty(o,"checked",{enumerable:!0,get:()=>o.getAttribute("aria-checked")==="true",set(l){l&&Array.from(o.parentNode.children).filter(d=>St(d,'[role="menuitemradio"]')).forEach(d=>d.setAttribute("aria-checked","false")),o.setAttribute("aria-checked",l?"true":"false")}}),this.listeners.bind(o,"click keyup",l=>{if(!E.keyboardEvent(l)||l.key===" "){switch(l.preventDefault(),l.stopPropagation(),o.checked=!0,t){case"language":this.currentTrack=Number(r);break;case"quality":this.quality=r;break;case"speed":this.speed=parseFloat(r)}N.showMenuPanel.call(this,"home",E.keyboardEvent(l))}},t,!1),N.bindMenuItemShortcuts.call(this,o,t),e.appendChild(o)},formatTime(r=0,e=!1){return E.number(r)?Si(r,gn(this.duration)>0,e):r},updateTimeDisplay(r=null,e=0,t=!1){E.element(r)&&E.number(e)&&(r.innerText=N.formatTime(e,t))},updateVolume(){this.supported.ui&&(E.element(this.elements.inputs.volume)&&N.setRange.call(this,this.elements.inputs.volume,this.muted?0:this.volume),E.element(this.elements.buttons.mute)&&(this.elements.buttons.mute.pressed=this.muted||this.volume===0))},setRange(r,e=0){E.element(r)&&(r.value=e,N.updateRangeFill.call(this,r))},updateProgress(r){if(!this.supported.ui||!E.event(r))return;let e=0;const t=(i,s)=>{const n=E.number(s)?s:0,a=E.element(i)?i:this.elements.display.buffer;if(E.element(a)){a.value=n;const o=a.getElementsByTagName("span")[0];E.element(o)&&(o.childNodes[0].nodeValue=n)}};if(r)switch(r.type){case"timeupdate":case"seeking":case"seeked":e=Jl(this.currentTime,this.duration),r.type==="timeupdate"&&N.setRange.call(this,this.elements.inputs.seek,e);break;case"playing":case"progress":t(this.elements.display.buffer,100*this.buffered)}},updateRangeFill(r){const e=E.event(r)?r.target:r;if(E.element(e)&&e.getAttribute("type")==="range"){if(St(e,this.config.selectors.inputs.seek)){e.setAttribute("aria-valuenow",this.currentTime);const t=N.formatTime(this.currentTime),i=N.formatTime(this.duration),s=_e.get("seekLabel",this.config);e.setAttribute("aria-valuetext",s.replace("{currentTime}",t).replace("{duration}",i))}else if(St(e,this.config.selectors.inputs.volume)){const t=100*e.value;e.setAttribute("aria-valuenow",t),e.setAttribute("aria-valuetext",`${t.toFixed(1)}%`)}else e.setAttribute("aria-valuenow",e.value);(Le.isWebKit||Le.isIPadOS)&&e.style.setProperty("--value",e.value/e.max*100+"%")}},updateSeekTooltip(r){var e,t;if(!this.config.tooltips.seek||!E.element(this.elements.inputs.seek)||!E.element(this.elements.display.seekTooltip)||this.duration===0)return;const i=this.elements.display.seekTooltip,s=`${this.config.classNames.tooltip}--visible`,n=d=>oe(i,s,d);if(this.touch)return void n(!1);let a=0;const o=this.elements.progress.getBoundingClientRect();if(E.event(r))a=100/o.width*(r.pageX-o.left);else{if(!Ti(i,s))return;a=parseFloat(i.style.left,10)}a<0?a=0:a>100&&(a=100);const c=this.duration/100*a;i.innerText=N.formatTime(c);const l=(e=this.config.markers)===null||e===void 0||(t=e.points)===null||t===void 0?void 0:t.find(({time:d})=>d===Math.round(c));l&&i.insertAdjacentHTML("afterbegin",`${l.label}
`),i.style.left=`${a}%`,E.event(r)&&["mouseenter","mouseleave"].includes(r.type)&&n(r.type==="mouseenter")},timeUpdate(r){const e=!E.element(this.elements.display.duration)&&this.config.invertTime;N.updateTimeDisplay.call(this,this.elements.display.currentTime,e?this.duration-this.currentTime:this.currentTime,e),r&&r.type==="timeupdate"&&this.media.seeking||N.updateProgress.call(this,r)},durationUpdate(){if(!this.supported.ui||!this.config.invertTime&&this.currentTime)return;if(this.duration>=Ur(2,32))return xt(this.elements.display.currentTime,!0),void xt(this.elements.progress,!0);E.element(this.elements.inputs.seek)&&this.elements.inputs.seek.setAttribute("aria-valuemax",this.duration);const r=E.element(this.elements.display.duration);!r&&this.config.displayDuration&&this.paused&&N.updateTimeDisplay.call(this,this.elements.display.currentTime,this.duration),r&&N.updateTimeDisplay.call(this,this.elements.display.duration,this.duration),this.config.markers.enabled&&N.setMarkers.call(this),N.updateSeekTooltip.call(this)},toggleMenuButton(r,e){xt(this.elements.settings.buttons[r],!e)},updateSetting(r,e,t){const i=this.elements.settings.panels[r];let s=null,n=e;if(r==="captions")s=this.currentTrack;else{if(s=E.empty(t)?this[r]:t,E.empty(s)&&(s=this.config[r].default),!E.empty(this.options[r])&&!this.options[r].includes(s))return void this.debug.warn(`Unsupported value of '${s}' for ${r}`);if(!this.config[r].options.includes(s))return void this.debug.warn(`Disabled value of '${s}' for ${r}`)}if(E.element(n)||(n=i&&i.querySelector('[role="menu"]')),!E.element(n))return;this.elements.settings.buttons[r].querySelector(`.${this.config.classNames.menu.value}`).innerHTML=N.getLabel.call(this,r,s);const a=n&&n.querySelector(`[value="${s}"]`);E.element(a)&&(a.checked=!0)},getLabel(r,e){switch(r){case"speed":return e===1?_e.get("normal",this.config):`${e}×`;case"quality":if(E.number(e)){const t=_e.get(`qualityLabel.${e}`,this.config);return t.length?t:`${e}p`}return un(e);case"captions":return ne.getLabel.call(this);default:return null}},setQualityMenu(r){if(!E.element(this.elements.settings.panels.quality))return;const e="quality",t=this.elements.settings.panels.quality.querySelector('[role="menu"]');E.array(r)&&(this.options.quality=ys(r).filter(n=>this.config.quality.options.includes(n)));const i=!E.empty(this.options.quality)&&this.options.quality.length>1;if(N.toggleMenuButton.call(this,e,i),vi(t),N.checkMenu.call(this),!i)return;const s=n=>{const a=_e.get(`qualityBadge.${n}`,this.config);return a.length?N.createBadge.call(this,a):null};this.options.quality.sort((n,a)=>{const o=this.config.quality.options;return o.indexOf(n)>o.indexOf(a)?1:-1}).forEach(n=>{N.createMenuItem.call(this,{value:n,list:t,type:e,title:N.getLabel.call(this,"quality",n),badge:s(n)})}),N.updateSetting.call(this,e,t)},setCaptionsMenu(){if(!E.element(this.elements.settings.panels.captions))return;const r="captions",e=this.elements.settings.panels.captions.querySelector('[role="menu"]'),t=ne.getTracks.call(this),i=!!t.length;if(N.toggleMenuButton.call(this,r,i),vi(e),N.checkMenu.call(this),!i)return;const s=t.map((n,a)=>({value:a,checked:this.captions.toggled&&this.currentTrack===a,title:ne.getLabel.call(this,n),badge:n.language&&N.createBadge.call(this,n.language.toUpperCase()),list:e,type:"language"}));s.unshift({value:-1,checked:!this.captions.toggled,title:_e.get("disabled",this.config),list:e,type:"language"}),s.forEach(N.createMenuItem.bind(this)),N.updateSetting.call(this,r,e)},setSpeedMenu(){if(!E.element(this.elements.settings.panels.speed))return;const r="speed",e=this.elements.settings.panels.speed.querySelector('[role="menu"]');this.options.speed=this.options.speed.filter(i=>i>=this.minimumSpeed&&i<=this.maximumSpeed);const t=!E.empty(this.options.speed)&&this.options.speed.length>1;N.toggleMenuButton.call(this,r,t),vi(e),N.checkMenu.call(this),t&&(this.options.speed.forEach(i=>{N.createMenuItem.call(this,{value:i,list:e,type:r,title:N.getLabel.call(this,"speed",i)})}),N.updateSetting.call(this,r,e))},checkMenu(){const{buttons:r}=this.elements.settings,e=!E.empty(r)&&Object.values(r).some(t=>!t.hidden);xt(this.elements.settings.menu,!e)},focusFirstMenuItem(r,e=!1){if(this.elements.settings.popup.hidden)return;let t=r;E.element(t)||(t=Object.values(this.elements.settings.panels).find(s=>!s.hidden));const i=t.querySelector('[role^="menuitem"]');ps.call(this,i,e)},toggleMenu(r){const{popup:e}=this.elements.settings,t=this.elements.buttons.settings;if(!E.element(e)||!E.element(t))return;const{hidden:i}=e;let s=i;if(E.boolean(r))s=r;else if(E.keyboardEvent(r)&&r.key==="Escape")s=!1;else if(E.event(r)){const n=E.function(r.composedPath)?r.composedPath()[0]:r.target,a=e.contains(n);if(a||!a&&r.target!==t&&s)return}t.setAttribute("aria-expanded",s),xt(e,!s),oe(this.elements.container,this.config.classNames.menu.open,s),s&&E.keyboardEvent(r)?N.focusFirstMenuItem.call(this,null,!0):s||i||ps.call(this,t,E.keyboardEvent(r))},getMenuSize(r){const e=r.cloneNode(!0);e.style.position="absolute",e.style.opacity=0,e.removeAttribute("hidden"),r.parentNode.appendChild(e);const t=e.scrollWidth,i=e.scrollHeight;return nt(e),{width:t,height:i}},showMenuPanel(r="",e=!1){const t=this.elements.container.querySelector(`#plyr-settings-${this.id}-${r}`);if(!E.element(t))return;const i=t.parentNode,s=Array.from(i.children).find(n=>!n.hidden);if(Ee.transitions&&!Ee.reducedMotion){i.style.width=`${s.scrollWidth}px`,i.style.height=`${s.scrollHeight}px`;const n=N.getMenuSize.call(this,t),a=o=>{o.target===i&&["width","height"].includes(o.propertyName)&&(i.style.width="",i.style.height="",Ei.call(this,i,fs,a))};se.call(this,i,fs,a),i.style.width=`${n.width}px`,i.style.height=`${n.height}px`}xt(s,!0),xt(t,!1),N.focusFirstMenuItem.call(this,t,e)},setDownloadUrl(){const r=this.elements.buttons.download;E.element(r)&&r.setAttribute("href",this.download)},create(r){const{bindMenuItemShortcuts:e,createButton:t,createProgress:i,createRange:s,createTime:n,setQualityMenu:a,setSpeedMenu:o,showMenuPanel:c}=N;this.elements.controls=null,E.array(this.config.controls)&&this.config.controls.includes("play-large")&&this.elements.container.appendChild(t.call(this,"play-large"));const l=j("div",qe(this.config.selectors.controls.wrapper));this.elements.controls=l;const d={class:"plyr__controls__item"};return ys(E.array(this.config.controls)?this.config.controls:[]).forEach(u=>{if(u==="restart"&&l.appendChild(t.call(this,"restart",d)),u==="rewind"&&l.appendChild(t.call(this,"rewind",d)),u==="play"&&l.appendChild(t.call(this,"play",d)),u==="fast-forward"&&l.appendChild(t.call(this,"fast-forward",d)),u==="progress"){const h=j("div",{class:`${d.class} plyr__progress__container`}),f=j("div",qe(this.config.selectors.progress));if(f.appendChild(s.call(this,"seek",{id:`plyr-seek-${r.id}`})),f.appendChild(i.call(this,"buffer")),this.config.tooltips.seek){const g=j("span",{class:this.config.classNames.tooltip},"00:00");f.appendChild(g),this.elements.display.seekTooltip=g}this.elements.progress=f,h.appendChild(this.elements.progress),l.appendChild(h)}if(u==="current-time"&&l.appendChild(n.call(this,"currentTime",d)),u==="duration"&&l.appendChild(n.call(this,"duration",d)),u==="mute"||u==="volume"){let{volume:h}=this.elements;if(E.element(h)&&l.contains(h)||(h=j("div",Te({},d,{class:`${d.class} plyr__volume`.trim()})),this.elements.volume=h,l.appendChild(h)),u==="mute"&&h.appendChild(t.call(this,"mute")),u==="volume"&&!Le.isIos&&!Le.isIPadOS){const f={max:1,step:.05,value:this.config.volume};h.appendChild(s.call(this,"volume",Te(f,{id:`plyr-volume-${r.id}`})))}}if(u==="captions"&&l.appendChild(t.call(this,"captions",d)),u==="settings"&&!E.empty(this.config.settings)){const h=j("div",Te({},d,{class:`${d.class} plyr__menu`.trim(),hidden:""}));h.appendChild(t.call(this,"settings",{"aria-haspopup":!0,"aria-controls":`plyr-settings-${r.id}`,"aria-expanded":!1}));const f=j("div",{class:"plyr__menu__container",id:`plyr-settings-${r.id}`,hidden:""}),g=j("div"),m=j("div",{id:`plyr-settings-${r.id}-home`}),y=j("div",{role:"menu"});m.appendChild(y),g.appendChild(m),this.elements.settings.panels.home=m,this.config.settings.forEach(v=>{const T=j("button",Te(qe(this.config.selectors.buttons.settings),{type:"button",class:`${this.config.classNames.control} ${this.config.classNames.control}--forward`,role:"menuitem","aria-haspopup":!0,hidden:""}));e.call(this,T,v),se.call(this,T,"click",()=>{c.call(this,v,!1)});const b=j("span",null,_e.get(v,this.config)),x=j("span",{class:this.config.classNames.menu.value});x.innerHTML=r[v],b.appendChild(x),T.appendChild(b),y.appendChild(T);const S=j("div",{id:`plyr-settings-${r.id}-${v}`,hidden:""}),k=j("button",{type:"button",class:`${this.config.classNames.control} ${this.config.classNames.control}--back`});k.appendChild(j("span",{"aria-hidden":!0},_e.get(v,this.config))),k.appendChild(j("span",{class:this.config.classNames.hidden},_e.get("menuBack",this.config))),se.call(this,S,"keydown",A=>{A.key==="ArrowLeft"&&(A.preventDefault(),A.stopPropagation(),c.call(this,"home",!0))},!1),se.call(this,k,"click",()=>{c.call(this,"home",!1)}),S.appendChild(k),S.appendChild(j("div",{role:"menu"})),g.appendChild(S),this.elements.settings.buttons[v]=T,this.elements.settings.panels[v]=S}),f.appendChild(g),h.appendChild(f),l.appendChild(h),this.elements.settings.popup=f,this.elements.settings.menu=h}if(u==="pip"&&Ee.pip&&l.appendChild(t.call(this,"pip",d)),u==="airplay"&&Ee.airplay&&l.appendChild(t.call(this,"airplay",d)),u==="download"){const h=Te({},d,{element:"a",href:this.download,target:"_blank"});this.isHTML5&&(h.download="");const{download:f}=this.config.urls;!E.url(f)&&this.isEmbed&&Te(h,{icon:`logo-${this.provider}`,label:this.provider}),l.appendChild(t.call(this,"download",h))}u==="fullscreen"&&l.appendChild(t.call(this,"fullscreen",d))}),this.isHTML5&&a.call(this,ht.getQualityOptions.call(this)),o.call(this),l},inject(){if(this.config.loadSprite){const s=N.getIconUrl.call(this);s.cors&&fn(s.url,"sprite-plyr")}this.id=Math.floor(1e4*Math.random());let r=null;this.elements.controls=null;const e={id:this.id,seektime:this.config.seekTime,title:this.config.title};let t=!0;E.function(this.config.controls)&&(this.config.controls=this.config.controls.call(this,e)),this.config.controls||(this.config.controls=[]),E.element(this.config.controls)||E.string(this.config.controls)?r=this.config.controls:(r=N.create.call(this,{id:this.id,seektime:this.config.seekTime,speed:this.speed,quality:this.quality,captions:ne.getLabel.call(this)}),t=!1);let i;if(t&&E.string(this.config.controls)&&(r=(s=>{let n=s;return Object.entries(e).forEach(([a,o])=>{n=Xt(n,`{${a}}`,o)}),n})(r)),E.string(this.config.selectors.controls.container)&&(i=document.querySelector(this.config.selectors.controls.container)),E.element(i)||(i=this.elements.container),i[E.element(r)?"insertAdjacentElement":"insertAdjacentHTML"]("afterbegin",r),E.element(this.elements.controls)||N.findElements.call(this),!E.empty(this.elements.buttons)){const s=n=>{const a=this.config.classNames.controlPressed;n.setAttribute("aria-pressed","false"),Object.defineProperty(n,"pressed",{configurable:!0,enumerable:!0,get:()=>Ti(n,a),set(o=!1){oe(n,a,o),n.setAttribute("aria-pressed",o?"true":"false")}})};Object.values(this.elements.buttons).filter(Boolean).forEach(n=>{E.array(n)||E.nodeList(n)?Array.from(n).filter(Boolean).forEach(s):s(n)})}if(Le.isEdge&&en(i),this.config.tooltips.controls){const{classNames:s,selectors:n}=this.config,a=`${n.controls.wrapper} ${n.labels} .${s.hidden}`,o=qt.call(this,a);Array.from(o).forEach(c=>{oe(c,this.config.classNames.hidden,!1),oe(c,this.config.classNames.tooltip,!0)})}},setMediaMetadata(){try{"mediaSession"in navigator&&(navigator.mediaSession.metadata=new window.MediaMetadata({title:this.config.mediaMetadata.title,artist:this.config.mediaMetadata.artist,album:this.config.mediaMetadata.album,artwork:this.config.mediaMetadata.artwork}))}catch(r){}},setMarkers(){var r,e;if(!this.duration||this.elements.markers)return;const t=(r=this.config.markers)===null||r===void 0||(e=r.points)===null||e===void 0?void 0:e.filter(({time:c})=>c>0&&coe(n,a,c);t.forEach(c=>{const l=j("span",{class:this.config.classNames.marker},""),d=c.time/this.duration*100+"%";n&&(l.addEventListener("mouseenter",()=>{c.label||(n.style.left=d,n.innerHTML=c.label,o(!0))}),l.addEventListener("mouseleave",()=>{o(!1)})),l.addEventListener("click",()=>{this.currentTime=c.time}),l.style.left=d,s.appendChild(l)}),i.appendChild(s),this.config.tooltips.seek||(n=j("span",{class:this.config.classNames.tooltip},""),i.appendChild(n)),this.elements.markers={points:s,tip:n},this.elements.progress.appendChild(i)}};function pn(r,e=!0){let t=r;if(e){const i=document.createElement("a");i.href=t,t=i.href}try{return new URL(t)}catch(i){return null}}function mn(r){const e=new URLSearchParams;return E.object(r)&&Object.entries(r).forEach(([t,i])=>{e.set(t,i)}),e}const ne={setup(){if(!this.supported.ui)return;if(!this.isVideo||this.isYouTube||this.isHTML5&&!Ee.textTracks)return void(E.array(this.config.controls)&&this.config.controls.includes("settings")&&this.config.settings.includes("captions")&&N.setCaptionsMenu.call(this));if(E.element(this.elements.captions)||(this.elements.captions=j("div",qe(this.config.selectors.captions)),this.elements.captions.setAttribute("dir","auto"),Wl(this.elements.captions,this.elements.wrapper)),Le.isIE&&window.URL){const i=this.media.querySelectorAll("track");Array.from(i).forEach(s=>{const n=s.getAttribute("src"),a=pn(n);a!==null&&a.hostname!==window.location.href.hostname&&["http:","https:"].includes(a.protocol)&&Jt(n,"blob").then(o=>{s.setAttribute("src",window.URL.createObjectURL(o))}).catch(()=>{nt(s)})})}const r=ys((navigator.languages||[navigator.language||navigator.userLanguage||"en"]).map(i=>i.split("-")[0]));let e=(this.storage.get("language")||this.config.captions.language||"auto").toLowerCase();e==="auto"&&([e]=r);let t=this.storage.get("captions");if(E.boolean(t)||({active:t}=this.config.captions),Object.assign(this.captions,{toggled:!1,active:t,language:e,languages:r}),this.isHTML5){const i=this.config.captions.update?"addtrack removetrack":"removetrack";se.call(this,this.media.textTracks,i,ne.update.bind(this))}setTimeout(ne.update.bind(this),0)},update(){const r=ne.getTracks.call(this,!0),{active:e,language:t,meta:i,currentTrackNode:s}=this.captions,n=!!r.find(a=>a.language===t);this.isHTML5&&this.isVideo&&r.filter(a=>!i.get(a)).forEach(a=>{this.debug.log("Track added",a),i.set(a,{default:a.mode==="showing"}),a.mode==="showing"&&(a.mode="hidden"),se.call(this,a,"cuechange",()=>ne.updateCues.call(this))}),(n&&this.language!==t||!r.includes(s))&&(ne.setLanguage.call(this,t),ne.toggle.call(this,e&&n)),this.elements&&oe(this.elements.container,this.config.classNames.captions.enabled,!E.empty(r)),E.array(this.config.controls)&&this.config.controls.includes("settings")&&this.config.settings.includes("captions")&&N.setCaptionsMenu.call(this)},toggle(r,e=!0){if(!this.supported.ui)return;const{toggled:t}=this.captions,i=this.config.classNames.captions.active,s=E.nullOrUndefined(r)?!t:r;if(s!==t){if(e||(this.captions.active=s,this.storage.set({captions:s})),!this.language&&s&&!e){const n=ne.getTracks.call(this),a=ne.findTrack.call(this,[this.captions.language,...this.captions.languages],!0);return this.captions.language=a.language,void ne.set.call(this,n.indexOf(a))}this.elements.buttons.captions&&(this.elements.buttons.captions.pressed=s),oe(this.elements.container,i,s),this.captions.toggled=s,N.updateSetting.call(this,"captions"),z.call(this,this.media,s?"captionsenabled":"captionsdisabled")}setTimeout(()=>{s&&this.captions.toggled&&(this.captions.currentTrackNode.mode="hidden")})},set(r,e=!0){const t=ne.getTracks.call(this);if(r!==-1)if(E.number(r))if(r in t){if(this.captions.currentTrack!==r){this.captions.currentTrack=r;const i=t[r],{language:s}=i||{};this.captions.currentTrackNode=i,N.updateSetting.call(this,"captions"),e||(this.captions.language=s,this.storage.set({language:s})),this.isVimeo&&this.embed.enableTextTrack(s),z.call(this,this.media,"languagechange")}ne.toggle.call(this,!0,e),this.isHTML5&&this.isVideo&&ne.updateCues.call(this)}else this.debug.warn("Track not found",r);else this.debug.warn("Invalid caption argument",r);else ne.toggle.call(this,!1,e)},setLanguage(r,e=!0){if(!E.string(r))return void this.debug.warn("Invalid language argument",r);const t=r.toLowerCase();this.captions.language=t;const i=ne.getTracks.call(this),s=ne.findTrack.call(this,[t]);ne.set.call(this,i.indexOf(s),e)},getTracks(r=!1){return Array.from((this.media||{}).textTracks||[]).filter(e=>!this.isHTML5||r||this.captions.meta.has(e)).filter(e=>["captions","subtitles"].includes(e.kind))},findTrack(r,e=!1){const t=ne.getTracks.call(this),i=a=>Number((this.captions.meta.get(a)||{}).default),s=Array.from(t).sort((a,o)=>i(o)-i(a));let n;return r.every(a=>(n=s.find(o=>o.language===a),!n)),n||(e?s[0]:void 0)},getCurrentTrack(){return ne.getTracks.call(this)[this.currentTrack]},getLabel(r){let e=r;return!E.track(e)&&Ee.textTracks&&this.captions.toggled&&(e=ne.getCurrentTrack.call(this)),E.track(e)?E.empty(e.label)?E.empty(e.language)?_e.get("enabled",this.config):r.language.toUpperCase():e.label:_e.get("disabled",this.config)},updateCues(r){if(!this.supported.ui)return;if(!E.element(this.elements.captions))return void this.debug.warn("No captions element to render to");if(!E.nullOrUndefined(r)&&!Array.isArray(r))return void this.debug.warn("updateCues: Invalid input",r);let e=r;if(!e){const i=ne.getCurrentTrack.call(this);e=Array.from((i||{}).activeCues||[]).map(s=>s.getCueAsHTML()).map(ic)}const t=e.map(i=>i.trim()).join(` `);if(t!==this.elements.captions.innerHTML){vi(this.elements.captions);const i=j("span",qe(this.config.selectors.caption));i.innerHTML=t,this.elements.captions.appendChild(i),z.call(this,this.media,"cuechange")}}},yn={enabled:!0,title:"",debug:!1,autoplay:!1,autopause:!0,playsinline:!0,seekTime:10,volume:1,muted:!1,duration:null,displayDuration:!0,invertTime:!0,toggleInvert:!0,ratio:null,clickToPlay:!0,hideControls:!0,resetOnEnd:!1,disableContextMenu:!0,loadSprite:!0,iconPrefix:"plyr",iconUrl:"https://cdn.plyr.io/3.7.8/plyr.svg",blankVideo:"https://cdn.plyr.io/static/blank.mp4",quality:{default:576,options:[4320,2880,2160,1440,1080,720,576,480,360,240],forced:!1,onChange:null},loop:{active:!1},speed:{selected:1,options:[.5,.75,1,1.25,1.5,1.75,2,4]},keyboard:{focused:!0,global:!1},tooltips:{controls:!1,seek:!0},captions:{active:!1,language:"auto",update:!1},fullscreen:{enabled:!0,fallback:!0,iosNative:!1},storage:{enabled:!0,key:"plyr"},controls:["play-large","play","progress","current-time","mute","volume","captions","settings","pip","airplay","fullscreen"],settings:["captions","quality","speed"],i18n:{restart:"Restart",rewind:"Rewind {seektime}s",play:"Play",pause:"Pause",fastForward:"Forward {seektime}s",seek:"Seek",seekLabel:"{currentTime} of {duration}",played:"Played",buffered:"Buffered",currentTime:"Current time",duration:"Duration",volume:"Volume",mute:"Mute",unmute:"Unmute",enableCaptions:"Enable captions",disableCaptions:"Disable captions",download:"Download",enterFullscreen:"Enter fullscreen",exitFullscreen:"Exit fullscreen",frameTitle:"Player for {title}",captions:"Captions",settings:"Settings",pip:"PIP",menuBack:"Go back to previous menu",speed:"Speed",normal:"Normal",quality:"Quality",loop:"Loop",start:"Start",end:"End",all:"All",reset:"Reset",disabled:"Disabled",enabled:"Enabled",advertisement:"Ad",qualityBadge:{2160:"4K",1440:"HD",1080:"HD",720:"HD",576:"SD",480:"SD"}},urls:{download:null,vimeo:{sdk:"https://player.vimeo.com/api/player.js",iframe:"https://player.vimeo.com/video/{0}?{1}",api:"https://vimeo.com/api/oembed.json?url={0}"},youtube:{sdk:"https://www.youtube.com/iframe_api",api:"https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}"},googleIMA:{sdk:"https://imasdk.googleapis.com/js/sdkloader/ima3.js"}},listeners:{seek:null,play:null,pause:null,restart:null,rewind:null,fastForward:null,mute:null,volume:null,captions:null,download:null,fullscreen:null,pip:null,airplay:null,speed:null,quality:null,loop:null,language:null},events:["ended","progress","stalled","playing","waiting","canplay","canplaythrough","loadstart","loadeddata","loadedmetadata","timeupdate","volumechange","play","pause","error","seeking","seeked","emptied","ratechange","cuechange","download","enterfullscreen","exitfullscreen","captionsenabled","captionsdisabled","languagechange","controlshidden","controlsshown","ready","statechange","qualitychange","adsloaded","adscontentpause","adscontentresume","adstarted","adsmidpoint","adscomplete","adsallcomplete","adsimpression","adsclick"],selectors:{editable:"input, textarea, select, [contenteditable]",container:".plyr",controls:{container:null,wrapper:".plyr__controls"},labels:"[data-plyr]",buttons:{play:'[data-plyr="play"]',pause:'[data-plyr="pause"]',restart:'[data-plyr="restart"]',rewind:'[data-plyr="rewind"]',fastForward:'[data-plyr="fast-forward"]',mute:'[data-plyr="mute"]',captions:'[data-plyr="captions"]',download:'[data-plyr="download"]',fullscreen:'[data-plyr="fullscreen"]',pip:'[data-plyr="pip"]',airplay:'[data-plyr="airplay"]',settings:'[data-plyr="settings"]',loop:'[data-plyr="loop"]'},inputs:{seek:'[data-plyr="seek"]',volume:'[data-plyr="volume"]',speed:'[data-plyr="speed"]',language:'[data-plyr="language"]',quality:'[data-plyr="quality"]'},display:{currentTime:".plyr__time--current",duration:".plyr__time--duration",buffer:".plyr__progress__buffer",loop:".plyr__progress__loop",volume:".plyr__volume--display"},progress:".plyr__progress",captions:".plyr__captions",caption:".plyr__caption"},classNames:{type:"plyr--{0}",provider:"plyr--{0}",video:"plyr__video-wrapper",embed:"plyr__video-embed",videoFixedRatio:"plyr__video-wrapper--fixed-ratio",embedContainer:"plyr__video-embed__container",poster:"plyr__poster",posterEnabled:"plyr__poster-enabled",ads:"plyr__ads",control:"plyr__control",controlPressed:"plyr__control--pressed",playing:"plyr--playing",paused:"plyr--paused",stopped:"plyr--stopped",loading:"plyr--loading",hover:"plyr--hover",tooltip:"plyr__tooltip",cues:"plyr__cues",marker:"plyr__progress__marker",hidden:"plyr__sr-only",hideControls:"plyr--hide-controls",isTouch:"plyr--is-touch",uiSupported:"plyr--full-ui",noTransition:"plyr--no-transition",display:{time:"plyr__time"},menu:{value:"plyr__menu__value",badge:"plyr__badge",open:"plyr--menu-open"},captions:{enabled:"plyr--captions-enabled",active:"plyr--captions-active"},fullscreen:{enabled:"plyr--fullscreen-enabled",fallback:"plyr--fullscreen-fallback"},pip:{supported:"plyr--pip-supported",active:"plyr--pip-active"},airplay:{supported:"plyr--airplay-supported",active:"plyr--airplay-active"},previewThumbnails:{thumbContainer:"plyr__preview-thumb",thumbContainerShown:"plyr__preview-thumb--is-shown",imageContainer:"plyr__preview-thumb__image-container",timeContainer:"plyr__preview-thumb__time-container",scrubbingContainer:"plyr__preview-scrubbing",scrubbingContainerShown:"plyr__preview-scrubbing--is-shown"}},attributes:{embed:{provider:"data-plyr-provider",id:"data-plyr-embed-id",hash:"data-plyr-embed-hash"}},ads:{enabled:!1,publisherId:"",tagUrl:""},previewThumbnails:{enabled:!1,src:""},vimeo:{byline:!1,portrait:!1,title:!1,speed:!0,transparent:!1,customControls:!0,referrerPolicy:null,premium:!1},youtube:{rel:0,showinfo:0,iv_load_policy:3,modestbranding:1,customControls:!0,noCookie:!1},mediaMetadata:{title:"",artist:"",album:"",artwork:[]},markers:{enabled:!1,points:[]}},Ts={active:"picture-in-picture",inactive:"inline"},ft={html5:"html5",youtube:"youtube",vimeo:"vimeo"},Es={audio:"audio",video:"video"};function nc(r){return/^(https?:\/\/)?(www\.)?(youtube\.com|youtube-nocookie\.com|youtu\.?be)\/.+$/.test(r)?ft.youtube:/^https?:\/\/player.vimeo.com\/video\/\d{0,9}(?=\b|\/)/.test(r)?ft.vimeo:null}const xs=()=>{};class ac{constructor(e=!1){this.enabled=window.console&&e,this.enabled&&this.log("Debugging enabled")}get log(){return this.enabled?Function.prototype.bind.call(console.log,console):xs}get warn(){return this.enabled?Function.prototype.bind.call(console.warn,console):xs}get error(){return this.enabled?Function.prototype.bind.call(console.error,console):xs}}class He{constructor(e){F(this,"onChange",()=>{if(!this.supported)return;const t=this.player.elements.buttons.fullscreen;E.element(t)&&(t.pressed=this.active);const i=this.target===this.player.media?this.target:this.player.elements.container;z.call(this.player,i,this.active?"enterfullscreen":"exitfullscreen",!0)}),F(this,"toggleFallback",(t=!1)=>{var i,s;if(t?this.scrollPosition={x:(i=window.scrollX)!=null?i:0,y:(s=window.scrollY)!=null?s:0}:window.scrollTo(this.scrollPosition.x,this.scrollPosition.y),document.body.style.overflow=t?"hidden":"",oe(this.target,this.player.config.classNames.fullscreen.fallback,t),Le.isIos){let n=document.head.querySelector('meta[name="viewport"]');const a="viewport-fit=cover";n||(n=document.createElement("meta"),n.setAttribute("name","viewport"));const o=E.string(n.content)&&n.content.includes(a);t?(this.cleanupViewport=!o,o||(n.content+=`,${a}`)):this.cleanupViewport&&(n.content=n.content.split(",").filter(c=>c.trim()!==a).join(","))}this.onChange()}),F(this,"trapFocus",t=>{if(Le.isIos||Le.isIPadOS||!this.active||t.key!=="Tab")return;const i=document.activeElement,s=qt.call(this.player,"a[href], button:not(:disabled), input:not(:disabled), [tabindex]"),[n]=s,a=s[s.length-1];i!==a||t.shiftKey?i===n&&t.shiftKey&&(a.focus(),t.preventDefault()):(n.focus(),t.preventDefault())}),F(this,"update",()=>{if(this.supported){let t;t=this.forceFallback?"Fallback (forced)":He.nativeSupported?"Native":"Fallback",this.player.debug.log(`${t} fullscreen enabled`)}else this.player.debug.log("Fullscreen not supported and fallback disabled");oe(this.player.elements.container,this.player.config.classNames.fullscreen.enabled,this.supported)}),F(this,"enter",()=>{this.supported&&(Le.isIos&&this.player.config.fullscreen.iosNative?this.player.isVimeo?this.player.embed.requestFullscreen():this.target.webkitEnterFullscreen():!He.nativeSupported||this.forceFallback?this.toggleFallback(!0):this.prefix?E.empty(this.prefix)||this.target[`${this.prefix}Request${this.property}`]():this.target.requestFullscreen({navigationUI:"hide"}))}),F(this,"exit",()=>{if(this.supported)if(Le.isIos&&this.player.config.fullscreen.iosNative)this.player.isVimeo?this.player.embed.exitFullscreen():this.target.webkitEnterFullscreen(),ze(this.player.play());else if(!He.nativeSupported||this.forceFallback)this.toggleFallback(!1);else if(this.prefix){if(!E.empty(this.prefix)){const t=this.prefix==="moz"?"Cancel":"Exit";document[`${this.prefix}${t}${this.property}`]()}}else(document.cancelFullScreen||document.exitFullscreen).call(document)}),F(this,"toggle",()=>{this.active?this.exit():this.enter()}),this.player=e,this.prefix=He.prefix,this.property=He.property,this.scrollPosition={x:0,y:0},this.forceFallback=e.config.fullscreen.fallback==="force",this.player.elements.fullscreen=e.config.fullscreen.container&&Yl(this.player.elements.container,e.config.fullscreen.container),se.call(this.player,document,this.prefix==="ms"?"MSFullscreenChange":`${this.prefix}fullscreenchange`,()=>{this.onChange()}),se.call(this.player,this.player.elements.container,"dblclick",t=>{E.element(this.player.elements.controls)&&this.player.elements.controls.contains(t.target)||this.player.listeners.proxy(t,this.toggle,"fullscreen")}),se.call(this,this.player.elements.container,"keydown",t=>this.trapFocus(t)),this.update()}static get nativeSupported(){return!!(document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled)}get useNative(){return He.nativeSupported&&!this.forceFallback}static get prefix(){if(E.function(document.exitFullscreen))return"";let e="";return["webkit","moz","ms"].some(t=>!(!E.function(document[`${t}ExitFullscreen`])&&!E.function(document[`${t}CancelFullScreen`]))&&(e=t,!0)),e}static get property(){return this.prefix==="moz"?"FullScreen":"Fullscreen"}get supported(){return[this.player.config.fullscreen.enabled,this.player.isVideo,He.nativeSupported||this.player.config.fullscreen.fallback,!this.player.isYouTube||He.nativeSupported||!Le.isIos||this.player.config.playsinline&&!this.player.config.fullscreen.iosNative].every(Boolean)}get active(){if(!this.supported)return!1;if(!He.nativeSupported||this.forceFallback)return Ti(this.target,this.player.config.classNames.fullscreen.fallback);const e=this.prefix?this.target.getRootNode()[`${this.prefix}${this.property}Element`]:this.target.getRootNode().fullscreenElement;return e&&e.shadowRoot?e===this.target.getRootNode().host:e===this.target}get target(){var e;return Le.isIos&&this.player.config.fullscreen.iosNative?this.player.media:(e=this.player.elements.fullscreen)!=null?e:this.player.elements.container}}function Ai(r,e=1){return new Promise((t,i)=>{const s=new Image,n=()=>{delete s.onload,delete s.onerror,(s.naturalWidth>=e?t:i)(s)};Object.assign(s,{onload:n,onerror:n,src:r})})}const fe={addStyleHook(){oe(this.elements.container,this.config.selectors.container.replace(".",""),!0),oe(this.elements.container,this.config.classNames.uiSupported,this.supported.ui)},toggleNativeControls(r=!1){r&&this.isHTML5?this.media.setAttribute("controls",""):this.media.removeAttribute("controls")},build(){if(this.listeners.media(),!this.supported.ui)return this.debug.warn(`Basic support only for ${this.provider} ${this.type}`),void fe.toggleNativeControls.call(this,!0);E.element(this.elements.controls)||(N.inject.call(this),this.listeners.controls()),fe.toggleNativeControls.call(this),this.isHTML5&&ne.setup.call(this),this.volume=null,this.muted=null,this.loop=null,this.quality=null,this.speed=null,N.updateVolume.call(this),N.timeUpdate.call(this),N.durationUpdate.call(this),fe.checkPlaying.call(this),oe(this.elements.container,this.config.classNames.pip.supported,Ee.pip&&this.isHTML5&&this.isVideo),oe(this.elements.container,this.config.classNames.airplay.supported,Ee.airplay&&this.isHTML5),oe(this.elements.container,this.config.classNames.isTouch,this.touch),this.ready=!0,setTimeout(()=>{z.call(this,this.media,"ready")},0),fe.setTitle.call(this),this.poster&&fe.setPoster.call(this,this.poster,!1).catch(()=>{}),this.config.duration&&N.durationUpdate.call(this),this.config.mediaMetadata&&N.setMediaMetadata.call(this)},setTitle(){let r=_e.get("play",this.config);if(E.string(this.config.title)&&!E.empty(this.config.title)&&(r+=`, ${this.config.title}`),Array.from(this.elements.buttons.play||[]).forEach(e=>{e.setAttribute("aria-label",r)}),this.isEmbed){const e=xe.call(this,"iframe");if(!E.element(e))return;const t=E.empty(this.config.title)?"video":this.config.title,i=_e.get("frameTitle",this.config);e.setAttribute("title",i.replace("{title}",t))}},togglePoster(r){oe(this.elements.container,this.config.classNames.posterEnabled,r)},setPoster(r,e=!0){return e&&this.poster?Promise.reject(new Error("Poster already set")):(this.media.setAttribute("data-poster",r),this.elements.poster.removeAttribute("hidden"),zl.call(this).then(()=>Ai(r)).catch(t=>{throw r===this.poster&&fe.togglePoster.call(this,!1),t}).then(()=>{if(r!==this.poster)throw new Error("setPoster cancelled by later call to setPoster")}).then(()=>(Object.assign(this.elements.poster.style,{backgroundImage:`url('${r}')`,backgroundSize:""}),fe.togglePoster.call(this,!0),r)))},checkPlaying(r){oe(this.elements.container,this.config.classNames.playing,this.playing),oe(this.elements.container,this.config.classNames.paused,this.paused),oe(this.elements.container,this.config.classNames.stopped,this.stopped),Array.from(this.elements.buttons.play||[]).forEach(e=>{Object.assign(e,{pressed:this.playing}),e.setAttribute("aria-label",_e.get(this.playing?"pause":"play",this.config))}),E.event(r)&&r.type==="timeupdate"||fe.toggleControls.call(this)},checkLoading(r){this.loading=["stalled","waiting"].includes(r.type),clearTimeout(this.timers.loading),this.timers.loading=setTimeout(()=>{oe(this.elements.container,this.config.classNames.loading,this.loading),fe.toggleControls.call(this)},this.loading?250:0)},toggleControls(r){const{controls:e}=this.elements;if(e&&this.config.hideControls){const t=this.touch&&this.lastSeekTime+2e3>Date.now();this.toggleControls(!!(r||this.loading||this.paused||e.pressed||e.hover||t))}},migrateStyles(){Object.values(wt({},this.media.style)).filter(r=>!E.empty(r)&&E.string(r)&&r.startsWith("--plyr")).forEach(r=>{this.elements.container.style.setProperty(r,this.media.style.getPropertyValue(r)),this.media.style.removeProperty(r)}),E.empty(this.media.style)&&this.media.removeAttribute("style")}};class oc{constructor(e){F(this,"firstTouch",()=>{const{player:t}=this,{elements:i}=t;t.touch=!0,oe(i.container,t.config.classNames.isTouch,!0)}),F(this,"global",(t=!0)=>{const{player:i}=this;i.config.keyboard.global&&zt.call(i,window,"keydown keyup",this.handleKey,t,!1),zt.call(i,document.body,"click",this.toggleMenu,t),ms.call(i,document.body,"touchstart",this.firstTouch)}),F(this,"container",()=>{const{player:t}=this,{config:i,elements:s,timers:n}=t;!i.keyboard.global&&i.keyboard.focused&&se.call(t,s.container,"keydown keyup",this.handleKey,!1),se.call(t,s.container,"mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen",c=>{const{controls:l}=s;l&&c.type==="enterfullscreen"&&(l.pressed=!1,l.hover=!1);let d=0;["touchstart","touchmove","mousemove"].includes(c.type)&&(fe.toggleControls.call(t,!0),d=t.touch?3e3:2e3),clearTimeout(n.controls),n.controls=setTimeout(()=>fe.toggleControls.call(t,!1),d)});const a=()=>{if(!t.isVimeo||t.config.vimeo.premium)return;const c=s.wrapper,{active:l}=t.fullscreen,[d,u]=vs.call(t),h=on(`aspect-ratio: ${d} / ${u}`);if(!l)return void(h?(c.style.width=null,c.style.height=null):(c.style.maxWidth=null,c.style.margin=null));const[f,g]=Xl(),m=f/g>d/u;h?(c.style.width=m?"auto":"100%",c.style.height=m?"100%":"auto"):(c.style.maxWidth=m?g/u*d+"px":null,c.style.margin=m?"0 auto":null)},o=()=>{clearTimeout(n.resized),n.resized=setTimeout(a,50)};se.call(t,s.container,"enterfullscreen exitfullscreen",c=>{const{target:l}=t.fullscreen;l===s.container&&(!t.isEmbed&&E.empty(t.config.ratio)||(a(),(c.type==="enterfullscreen"?se:Ei).call(t,window,"resize",o)))})}),F(this,"media",()=>{const{player:t}=this,{elements:i}=t;if(se.call(t,t.media,"timeupdate seeking seeked",n=>N.timeUpdate.call(t,n)),se.call(t,t.media,"durationchange loadeddata loadedmetadata",n=>N.durationUpdate.call(t,n)),se.call(t,t.media,"ended",()=>{t.isHTML5&&t.isVideo&&t.config.resetOnEnd&&(t.restart(),t.pause())}),se.call(t,t.media,"progress playing seeking seeked",n=>N.updateProgress.call(t,n)),se.call(t,t.media,"volumechange",n=>N.updateVolume.call(t,n)),se.call(t,t.media,"playing play pause ended emptied timeupdate",n=>fe.checkPlaying.call(t,n)),se.call(t,t.media,"waiting canplay seeked playing",n=>fe.checkLoading.call(t,n)),t.supported.ui&&t.config.clickToPlay&&!t.isAudio){const n=xe.call(t,`.${t.config.classNames.video}`);if(!E.element(n))return;se.call(t,i.container,"click",a=>{([i.container,n].includes(a.target)||n.contains(a.target))&&(t.touch&&t.config.hideControls||(t.ended?(this.proxy(a,t.restart,"restart"),this.proxy(a,()=>{ze(t.play())},"play")):this.proxy(a,()=>{ze(t.togglePlay())},"play")))})}t.supported.ui&&t.config.disableContextMenu&&se.call(t,i.wrapper,"contextmenu",n=>{n.preventDefault()},!1),se.call(t,t.media,"volumechange",()=>{t.storage.set({volume:t.volume,muted:t.muted})}),se.call(t,t.media,"ratechange",()=>{N.updateSetting.call(t,"speed"),t.storage.set({speed:t.speed})}),se.call(t,t.media,"qualitychange",n=>{N.updateSetting.call(t,"quality",null,n.detail.quality)}),se.call(t,t.media,"ready qualitychange",()=>{N.setDownloadUrl.call(t)});const s=t.config.events.concat(["keyup","keydown"]).join(" ");se.call(t,t.media,s,n=>{let{detail:a={}}=n;n.type==="error"&&(a=t.media.error),z.call(t,i.container,n.type,!0,a)})}),F(this,"proxy",(t,i,s)=>{const{player:n}=this,a=n.config.listeners[s];let o=!0;E.function(a)&&(o=a.call(n,t)),o!==!1&&E.function(i)&&i.call(n,t)}),F(this,"bind",(t,i,s,n,a=!0)=>{const{player:o}=this,c=o.config.listeners[n],l=E.function(c);se.call(o,t,i,d=>this.proxy(d,s,n),a&&!l)}),F(this,"controls",()=>{const{player:t}=this,{elements:i}=t,s=Le.isIE?"change":"input";if(i.buttons.play&&Array.from(i.buttons.play).forEach(n=>{this.bind(n,"click",()=>{ze(t.togglePlay())},"play")}),this.bind(i.buttons.restart,"click",t.restart,"restart"),this.bind(i.buttons.rewind,"click",()=>{t.lastSeekTime=Date.now(),t.rewind()},"rewind"),this.bind(i.buttons.fastForward,"click",()=>{t.lastSeekTime=Date.now(),t.forward()},"fastForward"),this.bind(i.buttons.mute,"click",()=>{t.muted=!t.muted},"mute"),this.bind(i.buttons.captions,"click",()=>t.toggleCaptions()),this.bind(i.buttons.download,"click",()=>{z.call(t,t.media,"download")},"download"),this.bind(i.buttons.fullscreen,"click",()=>{t.fullscreen.toggle()},"fullscreen"),this.bind(i.buttons.pip,"click",()=>{t.pip="toggle"},"pip"),this.bind(i.buttons.airplay,"click",t.airplay,"airplay"),this.bind(i.buttons.settings,"click",n=>{n.stopPropagation(),n.preventDefault(),N.toggleMenu.call(t,n)},null,!1),this.bind(i.buttons.settings,"keyup",n=>{[" ","Enter"].includes(n.key)&&(n.key!=="Enter"?(n.preventDefault(),n.stopPropagation(),N.toggleMenu.call(t,n)):N.focusFirstMenuItem.call(t,null,!0))},null,!1),this.bind(i.settings.menu,"keydown",n=>{n.key==="Escape"&&N.toggleMenu.call(t,n)}),this.bind(i.inputs.seek,"mousedown mousemove",n=>{const a=i.progress.getBoundingClientRect(),o=100/a.width*(n.pageX-a.left);n.currentTarget.setAttribute("seek-value",o)}),this.bind(i.inputs.seek,"mousedown mouseup keydown keyup touchstart touchend",n=>{const a=n.currentTarget,o="play-on-seeked";if(E.keyboardEvent(n)&&!["ArrowLeft","ArrowRight"].includes(n.key))return;t.lastSeekTime=Date.now();const c=a.hasAttribute(o),l=["mouseup","touchend","keyup"].includes(n.type);c&&l?(a.removeAttribute(o),ze(t.play())):!l&&t.playing&&(a.setAttribute(o,""),t.pause())}),Le.isIos){const n=qt.call(t,'input[type="range"]');Array.from(n).forEach(a=>this.bind(a,s,o=>en(o.target)))}this.bind(i.inputs.seek,s,n=>{const a=n.currentTarget;let o=a.getAttribute("seek-value");E.empty(o)&&(o=a.value),a.removeAttribute("seek-value"),t.currentTime=o/a.max*t.duration},"seek"),this.bind(i.progress,"mouseenter mouseleave mousemove",n=>N.updateSeekTooltip.call(t,n)),this.bind(i.progress,"mousemove touchmove",n=>{const{previewThumbnails:a}=t;a&&a.loaded&&a.startMove(n)}),this.bind(i.progress,"mouseleave touchend click",()=>{const{previewThumbnails:n}=t;n&&n.loaded&&n.endMove(!1,!0)}),this.bind(i.progress,"mousedown touchstart",n=>{const{previewThumbnails:a}=t;a&&a.loaded&&a.startScrubbing(n)}),this.bind(i.progress,"mouseup touchend",n=>{const{previewThumbnails:a}=t;a&&a.loaded&&a.endScrubbing(n)}),Le.isWebKit&&Array.from(qt.call(t,'input[type="range"]')).forEach(n=>{this.bind(n,"input",a=>N.updateRangeFill.call(t,a.target))}),t.config.toggleInvert&&!E.element(i.display.duration)&&this.bind(i.display.currentTime,"click",()=>{t.currentTime!==0&&(t.config.invertTime=!t.config.invertTime,N.timeUpdate.call(t))}),this.bind(i.inputs.volume,s,n=>{t.volume=n.target.value},"volume"),this.bind(i.controls,"mouseenter mouseleave",n=>{i.controls.hover=!t.touch&&n.type==="mouseenter"}),i.fullscreen&&Array.from(i.fullscreen.children).filter(n=>!n.contains(i.container)).forEach(n=>{this.bind(n,"mouseenter mouseleave",a=>{i.controls&&(i.controls.hover=!t.touch&&a.type==="mouseenter")})}),this.bind(i.controls,"mousedown mouseup touchstart touchend touchcancel",n=>{i.controls.pressed=["mousedown","touchstart"].includes(n.type)}),this.bind(i.controls,"focusin",()=>{const{config:n,timers:a}=t;oe(i.controls,n.classNames.noTransition,!0),fe.toggleControls.call(t,!0),setTimeout(()=>{oe(i.controls,n.classNames.noTransition,!1)},0);const o=this.touch?3e3:4e3;clearTimeout(a.controls),a.controls=setTimeout(()=>fe.toggleControls.call(t,!1),o)}),this.bind(i.inputs.volume,"wheel",n=>{const a=n.webkitDirectionInvertedFromDevice,[o,c]=[n.deltaX,-n.deltaY].map(u=>a?-u:u),l=Math.sign(Math.abs(o)>Math.abs(c)?o:c);t.increaseVolume(l/50);const{volume:d}=t.media;(l===1&&d<1||l===-1&&d>0)&&n.preventDefault()},"volume",!1)}),this.player=e,this.lastKey=null,this.focusTimer=null,this.lastKeyDown=null,this.handleKey=this.handleKey.bind(this),this.toggleMenu=this.toggleMenu.bind(this),this.firstTouch=this.firstTouch.bind(this)}handleKey(e){const{player:t}=this,{elements:i}=t,{key:s,type:n,altKey:a,ctrlKey:o,metaKey:c,shiftKey:l}=e,d=n==="keydown",u=d&&s===this.lastKey;if(!(a||o||c||l)&&s){if(d){const f=document.activeElement;if(E.element(f)){const{editable:g}=t.config.selectors,{seek:m}=i.inputs;if(f!==m&&St(f,g)||e.key===" "&&St(f,'button, [role^="menuitem"]'))return}switch([" ","ArrowLeft","ArrowUp","ArrowRight","ArrowDown","0","1","2","3","4","5","6","7","8","9","c","f","k","l","m"].includes(s)&&(e.preventDefault(),e.stopPropagation()),s){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":u||(h=parseInt(s,10),t.currentTime=t.duration/10*h);break;case" ":case"k":u||ze(t.togglePlay());break;case"ArrowUp":t.increaseVolume(.1);break;case"ArrowDown":t.decreaseVolume(.1);break;case"m":u||(t.muted=!t.muted);break;case"ArrowRight":t.forward();break;case"ArrowLeft":t.rewind();break;case"f":t.fullscreen.toggle();break;case"c":u||t.toggleCaptions();break;case"l":t.loop=!t.loop}s==="Escape"&&!t.fullscreen.usingNative&&t.fullscreen.active&&t.fullscreen.toggle(),this.lastKey=s}else this.lastKey=null;var h}}toggleMenu(e){N.toggleMenu.call(this.player,e)}}function lc(r,e){return r(e={exports:{}},e.exports),e.exports}var cc=lc(function(r,e){r.exports=function(){var t=function(){},i={},s={},n={};function a(h,f){h=h.push?h:[h];var g,m,y,v=[],T=h.length,b=T;for(g=function(x,S){S.length&&v.push(x),--b||f(v)};T--;)m=h[T],(y=s[m])?g(m,y):(n[m]=n[m]||[]).push(g)}function o(h,f){if(h){var g=n[h];if(s[h]=f,g)for(;g.length;)g[0](h,f),g.splice(0,1)}}function c(h,f){h.call&&(h={success:h}),f.length?(h.error||t)(f):(h.success||t)(h)}function l(h,f,g,m){var y,v,T=document,b=g.async,x=(g.numRetries||0)+1,S=g.before||t,k=h.replace(/[\?|#].*$/,""),A=h.replace(/^(css|img)!/,"");m=m||0,/(^css!|\.css$)/.test(k)?((v=T.createElement("link")).rel="stylesheet",v.href=A,(y="hideFocus"in v)&&v.relList&&(y=0,v.rel="preload",v.as="style")):/(^img!|\.(png|gif|jpg|svg|webp)$)/.test(k)?(v=T.createElement("img")).src=A:((v=T.createElement("script")).src=h,v.async=b===void 0||b),v.onload=v.onerror=v.onbeforeload=function(I){var w=I.type[0];if(y)try{v.sheet.cssText.length||(w="e")}catch(L){L.code!=18&&(w="e")}if(w=="e"){if((m+=1){cc(r,{success:e,error:t})})}function dc(r){return E.empty(r)?null:E.number(Number(r))?r:r.match(/^.*(vimeo.com\/|video\/)(\d+).*/)?RegExp.$2:r}function uc(r){const e=r.match(/^.*(vimeo.com\/|video\/)(\d+)(\?.*&*h=|\/)+([\d,a-f]+)/);return e&&e.length===5?e[4]:null}function Zt(r){r&&!this.embed.hasPlayed&&(this.embed.hasPlayed=!0),this.media.paused===r&&(this.media.paused=!r,z.call(this,this.media,r?"play":"pause"))}const As={setup(){const r=this;oe(r.elements.wrapper,r.config.classNames.embed,!0),r.options.speed=r.config.speed.options,Ct.call(r),E.object(window.Vimeo)?As.ready.call(r):Ss(r.config.urls.vimeo.sdk).then(()=>{As.ready.call(r)}).catch(e=>{r.debug.warn("Vimeo SDK (player.js) failed to load",e)})},ready(){const r=this,e=r.config.vimeo,T=e,{premium:t,referrerPolicy:i}=T,s=pl(T,["premium","referrerPolicy"]);let n=r.media.getAttribute("src"),a="";E.empty(n)?(n=r.media.getAttribute(r.config.attributes.embed.id),a=r.media.getAttribute(r.config.attributes.embed.hash)):a=uc(n);const o=a?{h:a}:{};t&&Object.assign(s,{controls:!1,sidedock:!1});const c=mn(wt(wt({loop:r.config.loop.active,autoplay:r.autoplay,muted:r.muted,gesture:"media",playsinline:r.config.playsinline},o),s)),l=dc(n),d=j("iframe"),u=bs(r.config.urls.vimeo.iframe,l,c);if(d.setAttribute("src",u),d.setAttribute("allowfullscreen",""),d.setAttribute("allow",["autoplay","fullscreen","picture-in-picture","encrypted-media","accelerometer","gyroscope"].join("; ")),E.empty(i)||d.setAttribute("referrerPolicy",i),t||!e.customControls)d.setAttribute("data-poster",r.poster),r.media=bi(d,r.media);else{const b=j("div",{class:r.config.classNames.embedContainer,"data-poster":r.poster});b.appendChild(d),r.media=bi(b,r.media)}e.customControls||Jt(bs(r.config.urls.vimeo.api,u)).then(b=>{!E.empty(b)&&b.thumbnail_url&&fe.setPoster.call(r,b.thumbnail_url).catch(()=>{})}),r.embed=new window.Vimeo.Player(d,{autopause:r.config.autopause,muted:r.muted}),r.media.paused=!0,r.media.currentTime=0,r.supported.ui&&r.embed.disableTextTrack(),r.media.play=()=>(Zt.call(r,!0),r.embed.play()),r.media.pause=()=>(Zt.call(r,!1),r.embed.pause()),r.media.stop=()=>{r.pause(),r.currentTime=0};let{currentTime:h}=r.media;Object.defineProperty(r.media,"currentTime",{get:()=>h,set(b){const{embed:x,media:S,paused:k,volume:A}=r,I=k&&!x.hasPlayed;S.seeking=!0,z.call(r,S,"seeking"),Promise.resolve(I&&x.setVolume(0)).then(()=>x.setCurrentTime(b)).then(()=>I&&x.pause()).then(()=>I&&x.setVolume(A)).catch(()=>{})}});let f=r.config.speed.selected;Object.defineProperty(r.media,"playbackRate",{get:()=>f,set(b){r.embed.setPlaybackRate(b).then(()=>{f=b,z.call(r,r.media,"ratechange")}).catch(()=>{r.options.speed=[1]})}});let{volume:g}=r.config;Object.defineProperty(r.media,"volume",{get:()=>g,set(b){r.embed.setVolume(b).then(()=>{g=b,z.call(r,r.media,"volumechange")})}});let{muted:m}=r.config;Object.defineProperty(r.media,"muted",{get:()=>m,set(b){const x=!!E.boolean(b)&&b;r.embed.setMuted(!!x||r.config.muted).then(()=>{m=x,z.call(r,r.media,"volumechange")})}});let y,{loop:v}=r.config;Object.defineProperty(r.media,"loop",{get:()=>v,set(b){const x=E.boolean(b)?b:r.config.loop.active;r.embed.setLoop(x).then(()=>{v=x})}}),r.embed.getVideoUrl().then(b=>{y=b,N.setDownloadUrl.call(r)}).catch(b=>{this.debug.warn(b)}),Object.defineProperty(r.media,"currentSrc",{get:()=>y}),Object.defineProperty(r.media,"ended",{get:()=>r.currentTime===r.duration}),Promise.all([r.embed.getVideoWidth(),r.embed.getVideoHeight()]).then(b=>{const[x,S]=b;r.embed.ratio=dn(x,S),Ct.call(this)}),r.embed.setAutopause(r.config.autopause).then(b=>{r.config.autopause=b}),r.embed.getVideoTitle().then(b=>{r.config.title=b,fe.setTitle.call(this)}),r.embed.getCurrentTime().then(b=>{h=b,z.call(r,r.media,"timeupdate")}),r.embed.getDuration().then(b=>{r.media.duration=b,z.call(r,r.media,"durationchange")}),r.embed.getTextTracks().then(b=>{r.media.textTracks=b,ne.setup.call(r)}),r.embed.on("cuechange",({cues:b=[]})=>{const x=b.map(S=>tc(S.text));ne.updateCues.call(r,x)}),r.embed.on("loaded",()=>{r.embed.getPaused().then(b=>{Zt.call(r,!b),b||z.call(r,r.media,"playing")}),E.element(r.embed.element)&&r.supported.ui&&r.embed.element.setAttribute("tabindex",-1)}),r.embed.on("bufferstart",()=>{z.call(r,r.media,"waiting")}),r.embed.on("bufferend",()=>{z.call(r,r.media,"playing")}),r.embed.on("play",()=>{Zt.call(r,!0),z.call(r,r.media,"playing")}),r.embed.on("pause",()=>{Zt.call(r,!1)}),r.embed.on("timeupdate",b=>{r.media.seeking=!1,h=b.seconds,z.call(r,r.media,"timeupdate")}),r.embed.on("progress",b=>{r.media.buffered=b.percent,z.call(r,r.media,"progress"),parseInt(b.percent,10)===1&&z.call(r,r.media,"canplaythrough"),r.embed.getDuration().then(x=>{x!==r.media.duration&&(r.media.duration=x,z.call(r,r.media,"durationchange"))})}),r.embed.on("seeked",()=>{r.media.seeking=!1,z.call(r,r.media,"seeked")}),r.embed.on("ended",()=>{r.media.paused=!0,z.call(r,r.media,"ended")}),r.embed.on("error",b=>{r.media.error=b,z.call(r,r.media,"error")}),e.customControls&&setTimeout(()=>fe.build.call(r),0)}};function hc(r){return E.empty(r)?null:r.match(/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/)?RegExp.$2:r}function ei(r){r&&!this.embed.hasPlayed&&(this.embed.hasPlayed=!0),this.media.paused===r&&(this.media.paused=!r,z.call(this,this.media,r?"play":"pause"))}function fc(r){return r.noCookie?"https://www.youtube-nocookie.com":window.location.protocol==="http:"?"http://www.youtube.com":void 0}const Li={setup(){if(oe(this.elements.wrapper,this.config.classNames.embed,!0),E.object(window.YT)&&E.function(window.YT.Player))Li.ready.call(this);else{const r=window.onYouTubeIframeAPIReady;window.onYouTubeIframeAPIReady=()=>{E.function(r)&&r(),Li.ready.call(this)},Ss(this.config.urls.youtube.sdk).catch(e=>{this.debug.warn("YouTube API failed to load",e)})}},getTitle(r){Jt(bs(this.config.urls.youtube.api,r)).then(e=>{if(E.object(e)){const{title:t,height:i,width:s}=e;this.config.title=t,fe.setTitle.call(this),this.embed.ratio=dn(s,i)}Ct.call(this)}).catch(()=>{Ct.call(this)})},ready(){const r=this,e=r.config.youtube,t=r.media&&r.media.getAttribute("id");if(!E.empty(t)&&t.startsWith("youtube-"))return;let i=r.media.getAttribute("src");E.empty(i)&&(i=r.media.getAttribute(this.config.attributes.embed.id));const s=hc(i),n=j("div",{id:Ql(r.provider),"data-poster":e.customControls?r.poster:void 0});if(r.media=bi(n,r.media),e.customControls){const a=o=>`https://i.ytimg.com/vi/${s}/${o}default.jpg`;Ai(a("maxres"),121).catch(()=>Ai(a("sd"),121)).catch(()=>Ai(a("hq"))).then(o=>fe.setPoster.call(r,o.src)).then(o=>{o.includes("maxres")||(r.elements.poster.style.backgroundSize="cover")}).catch(()=>{})}r.embed=new window.YT.Player(r.media,{videoId:s,host:fc(e),playerVars:Te({},{autoplay:r.config.autoplay?1:0,hl:r.config.hl,controls:r.supported.ui&&e.customControls?0:1,disablekb:1,playsinline:r.config.playsinline&&!r.config.fullscreen.iosNative?1:0,cc_load_policy:r.captions.active?1:0,cc_lang_pref:r.config.captions.language,widget_referrer:window?window.location.href:null},e),events:{onError(a){if(!r.media.error){const o=a.data,c={2:"The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.",5:"The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.",100:"The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.",101:"The owner of the requested video does not allow it to be played in embedded players.",150:"The owner of the requested video does not allow it to be played in embedded players."}[o]||"An unknown error occurred";r.media.error={code:o,message:c},z.call(r,r.media,"error")}},onPlaybackRateChange(a){const o=a.target;r.media.playbackRate=o.getPlaybackRate(),z.call(r,r.media,"ratechange")},onReady(a){if(E.function(r.media.play))return;const o=a.target;Li.getTitle.call(r,s),r.media.play=()=>{ei.call(r,!0),o.playVideo()},r.media.pause=()=>{ei.call(r,!1),o.pauseVideo()},r.media.stop=()=>{o.stopVideo()},r.media.duration=o.getDuration(),r.media.paused=!0,r.media.currentTime=0,Object.defineProperty(r.media,"currentTime",{get:()=>Number(o.getCurrentTime()),set(u){r.paused&&!r.embed.hasPlayed&&r.embed.mute(),r.media.seeking=!0,z.call(r,r.media,"seeking"),o.seekTo(u)}}),Object.defineProperty(r.media,"playbackRate",{get:()=>o.getPlaybackRate(),set(u){o.setPlaybackRate(u)}});let{volume:c}=r.config;Object.defineProperty(r.media,"volume",{get:()=>c,set(u){c=u,o.setVolume(100*c),z.call(r,r.media,"volumechange")}});let{muted:l}=r.config;Object.defineProperty(r.media,"muted",{get:()=>l,set(u){const h=E.boolean(u)?u:l;l=h,o[h?"mute":"unMute"](),o.setVolume(100*c),z.call(r,r.media,"volumechange")}}),Object.defineProperty(r.media,"currentSrc",{get:()=>o.getVideoUrl()}),Object.defineProperty(r.media,"ended",{get:()=>r.currentTime===r.duration});const d=o.getAvailablePlaybackRates();r.options.speed=d.filter(u=>r.config.speed.options.includes(u)),r.supported.ui&&e.customControls&&r.media.setAttribute("tabindex",-1),z.call(r,r.media,"timeupdate"),z.call(r,r.media,"durationchange"),clearInterval(r.timers.buffering),r.timers.buffering=setInterval(()=>{r.media.buffered=o.getVideoLoadedFraction(),(r.media.lastBuffered===null||r.media.lastBufferedfe.build.call(r),50)},onStateChange(a){const o=a.target;switch(clearInterval(r.timers.playing),r.media.seeking&&[1,2].includes(a.data)&&(r.media.seeking=!1,z.call(r,r.media,"seeked")),a.data){case-1:z.call(r,r.media,"timeupdate"),r.media.buffered=o.getVideoLoadedFraction(),z.call(r,r.media,"progress");break;case 0:ei.call(r,!1),r.media.loop?(o.stopVideo(),o.playVideo()):z.call(r,r.media,"ended");break;case 1:e.customControls&&!r.config.autoplay&&r.media.paused&&!r.embed.hasPlayed?r.media.pause():(ei.call(r,!0),z.call(r,r.media,"playing"),r.timers.playing=setInterval(()=>{z.call(r,r.media,"timeupdate")},50),r.media.duration!==o.getDuration()&&(r.media.duration=o.getDuration(),z.call(r,r.media,"durationchange")));break;case 2:r.muted||r.embed.unMute(),ei.call(r,!1);break;case 3:z.call(r,r.media,"waiting")}z.call(r,r.elements.container,"statechange",!1,{code:a.data})}}})}},vn={setup(){this.media?(oe(this.elements.container,this.config.classNames.type.replace("{0}",this.type),!0),oe(this.elements.container,this.config.classNames.provider.replace("{0}",this.provider),!0),this.isEmbed&&oe(this.elements.container,this.config.classNames.type.replace("{0}","video"),!0),this.isVideo&&(this.elements.wrapper=j("div",{class:this.config.classNames.video}),sn(this.media,this.elements.wrapper),this.elements.poster=j("div",{class:this.config.classNames.poster}),this.elements.wrapper.appendChild(this.elements.poster)),this.isHTML5?ht.setup.call(this):this.isYouTube?Li.setup.call(this):this.isVimeo&&As.setup.call(this)):this.debug.warn("No media element found!")}};class gc{constructor(e){F(this,"load",()=>{this.enabled&&(E.object(window.google)&&E.object(window.google.ima)?this.ready():Ss(this.player.config.urls.googleIMA.sdk).then(()=>{this.ready()}).catch(()=>{this.trigger("error",new Error("Google IMA SDK failed to load"))}))}),F(this,"ready",()=>{var t;this.enabled||((t=this).manager&&t.manager.destroy(),t.elements.displayContainer&&t.elements.displayContainer.destroy(),t.elements.container.remove()),this.startSafetyTimer(12e3,"ready()"),this.managerPromise.then(()=>{this.clearSafetyTimer("onAdsManagerLoaded()")}),this.listeners(),this.setupIMA()}),F(this,"setupIMA",()=>{this.elements.container=j("div",{class:this.player.config.classNames.ads}),this.player.elements.container.appendChild(this.elements.container),google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED),google.ima.settings.setLocale(this.player.config.ads.language),google.ima.settings.setDisableCustomPlaybackForIOS10Plus(this.player.config.playsinline),this.elements.displayContainer=new google.ima.AdDisplayContainer(this.elements.container,this.player.media),this.loader=new google.ima.AdsLoader(this.elements.displayContainer),this.loader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,t=>this.onAdsManagerLoaded(t),!1),this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR,t=>this.onAdError(t),!1),this.requestAds()}),F(this,"requestAds",()=>{const{container:t}=this.player.elements;try{const i=new google.ima.AdsRequest;i.adTagUrl=this.tagUrl,i.linearAdSlotWidth=t.offsetWidth,i.linearAdSlotHeight=t.offsetHeight,i.nonLinearAdSlotWidth=t.offsetWidth,i.nonLinearAdSlotHeight=t.offsetHeight,i.forceNonLinearFullSlot=!1,i.setAdWillPlayMuted(!this.player.muted),this.loader.requestAds(i)}catch(i){this.onAdError(i)}}),F(this,"pollCountdown",(t=!1)=>{if(!t)return clearInterval(this.countdownTimer),void this.elements.container.removeAttribute("data-badge-text");this.countdownTimer=setInterval(()=>{const i=Si(Math.max(this.manager.getRemainingTime(),0)),s=`${_e.get("advertisement",this.player.config)} - ${i}`;this.elements.container.setAttribute("data-badge-text",s)},100)}),F(this,"onAdsManagerLoaded",t=>{if(!this.enabled)return;const i=new google.ima.AdsRenderingSettings;i.restoreCustomPlaybackStateOnAdBreakComplete=!0,i.enablePreloading=!0,this.manager=t.getAdsManager(this.player,i),this.cuePoints=this.manager.getCuePoints(),this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR,s=>this.onAdError(s)),Object.keys(google.ima.AdEvent.Type).forEach(s=>{this.manager.addEventListener(google.ima.AdEvent.Type[s],n=>this.onAdEvent(n))}),this.trigger("loaded")}),F(this,"addCuePoints",()=>{E.empty(this.cuePoints)||this.cuePoints.forEach(t=>{if(t!==0&&t!==-1&&t{const{container:i}=this.player.elements,s=t.getAd(),n=t.getAdData();switch((a=>{z.call(this.player,this.player.media,`ads${a.replace(/_/g,"").toLowerCase()}`)})(t.type),t.type){case google.ima.AdEvent.Type.LOADED:this.trigger("loaded"),this.pollCountdown(!0),s.isLinear()||(s.width=i.offsetWidth,s.height=i.offsetHeight);break;case google.ima.AdEvent.Type.STARTED:this.manager.setVolume(this.player.volume);break;case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:this.player.ended?this.loadAds():this.loader.contentComplete();break;case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:this.pauseContent();break;case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:this.pollCountdown(),this.resumeContent();break;case google.ima.AdEvent.Type.LOG:n.adError&&this.player.debug.warn(`Non-fatal ad error: ${n.adError.getMessage()}`)}}),F(this,"onAdError",t=>{this.cancel(),this.player.debug.warn("Ads error",t)}),F(this,"listeners",()=>{const{container:t}=this.player.elements;let i;this.player.on("canplay",()=>{this.addCuePoints()}),this.player.on("ended",()=>{this.loader.contentComplete()}),this.player.on("timeupdate",()=>{i=this.player.currentTime}),this.player.on("seeked",()=>{const s=this.player.currentTime;E.empty(this.cuePoints)||this.cuePoints.forEach((n,a)=>{i{this.manager&&this.manager.resize(t.offsetWidth,t.offsetHeight,google.ima.ViewMode.NORMAL)})}),F(this,"play",()=>{const{container:t}=this.player.elements;this.managerPromise||this.resumeContent(),this.managerPromise.then(()=>{this.manager.setVolume(this.player.volume),this.elements.displayContainer.initialize();try{this.initialized||(this.manager.init(t.offsetWidth,t.offsetHeight,google.ima.ViewMode.NORMAL),this.manager.start()),this.initialized=!0}catch(i){this.onAdError(i)}}).catch(()=>{})}),F(this,"resumeContent",()=>{this.elements.container.style.zIndex="",this.playing=!1,ze(this.player.media.play())}),F(this,"pauseContent",()=>{this.elements.container.style.zIndex=3,this.playing=!0,this.player.media.pause()}),F(this,"cancel",()=>{this.initialized&&this.resumeContent(),this.trigger("error"),this.loadAds()}),F(this,"loadAds",()=>{this.managerPromise.then(()=>{this.manager&&this.manager.destroy(),this.managerPromise=new Promise(t=>{this.on("loaded",t),this.player.debug.log(this.manager)}),this.initialized=!1,this.requestAds()}).catch(()=>{})}),F(this,"trigger",(t,...i)=>{const s=this.events[t];E.array(s)&&s.forEach(n=>{E.function(n)&&n.apply(this,i)})}),F(this,"on",(t,i)=>(E.array(this.events[t])||(this.events[t]=[]),this.events[t].push(i),this)),F(this,"startSafetyTimer",(t,i)=>{this.player.debug.log(`Safety timer invoked from: ${i}`),this.safetyTimer=setTimeout(()=>{this.cancel(),this.clearSafetyTimer("startSafetyTimer()")},t)}),F(this,"clearSafetyTimer",t=>{E.nullOrUndefined(this.safetyTimer)||(this.player.debug.log(`Safety timer cleared from: ${t}`),clearTimeout(this.safetyTimer),this.safetyTimer=null)}),this.player=e,this.config=e.config.ads,this.playing=!1,this.initialized=!1,this.elements={container:null,displayContainer:null},this.manager=null,this.loader=null,this.cuePoints=null,this.events={},this.safetyTimer=null,this.countdownTimer=null,this.managerPromise=new Promise((t,i)=>{this.on("loaded",t),this.on("error",i)}),this.load()}get enabled(){const{config:e}=this;return this.player.isHTML5&&this.player.isVideo&&e.enabled&&(!E.empty(e.publisherId)||E.url(e.tagUrl))}get tagUrl(){const{config:e}=this;return E.url(e.tagUrl)?e.tagUrl:`https://go.aniview.com/api/adserver6/vast/?${mn({AV_PUBLISHERID:"58c25bb0073ef448b1087ad6",AV_CHANNELID:"5a0458dc28a06145e4519d21",AV_URL:window.location.hostname,cb:Date.now(),AV_WIDTH:640,AV_HEIGHT:480,AV_CDIM2:e.publisherId})}`}}function bn(r=0,e=0,t=255){return Math.min(Math.max(r,e),t)}const pc=r=>{const e=[];return r.split(/\r\n\r\n|\n\n|\r\r/).forEach(t=>{const i={};t.split(/\r\n|\n|\r/).forEach(s=>{if(E.number(i.startTime)){if(!E.empty(s.trim())&&E.empty(i.text)){const n=s.trim().split("#xywh=");[i.text]=n,n[1]&&([i.x,i.y,i.w,i.h]=n[1].split(","))}}else{const n=s.match(/([0-9]{2})?:?([0-9]{2}):([0-9]{2}).([0-9]{2,3})( ?--> ?)([0-9]{2})?:?([0-9]{2}):([0-9]{2}).([0-9]{2,3})/);n&&(i.startTime=60*Number(n[1]||0)*60+60*Number(n[2])+Number(n[3])+ +`0.${n[4]}`,i.endTime=60*Number(n[6]||0)*60+60*Number(n[7])+Number(n[8])+ +`0.${n[9]}`)}}),i.text&&e.push(i)}),e},Tn=(r,e)=>{const t={};return r>e.width/e.height?(t.width=e.width,t.height=1/r*e.width):(t.height=e.height,t.width=r*e.height),t};class Ls{constructor(e){F(this,"load",()=>{this.player.elements.display.seekTooltip&&(this.player.elements.display.seekTooltip.hidden=this.enabled),this.enabled&&this.getThumbnails().then(()=>{this.enabled&&(this.render(),this.determineContainerAutoSizing(),this.listeners(),this.loaded=!0)})}),F(this,"getThumbnails",()=>new Promise(t=>{const{src:i}=this.player.config.previewThumbnails;if(E.empty(i))throw new Error("Missing previewThumbnails.src config attribute");const s=()=>{this.thumbnails.sort((n,a)=>n.height-a.height),this.player.debug.log("Preview thumbnails",this.thumbnails),t()};if(E.function(i))i(n=>{this.thumbnails=n,s()});else{const n=(E.string(i)?[i]:i).map(a=>this.getThumbnail(a));Promise.all(n).then(s)}})),F(this,"getThumbnail",t=>new Promise(i=>{Jt(t).then(s=>{const n={frames:pc(s),height:null,urlPrefix:""};n.frames[0].text.startsWith("/")||n.frames[0].text.startsWith("http://")||n.frames[0].text.startsWith("https://")||(n.urlPrefix=t.substring(0,t.lastIndexOf("/")+1));const a=new Image;a.onload=()=>{n.height=a.naturalHeight,n.width=a.naturalWidth,this.thumbnails.push(n),i()},a.src=n.urlPrefix+n.frames[0].text})})),F(this,"startMove",t=>{if(this.loaded&&E.event(t)&&["touchmove","mousemove"].includes(t.type)&&this.player.media.duration){if(t.type==="touchmove")this.seekTime=this.player.media.duration*(this.player.elements.inputs.seek.value/100);else{var i,s;const n=this.player.elements.progress.getBoundingClientRect(),a=100/n.width*(t.pageX-n.left);this.seekTime=this.player.media.duration*(a/100),this.seekTime<0&&(this.seekTime=0),this.seekTime>this.player.media.duration-1&&(this.seekTime=this.player.media.duration-1),this.mousePosX=t.pageX,this.elements.thumb.time.innerText=Si(this.seekTime);const o=(i=this.player.config.markers)===null||i===void 0||(s=i.points)===null||s===void 0?void 0:s.find(({time:c})=>c===Math.round(this.seekTime));o&&this.elements.thumb.time.insertAdjacentHTML("afterbegin",`${o.label}
`)}this.showImageAtCurrentTime()}}),F(this,"endMove",()=>{this.toggleThumbContainer(!1,!0)}),F(this,"startScrubbing",t=>{(E.nullOrUndefined(t.button)||t.button===!1||t.button===0)&&(this.mouseDown=!0,this.player.media.duration&&(this.toggleScrubbingContainer(!0),this.toggleThumbContainer(!1,!0),this.showImageAtCurrentTime()))}),F(this,"endScrubbing",()=>{this.mouseDown=!1,Math.ceil(this.lastTime)===Math.ceil(this.player.media.currentTime)?this.toggleScrubbingContainer(!1):ms.call(this.player,this.player.media,"timeupdate",()=>{this.mouseDown||this.toggleScrubbingContainer(!1)})}),F(this,"listeners",()=>{this.player.on("play",()=>{this.toggleThumbContainer(!1,!0)}),this.player.on("seeked",()=>{this.toggleThumbContainer(!1)}),this.player.on("timeupdate",()=>{this.lastTime=this.player.media.currentTime})}),F(this,"render",()=>{this.elements.thumb.container=j("div",{class:this.player.config.classNames.previewThumbnails.thumbContainer}),this.elements.thumb.imageContainer=j("div",{class:this.player.config.classNames.previewThumbnails.imageContainer}),this.elements.thumb.container.appendChild(this.elements.thumb.imageContainer);const t=j("div",{class:this.player.config.classNames.previewThumbnails.timeContainer});this.elements.thumb.time=j("span",{},"00:00"),t.appendChild(this.elements.thumb.time),this.elements.thumb.imageContainer.appendChild(t),E.element(this.player.elements.progress)&&this.player.elements.progress.appendChild(this.elements.thumb.container),this.elements.scrubbing.container=j("div",{class:this.player.config.classNames.previewThumbnails.scrubbingContainer}),this.player.elements.wrapper.appendChild(this.elements.scrubbing.container)}),F(this,"destroy",()=>{this.elements.thumb.container&&this.elements.thumb.container.remove(),this.elements.scrubbing.container&&this.elements.scrubbing.container.remove()}),F(this,"showImageAtCurrentTime",()=>{this.mouseDown?this.setScrubbingContainerSize():this.setThumbContainerSizeAndPos();const t=this.thumbnails[0].frames.findIndex(n=>this.seekTime>=n.startTime&&this.seekTime<=n.endTime),i=t>=0;let s=0;this.mouseDown||this.toggleThumbContainer(i),i&&(this.thumbnails.forEach((n,a)=>{this.loadedImages.includes(n.frames[t].text)&&(s=a)}),t!==this.showingThumb&&(this.showingThumb=t,this.loadImage(s)))}),F(this,"loadImage",(t=0)=>{const i=this.showingThumb,s=this.thumbnails[t],{urlPrefix:n}=s,a=s.frames[i],o=s.frames[i].text,c=n+o;if(this.currentImageElement&&this.currentImageElement.dataset.filename===o)this.showImage(this.currentImageElement,a,t,i,o,!1),this.currentImageElement.dataset.index=i,this.removeOldImages(this.currentImageElement);else{this.loadingImage&&this.usingSprites&&(this.loadingImage.onload=null);const l=new Image;l.src=c,l.dataset.index=i,l.dataset.filename=o,this.showingThumbFilename=o,this.player.debug.log(`Loading image: ${c}`),l.onload=()=>this.showImage(l,a,t,i,o,!0),this.loadingImage=l,this.removeOldImages(l)}}),F(this,"showImage",(t,i,s,n,a,o=!0)=>{this.player.debug.log(`Showing thumb: ${a}. num: ${n}. qual: ${s}. newimg: ${o}`),this.setImageSizeAndOffset(t,i),o&&(this.currentImageContainer.appendChild(t),this.currentImageElement=t,this.loadedImages.includes(a)||this.loadedImages.push(a)),this.preloadNearby(n,!0).then(this.preloadNearby(n,!1)).then(this.getHigherQuality(s,t,i,a))}),F(this,"removeOldImages",t=>{Array.from(this.currentImageContainer.children).forEach(i=>{if(i.tagName.toLowerCase()!=="img")return;const s=this.usingSprites?500:1e3;if(i.dataset.index!==t.dataset.index&&!i.dataset.deleting){i.dataset.deleting=!0;const{currentImageContainer:n}=this;setTimeout(()=>{n.removeChild(i),this.player.debug.log(`Removing thumb: ${i.dataset.filename}`)},s)}})}),F(this,"preloadNearby",(t,i=!0)=>new Promise(s=>{setTimeout(()=>{const n=this.thumbnails[0].frames[t].text;if(this.showingThumbFilename===n){let a;a=i?this.thumbnails[0].frames.slice(t):this.thumbnails[0].frames.slice(0,t).reverse();let o=!1;a.forEach(c=>{const l=c.text;if(l!==n&&!this.loadedImages.includes(l)){o=!0,this.player.debug.log(`Preloading thumb filename: ${l}`);const{urlPrefix:d}=this.thumbnails[0],u=d+l,h=new Image;h.src=u,h.onload=()=>{this.player.debug.log(`Preloaded thumb filename: ${l}`),this.loadedImages.includes(l)||this.loadedImages.push(l),s()}}}),o||s()}},300)})),F(this,"getHigherQuality",(t,i,s,n)=>{if(t{this.showingThumbFilename===n&&(this.player.debug.log(`Showing higher quality thumb for: ${n}`),this.loadImage(t+1))},300)}}),F(this,"toggleThumbContainer",(t=!1,i=!1)=>{const s=this.player.config.classNames.previewThumbnails.thumbContainerShown;this.elements.thumb.container.classList.toggle(s,t),!t&&i&&(this.showingThumb=null,this.showingThumbFilename=null)}),F(this,"toggleScrubbingContainer",(t=!1)=>{const i=this.player.config.classNames.previewThumbnails.scrubbingContainerShown;this.elements.scrubbing.container.classList.toggle(i,t),t||(this.showingThumb=null,this.showingThumbFilename=null)}),F(this,"determineContainerAutoSizing",()=>{(this.elements.thumb.imageContainer.clientHeight>20||this.elements.thumb.imageContainer.clientWidth>20)&&(this.sizeSpecifiedInCSS=!0)}),F(this,"setThumbContainerSizeAndPos",()=>{const{imageContainer:t}=this.elements.thumb;if(this.sizeSpecifiedInCSS){if(t.clientHeight>20&&t.clientWidth<20){const i=Math.floor(t.clientHeight*this.thumbAspectRatio);t.style.width=`${i}px`}else if(t.clientHeight<20&&t.clientWidth>20){const i=Math.floor(t.clientWidth/this.thumbAspectRatio);t.style.height=`${i}px`}}else{const i=Math.floor(this.thumbContainerHeight*this.thumbAspectRatio);t.style.height=`${this.thumbContainerHeight}px`,t.style.width=`${i}px`}this.setThumbContainerPos()}),F(this,"setThumbContainerPos",()=>{const t=this.player.elements.progress.getBoundingClientRect(),i=this.player.elements.container.getBoundingClientRect(),{container:s}=this.elements.thumb,n=i.left-t.left+10,a=i.right-t.left-s.clientWidth-10,o=this.mousePosX-t.left-s.clientWidth/2,c=bn(o,n,a);s.style.left=`${c}px`,s.style.setProperty("--preview-arrow-offset",o-c+"px")}),F(this,"setScrubbingContainerSize",()=>{const{width:t,height:i}=Tn(this.thumbAspectRatio,{width:this.player.media.clientWidth,height:this.player.media.clientHeight});this.elements.scrubbing.container.style.width=`${t}px`,this.elements.scrubbing.container.style.height=`${i}px`}),F(this,"setImageSizeAndOffset",(t,i)=>{if(!this.usingSprites)return;const s=this.thumbContainerHeight/i.h;t.style.height=t.naturalHeight*s+"px",t.style.width=t.naturalWidth*s+"px",t.style.left=`-${i.x*s}px`,t.style.top=`-${i.y*s}px`}),this.player=e,this.thumbnails=[],this.loaded=!1,this.lastMouseMoveTime=Date.now(),this.mouseDown=!1,this.loadedImages=[],this.elements={thumb:{},scrubbing:{}},this.load()}get enabled(){return this.player.isHTML5&&this.player.isVideo&&this.player.config.previewThumbnails.enabled}get currentImageContainer(){return this.mouseDown?this.elements.scrubbing.container:this.elements.thumb.imageContainer}get usingSprites(){return Object.keys(this.thumbnails[0].frames[0]).includes("w")}get thumbAspectRatio(){return this.usingSprites?this.thumbnails[0].frames[0].w/this.thumbnails[0].frames[0].h:this.thumbnails[0].width/this.thumbnails[0].height}get thumbContainerHeight(){if(this.mouseDown){const{height:e}=Tn(this.thumbAspectRatio,{width:this.player.media.clientWidth,height:this.player.media.clientHeight});return e}return this.sizeSpecifiedInCSS?this.elements.thumb.imageContainer.clientHeight:Math.floor(this.player.media.clientWidth/this.thumbAspectRatio/4)}get currentImageElement(){return this.mouseDown?this.currentScrubbingImageElement:this.currentThumbnailImageElement}set currentImageElement(e){this.mouseDown?this.currentScrubbingImageElement=e:this.currentThumbnailImageElement=e}}const _s={insertElements(r,e){E.string(e)?rn(r,this.media,{src:e}):E.array(e)&&e.forEach(t=>{rn(r,this.media,t)})},change(r){tn(r,"sources.length")?(ht.cancelRequests.call(this),this.destroy.call(this,()=>{this.options.quality=[],nt(this.media),this.media=null,E.element(this.elements.container)&&this.elements.container.removeAttribute("class");const{sources:e,type:t}=r,[{provider:i=ft.html5,src:s}]=e,n=i==="html5"?t:"div",a=i==="html5"?{}:{src:s};Object.assign(this,{provider:i,type:t,supported:Ee.check(t,i,this.config.playsinline),media:j(n,a)}),this.elements.container.appendChild(this.media),E.boolean(r.autoplay)&&(this.config.autoplay=r.autoplay),this.isHTML5&&(this.config.crossorigin&&this.media.setAttribute("crossorigin",""),this.config.autoplay&&this.media.setAttribute("autoplay",""),E.empty(r.poster)||(this.poster=r.poster),this.config.loop.active&&this.media.setAttribute("loop",""),this.config.muted&&this.media.setAttribute("muted",""),this.config.playsinline&&this.media.setAttribute("playsinline","")),fe.addStyleHook.call(this),this.isHTML5&&_s.insertElements.call(this,"source",e),this.config.title=r.title,vn.setup.call(this),this.isHTML5&&Object.keys(r).includes("tracks")&&_s.insertElements.call(this,"track",r.tracks),(this.isHTML5||this.isEmbed&&!this.supported.ui)&&fe.build.call(this),this.isHTML5&&this.media.load(),E.empty(r.previewThumbnails)||(Object.assign(this.config.previewThumbnails,r.previewThumbnails),this.previewThumbnails&&this.previewThumbnails.loaded&&(this.previewThumbnails.destroy(),this.previewThumbnails=null),this.config.previewThumbnails.enabled&&(this.previewThumbnails=new Ls(this))),this.fullscreen.update()},!0)):this.debug.warn("Invalid source format")}};class ti{constructor(e,t){if(F(this,"play",()=>E.function(this.media.play)?(this.ads&&this.ads.enabled&&this.ads.managerPromise.then(()=>this.ads.play()).catch(()=>ze(this.media.play())),this.media.play()):null),F(this,"pause",()=>this.playing&&E.function(this.media.pause)?this.media.pause():null),F(this,"togglePlay",o=>(E.boolean(o)?o:!this.playing)?this.play():this.pause()),F(this,"stop",()=>{this.isHTML5?(this.pause(),this.restart()):E.function(this.media.stop)&&this.media.stop()}),F(this,"restart",()=>{this.currentTime=0}),F(this,"rewind",o=>{this.currentTime-=E.number(o)?o:this.config.seekTime}),F(this,"forward",o=>{this.currentTime+=E.number(o)?o:this.config.seekTime}),F(this,"increaseVolume",o=>{const c=this.media.muted?0:this.volume;this.volume=c+(E.number(o)?o:0)}),F(this,"decreaseVolume",o=>{this.increaseVolume(-o)}),F(this,"airplay",()=>{Ee.airplay&&this.media.webkitShowPlaybackTargetPicker()}),F(this,"toggleControls",o=>{if(this.supported.ui&&!this.isAudio){const c=Ti(this.elements.container,this.config.classNames.hideControls),l=o===void 0?void 0:!o,d=oe(this.elements.container,this.config.classNames.hideControls,l);if(d&&E.array(this.config.controls)&&this.config.controls.includes("settings")&&!E.empty(this.config.settings)&&N.toggleMenu.call(this,!1),d!==c){const u=d?"controlshidden":"controlsshown";z.call(this,this.media,u)}return!d}return!1}),F(this,"on",(o,c)=>{se.call(this,this.elements.container,o,c)}),F(this,"once",(o,c)=>{ms.call(this,this.elements.container,o,c)}),F(this,"off",(o,c)=>{Ei(this.elements.container,o,c)}),F(this,"destroy",(o,c=!1)=>{if(!this.ready)return;const l=()=>{document.body.style.overflow="",this.embed=null,c?(Object.keys(this.elements).length&&(nt(this.elements.buttons.play),nt(this.elements.captions),nt(this.elements.controls),nt(this.elements.wrapper),this.elements.buttons.play=null,this.elements.captions=null,this.elements.controls=null,this.elements.wrapper=null),E.function(o)&&o()):(ql.call(this),ht.cancelRequests.call(this),bi(this.elements.original,this.elements.container),z.call(this,this.elements.original,"destroyed",!0),E.function(o)&&o.call(this.elements.original),this.ready=!1,setTimeout(()=>{this.elements=null,this.media=null},200))};this.stop(),clearTimeout(this.timers.loading),clearTimeout(this.timers.controls),clearTimeout(this.timers.resized),this.isHTML5?(fe.toggleNativeControls.call(this,!0),l()):this.isYouTube?(clearInterval(this.timers.buffering),clearInterval(this.timers.playing),this.embed!==null&&E.function(this.embed.destroy)&&this.embed.destroy(),l()):this.isVimeo&&(this.embed!==null&&this.embed.unload().then(l),setTimeout(l,200))}),F(this,"supports",o=>Ee.mime.call(this,o)),this.timers={},this.ready=!1,this.loading=!1,this.failed=!1,this.touch=Ee.touch,this.media=e,E.string(this.media)&&(this.media=document.querySelectorAll(this.media)),(window.jQuery&&this.media instanceof jQuery||E.nodeList(this.media)||E.array(this.media))&&(this.media=this.media[0]),this.config=Te({},yn,ti.defaults,t||{},(()=>{try{return JSON.parse(this.media.getAttribute("data-plyr-config"))}catch(o){return{}}})()),this.elements={container:null,fullscreen:null,captions:null,buttons:{},display:{},progress:{},inputs:{},settings:{popup:null,menu:null,panels:{},buttons:{}}},this.captions={active:null,currentTrack:-1,meta:new WeakMap},this.fullscreen={active:!1},this.options={speed:[],quality:[]},this.debug=new ac(this.config.debug),this.debug.log("Config",this.config),this.debug.log("Support",Ee),E.nullOrUndefined(this.media)||!E.element(this.media))return void this.debug.error("Setup failed: no suitable element passed");if(this.media.plyr)return void this.debug.warn("Target already setup");if(!this.config.enabled)return void this.debug.error("Setup failed: disabled by config");if(!Ee.check().api)return void this.debug.error("Setup failed: no support");const i=this.media.cloneNode(!0);i.autoplay=!1,this.elements.original=i;const s=this.media.tagName.toLowerCase();let n=null,a=null;switch(s){case"div":if(n=this.media.querySelector("iframe"),E.element(n)){if(a=pn(n.getAttribute("src")),this.provider=nc(a.toString()),this.elements.container=this.media,this.media=n,this.elements.container.className="",a.search.length){const o=["1","true"];o.includes(a.searchParams.get("autoplay"))&&(this.config.autoplay=!0),o.includes(a.searchParams.get("loop"))&&(this.config.loop.active=!0),this.isYouTube?(this.config.playsinline=o.includes(a.searchParams.get("playsinline")),this.config.youtube.hl=a.searchParams.get("hl")):this.config.playsinline=!0}}else this.provider=this.media.getAttribute(this.config.attributes.embed.provider),this.media.removeAttribute(this.config.attributes.embed.provider);if(E.empty(this.provider)||!Object.values(ft).includes(this.provider))return void this.debug.error("Setup failed: Invalid provider");this.type=Es.video;break;case"video":case"audio":this.type=s,this.provider=ft.html5,this.media.hasAttribute("crossorigin")&&(this.config.crossorigin=!0),this.media.hasAttribute("autoplay")&&(this.config.autoplay=!0),(this.media.hasAttribute("playsinline")||this.media.hasAttribute("webkit-playsinline"))&&(this.config.playsinline=!0),this.media.hasAttribute("muted")&&(this.config.muted=!0),this.media.hasAttribute("loop")&&(this.config.loop.active=!0);break;default:return void this.debug.error("Setup failed: unsupported type")}this.supported=Ee.check(this.type,this.provider),this.supported.api?(this.eventListeners=[],this.listeners=new oc(this),this.storage=new Qt(this),this.media.plyr=this,E.element(this.elements.container)||(this.elements.container=j("div"),sn(this.media,this.elements.container)),fe.migrateStyles.call(this),fe.addStyleHook.call(this),vn.setup.call(this),this.config.debug&&se.call(this,this.elements.container,this.config.events.join(" "),o=>{this.debug.log(`event: ${o.type}`)}),this.fullscreen=new He(this),(this.isHTML5||this.isEmbed&&!this.supported.ui)&&fe.build.call(this),this.listeners.container(),this.listeners.global(),this.config.ads.enabled&&(this.ads=new gc(this)),this.isHTML5&&this.config.autoplay&&this.once("canplay",()=>ze(this.play())),this.lastSeekTime=0,this.config.previewThumbnails.enabled&&(this.previewThumbnails=new Ls(this))):this.debug.error("Setup failed: no support")}get isHTML5(){return this.provider===ft.html5}get isEmbed(){return this.isYouTube||this.isVimeo}get isYouTube(){return this.provider===ft.youtube}get isVimeo(){return this.provider===ft.vimeo}get isVideo(){return this.type===Es.video}get isAudio(){return this.type===Es.audio}get playing(){return!!(this.ready&&!this.paused&&!this.ended)}get paused(){return!!this.media.paused}get stopped(){return!!(this.paused&&this.currentTime===0)}get ended(){return!!this.media.ended}set currentTime(e){if(!this.duration)return;const t=E.number(e)&&e>0;this.media.currentTime=t?Math.min(e,this.duration):0,this.debug.log(`Seeking to ${this.currentTime} seconds`)}get currentTime(){return Number(this.media.currentTime)}get buffered(){const{buffered:e}=this.media;return E.number(e)?e:e&&e.length&&this.duration>0?e.end(0)/this.duration:0}get seeking(){return!!this.media.seeking}get duration(){const e=parseFloat(this.config.duration),t=(this.media||{}).duration,i=E.number(t)&&t!==1/0?t:0;return e||i}set volume(e){let t=e;E.string(t)&&(t=Number(t)),E.number(t)||(t=this.storage.get("volume")),E.number(t)||({volume:t}=this.config),t>1&&(t=1),t<0&&(t=0),this.config.volume=t,this.media.volume=t,!E.empty(e)&&this.muted&&t>0&&(this.muted=!1)}get volume(){return Number(this.media.volume)}set muted(e){let t=e;E.boolean(t)||(t=this.storage.get("muted")),E.boolean(t)||(t=this.config.muted),this.config.muted=t,this.media.muted=t}get muted(){return!!this.media.muted}get hasAudio(){return!this.isHTML5||!!this.isAudio||!!this.media.mozHasAudio||!!this.media.webkitAudioDecodedByteCount||!!(this.media.audioTracks&&this.media.audioTracks.length)}set speed(e){let t=null;E.number(e)&&(t=e),E.number(t)||(t=this.storage.get("speed")),E.number(t)||(t=this.config.speed.selected);const{minimumSpeed:i,maximumSpeed:s}=this;t=bn(t,i,s),this.config.speed.selected=t,setTimeout(()=>{this.media&&(this.media.playbackRate=t)},0)}get speed(){return Number(this.media.playbackRate)}get minimumSpeed(){return this.isYouTube?Math.min(...this.options.speed):this.isVimeo?.5:.0625}get maximumSpeed(){return this.isYouTube?Math.max(...this.options.speed):this.isVimeo?2:16}set quality(e){const t=this.config.quality,i=this.options.quality;if(!i.length)return;let s=[!E.empty(e)&&Number(e),this.storage.get("quality"),t.selected,t.default].find(E.number),n=!0;if(!i.includes(s)){const a=an(i,s);this.debug.warn(`Unsupported quality option: ${s}, using ${a} instead`),s=a,n=!1}t.selected=s,this.media.quality=s,n&&this.storage.set({quality:s})}get quality(){return this.media.quality}set loop(e){const t=E.boolean(e)?e:this.config.loop.active;this.config.loop.active=t,this.media.loop=t}get loop(){return!!this.media.loop}set source(e){_s.change.call(this,e)}get source(){return this.media.currentSrc}get download(){const{download:e}=this.config.urls;return E.url(e)?e:this.source}set download(e){E.url(e)&&(this.config.urls.download=e,N.setDownloadUrl.call(this))}set poster(e){this.isVideo?fe.setPoster.call(this,e,!1).catch(()=>{}):this.debug.warn("Poster can only be set for video")}get poster(){return this.isVideo?this.media.getAttribute("poster")||this.media.getAttribute("data-poster"):null}get ratio(){if(!this.isVideo)return null;const e=xi(vs.call(this));return E.array(e)?e.join(":"):e}set ratio(e){this.isVideo?E.string(e)&&cn(e)?(this.config.ratio=xi(e),Ct.call(this)):this.debug.error(`Invalid aspect ratio specified (${e})`):this.debug.warn("Aspect ratio can only be set for video")}set autoplay(e){this.config.autoplay=E.boolean(e)?e:this.config.autoplay}get autoplay(){return!!this.config.autoplay}toggleCaptions(e){ne.toggle.call(this,e,!1)}set currentTrack(e){ne.set.call(this,e,!1),ne.setup.call(this)}get currentTrack(){const{toggled:e,currentTrack:t}=this.captions;return e?t:-1}set language(e){ne.setLanguage.call(this,e,!1)}get language(){return(ne.getCurrentTrack.call(this)||{}).language}set pip(e){if(!Ee.pip)return;const t=E.boolean(e)?e:!this.pip;E.function(this.media.webkitSetPresentationMode)&&this.media.webkitSetPresentationMode(t?Ts.active:Ts.inactive),E.function(this.media.requestPictureInPicture)&&(!this.pip&&t?this.media.requestPictureInPicture():this.pip&&!t&&document.exitPictureInPicture())}get pip(){return Ee.pip?E.empty(this.media.webkitPresentationMode)?this.media===document.pictureInPictureElement:this.media.webkitPresentationMode===Ts.active:null}setPreviewThumbnails(e){this.previewThumbnails&&this.previewThumbnails.loaded&&(this.previewThumbnails.destroy(),this.previewThumbnails=null),Object.assign(this.config.previewThumbnails,e),this.config.previewThumbnails.enabled&&(this.previewThumbnails=new Ls(this))}static supported(e,t){return Ee.check(e,t)}static loadSprite(e,t){return fn(e,t)}static setup(e,t={}){let i=null;return E.string(e)?i=Array.from(document.querySelectorAll(e)):E.nodeList(e)?i=Array.from(e):E.array(e)&&(i=e.filter(E.element)),E.empty(i)?null:i.map(s=>new ti(s,t))}}ti.defaults=Kl(yn);const mc=`\r
\r
\r
Доступ ограничен
\r
\r Чтобы продолжить просмотр, оплатите доступ прямо сейчас. Не упустите возможность досмотреть до конца!\r
\r Продолжить\r
\r
\r `;function yc(r,e={}){return r.replace(/{{(.*?)}}/g,(t,i)=>{var s;return(s=e[i.trim()])!=null?s:""})}function En(r){return $r(this,null,function*(){const t=new TextEncoder().encode(r),i=yield crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(s=>s.toString(16).padStart(2,"0")).join("")})}function vc(r,e,t,i){const s=new URL(window.location.href);s.searchParams.set("since",i==null?void 0:i.delay),r.innerHTML=yc(mc),En(i==null?void 0:i.video).then(n=>{let a=(i==null?void 0:i.dcuuid)+":"+n,o=document.querySelector(".dialog-cta");o&&(o.href=(i==null?void 0:i.formshost)+"/payment?backuri="+encodeURIComponent(s.toString())+"&dcuuid="+a,i!=null&&i.cta_text&&(o.innerHTML=i==null?void 0:i.cta_text))})}const B=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},bc=Number.isSafeInteger||function(r){return typeof r=="number"&&Math.abs(r)<=Tc},Tc=Number.MAX_SAFE_INTEGER||9007199254740991;let G=function(r){return r.NETWORK_ERROR="networkError",r.MEDIA_ERROR="mediaError",r.KEY_SYSTEM_ERROR="keySystemError",r.MUX_ERROR="muxError",r.OTHER_ERROR="otherError",r}({}),R=function(r){return r.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",r.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",r.KEY_SYSTEM_NO_SESSION="keySystemNoSession",r.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",r.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",r.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",r.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",r.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",r.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",r.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",r.MANIFEST_LOAD_ERROR="manifestLoadError",r.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",r.MANIFEST_PARSING_ERROR="manifestParsingError",r.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",r.LEVEL_EMPTY_ERROR="levelEmptyError",r.LEVEL_LOAD_ERROR="levelLoadError",r.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",r.LEVEL_PARSING_ERROR="levelParsingError",r.LEVEL_SWITCH_ERROR="levelSwitchError",r.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",r.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",r.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",r.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",r.FRAG_LOAD_ERROR="fragLoadError",r.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",r.FRAG_DECRYPT_ERROR="fragDecryptError",r.FRAG_PARSING_ERROR="fragParsingError",r.FRAG_GAP="fragGap",r.REMUX_ALLOC_ERROR="remuxAllocError",r.KEY_LOAD_ERROR="keyLoadError",r.KEY_LOAD_TIMEOUT="keyLoadTimeOut",r.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",r.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",r.BUFFER_APPEND_ERROR="bufferAppendError",r.BUFFER_APPENDING_ERROR="bufferAppendingError",r.BUFFER_STALLED_ERROR="bufferStalledError",r.BUFFER_FULL_ERROR="bufferFullError",r.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",r.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",r.ASSET_LIST_LOAD_ERROR="assetListLoadError",r.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",r.ASSET_LIST_PARSING_ERROR="assetListParsingError",r.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",r.INTERNAL_EXCEPTION="internalException",r.INTERNAL_ABORTED="aborted",r.ATTACH_MEDIA_ERROR="attachMediaError",r.UNKNOWN="unknown",r}({}),p=function(r){return r.MEDIA_ATTACHING="hlsMediaAttaching",r.MEDIA_ATTACHED="hlsMediaAttached",r.MEDIA_DETACHING="hlsMediaDetaching",r.MEDIA_DETACHED="hlsMediaDetached",r.MEDIA_ENDED="hlsMediaEnded",r.STALL_RESOLVED="hlsStallResolved",r.BUFFER_RESET="hlsBufferReset",r.BUFFER_CODECS="hlsBufferCodecs",r.BUFFER_CREATED="hlsBufferCreated",r.BUFFER_APPENDING="hlsBufferAppending",r.BUFFER_APPENDED="hlsBufferAppended",r.BUFFER_EOS="hlsBufferEos",r.BUFFERED_TO_END="hlsBufferedToEnd",r.BUFFER_FLUSHING="hlsBufferFlushing",r.BUFFER_FLUSHED="hlsBufferFlushed",r.MANIFEST_LOADING="hlsManifestLoading",r.MANIFEST_LOADED="hlsManifestLoaded",r.MANIFEST_PARSED="hlsManifestParsed",r.LEVEL_SWITCHING="hlsLevelSwitching",r.LEVEL_SWITCHED="hlsLevelSwitched",r.LEVEL_LOADING="hlsLevelLoading",r.LEVEL_LOADED="hlsLevelLoaded",r.LEVEL_UPDATED="hlsLevelUpdated",r.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",r.LEVELS_UPDATED="hlsLevelsUpdated",r.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",r.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",r.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",r.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",r.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",r.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",r.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",r.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",r.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",r.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",r.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",r.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",r.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",r.CUES_PARSED="hlsCuesParsed",r.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",r.INIT_PTS_FOUND="hlsInitPtsFound",r.FRAG_LOADING="hlsFragLoading",r.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",r.FRAG_LOADED="hlsFragLoaded",r.FRAG_DECRYPTED="hlsFragDecrypted",r.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",r.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",r.FRAG_PARSING_METADATA="hlsFragParsingMetadata",r.FRAG_PARSED="hlsFragParsed",r.FRAG_BUFFERED="hlsFragBuffered",r.FRAG_CHANGED="hlsFragChanged",r.FPS_DROP="hlsFpsDrop",r.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",r.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",r.ERROR="hlsError",r.DESTROYING="hlsDestroying",r.KEY_LOADING="hlsKeyLoading",r.KEY_LOADED="hlsKeyLoaded",r.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",r.BACK_BUFFER_REACHED="hlsBackBufferReached",r.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",r.ASSET_LIST_LOADING="hlsAssetListLoading",r.ASSET_LIST_LOADED="hlsAssetListLoaded",r.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",r.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",r.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",r.INTERSTITIAL_STARTED="hlsInterstitialStarted",r.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",r.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",r.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",r.INTERSTITIAL_ENDED="hlsInterstitialEnded",r.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",r.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",r.EVENT_CUE_ENTER="hlsEventCueEnter",r}({});var ee={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},$={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Dt{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class Ec{constructor(e,t,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 Dt(e),this.fast_=new Dt(t),this.defaultTTFB_=s,this.ttfb_=new Dt(e)}update(e,t){const{slow_:i,fast_:s,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new Dt(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new Dt(t,s.getEstimate(),s.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new Dt(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const i=8*t,s=e/1e3,n=i/s;this.fast_.sample(s,n),this.slow_.sample(s,n)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,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 xc(r,e,t){return(e=Ac(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function ue(){return ue=Object.assign?Object.assign.bind():function(r){for(var e=1;e`):gt}function Sn(r,e,t){return e[r]?e[r].bind(e):_c(r,t)}const Rs=Is();function Ic(r,e,t){const i=Is();if(typeof console=="object"&&r===!0||typeof r=="object"){const s=["debug","log","info","warn","error"];s.forEach(n=>{i[n]=Sn(n,r,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.2`)}catch(n){return Is()}s.forEach(n=>{Rs[n]=Sn(n,r)})}else ue(Rs,i);return i}const ie=Rs;function pt(r=!0){return typeof self=="undefined"?void 0:(r||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Rc(r){return typeof self!="undefined"&&r===self.ManagedMediaSource}function An(r,e){const t=Object.keys(r),i=Object.keys(e),s=t.length,n=i.length;return!s||!n||s===n&&!t.some(a=>i.indexOf(a)===-1)}function Ne(r,e=!1){if(typeof TextDecoder!="undefined"){const l=new TextDecoder("utf-8").decode(r);if(e){const d=l.indexOf("\0");return d!==-1?l.substring(0,d):l}return l.replace(/\0/g,"")}const t=r.length;let i,s,n,a="",o=0;for(;o>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:s=r[o++],a+=String.fromCharCode((i&31)<<6|s&63);break;case 14:s=r[o++],n=r[o++],a+=String.fromCharCode((i&15)<<12|(s&63)<<6|(n&63)<<0);break}}return a}const Xe={hexDump:function(r){let e="";for(let t=0;t1||i===1&&this.levelkeys[t[0]].encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!B(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Ie(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,s,n,a=!1){const{elementaryStreams:o}=this,c=o[e];if(!c){o[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:n,partial:a};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,i),c.startDTS=Math.min(c.startDTS,s),c.endDTS=Math.max(c.endDTS,n)}}class Cc extends _n{constructor(e,t,i,s,n){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=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,n),n&&(this.fragOffset=n.fragOffset+n.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function In(r,e){const t=Object.getPrototypeOf(r);if(t){const i=Object.getOwnPropertyDescriptor(t,e);return i||In(t,e)}}function Dc(r,e){const t=In(r,e);t&&(t.enumerable=!0,Object.defineProperty(r,e,t))}const _i=Math.pow(2,32)-1,Pc=[].push,Rn={video:1,audio:2,id3:3,text:4};function Se(r){return String.fromCharCode.apply(null,r)}function kn(r,e){const t=r[e]<<8|r[e+1];return t<0?65536+t:t}function W(r,e){const t=Cn(r,e);return t<0?4294967296+t:t}function wn(r,e){let t=W(r,e);return t*=Math.pow(2,32),t+=W(r,e+4),t}function Cn(r,e){return r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}function Ps(r,e,t){r[e]=t>>24,r[e+1]=t>>16&255,r[e+2]=t>>8&255,r[e+3]=t&255}function Oc(r){const e=r.byteLength;for(let t=0;t8&&r[t+4]===109&&r[t+5]===111&&r[t+6]===111&&r[t+7]===102)return!0;t=i>1?t+i:e}return!1}function Q(r,e){const t=[];if(!e.length)return t;const i=r.byteLength;for(let s=0;s1?s+n:i;if(a===e[0])if(e.length===1)t.push(r.subarray(s+8,o));else{const c=Q(r.subarray(s+8,o),e.slice(1));c.length&&Pc.apply(t,c)}s=o}return t}function Mc(r){const e=[],t=r[0];let i=8;const s=W(r,i);i+=4;let n=0,a=0;t===0?(n=W(r,i),a=W(r,i+4),i+=8):(n=wn(r,i),a=wn(r,i+8),i+=16),i+=2;let o=r.length+a;const c=kn(r,i);i+=2;for(let l=0;l>>31===1)return ie.warn("SIDX has hierarchical references (not supported)"),null;const g=W(r,d);d+=4,e.push({referenceSize:h,subsegmentDuration:g,info:{duration:g/s,start:o,end:o+h-1}}),o+=h,d+=4,i=d}return{earliestPresentationTime:n,timescale:s,version:t,referencesCount:c,references:e}}function Dn(r){const e=[],t=Q(r,["moov","trak"]);for(let s=0;s{const n=W(s,4),a=e[n];a&&(a.default={duration:W(s,12),flags:W(s,20)})}),e}function Fc(r){const e=r.subarray(8),t=e.subarray(86),i=Se(e.subarray(4,8));let s=i,n;const a=i==="enca"||i==="encv";if(a){const l=Q(e,[i])[0].subarray(i==="enca"?28:78);Q(l,["sinf"]).forEach(u=>{const h=Q(u,["schm"])[0];if(h){const f=Se(h.subarray(4,8));if(f==="cbcs"||f==="cenc"){const g=Q(u,["frma"])[0];g&&(s=Se(g))}}})}const o=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const c=Q(t,["avcC"])[0];c&&c.length>3&&(s+="."+Ri(c[1])+Ri(c[2])+Ri(c[3]),n=Ii(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=Q(e,[i])[0],l=Q(c.subarray(28),["esds"])[0];if(l&&l.length>7){let d=4;if(l[d++]!==3)break;d=Os(l,d),d+=2;const u=l[d++];if(u&128&&(d+=2),u&64&&(d+=l[d++]),l[d++]!==4)break;d=Os(l,d);const h=l[d++];if(h===64)s+="."+Ri(h);else break;if(d+=12,l[d++]!==5)break;d=Os(l,d);const f=l[d++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((l[d]&224)>>5)),s+="."+g}break}case"hvc1":case"hev1":{const c=Q(t,["hvcC"])[0];if(c&&c.length>12){const l=c[1],d=["","A","B","C"][l>>6],u=l&31,h=W(c,2),f=(l&32)>>5?"H":"L",g=c[12],m=c.subarray(6,12);s+="."+d+u,s+="."+h.toString(16).toUpperCase(),s+="."+f+g;let y="";for(let v=m.length;v--;){const T=m[v];(T||y)&&(y="."+T.toString(16).toUpperCase()+y)}s+=y}n=Ii(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{s=Ii(s,t)||s;break}case"vp09":{const c=Q(t,["vpcC"])[0];if(c&&c.length>6){const l=c[4],d=c[5],u=c[6]>>4&15;s+="."+Qe(l)+"."+Qe(d)+"."+Qe(u)}break}case"av01":{const c=Q(t,["av1C"])[0];if(c&&c.length>2){const l=c[1]>>>5,d=c[1]&31,u=c[2]>>>7?"H":"M",h=(c[2]&64)>>6,f=(c[2]&32)>>5,g=l===2&&h?f?12:10:h?10:8,m=(c[2]&16)>>4,y=(c[2]&8)>>3,v=(c[2]&4)>>2,T=c[2]&3;s+="."+l+"."+Qe(d)+u+"."+Qe(g)+"."+m+"."+y+v+T+"."+Qe(1)+"."+Qe(1)+"."+Qe(1)+"."+0,n=Ii("dav1",t)}break}}return{codec:s,encrypted:a,supplemental:n}}function Ii(r,e){const t=Q(e,["dvvC"]),i=t.length?t[0]:Q(e,["dvcC"])[0];if(i){const s=i[2]>>1&127,n=i[2]<<5&32|i[3]>>3&31;return r+"."+Qe(s)+"."+Qe(n)}}function Os(r,e){const t=e+5;for(;r[e++]&128&&e{const a=Q(s,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=Q(a,["enca"]);const c=o.length>0;c||(o=Q(a,["encv"])),o.forEach(l=>{const d=c?l.subarray(28):l.subarray(78);Q(d,["sinf"]).forEach(h=>{const f=Pn(h);if(f){const g=f.subarray(8,24);g.some(m=>m!==0)||(ie.log(`[eme] Patching keyId in 'enc${c?"a":"v"}>sinf>>tenc' box: ${Xe.hexDump(g)} -> ${Xe.hexDump(t)}`),f.set(t,8))}})})}),r}function Pn(r){const e=Q(r,["schm"])[0];if(e){const t=Se(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return Q(r,["schi","tenc"])[0]}return null}function Bc(r,e){return Q(e,["moof","traf"]).reduce((t,i)=>{const s=Q(i,["tfdt"])[0],n=s[0],a=Q(i,["tfhd"]).reduce((o,c)=>{const l=W(c,4),d=r[l];if(d){let u=W(s,4);if(n===1){if(u===_i)return ie.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;u*=_i+1,u+=W(s,8)}const h=d.timescale||9e4,f=u/h;if(B(f)&&(o===null||ff+g.info.duration||0,0);o=Math.max(o,h+u.earliestPresentationTime/u.timescale),c=o-a}}if(c&&B(c))return c}return i||s}function $c(r){const e=W(r,0);let t=8;e&1&&(t+=4),e&4&&(t+=4);let i=0;const s=W(r,4);for(let n=0;n{Q(i,["tfhd"]).forEach(s=>{const n=W(s,4),a=r[n];if(!a)return;const o=a.timescale||9e4;Q(i,["tfdt"]).forEach(c=>{const l=c[0],d=t*o;if(d){let u=W(c,4);if(l===0)u-=d,u=Math.max(u,0),Ps(c,4,u);else{u*=Math.pow(2,32),u+=W(c,8),u-=d,u=Math.max(u,0);const h=Math.floor(u/(_i+1)),f=Math.floor(u%(_i+1));Ps(c,4,h),Ps(c,8,f)}}})})})}function Vc(r){const e={valid:null,remainder:null},t=Q(r,["moof"]);if(t.length<2)return e.remainder=r,e;const i=t[t.length-1];return e.valid=r.slice(0,i.byteOffset-8),e.remainder=r.slice(i.byteOffset-8),e}function Ue(r,e){const t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function On(r,e){const t=[],i=e.samples,s=e.timescale,n=e.id;let a=!1;return Q(i,["moof"]).map(c=>{const l=c.byteOffset-8;Q(c,["traf"]).map(u=>{const h=Q(u,["tfdt"]).map(f=>{const g=f[0];let m=W(f,4);return g===1&&(m*=Math.pow(2,32),m+=W(f,8)),m/s})[0];return h!==void 0&&(r=h),Q(u,["tfhd"]).map(f=>{const g=W(f,4),m=W(f,0)&16777215,y=(m&1)!==0,v=(m&2)!==0,T=(m&8)!==0;let b=0;const x=(m&16)!==0;let S=0;const k=(m&32)!==0;let A=8;g===n&&(y&&(A+=8),v&&(A+=4),T&&(b=W(f,A),A+=4),x&&(S=W(f,A),A+=4),k&&(A+=4),e.type==="video"&&(a=ki(e.codec)),Q(u,["trun"]).map(I=>{const w=I[0],L=W(I,0)&16777215,D=(L&1)!==0;let M=0;const te=(L&4)!==0,Y=(L&256)!==0;let H=0;const U=(L&512)!==0;let K=0;const V=(L&1024)!==0,P=(L&2048)!==0;let O=0;const X=W(I,4);let q=8;D&&(M=W(I,q),q+=4),te&&(q+=4);let Z=M+l;for(let re=0;re>1&63;return t===39||t===40}else return(e&31)===6}function Ms(r,e,t,i){const s=Mn(r);let n=0;n+=e;let a=0,o=0,c=0;for(;n=s.length)break;c=s[n++],a+=c}while(c===255);o=0;do{if(n>=s.length)break;c=s[n++],o+=c}while(c===255);const l=s.length-n;let d=n;if(ol){ie.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(a===4){if(s[d++]===181){const h=kn(s,d);if(d+=2,h===49){const f=W(s,d);if(d+=4,f===1195456820){const g=s[d++];if(g===3){const m=s[d++],y=31&m,v=64&m,T=v?2+y*3:0,b=new Uint8Array(T);if(v){b[0]=m;for(let x=1;x16){const u=[];for(let g=0;g<16;g++){const m=s[d++].toString(16);u.push(m.length==1?"0"+m:m),(g===3||g===5||g===7||g===9)&&u.push("-")}const h=o-16,f=new Uint8Array(h);for(let g=0;g>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=i&255,n.set(r,4),s=0,i=8;s0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return t&&t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),Wc([112,115,115,104],new Uint8Array([i,0,0,0]),r,n,s,a,t||new Uint8Array)}function jc(r){const e=[];if(r instanceof ArrayBuffer){const t=r.byteLength;let i=0;for(;i+32>>24;if(n!==0&&n!==1)return{offset:t,size:e};const a=r.buffer,o=Xe.hexDump(new Uint8Array(a,t+12,16)),c=r.getUint32(28);let l=null,d=null;if(n===0){if(e-32/\(Windows.+Firefox\//i.test(navigator.userAgent),Pt={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 Nn(r,e){const t=Pt[e];return!!t&&!!t[r.slice(0,4)]}function Fs(r,e,t=!0){return!r.split(",").some(i=>!Bn(i,e,t))}function Bn(r,e,t=!0){var i;const s=pt(t);return(i=s==null?void 0:s.isTypeSupported(ii(r,e)))!=null?i:!1}function ii(r,e){return`${e}/mp4;codecs=${r}`}function Un(r){if(r){const e=r.substring(0,4);return Pt.video[e]}return 2}function wi(r){const e=Fn();return r.split(",").reduce((t,i)=>{const n=e&&ki(i)?9:Pt.video[i];return n?(n*2+t)/(t?3:2):(Pt.audio[i]+t)/(t?2:1)},0)}const Ns={};function zc(r,e=!0){if(Ns[r])return Ns[r];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[r];for(let s=0;szc(t.toLowerCase(),e))}function Qc(r,e){const t=[];if(r){const i=r.split(",");for(let s=0;s4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(r)!==-1))return r;if(e){const t=e.split(",");if(t.length>1){if(r){for(let i=t.length;i--;)if(t[i].substring(0,4)===r.substring(0,4))return t[i]}return t[0]}}return e||r}function Jc(r){const e=r.split(",");for(let t=0;t2){let s=i.shift()+".";s+=parseInt(i.shift()).toString(16),s+=("000"+parseInt(i.shift()).toString(16)).slice(-4),e[t]=s}}return e.join(",")}function Zc(r){if(r.startsWith("av01.")){const e=r.split("."),t=["0","111","01","01","01","0"];for(let i=e.length;i>4&&i<10;i++)e[i]=t[i-4];return e.join(".")}return r}function $n(r){const e=pt(r)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Gn(r){return r.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Vn={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Hn(r,e){return{supported:!1,configurations:e,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:r}}const Kn={};function ed(r,e,t,i,s,n){const a=r.audioCodec?r.audioGroups:null,o=n==null?void 0:n.audioCodec,c=n==null?void 0:n.channels,l=c?parseInt(c):o?1/0:2;let d=null;if(a!=null&&a.length)try{a.length===1&&a[0]?d=e.groups[a[0]].channels:d=a.reduce((u,h)=>{if(h){const f=e.groups[h];if(!f)throw new Error(`Audio track group ${h} not found`);Object.keys(f.channels).forEach(g=>{u[g]=(u[g]||0)+f.channels[g]})}return u},{2:0})}catch(u){return!0}return r.videoCodec!==void 0&&(r.width>1920&&r.height>1088||r.height>1920&&r.width>1088||r.frameRate>Math.max(i,30)||r.videoRange!=="SDR"&&r.videoRange!==t||r.bitrate>Math.max(s,8e6))||!!d&&B(l)&&Object.keys(d).some(u=>parseInt(u)>l)}function Wn(r,e,t){const i=r.videoCodec,s=r.audioCodec;if(!i&&!s||!t)return Promise.resolve(Vn);const n=[];if(i){const a={width:r.width,height:r.height,bitrate:Math.ceil(Math.max(r.bitrate*.9,r.averageBitrate)),framerate:r.frameRate||30},o=r.videoRange;o!=="SDR"&&(a.transferFunction=o.toLowerCase());const c=i.split(","),l=navigator.userAgent;if(c.some(d=>ki(d))&&Fn())return Promise.resolve(Hn(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: (${l})`),n));n.push.apply(n,c.map(d=>({type:"media-source",video:le(le({},a),{},{contentType:ii(Zc(d),"video")})})))}return s&&r.audioGroups&&r.audioGroups.forEach(a=>{var o;a&&((o=e.groups[a])==null||o.tracks.forEach(c=>{if(c.groupId===a){const l=c.channels||"",d=parseFloat(l);B(d)&&d>2&&n.push.apply(n,s.split(",").map(u=>({type:"media-source",audio:{contentType:ii(u,"audio"),channels:""+d}})))}}))}),Promise.all(n.map(a=>{const o=td(a);return Kn[o]||(Kn[o]=t.decodingInfo(a))})).then(a=>({supported:!a.some(o=>!o.supported),configurations:n,decodingInfoResults:a})).catch(a=>({supported:!1,configurations:n,decodingInfoResults:[],error:a}))}function td(r){const{audio:e,video:t}=r,i=t||e;if(i){const s=Gn(i.contentType);if(t)return`r${t.height}x${t.width}f${Math.ceil(t.framerate)}${t.transferFunction||"sd"}_${s}_${Math.ceil(t.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${s}`}return""}const Bs=["NONE","TYPE-0","TYPE-1",null];function id(r){return Bs.indexOf(r)>-1}const Pi=["SDR","PQ","HLG"];function sd(r){return!!r&&Pi.indexOf(r)>-1}var Oi={No:"",Yes:"YES",v2:"v2"};function Yn(r){const{canSkipUntil:e,canSkipDateRanges:t,age:i}=r,s=i!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.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(e){return qn(this._audioGroups,e)}hasSubtitleGroup(e){return qn(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function qn(r,e){return!e||!r?!1:r.indexOf(e)!==-1}function rd(){if(typeof matchMedia=="function"){const r=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(r.media!==e.media)return r.matches===!0}return!1}function nd(r,e){let t=!1,i=[];if(r&&(t=r!=="SDR",i=[r]),e){i=e.allowedVideoRanges||Pi.slice(0);const s=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:s&&rd(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}const ad=r=>{const e=new WeakSet;return(t,i)=>{if(r&&(i=r(t,i)),typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i)}return i}},me=(r,e)=>JSON.stringify(r,ad(e));function od(r,e,t,i,s){const n=Object.keys(r),a=i==null?void 0:i.channels,o=i==null?void 0:i.audioCodec,c=s==null?void 0:s.videoCodec,l=a&&parseInt(a)===2;let d=!1,u=!1,h=1/0,f=1/0,g=1/0,m=1/0,y=0,v=[];const{preferHDR:T,allowedVideoRanges:b}=nd(e,s);for(let I=n.length;I--;){const w=r[n[I]];d||(d=w.channels[2]>0),h=Math.min(h,w.minHeight),f=Math.min(f,w.minFramerate),g=Math.min(g,w.minBitrate),b.filter(D=>w.videoRanges[D]>0).length>0&&(u=!0)}h=B(h)?h:0,f=B(f)?f:0;const x=Math.max(1080,h),S=Math.max(30,f);g=B(g)?g:t,t=Math.max(g,t),u||(e=void 0);const k=n.length>1;return{codecSet:n.reduce((I,w)=>{const L=r[w];if(w===I)return I;if(v=u?b.filter(D=>L.videoRanges[D]>0):[],k){if(L.minBitrate>t)return Je(w,`min bitrate of ${L.minBitrate} > current estimate of ${t}`),I;if(!L.hasDefaultAudio)return Je(w,"no renditions with default or auto-select sound found"),I;if(o&&w.indexOf(o.substring(0,4))%5!==0)return Je(w,`audio codec preference "${o}" not found`),I;if(a&&!l){if(!L.channels[a])return Je(w,`no renditions with ${a} channel sound found (channels options: ${Object.keys(L.channels)})`),I}else if((!o||l)&&d&&L.channels[2]===0)return Je(w,"no renditions with stereo sound found"),I;if(L.minHeight>x)return Je(w,`min resolution of ${L.minHeight} > maximum of ${x}`),I;if(L.minFramerate>S)return Je(w,`min framerate of ${L.minFramerate} > maximum of ${S}`),I;if(!v.some(D=>L.videoRanges[D]>0))return Je(w,`no variants with VIDEO-RANGE of ${me(v)} found`),I;if(c&&w.indexOf(c.substring(0,4))%5!==0)return Je(w,`video codec preference "${c}" not found`),I;if(L.maxScore=wi(I)||L.fragmentError>r[I].fragmentError)?I:(m=L.minIndex,y=L.maxScore,w)},void 0),videoRanges:v,preferHDR:T,minFramerate:f,minBitrate:g,minIndex:m}}function Je(r,e){ie.log(`[abr] start candidates with "${r}" ignored because ${e}`)}function zn(r){return r.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const s=t.channels||"2";return i.channels[s]=(i.channels[s]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function ld(r,e,t,i){return r.slice(t,i+1).reduce((s,n,a)=>{if(!n.codecSet)return s;const o=n.audioGroups;let c=s[n.codecSet];c||(s[n.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,n.bitrate);const l=Math.min(n.height,n.width);return c.minHeight=Math.min(c.minHeight,l),c.minFramerate=Math.min(c.minFramerate,n.frameRate),c.minIndex=Math.min(c.minIndex,a),c.maxScore=Math.max(c.maxScore,n.score),c.fragmentError+=n.fragmentError,c.videoRanges[n.videoRange]=(c.videoRanges[n.videoRange]||0)+1,o&&o.forEach(d=>{if(!d)return;const u=e.groups[d];u&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(h=>{c.channels[h]=(c.channels[h]||0)+u.channels[h]}))}),s},{})}function Xn(r){if(!r)return r;const{lang:e,assocLang:t,characteristics:i,channels:s,audioCodec:n}=r;return{lang:e,assocLang:t,characteristics:i,channels:s,audioCodec:n}}function Ze(r,e,t){if("attrs"in r){const i=e.indexOf(r);if(i!==-1)return i}for(let i=0;ii.indexOf(s)===-1)}function Lt(r,e){const{audioCodec:t,channels:i}=r;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function ud(r,e,t,i,s){const n=e[i],o=e.reduce((h,f,g)=>{const m=f.uri;return(h[m]||(h[m]=[])).push(g),h},{})[n.uri];o.length>1&&(i=Math.max.apply(Math,o));const c=n.videoRange,l=n.frameRate,d=n.codecSet.substring(0,4),u=Qn(e,i,h=>{if(h.videoRange!==c||h.frameRate!==l||h.codecSet.substring(0,4)!==d)return!1;const f=h.audioGroups,g=t.filter(m=>!f||f.indexOf(m.groupId)!==-1);return Ze(r,g,s)>-1});return u>-1?u:Qn(e,i,h=>{const f=h.audioGroups,g=t.filter(m=>!f||f.indexOf(m.groupId)!==-1);return Ze(r,g,s)>-1})}function Qn(r,e,t){for(let i=e;i>-1;i--)if(t(r[i]))return i;for(let i=e+1;i{var i;const{fragCurrent:s,partCurrent:n,hls:a}=this,{autoLevelEnabled:o,media:c}=a;if(!s||!c)return;const l=performance.now(),d=n?n.stats:s.stats,u=n?n.duration:s.duration,h=l-d.loading.start,f=a.minAutoLevel,g=s.level,m=this._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const y=m>-1&&m!==g,v=!!t||y;if(!v&&(c.paused||!c.playbackRate||!c.readyState))return;const T=a.mainForwardBufferInfo;if(!v&&T===null)return;const b=this.bwEstimator.getEstimateTTFB(),x=Math.abs(c.playbackRate);if(h<=Math.max(b,1e3*(u/(x*2))))return;const S=T?T.len/x:0,k=d.loading.first?d.loading.first-d.loading.start:-1,A=d.loaded&&k>-1,I=this.getBwEstimate(),w=a.levels,L=w[g],D=Math.max(d.loaded,Math.round(u*(s.bitrate||L.averageBitrate)/8));let M=A?h-k:h;M<1&&A&&(M=Math.min(h,d.loaded*8/I));const te=A?d.loaded*1e3/M:0,Y=b/1e3,H=te?(D-d.loaded)/te:D*8/I+Y;if(H<=S)return;const U=te?te*8:I,K=((i=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,V=this.hls.config.abrBandWidthUpFactor;let P=Number.POSITIVE_INFINITY,O;for(O=g-1;O>f;O--){const re=w[O].maxBitrate,de=!w[O].details||K;if(P=this.getTimeToLoadFrag(Y,U,u*re,de),P=H||P>u*10)return;A?this.bwEstimator.sample(h-Math.min(b,k),d.loaded):this.bwEstimator.sampleTTFB(h);const X=w[O].maxBitrate;this.getBwEstimate()*V>X&&this.resetEstimator(X);const q=this.findBestLevel(X,f,O,0,S,1,1);q>-1&&(O=q),this.warn(`Fragment ${s.sn}${n?" part "+n.index:""} of level ${g} is loading too slowly; Fragment duration: ${s.duration.toFixed(3)} Time to underbuffer: ${S.toFixed(3)} s Estimated load time for current fragment: ${H.toFixed(3)} s Estimated load time for down switch fragment: ${P.toFixed(3)} s TTFB estimate: ${k|0} ms Current BW estimate: ${B(I)?I|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${O} @ ${X|0} bps`),a.nextLoadLevel=a.nextAutoLevel=O,this.clearTimer();const Z=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===O&&O>0){const re=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${O>0?"and switching down":""} Fragment duration: ${s.duration.toFixed(3)} s Time to underbuffer: ${re.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,O>f){let de=this.findBestLevel(this.hls.levels[f].bitrate,f,O,0,re,1,1);de===-1&&(de=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=de,this.resetEstimator(this.hls.levels[de].bitrate)}}};y||H>P*2?Z():this.timer=self.setInterval(Z,P*1e3),a.trigger(p.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:n,stats:d})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new Ec(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(p.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,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(e,t){const i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var s;this.fragCurrent=i,this.partCurrent=(s=t.part)!=null?s:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case R.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:s,partCurrent:n}=this;if(i&&s&&i.sn===s.sn&&i.level===s.level){const a=performance.now(),o=n?n.stats:i.stats,c=a-o.loading.start,l=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&l>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(u,l),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,i,s){const n=e+i/t,a=s?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){const i=this.hls.config,{loading:s}=t.stats,n=s.end-s.first;B(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const s=i?i.stats:t.stats;if(t.type===$.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const n=i?i.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+s.loaded,c=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:c},a.realBitrate=Math.round(8*o/c)}if(t.bitrateTest){const n={stats:s,frag:t,part:i,id:t.type};this.onFragBuffered(p.FRAG_BUFFERED,n),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:s}=t,n=s!=null&&s.stats.loaded?s.stats:i.stats;if(n.aborted||this.ignoreFragment(i))return;const a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==$.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,n=this.findBestLevel(i,t,e,0,s,1,1);if(n>-1)return n;const a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const n=i&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,n)&&a[e].loadError<=a[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:s,config:n,minAutoLevel:a}=i,o=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),l=this.getStarvationDelay();let d=n.abrBandWidthFactor,u=n.abrBandWidthUpFactor;if(l){const y=this.findBestLevel(c,a,s,l,0,d,u);if(y>=0)return this.rebufferNotice=-1,y}let h=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){const y=this.bitrateTestDelay;y&&(h=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-y,this.info(`bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),d=u=1)}const f=this.findBestLevel(c,a,s,l,h,d,u);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const g=i.levels[a],m=i.loadLevelObj;return m&&(g==null?void 0:g.bitrate)=t;U--){var H;const K=g[U],V=U>u;if(!K)continue;if(v.useMediaCapabilities&&!K.supportedResult&&!K.supportedPromise){const de=navigator.mediaCapabilities;typeof(de==null?void 0:de.decodingInfo)=="function"&&(ed(K,L,k,A,e,I)||ki(K.videoCodec))?(K.supportedPromise=Wn(K,L,de),K.supportedPromise.then(pe=>{if(!this.hls)return;K.supportedResult=pe;const De=this.hls.levels,Me=De.indexOf(K);pe.error?this.warn(`MediaCapabilities decodingInfo error: "${pe.error}" for level ${Me} ${me(pe)}`):pe.supported||(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Me} ${me(pe)}`),Me>-1&&De.length>1&&(this.log(`Removing unsupported level ${Me}`),this.hls.removeLevel(Me),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))})):K.supportedResult=Vn}if((S&&K.codecSet!==S||k&&K.videoRange!==k||V&&A>K.frameRate||!V&&A>0&&A=M*2&&n===0?K.averageBitrate:K.maxBitrate,Z=this.getTimeToLoadFrag(te,X,q*O,P===void 0);if(X>=q&&(U===d||K.loadError===0&&K.fragmentError===0)&&(Z<=te||!B(Z)||b&&!this.bitrateTestDelay||Z${U} adjustedbw(${Math.round(X)})-bitrate=${Math.round(X-q)} ttfb:${te.toFixed(1)} avgDuration:${O.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${Z.toFixed(1)} firstSelection:${x} codecSet:${K.codecSet} videoRange:${K.videoRange} hls.loadLevel:${y}`)),x&&(this.firstSelection=U),U}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}}const Us={search:function(r,e){let t=0,i=r.length-1,s=null,n=null;for(;t<=i;){s=(t+i)/2|0,n=r[s];const a=e(n);if(a>0)t=s+1;else if(a<0)i=s-1;else return n}return null}};function fd(r,e,t){if(e===null||!Array.isArray(r)||!r.length||!B(e))return null;const i=r[0].programDateTime;if(e<(i||0))return null;const s=r[r.length-1].endProgramDateTime;if(e>=(s||0))return null;t=t||0;for(let n=0;n0&&o<15e-7&&(t+=15e-7),n&&r.level!==n.level&&n.end<=r.end&&(n=e[2+r.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!r||r.level===n.level)&&Jn(t,i,n)===0||gd(n,r,Math.min(s,i))))return n;const a=Us.search(e,Jn.bind(null,t,i));return a&&(a!==r||!n)?a:n}function gd(r,e,t){if(e&&e.start===0&&e.level0){const i=e.tagList.reduce((s,n)=>(n[0]==="INF"&&(s+=parseFloat(n[1])),s),t);return r.start<=i}return!1}function Jn(r=0,e=0,t){if(t.start<=r&&t.start+t.duration>r)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=r?1:t.start-i>r&&t.start?-1:0}function pd(r,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>r}function Zn(r,e){return Us.search(r,t=>t.cce?-1:0)}function md(r,e,t){if(r&&r.startCC<=e&&r.endCC>=e){const i=t.start,s=t.end;let n=r.fragments;if(!t.relurl){const{fragmentHint:a}=r;a&&(n=n.concat(a))}return Us.search(n,a=>a.cce||a.start>=s?-1:0)}return null}function Fi(r){switch(r.details){case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_TIMEOUT:case R.LEVEL_LOAD_TIMEOUT:case R.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function ea(r,e){const t=Fi(e);return r.default[`${t?"timeout":"error"}Retry`]}function $s(r,e){const t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function ta(r){return le(le({},r),{errorRetry:null,timeoutRetry:null})}function Ni(r,e,t,i){if(!r)return!1;const s=i==null?void 0:i.code,n=e499)}var we={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Ke={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2};class vd extends at{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.ERROR,this.onError,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.ERROR,this.onError,this),e.off(p.ERROR,this.onErrorOut,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===$.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const s=this.hls,n=t.context;switch(t.details){case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case R.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=ri();return}case R.FRAG_GAP:case R.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=we.SendAlternateToPenaltyBox;return}case R.LEVEL_EMPTY_ERROR:case R.LEVEL_PARSING_ERROR:{var a,o;const l=t.parent===$.MAIN?t.level:s.loadLevel;t.details===R.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(o=a.levelDetails)!=null&&o.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l))}return;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:typeof(n==null?void 0:n.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_LOAD_ERROR:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const l=s.loadLevelObj;if(l&&(n.type===ee.AUDIO_TRACK&&l.hasAudioGroup(n.groupId)||n.type===ee.SUBTITLE_TRACK&&l.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=we.SendAlternateToPenaltyBox,t.errorAction.flags=Ke.MoveAllAlternatesMatchingHost;return}}return;case R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const l=s.loadLevelObj,d=l==null?void 0:l.attrs["HDCP-LEVEL"];d?t.errorAction={action:we.SendAlternateToPenaltyBox,flags:Ke.MoveAllAlternatesMatchingHDCP,hdcpLevel:d}:this.keySystemError(t)}return;case R.BUFFER_ADD_CODEC_ERROR:case R.REMUX_ALLOC_ERROR:case R.BUFFER_APPEND_ERROR:if(!t.errorAction){var c;t.errorAction=this.getLevelSwitchAction(t,(c=t.level)!=null?c:s.loadLevel)}return;case R.INTERNAL_EXCEPTION:case R.BUFFER_APPENDING_ERROR:case R.BUFFER_FULL_ERROR:case R.LEVEL_SWITCH_ERROR:case R.BUFFER_STALLED_ERROR:case R.BUFFER_SEEK_OVER_HOLE:case R.BUFFER_NUDGE_ON_STALL:t.errorAction=ri();return}t.type===G.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,s=ea(i.config.playlistLoadPolicy,e),n=this.playlistError++;if(Ni(s,n,Fi(e),e.response))return{action:we.RetryRequest,flags:Ke.None,retryConfig:s,retryCount:n};const o=this.getLevelSwitchAction(e,t);return s&&(o.retryConfig=s,o.retryCount=n),o}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=ea(e.details.startsWith("key")?a:n,e),c=t.levels.reduce((d,u)=>d+u.fragmentError,0);if(s&&(e.details!==R.FRAG_GAP&&s.fragmentError++,Ni(o,c,Fi(e),e.response)))return{action:we.RetryRequest,flags:Ke.None,retryConfig:o,retryCount:c};const l=this.getLevelSwitchAction(e,i);return o&&(l.retryConfig=o,l.retryCount=c),l}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const s=this.hls.levels[t];if(s){var n,a;const l=e.details;s.loadError++,l===R.BUFFER_APPEND_ERROR&&s.fragmentError++;let d=-1;const{levels:u,loadLevel:h,minAutoLevel:f,maxAutoLevel:g}=i;i.autoLevelEnabled||(i.loadLevel=-1);const m=(n=e.frag)==null?void 0:n.type,v=(m===$.AUDIO&&l===R.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===R.BUFFER_ADD_CODEC_ERROR||l===R.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:k})=>s.audioCodec!==k),b=e.sourceBufferName==="video"&&(l===R.BUFFER_ADD_CODEC_ERROR||l===R.BUFFER_APPEND_ERROR)&&u.some(({codecSet:k,audioCodec:A})=>s.codecSet!==k&&s.audioCodec===A),{type:x,groupId:S}=(a=e.context)!=null?a:{};for(let k=u.length;k--;){const A=(k+h)%u.length;if(A!==h&&A>=f&&A<=g&&u[A].loadError===0){var o,c;const I=u[A];if(l===R.FRAG_GAP&&m===$.MAIN&&e.frag){const w=u[A].details;if(w){const L=_t(e.frag,w.fragments,e.frag.start);if(L!=null&&L.gap)continue}}else{if(x===ee.AUDIO_TRACK&&I.hasAudioGroup(S)||x===ee.SUBTITLE_TRACK&&I.hasSubtitleGroup(S))continue;if(m===$.AUDIO&&(o=s.audioGroups)!=null&&o.some(w=>I.hasAudioGroup(w))||m===$.SUBTITLE&&(c=s.subtitleGroups)!=null&&c.some(w=>I.hasSubtitleGroup(w))||v&&s.audioCodec===I.audioCodec||!v&&s.audioCodec!==I.audioCodec||b&&s.codecSet===I.codecSet)continue}d=A;break}}if(d>-1&&i.loadLevel!==d)return e.levelRetry=!0,this.playlistError=0,{action:we.SendAlternateToPenaltyBox,flags:Ke.None,nextAutoLevel:d}}return{action:we.SendAlternateToPenaltyBox,flags:Ke.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case we.DoNothing:break;case we.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==R.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:s,hdcpLevel:n,nextAutoLevel:a}=i;switch(s){case Ke.None:this.switchLevel(e,a);break;case Ke.MoveAllAlternatesMatchingHDCP:n&&(t.maxHdcpLevel=Bs[Bs.indexOf(n)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(e,a)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===R.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const i=Gn(e.mimeType),s=this.hls.levels;for(let n=s.length;n--;)s[n][`${e.sourceBufferName}Codec`]===i&&this.hls.removeLevel(n)}}}function ri(r){const e={action:we.DoNothing,flags:Ke.None};return r&&(e.resolved=!0),e}var Ae={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class bd{constructor(e){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=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let s=i.length;s--;){const n=i[s];if(!n)break;const a=n.end;if(n.start<=e&&a!==null&&e<=a)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){const{fragments:s}=this,n=Object.keys(s);for(let a=n.length;a--;){const o=s[n[a]];if((o==null?void 0:o.body.type)===t&&(!i||o.buffered)){const c=o.body;if(c.start<=e&&e<=c.end)return c}}return null}detectEvictedFragments(e,t,i,s,n){this.timeRanges&&(this.timeRanges[e]=t);const a=(s==null?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{const c=this.fragments[o];if(!c||a>=c.body.sn)return;if(!c.buffered&&(!c.loaded||n)){c.body.type===i&&this.removeFragment(c.body);return}const l=c.range[e];if(l){if(l.time.length===0){this.removeFragment(c.body);return}l.time.some(d=>{const u=!this.isTimeBuffered(d.startPTS,d.endPTS,t);return u&&this.removeFragment(c.body),u})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const i=e.frag,s=Ot(i),n=this.fragments[s];if(!n||n.buffered&&i.gap)return;const a=!i.relurl;Object.keys(t).forEach(o=>{const c=i.elementaryStreams[o];if(!c)return;const l=t[o],d=a||c.partial===!0;n.range[o]=this.getBufferedTimes(i,e.part,d,l)}),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,(n.body.endList=i.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),Bi(n)||this.removeParts(i.sn-1,i.type)):this.removeFragment(n.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=ia(i,s=>s.fragment.sn>=e))}fragBuffered(e,t){const i=Ot(e);let s=this.fragments[i];!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,s.buffered=!0)}getBufferedTimes(e,t,i,s){const n={time:[],partial:i},a=e.start,o=e.end,c=e.minEndPTS||o,l=e.maxStartPTS||a;for(let d=0;d=u&&c<=h){n.time.push({startPTS:Math.max(a,s.start(d)),endPTS:Math.min(o,s.end(d))});break}else if(au){const f=Math.max(a,s.start(d)),g=Math.min(o,s.end(d));g>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:g}))}else if(o<=u)break}return n}getPartialFragment(e){let t=null,i,s,n,a=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(l=>{const d=c[l];d&&Bi(d)&&(s=d.body.start-o,n=d.body.end+o,e>=s&&e<=n&&(i=Math.min(e-s,n-e),a<=i&&(t=d.body,a=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Bi(t))}getState(e){const t=Ot(e),i=this.fragments[t];return i?i.buffered?Bi(i)?Ae.PARTIAL:Ae.OK:Ae.APPENDING:Ae.NOT_LOADED}isTimeBuffered(e,t,i){let s,n;for(let a=0;a=s&&t<=n)return!0;if(t<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const i=t.frag,s=t.part?null:t,n=Ot(i);this.fragments[n]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:s,timeRanges:n,type:a}=t;if(i.sn==="initSegment")return;const o=i.type;if(s){let l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(s)}this.timeRanges=n;const c=n[a];this.detectEvictedFragments(a,c,o,s)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Ot(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let s=i.length;s--;){const n=t[i[s]];if((n==null?void 0:n.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,s,n){s&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const c=o.body;c.type!==i||s&&!c.gap||c.starte&&(o.buffered||n)&&this.removeFragment(c)})}removeFragment(e){const t=Ot(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const s=e.sn;this.activePartLists[e.type]=ia(i,n=>n.fragment.sn!==s)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e,t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const i=(e=this.hls)==null||(t=e.latestLevelDetails)==null?void 0:t.partList;i&&i.forEach(s=>s.clearElementaryStreamInfo())}}function Bi(r){var e,t,i;return r.buffered&&(r.body.gap||((e=r.range.video)==null?void 0:e.partial)||((t=r.range.audio)==null?void 0:t.partial)||((i=r.range.audiovideo)==null?void 0:i.partial))}function Ot(r){return`${r.type}_${r.level}_${r.sn}`}function ia(r,e){return r.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var mt={cbc:0,ctr:1};class Td{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case mt.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case mt.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function Ed(r){const e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?r.slice(0,e-t):r}class xd{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_(e){const t=new DataView(e),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=t.getUint32(s*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],n=i[1],a=i[2],o=i[3],c=this.invSubMix,l=c[0],d=c[1],u=c[2],h=c[3],f=new Uint32Array(256);let g=0,m=0,y=0;for(y=0;y<256;y++)y<128?f[y]=y<<1:f[y]=y<<1^283;for(y=0;y<256;y++){let v=m^m<<1^m<<2^m<<3^m<<4;v=v>>>8^v&255^99,e[g]=v,t[v]=g;const T=f[g],b=f[T],x=f[b];let S=f[v]*257^v*16843008;s[g]=S<<24|S>>>8,n[g]=S<<16|S>>>16,a[g]=S<<8|S>>>24,o[g]=S,S=x*16843009^b*65537^T*257^g*16843008,l[v]=S<<24|S>>>8,d[v]=S<<16|S>>>16,u[v]=S<<8|S>>>24,h[v]=S,g?(g=T^f[f[f[x^T]]],m^=f[f[m]]):g=m=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,s=0;for(;s{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,i,s);const c=this.flush();c?n(c.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,s)}softwareDecrypt(e,t,i,s){const{currentIV:n,currentResult:a,remainderData:o}=this;if(s!==mt.cbc||t.byteLength!==16)return ie.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Ue(o,e),this.remainderData=null);const c=this.getValidChunk(e);if(!c.length)return null;n&&(i=n);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new xd),l.expandKey(t);const d=a;return this.currentResult=l.decrypt(c.buffer,0,i),this.currentIV=c.slice(-16).buffer,d||null}webCryptoDecrypt(e,t,i,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,s));this.key=t,this.fastAesKey=new Sd(this.subtle,t,s)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Td(this.subtle,new Uint8Array(i),s).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(ie.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i,s)))}onWebCryptoError(e,t,i,s){const n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,s);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%Ld;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(ie.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const sa=Math.pow(2,17);class _d{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const i=e.url;if(!i)return Promise.reject(new ot({type:G.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const s=this.config,n=s.fLoader,a=s.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(g=>g[0]==="GAP")){c(na(e));return}else e.gap=!1;const l=this.loader=n?new n(s):new a(s),d=ra(e);e.loader=l;const u=ta(s.fragLoadPolicy.default),h={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:sa};e.stats=l.stats;const f={onSuccess:(g,m,y,v)=>{this.resetLoader(e,l);let T=g.data;y.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(T.slice(0,16)),T=T.slice(16)),o({frag:e,part:null,payload:T,networkDetails:v})},onError:(g,m,y,v)=>{this.resetLoader(e,l),c(new ot({type:G.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:le({url:i,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:y,stats:v}))},onAbort:(g,m,y)=>{this.resetLoader(e,l),c(new ot({type:G.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:y,stats:g}))},onTimeout:(g,m,y)=>{this.resetLoader(e,l),c(new ot({type:G.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:y,stats:g}))}};t&&(f.onProgress=(g,m,y,v)=>t({frag:e,part:null,payload:y,networkDetails:v})),l.load(d,h,f)})}loadPart(e,t,i){this.abort();const s=this.config,n=s.fLoader,a=s.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(na(e,t));return}const l=this.loader=n?new n(s):new a(s),d=ra(e,t);e.loader=l;const u=ta(s.fragLoadPolicy.default),h={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:sa};t.stats=l.stats,l.load(d,h,{onSuccess:(f,g,m,y)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:f.data,networkDetails:y};i(v),o(v)},onError:(f,g,m,y)=>{this.resetLoader(e,l),c(new ot({type:G.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:le({url:d.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:m,stats:y}))},onAbort:(f,g,m)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new ot({type:G.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:m,stats:f}))},onTimeout:(f,g,m)=>{this.resetLoader(e,l),c(new ot({type:G.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:m,stats:f}))}})})}updateStatsFromPart(e,t){const i=e.stats,s=t.stats,n=s.total;if(i.loaded+=s.loaded,n){const c=Math.round(e.duration/t.duration),l=Math.min(Math.round(i.loaded/n),c),u=(c-l)*Math.round(i.loaded/l);i.total=i.loaded+u}else i.total=Math.max(i.loaded,i.total);const a=i.loading,o=s.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function ra(r,e=null){const t=e||r,i={frag:r,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},s=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(B(s)&&B(n)){var a;let o=s,c=n;if(r.sn==="initSegment"&&Id((a=r.decryptdata)==null?void 0:a.method)){const l=n-s;l%16&&(c=n+(16-l%16)),s!==0&&(i.resetIV=!0,o=s-16)}i.rangeStart=o,i.rangeEnd=c}return i}function na(r,e){const t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),i={type:G.MEDIA_ERROR,details:R.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(i.part=e),(e||r).stats.aborted=!0,new ot(i)}function Id(r){return r==="AES-128"||r==="AES-256"}class ot extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class aa extends at{constructor(e,t){super(e,t),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(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Vs{constructor(e,t,i,s=0,n=-1,a=!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=Ui(),this.buffering={audio:Ui(),video:Ui(),audiovideo:Ui()},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=n,this.partial=a}}function Ui(){return{start:0,executeStart:0,executeEnd:0,end:0}}const oa={length:0,start:()=>0,end:()=>0};class J{static isBuffered(e,t){if(e){const i=J.getBuffered(e);for(let s=i.length;s--;)if(t>=i.start(s)&&t<=i.end(s))return!0}return!1}static bufferedRanges(e){if(e){const t=J.getBuffered(e);return J.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let i=0;i1&&e.sort((d,u)=>d.start-u.start||u.end-d.end);let s=-1,n=[];if(i)for(let d=0;d=e[d].start&&t<=e[d].end&&(s=d);const u=n.length;if(u){const h=n[u-1].end;e[d].start-hh&&(n[u-1].end=e[d].end):n.push(e[d])}else n.push(e[d])}else n=e;let a=0,o,c=t,l=t;for(let d=0;d=u&&t<=h&&(s=d),t+i>=u&&t{const s=i.substring(2,i.length-1),n=t==null?void 0:t[s];return n===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),i):n})}return e}function da(r,e,t){let i=r.variableList;i||(r.variableList=i={});let s,n;if("QUERYPARAM"in e){s=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(s))n=a.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${t}"`)}catch(a){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else s=e.NAME,n=e.VALUE;s in i?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):i[s]=n||""}function Rd(r,e,t){const i=e.IMPORT;if(t&&i in t){let s=r.variableList;s||(r.variableList=s={}),s[i]=t[i]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const kd=/^(\d+)x(\d+)$/,ua=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ve{constructor(e,t){typeof e=="string"&&(e=ve.parseAttrList(e,t)),ue(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const i=new Uint8Array(t.length/2);for(let s=0;sNumber.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((s,n)=>(s[n.toLowerCase()]=!0,s),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=kd.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const s={},n='"';for(ua.lastIndex=0;(i=ua.exec(e))!==null;){const a=i[1].trim();let o=i[2];const c=o.indexOf(n)===0&&o.lastIndexOf(n)===o.length-1;let l=!1;if(c)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(c||l))o=Hs(t,o);else if(!l&&!c)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")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":ie.warn(`${e}: attribute ${a} is missing quotes`)}s[a]=o}return s}}const wd="com.apple.hls.interstitial";function Cd(r){return r!=="ID"&&r!=="CLASS"&&r!=="CUE"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function Dd(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"||r==="SCTE35-CMD"}class ha{constructor(e,t,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=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(s=t==null?void 0:t.tagOrder)!=null?s:i,t){const n=t.attr;for(const a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){ie.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=ue(new ve({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const n=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);B(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(ie.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(B(e))return e}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 this.class===wd}get isValid(){return!!this.id&&!this._badValueForSameId&&B(this.startDate.getTime())&&(this.duration===null||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)}}const Pd=10;class Od{constructor(e){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=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}get hasProgramDateTime(){return this.fragments.length?B(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Pd}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function Mt(r){return r==="AES-128"||r==="AES-256"||r==="AES-256-CTR"}function Ks(r){switch(r){case"AES-128":case"AES-256":return mt.cbc;case"AES-256-CTR":return mt.ctr;default:throw new Error(`invalid full segment method ${r}`)}}function Ws(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function Ys(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}function Md(r){const e=Ys(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Fd(r){const e=function(i,s,n){const a=i[s];i[s]=i[n],i[n]=a};e(r,0,3),e(r,1,2),e(r,4,5),e(r,6,7)}function Nd(r){const e=r.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),s=i[i.length-1].split(",");if(s.length===2){const n=s[0]==="base64",a=s[1];n?(i.splice(-1,1),t=Ws(a)):t=Md(a)}}return t}const $i=typeof self!="undefined"?self:void 0;var ce={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Pe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function js(r){switch(r){case Pe.FAIRPLAY:return ce.FAIRPLAY;case Pe.PLAYREADY:return ce.PLAYREADY;case Pe.WIDEVINE:return ce.WIDEVINE;case Pe.CLEARKEY:return ce.CLEARKEY}}var Gi={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function qs(r){if(r===Gi.WIDEVINE)return ce.WIDEVINE;if(r===Gi.PLAYREADY)return ce.PLAYREADY;if(r===Gi.CENC||r===Gi.CLEARKEY)return ce.CLEARKEY}function zs(r){switch(r){case ce.FAIRPLAY:return Pe.FAIRPLAY;case ce.PLAYREADY:return Pe.PLAYREADY;case ce.WIDEVINE:return Pe.WIDEVINE;case ce.CLEARKEY:return Pe.CLEARKEY}}function Vi(r){const{drmSystems:e,widevineLicenseUrl:t}=r,i=e?[ce.FAIRPLAY,ce.WIDEVINE,ce.PLAYREADY,ce.CLEARKEY].filter(s=>!!e[s]):[];return!i[ce.WIDEVINE]&&t&&i.push(ce.WIDEVINE),i}const fa=function(r){return $i!=null&&(r=$i.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Bd(r,e,t,i){let s;switch(r){case ce.FAIRPLAY:s=["cenc","sinf"];break;case ce.WIDEVINE:case ce.PLAYREADY:s=["cenc"];break;case ce.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return Ud(s,e,t,i)}function Ud(r,e,t,i){return[{initDataTypes:r,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function $d(r){var e;return r.sessionType==="persistent-license"||!!((e=r.sessionTypes)!=null&&e.some(t=>t==="persistent-license"))}function ga(r){const e=new Uint16Array(r.buffer,r.byteOffset,r.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),i=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(a){const o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){const c=Ws(o).subarray(0,16);return Fd(c),c}}return null}let Hi={};class ni{static clearKeyUriToKeyIdMap(){Hi={}}constructor(e,t,i,s=[1],n=null){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=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=s,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Mt(e)}isSupported(){if(this.method){if(Mt(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Pe.FAIRPLAY:case Pe.WIDEVINE:case Pe.PLAYREADY:case Pe.CLEARKEY:return["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(Mt(this.method)&&this.uri&&!this.iv){typeof e!="number"&&(ie.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const i=Gd(e);return new ni(this.method,this.uri,"identity",this.keyFormatVersions,i)}const t=Nd(this.uri);if(t)switch(this.keyFormat){case Pe.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Pe.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Yc(i,null,t),this.keyId=ga(t);break}default:{let i=t.subarray(0,16);if(i.length!==16){const s=new Uint8Array(16);s.set(i,16-i.length),i=s}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=Hi[this.uri];if(!i){const s=Object.keys(Hi).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,s),Hi[this.uri]=i}this.keyId=i}return this}}function Gd(r){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}const pa=/#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,ma=/#EXT-X-MEDIA:(.*)/g,Vd=/^#EXT(?:INF|-X-TARGETDURATION):/m,Xs=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Hd=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 et{static findGroup(e,t){for(let i=0;i0&&n.length({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:a.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(ma.lastIndex=0;(s=ma.exec(e))!==null;){const l=new ve(s[1],i),d=l.TYPE;if(d){const u=o[d],h=n[d]||[];n[d]=h;const f=l.LANGUAGE,g=l["ASSOC-LANGUAGE"],m=l.CHANNELS,y=l.CHARACTERISTICS,v=l["INSTREAM-ID"],T={attrs:l,bitrate:0,id:c++,groupId:l["GROUP-ID"]||"",name:l.NAME||f||"",type:d,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:f,url:l.URI?et.resolve(l.URI,t):""};if(g&&(T.assocLang=g),m&&(T.channels=m),y&&(T.characteristics=y),v&&(T.instreamId=v),u!=null&&u.length){const b=et.findGroup(u,T.groupId)||u[0];Ea(T,b,"audioCodec"),Ea(T,b,"textCodec")}h.push(T)}}return n}static parseLevelPlaylist(e,t,i,s,n,a){var o;const c={url:t},l=new Od(t),d=l.fragments,u=[];let h=null,f=0,g=0,m=0,y=0,v=0,T=null,b=new Ds(s,c),x,S,k,A=-1,I=!1,w=null,L;if(Xs.lastIndex=0,l.m3u8=e,l.hasVariableRefs=ca(e),((o=Xs.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(x=Xs.exec(e))!==null;){I&&(I=!1,b=new Ds(s,c),b.playlistOffset=m,b.start=m,b.sn=f,b.cc=y,v&&(b.bitrate=v),b.level=i,h&&(b.initSegment=h,h.rawProgramDateTime&&(b.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),w&&(b.setByteRange(w),w=null)));const Y=x[1];if(Y){b.duration=parseFloat(Y);const H=(" "+x[2]).slice(1);b.title=H||null,b.tagList.push(H?["INF",Y,H]:["INF",Y])}else if(x[3]){if(B(b.duration)){b.playlistOffset=m,b.start=m,k&&Sa(b,k,l),b.sn=f,b.level=i,b.cc=y,d.push(b);const H=(" "+x[3]).slice(1);b.relurl=Hs(l,H),Qs(b,T,u),T=b,m+=b.duration,f++,g=0,I=!0}}else{if(x=x[0].match(Hd),!x){ie.warn("No matches on slow regex match for level playlist!");continue}for(S=1;S0&&Aa(l,H,x),f=l.startSN=parseInt(U);break;case"SKIP":{l.skippedSegments&<(l,H,x);const V=new ve(U,l),P=V.decimalInteger("SKIPPED-SEGMENTS");if(B(P)){l.skippedSegments+=P;for(let X=P;X--;)d.push(null);f+=P}const O=V.enumeratedString("RECENTLY-REMOVED-DATERANGES");O&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(O.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&<(l,H,x),l.targetduration=Math.max(parseInt(U),1);break;case"VERSION":l.version!==null&<(l,H,x),l.version=parseInt(U);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||lt(l,H,x),l.live=!1;break;case"#":(U||K)&&b.tagList.push(K?[U,K]:[U]);break;case"DISCONTINUITY":y++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([H]);break;case"BITRATE":b.tagList.push([H,U]),v=parseInt(U)*1e3,B(v)?b.bitrate=v:v=0;break;case"DATERANGE":{const V=new ve(U,l),P=new ha(V,l.dateRanges[V.ID],l.dateRangeTagCount);l.dateRangeTagCount++,P.isValid||l.skippedSegments?l.dateRanges[P.id]=P:ie.warn(`Ignoring invalid DATERANGE tag: "${U}"`),b.tagList.push(["EXT-X-DATERANGE",U]);break}case"DEFINE":{{const V=new ve(U,l);"IMPORT"in V?Rd(l,V,a):da(l,V,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?lt(l,H,x):d.length>0&&Aa(l,H,x),l.startCC=y=parseInt(U);break;case"KEY":{const V=va(U,t,l);if(V.isSupported()){if(V.method==="NONE"){k=void 0;break}k||(k={}),k[V.keyFormat]&&(k=ue({},k)),k[V.keyFormat]=V}else ie.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${U}"`);break}case"START":l.startTimeOffset=ba(U);break;case"MAP":{const V=new ve(U,l);if(b.duration){const P=new Ds(s,c);xa(P,V,i,k),h=P,b.initSegment=h,h.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=h.rawProgramDateTime)}else{const P=b.byteRangeEndOffset;if(P){const O=b.byteRangeStartOffset;w=`${P-O}@${O}`}else w=null;xa(b,V,i,k),h=b,I=!0}h.cc=y;break}case"SERVER-CONTROL":{L&<(l,H,x),L=new ve(U),l.canBlockReload=L.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=L.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&L.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=L.optionalFloat("PART-HOLD-BACK",0),l.holdBack=L.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&<(l,H,x);const V=new ve(U);l.partTarget=V.decimalFloatingPoint("PART-TARGET");break}case"PART":{let V=l.partList;V||(V=l.partList=[]);const P=g>0?V[V.length-1]:void 0,O=g++,X=new ve(U,l),q=new Cc(X,b,c,O,P);V.push(q),b.duration+=q.duration;break}case"PRELOAD-HINT":{const V=new ve(U,l);l.preloadHint=V;break}case"RENDITION-REPORT":{const V=new ve(U,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(V);break}default:ie.warn(`line parsed but not handled: ${x}`);break}}}T&&!T.relurl?(d.pop(),m-=T.duration,l.partList&&(l.fragmentHint=T)):l.partList&&(Qs(b,T,u),b.cc=y,l.fragmentHint=b,k&&Sa(b,k,l)),l.targetduration||(l.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const D=d.length,M=d[0],te=d[D-1];if(m+=l.skippedSegments*l.targetduration,m>0&&D&&te){l.averagetargetduration=m/D;const Y=te.sn;l.endSN=Y!=="initSegment"?Y:0,l.live||(te.endList=!0),M&&l.startCC===void 0&&(l.startCC=M.cc),A>0&&(Wd(d,A),M&&u.unshift(M))}else l.endSN=0,l.startCC=0;return l.fragmentHint&&(m+=l.fragmentHint.duration),l.totalduration=m,u.length&&l.dateRangeTagCount&&M&&ya(u,l),l.endCC=y,l}}function ya(r,e){const t=r.length,i=r[t-1],s=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let a=n.length;a--;){const o=e.dateRanges[n[a]],c=o.startDate.getTime();o.tagAnchor=i.ref;for(let l=t;l--;){const d=Kd(e,c,r,l,s);if(d!==-1){o.tagAnchor=e.fragments[d].ref;break}}}}function Kd(r,e,t,i,s){const n=t[i];if(n){const o=n.programDateTime;if(e>=o||i===0){var a;const c=(((a=t[i+1])==null?void 0:a.start)||s)-n.start;if(e<=o+c*1e3){const l=t[i].sn-r.startSN,d=r.fragments;if(d.length>t.length){const h=(t[i+1]||d[d.length-1]).sn-r.startSN;for(let f=h;f>l;f--){const g=d[f].programDateTime;if(e>=g&&ei);["video","audio","text"].forEach(i=>{const s=t.filter(n=>Nn(n,i));s.length&&(e[`${i}Codec`]=s.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>s.indexOf(n)===-1))}),e.unknownCodecs=t}function Ea(r,e,t){const i=e[t];i&&(r[t]=i)}function Wd(r,e){let t=r[e];for(let i=e;i--;){const s=r[i];if(!s)return;s.programDateTime=t.programDateTime-s.duration*1e3,t=s}}function Qs(r,e,t){r.rawProgramDateTime?t.push(r):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime)}function xa(r,e,t,i){r.relurl=e.URI,e.BYTERANGE&&r.setByteRange(e.BYTERANGE),r.level=t,r.sn="initSegment",i&&(r.levelkeys=i),r.initSegment=null}function Sa(r,e,t){r.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(s=>e[s].isCommonEncryption)&&i.push(r)}function lt(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function Aa(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Js(r,e){const t=e.startPTS;if(B(t)){let i=0,s;e.sn>r.sn?(i=t-r.start,s=r):(i=r.start-t,s=e),s.duration!==i&&s.setDuration(i)}else e.sn>r.sn?r.cc===e.cc&&r.minEndPTS?e.setStart(r.start+(r.minEndPTS-r.start)):e.setStart(r.start+r.duration):e.setStart(Math.max(r.start-e.duration,0))}function La(r,e,t,i,s,n){i-t<=0&&(ie.warn("Fragment should have a positive duration",e),i=t+e.duration,n=s+e.duration);let o=t,c=i;const l=e.startPTS,d=e.endPTS;if(B(l)){const y=Math.abs(l-t);B(e.deltaPTS)?e.deltaPTS=Math.max(y,e.deltaPTS):e.deltaPTS=y,o=Math.max(t,l),t=Math.min(t,l),s=Math.min(s,e.startDTS),c=Math.min(i,d),i=Math.max(i,d),n=Math.max(n,e.endDTS)}const u=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=o,e.startDTS=s,e.endPTS=i,e.minEndPTS=c,e.endDTS=n;const h=e.sn;if(!r||hr.endSN)return 0;let f;const g=h-r.startSN,m=r.fragments;for(m[g]=e,f=g;f>0;f--)Js(m[f],m[f-1]);for(f=g;f=0;c--){const l=i[c].initSegment;if(l){t=l;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let s;zd(r,e,(c,l,d,u)=>{if(!e.startCC&&l.cc!==c.cc){var h,f;const g=c.cc-l.cc;for(let m=d;m{var l;c&&(!c.initSegment||c.initSegment.relurl===((l=t)==null?void 0:l.relurl))&&(c.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=n.some(c=>!c),e.deltaUpdateFailed){ie.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let c=e.skippedSegments;c--;)n.shift();e.startSN=n[0].sn}else{e.endCC=n[n.length-1].cc,e.canSkipDateRanges&&(e.dateRanges=jd(r.dateRanges,e));const c=r.fragments.filter(l=>l.rawProgramDateTime);if(r.hasProgramDateTime&&!e.hasProgramDateTime)for(let l=1;l{l.elementaryStreams=c.elementaryStreams,l.stats=c.stats}),s?La(e,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):Ia(r,e),n.length&&(e.totalduration=e.edge-n[0].start),e.driftStartTime=r.driftStartTime,e.driftStart=r.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const c=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=c),e.driftEndTime=o,e.driftEnd=c}else e.driftEndTime=r.driftEndTime,e.driftEnd=r.driftEnd,e.advancedDateTime=r.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=r.requestScheduled)}function jd(r,e){const{dateRanges:t,recentlyRemovedDateranges:i}=e,s=ue({},r);i&&i.forEach(o=>{delete s[o]});const a=Object.keys(s).length;return a&&Object.keys(t).forEach(o=>{const c=s[o],l=new ha(t[o].attr,c);l.isValid?(s[o]=l,c||(l.tagOrder+=a)):ie.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${me(t[o].attr)}"`)}),s}function qd(r,e,t){if(r&&e){let i=0;for(let s=0,n=r.length;s<=n;s++){const a=r[s],o=e[s+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--}}}function zd(r,e,t){const i=e.skippedSegments,s=Math.max(r.startSN,e.startSN)-e.startSN,n=(r.fragmentHint?1:0)+(i?e.endSN:Math.min(r.endSN,e.endSN))-e.startSN,a=e.startSN-r.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=r.fragmentHint?r.fragments.concat(r.fragmentHint):r.fragments;for(let l=s;l<=n;l++){const d=c[a+l];let u=o[l];if(i&&!u&&d&&(u=e.fragments[l]=d),d&&u){if(t(d,u,l,o),d.url&&d.url!==u.url){e.playlistParsingError=_a(`media sequence mismatch ${u.sn}:`,r,e,d,u);return}else if(d.cc!==u.cc){e.playlistParsingError=_a(`discontinuity sequence mismatch (${d.cc}!=${u.cc})`,r,e,d,u);return}}}}function _a(r,e,t,i,s){return new Error(`${r} ${s.url} Playlist starting @${e.startSN} ${e.m3u8} Playlist starting @${t.startSN} ${t.m3u8}`)}function Ia(r,e,t=!0){const i=e.startSN+e.skippedSegments-r.startSN,s=r.fragments,n=i>=0;let a=0;if(n&&ie){const n=i[i.length-1].duration*1e3;n{var i;(i=e.details)==null||i.fragments.forEach(s=>{s.level=t,s.initSegment&&(s.initSegment.level=t)})})}function ai(r,e){for(let i=0,s=r.length;ir.startCC)}function Pa(r,e){if(r){const t=r.start+e;r.start=r.startPTS=t,r.endPTS=t+r.duration}}function Oa(r,e){const t=e.fragments;for(let i=0,s=t.length;i{const{config:a,fragCurrent:o,media:c,mediaBuffer:l,state:d}=this,u=c?c.currentTime:0,h=J.bufferInfo(l||c,u,a.maxBufferHole);if(this.log(`media seeking to ${B(u)?u.toFixed(3):u}, state: ${d}`),this.state===C.ENDED)this.resetLoadingState();else if(o){const f=a.maxFragLookUpTolerance,g=o.start-f,m=o.start+o.duration+f;if(!h.len||mh.end){const y=u>m;(uf&&(this.lastCurrentTime=u),!this.loadingParts){const g=Math.max(h.end,u),m=this.shouldLoadParts(this.getLevelDetails(),g);m&&(this.log(`LL-Part loading ON after seeking to ${u.toFixed(2)} with buffer @${g.toFixed(2)}`),this.loadingParts=m)}}!this.hls.hasEnoughToStart&&!h.len&&(this.log(`setting startPosition to ${u} because of seek before start`),this.nextLoadPosition=this.startPosition=u),this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=e,this.fragmentLoader=new _d(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Gs(e.config)}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===C.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=C.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;const n=e.nextStart;if(n&&n>s&&n{const a=n.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,!1,n.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,i,s).then(n=>{if(!n)return;const a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===C.FRAG_LOADING||!this.fragCurrent&&a===C.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=C.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(p.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(`Frag error: ${(n==null?void 0:n.message)||n}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===Ae.APPENDING){const n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===Ae.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const s={startOffset:e,endOffset:t,type:i};this.hls.trigger(p.BUFFER_FLUSHING,s)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{const s=i==null?void 0:i.frag;if(!s||this.fragContextChanged(s)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:s}=this,{frag:n,payload:a}=i,o=n.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&Mt(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,Ks(o.method)).catch(l=>{throw s.trigger(p.ERROR,{type:G.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:n}),l}).then(l=>{const d=self.performance.now();return s.trigger(p.FRAG_DECRYPTED,{frag:n,payload:l,stats:{tstart:c,tdecrypt:d}}),i.payload=l,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state!==C.STOPPED&&(this.state=C.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?Jd.toString(J.getBuffered(i)):"(detached)"})`),Ie(e)){var s;if(e.type!==$.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=C.IDLE;return}}const n=(s=this.levels)==null?void 0:s[e.level];n!=null&&n.fragmentError&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0)}this.state=C.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:s,partsLoaded:n}=e,a=!n||n.length===0||n.some(c=>!c),o=new Vs(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,s){var n;this.fragCurrent=e;const a=t==null?void 0:t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;e.encrypted&&!((n=e.decryptdata)!=null&&n.key)?(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=C.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(u=>{if(!this.fragContextChanged(u.frag))return this.hls.trigger(p.KEY_LOADED,u),this.state===C.KEY_LOADING&&(this.state=C.IDLE),u}),this.hls.trigger(p.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(e,a.encryptedFragments);const c=this.fragPrevious;if(Ie(e)&&(!c||e.sn!==c.sn)){const u=this.shouldLoadParts(t.details,e.end);u!==this.loadingParts&&(this.log(`LL-Part loading ${u?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${e.sn}`),this.loadingParts=u)}if(i=Math.max(e.start,i||0),this.loadingParts&&Ie(e)){const u=a.partList;if(u&&s){i>e.end&&a.fragmentHint&&(e=a.fragmentHint);const h=this.getNextPart(u,e,i);if(h>-1){const f=u[h];e=this.fragCurrent=f.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${f.index} (${h}/${u.length-1}) of ${this.fragInfo(e,!1,f)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=f.start+f.duration,this.state=C.FRAG_LOADING;let g;return o?g=o.then(m=>!m||this.fragContextChanged(m.frag)?null:this.doFragPartsLoad(e,f,t,s)).catch(m=>this.handleFragLoadError(m)):g=this.doFragPartsLoad(e,f,t,s).catch(m=>this.handleFragLoadError(m)),this.hls.trigger(p.FRAG_LOADING,{frag:e,part:f,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):g}else if(!e.url||this.loadedEndOfParts(u,i))return Promise.resolve(null)}}if(Ie(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${a?"["+a.startSN+"-"+a.endSN+"]":""}, target: ${parseFloat(i.toFixed(3))}`),B(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=C.FRAG_LOADING;const l=this.config.progressive;let d;return l&&o?d=o.then(u=>!u||this.fragContextChanged(u==null?void 0:u.frag)?null:this.fragmentLoader.load(e,s)).catch(u=>this.handleFragLoadError(u)):d=Promise.all([this.fragmentLoader.load(e,l?s:void 0),o]).then(([u])=>(!l&&u&&s&&s(u),u)).catch(u=>this.handleFragLoadError(u)),this.hls.trigger(p.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):d}doFragPartsLoad(e,t,i,s){return new Promise((n,a)=>{var o;const c=[],l=(o=i.details)==null?void 0:o.partList,d=u=>{this.fragmentLoader.loadPart(e,u,s).then(h=>{c[u.index]=h;const f=h.part;this.hls.trigger(p.FRAG_LOADED,h);const g=wa(i.details,e.sn,u.index+1)||Ca(l,e.sn,u.index+1);if(g)d(g);else return n({frag:e,part:f,partsLoaded:c})}).catch(a)};d(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===R.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(p.ERROR,t)}else this.hls.trigger(p.ERROR,{type:G.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==C.PARSING){!this.fragCurrent&&this.state!==C.STOPPED&&this.state!==C.ERROR&&(this.state=C.IDLE);return}const{frag:i,part:s,level:n}=t,a=self.performance.now();i.stats.parsing.end=a,s&&(s.stats.parsing.end=a);const o=this.getLevelDetails(),l=o&&i.sn>o.endSN||this.shouldLoadParts(o,i.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(i,s,n,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e!=null&&e.partList){var i;const n=e.partList[0],a=n.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=a){var s;if((this.hls.hasEnoughToStart?((s=this.media)==null?void 0:s.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:s,sn:n,part:a}=e;if(!(t!=null&&t[s]))return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const o=t[s],c=o.details,l=a>-1?wa(c,n,a):null,d=l?l.fragment:ka(c,n,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:l,level:o}):null}bufferFragmentData(e,t,i,s,n){var a;if(!e||this.state!==C.PARSING)return;const{data1:o,data2:c}=e;let l=o;if(o&&c&&(l=Ue(o,c)),!((a=l)!=null&&a.length))return;const d={type:e.type,frag:t,part:i,chunkMeta:s,parent:t.type,data:l};if(this.hls.trigger(p.BUFFER_APPENDING,d),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!J.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,s=J.bufferInfo(t,i,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,s.end-a),i+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var i;const s=this.getLoadPosition();if(!B(s))return null;const a=this.lastCurrentTime>s||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,a)}getFwdBufferInfoAtPos(e,t,i,s){const n=J.bufferInfo(e,t,s);if(n.len===0&&n.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(n.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(n.nextStart,a.end)-t,s);return J.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const i=this.config,s=Math.max(Math.min(e-t,i.maxBufferLength),t),n=Math.max(e-t*3,i.maxMaxBufferLength/2,s);return n>=s?(i.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0):!1}getAppendedFrag(e,t=$.MAIN){var i;const s=(i=this.fragmentTracker)==null?void 0:i.getAppendedFrag(e,t);return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const i=t.fragments,s=i.length;if(!s)return null;const{config:n}=this,a=i[0].start,o=n.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const u=n.initialLiveManifestSize;if(s=a?h:f)||c.start:e;this.log(`Setting startPosition to ${g} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${f} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=g}}else e<=a&&(c=i[0]);if(!c){const u=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,u,t)}let d=this.filterReplacedPrimary(c,t);if(!d&&c){const u=c.sn-t.startSN;d=this.filterReplacedPrimary(i[u+1]||null,t)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===Ae.OK||i===Ae.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,s,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&i.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(o!==null&&i.len+o.len>=n){const c=a.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(Fa(this.hls.config)){var e,t;if((e=this.hls.interstitialsManager)==null||(t=e.playingItem)==null?void 0:t.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Fa(this.hls.config)&&e.type!==$.SUBTITLE){const i=this.hls.interstitialsManager,s=i==null?void 0:i.bufferingItem;if(s){const a=s.event;if(a){if(a.appendInPlace||Math.abs(e.start-s.start)>1||s.start===0)return null}else if(e.end<=s.start&&(t==null?void 0:t.live)===!1||e.start>s.end&&s.nextEvent&&(s.nextEvent.appendInPlace||e.start-s.end>1))return null}const n=i==null?void 0:i.playerQueue;if(n)for(let a=n.length;a--;){const o=n[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let s=-1,n=!1,a=!0;for(let o=0,c=e.length;o-1&&ii.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let s=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=fd(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){const a=t[n-e.startSN];i.cc===a.cc&&(s=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=Zn(t,i.cc),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const n=this.hls.liveSyncPosition;n!==null&&(s=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){const{config:s}=this;let{fragPrevious:n}=this,{fragments:a,endSN:o}=i;const{fragmentHint:c}=i,{maxFragLookUpTolerance:l}=s,d=i.partList,u=!!(this.loadingParts&&d!=null&&d.length&&c);u&&c&&!this.bitrateTest&&d[d.length-1].fragment.sn===c.sn&&(a=a.concat(c),o=c.sn);let h;if(et-l||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:l;h=_t(n,a,e,m)}else h=a[a.length-1];if(h){const g=h.sn-i.startSN,m=this.fragmentTracker.getState(h);if((m===Ae.OK||m===Ae.PARTIAL&&h.gap)&&(n=h),n&&h.sn===n.sn&&(!u||d[0].fragment.sn>h.sn||!i.live&&!u)&&n&&h.level===n.level){const v=a[g+1];h.sn${e.startSN} fragments: ${s}`),c}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ie(e)&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==C.FRAG_LOADING_WAITING_RETRY)&&(this.state=C.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const g=this.getCurrentContext(t.chunkMeta);g&&(t.frag=g.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var s;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(s=this.fragCurrent)==null?void 0:s.url}`);return}const n=t.details===R.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const a=t.errorAction,{action:o,flags:c,retryCount:l=0,retryConfig:d}=a||{},u=!!a&&!!d,h=u&&o===we.RetryRequest,f=u&&!a.resolved&&c===Ke.MoveAllAlternatesMatchingHost;if(!h&&f&&Ie(i)&&!i.endList)this.resetFragmentErrors(e),this.treatAsGap(i),a.resolved=!0;else if((h||f)&&l.5;n&&this.reduceMaxBufferLength(s.len,(t==null?void 0:t.duration)||10);const a=!n;return a&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===$.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==C.STOPPED&&(this.state=C.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const s=J.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,i),this.state===C.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==C.STOPPED&&(this.state=C.IDLE)}resetStartWhenNotLoaded(e){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of ${this.playlistLabel()} ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){const n=i.details;if(!n){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,l)=>{const d=e.elementaryStreams[l];if(d){const u=d.endPTS-d.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${u})`),c||!1;const h=s?0:La(n,e,d.startPTS,d.endPTS,d.startDTS,d.endDTS);return this.hls.trigger(p.LEVEL_PTS_UPDATED,{details:n,level:i,drift:h,type:l,frag:e,start:d.startPTS,end:d.endPTS}),!0}return c},!1)){var o;if(i.fragmentError===0&&this.treatAsGap(e,i),((o=this.transmuxer)==null?void 0:o.error)===null){const c=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(c.message),this.hls.trigger(p.ERROR,{type:G.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:c,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=C.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(p.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===$.MAIN?"level":"track"}fragInfo(e,t=!0,i){var s,n;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((s=t&&!i?e.startPTS:(i||e).start)!=null?s:NaN).toFixed(3)}-${((n=t&&!i?e.endPTS:(i||e).end)!=null?n:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function Fa(r){return!!r.interstitialsController&&r.enableInterstitialPlayback!==!1}class Na{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=Zd(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function Zd(r,e){const t=new Uint8Array(e);let i=0;for(let s=0;s0)return r.subarray(t,t+i)}function au(r,e,t,i){const s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=e[t+2],a=n>>2&15;if(a>12){const f=new Error(`invalid ADTS sampling index:${a}`);r.emit(p.ERROR,p.ERROR,{type:G.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(n>>6&3)+1,c=e[t+3]>>6&3|(n&1)<<2,l="mp4a.40."+o,d=s[a];let u=a;(o===5||o===29)&&(u-=3);const h=[o<<3|(u&14)>>1,(u&1)<<7|c<<3];return ie.log(`manifest codec:${i}, parsed codec:${l}, channels:${c}, rate:${d} (ADTS object type:${o} sampling index:${a})`),{config:h,samplerate:d,channelCount:c,codec:l,parsedCodec:l,manifestCodec:i}}function $a(r,e){return r[e]===255&&(r[e+1]&246)===240}function Ga(r,e){return r[e+1]&1?7:9}function rr(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function ou(r,e){return e+5=r.length)return!1;const i=rr(r,e);if(i<=t)return!1;const s=e+i;return s===r.length||Yi(r,s)}return!1}function Va(r,e,t,i,s){if(!r.samplerate){const n=au(e,t,i,s);if(!n)return;ue(r,n)}}function Ha(r){return 1024*9e4/r}function du(r,e){const t=Ga(r,e);if(e+t<=r.length){const i=rr(r,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function Ka(r,e,t,i,s){const n=Ha(r.samplerate),a=i+s*n,o=du(e,t);let c;if(o){const{frameLength:u,headerLength:h}=o,f=h+u,g=Math.max(0,t+f-e.length);g?(c=new Uint8Array(f-h),c.set(e.subarray(t+h,e.length),0)):c=e.subarray(t+h,t+f);const m={unit:c,pts:a};return g||r.samples.push(m),{sample:m,length:f,missing:g}}const l=e.length-t;return c=new Uint8Array(l),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:a},length:l,missing:-1}}function uu(r,e){return sr(r,e)&&Wi(r,e+6)+10<=r.length-e}function hu(r){if(r.size<2)return;const e=Ne(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}}function fu(r){if(r.size<2)return;if(r.type==="TXXX"){let t=1;const i=Ne(r.data.subarray(t),!0);t+=i.length+1;const s=Ne(r.data.subarray(t));return{key:r.type,info:i,data:s}}const e=Ne(r.data.subarray(1));return{key:r.type,info:"",data:e}}function gu(r){if(r.type==="WXXX"){if(r.size<2)return;let t=1;const i=Ne(r.data.subarray(t),!0);t+=i.length+1;const s=Ne(r.data.subarray(t));return{key:r.type,info:i,data:s}}const e=Ne(r.data);return{key:r.type,info:"",data:e}}function pu(r){return btoa(String.fromCharCode(...r))}function Wa(r,e){if(r<0)return-Wa(-r,e);const t=Math.pow(10,e);if(Math.abs(r*t%1-.5){const n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(s=="x"?n:n&3|8).toString(16)})}}}function vu(r){return r instanceof ArrayBuffer?r:r.byteOffset==0&&r.byteLength==r.buffer.byteLength?r.buffer:new Uint8Array(r).buffer}function nr(r,e=0,t=1/0){return bu(r,e,t,Uint8Array)}function bu(r,e,t,i){const s=Tu(r);let n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);const a=Eu(r)?r.byteOffset:0,o=(a+r.byteLength)/n,c=(a+e)/n,l=Math.floor(Math.max(0,Math.min(c,o))),d=Math.floor(Math.min(l+Math.max(t,0),o));return new i(s,l,d-l)}function Tu(r){return r instanceof ArrayBuffer?r:r.buffer}function Eu(r){return r&&r.buffer instanceof ArrayBuffer&&r.byteLength!==void 0&&r.byteOffset!==void 0}function xu(r){const e={key:r.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(r.size<2)return;if(r.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const i=r.data.subarray(1).indexOf(0);if(i===-1)return;const s=Ne(nr(r.data,1,i)),n=r.data[2+i],a=r.data.subarray(3+i).indexOf(0);if(a===-1)return;const o=Ne(nr(r.data,3+i,a));let c;return s==="-->"?c=Ne(nr(r.data,4+i+a)):c=vu(r.data.subarray(4+i+a)),e.mimeType=s,e.pictureType=n,e.description=o,e.data=c,e}function Su(r){return r.type==="PRIV"?hu(r):r.type[0]==="W"?gu(r):r.type==="APIC"?xu(r):fu(r)}function Au(r){const e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=Wi(r,4),i=10;return{type:e,size:t,data:r.subarray(i,i+t)}}const ji=10,Lu=10;function Ya(r){let e=0;const t=[];for(;sr(r,e);){const i=Wi(r,e+6);r[e+5]>>6&1&&(e+=ji),e+=ji;const s=e+i;for(;e+Lu0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Be.audioId3,duration:Number.POSITIVE_INFINITY});s{if(B(r))return r*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};let qi=null;const Ru=[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],ku=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],wu=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Cu=[0,1,1,4];function qa(r,e,t,i,s){if(t+24>e.length)return;const n=za(e,t);if(n&&t+n.frameLength<=e.length){const a=n.samplesPerFrame*9e4/n.sampleRate,o=i+s*a,c={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return r.config=[],r.channelCount=n.channelCount,r.samplerate=n.sampleRate,r.samples.push(c),{sample:c,length:n.frameLength,missing:0}}}function za(r,e){const t=r[e+1]>>3&3,i=r[e+1]>>1&3,s=r[e+2]>>4&15,n=r[e+2]>>2&3;if(t!==1&&s!==0&&s!==15&&n!==3){const a=r[e+2]>>1&1,o=r[e+3]>>6,c=t===3?3-i:i===3?3:4,l=Ru[c*14+s-1]*1e3,u=ku[(t===3?0:t===2?1:2)*3+n],h=o===3?1:2,f=wu[t][i],g=Cu[i],m=f*8*g,y=Math.floor(f*l/u+a)*g;if(qi===null){const b=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);qi=b?parseInt(b[1]):0}return!!qi&&qi<=87&&i===2&&l>=224e3&&o===0&&(r[e+3]=r[e+3]|128),{sampleRate:u,channelCount:h,frameLength:y,samplesPerFrame:m}}}function lr(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function Xa(r,e){return e+1{let t=0,i=5;e+=i;const s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=r[e];const o=Math.min(i,8),c=8-o;n[0]=4278190080>>>24+c<>c,t=t?t<e.length||e[t]!==11||e[t+1]!==119)return-1;const n=e[t+4]>>6;if(n>=3)return-1;const o=[48e3,44100,32e3][n],c=e[t+4]&63,d=[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][c*3+n]*2;if(t+d>e.length)return-1;const u=e[t+6]>>5;let h=0;u===2?h+=2:(u&1&&u!==1&&(h+=2),u&4&&(h+=2));const f=(e[t+6]<<8|e[t+7])>>12-h&1,m=[2,1,2,3,3,4,4,5][u]+f,y=e[t+5]>>3,v=e[t+5]&7,T=new Uint8Array([n<<6|y<<1|v>>2,(v&3)<<6|u<<3|f<<2|c>>4,c<<4&224]),b=1536/o*9e4,x=i+s*b,S=e.subarray(t,t+d);return r.config=T,r.channelCount=m,r.samplerate=o,r.samples.push({unit:S,pts:x}),d}class Mu extends or{resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=li(e,0);let i=(t==null?void 0:t.length)||0;if(t&&e[i]===11&&e[i+1]===119&&ar(t)!==void 0&&Ja(e,i)<=16)return!1;for(let s=e.length;i{const a=Kc(n);if(Fu.test(a.schemeIdUri)){const o=eo(a,t);let c=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const l=a.payload;i.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:Be.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=eo(a,t);i.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:Be.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(e,t,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}}function eo(r,e){return B(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale}class Bu{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Gs(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,mt.cbc)}decryptAacSample(e,t,i){const s=e[t].unit;if(s.length<=16)return;const n=s.subarray(16,s.length-s.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{const c=new Uint8Array(o);s.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)})}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let s=0;for(let n=32;n{n.data=this.getAvcDecryptedUnit(a,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,s)})}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){s();return}const n=e[t].units;for(;!(i>=n.length);i++){const a=n[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,s,a),!this.decrypter.isSync()))return}}}}class to{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,s;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const n=i.units;s=n[n.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,s=i.length;if(s){const n=i[s-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){const s=t.byteLength;let n=e.naluState||0;const a=n,o=[];let c=0,l,d,u,h=-1,f=0;for(n===-1&&(h=0,f=this.getNALuType(t,0),n=0,c=1);c=0){const g={data:t.subarray(h,d),type:f};o.push(g)}else{const g=this.getLastNalUnit(e.samples);g&&(a&&c<=4-a&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-a)),d>0&&(g.data=Ue(g.data,t.subarray(0,d)),g.state=0))}c=0&&n>=0){const g={data:t.subarray(h,s),type:f,state:n};o.push(g)}if(o.length===0){const g=this.getLastNalUnit(e.samples);g&&(g.data=Ue(g.data,t))}return e.naluState=n,o}}class ci{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,s=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");s.set(e.subarray(i,i+n)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&ie.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class io extends to{parsePES(e,t,i,s){const n=this.parseNALu(e,i.data,s);let a=this.VideoSample,o,c=!1;i.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),n.forEach(l=>{var d,u;switch(l.type){case 1:{let m=!1;o=!0;const y=l.data;if(c&&y.length>4){const v=this.readSliceType(y);(v===2||v===4||v===7||v===9)&&(m=!0)}if(m){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=m;break}case 5:o=!0,(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:{o=!0,Ms(l.data,1,i.pts,t.samples);break}case 7:{var f,g;o=!0,c=!0;const m=l.data,y=this.readSPS(m);if(!e.sps||e.width!==y.width||e.height!==y.height||((f=e.pixelRatio)==null?void 0:f[0])!==y.pixelRatio[0]||((g=e.pixelRatio)==null?void 0:g[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[m];const v=m.subarray(1,4);let T="avc1.";for(let b=0;b<3;b++){let x=v[b].toString(16);x.length<2&&(x="0"+x),T+=x}e.codec=T}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(u=a)!=null&&u.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(l)}),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new ci(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,s=8,n;for(let a=0;a{var d,u;switch(l.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,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),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:o=!0,(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:o=!0,Ms(l.data,2,i.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ue(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(o=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const f=this.readSPS(l.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const g in f.params)e.params[g]=f.params[g]}this.pushParameterSet(e.sps,l.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const f=this.readPPS(l.data);for(const g in f)e.params[g]=f[g]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(u=a)!=null&&u.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:o=!1;break}a&&o&&a.units.push(l)}),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let s=0;s=2&&e[s]===3&&e[s-1]===0&&e[s-2]===0||(t[i]=e[s],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new ci(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const i=t.readBits(3),s=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:s}}readSPS(e){const t=new ci(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const s=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),c=t.readUByte(),l=t.readUByte(),d=t.readUByte(),u=t.readUByte(),h=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),y=t.readUByte(),v=t.readUByte(),T=[],b=[];for(let ae=0;ae0)for(let ae=i;ae<8;ae++)t.readBits(2);for(let ae=0;ae1&&t.readEG();for(let Ht=0;Ht0&&kt<16?(q=ol[kt-1],Z=as[kt-1]):kt===255&&(q=t.readBits(16),Z=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),De=t.readBoolean(),De&&(I+=t.readUEG(),w+=t.readUEG(),L+=t.readUEG(),D+=t.readUEG()),t.readBoolean()&&(de=t.readBits(32),pe=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const as=t.readBoolean(),ll=t.readBoolean();let pi=!1;(as||ll)&&(pi=t.readBoolean(),pi&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),pi&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let cl=0;cl<=i;cl++){re=t.readBoolean();const mg=re||t.readBoolean();let dl=!1;mg?t.readEG():dl=t.readBoolean();const ul=dl?1:t.readUEG()+1;if(as)for(let mi=0;mi>ae&1)<<31-ae)>>>0;let Br=Nr.toString(16);return a===1&&Br==="2"&&(Br="6"),{codecString:`hvc1.${gg}${a}.${Br}.${n?"H":"L"}${v}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:s,general_profile_compatibility_flags:[o,c,l,d],general_constraint_indicator_flags:[u,h,f,g,m,y],general_level_idc:v,bit_depth:M+8,bit_depth_luma_minus8:M,bit_depth_chroma_minus8:te,min_spatial_segmentation_idc:X,chroma_format_idc:x,frame_rate:{fixed:re,fps:pe/de}},width:Et,height:al,pixelRatio:[q,Z]}}readPPS(e){const t=new ci(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const s=t.readBoolean(),n=t.readBoolean();let a=1;return n&&s?a=0:n?a=3:s&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Re=188;class yt{constructor(e,t,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=e,this.config=t,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(e,t){const i=yt.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){const t=e.length;let i=Math.min(Re*5,t-Re)+1,s=0;for(;s1&&(a===0&&o>2||c+Re>i))return a}else{if(o)return-1;break}s++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Rn[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=yt.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=yt.createTrack("audio",s),this._id3Track=yt.createTrack("id3"),this._txtTrack=yt.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,s=!1){i||(this.sampleAes=null);let n;const a=this._videoTrack,o=this._audioTrack,c=this._id3Track,l=this._txtTrack;let d=a.pid,u=a.pesData,h=o.pid,f=c.pid,g=o.pesData,m=c.pesData,y=null,v=this.pmtParsed,T=this._pmtId,b=e.length;if(this.remainderData&&(e=Ue(this.remainderData,e),b=e.length,this.remainderData=null),b>4;let D;if(L>1){if(D=A+5+e[A+4],D===A+Re)continue}else D=A+4;switch(w){case d:if(I){if(u&&(n=Nt(u,this.logger))){if(this.videoParser===null)switch(a.segmentCodec){case"avc":this.videoParser=new io;break;case"hevc":this.videoParser=new so;break}this.videoParser!==null&&this.videoParser.parsePES(a,l,n,!1)}u={data:[],size:0}}u&&(u.data.push(e.subarray(D,A+Re)),u.size+=A+Re-D);break;case h:if(I){if(g&&(n=Nt(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n);break}g={data:[],size:0}}g&&(g.data.push(e.subarray(D,A+Re)),g.size+=A+Re-D);break;case f:I&&(m&&(n=Nt(m,this.logger))&&this.parseID3PES(c,n),m={data:[],size:0}),m&&(m.data.push(e.subarray(D,A+Re)),m.size+=A+Re-D);break;case 0:I&&(D+=e[D]+1),T=this._pmtId=Uu(e,D);break;case T:{I&&(D+=e[D]+1);const M=$u(e,D,this.typeSupported,i,this.observer,this.logger);d=M.videoPid,d>0&&(a.pid=d,a.segmentCodec=M.segmentVideoCodec),h=M.audioPid,h>0&&(o.pid=h,o.segmentCodec=M.segmentAudioCodec),f=M.id3Pid,f>0&&(c.pid=f),y!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${A} after unknown PID '${y}'. Backtracking to sync byte @${x} to parse all TS packets.`),y=null,A=x-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=w;break}}else S++;S>0&&dr(this.observer,new Error(`Found ${S} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=u,o.pesData=g,c.pesData=m;const k={audioTrack:o,videoTrack:a,id3Track:c,textTrack:l};return s&&this.extractRemainingSamples(k),k}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:s,textTrack:n}=e,a=i.pesData,o=t.pesData,c=s.pesData;let l;if(a&&(l=Nt(a,this.logger))){if(this.videoParser===null)switch(i.segmentCodec){case"avc":this.videoParser=new io;break;case"hevc":this.videoParser=new so;break}this.videoParser!==null&&(this.videoParser.parsePES(i,n,l,!0),i.pesData=null)}else i.pesData=a;if(o&&(l=Nt(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;c&&(l=Nt(c,this.logger))?(this.parseID3PES(s,l),s.pesData=null):s.pesData=c}demuxSampleAes(e,t,i){const s=this.demux(e,i,!0,!this.config.progressive),n=this.sampleAes=new Bu(this.observer,this.config,t);return this.decrypt(s,n)}decrypt(e,t){return new Promise(i=>{const{audioTrack:s,videoTrack:n}=e;s.samples&&s.segmentCodec==="aac"?t.decryptAacSamples(s.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{i(e)}):i(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{i(e)})})}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(e,t){let i=0;const s=this.aacOverFlow;let n=t.data;if(s){this.aacOverFlow=null;const u=s.missing,h=s.sample.unit.byteLength;if(u===-1)n=Ue(s.sample.unit,n);else{const f=h-u;s.sample.unit.set(n.subarray(0,u),f),e.samples.push(s.sample),i=s.missing}}let a,o;for(a=i,o=n.length;a0;)o+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=ue({},t,{type:this._videoTrack?Be.emsg:Be.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function cr(r,e){return((r[e+1]&31)<<8)+r[e+2]}function Uu(r,e){return(r[e+10]&31)<<8|r[e+11]}function $u(r,e,t,i,s,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(r[e+1]&15)<<8|r[e+2],c=e+3+o-4,l=(r[e+10]&15)<<8|r[e+11];for(e+=12+l;e0){let h=e+5,f=u;for(;f>2;){switch(r[h]){case 106:t.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=d,a.segmentAudioCodec="ac3");break}const m=r[h+1]+2;h+=m,f-=m}}break;case 194:case 135:return dr(s,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:a.videoPid===-1&&(a.videoPid=d,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}e+=u+5}return a}function dr(r,e,t,i){i.warn(`parsing error: ${e.message}`),r.emit(p.ERROR,p.ERROR,{type:G.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function ur(r,e){e.log(`${r} with AES-128-CBC encryption found in unencrypted stream`)}function Nt(r,e){let t=0,i,s,n,a,o;const c=r.data;if(!r||r.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=Ue(c[0],c[1]),c.splice(1,1);if(i=c[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(s=(i[4]<<8)+i[5],s&&s>r.size-6)return null;const d=i[7];d&192&&(a=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,d&64?(o=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),n=i[8];let u=n+9;if(r.size<=u)return null;r.size-=u;const h=new Uint8Array(r.size);for(let f=0,g=c.length;fm){u-=m;continue}else i=i.subarray(u),m-=u,u=0;h.set(i,t),t+=m}return s&&(s-=n+3),{data:h,pts:a,dts:o,len:s}}return null}class Gu{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)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(t===6)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]);break;default:if(t===1)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(t===2)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(t===3)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]);break}}}const vt=Math.pow(2,32)-1;class _{static init(){_.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:[]};let e;for(e in _.types)_.types.hasOwnProperty(e)&&(_.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=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]);_.HDLR_TYPES={video:t,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]),n=new Uint8Array([0,0,0,0,0,0,0,0]);_.STTS=_.STSC=_.STCO=n,_.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),_.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),_.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),_.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);_.FTYP=_.box(_.types.ftyp,a,c,a,o),_.DINF=_.box(_.types.dinf,_.box(_.types.dref,s))}static box(e,...t){let i=8,s=t.length;const n=s;for(;s--;)i+=t[s].byteLength;const a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.set(e,4),s=0,i=8;s>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(e){return _.box(_.types.mdia,_.mdhd(e.timescale||0,e.duration||0),_.hdlr(e.type),_.minf(e))}static mfhd(e){return _.box(_.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?_.box(_.types.minf,_.box(_.types.smhd,_.SMHD),_.DINF,_.stbl(e)):_.box(_.types.minf,_.box(_.types.vmhd,_.VMHD),_.DINF,_.stbl(e))}static moof(e,t,i){return _.box(_.types.moof,_.mfhd(e),_.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=_.trak(e[t]);return _.box.apply(null,[_.types.moov,_.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(_.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=_.trex(e[t]);return _.box.apply(null,[_.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(vt+1)),s=Math.floor(t%(vt+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,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 _.box(_.types.mvhd,n)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let s,n;for(s=0;s>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(s=0;s>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(n));const o=_.box(_.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),c=e.width,l=e.height,d=e.pixelRatio[0],u=e.pixelRatio[1];return _.box(_.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,c>>8&255,c&255,l>>8&255,l&255,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,_.box(_.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),_.box(_.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(e){const t=e.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,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return _.box(_.types.mp4a,_.audioStsd(e),_.box(_.types.esds,_.esds(e)))}static mp3(e){return _.box(_.types[".mp3"],_.audioStsd(e))}static ac3(e){return _.box(_.types["ac-3"],_.audioStsd(e),_.box(_.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return _.box(_.types.stsd,_.STSD,_.mp4a(e));if(t==="ac3"&&e.config)return _.box(_.types.stsd,_.STSD,_.ac3(e));if(t==="mp3"&&e.codec==="mp3")return _.box(_.types.stsd,_.STSD,_.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return _.box(_.types.stsd,_.STSD,_.avc1(e));if(t==="hevc"&&e.vps)return _.box(_.types.stsd,_.STSD,_.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,i=(e.duration||0)*(e.timescale||0),s=e.width||0,n=e.height||0,a=Math.floor(i/(vt+1)),o=Math.floor(i%(vt+1));return _.box(_.types.tkhd,new Uint8Array([1,0,0,7,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,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,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,s&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){const i=_.sdtp(e),s=e.id,n=Math.floor(t/(vt+1)),a=Math.floor(t%(vt+1));return _.box(_.types.traf,_.box(_.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),_.box(_.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),_.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,_.box(_.types.trak,_.tkhd(e),_.mdia(e))}static trex(e){const t=e.id;return _.box(_.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],s=i.length,n=12+16*s,a=new Uint8Array(n);let o,c,l,d,u,h;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o>>24&255,l>>>16&255,l>>>8&255,l&255,d>>>24&255,d>>>16&255,d>>>8&255,d&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*o);return _.box(_.types.trun,a)}static initSegment(e){_.types||_.init();const t=_.moov(e);return Ue(_.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],s=4,n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),s-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let a=n.length;for(let g=0;g>8,i[g][m].length&255]),a),a+=2,o.set(i[g][m],a),a+=i[g][m].length}const l=_.box(_.types.hvcC,o),d=e.width,u=e.height,h=e.pixelRatio[0],f=e.pixelRatio[1];return _.box(_.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,d>>8&255,d&255,u>>8&255,u&255,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]),l,_.box(_.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),_.box(_.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,f>>24,f>>16&255,f>>8&255,f&255])))}}_.types=void 0,_.HDLR_TYPES=void 0,_.STTS=void 0,_.STSC=void 0,_.STCO=void 0,_.STSZ=void 0,_.VMHD=void 0,_.SMHD=void 0,_.STSD=void 0,_.FTYP=void 0,_.DINF=void 0;const ro=9e4;function hr(r,e,t=1,i=!1){const s=r*e*t;return i?Math.round(s):s}function Vu(r,e,t=1,i=!1){return hr(r,e,1/t,i)}function di(r,e=!1){return hr(r,1e3,1/ro,e)}function Hu(r,e=1){return hr(r,ro,1/e)}const Ku=10*1e3,Wu=1024,Yu=1152,ju=1536;let Bt=null,fr=null;function no(r,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:r?2:1,isNonSync:r?0:1}}}class zi{constructor(e,t,i,s){if(this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=s,this.ISGenerated=!1,Bt===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Bt=a?parseInt(a[1]):0}if(fr===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);fr=n?parseInt(n[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,s=e.reduce((n,a)=>{let o=a.pts,c=o-n;return c<-4294967296&&(t=!0,o=$e(o,i),c=o-n),c>0?n:o},i);return t&&this.logger.debug("PTS rollover detected"),s}remux(e,t,i,s,n,a,o,c){let l,d,u,h,f,g,m=n,y=n;const v=e.pid>-1,T=t.pid>-1,b=t.samples.length,x=e.samples.length>0,S=o&&b>0||b>1;if((!v||x)&&(!T||S)||this.ISGenerated||o){if(this.ISGenerated){var A,I,w,L;const Y=this.videoTrackConfig;(Y&&(t.width!==Y.width||t.height!==Y.height||((A=t.pixelRatio)==null?void 0:A[0])!==((I=Y.pixelRatio)==null?void 0:I[0])||((w=t.pixelRatio)==null?void 0:w[1])!==((L=Y.pixelRatio)==null?void 0:L[1]))||!Y&&S||this.nextAudioPts===null&&x)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,n,a));const D=this.isVideoContiguous;let M=-1,te;if(S&&(M=qu(t.samples),!D&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,M>0){this.logger.warn(`[mp4-remuxer]: Dropped ${M} out of ${b} video samples due to a missing keyframe`);const Y=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(M),t.dropped+=M,y+=(t.samples[0].pts-Y)/t.inputTimeScale,te=y}else M===-1&&(this.logger.warn(`[mp4-remuxer]: No keyframe found out of ${b} video samples`),g=!1);if(this.ISGenerated){if(x&&S){const Y=this.getVideoStartPts(t.samples),U=($e(e.samples[0].pts,Y)-Y)/t.inputTimeScale;m+=Math.max(0,U),y+=Math.max(0,-U)}if(x){if(e.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),u=this.generateIS(e,t,n,a)),d=this.remuxAudio(e,m,this.isAudioContiguous,a,T||S||c===$.AUDIO?y:void 0),S){const Y=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=this.generateIS(e,t,n,a)),l=this.remuxVideo(t,y,D,Y)}}else S&&(l=this.remuxVideo(t,y,D,0));l&&(l.firstKeyFrame=M,l.independent=M!==-1,l.firstKeyFramePTS=te)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=ao(i,n,this._initPTS,this._initDTS)),s.samples.length&&(h=oo(s,n,this._initPTS))),{audio:d,video:l,initSegment:u,independent:g,text:h,id3:f}}generateIS(e,t,i,s){const n=e.samples,a=t.samples,o=this.typeSupported,c={},l=this._initPTS;let d=!l||s,u="audio/mp4",h,f,g;if(d&&(h=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):_.initSegment([e]),metadata:{channelCount:e.channelCount}},d&&(g=e.inputTimeScale,!l||g!==l.timescale?h=f=n[0].pts-Math.round(g*i):d=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:_.initSegment([t]),metadata:{width:t.width,height:t.height}},d)if(g=t.inputTimeScale,!l||g!==l.timescale){const m=this.getVideoStartPts(a),y=Math.round(g*i);f=Math.min(f,$e(a[0].dts,m)-y),h=Math.min(h,m-y)}else d=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,d?(this._initPTS={baseTime:h,timescale:g},this._initDTS={baseTime:f,timescale:g}):h=g=void 0,{tracks:c,initPTS:h,timescale:g}}remuxVideo(e,t,i,s){const n=e.inputTimeScale,a=e.samples,o=[],c=a.length,l=this._initPTS;let d=this.nextAvcDts,u=8,h=this.videoSampleDuration,f,g,m=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,v=!1;if(!i||d===null){const P=t*n,O=a[0].pts-$e(a[0].dts,a[0].pts);Bt&&d!==null&&Math.abs(P-O-d)<15e3?i=!0:d=P-O}const T=l.baseTime*n/l.timescale;for(let P=0;P0?P-1:P].dts&&(v=!0)}v&&a.sort(function(P,O){const X=P.dts-O.dts,q=P.pts-O.pts;return X||q}),f=a[0].dts,g=a[a.length-1].dts;const b=g-f,x=b?Math.round(b/(c-1)):h||e.inputTimeScale/30;if(i){const P=f-d,O=P>x,X=P<-1;if((O||X)&&(O?this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${di(P,!0)} ms (${P}dts) hole between fragments detected at ${t.toFixed(3)}`):this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${di(-P,!0)} ms (${P}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!X||d>=a[0].pts||Bt)){f=d;const q=a[0].pts-P;if(O)a[0].dts=f,a[0].pts=q;else{let Z=!0;for(let re=0;req&&Z);re++){const de=a[re].pts;if(a[re].dts-=P,a[re].pts-=P,re0?O.dts-a[P-1].dts:x;if(Z=P>0?O.pts-a[P-1].pts:x,de.stretchShortVideoTrack&&this.nextAudioPts!==null){const De=Math.floor(de.maxBufferHole*n),Me=(s?m+s*n:this.nextAudioPts)-O.pts;Me>De?(h=Me-pe,h<0?h=pe:D=!0,this.logger.log(`[mp4-remuxer]: It is approximately ${Me/90} ms to the next segment; using duration ${h/90} ms for the last video frame.`)):h=pe}else h=pe}const re=Math.round(O.pts-O.dts);M=Math.min(M,h),Y=Math.max(Y,h),te=Math.min(te,Z),H=Math.max(H,Z),o.push(no(O.key,h,q,re))}if(o.length){if(Bt){if(Bt<70){const P=o[0].flags;P.dependsOn=2,P.isNonSync=0}}else if(fr&&H-te0&&(s&&Math.abs(T-v)<9e3||Math.abs($e(m[0].pts-b,T)-v)<20*d),m.forEach(function(U){U.pts=$e(U.pts-b,T)}),!i||v<0){if(m=m.filter(U=>U.pts>=0),!m.length)return;n===0?v=0:s&&!g?v=Math.max(0,T):v=m[0].pts}if(e.segmentCodec==="aac"){const U=this.config.maxAudioFramesDrift;for(let K=0,V=v;K=U*d&&q0){A+=y;try{k=new Uint8Array(A)}catch(q){this.observer.emit(p.ERROR,p.ERROR,{type:G.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:q,bytes:A,reason:`fail allocating audio mdat ${A}`});return}h||(new DataView(k.buffer).setUint32(0,A),k.set(_.types.mdat,4))}else return;k.set(P,y);const X=P.byteLength;y+=X,f.push(no(!0,l,X,0)),S=O}const w=f.length;if(!w)return;const L=f[f.length-1];this.nextAudioPts=v=S+c*L.duration;const D=h?new Uint8Array(0):_.moof(e.sequenceNumber++,x/c,ue({},e,{samples:f}));e.samples=[];const M=x/a,te=v/a,H={data1:D,data2:k,startPTS:M,endPTS:te,startDTS:M,endDTS:te,type:"audio",hasAudio:!0,hasVideo:!1,nb:w};return this.isAudioContiguous=!0,H}}function $e(r,e){let t;if(e===null)return r;for(e4294967296;)r+=t;return r}function qu(r){for(let e=0;ea.pts-o.pts);const n=r.samples;return r.samples=[],{samples:n}}class zu{constructor(e,t,i,s){this.logger=void 0,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.logger=s}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,s){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(Nc(e,s)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const s=this.initData=Dn(e);s.audio&&(t=lo(s.audio,he.AUDIO)),s.video&&(i=lo(s.video,he.VIDEO));const n={};s.audio&&s.video?n.audiovideo={container:"video/mp4",codec:t+","+i,supplemental:s.video.supplemental,initSegment:e,id:"main"}:s.audio?n.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:s.video?n.video={container:"video/mp4",codec:i,supplemental:s.video.supplemental,initSegment:e,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n}remux(e,t,i,s,n,a){var o,c;let{initPTS:l,lastEndTime:d}=this;const u={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};B(d)||(d=this.lastEndTime=n||0);const h=t.samples;if(!(h!=null&&h.length))return u;const f={initPTS:void 0,timescale:1};let g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(h),g=this.initData),!((c=g)!=null&&c.length))return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const m=Uc(h,g),y=Bc(g,h),v=y===null?n:y;(a||!l)&&(Xu(l,v,n,m)||f.timescale!==l.timescale)&&(f.initPTS=v-n,l&&l.timescale===1&&this.logger.warn(`Adjusting initPTS @${n} from ${l.baseTime/l.timescale} to ${f.initPTS}`),this.initPTS=l={baseTime:f.initPTS,timescale:1});const T=e?v-l.baseTime/l.timescale:d,b=T+m;Gc(g,h,l.baseTime/l.timescale),m>0?this.lastEndTime=b:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const x=!!g.audio,S=!!g.video;let k="";x&&(k+="audio"),S&&(k+="video");const A={data1:h,startPTS:T,startDTS:T,endPTS:b,endDTS:b,type:k,hasAudio:x,hasVideo:S,nb:1,dropped:0};return u.audio=A.type==="audio"?A:void 0,u.video=A.type!=="audio"?A:void 0,u.initSegment=f,u.id3=ao(i,n,l,l),s.samples.length&&(u.text=oo(s,n,l)),u}}function Xu(r,e,t,i){if(r===null)return!0;const s=Math.max(i,1),n=e-r.baseTime/r.timescale;return Math.abs(n-t)>s}function lo(r,e){const t=r==null?void 0:r.codec;return t&&t.length>4?t:e===he.AUDIO?t==="ec-3"||t==="ac-3"||t==="alac"?t:t==="fLaC"||t==="Opus"?Ci(t,!1):(ie.warn(`Unhandled audio codec "${t}" in mp4 MAP`),t||"mp4a"):(ie.warn(`Unhandled video codec "${t}" in mp4 MAP`),t||"avc1")}let ct;try{ct=self.performance.now.bind(self.performance)}catch(r){ct=Date.now}const Xi=[{demux:Nu,remux:zu},{demux:yt,remux:zi},{demux:Pu,remux:zi},{demux:Mu,remux:zi}];Xi.splice(2,0,{demux:Ou,remux:zi});class co{constructor(e,t,i,s,n,a){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=e,this.typeSupported=t,this.config=i,this.id=n,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){const n=i.transmuxing;n.executeStart=ct();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:c}=this;s&&(this.currentTransmuxState=s);const{contiguous:l,discontinuity:d,trackSwitch:u,accurateTimeOffset:h,timeOffset:f,initSegmentChange:g}=s||o,{audioCodec:m,videoCodec:y,defaultInitPts:v,duration:T,initSegmentData:b}=c,x=Qu(a,t);if(x&&Mt(x.method)){const I=this.getDecrypter(),w=Ks(x.method);if(I.isSync()){let L=I.softwareDecrypt(a,x.key.buffer,x.iv.buffer,w);if(i.part>-1){const M=I.flush();L=M&&M.buffer}if(!L)return n.executeEnd=ct(),gr(i);a=new Uint8Array(L)}else return this.asyncResult=!0,this.decryptionPromise=I.webCryptoDecrypt(a,x.key.buffer,x.iv.buffer,w).then(L=>{const D=this.push(L,null,i);return this.decryptionPromise=null,D}),this.decryptionPromise}const S=this.needsProbing(d,u);if(S){const I=this.configureTransmuxer(a);if(I)return this.logger.warn(`[transmuxer] ${I.message}`),this.observer.emit(p.ERROR,p.ERROR,{type:G.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),n.executeEnd=ct(),gr(i)}(d||u||g||S)&&this.resetInitSegment(b,m,y,T,t),(d||g||S)&&this.resetInitialTimestamp(v),l||this.resetContiguity();const k=this.transmux(a,x,f,h,i);this.asyncResult=ui(k);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,n.executeEnd=ct(),k}flush(e){const t=e.transmuxing;t.executeStart=ct();const{decrypter:i,currentTransmuxState:s,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));const a=[],{timeOffset:o}=s;if(i){const u=i.flush();u&&a.push(this.push(u.buffer,null,e))}const{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=ct();const u=[gr(e)];return this.asyncResult?Promise.resolve(u):u}const d=c.flush(o);return ui(d)?(this.asyncResult=!0,d.then(u=>(this.flushRemux(a,u,e),a))):(this.flushRemux(a,d,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,i){const{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===$.MAIN?"level":"track"} ${i.level}`);const d=this.remuxer.remux(s,n,a,o,l,c,!0,this.id);e.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=ct()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,s,n){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,i,s),o.resetInitSegment(e,t,i,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,s,n){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,s,n):a=this.transmuxUnencrypted(e,i,s,n),a}transmuxUnencrypted(e,t,i,s){const{audioTrack:n,videoTrack:a,id3Track:o,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,a,o,c,t,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,t,i,s,n){return this.demuxer.demuxSampleAes(e,t,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,s,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:s}=this;let n;for(let u=0,h=Xi.length;u0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const gr=r=>({remuxResult:{},chunkMeta:r});function ui(r){return"then"in r&&r.then instanceof Function}class Ju{constructor(e,t,i,s,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=s,this.defaultInitPts=n||null}}class Zu{constructor(e,t,i,s,n,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=n,this.initSegmentChange=a}}let uo=0;class ho{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=uo++,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=c=>{const l=c.data,d=this.hls;if(!(!d||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var u;const h=(u=this.workerContext)==null?void 0:u.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{d.logger[l.data.logType]&&d.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,d.trigger(l.event,l.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const l=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(p.ERROR,{type:G.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const a=(c,l)=>{l=l||{},l.frag=this.frag||void 0,c===p.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(c,l)};this.observer=new ir,this.observer.on(p.FRAG_DECRYPTED,a),this.observer.on(p.ERROR,a);const o=$n(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker!="undefined"){const c=this.hls.logger;if(n.workerPath||iu()){try{n.workerPath?(c.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=ru(n.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=su());const{worker:d}=this.workerContext;d.addEventListener("message",this.onWorkerMessage),d.addEventListener("error",this.onWorkerError),d.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:me(n)})}catch(d){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,d),this.terminateWorker(),this.error=null,this.transmuxer=new co(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new co(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=uo++;const t=this.hls.config,i=$n(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:me(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),nu(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 e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,s,n,a,o,c,l,d){var u,h;l.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,m=a?a.start:n.start,y=n.decryptdata,v=this.frag,T=!(v&&n.cc===v.cc),b=!(v&&l.level===v.level),x=v?l.sn-v.sn:-1,S=this.part?l.part-this.part.index:-1,k=x===0&&l.id>1&&l.id===(v==null?void 0:v.stats.chunkCount),A=!b&&(x===1||x===0&&(S===1||k&&S<=0)),I=self.performance.now();(b||x||n.stats.parsing.start===0)&&(n.stats.parsing.start=I),a&&(S||!A)&&(a.stats.parsing.start=I);const w=!(v&&((u=n.initSegment)==null?void 0:u.url)===((h=v.initSegment)==null?void 0:h.url)),L=new Zu(T,A,c,b,m,w);if(!A||T||w){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===$.MAIN?"level":"track"}: ${l.level} id: ${l.id} discontinuity: ${T} trackSwitch: ${b} contiguous: ${A} accurateTimeOffset: ${c} timeOffset: ${m} initSegmentChange: ${w}`);const D=new Ju(i,s,t,o,d);this.configureTransmuxer(D)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:y,chunkMeta:l,state:L},e instanceof ArrayBuffer?[e]:[]);else if(g){const D=g.push(e,y,l,L);ui(D)?D.then(M=>{this.handleTransmuxComplete(M)}).catch(M=>{this.transmuxerError(M,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(D)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const s=i.flush(e);ui(s)?s.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")}):this.handleFlushResult(s,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(p.ERROR,{type:G.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const fo=100;class eh extends er{constructor(e,t,i){super(e,t,i,"audio-stream-controller",$.AUDIO),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:e}=this;e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n}){if(i===$.MAIN){const a=t.cc,o=this.fragCurrent;if(this.initPTS[a]={baseTime:s,timescale:n},this.log(`InitPTS for cc: ${a} found from main: ${s}/${n}`),this.mainAnchor=t,this.state===C.WAITING_INIT_PTS){const c=this.waitingData;(!c&&!this.loadingParts||c&&c.frag.cc!==a)&&(this.nextLoadPosition=this.findSyncFrag(t).start),this.tick()}else!this.hls.hasEnoughToStart&&o&&o.cc!==a?(this.startFragRequested=!1,this.nextLoadPosition=this.findSyncFrag(t).start,o.abortRequests(),this.resetLoadingState()):this.state===C.IDLE&&this.tick()}}findSyncFrag(e){const t=this.getLevelDetails(),i=e.cc;return md(t,i,e)||t&&Zn(t.fragments,i)||e}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=C.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(fo),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=C.IDLE):this.state=C.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case C.IDLE:this.doTickIdle();break;case C.WAITING_TRACK:{const{levels:t,trackId:i}=this,s=t==null?void 0:t[i],n=s==null?void 0:s.details;if(n&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(n))break;this.state=C.WAITING_INIT_PTS}break}case C.FRAG_LOADING_WAITING_RETRY:{var e;const t=performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){const{levels:s,trackId:n}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((s==null?void 0:s[n])||null),this.state=C.IDLE}break}case C.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:i,part:s,cache:n,complete:a}=t,o=this.mainAnchor;if(this.initPTS[i.cc]!==void 0){this.waitingData=null,this.state=C.FRAG_LOADING;const c=n.flush().buffer,l={frag:i,part:s,payload:c,networkDetails:null};this._handleFragmentLoadProgress(l),a&&super._handleFragmentLoadComplete(l)}else o&&o.cc!==t.frag.cc&&(this.log(`Waiting fragment cc (${i.cc}) cancelled because video is at cc ${o.cc}`),this.nextLoadPosition=this.findSyncFrag(o).start,this.clearWaitingFragment())}else this.state=C.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.state!==C.STOPPED&&(this.state=C.IDLE))}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:s,trackId:n}=this,a=t.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(i!=null&&i[n]))return;const o=i[n],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=C.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,he.AUDIO,$.AUDIO));const d=this.getFwdBufferInfo(l,$.AUDIO);if(d===null)return;if(!this.switchingTrack&&this._streamEnded(d,c)){t.trigger(p.BUFFER_EOS,{type:"audio"}),this.state=C.ENDED;return}const u=d.len,h=t.maxBufferLength,f=c.fragments,g=f[0].start,m=this.getLoadPosition(),y=this.flushing?m:d.end;if(this.switchingTrack&&s){const b=m;c.PTSKnown&&bg||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=g+.05)}if(u>=h&&!this.switchingTrack&&yT.end){const x=this.fragmentTracker.getFragAtPos(y,$.MAIN);x&&x.end>T.end&&(T=x,this.mainFragLoading={frag:x,targetBufferTime:null})}if(v.start>T.end)return}this.loadFragment(v,o,y)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new si(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==C.STOPPED&&(this.setInterval(fo),this.state=C.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(p.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:s}=this,{details:n,id:a,groupId:o,track:c}=t;if(!s){this.warn(`Audio tracks reset while loading track ${a} "${c.name}" of "${o}"`);return}const l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==C.STOPPED&&(this.state=C.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${c.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const d=s[a];let u=0;if(n.live||(i=d.details)!=null&&i.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(d.details){var h;u=this.alignPlaylists(n,d.details,(h=this.levelLastLoaded)==null?void 0:h.details)}n.alignedSliding||(Ma(n,l),n.alignedSliding||Ki(n,l),u=n.fragmentStart)}d.details=n,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(l,u),this.hls.trigger(p.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===C.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=C.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:n}=e,{config:a,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const l=c[o];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const d=l.details;if(!d){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const u=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new ho(this.hls,$.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[i.cc],g=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){const y=s?s.index:-1,v=y!==-1,T=new Vs(i.level,i.sn,i.stats.chunkCount,n.byteLength,y,v);h.push(n,g,u,"",i,s,d.totalduration,!1,T,f)}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 ${o}`);const{cache:m}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Na,complete:!1};m.push(new Uint8Array(n)),this.state!==C.STOPPED&&(this.state=C.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===$.MAIN&&Ie(t.frag)&&(this.mainFragLoading=t,this.state===C.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i.type!==$.AUDIO){!this.audioOnly&&i.type===$.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}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"}`);return}if(Ie(i)){this.fragPrevious=i;const n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(p.AUDIO_TRACK_SWITCHED,le({},n)))}this.fragBufferedComplete(i,s),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError($.AUDIO,t);break;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===ee.AUDIO_TRACK&&(this.state=C.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==he.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==he.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===C.ENDED&&(this.state=C.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,$.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:s}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:c,part:l,level:d}=o,{details:u}=d,{audio:h,text:f,id3:g,initSegment:m}=n;if(this.fragContextChanged(c)||!u){this.fragmentTracker.removeFragment(c);return}if(this.state=C.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),m!=null&&m.tracks){const y=c.initSegment||c;this._bufferInitSegment(d,m.tracks,y,a),s.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:i,tracks:m.tracks})}if(h){const{startPTS:y,endPTS:v,startDTS:T,endDTS:b}=h;l&&(l.elementaryStreams[he.AUDIO]={startPTS:y,endPTS:v,startDTS:T,endDTS:b}),c.setElementaryStreamInfo(he.AUDIO,y,v,T,b),this.bufferFragmentData(h,c,l,a)}if(g!=null&&(t=g.samples)!=null&&t.length){const y=ue({id:i,frag:c,details:u},g);s.trigger(p.FRAG_PARSING_METADATA,y)}if(f){const y=ue({id:i,frag:c,details:u},f);s.trigger(p.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,i,s){if(this.state!==C.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const n=t.audio;n.id=$.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`),a&&a.split(",").length===1&&(n.levelCodec=a),this.hls.trigger(p.BUFFER_CODECS,t);const o=n.initSegment;if(o!=null&&o.byteLength){const c={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:o};this.hls.trigger(p.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);if(this.switchingTrack||s===Ae.NOT_LOADED||s===Ae.PARTIAL){var n;if(!Ie(e))this._loadInitSegment(e,t);else if((n=t.details)!=null&&n.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=C.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Ki(t.details,a)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:s,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;At({name:t,lang:i,assocLang:s,characteristics:n,audioCodec:a,channels:o},e,Lt)||(Mi(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(p.AUDIO_TRACK_SWITCHED,le({},e))}}class pr extends at{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const s=t==null?void 0:t.renditionReports;if(s){let n=-1;for(let a=0;a=0&&d>t.partTarget&&(c+=1)}const l=i&&Yn(i);return new jn(o,c>=0?c:void 0,l)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){const{details:s,stats:n}=t,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;s.advancedDateTime=Date.now()-o;const c=this.hls.config.timelineOffset;if(c!==s.appliedTimelineOffset){const d=Math.max(c||0,0);s.appliedTimelineOffset=d,s.fragments.forEach(u=>{u.start=u.playlistOffset+d})}if(s.live||i!=null&&i.live){const d="levelInfo"in t?t.levelInfo:t.track;if(s.reloaded(i),i&&s.fragments.length>0){Yd(i,s);const T=s.playlistParsingError;if(T){this.warn(T);const b=this.hls;if(!b.config.ignorePlaylistParsingErrors){var l;const{networkDetails:x}=t;b.trigger(p.ERROR,{type:G.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:T,reason:T.message,level:t.level||void 0,parent:(l=s.fragments[0])==null?void 0:l.type,networkDetails:x,stats:n});return}s.playlistParsingError=null}}s.requestScheduled===-1&&(s.requestScheduled=n.loading.start);const u=this.hls.mainForwardBufferInfo,h=u?u.end-u.len:0,f=(s.edge-h)*1e3,g=Ra(s,f);if(s.requestScheduled+g0){if(w>s.targetduration*3)this.log(`Playlist last advanced ${I.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,v=void 0;else if(i!=null&&i.tuneInGoal&&w-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${L} with playlist age: ${s.age}`),L=0;else{const D=Math.floor(L/s.targetduration);if(y+=D,v!==void 0){const M=Math.round(L%s.targetduration/s.partTarget);v+=M}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${I.toFixed(2)}s goal: ${L} skip sn ${D} to part ${v}`)}s.tuneInGoal=L}if(m=this.getDeliveryDirectives(s,t.deliveryDirectives,y,v),T||!A){s.requestScheduled=a,this.loadingPlaylist(d,m);return}}else(s.canBlockReload||s.canSkipUntil)&&(m=this.getDeliveryDirectives(s,t.deliveryDirectives,y,v));m&&y!==void 0&&s.canBlockReload&&(s.requestScheduled=n.loading.first+Math.max(g-o*2,g/2)),this.scheduleLoading(d,m,s)}else this.clearTimer()}scheduleLoading(e,t,i){const s=i||e.details;if(!s){this.loadingPlaylist(e,t);return}const n=self.performance.now(),a=s.requestScheduled;if(n>=a){this.loadingPlaylist(e,t);return}const o=a-n;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,i,s){let n=Yn(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,n=Oi.No),new jn(i,s,n)}checkRetry(e){const t=e.details,i=Fi(e),s=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=s||{},c=!!s&&!!o&&(n===we.RetryRequest||!s.resolved&&n===we.SendAlternateToPenaltyBox);if(c){var l;if(a>=o.maxNumRetry)return!1;if(i&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const d=$s(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),d),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${d}ms`)}e.levelRetry=!0,s.resolved=!0}return c}}function go(r,e){if(r.length!==e.length)return!1;for(let t=0;tr[s]!==e[s])}function mr(r,e){return e.label.toLowerCase()===r.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(r.lang||"").toLowerCase())}class th extends pr{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.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(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:s,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Audio track with id:${i} and group:${s} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,s=this.groupIds;let n=this.currentTrack;if(!i||(s==null?void 0:s.length)!==(i==null?void 0:i.length)||i!=null&&i.some(o=>(s==null?void 0:s.indexOf(o))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(h=>!i||i.indexOf(h.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(h=>h.default)&&(this.selectDefaultTrack=!1),o.forEach((h,f)=>{h.id=f});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!n&&c){const h=Ze(c,o,Lt);if(h>-1)n=o[h];else{const f=Ze(c,this.tracks);n=this.tracks[f]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));const d={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(p.AUDIO_TRACKS_UPDATED,d);const u=this.trackId;if(l!==-1&&u===-1)this.setAudioTrack(l);else if(o.length&&u===-1){var a;const h=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(h.message),this.hls.trigger(p.ERROR,{type:G.MEDIA_ERROR,details:R.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===ee.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&At(e,s,Lt))return s;const n=Ze(e,this.tracksInGroup,Lt);if(n>-1){const a=this.tracksInGroup[n];return this.setAudioTrack(n),a}else if(s){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=ud(e,t.levels,i,a,Lt);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=Ze(e,i);if(a>-1)return i[a]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e],n=s.details&&!s.details.live;if(e===this.trackId&&s===i&&n||(this.log(`Switching to audio-track ${e} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=e,this.currentTrack=s,this.hls.trigger(p.AUDIO_TRACK_SWITCHING,le({},s)),n))return;const a=this.switchParams(s.url,i==null?void 0:i.details,s.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const s=t[0];try{s.execute()}catch(n){var i;if(s.onError(n),this.queues===null||this.tracks===null)return;const a=(i=this.tracks[e])==null?void 0:i.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"":` ${this.list("video")} ${this.list("audio")} ${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=(t=this.tracks)==null?void 0:t[e],s=i==null?void 0:i.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}}const po=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,mo="HlsJsTrackRemovedError";class sh extends Error{constructor(e){super(e),this.name=mo}}class rh extends at{constructor(e,t){super("buffer-controller",e.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=i=>{var s;this.hls&&((s=this.mediaSource)==null?void 0:s.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=i=>{const{media:s,mediaSource:n}=this;i&&this.log("Media source opened"),!(!s||!n)&&(n.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(p.MEDIA_ATTACHED,{media:s,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:i,_objectUrl:s}=this;i!==s&&this.error(`Media element src was set while attaching MediaSource (${s} > ${i})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=Rc(pt(e.config.preferManagedMediaSource)),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:e}=this;e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_APPENDING,this.onBufferAppending,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.BUFFER_EOS,this.onBufferEos,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.FRAG_PARSED,this.onFragParsed,this),e.on(p.FRAG_CHANGED,this.onFragChanged,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_APPENDING,this.onBufferAppending,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_EOS,this.onBufferEos,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.FRAG_PARSED,this.onFragParsed,this),e.off(p.FRAG_CHANGED,this.onFragChanged,this),e.off(p.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const i={};if(this.operationQueue){const n=this.isUpdating();n||this.operationQueue.removeBlockers();const a=this.isQueued();(n||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${n?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===t?ue(i,s.tracks):this.sourceBuffers.forEach(n=>{const[a]=n;a&&(i[a]=ue({},this.tracks[a]),this.removeBuffer(a)),n[0]=n[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var i;let s=2;(t.audio&&!t.video||!t.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(e,t){const i=this.media=t.media,s=pt(this.appendSource);if(this.transferData=this.overrides=void 0,i&&s){const n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const a=this.mediaSource=t.mediaSource||new s;if(this.assignMediaSource(a),n)this._objectUrl=i.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");const c=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||c&&a instanceof c,yo(i),nh(i,o),i.load()}catch(c){i.src=o}else i.src=o}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const i=this.tracks,s=t.tracks,n=s?Object.keys(s):null,a=n?n.length:0,o=()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()};if(s&&n&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) required tracks: ${me(i,(c,l)=>c==="initSegment"?void 0:l)}; transfer tracks: ${me(s,(c,l)=>c==="initSegment"?void 0:l)}}`),!An(s,i)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,l=this.details,d=Math.max(c,(l==null?void 0:l.fragments[0].start)||0);if(d-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${d}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${d} currentTime: ${c}`),this.onMediaDetaching(p.MEDIA_DETACHING,{}),this.onMediaAttaching(p.MEDIA_ATTACHING,t),e.currentTime=d;return}this.transferData=void 0,n.forEach(c=>{const l=c,d=s[l];if(d){const u=d.buffer;if(u){const h=this.fragmentTracker,f=d.id;if(h.hasFragments(f)||h.hasParts(f)){const y=J.getBuffered(u);h.detectEvictedFragments(l,y,f,null,!0)}const g=yr(l),m=[l,u];this.sourceBuffers[g]=m,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,d)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:s,mediaSource:n,_objectUrl:a}=this;if(n){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=n.readyState==="open";try{const c=n.sourceBuffers;for(let l=c.length;l--;)o&&c[l].abort(),n.removeSourceBuffer(c[l]);o&&n.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(s.removeAttribute("src"),this.appendSource&&yo(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(p.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var s;(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(n){this.warn(`onBufferReset ${e}`,n)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[yr(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new ih(this.tracks)}onBufferCodecs(e,t){const i=this.tracks,s=Object.keys(t);this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&s.some(o=>!i[o]);if(n||a){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${s}" SourceBuffers`);return}s.forEach(o=>{var c,l,d;const u=t[o],{id:h,codec:f,levelCodec:g,container:m,metadata:y,supplemental:v}=u;let T=i[o];const b=(c=this.transferData)==null||(l=c.tracks)==null?void 0:l[o],x=b!=null&&b.buffer?b:T,S=(x==null?void 0:x.pendingCodec)||(x==null?void 0:x.codec),k=x==null?void 0:x.levelCodec;T||(T=i[o]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:m,levelCodec:g,metadata:y,id:h});const A=Di(S,k),I=A==null?void 0:A.replace(po,"$1");let w=Di(f,g);const L=(d=w)==null?void 0:d.replace(po,"$1");w&&A&&I!==L&&(o.slice(0,5)==="audio"&&(w=Ci(w,this.appendSource)),this.log(`switching codec ${S} to ${w}`),w!==(T.pendingCodec||T.codec)&&(T.pendingCodec=w),T.container=m,this.appendChangeType(o,m,w))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&this.mediaSourceOpenOrEnded&&this.checkPendingTracks()}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){const s=`${t};codecs=${i}`,n={label:`change-type=${s}`,execute:()=>{const a=this.tracks[e];if(a){const o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${s}`),o.changeType(s),a.codec=i,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(n,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,s=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,$.MAIN))==null?void 0:t.gap)===!0)return;const a={label:"block-audio",execute:()=>{var o;const c=this.tracks.video;(this.lastVideoAppendEnd>s||c!=null&&c.buffer&&J.isBuffered(c.buffer,s)||((o=this.fragmentTracker.getAppendedFrag(s,$.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:s,type:n,parent:a,frag:o,part:c,chunkMeta:l}=t,d=l.buffering[n],u=o.sn,h=self.performance.now();d.start=h;const f=o.stats.buffering,g=c?c.stats.buffering:null;f.start===0&&(f.start=h),g&&g.start===0&&(g.start=h);const m=i.audio;let y=!1;n==="audio"&&(m==null?void 0:m.container)==="audio/mpeg"&&(y=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const v=this.tracks.video,T=v==null?void 0:v.buffer;if(T&&u!=="initSegment"){const S=c||o,k=this.blockedAudioAppend;if(n==="audio"&&a!=="main"&&!this.blockedAudioAppend){const I=S.start+S.duration*.05,w=T.buffered,L=this.currentOp("video");!w.length&&!L?this.blockAudio(S):!L&&!J.isBuffered(T,I)&&this.lastVideoAppendEndI||A{if(d.executeStart=self.performance.now(),y){const S=this.tracks[n];if(S){const k=S.buffer;if(k){const A=b-k.timestampOffset;Math.abs(A)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${b} (delta: ${A}) sn: ${u})`),k.timestampOffset=b)}}}this.appendExecutor(s,n)},onStart:()=>{},onComplete:()=>{const S=self.performance.now();d.executeEnd=d.end=S,f.first===0&&(f.first=S),g&&g.first===0&&(g.first=S);const k={};this.sourceBuffers.forEach(([A,I])=>{A&&(k[A]=J.getBuffered(I))}),this.appendErrors[n]=0,n==="audio"||n==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(p.BUFFER_APPENDED,{type:n,frag:o,part:c,chunkMeta:l,parent:o.type,timeRanges:k})},onError:S=>{var k;const A={type:G.MEDIA_ERROR,parent:o.type,details:R.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:c,chunkMeta:l,error:S,err:S,fatal:!1},I=(k=this.media)==null?void 0:k.error;if(S.code===DOMException.QUOTA_EXCEEDED_ERR)A.details=R.BUFFER_FULL_ERROR;else if(S.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!I)A.errorAction=ri(!0);else if(S.name===mo&&this.sourceBufferCount===0)A.errorAction=ri(!0);else{const w=++this.appendErrors[n];this.warn(`Failed ${w}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${I||"no media error"})`),(w>=this.hls.config.appendErrorMaxRetry||I)&&(A.fatal=!0)}this.hls.trigger(p.ERROR,A)}};this.append(x,n,this.isPending(this.tracks[n]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(p.BUFFER_FLUSHED,{type:e})},onError:s=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,s)}}}onBufferFlushing(e,t){const{type:i,startOffset:s,endOffset:n}=t;i?this.append(this.getFlushOp(i,s,n),i):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,s,n),a)})}onFragParsed(e,t){const{frag:i,part:s}=t,n=[],a=s?s.elementaryStreams:i.elementaryStreams;a[he.AUDIOVIDEO]?n.push("audiovideo"):(a[he.AUDIO]&&n.push("audio"),a[he.VIDEO]&&n.push("video"));const o=()=>{const c=self.performance.now();i.stats.buffering.end=c,s&&(s.stats.buffering.end=c);const l=s?s.stats:i.stats;this.hls.trigger(p.FRAG_BUFFERED,{frag:i,part:s,stats:l,id:i.type})};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(o,n).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t,i;return e&&(!((t=this.tracks[e])!=null&&t.ended)||((i=this.tracks[e])==null?void 0:i.ending))})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([a])=>{if(a){const o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});const s=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})&&(s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:a}=this;if(!a||a.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(p.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(p.BUFFERED_TO_END,void 0)))}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){const e=this.getDurationAndRange();e&&this.blockUntilOpen(()=>this.updateMediaSource(e))}onError(e,t){if(t.details===R.BUFFER_APPEND_ERROR&&t.frag){var i;const s=(i=t.errorAction)==null?void 0:i.nextAutoLevel;B(s)&&s!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;const s=e.config,n=i.currentTime,a=t.levelTargetDuration,o=t.live&&s.liveBackBufferLength!==null?s.liveBackBufferLength:s.backBufferLength;if(B(o)&&o>=0){const c=Math.max(o,a),l=Math.floor(n/a)*a-c;this.flushBackBuffer(n,a,l)}if(B(s.frontBufferFlushThreshold)&&s.frontBufferFlushThreshold>0){const c=Math.max(s.maxBufferLength,s.frontBufferFlushThreshold),l=Math.max(c,a),d=Math.floor(n/a)*a+l;this.flushFrontBuffer(n,a,d)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([s,n])=>{if(n){const o=J.getBuffered(n);if(o.length>0&&i>o.start(0)){var a;this.hls.trigger(p.BACK_BUFFER_REACHED,{bufferEnd:i});const c=this.tracks[s];if((a=this.details)!=null&&a.live)this.hls.trigger(p.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(c!=null&&c.ended){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:s})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([s,n])=>{if(n){const a=J.getBuffered(n),o=a.length;if(o<2)return;const c=a.start(o-1),l=a.end(o-1);if(i>c||e>=c&&e<=l)return;this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:s})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||(i==null?void 0:i.readyState)!=="open")return null;const s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&i.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),d=Math.max(l,s);return{duration:1/0,start:l,end:d}}return{duration:1/0}}const n=(e=this.overrides)==null?void 0:e.duration;if(n)return B(n)?{duration:n}:null;const a=this.media.duration,o=B(i.duration)?i.duration:0;return s>o&&s>a||!B(a)?{duration:s}:null}updateMediaSource({duration:e,start:t,end:i}){const s=this.mediaSource;!this.media||!s||s.readyState!=="open"||(s.duration!==e&&(B(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),s.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${t}-${i}.`),s.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${me(i)}`),this.tracksReady){var s;const n=(s=this.transferData)==null?void 0:s.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,i])=>{if(t){const s=this.tracks[t];e[t]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(p.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(p.ERROR,{type:G.MEDIA_ERROR,details:R.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const n in e){const a=n,o=e[a];if(this.isPending(o)){const c=this.getTrackCodec(o,a),l=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${l})${this.currentOp(a)?" Queued":""} ${me(o)}`);try{const d=i.addSourceBuffer(l),u=yr(a),h=[a,d];t[u]=h,o.buffer=d}catch(d){var s;this.error(`error while trying to add sourceBuffer: ${d.message}`),this.shiftAndExecuteNext(a),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[a],this.hls.trigger(p.ERROR,{type:G.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:d,sourceBufferName:a,mimeType:l,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let s=e.codec;i&&(t==="video"||t==="audiovideo")&&Fs(i,"video")&&(s=Qc(s,i));const n=Di(s,e.levelCodec);return n?t.slice(0,5)==="audio"?Ci(n,this.appendSource):n:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const s=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:s,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,a)=>{const o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(p.BUFFER_FLUSHED,{type:n})})}get mediaSrc(){var e,t;const i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i==null?void 0:i.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const s=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${s}`,t),this.hls.trigger(p.ERROR,{type:G.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});const n=this.currentOp(e);n&&n.onError(s)}removeExecutor(e,t,i){const{media:s,mediaSource:n}=this,a=this.tracks[e],o=a==null?void 0:a.buffer;if(!s||!n||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const c=B(s.duration)?s.duration:1/0,l=B(n.duration)?n.duration:1/0,d=Math.max(0,t),u=Math.min(i,c,l);u>d&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${d},${u}] from the ${e} SourceBuffer`),o.remove(d,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],s=i==null?void 0:i.buffer;if(!s)throw new sh(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,s.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,s=t.map(a=>this.appendBlocker(a));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then(a=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;const s=(i=this.tracks[t])==null?void 0:i.buffer;!s||s.updating||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const s=this.tracks[e];if(!s)return;const n=s.buffer;if(!n)return;const a=i.bind(this,e);s.listeners.push({event:t,listener:a}),n.addEventListener(t,a)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(s=>{i.removeEventListener(s.event,s.listener)}),t.listeners.length=0)}}function yo(r){const e=r.querySelectorAll("source");[].slice.call(e).forEach(t=>{r.removeChild(t)})}function nh(r,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,r.appendChild(t)}function yr(r){return r==="audio"?1:0}class vr{constructor(e){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=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&B(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((s,n)=>this.isLevelAllowed(s)&&n<=e);return this.clientRect=null,vr.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 e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(t){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const s=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0;let n=e.length-1;const a=Math.max(t,i);for(let o=0;o=a||c.height>=a)&&s(c,e[o+1])){n=o;break}}return n}}const Oe={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},ah={HLS:"h"},fi={OBJECT:"CMCD-Object",REQUEST:"CMCD-Request",SESSION:"CMCD-Session",STATUS:"CMCD-Status"},oh={[fi.OBJECT]:["br","d","ot","tb"],[fi.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[fi.SESSION]:["cid","pr","sf","sid","st","v"],[fi.STATUS]:["bs","rtp"]};class Ut{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof Ut?i:new Ut(i))),this.value=e,this.params=t}}const lh="Dict";function ch(r){return Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":typeof r=="object"?JSON.stringify(r):String(r)}function dh(r,e,t,i){return new Error(`failed to ${r} "${ch(e)}" as ${t}`,{cause:i})}function it(r,e,t){return dh("serialize",r,e,t)}class vo{constructor(e){this.description=e}}const bo="Bare Item",uh="Boolean";function hh(r){if(typeof r!="boolean")throw it(r,uh);return r?"?1":"?0"}const fh="Byte Sequence";function gh(r){if(ArrayBuffer.isView(r)===!1)throw it(r,fh);return`:${pu(r)}:`}const ph="Integer";function mh(r){return r<-999999999999999||99999999999999912)throw it(r,vh);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Th="String",Eh=/[\x00-\x1f\x7f]+/;function xh(r){if(Eh.test(r))throw it(r,Th);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Sh(r){return r.description||r.toString().slice(7,-1)}const Ah="Token";function Eo(r){const e=Sh(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw it(e,Ah);return e}function br(r){switch(typeof r){case"number":if(!B(r))throw it(r,bo);return Number.isInteger(r)?To(r):bh(r);case"string":return xh(r);case"symbol":return Eo(r);case"boolean":return hh(r);case"object":if(r instanceof Date)return yh(r);if(r instanceof Uint8Array)return gh(r);if(r instanceof vo)return Eo(r);default:throw it(r,bo)}}const Lh="Key";function Tr(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw it(r,Lh);return r}function Er(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${Tr(e)}`:`;${Tr(e)}=${br(t)}`).join("")}function xo(r){return r instanceof Ut?`${br(r.value)}${Er(r.params)}`:br(r)}function _h(r){return`(${r.value.map(xo).join(" ")})${Er(r.params)}`}function Ih(r,e={whitespace:!0}){if(typeof r!="object")throw it(r,lh);const t=r instanceof Map?r.entries():Object.entries(r),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([s,n])=>{n instanceof Ut||(n=new Ut(n));let a=Tr(s);return n.value===!0?a+=Er(n.params):(a+="=",Array.isArray(n.value)?a+=_h(n):a+=xo(n)),a}).join(`,${i}`)}function Rh(r,e){return Ih(r,e)}function kh(r){return r==="ot"||r==="sf"||r==="st"}function wh(r){return typeof r=="number"?B(r):r!=null&&r!==""&&r!==!1}const Qi=r=>Math.round(r),Ch=(r,e)=>(e!=null&&e.baseUrl&&(r=mu(r,e.baseUrl)),encodeURIComponent(r)),Ji=r=>Qi(r/100)*100,Dh={br:Qi,d:Qi,bl:Ji,dl:Ji,mtp:Ji,nor:Ch,rtp:Ji,tb:Qi};function Ph(r,e){const t={};if(r==null||typeof r!="object")return t;const i=Object.keys(r).sort(),s=ue({},Dh,e==null?void 0:e.formatters),n=e==null?void 0:e.filter;return i.forEach(a=>{if(n!=null&&n(a))return;let o=r[a];const c=s[a];c&&(o=c(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||wh(o)&&(kh(a)&&typeof o=="string"&&(o=new vo(o)),t[a]=o))}),t}function So(r,e={}){return r?Rh(Ph(r,e),ue({whitespace:!1},e)):""}function Oh(r,e={}){const t={};if(!r)return t;const i=Object.entries(r),s=Object.entries(oh).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),n=i.reduce((a,o)=>{var c,l;const[d,u]=o,h=((c=s.find(f=>f[1].includes(d)))===null||c===void 0?void 0:c[0])||fi.REQUEST;return(l=a[h])!==null&&l!==void 0||(a[h]={}),a[h][d]=u,a},{});return Object.entries(n).reduce((a,[o,c])=>(a[o]=So(c,e),a),t)}function Mh(r,e,t){return ue(r,Oh(e,t))}const Fh="CMCD";function Nh(r,e={}){if(!r)return"";const t=So(r,e);return`${Fh}=${encodeURIComponent(t)}`}const Ao=/CMCD=[^&#]+/;function Bh(r,e,t){const i=Nh(e,t);if(!i)return r;if(Ao.test(r))return r.replace(Ao,i);const s=r.includes("?")?"&":"?";return`${r}${s}${i}`}class Uh{constructor(e){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=s=>{try{this.apply(s,{ot:Oe.MANIFEST,su:!this.initialized})}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=s=>{try{const{frag:n,part:a}=s,o=this.hls.levels[n.level],c=this.getObjectType(n),l={d:(a||n).duration*1e3,ot:c};(c===Oe.VIDEO||c===Oe.AUDIO||c==Oe.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));const d=a?this.getNextPart(a):this.getNextFrag(n);d!=null&&d.url&&d.url!==n.url&&(l.nor=d.url),this.apply(s,l)}catch(n){this.hls.logger.warn("Could not generate segment CMCD data.",n)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.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(e,t){this.media=t.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(e,t){var i,s;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(s=t.tracks.video)==null?void 0:s.buffer}createData(){var e;return{v:1,sf:ah.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ue(t,this.createData());const i=t.ot===Oe.INIT||t.ot===Oe.VIDEO||t.ot===Oe.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:s}=this;s&&(t=Object.keys(t).reduce((a,o)=>(s.includes(o)&&(a[o]=t[o]),a),{}));const n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Mh(e.headers,t,n)):e.url=Bh(e.url,t,n)}getNextFrag(e){var t;const i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){const s=e.sn-i.startSN;return i.fragments[s+1]}}getNextPart(e){var t,i;const{index:s,fragment:n}=e,a=(t=this.hls.levels[n.level])==null||(i=t.details)==null?void 0:i.partList;if(a){const{sn:o}=n;for(let c=a.length-1;c>=0;c--){const l=a[c];if(l.index===s&&l.fragment.sn===o)return a[c+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Oe.TIMED_TEXT;if(e.sn==="initSegment")return Oe.INIT;if(t==="audio")return Oe.AUDIO;if(t==="main")return this.hls.audioTracks.length?Oe.VIDEO:Oe.MUXED}getTopBandwidth(e){let t=0,i;const s=this.hls;if(e===Oe.AUDIO)i=s.audioTracks;else{const n=s.maxAutoLevel,a=n>-1?n+1:s.levels.length;i=s.levels.slice(0,a)}for(const n of i)n.bitrate>t&&(t=n.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.media,i=e===Oe.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:J.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}}const $h=3e5;class Gh extends at{constructor(e){super("content-steering",e.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=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}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(e,t){const{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((i==null?void 0:i.action)===we.SendAlternateToPenaltyBox&&i.flags===Ke.MoveAllAlternatesMatchingHost){const s=this.levels;let n=this._pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:c,type:l}=t.context;o&&s?a=this.getPathwayForGroupId(o,l,a):c&&(a=c)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&s&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a),i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${s&&s.length} priorities: ${me(n)} penalized: ${me(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(n=>{s-i[n]>$h&&delete i[n]});for(let n=0;n0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,Da(t),this.hls.trigger(p.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[o];c&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":c}=n;if(t.some(d=>d.pathwayId===a))return;const l=this.getLevelsForPathway(o).map(d=>{const u=new ve(d.attrs);u["PATHWAY-ID"]=a;const h=u.AUDIO&&`${u.AUDIO}_clone_${a}`,f=u.SUBTITLES&&`${u.SUBTITLES}_clone_${a}`;h&&(i[u.AUDIO]=h,u.AUDIO=h),f&&(s[u.SUBTITLES]=f,u.SUBTITLES=f);const g=_o(d.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),m=new si({attrs:u,audioCodec:d.audioCodec,bitrate:d.bitrate,height:d.height,name:d.name,url:g,videoCodec:d.videoCodec,width:d.width});if(d.audioGroups)for(let y=1;y{this.log(`Loaded steering manifest: "${s}"`);const g=d.data;if((g==null?void 0:g.VERSION)!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":m,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":v}=g;if(m)try{this.uri=new self.URL(m,s).href}catch(b){this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||h.url),y&&this.clonePathways(y);const T={steeringManifest:g,url:s.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,T),v&&this.updatePathwayPriority(v)},onError:(d,u,h,f)=>{if(this.log(`Error loading steering manifest: ${d.code} ${d.text} (${u.url})`),this.stopLoad(),d.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let g=this.timeToLoad*1e3;if(d.code===429){const m=this.loader;if(typeof(m==null?void 0:m.getResponseHeader)=="function"){const y=m.getResponseHeader("Retry-After");y&&(g=parseFloat(y)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,g)},onTimeout:(d,u,h)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(n,c,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const s=(i=this.hls)==null?void 0:i.media;if(s&&!s.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Lo(r,e,t,i){r&&Object.keys(e).forEach(s=>{const n=r.filter(a=>a.groupId===s).map(a=>{const o=ue({},a);return o.details=void 0,o.attrs=new ve(o.attrs),o.url=o.attrs.URI=_o(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[s],o.attrs["PATHWAY-ID"]=i,o});r.push(...n)})}function _o(r,e,t,i){const{HOST:s,PARAMS:n,[t]:a}=i;let o;e&&(o=a==null?void 0:a[e],o&&(r=o));const c=new self.URL(r);return s&&!o&&(c.host=s),n&&Object.keys(n).sort().forEach(l=>{l&&c.searchParams.set(l,n[l])}),c.href}class $t extends at{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=$t.CDMCleanupPromise?[$t.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:i,initData:s}=t,n=`"${t.type}" event: init data type: "${i}"`;if(this.debug(n),s!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Vi(this.config));const o=a.map(zs).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=js(a);let c,l;if(i==="sinf"){if(o!==ce.FAIRPLAY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${o}`);return}const g=Se(new Uint8Array(s));try{const m=Ws(JSON.parse(g).sinf),y=Pn(m);if(!y)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(y.subarray(8,24)),l=ce.FAIRPLAY}catch(m){this.warn(`${n} Failed to parse sinf: ${m}`);return}}else{if(o!==ce.WIDEVINE&&o!==ce.PLAYREADY){this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${i}" for selected key-system ${o}`);return}const g=jc(s),m=g.filter(v=>!!v.systemId&&qs(v.systemId)===o);m.length>1&&this.warn(`${n} Using first of ${m.length} pssh found for selected key-system ${o}`);const y=m[0];if(!y){g.length===0||g.some(v=>!v.systemId)?this.warn(`${n} contains incomplete or invalid pssh data`):this.log(`ignoring ${n} for ${g.map(v=>qs(v.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(l=qs(y.systemId),y.version===0&&y.data)if(l===ce.WIDEVINE){const v=y.data.length-22;c=new Uint8Array(y.data.subarray(v,v+16))}else l===ce.PLAYREADY&&(c=ga(y.data))}if(!l||!c)return;const d=Xe.hexDump(c),{keyIdToKeySessionPromise:u,mediaKeySessions:h}=this;let f=u[d];for(let g=0;gthis.generateRequestWithPreferredKeySession(m,i,s,"encrypted-event-key-match")),f.catch(T=>this.handleError(T));break}}if(!f){if(l!==o){this.log(`Ignoring "${t.type}" event with ${l} init data for selected key-system ${o}`);return}f=u[d]=this.getKeySystemSelectionPromise([l]).then(({keySystem:g,mediaKeys:m})=>{var y;this.throwIfDestroyed();const v=new ni("ISO-23001-7",d,(y=zs(g))!=null?y:"");return v.pssh=new Uint8Array(s),v.keyId=c,this.attemptSetMediaKeys(g,m).then(()=>{this.throwIfDestroyed();const T=this.createMediaKeySessionContext({decryptdata:v,keySystem:g,mediaKeys:m});return this.generateRequestWithPreferredKeySession(T,i,s,"encrypted-event-no-match")})}),f.catch(g=>this.handleError(g))}})}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){const e=this.media;this.unregisterListeners(),this.onMediaDetached(),this._clear(e);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}registerListeners(){this.hls.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(p.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(p.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,s=t[e];if(s)return s.licenseUrl;if(e===ce.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(a,o,c)=>!!a&&c.indexOf(a)===o,s=t.map(a=>a.audioCodec).filter(i),n=t.map(a=>a.videoCodec).filter(i);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{const c=l=>{const d=l.shift();this.getMediaKeysPromise(d,s,n).then(u=>a({keySystem:d,mediaKeys:u})).catch(u=>{l.length?c(l):u instanceof Ge?o(u):o(new Ge({type:G.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${i}`;return fa===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return i(e,t)}getMediaKeysPromise(e,t,i){const s=Bd(e,t,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[e];let a=n==null?void 0:n.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${me(s)}`),a=this.requestMediaKeySystemAccess(e,s);const o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(c=>{this.log(`Failed to obtain access to key-system "${e}": ${c}`)}),a.then(c=>{this.log(`Access for key-system "${c.keySystem}" obtained`);const l=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=c.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),l.then(u=>u?this.setMediaKeysServerCertificate(d,e,u):d))),o.mediaKeys.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),o.mediaKeys})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${Xe.hexDump(e.keyId||[])}`);const s=i.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),s=this.getKeyIdString(t),n="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,n,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return Xe.hexDump(e.keyId)}updateKeySession(e,t){var i;const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyID ${Xe.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])} } (data length: ${t&&t.byteLength})`),s.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,i)=>{const s=Vi(this.config),n=e.map(js).filter(a=>!!a&&s.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(n).then(({keySystem:a})=>{const o=zs(a);o?t(o):i(new Error(`Unable to find format for key-system "${a}"`))}).catch(i)})}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),s=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${s}`);let n=this.keyIdToKeySessionPromise[i];return n||(n=this.getKeySystemForKeyPromise(t).then(({keySystem:o,mediaKeys:c})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${s}`),this.attemptSetMediaKeys(o,c).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:o,mediaKeys:c,decryptdata:t}))))),(this.keyIdToKeySessionPromise[i]=n.then(o=>{const c="cenc",l=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(o,c,l,"playlist-key")})).catch(o=>this.handleError(o))),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Ge?this.hls.trigger(p.ERROR,e.data):this.hls.trigger(p.ERROR,{type:G.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const s=js(e.keyFormat),n=s?[s]:Vi(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Vi(this.config)),e.length===0)throw new Ge({type:G.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${me({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const s=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,i,s){var n,a;const o=(n=this.config.drmSystems)==null||(a=n[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const g=o.call(this.hls,t,i,e);if(!g)throw new Error("Invalid response from configured generateRequest filter");t=g.initDataType,i=g.initData?g.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(g){var c;if(this.warn(g.message),(c=this.hls)!=null&&c.config.debug)throw g}if(i===null)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e);const l=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${s}": ${l} (init data type: ${t} length: ${i?i.byteLength:null})`);const d=new ir,u=e._onmessage=g=>{const m=e.mediaKeysSession;if(!m){d.emit("error",new Error("invalid state"));return}const{messageType:y,message:v}=g;this.log(`"${y}" message event for session "${m.sessionId}" message size: ${v.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,v).catch(T=>{d.eventNames().length?d.emit("error",T):this.handleError(T)}):y==="license-release"?e.keySystem===ce.FAIRPLAY&&(this.updateKeySession(e,Ys("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${y}"`)},h=e._onkeystatuseschange=g=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const y=e.keyStatus;d.emit("keyStatus",y),y==="expired"&&(this.warn(`${e.keySystem} expired for key ${l}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",u),e.mediaKeysSession.addEventListener("keystatuseschange",h);const f=new Promise((g,m)=>{d.on("error",m),d.on("keyStatus",y=>{y.startsWith("usable")?g():y==="output-restricted"?m(new Ge({type:G.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):y==="internal-error"?m(new Ge({type:G.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${y}"`)):y==="expired"?m(new Error("key expired while generating request")):this.warn(`unhandled key status change "${y}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var g;this.log(`Request generated for key-session "${(g=e.mediaKeysSession)==null?void 0:g.sessionId}" keyId: ${l}`)}).catch(g=>{throw new Ge({type:G.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_SESSION,error:g,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>{throw d.removeAllListeners(),this.removeSession(e),g}).then(()=>(d.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{if(typeof i=="string"&&typeof t=="object"){const s=i;i=t,t=s}this.log(`key status change "${t}" for keyStatuses keyId: ${Xe.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${Xe.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,i=t.loader,s=new i(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const c={responseType:"arraybuffer",url:n},l=t.certLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(h,f,g,m)=>{a(h.data)},onError:(h,f,g,m)=>{o(new Ge({type:G.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:le({url:c.url,data:void 0},h)},`"${e}" certificate request failed (${n}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,g)=>{o(new Ge({type:G.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(h,f,g)=>{o(new Error("aborted"))}};s.load(c,d,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((s,n)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${t}"`),s(e)}).catch(a=>{n(new Ge({type:G.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(s=>{throw new Ge({type:G.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:s,fatal:!0},s.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const s=new DOMParser().parseFromString(i,"application/xml"),n=s.querySelectorAll("HttpHeader");if(n.length>0){let d;for(let u=0,h=n.length;u in key message");return Ys(atob(l))}setupLicenseXHR(e,t,i,s){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,i,s)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,i,s)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||s})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:s}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((s,n)=>{const a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const l=this.config.licenseResponseCallback;if(l)try{c=l.call(this.hls,o,a,e)}catch(d){this.error(d)}s(c)}else{const c=i.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)n(new Ge({type:G.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const d=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${d} attempts left`),this.requestLicense(e,t).then(s,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:c,licenseChallenge:l})=>{e.keySystem==ce.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(c,l)),c.send(l)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.removeEventListener("encrypted",this.onMediaEncrypted),i.removeEventListener("waitingforkey",this.onWaitingForKey),i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null)}_clear(e){var t;const i=this.mediaKeySessions;this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},ni.clearKeyUriToKeyIdMap();const s=i.length;$t.CDMCleanupPromise=Promise.all(i.map(n=>this.removeSession(n)).concat(e==null||(t=e.setMediaKeys(null))==null?void 0:t.catch(n=>{var a;this.log(`Could not clear media keys: ${n}`),(a=this.hls)==null||a.trigger(p.ERROR,{type:G.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${n}`)})}))).then(()=>{s&&(this.log("finished closing key sessions and clearing media keys"),i.length=0)}).catch(n=>{var a;this.log(`Could not close sessions and clear media keys: ${n}`),(a=this.hls)==null||a.trigger(p.ERROR,{type:G.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${n}`)})})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((s,n)=>(s.indexOf(n.keyFormat)===-1&&s.push(n.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const s=this.mediaKeySessions.indexOf(e);s>-1&&this.mediaKeySessions.splice(s,1);const{drmSystemOptions:n}=this.config;return($d(n)?new Promise((o,c)=>{self.setTimeout(()=>c(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(o)}):Promise.resolve()).catch(o=>{var c;this.log(`Could not remove session: ${o}`),(c=this.hls)==null||c.trigger(p.ERROR,{type:G.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${o}`)})}).then(()=>t.close()).catch(o=>{var c;this.log(`Could not close session: ${o}`),(c=this.hls)==null||c.trigger(p.ERROR,{type:G.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${o}`)})})}}}$t.CDMCleanupPromise=void 0;class Ge extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}class Vh{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(p.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(p.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const s=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){const s=performance.now();if(t){if(this.lastTime){const n=s-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,c=1e3*a/n,l=this.hls;if(l.trigger(p.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),c>0&&a>l.config.fpsDroppedMonitoringThreshold*o){let d=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=d)&&(d=d-1,l.trigger(p.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:l.currentLevel}),l.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function Io(r,e){let t;try{t=new Event("addtrack")}catch(i){t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=r,e.dispatchEvent(t)}function Ro(r,e){const t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues&&!r.cues.getCueById(e.id))try{if(r.addCue(e),!r.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){ie.debug(`[texttrack-utils]: ${i}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,r.addCue(s)}catch(s){ie.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}t==="disabled"&&(r.mode=t)}function Gt(r,e){const t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues)for(let i=r.cues.length;i--;)e&&r.cues[i].removeEventListener("enter",e),r.removeCue(r.cues[i]);t==="disabled"&&(r.mode=t)}function xr(r,e,t,i){const s=r.mode;if(s==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){const n=Kh(r.cues,e,t);for(let a=0;ar[t].endTime)return-1;let i=0,s=t,n;for(;i<=s;)if(n=Math.floor((s+i)/2),er[n].startTime&&i-1)for(let n=s,a=r.length;n=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}function Zi(r){const e=[];for(let t=0;tthis.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const i=Zi(this.media.textTracks);for(let n=0;n-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.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(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const s=!!t.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;Zi(i.textTracks).forEach(a=>{Gt(a)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:s,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,s=this.groupIds;let n=this.currentTrack;if(!i||(s==null?void 0:s.length)!==(i==null?void 0:i.length)||i!=null&&i.some(a=>(s==null?void 0:s.indexOf(a))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(d=>!i||i.indexOf(d.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(d=>d.default)&&(this.selectDefaultTrack=!1),a.forEach((d,u)=>{d.id=u});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;const d=Ze(o,a);if(d>-1)n=a[d];else{const u=Ze(o,this.tracks);n=this.tracks[u]}}let c=this.findTrackId(n);c===-1&&n&&(c=this.findTrackId(null));const l={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i==null?void 0:i.join(",")}" group-id`),this.hls.trigger(p.SUBTITLE_TRACKS_UPDATED,l),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s-1){const n=this.tracksInGroup[s];return this.setSubtitleTrack(s),n}else{if(i)return null;{const n=Ze(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,s=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${s}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(p.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Zi(e.textTracks),i=this.currentTrack;let s;if(i&&(s=t.filter(n=>mr(i,n))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==s&&(n.mode="disabled")}),s){const n=this.subtitleDisplay?"showing":"hidden";s.mode!==n&&(s.mode=n)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!B(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e]||null;if(this.trackId=e,this.currentTrack=s,this.toggleTrackModes(),!s){this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:e});return}const n=!!s.details&&!s.details.live;if(e===this.trackId&&s===i&&n)return;this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:a,groupId:o="",name:c,type:l,url:d}=s;this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:c,type:l,url:d});const u=this.switchParams(s.url,i==null?void 0:i.details,s.details);this.loadPlaylist(u)}}function gi(r){let e=5381,t=r.length;for(;t;)e=e*33^r.charCodeAt(--t);return(e>>>0).toString()}const Vt=.025;let es=function(r){return r[r.Point=0]="Point",r[r.Range=1]="Range",r}({});function Yh(r,e,t){return`${r.identifier}-${t+1}-${gi(e)}`}class jh{constructor(e,t){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=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){if(e>=this.assetList.length)return!0;const t=this.playoutLimit;return e<=0||isNaN(t)?!1:this.assetList[e].startOffset>t}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return Sr(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,i=Sr(t,e);return t-i<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=B(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return Sr(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)0||this.assetListResponse!==null}toString(){return qh(this)}}function Sr(r,e){return r-e.start":r.cue.post?"":""}${r.timelineStart.toFixed(2)}-${r.resumeTime.toFixed(2)}]`}function Ar(r){const e=r.timelineStart,t=r.duration||0;return`["${r.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class zh{constructor(e,t,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=()=>{const l=this.interstitial.playoutLimit,d=this.currentTime;this.startOffset+d>=l&&this.hls.trigger(p.PLAYOUT_LIMIT_REACHED,{})};const n=this.hls=new e(t);this.interstitial=i,this.assetItem=s;let a=s.uri;try{a=ko(a,n.sessionId).href}catch(c){}n.loadSource(a);const o=()=>{this.hasDetails=!0};n.once(p.LEVEL_LOADED,o),n.once(p.AUDIO_TRACK_LOADED,o),n.once(p.SUBTITLE_TRACK_LOADED,o),n.on(p.MEDIA_ATTACHING,(c,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&l.addEventListener("timeupdate",this.checkPlayout)})}bufferedInPlaceToEnd(e){var t;if(!this.interstitial.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e||!this._bufferedEosTime)return!1;const i=this.timelineOffset,s=J.bufferInfo(e,i,0);return this.getAssetTime(s.end)>=this._bufferedEosTime-.02}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=J.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;return e||0}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const i=e-t;if(Math.abs(i)>1/9e4){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){this.hls.attachMedia(e)}detachMedia(){this.removeMediaListeners(),this.mediaAttached=null,this.hls.detachMedia()}resumeBuffering(){this.hls.resumeBuffering()}pauseBuffering(){this.hls.pauseBuffering()}transferMedia(){return this.bufferSnapShot(),this.hls.transferMedia()}on(e,t,i){this.hls.on(e,t)}once(e,t,i){this.hls.once(e,t)}off(e,t,i){this.hls.off(e,t)}toString(){var e,t;return`HlsAssetPlayer: ${Ar(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${(t=this.interstitial)!=null&&t.appendInPlace?"append-in-place":""}`}}const wo=.033;class Xh extends at{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,s)=>e<=s.startOffset&&t>s.startOffset?(delete s.error,i+1):i,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);const s=this.items;if(s)for(s[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(n=s[i])!=null&&n.event;){var n;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let s=0;sn.start&&e1)for(let n=0;no&&t!o.includes(l.identifier)):[];a.length&&a.sort((l,d)=>{const u=l.cue.pre,h=l.cue.post,f=d.cue.pre,g=d.cue.post;if(u&&!f)return-1;if(f&&!u||h&&!g)return 1;if(g&&!h)return-1;if(!u&&!f&&!h&&!g){const m=l.startTime,y=d.startTime;if(m!==y)return m-y}return l.dateRange.tagOrder-d.dateRange.tagOrder}),this.events=a,c.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,c)}updateSchedule(e,t=[]){const i=this.events||[];if(i.length||t.length||this.length<2){const s=this.items,n=this.parseSchedule(i,e);(t.length||(s==null?void 0:s.length)!==n.length||n.some((o,c)=>Math.abs(o.playout.start-s[c].playout.start)>.005||Math.abs(o.playout.end-s[c].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(t,s))}}parseDateRanges(e,t,i){const s=[],n=Object.keys(e);for(let a=0;a!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,l=0;if(e.forEach((d,u)=>{const h=d.cue.pre,f=d.cue.post,g=e[u-1]||null,m=d.appendInPlace,y=f?n:d.startOffset,v=d.duration,T=d.timelineOccupancy===es.Range?v:0,b=d.resumptionOffset,x=(g==null?void 0:g.startTime)===y,S=y+d.cumulativeDuration;let k=m?S+v:y+b;if(h||!f&&y<=0){const I=l;l+=T,d.timelineStart=S;const w=a;a+=v,i.push({event:d,start:S,end:k,playout:{start:w,end:a},integrated:{start:I,end:l}})}else if(y<=n){if(!x){const L=y-c;if(L>wo){const D=c,M=l;l+=L;const te=a;a+=L;const Y={previousEvent:e[u-1]||null,nextEvent:d,start:D,end:D+L,playout:{start:te,end:a},integrated:{start:M,end:l}};i.push(Y)}else L>0&&g&&(g.cumulativeDuration+=L,i[i.length-1].end=y)}f&&(k=S),d.timelineStart=S;const I=l;l+=T;const w=a;a+=v,i.push({event:d,start:S,end:k,playout:{start:w,end:a},integrated:{start:I,end:l}})}else return;const A=d.resumeTime;f||A>n?c=n:c=A}),c{const l=o.cue.pre,d=o.cue.post,u=l?0:d?s:o.startTime;this.updateAssetDurations(o),a===u?o.cumulativeDuration=n:(n=0,a=u),!d&&o.snapOptions.in&&(o.resumeAnchor=_t(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1Vt?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1):t?!Object.keys(t).some(a=>{const o=t[a].details,c=o.edge;if(i>=c)return this.log(`"${e.identifier}" resumption ${i} past ${a} playlist end ${c}`),!1;const l=_t(null,o.fragments,i);if(!l)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const d=a==="audio"?.175:0;return Math.abs(l.start-i){const c=t+i;a.startOffset=i,a.timelineStart=c,s||(s=a.duration===null),n||(n=!!a.error);const l=a.error?0:a.duration||0;i+=l}),s&&!n?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function bt(r){return`[${r.event?'"'+r.event.identifier+'"':"primary"}: ${r.start.toFixed(2)}-${r.end.toFixed(2)}]`}class Qh{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const i=e.assetListUrl;let s;try{s=ko(i,this.hls.sessionId,e.baseUrl)}catch(h){const f=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,h,i);this.hls.trigger(p.ERROR,f);return}t&&s.protocol!=="data:"&&s.searchParams.set("_HLS_start_offset",""+t);const n=this.hls.config,a=n.loader,o=new a(n),c={responseType:"json",url:s.href},l=n.interstitialAssetListLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(h,f,g,m)=>{const y=h.data,v=y==null?void 0:y.ASSETS;if(!Array.isArray(v)){const T=this.assignAssetListError(e,R.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,m);this.hls.trigger(p.ERROR,T);return}e.assetListResponse=y,this.hls.trigger(p.ASSET_LIST_LOADED,{event:e,assetListResponse:y,networkDetails:m})},onError:(h,f,g,m)=>{const y=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${f.url})`),f.url,m,g);this.hls.trigger(p.ERROR,y)},onTimeout:(h,f,g)=>{const m=this.assignAssetListError(e,R.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,h,g);this.hls.trigger(p.ERROR,m)}};return o.load(c,d,u),this.hls.trigger(p.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,i,s,n,a){return e.error=i,{type:G.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:s,error:i,networkDetails:a,stats:n}}}function dt(r,e,t){st(r,e,t),r.addEventListener(e,t)}function st(r,e,t){r.removeEventListener(e,t)}function Co(r){r==null||r.play().catch(()=>{})}class Jh extends at{constructor(e,t){super("interstitials",e.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},this.onSeeking=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;const s=i-this.timelinePos;if(Math.abs(s)<1/7056e5)return;const a=s<=-.01;this.timelinePos=i,this.bufferedPos=i;const o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(i,i-s)&&this.updateSchedule(),this.checkBuffer(),a&&i=o.end){var c;const h=this.schedule.findItemIndexAtTime(this.timelinePos);if(!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!a){const f=this.findItemIndex(o);if(h>f){const g=this.schedule.findJumpRestrictedIndex(f+1,h);if(g>f){this.setSchedulePosition(g);return}}}this.setSchedulePosition(h);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const h=o.event.assetList[0];h&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,h))}return}const d=l.timelineStart,u=l.duration||0;(a&&i=d+u)&&this.setScheduleToAssetAtTime(i,l)},this.onTimeupdate=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;const s=this.playingItem;if(!s||this.playingLastItem)return;if(i>=s.end){this.timelinePos=s.end;const o=this.findItemIndex(s);this.setSchedulePosition(o+1)}const n=this.playingAsset;if(!n)return;const a=n.timelineStart+(n.duration||0);i>=a&&this.setScheduleToAssetAtTime(i,n)},this.onScheduleUpdate=(i,s)=>{const n=this.schedule,a=this.playingItem,o=n.events||[],c=n.items||[],l=n.durations,d=i.map(f=>f.identifier),u=!!(o.length||d.length);if(u&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o} Schedule: ${c.map(f=>bt(f))}`),d.length&&this.log(`Removed events ${d}`),this.playerQueue.forEach(f=>{if(f.interstitial.appendInPlace){const g=f.assetItem.timelineStart,m=f.timelineOffset-g;if(m)try{f.timelineOffset=g}catch(y){Math.abs(m)>Vt&&this.warn(`${y} ("${f.assetId}" ${f.timelineOffset}->${g})`)}}}),a){const f=this.updateItem(a,this.timelinePos);this.itemsMatch(a,f)&&(this.playingItem=f,this.waitingItem=this.endedItem=null)}else this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const h=this.bufferingItem;if(h){const f=this.updateItem(h,this.bufferedPos);this.itemsMatch(h,f)?this.bufferingItem=f:h.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(h.event,null))}if(i.forEach(f=>{f.assetList.forEach(g=>{this.clearAssetPlayer(g.identifier,null)})}),u||s){if(this.hls.trigger(p.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:l,removedIds:d}),this.isInterstitial(a)&&d.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Qh(e),this.schedule=new Xh(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(p.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(p.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(p.MEDIA_ENDED,this.onMediaEnded,this),e.on(p.ERROR,this.onError,this),e.on(p.DESTROYING,this.onDestroying,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(p.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(p.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(p.MEDIA_ENDED,this.onMediaEnded,this),e.off(p.ERROR,this.onError,this),e.off(p.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.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.manager=null,this.hls=this.HlsPlayerClass=this.schedule=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){st(e,"play",this.onPlay),st(e,"pause",this.onPause),st(e,"seeking",this.onSeeking),st(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;dt(i,"seeking",this.onSeeking),dt(i,"timeupdate",this.onTimeupdate),dt(i,"play",this.onPlay),dt(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!s){this.clearScheduleState();const n=this.findItemIndex(i);this.setSchedulePosition(n)}}clearScheduleState(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const i=!!t.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){const n=this.getBufferingPlayer();n&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.manager){if(!this.hls)return null;const e=this,t=()=>e.bufferingItem||e.waitingItem,i=u=>u&&e.getAssetPlayer(u.identifier),s=(u,h,f,g,m)=>{if(u){let y=u[h].start;const v=u.event;if(v){if(h==="playout"||v.timelineOccupancy!==es.Point){const T=i(f);(T==null?void 0:T.interstitial)===v&&(y+=T.assetItem.startOffset+T[m])}}else{const T=g==="bufferedPos"?a():e[g];y+=T-u.start}return y}return 0},n=(u,h)=>{if(u!==0&&h!=="primary"&&e.schedule.length){var f;const g=e.schedule.findItemIndexAtTime(u),m=(f=e.schedule.items)==null?void 0:f[g];if(m){const y=m[h].start-m.start;return u+y}}return u},a=()=>{const u=e.bufferedPos;return u===Number.MAX_VALUE?o("primary"):Math.max(u,0)},o=u=>{var h;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:e.schedule.durations[u]},c=(u,h)=>{var f,g;const m=e.effectivePlayingItem;if(m!=null&&(f=m.event)!=null&&f.restrictions.skip)return;e.log(`seek to ${u} "${h}"`);const y=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(u,h),T=(g=e.schedule.items)==null?void 0:g[v],b=e.getBufferingPlayer(),x=b==null?void 0:b.interstitial,S=x==null?void 0:x.appendInPlace,k=y&&e.itemsMatch(y,T);if(y&&(S||k)){const I=i(e.playingAsset),w=(I==null?void 0:I.media)||e.primaryMedia;if(w){const L=h==="primary"?w.currentTime:s(y,h,e.playingAsset,"timelinePos","currentTime"),D=u-L,M=(S?L:w.currentTime)+D;if(M>=0&&(!I||S||M<=I.duration)){w.currentTime=M;return}}}if(T){let I=u;if(h!=="primary"){const L=T[h].start,D=u-L;I=T.start+D}const w=!e.isInterstitial(T);if((!e.isInterstitial(y)||y.event.appendInPlace)&&(w||T.event.appendInPlace)){const L=e.media||(S?b==null?void 0:b.media:null);L&&(L.currentTime=I)}else if(y){const L=e.findItemIndex(y);if(v>L){const M=e.schedule.findJumpRestrictedIndex(L+1,v);if(M>L){e.setSchedulePosition(M);return}}let D=0;if(w)e.timelinePos=I,e.checkBuffer();else{var A;const M=T==null||(A=T.event)==null?void 0:A.assetList;if(M){const te=u-(T[h]||T).start;for(let Y=M.length;Y--;){const H=M[Y];if(H.duration&&te>=H.startOffset&&te{const u=e.effectivePlayingItem;if(e.isInterstitial(u))return u;const h=t();return e.isInterstitial(h)?h:null},d={get currentTime(){const u=l(),h=e.effectivePlayingItem;return h&&h===u?s(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(u){const h=l(),f=e.effectivePlayingItem;f&&f===h&&c(u+f.playout.start,"playout")},get duration(){const u=l();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;const h=(u=l())==null?void 0:u.event.assetList;return h?h.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var u;const h=(u=l())==null?void 0:u.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};this.manager={get events(){var u,h;return((u=e.schedule)==null||(h=u.events)==null?void 0:h.slice(0))||[]},get schedule(){var u,h;return((u=e.schedule)==null||(h=u.items)==null?void 0:h.slice(0))||[]},get interstitialPlayer(){return l()?d:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const u=t();return e.findItemIndex(u)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const u=e.effectivePlayingItem;return e.findItemIndex(u)},primary:{get bufferedEnd(){return a()},get currentTime(){const u=e.timelinePos;return u>0?u:0},set currentTime(u){c(u,"primary")},get duration(){return o("primary")},get seekableStart(){var u;return((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0}},integrated:{get bufferedEnd(){return s(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(u){c(u,"integrated")},get duration(){return o("integrated")},get seekableStart(){var u;return n(((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0,"integrated")}},skip:()=>{const u=e.effectivePlayingItem,h=u==null?void 0:u.event;if(h&&!h.restrictions.skip){const f=e.findItemIndex(u);if(h.appendInPlace){const g=u.playout.start+u.event.duration;c(g+.001,"playout")}else e.advanceAfterAssetEnded(h,f,1/0)}}}}return this.manager}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!i?!1:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t,i;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let n=this.media;!n&&(e=this.bufferingItem)!=null&&(t=e.event)!=null&&t.appendInPlace&&(n=this.primaryMedia);const a=(i=n)==null?void 0:i.currentTime;if(!(a===void 0||!B(a)))return a}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){const i=e.interstitial.appendInPlace,s=e.media;if(i&&s===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&s){this.detachedData={media:s};return}const n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${me(n)}`),this.detachedData=n}else t&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(e,t){var i,s;if(e.media===t)return;let n=null;const a=this.hls,o=e!==a,c=o&&e.interstitial.appendInPlace,l=(i=this.detachedData)==null?void 0:i.mediaSource;let d;if(a.media)c&&(n=a.transferMedia(),this.detachedData=n),d="Primary";else if(l){const f=this.getBufferingPlayer();f?(n=f.transferMedia(),d=`${f}`):d="detached MediaSource"}else d="detached media";if(!n){if(l)n=this.detachedData,this.log(`using detachedData: MediaSource ${me(n)}`);else if(!this.detachedData||a.media===t){const f=this.playerQueue;f.length>1&&f.forEach(g=>{if(o&&g.interstitial.appendInPlace!==c){const m=g.interstitial;this.clearInterstitial(g.interstitial,null),m.appendInPlace=!1,m.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${m}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const u=n&&"mediaSource"in n&&((s=n.mediaSource)==null?void 0:s.readyState)!=="closed",h=u&&n?n:t;if(this.log(`${u?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${d}`),h===n){const f=o&&e.assetId===this.schedule.assetIdAtEnd;h.overrides={duration:this.schedule.duration,endOfStream:!o||f,cueRemoval:!o}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const i=this.timelinePos,s=this.effectivePlayingItem;if(i===-1){const n=this.hls.startPosition;if(this.timelinePos=n,t.length&&t[0].cue.pre){const a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(n>=0||!this.primaryLive){const a=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}}else if(s&&!this.playingItem){const n=e.findItemIndex(s);this.setSchedulePosition(n)}}advanceAfterAssetEnded(e,t,i){const s=i+1;if(!e.isAssetPastPlayoutLimit(s)&&!e.assetList[s].error)this.setSchedulePosition(t,s);else{const n=this.schedule.items;if(n){const a=t+1,o=n.length;if(a>=o){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos=0?i[e]:null,n=this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){var o;const l=n.event,d=this.playingAsset,u=d==null?void 0:d.identifier,h=u?this.getAssetPlayer(u):null;if(h&&u&&(!this.eventItemsMatch(n,s)||t!==void 0&&u!==((o=l.assetList)==null?void 0:o[t].identifier))){var c;const f=l.findAssetIndex(d);this.log(`INTERSTITIAL_ASSET_ENDED ${f+1}/${l.assetList.length} ${Ar(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(p.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:f,event:l,schedule:i.slice(0),scheduleIndex:e,player:h}),this.retreiveMediaSource(u,s),h.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&h.detachMedia()}if(!this.eventItemsMatch(n,s)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${l} ${bt(n)}`),l.hasPlayed=!0,this.hls.trigger(p.INTERSTITIAL_ENDED,{event:l,schedule:i.slice(0),scheduleIndex:e}),l.cue.once)){this.updateSchedule();const f=this.schedule.items;if(s&&f){const g=this.schedule.findItemIndex(s);this.advanceSchedule(g,f,t,n,a)}return}}this.advanceSchedule(e,i,t,n,a)}advanceSchedule(e,t,i,s,n){const a=e>=0?t[e]:null,o=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(l=>{const d=l.interstitial,u=this.schedule.findEventIndex(d.identifier);(ue+1)&&this.clearInterstitial(d,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const l=a.event;i===void 0&&(i=this.schedule.findAssetIndex(l,this.timelinePos));const d=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let u=this.preloadAssets(l,i);if(this.eventItemsMatch(a,d||s)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${bt(a)} ${l.appendInPlace?"append in place":""}`),this.hls.trigger(p.INTERSTITIAL_STARTED,{event:l,schedule:t.slice(0),scheduleIndex:e})),!l.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${l}`);return}if(l.assetListLoader&&(l.assetListLoader.destroy(),l.assetListLoader=void 0),!o){this.log(`Waiting for attachMedia to start Interstitial ${l}`);return}this.waitingItem=this.endedItem=null,this.playingItem=a;const h=l.assetList[i];if(!h){const f=t[e+1],g=this.media;f&&g&&!this.isInterstitial(f)&&g.currentTime=e.end)&&(a=this.getPrimaryResumption(e,t),this.timelinePos=a),this.attachPrimary(a,e)}if(!i)return;const n=this.schedule.items;n&&(this.log(`resumed ${bt(e)}`),this.hls.trigger(p.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const s=this.primaryDetails;if(t===0)return this.hls.startPosition;if(s&&(is.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:J.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const s=this.primaryMedia;if(!s)return;const n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,s),i&&this.startLoadingPrimaryAt(e,i)),i||(this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;const s=this.hls;!s.loadingEnabled||!s.media||Math.abs((((i=s.mainForwardBufferInfo)==null?void 0:i.start)||s.media.currentTime)-e)>.5?s.startLoad(e,t):s.bufferingEnabled||s.resumeBuffering()}onManifestLoading(){this.stopLoad(),this.schedule.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(p.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(p.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1)return;const i=this.hls.levels[t.level],s=le(le({},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(e,t){const i=this.hls.audioTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=le(le({},this.altSelection),{},{audio:i});return}const n=le(le({},s),{},{audio:i});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=le(le({},this.altSelection),{},{subtitles:i});return}const n=le(le({},s),{},{subtitles:i});this.mediaSelection=n}onAudioTrackSwitching(e,t){const i=Xn(t);this.playerQueue.forEach(s=>s.hls.setAudioOption(t)||s.hls.setAudioOption(i))}onSubtitleTrackSwitch(e,t){const i=Xn(t);this.playerQueue.forEach(s=>s.hls.setSubtitleOption(t)||t.id!==-1&&s.hls.setSubtitleOption(i))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const s=this.timelinePos;this.bufferedPos=s,this.checkBuffer()}}onBufferedToEnd(e){const t=this.schedule.events;if(this.bufferedPose)return;if(t.length===1&&this.itemsMatch(t[0],n)){this.bufferedPos=e;return}const a=this.playingItem,o=this.findItemIndex(a);let c=s.findItemIndexAtTime(e);if(this.bufferedPos=n.end||(l=f.event)!=null&&l.appendInPlace&&e+.01>=f.start)&&(c=h),h-o>1&&(n==null||(d=n.event)==null?void 0:d.appendInPlace)===!1)return;if(this.bufferedPos=e,c>u&&c>o)this.bufferedToItem(f);else{const g=this.primaryDetails;this.primaryLive&&g&&e>g.edge-g.targetduration&&f.start{const n=this.getAssetPlayer(s.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(this.itemsMatch(e,t))this.bufferingItem!==e&&(this.bufferingItem=e);else{const{items:s,events:n}=i;if(!s||!n)return t;const a=this.isInterstitial(e),o=this.getBufferingPlayer();if(this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos)),!this.playbackDisabled){const c=o?o.remaining:t?t.end-this.timelinePos:0;this.log(`buffered to boundary ${bt(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),a?e.event.assetList.forEach(l=>{const d=this.getAssetPlayer(l.identifier);d&&d.resumeBuffering()}):(this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering()))}this.hls.trigger(p.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}return t}bufferedToItem(e,t=0){const i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;const s=this.detachedData;s?s.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,s=i.assetList.length===0&&!i.assetListLoader,n=i.cue.once;if(s||!n){const a=this.preloadAssets(i,t);if(a!=null&&a.interstitial.appendInPlace){const o=i.assetList[t],c=this.primaryMedia;o&&c&&this.bufferAssetPlayer(a,c)}}}preloadAssets(e,t){const i=e.assetUrl,s=e.assetList.length,n=s===0&&!e.assetListLoader,a=e.cue.once;if(n){const c=e.timelineStart;if(e.appendInPlace){var o;const h=this.playingItem;!this.isInterstitial(h)&&(h==null||(o=h.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(c+.25)}let l,d=0;if(!this.playingItem&&this.primaryLive&&(d=this.hls.startPosition,d===-1&&(d=this.hls.liveSyncPosition||0)),d&&!(e.cue.pre||e.cue.post)){const h=d-c;h>0&&(l=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:s} ${e}${l?` live-start: ${d} start-offset: ${l}`:""}`),i)return this.createAsset(e,0,0,c,e.duration,i);const u=this.assetListLoader.loadAssetList(e,l);u&&(e.assetListLoader=u)}else if(!a&&s){for(let c=t;c{this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:s})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i1){const x=t.duration;x&&b{if(b.live){const k=new Error(`Interstitials MUST be VOD assets ${e}`),A={fatal:!0,type:G.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:k};this.handleAssetItemError(A,e,this.schedule.findEventIndex(e.identifier),i,k.message);return}const x=b.edge-b.fragmentStart,S=t.duration;(S===null||x>S)&&(this.log(`Interstitial asset "${u}" duration change ${S} > ${x}`),t.duration=x,this.updateSchedule())};g.on(p.LEVEL_UPDATED,(b,{details:x})=>m(x)),g.on(p.LEVEL_PTS_UPDATED,(b,{details:x})=>m(x));const y=(b,x)=>{const S=this.getAssetPlayer(u);if(S&&x.tracks){S.off(p.BUFFER_CODECS,y),S.tracks=x.tracks;const k=this.primaryMedia;this.bufferingAsset===S.assetItem&&k&&!S.media&&this.bufferAssetPlayer(S,k)}};g.on(p.BUFFER_CODECS,y);const v=()=>{var b;const x=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${x}`),!x)return;const S=this.schedule.findEventIndex(e.identifier),k=e.findAssetIndex(t),A=k+1,I=(b=this.schedule.items)==null?void 0:b[S];if(this.isInterstitial(I))if(k!==-1&&!e.isAssetPastPlayoutLimit(A)&&!e.assetList[A].error)this.bufferedToItem(I,A);else{var w;const L=(w=this.schedule.items)==null?void 0:w[S+1];L&&this.bufferedToItem(L)}};g.on(p.BUFFERED_TO_END,v);const T=b=>()=>{if(!this.getAssetPlayer(u))return;this.shouldPlay=!0;const S=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,S,b)};return g.once(p.MEDIA_ENDED,T(i)),g.once(p.PLAYOUT_LIMIT_REACHED,T(1/0)),g.on(p.ERROR,(b,x)=>{const S=this.getAssetPlayer(u);if(x.details===R.BUFFER_STALLED_ERROR){if(S!=null&&S.media){const k=S.currentTime,A=S.duration-k;k&&e.appendInPlace&&A/S.media.playbackRate<.5?(this.log(`Advancing buffer past end of asset ${u} ${e} at ${S.media.currentTime}`),v()):(this.warn(`Stalled at ${k} of ${k+A} in asset ${u} ${e}`),this.onTimeupdate(),this.checkBuffer(!0))}return}this.handleAssetItemError(x,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${x.error} ${e}`)}),g.on(p.DESTROYING,()=>{if(!this.getAssetPlayer(u))return;const x=new Error(`Asset player destroyed unexpectedly ${u}`),S={fatal:!0,type:G.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:x};this.handleAssetItemError(S,e,this.schedule.findEventIndex(e.identifier),i,x.message)}),this.hls.trigger(p.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:g}),g}clearInterstitial(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)}),e.reset()}clearAssetPlayer(e,t){const i=this.getAssetPlayerQueueIndex(e);if(i!==-1){this.log(`clearAssetPlayer "${e}" toSegment: ${t&&bt(t)}`);const s=this.playerQueue[i];this.transferMediaFromPlayer(s,t),this.playerQueue.splice(i,1),s.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,s,n){const{interstitial:a,assetItem:o,assetId:c}=e,l=a.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!d||d.identifier!==c)&&(d&&(this.clearAssetPlayer(d.identifier,i[s]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${e}`),this.hls.trigger(p.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:i.slice(0),scheduleIndex:s,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var i,s;const{interstitial:n,assetItem:a,assetId:o}=e,c=this.schedule.findEventIndex(n.identifier),l=(i=this.schedule.items)==null?void 0:i[c];if(!l)return;this.setBufferingItem(l),this.bufferingAsset=a;const d=this.getBufferingPlayer();if(d===e)return;const u=n.appendInPlace;if(u&&(d==null?void 0:d.interstitial.appendInPlace)===!1)return;const h=(d==null?void 0:d.tracks)||((s=this.detachedData)==null?void 0:s.tracks)||this.requiredTracks;if(u&&a!==this.playingAsset){if(!e.tracks)return;if(h&&!An(h,e.tracks)){const f=new Error(`Asset "${o}" SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),g={fatal:!0,type:G.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:f},m=n.findAssetIndex(a);this.handleAssetItemError(g,n,c,m,f.message);return}}this.transferMediaTo(e,t)}handleAssetItemError(e,t,i,s,n){if(e.details===R.BUFFER_STALLED_ERROR)return;const a=t.assetList[s]||null;let o=null;if(a){const u=this.getAssetPlayerQueueIndex(a.identifier);o=this.playerQueue[u]||null}const c=this.schedule.items,l=ue({},e,{fatal:!1,errorAction:ri(!0),asset:a,assetListIndex:s,event:t,schedule:c,scheduleIndex:i,player:o});if(this.warn(`Asset item error: ${e.error}`),this.hls.trigger(p.INTERSTITIAL_ASSET_ERROR,l),!e.fatal)return;const d=new Error(n);a&&(this.playingAsset!==a&&this.clearAssetPlayer(a.identifier,null),a.error=d),t.assetList.some(u=>!u.error)?t.appendInPlace&&(t.error=d):t.error=d,this.primaryFallback(t)}primaryFallback(e){const t=e.timelineStart,i=this.effectivePlayingItem;if(this.updateSchedule(),i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${i?bt(i):""} error: ${e.error}`),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t));let s=this.timelinePos;s===-1&&(s=this.hls.startPosition);const n=this.updateItem(i,s);if(this.itemsMatch(i,n))this.clearInterstitial(e,null);else{const a=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(a)}}else this.checkStart()}onAssetListLoaded(e,t){var i;const s=t.event,n=s.identifier,a=t.assetListResponse.ASSETS;if(!this.schedule.hasEvent(n))return;const o=s.timelineStart,c=s.duration;let l=0;a.forEach((g,m)=>{const y=parseFloat(g.DURATION);this.createAsset(s,m,l,o+l,y,g.URI),l+=y}),s.duration=l,this.log(`Loaded asset-list with duration: ${l} (was: ${c}) ${s}`);const d=this.waitingItem,u=(d==null?void 0:d.event.identifier)===n;this.updateSchedule();const h=(i=this.bufferingItem)==null?void 0:i.event;if(u){var f;const g=this.schedule.findEventIndex(n),m=(f=this.schedule.items)==null?void 0:f[g];if(m){if(!this.playingItem&&this.timelinePos>m.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g){s.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${s}`),this.primaryFallback(s);return}this.setBufferingItem(m)}this.setSchedulePosition(g)}else if((h==null?void 0:h.identifier)===n&&h.appendInPlace){const g=s.assetList[0],m=this.getAssetPlayer(g.identifier),y=this.primaryMedia;g&&m&&y&&this.bufferAssetPlayer(m,y)}}onError(e,t){switch(t.details){case R.ASSET_LIST_PARSING_ERROR:case R.ASSET_LIST_LOAD_ERROR:case R.ASSET_LIST_LOAD_TIMEOUT:{const i=t.interstitial;i&&this.primaryFallback(i);break}case R.BUFFER_STALLED_ERROR:{this.onTimeupdate(),this.checkBuffer(!0);break}}}}const Do=500;class Zh extends er{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",$.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=C.IDLE,this.setInterval(Do),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:s}=t;if(Ie(i)&&(this.fragPrevious=i),this.state=C.IDLE,!s)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a;const o=i.start;for(let l=0;l=n[l].start&&o<=n[l].end){a=n[l];break}const c=i.start+i.duration;a?a.end=c:(a={start:o,end:c},n.push(a)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:i,endOffset:s}=t;if(i===0&&s!==Number.POSITIVE_INFINITY){const n=s-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(a=>{for(let o=0;onew si(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const s=new si(i);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,$.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}const s=this.levels[this.currentTrackId];s!=null&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.state!==C.STOPPED&&this.setInterval(Do)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:s,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const c=n[o];if(o>=n.length||!c)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(a.live||(i=c.details)!=null&&i.live){const u=this.mainDetails;if(a.deltaUpdateFailed||!u)return;const h=u.fragments[0];if(!c.details)a.hasProgramDateTime&&u.hasProgramDateTime?(Ki(a,u),l=a.fragmentStart):h&&(l=h.start,Zs(a,l));else{var d;l=this.alignPlaylists(a,c.details,(d=this.levelLastLoaded)==null?void 0:d.details),l===0&&h&&(l=h.start,Zs(a,l))}}c.details=a,this.levelLastLoaded=c,o===s&&(this.hls.trigger(p.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===C.IDLE&&(_t(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,s=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&s!=null&&s.key&&s.iv&&Mt(s.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,Ks(s.method)).catch(o=>{throw n.trigger(p.ERROR,{type:G.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const c=performance.now();n.trigger(p.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=C.IDLE})}}doTick(){if(!this.media){this.state=C.IDLE;return}if(this.state===C.IDLE){const{currentTrackId:e,levels:t}=this,i=t==null?void 0:t[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;const{config:s}=this,n=this.getLoadPosition(),a=J.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,s.maxBufferHole),{end:o,len:c}=a,l=i.details,d=this.hls.maxBufferLength+l.levelTargetDuration;if(c>d)return;const u=l.fragments,h=u.length,f=l.edge;let g=null;const m=this.fragPrevious;if(of-T?0:T;g=_t(m,u,Math.max(u[0].start,o),b),!g&&m&&m.start{if(s=s>>>0,s>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${n})`);return e[s][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}}const tf={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},Po=r=>String.fromCharCode(tf[r]||r),We=15,ut=100,sf={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},rf={17:2,18:4,21:6,22:8,23:10,19:13,20:15},nf={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},af={25:2,26:4,29:6,30:8,31:10,27:13,28:15},of=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class lf{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;ie.log(`${this.time} [${e}] ${i}`)}}}const It=function(e){const t=[];for(let i=0;iut&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ut)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i=144&&this.backSpace();const t=Po(e);if(this.pos>=ut){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t"pacData = "+me(e));let t=e.row-1;if(this.nrRollUpRows&&t"bkgData = "+me(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",s=-1;for(let n=0;n0&&(e?i="["+t.join(" | ")+"]":i=t.join(` `)),i}getTextAndFormat(){return this.rows}}class Mo{constructor(e,t,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=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Lr(i),this.nonDisplayedMemory=new Lr(i),this.lastOutputScreen=new Lr(i),this.currRollUpRow=this.displayedMemory.rows[We-1],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[We-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let i=0;it+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(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"),this.mode!=="MODE_TEXT"&&(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(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}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"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=s[i]}this.logger.log(2,"MIDROW: "+me(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Fo{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=hf(),this.logger=void 0;const s=this.logger=new lf;this.channels=[null,new Mo(e,t,s),new Mo(e+1,i,s)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let i=0;i"["+It([t[i],t[i+1]])+"] -> ("+It([s,n])+")");const c=this.cmdHistory;if(s>=16&&s<=31){if(uf(s,n,c)){ts(null,null,c),this.logger.log(3,()=>"Repeated command ("+It([s,n])+") is dropped");continue}ts(s,n,this.cmdHistory),a=this.parseCmd(s,n),a||(a=this.parseMidrow(s,n)),a||(a=this.parsePAC(s,n)),a||(a=this.parseBackgroundAttributes(s,n))}else ts(null,null,c);if(!a&&(o=this.parseChars(s,n),o)){const d=this.currentChannel;d&&d>0?this.channels[d].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+It([s,n])+" orig: "+It([t[i],t[i+1]]))}}parseCmd(e,t){const i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=33&&t<=35;if(!(i||s))return!1;const n=e===20||e===21||e===23?1:2,a=this.channels[n];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const s=this.channels[i];return s?(s.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+It([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;const s=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(s||n))return!1;const a=e<=23?1:2;t>=64&&t<=95?i=a===1?sf[e]:nf[e]:i=a===1?rf[e]:af[e];const o=this.channels[a];return o?(o.setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!0):!1}interpretPAC(e,t){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,s.underline=(i&1)===1,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=Math.floor((i-16)/2)*4,s}parseChars(e,t){let i,s=null,n=null;if(e>=25?(i=2,n=e-8):(i=1,n=e),n>=17&&n<=19){let a;n===17?a=t+80:n===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+Po(a)+"' in channel "+i),s=[a]}else e>=32&&e<=127&&(s=t===0?[e]:[e,t]);return s&&this.logger.log(3,()=>"Char codes = "+It(s).join(",")),s}parseBackgroundAttributes(e,t){const i=(e===16||e===24)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=45&&t<=47;if(!(i||s))return!1;let n;const a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=of[n],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(a),!0}reset(){for(let e=0;e100)throw new Error("Position must be between 0 and 100.");k=L,this.hasBeenReset=!0}})),Object.defineProperty(d,"positionAlign",n({},u,{get:function(){return A},set:function(L){const D=s(L);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");A=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"size",n({},u,{get:function(){return I},set:function(L){if(L<0||L>100)throw new Error("Size must be between 0 and 100.");I=L,this.hasBeenReset=!0}})),Object.defineProperty(d,"align",n({},u,{get:function(){return w},set:function(L){const D=s(L);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");w=D,this.hasBeenReset=!0}})),d.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class ff{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function No(r){function e(i,s,n,a){return(i|0)*3600+(s|0)*60+(n|0)+parseFloat(a||0)}const t=r.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class gf{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let s=0;s=0&&i<=100)return this.set(e,i),!0}return!1}}function Bo(r,e,t,i){const s=i?r.split(i):[r];for(const n in s){if(typeof s[n]!="string")continue;const a=s[n].split(t);if(a.length!==2)continue;const o=a[0],c=a[1];e(o,c)}}const Ir=new _r(0,0,""),is=Ir.align==="middle"?"middle":"center";function pf(r,e,t){const i=r;function s(){const o=No(r);if(o===null)throw new Error("Malformed timestamp: "+i);return r=r.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,c){const l=new gf;Bo(o,function(h,f){let g;switch(h){case"region":for(let m=t.length-1;m>=0;m--)if(t[m].id===f){l.set(h,t[m].region);break}break;case"vertical":l.alt(h,f,["rl","lr"]);break;case"line":g=f.split(","),l.integer(h,g[0]),l.percent(h,g[0])&&l.set("snapToLines",!1),l.alt(h,g[0],["auto"]),g.length===2&&l.alt("lineAlign",g[1],["start",is,"end"]);break;case"position":g=f.split(","),l.percent(h,g[0]),g.length===2&&l.alt("positionAlign",g[1],["start",is,"end","line-left","line-right","auto"]);break;case"size":l.percent(h,f);break;case"align":l.alt(h,f,["start",is,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let d=l.get("line","auto");d==="auto"&&Ir.line===-1&&(d=-1),c.line=d,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",is);let u=l.get("position","auto");u==="auto"&&Ir.position===50&&(u=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=u}function a(){r=r.replace(/^\s+/,"")}if(a(),e.startTime=s(),a(),r.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);r=r.slice(3),a(),e.endTime=s(),a(),n(r,e)}function Uo(r){return r.replace(//gi,` `)}class mf{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new ff,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let n=t.buffer,a=0;for(n=Uo(n);a")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{pf(n,t.cue,t.regionList)}catch(o){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=n.indexOf("-->")!==-1;if(!n||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=` `),t.cue.text+=n}continue;case"BADCUE":n||(t.state="ID")}}}catch(n){t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=` `,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const yf=/\r\n|\n\r|\n|\r/g,Rr=function(e,t,i=0){return e.slice(i,i+t.length)===t},vf=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),s=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!B(t)||!B(i)||!B(s)||!B(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*s,t+=60*60*1e3*n,t};function kr(r,e,t){return gi(r.toString())+gi(e.toString())+gi(t)}const bf=function(e,t,i){let s=e[t],n=e[s.prevCC];if(!n||!n.new&&s.new){e.ccOffset=e.presentationOffset=s.start,s.new=!1;return}for(;(a=n)!=null&&a.new;){var a;e.ccOffset+=s.start-n.start,s.new=!1,s=n,n=e[s.prevCC]}e.presentationOffset=i};function Tf(r,e,t,i,s,n,a){const o=new mf,c=Ne(new Uint8Array(r)).trim().replace(yf,` `).split(` `),l=[],d=e?Hu(e.baseTime,e.timescale):0;let u="00:00.000",h=0,f=0,g,m=!0;o.oncue=function(y){const v=t[i];let T=t.ccOffset;const b=(h-d)/9e4;if(v!=null&&v.new&&(f!==void 0?T=t.ccOffset=v.start:bf(t,i,b)),b){if(!e){g=new Error("Missing initPTS for VTT MPEGTS");return}T=b-t.presentationOffset}const x=y.endTime-y.startTime,S=$e((y.startTime+T-f)*9e4,s*9e4)/9e4;y.startTime=Math.max(S,0),y.endTime=Math.max(S+x,0);const k=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(k)),y.id||(y.id=kr(y.startTime,y.endTime,k)),y.endTime>0&&l.push(y)},o.onparsingerror=function(y){g=y},o.onflush=function(){if(g){a(g);return}n(l)},c.forEach(y=>{if(m)if(Rr(y,"X-TIMESTAMP-MAP=")){m=!1,y.slice(16).split(",").forEach(v=>{Rr(v,"LOCAL:")?u=v.slice(6):Rr(v,"MPEGTS:")&&(h=parseInt(v.slice(7)))});try{f=vf(u)/1e3}catch(v){g=v}return}else y===""&&(m=!1);o.parse(y+` `)}),o.flush()}const wr="stpp.ttml.im1t",$o=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Go=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Ef={left:"start",center:"center",right:"end",start:"start",end:"end"};function Vo(r,e,t,i){const s=Q(new Uint8Array(r),["mdat"]);if(s.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const n=s.map(o=>Ne(o)),a=Vu(e.baseTime,1,e.timescale);try{n.forEach(o=>t(xf(o,a)))}catch(o){i(o)}}function xf(r,e){const s=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((u,h)=>(u[h]=s.getAttribute(`ttp:${h}`)||n[h],u),{}),o=s.getAttribute("xml:space")!=="preserve",c=Ho(Cr(s,"styling","style")),l=Ho(Cr(s,"layout","region")),d=Cr(s,"body","[begin]");return[].map.call(d,u=>{const h=Ko(u,o);if(!h||!u.hasAttribute("begin"))return null;const f=Pr(u.getAttribute("begin"),a),g=Pr(u.getAttribute("dur"),a);let m=Pr(u.getAttribute("end"),a);if(f===null)throw Wo(u);if(m===null){if(g===null)throw Wo(u);m=f+g}const y=new _r(f-e,m-e,h);y.id=kr(y.startTime,y.endTime,y.text);const v=l[u.getAttribute("region")],T=c[u.getAttribute("style")],b=Sf(v,T,c),{textAlign:x}=b;if(x){const S=Ef[x];S&&(y.lineAlign=S),y.align=x}return ue(y,b),y}).filter(u=>u!==null)}function Cr(r,e,t){const i=r.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function Ho(r){return r.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function Ko(r,e){return[].slice.call(r.childNodes).reduce((t,i,s)=>{var n;return i.nodeName==="br"&&s?t+` `:(n=i.childNodes)!=null&&n.length?Ko(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function Sf(r,e,t){const i="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(s=t[a]),n.reduce((o,c)=>{const l=Dr(e,i,c)||Dr(r,i,c)||Dr(s,i,c);return l&&(o[c]=l),o},{})}function Dr(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function Wo(r){return new Error(`Could not parse ttml timestamp ${r}`)}function Pr(r,e){if(!r)return null;let t=No(r);return t===null&&($o.test(r)?t=Af(r,e):Go.test(r)&&(t=Lf(r,e))),t}function Af(r,e){const t=$o.exec(r),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function Lf(r,e){const t=Go.exec(r),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}class ss{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class _f{constructor(e){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=qo(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.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}},e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new ss(this,"textTrack1"),t=new ss(this,"textTrack2"),i=new ss(this,"textTrack3"),s=new ss(this,"textTrack4");this.cea608Parser1=new Fo(1,e,t),this.cea608Parser2=new Fo(3,i,s)}addCues(e,t,i,s,n){let a=!1;for(let o=n.length;o--;){const c=n[o],l=If(c[0],c[1],t,i);if(l>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],i),a=!0,l/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,i,s)}else{const o=this.Cues.newCue(null,t,i,s);this.hls.trigger(p.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n}){const{unparsedVttFrags:a}=this;i===$.MAIN&&(this.initPTS[t.cc]={baseTime:s,timescale:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(p.FRAG_LOADED,o)}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let s=0;s{Gt(s[n]),delete s[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=qo(),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:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let i=0;in.textCodec===wr);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(go(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const a=this.media,o=a?Zi(a.textTracks):null;if(this.tracks.forEach((c,l)=>{let d;if(o){let u=null;for(let h=0;hl!==null).map(l=>l.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;const n=`textTrack${s[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===$.MAIN){var i,s;const{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:c,sn:l}=t.frag,d=(i=(s=t.part)==null?void 0:s.index)!=null?i:-1;n&&a&&(l!==o+1||l===o&&d!==this.lastPartIndex+1||c!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=c,this.lastSn=l,this.lastPartIndex=d}}onFragLoaded(e,t){const{frag:i,payload:s}=t;if(i.type===$.SUBTITLE)if(s.byteLength){const n=i.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){const o=this.tracks[i.level],c=this.vttCCs;c[i.cc]||(c[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===wr?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;Vo(t,this.initPTS[e.cc],s=>{this._appendCues(s,e.level),i.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},s=>{i.logger.log(`Failed to parse IMSC1: ${s}`),i.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:s})})}_parseVTTs(e){var t;const{frag:i,payload:s}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[i.cc]&&o===-1){a.push(e);return}const c=this.hls,l=(t=i.initSegment)!=null&&t.data?Ue(i.initSegment.data,new Uint8Array(s)).buffer:s;Tf(l,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,d=>{this._appendCues(d,i.level),c.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},d=>{const u=d.message==="Missing initPTS for VTT MPEGTS";u?a.push(e):this._fallbackToIMSC1(i,s),c.logger.log(`Failed to parse VTT cue: ${d}`),!(u&&o>i.cc)&&c.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:d})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||Vo(t,this.initPTS[e.cc],()=>{i.textCodec=wr,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[t];if(!s||s.mode==="disabled")return;e.forEach(n=>Ro(s,n))}else{const s=this.tracks[t];if(!s)return;const n=s.default?"default":"subtitles"+t;i.trigger(p.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===$.SUBTITLE&&this.onFragLoaded(p.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:s}=t;if(!(i.type===$.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let n=0;nxr(o[c],t,i))}if(this.config.renderTextTracksNatively&&t===0&&s!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>xr(o[c],t,s))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let s=2;for(let n=0;n=16?c--:c++;const f=Uo(l.trim()),g=kr(e,t,f);r!=null&&(u=r.cues)!=null&&u.getCueById(g)||(a=new d(e,t,f),a.id=g,a.line=h+1,a.align="left",a.position=10+Math.min(80,Math.floor(c*8/32)*10),s.push(a))}return r&&s.length&&(s.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),s.forEach(h=>Ro(r,h))),s}};function wf(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(r){}return!1}const Cf=/(\d+)-(\d+)\/(\d+)/;class zo{constructor(e){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=e.fetchSetup||Mf,this.controller=new self.AbortController,this.stats=new Cs}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 e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,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 n=Df(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=c&&B(c)?c:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},t.timeout),(ui(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var h;this.response=this.loader=u;const f=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},l-(f-s.loading.start)),!u.ok){const{status:m,statusText:y}=u;throw new Ff(y||"fetch, bad network response",m,u)}s.loading.first=f,s.total=Of(u.headers)||s.total;const g=(h=this.callbacks)==null?void 0:h.onProgress;return g&&B(t.highWaterMark)?this.loadProgressively(u,s,e,t.highWaterMark,g):a?u.arrayBuffer():e.responseType==="json"?u.json():u.text()}).then(u=>{var h,f;const g=this.response;if(!g)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const m=u[o];m&&(s.loaded=s.total=m);const y={url:g.url,data:u,code:g.status},v=(h=this.callbacks)==null?void 0:h.onProgress;v&&!B(t.highWaterMark)&&v(s,e,u,g),(f=this.callbacks)==null||f.onSuccess(y,s,e,g)}).catch(u=>{var h;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const f=u&&u.code||0,g=u?u.message:null;(h=this.callbacks)==null||h.onError({code:f,text:g},e,u?u.details:null,s)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,s=0,n){const a=new Na,o=e.body.getReader(),c=()=>o.read().then(l=>{if(l.done)return a.dataLength&&n(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const d=l.value,u=d.length;return t.loaded+=u,u=s&&n(t,i,a.flush().buffer,e)):n(t,i,d.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function Df(r,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ue({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function Pf(r){const e=Cf.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Of(r){const e=r.get("Content-Range");if(e){const i=Pf(e);if(B(i))return i}const t=r.get("Content-Length");if(t)return parseInt(t)}function Mf(r,e){return new self.Request(r.url,e)}class Ff extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const Nf=/^age:\s*[\d.]+\s*$/im;class Xo{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Cs,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n(i,t.url)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),n(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:i.status,text:a.message},t,i,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const s=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(s)for(const o in s)e.setRequestHeader(o,s[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&B(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const s=t.readyState,n=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,d=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const g=d!=null?d:t.response;if(g!=null){var a,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);const m=t.responseType==="arraybuffer"?g.byteLength:g.length;i.loaded=i.total=m,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const y=(a=this.callbacks)==null?void 0:a.onProgress;y&&y(i,e,g,t);const v={url:t.responseURL,data:g,code:l};(o=this.callbacks)==null||o.onSuccess(v,i,e,t);return}}const u=n.loadPolicy.errorRetry,h=i.retry,f={url:e.url,data:void 0,code:l};if(Ni(u,h,!1,f))this.retry(u);else{var c;ie.error(`${l} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:l,text:t.statusText},e,t,i)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Ni(e,t,!0))this.retry(e);else{var i;ie.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=$s(e,i.retry),i.retry++,ie.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${i.retry}/${e.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(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Nf.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const Bf={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Uf=le(le({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,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,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:Xo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:hd,bufferController:rh,capLevelController:vr,errorController:vd,fpsController:Vh,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:fa,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,certLoadPolicy:{default:Bf},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},$f()),{},{subtitleStreamController:Zh,subtitleTrackController:Wh,timelineController:_f,audioStreamController:eh,audioTrackController:th,emeController:$t,cmcdController:Uh,contentSteeringController:Gh,interstitialsController:Jh});function $f(){return{cueHandler:kf,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Gf(r,e,t){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(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=Or(r),s=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,c=e[o]===void 0,l=[];n.forEach(d=>{const u=`${a}Loading${d}`,h=e[u];if(h!==void 0&&c){l.push(u);const f=i[o].default;switch(e[o]={default:f},d){case"TimeOut":f.maxLoadTimeMs=h,f.maxTimeToFirstByteMs=h;break;case"MaxRetry":f.errorRetry.maxNumRetry=h,f.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":f.errorRetry.retryDelayMs=h,f.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=h,f.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${me(e[o])}`)}),le(le({},i),e)}function Or(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(Or):Object.keys(r).reduce((e,t)=>(e[t]=Or(r[t]),e),{}):r}function Vf(r,e){const t=r.loader;t!==zo&&t!==Xo?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):wf()&&(r.loader=zo,r.progressive=!0,r.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const rs=2,Hf=.1,Kf=.05,Wf=100;class Yf extends aa{constructor(e,t){super("gap-controller",e.logger),this.hls=null,this.fragmentTracker=null,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 i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(Wf),this.mediaSource=t.mediaSource;const i=this.media=t.media;dt(i,"playing",this.onMediaPlaying),dt(i,"waiting",this.onMediaWaiting),dt(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(st(i,"playing",this.onMediaPlaying),st(i,"waiting",this.onMediaWaiting),st(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,s;const n=(i=this.hls)==null?void 0:i.config;if(!n)return;const{media:a,stalled:o}=this;if(!a)return;const{seeking:c}=a,l=this.seeking&&!c,d=!this.seeking&&c,u=a.paused&&!c||a.ended||a.playbackRate===0;if(this.seeking=c,e!==t){t&&(this.ended=0),this.moved=!0,c||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||l){l&&this.stallResolved(e);return}if(u){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!1}));return}if(!J.getBuffered(a).length){this.nudgeRetry=0;return}const h=J.bufferInfo(a,e,0),f=h.nextStart||0,g=this.fragmentTracker;if(c&&g&&this.hls){const k=Qo(this.hls.inFlightFragments,e),A=h.len>rs,I=!f||k||f-e>rs&&!g.getPartialFragment(e);if(A||I)return;this.moved=!1}const m=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&g){if(!(h.len>0)&&!f)return;const A=Math.max(f,h.start||0)-e,w=!!(m!=null&&m.live)?m.targetduration*2:rs,L=g.getPartialFragment(e);if(A>0&&(A<=w||L)){a.paused||this._trySkipBufferHole(L);return}}const y=n.detectStallWithCurrentTimeMs,v=self.performance.now(),T=this.waiting;if(o===null){T>0&&v-T=y||T)&&this.hls){var x;if(((x=this.mediaSource)==null?void 0:x.readyState)==="ended"&&!(m!=null&&m.live)&&Math.abs(e-((m==null?void 0:m.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}const S=J.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(S,b)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(p.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&s&&s.length>1&&e>s.end(0)){const n=J.bufferedInfo(J.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){const a=J.timeRangesToArray(s),o=J.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&oo)&&d-l<1&&e-l<2){const u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${d} buffered index: ${c}`);this.warn(u.message),this.media.currentTime+=1e-6;const h=this.fragmentTracker.getPartialFragment(e)||void 0,f=J.bufferInfo(this.media,e,0);this.hls.trigger(p.ERROR,{type:G.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:h,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t){var i,s;const{fragmentTracker:n,media:a}=this,o=(i=this.hls)==null?void 0:i.config;if(!a||!n||!o)return;const c=a.currentTime,l=(s=this.hls)==null?void 0:s.latestLevelDetails,d=n.getPartialFragment(c);if((d||l!=null&&l.live&&c1&&e.len>o.maxBufferHole||e.nextStart&&e.nextStart-co.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}_reportStall(e){const{hls:t,media:i,stallReported:s,stalled:n}=this;if(!s&&n!==null&&i&&t){this.stallReported=!0;const a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${me(e)})`);this.warn(a.message),t.trigger(p.ERROR,{type:G.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:s}=this,n=(t=this.hls)==null?void 0:t.config;if(!s||!i||!n)return 0;const a=s.currentTime,o=J.bufferInfo(s,a,0),c=a0&&o.len<1&&s.readyState<3,h=c-a;if(h>0&&(d||u)){if(h>n.maxBufferHole){let g=!1;if(a===0){const m=i.getAppendedFrag(0,$.MAIN);m&&c{const r=Mr();try{r&&new r(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function qf(r){return Uint8Array.from(r.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class zf{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(p.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(e,t){var i;this.media=t.media,((i=t.overrides)==null?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){const e=this.hls.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&Gt(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;tns&&(u=ns),u-d<=0&&(u=d+jf);for(let f=0;fd.type===Be.audioId3&&c:s==="video"?l=d=>d.type===Be.emsg&&o:l=d=>d.type===Be.audioId3&&c||d.type===Be.emsg&&o,xr(n,t,i,l)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{id3Track:i}=this,{dateRanges:s}=e,n=Object.keys(s);let a=this.dateRangeCuesAppended;if(i&&t){var o;if((o=i.cues)!=null&&o.length){const d=Object.keys(a).filter(u=>!n.includes(u));for(let u=d.length;u--;){const h=d[u],f=a[h].cues;delete a[h],Object.keys(f).forEach(g=>{try{const m=f[g];m.removeEventListener("enter",this.onEventCueEnter),i.removeCue(m)}catch(m){}})}}else a=this.dateRangeCuesAppended={}}const c=e.fragments[e.fragments.length-1];if(n.length===0||!B(c==null?void 0:c.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=Mr();for(let d=0;d{if(A!==h.id){const I=s[A];if(I.class===h.class&&I.startDate>h.startDate&&(!k||h.startDate.01&&(A.startTime=f,A.endTime=v);else if(l){let I=h.attr[k];Dd(k)&&(I=qf(I));const L=Zo(l,f,v,{key:k,data:I},Be.dateRange);L&&(L.id=u,this.id3Track.addCue(L),m[k]=L,this.hls.config.interstitialsController&&(k==="X-ASSET-LIST"||k==="X-ASSET-URL")&&L.addEventListener("enter",this.onEventCueEnter))}}a[u]={cues:m,dateRange:h,durationKnown:y}}}}class Xf{constructor(e){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,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.currentTime;const s=this.computeLatency();if(s===null)return;this._latency=s;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=this.config;if(!n||a===1||!i.live)return;const o=this.targetLatency;if(o===null)return;const c=s-o,l=Math.min(this.maxLatency,o+i.targetduration);if(c.05&&this.forwardBufferLength>1){const u=Math.min(2,Math.max(1,a)),h=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,f=Math.min(u,Math.max(1,h));this.changeMediaPlaybackRate(t,f)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:i,targetduration:s}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let l=o&&i||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=n!==void 0?n:a*s);const d=s;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const i=this.levelDetails;if(i===null)return null;const s=i.edge,n=e-t-this.edgeStalled,a=s-i.totalduration,o=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),o)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.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(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===R.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,s;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class Qf extends pr{constructor(e,t){super(e,"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=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.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(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,s=[],n={},a={};let o=!1,c=!1,l=!1;t.levels.forEach(d=>{var u;const h=d.attrs;let{audioCodec:f,videoCodec:g}=d;f&&(d.audioCodec=f=Ci(f,i)||void 0),((u=g)==null?void 0:u.indexOf("avc1"))===0&&(g=d.videoCodec=Jc(g));const{width:m,height:y,unknownCodecs:v}=d;let T=v?v.length:0;if(v)for(let D=T;D--;){const M=v[D];this.isAudioSupported(M)?(d.audioCodec=f=f?`${f},${M}`:M,T--,Pt.audio[f.substring(0,4)]=2):this.isVideoSupported(M)&&(d.videoCodec=g=g?`${g},${M}`:M,T--,Pt.video[g.substring(0,4)]=2)}if(o||(o=!!(m&&y)),c||(c=!!g),l||(l=!!f),T||f&&!this.isAudioSupported(f)||g&&!this.isVideoSupported(g)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:b,"FRAME-RATE":x,"HDCP-LEVEL":S,"PATHWAY-ID":k,RESOLUTION:A,"VIDEO-RANGE":I}=h,L=`${`${k||"."}-`}${d.bitrate}-${A}-${x}-${b}-${I}-${S}`;if(n[L])if(n[L].uri!==d.url&&!d.attrs["PATHWAY-ID"]){const D=a[L]+=1;d.attrs["PATHWAY-ID"]=new Array(D+1).join(".");const M=this.createLevel(d);n[L]=M,s.push(M)}else n[L].addGroupId("audio",h.AUDIO),n[L].addGroupId("text",h.SUBTITLES);else{const D=this.createLevel(d);n[L]=D,a[L]=1,s.push(D)}}),this.filterAndSortMediaOptions(s,t,o,c,l)}createLevel(e){const t=new si(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const s=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(s.message),t.supportedResult=Hn(s,[])}return t}isAudioSupported(e){return Fs(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Fs(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,s,n){let a=[],o=[],c=e;if((i||s)&&n&&(c=c.filter(({videoCodec:y,videoRange:v,width:T,height:b})=>(!!y||!!(T&&b))&&sd(v))),c.length===0){Promise.resolve().then(()=>{if(this.hls){let y="no level with compatible codecs found in manifest",v=y;t.levels.length&&(v=`one or more CODECS in variant not supported: ${me(t.levels.map(b=>b.attrs.CODECS).filter((b,x,S)=>S.indexOf(b)===x))}`,this.warn(v),y+=` (${v})`);const T=new Error(y);this.hls.trigger(p.ERROR,{type:G.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:T,reason:v})}});return}t.audioTracks&&(a=t.audioTracks.filter(y=>!y.audioCodec||this.isAudioSupported(y.audioCodec)),el(a)),t.subtitles&&(o=t.subtitles,el(o));const l=c.slice(0);c.sort((y,v)=>{if(y.attrs["HDCP-LEVEL"]!==v.attrs["HDCP-LEVEL"])return(y.attrs["HDCP-LEVEL"]||"")>(v.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&y.height!==v.height)return y.height-v.height;if(y.frameRate!==v.frameRate)return y.frameRate-v.frameRate;if(y.videoRange!==v.videoRange)return Pi.indexOf(y.videoRange)-Pi.indexOf(v.videoRange);if(y.videoCodec!==v.videoCodec){const T=Un(y.videoCodec),b=Un(v.videoCodec);if(T!==b)return b-T}if(y.uri===v.uri&&y.codecSet!==v.codecSet){const T=wi(y.codecSet),b=wi(v.codecSet);if(T!==b)return b-T}return y.averageBitrate!==v.averageBitrate?y.averageBitrate-v.averageBitrate:0});let d=l[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==l.length)){for(let y=0;yT&&T===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=b)}break}const h=n&&!s,f=this.hls.config,g=!!(f.audioStreamController&&f.audioTrackController),m={levels:c,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:s,altAudio:g&&!h&&a.some(y=>!!y.url)};this.hls.trigger(p.MANIFEST_PARSED,m)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const d=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(p.ERROR,{type:G.OTHER_ERROR,details:R.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:d,reason:d.message}),u)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,n=s?s.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&s&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);const c={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(p.LEVEL_SWITCHING,c);const l=a.details;if(!l||l.live){const d=this.switchParams(a.uri,s==null?void 0:s.details,l);this.loadPlaylist(d)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),i=e.filter(s=>t.indexOf(s)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===ee.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===$.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;const s=this._levels[t.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var i;const{level:s,details:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${s}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let c=a.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(s,t,c)}else(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a==null?void 0:a.age;this.log(`Loading level index ${s}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(p.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const i=this._levels.filter((n,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));Da(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.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(p.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function el(r){const e={};r.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function tl(){return self.SourceBuffer||self.WebKitSourceBuffer}function il(){if(!pt())return!1;const e=tl();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Jf(){if(!il())return!1;const r=pt();return typeof(r==null?void 0:r.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>r.isTypeSupported(ii(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(ii(e,"audio"))))}function Zf(){var r;const e=tl();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}const eg=100;class tg extends er{constructor(e,t,i){super(e,t,i,"stream-controller",$.MAIN),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 s=this.media,n=s?s.currentTime:null;if(n===null||!B(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;const a=this.getFwdBufferInfoAtPos(s,n,$.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${n} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(eg),this.level=-1,!this.startFragRequested){let n=s.startLevel;n===-1&&(s.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=s.firstAutoLevel),s.nextLoadLevel=n,this.level=s.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=C.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=C.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case C.WAITING_LEVEL:{const{levels:t,level:i}=this,s=t==null?void 0:t[i],n=s==null?void 0:s.details;if(n&&(!n.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(n))break;this.state=C.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=C.IDLE;break}break}case C.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){const{levels:s,level:n}=this,a=s==null?void 0:s[n];this.resetStartWhenNotLoaded(a||null),this.state=C.IDLE}}break}this.state===C.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(t===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[n]))return;const a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const m={};this.altAudio===2&&(m.type="video"),this.hls.trigger(p.BUFFER_EOS,m),this.state=C.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;const l=a.details;if(!l||this.state===C.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=C.WAITING_LEVEL,this.startFragRequested=!1;return}const d=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(d>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(h,l);if(this.couldBacktrack&&!this.fragPrevious&&f&&Ie(f)&&this.fragmentTracker.getState(f)!==Ae.OK){var g;const y=((g=this.backtrackFragment)!=null?g:f).sn-l.startSN,v=l.fragments[y-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){const y=this.audioOnly&&!this.altAudio?he.AUDIO:he.VIDEO,v=(y===he.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,y,$.MAIN)}f=this.getNextFragmentLoopLoading(f,l,o,$.MAIN,u)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,h))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);s===Ae.NOT_LOADED||s===Ae.PARTIAL?Ie(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,$.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let i;const s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const n=this.getLevelDetails();if(n!=null&&n.live){const o=this.getMainFwdBufferInfo();if(!o||o.len{const a=n.audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,s=s||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=i&&s&&!Zf(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==C.IDLE)return;const s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=C.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:s,startFragRequested:n}=this,a=t.level,o=t.details,c=o.totalduration;if(!s){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${c}`);const l=t.levelInfo,d=this.fragCurrent;d&&(this.state===C.FRAG_LOADING||this.state===C.FRAG_LOADING_WAITING_RETRY)&&d.level!==t.level&&d.loader&&this.abortCurrentFrag();let u=0;if(o.live||(i=l.details)!=null&&i.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,l.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(l.details=o,this.levelLastLoaded=l,n||this.setStartPosition(o,u),this.hls.trigger(p.LEVEL_UPDATED,{details:o,level:a}),this.state===C.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=C.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,c=n>=a-t.maxFragLookUpTolerance&&n<=o;if(s!==null&&i.duration>s&&(n{var a;(a=this.hls)==null||a.trigger(p.AUDIO_TRACK_SWITCHED,t)}),i.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(p.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=Mi(t.url,this.hls);if(i){const s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=i?2:0,this.tick()}onBufferCreated(e,t){const i=t.tracks;let s,n,a=!1;for(const o in i){const c=i[o];if(c.id==="main"){if(n=o,s=c,o==="video"){const l=i[o];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:s}=t,n=i.type===$.MAIN;if(n){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}`),this.state===C.PARSED&&(this.state=C.IDLE);return}const o=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),Ie(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}const a=this.media;a&&(!this._hasEnoughToStart&&J.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError($.MAIN,t);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===ee.LEVEL&&(this.state=C.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=C.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==he.AUDIO||!this.altAudio){const i=(t===he.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,$.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t0&&(c{const{hls:s}=this,n=i==null?void 0:i.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=C.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),s.trigger(p.FRAG_LOADED,i),n.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const i=this.playlistType,{hls:s}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:c,part:l,level:d}=o,{video:u,text:h,id3:f,initSegment:g}=n,{details:m}=d,y=this.altAudio?void 0:n.audio;if(this.fragContextChanged(c)){this.fragmentTracker.removeFragment(c);return}if(this.state=C.PARSING,g){if(g!=null&&g.tracks){const b=c.initSegment||c;this._bufferInitSegment(d,g.tracks,b,a),s.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:b,id:i,tracks:g.tracks})}const v=g.initPTS,T=g.timescale;B(v)&&(this.initPTS[c.cc]={baseTime:v,timescale:T},s.trigger(p.INIT_PTS_FOUND,{frag:c,id:i,initPTS:v,timescale:T}))}if(u&&m){y&&u.type==="audiovideo"&&this.logMuxedErr(c);const v=m.fragments[c.sn-1-m.startSN],T=c.sn===m.startSN,b=!v||c.cc>v.cc;if(n.independent!==!1){const{startPTS:x,endPTS:S,startDTS:k,endDTS:A}=u;if(l)l.elementaryStreams[u.type]={startPTS:x,endPTS:S,startDTS:k,endDTS:A};else if(u.firstKeyFrame&&u.independent&&a.id===1&&!b&&(this.couldBacktrack=!0),u.dropped&&u.independent){const I=this.getMainFwdBufferInfo(),w=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,L=u.firstKeyFramePTS?u.firstKeyFramePTS:x;if(!T&&wrs&&(c.gap=!0);c.setElementaryStreamInfo(u.type,x,S,k,A),this.backtrackFragment&&(this.backtrackFragment=c),this.bufferFragmentData(u,c,l,a,T||b)}else if(T||b)c.gap=!0;else{this.backtrack(c);return}}if(y){const{startPTS:v,endPTS:T,startDTS:b,endDTS:x}=y;l&&(l.elementaryStreams[he.AUDIO]={startPTS:v,endPTS:T,startDTS:b,endDTS:x}),c.setElementaryStreamInfo(he.AUDIO,v,T,b,x),this.bufferFragmentData(y,c,l,a)}if(m&&f!=null&&(t=f.samples)!=null&&t.length){const v={id:i,frag:c,details:m,samples:f.samples};s.trigger(p.FRAG_PARSING_METADATA,v)}if(m&&h){const v={id:i,frag:c,details:m,samples:h.samples};s.trigger(p.FRAG_PARSING_USERDATA,v)}}logMuxedErr(e){this.warn(`${Ie(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==C.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:n,video:a,audiovideo:o}=t;if(n){let l=Di(n.codec,e.audioCodec);l==="mp4a"&&(l="mp4a.40.5");const d=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5");const u=n.metadata;u&&"channelCount"in u&&(u.channelCount||1)!==1&&d.indexOf("firefox")===-1&&(l="mp4a.40.5")}l&&l.indexOf("mp4a.40.5")!==-1&&d.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),n.levelCodec=l,n.id=$.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=$.MAIN;const l=a.codec;if((l==null?void 0:l.length)===4)switch(l){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${a.codec!==l?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const c=Object.keys(t);if(c.length){if(this.hls.trigger(p.BUFFER_CODECS,t),!this.hls)return;c.forEach(l=>{const u=t[l].initSegment;u!=null&&u.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:l,data:u,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,$.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,i=e==null?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=C.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(J.isBuffered(e,i)?t=this.getAppendedFrag(i):J.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const s=this.fragPlaying,n=t.level;(!s||t.sn!==s.sn||s.level!==n)&&(this.fragPlaying=t,this.hls.trigger(p.FRAG_CHANGED,{frag:t}),(!s||s.level!==n)&&this.hls.trigger(p.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return B(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(B(t)){const i=this.getLevelDetails(),s=this.currentFrag||(i?_t(null,i.fragments,t):null);if(s){const n=s.programDateTime;if(n!==null){const a=n+(t-s.start)*1e3;return new Date(a)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class ig{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyUriToKeyInfo){const s=this.keyUriToKeyInfo[i].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=R.KEY_LOAD_ERROR,i,s,n){return new ot({type:G.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:s})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:s}=e;for(let n=0;n{a.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,s;t&&e.setKeyFormat(t);const n=e.decryptdata;if(!n){const l=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,l))}const a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return n.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((s=o)!=null&&s.keyLoadPromise){var c;switch((c=o.mediaKeySessionContext)==null?void 0:c.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(l=>(n.key=l.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const s=this.emeController.loadKey(i);if(s)return(e.keyLoadPromise=s.then(n=>(e.mediaKeySessionContext=n,i))).catch(n=>{throw e.keyLoadPromise=null,n})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,s=i.loader,n=new s(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=i.keyLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(h,f,g,m)=>{const{frag:y,keyInfo:v,url:T}=g;if(!y.decryptdata||v!==this.keyUriToKeyInfo[T])return o(this.createKeyLoadError(y,R.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),m));v.decryptdata.key=y.decryptdata.key=new Uint8Array(h.data),y.keyLoader=null,v.loader=null,a({frag:y,keyInfo:v})},onError:(h,f,g,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),g,le({url:c.url,data:void 0},h)))},onTimeout:(h,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(h,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};n.load(c,d,u)})}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[s],n&&n.destroy()}}function sl(r){const{type:e}=r;switch(e){case ee.AUDIO_TRACK:return $.AUDIO;case ee.SUBTITLE_TRACK:return $.SUBTITLE;default:return $.MAIN}}function Fr(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class sg{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,s=t.loader,n=i||s,a=new n(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ee.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:s,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:c}=t;this.load({id:i,level:s,pathwayId:n,responseType:"text",type:ee.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:ee.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:ee.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){const i=this.loaders[ee.LEVEL];if(i){const s=i.context;s&&!t.levels.some(n=>n===s.levelOrTrack)&&(i.abort(),delete this.loaders[ee.LEVEL])}}load(e){var t;const i=this.hls.config;let s=this.getInternalLoader(e);if(s){const l=this.hls.logger,d=s.context;if(d&&d.levelOrTrack===e.levelOrTrack&&(d.url===e.url||d.deliveryDirectives&&!e.deliveryDirectives)){d.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${d.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let n;if(e.type===ee.MANIFEST?n=i.manifestLoadPolicy.default:n=ue({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),B((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===ee.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===ee.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===ee.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const d=l.partTarget,u=l.targetduration;if(d&&u){const h=Math.max(d*3,u*.8)*1e3;n=ue({},n,{maxTimeToFirstByteMs:Math.min(h,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,n.maxTimeToFirstByteMs)})}}}const a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},c={onSuccess:(l,d,u,h)=>{const f=this.getInternalLoader(u);this.resetInternalLoader(u.type);const g=l.data;if(g.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(l,u,new Error("no EXTM3U delimiter"),h||null,d);return}d.parsing.start=performance.now(),et.isMediaPlaylist(g)||u.type!==ee.MANIFEST?this.handleTrackOrLevelPlaylist(l,d,u,h||null,f):this.handleMasterPlaylist(l,d,u,h)},onError:(l,d,u,h)=>{this.handleNetworkError(d,u,!1,l,h)},onTimeout:(l,d,u)=>{this.handleNetworkError(d,u,!0,void 0,l)}};s.load(e,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,s){const n=this.hls,a=e.data,o=Fr(e,i),c=et.parseMasterPlaylist(a,o);if(c.playlistParsingError){this.handleManifestParsingError(e,i,c.playlistParsingError,s,t);return}const{contentSteering:l,levels:d,sessionData:u,sessionKeys:h,startTimeOffset:f,variableList:g}=c;this.variableList=g;const{AUDIO:m=[],SUBTITLES:y,"CLOSED-CAPTIONS":v}=et.parseMasterPlaylistMedia(a,o,c);m.length&&!m.some(b=>!b.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"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ve({}),bitrate:0,url:""})),n.trigger(p.MANIFEST_LOADED,{levels:d,audioTracks:m,subtitles:y,captions:v,contentSteering:l,url:o,stats:t,networkDetails:s,sessionData:u,sessionKeys:h,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,i,s,n){const a=this.hls,{id:o,level:c,type:l}=i,d=Fr(e,i),u=B(c)?c:B(o)?o:0,h=sl(i),f=et.parseLevelPlaylist(e.data,d,u,h,0,this.variableList);if(l===ee.MANIFEST){const g={attrs:new ve({}),bitrate:0,details:f,name:"",url:d};f.requestScheduled=t.loading.start+Ra(f,0),a.trigger(p.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:d,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,e,t,i,s,n)}handleManifestParsingError(e,t,i,s,n){this.hls.trigger(p.ERROR,{type:G.NETWORK_ERROR,details:R.MANIFEST_PARSING_ERROR,fatal:t.type===ee.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:n})}handleNetworkError(e,t,i=!1,s,n){let a=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===ee.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===ee.AUDIO_TRACK||e.type===ee.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let c=R.UNKNOWN,l=!1;const d=this.getInternalLoader(e);switch(e.type){case ee.MANIFEST:c=i?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,l=!0;break;case ee.LEVEL:c=i?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,l=!1;break;case ee.AUDIO_TRACK:c=i?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ee.SUBTITLE_TRACK:c=i?R.SUBTITLE_TRACK_LOAD_TIMEOUT:R.SUBTITLE_LOAD_ERROR,l=!1;break}d&&this.resetInternalLoader(e.type);const u={type:G.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:d,context:e,error:o,networkDetails:t,stats:n};if(s){const h=(t==null?void 0:t.url)||e.url;u.response=le({url:h,data:void 0},s)}this.hls.trigger(p.ERROR,u)}handlePlaylistLoaded(e,t,i,s,n,a){const o=this.hls,{type:c,level:l,id:d,groupId:u,deliveryDirectives:h}=s,f=Fr(t,s),g=sl(s),m=typeof s.level=="number"&&g===$.MAIN?l:void 0;if(!e.fragments.length){const v=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(p.ERROR,{type:G.NETWORK_ERROR,details:R.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:t,context:s,level:m,parent:g,networkDetails:n,stats:i});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const y=e.playlistParsingError;if(y){if(this.hls.logger.warn(y),!o.config.ignorePlaylistParsingErrors){o.trigger(p.ERROR,{type:G.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:t,context:s,level:m,parent:g,networkDetails:n,stats:i});return}e.playlistParsingError=null}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case ee.MANIFEST:case ee.LEVEL:o.trigger(p.LEVEL_LOADED,{details:e,levelInfo:s.levelOrTrack||o.levels[0],level:m||0,id:d||0,stats:i,networkDetails:n,deliveryDirectives:h,withoutMultiVariant:c===ee.MANIFEST});break;case ee.AUDIO_TRACK:o.trigger(p.AUDIO_TRACK_LOADED,{details:e,track:s.levelOrTrack,id:d||0,groupId:u||"",stats:i,networkDetails:n,deliveryDirectives:h});break;case ee.SUBTITLE_TRACK:o.trigger(p.SUBTITLE_TRACK_LOADED,{details:e,track:s.levelOrTrack,id:d||0,groupId:u||"",stats:i,networkDetails:n,deliveryDirectives:h});break}}}class Tt{static get version(){return oi}static isMSESupported(){return il()}static isSupported(){return Jf()}static getMediaSource(){return pt()}static get Events(){return p}static get MetadataSchema(){return Be}static get ErrorTypes(){return G}static get ErrorDetails(){return R}static get DefaultConfig(){return Tt.defaultConfig?Tt.defaultConfig:Uf}static set DefaultConfig(e){Tt.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new ir,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 t=this.logger=Ic(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=Gf(Tt.DefaultConfig,e,t);this.userConfig=e,i.progressive&&Vf(i,t);const{abrController:s,bufferController:n,capLevelController:a,errorController:o,fpsController:c}=i,l=new o(this),d=this.abrController=new s(this),u=new bd(this),h=i.interstitialsController,f=h?this.interstitialsController=new h(this,Tt):null,g=this.bufferController=new n(this,u),m=this.capLevelController=new a(this),y=new c(this),v=new sg(this),T=i.contentSteeringController,b=T?new T(this):null,x=this.levelController=new Qf(this,b),S=new zf(this),k=new ig(this.config),A=this.streamController=new tg(this,u,k),I=this.gapController=new Yf(this,u);m.setStreamController(A),y.setStreamController(A);const w=[v,x,A];f&&w.splice(1,0,f),b&&w.splice(1,0,b),this.networkControllers=w;const L=[d,g,I,m,y,S,u];this.audioTrackController=this.createController(i.audioTrackController,w);const D=i.audioStreamController;D&&w.push(this.audioStreamController=new D(this,u,k)),this.subtitleTrackController=this.createController(i.subtitleTrackController,w);const M=i.subtitleStreamController;M&&w.push(this.subtititleStreamController=new M(this,u,k)),this.createController(i.timelineController,L),k.emeController=this.emeController=this.createController(i.emeController,L),this.cmcdController=this.createController(i.cmcdController,L),this.latencyController=this.createController(Xf,L),this.coreComponents=L,w.push(l);const te=l.onErrorOut;typeof te=="function"&&this.on(p.ERROR,te,l),this.on(p.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,s){this._emitter.off(e,t,i,s)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const s=e===p.ERROR;this.trigger(p.ERROR,{type:G.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:s,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(p.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 e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(p.ERROR,{type:G.OTHER_ERROR,details:R.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,i=t?e.media:e,s=t?e:{media:i};this._media=i,this.trigger(p.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(p.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(p.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,s=this._url=ws.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(p.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", ":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[$.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[$.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[$.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=yu()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){id(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let s=0;s=t)return s;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let s;if(t===-1&&e!=null&&e.length?s=e.length-1:s=t,i)for(let n=s;n--;){const a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}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(e){this.latencyController.targetLatency=e}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(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const i=zn(t);return Wn(e,i,navigator.mediaCapabilities)}}Tt.defaultConfig=void 0;var rg={VITE_VERSION:"0.1.06"};function ng(r,e){r.pause(),r.config.controls=[],r.config.clickToPlay=!1,r.config.keyboard={focused:!1,global:!1},r.elements.controls.style.display="none",r.elements.buttons.play.forEach(t=>t.style.display="none"),r.elements.container.style.pointerEvents="none"}function ag(r){r.config.controls=["play-large","play","progress","current-time","mute","volume","captions","settings","pip","airplay","fullscreen"],r.config.clickToPlay=!0,r.config.keyboard={focused:!0,global:!0},r.elements.controls.style.display="",r.elements.buttons.play.forEach(e=>e.style.display=""),r.elements.container.style.pointerEvents="",r.play()}function rl(r){const e=Math.floor(r/60),t=Math.floor(r%60);return`${e}:${t.toString().padStart(2,"0")}`}function og(r,e){if(r){const t=decodeURIComponent(atob(r));if(t.startsWith(e))return t.slice(e.length)}return null}function lg(r,e){return $r(this,null,function*(){var t;try{let i=yield En(e==null?void 0:e.video),s=(e==null?void 0:e.dcuuid)+":"+i;const a=yield(yield fetch((e==null?void 0:e.apihost)+"/validate-customer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({card_id:r,dcuuid:s})})).json();return((t=a==null?void 0:a.exp_sec)!=null?t:0)>0}catch(i){return!1}})}function cg(r){r.apihost=r.apihost||"https://vidu.my/api",r.formshost=r.formshost||"https://vidu.my";const e=new URLSearchParams(window.location.search);let t=e.get("since")||0,i=!1,s=og(e.get("token"),"vidu.my")||localStorage.getItem("token")||null;s&&s!=="null"&&localStorage.setItem("token",s),s&&typeof s=="string"&&s.length>=3&&s!=="null"&&lg(s,r).then(m=>{i=m});let n=r!=null&&r.looping_min?(r==null?void 0:r.looping_min)*60:!1,a=0,o=0;console.log(`Vidu Player v.${rg.VITE_VERSION} / ${JSON.stringify(r)} / payed=${i}`);const c=document.getElementById(r.id),l=document.createElement("video");c.innerHTML="";const d=document.createElement("div");d.id="dcoverlay",d.className="overlay hidden",c.appendChild(d);const u=document.createElement("div");u.classList.add("plyr-spinner"),u.classList.add("hidden"),c.appendChild(l),c.appendChild(d),c.appendChild(u),vc(d,l,u,r),l.addEventListener("cardFormSubmitted",m=>{i=!0,d.classList.add("hidden"),ag(f)});const h={start:t,autoplay:(r==null?void 0:r.autoplay)||t>0||!1,muted:!0,youtube:{noCookie:!0,rel:0,showinfo:0,iv_load_policy:3}},f=new ti(l,h);function g(){if(n){f.currentTime>=f.duration-.5&&a0&&(a+=m),o=f.currentTime,a>=n&&(a=0,f.currentTime=0,f.stop());const y=Math.max(0,n-a);if(y>0){const v=c.querySelector(".plyr__time--current"),T=v.textContent.startsWith("-");v&&(v.textContent=T?"-"+rl(y):rl(a))}}}if(r!=null&&r.video)if(r.video.endsWith(".m3u8")){const m=new Tt;m.loadSource(r.video),m.attachMedia(l)}else f.source={type:"video",sources:[{src:r.video,type:"video/mp4"}]};else r!=null&&r.youtube?f.source={type:"video",sources:[{src:r.youtube,provider:"youtube"}]}:r!=null&&r.vimeo&&(f.source={type:"video",sources:[{src:r.vimeo,provider:"vimeo"}]});return f.on("waiting",()=>{u.classList.remove("hidden")}),f.on("playing",()=>{u.classList.add("hidden")}),f.on("loadeddata",()=>{u.classList.add("hidden")}),f.on("playing",()=>{o=f.currentTime}),f.on("seeked",()=>{o=f.currentTime,g()}),f.on("timeupdate",()=>{!i&&f.currentTime>=((r==null?void 0:r.delay)||.1)&&(d.classList.remove("hidden"),ng(f)),g()}),f}var dg={VITE_VERSION:"0.1.06"};function ug(r){const e=document.createElement("style");e.textContent=r,document.head.appendChild(e)}ug(ye+be+Fe);const hg=new URLSearchParams(window.location.search);Object.fromEntries(hg.entries());function fg(){const r=localStorage.getItem("dctrack");return r?JSON.parse(r):{}}function nl(r){window.dcplayer=window.dcplayer||{},window.dcplayer.player=cg(r),window.dcplayer.v=dg.VITE_VERSION}typeof window!="undefined"&&(window.dcplayer=window.dcplayer||{},window.dcplayer.load=nl),ge.getDcTrack=fg,ge.load=nl,Object.defineProperty(ge,Symbol.toStringTag,{value:"Module"})});