PageSourceSearch

https://www.vox.com/_next/static/chunks/1-28sa_4w8-4z.js

js vox.com collected 2026-09-24 07:34:03 UTC 584,078 bytes, 33 lines download raw bytes

1;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="b8d30da5-705e-1dcc-c8c4-5984940830f6")}catch(e){}}();
2(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,606921,e=>{"use strict";var t;let i={argumentDefinitions:[],kind:"Fragment",metadata:null,name:"CuratedContentContainer_homepageResource",selections:[{alias:null,args:null,concreteType:"CuratedContentSectionType",kind:"LinkedField",name:"curatedContentSections",plural:!0,selections:[t={alias:null,args:null,kind:"ScalarField",name:"title",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"showMoreLink",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"hidden",storageKey:null},{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"resource",plural:!1,selections:[{alias:null,args:null,kind:"ScalarField",name:"__typename",storageKey:null},{kind:"InlineFragment",selections:[{alias:null,args:null,kind:"ScalarField",name:"path",storageKey:null},t],type:"ArchiveResourceInterface",abstractKey:"__isArchiveResourceInterface"}],storageKey:null},{alias:null,args:[{kind:"Literal",name:"first",value:3}],concreteType:"CuratedContentConnection",kind:"LinkedField",name:"posts",plural:!1,selections:[{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"nodes",plural:!0,selections:[{args:null,kind:"FragmentSpread",name:"useContentCardDataMapper_contentResource"}],storageKey:null}],storageKey:"posts(first:3)"}],storageKey:null}],type:"HomepageResourceType",abstractKey:null};i.hash="30f3806edfea6da41a0efd031a6c106d",e.s(["default",0,i])},811723,e=>{"use strict";var t,i,s;let r={argumentDefinitions:[],kind:"Fragment",metadata:null,name:"VideoSectionContainer_homepageResource",selections:[{alias:"videos",args:[{kind:"Literal",name:"first",value:5},{kind:"Literal",name:"where",value:{path:"/videos"}}],concreteType:"HomepageCategoryPostsConnection",kind:"LinkedField",name:"categoryPosts",plural:!1,selections:[{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"nodes",plural:!0,selections:[t={alias:null,args:null,kind:"ScalarField",name:"title",storageKey:null},{alias:null,args:null,concreteType:"RichTextType",kind:"LinkedField",name:"dek",plural:!1,selections:[{alias:null,args:null,kind:"ScalarField",name:"html",storageKey:null}],storageKey:null},{alias:null,args:null,concreteType:"ResolvedResourceSiteDataType",kind:"LinkedField",name:"site",plural:!1,selections:[{alias:null,args:null,kind:"ScalarField",name:"isCrossCommunity",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"wpId",storageKey:null}],storageKey:null},i={alias:null,args:null,kind:"ScalarField",name:"permalink",storageKey:null},{alias:null,args:null,concreteType:"CategoryResourceType",kind:"LinkedField",name:"primaryCategory",plural:!1,selections:[t],storageKey:null},{alias:null,args:null,concreteType:"AuthorProfileResourceType",kind:"LinkedField",name:"authors",plural:!0,selections:[{alias:null,args:null,kind:"ScalarField",name:"id",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"name",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"path",storageKey:null},i],storageKey:null},{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"ledeMedia",plural:!1,selections:[{kind:"InlineFragment",selections:[{alias:null,args:null,concreteType:"VolumeVideoResourceType",kind:"LinkedField",name:"video",plural:!1,selections:[{alias:null,args:null,kind:"ScalarField",name:"volumeUuid",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"player",storageKey:null},t,{alias:null,args:null,concreteType:"ImageResourceType",kind:"LinkedField",name:"poster",plural:!1,selections:[{alias:null,args:null,concreteType:"ThumbnailMapType",kind:"LinkedField",name:"thumbnails",plural:!1,selections:[{alias:null,args:null,concreteType:"ThumbnailType",kind:"LinkedField",name:"horizontal",plural:!1,selections:s=[{alias:null,args:null,kind:"ScalarField",name:"url",storageKey:null}],storageKey:null}
2,{alias:null,args:null,concreteType:"ThumbnailType",kind:"LinkedField",name:"square",plural:!1,selections:s,storageKey:null}],storageKey:null}],storageKey:null}],storageKey:null}],type:"LedeMediaVideoType",abstractKey:null}],storageKey:null},{args:null,kind:"FragmentSpread",name:"useContentCardDataMapper_contentResource"}],storageKey:null}],storageKey:'categoryPosts(first:5,where:{"path":"/videos"})'}],type:"HomepageResourceType",abstractKey:null};r.hash="d11310df8abefa000dc53da30b9d73a5",e.s(["default",0,r])},825727,e=>{"use strict";var t,i,s,r,a,n,l,o,d,h,u,c,f,g,m,p,y,v,T,E,S,L,k,A,R,b,I,_,C,D,P,x,F,w,M,O,N,B,U,$,K,G,j,H,V,W,Y,q,z,X,Q,Z,J,ee,et,ei,es,er,ea,en,el,eo,ed,eh,eu,ec,ef,eg,em,ep,ey,ev,eT,eE,eS,eL,ek,eA,eR,eb,eI,e_,eC,eD,eP,ex,eF,ew,eM,eO,eN,eB,eU,e$,eK,eG,ej,eH,eV,eW,eY,eq,ez,eX,eQ,eZ;let eJ=(t=[{defaultValue:null,kind:"LocalArgument",name:"limit"}],i=[{kind:"Literal",name:"path",value:"/"}],s={alias:null,args:null,kind:"ScalarField",name:"__typename",storageKey:null},r={alias:null,args:null,kind:"ScalarField",name:"id",storageKey:null},a={alias:null,args:null,kind:"ScalarField",name:"resourceType",storageKey:null},n={alias:null,args:null,kind:"ScalarField",name:"customCss",storageKey:null},l={alias:null,args:null,kind:"ScalarField",name:"description",storageKey:null},o={alias:null,args:null,kind:"ScalarField",name:"headline",storageKey:null},d={alias:null,args:null,kind:"ScalarField",name:"originalUrl",storageKey:null},h={alias:null,args:null,kind:"ScalarField",name:"ledeLayout",storageKey:null},g={alias:null,args:null,concreteType:"StartHereHomepageType",kind:"LinkedField",name:"startHere",plural:!1,selections:[u={alias:null,args:null,kind:"ScalarField",name:"title",storageKey:null},{alias:null,args:null,concreteType:"RichTextType",kind:"LinkedField",name:"items",plural:!0,selections:f=[c={alias:null,args:null,kind:"ScalarField",name:"html",storageKey:null}],storageKey:null}],storageKey:null},m={alias:null,args:null,kind:"ScalarField",name:"volumeUuid",storageKey:null},p={alias:null,args:null,kind:"ScalarField",name:"player",storageKey:null},E={alias:null,args:null,concreteType:"ThumbnailMapType",kind:"LinkedField",name:"thumbnails",plural:!1,selections:[T={alias:null,args:null,concreteType:"ThumbnailType",kind:"LinkedField",name:"horizontal",plural:!1,selections:v=[y={alias:null,args:null,kind:"ScalarField",name:"url",storageKey:null}],storageKey:null}],storageKey:null},S={alias:null,args:null,concreteType:"VolumeVideoPlayerMetadataType",kind:"LinkedField",name:"playerMetadata",plural:!1,selections:[{alias:null,args:null,concreteType:"VolumeVideoChorusPlayerMetadataType",kind:"LinkedField",name:"chorus",plural:!1,selections:[{alias:null,args:null,kind:"ScalarField",name:"hlsUrl",storageKey:null}],storageKey:null}],storageKey:null},L=[{kind:"Literal",name:"first",value:6}],k=[{kind:"Variable",name:"first",variableName:"limit"}],A={alias:null,args:null,concreteType:"HomepageLayoutPostsConnectionPageInfo",kind:"LinkedField",name:"pageInfo",plural:!1,selections:[{alias:null,args:null,kind:"ScalarField",name:"hasNextPage",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"totalPages",storageKey:null}],storageKey:null},R={alias:null,args:null,concreteType:"ImageResourceType",kind:"LinkedField",name:"poster",plural:!1,selections:[E,r],storageKey:null},b={kind:"TypeDiscriminator",abstractKey:"__isFeedContentResourceInterface"},_={alias:null,args:null,kind:"ScalarField",name:"globalId",storageKey:null},C={alias:null,args:null,kind:"ScalarField",name:"chorusId",storageKey:null},D={alias:null,args:null,kind:"ScalarField",name:"chorusUuid",storageKey:null},P={alias:null,args:null,concreteType:"ResolvedResourceSiteDataType",kind:"LinkedField",name:"site",plural:!1,selections:[{alias:null,args:null,kind:"ScalarField",name:"isCrossCommunity",storageKey:null},I={alias:null,args:null,kind:"ScalarField",name:"wpId",storageKey:null}],storageKey:null},x={alias:null,args:null,concreteType:"RichTextType",kind:"LinkedField",name:"dek",plural:!1,selections:f,storageKey:null},F={alias:null,args:null,kind:"ScalarField",name:"permalink",storageKey:null},w={alias:null,args:null,kind:"ScalarField",name:"publishedAt",storageKey:null},N={alias:null,args:null,concreteType:"AuthorProfileResourceType",kind:"LinkedField",name:"authors",plural:!0,selections:[M={alias:null,args:null,kind:"ScalarField",name:"name",storageKey:null},O={alias:null,args:null,kind:"ScalarField",name:"path",storageKey:null},r],storageKey:null},U={alias:null,args:null,concreteType:"CategoryResourceType",kind:"LinkedField",name:"primaryCategory",plural:!1,selections:B=[u,r],storageKey:null},K={alias:null,args:null,concreteType:"CategoryResourceType",kind:"LinkedField",name:"categories",plural:!0,selections:[r,u,$={alias:null,args:null,kind:"ScalarField",name:"slug",storageKey:null}],storageKey:null},G={alias:null,args:null,concreteType:"InternalCategoryResourceType",kind:"LinkedField",name:"internalCategories",plural:!0,selections:[$,r],storageKey:null},j={alias:null,args:null,kind:"ScalarField",name:"liveBadge",storageKey:null},H={alias:null,args:null,concreteType:"PackageResourceType",kind:"LinkedField",name:"package",plural:!1,selections:[F,u,{alias:null,args:null,concreteType:"PromoDataType",kind:"LinkedField",name:"promo",plural:!1,selections:[o],storageKey:null},r],storageKey:null},z={alias:null,args:null,concreteType:"PromoDataType",kind:"LinkedField",name:"promo",plural:!1,selections:[o,{alias:null,args:null,concreteType:"RichTextType",kind:"LinkedField",name:"description",plural:!1,selections:f,storageKey:null},q={alias:null,args:null,concreteType:"ImageResourceType",kind:"LinkedField",name:"image",plural:!1,selections:Y=[W={alias:null,args:null,concreteType:"Thumbn
2ailMapType",kind:"LinkedField",name:"thumbnails",plural:!1,selections:[T,V={alias:null,args:null,concreteType:"ThumbnailType",kind:"LinkedField",name:"square",plural:!1,selections:v,storageKey:null}],storageKey:null},r],storageKey:null}],storageKey:null},X={alias:null,args:null,concreteType:"CampaignResourceType",kind:"LinkedField",name:"primaryCampaign",plural:!1,selections:[{alias:null,args:null,kind:"ScalarField",name:"advertiserName",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"advertiserPreamble",storageKey:null},r],storageKey:null},J={alias:null,args:null,concreteType:null,kind:"LinkedField",name:"ledeMedia",plural:!1,selections:[s,Q={kind:"InlineFragment",selections:[q],type:"LedeMediaImageType",abstractKey:null},{kind:"InlineFragment",selections:[{alias:null,args:null,concreteType:"VolumeVideoResourceType",kind:"LinkedField",name:"video",plural:!1,selections:[m,p,Z={alias:null,args:null,concreteType:"ImageResourceType",kind:"LinkedField",name:"poster",plural:!1,selections:Y,storageKey:null},r],storageKey:null}],type:"LedeMediaVideoType",abstractKey:null}],storageKey:null},ei={alias:null,args:null,concreteType:"CommentsType",kind:"LinkedField",name:"comments",plural:!1,selections:[ee={alias:null,args:null,kind:"ScalarField",name:"enabled",storageKey:null},et={alias:null,args:null,kind:"ScalarField",name:"mode",storageKey:null}],storageKey:null},er={alias:null,args:es=[{kind:"Literal",name:"first",value:1}],concreteType:"FeedContentStreamsConnection",kind:"LinkedField",name:"streams",plural:!1,selections:[{alias:null,args:null,concreteType:"StreamResourceType",kind:"LinkedField",name:"nodes",plural:!0,selections:B,storageKey:null}],storageKey:"streams(first:1)"},ea={alias:null,args:null,concreteType:null,kind:"LinkedField",name:"blocks",plural:!0,selections:[s,{kind:"InlineFragment",selections:[{alias:null,args:null,concreteType:"ProductBlockProductType",kind:"LinkedField",name:"product",plural:!1,selections:[{alias:null,args:null,kind:"ScalarField",name:"score",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"showScores",storageKey:null}],storageKey:null}],type:"ProductBlockType",abstractKey:null}],storageKey:null},eu={kind:"InlineFragment",selections:[en={alias:null,args:null,kind:"ScalarField",name:"customBadgeEnabled",storageKey:null},el={alias:null,args:null,kind:"ScalarField",name:"customBadgeName",storageKey:null},ed={alias:null,args:null,concreteType:"AuthorProfileResourceType",kind:"LinkedField",name:"authors",plural:!0,selections:[F,eo={alias:null,args:null,concreteType:"RichTextType",kind:"LinkedField",name:"shortBio",plural:!0,selections:f,storageKey:null}],storageKey:null},eh={alias:null,args:null,kind:"ScalarField",name:"template",storageKey:null}],type:"PostResourceType",abstractKey:null},ef={kind:"InlineFragment",selections:ec=[ed],type:"VideoPostResourceType",abstractKey:null},ev={kind:"InlineFragment",selections:[{alias:null,args:null,kind:"ScalarField",name:"streamPublishedAt",storageKey:null}],type:"StreamResourceType",abstractKey:null},eE=[s,b,r,I,_,C,D,a,P,x,F,u,w,N,U,K,G,j,H,z,X,J,ei,er,ea,eu,ef,eg={kind:"InlineFragment",selections:ec,type:"MapResourceType",abstractKey:null},ep={kind:"InlineFragment",selections:[ed,em={alias:null,args:null,kind:"ScalarField",name:"authorByLine",storageKey:null}],type:"LinkPostResourceType",abstractKey:null},ey={kind:"InlineFragment",selections:ec,type:"VaultResourceType",abstractKey:null},ev,eT={kind:"InlineFragment",selections:[ed,eh],type:"DiningReportResourceType",abstractKey:null}],eS=[{alias:null,args:null,concreteType:"ThumbnailMapType",kind:"LinkedField",name:"thumbnails",plural:!1,selections:[V],storageKey:null},r],eL={alias:null,args:null,concreteType:"RichTextType",kind:"LinkedField",name:"paragraphContents",plural:!0,selections:f,storageKey:null},ek={alias:null,args:null,kind:"ScalarField",name:"placement",storageKey:null},eA={alias:null,args:null,concreteType:"RichTextType",kind:"LinkedField",name:"contents",plural:!1,selections:f,storageKey:null},eR={alias:null,args:null,kind:"ScalarField",name:"alt",storageKey:null},eb={alias:null,args:null,kind:"ScalarField",name:"hideCredit",storageKey:null},e_=[c,eI={alias:null,args:null,kind:"ScalarField",name:"plaintext",storageKey:null}],eC={alias:null,args:null,kind:"ScalarField",name:"isSensitive",storageKey:null},eD=[eI],eP={alias:null,args:null,kind:"ScalarField",name:"normalizedRatio",storageKey:null},ex={alias:null,args:null,kind:"ScalarField",name:"originalHeight",storageKey:null},eF={alias:null,args:null,kind:"ScalarField",name:"originalWidth",storageKey:null},ew={alias:null,args:null,concreteType:"CoordinatesType",kind:"LinkedField",name:"cropCoordinates",plural:!1,selections:[{alias:null,args:null,kind:"ScalarField",name:"height",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"width",storageKey:null}],storageKey:null},eM={alias:null,args:null,concreteType:"RichTextType",kind:"LinkedField",name:"citation",plural:!1,selections:f,storageKey:null},eO={alias:null,args:null,concreteType:"RichTextType",kind:"LinkedField",name:"caption",plural:!1,selections:f,storageKey:null},eN={alias:null,args:null,kind:"ScalarField",name:"imagesOrientation",storageKey:null},eB={alias:null,args:null,concreteType:"RichTextType",kind:"LinkedField",name:"credit",plural:!1,selections:eD,storageKey:null},eU=[ex,eF,y,eP,ew],eK={kind:"InlineFragment",selections:e$=[r],type:"Node",abstractKey:"__isNode"},eG=[ek],ej=[{kind:"TypeDiscriminator",abstractKey:"__isBlockType"},s,{kind:"InlineFragment",selections:[eL,{alias:null,args:null,kind:"ScalarField",name:"dropcap",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"endmark",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"lead",storageKey:null}
2],type:"CoreParagraphBlockType",abstractKey:null},{kind:"InlineFragment",selections:[{alias:null,args:null,kind:"ScalarField",name:"ordered",storageKey:null},ek,{alias:null,args:null,concreteType:"CoreListItemBlockType",kind:"LinkedField",name:"items",plural:!0,selections:[eA,{alias:null,args:null,concreteType:"CoreListBlockType",kind:"LinkedField",name:"nestedList",plural:!1,selections:[{alias:null,args:null,concreteType:"CoreListItemBlockType",kind:"LinkedField",name:"items",plural:!0,selections:[eA,{alias:null,args:null,concreteType:"CoreListBlockType",kind:"LinkedField",name:"nestedList",plural:!1,selections:[{alias:null,args:null,concreteType:"CoreListItemBlockType",kind:"LinkedField",name:"items",plural:!0,selections:[eA,{alias:null,args:null,concreteType:"CoreListBlockType",kind:"LinkedField",name:"nestedList",plural:!1,selections:[{alias:null,args:null,concreteType:"CoreListItemBlockType",kind:"LinkedField",name:"items",plural:!0,selections:[eA],storageKey:null}],storageKey:null}],storageKey:null}],storageKey:null}],storageKey:null}],storageKey:null}],storageKey:null}],type:"CoreListBlockType",abstractKey:null},{kind:"InlineFragment",selections:[{alias:null,args:null,kind:"ScalarField",name:"provider",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"embedHtml",storageKey:null},ek],type:"CoreEmbedBlockType",abstractKey:null},{kind:"InlineFragment",selections:[eR,eb,ek,{alias:null,args:null,concreteType:"RichTextType",kind:"LinkedField",name:"credit",plural:!1,selections:e_,storageKey:null},{alias:null,args:null,concreteType:"RichTextType",kind:"LinkedField",name:"caption",plural:!1,selections:e_,storageKey:null},eC,{alias:null,args:null,concreteType:"RichTextType",kind:"LinkedField",name:"contentWarning",plural:!1,selections:eD,storageKey:null},{alias:null,args:null,concreteType:"ThumbnailType",kind:"LinkedField",name:"thumbnail",plural:!1,selections:[{alias:null,args:null,kind:"ScalarField",name:"size",storageKey:null},y,eP,ex,eF,ew],storageKey:null},{alias:null,args:null,concreteType:"ImageResourceType",kind:"LinkedField",name:"image",plural:!1,selections:[r,eR],storageKey:null}],type:"CoreImageBlockType",abstractKey:null},{kind:"InlineFragment",selections:[eA,eM,ek],type:"CorePullquoteBlockType",abstractKey:null},{kind:"InlineFragment",selections:[{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"children",plural:!0,selections:[s,{kind:"InlineFragment",selections:[eL],type:"C
2oreParagraphBlockType",abstractKey:null}],storageKey:null},eM],type:"CoreQuoteBlockType",abstractKey:null},{kind:"InlineFragment",selections:[{alias:null,args:null,kind:"ScalarField",name:"autoplay",storageKey:null},eO,eC,ek,{alias:null,args:null,concreteType:"VolumeVideoResourceType",kind:"LinkedField",name:"video",plural:!1,selections:[u,m,p,R,r],storageKey:null}],type:"VideoBlockType",abstractKey:null},{kind:"InlineFragment",selections:[eN,{alias:null,args:null,concreteType:"CoreImageBlockType",kind:"LinkedField",name:"images",plural:!0,selections:[eR,eb,eB,eO,{alias:null,args:null,concreteType:"ImageResourceType",kind:"LinkedField",name:"image",plural:!1,selections:[d,ex,eF,{alias:null,args:null,concreteType:"ThumbnailMapType",kind:"LinkedField",name:"thumbnails",plural:!1,selections:[{alias:null,args:null,concreteType:"ThumbnailType",kind:"LinkedField",name:"original",plural:!1,selections:[eP],storageKey:null}],storageKey:null},r],storageKey:null}],storageKey:null},ek],type:"ImageSliderBlockType",abstractKey:null},{kind:"InlineFragment",selections:[eN,{alias:null,args:null,concreteType:"CoreImageBlockType",kind:"LinkedField",name:"images",plural:!0,selections:[eR,eb,eB,eO,{alias:null,args:null,concreteType:"ImageResourceType",kind:"LinkedField",name:"image",plural:!1,selections:[r,eF,ex,{alias:null,args:null,concreteType:"ThumbnailMapType",kind:"LinkedField",name:"thumbnails",plural:!1,selections:[{alias:null,args:null,concreteType:"ThumbnailType",kind:"LinkedField",name:"horizontal",plural:!1,selections:eU,storageKey:null},{alias:null,args:null,concreteType:"ThumbnailType",kind:"LinkedField",name:"vertical",plural:!1,selections:eU,storageKey:null},{alias:null,args:null,concreteType:"ThumbnailType",kind:"LinkedField",name:"original",plural:!1,selections:eU,storageKey:null}],storageKey:null}],storageKey:null}],storageKey:null},ek],type:"CoreGalleryBlockType",abstractKey:null},{kind:"InlineFragment",selections:[{alias:null,args:null,kind:"ScalarField",name:"source",storageKey:null},u,y,{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"resource",plural:!1,selections:[s,{kind:"InlineFragment",selections:[{alias:null,args:null,concreteType:"AuthorProfileResourceType",kind:"LinkedField",name:"authors",plural:!0,selections:[M,r],storageKey:null},w,{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"ledeMedia",plural:!1,selections:[s,{kind:"InlineFragment",selections:[{alias:null,args:null,concreteType:"ImageResourceType",kind:"LinkedField",name:"image",plural:!1,selections:eS,storageKey:null}],type:"LedeMediaImageType",abstractKey:null}],storageKey:null}],type:"PostResourceType",abstractKey:null},eK],storageKey:null}],type:"LinkBlockType",abstractKey:null},{kind:"InlineFragment",selections:[{alias:null,args:null,concreteType:"ProductBlockProductType",kind:"LinkedField",name:"product",plural:!1,selections:[{alias:null,args:null,kind:"ScalarField",name:"productId",storageKey:null},u,{alias:null,args:null,kind:"ScalarField",name:"showImage",storageKey:null},{alias:null,args:null,concreteType:"ProductBrandResourceType",kind:"LinkedField",name:"brand",plural:!1,selections:[r,u],storageKey:null},{alias:null,args:null,concreteType:"ImageResourceType",kind:"LinkedField",name:"image",plural:!1,selections:[eR,W,r],storageKey:null},{alias:null,args:null,concreteType:"ProductRetailLinkType",kind:"LinkedField",name:"bestRetailLink",plural:!1,selections:v,storageKey:null},{alias:null,args:null,concreteType:"ProductRetailLinkType",kind:"LinkedField",name:"retailLinks",plural:!0,selections:[{alias:null,args:null,kind:"ScalarField",name:"price",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"retailer",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"salePrice",storageKey:null},y],storageKey:null}],storageKey:null},ek],type:"ProductBlockType",abstractKey:null},{kind:"InlineFragment",selections:eG,type:"ActionBoxBlockType",abstractKey:null},{kind:"InlineFragment",selections:eG,type:"CoreHeadingBlockType",abstractKey:null},{kind:"InlineFragment",selections:eG,type:"CoreHTMLBlockType",abstractKey:null},{kind:"InlineFragment",selections:eG,type:"CoreSeparatorBlockType",abstractKey:null},{kind:"InlineFragment",selections:eG,type:"HighlightBlockType",abstractKey:null},{kind:"InlineFragment",selections:eG,type:"ImageCompareBlockType",abstractKey:null},{kind:"InlineFragment",selections:eG,type:"NewsletterBlockType",abstractKey:null},{kind:"InlineFragment",selections:eG,type:"RatingBlockType",abstractKey:null},{kind:"InlineFragment",selections:eG,type:"RelatedPostsBlockType",abstractKey:null},{kind:"InlineFragment",selections:eG,type:"TableBlockType",abstractKey:null},{kind:"InlineFragment",selections:eG,type:"TableOfContentsBlockType",abstractKey:null},{kind:"InlineFragment",selections:eG,type:"ProductsTableBlockType",abstractKey:null},{kind:"InlineFragment",selections:eG,type:"LegacyProductBlockType",abstractKey:null},{kind:"InlineFragment",selections:eG,type:"LegacyProductsTableBlockType",abstractKey:null}],eH={alias:null,args:null,kind:"ScalarField",name:"hidden",storageKey:null},eV={alias:null,args:null,kind:"ScalarField",name:"layout",storageKey:null},eW={kind:"Literal",name:"first",value:5},eY=[{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"nodes",plural:!0,selections:eE,storageKey:null}],ez={kind:"InlineFragment",selections:eq=[r,u,O],type:"CategoryResourceType",abstractKey:null},eQ=[eX={alias:null,args:null,concreteType:"AuthorProfileResourceType",kind:"LinkedField",name:"authors",plural:!0,selections:[eo],storageKey:null}],eZ=[F],{fragment:{argumentDefinitions:t,kind:"Fragment",metadata:null,name:"HomepageLayoutQuery",selections:[{kind:"RequiredField",field:{alias:null,args:i,concreteType:null,kind:"LinkedField",name:"resource",plural:!1,selections:[s,{kind:"InlineFragment",selections:[r,a,n,{alias:null,args:null,concreteType:"ShareableDataType",kind:"LinkedField",name:"seo",plural:!1,selections:[l,o,{alias:null,args:null,concreteType:"ImageResourceType",kind:"LinkedField",name:"image",plural:!1,selections:[d],storageKey:null}],storageKey:null},{alias:null,args:null,concreteType:"HeroLedesType",kind:"LinkedField",name:"heroLede",plural:!1,selections:[h,g,{alias:null,args:null,concreteType:"VolumeVideoResourceType",kind:"LinkedField",name:"video",plural:!1,selections:[u,m,p,{alias:null,args:null,concreteType:"ImageResourceType",kind:"LinkedField",name:"poster",plural:!1,selections:[E],storageKey:null},S],storageKey:null},{alias:null,args:L,concreteType:"HeroLedesTypeConnection",kind:"LinkedField",name:"posts",plural:!1,selections:[{alias:null,args:null,concreteType:"HeroLedesTypeConnectionEdge",kind:"LinkedField",name:"edges",plural:!0,selections:[{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"node",plural:!1,selections:[{args:null,kind:"FragmentSpread",name:"useContentCardDataMapper_contentResource"}],storageKey:null}],storageKey:null}],storageKey:"posts(first:6)"}],storageKey:null},{alias:null,args:k,concreteType:"HomepageLayoutPostsConnection",kind:"LinkedField",name:"homepageLayoutPosts",plural:!1,selections:[A,{args:null,kind:"FragmentSpread",name:"ContentCardRiverContainer_posts"}],storageKey:null},{args:null,kind:"FragmentSpread",name:"AdminContainer_resolvedResource"},{args:null,kind:"FragmentSpread",name:"SpotlightSectionsContainer_homepageResource"},{args:null,kind:"FragmentSpread",name:"CategoryPillarsContainer_homepageResource"},{args:null,kind:"FragmentSpread",name:"VideoSectionContainer_homepageResource"},{args:null,kind:"FragmentSpread",name:"CuratedContentContainer_homepageResource"}],type:"HomepageResourceType",abstractKey:null}],storageKey:'resource(path:"/")'},action:"THROW"},{args:null,kind:"FragmentSpread",name:"QuickLinksContainer_query"}],type:"RootQuery",abstractKey:null},kind:"Request",operation:{argumentDefinitions:t,kind:"Operation",name:"HomepageLayoutQuery",selections:[{alias:null,args:i,concreteType:null,kind:"LinkedField",name:"resource",plural:!1,selections:[s,{kind:"InlineFragment",selections:[r,a,n,{alias:null,args:null,concreteType:"ShareableDataType",kind:"LinkedField",name:"seo",plural:!1,selections:[l,o,{alias:null,args:null,concreteType:"ImageResourceType",kind:"LinkedField",name:"image",plural:!1,selections:[d,r],storageKey:null}],storageKey:null},{alias:null,args:null,concreteType:"HeroLedesType",kind:"LinkedField",name:"heroLede",plural:!1,selections:[h,g,{alias:null,args:null,concreteType:"VolumeVideoResourceType",kind:"LinkedField",name:"video",plural:!1,selections:[u,m,p,R,S,r],storageKey:null},{alias:null,args:L,concreteType:"HeroLedesTypeConnection",kind:"LinkedField",name:"posts",plural:!1,selections:[{alias:null,args:null,concreteType:"HeroLedesTypeConnectionEdge",kind:"LinkedField",name:"edges",plural:!0,selections:[{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"node",plural:!1,selections:eE,storageKey:null}],storageKey:null}],storageKey:"posts(first:6)"}],storageKey:null},{alias:null,args:k,concreteType:"HomepageLayoutPostsConnection",kind:"LinkedField",name:"homepageLayoutPosts",plural:!1,selections:[A,{kind:"InlineFragment",selections:[{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"nodes",plural:!0,selections:[s,r,{kind:"InlineFragment",selections:[{kind:"InlineFragment",selections:[I,_,C,D,a,P,x,F,u,w,N,U,K,G,j,H,z,X,J,ei,er,ea,eu,ef,eg,ep,ey,ev,eT],type:"FeedContentResourceInterface",abstractKey:"__isFeedContentResourceInterface"},{kind:"InlineFragment",selections:[{alias:null,args:null,concreteType:"AuthorProfileResourceType",kind:"LinkedField",name:"authors",plural:!0,selections:[r,M,F,u,{alias:null,args:null,concreteType:"ImageResourceType",kind:"LinkedField",name:"profileImage",plural:!1,selections:eS,storageKey:null},{alias:null,args:es,concreteType:"ArchiveFeedContentConnection",kind:"LinkedField",name:"posts",plural:!1,selections:[{alias:null,args:null,concreteType:"ArchiveFeedContentConnectionEdge",kind:"LinkedField",name:"edges",plural:!0,selections:[{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"node",plural:!1,selections:[s,w,r],storageKey:null}],storageKey:null}],storageKey:"posts(first:1)"}],storageKey:null},_,P,{alias:null,args:null,concreteType:"CommentsType",kind:"LinkedField",name:"comments",plural:!1,selections:[et,ee],storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"createdAt",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"excludedFromHomepage",storageKey:null},a,O,{alias:null,args:null,kind:"ScalarField",name:"originalPublishedAt",storageKey:null},F,w,u,{alias:null,args:null,kind:"ScalarField",name:"updatedAt",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"hasAffiliateLinks",storageKey:null},{alias:null,args:null,concreteType:"CategoryResourceType",kind:"LinkedField",name:"categories",plural:!0,selections:[u,O,$,r],storageKey:null},{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"blocks",plural:!0,selections:ej,storageKey:null},{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"quickAttachment",plural:!1,selections:ej,storageKey:null}],type:"QuickPostResourceType",abstractKey:null},{kind:"InlineFragment",selections:[eh],type:"PostResourceType",abstractKey:null}
2],type:"ContentResourceInterface",abstractKey:"__isContentResourceInterface"}],storageKey:null}],type:"FeedContentResourceInterfaceConnection",abstractKey:"__isFeedContentResourceInterfaceConnection"}],storageKey:null},{alias:null,args:null,concreteType:"SpotlightSectionType",kind:"LinkedField",name:"spotlightSections",plural:!0,selections:[eH,eV,{alias:null,args:[eW],concreteType:"SpotlightSectionConnection",kind:"LinkedField",name:"posts",plural:!1,selections:eY,storageKey:"posts(first:5)"},{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"resource",plural:!1,selections:[s,ez,{kind:"InlineFragment",selections:eq,type:"PackageResourceType",abstractKey:null},{kind:"InlineFragment",selections:eq,type:"StreamResourceType",abstractKey:null},eK],storageKey:null}],storageKey:null},{alias:null,args:null,concreteType:"CategoryPillar",kind:"LinkedField",name:"categoryPillars",plural:!0,selections:[eV,{alias:null,args:L,concreteType:"CategoryPillarConnection",kind:"LinkedField",name:"posts",plural:!1,selections:eY,storageKey:"posts(first:6)"},{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"resource",plural:!1,selections:[s,ez,{kind:"InlineFragment",selections:eq,type:"SuperCatResourceType",abstractKey:null},eK],storageKey:null}],storageKey:null},{alias:"videos",args:[eW,{kind:"Literal",name:"where",value:{path:"/videos"}}],concreteType:"HomepageCategoryPostsConnection",kind:"LinkedField",name:"categoryPosts",plural:!1,selections:[{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"nodes",plural:!0,selections:[s,u,x,P,F,U,{alias:null,args:null,concreteType:"AuthorProfileResourceType",kind:"LinkedField",name:"authors",plural:!0,selections:[r,M,O,F],storageKey:null},{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"ledeMedia",plural:!1,selections:[s,{kind:"InlineFragment",selections:[{alias:null,args:null,concreteType:"VolumeVideoResourceType",kind:"LinkedField",name:"video",plural:!1,selections:[m,p,u,Z,r],storageKey:null}],type:"LedeMediaVideoType",abstractKey:null},Q],storageKey:null},b,r,I,_,C,D,a,w,K,G,j,H,z,X,ei,er,ea,{kind:"InlineFragment",selections:[en,el,eX,eh],type:"PostResourceType",abstractKey:null},{kind:"InlineFragment",selections:eQ,type:"VideoPostResourceType",abstractKey:null},{kind:"InlineFragment",selections:eQ,type:"MapResourceType",abstractKey:null},{kind:"InlineFragment",selections:[eX,em],type:"LinkPostResourceType",abstractKey:null},{kind:"InlineFragment",selections:eQ,type:"VaultResourceType",abstractKey:null},ev,{kind:"InlineFragment",selections:[eX,eh],type:"DiningReportResourceType",abstractKey:null}],storageKey:null}],storageKey:'categoryPosts(first:5,where:{"path":"/videos"})'},{alias:null,args:null,concreteType:"CuratedContentSectionType",kind:"LinkedField",name:"curatedContentSections",plural:!0,selections:[u,{alias:null,args:null,kind:"ScalarField",name:"showMoreLink",storageKey:null},eH,{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"resource",plural:!1,selections:[s,{kind:"InlineFragment",selections:[O,u],type:"ArchiveResourceInterface",abstractKey:"__isArchiveResourceInterface"},eK],storageKey:null},{alias:null,args:[{kind:"Literal",name:"first",value:3}],concreteType:"CuratedContentConnection",kind:"LinkedField",name:"posts",plural:!1,selections:eY,storageKey:"posts(first:3)"}],storageKey:null},{kind:"InlineFragment",selections:[I,_,{kind:"InlineFragment",selections:[C,D,{alias:null,args:null,concreteType:"FeaturedImageType",kind:"LinkedField",name:"featuredImage",plural:!1,selections:[{alias:null,args:null,concreteType:"ImageResourceType",kind:"LinkedField",name:"image",plural:!1,selections:[d,I,r],storageKey:null}],storageKey:null},{kind:"InlineFragment",selections:[{alias:null,args:null,concreteType:"CategoryResourceType",kind:"LinkedField",name:"primaryCategory",plural:!1,selections:e$,storageKey:null}],type:"FeedContentResourceInterface",abstractKey:"__isFeedContentResourceInterface"}],type:"ContentResourceInterface",abstractKey:"__isContentResourceInterface"}],type:"ResolvedResourceInterface",abstractKey:"__isResolvedResourceInterface"}],type:"HomepageResourceType",abstractKey:null},eK],storageKey:'resource(path:"/")'},{alias:null,args:null,concreteType:"QuickLinksItemType",kind:"LinkedField",name:"quickLinks",plural:!0,selections:[u,{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"resource",plural:!1,selections:[s,{kind:"InlineFragment",selections:eZ,type:"EmbedStoryResourceType",abstractKey:null},{kind:"InlineFragment",selections:eZ,type:"PageResourceType",abstractKey:null},{kind:"InlineFragment",selections:eZ,type:"PostResourceType",abstractKey:null},{kind:"InlineFragment",selections:eZ,type:"PackageResourceType",abstractKey:null},{kind:"InlineFragment",selections:eZ,type:"StreamResourceType",abstractKey:null},{kind:"InlineFragment",selections:eZ,type:"CategoryResourceType",abstractKey:null},eK],storageKey:null}],storageKey:null}]},params:{id:"631fd578fdc39ef7250ce3e8dddb8e16",metadata:{},name:"HomepageLayoutQuery",operationKind:"query",text:null}});eJ.hash="c38d2bb331aaa53267b3802a1b8140e7",e.s(["default",0,eJ])},595499,e=>{"use strict";let t;var i,s,r,a,n,l,o,d,h,u,c,f,g,m,p,y,v,T=e.i(478902),E=e.i(591370),S=e.i(197649),L=e.i(94685),k=e.i(434937),A=e.i(608439),R=e.i(714060),b=e.i(873597),I=e.i(312721),_=e.i(478381),C=e.i(766221),D=e.i(307197);e.i(299438);var P=e.i(403570);let x={argumentDefinitions:[],kind:"Fragment",metadata:null,name:"CategoryPillarsContainer_homepageResource",selections:[{alias:null,args:null,concreteType:"CategoryPillar",kind:"LinkedField",name:"categoryPillars",plural:!0,selections:[{args:null,kind:"FragmentSpread",name:"CategoryPillarContainer_
2categoryPillar"}],storageKey:null}],type:"HomepageResourceType",abstractKey:null};x.hash="745bb39a3f1e148d605052d68fa0d8d1";let F={argumentDefinitions:[],kind:"Fragment",metadata:null,name:"CategoryPillarContainer_categoryPillar",selections:[{alias:null,args:null,kind:"ScalarField",name:"layout",storageKey:null},{alias:null,args:[{kind:"Literal",name:"first",value:6}],concreteType:"CategoryPillarConnection",kind:"LinkedField",name:"posts",plural:!1,selections:[{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"nodes",plural:!0,selections:[{args:null,kind:"FragmentSpread",name:"useContentCardDataMapper_contentResource"}],storageKey:null}],storageKey:"posts(first:6)"},{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"resource",plural:!1,selections:[{alias:null,args:null,kind:"ScalarField",name:"__typename",storageKey:null},{kind:"InlineFragment",selections:l=[{alias:null,args:null,kind:"ScalarField",name:"id",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"title",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"path",storageKey:null}],type:"CategoryResourceType",abstractKey:null},{kind:"InlineFragment",selections:l,type:"SuperCatResourceType",abstractKey:null}],storageKey:null}],type:"CategoryPillar",abstractKey:null};F.hash="9d38de0d45941632df81d63911d04482";var w=e.i(556591);e.i(663298);var M=e.i(921390);e.i(893594);var O=e.i(389572);e.i(400520);var N=e.i(915927);e.i(444461);var B=e.i(33703),U=e.i(340783),$=e.i(962973),K=e.i(713363),G=e.i(741490),j=e.i(79878),H=e.i(970060);let V=(0,G.withGracefulErrorBoundary)(e=>{let t=(0,K.useComponentConfig)("patternSwitcher",e.componentContext||""),{MobilePattern:i,TabletPattern:s,DesktopPattern:r,className:a}=(0,U.default)({},t,e);return(0,T.jsxs)("div",{className:(0,S.default)($.SELECTORS.PatternSwitcher,a),...(0,j.useDataAttributes)(e),children:[(0,T.jsx)("div",{className:(0,S.default)(s||r?H.sharedStyles.layout.hideTabletPlus:null),children:(0,T.jsx)(i,{...e})}),s&&(0,T.jsx)("div",{className:(0,S.default)(r?H.sharedStyles.layout.showTablet:H.sharedStyles.layout.showTabletPlus),children:(0,T.jsx)(s,{...e})}),r&&(0,T.jsx)("div",{className:H.sharedStyles.layout.showDesktop,children:(0,T.jsx)(r,{...e})})]})},{context:"PatternSwitcherErrorBoundary"});var W=e.i(389959);e.i(271832);var Y=e.i(466518);e.i(571350);var q=e.i(226338),z={top:"zuvxtk1 zuvxtk0",right:"zuvxtk2 zuvxtk0"},X={top:"zuvxtk4 zuvxtk3",right:"zuvxtk5 zuvxtk3"},Q={top:"zuvxtk7 zuvxtk6",right:"zuvxtk8 zuvxtk6"},Z="zuvxtkc",J="zuvxtke",ee="zuvxtkf";let et=e=>{let t=(0,K.useComponentConfig)("fourUpAltPattern"),{className:i,cardsData:s,gaComponentName:r="four_up_alt_pattern",desktopPrimaryPosition:a="top",overlap:n}=(0,U.default)({},t,e),l="right"===a;return(0,T.jsxs)("div",{className:(0,S.default)(z[a],i),children:[s[0]&&(0,T.jsxs)("div",{className:X[a],children:[(0,T.jsx)("div",{className:(0,S.default)(l&&H.sharedStyles.layout.hideDesktop),children:(0,T.jsx)(q.default,{...s[0],priorityImage:!0,gaComponentName:r,componentContext:"fourUpAltPattern",className:(0,S.default)("zuvxtk9",l&&H.sharedStyles.layout.hideDesktop),extraImageStyles:"zuvxtka",overlap:n,overlapStyle:n?"categoryPillar":void 0})}),l&&(0,T.jsx)(q.default,{...s[0],priorityImage:!0,gaComponentName:r,componentContext:"fourUpAltPrimaryRightPattern",className:H.sharedStyles.layout.showDesktop,extraImageStyles:"zuvxtkb",overlap:n})]}),(0,T.jsx)("div",{className:Q[a],children:s.slice(1,4).map((e,t)=>(0,T.jsxs)(W.Fragment,{children:[(0,T.jsx)("div",{className:H.sharedStyles.layout.hideTabletPlus,children:(0,T.jsx)(Y.default,{...e,priorityImage:!0,gaComponentName:r,componentContext:"fourUpAltPattern",className:(0,S.default)(Z,2===t&&J),extraImageStyles:ee,lastChild:2===t})}),(0,T.jsx)("div",{className:(0,S.default)(l?H.sharedStyles.layout.showTablet:H.sharedStyles.layout.showTabletPlus),children:(0,T.jsx)(Y.default,{...e,priorityImage:!0,gaComponentName:r,componentContext:"fourUpAltPatternTablet",className:(0,S.default)(Z,2===t&&J),extraImageStyles:ee,lastChild:2===t})}),l&&(0,T.jsx)("div",{className:H.sharedStyles.layout.showDesktop,children:(0,T.jsx)(Y.default,{...e,priorityImage:!0,gaComponentName:r,componentContext:"fourUpAltPrimaryRightPattern",className:(0,S.default)("zuvxtkd",2===t&&J),extraImageStyles:ee,lastChild:2===t})})]},`four-up-alt-pattern-secondary-card-${t}`))})]})};var ei=e.i(236173),es=e.i(977326),er=e.i(453640);let ea=({cardsData:e,gaComponentName:t="three_grid_alt_pattern",mobileCardContext:i="threeGridAltPattern",desktopCardContext:s,mobileCardClassName:r,desktopCardClassName:a,desktopContainerClassName:n})=>{let{mobileContext:l,desktopContext:o}=(0,es.getContexts)(e.length,i,s),d=[],h=[];return e.forEach((i,s)=>{d.push((0,T.jsx)("div",{className:(0,S.default)(er.desktopCardContainer,ei.gridBorders),children:(0,T.jsx)(Y.default,{...i,componentContext:o[s],gaComponentName:t,className:(0,S.default)(er.altCard,a)})},i.id)),h.push((0,W.createElement)(Y.default,{...i,key:i.id,componentContext:l[s],gaComponentName:t,firstChild:0===s,lastChild:s===e.length-1,className:r,imagePosition:"hideImage",mediaVariationIconPlacement:"title"}))}),(0,T.jsxs)("div",{children:[(0,T.jsx)("div",{className:(0,S.default)(er.desktopContainer,n),children:d}),(0,T.jsx)("div",{className:ei.mobileContainer,children:h})]})};e.i(716861);var en=e.i(206580);let el=({cardsData:e,gaComponentName:t="six_up_alt_pattern",className:i})=>(0,T.jsxs)("div",{className:i,children:[(0,T.jsx)(en.default,{className:"_1ax82rg0 _10sa9om11",cardsData:e.slice(0,3),gaComponentName:t}),(0,T.jsx)(ea,{cardsData:e.slice(3),mobileCardContext:"threeGridAltPattern",gaComponentName:t})]});var eo=e.i(913345);let ed=({cardsData:e,ad:t,insertAdBelowPrimaryContainer:i,primaryChildren:s,gaComponentName:r="six_up_pattern",className:a,listClassName:n,primaryContainerClassName:l,secondaryContainerClassName:o,secondaryContainerCardClassName:d,secondaryAnalyticsMetadata:h={},priorityImage:u,heading:c,showNumbers:f=!1,showMobileCard:g=!1})=>{let m={componentContext:"sixUpPatternTop"},p={componentContext:"sixUpPatternBottom"};return(0,T.jsxs)("div",{className:(0,S.default)("b2ghjs0",a),children:[e[0]&&(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)("div",{className:(0,S.default)("b2ghjs1",l),children:s||(0,T.jsx)(q.default,{...e[0],componentContext:"sixUpPatternPrimaryWide",gaComponentName:r,priorityImage:u})},"sixup-primary"),i&&t]}),(0,T.jsx)(eo.default,{metadata:h,children:(0,T.jsxs)("div",{className:(0,S.default)("b2ghjs2",o),children:[c,e.slice(1,6).map((e,s)=>(0,T.jsxs)(W.Fragment,{children:[2===s&&!i&&t,f&&(0,T.jsx)("div",{className:n,children:s+1}),(0,T.jsx)(Y.default,{...e,...s<2?m:p,gaComponentName:r,priorityImage:u,last
2Child:4===s,className:(0,S.default)("b2ghjs3",g&&"b2ghjs5",d)}),g&&(0,T.jsx)(Y.default,{...e,componentContext:"sixUpPatternMobile",gaComponentName:r,priorityImage:u,lastChild:4===s,className:(0,S.default)("b2ghjs4")})]},`six-up-pattern-container-${s}`))]},"sixup-secondary")})]})},eh=({categoryPillar:e,className:t,classNameTitle:i,classNameHeader:s,classNamePattern:r,pillarIndex:a,insertAdAfterLastPillar:n=!0,isLastPillar:l=!1,moreLinkIcon:o,moreLinkText:d="More",moreLinkUnderContentOnMobile:h,classNameMoreLinkText:u,layoutOverride:c})=>{var f,g,m;let p,{layout:y,resource:v,posts:E}=(0,k.useFragment)((F.hash&&"9d38de0d45941632df81d63911d04482"!==F.hash&&console.error("The definition of 'CategoryPillarContainer_categoryPillar' appears to have changed. Run `relay-compiler` to update the generated files to receive the expected data."),F),e),L=(0,w.default)(E?.nodes||[]),A=(f=a,g=l,m=n,p=f%2!=0,g&&p&&m||!g&&p);return"CategoryResourceType"!==v.__typename&&"SuperCatResourceType"!==v.__typename?null:(0,T.jsxs)(eo.default,{metadata:{article_section:v.title},children:[(0,T.jsxs)("div",{className:H.sharedStyles.layout.standardSpacing.xlarge,children:[(0,T.jsx)(N.default,{className:t,classNameHeader:s,header:(0,T.jsx)(B.default,{title:v.title,headingLevel:"h2",componentContext:"categoryPillar",moreLink:{text:d,url:v.path},moreLinkIcon:o,classNameMoreLink:h?H.sharedStyles.layout.showTabletPlus:void 0,classNameTitle:i,classNameMoreLinkText:u}),pattern:((e,t,i,s)=>{switch(t){case"three_up":return i%2==0?(0,T.jsx)(V,{cardsData:e.slice(0,3),componentContext:"categoryPillarThreeUp",mobileContainerClassName:s,desktopContainerClassName:s,gaComponentName:"homepage_category_pillars"}):(0,T.jsx)(en.default,{cardsData:e.slice(0,3),gaComponentName:"homepage_category_pillars",className:s});case"four_up_alt":return(0,T.jsx)(et,{cardsData:e.slice(0,4),gaComponentName:"homepage_category_pillars",className:s,desktopPrimaryPosition:i%2==0?"top":"right"});default:return i%2==0?(0,T.jsx)(ed,{cardsData:e.slice(0,6),gaComponentName:"homepage_category_pillars",className:s}):(0,T.jsx)(el,{cardsData:e.slice(0,6),gaComponentName:"homepage_category_pillars",className:s})}})(L,c??y,a,r)},v.id),h&&(0,T.jsx)("div",{className:(0,S.default)(H.sharedStyles.layout.hideTabletPlus,"_1hfmylg0"),children:(0,T.jsx)(O.default,{href:v.path,text:d,iconRight:o})})]}),A&&(0,T.jsx)(M.default,{adType:"networkRiverHome"})]})},eu=({homepageResource:e,className:t,classNameTitle:i,classNameHeader:s,classNamePattern:r,insertAdAfterLastPillar:a=!0,moreLinkIcon:n,moreLinkText:l,classNameMoreLinkText:o,moreLinkUnderContentOnMobile:d,layoutOverride:h})=>{let{categoryPillars:u}=(0,k.useFragment)((x.hash&&"745bb39a3f1e148d605052d68fa0d8d1"!==x.hash&&console.error("The definition of 'CategoryPillarsContainer_homepageResource' appears to have changed. Run `relay-compiler` to update the generated files to receive the expected data."),x),e);return(0,T.jsx)(T.Fragment,{children:u.map((e,u,c)=>(0,T.jsx)(eh,{categoryPillar:e,pillarIndex:u,insertAdAfterLastPillar:a,isLastPillar:c.length-1===u,className:t,classNameTitle:i,classNameHeader:s,classNamePattern:r,moreLinkIcon:n,moreLinkText:l,moreLinkUnderContentOnMobile:d,layoutOverride:h,classNameMoreLinkText:o},`category-pillar-${u}`))})},ec={argumentDefinitions:[],kind:"Fragment",metadata:null,name:"QuickLinksContainer_query",selections:[{alias:null,args:null,concreteType:"QuickLinksItemType",kind:"LinkedField",name:"quickLinks",plural:!0,selections:[{alias:null,args:null,kind:"ScalarField",name:"title",storageKey:null},{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"resource",plural:!1,selections:[{kind:"InlineFragment",selections:o=[{alias:null,args:null,kind:"ScalarField",name:"permalink",storageKey:null}],type:"EmbedStoryResourceType",abstractKey:null},{kind:"InlineFragment",selections:o,type:"PageResourceType",abstractKey:null},{kind:"InlineFragment",selections:o,type:"PostResourceType",abstractKey:null},{kind:"InlineFragment",selections:o,type:"PackageResourceType",abstractKey:null},{kind:"InlineFragment",selections:o,type:"StreamResourceType",abstractKey:null},{kind:"InlineFragment",selections:o,type:"CategoryResourceType",abstractKey:null}],storageKey:null}],storageKey:null}],type:"RootQuery",abstractKey:null};ec.hash="a3a699a8399281b436c98d533a9344ab";var ef=e.i(210982);let eg=({headline:e="Our World, Explained:",quickLinks:t,className:i})=>{let s=(0,ef.useAnalytics)();return(0,T.jsxs)("div",{className:(0,S.default)($.SELECTORS.QuickLinks,"o6hgaf0",i&&i),children:[(0,T.jsx)("h2",{className:"o6hgaf1",children:e}),(0,T.jsx)("ul",{className:"o6hgaf2",children:t.map((e,i)=>(0,T.jsxs)("li",{className:"o6hgaf4 o6hgaf3",children:[(0,T.jsx)("a",{className:"o6hgaf5",href:e.permalink,onClick:()=>{s?.emit({event:"quick_link_click",quick_link_click:{link_uri:e.permalink,link_title:e.title,index:i}})},children:e.title}),i<t.length-1&&(0,T.jsx)("span",{className:"o6hgaf6 o6hgaf3"})]},i))})]})},em=({query:e,headline:t,className:i})=>{let{quickLinks:s}=(0,k.useFragment)((ec.hash&&"a3a699a8399281b436c98d533a9344ab"!==ec.hash&&console.error("The definition of 'QuickLinksContainer_query' appears to have changed. Run `relay-compiler` to update the generated files to receive the expected data."),ec),e);if(0===s.length)return null;let r=s.map(e=>({title:e.title,permalink:e.resource.permalink||""}));return(0,T.jsx)(eg,{className:i,quickLinks:r,headline:t})},ep={argumentDefinitions:[],kind:"Fragment",metadata:null,name:"SpotlightSectionsContainer_homepageResource",selections:[{alias:null,args:null,concreteType:"SpotlightSectionType",kind:"LinkedField",name:"spotlightSections",plural:!0,selections:[{args:null,kind:"FragmentSpread",name:"SpotlightSectionContainer_spotlightSection"}],storageKey:null}],type:"HomepageResourceType",abstractKey:null};ep.hash="a6c276b3cf89b9c433ca82f87379360d";let ey={argumentDefinitions:[],kind:"Fragment",metadata:null,name:"SpotlightSectionContainer_spotlightSection",selections:[{alias:null,args:null,kind:"ScalarField",name:"hidden",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"layout",storageKey:null},{alias:null,args:[{kind:"Literal",name:"first",value:5}],concreteType:"SpotlightSectionConnection",kind:"LinkedField",name:"posts",plural:!1,selections:[{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"nodes",plural:!0,selections:[{args:null,kind:"FragmentSpread",name:"useContentCardDataMapper_contentResource"}],storageKey:null}],storageKey:"posts(first:5)"},{alias:null,args:null,concreteType:null,kind:"LinkedField",name:"resource",plural:!1,selections:[{alias:null,args:null,kind:"ScalarField",name:"__typename",storageKey:null},{kind:"InlineFragment",selections:d=[{alias:null,args:null,kind:"ScalarField",name:"id",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"title",storageKey:null},{alias:null,args:null,kind:"ScalarField",name:"path",storageKey:null}],type:"CategoryResourceType",abstractKey:null},{kind:"InlineFragment",selections:d,type:"PackageResourceType",abstractKey:null},{kind:"InlineFragment",selections:d,type:"StreamResourceType",abstractKey:null}],storageKey:null}],type:"SpotlightSectionType",abstractKey:null};ey.hash="f7a4a7ac460d6f8d43828164c6c897c5";var ev=e.i(641824);let eT=e=>{let t=(0,K.useComponentConfig)("fiveGridOverflowPattern",e.componentContext||""),{cardsData:i,gaComponentName:s="five_grid_pattern",mobileCardContext:r="fiveGridOverflowPattern",desktopCardContext:a,showGridBorders:n,fixedWidthClassname:l=H.sharedStyles.contentCard.fixedWidthCard,gridBorderClassname:o="a5kjze3",mobileContainerClassName:d,desktopContainerClassName:h,cardExtraImageStyles:u,cardExtraContentBlockStyles:c,cardContainerStyles:f,cardHeadlineClassName:g,cardStyles:m,desktopContainerRef:p}=(0,ev.default)(e,t),{mobileContext:y,desktopContext:v}=(0,es.getContexts)(i.length,r,a),E=[],L=[];
2return i.forEach((e,t)=>{E.push((0,T.jsx)("div",{className:(0,S.default)("a5kjze1",n&&o,f),children:(0,T.jsx)(q.default,{...e,componentContext:v[t],gaComponentName:s,extraImageStyles:u,extraContentBlockStyles:c,className:m,headlineClassName:g})},e.id)),L.push((0,T.jsx)("div",{className:(0,S.default)("a5kjze2",l,n&&o,f),children:(0,T.jsx)(q.default,{...e,componentContext:y[t],gaComponentName:s,extraImageStyles:u,extraContentBlockStyles:c,className:m})},e.id))}),(0,T.jsxs)("div",{children:[(0,T.jsx)("div",{className:(0,S.default)("a5kjze0",h),ref:p,children:E}),(0,T.jsx)("div",{className:(0,S.default)("a5kjze4",d),children:(0,T.jsx)("div",{className:"a5kjze5",children:L})})]})};var eE=e.i(968779);let eS=({spotlightSection:e})=>{let{resource:t,posts:i,hidden:s}=(0,k.useFragment)((ey.hash&&"f7a4a7ac460d6f8d43828164c6c897c5"!==ey.hash&&console.error("The definition of 'SpotlightSectionContainer_spotlightSection' appears to have changed. Run `relay-compiler` to update the generated files to receive the expected data."),ey),e),r=(0,w.default)(i?.nodes||[]),a=(0,eE.filterByTypenames)([t],["PackageResourceType","StreamResourceType","CategoryResourceType"])[0];return!a||s?null:(0,T.jsx)(eo.default,{metadata:{article_section:a.title},children:(0,T.jsx)(N.default,{className:H.sharedStyles.layout.standardSpacing.medium,header:(0,T.jsx)(B.default,{size:"medium",title:a.title,headingLevel:"h2",componentContext:"spotlightSection",moreLink:{text:"More",url:a.path}}),pattern:(0,T.jsx)(eT,{cardsData:r,gaComponentName:"homepage_spotlight"}),indent:!1},a.id)})},eL=({homepageResource:e})=>{let{spotlightSections:t}=(0,k.useFragment)((ep.hash&&"a6c276b3cf89b9c433ca82f87379360d"!==ep.hash&&console.error("The definition of 'SpotlightSectionsContainer_homepageResource' appears to have changed. Run `relay-compiler` to update the generated files to receive the expected data."),ep),e);return t&&t.length?(0,T.jsx)(T.Fragment,{children:t.filter(eE.notNullish).map((e,t)=>(0,T.jsx)(eS,{spotlightSection:e},`spotlight-section-${t}`))}):null};var ek=e.i(385921),eA=e.i(128052),eR=e.i(242399),eb=e.i(424831);e.i(982632);var eI=e.i(679346);e.i(285811);var e_=e.i(14569),eC=e.i(108835);e.i(258175);var eD=e.i(657880);e.i(873832);var eP=e.i(762716);e.i(576337);var ex=e.i(430822);e.i(541638);var eF=e.i(907684),ew=e.i(156378),eM=e.i(179171);let eO=({cardsData:e,gaComponentName:t="curated_content_pattern"})=>{let i=[],s=[];return e.forEach((r,a)=>{i.push((0,W.createElement)(Y.default,{...r,key:r.id,componentContext:"curatedContentMobile",gaComponentName:t,firstChild:0===a,lastChild:a===e.length-1})),s.push((0,W.createElement)(Y.default,{...r,key:r.id,componentContext:"curatedContentDesktop",gaComponentName:t,className:"_15cqxxr2"}))}),(0,T.jsxs)("div",{children:[(0,T.jsx)("div",{className:"_15cqxxr0",children:i}),(0,T.jsx)("div",{className:"_15cqxxr1",children:s})]})},eN=({homepageResource:t})=>{let{curatedContentSections:i}=(0,k.useFragment)(e.r(606921),t),s=i.filter(eE.notNullish)[0],r=(0,w.default)(s?.posts?.nodes??[]);if(!s||s.hidden||!r.length)return null;let a=s.resource&&"path"in s.resource?s.resource:null,n=a?.path??null,l=s.title||a?.title||null;return(0,T.jsx)(N.default,{className:(0,S.default)($.SELECTORS.HomepageBottomCuratedContent,H.sharedStyles.layout.standardSpacing.medium,"x9rqz60 _10sa9om11"),classNameHeader:"x9rqz61",header:(0,T.jsx)(B.default,{size:"xsmall",title:l,headingLevel:"h2",componentContext:"curatedContent",classNameContainer:"x9rqz62",...s.showMoreLink&&n?{moreLink:{text:"More",url:n}}:{}}),pattern:(0,T.jsx)(eO,{cardsData:r,gaComponentName:"homepage_curated_content"}),indent:!1})},eB=({className:e="",width:t=31,height:i=30})=>(0,T.jsxs)("svg",{className:e,width:t,height:i,xmlns:"http://www.w3.org/2000/svg",xmlSpace:"preserve",x:"0",y:"0",version:"1.1",viewBox:"0 0 50.6 50.2",children:[(0,T.jsx)("title",{children:"Crossword"}),(0,T.jsx)("style",{children:".st0{fill:#fff200;stroke:#000;stroke-width:4;stroke-miterlimit:10}.st1{fill:none}.st1,.st2{stroke:#000;stroke-width:4;stroke-miterlimit:10}.st2,.st4{fill:#fff}.st5{fill:#8e8e8e;stroke:#020202;stroke-width:14;stroke-linejoin:round}.st6{fill:#fff;stroke-width:13}.st6,.st7,.st8{stroke:#000;stroke-linejoin:round}
2.st7{fill:none;stroke-width:15;stroke-linecap:round}.st8{fill:#fff200;stroke-width:14}.st9{fill:#8e8e8e}.st10{fill:#020202}"}),(0,T.jsx)("path",{d:"M1.6 1.7H49V48H1.6z",style:{fill:"#fff200"}}),(0,T.jsx)("path",{d:"M1.5 1.3v47.5H49V1.3H1.5zm17.1 17.1h13.3v13.4H18.6V18.4zm-1.8 13.4H3.3V18.4h13.5v13.4zm0-15.2H3.3V3.1h13.5v13.5zm1.8 17h13.3V47H18.6V33.6zm28.6 13.5H33.7V33.6h13.5v13.5zm0-30.5H33.7V3.1h13.5v13.5z"})]});var eU=e.i(847374);let e$=({className:e,labelClassName:t})=>{let i=(0,ef.useAnalytics)();return(0,T.jsxs)("a",{href:"/21523212/crossword-puzzles-free-daily-printable",className:(0,S.default)("theqgh0",e),onClick:()=>{i?.emit({event:"utility_link_click",utility_link_click:{url:"/21523212/crossword-puzzles-free-daily-printable",name:"Play the Vox crossword"}})},children:[(0,T.jsx)("span",{className:"theqgh1",children:(0,T.jsx)(eB,{width:28,height:27})}),(0,T.jsxs)("span",{className:(0,S.default)("theqgh2",t),children:["Play today's crossword       ",(0,T.jsx)(eU.default,{width:14,height:14,className:"theqgh3"})]})]})};e.i(824158);var eK=e.i(778888);let eG=({items:e,title:t,placement:i,className:s})=>{let r=(0,ef.useAnalytics)();return 0===e.length?null:(0,T.jsxs)("div",{className:(0,S.default)("bmn4dj0","desktop"===i?"bmn4dj8":"mobile"===i?"bmn4dj9":void 0,s),onClick:e=>{let t=e.target.closest("a");if(!t)return;let i="www.vox.com"!==new URL(t.href,window.location.href).hostname,s=t.closest("li"),a=null;s?.parentElement&&(a=Array.from(s.parentElement.children).indexOf(s)+1);let n=i?"click":"article_click";r?.emit({event:n,[n]:{outbound:String(i),component_name:"start_here",position:a}})},children:[t&&(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)("p",{className:"bmn4dj1",children:t}),(0,T.jsx)("hr",{className:"bmn4dj2"})]}),(0,T.jsx)("ol",{className:"bmn4dj3",children:e.map((e,t)=>(0,T.jsxs)("li",{className:"bmn4dj4",children:[(0,T.jsx)("span",{className:"bmn4dj5","aria-hidden":"true",children:(0,T.jsx)("span",{className:"bmn4dj6",children:t+1})}),(0,T.jsx)("span",{className:(0,S.default)(H.sharedStyles.text.standardLinkStyles),children:(0,T.jsx)(eK.default,{className:"bmn4dj7",html:e.html,component:"span"})})]},t))})]})},ej=({data:e})=>{let t=e.posts?.edges??[],i=t[0]?.node,s=t.slice(1,6).map(e=>
2e.node).filter(Boolean),r=(0,w.default)(i?[i]:[]),a=(0,w.default)(s),n=a.slice(-2),l=r[0];if(!i||!l)return null;let o=e.startHere?.items??[],d=e.startHere?.title;return(0,T.jsxs)("div",{className:"_10j2bu50",children:[(0,T.jsx)(eG,{items:o,title:d,placement:"desktop",className:"_10j2bu55"}),(0,T.jsx)("div",{className:"_10j2bu51",children:(0,T.jsx)(eo.default,{metadata:{position:1},children:(0,T.jsx)(q.default,{...l,componentContext:"heroLedeSixUpJumbo",gaComponentName:"home_hero",className:"_10j2bu52",imageAspectRatio:"fourThree",priorityImage:!0})})}),(0,T.jsxs)("div",{className:"_10j2bu53",children:[a.map((e,t)=>{let i=t>=a.length-2,s=t===a.length-3;return(0,T.jsx)(eo.default,{metadata:{position:t+2},children:(0,T.jsx)(Y.default,{...e,componentContext:"heroLedeSixUpMicro",imagePosition:"right",gaComponentName:"hero_lede_six_up",lastChild:t===a.length-1,className:(0,S.default)(0===t&&"_10j2bu54",i?"_10j2bu58":s&&"_10j2bu5a")})},e.id)}),n.map((e,t,i)=>(0,T.jsx)(eo.default,{metadata:{position:a.length-2+t+2},children:(0,T.jsx)(Y.default,{...e,componentContext:"heroLedeSixUpMicro",gaComponentName:"hero_lede_six_up",imagePosition:"hideImage",lastChild:t===i.length-1,className:"_10j2bu57"})},`desktop-${e.id}`)),(0,T.jsx)("div",{className:"_10j2bu5b",children:(0,T.jsx)(e$,{className:"_10j2bu5c",labelClassName:"_10j2bu5d"})})]}),(0,T.jsx)(M.default,{adType:"medrecFrontpageHero"}),(0,T.jsx)(eG,{items:o,title:d,placement:"mobile"}),(0,T.jsx)("div",{className:"_10j2bu5e",children:n.map((e,t,i)=>(0,T.jsx)(eo.default,{metadata:{position:a.length-2+t+2},children:(0,T.jsx)(Y.default,{...e,componentContext:"heroLedeSixUpMicro",gaComponentName:"hero_lede_six_up",imagePosition:"right",lastChild:t===i.length-1})},`mobile-last-${e.id}`))}),(0,T.jsx)("div",{className:"_10j2bu5f",children:(0,T.jsx)(e$,{})})]})},eH=({cards:e,placement:t,startPosition:i})=>0===e.length?null:"belowVideo"===t?(0,T.jsx)("div",{className:"_1wvb8a95",children:e.map((t,s)=>(0,T.jsx)(eo.default,{metadata:{position:i+s},children:(0,T.jsx)(Y.default,{...t,componentContext:"heroLedeThreeUpCompactBelowVideo",gaComponentName:"hero_lede_three_up",imagePosition:"hideImage",className:"_1wvb8a96",lastChild:s===e.length-1})},`desktop-${t.id}`))}):(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)("div",{className:"_1wvb8a90",children:e.map((t,s)=>(0,T.jsx)(eo.default,{metadata:{position:i+s},children:(0,T.jsx)(Y.default,{...t,componentContext:"heroLedeThreeUpCompact",gaComponentName:"hero_lede_three_up",imagePosition:"right",firstChild:0===s,lastChild:s===e.length-1})},`mobile-${t.id}`))}),(0,T.jsx)("div",{className:"_1wvb8a91",children:e.map((e,t)=>(0,T.jsxs)(W.Fragment,{children:[(0,T.jsx)(eo.default,{metadata:{position:i+t},children:(0,T.jsx)(Y.default,{...e,componentContext:"heroLedeThreeUpCompact",gaComponentName:"hero_lede_three_up",imagePosition:"right",className:0===t?"_1wvb8a92":"_1wvb8a93"})}),0===t&&(0,T.jsx)("div",{"aria-hidden":!0,className:"_1wvb8a94"})]},`tablet-${e.id}`))})]}),eV=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},eW=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=eY},eY=Number.MAX_SAFE_INTEGER||0x1fffffffffffff,eq=((h={}).NETWORK_ERROR="networkError",h.MEDIA_ERROR="mediaError",h.KEY_SYSTEM_ERROR="keySystemError",h.MUX_ERROR="muxError",h.OTHER_ERROR="otherError",h),ez=((u={}).KEY_SYSTEM_NO_KEYS="keySystemNoKeys",u.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",u.KEY_SYSTEM_NO_SESSION="keySystemNoSession",u.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",u.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",u.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",u.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",u.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",u.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",u.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",u.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",u.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",u.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",u.MANIFEST_LOAD_ERROR="manifestLoadError",u.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",u.MANIFEST_PARSING_ERROR="manifestParsingError",u.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",u.LEVEL_EMPTY_ERROR="levelEmptyError",u.LEVEL_LOAD_ERROR="levelLoadError",u.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",u.
2LEVEL_PARSING_ERROR="levelParsingError",u.LEVEL_SWITCH_ERROR="levelSwitchError",u.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",u.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",u.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",u.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",u.FRAG_LOAD_ERROR="fragLoadError",u.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",u.FRAG_DECRYPT_ERROR="fragDecryptError",u.FRAG_PARSING_ERROR="fragParsingError",u.FRAG_GAP="fragGap",u.REMUX_ALLOC_ERROR="remuxAllocError",u.KEY_LOAD_ERROR="keyLoadError",u.KEY_LOAD_TIMEOUT="keyLoadTimeOut",u.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",u.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",u.BUFFER_APPEND_ERROR="bufferAppendError",u.BUFFER_APPENDING_ERROR="bufferAppendingError",u.BUFFER_STALLED_ERROR="bufferStalledError",u.BUFFER_FULL_ERROR="bufferFullError",u.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",u.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",u.ASSET_LIST_LOAD_ERROR="assetListLoadError",u.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",u.ASSET_LIST_PARSING_ERROR="assetListParsingError",u.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",u.INTERNAL_EXCEPTION="internalException",u.INTERNAL_ABORTED="aborted",u.ATTACH_MEDIA_ERROR="attachMediaError",u.UNKNOWN="unknown",u),eX=((c={}).MEDIA_ATTACHING="hlsMediaAttaching",c.MEDIA_ATTACHED="hlsMediaAttached",c.MEDIA_DETACHING="hlsMediaDetaching",c.MEDIA_DETACHED="hlsMediaDetached",c.MEDIA_ENDED="hlsMediaEnded",c.STALL_RESOLVED="hlsStallResolved",c.BUFFER_RESET="hlsBufferReset",c.BUFFER_CODECS="hlsBufferCodecs",c.BUFFER_CREATED="hlsBufferCreated",c.BUFFER_APPENDING="hlsBufferAppending",c.BUFFER_APPENDED="hlsBufferAppended",c.BUFFER_EOS="hlsBufferEos",c.BUFFERED_TO_END="hlsBufferedToEnd",c.BUFFER_FLUSHING="hlsBufferFlushing",c.BUFFER_FLUSHED="hlsBufferFlushed",c.MANIFEST_LOADING="hlsManifestLoading",c.MANIFEST_LOADED="hlsManifestLoaded",c.MANIFEST_PARSED="hlsManifestParsed",c.LEVEL_SWITCHING="hlsLevelSwitching",c.LEVEL_SWITCHED="hlsLevelSwitched",c.LEVEL_LOADING="hlsLevelLoading",c.LEVEL_LOADED="hlsLevelLoaded",c.LEVEL_UPDATED="hlsLevelUpdated",c.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",c.LEVELS_UPDATED="hlsLevelsUpdated",c.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",c.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",c.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",c.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",c.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",c.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",c.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",c.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",c.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",c.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",c.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",c.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",c.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",c.CUES_PARSED="hlsCuesParsed",c.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",c.INIT_PTS_FOUND="hlsInitPtsFound",c.FRAG_LOADING="hlsFragLoading",c.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",c.FRAG_LOADED="hlsFragLoaded",c.FRAG_DECRYPTED="hlsFragDecrypted",c.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",c.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",c.FRAG_PARSING_METADATA="hlsFragParsingMetadata",c.FRAG_PARSED="hlsFragParsed",c.FRAG_BUFFERED="hlsFragBuffered",c.FRAG_CHANGED="hlsFragChanged",c.FPS_DROP="hlsFpsDrop",c.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",c.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",c.ERROR="hlsError",c.DESTROYING="hlsDestroying",c.KEY_LOADING="hlsKeyLoading",c.KEY_LOADED="hlsKeyLoaded",c.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",c.BACK_BUFFER_REACHED="hlsBackBufferReached",c.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",c.ASSET_LIST_LOADING="hlsAssetListLoading",c.ASSET_LIST_LOADED="hlsAssetListLoaded",c.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",c.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",c.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",c.INTERSTITIAL_STARTED="hlsInterstitialStarted",c.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",c.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",c.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",c.INTERSTITIAL_ENDED="hlsInterstitialEnded",c.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",c.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",c.EVENT_CUE_ENTER="hlsEventCueEnter",c);var eQ="manifest",eZ="level",eJ="audioTrack",e0="subtitleTrack",e1="main",e2="audio",e3="subtitle";class e4{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){let i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}
2getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class e5{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 e4(e),this.fast_=new e4(t),this.defaultTTFB_=s,this.ttfb_=new e4(e)}update(e,t){let{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new e4(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new e4(t,s.getEstimate(),s.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new e4(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){let i=(e=Math.max(e,this.minDelayMs_))/1e3,s=8*t/i;this.fast_.sample(i,s),this.slow_.sample(i,s)}sampleTTFB(e){let t=Math.sqrt(2)*Math.exp(-Math.pow(e/1e3,2)/2);this.ttfb_.sample(t,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 e8(){return(e8=Object.assign.bind()).apply(null,arguments)}function e6(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function e9(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?e6(Object(i),!0).forEach(function(t){var s,r;s=t,r=i[t],(s=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var s=i.call(e,t);if("object"!=typeof s)return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(s))in e?Object.defineProperty(e,s,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[s]=r}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):e6(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class e7{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${e}]:`;this.trace=te,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)}}let te=function(){},tt={trace:te,debug:te,log:te,warn:te,info:te,error:te};function ti(){return e8({},tt)}function ts(e,t,i){let s;return t[e]?t[e].bind(t):(s=self.console[e])?s.bind(self.console,`${i?"["+i+"] ":""}[${e}] >`):te}let tr=ti();function ta(e=!0){if(!("u"<typeof self))return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function tn(e,t){let i=Object.keys(e),s=Object.keys(t),r=i.length,a=s.length;return!r||!a||r===a&&!i.some(e=>-1===s.indexOf(e))}function tl(e,t=!1){let i,s;if("u">typeof TextDecoder){let i=new TextDecoder("utf-8").decode(e);if(t){let e=i.indexOf("\0");return -1!==e?i.substring(0,e):i}return i.replace(/\0/g,"")}let r=e.length,a="",n=0;for(;n<r&&(0!==(i=e[n++])||!t);)if(0!==i&&3!==i)switch(i>>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:a+=String.fromCharCode((31&i)<<6|63&(s=e[n++]));break;case 14:a+=String.fromCharCode((15&i)<<12|(63&(s=e[n++]))<<6|63&e[n++])}return a}function to(e){let t="";for(let i=0;i<e.length;i++){let s=e[i].toString(16);s.length<2&&(s="0"+s),t+=s}return t}function td(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var th={exports:{}},tu=y?th.exports:(y=1,i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,th.exports=n={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var r=n.parseURL(e);if(!r)throw Error("Error trying to parse base URL.");return r.path=n.normalizePath(r.path),n.buildURLFromParts(r)}var a=n.parseURL(t);if(!a)throw Error("Error trying to parse relative URL.");
vendor: 1,108 bytes, line 2
2if(a.scheme)return i.alwaysNormalize?(a.path=n.normalizePath(a.path),n.buildURLFromParts(a)):t;var l=n.parseURL(e);if(!l)throw Error("Error trying to parse base URL.");if(!l.netLoc&&l.path&&"/"!==l.path[0]){var o=s.exec(l.path);l.netLoc=o[1],l.path=o[2]}l.netLoc&&!l.path&&(l.path="/");var d={scheme:l.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(d.netLoc=l.netLoc,"/"!==a.path[0]))if(a.path){var h=l.path,u=h.substring(0,h.lastIndexOf("/")+1)+a.path;d.path=n.normalizePath(u)}else d.path=l.path,!a.params&&(d.params=l.params,a.query||(d.query=l.query));return null===d.path&&(d.path=i.alwaysNormalize?n.normalizePath(a.path):a.path),n.buildURLFromParts(d)},parseURL:function(e){var t=i.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(r,"");e.length!==(e=e.replace(a,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}}
2,th.exports);class tc{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var tf="audio",tg="video",tm="audiovideo";class tp{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,function(e,t){let i=function e(t,i){let s=Object.getPrototypeOf(t);if(s){let t=Object.getOwnPropertyDescriptor(s,i);return t||e(s,i)}}(e,t);i&&(i.enumerable=!0,Object.defineProperty(e,t,i))}(this,"stats")}setByteRange(e,t){let i,s=e.split("@",2);i=1===s.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[tf]:null,[tg]:null,[tm]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new tc),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=tu.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[tf]=null,e[tg]=null,e[tm]=null}}function ty(e){return"initSegment"!==e.sn}class tv extends tp{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if(eV(e)&&eV(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!(null!=(e=this._decryptdata)&&e.keyId)){let e=Object.keys(t);if(1===e.length){let i=this._decryptdata=t[e[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;let e=eV(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e,t;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){let e=Object.keys(this.levelkeys),i=e.length;if(i>1||1===i&&null!=(t=this.levelkeys[e[0]])&&t.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!eV(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return ty(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){let t=this.levelkeys;if(t){var i;let s=t[e];s&&!(null!=(i=this._decryptdata)&&i.keyId)&&(this._decryptdata=s.getDecryptData(this.sn,t))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,i,s,r,a=!1){let{elementaryStreams:n}=this,l=n[e];if(!l){n[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:r,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,s),l.endDTS=Math.max(l.endDTS,r)}}class tT extends tp{constructor(e,t,i,s,r){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=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,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}let tE=[].push,tS={video:1,audio:2,id3:3,text:4};function tL(e){return String.fromCharCode.apply(null,e)}function tk(e,t){let i=e[t]<<8|e[t+1];return i<0?65536+i:i}function tA(e,t){let i=tb(e,t);return i<0?0x100000000+i:i}function tR(e,t){let i=tA(e,t);return i*=0x100000000,i+=tA(e,t+4)}function tb(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function tI(e,t){let i=[];if(!t.length)return i;let s=e.byteLength;for(let r=0;r<s;){let a=tA(e,r),n=tL(e.subarray(r+4,r+8)),l=a>1?r+a:s;if(n===t[0])if(1===t.length)i.push(e.subarray(r+8,l));else{let s=tI(e.subarray(r+8,l),t.slice(1));s.length&&tE.apply(i,s)}r=l}return i}function t_(e){let t=[],i=tI(e,["moov","trak"]);for(let e=0;e<i.length;e++){let s=i[e],r=tI(s,["tkhd"])[0];if(r){let e=r[0],i=tA(r,0===e?12:20),a=tI(s,["mdia","mdhd"])[0];if(a){e=a[0];let r=tA(a,0===e?12:20),n=tI(s,["mdia","hdlr"])[0];if(n){let e=tL(n.subarray(8,12)),a={soun:tf,vide:tg}[e],l=function(e){let t,i=e.subarray(8),s=i.subarray(86),r=tL(i.subarray(4,8)),a=r,n="enca"===r||"encv"===r;if(n){let e=tI(i,[r])[0].subarray("enca"===r?28:78);
2tI(e,["sinf"]).forEach(e=>{let t=tI(e,["schm"])[0];if(t){let i=tL(t.subarray(4,8));if("cbcs"===i||"cenc"===i){let t=tI(e,["frma"])[0];t&&(a=tL(t))}}})}let l=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":{let e=tI(s,["avcC"])[0];e&&e.length>3&&(a+="."+tP(e[1])+tP(e[2])+tP(e[3]),t=tC("avc1"===l?"dva1":"dvav",s));break}case"mp4a":{let e=tI(i,[r])[0],t=tI(e.subarray(28),["esds"])[0];if(t&&t.length>7){let e=4;if(3!==t[e++])break;e=tD(t,e)+2;let i=t[e++];if(128&i&&(e+=2),64&i&&(e+=t[e++]),4!==t[e++])break;e=tD(t,e);let s=t[e++];if(64===s)a+="."+tP(s);else break;if(e+=12,5!==t[e++])break;e=tD(t,e);let r=t[e++],n=(248&r)>>3;31===n&&(n+=1+((7&r)<<3)+((224&t[e])>>5)),a+="."+n}break}case"hvc1":case"hev1":{let e=tI(s,["hvcC"])[0];if(e&&e.length>12){let t=e[1],i=["","A","B","C"][t>>6],s=tA(e,2),r=e[12],n=e.subarray(6,12);a+="."+i+(31&t),a+="."+(function(e){let t=0;for(let i=0;i<32;i++)t|=(e>>i&1)<<31-i;return t>>>0})(s).toString(16).toUpperCase(),a+="."+((32&t)>>5?"H":"L")+r;let l="";for(let e=n.length;e--;){let t=n[e];(t||l)&&(l="."+t.toString(16).toUpperCase()+l)}a+=l}t=tC("hev1"==l?"dvhe":"dvh1",s);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":a=tC(a,s)||a;break;case"vp09":{let e=tI(s,["vpcC"])[0];if(e&&e.length>6){let t=e[4],i=e[5],s=e[6]>>4&15;a+="."+tx(t)+"."+tx(i)+"."+tx(s)}break}case"av01":{let e=tI(s,["av1C"])[0];if(e&&e.length>2){let i=e[1]>>>5,r=31&e[1],n=e[2]>>>7?"H":"M",l=(64&e[2])>>6,o=(32&e[2])>>5,d=(16&e[2])>>4,h=(8&e[2])>>3,u=(4&e[2])>>2,c=3&e[2];a+="."+i+"."+tx(r)+n+"."+tx(2===i&&l?o?12:10:l?10:8)+"."+d+"."+h+u+c+"."+tx(1)+"."+tx(1)+"."+tx(1)+".0",t=tC("dav1",s)}}}return{codec:a,encrypted:n,supplemental:t}}(tI(s,["mdia","minf","stbl","stsd"])[0]);a?(t[i]={timescale:r,type:a,stsd:l},t[a]=e9({timescale:r,id:i},l)):t[i]={timescale:r,type:e,stsd:l}}}}}return tI(e,["moov","mvex","trex"]).forEach(e=>{let i=t[tA(e,4)];i&&(i.default={duration:tA(e,12),flags:tA(e,20)})}),t}function tC(e,t){let i=tI(t,["dvvC"]),s=i.length?i[0]:tI(t,["dvcC"])[0];if(s){let t=s[2]>>1&127,i=s[2]<<5&32|s[3]>>3&31;return e+"."+tx(t)+"."+tx(i)}}function tD(e,t){let i=t+5;for(;128&e[t++]&&t<i;);return t}function tP(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function tx(e){return(e<10?"0":"")+e}function tF(e,t){tI(e,["moov","trak"]).forEach(e=>{let i=tI(e,["mdia","minf","stbl","stsd"])[0];if(!i)return;let s=i.subarray(8),r=tI(s,["enca"]),a=r.length>0;a||(r=tI(s,["encv"])),r.forEach(e=>{tI(a?e.subarray(28):e.subarray(78),["sinf"]).forEach(e=>{let i=tw(e);i&&t(i,a)})})})}function tw(e){let t=tI(e,["schm"])[0];if(t){let i=tL(t.subarray(4,8));if("cbcs"===i||"cenc"===i){let t=tI(e,["schi","tenc"])[0];if(t)return t}}}function tM(e,t){let i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function tO(e,t){let i=[],s=t.samples,r=t.timescale,a=t.id,n=!1;
2return tI(s,["moof"]).map(l=>{let o=l.byteOffset-8;tI(l,["traf"]).map(l=>{let d=tI(l,["tfdt"]).map(e=>{let t=e[0],i=tA(e,4);return 1===t&&(i*=0x100000000,i+=tA(e,8)),i/r})[0];return void 0!==d&&(e=d),tI(l,["tfhd"]).map(d=>{let h=tA(d,4),u=0xffffff&tA(d,0),c=0,f=0,g=8;h===a&&((1&u)!=0&&(g+=8),(2&u)!=0&&(g+=4),(8&u)!=0&&(c=tA(d,g),g+=4),(16&u)!=0&&(f=tA(d,g),g+=4),(32&u)!=0&&(g+=4),"video"===t.type&&(n=tN(t.codec)),tI(l,["trun"]).map(a=>{let l=a[0],d=0xffffff&tA(a,0),h=0,u=(256&d)!=0,g=0,m=(512&d)!=0,p=0,y=(1024&d)!=0,v=(2048&d)!=0,T=0,E=tA(a,4),S=8;(1&d)!=0&&(h=tA(a,S),S+=4),(4&d)!=0&&(S+=4);let L=h+o;for(let o=0;o<E;o++){if(u?(g=tA(a,S),S+=4):g=c,m?(p=tA(a,S),S+=4):p=f,y&&(S+=4),v&&(T=0===l?tA(a,S):tb(a,S),S+=4),t.type===tg){let t=0;for(;t<p;){let a=tA(s,L);L+=4,function(e,t){if(!e)return 6==(31&t);{let e=t>>1&63;return 39===e||40===e}}(n,s[L])&&tB(s.subarray(L,L+a),n?2:1,e+T/r,i),L+=a,t+=a+4}}e+=g/r}}))})})}),i}function tN(e){if(!e)return!1;let t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function tB(e,t,i,s){let r,a=tU(e);r=0+t;let n=0,l=0,o=0;for(;r<a.length;){n=0;do{if(r>=a.length)break;n+=o=a[r++]}while(255===o)l=0;do{if(r>=a.length)break;l+=o=a[r++]}while(255===o)let e=a.length-r,t=r;if(l<e)r+=l;else if(l>e){tr.error(`Malformed SEI payload. ${l} is too small, only ${e} bytes left to parse.`);break}if(4===n){if(181===a[t++]){let e=tk(a,t);if(t+=2,49===e){let e=tA(a,t);if(t+=4,0x47413934===e){let e=a[t++];if(3===e){let r=a[t++],l=31&r,o=64&r,d=o?2+3*l:0,h=new Uint8Array(d);if(o){h[0]=r;for(let e=1;e<d;e++)h[e]=a[t++]}s.push({type:e,payloadType:n,pts:i,bytes:h})}}}}}else if(5===n&&l>16){let e=[];for(let i=0;i<16;i++){let s=a[t++].toString(16);e.push(1==s.length?"0"+s:s),(3===i||5===i||7===i||9===i)&&e.push("-")}let r=l-16,o=new Uint8Array(r);for(let e=0;e<r;e++)o[e]=a[t++];s.push({payloadType:n,pts:i,uuid:e.join(""),userData:tl(o),userDataBytes:o})}}}function tU(e){let t=e.byteLength,i=[],s=1;for(;s<t-2;)0===e[s]&&0===e[s+1]&&3===e[s+2]?(i.push(s+2),s+=2):s++;if(0===i.length)return e;let r=t-i.length,a=new Uint8Array(r),n=0;for(s=0;s<r;n++,s++)n===i[0]&&(n++,i.shift()),a[s]=e[n];return a}let t$={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 tK(e,t){let i=t$[t];return!!i&&!!i[e.slice(0,4)]}function tG(e,t,i=!0){return!e.split(",").some(e=>!tj(e,t,i))}function tj(e,t,i=!0){var s;let r=ta(i);return null!=(s=null==r?void 0:r.isTypeSupported(tH(e,t)))&&s}function tH(e,t){return`${t}/mp4;codecs=${e}`}function tV(e){if(e){let t=e.substring(0,4);return t$.video[t]}return 2}function tW(e){let t=/\(Windows.+Firefox\//i.test(navigator.userAgent);return e.split(",").reduce((e,i)=>{let s=t&&tN(i)?9:t$.video[i];return s?(2*s+e)/(e?3:2):(t$.audio[i]+e)/(e?2:1)},0)}let tY={},tq=/flac|opus|mp4a\.40\.34/i;function tz(e,t=!0){return e.replace(tq,e=>(function(e,t=!0){if(tY[e])return tY[e];let i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let r=0;r<i.length;r++){var s;if(tj(i[r],"audio",t))return tY[e]=i[r],i[r];if("mp3"===i[r]&&null!=(s=ta(t))&&s.isTypeSupported("audio/mpeg"))return""}return e})(e.toLowerCase(),t))}function tX(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(tQ(e,"audio")||tQ(e,"video")))return e;if(t){let i=t.split(",");if(i.length>1){if(e){for(let t=i.length;t--;)if(i[t].substring(0,4)===e.substring(0,4))return i[t]}return i[0]}}return t||e}function tQ(e,t){return tK(e,t)&&tj(e,t)}function tZ(e){let t=ta(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function tJ(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}let t0={supported:!1,smooth:!1,powerEfficient:!1},t1={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function t2(e,t){return{supported:!1,configurations:t,decodingInfoResults:[t0],error:e}}function t3(e,t,i,s={}){var r,a,n,l,o,d;let h,u,c,f,g,m,p,y,v=e.videoCodec;if(!v&&!e.audioCodec||!i)return Promise.resolve(t1);let T=[],E=(h=null==(a=(r=e).videoCodec)?void 0:a.split(","),u=t4(r),c=r.width||640,f=r.height||480,g=r.frameRate||30,m=r.videoRange.toLowerCase(),h?h.map(e=>{let t={contentType:tH(function(e){if(e.startsWith("av01.")){let t=e.split("."),i=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=i[e-4];return t.join(".")}return e}(e),"video"),width:c,height:f,bitrate:u,framerate:g};return"sdr"!==m&&(t.transferFunction=m),t}):[]),S=E.length,L=(n=e,l=t,o=S>0,p=null==(d=n.audioCodec)?void 0:d.split(","),y=t4(n),p&&n.audioGroups?n.audioGroups.reduce((e,t)=>
2{var i;let s=t?null==(i=l.groups[t])?void 0:i.tracks:null;return s?s.reduce((e,i)=>{if(i.groupId===t){let t=parseFloat(i.channels||"");p.forEach(i=>{let s={contentType:tH(i,"audio"),bitrate:o?function(e,t){if(t<=1)return 1;let i=128e3;return"ec-3"===e?i=768e3:"ac-3"===e&&(i=64e4),Math.min(t/2,i)}(i,y):y};t&&(s.channels=""+t),e.push(s)})}return e},e):e},[]):[]),k=L.length;for(let e=S||+k||1;e--;){let t={type:"media-source"};if(S&&(t.video=E[e%S]),k){t.audio=L[e%k];let i=t.audio.bitrate;t.video&&i&&(t.video.bitrate-=i)}T.push(t)}if(v){let e=navigator.userAgent;if(v.split(",").some(e=>tN(e))&&/\(Windows.+Firefox\//i.test(navigator.userAgent))return Promise.resolve(t2(Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),T))}return Promise.all(T.map(e=>{let t=function(e){let t="",{audio:i,video:s}=e;if(s){let e=tJ(s.contentType);t+=`${e}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(i){let e=tJ(i.contentType);t+=`${s?"_":""}${e}_c${i.channels}`}return t}(e);return s[t]||(s[t]=i.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:T,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:T,decodingInfoResults:[],error:e}))}function t4(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}let t5=["NONE","TYPE-0","TYPE-1",null],t8=["SDR","PQ","HLG"];function t6(e){let{canSkipUntil:t,canSkipDateRanges:i,age:s}=e;return t&&s<t/2?i?"v2":"YES":""}class t9{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){let t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class t7{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(e=>!!e).map(e=>e.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=null==(t=e.supplemental)?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 ie(this._audioGroups,e)}hasSubtitleGroup(e){return ie(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.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 null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function ie(e,t){return!!t&&!!e&&-1!==e.indexOf(t)}let it=(e,t)=>
2{let i;return JSON.stringify(e,(i=new WeakSet,(e,s)=>{if(t&&(s=t(e,s)),"object"==typeof s&&null!==s){if(i.has(s))return;i.add(s)}return s}))};function ii(e,t){tr.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function is(e){return e.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);let 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 ir(e){if(!e)return e;let{lang:t,assocLang:i,characteristics:s,channels:r,audioCodec:a}=e;return{lang:t,assocLang:i,characteristics:s,channels:r,audioCodec:a}}function ia(e,t,i){if("attrs"in e){let i=t.indexOf(e);if(-1!==i)return i}for(let s=0;s<t.length;s++)if(il(e,t[s],i))return s;return -1}function il(e,t,i){let{groupId:s,name:r,lang:a,assocLang:n,default:l}=e,o=e.forced;return(void 0===s||t.groupId===s)&&(void 0===r||t.name===r)&&(void 0===a||function(e,t="--"){return e.length===t.length?e===t:e.startsWith(t)||t.startsWith(e)}(a,t.lang))&&(void 0===a||t.assocLang===n)&&(void 0===l||t.default===l)&&(void 0===o||t.forced===o)&&(!("characteristics"in e)||function(e,t=""){let i=e.split(","),s=t.split(",");return i.length===s.length&&!i.some(e=>-1===s.indexOf(e))}(e.characteristics||"",t.characteristics))&&(void 0===i||i(e,t))}function io(e,t){let{audioCodec:i,channels:s}=e;return(void 0===i||(t.audioCodec||"").substring(0,4)===i.substring(0,4))&&(void 0===s||s===(t.channels||"2"))}function id(e,t,i){for(let s=t;s>-1;s--)if(i(e[s]))return s;for(let s=t+1;
2s<e.length;s++)if(i(e[s]))return s;return -1}function ih(e,t){var i;return!!e&&e!==(null==(i=t.loadLevelObj)?void 0:i.uri)}let iu=function(e,t){let i=0,s=e.length-1,r=null,a=null;for(;i<=s;){let n=t(a=e[r=(i+s)/2|0]);if(n>0)i=r+1;else{if(!(n<0))return a;s=r-1}}return null};function ic(e,t,i=0,s=0,r=.005){let a=null;if(e){a=t[1+e.sn-t[0].sn]||null;let s=e.endDTS-i;s>0&&s<15e-7&&(i+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else 0===i&&0===t[0].start&&(a=t[0]);if(a&&((!e||e.level===a.level)&&0===ig(i,s,a)||function(e,t,i){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){let s=t.tagList.reduce((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e),i);return e.start<=s}return!1}(a,e,Math.min(r,s))))return a;let n=iu(t,ig.bind(null,i,s));return n&&(n!==e||!a)?n:a}function ig(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;let s=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-s<=e?1:i.start-s>e&&i.start?-1:0}function im(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){let s,r=e.fragments,{fragmentHint:a}=e;return a&&(r=r.concat(a)),iu(r,e=>e.cc<t?1:e.cc>t?-1:(s=e,e.end<=i)?1:e.start>i?-1:0),s||null}return null}function ip(e){switch(e.details){case ez.FRAG_LOAD_TIMEOUT:case ez.KEY_LOAD_TIMEOUT:case ez.LEVEL_LOAD_TIMEOUT:case ez.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function iy(e){return e.details.startsWith("key")}function iv(e){return iy(e)&&!!e.frag&&!e.frag.decryptdata}function iT(e,t){let i=ip(t);return e.default[`${i?"timeout":"error"}Retry`]}function iE(e,t){return Math.min(("linear"===e.backoff?1:Math.pow(2,t))*e.retryDelayMs,e.maxRetryDelayMs)}function iS(e){return e9(e9({},e),{errorRetry:null,timeoutRetry:null})}function iL(e,t,i,s){var r;if(!e)return!1;let a=null==s?void 0:s.code,n=t<e.maxNumRetry&&(ik(r=a)||!!r&&(r<400||r>499)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,s,n):n}function ik(e){return 0===e&&!1===navigator.onLine}function iA(e){let t={action:0,flags:0};return e&&(t.resolved=!0),t}var iR="NOT_LOADED",ib="APPENDING",iI="PARTIAL";class i_{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(){let{hls:e}=this;e&&(e.on(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.on(eX.BUFFER_APPENDED,this.onBufferAppended,this),e.on(eX.FRAG_BUFFERED,this.onFragBuffered,this),e.on(eX.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.off(eX.BUFFER_APPENDED,this.onBufferAppended,this),e.off(eX.FRAG_BUFFERED,this.onFragBuffered,this),e.off(eX.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let i=this.activePartLists[t];if(i)for(let t=i.length;t--;){let s=i[t];if(!s)break;if(s.start<=e&&e<=s.end&&s.loaded)return s}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){let{fragments:s}=this,r=Object.keys(s);for(let a=r.length;a--;){let n=s[r[a]];if((null==n?void 0:n.body.type)===t&&(!i||n.buffered)){let t=n.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,i,s,r){this.timeRanges&&(this.timeRanges[e]=t);let a=(null==s?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach(s=>{let n=this.fragments[s];if(!n||a>=n.body.sn)return;if(!n.buffered&&(!n.loaded||r)){n.body.type===i&&this.removeFragment(n.body);return}let l=n.range[e];if(l){if(0===l.time.length)return void this.removeFragment(n.body);l.time.some(e=>{let i=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&this.removeFragment(n.body),i})}})}detectPartialFragments(e){let t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;let i=e.frag,s=iD(i),r=this.fragments[s];if(!r||r.buffered&&i.gap)return;let a=!i.relurl;Object.keys(t).forEach(s=>{let n=i.elementaryStreams[s];if(!n)return;
2let l=t[s],o=a||!0===n.partial;r.range[s]=this.getBufferedTimes(i,e.part,o,l)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,i),iC(r)||this.removeParts(i.sn-1,i.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){let i=this.activePartLists[t];i&&(this.activePartLists[t]=iP(i,t=>t.fragment.sn>=e))}fragBuffered(e,t){let i=iD(e),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,this.bufferedEnd(s,e))}getBufferedTimes(e,t,i,s){let r={time:[],partial:i},a=e.start,n=e.end,l=e.minEndPTS||n,o=e.maxStartPTS||a;for(let e=0;e<s.length;e++){let t=s.start(e)-this.bufferPadding,i=s.end(e)+this.bufferPadding;if(o>=t&&l<=i){r.time.push({startPTS:Math.max(a,s.start(e)),endPTS:Math.min(n,s.end(e))});break}if(a<i&&n>t){let t=Math.max(a,s.start(e)),i=Math.min(n,s.end(e));i>t&&(r.partial=!0,r.time.push({startPTS:t,endPTS:i}))}else if(n<=t)break}return r}getPartialFragment(e){let t,i,s,r=null,a=0,{bufferPadding:n,fragments:l}=this;return Object.keys(l).forEach(o=>{let d=l[o];d&&iC(d)&&(i=d.body.start-n,s=d.body.end+n,e>=i&&e<=s&&a<=(t=Math.min(e-i,s-e))&&(r=d.body,a=t))}),r}isEndListAppended(e){let t=this.endListFragments[e];return void 0!==t&&(t.buffered||iC(t))}getState(e){let t=iD(e),i=this.fragments[t];if(i)if(!i.buffered)return ib;else if(iC(i))return iI;else return"OK";return iR}isTimeBuffered(e,t,i){let s,r;for(let a=0;a<i.length;a++){if(s=i.start(a)-this.bufferPadding,r=i.end(a)+this.bufferPadding,e>=s&&t<=r)return!0;if(t<=s)break}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;let i=t.frag,s=t.part?null:t,r=iD(i);this.fragments[r]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:i,part:s,timeRanges:r,type:a}=t;if("initSegment"===i.sn)return;let n=i.type;if(s){let e=this.activePartLists[n];e||(this.activePartLists[n]=e=[]),e.push(s)}this.timeRanges=r;let l=r[a];this.detectEvictedFragments(a,l,n,s)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=iD(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let s=i.length;s--;){let r=t[i[s]];if((null==r?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!!(null!=(t=this.activePartLists[e])&&t.length)}removeFragmentsInRange(e,t,i,s,r){(!s||this.hasGaps)&&Object.keys(this.fragments).forEach(a=>{let n=this.fragments[a];if(!n)return;let l=n.body;l.type===i&&(!s||l.gap)&&l.start<t&&l.end>e&&(n.buffered||r)&&this.removeFragment(l)})}removeFragment(e){let t=iD(e);e.clearElementaryStreamInfo();let i=this.activePartLists[e.type];if(i){let t=e.sn;this.activePartLists[e.type]=iP(i,e=>e.fragment.sn!==t)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(e=>e.clearElementaryStreamInfo())}}function iC(e){var t,i,s;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(i=e.range.audio)&&i.partial||null!=(s=e.range.audiovideo)&&s.partial)}function iD(e){return`${e.type}_${e.level}_${e.sn}`}function iP(e,t){return e.filter(e=>{let i=t(e);return i||e.clearElementaryStreamInfo(),i})}class ix{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 0:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case 1:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class iF{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){let t=new DataView(e),i=new Uint32Array(4);for(let e=0;e<4;e++)i[e]=t.getUint32(4*e);return i}initTable(){let e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],r=i[1],a=i[2],n=i[3],l=this.invSubMix,o=l[0],d=l[1],h=l[2],u=l[3],c=new Uint32Array(256),f=0,g=0,m=0;for(m=0;m<256;m++)m<128?c[m]=m<<1:c[m]=m<<1^283;for(m=0;m<256;m++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,e[f]=i,t[i]=f;let l=c[f],m=c[l],p=c[m],y=257*c[i]^0x1010100*i;s[f]=y<<24|y>>>8,r[f]=y<<16|y>>>16,a[f]=y<<8|y>>>24,n[f]=y,y=0x1010101*p^65537*m^257*l^0x1010100*f,o[i]=y<<24|y>>>8,d[i]=y<<16|y>>>16,h[i]=y<<8|y>>>24,u[i]=y,f?(f=l^c[c[c[p^l]]],g^=c[c[g]]):f=g=1}}expandKey(e){let t,i,s,r,a=this.uint8ArrayToUint32Array_(e),n=!0,l=0;for(;l<a.length&&n;)n=a[l]===this.key[l],l++;if(n)return;this.key=a;let o=this.keySize=a.length;if(4!==o&&6!==o&&8!==o)throw Error("Invalid aes key size="+o);let d=this.ksRows=(o+6+1)*4,h=this.keySchedule=new Uint32Array(d),u=this.invKeySchedule=new Uint32Array(d),c=this.sBox,f=this.rcon,g=this.invSubMix,m=g[0],p=g[1],y=g[2],v=g[3];for(t=0;t<d;
2t++){if(t<o){s=h[t]=a[t];continue}r=s,t%o==0?r=(c[(r=r<<8|r>>>24)>>>24]<<24|c[r>>>16&255]<<16|c[r>>>8&255]<<8|c[255&r])^f[t/o|0]<<24:o>6&&t%o==4&&(r=c[r>>>24]<<24|c[r>>>16&255]<<16|c[r>>>8&255]<<8|c[255&r]),h[t]=s=(h[t-o]^r)>>>0}for(i=0;i<d;i++)t=d-i,r=3&i?h[t]:h[t-4],i<4||t<=4?u[i]=r:u[i]=m[c[r>>>24]]^p[c[r>>>16&255]]^y[c[r>>>8&255]]^v[c[255&r]],u[i]=u[i]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(0xff0000&e)>>8|e>>>24}decrypt(e,t,i){let s,r,a,n,l,o,d,h,u,c,f,g,m,p,y=this.keySize+6,v=this.invKeySchedule,T=this.invSBox,E=this.invSubMix,S=E[0],L=E[1],k=E[2],A=E[3],R=this.uint8ArrayToUint32Array_(i),b=R[0],I=R[1],_=R[2],C=R[3],D=new Int32Array(e),P=new Int32Array(D.length),x=this.networkToHostOrderSwap;for(;t<D.length;){for(u=x(D[t]),c=x(D[t+1]),f=x(D[t+2]),g=x(D[t+3]),l=u^v[0],o=g^v[1],d=f^v[2],h=c^v[3],m=4,p=1;p<y;p++)s=S[l>>>24]^L[o>>16&255]^k[d>>8&255]^A[255&h]^v[m],r=S[o>>>24]^L[d>>16&255]^k[h>>8&255]^A[255&l]^v[m+1],a=S[d>>>24]^L[h>>16&255]^k[l>>8&255]^A[255&o]^v[m+2],n=S[h>>>24]^L[l>>16&255]^k[o>>8&255]^A[255&d]^v[m+3],l=s,o=r,d=a,h=n,m+=4;s=T[l>>>24]<<24^T[o>>16&255]<<16^T[d>>8&255]<<8^T[255&h]^v[m],r=T[o>>>24]<<24^T[d>>16&255]<<16^T[h>>8&255]<<8^T[255&l]^v[m+1],a=T[d>>>24]<<24^T[h>>16&255]<<16^T[l>>8&255]<<8^T[255&o]^v[m+2],n=T[h>>>24]<<24^T[l>>16&255]<<16^T[o>>8&255]<<8^T[255&d]^v[m+3],P[t]=x(s^b),P[t+1]=x(n^I),P[t+2]=x(a^_),P[t+3]=x(r^C),b=u,I=c,_=f,C=g,t+=4}return P.buffer}}class iw{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){let e=function(e){switch(e){case 0:return"AES-CBC";case 1:return"AES-CTR";default:throw Error(`[FastAESKey] invalid aes mode ${e}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}class iM{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let i=new Uint8Array(e);if(this.reset(),this.removePKCS7Padding){let e,t;return(t=(e=i.byteLength)&&new DataView(i.buffer).getUint8(e-1))?i.slice(0,e-t):i}return i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,s){return this.useSoftware?new Promise((r,a)=>{let n=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(n,t,i,s);let l=this.flush();l?r(l.buffer):a(Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,s)}softwareDecrypt(e,t,i,s){let{currentIV:r,currentResult:a,remainderData:n}=this;if(0!==s||16!==t.byteLength)return tr.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),n&&(e=tM(n,e),this.remainderData=null);let l=this.getValidChunk(e);if(!l.length)return null;r&&(i=r);let o=this.softwareDecrypter;return(o||(o=this.softwareDecrypter=new iF),o.expandKey(t),this.currentResult=o.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,a)?a: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 iw(this.subtle,t,s)}return this.fastAesKey.expandKey().then(t=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new ix(this.subtle,new Uint8Array(i),s).decrypt(e.buffer,t)):Promise.reject(Error("web crypto not initialized"))).catch(r=>(tr.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i,s)))}
2onWebCryptoError(e,t,i,s){let r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,s);let r=this.flush();if(r)return r.buffer}throw Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,i=e.length-e.length%16;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(tr.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}class iO{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){let i=e.url;if(!i)return Promise.reject(new iU({type:eq.NETWORK_ERROR,details:ez.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();let s=this.config,r=s.fLoader,a=s.loader;return new Promise((n,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(e=>"GAP"===e[0]))return void l(iB(e));else e.gap=!1;let o=this.loader=r?new r(s):new a(s),d=iN(e);e.loader=o;let h=iS(s.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:131072};e.stats=o.stats;let c={onSuccess:(t,i,s,r)=>{this.resetLoader(e,o);let a=t.data;s.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),n({frag:e,part:null,payload:a,networkDetails:r})},onError:(t,s,r,a)=>{this.resetLoader(e,o),l(new iU({type:eq.NETWORK_ERROR,details:ez.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:e9({url:i,data:void 0},t),error:Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:r,stats:a}))},onAbort:(t,i,s)=>{this.resetLoader(e,o),l(new iU({type:eq.NETWORK_ERROR,details:ez.INTERNAL_ABORTED,fatal:!1,frag:e,error:Error("Aborted"),networkDetails:s,stats:t}))},onTimeout:(t,i,s)=>{this.resetLoader(e,o),l(new iU({type:eq.NETWORK_ERROR,details:ez.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:Error(`Timeout after ${u.timeout}ms`),networkDetails:s,stats:t}))}};t&&(c.onProgress=(i,s,r,a)=>t({frag:e,part:null,payload:r,networkDetails:a})),o.load(d,u,c)})}loadPart(e,t,i){this.abort();let s=this.config,r=s.fLoader,a=s.loader;return new Promise((n,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void l(iB(e,t));let o=this.loader=r?new r(s):new a(s),d=iN(e,t);e.loader=o;let h=iS(s.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:131072};t.stats=o.stats,o.load(d,u,{onSuccess:(s,r,a,l)=>{this.resetLoader(e,o),this.updateStatsFromPart(e,t);let d={frag:e,part:t,payload:s.data,networkDetails:l};i(d),n(d)},onError:(i,s,r,a)=>{this.resetLoader(e,o),l(new iU({type:eq.NETWORK_ERROR,details:ez.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:e9({url:d.url,data:void 0},i),error:Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:r,stats:a}))},onAbort:(i,s,r)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,o),l(new iU({type:eq.NETWORK_ERROR,details:ez.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:Error("Aborted"),networkDetails:r,stats:i}))},onTimeout:(i,s,r)=>{this.resetLoader(e,o),l(new iU({type:eq.NETWORK_ERROR,details:ez.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:Error(`Timeout after ${u.timeout}ms`),networkDetails:r,stats:i}))}})})}updateStatsFromPart(e,t){let i=e.stats,s=t.stats,r=s.total;if(i.loaded+=s.loaded,r){let s=Math.round(e.duration/t.duration),a=Math.min(Math.round(i.loaded/r),s),n=(s-a)*Math.round(i.loaded/a);i.total=i.loaded+n}else i.total=Math.max(i.loaded,i.total);let a=i.loading,n=s.loading;a.start?a.first+=n.first-n.start:(a.start=n.start,a.first=n.first),a.end=n.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function iN(e,t=null){let i=t||e,s={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},r=i.byteRangeStartOffset,a=i.byteRangeEndOffset;if(eV(r)&&eV(a)){var n,l;let t=r,i=a;if("initSegment"===e.sn&&("AES-128"===(l=null==(n=e.decryptdata)?void 0:n.method)||"AES-256"===l)){let e=a-r;e%16&&(i=a+(16-e%16)),0!==r&&(s.resetIV=!0,t=r-16)}s.rangeStart=t,s.rangeEnd=i}return s}function iB(e,t){let i=Error(`GAP ${e.gap?"tag":"attribute"} found`),s={type:eq.MEDIA_ERROR,details:ez.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(s.part=t),(t||e).stats.aborted=!0,new iU(s)}
2class iU extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class i$ extends e7{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&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class iK{constructor(e,t,i,s=0,r=-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=iG(),this.buffering={audio:iG(),video:iG(),audiovideo:iG()},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=r,this.partial=a}}function iG(){return{start:0,executeStart:0,executeEnd:0,end:0}}let ij={length:0,start:()=>0,end:()=>0};class iH{static isBuffered(e,t){if(e){let i=iH.getBuffered(e);for(let e=i.length;e--;)if(t>=i.start(e)&&t<=i.end(e))return!0}return!1}static bufferedRanges(e){if(e){let t=iH.getBuffered(e);return iH.timeRangesToArray(t)}return[]}static timeRangesToArray(e){let t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){let s=iH.bufferedRanges(e);if(s.length)return iH.bufferedInfo(s,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){let s;t=Math.max(0,t),e.length>1&&e.sort((e,t)=>e.start-t.start||t.end-e.end);let r=-1,a=[];if(i)for(let s=0;s<e.length;s++){t>=e[s].start&&t<=e[s].end&&(r=s);let n=a.length;if(n){let t=a[n-1].end;e[s].start-t<i?e[s].end>t&&(a[n-1].end=e[s].end):a.push(e[s])}else a.push(e[s])}else a=e;let n=0,l=t,o=t;for(let e=0;e<a.length;e++){let d=a[e].start,h=a[e].end;if(-1===r&&t>=d&&t<=h&&(r=e),t+i>=d&&t<h)l=d,n=(o=h)-t;else if(t+i<d){s=d;break}}return{len:n,start:l||0,end:o||0,nextStart:s,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||ij}catch(e){return tr.log("failed to get media.buffered",e),ij}}}let iV=/\{\$([a-zA-Z0-9-_]+)\}/g;function iW(e,t){if(null!==e.variableList||e.hasVariableRefs){let i=e.variableList;return t.replace(iV,t=>{let s=t.substring(2,t.length-1),r=null==i?void 0:i[s];return void 0===r?(e.playlistParsingError||(e.playlistParsingError=Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),t):r})}return t}function iY(e,t,i){let s,r,a=e.variableList;if(a||(e.variableList=a={}),"QUERYPARAM"in t){s=t.QUERYPARAM;try{let e=new self.URL(i).searchParams;if(e.has(s))r=e.get(s);else throw Error(`"${s}" does not match any query parameter in URI: "${i}"`)}catch(t){e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else s=t.NAME,r=t.VALUE;s in a?e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):a[s]=r||""}let iq=/^(\d+)x(\d+)$/,iz=/(.+?)=(".*?"|.*?)(?:,|$)/g;class iX{constructor(e,t){"string"==typeof e&&(e=iX.parseAttrList(e,t)),e8(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>"X-"===e.substring(0,2))}decimalInteger(e){let 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),i=new Uint8Array((t=(1&t.length?"0":"")+t).length/2);for(let e=0;e<t.length/2;e++)i[e]=parseInt(t.slice(2*e,2*e+2),16);return i}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((e,t)=>
2(e[t.toLowerCase()]=!0,e),t)}bool(e){return"YES"===this[e]}decimalResolution(e){let t=iq.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i,s={};for(iz.lastIndex=0;null!==(i=iz.exec(e));){let r=i[1].trim(),a=i[2],n=0===a.indexOf('"')&&a.lastIndexOf('"')===a.length-1,l=!1;if(n)a=a.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(n||l))a=iW(t,a);else if(!l&&!n)switch(r){case"CLOSED-CAPTIONS":if("NONE"===a)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":tr.warn(`${e}: attribute ${r} is missing quotes`)}s[r]=a}return s}}class iQ{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=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(s=null==t?void 0:t.tagOrder)?s:i,t){const i=t.attr;for(const t in i)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==i[t]){tr.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=e8(new iX({}),i,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 e=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);eV(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){let{tagAnchor:e}=this;return null===e||null===e.programDateTime?(tr.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(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if(eV(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"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&eV(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}class iZ{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.drift
2StartTime=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}let 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||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return!!this.fragments.length&&eV(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(-1!==t){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function iJ(e,t){return e.length===t.length&&!e.some((e,i)=>e!==t[i])}function i0(e,t){return!e&&!t||!!e&&!!t&&iJ(e,t)}function i1(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function i2(e){switch(e){case"AES-128":case"AES-256":return 0;case"AES-256-CTR":return 1;default:throw Error(`invalid full segment method ${e}`)}}function i3(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function i4(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function i5(e){let t=function(e,t,i){let s=e[t];e[t]=e[i],e[i]=s};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function i8(e){let t=e.split(":"),i=null;if("data"===t[0]&&2===t.length){let e=t[1].split(";"),s=e[e.length-1].split(",");if(2===s.length){let t="base64"===s[0],r=s[1];if(t)e.splice(-1,1),i=i3(r);else{let e,t;e=i4(r).subarray(0,16),(t=new Uint8Array(16)).set(e,16-e.length),i=t}}}return i}let i6="u">typeof self?self:void 0;var i9="org.w3.clearkey",i7="com.apple.fps",se="com.microsoft.playready",st="com.widevine.alpha",si="org.w3.clearkey",ss="com.apple.streamingkeydelivery",sr="com.microsoft.playready",sa="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function sn(e){switch(e){case ss:return i7;case sr:return se;case sa:return st;case si:return i9}}function sl(e){switch(e){case i7:return ss;case se:return sr;case st:return sa;case i9:return si}
2}function so(e){let{drmSystems:t,widevineLicenseUrl:i}=e,s=t?[i7,st,se,i9].filter(e=>!!t[e]):[];return!s[st]&&i&&s.push(st),s}let sd=null!=i6&&null!=(f=i6.navigator)&&f.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function sh(e){let t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),s=i.substring(i.indexOf("<"),i.length),r=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(r){let e=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(e){let t=i3(e).subarray(0,16);return i5(t),t}}return null}let su={};class sc{static clearKeyUriToKeyIdMap(){su={}}static setKeyIdForUri(e,t){su[e]=t}static addKeyIdForUri(e){let t=Object.keys(su).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),su[e]=i,i}constructor(e,t,i,s=[1],r=null,a){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=r,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!i1(e),null!=a&&a.startsWith("0x")&&(this.keyId=new Uint8Array(td(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&iJ(e.keyFormatVersions,this.keyFormatVersions)&&i0(e.iv,this.iv)&&i0(e.keyId,this.keyId)}isSupported(){if(this.method){if(i1(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case ss:case sa:case sr:case si:return -1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e,t){var i,s;if(!this.encrypted||!this.uri)return null;if(i1(this.method)){let t=this.iv;return t||("number"!=typeof e&&(tr.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),t=function(e){let t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(e)),new sc(this.method,this.uri,"identity",this.keyFormatVersions,t)}if(this.keyId){let e=su[this.uri];if(e&&!iJ(this.keyId,e)&&sc.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let r=i8(this.uri);if(r)switch(this.keyFormat){case sa:if(this.pssh=r,!this.keyId){let e=function(e){let t=[];if(e instanceof ArrayBuffer){let i=e.byteLength,s=0;for(;s+32<i;){let i=function(e){let t=e.getUint32(0),i=e.byteOffset,s=e.byteLength;if(s<t)return{offset:i,size:s};if(0x70737368!==e.getUint32(4))return{offset:i,size:t};let r=e.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:i,size:t};let a=e.buffer,n=to(new Uint8Array(a,i+12,16)),l=null,o=0;if(0===r)o=28;else{let r=e.getUint32(28);if(!r||s<32+16*r)return{offset:i,size:t};l=[];for(let e=0;e<r;e++)l.push(new Uint8Array(a,i+32+16*e,16));o=32+16*r}if(!o)return{offset:i,size:t};let d=e.getUint32(o);return t-32<d?{offset:i,size:t}:{version:r,systemId:n,kids:l,data:new Uint8Array(a,i+o+4,d),offset:i,size:t}}(new DataView(e,s));t.push(i),s+=i.size}}return t}(r.buffer);if(e.length){let t=e[0];this.keyId=null!=(i=t.kids)&&i.length?t.kids[0]:null}}this.keyId||(this.keyId=sf(t));break;case sr:{let e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=function(e,t){let i,s;if(16!==e.byteLength)throw RangeError("Invalid system id");i=new Uint8Array,s=new Uint8Array;let r=new Uint8Array(4);return t.byteLength>0&&new DataView(r.buffer).setUint32(0,t.byteLength,!1),function(e,...t){let i=t.length,s=8,r=i;for(;r--;)s+=t[r].byteLength;let a=new Uint8Array(s);for(a[0]=s>>24&255,a[1]=s>>16&255,a[2]=s>>8&255,a[3]=255&s,a.set(e,4),r=0,s=8;r<i;r++)a.set(t[r],s),s+=t[r].byteLength;return a}([112,115,115,104],new Uint8Array([0,0,0,0]),e,s,i,r,t)}(e,r),this.keyId=sh(r);break}default:{let e=r.subarray(0,16);if(16!==e.length){let t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e}}if(!this.keyId||16!==this.keyId.byteLength){let e,i;!(e=(i=null==(s=t)?void 0:s[sa])?i.keyId:null)&&((e=sf(t))||(e=su[this.uri])),e&&(this.keyId=e,sc.setKeyIdForUri(this.uri,e))}return this}}function sf(e){let t=null==e?void 0:e[sr];if(t){let e=i8(t.uri);if(e)return sh(e)}return null}let sg=/#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,sm=/#EXT-X-MEDIA:(.*)/g,sp=/^#EXT(?:INF|-X-TARGETDURATION):/m,sy=RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),sv=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 sT{static findGroup(e,t){for(let i=0;i<e.length;i++){let s=e[i];if(s.id===t)return s}}static resolve(e,t){return tu.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return sp.test(e)}static parseMasterPlaylist(e,t){var i;let s,r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:iV.test(e)},a=[];if(sg.lastIndex=0,!e.startsWith("#EXTM3U"))return r.playlistParsingError=Error("no EXTM3U delimiter"),r;for(;null!=(s=sg.exec(e));)if(s[1]){let e=new iX(s[1],r),n=iW(r,s[2]),l={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:sT.resolve(n,t)},o=e.decimalResolution("RESOLUTION");o&&(l.width=o.width,l.height=o.height),sk(e.CODECS,l);let d=e["SUPPLEMENTAL-CODECS"];d&&(l.supplemental={},sk(d,l.supplemental)),null!=(i=l.unknownCodecs)&&i.length||a.push(l),r.levels.push(l)}else if(s[3]){let e=s[3],i=s[4];switch(e){case"SESSION-DATA":{let e=new iX(i,r),t=e["DATA-ID"];t&&(null===r.sessionData&&(r.sessionData={}),r.sessionData[t]=e);break}case"SESSION-KEY":{let e=sS(i,t,r);e.encrypted&&e.isSupported()?(null===r.sessionKeys&&(r.sessionKeys=[]),r.sessionKeys.push(e)):tr.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${i}"`);break}case"DEFINE":{let e=new iX(i,r);iY(r,e,t)}break;case"CONTENT-STEERING":{let e=new iX(i,r);r.contentSteering={uri:sT.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":r.startTimeOffset=sL(i)}}let n=a.length>0&&a.length<r.levels.length;return r.levels=n?a:r.levels,0===r.levels.length&&(r.playlistParsingError=Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,i){let s,r={},a=i.levels,n={AUDIO:a.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:a.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(sm.lastIndex=0;null!==(s=sm.exec(e));){let e=new iX(s[1],i),a=e.TYPE;if(a){let i=n[a],s=r[a]||[];r[a]=s;let o=e.LANGUAGE,d=e["ASSOC-LANGUAGE"],h=e.CHANNELS,u=e.CHARACTERISTICS,c=e["INSTREAM-ID"],f={attrs:e,bitrate:0,id:l++,groupId:e["GROUP-ID"]||"",name:e.NAME||o||"",type:a,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:o,url:e.URI?sT.resolve(e.URI,t):""};if(d&&(f.assocLang=d),h&&(f.channels=h),u&&(f.characteristics=u),c&&(f.instreamId=c),null!=i&&i.length){let e=sT.findGroup(i,f.groupId)||i[0];sA(f,e,"audioCodec"),sA(f,e,"textCodec")}s.push(f)}}return r}static parseLevelPlaylist(e,t,i,s,r,a){var n;let l,o,d,h,u={url:t},c=new iZ(t),f=c.fragments,g=[],m=null,p=0,y=0,v=0,T=0,E=0,S=null,L=new tv(s,u),k=-1,A=!1,R=null;if(sy.lastIndex=0,c.m3u8=e,c.hasVariableRefs=iV.test(e),(null==(n=sy.exec(e))?void 0:n[0])!=="#EXTM3U")return c.playlistParsingError=Error("Missing format identifier #EXTM3U"),c;for(;null!==(l=sy.exec(e));){A&&(A=!1,(L=new tv(s,u)).playlistOffset=v,L.setStart(v),L.sn=p,L.cc=T,E&&(L.bitrate=E),L.level=i,m&&(L.initSegment=m,m.rawProgramDateTime&&(L.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),R&&(L.setByteRange(R),R=null)));let e=l[1];if(e){L.duration=parseFloat(e);let t=(" "+l[2]).slice(1);L.title=t||null,L.tagList.push(t?["INF",e,t]:["INF",e])}else if(l[3]){if(eV(L.duration)){L.playlistOffset=v,L.setStart(v),d&&sI(L,d,c),L.sn=p,L.level=i,L.cc=T,f.push(L);let e=(" "+l[3]).slice(1);L.relurl=iW(c,e),sR(L,S,g),S=L,v+=L.duration,p++,y=0,A=!0}}
2else{if(!(l=l[0].match(sv))){tr.warn("No matches on slow regex match for level playlist!");continue}for(o=1;o<l.length&&void 0===l[o];o++);let e=(" "+l[o]).slice(1),r=(" "+l[o+1]).slice(1),n=l[o+2]?(" "+l[o+2]).slice(1):null;switch(e){case"BYTERANGE":S?L.setByteRange(r,S):L.setByteRange(r);break;case"PROGRAM-DATE-TIME":L.rawProgramDateTime=r,L.tagList.push(["PROGRAM-DATE-TIME",r]),-1===k&&(k=f.length);break;case"PLAYLIST-TYPE":c.type&&s_(c,e,l),c.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==c.startSN?s_(c,e,l):f.length>0&&sC(c,e,l),p=c.startSN=parseInt(r);break;case"SKIP":{c.skippedSegments&&s_(c,e,l);let t=new iX(r,c),i=t.decimalInteger("SKIPPED-SEGMENTS");if(eV(i)){c.skippedSegments+=i;for(let e=i;e--;)f.push(null);p+=i}let s=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(c.recentlyRemovedDateranges=(c.recentlyRemovedDateranges||[]).concat(s.split("	")));break}case"TARGETDURATION":0!==c.targetduration&&s_(c,e,l),c.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==c.version&&s_(c,e,l),c.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":c.live||s_(c,e,l),c.live=!1;break;case"#":(r||n)&&L.tagList.push(n?[r,n]:[r]);break;case"DISCONTINUITY":T++,L.tagList.push(["DIS"]);break;case"GAP":L.gap=!0,L.tagList.push([e]);break;case"BITRATE":L.tagList.push([e,r]),eV(E=1e3*parseInt(r))?L.bitrate=E:E=0;break;case"DATERANGE":{let e=new iX(r,c),t=new iQ(e,c.dateRanges[e.ID],c.dateRangeTagCount);c.dateRangeTagCount++,t.isValid||c.skippedSegments?c.dateRanges[t.id]=t:tr.warn(`Ignoring invalid DATERANGE tag: "${r}"`),L.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{let e=new iX(r,c);"IMPORT"in e?function(e,t,i){let s=t.IMPORT;if(i&&s in i){let t=e.variableList;t||(e.variableList=t={}),t[s]=i[s]}else e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}(c,e,a):iY(c,e,t)}break;case"DISCONTINUITY-SEQUENCE":0!==c.startCC?s_(c,e,l):f.length>0&&sC(c,e,l),c.startCC=T=parseInt(r);break;case"KEY":{let e=sS(r,t,c);if(e.isSupported()){if("NONE"===e.method){d=void 0;break}d||(d={});let t=d[e.keyFormat];null!=t&&t.matches(e)||(t&&(d=e8({},d)),d[e.keyFormat]=e)}else tr.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}"`);break}case"START":c.startTimeOffset=sL(r);break;case"MAP":{let e=new iX(r,c);if(L.duration){let t=new tv(s,u);sb(t,e,i,d),m=t,L.initSegment=m,m.rawProgramDateTime&&!L.rawProgramDateTime&&(L.rawProgramDateTime=m.rawProgramDateTime)}else{let t=L.byteRangeEndOffset;if(t){let e=L.byteRangeStartOffset;R=`${t-e}@${e}`}else R=null;sb(L,e,i,d),m=L,A=!0}m.cc=T;break}case"SERVER-CONTROL":h&&s_(c,e,l),c.canBlockReload=(h=new iX(r)).bool("CAN-BLOCK-RELOAD"),c.canSkipUntil=h.optionalFloat("CAN-SKIP-UNTIL",0),c.canSkipDateRanges=c.canSkipUntil>0&&h.bool("CAN-SKIP-DATERANGES"),c.partHoldBack=h.optionalFloat("PART-HOLD-BACK",0),c.holdBack=h.optionalFloat("HOLD-BACK",0);break;case"PART-INF":c.partTarget&&s_(c,e,l),c.partTarget=new iX(r).decimalFloatingPoint("PART-TARGET");break;case"PART":{let e=c.partList;e||(e=c.partList=[]);let t=y>0?e[e.length-1]:void 0,i=y++,s=new tT(new iX(r,c),L,u,i,t);e.push(s),L.duration+=s.duration;break}case"PRELOAD-HINT":{let e=new iX(r,c);c.preloadHint=e;break}case"RENDITION-REPORT":{let e=new iX(r,c);c.renditionReports=c.renditionReports||[],c.renditionReports.push(e);break}default:tr.warn(`line parsed but not handled: ${l}`)}}}S&&!S.relurl?(f.pop(),v-=S.duration,c.partList&&(c.fragmentHint=S)):c.partList&&(sR(L,S,g),L.cc=T,c.fragmentHint=L,d&&sI(L,d,c)),c.targetduration||(c.playlistParsingError=Error("Missing Target Duration"));let b=f.length,I=f[0],_=f[b-1];if((v+=c.skippedSegments*c.targetduration)>0&&b&&_){c.averagetargetduration=v/b;let e=_.sn;c.endSN="initSegment"!==e?e:0,c.live||(_.endList=!0),k>0&&(function(e,t){let i=e[t];for(let s=t;s--;){let t=e[s];if(!t)return;t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(f,k),I&&g.unshift(I))}return c.fragmentHint&&(v+=c.fragmentHint.duration),c.totalduration=v,g.length&&c.dateRangeTagCount&&I&&sE(g,c),c.endCC=T,c}}function sE(e,t){let i=e.length;if(!i)if(!t.hasProgramDateTime)return;else{let s=t.fragments[t.fragments.length-1];e.push(s),i++}
2let s=e[i-1],r=t.live?1/0:t.totalduration,a=Object.keys(t.dateRanges);for(let l=a.length;l--;){let o=t.dateRanges[a[l]],d=o.startDate.getTime();o.tagAnchor=s.ref;for(let s=i;s--;){var n;if((null==(n=e[s])?void 0:n.sn)<t.startSN)break;let i=function(e,t,i,s,r){let a=i[s];if(a){let l=a.programDateTime;if(t>=l||0===s){var n;if(t<=l+1e3*(((null==(n=i[s+1])?void 0:n.start)||r)-a.start)){let r=i[s].sn-e.startSN;if(r<0)return -1;let a=e.fragments;if(a.length>i.length){let n=(i[s+1]||a[a.length-1]).sn-e.startSN;for(let e=n;e>r;e--){let i=a[e].programDateTime;if(t>=i&&t<i+1e3*a[e].duration)return e}}return r}}}return -1}(t,d,e,s,r);if(-1!==i){o.tagAnchor=t.fragments[i].ref;break}}}}function sS(e,t,i){var s,r;let a=new iX(e,i),n=null!=(s=a.METHOD)?s:"",l=a.URI,o=a.hexadecimalInteger("IV"),d=a.KEYFORMATVERSIONS,h=null!=(r=a.KEYFORMAT)?r:"identity";return l&&a.IV&&!o&&tr.error(`Invalid IV: ${a.IV}`),new sc(n,l?sT.resolve(l,t):"",h,(d||"1").split("/").map(Number).filter(Number.isFinite),o,a.KEYID)}function sL(e){let t=new iX(e).decimalFloatingPoint("TIME-OFFSET");return eV(t)?t:null}function sk(e,t){let i=(e||"").split(/[ ,]+/).filter(e=>e);["video","audio","text"].forEach(e=>{let s=i.filter(t=>tK(t,e));s.length&&(t[`${e}Codec`]=s.map(e=>e.split("/")[0]).join(","),i=i.filter(e=>-1===s.indexOf(e)))}),t.unknownCodecs=i}function sA(e,t,i){let s=t[i];s&&(e[i]=s)}function sR(e,t,i){e.rawProgramDateTime?i.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function sb(e,t,i,s){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",s&&(e.levelkeys=s),e.initSegment=null}function sI(e,t,i){e.levelkeys=t;let{encryptedFragments:s}=i;(!s.length||s[s.length-1].levelkeys!==t)&&Object.keys(t).some(e=>t[e].isCommonEncryption)&&s.push(e)}function s_(e,t,i){e.playlistParsingError=Error(`#EXT-X-${t} must not appear more than once (${i[0]})`)}function sC(e,t,i){e.playlistParsingError=Error(`#EXT-X-${t} must appear before the first Media Segment (${i[0]})`)}function sD(e,t){let i=t.startPTS;if(eV(i)){let s,r=0;t.sn>e.sn?(r=i-e.start,s=e):(r=e.start-i,s=t),s.duration!==r&&s.setDuration(r)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function sP(e,t,i,s,r,a,n){let l;s-i<=0&&(n.warn("Fragment should have a positive duration",t),s=i+t.duration,a=r+t.duration);let o=i,d=s,h=t.startPTS,u=t.endPTS;if(eV(h)){let l=Math.abs(h-i);e&&l>e.totalduration?n.warn(`media timestamps and playlist times differ by ${l}s for level ${t.level} ${e.url}`):eV(t.deltaPTS)?t.deltaPTS=Math.max(l,t.deltaPTS):t.deltaPTS=l,o=Math.max(i,h),i=Math.min(i,h),r=void 0!==t.startDTS?Math.min(r,t.startDTS):r,d=Math.min(s,u),s=Math.max(s,u),a=void 0!==t.endDTS?Math.max(a,t.endDTS):a}let c=i-t.start;0!==t.start&&t.setStart(i),t.setDuration(s-t.start),t.startPTS=i,t.maxStartPTS=o,t.startDTS=r,t.endPTS=s,t.minEndPTS=d,t.endDTS=a;let f=t.sn;if(!e||f<e.startSN||f>e.endSN)return 0;let g=f-e.startSN,m=e.fragments;for(m[g]=t,l=g;l>0;l--)sD(m[l],m[l-1]);for(l=g;l<m.length-1;l++)sD(m[l],m[l+1]);return e.fragmentHint&&sD(m[m.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,c}function sx(e,t,i,s,r){return Error(`${e} ${r.url}
3Playlist starting @${t.startSN}
4${t.m3u8}
5
6Playlist starting @${i.startSN}
7${i.m3u8}`)}function sF(e,t,i=!0){let s=t.startSN+t.skippedSegments-e.startSN,r=e.fragments,a=s>=0,n=0;if(a&&s<r.length)n=r[s].start;else if(a&&t.startSN===e.endSN+1)n=e.fragmentEnd;else if(a&&i)n=e.fragmentStart+s*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;n=e.fragmentStart}sw(t,n)}function sw(e,t){if(t){let i=e.fragments;for(let s=e.skippedSegments;s<i.length;s++)i[s].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function sM(e,t=1/0){let i=1e3*e.targetduration;if(e.updated){let s=e.fragments;if(s.length&&4*i>t){let e=1e3*s[s.length-1].duration;e<i&&(i=e)}}else i/=2;return Math.round(i)}function sO(e,t,i){if(!e)return null;let s=e.fragments[t-e.startSN];return s||(s=e.fragmentHint)&&s.sn===t?s:t<e.startSN&&i&&i.sn===t?i:null}function sN(e,t,i){return e?sB(e.partList,t,i):null}function sB(e,t,i){if(e)for(let s=e.length;s--;
7){let r=e[s];if(r.index===i&&r.fragment.sn===t)return r}return null}function sU(e){e.forEach((e,t)=>{var i;null==(i=e.details)||i.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function s$(e){return e.replace(/\?[^?]*$/,"")}function sK(e,t){for(let s=0,r=e.length;s<r;s++){var i;if((null==(i=e[s])?void 0:i.cc)===t)return e[s]}return null}function sG(e,t){let i=e.start+t;e.startPTS=i,e.setStart(i),e.endPTS=i+e.duration}function sj(e,t){let i=t.fragments;for(let t=0,s=i.length;t<s;t++)sG(i[t],e);t.fragmentHint&&sG(t.fragmentHint,e),t.alignedSliding=!0}function sH(e,t){if((!t||!(e.startCC<t.endCC)||!(e.endCC>t.startCC))&&1)return;let i=Math.min(t.endCC,e.endCC),s=sK(t.fragments,i),r=sK(e.fragments,i);s&&r&&(tr.log(`Aligning playlist at start of dicontinuity sequence ${i}`),sj(s.start-r.start,e))}function sV(e,t){let i,s;if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;let r=e.fragments,a=t.fragments;if(!r.length||!a.length)return;let n=Math.min(t.endCC,e.endCC);t.startCC<n&&e.startCC<n&&(i=sK(a,n),s=sK(r,n)),i&&s||(s=sK(r,(i=a[Math.floor(a.length/2)]).cc)||r[Math.floor(r.length/2)]);let l=i.programDateTime,o=s.programDateTime;l&&o&&sj((o-l)/1e3-(s.start-i.start),e)}function sW(e,t,i){sY(e,t,i),e.addEventListener(t,i)}function sY(e,t,i){e.removeEventListener(t,i)}let sq=function(e){let t="",i=e.length;for(let s=0;s<i;s++)t+=`[${e.start(s).toFixed(3)}-${e.end(s).toFixed(3)}]`;return t},sz="STOPPED",sX="IDLE",sQ="KEY_LOADING",sZ="FRAG_LOADING",sJ="FRAG_LOADING_WAITING_RETRY",s0="WAITING_TRACK",s1="PARSING",s2="PARSED",s3="ENDED",s4="ERROR",s5="WAITING_INIT_PTS",s8="WAITING_LEVEL";class s6 extends i${constructor(e,t,i,s,r){super(s,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=sz,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:e,fragCurrent:t,media:i,mediaBuffer:s,state:r}=this,a=i?i.currentTime:0,n=iH.bufferInfo(s||i,a,e.maxBufferHole),l=!n.len;if(this.log(`Media seeking to ${eV(a)?a.toFixed(3):a}, state: ${r}, ${l?"out of":"in"} buffer`),this.state===s3)this.resetLoadingState();else if(t){let i=e.maxFragLookUpTolerance,s=t.start-i,r=t.start+t.duration+i;if(l||r<n.start||s>n.end){let e=a>r;(a<s||e)&&(e&&t.loader&&(this.log(`Cancelling fragment load for seek (sn: ${t.sn})`),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(i&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),a>this.lastCurrentTime&&(this.lastCurrentTime=a),!this.loadingParts)){let e=Math.max(n.end,a),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${a.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}!this.hls.hasEnoughToStart&&(this.log(`Setting ${l?"startPosition":"nextLoadPosition"} to ${a} for seek without enough to start`),this.nextLoadPosition=a,l&&(this.startPosition=a)),l&&this.state===sX&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new iO(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new iM(e.config)}registerListeners(){let{hls:e}=this;e.on(eX.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(eX.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.on(eX.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(eX.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(eX.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(eX.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.off(eX.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(eX.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===sz)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=sz}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;return -1===t&&e?e:t}get bufferingEnabled(){return this.buffering}
7pauseBuffering(){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;let i=e.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;let r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=iH.bufferedInfo(r,e.start,0));let a=e.nextStart;if(a&&a>s&&a<t.edge||this.media.currentTime<e.start)return!1;let n=t.partList;if(null!=n&&n.length){let e=n[n.length-1];return iH.isBuffered(this.media,e.start+e.duration/2)}let l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;if(e){var t;return(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){let i=this.media=this.mediaBuffer=t.media;sW(i,"seeking",this.onMediaSeeking),sW(i,"ended",this.onMediaEnded);let s=this.config;this.levels&&s.autoStartLoad&&this.state===sz&&this.startLoad(s.startPosition)}onMediaDetaching(e,t){let i=!!t.transferMedia,s=this.media;if(null!==s){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),sY(s,"seeking",this.onMediaSeeking),sY(s,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=sz,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){let s=e=>{let t=e.frag;if(this.fragContextChanged(t)){this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(t);return}t.stats.chunkCount++,this._handleFragmentLoadProgress(e)};this._doFragLoad(e,t,i,s).then(e=>{if(!e)return;let t=this.state,i=e.frag;if(this.fragContextChanged(i)){t!==sZ&&(this.fragCurrent||t!==s1)||(this.fragmentTracker.removeFragment(i),this.state=sX);return}"payload"in e&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level}`),this.hls.trigger(eX.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e)}).catch(t=>{this.state!==sz&&this.state!==s4&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:i}=this;if(i.getState(e)===ib){let t=e.type,s=this.getFwdBufferInfo(this.mediaBuffer,t),r=Math.max(e.duration,s?s.len:this.config.maxBufferLength),a=this.backtrackFragment;(1==(a?e.sn-a.sn:0)||this.reduceMaxBufferLength(r,e.duration))&&i.removeFragment(e)}else(null==(t=this.mediaBuffer)?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)===iI&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let 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){let t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){e-t&&this.hls.trigger(eX.BUFFER_FLUSHING,{startOffset:e,endOffset:t,type:i})}_loadInitSegment(e,t){this._doFragLoad(e,t).then(e=>{let t=null==e?void 0:e.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw Error("init load aborted");return e}).then(e=>{let{hls:t}=this,{frag:i,payload:s}=e,r=i.decryptdata;if(s&&s.byteLength>
70&&null!=r&&r.key&&r.iv&&i1(r.method)){let a=self.performance.now();return this.decrypter.decrypt(new Uint8Array(s),r.key.buffer,r.iv.buffer,i2(r.method)).catch(e=>{throw t.trigger(eX.ERROR,{type:eq.MEDIA_ERROR,details:ez.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e}).then(s=>{let r=self.performance.now();return t.trigger(eX.FRAG_DECRYPTED,{frag:i,payload:s,stats:{tstart:a,tdecrypt:r}}),e.payload=s,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)}).catch(t=>{this.state!==sz&&this.state!==s4&&(this.warn(t),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){let{levels:t}=this;if(!t)throw Error("init load aborted, missing levels");let i=e.frag.stats;this.state!==sz&&(this.state=sX),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()}unhandledEncryptionError(e,t){var i,s;let r=e.tracks;if(r&&!t.encrypted&&(null!=(i=r.audio)&&i.encrypted||null!=(s=r.video)&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let e=this.media,i=Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?"attached mediaKeys: "+e.mediaKeys:"detached"})`);return this.warn(i.message),!!e&&!e.mediaKeys&&(this.hls.trigger(eX.ERROR,{type:eq.KEY_SYSTEM_ERROR,details:ez.KEY_SYSTEM_NO_KEYS,fatal:!1,error:i,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){let 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?sq(iH.getBuffered(i)):"(detached)"})`),ty(e)){var s;if(e.type!==e3){let t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e])){this.state=sX;return}}let t=null==(s=this.levels)?void 0:s[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=sX}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:i,part:s,partsLoaded:r}=e,a=!r||0===r.length||r.some(e=>!e),n=new iK(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!a);t.flush(n)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,s){var r,a;let n;this.fragCurrent=e;let l=t.details;if(!this.levels||!l)throw Error(`frag load aborted, missing level${l?"":" detail"}s`);let o=null;if(e.encrypted&&!(null!=(r=e.decryptdata)&&r.key)){if(this.log(`Loading key for ${e.sn} of [${l.startSN}-${l.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=sQ,this.fragCurrent=e,o=this.keyLoader.load(e).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(eX.KEY_LOADED,e),this.state===sQ&&(this.state=sX),e}),this.hls.trigger(eX.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else!e.encrypted&&(o=this.keyLoader.loadClear(e,l.encryptedFragments,this.startFragRequested))&&this.log("[eme] blocking frag load until media-keys acquired");let d=this.fragPrevious;if(ty(e)&&(!d||e.sn!==d.sn)){let i=this.shouldLoadParts(t.details,e.end);i!==this.loadingParts&&(this.log(`LL-Part loading ${i?"ON":"OFF"} loading sn ${null==d?void 0:d.sn}->${e.sn}`),this.loadingParts=i)}if(i=Math.max(e.start,i||0),this.loadingParts&&ty(e)){let r=l.partList;if(r&&s){i>l.fragmentEnd&&l.fragmentHint&&(e=l.fragmentHint);let a=this.getNextPart(r,e,i);if(a>-1){let n,d=r[a];return(e=this.fragCurrent=d.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${d.index} (${a}/${r.length-1}) of ${this.fragInfo(e,!1,d)}) cc: ${e.cc} [${l.startSN}-${l.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=d.start+d.duration,this.state=sZ,n=o?o.then(i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(e,d,t,s)).catch(e=>this.handleFragLoadError(e)):this.doFragPartsLoad(e,d,t,s).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(eX.FRAG_LOADING,{frag:e,part:d,targetBufferTime:i}),null===this.fragCurrent)?Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING parts")):n}if(!e.url||this.loadedEndOfParts(r,i))return Promise.resolve(null)}}if(ty(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${null==(a=l.partList)?void 0:a.filter(e=>e.loaded).map(e=>`[${e.start}-${e.end}]`)}`),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} ${"["+l.startSN+"-"+l.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),eV(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=sZ;let h=this.config.progressive&&e.type!==e3;return(n=h&&o?o.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,s)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,h?s:void 0),o]).then(([e])=>(!h&&s&&s(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(eX.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent)?Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING")):n}doFragPartsLoad(e,t,i,s){return new Promise((r,a)=>{var n;let l=[],o=null==(n=i.details)?void 0:n.partList,d=t=>{this.fragmentLoader.loadPart(e,t,s).then(s=>{l[t.index]=s;let a=s.part;this.hls.trigger(eX.FRAG_LOADED,s);let n=sN(i.details,e.sn,t.index+1)||sB(o,e.sn,t.index+1);if(!n)return r({frag:e,part:a,partsLoaded:l});d(n)}).catch(a)};d(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===ez.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===eq.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(eX.ERROR,t)}else this.hls.trigger(eX.ERROR,{type:eq.OTHER_ERROR,details:ez.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==s1){this.fragCurrent||this.state===sz||this.state===s4||(this.state=sX);return}let{frag:i,part:s,level:r}=t,a=self.performance.now();i.stats.parsing.end=a,s&&(s.stats.parsing.end=a);let n=this.getLevelDetails(),l=n&&i.sn>n.endSN||this.shouldLoadParts(n,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,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i,s;let r=e.partList[0];if(r.fragment.type===e3)return!1;if(t>=r.end+((null==(i=e.fragmentHint)?void 0:i.duration)||0)&&(this.hls.hasEnoughToStart?(null==(s=this.media)?void 0:s.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:i}=this,{level:s,sn:r,part:a}=e;if(!(null!=t&&t[s]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;let n=t[s],l=n.details,o=a>-1?sN(l,r,a):null,d=o?o.fragment:sO(l,r,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:o,level:n}):null}bufferFragmentData(e,t,i,s,r){if(this.state!==s1)return;let{data1:a,data2:n}=e,l=a;if(n&&(l=tM(a,n)),!l.length)return;let o=this.initPTS[t.cc],d=o?-o.baseTime/o.timescale:void 0,h={type:e.type,frag:t,part:i,chunkMeta:s,offset:d,parent:t.type,data:l};if(this.hls.trigger(eX.BUFFER_APPENDING,h),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!iH.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);let i=t.currentTime,s=iH.bufferInfo(t,i,0),r=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),n=Math.max(Math.min(e.start-a,s.end-a),i+a);e.start-n>a&&this.flushMainBuffer(n,e.start)}getFwdBufferInfo(e,t){var i;let s=this.getLoadPosition();if(!eV(s))return null;let r=this.lastCurrentTime>s||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,r)}getFwdBufferInfoAtPos(e,t,i,s){let r=iH.bufferInfo(e,t,s);if(0===r.len&&void 0!==r.nextStart){let a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(r.nextStart<=a.end||a.gap)){let i=Math.max(Math.min(r.nextStart,a.end)-t,s);return iH.bufferInfo(e,t,i)}}return r}
7getMaxBufferLength(e){let{config:t}=this;return Math.min(e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,i){let s=e.nextStart;if(s&&i.start>s){let s=e.buffered;if(s){let r=e.len,a=e.bufferedIndex;for(let e=s.length-1;e>a;e--)s[e].start<i.start&&(r+=s[e].end-s[e].start);return r>=t}}return!1}reduceMaxBufferLength(e,t){let i=this.config,s=Math.max(Math.min(e-t,i.maxBufferLength),t),r=Math.max(e-3*t,i.maxMaxBufferLength/2,s);return r>=s&&(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(e,t=e1){let i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){let i=t.fragments,s=i.length;if(!s)return null;let{config:r}=this,a=t.fragmentStart,n=r.lowLatencyMode&&!!t.partList,l=null;if(t.live){let i=r.initialLiveManifestSize;if(s<i)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${i})`),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<a){var o;let i,s;n&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(t);let r=this.config.startPosition,d=this.hls.startPosition,h=this.hls.liveSyncPosition,u=(null==(o=l)?void 0:o.start)||0;-1!==d&&d>=a?(i=d,s=d===r?"config":"next load start"):null!==h?(i=h,s="live edge"):(i=e,s="buffer pos"),i<u&&(i=u,s="live frag start"),i<a&&(i=a,s="playlist start"),(this.startPosition!=i||this.nextLoadPosition!=i)&&(this.log(`Setting startPosition to ${i.toFixed(3)} ${-1===d?"":`(from ${r}) `}based on ${s}. live edge: ${h} live frag start: ${u.toFixed(3)} playlist start: ${a.toFixed(3)} buffer pos: ${e}`),this.startPosition=this.nextLoadPosition=i)}}else e<=a&&(l=i[0]);if(!l){let i=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,i,t)}let d=this.filterReplacedPrimary(l,t);if(!d&&l){let e=l.sn-t.startSN;d=this.filterReplacedPrimary(i[e+1]||null,t)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;let i=this.fragmentTracker.getState(e);return"OK"===i||i===iI&&!!e.gap}getNextFragmentLoopLoading(e,t,i,s,r){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t))&&!a.gap&&i.nextStart){let e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(null!==e&&i.len+e.len>=r){let e=a.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(s9(this.config)){var e;if(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(s9(this.config)&&e.type!==e3){let i=this.hls.interstitialsManager,s=null==i?void 0:i.bufferingItem;if(s){let i=s.event;if(i){if(i.appendInPlace||Math.abs(e.start-s.start)>1||0===s.start)return null}else if(e.end<=s.start&&(null==t?void 0:t.live)===!1||e.start>s.end&&s.nextEvent&&(s.nextEvent.appendInPlace||e.start-s.end>1))return null}let r=null==i?void 0:i.playerQueue;if(r)for(let t=r.length;t--;){let i=r[t].interstitial;if(i.appendInPlace&&e.start>=i.startTime&&e.end<=i.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,i){let s=-1,r=!1,a=!0;for(let n=0,l=e.length;n<l;n++){let l=e[n];if(a=a&&!l.independent,s>-1&&i<l.start)break;let o=l.loaded;o?s=-1:(r||(l.independent||a)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${l.start}`),s=n),r=o}return s}loadedEndOfParts(e,t){let i;for(let s=e.length;s--&&(i=e[s]).loaded;)if(t>i.start)return!0;return!1}getInitialLiveFragment(e){let t=e.fragments,i=this.fragPrevious,s=null;if(i){if(e.hasProgramDateTime&&(s=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!eV(t)||t<(e[0].programDateTime||0)||t>=(e[e.length-1].endProgramDateTime||0))return null;for(let s=0;s<e.length;
7++s){let r=e[s];if(function(e,t,i){let s=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-s>e}(t,i,r))return r}return null}(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance))&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),!s){let r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){let a=t[r-e.startSN];i.cc===a.cc&&(s=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}!s&&(s=im(e,i.cc,i.end))&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`)}}else{let t=this.hls.liveSyncPosition;null!==t&&(s=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){let s,{config:r}=this,{fragPrevious:a}=this,{fragments:n,endSN:l}=i,{fragmentHint:o}=i,{maxFragLookUpTolerance:d}=r,h=i.partList,u=!!(this.loadingParts&&null!=h&&h.length&&o);if(u&&!this.bitrateTest&&h[h.length-1].fragment.sn===o.sn&&(n=n.concat(o),l=o.sn),e<t){var c;let i=e<this.lastCurrentTime||e>t-d||null!=(c=this.media)&&c.paused||!this.startFragRequested?0:d;s=ic(a,n,e,i)}else s=n[n.length-1];if(s){let e=s.sn-i.startSN,t=this.fragmentTracker.getState(s);if(("OK"===t||t===iI&&s.gap)&&(a=s),a&&s.sn===a.sn&&(!u||h[0].fragment.sn>s.sn||!i.live)&&s.level===a.level){let t=n[e+1];s=s.sn<l&&"OK"!==this.fragmentTracker.getState(t)?t:null}}return s}alignPlaylists(e,t,i){let s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;let r=e.fragmentStart,a=!t,n=e.alignedSliding&&eV(r);if(a||!n&&!r){i&&(sH(e,i),e.alignedSliding||sV(e,i),e.alignedSliding||e.skippedSegments||sF(i,e,!1));let r=e.fragmentStart;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${s}`),r}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);let s=this.timelineOffset;if(-1===i){let r=null!==this.startTimeOffset,a=r?this.startTimeOffset:e.startTimeOffset;null!==a&&eV(a)?(i=t+a,a<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${r?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+s}this.nextLoadPosition=i+s}getLoadPosition(){var e;let{media:t}=this,i=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&ty(e)&&e.stats.aborted&&(this.log(`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===sJ)||(this.state=sX)}onFragmentOrKeyLoadError(e,t){var i,s,r;if(t.chunkMeta&&!t.frag){let e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}let a=t.frag;if(!a||a.type!==e||!this.levels)return;if(this.fragContextChanged(a))return void this.warn(`Frag load error must match current frag to retry ${a.url} > ${null==(s=this.fragCurrent)?void 0:s.url}`);let n=t.details===ez.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(a,!0);let l=t.errorAction;if(!l){this.state=s4;return}let{action:o,flags:d,retryCount:h=0,retryConfig:u}=l,c=!!u,f=c&&5===o,g=c&&!l.resolved&&1===d,m=null==(i=this.hls.latestLevelDetails)?void 0:i.live;if(!f&&g&&ty(a)&&!a.endList&&m&&!iv(t))this.resetFragmentErrors(e),this.treatAsGap(a),l.resolved=!0;else if((f||g)&&h<u.maxNumRetry){let i=ik(null==(r=t.response)?void 0:r.code),s=iE(u,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+s,this.state=sJ,l.resolved=!0,i){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${a.sn} of ${e} ${a.level} errored with ${t.details}, retrying loading ${h+1}/${u.maxNumRetry} in ${s}ms`)}else if(u){if(this.resetFragmentErrors(e),!(h<u.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${h})`);n||3===o||(l.resolved=!0)}else 2===o?this.state=s8:this.state=s4;this.tickImmediate()}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!ik(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=sX)}reduceLengthAndFlushBuffer(e){if(this.state===s1||this.state===s2){let t=e.frag,i=e.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len,(null==t?void 0:t.duration)||10);let a=!r;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===e2&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==sz&&(this.state=sX)}afterBufferFlushed(e,t,i){if(!e)return;let s=iH.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,i),this.state===s3&&this.resetLoadingState()}
7resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==sz&&(this.state=sX)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.levelLastLoaded,t=e?e.details:null;null!=t&&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.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${-1===e.level?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){let r=i.details;if(!r)return void this.warn("level.details undefined");if(!Object.keys(e.elementaryStreams).reduce((t,a)=>{let n=e.elementaryStreams[a];if(n){let l=n.endPTS-n.startPTS;if(l<=0)return this.warn(`Could not parse fragment ${e.sn} ${a} duration reliably (${l})`),t||!1;let o=s?0:sP(r,e,n.startPTS,n.endPTS,n.startDTS,n.endDTS,this);return this.hls.trigger(eX.LEVEL_PTS_UPDATED,{details:r,level:i,drift:
7o,type:a,frag:e,start:n.startPTS,end:n.endPTS}),!0}return t},!1)){var a;let t=(null==(a=this.transmuxer)?void 0:a.error)===null;if((0===i.fragmentError||t&&(i.fragmentError<2||e.endList))&&this.treatAsGap(e,i),t){let t=Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(eX.ERROR,{type:eq.MEDIA_ERROR,details:ez.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=s2,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(eX.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===e1?"level":"track"}fragInfo(e,t=!0,i){var s,r;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${(null!=(s=t&&!i?e.startPTS:(i||e).start)?s:NaN).toFixed(3)}-${(null!=(r=t&&!i?e.endPTS:(i||e).end)?r:NaN).toFixed(3)}]${i&&"main"===e.type?"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;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function s9(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}class s7{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let e,{chunks:t,dataLength:i}=this;return t.length?(e=1===t.length?t[0]:function(e,t){let i=new Uint8Array(t),s=0;for(let t=0;t<e.length;t++){let r=e[t];i.set(r,s),s+=r.length}return i}(t,i),this.reset(),e):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var re={exports:{}},rt=(v||(v=1,!function(e){var t=Object.prototype.hasOwnProperty,i="~";function s(){}function r(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function a(e,t,s,a,n){if("function"!=typeof s)throw TypeError("The listener must be a function");var l=new r(s,a||e,n),o=i?i+t:t;return e._events[o]?e._events[o].fn?e._events[o]=[e._events[o],l]:e._events[o].push(l):(e._events[o]=l,e._eventsCount++),e}function n(e,t){0==--e._eventsCount?e._events=new s:delete e._events[t]}function l(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(i=!1)),l.prototype.eventNames=function(){var e,s,r=[];if(0===this._eventsCount)return r;for(s in e=this._events)t.call(e,s)&&r.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},l.prototype.listeners=function(e){var t=i?i+e:e,s=this._events[t];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,a=s.length,n=Array(a);r<a;r++)n[r]=s[r].fn;return n},l.prototype.listenerCount=function(e){var t=i?i+e:e,s=this._events[t];return s?s.fn?1:s.length:0},l.prototype.emit=function(e,t,s,r,a,n){var l=i?i+e:e;if(!this._events[l])return!1;var o,d,h=this._events[l],u=arguments.length;if(h.fn){switch(h.once&&this.removeListener(e,h.fn,void 0,!0),u){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,t),!0;case 3:return h.fn.call(h.context,t,s),!0;case 4:return h.fn.call(h.context,t,s,r),!0;case 5:return h.fn.call(h.context,t,s,r,a),!0;case 6:return h.fn.call(h.context,t,s,r,a,n),!0}for(d=1,o=Array(u-1);d<u;d++)o[d-1]=arguments[d];h.fn.apply(h.context,o)}else{var c,f=h.length;for(d=0;d<f;d++)switch(h[d].once&&this.removeListener(e,h[d].fn,void 0,!0),u){case 1:h[d].fn.call(h[d].context);break;case 2:h[d].fn.call(h[d].context,t);break;case 3:h[d].fn.call(h[d].context,t,s);break;case 4:h[d].fn.call(h[d].context,t,s,r);break;default:if(!o)for(c=1,o=Array(u-1);c<u;c++)o[c-1]=arguments[c];h[d].fn.apply(h[d].context,o)}}return!0},l.prototype.on=function(e,t,i){return a(this,e,t,i,!1)},l.prototype.once=function(e,t,i){return a(this,e,t,i,!0)},l.prototype.removeListener=function(e,t,s,r){var a=i?i+e:e;if(!this._events[a])return this;if(!t)return n(this,a),this;var l=this._events[a];if(l.fn)l.fn!==t||r&&!l.once||s&&l.context!==s||n(this,a);else{for(var o=0,d=[],h=l.length;o<h;o++)(l[o].fn!==t||r&&!l[o].once||s&&l[o].context!==s)&&d.push(l[o]);d.length?this._events[a]=1===d.length?d[0]:d:n(this,a)}return this},l.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&n(this,t)):(this._events=new s,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=i,l.EventEmitter=l,e.exports=l}(re)),(g=re.exports)&&g.__esModule&&Object.prototype.hasOwnProperty.call(g,"default"))?g.default:g;let ri="1.6.16",rs={};function rr(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128||!1}function ra(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128||!1}function rn(e,t){return(127&e[t])<<21|(127&e[t+1])<<14|(127&e[t+2])<<7|127&e[t+3]}function rl(e,t){let i=t,s=0;for(;ra(e,t);)s+=10,s+=rn(e,t+6),rr(e,t+10)&&(s+=10),t+=s;
7if(s>0)return e.subarray(i,i+s)}function ro(e,t){return 255===e[t]&&(246&e[t+1])==240}function rd(e,t){return 1&e[t+1]?7:9}function rh(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function ru(e,t){return t+1<e.length&&ro(e,t)}function rc(e,t,i,s,r){if(!e.samplerate){let a=function(e,t,i,s){let r=t[i+2],a=r>>2&15;if(a>12){let t=Error(`invalid ADTS sampling index:${a}`);e.emit(eX.ERROR,eX.ERROR,{type:eq.MEDIA_ERROR,details:ez.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message});return}let n=(r>>6&3)+1,l=t[i+3]>>6&3|(1&r)<<2,o="mp4a.40."+n,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],h=a;(5===n||29===n)&&(h-=3);let u=[n<<3|(14&h)>>1,(1&h)<<7|l<<3];return tr.log(`manifest codec:${s}, parsed codec:${o}, channels:${l}, rate:${d} (ADTS object type:${n} sampling index:${a})`),{config:u,samplerate:d,channelCount:l,codec:o,parsedCodec:o,manifestCodec:s}}(t,i,s,r);a&&e8(e,a)}}function rf(e,t,i,s,r){let a,n=s+r*(9216e4/e.samplerate),l=function(e,t){let i=rd(e,t);if(t+i<=e.length){let s=rh(e,t)-i;if(s>0)return{headerLength:i,frameLength:s}}}(t,i);if(l){let{frameLength:s,headerLength:r}=l,o=r+s,d=Math.max(0,i+o-t.length);d?(a=new Uint8Array(o-r)).set(t.subarray(i+r,t.length),0):a=t.subarray(i+r,i+o);let h={unit:a,pts:n};return d||e.samples.push(h),{sample:h,length:o,missing:d}}let o=t.length-i;return(a=new Uint8Array(o)).set(t.subarray(i,t.length),0),{sample:{unit:a,pts:n},length:o,missing:-1}}function rg(e,t=0,i=1/0){var s,r,a,n,l,o;let d,h,u,c,f,g;return s=e,r=t,a=i,n=Uint8Array,d=(l=s)instanceof ArrayBuffer?l:l.buffer,h=1,"BYTES_PER_ELEMENT"in n&&(h=n.BYTES_PER_ELEMENT),c=((u=(o=s)&&o.buffer instanceof ArrayBuffer&&void 0!==o.byteLength&&void 0!==o.byteOffset?s.byteOffset:0)+s.byteLength)/h,g=Math.floor(Math.min((f=Math.floor(Math.max(0,Math.min((u+r)/h,c))))+Math.max(a,0),c)),new n(d,f,g-f)}function rm(e){let t=0,i=[];for(;ra(e,t);){let s=rn(e,t+6);e[t+5]>>6&1&&(t+=10);let r=(t+=10)+s;for(;t+10<r;){let s=function(e){let t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=rn(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}}(e.subarray(t)),r=function(e){if("PRIV"===e.type){if(e.size<2)return;let t=tl(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}if("W"===e.type[0]){if("WXXX"===e.type){if(e.size<2)return;let t=1,i=tl(e.data.subarray(t),!0);t+=i.length+1;let s=tl(e.data.subarray(t));return{key:e.type,info:i,data:s}}let t=tl(e.data);return{key:e.type,info:"",data:t}}if("APIC"===e.type)return function(e){let t,i={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");let s=e.data.subarray(1).indexOf(0);if(-1===s)return;let r=tl(rg(e.data,1,s)),a=e.data[2+s],n=e.data.subarray(3+s).indexOf(0);if(-1===n)return;let l=tl(rg(e.data,3+s,n));if("-->"===r)t=tl(rg(e.data,4+s+n));else{var o;t=(o=e.data.subarray(4+s+n))instanceof ArrayBuffer?o:0==o.byteOffset&&o.byteLength==o.buffer.byteLength?o.buffer:new Uint8Array(o).buffer}return i.mimeType=r,i.pictureType=a,i.description=l,i.data=t,i}(e);if(e.size<2)return;if("TXXX"===e.type){let t=1,i=tl(e.data.subarray(t),!0);t+=i.length+1;let s=tl(e.data.subarray(t));return{key:e.type,info:i,data:s}}let t=tl(e.data.subarray(1));return{key:e.type,info:"",data:t}}(s);r&&i.push(r),t+=s.size+10}rr(e,t)&&(t+=10)}return i}function rp(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function ry(e){let t=rm(e);for(let e=0;e<t.length;e++){let i=t[e];if(rp(i))return function(e){if(8===e.data.byteLength){let t=new Uint8Array(e.data),i=1&t[3],s=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return s/=45,i&&(s+=47721858.84),Math.round(s)}}(i)}}let rv=((m={}).audioId3="org.id3",m.dateRange="com.apple.quicktime.HLS",m.emsg="https://aomedia.org/emsg/ID3",m.misbklv="urn:misb:KLV:bin:1910.1",m);function rT(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class rE{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){let i;this.cachedData&&(e=tM(this.cachedData,e),this.cachedData=null);let s=rl(e,0),r=s?s.length:0,a=this._audioTrack,n=this._id3Track,l=s?ry(s):void 0,o=e.length;for((null===this.basePTS||0===this.frameIndex&&eV(l))&&(this.basePTS=rS(l,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),s&&s.length>0&&n.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:rv.audioId3,duration:1/0});r<o;){if(this.canParse(e,r)){let t=this.appendFrame(a,e,r);t?(this.frameIndex++,this.lastPTS=t.sample.pts,r+=t.length,i=r):r=o}else{var d,h;ra(d=e,h=r)&&rn(d,h+6)+10<=d.length-h?(s=rl(e,r),n.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:rv.audioId3,duration:1/0}),r+=s.length,i=r):r++}if(r===o&&i!==o){let t=e.slice(i);this.cachedData?this.cachedData=tM(this.cachedData,t):this.cachedData=t}}return{audioTrack:a,videoTrack:rT(),id3Track:n,textTrack:rT()}}demuxSampleAes(e,t,i){return Promise.reject(Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:rT(),id3Track:this._id3Track,textTrack:rT()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}let rS=(e,t,i)=>eV(e)?90*e:9e4*t+(i?9e4*i.baseTime/i.timescale:0),rL=null,rk=[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],rA=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],rR=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],rb=[0,1,1,4];function rI(e,t,i,s,r){if(i+24>t.length)return;let a=r_(t,i);if(a&&i+a.frameLength<=t.length){let n=s+r*(9e4*a.samplesPerFrame/a.sampleRate),l={unit:t.subarray(i,i+a.frameLength),pts:n,dts:n};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(l),{sample:l,length:a.frameLength,missing:0}}}function r_(e,t){let i=e[t+1]>>
73&3,s=e[t+1]>>1&3,r=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==i&&0!==r&&15!==r&&3!==a){let n=e[t+2]>>1&1,l=e[t+3]>>6,o=1e3*rk[14*(3===i?3-s:3===s?3:4)+r-1],d=rA[3*(3===i?0:2===i?1:2)+a],h=rR[i][s],u=rb[s],c=Math.floor(h*o/d+n)*u;if(null===rL){let e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);rL=e?parseInt(e[1]):0}return rL&&rL<=87&&2===s&&o>=224e3&&0===l&&(e[t+3]=128|e[t+3]),{sampleRate:d,channelCount:3===l?1:2,frameLength:c,samplesPerFrame:8*h*u}}}function rC(e,t){return 255===e[t]&&(224&e[t+1])==224&&(6&e[t+1])!=0}function rD(e,t){return t+1<e.length&&rC(e,t)}function rP(e,t){if(t+1<e.length&&rC(e,t)){let i=r_(e,t),s=4;null!=i&&i.frameLength&&(s=i.frameLength);let r=t+s;return r===e.length||rD(e,r)}return!1}let rx=(e,t)=>{let i=0,s=5;t+=5;let r=new Uint32Array(1),a=new Uint32Array(1),n=new Uint8Array(1);for(;s>0;){n[0]=e[t];let l=Math.min(s,8),o=8-l;a[0]=0xff000000>>>24+o<<o,r[0]=(n[0]&a[0])>>o,i=i?i<<l|r[0]:r[0],t+=1,s-=l}return i};function rF(e,t,i,s,r){if(i+8>t.length||11!==t[i]||119!==t[i+1])return -1;let a=t[i+4]>>6;if(a>=3)return -1;let n=[48e3,44100,32e3][a],l=63&t[i+4],o=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*l+a];if(i+o>t.length)return -1;let d=t[i+6]>>5,h=0;2===d?h+=2:(1&d&&1!==d&&(h+=2),4&d&&(h+=2));let u=(t[i+6]<<8|t[i+7])>>12-h&1,c=[2,1,2,3,3,4,4,5][d]+u,f=t[i+5]>>3,g=7&t[i+5],m=new Uint8Array([a<<6|f<<1|g>>2,(3&g)<<6|d<<3|u<<2|l>>4,l<<4&224]),p=t.subarray(i,i+o);return e.config=m,e.channelCount=c,e.samplerate=n,e.samples.push({unit:p,pts:s+1536/n*9e4*r}),o}let rw=/\/emsg[-/]ID3/i;function rM(e,t){return eV(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class rO{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new iM(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,0)}decryptAacSample(e,t,i){let s=e[t].unit;if(s.length<=16)return;let r=s.subarray(16,s.length-s.length%16),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).then(r=>{let a=new Uint8Array(r);s.set(a,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=new Int8Array(16*Math.floor((e.length-48)/160)+16),i=0;for(let s=32;s<e.length-16;s+=160,i+=16)t.set(e.subarray(s,s+16),i);return t}getAvcDecryptedUnit(e,t){let i=new Uint8Array(t),s=0;for(let t=32;t<e.length-16;t+=160,s+=16)e.set(i.subarray(s,s+16),t);return e}decryptAvcSample(e,t,i,s,r){let a=tU(r.data),n=this.getAvcEncryptedData(a);this.decryptBuffer(n.buffer).then(n=>{r.data=this.getAvcDecryptedUnit(a,n),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,s)}).catch(s)}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length)return void s();let r=e[t].units;for(;!(i>=r.length);i++){let a=r[i];if(!(a.data.length<=48)&&(1===a.type||5===a.type)&&(this.decryptAvcSample(e,t,i,s,a),!this.decrypter.isSync()))return}}}}class rN{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,s=this.VideoSample;if(s&&0!==s.units.length||(s=e[e.length-1]),null!=(t=s)&&t.units){let e=s.units;i=e[e.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){let i=t.samples,s=i.length;if(!s)return void t.dropped++;{let t=i[s-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,i){let s,r,a,n=t.byteLength,l=e.naluState||0,o=l,d=[],h=0,u=-1,c=0;for(-1===l&&(u=0,c=this.getNALuType(t,0),l=0,h=1);h<n;){if(s=t[h++],!l){l=+!s;continue}if(1===l){l=2*!s;continue}
7if(s)if(1===s){if(r=h-l-1,u>=0){let e={data:t.subarray(u,r),type:c};d.push(e)}else{let i=this.getLastNalUnit(e.samples);i&&(o&&h<=4-o&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-o)),r>0&&(i.data=tM(i.data,t.subarray(0,r)),i.state=0))}h<n?(a=this.getNALuType(t,h),u=h,c=a,l=0):l=-1}else l=0;else l=3}if(u>=0&&l>=0){let e={data:t.subarray(u,n),type:c,state:l};d.push(e)}if(0===d.length){let i=this.getLastNalUnit(e.samples);i&&(i.data=tM(i.data,t))}return e.naluState=l,d}}class rB{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(){let e=this.data,t=this.bytesAvailable,i=e.byteLength-t,s=new Uint8Array(4),r=Math.min(4,t);if(0===r)throw Error("no bytes available");s.set(e.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),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),i=this.word>>>32-t;if(e>32&&tr.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 Error("no bits available");return(t=e-t)>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&0x80000000>>>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(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class rU extends rN{parsePES(e,t,i,s){let r,a=this.parseNALu(e,i.data,s),n=this.VideoSample,l=!1;i.data=null,n&&a.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.forEach(s=>{var a,o,d,h,u;switch(s.type){case 1:{let t=!1;r=!0;let a=s.data;if(l&&a.length>4){let e=this.readSliceType(a);(2===e||4===e||7===e||9===e)&&(t=!0)}t&&null!=(d=n)&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.frame=!0,n.key=t;break}case 5:r=!0,null!=(a=n)&&a.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.key=!0,n.frame=!0;break;case 6:r=!0,tB(s.data,1,i.pts,t.samples);break;case 7:{r=!0,l=!0;let t=s.data,i=this.readSPS(t);if(!e.sps||e.width!==i.width||e.height!==i.height||(null==(h=e.pixelRatio)?void 0:h[0])!==i.pixelRatio[0]||(null==(u=e.pixelRatio)?void 0:u[1])!==i.pixelRatio[1]){e.width=i.width,e.height=i.height,e.pixelRatio=i.pixelRatio,e.sps=[t];let s=t.subarray(1,4),r="avc1.";for(let e=0;e<3;e++){let t=s[e].toString(16);t.length<2&&(t="0"+t),r+=t}e.codec=r}break}case 8:r=!0,e.pps=[s.data];break;case 9:r=!0,e.audFound=!0,null!=(o=n)&&o.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:r=!0;break;default:r=!1}n&&r&&n.units.push(s)}),s&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){let t=new rB(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,s=8;for(let r=0;r<e;r++)0!==s&&(s=(i+t.readEG()+256)%256),i=0===s?i:s}readSPS(e){let t,i,s,r=new rB(e),a=0,n=0,l=0,o=0,d=r.readUByte.bind(r),h=r.readBits.bind(r),u=r.readUEG.bind(r),c=r.readBoolean.bind(r),f=r.skipBits.bind(r),g=r.skipEG.bind(r),m=r.skipUEG.bind(r),p=this.skipScalingList.bind(this);d();let y=d();if(h(5),f(3),d(),m(),100===y||110===y||122===y||244===y||44===y||83===y||86===y||118===y||128===y){let e=u();if(3===e&&f(1),m(),m(),f(1),c())for(i=3!==e?8:12,s=0;s<i;s++)c()&&p(s<6?16:64,r)}m();let v=u();if(0===v)u();else if(1===v)for(f(1),g(),g(),t=u(),s=0;s<t;s++)g();m(),f(1);let T=u(),E=u(),S=h(1);0===S&&f(1),f(1),c()&&(a=u(),n=u(),l=u(),o=u());let L=[1,1];if(c()&&c())switch(d()){case 1:L=[1,1];break;case 2:L=[12,11];break;case 3:L=[10,11];break;case 4:L=[16,11];break;case 5:L=[40,33];break;case 6:L=[24,11];break;case 7:L=[20,11];break;case 8:L=[32,11];break;case 9:L=[80,33];break;case 10:L=[18,11];break;case 11:L=[15,11];break;case 12:L=[64,33];break;case 13:L=[160,99];break;case 14:L=[4,3];break;case 15:L=[3,2];break;case 16:L=[2,1];break;case 255:L=[d()<<8|d(),d()<<8|d()]}return{width:Math.ceil((T+1)*16-2*a-2*n),height:(2-S)*(E+1)*16-(S?2:4)*(l+o),pixelRatio:L}}}class r$ extends rN{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,s){let r,a=this.parseNALu(e,i.data,s),n=this.VideoSample,l=!1;i.data=null,n&&a.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.forEach(s=>{var a,o,d;
7switch(s.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:n||(n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),n.frame=!0,r=!0;break;case 16:case 17:case 18:case 21:r=!0,l&&null!=(d=n)&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.key=!0,n.frame=!0;break;case 19:case 20:r=!0,null!=(a=n)&&a.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.key=!0,n.frame=!0;break;case 39:r=!0,tB(s.data,2,i.pts,t.samples);break;case 32:r=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=e8(e.params,this.readVPS(s.data)),this.initVPS=s.data),e.vps=[s.data];break;case 33:if(r=!0,l=!0,void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],s.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let t=this.readSPS(s.data);for(let i in e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={}),t.params)e.params[i]=t.params[i]}this.pushParameterSet(e.sps,s.data,e.vps),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.key=!0;break;case 34:if(r=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];let t=this.readPPS(s.data);for(let i in t)e.params[i]=t[i]}this.pushParameterSet(e.pps,s.data,e.vps)}break;case 35:r=!0,e.audFound=!0,null!=(o=n)&&o.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:r=!1}n&&r&&n.units.push(s)}),s&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}pushParameterSet(e,t,i){(!i||i[0]!==this.initVPS)&&(i||e.length)||e.push(t)}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),i=0;for(let s=0;s<e.byteLength;s++)(!(s>=2)||3!==e[s]||0!==e[s-1]||0!==e[s-2])&&(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){let t=new rB(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){let t=new rB(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let i=t.readBits(3);t.readBoolean();let s=t.readBits(2),r=t.readBoolean(),a=t.readBits(5),n=t.readUByte(),l=t.readUByte(),o=t.readUByte(),d=t.readUByte(),h=t.readUByte(),u=t.readUByte(),c=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),y=[],v=[];for(let e=0;e<i;e++)y.push(t.readBoolean()),v.push(t.readBoolean());if(i>0)for(let e=i;e<8;e++)t.readBits(2);for(let e=0;e<i;e++)y[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),v[e]&&t.readUByte();t.readUEG();let T=t.readUEG();3==T&&t.skipBits(1);let E=t.readUEG(),S=t.readUEG(),L=t.readBoolean(),k=0,A=0,R=0,b=0;L&&(k+=t.readUEG(),A+=t.readUEG(),R+=t.readUEG(),b+=t.readUEG());let I=t.readUEG(),_=t.readUEG(),C=t.readUEG(),D=t.readBoolean();for(let e=D?0:i;e<=i;e++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let e=0;e<4;e++)for(let i=0;i<(3===e?2:6);i++)if(t.readBoolean()){let i=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<i;e++)t.readEG()}else t.readUEG();t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let P=t.readUEG(),x=0;for(let e=0;e<P;e++){let i=!1;if(0!==e&&(i=t.readBoolean()),i){e===P&&t.readUEG(),t.readBoolean(),t.readUEG();let i=0;for(let e=0;e<=x;e++){let e=t.readBoolean(),s=!1;e||(s=t.readBoolean()),(e||s)&&i++}x=i}else{let e=t.readUEG(),i=t.readUEG();x=e+i;for(let i=0;i<e;i++)t.readUEG(),t.readBoolean();for(let e=0;e<i;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let e=t.readUEG();for(let i=0;i<e;i++){for(let e=0;e<C+4;e++)t.readBits(1);t.readBits(1)}}let F=0,w=1,M=1,O=!0,N=1,B=0;t.readBoolean(),t.readBoolean();if(t.readBoolean()){if(t.readBoolean()){let e=t.readUByte();e>0&&e<16?(w=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],M=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(w=t.readBits(16),M=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(),t.readBoolean()&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(N=t.readBits(32),B=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let e=t.readBoolean(),s=t.readBoolean(),r=!1;(e||s)&&((r=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),r&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let a=0;a<=i;a++){let i=(O=t.readBoolean())||t.readBoolean(),a=!1;i?t.readEG():a=t.readBoolean();let n=a?1:t.readUEG()+1;if(e)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(s)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),F=t.readUEG())}let U=E,$=S;if(L){let e=1,t=1;1===T?e=t=2:2==T&&(e=2),U=E-e*A-e*k,$=S-t*b-t*R}let K=s?["A","B","C"][s]:"",G=n<<24|l<<16|o<<8|d,j=0;for(let e=0;e<32;e++)j=(j|(G>>e&1)<<31-e)>>>0;let H=j.toString(16);return 1===a&&"2"===H&&(H="6"),{codecString:`hvc1.${K}${a}.${H}.${r?"H":"L"}${p}.B0`,params:{general_tier_flag:r,general_profile_idc:a,general_profile_space:s,general_profile_compatibility_flags:[n,l,o,d],general_constraint_indicator_flags:[h,u,c,f,g,m],general_level_idc:
7p,bit_depth:I+8,bit_depth_luma_minus8:I,bit_depth_chroma_minus8:_,min_spatial_segmentation_idc:F,chroma_format_idc:T,frame_rate:{fixed:O,fps:B/N}},width:U,height:$,pixelRatio:[w,M]}}readPPS(e){let t=new rB(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);let i=t.readBoolean(),s=t.readBoolean(),r=1;return s&&i?r=0:s?r=3:i&&(r=2),{parallelismType:r}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}function rK(e,t){return((31&e[t+1])<<8)+e[t+2]}function rG(e,t,i,s){s.warn(`parsing error: ${t.message}`),e.emit(eX.ERROR,eX.ERROR,{type:eq.MEDIA_ERROR,details:ez.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function rj(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function rH(e,t){let i,s,r,a,n,l=0,o=e.data;if(!e||0===e.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=tM(o[0],o[1]),o.splice(1,1);if(1===((i=o[0])[0]<<16)+(i[1]<<8)+i[2]){if((s=(i[4]<<8)+i[5])&&s>e.size-6)return null;let d=i[7];192&d&&(a=(14&i[9])*0x20000000+(255&i[10])*4194304+(254&i[11])*16384+(255&i[12])*128+(254&i[13])/2,64&d?a-(n=(14&i[14])*0x20000000+(255&i[15])*4194304+(254&i[16])*16384+(255&i[17])*128+(254&i[18])/2)>54e5&&(t.warn(`${Math.round((a-n)/9e4)}s delta between PTS and DTS, align them`),a=n):n=a);let h=(r=i[8])+9;if(e.size<=h)return null;e.size-=h;let u=new Uint8Array(e.size);for(let e=0,t=o.length;e<t;e++){let t=(i=o[e]).byteLength;if(h)if(h>t){h-=t;continue}else i=i.subarray(h),t-=h,h=0;u.set(i,l),l+=t}return s&&(s-=r+3),{data:u,pts:a,dts:n,len:s}}return null}class rV{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);else if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);else if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);else if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)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])}}}class rW{static init(){let e;for(e in rW.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:[]},rW.types)rW.types.hasOwnProperty(e)&&(rW.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);rW.HDLR_TYPES={video: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]),audio: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])};let t=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]);rW.STTS=rW.STSC=rW.STCO=new Uint8Array([0,0,0,0,0,0,0,0]),rW.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),rW.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),rW.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),rW.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);let i=new Uint8Array([105,115,111,109]),s=new Uint8Array([97,118,99,49]),r=new 
7Uint8Array([0,0,0,1]);rW.FTYP=rW.box(rW.types.ftyp,i,r,i,s),rW.DINF=rW.box(rW.types.dinf,rW.box(rW.types.dref,t))}static box(e,...t){let i=8,s=t.length,r=s;for(;s--;)i+=t[s].byteLength;let a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=255&i,a.set(e,4),s=0,i=8;s<r;s++)a.set(t[s],i),i+=t[s].byteLength;return a}static hdlr(e){return rW.box(rW.types.hdlr,rW.HDLR_TYPES[e])}static mdat(e){return rW.box(rW.types.mdat,e)}static mdhd(e,t){let i=Math.floor((t*=e)/0x100000000),s=Math.floor(t%0x100000000);return rW.box(rW.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))}static mdia(e){return rW.box(rW.types.mdia,rW.mdhd(e.timescale||0,e.duration||0),rW.hdlr(e.type),rW.minf(e))}static mfhd(e){return rW.box(rW.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?rW.box(rW.types.minf,rW.box(rW.types.smhd,rW.SMHD),rW.DINF,rW.stbl(e)):rW.box(rW.types.minf,rW.box(rW.types.vmhd,rW.VMHD),rW.DINF,rW.stbl(e))}static moof(e,t,i){return rW.box(rW.types.moof,rW.mfhd(e),rW.traf(i,t))}static moov(e){let t=e.length,i=[];for(;t--;)i[t]=rW.trak(e[t]);return rW.box.apply(null,[rW.types.moov,rW.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(rW.mvex(e)))}static mvex(e){let t=e.length,i=[];for(;t--;)i[t]=rW.trex(e[t]);return rW.box.apply(null,[rW.types.mvex,...i])}static mvhd(e,t){let i=Math.floor((t*=e)/0x100000000),s=Math.floor(t%0x100000000),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return rW.box(rW.types.mvhd,r)}static sdtp(e){let t,i,s=e.samples||[],r=new Uint8Array(4+s.length);for(t=0;t<s.length;t++)i=s[t].flags,r[t+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return rW.box(rW.types.sdtp,r)}static stbl(e){return rW.box(rW.types.stbl,rW.stsd(e),rW.box(rW.types.stts,rW.STTS),rW.box(rW.types.stsc,rW.STSC),rW.box(rW.types.stsz,rW.STSZ),rW.box(rW.types.stco,rW.STCO))}static avc1(e){let t,i,s,r=[],a=[];for(t=0;t<e.sps.length;t++)s=(i=e.sps[t]).byteLength,r.push(s>>>8&255),r.push(255&s),r=r.concat(Array.prototype.slice.call(i));for(t=0;t<e.pps.length;t++)s=(i=e.pps[t]).byteLength,a.push(s>>>8&255),a.push(255&s),a=a.concat(Array.prototype.slice.call(i));let n=rW.box(rW.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|e.sps.length].concat(r).concat([e.pps.length]).concat(a))),l=e.width,o=e.height,d=e.pixelRatio[0],h=e.pixelRatio[1];return rW.box(rW.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,o>>8&255,255&o,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]),n,rW.box(rW.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),rW.box(rW.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))}static esds(e){return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...e.config,6,1,2])}static audioStsd(e){let 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,255&t,0,0])}static mp4a(e){return rW.box(rW.types.mp4a,rW.audioStsd(e),rW.box(rW.types.esds,rW.esds(e)))}static mp3(e){return rW.box(rW.types[".mp3"],rW.audioStsd(e))}static ac3(e){return rW.box(rW.types["ac-3"],rW.audioStsd(e),rW.box(rW.types.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return rW.box(rW.types.stsd,rW.STSD,rW.mp4a(e));if("ac3"===t&&e.config)return rW.box(rW.types.stsd,rW.STSD,rW.ac3(e));if("mp3"===t&&"mp3"===e.codec)return rW.box(rW.types.stsd,rW.STSD,rW.mp3(e))}else if(e.pps&&e.sps){if("avc"===t)return rW.box(rW.types.stsd,rW.STSD,rW.avc1(e));
7if("hevc"===t&&e.vps)return rW.box(rW.types.stsd,rW.STSD,rW.hvc1(e))}else throw Error("video track missing pps or sps");throw Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){let t=e.id,i=(e.duration||0)*(e.timescale||0),s=e.width||0,r=e.height||0,a=Math.floor(i/0x100000000),n=Math.floor(i%0x100000000);return rW.box(rW.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,255&t,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,n>>24,n>>16&255,n>>8&255,255&n,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,255&s,0,0,r>>8&255,255&r,0,0]))}static traf(e,t){let i=rW.sdtp(e),s=e.id,r=Math.floor(t/0x100000000),a=Math.floor(t%0x100000000);return rW.box(rW.types.traf,rW.box(rW.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),rW.box(rW.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,a>>24,a>>16&255,a>>8&255,255&a])),rW.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||0xffffffff,rW.box(rW.types.trak,rW.tkhd(e),rW.mdia(e))}static trex(e){let t=e.id;return rW.box(rW.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){let i,s,r,a,n,l,o=e.samples||[],d=o.length,h=12+16*d,u=new Uint8Array(h);for(t+=8+h,u.set([+("video"===e.type),0,15,1,d>>>24&255,d>>>16&255,d>>>8&255,255&d,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),i=0;i<d;i++)r=(s=o[i]).duration,a=s.size,n=s.flags,l=s.cts,u.set([r>>>24&255,r>>>16&255,r>>>8&255,255&r,a>>>24&255,a>>>16&255,a>>>8&255,255&a,n.isLeading<<2|n.dependsOn,n.isDependedOn<<6|n.hasRedundancy<<4|n.paddingValue<<1|n.isNonSync,61440&n.degradPrio,15&n.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return rW.box(rW.types.trun,u)}static initSegment(e){rW.types||rW.init();let t=rW.moov(e);return tM(rW.FTYP,t)}static hvc1(e){let t=e.params,i=[e.vps,e.sps,e.pps],s=new Uint8Array([1,t.general_profile_space<<6|32*!!t.general_tier_flag|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),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|64*!!t.frame_rate.fixed,i.length]),r=s.length;for(let e=0;e<i.length;e+=1){r+=3;for(let t=0;t<i[e].length;t+=1)r+=2+i[e][t].length}let a=new Uint8Array(r);a.set(s,0),r=s.length;let n=i.length-1;for(let e=0;e<i.length;e+=1){a.set(new Uint8Array([32+e|128*(e===n),0,i[e].length]),r),r+=3;for(let t=0;t<i[e].length;t+=1)a.set(new Uint8Array([i[e][t].length>>8,255&i[e][t].length]),r),r+=2,a.set(i[e][t],r),r+=i[e][t].length}let l=rW.box(rW.types.hvcC,a),o=e.width,d=e.height,h=e.pixelRatio[0],u=e.pixelRatio[1];return rW.box(rW.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,o>>8&255,255&o,d>>8&255,255&d,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,rW.box(rW.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),rW.box(rW.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,u>>24,u>>16&255,u>>8&255,255&u])))}}function rY(e,t,i=1,s=!1){let r=e*t*i;return s?Math.round(r):r}function rq(e,t=!1){return rY(e,1e3,11111111111111112e-21,t)}function rz(e){let{baseTime:t,timescale:i,trackId:s}=e;return`${t/i} (${t}/${i}) trackId: ${s}`}rW.types=void 0,rW.HDLR_TYPES=void 0,rW.STTS=void 0,rW.STSC=void 0,rW.STCO=void 0,rW.STSZ=void 0,rW.VMHD=void 0,rW.SMHD=void 0,rW.STSD=void 0,rW.FTYP=void 0,rW.DINF=void 0;let rX=null,rQ=null;function rZ(e,t,i,s){return{duration:t,size:i,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:+!e}}}class rJ extends e7{constructor(e,t,i,s){if(super("mp4-remuxer",s),this.observer=void 0,this.config=void 0,this.typeSupp
7orted=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,null===rX){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);rX=e?parseInt(e[1]):0}if(null===rQ){const e=navigator.userAgent.match(/Safari\/(\d+)/i);rQ=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){let t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log(`Reset initPTS: ${t?rz(t):t} > ${e?rz(e):e}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1,i=e[0].pts,s=e.reduce((e,s)=>{let r=s.pts,a=r-e;return(a<-0x100000000&&(t=!0,a=(r=r0(r,i))-e),a>0)?e:r},i);return t&&this.debug("PTS rollover detected"),s}remux(e,t,i,s,r,a,n,l){let o,d,h,u,c,f,g=r,m=r,p=e.pid>-1,y=t.pid>-1,v=t.samples.length,T=e.samples.length>0,E=n&&v>0||v>1;if((!p||T)&&(!y||E)||this.ISGenerated||n){let i;if(this.ISGenerated){var S,L,k,A;let e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(S=t.pixelRatio)?void 0:S[0])!==(null==(L=e.pixelRatio)?void 0:L[0])||(null==(k=t.pixelRatio)?void 0:k[1])!==(null==(A=e.pixelRatio)?void 0:A[1]))||!e&&E||null===this.nextAudioTs&&T)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,r,a));let s=this.isVideoContiguous,n=-1;if(E&&(n=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return -1}(t.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,n>0){this.warn(`Dropped ${n} out of ${v} video samples due to a missing keyframe`);let e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(n),t.dropped+=n,m+=(t.samples[0].pts-e)/t.inputTimeScale,i=m}else -1===n&&(this.warn(`No keyframe found out of ${v} video samples`),f=!1);if(this.ISGenerated){if(T&&E){let i=this.getVideoStartPts(t.samples),s=(r0(e.samples[0].pts,i)-i)/t.inputTimeScale;g+=Math.max(0,s),m+=Math.max(0,-s)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(e,t,r,a)),d=this.remuxAudio(e,g,this.isAudioContiguous,a,y||E||l===e2?m:void 0),E){let i=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(e,t,r,a)),o=this.remuxVideo(t,m,s,i)}}else E&&(o=this.remuxVideo(t,m,s,0));o&&(o.firstKeyFrame=n,o.independent=-1!==n,o.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(c=r1(i,r,this._initPTS,this._initDTS)),s.samples.length&&(u=r2(s,r,this._initPTS))),{audio:d,video:o,initSegment:h,independent:f,text:u,id3:c}}computeInitPts(e,t,i,s){let r=Math.round(i*t),a=r0(e,r);if(a<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-a)/t} ${s}`);a<r+t;)a+=0x200000000;return a-r}generateIS(e,t,i,s){let r,a,n,l=e.samples,o=t.samples,d=this.typeSupported,h={},u=this._initPTS,c=!u||s,f="audio/mp4",g=-1;if(c&&(r=a=1/0),e.config&&l.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":d.mpeg?(f="audio/mpeg",e.codec=""):d.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}h.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&d.mpeg?new Uint8Array(0):rW.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(g=e.id,n=e.inputTimeScale,u&&n===u.timescale?c=!1:r=a=this.computeInitPts(l[0].pts,n,i,"audio"))}if(t.sps&&t.pps&&o.length){if(t.timescale=t.inputTimeScale,h.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:rW.initSegment([t]),metadata:{width:t.width,height:t.height}},c)if(g=t.id,n=t.inputTimeScale,u&&n===u.timescale)c=!1;else{let e=this.getVideoStartPts(o),t=r0(o[0].dts,e),s=this.computeInitPts(t,n,i,"video"),l=this.computeInitPts(e,n,i,"video");a=Math.min(a,s),r=Math.min(r,l)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(h).length)return this.ISGenerated=!0,c?(u&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${i} ${r/n} != initPTS: ${u.baseTime/u.timescale} (${u.baseTime}/${u.timescale}) trackId: ${u.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${r/n} (${r}/${n}) trackId: ${g}`),this._initPTS={baseTime:r,timescale:n,trackId:g},this._initDTS={baseTime:a,timescale:n,trackId:g}):r=n=void 0,{tracks:h,initPTS:r,timescale:n,trackId:g}}remuxVideo(e,t,i,s){let r,a,n,l=e.inputTimeScale,o=e.samples,d=[],h=o.length,u=this._initPTS,c=u.baseTime*l/u.timescale,f=this.nextVideoTs,g=8,m=this.videoSampleDuration,p=1/0,y=-1/0,v=!1;if(!i||null===f){let e=c+t*l,s=o[0].pts-r0(o[0].dts,o[0].pts);rX&&null!==f&&15e3>Math.abs(e-s-(f+c))?i=!0:f=e-s-c}let T=f+c;for(let e=0;e<h;
7e++){let t=o[e];t.pts=r0(t.pts,T),t.dts=r0(t.dts,T),t.dts<o[e>0?e-1:e].dts&&(v=!0)}v&&o.sort(function(e,t){let i=e.dts-t.dts,s=e.pts-t.pts;return i||s}),r=o[0].dts;let E=(a=o[o.length-1].dts)-r,S=E?Math.round(E/(h-1)):m||e.inputTimeScale/30;if(i){let i=r-T,s=i>S,a=i<-1;if((s||a)&&(s?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${rq(i,!0)} ms (${i}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${rq(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!a||T>=o[0].pts||rX)){r=T;let e=o[0].pts-i;if(s)o[0].dts=r,o[0].pts=e;else{let t=!0;for(let s=0;s<o.length&&(!(o[s].dts>e)||!t);s++){let e=o[s].pts;if(o[s].dts-=i,o[s].pts-=i,s<o.length-1){let i=o[s+1].pts;t=i<=o[s].pts==i<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${rq(e,!0)}/${rq(r,!0)}, delta: ${rq(i,!0)} ms`)}}let L=0,k=0,A=r=Math.max(0,r);for(let e=0;e<h;e++){let t=o[e],i=t.units,s=i.length,r=0;for(let e=0;e<s;e++)r+=i[e].data.length;k+=r,L+=s,t.length=r,t.dts<A?(t.dts=A,A+=S/4|0||1):A=t.dts,p=Math.min(t.pts,p),y=Math.max(t.pts,y)}a=o[h-1].dts;let R=k+4*L+8;try{n=new Uint8Array(R)}catch(e){this.observer.emit(eX.ERROR,eX.ERROR,{type:eq.MUX_ERROR,details:ez.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:R,reason:`fail allocating video mdat ${R}`});return}let b=new DataView(n.buffer);b.setUint32(0,R),n.set(rW.types.mdat,4);let I=!1,_=1/0,C=1/0,D=-1/0,P=-1/0;for(let e=0;e<h;e++){let t,i=o[e],r=i.units,a=0;for(let e=0,t=r.length;e<t;e++){let t=r[e],i=t.data,s=t.data.byteLength;b.setUint32(g,s),g+=4,n.set(i,g),g+=s,a+=4+s}if(e<h-1)m=o[e+1].dts-i.dts,t=o[e+1].pts-i.pts;else{let r=this.config,a=e>0?i.dts-o[e-1].dts:S;if(t=e>0?i.pts-o[e-1].pts:S,r.stretchShortVideoTrack&&null!==this.nextAudioTs){let e=Math.floor(r.maxBufferHole*l),t=(s?p+s*l:this.nextAudioTs+c)-i.pts;t>e?((m=t-a)<0?m=a:I=!0,this.log(`It is approximately ${t/90} ms to the next segment; using duration ${m/90} ms for the last video frame.`)):m=a}else m=a}let u=Math.round(i.pts-i.dts);_=Math.min(_,m),D=Math.max(D,m),C=Math.min(C,t),P=Math.max(P,t),d.push(rZ(i.key,m,a,u))}if(d.length){if(rX){if(rX<70){let e=d[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(rQ&&P-C<D-_&&S/D<.025&&0===d[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=r;for(let t=0,i=d.length;t<i;t++){let s=e+d[t].duration,r=e+d[t].cts;if(t<i-1){let e=s+d[t+1].cts;d[t].duration=e-r}else d[t].duration=t?d[t-1].duration:S;d[t].cts=0,e=s}}}let x=a+(m=I||!m?S:m);this.nextVideoTs=f=x-c,this.videoSampleDuration=m,this.isVideoContiguous=!0;let F={data1:rW.moof(e.sequenceNumber++,r,e8(e,{samples:d})),data2:n,startPTS:(p-c)/l,endPTS:(y+m-c)/l,startDTS:(r-c)/l,endDTS:f/l,type:"video",hasAudio:!1,hasVideo:!0,nb:d.length,dropped:e.dropped};return e.samples=[],e.dropped=0,F}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,i,s,r){let a,n=e.inputTimeScale,l=e.samplerate?e.samplerate:n,o=n/l,d=this.getSamplesPerFrame(e),h=d*o,u=this._initPTS,c="mp3"===e.segmentCodec&&this.typeSupported.mpeg,f=[],g=void 0!==r,m=e.samples,p=8*!c,y=this.nextAudioTs||-1,v=u.baseTime*n/u.timescale,T=v+t*n;if(this.isAudioContiguous=i=i||m.length&&y>0&&(s&&9e3>Math.abs(T-(y+v))||Math.abs(r0(m[0].pts,T)-(y+v))<20*h),m.forEach(function(e){e.pts=r0(e.pts,T)}),!i||y<0){let e=m.length;if(e!==(m=m.filter(e=>e.pts>=0)).length&&this.warn(`Removed ${m.length-e} of ${e} samples (initPTS ${v} / ${n})`),!m.length)return;y=0===r?0:s&&!g?Math.max(0,T-v):m[0].pts-v}if("aac"===e.segmentCodec){let t=this.config.maxAudioFramesDrift;for(let i=0,s=y+v;i<m.length;i++){let r=m[i],a=r.pts,l=a-s,o=Math.abs(1e3*l/n);
7if(l<=-t*h&&g)0===i&&(this.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*l/n)} ms.`),this.nextAudioTs=y=a-v,s=a);else if(l>=t*h&&o<1e4&&g){let t=Math.round(l/h);for(s=a-t*h;s<0&&t&&h;)t--,s+=h;0===i&&(this.nextAudioTs=y=s-v),this.warn(`Injecting ${t} audio frames @ ${((s-v)/n).toFixed(3)}s due to ${Math.round(1e3*l/n)} ms gap.`);for(let a=0;a<t;a++){let t=rV.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),t=r.unit.subarray()),m.splice(i,0,{unit:t,pts:s}),s+=h,i++}}r.pts=s,s+=h}}let E=null,S=null,L=0,k=m.length;for(;k--;)L+=m[k].unit.byteLength;for(let t=0,s=m.length;t<s;t++){let s=m[t],r=s.unit,n=s.pts;if(null!==S)f[t-1].duration=Math.round((n-S)/o);else{if(i&&"aac"===e.segmentCodec&&(n=y+v),E=n,!(L>0))return;L+=p;try{a=new Uint8Array(L)}catch(e){this.observer.emit(eX.ERROR,eX.ERROR,{type:eq.MUX_ERROR,details:ez.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:L,reason:`fail allocating audio mdat ${L}`});return}c||(new DataView(a.buffer).setUint32(0,L),a.set(rW.types.mdat,4))}a.set(r,p);let l=r.byteLength;p+=l,f.push(rZ(!0,d,l,0)),S=n}let A=f.length;if(!A)return;let R=f[f.length-1];y=S-v,this.nextAudioTs=y+o*R.duration;let b=c?new Uint8Array(0):rW.moof(e.sequenceNumber++,E/o,e8({},e,{samples:f}));e.samples=[];let I=(E-v)/n,_=this.nextAudioTs/n,C={data1:b,data2:a,startPTS:I,endPTS:_,startDTS:I,endDTS:_,type:"audio",hasAudio:!0,hasVideo:!1,nb:A};return this.isAudioContiguous=!0,C}}function r0(e,t){let i;if(null===t)return e;for(i=t<e?-0x200000000:0x200000000;Math.abs(e-t)>0x100000000;)e+=i;return e}function r1(e,t,i,s){let r=e.samples.length;if(!r)return;let a=e.inputTimeScale;for(let n=0;n<r;n++){let r=e.samples[n];r.pts=r0(r.pts-i.baseTime*a/i.timescale,t*a)/a,r.dts=r0(r.dts-s.baseTime*a/s.timescale,t*a)/a}let n=e.samples;return e.samples=[],{samples:n}}function r2(e,t,i){let s=e.samples.length;if(!s)return;let r=e.inputTimeScale;for(let a=0;a<s;a++){let s=e.samples[a];s.pts=r0(s.pts-i.baseTime*r/i.timescale,t*r)/r}e.samples.sort((e,t)=>e.pts-t.pts);let a=e.samples;return e.samples=[],{samples:a}}function r3(e,t,i=!1){return(null==e?void 0:e.start)!==void 0?(e.start+(i?e.duration:0))/e.timescale:t}function r4(e,t,i){let s=e.codec;return s&&s.length>4?s:t===tf?"ec-3"===s||"ac-3"===s||"alac"===s?s:"fLaC"===s||"Opus"===s?tz(s,!1):(i.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(i.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}try{t=self.performance.now.bind(self.performance)}catch(e){t=Date.now}let r5=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,s){let r=this.videoTrack=rT("video",1),a=this.audioTrack=rT("audio",1),n=this.txtTrack=rT("text",1);if(this.id3Track=rT("id3",1),this.timeOffset=0,!(null!=e&&e.byteLength))return;let l=t_(e);if(l.video){let{id:e,timescale:t,codec:i,supplemental:s}=l.video;r.id=e,r.timescale=n.timescale=t,r.codec=i,r.supplemental=s}if(l.audio){let{id:e,timescale:t,codec:i}=l.audio;a.id=e,a.timescale=t,a.codec=i}n.id=tS.text,r.sampleDuration=0,r.duration=a.duration=s}resetContiguity(){this.remainderData=null}static probe(e){let t=e.byteLength;for(let i=0;i<t;){let s=tA(e,i);if(s>8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=s>1?i+s:t}return!1}demux(e,t){this.timeOffset=t;let i=e,s=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=tM(this.remainderData,e));let t=function(e){let t={valid:null,remainder:null},i=tI(e,["moof"]);if(i.length<2)return t.remainder=e,t;let s=i[i.length-1];return t.valid=e.slice(0,s.byteOffset-8),t.remainder=e.slice(s.byteOffset-8),t}(i);this.remainderData=t.remainder,s.samples=t.valid||new Uint8Array}else s.samples=i;let a=this.extractID3Track(s,t);
7return r.samples=tO(t,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){let e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;let s=this.extractID3Track(t,this.timeOffset);return i.samples=tO(e,t),{videoTrack:t,audioTrack:rT(),id3Track:s,textTrack:rT()}}extractID3Track(e,t){let i=this.id3Track;return e.samples.length&&tI(e.samples,["emsg"]).forEach(e=>{let s=function(e){let t=e[0],i="",s="",r=0,a=0,n=0,l=0,o=0,d=0;if(0===t){for(;"\0"!==tL(e.subarray(d,d+1));)i+=tL(e.subarray(d,d+1)),d+=1;for(i+=tL(e.subarray(d,d+1)),d+=1;"\0"!==tL(e.subarray(d,d+1));)s+=tL(e.subarray(d,d+1)),d+=1;s+=tL(e.subarray(d,d+1)),d+=1,r=tA(e,12),a=tA(e,16),l=tA(e,20),o=tA(e,24),d=28}else if(1===t){d+=4,r=tA(e,d);let t=tA(e,d+=4),a=tA(e,d+=4);for(d+=4,eW(n=0x100000000*t+a)||(n=Number.MAX_SAFE_INTEGER,tr.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=tA(e,d),d+=4,o=tA(e,d),d+=4;"\0"!==tL(e.subarray(d,d+1));)i+=tL(e.subarray(d,d+1)),d+=1;for(i+=tL(e.subarray(d,d+1)),d+=1;"\0"!==tL(e.subarray(d,d+1));)s+=tL(e.subarray(d,d+1)),d+=1;s+=tL(e.subarray(d,d+1)),d+=1}return{schemeIdUri:i,value:s,timeScale:r,presentationTime:n,presentationTimeDelta:a,eventDuration:l,id:o,payload:e.subarray(d,e.byteLength)}}(e);if(rw.test(s.schemeIdUri)){let e=rM(s,t),r=0xffffffff===s.eventDuration?1/0:s.eventDuration/s.timeScale;r<=.001&&(r=1/0);let a=s.payload;i.samples.push({data:a,len:a.byteLength,dts:e,pts:e,type:rv.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata&&s.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){let e=rM(s,t);i.samples.push({data:s.payload,len:s.payload.byteLength,dts:e,pts:e,type:rv.misbklv,duration:1/0})}}),i}demuxSampleAes(e,t,i){return Promise.reject(Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class extends e7{constructor(e,t,i,s){super("passthrough-remuxer",s),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,s){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,s),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:i,videoCodec:s}=this;if(!(null!=e&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:r,video:a}=this.initData=t_(e);if(t)!function(e,t){if(!e||!t)return;let i=t.keyId;i&&t.isCommonEncryption&&tF(e,(e,t)=>{let s=e.subarray(8,24);s.some(e=>0!==e)||(tr.log(`[eme] Patching keyId in 'enc${t?"a":"v"}>sinf>>tenc' box: ${to(s)} -> ${to(i)}`),e.set(i,8))})}(e,t);else{let e=r||a;null!=e&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}r&&(i=r4(r,tf,this)),a&&(s=r4(a,tg,this));let n={};r&&a?n.audiovideo={container:"video/mp4",codec:i+","+s,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:r?n.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:e,id:"audio"}:a?n.video={container:"video/mp4",codec:s,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=n}remux(e,t,i,s,r,a){var n,l;let{initPTS:o,lastEndTime:d}=this,h={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};eV(d)||(d=this.lastEndTime=r||0);let u=t.samples;if(!u.length)return h;let c={initPTS:void 0,timescale:void 0,trackId:void 0},f=this.initData;if(null!=(n=f)&&n.length||(this.generateInitSegment(u),f=this.initData),!(null!=(l=f)&&l.length))return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(c.tracks=this.initTracks,this.emitInitSegment=!1);let g=function(e,t,i){let s={},r=tI(e,["moof","traf"]);for(let e=0;e<r.length;e++){let a=r[e],n=tI(a,["tfhd"])[0],l=tA(n,4),o=t[l];if(!o)continue;s[l]||(s[l]={start:NaN,duration:0,sampleCount:0,timescale:o.timescale,type:o.type});let d=s[l],h=tI(a,["tfdt"])[0];if(h){let e=h[0],t=tA(h,4);1===e&&(0xffffffff===t?i.warn("[mp4-demuxer]: Ignoring assumed invali
7d signed 64-bit track fragment decode time"):(t*=0x100000000,t+=tA(h,8))),eV(t)&&(!eV(d.start)||t<d.start)&&(d.start=t)}let u=o.default,c=tA(n,0)|(null==u?void 0:u.flags),f=(null==u?void 0:u.duration)||0;8&c&&(f=2&c?tA(n,12):tA(n,8));let g=tI(a,["trun"]),m=d.start||0,p=0,y=f;for(let e=0;e<g.length;e++){let t=g[e],i=tA(t,4),s=d.sampleCount;d.sampleCount+=i;let r=1&t[3],a=4&t[3],n=1&t[2],l=2&t[2],o=4&t[2],h=8&t[2],u=8,c=i;for(r&&(u+=4),a&&i&&(1&t[u+1]||void 0!==d.keyFrameIndex||(d.keyFrameIndex=s),u+=4,n?(y=tA(t,u),u+=4):y=f,l&&(u+=4),h&&(u+=4),m+=y,p+=y,c--);c--;)n?(y=tA(t,u),u+=4):y=f,l&&(u+=4),o&&(1&t[u+1]||void 0!==d.keyFrameIndex||(d.keyFrameIndex=d.sampleCount-(c+1),d.keyFrameStart=m),u+=4),h&&(u+=4),m+=y,p+=y;!p&&f&&(p+=f*i)}d.duration+=p}if(!Object.keys(s).some(e=>s[e].duration)){let t=1/0,i=0,r=tI(e,["sidx"]);for(let e=0;e<r.length;e++){let s=function(e){let t=[],i=e[0],s=8,r=tA(e,8);s+=4;let a=0,n=0;0===i?(a=tA(e,s),n=tA(e,s+4),s+=8):(a=tR(e,s),n=tR(e,s+8),s+=16),s+=2;let l=e.length+n,o=tk(e,s);s+=2;for(let i=0;i<o;i++){let i=s,a=tA(e,i);i+=4;let n=0x7fffffff&a;if(1==(0x80000000&a)>>>31)return tr.warn("SIDX has hierarchical references (not supported)"),null;let o=tA(e,i);i+=4,t.push({referenceSize:n,subsegmentDuration:o,info:{duration:o/r,start:l,end:l+n-1}}),l+=n,i+=4,s=i}return{earliestPresentationTime:a,timescale:r,version:i,referencesCount:o,references:t}}(r[e]);if(null!=s&&s.references){t=Math.min(t,s.earliestPresentationTime/s.timescale);let e=s.references.reduce((e,t)=>e+t.info.duration||0,0);i=Math.max(i,e+s.earliestPresentationTime/s.timescale)}}i&&eV(i)&&Object.keys(s).forEach(e=>{s[e].duration||(s[e].duration=i*s[e].timescale-s[e].start)})}return s}(u,f,this),m=f.audio?g[f.audio.id]:null,p=f.video?g[f.video.id]:null,y=r3(p,1/0),v=r3(m,1/0),T=r3(p,0,!0),E=r3(m,0,!0),S=r,L=0,k=m&&(!p||!o&&v<y||o&&o.trackId===f.audio.id),A=k?m:p;if(A){let e=A.timescale,t=A.start-r*e,i=k?f.audio.id:f.video.id;S=A.start/e,L=k?E-v:T-y,(a||!o)&&(function(e,t,i,s){if(null===e)return!0;let r=Math.max(s,1);return Math.abs(t-e.baseTime/e.timescale-i)>r}(o,S,r,L)||e!==o.timescale)&&(o&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${r} ${t/e} != initPTS: ${o.baseTime/o.timescale} (${o.baseTime}/${o.timescale}) trackId: ${o.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${S-r} (${t}/${e}) trackId: ${i}`),o=null,c.initPTS=t,c.timescale=e,c.trackId=i)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);o?(c.initPTS=o.baseTime,c.timescale=o.timescale,c.trackId=o.trackId):(c.timescale&&void 0!==c.trackId&&void 0!==c.initPTS||(this.warn("Could not set initPTS"),c.initPTS=S,c.timescale=1,c.trackId=-1),this.initPTS=o={baseTime:c.initPTS,timescale:c.timescale,trackId:c.trackId});let R=S-o.baseTime/o.timescale,b=R+L;L>0?this.lastEndTime=b:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let I=!!f.audio,_=!!f.video,C="";I&&(C+="audio"),_&&(C+="video");let D={data1:u,startPTS:R,startDTS:R,endPTS:b,endDTS:b,type:C,hasAudio:I,hasVideo:_,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};h.audio=I&&!_?D:void 0,h.video=_?D:void 0;let P=null==p?void 0:p.sampleCount;if(P){let e=p.keyFrameIndex,t=-1!==e;D.nb=P,D.dropped=0===e||this.isVideoContiguous?0:t?e:P,D.independent=t,D.firstKeyFrame=e,t&&p.keyFrameStart&&(D.firstKeyFramePTS=(p.keyFrameStart-o.baseTime)/o.timescale),this.isVideoContiguous||(h.independent=t),this.isVideoContiguous||(this.isVideoContiguous=t),D.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${P} dropped: ${D.dropped} start: ${D.firstKeyFramePTS||"NA"}`)}return h.initSegment=c,h.id3=r1(i,r,o,o),s.samples.length&&(h.text=r2(s,r,o)),h}}},{demux:class e{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.typeSupp
7orted=i,this.logger=s,this.videoParser=null}static probe(t,i){let s=e.syncOffset(t);return s>0&&i.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),-1!==s}static syncOffset(e){let t=e.length,i=Math.min(940,t-188)+1,s=0;for(;s<i;){let r=!1,a=-1,n=0;for(let l=s;l<t;l+=188)if(71===e[l]&&(t-l==188||71===e[l+188])){if(n++,-1===a&&0!==(a=l)&&(i=Math.min(a+18612,e.length-188)+1),r||(r=0===rK(e,l)),r&&n>1&&(0===a&&n>2||l+188>i))return a}else if(n)return -1;else break;s++}return -1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:tS[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(t,i,s,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=e.createTrack("audio",r),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=i,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){let{_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(t,i,s=!1,r=!1){let a;s||(this.sampleAes=null);let n=this._videoTrack,l=this._audioTrack,o=this._id3Track,d=this._txtTrack,h=n.pid,u=n.pesData,c=l.pid,f=o.pid,g=l.pesData,m=o.pesData,p=null,y=this.pmtParsed,v=this._pmtId,T=t.length;if(this.remainderData&&(T=(t=tM(this.remainderData,t)).length,this.remainderData=null),T<188&&!r)return this.remainderData=t,{audioTrack:l,videoTrack:n,id3Track:o,textTrack:d};let E=Math.max(0,e.syncOffset(t));(T-=(T-E)%188)<t.byteLength&&!r&&(this.remainderData=new Uint8Array(t.buffer,T,t.buffer.byteLength-T));let S=0;for(let e=E;e<T;e+=188)if(71===t[e]){let i,r=!!(64&t[e+1]),T=rK(t,e);if((48&t[e+3])>>4>1){if((i=e+5+t[e+4])===e+188)continue}else i=e+4;switch(T){case h:r&&(u&&(a=rH(u,this.logger))&&(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(n,d,a,!1)),u={data:[],size:0}),u&&(u.data.push(t.subarray(i,e+188)),u.size+=e+188-i);break;case c:if(r){if(g&&(a=rH(g,this.logger)))switch(l.segmentCodec){case"aac":this.parseAACPES(l,a);break;case"mp3":this.parseMPEGPES(l,a);break;case"ac3":this.parseAC3PES(l,a)}g={data:[],size:0}}g&&(g.data.push(t.subarray(i,e+188)),g.size+=e+188-i);break;case f:r&&(m&&(a=rH(m,this.logger))&&this.parseID3PES(o,a),m={data:[],size:0}),m&&(m.data.push(t.subarray(i,e+188)),m.size+=e+188-i);break;case 0:var L,k;r&&(i+=t[i]+1),v=this._pmtId=(31&(L=t)[(k=i)+10])<<8|L[k+11];break;case v:{r&&(i+=t[i]+1);let a=function(e,t,i,s,r,a){let n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},l=(15&e[t+1])<<8|e[t+2],o=t+3+l-4,d=(15&e[t+10])<<8|e[t+11];for(t+=12+d;t<o;){let l=rK(e,t),o=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!s){rj("ADTS AAC",a);break}case 15:-1===n.audioPid&&(n.audioPid=l);break;case 21:-1===n.id3Pid&&(n.id3Pid=l);break;case 219:if(!s){rj("H.264",a);break}case 27:-1===n.videoPid&&(n.videoPid=l);break;case 3:case 4:i.mpeg||i.mp3?-1===n.audioPid&&(n.audioPid=l,n.segmentAudioCodec="mp3"):a.log("MPEG audio found, not supported in this browser");break;case 193:if(!s){rj("AC-3",a);break}case 129:i.ac3?-1===n.audioPid&&(n.audioPid=l,n.segmentAudioCodec="ac3"):a.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===n.audioPid&&o>0){let s=t+5,r=o;for(;r>2;){106===e[s]&&(!0!==i.ac3?a.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=l,n.segmentAudioCodec="ac3"));let t=e[s+1]+2;s+=t,r-=t}}break;case 194:case 135:return rG(r,Error("Unsupported EC-3 in M2TS found"),void 0,a),n;case 36:-1===n.videoPid&&(n.videoPid=l,n.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"))}t+=o+5}return n}(t,i,this.typeSupported,s,this.observer,this.logger);(h=a.videoPid)>0&&(n.pid=h,n.segmentCodec=a.segmentVideoCodec),(c=a.audioPid)>0&&(l.pid=c,l.segmentCodec=a.segmentAudioCodec),(f=a.id3Pid)>0&&(o.pid=f),null===p||y||(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${p}'. Backtracking to sync byte @${E} to parse all TS packets.`),p=null,e=E-188),y=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=T}}else S++;S>0&&rG(this.observer,Error(`Found ${S} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=u,l.pesData=g,o.pesData=m;let A={audioTrack:l,videoTrack:n,id3Track:o,textTrack:d};return r&&this.extractRemainingSamples(A),A}flush(){let e,{remainderData:t}=this;
7return(this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes)?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(e){let t,{audioTrack:i,videoTrack:s,id3Track:r,textTrack:a}=e,n=s.pesData,l=i.pesData,o=r.pesData;if(n&&(t=rH(n,this.logger))?(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(s,a,t,!0),s.pesData=null)):s.pesData=n,l&&(t=rH(l,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,t);break;case"mp3":this.parseMPEGPES(i,t);break;case"ac3":this.parseAC3PES(i,t)}i.pesData=null}else null!=l&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=l;o&&(t=rH(o,this.logger))?(this.parseID3PES(r,t),r.pesData=null):r.pesData=o}demuxSampleAes(e,t,i){let s=this.demux(e,i,!0,!this.config.progressive),r=this.sampleAes=new rO(this.observer,this.config,t);return this.decrypt(s,r)}readyVideoParser(e){null===this.videoParser&&("avc"===e?this.videoParser=new rU:"hevc"===e&&(this.videoParser=new r$))}decrypt(e,t){return new Promise(i=>{let{audioTrack:s,videoTrack:r}=e;s.samples&&"aac"===s.segmentCodec?t.decryptAacSamples(s.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{i(e)}):i(e)}):r.samples&&t.decryptAvcSamples(r.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,s,r,a,n=0,l=this.aacOverFlow,o=t.data;if(l){this.aacOverFlow=null;let t=l.missing,i=l.sample.unit.byteLength;-1===t?o=tM(l.sample.unit,o):(l.sample.unit.set(o.subarray(0,t),i-t),e.samples.push(l.sample),n=l.missing)}for(i=n,s=o.length;i<s-1&&!ru(o,i);i++);if(i!==n){let e,t=i<s-1;if(e=t?`AAC PES did not start with ADTS header,offset:${i}`:"No ADTS header found in AAC PES",rG(this.observer,Error(e),t,this.logger),!t)return}if(rc(e,this.observer,o,i,this.audioCodec),void 0!==t.pts)r=t.pts;else{if(!l)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");let t=9216e4/e.samplerate;r=l.sample.pts+t}let d=0;for(;i<s;){if(a=rf(e,o,i,r,d),i+=a.length,a.missing){this.aacOverFlow=a;break}for(d++;i<s-1&&!ru(o,i);i++);}}parseMPEGPES(e,t){let i=t.data,s=i.length,r=0,a=0,n=t.pts;if(void 0===n)return void this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");for(;a<s;)if(rD(i,a)){let t=rI(e,i,a,n,r);if(t)a+=t.length,r++;else break}else a++}parseAC3PES(e,t){{let i,s=t.data,r=t.pts;if(void 0===r)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");let a=s.length,n=0,l=0;for(;l<a&&(i=rF(e,s,l,r,n++))>0;)l+=i}}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");let i=e8({},t,{type:this._videoTrack?rv.emsg:rv.audioId3,duration:1/0});e.samples.push(i)}},remux:rJ},{demux:class extends rE{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let i=rl(e,0),s=(null==i?void 0:i.length)||0;if(rP(e,s))return!1;for(let i=e.length;s<i;s++)if(function(e,t){if(ru(e,t)){let i=rd(e,t);if(t+i>=e.length)return!1;let s=rh(e,t);if(s<=i)return!1;let r=t+s;return r===e.length||ru(e,r)}return!1}(e,s))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return t+5<e.length&&ro(e,t)&&rh(e,t)<=e.length-t}appendFrame(e,t,i){rc(e,this.observer,t,i,e.manifestCodec);let s=rf(e,t,i,this.basePTS,this.frameIndex);if(s&&0===s.missing)return s}},remux:rJ},{demux:class extends rE{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;let t=rl(e,0),i=(null==t?void 0:t.length)||0;
7if(t&&11===e[i]&&119===e[i+1]&&void 0!==ry(t)&&16>=rx(e,i))return!1;for(let t=e.length;i<t;i++)if(rP(e,i))return tr.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return rC(e,t)&&4<=e.length-t}appendFrame(e,t,i){if(null!==this.basePTS)return rI(e,t,i,this.basePTS,this.frameIndex)}},remux:rJ}];r5.splice(2,0,{demux:class extends rE{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){let s=rF(e,t,i,this.basePTS,this.frameIndex);if(-1!==s)return{sample:e.samples[e.samples.length-1],length:s,missing:0}}static probe(e){if(!e)return!1;let t=rl(e,0);if(!t)return!1;let i=t.length;return!!(11===e[i]&&119===e[i+1]&&void 0!==ry(t)&&16>rx(e,i))}},remux:rJ});class r8{constructor(e,t,i,s,r,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=r,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,i,s,r){var a,n;let l,o=s.transmuxing;o.executeStart=t();let d=new Uint8Array(e),{currentTransmuxState:h,transmuxConfig:u}=this;r&&(this.currentTransmuxState=r);let{contiguous:c,discontinuity:f,trackSwitch:g,accurateTimeOffset:m,timeOffset:p,initSegmentChange:y}=r||h,{audioCodec:v,videoCodec:T,defaultInitPts:E,duration:S,initSegmentData:L}=u,k=(a=d,n=i,l=null,a.byteLength>0&&(null==n?void 0:n.key)!=null&&null!==n.iv&&null!=n.method&&(l=n),l);if(k&&i1(k.method)){let e=this.getDecrypter(),i=i2(k.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(d,k.key.buffer,k.iv.buffer,i).then(e=>{let t=this.push(e,null,s);return this.decryptionPromise=null,t}),this.decryptionPromise;{let r=e.softwareDecrypt(d,k.key.buffer,k.iv.buffer,i);if(s.part>-1){let t=e.flush();r=t?t.buffer:t}if(!r)return o.executeEnd=t(),r6(s);d=new Uint8Array(r)}}let A=this.needsProbing(f,g);if(A){let e=this.configureTransmuxer(d);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(eX.ERROR,eX.ERROR,{type:eq.MEDIA_ERROR,details:ez.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),o.executeEnd=t(),r6(s)}(f||g||y||A)&&this.resetInitSegment(L,v,T,S,i),(f||y||A)&&this.resetInitialTimestamp(E),c||this.resetContiguity();let R=this.transmux(d,k,p,m,s);this.asyncResult=r9(R);let b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,o.executeEnd=t(),R}flush(e){let i=e.transmuxing;i.executeStart=t();let{decrypter:s,currentTransmuxState:r,decryptionPromise:a}=this;if(a)return this.asyncResult=!0,a.then(()=>this.flush(e));let n=[],{timeOffset:l}=r;if(s){let t=s.flush();t&&n.push(this.push(t.buffer,null,e))}let{demuxer:o,remuxer:d}=this;if(!o||!d){i.executeEnd=t();let s=[r6(e)];return this.asyncResult?Promise.resolve(s):s}let h=o.flush(l);return r9(h)?(this.asyncResult=!0,h.then(t=>(this.flushRemux(n,t,e),n))):(this.flushRemux(n,h,e),this.asyncResult)?Promise.resolve(n):n}flushRemux(e,i,s){let{audioTrack:r,videoTrack:a,id3Track:n,textTrack:l}=i,{accurateTimeOffset:o,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===e1?"level":"track"} ${s.level}`);let h=this.remuxer.remux(r,a,n,l,d,o,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=t()}resetInitialTimestamp(e){let{demuxer:t,remuxer:i}=this;t&&i&&(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,s,r){let{demuxer:a,remuxer:n}=this;a&&n&&(a.resetInitSegment(e,t,i,s),n.resetInitSegment(e,t,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,s,r){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,s,r):this.transmuxUnencrypted(e,i,s,r)}transmuxUnencrypted(e,t,i,s){let{audioTrack:r,videoTrack:a,id3Track:n,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,a,n,l,t,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,t,i,s,r){return this.demuxer.demuxSampleAes(e,t,i).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,s,!1,this.id),chunkMeta:r}))}
7configureTransmuxer(e){let t,{config:i,observer:s,typeSupported:r}=this;for(let i=0,s=r5.length;i<s;i++){var a;if(null!=(a=r5[i].demux)&&a.probe(e,this.logger)){t=r5[i];break}}if(!t)return Error("Failed to find demuxer by probing fragment data");let n=this.demuxer,l=this.remuxer,o=t.remux,d=t.demux;l&&l instanceof o||(this.remuxer=new o(s,i,r,this.logger)),n&&n instanceof d||(this.demuxer=new d(s,i,r,this.logger),this.probe=d.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new iM(this.config)),e}}let r6=e=>({remuxResult:{},chunkMeta:e});function r9(e){return"then"in e&&e.then instanceof Function}class r7{constructor(e,t,i,s,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}}class ae{constructor(e,t,i,s,r,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=r,this.initSegmentChange=a}}let at=0;class ai{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=at++,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=e=>{let t=e.data,i=this.hls;if(i&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var s;let e=null==(s=this.workerContext)?void 0:s.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":i.logger[t.data.logType]&&i.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,i.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;let t=Error(`${e.message}  (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(eX.ERROR,{type:eq.OTHER_ERROR,details:ez.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const a=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===eX.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new rt,this.observer.on(eX.FRAG_DECRYPTED,a),this.observer.on(eX.ERROR,a);const n=tZ(r.preferManagedMediaSource);if(this.useWorker&&"u">typeof Worker){const i=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(i.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=function(e){let t=rs[e];if(t)return t.clientCount++,t;let i=new self.URL(e,self.location.href).href,s={worker:new self.Worker(i),scriptURL:i,clientCount:1};return rs[e]=s,s}(r.workerPath)):(i.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){let e=rs[ri];if(e)return e.clientCount++,e;let t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(t),s={worker:new self.Worker(i),objectURL:i,clientCount:1};return rs[ri]=s,s}());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:n,id:t,config:it(r)})}catch(s){i.warn(`Error setting up "${t}" Web Worker, fallback to inline`,s),this.terminateWorker(),this.error=null,this.transmuxer=new r8(this.observer,n,r,"",t,e.logger)}return}}this.transmuxer=new r8(this.observer,n,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=at++;let t=this.hls.config,i=tZ(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupp
7orted:i,id:this.id,config:it(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){let t=rs[e||ri];if(t&&1==t.clientCount--){let{worker:i,objectURL:s}=t;delete rs[e||ri],s&&self.URL.revokeObjectURL(s),i.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,s,r,a,n,l,o,d){var h,u;o.transmuxing.start=self.performance.now();let{instanceNo:c,transmuxer:f}=this,g=a?a.start:r.start,m=r.decryptdata,p=this.frag,y=!(p&&r.cc===p.cc),v=!(p&&o.level===p.level),T=p?o.sn-p.sn:-1,E=this.part?o.part-this.part.index:-1,S=0===T&&o.id>1&&o.id===(null==p?void 0:p.stats.chunkCount),L=!v&&(1===T||0===T&&(1===E||S&&E<=0)),k=self.performance.now();(v||T||0===r.stats.parsing.start)&&(r.stats.parsing.start=k),a&&(E||!L)&&(a.stats.parsing.start=k);let A=!(p&&(null==(h=r.initSegment)?void 0:h.url)===(null==(u=p.initSegment)?void 0:u.url)),R=new ae(y,L,l,v,g,A);if(!L||y||A){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${o.sn}${o.part>-1?" part: "+o.part:""} ${this.id===e1?"level":"track"}: ${o.level} id: ${o.id}
8        discontinuity: ${y}
9        trackSwitch: ${v}
10        contiguous: ${L}
11        accurateTimeOffset: ${l}
12        timeOffset: ${g}
13        initSegmentChange: ${A}`);let e=new r7(i,s,t,n,d);this.configureTransmuxer(e)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:c,cmd:"demux",data:e,decryptdata:m,chunkMeta:o,state:R},e instanceof ArrayBuffer?[e]:[]);else if(f){let t=f.push(e,m,o,R);r9(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,o,"transmuxer-interface push error")}):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){let t=i.flush(e);r9(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}):this.handleFlushResult(t,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(eX.ERROR,{type:eq.MEDIA_ERROR,details:ez.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(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}configureTransmuxer(e){let{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)}}class as extends e7{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(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){let s=null==t?void 0:t.renditionReports;if(s){let r=-1;for(let i=0;i<s.length;i++){let a,n=s[i];try{a=new self.URL(n.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),a=n.URI||""}if(a===e){r=i;break}a===e.substring(0,a.length)&&(r=i)}if(-1!==r){let e=s[r],a=parseInt(e["LAST-MSN"])||t.lastPartSn,n=parseInt(e["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let e=Math.min(t.age-t.partTarget,t.targetduration);n>=0&&e>t.partTarget&&(n+=1)}return new t9(a,n>=0?n:void 0,i&&t6(i))}}}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(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,i){let{details:s,stats:r}=t,a=self.performance.now(),n=r.loading.first?Math.max(0,a-r.loading.first):0;s.advancedDateTime=Date.now()-n;let l=this.hls.config.timelineOffset;
13if(l!==s.appliedTimelineOffset){let e=Math.max(l||0,0);s.appliedTimelineOffset=e,s.fragments.forEach(t=>{t.setStart(t.playlistOffset+e)})}if(s.live||null!=i&&i.live){let l,d,h,u="levelInfo"in t?t.levelInfo:t.track;if(s.reloaded(i),i&&s.fragments.length>0){!function(e,t,i){let s;if(e===t)return;let r=null,a=e.fragments;for(let e=a.length-1;e>=0;e--){let t=a[e].initSegment;if(t){r=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,i){let s=t.skippedSegments,r=Math.max(e.startSN,t.startSN)-t.startSN,a=+!!e.fragmentHint+(s?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,n=t.startSN-e.startSN,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let u=r;u<=a;u++){let r=o[n+u],a=l[u];if(s&&!a&&r&&(a=t.fragments[u]=r),r&&a){var d,h;i(r,a,u,l);let s=r.relurl,n=a.relurl;if(s&&(d=s)!==(h=n)&&h&&s$(d)!==s$(h)){t.playlistParsingError=sx(`media sequence mismatch ${a.sn}:`,e,t,r,a);return}if(r.cc!==a.cc){t.playlistParsingError=sx(`discontinuity sequence mismatch (${r.cc}!=${a.cc})`,e,t,r,a);return}}}}(e,t,(e,i,a,n)=>{if((!t.startCC||t.skippedSegments)&&i.cc!==e.cc){let s=e.cc-i.cc;for(let e=a;e<n.length;e++)n[e].cc+=s;t.endCC=n[n.length-1].cc}eV(e.startPTS)&&eV(e.endPTS)&&(i.setStart(i.startPTS=e.startPTS),i.startDTS=e.startDTS,i.maxStartPTS=e.maxStartPTS,i.endPTS=e.endPTS,i.endDTS=e.endDTS,i.minEndPTS=e.minEndPTS,i.setDuration(e.endPTS-e.startPTS),i.duration&&(s=i),t.PTSKnown=t.alignedSliding=!0),e.hasStream
13s&&(i.elementaryStreams=e.elementaryStreams),i.loader=e.loader,e.hasStats&&(i.stats=e.stats),e.initSegment&&(i.initSegment=e.initSegment,r=e.initSegment)});let n=t.fragments,l=t.fragmentHint?n.concat(t.fragmentHint):n;if(r&&l.forEach(e=>{var t;e&&(!e.initSegment||e.initSegment.relurl===(null==(t=r)?void 0:t.relurl))&&(e.initSegment=r)}),t.skippedSegments){if(t.deltaUpdateFailed=n.some(e=>!e),t.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)n.shift();t.startSN=n[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,i){let{dateRanges:s,recentlyRemovedDateranges:r}=t,a=e8({},e);r&&r.forEach(e=>{delete a[e]});let n=Object.keys(a).length;return n?(Object.keys(s).forEach(e=>{let t=a[e],r=new iQ(s[e].attr,t);r.isValid?(a[e]=r,t||(r.tagOrder+=n)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${it(s[e].attr)}"`)}),a):s}(e.dateRanges,t,i));let s=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<l.length;e++)null===l[e].programDateTime&&sR(l[e],l[e-1],s);sE(s,t)}t.endCC=n[n.length-1].cc}if(!t.startCC){var o;let i=sO(e,t.startSN-1);t.startCC=null!=(o=null==i?void 0:i.cc)?o:n[0].cc}(function(e,t,i){if(e&&t){let s=0;for(let r=0,a=e.length;r<=a;r++){let a=e[r],n=t[r+s];a&&n&&a.index===n.index&&a.fragment.sn===n.fragment.sn?i(a,n):s--}}})(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),s?sP(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS,i):sF(e,t),n.length&&(t.totalduration=t.edge-n[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;let d=t.advancedDateTime;if(t.advanced&&d){let e=t.edge;t.driftStart||(t.driftStartTime=d,t.driftStart=e),t.driftEndTime=d,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}(i,s,this);let e=s.playlistParsingError;if(e){this.warn(e);let i=this.hls;if(!i.config.ignorePlaylistParsingErrors){var o;let{networkDetails:a}=t;i.trigger(eX.ERROR,{type:eq.NETWORK_ERROR,details:ez.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:e,reason:e.message,level:t.level||void 0,parent:null==(o=s.fragments[0])?void 0:o.type,networkDetails:a,stats:r});return}s.playlistParsingError=null}}-1===s.requestScheduled&&(s.requestScheduled=r.loading.start);let c=this.hls.mainForwardBufferInfo,f=c?c.end-c.len:0,g=(s.edge-f)*1e3,m=sM(s,g);if(s.requestScheduled+m<a?s.requestScheduled=a:s.requestScheduled+=m,this.log(`live playlist ${e} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),!this.canLoad||!s.live)return;if(s.canBlockReload&&s.endSN&&s.advanced){let e=this.hls.config.lowLatencyMode,r=s.lastPartSn,n=s.endSN,o=s.lastPartIndex,c=r===n;-1!==o?c?(d=n+1,h=e?0:o):(d=r,h=e?o+1:s.maxPartIndex):d=n+1;let f=s.age,g=f+s.ageHeader,m=Math.min(g-s.partTarget,1.5*s.targetduration);if(m>0){if(g>3*s.targetduration)this.log(`Playlist last advanced ${f.toFixed(2)}s ago. Omitting segment and part directives.`),d=void 0,h=void 0;else if(null!=i&&i.tuneInGoal&&g-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${m} with playlist age: ${s.age}`),m=0;else{let e=Math.floor(m/s.targetduration);d+=e,void 0!==h&&(h+=Math.round(m%s.targetduration/s.partTarget)),this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${f.toFixed(2)}s goal: ${m} skip sn ${e} to part ${h}`)}s.tuneInGoal=m}if(l=this.getDeliveryDirectives(s,t.deliveryDirectives,d,h),e||!c){s.requestScheduled=a,this.loadingPlaylist(u,l);return}}else(s.canBlockReload||s.canSkipUntil)&&(l=this.getDeliveryDirectives(s,t.deliveryDirectives,d,h));l&&void 0!==d&&s.canBlockReload&&(s.requestScheduled=r.loading.first+Math.max(m-2*n,m/2)),this.scheduleLoading(u,l,s)}else this.clearTimer()}scheduleLoading(e,t,i){let s=i||e.details;if(!s)return void this.loadingPlaylist(e,t);let r=self.performance.now(),a=s.requestScheduled;if(r>=a)return void this.loadingPlaylist(e,t);let n=a-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(n)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),n)}getDeliveryDirectives(e,t,i,s){let r=t6(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,r=""),new t9(i,s,r)}checkRetry(e){let t=e.details,i=ip(e),s=e.errorAction,{action:r,retryCount:a=0,retryConfig:n}=s||{},l=!!s&&!!n&&(5===r||!s.resolved&&2===r);if(l){var o;if(a>=n.maxNumRetry)return!1;if(i&&null!=(o=e.context)&&o.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${n.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let e=iE(n,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),e),this.warn(`Retrying playlist loading ${a+1}/${n.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,s.resolved=!0}return l}}function ar(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!aa(e[i].attrs,t[i].attrs))return!1;return!0}function aa(e,t,i){let s=e["STABLE-RENDITION-ID"];return s&&!i?s===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>e[i]!==t[i])}function an(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}class al{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(null===this.queues||null===this.tracks)return;let s=this.queues[t];s.push(e),1!==s.length||i||this.executeNext(t)}appendBlocker(e){return new Promise(t=>{this.append({label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}},e)})}prependBlocker(e){return new Promise(t=>{this.queues&&this.queues[e].unshift({label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}})})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEac
13h(e=>{var t;let i=null==(t=e[0])?void 0:t.label;("async-blocker"===i||"async-blocker-prepend"===i)&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){null===this.queues||this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;let t=this.queues[e];if(t.length){let s=t[0];try{s.execute()}catch(r){var i;if(s.onError(r),null===this.queues||null===this.tracks)return;let t=null==(i=this.tracks[e])?void 0:i.buffer;null!=t&&t.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){let{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`
14${this.list("video")}
15${this.list("audio")}
16${this.list("audiovideo")}}`}list(e){var t,i;return null!=(t=this.queues)&&t[e]||null!=(i=this.tracks)&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let i=null==(t=this.tracks)?void 0:t[e],s=null==i?void 0:i.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map(e=>e.label).join(", "))||""}}let ao=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,ad="HlsJsTrackRemovedError";class ah extends Error{constructor(e){super(e),this.name=ad}}function au(e){let t=e.querySelectorAll("source");[].slice.call(t).forEach(t=>{e.removeChild(t)})}function ac(e){return+("audio"===e)}class af{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=1/0,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(){let{hls:e}=this;e.on(eX.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(eX.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(eX.MANIFEST_PARSED,this.onManifestParsed,this),e.on(eX.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(eX.BUFFER_CODECS,this.onBufferCodecs,this),e.on(eX.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(eX.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(eX.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(eX.MANIFEST_PARSED,this.onManifestParsed,this),e.off(eX.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(eX.BUFFER_CODECS,this.onBufferCodecs,this),e.off(eX.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let 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){let i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&eV(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}let e=this.hls.levels;if(e.length){let 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){let t=this.hls.levels;if(!t.length)return -1;let i=t.filter((t,i)=>this.isLevelAllowed(t)&&i<=e);return this.clientRect=null,af.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=1/0,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=1/0,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,t.width||t.height||(t.width=i.right-i.left||e.
16width||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(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,i){if(!(null!=e&&e.length))return -1;let s=(e,t)=>!t||e.width!==t.width||e.height!==t.height,r=e.length-1,a=Math.max(t,i);for(let t=0;t<e.length;t+=1){let i=e[t];if((i.width>=a||i.height>=a)&&s(i,e[t+1])){r=t;break}}return r}}class ag{constructor(e,t){Array.isArray(e)&&(e=e.map(e=>e instanceof ag?e:new ag(e))),this.value=e,this.params=t}}function am(e,t,i){return Error(`failed to serialize "${Array.isArray(e)?JSON.stringify(e):e instanceof Map?"Map{}":e instanceof Set?"Set{}":"object"==typeof e?JSON.stringify(e):String(e)}" as ${t}`,{cause:i})}class ap{constructor(e){this.description=e}}let ay="Bare Item";function av(e){if(e<-0x38d7ea4c67fff||0x38d7ea4c67fff<e)throw am(e,"Integer");return e.toString()}let aT=/[\x00-\x1f\x7f]+/;function aE(e){let t=e.description||e.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw am(t,"Token");return t}function aS(e){switch(typeof e){case"number":if(!eV(e))throw am(e,ay);if(Number.isInteger(e))return av(e);let t=function e(t,i){if(t<0)return-e(-t,i);let s=Math.pow(10,i);if(!(Math.abs(t*s%1-.5)<Number.EPSILON))return Math.round(t*s)/s;{let e=Math.floor(t*s);return(e%2==0?e:e+1)/s}}(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw am(e,"Decimal");let i=t.toString();return i.includes(".")?i:`${i}.0`;case"string":if(aT.test(e))throw am(e,"String");return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;case"symbol":return aE(e);case"boolean":if("boolean"!=typeof e)throw am(e,"Boolean");return e?"?1":"?0";case"object":if(e instanceof Date)return`@${av(e.getTime()/1e3)}`;if(e instanceof Uint8Array){if(!1===ArrayBuffer.isView(e))throw am(e,"Byte Sequence");return`:${btoa(String.fromCharCode(...e))}:`}if(e instanceof ap)return aE(e);default:throw am(e,ay)}}function aL(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw am(e,"Key");return e}function ak(e){return null==e?"":Object.entries(e).map(([e,t])=>!0===t?`;${aL(e)}`:`;${aL(e)}=${aS(t)}`).join("")}function aA(e){return e instanceof ag?`${aS(e.value)}${ak(e.params)}`:aS(e)}function aR(e,t){return function(e,t={whitespace:!0}){if("object"!=typeof e||null==e)throw am(e,"Dict");let i=e instanceof Map?e.entries():Object.entries(e),s=(null==t?void 0:t.whitespace)?" ":"";return Array.from(i).map(([e,t])=>{t instanceof ag==!1&&(t=new ag(t));let i=aL(e);if(!0===t.value)i+=ak(t.params);else if(i+="=",Array.isArray(t.value)){var s;i+=(s=t,`(${s.value.map(aA).join(" ")})${ak(s.params)}`)}else i+=aA(t);return i}).join(`,${s}`)}(e,t)}let ab="CMCD-Object",aI="CMCD-Request",a_="CMCD-Session",aC="CMCD-Status",aD={br:ab,ab:ab,d:ab,ot:ab,tb:ab,tpb:ab,lb:ab,tab:ab,lab:ab,url:ab,pb:aI,bl:aI,tbl:aI,dl:aI,ltc:aI,mtp:aI,nor:aI,nrr:aI,rc:aI,sn:aI,sta:aI,su:aI,ttfb:aI,ttfbb:aI,ttlb:aI,cmsdd:aI,cmsds:aI,smrt:aI,df:aI,cs:aI,ts:aI,cid:a_,pr:a_,sf:a_,sid:a_,st:a_,v:a_,msd:a_,bs:aC,bsd:aC,cdn:aC,rtp:aC,bg:aC,pt:aC,ec:aC,e:aC},aP="event",ax=e=>Math.round(e),aF=(e,t)=>Array.isArray(e)?e.map(e=>aF(e,t)):e instanceof ag&&"string"==typeof e.value?new ag(aF(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){let i=new URL(e),s=new URL(t);if(i.origin!==s.origin)return e;let r=i.pathname.split("/").slice(1),a=s.pathname.split("/").slice(1,-1);for(;r[0]===a[0];)r.shift(),a.shift();for(;a.length;)a.shift(),r.unshift("..");return r.join("/")+i.search+i.hash}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e),aw=e=>100*ax(e/100),aM={br:ax,d:ax,bl:aw,dl:aw,mtp:aw,nor:(e,t)=>{let i=e;return t.version>=2&&(e instanceof ag&&"string"==typeof e.value?i=new ag([e]):"string"==typeof e&&(i=[e])),aF(i,t)},rtp:aw,tb:ax}
16,aO="request",aN="response",aB=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],aU=["e"],a$=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function aK(e){return a$.test(e)}let aG=["d","dl","nor","ot","rtp","su"],aj=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],aH=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function aV(e){return aH.includes(e)||aK(e)}let aW={[aN]:function(e){return aB.includes(e)||aG.includes(e)||aj.includes(e)||aK(e)},[aP]:function(e){return aB.includes(e)||aU.includes(e)||aK(e)},[aO]:function(e){return aB.includes(e)||aG.includes(e)||aK(e)}};function aY(e,t={}){let i={};if(null==e||"object"!=typeof e)return i;let s=t.version||e.v||1,r=t.reportingMode||aO,a=1===s?aV:aW[r],n=Object.keys(e).filter(a),l=t.filter;"function"==typeof l&&(n=n.filter(l));let o=r===aN||r===aP;o&&!n.includes("ts")&&n.push("ts"),s>1&&!n.includes("v")&&n.push("v");let d=e8({},aM,t.formatters),h={version:s,reportingMode:r,baseUrl:t.baseUrl};return n.sort().forEach(t=>{var r;let a=e[t],n=d[t];if("function"==typeof n&&(a=n(a,h)),"v"===t)if(1===s)return;else a=s;("pr"!=t||1!==a)&&(o&&"ts"===t&&!eV(a)&&(a=Date.now()),("number"==typeof(r=a)?eV(r):null!=r&&""!==r&&!1!==r)&&(["ot","sf","st","e","sta"].includes(t)&&"string"==typeof a&&(a=new ap(a)),i[t]=a))}),i}let aq=/CMCD=[^&#]+/;function az(e,t,i,s){e&&Object.keys(t).forEach(r=>{let a=e.filter(e=>e.groupId===r).map(e=>{let a=e8({},e);return a.details=void 0,a.attrs=new iX(a.attrs),a.url=a.attrs.URI=aX(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),a.groupId=a.attrs["GROUP-ID"]=t[r],a.attrs["PATHWAY-ID"]=s,a});e.push(...a)})}function aX(e,t,i,s){let r,{HOST:a,PARAMS:n,[i]:l}=s;t&&(r=null==l?void 0:l[t])&&(e=r);let o=new self.URL(e);return a&&!r&&(o.host=a),n&&Object.keys(n).sort().forEach(e=>{e&&o.searchParams.set(e,n[e])}),o.href}class aQ extends e7{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=aQ.CDMCleanupPromise?[aQ.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=e=>{let{initDataType:t,initData:i}=e,s=`"${e.type}" event: init data type: "${t}"`;if(this.debug(s),null!==i){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=so(this.config));let t=e.map(sl).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(r=>{let a,n=sn(r);if("sinf"!==t||n!==i7)return void this.log(`Ignoring "${e.type}" event with init data type: "${t}" for selected key-system ${n}`);try{let e=tL(new Uint8Array(i)),t=i3(JSON.parse(e).sinf),s=tw(t);if(!s)throw Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(s.subarray(8,24))}catch(e){this.warn(`${s} Failed to parse sinf: ${e}`);return}let l=to(a),{keyIdToKeySessionPromise:o,mediaKeySessions:d}=this,h=o[l];for(let e=0;e<d.length;e++){let s=d[e],r=s.decryptdata;if(!r.keyId)continue;let n=to(r.keyId);if(iJ(a,r.keyId)||-1!==r.uri.replace(/-/g,"").indexOf(l)){if(!(h=o[n]))continue;if(r.pssh)break;delete o[n],r.pssh=new Uint8Array(i),r.keyId=a,(h=o[l]=h.then(()=>this.generateRequestWithPreferredKeySession(s,t,i,"encrypted-event-key-match"))).catch(e=>this.handleError(e));break}}h||this.handleError(Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${d.length}.`))}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}
16registerListeners(){this.hls.on(eX.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(eX.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(eX.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(eX.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(eX.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(eX.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(eX.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(eX.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(eX.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(eX.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:i}=this.config,s=null==t?void 0:t[e];return s?s.licenseUrl:e===st&&i?i:void 0}getLicenseServerUrlOrThrow(e){let t=this.getLicenseServerUrl(e);if(void 0===t)throw Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){let{drmSystems:t}=this.config,i=null==t?void 0:t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,i=(e,t,i)=>!!e&&i.indexOf(e)===t,s=t.map(e=>e.audioCodec).filter(i),r=t.map(e=>e.videoCodec).filter(i);return s.length+r.length===0&&r.push("avc1.42e01e"),new Promise((t,i)=>{let a=e=>{let n=e.shift();this.getMediaKeysPromise(n,s,r).then(e=>t({keySystem:n,mediaKeys:e})).catch(t=>{e.length?a(e):t instanceof aJ?i(t):i(new aJ({type:eq.KEY_SYSTEM_ERROR,details:ez.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};a(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let e=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===sd&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(Error(e))}return i(e,t)}getMediaKeysPromise(e,t,i){var s;let r=function(e,t,i,s){var r,a,n,l;let o;switch(e){case i7:o=["cenc","sinf"];break;case st:case se:o=["cenc"];break;case i9:o=["cenc","keyids"];break;default:throw Error(`Unknown key-system: ${e}`)}return r=o,a=t,n=i,[{initDataTypes:r,persistentState:(l=s).persistentState||"optional",distinctiveIdentifier:l.distinctiveIdentifier||"optional",sessionTypes:l.sessionTypes||[l.sessionType||"temporary"],audioCapabilities:a.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:l.audioRobustness||"",encryptionScheme:l.audioEncryptionScheme||null})),videoCapabilities:n.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:l.videoRobustness||"",encryptionScheme:l.videoEncryptionScheme||null}))}]}(e,t,i,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],n=null==(s=a)?void 0:s.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${e}" key-system access with config: ${it(r)}`),n=this.requestMediaKeySystemAccess(e,r);let t=a=this.keySystemAccessPromises[e]={keySystemAccess:n};return n.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),n.then(i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);let s=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let r=t.mediaKeys=i.createMediaKeys().then(i=>(this.log(`Media-keys created for "${e}"`),t.hasMediaKeys=!0,s.then(t=>t?this.setMediaKeysServerCertificate(i,e,t):i)));return r.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),r})}return n.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${to(e.keyId||[])} keyUri: ${e.uri}`);let s=i.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let i=this.createMediaKeySessionContext(e),s=aZ(t);this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,"cenc",t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){let i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${to(e.decryptdata.keyId||[])}
17      } (data length: ${t.byteLength})`),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>sl(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return new Promise((t,i)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{let s=sl(e);s?t(s):i(Error(`Unable to find format for key-system "${e}"`))}).catch(i)})}selectKeySystemFormat(e){let 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){let t=so(this.config),i=e.map(sn).filter(e=>!!e&&-1!==t.indexOf(e));return this.selectKeySystem(i)}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let r=0;r<t.length;r++){var i,s;let a=(i=e,s=t[r],i.keyId&&s.mediaKeysSession.keyStatuses.has(i.keyId)?s.mediaKeysSession.keyStatuses.get(i.keyId):i.matches(s.decryptdata)?s.keyStatus:void 0);if(a)return a}}loadKey(e){let t=e.keyInfo.decryptdata,i=aZ(t),s=this.bannedKeyIds[i];if(s||"internal-error"===this.getKeyStatus(t)){let i=a0(s||"internal-error",t);return this.handleError(i,e.frag),Promise.reject(i)}let r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let a=this.keyIdToKeySessionPromise[i];if(!a){let s=this.getKeySystemForKeyPromise(t).then(({keySystem:i,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(i,s).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:i,mediaKeys:s,decryptdata:t}))))).then(e=>{let i=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,"cenc",i,"playlist-key")});return s.catch(t=>this.handleError(t,e.frag)),this.keyIdToKeySessionPromise[i]=s,s}return a.catch(i=>{if(i instanceof aJ){let s=e9({},i.data);"internal-error"===this.getKeyStatus(t)&&(s.decryptdata=t);let r=new aJ(s,i.message);this.handleError(r,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof aJ){t&&(e.data.frag=t);let i=e.data.decryptdata;this.error(`${e.message}${i?` (${to(i.keyId||[])})`:""}`),this.hls.trigger(eX.ERROR,e.data)}else this.error(e.message),this.hls.trigger(eX.ERROR,{type:eq.KEY_SYSTEM_ERROR,details:ez.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}
17getKeySystemForKeyPromise(e){let t=aZ(e),i=this.keyIdToKeySessionPromise[t];if(!i){let t=sn(e.keyFormat),i=t?[t]:so(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=so(this.config)),0===e.length)throw new aJ({type:eq.KEY_SYSTEM_ERROR,details:ez.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${it({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let s=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((e,i)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return i(Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(e).catch(i)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(e=>-1===i.indexOf(e))})}generateRequestWithPreferredKeySession(e,t,i,s){var r;let a=null==(r=this.config.drmSystems)||null==(r=r[e.keySystem])?void 0:r.generateRequest;if(a)try{let s=a.call(this.hls,t,i,e);if(!s)throw Error("Invalid response from configured generateRequest filter");t=s.initDataType,i=s.initData?s.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(null===i)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e);let n=aZ(e.decryptdata),l=e.decryptdata.uri;this.log(`Generating key-session request for "${s}" keyId: ${n} URI: ${l} (init data type: ${t} length: ${i.byteLength})`);let o=new rt,d=e._onmessage=t=>{let i=e.mediaKeysSession;if(!i)return void o.emit("error",Error("invalid state"));let{messageType:s,message:r}=t;this.log(`"${s}" message event for session "${i.sessionId}" message size: ${r.byteLength}`),"license-request"===s||"license-renewal"===s?this.renewLicense(e,r).catch(e=>
17{o.eventNames().length?o.emit("error",e):this.handleError(e)}):"license-release"===s?e.keySystem===i7&&this.updateKeySession(e,i4("acknowledged")).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${s}"`)},h=(e,t)=>{let i;t.keyStatus=e,e.startsWith("usable")?o.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?i=a0(e,t.decryptdata):"expired"===e?i=Error(`key expired (keyId: ${n})`):"released"===e?i=Error("key released"):"status-pending"===e||this.warn(`unhandled key status change "${e}" (keyId: ${n})`),i&&(o.eventNames().length?o.emit("error",i):this.handleError(i))},u=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void o.emit("error",Error("invalid state"));let i=this.getKeyStatuses(e);if(!Object.keys(i).some(e=>"status-pending"!==i[e]))return;if("expired"===i[n]){this.log(`Expired key ${it(i)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let s=i[n];if(s)h(s,e);else{var r;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(r=e.keyStatusTimeouts)[n]||(r[n]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;let t=this.getKeyStatus(e.decryptdata);if(t&&"status-pending"!==t)return this.log(`No status for keyId ${n} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${t} from other session.`),h(t,e);this.log(`key status for ${n} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),h(s="internal-error",e)},1e3)),this.log(`No status for keyId ${n} (${it(i)}).`)}};sW(e.mediaKeysSession,"message",d),sW(e.mediaKeysSession,"keystatuseschange",u);let c=new Promise((e,t)=>{o.on("error",t),o.on("resolved",e)});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${n} URI: ${l}`)}).catch(t=>{throw new aJ({type:eq.KEY_SYSTEM_ERROR,details:ez.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>c).catch(t=>(o.removeAllListeners(),this.removeSession(e).then(()=>{throw t}))).then(()=>(o.removeAllListeners(),e))}getKeyStatuses(e){let t={};return e.mediaKeysSession.keyStatuses.forEach((i,s)=>{if("string"==typeof s&&"object"==typeof i){let e=s;s=i,i=e}let r="buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s);e.keySystem===se&&16===r.length&&(t[to(r)]=i,i5(r));let a=to(r);"internal-error"===i&&(this.bannedKeyIds[a]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=i}),t}fetchServerCertificate(e){let t=this.config,i=new t.loader(t),s=this.getServerCertificateUrl(e);return s?(this.log(`Fetching server certificate for "${e}"`),new Promise((r,a)=>{let n={responseType:"arraybuffer",url:s},l=t.certLoadPolicy.default,o={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};i.load(n,o,{onSuccess:(e,t,i,s)=>{r(e.data)},onError:(t,i,r,l)=>{a(new aJ({type:eq.KEY_SYSTEM_ERROR,details:ez.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:e9({url:n.url,data:void 0},t)},`"${e}" certificate request failed (${s}). Status: ${t.code} (${t.text})`))},onTimeout:(t,i,r)=>{a(new aJ({type:eq.KEY_SYSTEM_ERROR,details:ez.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:n.url,data:void 0}},`"${e}" certificate request timed out (${s})`))},onAbort:(e,t,i)=>{a(Error("aborted"))}})})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((s,r)=>{e.setServerCertificate(i).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),s(e)}).catch(e=>{r(new aJ({type:eq.KEY_SYSTEM_ERROR,details:ez.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(t=>this.updateKeySession(e,new Uint8Array(t)).catch(t=>{throw new aJ({type:eq.KEY_SYSTEM_ERROR,details:ez.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(e,t){let i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let s=new DOMParser().parseFromString(i,"application/xml"),r=s.querySelectorAll("HttpHeader");if(r.length>0){let t;for(let i=0,s=r.length;i<s;i++){var a,n;let s=null==(a=(t=r[i]).querySelector("name"))?void 0:a.textContent,l=null==(n=t.querySelector("value"))?void 0:n.textContent;s&&l&&e.setRequestHeader(s,l)}}let l=s.querySelector("Challenge"),o=null==l?void 0:l.textContent;
17if(!o)throw Error("Cannot find <Challenge> in key message");return i4(atob(o))}setupLicenseXHR(e,t,i,s){let r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!i.decryptdata)throw Error("Key removed");return r.call(this.hls,e,t,i,s)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),r.call(this.hls,e,t,i,s)}).then(i=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:i||s})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:s}))}requestLicense(e,t){let i=this.config.keyLoadPolicy.default;return new Promise((s,r)=>{let a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);let n=new XMLHttpRequest;n.responseType="arraybuffer",n.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(Error("invalid state"));if(4===n.readyState)if(200===n.status){this._requestLicenseFailureCount=0;let t=n.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);let i=this.config.licenseResponseCallback;if(i)try{t=i.call(this.hls,n,a,e)}catch(e){this.error(e)}s(t)}else{let l=i.errorRetry,o=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>o||n.status>=400&&n.status<500)r(new aJ({type:eq.KEY_SYSTEM_ERROR,details:ez.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:n,response:{url:a,data:void 0,code:n.status,text:n.statusText}},`License Request XHR failed (${a}). Status: ${n.status} (${n.statusText})`));else{let i=o-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(e,t).then(s,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=n,this.setupLicenseXHR(n,a,e,t).then(({xhr:t,licenseChallenge:i})=>{e.keySystem==se&&(i=this.unpackPlayReadyKeyMessage(t,i)),t.send(i)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,sW(i,"encrypted",this.onMediaEncrypted),sW(i,"waitingforkey",this.onWaitingForKey);let s=this.mediaResolved;s?s():this.mediaKeys=i.mediaKeys}onMediaDetached(){let e=this.media;e&&(sY(e,"encrypted",this.onMediaEncrypted),sY(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};let t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let i=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,sc.clearKeyUriToKeyIdMap();let r=s.length;aQ.CDMCleanupPromise=Promise.all(s.map(e=>this.removeSession(e)).concat((null==i||null==(e=i.setMediaKeys(null))?void 0:e.catch(e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(eX.ERROR,{type:eq.OTHER_ERROR,details:ez.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:Error(`Could not clear media keys: ${e}`)})}))||Promise.resolve())).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(eX.ERROR,{type:eq.OTHER_ERROR,details:ez.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close sessions and clear media keys: ${e}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){let e=t.reduce((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:i,decryptdata:s}=e;if(t){var r;this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${to((null==s?void 0:s.keyId)||[])}`),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;let a=this.mediaKeySessions.indexOf(e);a>-1&&this.mediaKeySessions.splice(a,1);let{keyStatusTimeouts:n}=e;
17n&&Object.keys(n).forEach(e=>self.clearTimeout(n[e]));let{drmSystemOptions:l}=this.config;return(l&&("persistent-license"===l.sessionType||null!=(r=l.sessionTypes)&&r.some(e=>"persistent-license"===e))?new Promise((e,i)=>{self.setTimeout(()=>i(Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(e).catch(i)}):Promise.resolve()).catch(e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(eX.ERROR,{type:eq.OTHER_ERROR,details:ez.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:Error(`Could not remove session: ${e}`)})}).then(()=>t.close()).catch(e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(eX.ERROR,{type:eq.OTHER_ERROR,details:ez.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close session: ${e}`)})})}return Promise.resolve()}}function aZ(e){if(!e)throw Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw Error("keyId is null");return to(e.keyId)}aQ.CDMCleanupPromise=void 0;class aJ extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=Error(t)),this.data=e,e.err=e.error}}function a0(e,t){let i="output-restricted"===e,s=i?ez.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:ez.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new aJ({type:eq.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:t},i?"HDCP level output restricted":`key status changed to "${e}"`)}function a1(e,t){let i;try{i=new Event("addtrack")}catch(e){(i=document.createEvent("Event")).initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function a2(e,t){let i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw Error(`addCue is failed for: ${t}`)}catch(i){tr.debug(`[texttrack-utils]: ${i}`);try{let i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){tr.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===i&&(e.mode=i)}function a3(e,t){let i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues)for(let i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===i&&(e.mode=i)}function a4(e,t,i,s){let r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&e.cues.length>0){let r=function(e,t,i){let s=[],r=function(e,t){let i;if(t<=e[0].startTime)return 0;let s=e.length-1;if(t>e[s].endTime)return -1;let r=0,a=s;for(;r<=a;)if(t<e[i=Math.floor((a+r)/2)].startTime)a=i-1;else{if(!(t>e[i].startTime)||!(r<s))return i;r=i+1}return e[r].startTime-t<t-e[a].startTime?r:a}(e,t);if(r>-1)for(let a=r,n=e.length;a<n;a++){let r=e[a];if(r.startTime>=t&&r.endTime<=i)s.push(r);else if(r.startTime>i)break}return s}(e.cues,t,i);for(let t=0;t<r.length;t++)(!s||s(r[t]))&&e.removeCue(r[t])}"disabled"===r&&(e.mode=r)}function a5(e){let t=[];for(let i=0;i<e.length;i++){let s=e[i];("subtitles"===s.kind||"captions"===s.kind)&&s.label&&t.push(e[i])}return t}function a8(e){let t=5381,i=e.length;for(;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()}let a6=((p={})[p.Point=0]="Point",p[p.Range=1]="Range",p);class a9{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,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;let i=this.playoutLimit;return!(e<=0||isNaN(i))&&(0===i||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>i)}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return a7(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime,i=a7(t,e);return t-i<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=eV(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return a7(e,t)}return e}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&.025>Math.abs(this.resumeOffset-this.duration)))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){let e,t=this.playoutLimit;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?a6.Range:a6.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){var e;return e=this,`["${e.identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}}function a7(e,t){return e-t.start<t.duration/2&&!(.025>Math.abs(e-(t.start+t.duration)))?t.start:t.start+t.duration}function ne(e,t,i){let s=new self.URL(e,i);return"data:"!==s.protocol&&s.searchParams.set("_HLS_primary_id",t),s}function nt(e,t){for(;null!=(i=e.assetList[++t])&&i.error;)var i;return t}function ni(e){let t=e.timelineStart,i=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+i).toFixed(2)}]`}class ns{constructor(e,t,i,s){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetail
17s=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(eX.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=i,this.assetItem=s;const a=()=>{this.hasDetails=!0};r.once(eX.LEVEL_LOADED,a),r.once(eX.AUDIO_TRACK_LOADED,a),r.once(eX.SUBTITLE_TRACK_LOADED,a),r.on(eX.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t,this.interstitial.playoutLimit&&(t.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(eX.BUFFER_APPENDED,()=>{let e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,r.trigger(eX.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=ne(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e)return!1;let i=Math.min(this._bufferedEosTime||1/0,this.duration),s=this.timelineOffset,r=iH.bufferInfo(e,s,0);return this.getAssetTime(r.end)>=i-.02}reachedPlayout(e){let t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return(null==(e=this.hls)?void 0:e.media)||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=iH.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){let e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t&&Math.abs(e-t)>1/9e4&&this.hls){if(this.hasDetails)throw Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}getAssetTime(e){return Math.min(Math.max(0,e-this.timelineOffset),this.duration)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}resumeBuffering(){var e;null==(e=this.hls)||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.hls)||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var s;null==(s=this.hls)||s.on(e,t)}once(e,t,i){var s;null==(s=this.hls)||s.once(e,t)}off(e,t,i){var s;null==(s=this.hls)||s.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${ni(this.assetItem)} ${null==(e=this.hls)?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class nr extends e7{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={}
17,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(){let 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);let s=this.items;if(s)for(s[i]||(void 0===t&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&null!=(r=s[i])&&r.event;){var r;i--}return i}findItemIndexAtTime(e,t){let i=this.items;if(i)for(let s=0;s<i.length;s++){let r=i[s];if(t&&"primary"!==t&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return s}return -1}findJumpRestrictedIndex(e,t){let i=this.items;if(i)for(let s=e;s<=t&&i[s];s++){let e=i[s].event;if(null!=e&&e.restrictions.jump&&!e.appendInPlace)return s}return -1}findEventIndex(e){let t=this.items;if(t)for(let s=t.length;s--;){var i;if((null==(i=t[s].event)?void 0:i.identifier)===e)return s}return -1}findAssetIndex(e,t){let i=e.assetList,s=i.length;if(s>1)for(let e=0;e<s;e++){let r=i[e];if(!r.error){let i=r.timelineStart;if(t===i||t>i&&(t<i+(r.duration||0)||e===s-1))return e}}return 0}get assetIdAtEnd(){var e;let t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){let e=t.assetList,i=e[e.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){let i=e.main.details,{dateRanges:s}=i,r=this.events,a=this.parseDateRanges(s,{url:i.url},t),n=Object.keys(s),l=r?r.filter(e=>!n.includes(e.identifier)):[];a.length&&a.sort((e,t)=>{let i=e.cue.pre,s=e.cue.post,r=t.cue.pre,a=t.cue.post;if(i&&!r)return -1;if(r&&!i||s&&!a)return 1;if(a&&!s)return -1;if(!i&&!r&&!s&&!a){let i=e.startTime,s=t.startTime;if(i!==s)return i-s}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=a,l.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,l)}updateSchedule(e,t=[],i=!1){let s=this.events||[];
17if(s.length||t.length||this.length<2){let r=this.items,a=this.parseSchedule(s,e);(i||t.length||(null==r?void 0:r.length)!==a.length||a.some((e,t)=>Math.abs(e.playout.start-r[t].playout.start)>.005||Math.abs(e.playout.end-r[t].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,i){let s=[],r=Object.keys(e);for(let a=0;a<r.length;a++){let n=r[a],l=e[n];if(l.isInterstitial){let e=this.eventMap[n];e?e.setDateRange(l):(e=new a9(l,t),this.eventMap[n]=e,!1===i&&(e.appendInPlace=i)),s.push(e)}}return s}parseSchedule(e,t){let i=[],s=t.main.details,r=s.live?1/0:s.edge,a=0;if((e=e.filter(e=>!e.error&&!(e.cue.once&&e.hasPlayed))).length){this.resolveOffsets(e,t);let s=0,l=0;if(e.forEach((t,n)=>{let o=t.cue.pre,d=t.cue.post,h=e[n-1]||null,u=t.appendInPlace,c=d?r:t.startOffset,f=t.duration,g=t.timelineOccupancy===a6.Range?f:0,m=t.resumptionOffset,p=(null==h?void 0:h.startTime)===c,y=c+t.cumulativeDuration,v=u?y+f:c+m;if(o||!d&&c<=0){let e=l;l+=g,t.timelineStart=y;let s=a;a+=f,i.push({event:t,start:y,end:v,playout:{start:s,end:a},integrated:{start:e,end:l}})}else{if(!(c<=r))return;if(!p){let r=c-s;if(r>.033){let o=s,d=l;l+=r;let h=a;a+=r;let u={previousEvent:e[n-1]||null,nextEvent:t,start:o,end:o+r,playout:{start:h,end:a},integrated:{start:d,end:l}};i.push(u)}else r>0&&h&&(h.cumulativeDuration+=r,i[i.length-1].end=c)}d&&(v=y),t.timelineStart=y;let o=l;l+=g;let u=a;a+=f,i.push({event:t,start:y,end:v,playout:{start:u,end:a},integrated:{start:o,end:l}})}let T=t.resumeTime;s=d||T>r?r:T}),s<r){var n;let e=s,t=l,o=r-s;l+=o;let d=a;a+=o,i.push({previousEvent:(null==(n=i[i.length-1])?void 0:n.event)||null,nextEvent:null,start:s,end:e+o,playout:{start:d,end:a},integrated:{start:t,end:l}})}this.setDurations(r,a,l)}else i.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return i}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){let i=t.main.details,s=i.live?1/0:i.edge,r=0,a=-1;e.forEach((n,l)=>{let o=n.cue.pre,d=n.cue.post,h=o?0:d?s:n.startTime;this.updateAssetDurations(n),a===h?n.cumulativeDuration=r:(r=0,a=h),!d&&n.snapOptions.in&&(n.resumeAnchor=ic(null,i.fragments,n.startOffset+n.resumptionOffset,0,0)||void 0),n.appendInPlace&&!n.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(n,t)||(n.appendInPlace=!1)),!n.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<.033&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${n}`));let u=eV(n.resumeOffset)?n.resumeOffset:n.duration;r+=u})}primaryCanResumeInPlaceAt(e,t){let i=e.resumeTime,s=e.startTime+e.resumptionOffset;return Math.abs(i-s)>.025?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1):!Object.keys(t).some(s=>{let r=t[s].details,a=r.edge;if(i>=a)return this.log(`"${e.identifier}" resumption ${i} past ${s} playlist end ${a}`),!1;let n=ic(null,r.fragments,i);if(!n)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${s} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;let l=.175*("audio"===s);return!(Math.abs(n.start-i)<.025+l||Math.abs(n.end-i)<.025+l)&&(this.log(`"${e.identifier}" resumption ${i} not aligned with ${s} fragment bounds (${n.start}-${n.end} sn: ${n.sn} cc: ${n.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,i=0,s=!1,r=!1;for(let a=0;a<e.assetList.length;a++){let n=e.assetList[a],l=t+i;n.startOffset=i,n.timelineStart=l,s||(s=null===n.duration),r||(r=!!n.error),i+=n.error?0:n.duration||0}s&&!r?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function na(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}class nn{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let i,s=e.assetListUrl;try{i=ne(s,this.hls.sessionId,e.baseUrl)}catch(i){let t=this.assignAssetListError(e,ez.ASSET_LIST_LOAD_ERROR,i,s);this.hls.trigger(eX.ERROR,t);return}t&&"data:"!==i.protocol&&i.searchParams.set("_HLS_start_offset",""+t);let r=this.hls.config,a=new r.loader(r),n={responseType:"json",url:i.href},l=r.interstitialAssetListLoadPolicy.default,o={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};return a.load(n,o,{onSuccess:(t,i,s,r)=>{let a=t.data;if(!Array.isArray(null==a?void 0:a.ASSETS)){let t=this.assignAssetListError(e,ez.ASSET_LIST_PARSING_ERROR,Error("Invalid interstitial asset list"),s.url,i,r);this.hls.trigger(eX.ERROR,t);return}e.assetListResponse=a,this.hls.trigger(eX.ASSET_LIST_LOADED,{event:e,assetListResponse:a,networkDetails:r})},onError:(t,i,s,r)=>{let a=this.assignAssetListError(e,ez.ASSET_LIST_LOAD_ERROR,Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${i.url})`),i.url,r,s);this.hls.trigger(eX.ERROR,a)},onTimeout:(t,i,s)=>{let r=this.assignAssetListError(e,ez.ASSET_LIST_LOAD_TIMEOUT,Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,t,s);this.hls.trigger(eX.ERROR,r)}}),this.hls.trigger(eX.ASSET_LIST_LOADING,{event:e}),a}assignAssetListError(e,t,i,s,r,a){return e.error=i,{type:eq.NETWORK_E
17RROR,details:t,fatal:!1,interstitial:e,url:s,error:i,networkDetails:a,stats:r}}}function nl(e){var t;null==e||null==(t=e.play())||t.catch(()=>{})}function no(e,t){return`[${e}] Advancing timeline position to ${t}`}class nd{constructor(e){this.buffered=void 0;const t=(t,i,s)=>{if((i>>>=0)>s-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${s})`);return e[i][t]};this.buffered={get length(){return e.length},end:i=>t("end",i,e.length),start:i=>t("start",i,e.length)}}}let nh={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},nu=e=>String.fromCharCode(nh[e]||e),nc={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},nf={17:2,18:4,21:6,22:8,23:10,19:13,20:15},ng={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},nm={25:2,26:4,29:6,30:8,31:10,27:13,28:15},np=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class ny{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let i="function"==typeof t?t():t;tr.log(`${this.time} [${e}] ${i}`)}}}let nv=function(e){let t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class nT{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){let t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){let s=t[i];e.hasOwnProperty(s)&&(this[s]=e[s])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class nE{constructor(){this.uchar=" ",this.penState=new nT}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class nS{constructor(e){this.chars=[],this.pos=0,this.currPenState=new nT,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<100;e++)this.chars.push(new nE);this.logger=e}equals(e){for(let t=0;t<100;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<100;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<100;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>100&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=100)}moveCursor(e){let t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();let t=nu(e);this.pos>=100?this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<100;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){let e=[],t=!0;for(let i=0;i<100;i++){let s=this.chars[i].uchar;" "!==s&&(t=!1),e.push(s)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class nL{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<15;t++)this.rows.push(new nS(e));this.logger=e}reset(){for(let e=0;e<15;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let i=0;i<15;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<15;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<15;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+it(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<15;e++)this.rows[e].clear();let e=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){let s=i.rows[e].cueStartTime,r=this.logger.time;if(null!==s&&null!==r&&s<r)for(let s=0;s<this.nrRollUpRows;s++)this.rows[t-this.nrRollUpRows+s+1].copy(i.rows[e+s])}}this.currRow=t;let i=this.rows[this.currRow];if(null!==e.indent){let t=Math.max(e.indent-1,0);i.setCursor(e.indent),e.color=i.chars[t].penState.foreground}let s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+it(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());let 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;let t=[],i="",s=-1;for(let i=0;i<15;i++){let r=this.rows[i].getTextString();r&&(s=i+1,e?t.push("Row "+s+": '"+r+"'"):t.push(r.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i}getTextAndFormat(){return this.rows}}class nk{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 nL(i),this.nonDisplayedMemory=new nL(i),this.lastOutputScreen=new nL(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(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),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);let t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),("MODE_PAINT-ON"===this.mode||"MODE_ROLL-UP"===this.mode)&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(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})}
17ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){let 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){let t={flash:!1};(t.underline=e%2==1,t.italics=e>=46,t.italics)?t.foreground="white":t.foreground=["white","green","blue","cyan","red","yellow","magenta"][Math.floor(e/2)-16],this.logger.log(2,"MIDROW: "+it(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?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.cueStartTime=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 nA{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const s=this.logger=new ny;this.channels=[null,new nk(e,t,s),new nk(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 e=0;e<t.length;e+=2){var i,s,r,a,n,l,o,d;let h=127&t[e],u=127&t[e+1],c=!1,f=null;if(0===h&&0===u)continue;this.logger.log(3,()=>"["+nv([t[e],t[e+1]])+"] -> ("+nv([h,u])+")");let g=this.cmdHistory;if(h>=16&&h<=31){if(i=h,s=u,(r=g).a===i&&r.b===s){(a=g).a=null,a.b=null,this.logger.log(3,()=>"Repeated command ("+nv([h,u])+") is dropped");continue}n=h,l=u,(o=this.cmdHistory).a=n,o.b=l,(c=this.parseCmd(h,u))||(c=this.parseMidrow(h,u)),c||(c=this.parsePAC(h,u)),c||(c=this.parseBackgroundAttributes(h,u))}else{(d=g).a=null,d.b=null}if(!c&&(f=this.parseChars(h,u))){let e=this.currentChannel;e&&e>0?this.channels[e].insertChars(f):this.logger.log(2,"No channel found yet. TEXT-MODE?")}c||f||this.logger.log(2,()=>"Couldn't parse cleaned data "+nv([h,u])+" orig: "+nv([t[e],t[e+1]]))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;let i=20===e||21===e||23===e?1:2,s=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?s.ccRCL():33===t?s.ccBS():34===t?s.ccAOF():35===t?s.ccAON():36===t?s.ccDER():37===t?s.ccRU(2):38===t?s.ccRU(3):39===t?s.ccRU(4):40===t?s.ccFON():41===t?s.ccRDC():42===t?s.ccTR():43===t?s.ccRTD():44===t?s.ccEDM():45===t?s.ccCR():46===t?s.ccENM():47===t&&s.ccEOC():s.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let i=0;if((17===e||25===e)&&t>=32&&t<=47){if((i=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let s=this.channels[i];return!!s&&(s.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+nv([e,t])+")"),!0)}return!1}parsePAC(e,t){let i,s=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(16===e||24===e)&&t>=64&&t<=95;if(!(s||r))return!1;let a=e<=23?1:2;i=t>=64&&t<=95?1===a?nc[e]:ng[e]:1===a?nf[e]:nm[e];let n=this.channels[a];return!!n&&(n.setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!0)}interpretPAC(e,t){let i,s={color:null,italics:!1,indent:null,underline:!1,row:e};return s.underline=(1&(i=t>95?t-96:t-64))==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=4*Math.floor((i-16)/2),s}parseChars(e,t){let i,s=null,r=null;if(e>=25?(i=2,r=e-8):(i=1,r=e),r>=17&&r<=19){let e;e=17===r?t+80:18===r?t+112:t+144,this.logger.log(2,()=>"Special char '"+nu(e)+"' in channel "+i),s=[e]}else e>=32&&e<=127&&(s=0===t?[e]:[e,t]);return s&&this.logger.log(3,()=>"Char codes =  "+nv(s).join(",")),s}
17parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=45&&t<=47))return!1;let i={};return 16===e||24===e?(i.background=np[Math.floor((t-32)/2)],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0)),this.channels[e<=23?1:2].setBkgData(i),!0}reset(){var e;for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}(e=this.cmdHistory).a=null,e.b=null}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let i=this.channels[t];i&&i.cueSplitAtTime(e)}}}var nR=function(){if(null!=i6&&i6.VTTCue)return self.VTTCue;let e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t||!Array.isArray(e))return!1;let i=t.toLowerCase();return!!~e.indexOf(i)&&i}function s(e){let t=1;for(;t<arguments.length;t++){let i=arguments[t];for(let t in i)e[t]=i[t]}return e}function r(r,a,n){let l={enumerable:!0};this.hasBeenReset=!1;let o="",d=!1,h=r,u=a,c=n,f=null,g="",m=!0,p="auto",y="start",v=50,T="middle",E=50,S="middle";Object.defineProperty(this,"id",s({},l,{get:function(){return o},set:function(e){o=""+e}})),Object.defineProperty(this,"pauseOnExit",s({},l,{get:function(){return d},set:function(e){d=!!e}})),Object.defineProperty(this,"startTime",s({},l,{get:function(){return h},set:function(e){if("number"!=typeof e)throw TypeError("Start time must be set to a number.");h=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"endTime",s({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw TypeError("End time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"text",s({},l,{get:function(){return c},set:function(e){c=""+e,this.hasBeenReset=!0}})),Object.defineProperty(this,"region",s({},l,{get:function(){return f},set:function(e){f=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"vertical",s({},l,{get:function(){return g},set:function(t){let s=i(e,t);if(!1===s)throw SyntaxError("An invalid or illegal string was specified.");g=s,this.hasBeenReset=!0}})),Object.defineProperty(this,"snapToLines",s({},l,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(this,"line",s({},l,{get:function(){return p},set:function(e){if("number"!=typeof e&&"auto"!==e)throw SyntaxError("An invalid number or illegal string was specified.");p=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"lineAlign",s({},l,{get:function(){return y},set:function(e){let s=i(t,e);if(!s)throw SyntaxError("An invalid or illegal string was specified.");y=s,this.hasBeenReset=!0}})),Object.defineProperty(this,"position",s({},l,{get:function(){return v},set:function(e){if(e<0||e>100)throw Error("Position must be between 0 and 100.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"positionAlign",s({},l,{get:function(){return T},set:function(e){let s=i(t,e);if(!s)throw SyntaxError("An invalid or illegal string was specified.");T=s,this.hasBeenReset=!0}})),Object.defineProperty(this,"size",s({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw Error("Size must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"align",s({},l,{get:function(){return S},set:function(e){let s=i(t,e);if(!s)throw SyntaxError("An invalid or illegal string was specified.");S=s,this.hasBeenReset=!0}})),this.displayState=void 0}return r.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},r}();class nb{decode(e,t){if(!e)return"";if("string"!=typeof e)throw Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function nI(e){function t(e,t,i,s){return(0|e)*3600+(0|t)*60+(0|i)+parseFloat(s||0)}let i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}class n_{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<i.length;++s)if(t===i[s]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}function nC(e,t,i,s){let r=s?e.split(s):[e];for(let e in r){if("string"!=typeof r[e])continue;let s=r[e].split(i);if(2===s.length)t(s[0],s[1])}}let nD=new nR(0,0,""),nP="middle"===nD.align?"middle":"center";function nx(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class nF{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new nb,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;function i(){let e=t.buffer,i=0;for(e=nx(e);i<e.length&&"\r"!==e[i]&&"\n"!==e[i];)++i;let s=e.slice(0,i);return"\r"===e[i]&&++i,"\n"===e[i]&&++i,t.buffer=e.slice(i),s}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;let s=(e=i()).match(/^()?WEBVTT([ \t].*)?$/);if(!(null!=s&&s[0]))throw Error("Malformed WebVTT signature.");t.state="HEADER"}let r=!1;for(;t.buffer&&/\r\n|\n/.test(t.buffer);)switch(r?r=!1:e=i(),t.state){case"HEADER":if(/:/.test(e)){var s;s=e,nC(s,function(e,t){},/:/)}else e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new nR(0,0,""),t.state="CUE",-1===e.indexOf("-->")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{!function(e,t,i){var s;let r,a,n,l=e;function o(){let t=nI(e);if(null===t)throw Error("Malformed timestamp: "+l);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function d(){e=e.replace(/^\s+/,"")}if(d(),t.startTime=o(),d(),"-->"!==e.slice(0,3))throw Error("Malformed time stamp (time stamps must be separated by '-->'): "+l);e=e.slice(3),d(),t.endTime=o(),d(),s=e,r=new n_,nC(s,function(e,t){let s;switch(e){case"region":for(let s=i.length-1;s>=0;s--)if(i[s].id===t){r.set(e,i[s].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":s=t.split(","),r.integer(e,s[0]),r.percent(e,s[0])&&r.set("snapToLines",!1),r.alt(e,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",nP,"end"]);break;case"position":s=t.split(","),r.percent(e,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",nP,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",nP,"end","left","right"])}},/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical",""),"auto"===(a=r.get("line","auto"))&&-1===nD.line&&(a=-1),t.line=a,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",nP),"auto"===(n=r.get("position","auto"))&&50===nD.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{let i=-1!==e.indexOf("-->");if(!e||i&&(r=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){try{if((this.cue||"HEADER"===this.state)&&(this.buffer+="\n\n",this.parse()),"INITIAL"===this.state||"BADWEBVTT"===this.state)throw Error("Malformed WebVTT signature.")}catch(e){this.onparsingerror&&this.onparsingerror(e)}return this.onflush&&this.onflush(),this}}let nw=/\r\n|\n\r|\n|\r/g,nM=function(e,t,i=0){return e.slice(i,i+t.length)===t},nO=function(e){let t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),s=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!eV(t)||!eV(i)||!eV(s)||!eV(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=6e4*s,t+=36e5*r};function nN(e,t,i){return a8(e.toString())+a8(t.toString())+a8(i)}let nB=function(e,t,i){let s=e[t],r=e[s.prevCC];if(!r||!r.new&&s.new){e.ccOffset=e.presentationOffset=s.start,s.new=!1;return}for(;null!=(a=r)&&a.new;){var a;e.ccOffset+=s.start-r.start,s.new=!1,r=e[(s=r).prevCC]}e.presentationOffset=i},nU="stpp.ttml.im1t",n$=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,nK=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,nG={left:"start",center:"center",right:"end",start:"start",end:"end"};function nj(e,t,i,s){let r=tI(new Uint8Array(e),["mdat"]);if(0===r.length)return void s(Error("Could not parse IMSC1 mdat"));let a=r.map(e=>tl(e)),n=function(e,t=1,i=!1){return rY(e,1,1/t,i)}(t.baseTime,t.timescale);
17try{a.forEach(e=>i(function(e,t){let i=new DOMParser().parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!i)throw Error("Invalid ttml");let s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},r=Object.keys(s).reduce((e,t)=>(e[t]=i.getAttribute(`ttp:${t}`)||s[t],e),{}),a="preserve"!==i.getAttribute("xml:space"),n=nV(nH(i,"styling","style")),l=nV(nH(i,"layout","region")),o=nH(i,"body","[begin]");return[].map.call(o,e=>{var i,s,o;let d,h,u,c=function e(t,i){return[].slice.call(t.childNodes).reduce((t,s,r)=>{var a;return"br"===s.nodeName&&r?t+"\n":null!=(a=s.childNodes)&&a.length?e(s,i):i?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}(e,a);if(!c||!e.hasAttribute("begin"))return null;let f=nq(e.getAttribute("begin"),r),g=nq(e.getAttribute("dur"),r),m=nq(e.getAttribute("end"),r);if(null===f)throw nY(e);if(null===m){if(null===g)throw nY(e);m=f+g}let p=new nR(f-t,m-t,c);p.id=nN(p.startTime,p.endTime,p.text);let y=(i=l[e.getAttribute("region")],s=n[e.getAttribute("style")],o=n,d="http://www.w3.org/ns/ttml#styling",h=null,(u=null!=i&&i.hasAttribute("style")?i.getAttribute("style"):null)&&o.hasOwnProperty(u)&&(h=o[u]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((e,t)=>{let r=nW(s,d,t)||nW(i,d,t)||nW(h,d,t);return r&&(e[t]=r),e},{})),{textAlign:v}=y;if(v){let e=nG[v];e&&(p.lineAlign=e),p.align=v}return e8(p,y),p}).filter(e=>null!==e)}(e,n)))}catch(e){s(e)}}function nH(e,t,i){let s=e.getElementsByTagName(t)[0];return s?[].slice.call(s.querySelectorAll(i)):[]}function nV(e){return e.reduce((e,t)=>{let i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function nW(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function nY(e){return Error(`Could not parse ttml timestamp ${e}`)}function nq(e,t){var i,s;let r,a;if(!e)return null;let n=nI(e);return null===n&&(n$.test(e)?(i=e,s=t,a=(0|(r=n$.exec(i))[4])+(0|r[5])/s.subFrameRate,n=(0|r[1])*3600+(0|r[2])*60+(0|r[3])+a/s.frameRate):nK.test(e)&&(n=function(e,t){let i=nK.exec(e),s=Number(i[1]);switch(i[2]){case"h":return 3600*s;case"m":return 60*s;case"ms":return 1e3*s;case"f":return s/t.frameRate;case"t":return s/t.tickRate}return s}(e,t))),n}class nz{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(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function nX(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function nQ(e,t){return!!e&&e.kind===nX(t)&&an(t,e)}function nZ(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}let nJ=/\s/,n0={newCue(e,t,i,s){let r,a,n,l,o,d=[],h=self.VTTCue||self.TextTrackCue;for(let c=0;c<s.rows.length;c++)if(r=s.rows[c],n=!0,l=0,o="",!r.isEmpty()){var u;for(let e=0;e<r.chars.length;e++)nJ.test(r.chars[e].uchar)&&n?l++:(o+=r.chars[e].uchar,n=!1);r.cueStartTime=t,t===i&&(i+=1e-4),l>=16?l--:l++;let s=nx(o.trim()),f=nN(t,i,s);null!=e&&null!=(u=e.cues)&&u.getCueById(f)||((a=new h(t,i,s)).id=f,a.line=c+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),d.push(a))}return e&&d.length&&(d.sort((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),d.forEach(t=>a2(e,t))),d}},n1=/(\d+)-(\d+)\/(\d+)/;class n2{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||n3,this.controller=new self.AbortController,this.stats=new tc}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(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){var s;let r,a=this.stats;if(a.loading.start)throw Error("Loader can only be used once.");a.loading.start=self.performance.now();let n=(s=e,r={method:"GET",mode:"cors",credentials:"same-origin",signal:this.controller.signal,headers:new self.Headers(e8({},s.headers))},s.rangeEnd&&r.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),r),l="arraybuffer"===e.responseType,o=l?"byteLength":"length",{maxTimeToFirstByteMs:d,maxLoadTimeMs:h}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=
17d&&eV(d)?d:h,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,e,this.response))},t.timeout),(r9(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(i=>{var s;this.response=this.loader=i;let r=Math.max(self.performance.now(),a.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=h,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,e,this.response))},h-(r-a.loading.start)),!i.ok){let{status:e,statusText:t}=i;throw new n4(t||"fetch, bad network response",e,i)}a.loading.first=r,a.total=function(e){let t=e.get("Content-Range");if(t){let e=function(e){let t=n1.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(eV(e))return e}let i=e.get("Content-Length");if(i)return parseInt(i)}(i.headers)||a.total;let n=null==(s=this.callbacks)?void 0:s.onProgress;return n&&eV(t.highWaterMark)?this.loadProgressively(i,a,e,t.highWaterMark,n):l?i.arrayBuffer():"json"===e.responseType?i.json():i.text()}).then(i=>{var s,r;let n=this.response;if(!n)throw Error("loader destroyed");self.clearTimeout(this.requestTimeout),a.loading.end=Math.max(self.performance.now(),a.loading.first);let l=i[o];l&&(a.loaded=a.total=l);let d={url:n.url,data:i,code:n.status},h=null==(s=this.callbacks)?void 0:s.onProgress;h&&!eV(t.highWaterMark)&&h(a,e,i,n),null==(r=this.callbacks)||r.onSuccess(d,a,e,n)}).catch(t=>{var i;if(self.clearTimeout(this.requestTimeout),a.aborted)return;let s=t&&t.code||0,r=t?t.message:null;null==(i=this.callbacks)||i.onError({code:s,text:r},e,t?t.details:null,a)})}getCacheAge(){let e=null;if(this.response){let 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,r){let a=new s7,n=e.body.getReader(),l=()=>n.read().then(n=>{if(n.done)return a.dataLength&&r(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let o=n.value,d=o.length;return t.loaded+=d,d<s||a.dataLength?(a.push(o),a.dataLength>=s&&r(t,i,a.flush().buffer,e)):r(t,i,o.buffer,e),l()}).catch(()=>Promise.reject());return l()}}function n3(e,t){return new self.Request(e.url,t)}class n4 extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}let n5=/^age:\s*[\d.]+\s*$/im;class n8{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 tc,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw 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(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;let r=this.xhrSetup;r?Promise.resolve().then(()=>{if(this.loader===i&&!this.stats.aborted)return r(i,t.url)}).catch(e=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",t.url,!0),r(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(e=>{var r;null==(r=this.callbacks)||r.onError({code:i.status,text:e.message},t,i,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);let s=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=i.loadPolicy;if(s)for(let t in s)e.setRequestHeader(t,s[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.on
17progress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=r&&eV(r)?r:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let s=t.readyState,r=this.config;if(!i.aborted&&s>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===s)){var a,n,l;self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let s=t.status,o="text"===t.responseType?t.responseText:null;if(s>=200&&s<300){let r=null!=o?o:t.response;if(null!=r){i.loading.end=Math.max(self.performance.now(),i.loading.first),i.loaded=i.total="arraybuffer"===t.responseType?r.byteLength:r.length,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);let l=null==(a=this.callbacks)?void 0:a.onProgress;l&&l(i,e,r,t);let o={url:t.responseURL,data:r,code:s};null==(n=this.callbacks)||n.onSuccess(o,i,e,t);return}}let d=r.loadPolicy.errorRetry;iL(d,i.retry,!1,{url:e.url,data:void 0,code:s})?this.retry(d):(tr.error(`${s} while loading ${e.url}`),null==(l=this.callbacks)||l.onError({code:s,text:t.statusText},e,t,i))}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry;if(iL(e,this.stats.retry,!0))this.retry(e);else{var t;tr.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);let e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:i}=this;this.retryDelay=iE(e,i.retry),i.retry++,tr.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?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){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&n5.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}let n6=e9(e9({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:1/0,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:n8,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends e7{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.co
17decTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;let i,{fragCurrent:s,partCurrent:r,hls:a}=this,{autoLevelEnabled:n,media:l}=a;if(!s||!l)return;let o=performance.now(),d=r?r.stats:s.stats,h=r?r.duration:s.duration,u=o-d.loading.start,c=a.minAutoLevel,f=s.level,g=this._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||f<=c){this.clearTimer(),this._nextAutoLevel=-1;return}if(!n)return;let m=g>-1&&g!==f,p=!!e||m;if(!p&&(l.paused||!l.playbackRate||!l.readyState))return;let y=a.mainForwardBufferInfo;if(!p&&null===y)return;let v=this.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(u<=Math.max(v,h/(2*T)*1e3))return;let E=y?y.len/T:0,S=d.loading.first?d.loading.first-d.loading.start:-1,L=d.loaded&&S>-1,k=this.getBwEstimate(),A=a.levels,R=A[f],b=Math.max(d.loaded,Math.round(h*(s.bitrate||R.averageBitrate)/8)),I=L?u-S:u;I<1&&L&&(I=Math.min(u,8*d.loaded/k));let _=L?1e3*d.loaded/I:0,C=v/1e3,D=_?(b-d.loaded)/_:8*b/k+C;if(D<=E)return;let P=_?8*_:k,x=(null==(t=(null==e?void 0:e.details)||this.hls.latestLevelDetails)?void 0:t.live)===!0,F=this.hls.config.abrBandWidthUpFactor,w=1/0;for(i=f-1;i>c;i--){let e=A[i].maxBitrate,t=!A[i].details||x;if((w=this.getTimeToLoadFrag(C,P,h*e,t))<Math.min(E,h+C))break}if(w>=D||w>10*h)return;L?this.bwEstimator.sample(u-Math.min(v,S),d.loaded):this.bwEstimator.sampleTTFB(u);let M=A[i].maxBitrate;this.getBwEstimate()*F>M&&this.resetEstimator(M);let O=this.findBestLevel(M,c,i,0,E,1,1);O>-1&&(i=O),this.warn(`Fragment ${s.sn}${r?" part "+r.index:""} of level ${f} is loading too slowly;
18      Fragment duration: ${s.duration.toFixed(3)}
19      Time to underbuffer: ${E.toFixed(3)} s
20      Estimated load time for current fragment: ${D.toFixed(3)} s
21      Estimated load time for down switch fragment: ${w.toFixed(3)} s
22      TTFB estimate: ${0|S} ms
23      Current BW estimate: ${eV(k)?0|k:"Unknown"} bps
24      New BW estimate: ${0|this.getBwEstimate()} bps
25      Switching to level ${i} @ ${0|M} bps`),a.nextLoadLevel=a.nextAutoLevel=i,this.clearTimer();let N=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===i&&i>0){let e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${i>0?"and switching down":""}
26      Fragment duration: ${s.duration.toFixed(3)} s
27      Time to underbuffer: ${e.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,i>c){let t=this.findBestLevel(this.hls.levels[c].bitrate,c,i,0,e,1,1);-1===t&&(t=c),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};m||D>2*w?N():this.timer=self.setInterval(N,1e3*w),a.trigger(eX.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:r,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(){let e=this.hls.config;return new e5(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let{hls:e}=this;e.on(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.on(eX.FRAG_LOADING,this.onFragLoading,this),e.on(eX.FRAG_LOADED,this.onFragLoaded,this),e.on(eX.FRAG_BUFFERED,this.onFragBuffered,this),e.on(eX.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(eX.LEVEL_LOADED,this.onLevelLoaded,this),e.on(eX.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(eX.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(eX.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.off(eX.FRAG_LOADING,this.onFragLoading,this),e.off(eX.FRAG_LOADED,this.onFragLoaded,this),e.off(eX.FRAG_BUFFERED,this.onFragBuffered,this),e.off(eX.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(eX.LEVEL_LOADED,this.onLevelLoaded,this),e.off(eX.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(eX.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(eX.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){let i=t.frag;
27if(!this.ignoreFragment(i)){if(!i.bitrateTest){var s;this.fragCurrent=i,this.partCurrent=null!=(s=t.part)?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 ez.BUFFER_ADD_CODEC_ERROR:case ez.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ez.FRAG_LOAD_TIMEOUT:{let e=t.frag,{fragCurrent:i,partCurrent:s}=this;if(e&&i&&e.sn===i.sn&&e.level===i.level){let t=performance.now(),i=s?s.stats:e.stats,r=t-i.loading.start,a=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&a>-1){let e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(e,a),i.loaded)}else this.bwEstimator.sampleTTFB(r)}}}}getTimeToLoadFrag(e,t,i,s){let r=s?e+this.lastLevelLoadSec:0;return e+i/t+r}onLevelLoaded(e,t){let i=this.hls.config,{loading:s}=t.stats,r=s.end-s.first;eV(r)&&(this.lastLevelLoadSec=r/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}){let s=i?i.stats:t.stats;if(t.type===e1&&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){let e=i?i.duration:t.duration,r=this.hls.levels[t.level],a=(r.loaded?r.loaded.bytes:0)+s.loaded,n=(r.loaded?r.loaded.duration:0)+e;r.loaded={bytes:a,duration:n},r.realBitrate=Math.round(8*a/n)}if(t.bitrateTest){let e={stats:s,frag:t,part:i,id:t.type};this.onFragBuffered(eX.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){let{frag:i,part:s}=t,r=null!=s&&s.stats.loaded?s.stats:i.stats;if(r.aborted||this.ignoreFragment(i))return;let a=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==e1||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,t,e,0,s,1,1);if(r>-1)return r;let a=this.hls.firstLevel,n=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 ${n}`),n}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){let e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(-1!==e&&(!t||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let s=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){let t=this.hls.levels;if(t.length>Math.max(e,s)&&t[e].loadError<=t[s].loadError)return e}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}
27_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;let{maxAutoLevel:s,config:r,minAutoLevel:a}=i,n=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),o=this.getStarvationDelay(),d=r.abrBandWidthFactor,h=r.abrBandWidthUpFactor;if(o){let e=this.findBestLevel(l,a,s,o,0,d,h);if(e>=0)return this.rebufferNotice=-1,e}let u=n?Math.min(n,r.maxStarvationDelay):r.maxStarvationDelay;if(!o){let e=this.bitrateTestDelay;e&&(u=(n?Math.min(n,r.maxLoadingDelay):r.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),d=h=1)}let c=this.findBestLevel(l,a,s,o,u,d,h);if(this.rebufferNotice!==c&&(this.rebufferNotice=c,this.info(`${o?"rebuffering expected":"buffer is empty"}, optimal quality level ${c}`)),c>-1)return c;let f=i.levels[a],g=i.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?a:i.loadLevel}getStarvationDelay(){let e=this.hls,t=e.media;if(!t)return 1/0;let i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,s,r,a,n){var l,o;let d,h=s+r,u=this.lastLoadedFragLevel,c=-1===u?this.hls.firstLevel:u,{fragCurrent:f,partCurrent:g}=this,{levels:m,allAudioTracks:p,loadLevel:y,config:v}=this.hls;if(1===m.length)return 0;let T=m[c],E=!!(null!=(l=this.hls.latestLevelDetails)&&l.live),S=-1===y||-1===u,L="SDR",k=(null==T?void 0:T.frameRate)||0,{audioPreference:A,videoPreference:R}=v,b=this.audioTracksByGroup||(this.audioTracksByGroup=is(p)),I=-1;if(S){if(-1!==this.firstSelection)return this.firstSelection;let s=function(e,t,i,s,r){let a=Object.keys(e),n=null==s?void 0:s.channels,l=null==s?void 0:s.audioCodec,o=null==r?void 0:r.videoCodec,d=n&&2===parseInt(n),h=!1,u=!1,
27c=1/0,f=1/0,g=1/0,m=1/0,p=0,y=[],{preferHDR:v,allowedVideoRanges:T}=function(e,t){let i=!1,s=[];if(e&&(i="SDR"!==e,s=[e]),t){let e="SDR"!==(s=t.allowedVideoRanges||t8.slice(0)).join("")&&!t.videoCodec;(i=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){let e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}())||(s=["SDR"])}return{preferHDR:i,allowedVideoRanges:s}}(t,r);for(let t=a.length;t--;){let i=e[a[t]];h||(h=i.channels[2]>0),c=Math.min(c,i.minHeight),f=Math.min(f,i.minFramerate),g=Math.min(g,i.minBitrate),T.filter(e=>i.videoRanges[e]>0).length>0&&(u=!0)}c=eV(c)?c:0,f=eV(f)?f:0;let E=Math.max(1080,c),S=Math.max(30,f);i=Math.max(g=eV(g)?g:i,i),u||(t=void 0);let L=a.length>1;return{codecSet:a.reduce((t,s)=>{let r=e[s];if(s===t)return t;if(y=u?T.filter(e=>r.videoRanges[e]>0):[],L){if(r.minBitrate>i)return ii(s,`min bitrate of ${r.minBitrate} > current estimate of ${i}`),t;if(!r.hasDefaultAudio)return ii(s,"no renditions with default or auto-select sound found"),t;if(l&&s.indexOf(l.substring(0,4))%5!=0)return ii(s,`audio codec preference "${l}" not found`),t;if(n&&!d){if(!r.channels[n])return ii(s,`no renditions with ${n} channel sound found (channels options: ${Object.keys(r.channels)})`),t}else if((!l||d)&&h&&0===r.channels["2"])return ii(s,"no renditions with stereo sound found"),t;if(r.minHeight>E)return ii(s,`min resolution of ${r.minHeight} > maximum of ${E}`),t;if(r.minFramerate>S)return ii(s,`min framerate of ${r.minFramerate} > maximum of ${S}`),t;if(!y.some(e=>r.videoRanges[e]>0))return ii(s,`no variants with VIDEO-RANGE of ${it(y)} found`),t;if(o&&s.indexOf(o.substring(0,4))%5!=0)return ii(s,`video codec preference "${o}" not found`),t;if(r.maxScore<p)return ii(s,`max score of ${r.maxScore} < selected max of ${p}`),t}return t&&(tW(s)>=tW(t)||r.fragmentError>e[t].fragmentError)?t:(m=r.minIndex,p=r.maxScore,s)},void 0),videoRanges:y,preferHDR:v,minFramerate:f,minBitrate:g,minIndex:m}}(this.codecTiers||(this.codecTiers=m.slice(t,i+1).reduce((e,t,i)=>{if(!t.codecSet)return e;let s=t.audioGroups,r=e[t.codecSet];r||(e[t.codecSet]=r={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!s,fragmentError:0}),r.minBitrate=Math.min(r.minBitrate,t.bitrate);let a=Math.min(t.height,t.width);return r.minHeight=Math.min(r.minHeight,a),r.minFramerate=Math.min(r.minFramerate,t.frameRate),r.minIndex=Math.min(r.minIndex,i),r.maxScore=Math.max(r.maxScore,t.score),r.fragmentError+=t.fragmentError,r.videoRanges[t.videoRange]=(r.videoRanges[t.videoRange]||0)+1,s&&s.forEach(e=>{if(!e)return;let t=b.groups[e];t&&(r.hasDefaultAudio=r.hasDefaultAudio||b.hasDefaultAudio?t.hasDefault:t.hasAutoSelect||!b.hasDefaultAudio&&!b.hasAutoSelectAudio,Object.keys(t.channels).forEach(e=>{r.channels[e]=(r.channels[e]||0)+t.channels[e]}))}),e},{})),L,e,A,R),{codecSet:r,videoRanges:a,minFramerate:n,minBitrate:l,minIndex:o,preferHDR:h}=s;I=o,d=r,L=h?a[a.length-1]:a[0],k=n,e=Math.max(e,l),this.log(`picked start tier ${it(s)}`)}else d=null==T?void 0:T.codecSet,L=null==T?void 0:T.videoRange;let _=g?g.duration:f?f.duration:0,C=this.bwEstimator.getEstimateTTFB()/1e3,D=[];for(let l=i;l>=t;l--){let t,f=m[l],p=l>c;if(!f)continue;if(v.useMediaCapabilities&&!f.supportedResult&&!f.supportedPromise){let t=navigator.mediaCapabilities;"function"==typeof(null==t?void 0:t.decodingInfo)&&function(e,t,i,s,r,a){let n=e.videoCodec,l=e.audioCodec?e.audioGroups:null,o=null==a?void 0:a.audioCodec,d=null==a?void 0:a.channels,h=d?parseInt(d):o?1/0:2,u=null;if(null!=l&&l.length)try{u=1===l.length&&l[0]?t.groups[l[0]].channels:l.reduce((e,i)=>{if(i){let s=t.groups[i];if(!s)throw Error(`Audio track group ${i} not found`);Object.keys(s.channels).forEach(t=>{e[t]=(e[t]||0)+s.channels[t]})}return e},{2:0})}catch(e){return!0}return void 0!==n&&(n.split(",").some(e=>tN(e))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(s,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(r,8e6))||!!u&&eV(h)&&Object.keys(u).some(e=>parseInt(e)>h)}
27(f,b,L,k,e,A)?(f.supportedPromise=t3(f,b,t,this.supportedCache),f.supportedPromise.then(e=>{if(!this.hls)return;f.supportedResult=e;let t=this.hls.levels,i=t.indexOf(f);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${i} ${it(e)}`):e.supported?e.decodingInfoResults.some(e=>!1===e.smooth||!1===e.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${i} not smooth or powerEfficient: ${it(e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${i} ${it(e)}`),i>-1&&t.length>1&&(this.log(`Removing unsupported level ${i}`),this.hls.removeLevel(i),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${e}`)})):f.supportedResult=t1}if((d&&f.codecSet!==d||L&&f.videoRange!==L||p&&k>f.frameRate||!p&&k>0&&k<f.frameRate||null!=(o=f.supportedResult)&&null!=(o=o.decodingInfoResults)&&o.some(e=>!1===e.smooth))&&(!S||l!==I)){D.push(l);continue}let T=f.details,R=(g?null==T?void 0:T.partTarget:null==T?void 0:T.averagetargetduration)||_;t=p?n*e:a*e;let P=_&&s>=2*_&&0===r?f.averageBitrate:f.maxBitrate,x=this.getTimeToLoadFrag(C,t,P*R,void 0===T);if(t>=P&&(l===u||0===f.loadError&&0===f.fragmentError)&&(x<=C||!eV(x)||E&&!this.bitrateTestDelay||x<h)){let e=this.forcedAutoLevel;return l!==y&&(-1===e||e!==y)&&(D.length&&this.trace(`Skipped level(s) ${D.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${m[D[0]].codecs}" ${m[D[0]].videoRange}; not compatible with "${d}" ${L}`),this.info(`switch candidate:${c}->${l} adjustedbw(${Math.round(t)})-bitrate=${Math.round(t-P)} ttfb:${C.toFixed(1)} avgDuration:${R.toFixed(1)} maxFetchDuration:${h.toFixed(1)} fetchDuration:${x.toFixed(1)} firstSelection:${S} codecSet:${f.codecSet} videoRange:${f.videoRange} hls.loadLevel:${y}`)),S&&(this.firstSelection=l),l}}return -1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){let{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},bufferController:class extends e7{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=e=>{var t;this.hls&&(null==(t=this.mediaSource)?void 0:t.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{let{media:t,mediaSource:i}=this;e&&this.log("Media source opened"),t&&i&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(eX.MEDIA_ATTACHED,{media:t,mediaSource:i}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=function(e){return"u">typeof self&&e===self.ManagedMediaSource}(ta(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(){let{hls:e}=this;
27e.on(eX.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(eX.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.on(eX.MANIFEST_PARSED,this.onManifestParsed,this),e.on(eX.BUFFER_RESET,this.onBufferReset,this),e.on(eX.BUFFER_APPENDING,this.onBufferAppending,this),e.on(eX.BUFFER_CODECS,this.onBufferCodecs,this),e.on(eX.BUFFER_EOS,this.onBufferEos,this),e.on(eX.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(eX.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(eX.FRAG_PARSED,this.onFragParsed,this),e.on(eX.FRAG_CHANGED,this.onFragChanged,this),e.on(eX.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(eX.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(eX.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.off(eX.MANIFEST_PARSED,this.onManifestParsed,this),e.off(eX.BUFFER_RESET,this.onBufferReset,this),e.off(eX.BUFFER_APPENDING,this.onBufferAppending,this),e.off(eX.BUFFER_CODECS,this.onBufferCodecs,this),e.off(eX.BUFFER_EOS,this.onBufferEos,this),e.off(eX.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(eX.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(eX.FRAG_PARSED,this.onFragParsed,this),e.off(eX.FRAG_CHANGED,this.onFragChanged,this),e.off(eX.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let i={};if(this.operationQueue){let e=this.isUpdating();e||this.operationQueue.removeBlockers();let t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}let s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===t?e8(i,s.tracks):this.sourceBuffers.forEach(e=>{let[t]=e;t&&(i[t]=e8({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(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.`),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(e,t){let i=this.media=t.media;this.transferData=this.overrides=void 0;let s=ta(this.appendSource);if(s){let e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let n=this.mediaSource=t.mediaSource||new s;if(this.assignMediaSource(n),e)this._objectUrl=i.src,this.attachTransferred();else{let e=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{var r,a;let t;i.removeAttribute("src");let s=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||s&&n instanceof s,au(i),r=i,a=e,(t=self.document.createElement("source")).type="video/mp4",t.src=a,r.appendChild(t),i.load()}catch(t){i.src=e}else i.src=e}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(i=e.constructor)?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(){let e=this.media,t=this.transferData;if(!t||!e)return;let i=this.tracks,s=t.tracks,r=s?Object.keys(s):null,a=r?r.length:0,n=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&r&&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})
28required tracks: ${it(i,(e,t)=>"initSegment"===e?void 0:t)};
29transfer tracks: ${it(s,(e,t)=>"initSegment"===e?void 0:t)}}`),!tn(s,i)){t.mediaSource=null,t.tracks=void 0;let r=e.currentTime,a=this.details,n=Math.max(r,(null==a?void 0:a.fragments[0].start)||0);return n-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${n}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${n} currentTime: ${r}`),this.onMediaDetaching(eX.MEDIA_DETACHING,{}
29),this.onMediaAttaching(eX.MEDIA_ATTACHING,t),void(e.currentTime=n))}this.transferData=void 0,r.forEach(e=>{let t=s[e];if(t){let i=t.buffer;if(i){let s=this.fragmentTracker,r=t.id;if(s.hasFragments(r)||s.hasParts(r)){let t=iH.getBuffered(i);s.detectEvictedFragments(e,t,r,null,!0)}let a=ac(e),n=[e,i];this.sourceBuffers[a]=n,i.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,t)}}}),n(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),n()}get mediaSourceOpenOrEnded(){var e;let t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){let i=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:s,mediaSource:r,_objectUrl:a}=this;if(r){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let e="open"===r.readyState;try{let t=r.sourceBuffers;for(let i=t.length;i--;)e&&t[i].abort(),r.removeSourceBuffer(t[i]);e&&r.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(s.removeAttribute("src"),this.appendSource&&au(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(eX.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t,i;let s=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),s)try{null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[ac(e)]=[null,null];let t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new al(this.tracks)}onBufferCodecs(e,t){var i;let s=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);let a="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),n=!a&&this.sourceBufferCount&&this.media&&r.some(e=>!s[e]);a||n?this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`):(r.forEach(e=>{var i,r;let{id:a,codec:n,levelCodec:l,container:o,metadata:d,supplemental:h}=t[e],u=s[e],c=null==(i=this.transferData)||null==(i=i.tracks)?void 0:i[e],f=null!=c&&c.buffer?c:u,g=(null==f?void 0:f.pendingCodec)||(null==f?void 0:f.codec),m=null==f?void 0:f.levelCodec;u||(u=s[e]={buffer:void 0,listeners:[],codec:n,supplemental:h,container:o,levelCodec:l,metadata:d,id:a});let p=tX(g,m),y=null==p?void 0:p.replace(ao,"$1"),v=tX(n,l),T=null==(r=v)?void 0:r.replace(ao,"$1");v&&p&&y!==T&&("audio"===e.slice(0,5)&&(v=tz(v,this.appendSource)),this.log(`switching codec ${g} to ${v}`),v!==(u.pendingCodec||u.codec)&&(u.pendingCodec=v),u.container=o,this.appendChangeType(e,o,v))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(!(this.bufferCodecEventsTotal>1)||this.tracks.video||t.video||(null==(i=t.audio)?void 0:i.id)!=="main"||(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){let s=`${t};codecs=${i}`,r={label:`change-type=${s}`,execute:()=>{let r=this.tracks[e];if(r){let a=r.buffer;null!=a&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${s}`),a.changeType(s),r.codec=i,r.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;let i=e.start,s=i+.05*e.duration;if((null==(t=this.fragmentTracker.getAppendedFrag(i,e1))?void 0:t.gap)===!0)return;let r={label:"block-audio",execute:()=>{var e;let t=this.tracks.video;(this.lastVideoAppendEnd>s||null!=t&&t.buffer&&iH.isBuffered(t.buffer,s)||(null==(e=this.fragmentTracker.getAppendedFrag(s,e1))?void 0:e.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:r,frag:e},this.append(r,"audio",!0)}unblockAudio(){let{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){let{tracks:i}=this,{data:s,type:r,parent:a,frag:n,part:l,chunkMeta:o,offset:d}=t,h=o.buffering[r],{sn:u,cc:c}=n,f=self.performance.now();h.start=f;let g=n.stats.buffering,m=l?l.stats.buffering:null;0===g.start&&(g.start=f),m&&0===m.start&&(m.start=f);let p=i.audio,y=!1;"audio"===r&&(null==p?void 0:p.container)==="audio/mpeg"&&(y=!this.lastMpegAudioChunk||1===o.id||this.lastMpegAudioChunk.sn!==o.sn,this.lastMpegAudioChunk=o);let v=i.video,T=null==v?void 0:v.buffer;if(T&&"initSegment"!==u){let e=l||n,t=this.blockedAudioAppend;if("audio"!==r||"main"===a||this.blockedAudioAppend||v.ending||v.ended){if("video"===r){let i=e.end;if(t){let e=t.frag.start;(i>e||i<this.lastVideoAppendEnd||iH.isBuffered(T,e))&&this.unblockAudio()}this.lastVideoAppendEnd=i}}else{let t=e.start+.05*e.duration,i=T.buffered,s=this.currentOp("video");(i.length||s)&&(s||iH.isBuffered(T,t)||!(this.lastVideoAppendEnd<t))||this.blockAudio(e)}}let E=(l||n).start,S={label:`append-${r}`,execute:()=>{var e;h.executeStart=self.performance.now();let t=null==(e=this.tracks[r])?void 0:e.buffer;t&&(y?this.updateTimestampOffset(t,E,.1,r,u,c):void 0!==d&&eV(d)&&this.updateTimestampOffset(t,d,1e-6,r,u,c)),this.appendExecutor(s,r)},onStart:()=>{},onComplete:()=>{let e=self.performance.now();h.executeEnd=h.end=e,0===g.first&&(g.first=e),m&&0===m.first&&(m.first=e);let t={};
29this.sourceBuffers.forEach(([e,i])=>{e&&(t[e]=iH.getBuffered(i))}),this.appendErrors[r]=0,"audio"===r||"video"===r?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(eX.BUFFER_APPENDED,{type:r,frag:n,part:l,chunkMeta:o,parent:n.type,timeRanges:t})},onError:e=>{var t;let i={type:eq.MEDIA_ERROR,parent:n.type,details:ez.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:n,part:l,chunkMeta:o,error:e,err:e,fatal:!1},s=null==(t=this.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)i.details=ez.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!s)i.errorAction=iA(!0);else if(e.name===ad&&0===this.sourceBufferCount)i.errorAction=iA(!0);else{let e=++this.appendErrors[r];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${s||"no media error"})`),(e>=this.hls.config.appendErrorMaxRetry||s)&&(i.fatal=!0)}this.hls.trigger(eX.ERROR,i)}};this.log(`queuing "${r}" append sn: ${u}${l?" p: "+l.index:""} of ${n.type===e1?"level":"track"} ${n.level} cc: ${c}`),this.append(S,r,this.isPending(this.tracks[r]))}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(eX.BUFFER_FLUSHED,{type:e})},onError:s=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,s)}}}onBufferFlushing(e,t){let{type:i,startOffset:s,endOffset:r}=t;i?this.append(this.getFlushOp(i,s,r),i):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,s,r),e)})}onFragParsed(e,t){let{frag:i,part:s}=t,r=[],a=s?s.elementaryStreams:i.elementaryStreams;a[tm]?r.push("audiovideo"):(a[tf]&&r.push("audio"),a[tg]&&r.push("video"));let n=()=>{let e=self.performance.now();i.stats.buffering.end=e,s&&(s.stats.buffering.end=e);let t=s?s.stats:i.stats;this.hls.trigger(eX.FRAG_BUFFERED,{frag:i,part:s,stats:t,id:i.type})};0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(n,r).catch(e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([e])=>{if(e){let i=this.tracks[e];(!t.type||t.type===e)&&(i.ending=!0,i.ended||(i.ended=!0,this.log(`${e} buffer reached EOS`)))}});let s=(null==(i=this.overrides)?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)})?s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:e}=this;if(!e||"open"!==e.readyState){e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(eX.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(eX.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(null!==e){let t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===ez.BUFFER_APPEND_ERROR&&t.frag){var i;let e=null==(i=t.errorAction)?void 0:i.nextAutoLevel;eV(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){let{hls:e,details:t,media:i}=this;if(!i||null===t||!this.sourceBufferCount)return;let s=e.config,r=i.currentTime,a=t.levelTargetDuration,n=t.live&&null!==s.liveBackBufferLength?s.liveBackBufferLength:s.backBufferLength;if(eV(n)&&n>=0){let e=Math.max(n,a),t=Math.floor(r/a)*a-e;this.flushBackBuffer(r,a,t)}let l=s.frontBufferFlushThreshold;if(eV(l)&&l>0){let e=Math.max(Math.max(s.maxBufferLength,l),a),t=Math.floor(r/a)*a+e;this.flushFrontBuffer(r,a,t)}}
29flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([e,t])=>{if(t){let r=iH.getBuffered(t);if(r.length>0&&i>r.start(0)){var s;this.hls.trigger(eX.BACK_BUFFER_REACHED,{bufferEnd:i});let t=this.tracks[e];if(null!=(s=this.details)&&s.live)this.hls.trigger(eX.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=t&&t.ended)return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(eX.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:e})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([t,s])=>{if(s){let r=iH.getBuffered(s),a=r.length;if(a<2)return;let n=r.start(a-1),l=r.end(a-1);i>n||e>=n&&e<=l||this.hls.trigger(eX.BUFFER_FLUSHING,{startOffset:n,endOffset:1/0,type:t})}})}getDurationAndRange(){var e;let{details:t,mediaSource:i}=this;if(!t||!this.media||(null==i?void 0:i.readyState)!=="open")return null;let s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){let e=Math.max(0,t.fragmentStart),i=Math.max(e,s);return{duration:1/0,start:e,end:i}}return{duration:1/0}}let r=null==(e=this.overrides)?void 0:e.duration;if(r)return eV(r)?{duration:r}:null;let a=this.media.duration;return s>(eV(i.duration)?i.duration:0)&&s>a||!eV(a)?{duration:s}:null}updateMediaSource({duration:e,start:t,end:i}){let s=this.mediaSource;this.media&&s&&"open"===s.readyState&&(s.duration!==e&&(eV(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),s.duration=e),void 0!==t&&void 0!==i&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${t}-${i}.`),s.setLiveSeekableRange(t,i)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${it(i)}`),this.tracksReady){var s;let e=null==(s=this.transferData)?void 0:s.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,i])=>{if(t){let 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(eX.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{let e=Error("could not create source buffer for media codec(s)");this.hls.trigger(eX.ERROR,{type:eq.MEDIA_ERROR,details:ez.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(let r in e){let a=e[r];if(this.isPending(a)){let e=this.getTrackCodec(a,r),n=`${a.container};codecs=${e}`;a.codec=e,this.log(`creating sourceBuffer(${n})${this.currentOp(r)?" Queued":""} ${it(a)}`);try{let e=i.addSourceBuffer(n),s=ac(r),l=[r,e];t[s]=l,a.buffer=e}catch(e){var s;this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(r),null==(s=this.operationQueue)||s.removeBlockers(),delete this.tracks[r],this.hls.trigger(eX.ERROR,{type:eq.MEDIA_ERROR,details:ez.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:r,mimeType:n,parent:a.id});return}this.trackSourceBuffer(r,a)}}this.bufferCreated()}getTrackCodec(e,t){let i=e.supplemental,s=e.codec;i&&("video"===t||"audiovideo"===t)&&tG(i,"video")&&(s=function(e,t){let i=[];if(e){let t=e.split(",");for(let e=0;e<t.length;e++)tK(t[e],"video")||i.push(t[e])}return t&&i.push(t),i.join(",")}(s,i));let r=tX(s,e.levelCodec);return r?"audio"===t.slice(0,5)?tz(r,this.appendSource):r:""}trackSourceBuffer(e,t){let i=t.buffer;if(!i)return;let 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",(e,t)=>{let i=t.removedRanges;null!=i&&i.length&&this.hls.trigger(eX.BUFFER_FLUSHED,{type:e})})}get mediaSrc(){var e,t;let i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==i?void 0:i.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if((null==(t=this.mediaSource)?void 0:t.readyState)==="closed")return void this.resetBuffer(e);let i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;let s=Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${s}`,t),this.hls.trigger(eX.ERROR,{type:eq.MEDIA_ERROR,details:ez.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});let r=this.currentOp(e);r&&r.onError(s)}updateTimestampOffset(e,t,i,s,r,a){Math.abs(t-e.timestampOffset)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,i){let{media:s,mediaSource:r}=this,a=this.tracks[e],n=null==a?void 0:a.buffer;if(!s||!r||!n){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}let l=eV(s.duration)?s.duration:1/0,o=eV(r.duration)?r.duration:1/0,d=Math.max(0,t),h=Math.min(i,l,o);h>d&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${d},${h}] from the ${e} SourceBuffer`),n.remove(d,h)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){let i=this.tracks[t],s=null==i?void 0:i.buffer;if(!s)throw new ah(`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(e=>{this.warn(`SourceBuffer blocked callback ${e}
29`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}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);let{operationQueue:i}=this,s=t.map(e=>this.appendBlocker(e));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then(t=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{var t;let i=null==(t=this.tracks[e])?void 0:t.buffer;i&&!i.updating&&this.shiftAndExecuteNext(e)})}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]),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+ +!!t,0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){let s=this.tracks[e];if(!s)return;let r=s.buffer;if(!r)return;let a=i.bind(this,e);s.listeners.push({event:t,listener:a}),r.addEventListener(t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let i=t.buffer;i&&(t.listeners.forEach(e=>{i.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}},capLevelController:af,errorController:class extends e7{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(eX.ERROR,this.onError,this),e.on(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.on(eX.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(eX.ERROR,this.onError,this),e.off(eX.ERROR,this.onErrorOut,this),e.off(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.off(eX.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===e1?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,i=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===i?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if(null!=(i=e.details)&&i.hasKey(t))return!0;let s=e.audioGroups;if(s)return this.hls.allAudioTracks.filter(e=>s.indexOf(e.groupId)>=0).some(e=>{var i;return null==(i=e.details)?void 0:i.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i,s,r;if(t.fatal)return;let a=this.hls,n=t.context;switch(t.details){case ez.FRAG_LOAD_ERROR:case ez.FRAG_LOAD_TIMEOUT:case ez.KEY_LOAD_ERROR:case ez.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case ez.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap){t.errorAction=iA();return}case ez.FRAG_GAP:case ez.FRAG_DECRYPT_ERROR:t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=2;return;case ez.LEVEL_EMPTY_ERROR:case ez.LEVEL_PARSING_ERROR:{let e=t.parent===e1?t.level:a.loadLevel;t.details===ez.LEVEL_EMPTY_ERROR&&null!=(s=t.context)&&null!=(s=s.levelDetails)&&s.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case ez.LEVEL_LOAD_ERROR:case ez.LEVEL_LOAD_TIMEOUT:"number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case ez.AUDIO_TRACK_LOAD_ERROR:case ez.AUDIO_TRACK_LOAD_TIMEOUT:case ez.SUBTITLE_LOAD_ERROR:case ez.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){let e=a.loadLevelObj;e&&(n.type===eJ&&e.hasAudioGroup(n.groupId)||n.type===e0&&e.hasSubtitleGroup(n.groupId))&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a.loadLevel),t.errorAction.action=2,t.errorAction.flags=1)}return;
29case ez.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:2,flags:2};return;case ez.KEY_SYSTEM_SESSION_UPDATE_FAILED:case ez.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case ez.KEY_SYSTEM_NO_SESSION:t.errorAction={action:2,flags:4};return;case ez.BUFFER_ADD_CODEC_ERROR:case ez.REMUX_ALLOC_ERROR:case ez.BUFFER_APPEND_ERROR:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,null!=(r=t.level)?r:a.loadLevel));return;case ez.INTERNAL_EXCEPTION:case ez.BUFFER_APPENDING_ERROR:case ez.BUFFER_FULL_ERROR:case ez.LEVEL_SWITCH_ERROR:case ez.BUFFER_STALLED_ERROR:case ez.BUFFER_SEEK_OVER_HOLE:case ez.BUFFER_NUDGE_ON_STALL:t.errorAction=iA();return}t.type===eq.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=iA())}getPlaylistRetryOrSwitchAction(e,t){let i=iT(this.hls.config.playlistLoadPolicy,e),s=this.playlistError++;if(iL(i,s,ip(e),e.response))return{action:5,flags:0,retryConfig:i,retryCount:s};let r=this.getLevelSwitchAction(e,t);return i&&(r.retryConfig=i,r.retryCount=s),r}getFragRetryOrSwitchAction(e){let t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:a}=t.config,n=iT(iy(e)?a:r,e),l=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(s&&(e.details!==ez.FRAG_GAP&&s.fragmentError++,!iv(e))&&iL(n,l,ip(e),e.response))return{action:5,flags:0,retryConfig:n,retryCount:l};let o=this.getLevelSwitchAction(e,i);return n&&(o.retryConfig=n,o.retryCount=l),o}getLevelSwitchAction(e,t){let i=this.hls;null==t&&(t=i.loadLevel);let s=this.hls.levels[t];if(s){var r,a,n,l;let t=e.details;s.loadError++,t===ez.BUFFER_APPEND_ERROR&&s.fragmentError++;let o=-1,{levels:d,loadLevel:h,minAutoLevel:u,maxAutoLevel:c}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);let f=null==(r=e.frag)?void 0:r.type,g=(f===e2&&t===ez.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===ez.BUFFER_ADD_CODEC_ERROR||t===ez.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:e})=>s.audioCodec!==e),m="video"===e.sourceBufferName&&(t===ez.BUFFER_ADD_CODEC_ERROR||t===ez.BUFFER_APPEND_ERROR)&&d.some(({codecSet:e,audioCodec:t})=>s.codecSet!==e&&s.audioCodec===t),{type:p,groupId:y}=null!=(a=e.context)?a:{};for(let i=d.length;i--;){let r=(i+h)%d.length;if(r!==h&&r>=u&&r<=c&&0===d[r].loadError){let i=d[r];if(t===ez.FRAG_GAP&&f===e1&&e.frag){let t=d[r].details;if(t){let i=ic(e.frag,t.fragments,e.frag.start);if(null!=i&&i.gap)continue}}else if(p===eJ&&i.hasAudioGroup(y)||p===e0&&i.hasSubtitleGroup(y))continue;else if(f===e2&&null!=(n=s.audioGroups)&&n.some(e=>i.hasAudioGroup(e))||f===e3&&null!=(l=s.subtitleGroups)&&l.some(e=>i.hasSubtitleGroup(e))||g&&s.audioCodec===i.audioCodec||m&&s.codecSet===i.codecSet||!g&&s.codecSet!==i.codecSet)continue;o=r;break}}if(o>-1&&i.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:2,flags:0,nextAutoLevel:o}}return{action:2,flags:1}}onErrorOut(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case 0:break;case 2:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===ez.FRAG_GAP?/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()):t.fatal=!0}if(t.fatal)return void this.hls.stopLoad()}sendAlternateToPenaltyBox(e){let t=this.hls,i=e.errorAction;if(!i)return;let{flags:s}=i,r=i.nextAutoLevel;switch(s){case 0:this.switchLevel(e,r);break;case 2:{let s=this.getVariantLevelIndex(e.frag),r=t.levels[s],a=null==r?void 0:r.attrs["HDCP-LEVEL"];if(i.hdcpLevel=a,"NONE"===a)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(a){t.maxHdcpLevel=t5[t5.indexOf(a)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case 4:{let t=e.decryptdata;if(t){let s=this.hls.levels,r=s.length;for(let i=r;i--;)if(this.variantHasKey(s[i],t)){var a,n;this.log(`Banned key found in level ${i} (${s[i].bitrate}bps) or audio group "${null==(a=s[i].audioGroups)?void 0:a.join(",")}" (${null==(n=e.frag)?void 0:n.type} fragment) ${to(t.keyId||[])}`),s[i].fragmentError++,s[i].loadError++,this.log(`Removing level ${i} with key error (${e.error})`),this.hls.removeLevel(i)}let l=e.frag;if(this.hls.levels.length<r)i.resolved=!0;else if(l&&l.type!==e1){let e=l.decryptdata;e&&!t.matches(e)&&(i.resolved=!0)}}}}i.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(void 0!==t&&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===ez.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){let t=tJ(e.mimeType),i=this.hls.levels;for(let s=i.length;s--;)i[s][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${s} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(s))}}},fpsController:class{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}
29registerListeners(){this.hls.on(eX.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(eX.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(eX.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(eX.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(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){let s=performance.now();if(t){if(this.lastTime){let e=s-this.lastTime,r=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,n=1e3*r/e,l=this.hls;if(l.trigger(eX.FPS_DROP,{currentDropped:r,currentDecoded:a,totalDroppedFrames:i}),n>0&&r>l.config.fpsDroppedMonitoringThreshold*a){let e=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=e)&&(e-=1,l.trigger(eX.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:l.currentLevel}),l.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:sd,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:n0,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends s6{constructor(e,t,i){super(e,t,i,"subt
29itle-stream-controller",e3),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(eX.LEVEL_LOADED,this.onLevelLoaded,this),e.on(eX.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(eX.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(eX.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(eX.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(eX.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(eX.LEVEL_LOADED,this.onLevelLoaded,this),e.off(eX.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(eX.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(eX.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(eX.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(eX.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=sX,this.setInterval(500),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){let i,{frag:s,success:r}=t;if(this.fragContextChanged(s)||(ty(s)&&(this.fragPrevious=s),this.state=sX),!r)return;let a=this.tracksBuffered[this.currentTrackId];if(!a)return;let n=s.start;for(let e=0;e<a.length;e++)if(n>=a[e].start&&n<=a[e].end){i=a[e];break}let l=s.start+s.duration;i?i.end=l:(i={start:n,end:l},a.push(i)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){let{startOffset:i,endOffset:s}=t;if(0===i&&s!==1/0){let e=s-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{for(let i=0;i<t.length;){if(t[i].end<=e){t.shift();continue}if(t[i].start<e)t[i].start=e;else break;i++}}),this.fragmentTracker.removeFragmentsInRange(i,e,e3)}}onError(e,t){let i=t.frag;(null==i?void 0:i.type)===e3&&(t.details===ez.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==sz&&(this.state=sX))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&ar(this.levels,t)){this.levels=t.map(e=>new t7(e));return}this.tracksBuffered=[],this.levels=t.map(e=>{let t=new t7(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,1/0,e3),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!(null!=(i=this.levels)&&i.length)||-1===this.currentTrackId)return void this.clearInterval();let s=this.levels[this.currentTrackId];null!=s&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.state!==sz&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var i,s;let{currentTrackId:r,levels:a}=this,{details:n,id:l}=t;if(!a)return void this.warn(`Subtitle tracks were reset while loading level ${l}`);let o=a[l];if(l>=a.length||!o)return;this.log(`Subtitle track ${l} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(n.live||null!=(i=o.details)&&i.live){if(n.deltaUpdateFailed)return;let e=this.mainDetails;if(!e){this.startFragRequested=!1;return}let t=e.fragments[0];o.details?0===(d=this.alignPlaylists(n,o.details,null==(s=this.levelLastLoaded)?void 0:s.details))&&t&&sw(n,d=t.start):n.hasProgramDateTime&&e.hasProgramDateTime?(sV(n,e),d=n.fragmentStart):t&&sw(n,d=t.start),e&&!this.startFragRequested&&this.setStartPosition(e,d)}o.details=n,this.levelLastLoaded=o,l===r&&(this.hls.trigger(eX.SUBTITLE_TRACK_UPDATED,{details:n,id:l,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===sX&&(ic(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}_handleFragmentLoadComplete(e){let{frag:t,payload:i}=e,s=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&null!=s&&s.key&&s.iv&&i1(s.method)){let e=performance.now();
29this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,i2(s.method)).catch(e=>{throw r.trigger(eX.ERROR,{type:eq.MEDIA_ERROR,details:ez.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(i=>{let s=performance.now();r.trigger(eX.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:e,tdecrypt:s}})}).catch(e=>{this.warn(`${e.name}: ${e.message}`),this.state=sX})}}doTick(){if(!this.media){this.state=sX;return}if(this.state===sX){let{currentTrackId:e,levels:t}=this,i=null==t?void 0:t[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;let{config:s}=this,r=this.getLoadPosition(),{end:a,len:n}=iH.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,s.maxBufferHole),l=i.details;if(n>this.hls.maxBufferLength+l.levelTargetDuration)return;let o=l.fragments,d=o.length,h=l.edge,u=null,c=this.fragPrevious;if(a<h){let e=s.maxFragLookUpTolerance;(u=ic(c,o,Math.max(o[0].start,a),a>h-e?0:e))||!c||!(c.start<o[0].start)||(u=o[0])}else u=o[d-1];if(!(u=this.filterReplacedPrimary(u,i.details)))return;let f=o[u.sn-l.startSN-1];if(f&&f.cc===u.cc&&this.fragmentTracker.getState(f)===iR&&(u=f),this.fragmentTracker.getState(u)===iR){let e=this.mapToInitFragWhenRequired(u);e&&this.loadFragment(e,i,a)}}}loadFragment(e,t,i){ty(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new nd(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends as{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null,t=a5(this.media.textTracks);for(let i=0;i<t.length;i++)if("hidden"===t[i].mode)e=t[i];else if("showing"===t[i].mode){e=t[i];break}let i=this.findTrackForTextTrack(e);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){let{hls:e}=this;e.on(eX.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(eX.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.on(eX.MANIFEST_PARSED,this.onManifestParsed,this),e.on(eX.LEVEL_LOADING,this.onLevelLoading,this),e.on(eX.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(eX.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(eX.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(eX.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(eX.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.off(eX.MANIFEST_PARSED,this.onManifestParsed,this),e.off(eX.LEVEL_LOADING,this.onLevelLoading,this),e.off(eX.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(eX.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(eX.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){let i=this.media;if(!i)return;let s=!!t.transferMedia;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||a5(i.textTracks).forEac
29h(e=>{a3(e)})}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){let{id:i,groupId:s,details:r}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==s)return void this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${null==a?void 0:a.groupId}`);let n=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,n)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.subtitleGroups||null,s=this.groupIds,r=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some(e=>(null==s?void 0:s.indexOf(e))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let e=this.tracks.filter(e=>!i||-1!==i.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=e;let t=this.hls.config.subtitlePreference;if(!r&&t){this.selectDefaultTrack=!1;let i=ia(t,e);if(i>-1)r=e[i];else{let e=ia(t,this.tracks);r=this.tracks[e]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null)),this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(eX.SUBTITLE_TRACKS_UPDATED,{subtitleTracks:e}),-1!==s&&-1===this.trackId&&this.setSubtitleTrack(s)}}findTrackId(e){let t=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<t.length;s++){let r=t[s];if((!i||r.default)&&(i||e)&&(!e||il(r,e)))return s}if(e){for(let i=0;i<t.length;i++){let s=t[i];if(aa(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){let s=t[i];if(aa(e.attrs,s.attrs,["LANGUAGE"]))return i}}return -1}findTrackForTextTrack(e){if(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++)if(an(t[i],e))return i}return -1}onError(e,t){!t.fatal&&t.context&&(t.context.type!==e0||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){let i=this.currentTrack;if(i&&il(e,i))return i;let s=ia(e,this.tracksInGroup);if(s>-1){let e=this.tracksInGroup[s];return this.setSubtitleTrack(s),e}{if(i)return null;let s=ia(e,t);if(s>-1)return t[s]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,s=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,n=null==a?void 0:a.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${s}${(null==t?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${n&&a.live?" age "+n.toFixed(1)+(a.type?" "+a.type:""):""} ${r}`),this.hls.trigger(eX.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null,track:e})}toggleTrackModes(){let e,{media:t}=this;if(!t)return;let i=a5(t.textTracks),s=this.currentTrack;if(s&&((e=i.filter(e=>an(s,e))[0])||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(i).forEach(t=>{"disabled"!==t.mode&&t!==e&&(t.mode="disabled")}),e){let t=this.subtitleDisplay?"showing":"hidden";e.mode!==t&&(e.mode=t)}}setSubtitleTrack(e){let t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!eV(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.selectDefaultTrack=!1;let i=this.currentTrack,s=t[e]||null;if(this.trackId=e,this.currentTrack=s,this.toggleTrackModes(),!s)return void this.hls.trigger(eX.SUBTITLE_TRACK_SWITCH,{id:e});let r=!!s.details&&!s.details.live;if(e===this.trackId&&s===i&&r)return;this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));let{id:a,groupId:n="",name:l,type:o,url:d}=s;this.hls.trigger(eX.SUBTITLE_TRACK_SWITCH,{id:a,groupId:n,name:l,type:o,url:d});let h=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(h)}},timelineController:class{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=nZ(),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}}
29,e.on(eX.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(eX.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.on(eX.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(eX.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(eX.FRAG_LOADING,this.onFragLoading,this),e.on(eX.FRAG_LOADED,this.onFragLoaded,this),e.on(eX.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(eX.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(eX.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(eX.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(eX.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(eX.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(eX.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.off(eX.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(eX.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(eX.FRAG_LOADING,this.onFragLoading,this),e.off(eX.FRAG_LOADED,this.onFragLoaded,this),e.off(eX.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(eX.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(eX.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(eX.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(eX.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new nz(this,"textTrack1"),t=new nz(this,"textTrack2"),i=new nz(this,"textTrack3"),s=new nz(this,"textTrack4");this.cea608Parser1=new nA(1,e,t),this.cea608Parser2=new nA(3,i,s)}addCues(e,t,i,s,r){let a=!1;for(let e=r.length;e--;){var n,l;let s=r[e],o=(n=s[0],l=s[1],Math.min(l,i)-Math.max(n,t));if(o>=0&&(s[0]=Math.min(s[0],t),s[1]=Math.max(s[1],i),a=!0,o/(i-t)>.5))return}if(a||r.push([t,i]),this.config.renderTextTracksNatively){let r=this.captionsTracks[e];this.Cues.newCue(r,t,i,s)}else{let r=this.Cues.newCue(null,t,i,s);this.hls.trigger(eX.CUES_PARSED,{type:"captions",cues:r,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:r,trackId:a}){let{unparsedVttFrags:n}=this;i===e1&&(this.initPTS[t.cc]={baseTime:s,timescale:r,trackId:a}),n.length&&(this.unparsedVttFrags=[],n.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(eX.FRAG_LOADED,e):this.hls.trigger(eX.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){let{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){let r=i.textTracks[s];if(nQ(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:i,media:s}=this,{label:r,languageCode:a}=t[e],n=this.getExistingTrack(r,a);if(n)i[e]=n,a3(i[e]),a1(i[e],s);else{let t=this.createTextTrack("captions",r,a);t&&(t[e]=!0,i[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(eX.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,i){let s=this.media;if(s)return s.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){let i=!!t.transferMedia;if(this.media=null,i)return;let{captionsTracks:s}=this;Object.keys(s).forEach(e=>{a3(s[e]),delete s[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=nZ(),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(){let{media:e}=this;if(!e)return;let t=e.textTracks;
29if(t)for(let e=0;e<t.length;e++)a3(t[e])}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[],s=i.some(e=>e.textCodec===nU);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(ar(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){let e=this.media,t=e?a5(e.textTracks):null;if(this.tracks.forEach((e,i)=>{let s;if(t){let i=null;for(let s=0;s<t.length;s++)if(t[s]&&nQ(t[s],e)){i=t[s],t[s]=null;break}i&&(s=i)}if(s)a3(s);else{let t=nX(e);(s=this.createTextTrack(t,e.name,e.lang))&&(s.mode="disabled")}s&&this.textTracks.push(s)}),null!=t&&t.length){let e=t.filter(e=>null!==e).map(e=>e.label);e.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){let e=this.tracks.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(eX.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{let t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;let i=`textTrack${t[1]}`,s=this.captionsProperties[i];s&&(s.label=e.name,e.lang&&(s.languageCode=e.lang),s.media=e)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===e1){var i,s;let{cea608Parser1:e,cea608Parser2:r,lastSn:a}=this,{cc:n,sn:l}=t.frag,o=null!=(i=null==(s=t.part)?void 0:s.index)?i:-1;e&&r&&(l!==a+1||l===a&&o!==this.lastPartIndex+1||n!==this.lastCc)&&(e.reset(),r.reset()),this.lastCc=n,this.lastSn=l,this.lastPartIndex=o}}onFragLoaded(e,t){let{frag:i,payload:s}=t;if(i.type===e3)if(s.byteLength){let e=i.decryptdata,r="stats"in t;if(null==e||!e.encrypted||r){let e=this.tracks[i.level],r=this.vttCCs;r[i.cc]||(r[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),e&&e.textCodec===nU?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(eX.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:Error("Empty subtitle payload")})}_parseIMSC1(e,t){let i=this.hls;nj(t,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),i.trigger(eX.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},t=>{i.logger.log(`Failed to parse IMSC1: ${t}`),i.trigger(eX.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}_parseVTTs(e){var t,i,s,r,a,n,l,o;let d,h,u,c,f,g,m,p,y,{frag:v,payload:T}=e,{initPTS:E,unparsedVttFrags:S}=this,L=E.length-1;if(!E[v.cc]&&-1===L)return void S.push(e);let k=this.hls;i=null!=(t=v.initSegment)&&t.data?tM(v.initSegment.data,new Uint8Array(T)).buffer:T,s=this.initPTS[v.cc],r=this.vttCCs,a=v.cc,n=v.start,l=e=>{this._appendCues(e,v.level),k.trigger(eX.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:v})},o=t=>{let i="Missing initPTS for VTT MPEGTS"===t.message;i?S.push(e):this._fallbackToIMSC1(v,T),k.logger.log(`Failed to parse VTT cue: ${t}`),i&&L>v.cc||k.trigger(eX.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:v,error:t})},h=new nF,u=tl(new Uint8Array(i)).trim().replace(nw,"\n").split("\n"),c=[],f=s?function(e,t=1){return rY(e,9e4,1/t)}(s.baseTime,s.timescale):0,g="00:00.000",m=0,p=0,y=!0,h.oncue=function(e){let t=r[a],i=r.ccOffset,l=(m-f)/9e4;if(null!=t&&t.new&&(void 0!==p?i=r.ccOffset=t.start:nB(r,a,l)),l){if(!s){d=Error("Missing initPTS for VTT MPEGTS");return}i=l-r.presentationOffset}let o=e.endTime-e.startTime,h=r0((e.startTime+i-p)*9e4,9e4*n)/9e4;e.startTime=Math.max(h,0),e.endTime=Math.max(h+o,0);let u=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(u)),e.id||(e.id=nN(e.startTime,e.endTime,u)),e.endTime>0&&c.push(e)},h.onparsingerror=function(e){d=e},h.onflush=function(){d?o(d):l(c)},u.forEach(e=>{if(y)if(nM(e,"X-TIMESTAMP-MAP=")){y=!1,e.slice(16).split(",").forEach(e=>{nM(e,"LOCAL:")?g=e.slice(6):nM(e,"MPEGTS:")&&(m=parseInt(e.slice(7)))});try{p=nO(g)/1e3}catch(e){d=e}return}else""===e&&(y=!1);h.parse(e+"\n")}),h.flush()}_fallbackToIMSC1(e,t){let i=this.tracks[e.level];i.textCodec||nj(t,this.initPTS[e.cc],()=>{i.textCodec=nU,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){let i=this.textTracks[t];if(!i||"disabled"===i.mode)return;
29e.forEach(e=>a2(i,e))}else{let s=this.tracks[t];if(!s)return;let r=s.default?"default":"subtitles"+t;i.trigger(eX.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){let{frag:i}=t;i.type===e3&&this.onFragLoaded(eX.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:i,samples:s}=t;if(i.type!==e1||"NONE"!==this.closedCaptionsForLevel(i))for(let e=0;e<s.length;e++){let t=s[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();let i=this.extractCea608Data(t);this.cea608Parser1.addData(s[e].pts,i[0]),this.cea608Parser2.addData(s[e].pts,i[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:s,type:r}){let{media:a}=this;if(a&&!(a.currentTime<i)){if(!r||"video"===r){let{captionsTracks:e}=this;Object.keys(e).forEach(s=>a4(e[s],t,i))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==s){let{textTracks:e}=this;Object.keys(e).forEach(i=>a4(e[i],t,s))}}}extractCea608Data(e){let t=[[],[]],i=31&e[0],s=2;for(let r=0;r<i;r++){let i=e[s++],r=127&e[s++],a=127&e[s++];if((0!==r||0!==a)&&(4&i)!=0){let e=3&i;(0===e||1===e)&&(t[e].push(r),t[e].push(a))}}return t}},audioStreamController:class extends s6{constructor(e,t,i){super(e,t,i,"audio-stream-controller",e2),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();let{hls:e}=this;e.on(eX.LEVEL_LOADED,this.onLevelLoaded,this),e.on(eX.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(eX.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(eX.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(eX.BUFFER_RESET,this.onBufferReset,this),e.on(eX.BUFFER_CREATED,this.onBufferCreated,this),e.on(eX.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(eX.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(eX.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(eX.FRAG_LOADING,this.onFragLoading,this),e.on(eX.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(eX.LEVEL_LOADED,this.onLevelLoaded,this),e.off(eX.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(eX.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(eX.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(eX.BUFFER_RESET,this.onBufferReset,this),e.off(eX.BUFFER_CREATED,this.onBufferCreated,this),e.off(eX.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(eX.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(eX.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(eX.FRAG_LOADING,this.onFragLoading,this),e.off(eX.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:r,trackId:a}){if(i===e1){let e=t.cc,i=this.fragCurrent;if(this.initPTS[e]={baseTime:s,timescale:r,trackId:a},this.log(`InitPTS for cc: ${e} found from main: ${s/r} (${s}/${r}) trackId: ${a}`),this.mainAnchor=t,this.state===s5){let i=this.waitingData;(i||this.loadingParts)&&(!i||i.frag.cc===e)||this.syncWithAnchor(t,null==i?void 0:i.frag)}else!this.hls.hasEnoughToStart&&i&&i.cc!==e?(i.abortRequests(),this.syncWithAnchor(t,i)):this.state===sX&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;let s=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(t&&(null==s?void 0:s.cc)===t.cc)return;let r=(s||e).cc,a=im(this.getLevelDetails(),r,this.getLoadPosition());a&&(this.log(`Syncing with main frag at ${a.start} cc ${a.cc}`),this.startFragRequested=!1,this.nextLoadPosition=a.start,this.resetLoadingState(),this.state===sX&&this.doTickIdle())}
29startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=sz;return}let i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=sX):this.state=s0,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case sX:this.doTickIdle();break;case s0:{let{levels:e,trackId:t}=this,i=null==e?void 0:e[t],s=null==i?void 0:i.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=s5}break}case sJ:this.checkRetryDate();break;case s5:{let e=this.waitingData;if(e){let{frag:t,part:i,cache:s,complete:r}=e,a=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=sZ;let e={frag:t,part:i,payload:s.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),r&&super._handleFragmentLoadComplete(e)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=sX}}this.onTickEnd()}resetLoadingState(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){let{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;let{hls:t,levels:i,media:s,trackId:r}=this,a=t.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(null!=i&&i[r]))return;let n=i[r],l=n.details;if(!l||this.waitForLive(n)||this.waitForCdnTuneIn(l)){this.state=s0,this.startFragRequested=!1;return}let o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,tf,e2));let d=this.getFwdBufferInfo(o,e2);if(null===d)return;if(!this.switchingTrack&&this._streamEnded(d,l)){t.trigger(eX.BUFFER_EOS,{type:"audio"}),this.state=s3;return}let h=d.len,u=t.maxBufferLength,c=l.fragments,f=c[0].start,g=this.getLoadPosition(),m=this.flushing?g:d.end;if(this.switchingTrack&&s&&l.PTSKnown&&g<f&&(d.end>f||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=f+.05),h>=u&&!this.switchingTrack&&m<c[c.length-1].start)return;let p=this.getNextFragment(m,l);if(p&&this.isLoopLoading(p,m)&&(p=this.getNextFragmentLoopLoading(p,l,d,e1,u)),!p){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(d,u,p))return;let y=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&ty(p)&&!p.endList&&(!l.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&("OK"===this.fragmentTracker.getState(y)&&(this.mainFragLoading=y=null),y&&ty(y))){if(p.start>y.end){let e=this.fragmentTracker.getFragAtPos(m,e1);e&&e.end>y.end&&(y=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(p.start>y.end)return}this.loadFragment(p,n,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new t7(e))}onAudioTrackSwitching(e,t){let i=!!t.url;this.trackId=t.id;let{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==sz&&(this.setInterval(100),this.state=sX,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;let i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(eX.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i,s;let{levels:r}=this,{details:a,id:n,groupId:l,track:o}=t;if(!r)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${l}"`);let d=this.mainDetails;if(!d||a.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==sz&&(this.state=s0);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${l}" loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`);let h=r[n],u=0;if(a.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;h.details&&(u=this.alignPlaylists(a,h.details,null==(s=this.levelLastLoaded)?void 0:s.details)),a.alignedSliding||(sH(a,d),a.alignedSliding||sV(a,d),u=a.fragmentStart)}h.details=a,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(d,u),this.hls.trigger(eX.AUDIO_TRACK_UPDATED,{details:a,id:n,groupId:t.groupId}),this.state!==s0||this.waitForCdnTuneIn(a)||(this.state=sX),this.tick()}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:s,payload:r}
29=e,{config:a,trackId:n,levels:l}=this;if(!l)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);let o=l[n];if(!o)return void this.warn("Audio track is undefined on fragment load progress");let d=o.details;if(!d){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}let h=a.defaultAudioCodec||o.audioCodec||"mp4a.40.2",u=this.transmuxer;u||(u=this.transmuxer=new ai(this.hls,e2,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let c=this.initPTS[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==c){let e=s?s.index:-1,t=new iK(i.level,i.sn,i.stats.chunkCount,r.byteLength,e,-1!==e);u.push(r,f,h,"",i,s,d.totalduration,!1,t,c)}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 ${n}`);let{cache:e}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new s7,complete:!1};e.push(new Uint8Array(r)),this.state!==sz&&(this.state=s5)}}_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;let i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===e1&&ty(t.frag)&&(this.mainFragLoading=t,this.state===sX&&this.tick())}onFragBuffered(e,t){let{frag:i,part:s}=t;if(i.type!==e2){this.audioOnly||i.type!==e1||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i))return void 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"}`);if(ty(i)){this.fragPrevious=i;let e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(eX.AUDIO_TRACK_SWITCHED,e9({},e)))}this.fragBufferedComplete(i,s),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=s4;return}switch(t.details){case ez.FRAG_GAP:case ez.FRAG_PARSING_ERROR:case ez.FRAG_DECRYPT_ERROR:case ez.FRAG_LOAD_ERROR:case ez.FRAG_LOAD_TIMEOUT:case ez.KEY_LOAD_ERROR:case ez.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(e2,t);break;case ez.AUDIO_TRACK_LOAD_ERROR:case ez.AUDIO_TRACK_LOAD_TIMEOUT:case ez.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==s0||(null==(i=t.context)?void 0:i.type)!==eJ||(this.state=sX);break;case ez.BUFFER_ADD_CODEC_ERROR:case ez.BUFFER_APPEND_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case ez.BUFFER_FULL_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,1/0,"audio"));break;case ez.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==tg&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==tg){this.flushing=!1,this.bufferFlushed=!0,this.state===s3&&(this.state=sX);let e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,e2),this.tick())}}_handleTransmuxComplete(e){var t;let i="audio",{hls:s}=this,{remuxResult:r,chunkMeta:a}=e,n=this.getCurrentContext(a);if(!n)return void this.resetWhenMissingContext(a);let{frag:l,part:o,level:d}=n,{details:h}=d,{audio:u,text:c,id3:f,initSegment:g}=r;if(this.fragContextChanged(l)||!h)return void this.fragmentTracker.removeFragment(l);if(this.state=s1,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){let e=l.initSegment||l;if(this.unhandledEncryptionError(g,l))return;this._bufferInitSegment(d,g.tracks,e,a),s.trigger(eX.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:g.tracks})}if(u){let{startPTS:e,endPTS:t,startDTS:i,endDTS:s}=u;o&&(o.elementaryStreams[tf]={startPTS:e,endPTS:t,startDTS:i,endDTS:s}),l.setElementaryStreamInfo(tf,e,t,i,s),this.bufferFragmentData(u,l,o,a)}
29if(null!=f&&null!=(t=f.samples)&&t.length){let e=e8({id:i,frag:l,details:h},f);s.trigger(eX.FRAG_PARSING_METADATA,e)}if(c){let e=e8({id:i,frag:l,details:h},c);s.trigger(eX.FRAG_PARSING_USERDATA,e)}}_bufferInitSegment(e,t,i,s){if(this.state!==s1||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let r=t.audio;r.id=e2;let a=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a&&1===a.split(",").length&&(r.levelCodec=a),this.hls.trigger(eX.BUFFER_CODECS,t);let n=r.initSegment;if(null!=n&&n.byteLength){let e={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:n};this.hls.trigger(eX.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,i){let s=this.fragmentTracker.getState(e);if(this.switchingTrack||s===iR||s===iI){var r;if(ty(e))if(null!=(r=t.details)&&r.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=s5;let i=this.mainDetails;i&&i.fragmentStart!==t.details.fragmentStart&&sV(t.details,i)}else super.loadFragment(e,t,i);else this._loadInitSegment(e,t)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){let{name:t,lang:i,assocLang:s,characteristics:r,audioCodec:a,channels:n}=this.bufferedTrack;il({name:t,lang:i,assocLang:s,characteristics:r,audioCodec:a,channels:n},e,io)||(ih(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,1/0,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){let{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(eX.AUDIO_TRACK_SWITCHED,e9({},e))}},audioTrackController:class extends as{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(){let{hls:e}=this;e.on(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.on(eX.MANIFEST_PARSED,this.onManifestParsed,this),e.on(eX.LEVEL_LOADING,this.onLevelLoading,this),e.on(eX.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(eX.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(eX.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.off(eX.MANIFEST_PARSED,this.onManifestParsed,this),e.off(eX.LEVEL_LOADING,this.onLevelLoading,this),e.off(eX.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(eX.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(eX.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){let{id:i,groupId:s,details:r}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==s)return void this.warn(`Audio track with id:${i} and group:${s} not found in active group ${null==a?void 0:a.groupId}`);let n=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,n)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.audioGroups||null,s=this.groupIds,r=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some(e=>(null==s?void 0:s.indexOf(e))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let e=this.tracks.filter(e=>!i||-1!==i.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=e;let t=this.hls.config.audioPreference;if(!r&&t){let i=ia(t,e,io);if(i>-1)r=e[i];else{let e=ia(t,this.tracks);r=this.tracks[e]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null)),this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(eX.AUDIO_TRACKS_UPDATED,{audioTracks:e});let n=this.trackId;if(-1!==s&&-1===n)this.setAudioTrack(s);else if(e.length&&-1===n){var a;let t=Error(`No audio track selected for current audio group-ID(s): ${null==(a=this.groupIds)?void 0:a.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(eX.ERROR,{type:eq.MEDIA_ERROR,details:ez.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&(t.context.type!==eJ||t.context.
29id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||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){let t=this.hls;if(t.config.audioPreference=e,e){let r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){let a=this.currentTrack;if(a&&il(e,a,io))return a;let n=ia(e,this.tracksInGroup,io);if(n>-1){let e=this.tracksInGroup[n];return this.setAudioTrack(n),e}if(a){var i,s;let a,n,l,o,d,h,u=t.loadLevel;-1===u&&(u=t.firstAutoLevel);let c=(i=t.levels,a=i[s=u],(n=i.reduce((e,t,i)=>{let s=t.uri;return(e[s]||(e[s]=[])).push(i),e},{})[a.uri]).length>1&&(s=Math.max.apply(Math,n)),l=a.videoRange,o=a.frameRate,d=a.codecSet.substring(0,4),(h=id(i,s,t=>{if(t.videoRange!==l||t.frameRate!==o||t.codecSet.substring(0,4)!==d)return!1;let i=t.audioGroups;return ia(e,r.filter(e=>!i||-1!==i.indexOf(e.groupId)),io)>-1}))>-1?h:id(i,s,t=>{let i=t.audioGroups;return ia(e,r.filter(e=>!i||-1!==i.indexOf(e.groupId)),io)>-1}));if(-1===c)return null;t.nextLoadLevel=c}if(e.channels||e.audioCodec){let t=ia(e,r);if(t>-1)return r[t]}}}return null}setAudioTrack(e){let t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.selectDefaultTrack=!1;let i=this.currentTrack,s=t[e],r=s.details&&!s.details.live;if(e===this.trackId&&s===i&&r||(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(eX.AUDIO_TRACK_SWITCHING,e9({},s)),r))return;let a=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(a)}findTrackId(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let s=t[i];if((!this.selectDefaultTrack||s.default)&&(!e||il(e,s,io)))return i}if(e){let{name:i,lang:s,assocLang:r,characteristics:a,audioCodec:n,channels:l}=e;for(let e=0;e<t.length;e++)if(il({name:i,lang:s,assocLang:r,characteristics:a,audioCodec:n,channels:l},t[e],io))return e;for(let i=0;i<t.length;i++){let s=t[i];if(aa(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){let s=t[i];if(aa(e.attrs,s.attrs,["LANGUAGE"]))return i}}return -1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&ih(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,s=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,n=null==a?void 0:a.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${s}${(null==t?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${n&&a.live?" age "+n.toFixed(1)+(a.type?" "+a.type:""):""} ${r}`),this.hls.trigger(eX.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null,track:e})}},emeController:aQ,cmcdController:class{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=e=>{try{this.apply(e,{ot:"m",su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{let{frag:t,part:i}=e,s=this.hls.levels[t.level],r=this.getObjectType(t),a={d:1e3*(i||t).duration,ot:r};("v"===r||"a"===r||"av"==r)&&(a.br=s.bitrate/1e3,a.tb=this.getTopBandwidth(r)/1e3,a.bl=this.getBufferLength(r));let n=i?this.getNextPart(i):this.getNextFrag(t);null!=n&&n.url&&n.url!==t.url&&(a.nor=n.url),this.apply(e,a)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;null!=i&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){let e=this.hls;
29e.on(eX.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(eX.MEDIA_DETACHED,this.onMediaDetached,this),e.on(eX.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(eX.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(eX.MEDIA_DETACHED,this.onMediaDetached,this),e.off(eX.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=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(s=t.tracks.video)?void 0:s.buffer}createData(){var e;return{v:1,sf:"h",sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){e8(t,this.createData());let i="i"===t.ot||"v"===t.ot||"av"===t.ot;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);let{includeKeys:s}=this;s&&(t=Object.keys(t).reduce((e,i)=>(s.includes(i)&&(e[i]=t[i]),e),{}));let r={baseUrl:e.url};if(this.useHeaders){var a;e.headers||(e.headers={}),a=e.headers,e8(a,function(e,t={}){let i={};return e?Object.entries(function(e,t){let i={};if(!e)return i;let s=Object.keys(e),r=t?Object.keys(t).reduce((e,i)=>{var s;return null==(s=t[i])||s.forEach(t=>e[t]=i),e},{}):{};return s.reduce((t,i)=>{var s;let a=aD[i]||r[i]||aI;return(null!=(s=t[a])?s:t[a]={})[i]=e[i],t},i)}(aY(e,t),null==t?void 0:t.customHeaderMap)).reduce((e,[t,i])=>{let s=aR(i,{whitespace:!1});return s&&(e[t]=s),e},i):i}(t,r))}else e.url=function(e,t,i){let s=function(e,t={}){if(!e)return"";let i=function(e,t={}){return e?encodeURIComponent(function(e,t={}){return e?aR(aY(e,t),{whitespace:!1}):""}(e,t)):""}(e,t);return`CMCD=${i}`}(t,i);if(!s)return e;if(aq.test(e))return e.replace(aq,s);let r=e.includes("?")?"&":"?";return`${e}${r}${s}`}(e.url,t,r)}getNextFrag(e){var t;let i=null==(t=this.hls.levels[e.level])?void 0:t.details;if(i){let t=e.sn-i.startSN;return i.fragments[t+1]}}getNextPart(e){var t;let{index:i,fragment:s}=e,r=null==(t=this.hls.levels[s.level])||null==(t=t.details)?void 0:t.partList;if(r){let{sn:e}=s;for(let t=r.length-1;t>=0;t--){let s=r[t];if(s.index===i&&s.fragment.sn===e)return r[t+1]}}}getObjectType(e){let{type:t}=e;return"subtitle"===t?"tt":"initSegment"===e.sn?"i":"audio"===t?"a":"main"===t?this.hls.audioTracks.length?"v":"av":void 0}getTopBandwidth(e){let t,i=0,s=this.hls;if("a"===e)t=s.audioTracks;else{let e=s.maxAutoLevel,i=e>-1?e+1:s.levels.length;t=s.levels.slice(0,i)}return t.forEach(e=>{e.bitrate>i&&(i=e.bitrate)}),i>0?i:NaN}getBufferLength(e){let t=this.media,i="a"===e?this.audioBuffer:this.videoBuffer;return i&&t?1e3*iH.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len:NaN}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,s){t(e),this.loader.load(e,i,s)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,s){t(e),this.loader.load(e,i,s)}}}},contentSteeringController:class extends e7{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(){let e=this.hls;e.on(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.on(eX.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(eX.MANIFEST_PARSED,this.onManifestParsed,this),e.on(eX.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.off(eX.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(eX.MANIFEST_PARSED,this.onManifestParsed,this),e.off(eX.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>
29(-1===e.indexOf(t.pathwayId)&&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){let e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(t=>t!==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){let{contentSteering:i}=t;null!==i&&(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){let{errorAction:i}=t;if((null==i?void 0:i.action)===2&&1===i.flags){let e=this.levels,s=this._pathwayPriority,r=this.pathwayId;if(t.context){let{groupId:i,pathwayId:s,type:a}=t.context;i&&e?r=this.getPathwayForGroupId(i,a,r):s&&(r=s)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!s&&e&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==r),t.details!==ez.BUFFER_APPEND_ERROR||t.fatal?i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${r} levels: ${e?e.length:e} priorities: ${it(s)} penalized: ${it(this.penalizedPathways)}`):i.resolved=!0}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){let 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 null===this.levels?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){let t;this._pathwayPriority=e;let i=this.penalizedPathways,s=performance.now();
29Object.keys(i).forEach(e=>{s-i[e]>3e5&&delete i[e]});for(let s=0;s<e.length;s++){let r=e[s];if(r in i)continue;if(r===this.pathwayId)return;let a=this.hls.nextLoadLevel,n=this.hls.levels[a];if((t=this.getLevelsForPathway(r)).length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,sU(t),this.hls.trigger(eX.LEVELS_UPDATED,{levels:t});let e=this.hls.levels[a];n&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==n.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==n.bitrate&&this.log(`Unstable Pathways change from bitrate ${n.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,i){let s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<s.length;i++)if(t===eJ&&s[i].hasAudioGroup(e)||t===e0&&s[i].hasSubtitleGroup(e))return s[i].pathwayId;return i}clonePathways(e){let t=this.levels;if(!t)return;let i={},s={};e.forEach(e=>{let{ID:r,"BASE-ID":a,"URI-REPLACEMENT":n}=e;if(t.some(e=>e.pathwayId===r))return;let l=this.getLevelsForPathway(a).map(e=>{let t=new iX(e.attrs);t["PATHWAY-ID"]=r;let a=t.AUDIO&&`${t.AUDIO}_clone_${r}`,l=t.SUBTITLES&&`${t.SUBTITLES}_clone_${r}`;a&&(i[t.AUDIO]=a,t.AUDIO=a),l&&(s[t.SUBTITLES]=l,t.SUBTITLES=l);let o=aX(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",n),d=new t7({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:o,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)d.addGroupId("audio",`${e.audioGroups[t]}_clone_${r}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)d.addGroupId("text",`${e.subtitleGroups[t]}_clone_${r}`);return d});t.push(...l),az(this.audioTracks,i,n,r),az(this.subtitleTracks,s,n,r)})}loadSteeringManifest(e){let t,i=this.hls.config,s=i.loader;this.loader&&this.loader.destroy(),this.loader=new s(i);try{t=new self.URL(e)}catch(t){this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if("data:"!==t.protocol){let e=0|(this.hls.bandwidthEstimate||i.abrEwmaDefaultEstimate);t.searchParams.set("_HLS_pathway",this.pathwayId),t.searchParams.set("_HLS_throughput",""+e)}let r={responseType:"json",url:t.href},a=i.steeringManifestLoadPolicy.default,n=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0};this.log(`Requesting steering manifest: ${t}`),this.loader.load(r,l,{onSuccess:(e,i,s,r)=>{this.log(`Loaded steering manifest: "${t}"`);let a=e.data;if((null==a?void 0:a.VERSION)!==1)return void this.log(`Steering VERSION ${a.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=a.TTL;let{"RELOAD-URI":n,"PATHWAY-CLONES":l,"PATHWAY-PRIORITY":o}=a;if(n)try{this.uri=new self.URL(n,t).href}catch(e){this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${n}`);return}this.scheduleRefresh(this.uri||s.url),l&&this.clonePathways(l);let d={steeringManifest:a,url:t.toString()};this.hls.trigger(eX.STEERING_MANIFEST_LOADED,d),o&&this.updatePathwayPriority(o)},onError:(e,t,i,s)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code){this.enabled=!1,this.log(`Steering manifest ${t.url} no longer available`);return}let r=1e3*this.timeToLoad;if(429===e.code){let e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){let t=e.getResponseHeader("Retry-After");t&&(r=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`);return}this.scheduleRefresh(this.uri||t.url,r)},onTimeout:(e,t,i)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}})}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var t;let i=null==(t=this.hls)?void 0:t.media;i&&!i.ended?this.loadSteeringManifest(e):this.scheduleRefresh(e,1e3*this.timeToLoad)},t)}},interstitialsController:class extends e7{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}
29,this.onSeeking=()=>{var e,t;let i=this.currentTime;if(void 0===i||this.playbackDisabled||!this.schedule)return;let s=i-this.timelinePos;if(Math.abs(s)<1/7056e5)return;let r=s<=-.01;-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),this.timelinePos=i,this.bufferedPos=i;let a=this.playingItem;if(!a)return void this.checkBuffer();if(r&&this.schedule.resetErrorsInRange(i,i-s)&&this.updateSchedule(!0),this.checkBuffer(),r&&i<a.start||i>=a.end){let t=this.findItemIndex(a),s=this.schedule.findItemIndexAtTime(i);if(-1===s&&(s=t+(r?-1:1),this.log(`seeked ${r?"back ":""}to position not covered by schedule ${i} (resolving from ${t} to ${s})`)),!this.isInterstitial(a)&&null!=(e=this.media)&&e.paused&&(this.shouldPlay=!1),!r&&s>t){let e=this.schedule.findJumpRestrictedIndex(t+1,s);if(e>t)return void this.setSchedulePosition(e)}this.setSchedulePosition(s);return}let n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(a)){let e=a.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,e))}return}let l=n.timelineStart,o=n.duration||0;(r&&i<l||i>=l+o)&&(null!=(t=a.event)&&t.appendInPlace&&(this.clearAssetPlayers(a.event,a),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,n))},this.onTimeupdate=()=>{let e=this.currentTime;if(void 0===e||this.playbackDisabled||(-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),!(e>this.timelinePos)))return;this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();let t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}let i=this.playingAsset;!i||e>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(e,i)},this.onScheduleUpdate=(e,t)=>{let i=this.schedule;if(!i)return;let s=this.playingItem,r=i.events||[],a=i.items||[],n=i.durations,l=e.map(e=>e.identifier),o=!!(r.length||l.length);(o||t)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}
30Schedule: ${a.map(e=>na(e))} pos: ${this.timelinePos}`),l.length&&this.log(`Removed events ${l}`);let d=null,h=null;s&&(d=this.updateItem(s,this.timelinePos),this.itemsMatch(s,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);let u=this.bufferingItem;if(u&&(h=this.updateItem(u,this.bufferedPos),this.itemsMatch(u,h)?this.bufferingItem=h:u.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(u.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){let t=e.assetItem.timelineStart,i=e.timelineOffset-t;if(i)try{e.timelineOffset=t}catch(s){Math.abs(i)>.025&&this.warn(`${s} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}}),o||t){if(this.hls.trigger(eX.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:a.slice(0),durations:n,removedIds:l}),this.isInterstitial(s)&&l.includes(s.event.identifier)){this.warn(`Interstitial "${s.event.identifier}" removed while playing`),this.primaryFallback(s.event);return}s&&this.trimInPlace(d,s),u&&h!==d&&this.trimInPlace(h,u),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new nn(e),this.schedule=new nr(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(eX.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(eX.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(eX.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.on(eX.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(eX.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(eX.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(eX.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(eX.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(eX.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(eX.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(eX.BUFFER_APPENDED,this.onBufferAppended,this),e.on(eX.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(eX.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(eX.MEDIA_ENDED,this.onMediaEnded,this),e.on(eX.ERROR,this.onError,this),e.on(eX.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;
30e&&(e.off(eX.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(eX.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(eX.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.off(eX.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(eX.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(eX.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(eX.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(eX.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(eX.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(eX.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(eX.BUFFER_CODECS,this.onBufferCodecs,this),e.off(eX.BUFFER_APPENDED,this.onBufferAppended,this),e.off(eX.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(eX.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(eX.MEDIA_ENDED,this.onMediaEnded,this),e.off(eX.ERROR,this.onError,this),e.off(eX.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.getBufferingPlayer())||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.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){sY(e,"play",this.onPlay),sY(e,"pause",this.onPause),sY(e,"seeking",this.onSeeking),sY(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){let i=this.media=t.media;sW(i,"seeking",this.onSeeking),sW(i,"timeupdate",this.onTimeupdate),sW(i,"play",this.onPlay),sW(i,"pause",this.onPause)}onMediaAttached(e,t){let i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!s){this.clearScheduleState();let e=this.findItemIndex(i);this.setSchedulePosition(e)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let i=!!t.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){let e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=t=>t?e.getAssetPlayer(t.identifier):t,i=(i,r,a,n,l)=>{if(i){let o=i[r].start,d=i.event;if(d){if("playout"===r||d.timelineOccupancy!==a6.Point){let e=t(a);(null==e?void 0:e.interstitial)===d&&(o+=e.assetItem.startOffset+e[l])}}else o+=("bufferedPos"===n?s():e[n])-i.start;return o}return 0},s=()=>{let t=e.bufferedPos;return t===Number.MAX_VALUE?r("primary"):Math.max(t,0)},r=t=>{var i,s;return null!=(i=e.primaryDetails)&&i.live?e.primaryDetails.edge:(null==(s=e.schedule)?void 0:s.durations[t])||0},a=(s,r)=>{var a,n;let l=e.effectivePlayingItem;if(null!=l&&null!=(a=l.event)&&a.restrictions.skip||!e.schedule)return;e.log(`seek to ${s} "${r}"`);let o=e.effectivePlayingItem,d=e.schedule.findItemIndexAtTime(s,r),h=null==(n=e.schedule.items)?void 0:n[d],u=e.getBufferingPlayer(),c=null==u?void 0:u.interstitial,f=null==c?void 0:c.appendInPlace,g=o&&e.itemsMatch(o,h);if(o&&(f||g)){let a=t(e.playingAsset),n=(null==a?void 0:a.media)||e.primaryMedia;if(n){let t="primary"===r?n.currentTime:i(o,r,e.playingAsset,"timelinePos","currentTime"),l=s-t,d=(f?t:n.currentTime)+l;if(d>=0&&(!a||f||d<=a.duration)){n.currentTime=d;return}}}if(h){let t=s;if("primary"!==r){let e=s-h[r].start;t=h.start+e}let i=!e.isInterstitial(h);if((!e.isInterstitial(o)||o.event.appendInPlace)&&(i||h.event.appendInPlace)){let i=e.media||(f?null==u?void 0:u.media:null);i&&(i.currentTime=t)}else if(o){let a=e.findItemIndex(o);if(d>a){let t=e.schedule.findJumpRestrictedIndex(a+1,d);if(t>a)return void e.setSchedulePosition(t)}let n=0;if(i)e.timelinePos=t,e.checkBuffer();else{let e=h.event.assetList,t=s-(h[r]||h).start;for(let i=e.length;i--;){let s=e[i];if(s.duration&&t>=s.startOffset&&t<s.startOffset+s.duration){n=i;break}}}e.setSchedulePosition(d,n)}}},n=()=>{let t=e.effectivePlayingItem;if(e.isInterstitial(t))return t;let i=e.bufferingItem||e.waitingItem;return e.isInterstitial(i)?i:null},l={get bufferedEnd(){let t=e.bufferingItem||e.waitingItem,s=e.bufferingItem;if(s&&s===t){var o;return i(s,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-s.playout.start||(null==(o=e.bufferingAsset)?void 0:o.startOffset)||0}return 0},get currentTime(){let t=n(),s=e.effectivePlayingItem;if(s&&s===t)return i(s,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-s.playout.start;return 0},set currentTime(time){let t=n(),i=e.effectivePlayingItem;i&&i===t&&a(time+i.playout.start,"playout")},get duration(){let e=n();if(e)return e.playout.end-e.playout.start;return 0},get assetPlayers(){var d;let t=null==(d=n())?void 0:d.event.assetList;if(t)return t.map(t=>e.getAssetPlayer(t.identifier));return[]},get playingIndex(){var h;let t=null==(h=n())?void 0:h.event;if(t&&e.effectivePlayingAsset)return t.findAssetIndex(e.effectivePlayingAsset);return -1},get scheduleItem(){return n()}};return this.manager={get events(){var u;return(null==(u=e.schedule)||null==(u=u.events)?void 0:u.slice(0))||[]},get schedule(){var c;return(null==(c=e.schedule)||null==(c=c.items)?void 0:c.slice(0))||[]},get interstitialPlayer(){if(n())return l;return null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return e.bufferingItem||e.waitingItem},get bufferingIndex(){let t=e.bufferingItem||e.waitingItem;return e.findItemIndex(t)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return s()},get currentTime(){let t=e.timelinePos;return t>0?t:0},set currentTime(time){a(time,"primary")},get duration(){return r("primary")},get seekableStart(){var f;return(null==(f=e.primaryDetails)?void 0:f.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(e.bufferingItem||e.waitingItem,"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(time){a(time,"integrated")},get duration(){return r("integrated")},get seekableStart(){var g;return((t,i)=>{var s,r;if(0!==t&&"primary"!==i&&null!=(s=e.schedule)&&s.length){let s=e.sc
30hedule.findItemIndexAtTime(t),a=null==(r=e.schedule.items)?void 0:r[s];if(a)return t+(a[i].start-a.start)}return t})((null==(g=e.primaryDetails)?void 0:g.fragmentStart)||0,"integrated")}},skip:()=>{let t=e.effectivePlayingItem,i=null==t?void 0:t.event;if(i&&!i.restrictions.skip){let s=e.findItemIndex(t);i.appendInPlace?a(t.playout.start+t.event.duration+.001,"playout"):e.advanceAfterAssetEnded(i,s,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;let t=this.playingItem,i=null==(e=this.schedule)?void 0:e.items;return!!this.playbackStarted&&!!t&&!!i&&this.findItemIndex(t)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var e,t;if(null===this.mediaSelection)return;let i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let s=this.media;!s&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(s=this.primaryMedia);let r=null==(t=s)?void 0:t.currentTime;if(void 0!==r&&eV(r))return r}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!!(null!=e&&e.event)}retreiveMediaSource(e,t){let i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){let 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}let i=e.transferMedia();this.log(`transfer MediaSource from ${e} ${it(i)}`),this.detachedData=i}else t&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(e,t){var i,s;let r;if(e.media===t)return;let a=null,n=this.hls,l=e!==n,o=l&&e.interstitial.appendInPlace,d=null==(i=this.detachedData)?void 0:i.mediaSource;if(n.media)o&&(a=n.transferMedia(),this.detachedData=a),r="Primary";else if(d){let e=this.getBufferingPlayer();e?(a=e.transferMedia(),r=`${e}`):r="detached MediaSource"}else r="detached media";if(!a){if(d)a=this.detachedData,this.log(`using detachedData: MediaSource ${it(a)}`);else if(!this.detachedData||n.media===t){let e=this.playerQueue;e.length>1&&e.forEach(e=>{if(l&&e.interstitial.appendInPlace!==o){let t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let h=a&&"mediaSource"in a&&(null==(s=a.mediaSource)?void 0:s.readyState)!=="closed",u=h&&a?a:t;this.log(`${h?"transfering MediaSource":"attaching media"} to ${l?e:"Primary"} from ${r} (media.currentTime: ${t.currentTime})`);let c=this.schedule;if(u===a&&c){let t=l&&e.assetId===c.assetIdAtEnd;u.overrides={duration:c.duration,endOfStream:!l||t,cueRemoval:!l}}e.attachMedia(u)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=null==e?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);let i=this.timelinePos,s=this.effectivePlayingItem;if(-1===i){let i=this.hls.startPosition;if(this.timelinePos=i,0===t.length)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(no("checkStart (preroll)",i));let s=e.findEventIndex(t[0].identifier);this.setSchedulePosition(s)}else if(i>=0||!this.primaryLive){this.log(no("checkStart",i));let t=this.timelinePos=i>0?i:0,s=e.findItemIndexAtTime(t);this.setSchedulePosition(s)}else 0===this.hls.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(s&&!this.playingItem){this.log(no("checkStart (playing item)",s.start));let t=e.findItemIndex(s);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){let i=e.event,s=i.findAssetIndex(t),r=nt(i,s);if(i.isAssetPastPlayoutLimit(r)){if(this.schedule){var a;let t=null==(a=this.schedule.items)?void 0:a[this.findItemIndex(e)+1];t&&this.bufferedToItem(t)}}else this.bufferedToEvent(e,r)}advanceAfterAssetEnded(e,t,i){let s=nt(e,i);
30if(e.isAssetPastPlayoutLimit(s)){if(this.schedule){let i=this.schedule.items;if(i){let s=t+1;if(s>=i.length)return void this.setSchedulePosition(-1);let r=e.resumeTime;this.timelinePos<r&&(this.log(no("advanceAfterAssetEnded",r)),this.timelinePos=r,e.appendInPlace&&this.advanceInPlace(r),this.checkBuffer(this.bufferedPos<r)),this.setSchedulePosition(s)}}}else{if(e.appendInPlace){let t=e.assetList[s];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,s)}}setScheduleToAssetAtTime(e,t){let i=this.schedule;if(!i)return;let s=t.parentIdentifier,r=i.getEvent(s);if(r){let t=i.findEventIndex(s),a=i.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,t,a-1)}}setSchedulePosition(e,t){var i,s,r;let a=null==(i=this.schedule)?void 0:i.items;if(!a||this.playbackDisabled)return;let n=e>=0?a[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n?na(n):n}) pos: ${this.timelinePos}`);let l=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(l)){let i=l.event,d=this.playingAsset,h=null==d?void 0:d.identifier,u=h?this.getAssetPlayer(h):null;if(u&&h&&(!this.eventItemsMatch(l,n)||void 0!==t&&h!==i.assetList[t].identifier)){let t=i.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${i.assetList.length} ${ni(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(eX.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:t,event:i,schedule:a.slice(0),scheduleIndex:e,player:u}),l!==this.playingItem){this.itemsMatch(l,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),t);return}this.retreiveMediaSource(h,n),u.media&&!(null!=(s=this.detachedData)&&s.mediaSource)&&u.detachMedia()}if(!this.eventItemsMatch(l,n)&&(this.endedItem=l,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${na(l)}`),i.hasPlayed=!0,this.hls.trigger(eX.INTERSTITIAL_ENDED,{event:i,schedule:a.slice(0),scheduleIndex:e}),i.cue.once)){this.updateSchedule();let e=null==(r=this.schedule)?void 0:r.items;if(n&&e){let i=this.findItemIndex(n);this.advanceSchedule(i,e,t,l,o)}return}}this.advanceSchedule(e,a,t,l,o)}advanceSchedule(e,t,i,s,r){let a=this.schedule;if(!a)return;let n=t[e]||null,l=this.primaryMedia,o=this.playerQueue;if(o.length&&o.forEach(t=>{let i=t.interstitial,s=a.findEventIndex(i.identifier);(s<e||s>e+1)&&this.clearInterstitial(i,n)}),this.isInterstitial(n)){this.timelinePos=Math.min(Math.max(this.timelinePos,n.start),n.end);let r=n.event;if(void 0===i){i=a.findAssetIndex(r,this.timelinePos);let t=nt(r,i-1);if(r.isAssetPastPlayoutLimit(t)||r.appendInPlace&&this.timelinePos===n.end)return void this.advanceAfterAssetEnded(r,e,i);i=t}let o=this.waitingItem;this.assetsBuffered(n,l)||this.setBufferingItem(n);let d=this.preloadAssets(r,i);if(this.eventItemsMatch(n,o||s)||(this.waitingItem=n,this.log(`INTERSTITIAL_STARTED ${na(n)} ${r.appendInPlace?"append in place":""}`),this.hls.trigger(eX.INTERSTITIAL_STARTED,{event:r,schedule:t.slice(0),scheduleIndex:e})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!l)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=n;let h=r.assetList[i];if(!h)return void this.advanceAfterAssetEnded(r,e,i||0);if(d||(d=this.getAssetPlayer(h.identifier)),null===d||d.destroyed){let e=r.assetList.length;this.warn(`asset ${i+1}/${e} player destroyed ${r}`),(d=this.createAssetPlayer(r,h,i)).loadSource()}if(!this.eventItemsMatch(n,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(h))return;this.startAssetPlayer(d,i,t,e,l),this.shouldPlay&&nl(d.media)}else n?(this.resumePrimary(n,e,s),this.shouldPlay&&nl(this.hls.media)):r&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}get primaryLive(){var e;return!!(null!=(e=this.primaryDetails)&&e.live)}resumePrimary(e,t,i){var s,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${na(e)}`),!(null!=(s=this.detachedData)&&s.mediaSource)){let i=this.timelinePos;(i<e.start||i>=e.end)&&(i=this.getPrimaryResumption(e,t),this.log(no("resumePrimary",i)),this.timelinePos=i),this.attachPrimary(i,e)}if(!i)return;let a=null==(r=this.schedule)?void 0:r.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${na(e)}`),this.hls.trigger(eX.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){let i=e.start;if(this.primaryLive){let e=this.primaryDetails;if(0===t)return this.hls.startPosition;if(e&&(i<e.fragmentStart||i>e.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:iH.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;let s=this.primaryMedia;if(!s)return;let r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,s),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(no("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}
30startLoadingPrimaryAt(e,t){var i;let s=this.hls;!s.loadingEnabled||!s.media||Math.abs(((null==(i=s.mainForwardBufferInfo)?void 0:i.start)||s.media.currentTime)-e)>.5?s.startLoad(e,t):s.bufferingEnabled||s.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),null==(e=this.schedule)||e.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(eX.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(eX.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(-1===t.level||!this.schedule)return;let i=this.hls.levels[t.level];if(!i.details)return;let s=e9(e9({},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){let i=this.hls.audioTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=e9(e9({},this.altSelection),{},{audio:i});return}let r=e9(e9({},s),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){let i=this.hls.subtitleTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=e9(e9({},this.altSelection),{},{subtitles:i});return}let r=e9(e9({},s),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(e,t){let i=ir(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){let i=ir(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||-1!==t.id&&e.setSubtitleOption(i)))}onBufferCodecs(e,t){let i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){let e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){let s=t[e];if(s.cue.post){var i;let e=this.schedule.findEventIndex(s.identifier),t=null==(i=this.schedule.items)?void 0:i[e];this.isInterstitial(t)&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){var i;let s=null==(i=this.schedule)?void 0:i.items;return e&&s&&s[this.findItemIndex(e,t)]||null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((t,i)=>{e.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(t.identifier,null)});let i=e.end+.25,s=iH.bufferInfo(this.primaryMedia,i,0);(s.end>i||(s.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${na(e)} (was ${na(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===(null==(i=t.event)?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;let i=this.mediaSelection;i&&(null==(t=this.schedule)||t.updateSchedule(i,[],e))}checkBuffer(e){var t;let i=null==(t=this.schedule)?void 0:t.items;if(!i)return;let s=iH.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=s.len<1),this.updateBufferedPos(s.end,i,e)}updateBufferedPos(e,t,i){let s=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!s)return;if(1===t.length&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}let a=this.playingItem,n=this.findItemIndex(a),l=s.findItemIndexAtTime(e);if(this.bufferedPos<e){var o;let i=this.findItemIndex(r),s=Math.min(i+1,t.length-1),a=t[s];if((-1===l&&r&&e>=r.end||null!=(o=a.event)&&o.appendInPlace&&e+.01>=a.start)&&(l=s),this.isInterstitial(r)){let e=r.event;if(s-n>1&&!1===e.appendInPlace||0===e.assetList.length&&e.assetListLoader)return}if(this.bufferedPos=e,l>i&&l>n)this.bufferedToItem(a);else{let t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&a.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(a)&&this.preloadAssets(a.event,0)}}else i&&a&&!this.itemsMatch(a,r)&&(l===n?this.bufferedToItem(a):l===n+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return 0!==e.event.assetList.length&&!e.event.assetList.some(e=>{let i=this.getAssetPlayer(e.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){let{items:s,events:r}=i;if(!s||!r)return t;
30let a=this.isInterstitial(e),n=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let l=n?n.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${na(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){let t=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,i)=>{let s=this.getAssetPlayer(e.identifier);s&&(i===t&&s.loadSource(),s.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering());this.hls.trigger(eX.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==i){this.bufferingAsset=null;let t=this.detachedData;t&&t.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e)}}}preloadPrimary(e){let t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){let i=e.event,s=0===i.assetList.length&&!i.assetListLoader,r=i.cue.once;if(s||!r){let e=this.preloadAssets(i,t);if(null!=e&&e.interstitial.appendInPlace){let t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){let i=e.assetUrl,s=e.assetList.length,r=0===s&&!e.assetListLoader,a=e.cue.once;if(r){let r,a=e.timelineStart;if(e.appendInPlace){var n;let t=this.playingItem;this.isInterstitial(t)||(null==t||null==(n=t.nextEvent)?void 0:n.identifier)!==e.identifier||this.flushFrontBuffer(a+.25)}let l=0;if(!this.playingItem&&this.primaryLive&&-1===(l=this.hls.startPosition)&&(l=this.hls.liveSyncPosition||0),l&&!(e.cue.pre||e.cue.post)){let e=l-a;e>0&&(r=Math.round(1e3*e)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:s} ${e}${r?` live-start: ${l} start-offset: ${r}`:""}`),i)return this.createAsset(e,0,0,a,e.duration,i);let o=this.assetListLoader.loadAssetList(e,r);o&&(e.assetListLoader=o)}else if(!a&&s){for(let i=t;i<s;i++){let t=e.assetList[i],s=this.getAssetPlayerQueueIndex(t.identifier);(-1===s||this.playerQueue[s].destroyed)&&!t.error&&this.createAssetPlayer(e,t,i)}let i=e.assetList[t];if(i){let e=this.getAssetPlayer(i.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){let t=this.requiredTracks;t&&(this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(t=>{this.hls.trigger(eX.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})}))}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return -1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,s,r,a){let n={parentIdentifier:e.identifier,identifier:`${e.identifier}-${t+1}-${a8(a)}`,duration:r,startOffset:i,timelineStart:s,uri:a};return this.createAssetPlayer(e,n,t)}createAssetPlayer(e,t,i){let s=this.hls,r=s.userConfig,a=r.videoPreference,n=s.loadLevelObj||s.levels[s.currentLevel];(a||n)&&(a=e8({},a),n.videoCodec&&(a.videoCodec=n.videoCodec),n.videoRange&&(a.allowedVideoRanges=[n.videoRange]));let l=s.audioTracks[s.audioTrack],o=s.subtitleTracks[s.subtitleTrack],d=0;if(this.primaryLive||e.appendInPlace){let e=this.timelinePos-t.timelineStart;if(e>1){let i=t.duration;i&&e<i&&(d=e)}}let h=t.identifier,u=e9(e9({},r),{},{maxMaxBufferLength:Math.min(180,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:l||r.audioPreference,subtitlePreference:o||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(u.timelineOffset=t.timelineStart));let c=u.cmcd;null!=c&&c.sessionId&&c.contentId&&(u.cmcd=e8({},c,{contentId:a8(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);let f=new ns(this.HlsPlayerClass,u,e,t);this.playerQueue.push(f),e.assetList[i]=t;let g=!0,m=s=>{if(s.live){var r;let t=Error(`Interstitials MUST be VOD assets ${e}`),s={fatal:!0,type:eq.OTHER_ERROR,details:ez.INTERSTITIAL_ASSET_ITEM_ER
30ROR,error:t},a=(null==(r=this.schedule)?void 0:r.findEventIndex(e.identifier))||-1;this.handleAssetItemError(s,e,a,i,t.message);return}let a=s.edge-s.fragmentStart,n=t.duration;(g||null===n||a>n)&&(g=!1,this.log(`Interstitial asset "${h}" duration change ${n} > ${a}`),t.duration=a,this.updateSchedule())};f.on(eX.LEVEL_UPDATED,(e,{details:t})=>m(t)),f.on(eX.LEVEL_PTS_UPDATED,(e,{details:t})=>m(t)),f.on(eX.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let p=(e,t)=>{let i=this.getAssetPlayer(h);if(i&&t.tracks){i.off(eX.BUFFER_CODECS,p),i.tracks=t.tracks;let e=this.primaryMedia;this.bufferingAsset===i.assetItem&&e&&!i.media&&this.bufferAssetPlayer(i,e)}};f.on(eX.BUFFER_CODECS,p);let y=()=>{var i;let s=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${s}`),!s||!this.schedule)return;let r=this.schedule.findEventIndex(e.identifier),a=null==(i=this.schedule.items)?void 0:i[r];this.isInterstitial(a)&&this.advanceAssetBuffering(a,t)};f.on(eX.BUFFERED_TO_END,y);let v=t=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;let i=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,i,t)};return f.once(eX.MEDIA_ENDED,v(i)),f.once(eX.PLAYOUT_LIMIT_REACHED,v(1/0)),f.on(eX.ERROR,(t,s)=>{if(!this.schedule)return;let r=this.getAssetPlayer(h);s.details===ez.BUFFER_STALLED_ERROR?null!=r&&r.appendInPlace?this.handleInPlaceStall(e):(this.onTimeupdate(),this.checkBuffer(!0)):this.handleAssetItemError(s,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${s.error} ${e}`)}),f.on(eX.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;let t=Error(`Asset player destroyed unexpectedly ${h}`),s={fatal:!0,type:eq.OTHER_ERROR,details:ez.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(s,e,this.schedule.findEventIndex(e.identifier),i,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${ni(t)}`),this.hls.trigger(eX.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log(`reset asset player "${e}" after error`);let i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){let i=this.getAssetPlayerQueueIndex(e);if(-1!==i){let e=this.playerQueue[i];this.log(`clear ${e} toSegment: ${t?na(t):t}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(i,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,s,r){let{interstitial:a,assetItem:n,assetId:l}=e,o=a.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=n,d&&d.identifier===l||(d&&(this.clearAssetPlayer(d.identifier,i[s]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${o} ${ni(n)}`),this.hls.trigger(eX.INTERSTITIAL_ASSET_STARTED,{asset:n,assetListIndex:t,event:a,schedule:i.slice(0),scheduleIndex:s,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var i,s;if(!this.schedule)return;let{interstitial:r,assetItem:a}=e,n=this.schedule.findEventIndex(r.identifier),l=null==(i=this.schedule.items)?void 0:i[n];if(!l)return;e.loadSource(),this.setBufferingItem(l),this.bufferingAsset=a;let o=this.getBufferingPlayer();if(o===e)return;let d=r.appendInPlace;if(d&&(null==o?void 0:o.interstitial.appendInPlace)===!1)return;let h=(null==o?void 0:o.tracks)||(null==(s=this.detachedData)?void 0:s.tracks)||this.requiredTracks;if(d&&a!==this.playingAsset){if(!e.tracks)return void this.log(`Waiting for track info before buffering ${e}`);if(h&&!tn(h,e.tracks)){let t=Error(`Asset ${ni(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),i={fatal:!0,type:eq.OTHER_ERROR,details:ez.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},s=r.findAssetIndex(a);this.handleAssetItemError(i,r,n,s,t.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,i=this.primaryMedia;if(!t||!i)return;let s=i.currentTime,r=t.findAssetIndex(e,s),a=e.assetList[r];if(a){let n=this.getAssetPlayer(a.identifier);if(n){let l=n.currentTime||s-a.timelineStart,o=n.duration-l;if(this.warn(`Stalled at ${l} of ${l+o} in ${n} ${e} (media.currentTime: ${s})`),l&&(o/i.playbackRate<.5||n.bufferedInPlaceToEnd(i))&&n.hls){let i=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,i,r)}}}}advanceInPlace(e){let t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,i,s,r){if(e.details===ez.BUFFER_STALLED_ERROR)return;let a=t.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a?ni(a):a} ${e.error}`),!this.schedule)return;let n=(null==a?void 0:a.identifier)||"",l=this.getAssetPlayerQueueIndex(n),o=this.playerQueue[l]||null,d=this.schedule.items,h=e8({},e,{fatal:!1,errorAction:iA(!0),asset:a,assetListIndex:s,event:t,schedule:d,scheduleIndex:i,player:o});if(this.hls.trigger(eX.INTERSTITIAL_ASSET_ERROR,h),!e.fatal)return;let u=this.playingAsset,c=this.bufferingAsset,f=Error(r);
30if(a&&(this.clearAssetPlayer(n,null),a.error=f),t.assetList.some(e=>!e.error))for(let e=s;e<t.assetList.length;e++)this.resetAssetPlayer(t.assetList[e].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):u&&u.identifier===n?this.advanceAfterAssetEnded(t,i,s):c&&c.identifier===n&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,c)}primaryFallback(e){let t=e.timelineStart,i=this.effectivePlayingItem,s=this.timelinePos;if(i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${s} playing: ${na(i)} error: ${e.error}`),-1===s&&(s=this.hls.startPosition);let r=this.updateItem(i,s);this.itemsMatch(i,r)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(-1===s)return void this.checkStart();if(!this.schedule)return;let r=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(r)}onAssetListLoaded(e,t){var i,s,r;let a=t.event,n=a.identifier,l=t.assetListResponse.ASSETS;if(!(null!=(i=this.schedule)&&i.hasEvent(n)))return;let o=a.timelineStart,d=a.duration,h=0;l.forEach((e,t)=>{let i=parseFloat(e.DURATION);this.createAsset(a,t,h,o+h,i,e.URI),h+=i}),a.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${d}) ${a}`);let u=this.waitingItem,c=(null==u?void 0:u.event.identifier)===n;this.updateSchedule();let f=null==(s=this.bufferingItem)?void 0:s.event;if(c){let e=this.schedule.findEventIndex(n),t=null==(r=this.schedule.items)?void 0:r[e];if(t){if(!this.playingItem&&this.timelinePos>t.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==e){a.error=Error(`Interstitial ${l.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${a}`),this.log(a.error.message),this.updateSchedule(!0),this.primaryFallback(a);return}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if((null==f?void 0:f.identifier)===n){let e=a.assetList[0];if(e){let t=this.getAssetPlayer(e.identifier);if(f.appendInPlace){let e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case ez.ASSET_LIST_PARSING_ERROR:case ez.ASSET_LIST_LOAD_ERROR:case ez.ASSET_LIST_LOAD_TIMEOUT:{let e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case ez.BUFFER_STALLED_ERROR:{let e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace)return void this.handleInPlaceStall(e.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0)}}}}});class n9 extends i${constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var e;this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(eX.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(eX.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(eX.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(eX.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(eX.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(eX.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(eX.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(100),this.mediaSource=t.mediaSource;let i=this.media=t.media;sW(i,"playing",this.onMediaPlaying),sW(i,"waiting",this.onMediaWaiting),sW(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:i}=this;i&&(sY(i,"playing",this.onMediaPlaying),sY(i,"waiting",this.onMediaWaiting),sY(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(!(null!=(e=this.media)&&e.readyState)||!this.hasBuffered)return;let t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,s,r;let a=null==(i=this.hls)?void 0:i.config;if(!a)return;let n=this.media;if(!n)return;let{seeking:l}=n,o=this.seeking&&!l,d=!this.seeking&&l,h=n.paused&&!l||n.ended||0===n.playbackRate;if(this.seeking=l,e!==t){t&&(this.ended=0),this.moved=!0,!l&&(this.nudgeRetry=0,a.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),0===this.waiting&&this.stallResolved(e);return}if(d||o){o&&this.stallResolved(e);return}if(h){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(eX.MEDIA_ENDED,{stalled:!1}));return}if(!iH.getBuffered(n).length){this.nudgeRetry=0;return}let u=iH.bufferInfo(n,e,0),c=u.nextStart||0,f=this.fragmentTracker;if(l&&f&&this.hls){let t=n7(this.hls.inFlightFragments,e),i=u.len>2,s=!c||t||c-e>2&&!f.getPartialFragment(e);
30if(i||s)return;this.moved=!1}let g=null==(s=this.hls)?void 0:s.latestLevelDetails;if(!this.moved&&null!==this.stalled&&f){if(!(u.len>0)&&!c)return;let t=Math.max(c,u.start||0)-e,i=null!=g&&g.live?2*g.targetduration:2,s=lt(e,f);if(t>0&&(t<=i||s)){n.paused||this._trySkipBufferHole(s);return}}let m=a.detectStallWithCurrentTimeMs,p=self.performance.now(),y=this.waiting,v=this.stalled;if(null===v)if(y>0&&p-y<m)v=this.stalled=y;else{this.stalled=p;return}let T=p-v;if(!l&&(T>=m||y)&&this.hls){if((null==(r=this.mediaSource)?void 0:r.readyState)==="ended"&&!(null!=g&&g.live)&&1>Math.abs(e-((null==g?void 0:g.edge)||0))){if(this.ended)return;this.ended=e||1,this.hls.trigger(eX.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(u),!this.media||!this.hls)return}let E=iH.bufferInfo(n,e,a.maxBufferHole);this._tryFixBufferStall(E,T,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let 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(eX.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;let s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&s&&s.length>1&&e>s.end(0)){let i=iH.bufferedInfo(iH.timeRangesToArray(this.buffered.audio),e,0);if(i.len>1&&t>=i.start){let i=iH.timeRangesToArray(s),r=iH.bufferedInfo(i,t,0).bufferedIndex;if(r>-1&&r<i.length-1){let t=iH.bufferedInfo(i,e,0).bufferedIndex,s=i[r].end,a=i[r+1].start;if((-1===t||t>r)&&a-s<1&&e-s<2){let i=Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${s} -> ${a} buffered index: ${t}`);this.warn(i.message),this.media.currentTime+=1e-6;let r=lt(e,this.fragmentTracker);r&&"fragment"in r?r=r.fragment:r||(r=void 0);let n=iH.bufferInfo(this.media,e,0);this.hls.trigger(eX.ERROR,{type:eq.MEDIA_ERROR,details:ez.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:r,buffer:n.len,bufferInfo:n})}}}}}_tryFixBufferStall(e,t,i){var s,r;let{fragmentTracker:a,media:n}=this,l=null==(s=this.hls)?void 0:s.config;if(!n||!a||!l)return;let o=null==(r=this.hls)?void 0:r.latestLevelDetails,d=lt(i,a);if((d||null!=o&&o.live&&i<o.fragmentStart)&&(this._trySkipBufferHole(d)||!this.media))return;let h=e.buffered,u=this.adjacentTraversal(e,i);(h&&h.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-i<l.maxBufferHole||u))&&(t>1e3*l.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let i=this.fragmentTracker,s=e.nextStart;if(i&&s){let e=i.getFragAtPos(t,e1),r=i.getFragAtPos(s,e1);if(e&&r)return r.sn-e.sn<2}return!1}_reportStall(e){let{hls:t,media:i,stallReported:s,stalled:r}=this;if(!s&&null!==r&&i&&t){this.stallReported=!0;let s=Error(`Playback stalling at @${i.currentTime} due to low buffer (${it(e)})`);this.warn(s.message),t.trigger(eX.ERROR,{type:eq.MEDIA_ERROR,details:ez.BUFFER_STALLED_ERROR,fatal:!1,error:s,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t,i;let{fragmentTracker:s,media:r}=this,a=null==(t=this.hls)?void 0:t.config;if(!r||!s||!a)return 0;let n=r.currentTime,l=iH.bufferInfo(r,n,0),o=n<l.start?l.start:l.nextStart;if(o&&this.hls){let t=l.len<=a.maxBufferHole,d=l.len>0&&l.len<1&&r.readyState<3,h=o-n;if(h>0&&(t||d)){if(h>a.maxBufferHole){let t=!1;if(0===n){let e=s.getAppendedFrag(0,e1);e&&o<e.end&&(t=!0)}if(!t&&e){if(!(null!=(i=this.hls.loadLevelObj)&&i.details)||n7(this.hls.inFlightFragments,o))return 0;let t=!1,r=e.end;for(;r<o;){let e=lt(r,s);if(e)r+=e.duration;else{t=!0;break}}if(t)return 0}}let t=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${t}`),this.moved=!0,r.currentTime=t,!(null!=e&&e.gap)){let i=Error(`fragment loaded with buffer holes, seeking from ${n} to ${t}`),s={type:eq.MEDIA_ERROR,details:ez.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,buffer:l.len,bufferInfo:l};e&&("fragment"in e?s.part=e:s.frag=e),this.hls.trigger(eX.ERROR,s)}return t}}return 0}_tryNudgeBuffer(e){let{hls:t,media:i,nudgeRetry:s}=this,r=null==t?void 0:t.config;if(!i||!r)return 0;let a=i.currentTime;if(this.nudgeRetry++,s<r.nudgeMaxRetry){let n=a+(s+1)*r.nudgeOffset,l=Error(`Nudging 'currentTime' from ${a} to ${n}`);this.warn(l.message),i.currentTime=n,t.trigger(eX.ERROR,{type:eq.MEDIA_ERROR,details:ez.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{let i=Error(`Playhead still not moving while enough data buffered @${a} after ${r.nudgeMaxRetry} nudges`);this.error(i.message),t.trigger(eX.ERROR,{type:eq.MEDIA_ERROR,details:ez.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:e.len,bufferInfo:e})}}}function n7(e,t){let i=le(e.main);if(i&&i.start<=t)return i;let s=le(e.audio);return s&&s.start<=t?s:null}function le(e){if(!e)return null;switch(e.state){case sX:case sz:case s3:case s4:return null}return e.frag}function lt(e,t){return t.getAppendedFrag(e,e1)||t.getPartialFragment(e)}function li(){if("u">typeof self)return self.VTTCue||self.TextTrackCue}function ls(e,t,i,s,r){let a=new e(t,i,"");try{a.value=s,r&&(a.type=r)}catch(n){a=new e(t,i,it(r?e9({type:r},s):s))}return a}let lr=(()=>{let e=li();try{e&&new e(0,1/0,"")}catch(e){return Number.MAX_VALUE}return 1/0})();class la{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(eX.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(){let{hls:e}=this;
30e&&(e.on(eX.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(eX.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(eX.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.on(eX.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(eX.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(eX.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(eX.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(eX.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(eX.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(eX.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.off(eX.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(eX.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(eX.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(eX.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,(null==(i=t.overrides)?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;let t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,t.transferMedia||(this.id3Track&&(this.removeCues&&a3(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){let i=e[t];if("metadata"===i.kind&&"id3"===i.label)return a1(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;let{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=li();if(a)for(let e=0;e<r.length;e++){let t=r[e].type;if(t===rv.emsg&&!i||!s)continue;let n=rm(r[e].data),l=r[e].pts,o=l+r[e].duration;o>lr&&(o=lr),o-l<=0&&(o=l+.25);for(let e=0;e<n.length;e++){let i=n[e];if(!rp(i)){this.updateId3CueEnds(l,t);let e=ls(a,l,o,i,t);e&&this.id3Track.addCue(e)}}}}updateId3CueEnds(e,t){var i;let s=null==(i=this.id3Track)?void 0:i.cues;if(s)for(let i=s.length;i--;){let r=s[i];r.type===t&&r.startTime<e&&r.endTime===lr&&(r.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){let{id3Track:r,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:n,enableID3MetadataCues:l}}=a;r&&(n||l)&&a4(r,t,i,"audio"===s?e=>e.type===rv.audioId3&&l:"video"===s?e=>e.type===rv.emsg&&n:e=>e.type===rv.audioId3&&l||e.type===rv.emsg&&n)}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){var i,s;if(!this.hls||!this.media)return;let{assetPlayerId:r,timelineOffset:a,enableDateRangeMetadataCues:n,interstitialsController:l}=this.hls.config;if(!n)return;let o=li();if(r&&a&&!l){let{fragmentStart:t,fragmentEnd:i}=e,s=this.assetCue;s?(s.startTime=t,s.endTime=i):o&&(s=this.assetCue=ls(o,t,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"))&&(s.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(s),s.addEventListener("enter",this.onEventCueEnter))}if(!e.hasProgramDateTime)return;let{id3Track:d}=this,{dateRanges:h}=e,u=Object.keys(h),c=this.dateRangeCuesAppended;if(d&&t)if(null!=(i=d.cues)&&i.length){let e=Object.keys(c).filter(e=>!u.includes(e));for(let t=e.length;t--;){let i=e[t],r=null==(s=c[i])?void 0:s.cues;delete c[i],r&&Object.keys(r).forEach(e=>{let t=r[e];if(t){t.removeEventListener("enter",this.onEventCueEnter);try{d.removeCue(t)}catch(e){}}})}}else c=this.dateRangeCuesAppended={};let f=e.fragments[e.fragments.length-1];if(0!==u.length&&eV(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let e=0;e<u.length;e++){let t=u[e],i=h[t],s=i.startTime,r=c[t],a=(null==r?void 0:r.cues)||{},n=(null==r?void 0:r.durationKnown)||!1,d=lr,{duration:f,endDate:g}=i;if(g&&null!==f)d=s+f,n=!0;else if(i.endOnNext&&!n){let e=u.reduce((e,t)=>
30{if(t!==i.id){let s=h[t];if(s.class===i.class&&s.startDate>i.startDate&&(!e||i.startDate<e.startDate))return s}return e},null);e&&(d=e.startTime,n=!0)}let m=Object.keys(i.attr);for(let e=0;e<m.length;e++){let h=m[e];if("ID"===h||"CLASS"===h||"CUE"===h||"START-DATE"===h||"DURATION"===h||"END-DATE"===h||"END-ON-NEXT"===h)continue;let u=a[h];if(u)n&&!(null!=r&&r.durationKnown)?u.endTime=d:Math.abs(u.startTime-s)>.01&&(u.startTime=s,u.endTime=d);else if(o){let e=i.attr[h];("SCTE35-OUT"===h||"SCTE35-IN"===h||"SCTE35-CMD"===h)&&(e=td(e));let r=ls(o,s,d,{key:h,data:e},rv.dateRange);r&&(r.id=t,this.id3Track.addCue(r),a[h]=r,l&&("X-ASSET-LIST"===h||"X-ASSET-URL"===h)&&r.addEventListener("enter",this.onEventCueEnter))}}c[t]={cues:a,dateRange:i,durationKnown:n}}}}}class ln{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=()=>{let{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;let i=this.computeLatency();if(null===i)return;this._latency=i;let{lowLatencyMode:s,maxLiveSyncPlaybackRate:r}=this.config;if(!s||1===r||!t.live)return;let a=this.targetLatency;if(null===a)return;let n=i-a;if(n<Math.min(this.maxLatency,a+t.targetduration)&&n>.05&&this.forwardBufferLength>1){let t=Math.min(Math.min(2,Math.max(1,r)),Math.max(1,Math.round(2/(1+Math.exp(-.75*n-this.edgeStalled))*20)/20));this.changeMediaPlaybackRate(e,t)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){let{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(null===e||null===this.hls)return null;let{holdBack:t,partHoldBack:i,targetduration:s}=e,{liveSyncDuration:r,liveSyncDurationCount:a,lowLatencyMode:n}=this.config,l=this.hls.userConfig,o=n&&i||t;return(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===o)&&(o=void 0!==r?r:a*s),o+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,s)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;let i=this.levelDetails;if(null===i)return null;let s=i.edge,r=e-t-this.edgeStalled;return Math.min(Math.max(s-i.totalduration,r),s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration))}get drift(){let e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(null===e)return 0;let t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(eX.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(eX.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.on(eX.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(eX.ERROR,this.onError,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(eX.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(eX.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.off(eX.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(eX.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===ez.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,s;e.playbackRate!==t&&(null==(i=this.hls)||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(s=this.targetLatency)?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){let e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class ll extends as{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(){let{hls:e}=this;e.on(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.on(eX.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(eX.LEVEL_LOADED,this.onLevelLoaded,this),e.on(eX.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(eX.FRAG_BUFFERED,this.onFragBuffered,this),e.on(eX.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.off(eX.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(eX.LEVEL_LOADED,this.onLevelLoaded,this),e.off(eX.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(eX.FRAG_BUFFERED,this.onFragBuffered,this),e.off(eX.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}
30stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.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){let i=this.hls.config.preferManagedMediaSource,s=[],r={},a={},n=!1,l=!1,o=!1;t.levels.forEach(e=>{let t=e.attrs,{audioCodec:d,videoCodec:h}=e;d&&(e.audioCodec=d=tz(d,i)||void 0),h&&(h=e.videoCodec=function(e){let t=e.split(",");for(let e=0;e<t.length;e++){let i=t[e].split(".");i.length>2&&"avc1"===i[0]&&(t[e]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return t.join(",")}(h));let{width:u,height:c,unknownCodecs:f}=e,g=(null==f?void 0:f.length)||0;if(n||(n=!!(u&&c)),l||(l=!!h),o||(o=!!d),g||d&&!this.isAudioSupported(d)||h&&!this.isVideoSupported(h))return void this.log(`Some or all CODECS not supported "${t.CODECS}"`);let{CODECS:m,"FRAME-RATE":p,"HDCP-LEVEL":y,"PATHWAY-ID":v,RESOLUTION:T,"VIDEO-RANGE":E}=t,S=`${v||"."}-`,L=`${S}${e.bitrate}-${T}-${p}-${m}-${E}-${y}`;if(r[L])if(r[L].uri===e.url||e.attrs["PATHWAY-ID"])r[L].addGroupId("audio",t.AUDIO),r[L].addGroupId("text",t.SUBTITLES);else{let t=a[L]+=1;e.attrs["PATHWAY-ID"]=Array(t+1).join(".");let i=this.createLevel(e);r[L]=i,s.push(i)}else{let t=this.createLevel(e);r[L]=t,a[L]=1,s.push(t)}}),this.filterAndSortMediaOptions(s,t,n,l,o)}createLevel(e){let t=new t7(e),i=e.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){let e=Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(e.message),t.supportedResult=t2(e,[])}return t}isAudioSupported(e){return tG(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return tG(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,s,r){var a,n;let l=[],o=[],d=e,h=(null==(a=t.stats)?void 0:a.parsing)||{};if((i||s)&&r&&(d=d.filter(({videoCodec:e,videoRange:t,width:i,height:s})=>{var r;return(!!e||!!(i&&s))&&!!(r=t)&&t8.indexOf(r)>-1})),0===d.length){Promise.resolve().then(()=>{if(this.hls){let e="no level with compatible codecs found in manifest",i=e;t.levels.length&&(i=`one or more CODECS in variant not supported: ${it(t.levels.map(e=>e.attrs.CODECS).filter((e,t,i)=>i.indexOf(e)===t))}`,this.warn(i),e+=` (${i})`);let s=Error(e);this.hls.trigger(eX.ERROR,{type:eq.MEDIA_ERROR,details:ez.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:s,reason:i})}}),h.end=performance.now();return}t.audioTracks&&lo(l=t.audioTracks.filter(e=>!e.audioCodec||this.isAudioSupported(e.audioCodec))),t.subtitles&&lo(o=t.subtitles);let u=d.slice(0);d.sort((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return t8.indexOf(e.videoRange)-t8.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){let i=tV(e.videoCodec),s=tV(t.videoCodec);if(i!==s)return s-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){let i=tW(e.codecSet),s=tW(t.codecSet);if(i!==s)return s-i}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});let c=u[0];if(this.steering&&(d=this.steering.filterParsedLevels(d)).length!==u.length){for(let e=0;e<u.length;e++)if(u[e].pathwayId===d[0].pathwayId){c=u[e];break}}this._levels=d;for(let e=0;e<d.length;e++)if(d[e]===c){this._firstLevel=e;let t=c.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${t}`),(null==(n=this.hls.userConfig)?void 0:n.abrEwmaDefaultEstimate)===void 0){let e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}let f=r&&!s,g=this.hls.config,m=!!(g.audioStreamController&&g.audioTrackController),p={levels:d,audioTracks:l,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:s,altAudio:m&&!f&&l.some(e=>!!e.url)};h.end=performance.now(),this.hls.trigger(eX.MANIFEST_PARSED,p)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){let i=Error("invalid level idx"),s=e<0;if(this.hls.trigger(eX.ERROR,{type:eq.OTHER_ERROR,details:ez.LEVEL_SWITCH_ERROR,level:e,fatal:s,error:i,reason:i.message}),s)return;e=Math.min(e,t.length-1)}let i=this.currentLevelIndex,s=this.currentLevel,r=s?s.attrs["PATHWAY-ID"]:void 0,a=t[e],n=a.attrs["PATHWAY-ID"];
30if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&s&&r===n)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${n?" with Pathway "+n:""} from level ${i}${r?" with Pathway "+r:""}`);let l={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(eX.LEVEL_SWITCHING,l);let o=a.details;if(!o||o.live){let e=this.switchParams(a.uri,null==s?void 0:s.details,o);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){let e=this.hls.config.startLevel;return void 0!==e?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){let t=this.steering.pathways(),i=e.filter(e=>-1!==t.indexOf(e));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=i}}onError(e,t){!t.fatal&&t.context&&t.context.type===eZ&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===e1){let e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;let i=this._levels[t.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var i,s;let{level:r,details:a}=t,n=t.levelInfo;if(!n){this.warn(`Invalid level index ${r}`),null!=(s=t.deliveryDirectives)&&s.skip&&(a.deltaUpdateFailed=!0);return}if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(r,t,e)}else null!=(i=t.deliveryDirectives)&&i.skip&&(a.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],a=e.details,n=null==a?void 0:a.age;this.log(`Loading level index ${s}${(null==t?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${n&&a.live?" age "+n.toFixed(1)+(a.type?" "+a.type:""):""} ${i}`),this.hls.trigger(eX.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return -1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;let i=this._levels.filter((t,i)=>i!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));sU(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(eX.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(eX.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function lo(e){let t={};
30e.forEach(e=>{let i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}function ld(){return self.SourceBuffer||self.WebKitSourceBuffer}function lh(){if(!ta())return!1;let e=ld();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}class lu extends s6{constructor(e,t,i){super(e,t,i,"stream-controller",e1),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=()=>{let e=this.media,t=e?e.currentTime:null;if(null===t||!eV(t)||(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t)))return;let i=this.getFwdBufferInfoAtPos(e,t,e1,0);null===i||0===i.len?this.warn(`Main forward buffer length at ${t} on "seeked" event ${i?i.len:"empty"})`):this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(eX.MANIFEST_PARSED,this.onManifestParsed,this),e.on(eX.LEVEL_LOADING,this.onLevelLoading,this),e.on(eX.LEVEL_LOADED,this.onLevelLoaded,this),e.on(eX.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(eX.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(eX.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(eX.BUFFER_CREATED,this.onBufferCreated,this),e.on(eX.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(eX.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(eX.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(eX.MANIFEST_PARSED,this.onManifestParsed,this),e.off(eX.LEVEL_LOADED,this.onLevelLoaded,this),e.off(eX.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(eX.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(eX.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(eX.BUFFER_CREATED,this.onBufferCreated,this),e.off(eX.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(eX.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(eX.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=s.startLevel;-1===e&&(s.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=s.firstAutoLevel),s.nextLoadLevel=e,this.level=s.loadLevel,this._hasEnoughToStart=!!t}i>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=sX,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=sz}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case s8:{let{levels:e,level:t}=this,i=null==e?void 0:e[t],s=null==i?void 0:i.details;if(!s||s.live&&(this.levelLastLoaded!==i||this.waitForLive(i)))this.hls.nextLoadLevel!==this.level&&(this.state=sX);else{if(this.waitForCdnTuneIn(s))break;this.state=sX}break}case sJ:this.checkRetryDate()}this.state===sX&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(null===t||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(null!=i&&i[r]))return;let a=i[r],n=this.getMainFwdBufferInfo();if(null===n)return;let l=this.getLevelDetails();if(l&&this._streamEnded(n,l)){let e={};2===this.altAudio&&(e.type="video"),this.hls.trigger(eX.BUFFER_EOS,e),this.state=s3;return}if(!this.buffering)return;e.loadLevel!==r&&-1===e.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;let o=a.details;if(!o||this.state===s8||this.waitForLive(a)){this.level=r,this.state=s8,this.startFragRequested=!1;return}let d=n.len,h=this.getMaxBufferLength(a.maxBitrate);
30if(d>=h)return;this.backtrackFragment&&this.backtrackFragment.start>n.end&&(this.backtrackFragment=null);let u=this.backtrackFragment?this.backtrackFragment.start:n.end,c=this.getNextFragment(u,o);if(this.couldBacktrack&&!this.fragPrevious&&c&&ty(c)&&"OK"!==this.fragmentTracker.getState(c)){var f;let e=(null!=(f=this.backtrackFragment)?f:c).sn-o.startSN,t=o.fragments[e-1];t&&c.cc===t.cc&&(c=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&n.len&&(this.backtrackFragment=null);if(c&&this.isLoopLoading(c,u)){if(!c.gap){let e=this.audioOnly&&!this.altAudio?tf:tg,t=(e===tg?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,e1)}c=this.getNextFragmentLoopLoading(c,o,n,e1,h)}!c||this.exceedsMaxBuffer(n,h,c)||(!c.initSegment||c.initSegment.data||this.bitrateTest||(c=c.initSegment),this.loadFragment(c,a,u))}loadFragment(e,t,i){let s=this.fragmentTracker.getState(e);s===iR||s===iI?ty(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,e1)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,1/0),0!==this.altAudio){var e;((null==(e=this.getLevelDetails())?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,1/0,"audio")}}nextLevelSwitch(){let{levels:e,media:t}=this;if(null!=t&&t.readyState){let i,s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);let r=this.getLevelDetails();if(null!=r&&r.live){let e=this.getMainFwdBufferInfo();if(!e||e.len<2*r.targetduration)return}if(!t.paused&&e){let t=e[this.hls.nextLoadLevel],s=this.fragLastKbps;i=s&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*s)+1:0}else i=0;let a=this.getBufferedFrag(t.currentTime+i);if(a){let e=this.followingBufferedFrag(a);if(e){this.abortCurrentFrag();let t=e.maxStartPTS?e.maxStartPTS:e.start,i=e.duration,s=Math.max(a.end,t+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(s,1/0)}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case sQ:case sZ:case sJ:case s1:case s2:this.state=sX}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;sW(i,"playing",this.onMediaPlaying),sW(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:i}=this;i&&(sY(i,"playing",this.onMediaPlaying),sY(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(eX.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){var i;let s,r=!1,a=!1;for(let e=0;e<t.levels.length;e++){let i=t.levels[e].audioCodec;i&&(r=r||-1!==i.indexOf("mp4a.40.2"),a=a||-1!==i.indexOf("mp4a.40.5"))}this.audioCodecSwitch=r&&a&&"function"!=typeof(null==(s=ld())||null==(i=s.prototype)?void 0:i.changeType),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){let{levels:i}=this;if(!i||this.state!==sX)return;let s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=s8)}onLevelLoaded(e,t){var i,s;let{levels:r,startFragRequested:a}=this,n=t.level,l=t.details,o=l.totalduration;if(!r)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${l.startSN},${l.endSN}]${l.lastPartSn?`[part-${l.lastPartSn}-${l.lastPartIndex}]`:""}, cc [${l.startCC}, ${l.endCC}] duration:${o}`);let d=t.levelInfo,h=this.fragCurrent;h&&(this.state===sZ||this.state===sJ)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let u=0;if(l.live||null!=(i=d.details)&&i.live){if(this.checkLiveUpdate(l),l.deltaUpdateFailed)return;u=this.alignPlaylists(l,d.details,null==(s=this.levelLastLoaded)?void 0:s.details)}if(d.details=l,this.levelLastLoaded=d,a||this.setStartPosition(l,u),this.hls.trigger(eX.LEVEL_UPDATED,{details:l,level:n}),this.state===s8){if(this.waitForCdnTuneIn(l))return;this.state=sX}a&&l.live&&this.synchronizeToLiveEdge(l),this.tick()}
30synchronizeToLiveEdge(e){let{config:t,media:i}=this;if(!i)return;let s=this.hls.liveSyncPosition,r=this.getLoadPosition(),a=e.fragmentStart,n=e.edge,l=r>=a-t.maxFragLookUpTolerance&&r<=n;if(null!==s&&i.duration>s&&(r<s||!l)){let a=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&i.readyState<4||r<n-a)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${n}, reset currentTime to : ${s.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var o;let e=iH.bufferInfo(i,s,0);if(!(null!=(o=e.buffered)&&o.length)||e.start<=r){i.currentTime=s;return}let{nextStart:t}=iH.bufferedInfo(e.buffered,r,0);t&&(i.currentTime=t)}else i.currentTime=s}}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:s,payload:r}=e,{levels:a}=this;if(!a)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);let n=a[i.level];if(!n)return void this.warn(`Level ${i.level} not found on progress`);let l=n.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}let o=n.videoCodec,d=l.PTSKnown||!l.live,h=null==(t=i.initSegment)?void 0:t.data,u=this._getAudioCodec(n),c=this.transmuxer=this.transmuxer||new ai(this.hls,e1,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=s?s.index:-1,g=new iK(i.level,i.sn,i.stats.chunkCount,r.byteLength,f,-1!==f),m=this.initPTS[i.cc];c.push(r,h,u,o,i,s,l.totalduration,d,g,m)}onAudioTrackSwitching(e,t){let i=this.hls,s=0!==this.altAudio;if(ih(t.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s){this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(eX.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(eX.AUDIO_TRACK_SWITCHED,t)}),i.trigger(eX.BUFFER_FLUSHING,{startOffset:0,endOffset:1/0,type:null});return}i.trigger(eX.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let i=ih(t.url,this.hls);if(i){let e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=2*!!i,this.tick()}onBufferCreated(e,t){let i,s,r=t.tracks,a=!1;for(let e in r){let t=r[e];if("main"===t.id){if(s=e,i=t,"video"===e){let t=r[e];t&&(this.videoBuffer=t.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:i,part:s}=t,r=i.type===e1;if(r){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===s2&&(this.state=sX);return}let e=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),ty(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}let a=this.media;a&&(!this._hasEnoughToStart&&iH.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=s4;return}switch(t.details){case ez.FRAG_GAP:case ez.FRAG_PARSING_ERROR:case ez.FRAG_DECRYPT_ERROR:case ez.FRAG_LOAD_ERROR:case ez.FRAG_LOAD_TIMEOUT:case ez.KEY_LOAD_ERROR:case ez.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(e1,t);break;case ez.LEVEL_LOAD_ERROR:case ez.LEVEL_LOAD_TIMEOUT:case ez.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==s8||(null==(i=t.context)?void 0:i.type)!==eZ||(this.state=sX);break;case ez.BUFFER_ADD_CODEC_ERROR:case ez.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case ez.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,1/0));break;case ez.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=sX,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==tf||!this.altAudio){let e=(t===tg?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,e1),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking)return void this.log(`could not seek to ${i}, already seeking at ${t}`);let s=this.timelineOffset;s&&i&&(i+=s);let r=this.getLevelDetails(),a=iH.getBuffered(e),n=a.length?a.start(0):0,l=n-i,o=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<o||this.loadingParts&&l<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),i+=l,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${n}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{let{hls:i}=this,s=null==e?void 0:e.frag;if(!s||this.fragContextChanged(s))return;t.fragmentError=0,this.state=sX,this.startFragRequested=!1,this.bitrateTest=!1;let r=s.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(eX.FRAG_LOADED,e),s.bitrateTest=!1}
30).catch(t=>{this.state!==sz&&this.state!==s4&&(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:r}=e,a=this.getCurrentContext(r);if(!a)return void this.resetWhenMissingContext(r);let{frag:n,part:l,level:o}=a,{video:d,text:h,id3:u,initSegment:c}=s,{details:f}=o,g=this.altAudio?void 0:s.audio;if(this.fragContextChanged(n))return void this.fragmentTracker.removeFragment(n);if(this.state=s1,c){let e=c.tracks;if(e){let s=n.initSegment||n;if(this.unhandledEncryptionError(c,n))return;this._bufferInitSegment(o,e,s,r),i.trigger(eX.FRAG_PARSING_INIT_SEGMENT,{frag:s,id:t,tracks:e})}let s=c.initPTS,a=c.timescale,l=this.initPTS[n.cc];if(eV(s)&&(!l||l.baseTime!==s||l.timescale!==a)){let e=c.trackId;this.initPTS[n.cc]={baseTime:s,timescale:a,trackId:e},i.trigger(eX.INIT_PTS_FOUND,{frag:n,id:t,initPTS:s,timescale:a,trackId:e})}}if(d&&f){g&&"audiovideo"===d.type&&this.logMuxedErr(n);let e=f.fragments[n.sn-1-f.startSN],t=n.sn===f.startSN,i=!e||n.cc>e.cc;if(!1!==s.independent){let{startPTS:e,endPTS:s,startDTS:a,endDTS:o}=d;if(l)l.elementaryStreams[d.type]={startPTS:e,endPTS:s,startDTS:a,endDTS:o};else if(d.firstKeyFrame&&d.independent&&1===r.id&&!i&&(this.couldBacktrack=!0),d.dropped&&d.independent){let r=this.getMainFwdBufferInfo(),a=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,l=d.firstKeyFramePTS?d.firstKeyFramePTS:e;if(!t&&a<l-this.config.maxBufferHole&&!i)return void this.backtrack(n);i&&(n.gap=!0),n.setElementaryStreamInfo(d.type,n.start,s,n.start,o,!0)}else t&&e-(f.appliedTimelineOffset||0)>2&&(n.gap=!0);n.setElementaryStreamInfo(d.type,e,s,a,o),this.backtrackFragment&&(this.backtrackFragment=n),this.bufferFragmentData(d,n,l,r,t||i)}else{if(!t&&!i)return void this.backtrack(n);n.gap=!0}}if(g){let{startPTS:e,endPTS:t,startDTS:i,endDTS:s}=g;l&&(l.elementaryStreams[tf]={startPTS:e,endPTS:t,startDTS:i,endDTS:s}),n.setElementaryStreamInfo(tf,e,t,i,s),this.bufferFragmentData(g,n,l,r)}if(f&&null!=u&&u.samples.length){let e={id:t,frag:n,details:f,samples:u.samples};i.trigger(eX.FRAG_PARSING_METADATA,e)}if(f&&h){let e={id:t,frag:n,details:f,samples:h.samples};i.trigger(eX.FRAG_PARSING_USERDATA,e)}}logMuxedErr(e){this.warn(`${ty(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==s1)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));let{audio:r,video:a,audiovideo:n}=t;if(r){let i=e.audioCodec,s=tX(r.codec,i);"mp4a"===s&&(s="mp4a.40.5");let a=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){s&&(s=-1!==s.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");let e=r.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===a.indexOf("firefox")&&(s="mp4a.40.5")}s&&-1!==s.indexOf("mp4a.40.5")&&-1!==a.indexOf("android")&&"audio/mpeg"!==r.container&&(s="mp4a.40.2",this.log(`Android: force audio codec to ${s}`)),i&&i!==s&&this.log(`Swapping manifest audio codec "${i}" for "${s}"`),r.levelCodec=s,r.id=e1,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${s||""}/${i||""}/${r.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=e1;let i=a.codec;if((null==i?void 0:i.length)===4)switch(i){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"}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${i}]${a.codec!==i?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}n&&(this.log(`Init audiovideo buffer, container:${n.container}, codecs[level/parsed]=[${e.codecs}/${n.codec}]`),delete t.video,delete t.audio);let l=Object.keys(t);if(l.length){if(this.hls.trigger(eX.BUFFER_CODECS,t),!this.hls)return;l.forEach(e=>{let r=t[e].initSegment;null!=r&&r.byteLength&&this.hls.trigger(eX.BUFFER_APPENDING,{type:e,data:r,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;
30return this.getFwdBufferInfo(e,e1)}get maxBufferLength(){let{levels:e,level:t}=this,i=null==e?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=sX}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){let i=e.currentTime;if(iH.isBuffered(e,i)?t=this.getAppendedFrag(i):iH.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;let e=this.fragPlaying,i=t.level;(!e||t.sn!==e.sn||e.level!==i)&&(this.fragPlaying=t,this.hls.trigger(eX.FRAG_CHANGED,{frag:t}),e&&e.level===i||this.hls.trigger(eX.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return eV(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(eV(t)){let e=this.getLevelDetails(),i=this.currentFrag||(e?ic(null,e.fragments,t):null);if(i){let e=i.programDateTime;if(null!==e)return new Date(e+(t-i.start)*1e3)}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class lc extends e7{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let i in this.keyIdToKeyInfo){let s=this.keyIdToKeyInfo[i].loader;if(s){var t;if(e&&e!==(null==(t=s.context)?void 0:t.frag.type))return;s.abort()}}}detach(){for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){for(let e in this.detach(),this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=ez.KEY_LOAD_ERROR,i,s,r){return new iU({type:eq.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:s})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let s=0,r=t.length;s<r;s++){let a=t[s];if(e.cc<=a.cc&&(!ty(e)||!ty(a)||e.sn<a.sn)||!i&&s==r-1)return this.emeController.selectKeySystemFormat(a).then(e=>{if(!this.emeController)return;a.setKeyFormat(e);let t=sn(e);if(t)return this.emeController.getKeySystemAccess([t])})}if(this.config.requireKeySystemAccessOnStart){let e=so(this.config);if(e.length)return this.emeController.getKeySystemAccess(e)}}return null}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);let r=e.decryptdata;if(!r){let i=Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,ez.KEY_LOAD_ERROR,i))}let a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,ez.KEY_LOAD_ERROR,Error(`Invalid key URI: "${a}"`)));let n=lf(r),l=this.keyIdToKeyInfo[n];if(null!=(i=l)&&i.decryptdata.key)return r.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&null!=(s=l)&&s.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(t=>{let{keyInfo:i}=t;return r.key=i.decryptdata.key,{frag:e,keyInfo:i}})}switch(this.log(`${this.keyIdToKeyInfo[n]?"Rel":"L"}oading${r.keyId?" keyId: "+to(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),l=this.keyIdToKeyInfo[n]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":if("identity"===r.keyFormat)return this.loadKeyHTTP(l,e);return this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,ez.KEY_LOAD_ERROR,Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){let i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var s,r;if(!e.decryptdata.keyId&&null!=(s=t.initSegment)&&s.data){let i,s=(r=t.initSegment.data,i=[],tF(r,e=>i.push(e.subarray(8,24))),i);if(s.length){let t=s[0];t.some(e=>0!==e)?(this.log(`Using keyId found in init segment ${to(t)}`),sc.setKeyIdForUri(e.decryptdata.uri,t)):(t=sc.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${to(t)}`)),e.decryptdata.keyId=t}}return e.decryptdata.keyId||ty(t)?(e.keyLoadPromise=this.emeController.loadKey(i).then(t=>(e.mediaKeySessionContext=t,i))).catch(i=>{throw e.keyLoadPromise=null,"data"in i&&(i.data.frag=t),i}):Promise.resolve(i)}return Promise.resolve(i)}loadKeyHTTP(e,t){let i=this.config,s=new i.loader(i);return t.keyLoader=e.loader=s,e.keyLoadPromise=new Promise((r,a)=>{let n={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=i.keyLoadPolicy.default,o={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};s.load(n,o,{onSuccess:(e,t,i,s)=>{let{frag:n,keyInfo:l}=i,o=lf(l.decryptdata);if(!n.decryptdata||l!==this.keyIdToKeyInfo[o])return a(this.createKeyLoadError(n,ez.KEY_LOAD_ERROR,Error("after key load, decryptdata unset or changed"),s));l.decryptdata.key=n.decryptdata.key=new Uint8Array(e.data),n.keyLoader=null,l.loader=null,r({frag:n,keyInfo:l})},onError:(e,i,s,r)=>{this.resetLoader(i),a(this.createKeyLoadError(t,ez.KEY_LOAD_ERROR,Error(`HTTP Error ${e.code} loading key ${e.text}`),s,e9({url:n.url,data:void 0},e)))},onTimeout:(e,i,s)=>{this.resetLoader(i),a(this.createKeyLoadError(t,ez.KEY_LOAD_TIMEOUT,Error("key loading timed out"),s))},onAbort:(e,i,s)=>{this.resetLoader(i),a(this.createKeyLoadError(t,ez.INTERNAL_ABORTED,Error("key loading aborted"),s))}})})}
30resetLoader(e){let{frag:t,keyInfo:i,url:s}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=null,i.loader=null);let a=lf(i.decryptdata)||s;delete this.keyIdToKeyInfo[a],r&&r.destroy()}}function lf(e){if(e.keyFormat!==ss){let t=e.keyId;if(t)return to(t)}return e.uri}function lg(e){let{type:t}=e;switch(t){case eJ:return e2;case e0:return e3;default:return e1}}function lm(e,t){let i=e.url;return(void 0===i||0===i.indexOf("data:"))&&(i=t.url),i}class lp{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(){let{hls:e}=this;e.on(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.on(eX.LEVEL_LOADING,this.onLevelLoading,this),e.on(eX.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(eX.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(eX.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(eX.MANIFEST_LOADING,this.onManifestLoading,this),e.off(eX.LEVEL_LOADING,this.onLevelLoading,this),e.off(eX.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(eX.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(eX.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,i=t.pLoader,s=t.loader,r=new(i||s)(t);return this.loaders[e.type]=r,r}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:eQ,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:i,level:s,pathwayId:r,url:a,deliveryDirectives:n,levelInfo:l}=t;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:eZ,url:a,deliveryDirectives:n,levelOrTrack:l})}onAudioTrackLoading(e,t){let{id:i,groupId:s,url:r,deliveryDirectives:a,track:n}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:eJ,url:r,deliveryDirectives:a,levelOrTrack:n})}onSubtitleTrackLoading(e,t){let{id:i,groupId:s,url:r,deliveryDirectives:a,track:n}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:e0,url:r,deliveryDirectives:a,levelOrTrack:n})}onLevelsUpdated(e,t){let i=this.loaders[eZ];if(i){let e=i.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(i.abort(),delete this.loaders[eZ])}}load(e){var t;let i,s=this.hls.config,r=this.getInternalLoader(e);if(r){let t=this.hls.logger,i=r.context;if(i&&i.levelOrTrack===e.levelOrTrack&&(i.url===e.url||i.deliveryDirectives&&!e.deliveryDirectives))return void(i.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${i.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}if(i=e.type===eQ?s.manifestLoadPolicy.default:e8({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),eV(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===eZ&&null!==e.level?t=this.hls.levels[e.level].details:e.type===eJ&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===e0&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){let e=t.partTarget,s=t.targetduration;if(e&&s){let t=1e3*Math.max(3*e,.8*s);i=e8({},i,{maxTimeToFirstByteMs:Math.min(t,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,i.maxTimeToFirstByteMs)})}}}let a=i.errorRetry||i.timeoutRetry||{},n={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0};r.load(e,n,{onSuccess:(e,t,i,s)=>{let r=this.getInternalLoader(i);this.resetInternalLoader(i.type);let a=e.data;t.parsing.start=performance.now(),sT.isMediaPlaylist(a)||i.type!==eQ?this.handleTrackOrLevelPlaylist(e,t,i,s||null,r):this.handleMasterPlaylist(e,t,i,s)},onError:(e,t,i,s)=>{this.handleNetworkError(t,i,!1,e,s)},onTimeout:(e,t,i)=>{this.handleNetworkError(t,i,!0,void 0,e)}})}
30checkAutostartLoad(){if(!this.hls)return;let{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){let r=this.hls,a=e.data,n=lm(e,i),l=sT.parseMasterPlaylist(a,n);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,l.playlistParsingError,s,t);return}let{contentSteering:o,levels:d,sessionData:h,sessionKeys:u,startTimeOffset:c,variableList:f}=l;this.variableList=f,d.forEach(e=>{let{unknownCodecs:t}=e;if(t){let{preferManagedMediaSource:i}=this.hls.config,{audioCodec:s,videoCodec:r}=e;for(let a=t.length;a--;){let n=t[a];tG(n,"audio",i)?(e.audioCodec=s=s?`${s},${n}`:n,t$.audio[s.substring(0,4)]=2,t.splice(a,1)):tG(n,"video",i)&&(e.videoCodec=r=r?`${r},${n}`:n,t$.video[r.substring(0,4)]=2,t.splice(a,1))}}});let{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=sT.parseMasterPlaylistMedia(a,n,l);g.length&&(g.some(e=>!e.url)||!d[0].audioCodec||d[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new iX({}),bitrate:0,url:""}))),r.trigger(eX.MANIFEST_LOADED,{levels:d,audioTracks:g,subtitles:m,captions:p,contentSteering:o,url:n,stats:t,networkDetails:s,sessionData:h,sessionKeys:u,startTimeOffset:c,variableList:f})}handleTrackOrLevelPlaylist(e,t,i,s,r){let a=this.hls,{id:n,level:l,type:o}=i,d=lm(e,i),h=eV(l)?l:eV(n)?n:0,u=lg(i),c=sT.parseLevelPlaylist(e.data,d,h,u,0,this.variableList);if(o===eQ){let e={attrs:new iX({}),bitrate:0,details:c,name:"",url:d};c.requestScheduled=t.loading.start+sM(c,0),a.trigger(eX.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:d,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=c,this.handlePlaylistLoaded(c,e,t,i,s,r)}handleManifestParsingError(e,t,i,s,r){this.hls.trigger(eX.ERROR,{type:eq.NETWORK_ERROR,details:ez.MANIFEST_PARSING_ERROR,fatal:t.type===eQ,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:r})}handleNetworkError(e,t,i=!1,s,r){let a=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===eZ?a+=`: ${e.level} id: ${e.id}`:(e.type===eJ||e.type===e0)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let n=Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=ez.UNKNOWN,o=!1,d=this.getInternalLoader(e);switch(e.type){case eQ:l=i?ez.MANIFEST_LOAD_TIMEOUT:ez.MANIFEST_LOAD_ERROR,o=!0;break;case eZ:l=i?ez.LEVEL_LOAD_TIMEOUT:ez.LEVEL_LOAD_ERROR,o=!1;break;case eJ:l=i?ez.AUDIO_TRACK_LOAD_TIMEOUT:ez.AUDIO_TRACK_LOAD_ERROR,o=!1;break;case e0:l=i?ez.SUBTITLE_TRACK_LOAD_TIMEOUT:ez.SUBTITLE_LOAD_ERROR,o=!1}d&&this.resetInternalLoader(e.type);let h={type:eq.NETWORK_ERROR,details:l,fatal:o,url:e.url,loader:d,context:e,error:n,networkDetails:t,stats:r};s&&(h.response=e9({url:(null==t?void 0:t.url)||e.url,data:void 0},s)),this.hls.trigger(eX.ERROR,h)}handlePlaylistLoaded(e,t,i,s,r,a){let n=this.hls,{type:l,level:o,levelOrTrack:d,id:h,groupId:u,deliveryDirectives:c}=s,f=lm(t,s),g=lg(s),m="number"==typeof s.level&&g===e1?o:void 0,p=e.playlistParsingError;if(p){if(this.hls.logger.warn(`${p} ${e.url}`),!n.config.ignorePlaylistParsingErrors)return void n.trigger(eX.ERROR,{type:eq.NETWORK_ERROR,details:ez.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:s,level:m,parent:g,networkDetails:r,stats:i});e.playlistParsingError=null}if(!e.fragments.length){let a=e.playlistParsingError=Error("No Segments found in Playlist");n.trigger(eX.ERROR,{type:eq.NETWORK_ERROR,details:ez.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:a,reason:a.message,response:t,context:s,level:m,parent:g,networkDetails:r,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case eQ:case eZ:if(m)if(d){if(d!==n.levels[m]){let e=n.levels.indexOf(d);e>-1&&(m=e)}}else m=0;n.trigger(eX.LEVEL_LOADED,{details:e,levelInfo:d||n.levels[0],level:m||0,id:h||0,stats:i,networkDetails:r,deliveryDirectives:c,withoutMultiVariant:l===eQ});break;case eJ:n.trigger(eX.AUDIO_TRACK_LOADED,{details:e,track:d,id:h||0,groupId:u||"",stats:i,networkDetails:r,deliveryDirectives:c});break;case e0:n.trigger(eX.SUBTITLE_TRACK_LOADED,{details:e,track:d,id:h||0,groupId:u||"",stats:i,networkDetails:r,deliveryDirectives:c})}}}class ly{static get version(){return ri}static isMSESupported(){return lh()}static isSupported(){if(!lh())return!1;let e=ta();
30return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(tH(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(tH(t,"audio"))))}static getMediaSource(){return ta()}static get Events(){return eX}static get MetadataSchema(){return rv}static get ErrorTypes(){return eq}static get ErrorDetails(){return ez}static get DefaultConfig(){return ly.defaultConfig?ly.defaultConfig:n6}static set DefaultConfig(e){ly.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 rt,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=function(e,t,i){let s=ti();if("object"==typeof console&&!0===e||"object"==typeof e){let r=["debug","log","info","warn","error"];r.forEach(t=>{s[t]=ts(t,e,i)});try{s.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch(e){return ti()}r.forEach(t=>{tr[t]=ts(t,e)})}else e8(tr,s);return s}(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=function(e,t,i){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let s=function e(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(e):Object.keys(t).reduce((i,s)=>(i[s]=e(t[s]),i),{}):t}(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(e=>{let a=`${"level"===e?"playlist":e}LoadPolicy`,n=void 0===t[a],l=[];r.forEach(i=>{let r=`${e}Loading${i}`,o=t[r];if(void 0!==o&&n){l.push(r);let e=s[a].default;switch(t[a]={default:e},i){case"TimeOut":e.maxLoadTimeMs=o,e.maxTimeToFirstByteMs=o;break;case"MaxRetry":e.errorRetry.maxNumRetry=o,e.timeoutRetry.maxNumRetry=o;break;case"RetryDelay":e.errorRetry.retryDelayMs=o,e.timeoutRetry.retryDelayMs=o;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=o,e.timeoutRetry.maxRetryDelayMs=o}}}),l.length&&i.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${it(t[a])}`)}),e9(e9({},s),t)}(ly.DefaultConfig,e,t);this.userConfig=e,i.progressive&&function(e,t){let i=e.loader;i!==n2&&i!==n8?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}()&&(e.loader=n2,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}(i,t);const{abrController:s,bufferController:r,capLevelController:a,errorController:n,fpsController:l}=i,o=new n(this),d=this.abrController=new s(this),h=new i_(this),u=i.interstitialsController,c=u?this.interstitialsController=new u(this,ly):null,f=this.bufferController=new r(this,h),g=this.capLevelController=new a(this),m=new l(this),p=new lp(this),y=i.contentSteeringController,v=y?new y(this):null,T=this.levelController=new ll(this,v),E=new la(this),S=new lc(this.config,this.logger),L=this.streamController=new lu(this,h,S),k=this.gapController=new n9(this,h);g.setStreamController(L),m.setStreamController(L);const A=[p,T,L];c&&A.splice(1,0,c),v&&A.splice(1,0,v),this.networkControllers=A;const R=[d,f,k,g,m,E,h];this.audioTrackController=this.createController(i.audioTrackController,A);const b=i.audioStreamController;b&&A.push(this.audioStreamController=new b(this,h,S)),this.subtitleTrackController=this.createController(i.subtitleTrackController,A);const I=i.subtitleStreamController;I&&A.push(this.subtititleStreamController=new I(this,h,S)),this.createController(i.timelineController,R),S.emeController=this.emeController=this.createController(i.emeController,R),this.cmcdController=this.createController(i.cmcdController,R),this.latencyController=this.createController(ln,R),this.coreComponents=R,A.push(o);const _=o.onErrorOut;"function"==typeof _&&this.on(eX.ERROR,_,o),this.on(eX.MANIFEST_LOADED,p.onManifestLoaded,p)}createController(e,t){if(e){let 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)}
30trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;let i=e===eX.ERROR;this.trigger(eX.ERROR,{type:eq.OTHER_ERROR,details:ez.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(eX.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){let t=Error(`attachMedia failed: invalid argument (${e})`);this.trigger(eX.ERROR,{type:eq.OTHER_ERROR,details:ez.ATTACH_MEDIA_ERROR,fatal:!0,error:t});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let t="media"in e,i=t?e.media:e,s=t?e:{media:i};this._media=i,this.trigger(eX.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(eX.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;let e=this.bufferController.transferMedia();return this.trigger(eX.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,i=this._url,s=this._url=tu.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(eX.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?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),this.started&&this.networkControllers);i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[e1]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[e2]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[e3]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=null==e?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=function(){try{return crypto.randomUUID()}catch(e){try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(t){let e=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|8).toString(16)})}}}()),e}get levels(){return this.levelController.levels||[]}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(){let e=this.levelController.startLevel;return -1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let 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(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{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){t5.indexOf(e)>-1&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return -1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let s=0;s<i;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){let e,{levels:t,autoLevelCapping:i,maxHdcpLevel:s}=this;if(e=-1===i&&null!=t&&t.length?t.length-1:i,s)for(let i=e;i--;){let e=t[i].attrs["HDCP-LEVEL"];if(e&&e<=s)return i}return e}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(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}
30setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){let 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!!(null!=(e=this.bufferController)&&e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return t3(e,is(t),navigator.mediaCapabilities)}}ly.defaultConfig=void 0;let lv=()=>(0,T.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[(0,T.jsx)("path",{d:"M11 5L6 9H2v6h4l5 4V5z",fill:"currentColor"}),(0,T.jsx)("line",{x1:"23",y1:"9",x2:"17",y2:"15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),(0,T.jsx)("line",{x1:"17",y1:"9",x2:"23",y2:"15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),lT=()=>(0,T.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[(0,T.jsx)("path",{d:"M11 5L6 9H2v6h4l5 4V5z",fill:"currentColor"}),(0,T.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),(0,T.jsx)("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),lE=({video:e})=>{let[t,i]=(0,W.useState)(null),[s,r]=(0,W.useState)(null),[a,n]=(0,W.useState)(null),[l,o]=(0,W.useState)(!0),[d,h]=(0,W.useState)(!1),u=(0,W.useRef)(null),c=(0,W.useRef)(null),f=(0,W.useRef)(null),g=(0,W.useRef)(!1),m=(0,W.useRef)(0),p=(0,W.useRef)(0),y=(0,W.useRef)({videoId:null,videoTitle:null}),v=(0,ef.useAnalytics)(),E=(0,W.useRef)(v);(0,W.useEffect)(()=>{let t=e?.playerMetadata?.chorus?.hlsUrl;if(t){i(t),r(e.title),n(e.volumeUuid);return}let s=!1;return fetch("/api/volume/latest/feed/voxvertical").then(e=>e.json()).then(e=>{if(s)return;let t=e.data?.items?.[0];t?.video.url&&(i(t.video.url),r(t.title??null),n(t.sourceId??t.video.url))}).catch(()=>{}),()=>{s=!0}},[e]),(0,W.useEffect)(()=>{y.current={videoId:a,videoTitle:s}},[a,s]),(0,W.useEffect)(()=>{E.current=v},[v]),(0,W.useEffect)(()=>{let e=u.current;if(e&&t){if(e.muted=!0,ly.isSupported()){let i=new ly;f.current=i,i.loadSource(t),i.attachMedia(e)}else e.canPlayType("application/vnd.apple.mpegurl")&&(e.src=t);return window.matchMedia("(prefers-reduced-motion: reduce)").matches||(e.play().catch(()=>{}),h(!0)),()=>{f.current?.destroy(),f.current=null}}},[t]),(0,W.useEffect)(()=>{let e=u.current;if(!e||!a)return;let t=e=>{let{videoId:t,videoTitle:i}=y.current;E.current?.emit({event:"video",video:{action:e,video_player:"vertical",video_id:t,video_title:i??""}})},i=()=>t("load"),s=()=>{g.current||(g.current=!0,t("contentStart"))},r=()=>{let{currentTime:i,duration:s}=e;p.current>.95*s&&i<.3&&(m.current+=1,t("contentComplete"),m.current>1&&(t("contentStart"),t("rewatch"))),p.current=i};return e.addEventListener("loadedmetadata",i),e.addEventListener("playing",s),e.addEventListener("timeupdate",r),()=>{e.removeEventListener("loadedmetadata",i),e.removeEventListener("playing",s),e.removeEventListener("timeupdate",r),g.current=!1,m.current=0,p.current=0}},[t,a]),(0,W.useEffect)(()=>
30{let e=c.current,i=u.current;if(!e||!i||!t||"u"<typeof IntersectionObserver)return;let s=window.matchMedia("(prefers-reduced-motion: reduce)").matches,r=new IntersectionObserver(([e])=>{if(e){if(e.isIntersecting){s||(i.play().catch(()=>{}),h(!0));return}i.pause(),h(!1)}},{threshold:.25});return r.observe(e),()=>{r.disconnect()}},[t]);let S=(0,W.useCallback)(()=>{let e=u.current;if(!e)return;let{videoId:t,videoTitle:i}=y.current,s=()=>E.current?.emit({event:"video",video:{action:e.paused?"play":"pause",video_player:"vertical",video_id:t,video_title:i??""}});e.paused?(s(),e.play().catch(()=>{}),h(!0)):(s(),e.pause(),h(!1))},[]),L=(0,W.useCallback)(e=>{(" "===e.key||"Enter"===e.key)&&(e.preventDefault(),S())},[S]),k=(0,W.useCallback)(e=>{e.stopPropagation();let t=u.current;if(!t)return;t.muted=!t.muted,o(t.muted);let{videoId:i,videoTitle:s}=y.current;E.current?.emit({event:"video",video:{action:t.muted?"mute":"unmute",video_player:"vertical",video_id:i,video_title:s??""}})},[]),A=e?.title??s,R=A?(0,T.jsx)("div",{className:"_3kww4u7",children:(0,T.jsxs)("p",{className:"_3kww4u9",children:[(0,T.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"_3kww4u8","aria-hidden":"true",children:[(0,T.jsx)("rect",{width:"12",height:"12",rx:"6",fill:"black"}),(0,T.jsx)("path",{d:"M8.66667 5.99989L4.5 8.5V3.5L8.66667 5.99989Z",fill:"white"})]}),(0,T.jsx)("span",{className:"_3kww4ua",children:"Watch "}),A]})}):null;return t?(0,T.jsxs)("div",{className:"_3kww4u0",children:[(0,T.jsxs)("div",{ref:c,className:"_3kww4u1",role:"button",tabIndex:0,"aria-label":d?"Pause video":"Play video",onClick:S,onKeyDown:L,children:[(0,T.jsx)("video",{ref:u,muted:!0,playsInline:!0,loop:!0,"aria-label":s??"Video"}),!d&&(0,T.jsx)("div",{className:"_3kww4u5","aria-hidden":"true",children:(0,T.jsx)("div",{className:"_3kww4u6",children:(0,T.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:(0,T.jsx)("polygon",{points:"6,4 20,12 6,20",fill:"white"})})})}),(0,T.jsx)("button",{className:"_3kww4u2",onClick:k,"aria-label":l?"Unmute video":"Mute video",type:"button",children:l?(0,T.jsx)(lv,{}):(0,T.jsx)(lT,{})})]}),(0,T.jsx)("div",{"aria-live":"polite",className:H.sharedStyles.accessibility.srOnly,children:d?"Video playing":"Video paused"}),R]}):(0,T.jsx)("div",{className:"_3kww4u4","aria-hidden":"true"})},lS=({data:e})=>{let t=e.posts?.edges??[],i=t[0]?.node,s=t.slice(1,3).map(e=>e.node).filter(e=>!!e),r=(0,w.default)(i?[i]:[]),a=(0,w.default)(s),n=e.startHere?.items??[],l=e.startHere?.title,o=r[0];return i&&o?(0,T.jsxs)("div",{className:"tsnmpo0",children:[(0,T.jsx)(eG,{items:n,title:l,placement:"desktop",className:"tsnmpo4"}),(0,T.jsxs)("div",{className:"tsnmpo1",children:[(0,T.jsx)(eo.default,{metadata:{position:1},children:(0,T.jsx)(q.default,{...o,componentContext:"heroLedeThreeUpJumbo",showDek:!0,gaComponentName:"hero_lede_three_up",className:"tsnmpo2",imageAspectRatio:"fourThree",priorityImage:!0})}),(0,T.jsx)(e$,{className:"tsnmpo6"})]}),(0,T.jsx)("div",{className:"tsnmpo5",children:(0,T.jsx)(eH,{cards:a,placement:"belowJumbo",startPosition:2})}),(0,T.jsx)(M.default,{adType:"medrecFrontpageHero"}),(0,T.jsxs)("div",{className:"tsnmpo3",children:[(0,T.jsx)(lE,{video:e.video}),(0,T.jsx)(eH,{cards:a,placement:"belowVideo",startPosition:2})]}),(0,T.jsx)(eG,{items:n,title:l,placement:"mobile"}),(0,T.jsx)(e$,{className:"tsnmpo7"})]}):null};var lL=e.i(323430);let lk=({cardsData:e,gaComponentName:t="two_grid_alt_pattern",mobileCardContext:i="twoGridAltPattern",desktopCardContext:s,showGridBorders:r=!0,desktopCardClassName:a,desktopCardAlignTop:n=!1,className:l})=>{let{mobileContext:o,desktopContext:d}=(0,es.getContexts)(e.length,i,s),h=[],u=[];return e.forEach((i,s)=>{h.push((0,T.jsx)("div",{className:(0,S.default)("u8f9wu3",r&&"u8f9wu1"),children:(0,T.jsx)(Y.default,{...i,componentContext:d[s],gaComponentName:t,className:(0,S.default)(er.altCard,a),alignTop:n})},i.id)),u.push((0,W.createElement)(Y.default,{...i,key:i.id,componentContext:o[s],gaComponentName:t,firstChild:0===s,lastChild:s===e.length-1}))}),(0,T.jsxs)("div",{className:l,children:[(0,T.jsx)("div",{className:"u8f9wu0",children:h}),(0,T.jsx)("div",{className:"u8f9wu2",children:u})]})};var lA="z757fm6",lR="z757fm7";let lb=({primaryShowCard:e,moreShowsCards:t,spotifyButtonPath:i="/static-assets/podcasts/spotifyButton.png",appleButtonPath:s="/static-assets/podcasts/applePodcastsButton.png",className:r})=>(0,T.jsx)("div",{className:(0,S.default)($.SELECTORS.PodcastSection,"z757fm0",r&&r),children:(0,T.jsxs)("div",{children:[e&&(0,T.jsxs)(T.Fragment,{children:[(0,T.jsxs)("div",{className:"z757fm1",children:[(0,T.jsxs)("div",{children:[(0,T.jsx)("h2",{className:"z757fm3",children:(0,T.jsx)("a",{className:H.sharedStyles.contentCard.contentCardLink,href:e.permalink,children:e.headline})}),(0,T.jsx)(eK.default,{className:"z757fm4",html:e.dek||""})]}),(0,T.jsxs)("div",{className:"z757fm5",children:[e.spotifyUrl&&(0,T.jsx)("a",{className:lA,href:e.spotifyUrl||"",children:(0,T.jsx)("img",{className:lR,src:i,alt:"Listen on Spotify"})}),e.applePodcastsUrl&&(0,T.jsx)("a",{className:lA,href:e.applePodcastsUrl||"",children:(0,T.jsx)("img",{className:lR,src:s,alt:"Listen on Apple Podcasts"})})]})]}),(0,T.jsx)("div",{className:"z757fm8 _10sa9om11",children:(0,T.jsx)("iframe",{className:"z757fm9",title:`Listen to the latest episode of ${e.headline}`,height:"200",frameBorder:"no",scrolling:"no",src:"https://playlist.megaphone.fm/?p=VMP5705694065&light=true",width:"100%"})}),(0,T.jsx)("h3",{className:"z757fma",children:"More shows"})]}),(0,T.jsx)(lk,{cardsData:t,mobileCardContext:"podcastSection",showGridBorders:!0,gaComponentName:"homepagePodcastsSection"})]})}),lI=()=>{let e={authors:[],chorusUuid:null,wpId:1,site:{isCrossCommunity:!1,wpId:2},globalId:"1",chorusId:null,contentType:"category",id:"1"},t=lL.default.podcasts.filter(e=>e.homepage.show).map(t=>({...e,...t,id:t.playlistId})).sort((e,t)=>
30e.homepage.sortPriority-t.homepage.sortPriority);return t[0]?(0,T.jsx)(N.default,{className:H.sharedStyles.layout.standardSpacing.medium,header:(0,T.jsx)(B.default,{title:"Listen",size:"medium",headingLevel:"h2",moreLink:{text:"All Podcasts",url:"/podcasts"}}),pattern:(0,T.jsx)(lb,{moreShowsCards:t})}):null};var l_=e.i(813603),lC=e.i(166854);let lD=()=>{let e=(0,lC.mapParselyDataToContentCardData)((0,l_.default)());if(!e)return;let t=e.map(e=>({...e,gaComponentName:"homepage_recommended"})).slice(0,5);return(0,T.jsx)(eo.default,{metadata:{article_section:"homepage_recommended"},children:(0,T.jsx)(N.default,{className:H.sharedStyles.layout.standardSpacing.medium,header:(0,T.jsx)(B.default,{title:"Recommended For You",headingLevel:"h2",size:"medium",borderTop:!0}),pattern:(0,T.jsx)(eT,{cardsData:t,gaComponentName:"homepage_recommended"}),indent:!1})})};var lP=e.i(860303);e.i(601972);var lx=e.i(317631);let lF=({videoData:e,cardsData:t,className:i,gaComponentName:s})=>(0,T.jsxs)("div",{className:(0,S.default)($.SELECTORS.VideoSection,"gx259n0",i&&i),children:[(0,T.jsxs)("div",{className:"gx259n1",children:[(0,T.jsx)(lx.default,{autoplay:!1,contentWarning:null,posterUrl:e.video.posterUrl,title:e.video.title,uuid:e.video.volumeUuid,playerType:e.video.player||"youtube",className:"gx259n2"}),(0,T.jsx)("div",{className:"gx259n3",children:(0,T.jsx)(lP.default,{headline:e.title,permalink:e.permalink,authors:e.authors,category:e.categoryTitle,dek:e.dek,site:e.site,gaComponentName:"videoSection",globalId:"",contentBlockSize:"large",upperMetaFirstComponent:"Category",lowerMetaFirstComponent:"ContentBlockByline",id:"",contentType:"post",showDek:!0})})]}),(0,T.jsx)("div",{className:"gx259n6",children:t.map((e,i)=>(0,W.createElement)(Y.default,{...e,componentContext:"videoSection",gaComponentName:s,key:i,lastChild:i===t.length-1}))})]}),lw=({homepageResource:t})=>{let{videos:i}=(0,k.useFragment)(e.r(811723),t),s=i?.nodes||[],r=s[0],a=(0,w.default)(s.slice(1));return!r||a.length<2?null:r.ledeMedia?.video&&(0,T.jsx)("div",{className:(0,S.default)("_15f6y84",H.sharedStyles.layout.standardSpacing.large),children:(0,T.jsx)("div",{className:H.sharedStyles.layout.mainColumn,children:(0,T.jsx)(N.default,{indent:!1,header:(0,T.jsx)(B.default,{title:"Watch",size:"medium",headingLevel:"h2",moreLink:{text:"All Videos",url:"/videos"}}),pattern:(0,T.jsx)(lF,{videoData:{...r,categoryTitle:r.primaryCategory.title,authors:r.authors,dek:r.dek.html,site:r.site,video:{...r.ledeMedia.video,posterUrl:r.ledeMedia.video.poster?.thumbnails.horizontal.url||""}},cardsData:a,gaComponentName:"homepageVideoSection"})})})})},lM=(0,eA.default)(({mostPopularArticles:t})=>{let i=(0,b.useServerAuth)(),s=(0,k.useLazyLoadQuery)(e.r(825727),{limit:ek.HOMEPAGE_POSTS_PER_PAGE}),{newsletters:r}=(0,R.useGlobalDataContext)(),a=r?.find(e=>e.default),{resource:n}=s;if("HomepageResourceType"!==n.__typename)throw Error("Unexpected resource type");let{customCss:l,homepageLayoutPosts:o}=n,{communityName:d,communityOrigin:h}=(0,A.useConfigContext)().communityConfig,u=(0,eR.default)(),c=(0,eb.default)({totalPages:o?.pageInfo.totalPages||void 0,totalPagesLimit:ek.PAGINATION_LIMIT,hasNextPage:o?.pageInfo.hasNextPage});c.nextPageHref&&(c.nextPageHref=`/news${c.nextPageHref}`);let f=(0,eM.getSeoTitle)([],d);return(0,T.jsxs)(G.default,{context:"HomepageLayoutErrorBoundary",layout:"Homepage",children:[(0,T.jsx)(I.default,{resolvedResource:n}),l&&(0,T.jsx)("style",{dangerouslySetInnerHTML:{__html:l}}),(0,T.jsx)(C.default,{pageType:"homepage"}),(0,T.jsx)(L.NextSeo,{title:f,canonical:h}),(0,T.jsx)(_.default,{seoHeadline:f,pageType:"home_page",adSlugParts:["front_page"]}),(0,T.jsx)("div",{className:(0,S.default)($.SELECTORS.HomepageLayout,u),children:(0,T.jsxs)("main",{id:"content",className:(0,S.default)("_15f6y80"),children:[(0,T.jsx)("div",{className:H.sharedStyles.layout.mainColumn,children:(0,T.jsx)(em,{query:s,headline:"Making sense of it all:"})}),!i?.isEntitled&&(0,T.jsx)(D.default,{className:"_15f6y81",isHomepage:!0}),(0,T.jsxs)("div",{className:H.sharedStyles.layout.mainColumn,children:[function(e){if(!e)return null;switch(e.ledeLayout){case"three_up":return(0,T.jsx)(lS,{data:e});case"six_up":return(0,T.jsx)(ej,{data:e});default:return(0,E.captureException)(Error(`Unknown ledeLayout: ${e.ledeLayout}`)),null}}(n.heroLede),(0,T.jsx)(eN,{homepageResource:n}),(0,T.jsx)(M.default,{adType:"frontpageHeroDesktop"}),(0,T.jsx)(M.default,{adType:"frontpageHeroTablet"}),(0,T.jsx)(lD,{}),(0,T.jsx)(eL,{homepageResource:n}),(0,T.jsxs)(eP.default,{className:H.sharedStyles.layout.standardSpacing.medium,children:[(0,T.jsxs)(eD.default,{indent:!1,createContainerContext:!1,children:[(0,T.jsx)(N.default,{className:H.sharedStyles.layout.standardSpacing.large,header:(0,T.jsx)(B.default,{title:"Most Popular",size:"medium",headingLevel:"h2"}),pattern:(0,T.jsx)(eF.default,{articles:t,variation:"homepage",componentContext:"homepage"})}),(0,T.jsx)(lI,{})]}),(0,T.jsx)(e_.default,{hideOnMobile:!1,children:(0,T.jsx)("div",{className:(0,S.default)(eC.stickySectionDesktop),children:(0,T.jsxs)("div",{children:[(0,T.jsx)(M.default,{adType:"rightRailNetworkRiverAboveNewsletter"}),a&&(0,T.jsx)(eI.default,{variation:"homepage",name:a.title,text:a.promoText.html,lists:[a.listId],source:"sidebar"})]})})})]})]}),(0,T.jsx)(lw,{homepageResource:n}),(0,T.jsxs)("div",{className:H.sharedStyles.layout.mainColumn,children:[(0,T.jsx)(M.default,{adType:"networkRiverHomeTop"}),(0,T.jsx)(eu,{className:"_15f6y82",classNamePattern:"_15f6y83",homepageResource:n}),o&&(0,T.jsxs)(eP.default,{children:[(0,T.jsxs)(eD.default,{header:"More News",borderTop:!0,children:[(0,T.jsx)(P.default,{posts:o,layout:"homepage",nativeAdContentLinkPlacement:3,gaComponentName:"categoryRiver"}),(0,T.jsx)(ex.default,{...c,pageLimit:ek.PAGINATION_LIMIT,fullArchivesPageHref:(0,ew.generateFullArchiveLink)({year:new Date().getFullYear(),month:new Date().getMonth()+1})})]}),(0,T.jsx)(e_.default,{children:(0,T.jsx)(M.default,{adType:"rightRailNetworkRiver"})})]})]})]})})]})});e.s(["__N_SSP",0,!0,"default",0,lM],595499)},412334,(e,t,i)=>{let s="/resource/homepage";(window.__NEXT_P=window.__NEXT_P||[]).push([s,()=>e.r(595499)]),t.hot&&t.hot.dispose(function(){window.__NEXT_P.push([s])})}]);
31
32//# debugId=b8d30da5-705e-1dcc-c8c4-5984940830f6
33//# sourceMappingURL=3_r6q81rg_al7.js.map

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