hls__js.js 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992
  1. import "./chunk-TDUMLE5V.js";
  2. // ../../../../../Desktop/项目/直播/liveH5-v3/node_modules/hls.js/dist/hls.mjs
  3. var isFiniteNumber = Number.isFinite || function(value) {
  4. return typeof value === "number" && isFinite(value);
  5. };
  6. var isSafeInteger = Number.isSafeInteger || function(value) {
  7. return typeof value === "number" && Math.abs(value) <= MAX_SAFE_INTEGER;
  8. };
  9. var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  10. var ErrorTypes = function(ErrorTypes2) {
  11. ErrorTypes2["NETWORK_ERROR"] = "networkError";
  12. ErrorTypes2["MEDIA_ERROR"] = "mediaError";
  13. ErrorTypes2["KEY_SYSTEM_ERROR"] = "keySystemError";
  14. ErrorTypes2["MUX_ERROR"] = "muxError";
  15. ErrorTypes2["OTHER_ERROR"] = "otherError";
  16. return ErrorTypes2;
  17. }({});
  18. var ErrorDetails = function(ErrorDetails2) {
  19. ErrorDetails2["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
  20. ErrorDetails2["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
  21. ErrorDetails2["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
  22. ErrorDetails2["KEY_SYSTEM_NO_CONFIGURED_LICENSE"] = "keySystemNoConfiguredLicense";
  23. ErrorDetails2["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
  24. ErrorDetails2["KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED"] = "keySystemServerCertificateRequestFailed";
  25. ErrorDetails2["KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED"] = "keySystemServerCertificateUpdateFailed";
  26. ErrorDetails2["KEY_SYSTEM_SESSION_UPDATE_FAILED"] = "keySystemSessionUpdateFailed";
  27. ErrorDetails2["KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED"] = "keySystemStatusOutputRestricted";
  28. ErrorDetails2["KEY_SYSTEM_STATUS_INTERNAL_ERROR"] = "keySystemStatusInternalError";
  29. ErrorDetails2["KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR"] = "keySystemDestroyMediaKeysError";
  30. ErrorDetails2["KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR"] = "keySystemDestroyCloseSessionError";
  31. ErrorDetails2["KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR"] = "keySystemDestroyRemoveSessionError";
  32. ErrorDetails2["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
  33. ErrorDetails2["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
  34. ErrorDetails2["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
  35. ErrorDetails2["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
  36. ErrorDetails2["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
  37. ErrorDetails2["LEVEL_LOAD_ERROR"] = "levelLoadError";
  38. ErrorDetails2["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
  39. ErrorDetails2["LEVEL_PARSING_ERROR"] = "levelParsingError";
  40. ErrorDetails2["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
  41. ErrorDetails2["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
  42. ErrorDetails2["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
  43. ErrorDetails2["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
  44. ErrorDetails2["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
  45. ErrorDetails2["FRAG_LOAD_ERROR"] = "fragLoadError";
  46. ErrorDetails2["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
  47. ErrorDetails2["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
  48. ErrorDetails2["FRAG_PARSING_ERROR"] = "fragParsingError";
  49. ErrorDetails2["FRAG_GAP"] = "fragGap";
  50. ErrorDetails2["REMUX_ALLOC_ERROR"] = "remuxAllocError";
  51. ErrorDetails2["KEY_LOAD_ERROR"] = "keyLoadError";
  52. ErrorDetails2["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
  53. ErrorDetails2["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
  54. ErrorDetails2["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
  55. ErrorDetails2["BUFFER_APPEND_ERROR"] = "bufferAppendError";
  56. ErrorDetails2["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
  57. ErrorDetails2["BUFFER_STALLED_ERROR"] = "bufferStalledError";
  58. ErrorDetails2["BUFFER_FULL_ERROR"] = "bufferFullError";
  59. ErrorDetails2["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
  60. ErrorDetails2["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
  61. ErrorDetails2["ASSET_LIST_LOAD_ERROR"] = "assetListLoadError";
  62. ErrorDetails2["ASSET_LIST_LOAD_TIMEOUT"] = "assetListLoadTimeout";
  63. ErrorDetails2["ASSET_LIST_PARSING_ERROR"] = "assetListParsingError";
  64. ErrorDetails2["INTERSTITIAL_ASSET_ITEM_ERROR"] = "interstitialAssetItemError";
  65. ErrorDetails2["INTERNAL_EXCEPTION"] = "internalException";
  66. ErrorDetails2["INTERNAL_ABORTED"] = "aborted";
  67. ErrorDetails2["ATTACH_MEDIA_ERROR"] = "attachMediaError";
  68. ErrorDetails2["UNKNOWN"] = "unknown";
  69. return ErrorDetails2;
  70. }({});
  71. var Events = function(Events2) {
  72. Events2["MEDIA_ATTACHING"] = "hlsMediaAttaching";
  73. Events2["MEDIA_ATTACHED"] = "hlsMediaAttached";
  74. Events2["MEDIA_DETACHING"] = "hlsMediaDetaching";
  75. Events2["MEDIA_DETACHED"] = "hlsMediaDetached";
  76. Events2["MEDIA_ENDED"] = "hlsMediaEnded";
  77. Events2["STALL_RESOLVED"] = "hlsStallResolved";
  78. Events2["BUFFER_RESET"] = "hlsBufferReset";
  79. Events2["BUFFER_CODECS"] = "hlsBufferCodecs";
  80. Events2["BUFFER_CREATED"] = "hlsBufferCreated";
  81. Events2["BUFFER_APPENDING"] = "hlsBufferAppending";
  82. Events2["BUFFER_APPENDED"] = "hlsBufferAppended";
  83. Events2["BUFFER_EOS"] = "hlsBufferEos";
  84. Events2["BUFFERED_TO_END"] = "hlsBufferedToEnd";
  85. Events2["BUFFER_FLUSHING"] = "hlsBufferFlushing";
  86. Events2["BUFFER_FLUSHED"] = "hlsBufferFlushed";
  87. Events2["MANIFEST_LOADING"] = "hlsManifestLoading";
  88. Events2["MANIFEST_LOADED"] = "hlsManifestLoaded";
  89. Events2["MANIFEST_PARSED"] = "hlsManifestParsed";
  90. Events2["LEVEL_SWITCHING"] = "hlsLevelSwitching";
  91. Events2["LEVEL_SWITCHED"] = "hlsLevelSwitched";
  92. Events2["LEVEL_LOADING"] = "hlsLevelLoading";
  93. Events2["LEVEL_LOADED"] = "hlsLevelLoaded";
  94. Events2["LEVEL_UPDATED"] = "hlsLevelUpdated";
  95. Events2["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
  96. Events2["LEVELS_UPDATED"] = "hlsLevelsUpdated";
  97. Events2["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
  98. Events2["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
  99. Events2["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
  100. Events2["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
  101. Events2["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
  102. Events2["AUDIO_TRACK_UPDATED"] = "hlsAudioTrackUpdated";
  103. Events2["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
  104. Events2["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
  105. Events2["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
  106. Events2["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
  107. Events2["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
  108. Events2["SUBTITLE_TRACK_UPDATED"] = "hlsSubtitleTrackUpdated";
  109. Events2["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
  110. Events2["CUES_PARSED"] = "hlsCuesParsed";
  111. Events2["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
  112. Events2["INIT_PTS_FOUND"] = "hlsInitPtsFound";
  113. Events2["FRAG_LOADING"] = "hlsFragLoading";
  114. Events2["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
  115. Events2["FRAG_LOADED"] = "hlsFragLoaded";
  116. Events2["FRAG_DECRYPTED"] = "hlsFragDecrypted";
  117. Events2["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
  118. Events2["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
  119. Events2["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
  120. Events2["FRAG_PARSED"] = "hlsFragParsed";
  121. Events2["FRAG_BUFFERED"] = "hlsFragBuffered";
  122. Events2["FRAG_CHANGED"] = "hlsFragChanged";
  123. Events2["FPS_DROP"] = "hlsFpsDrop";
  124. Events2["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
  125. Events2["MAX_AUTO_LEVEL_UPDATED"] = "hlsMaxAutoLevelUpdated";
  126. Events2["ERROR"] = "hlsError";
  127. Events2["DESTROYING"] = "hlsDestroying";
  128. Events2["KEY_LOADING"] = "hlsKeyLoading";
  129. Events2["KEY_LOADED"] = "hlsKeyLoaded";
  130. Events2["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
  131. Events2["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
  132. Events2["STEERING_MANIFEST_LOADED"] = "hlsSteeringManifestLoaded";
  133. Events2["ASSET_LIST_LOADING"] = "hlsAssetListLoading";
  134. Events2["ASSET_LIST_LOADED"] = "hlsAssetListLoaded";
  135. Events2["INTERSTITIALS_UPDATED"] = "hlsInterstitialsUpdated";
  136. Events2["INTERSTITIALS_BUFFERED_TO_BOUNDARY"] = "hlsInterstitialsBufferedToBoundary";
  137. Events2["INTERSTITIAL_ASSET_PLAYER_CREATED"] = "hlsInterstitialAssetPlayerCreated";
  138. Events2["INTERSTITIAL_STARTED"] = "hlsInterstitialStarted";
  139. Events2["INTERSTITIAL_ASSET_STARTED"] = "hlsInterstitialAssetStarted";
  140. Events2["INTERSTITIAL_ASSET_ENDED"] = "hlsInterstitialAssetEnded";
  141. Events2["INTERSTITIAL_ASSET_ERROR"] = "hlsInterstitialAssetError";
  142. Events2["INTERSTITIAL_ENDED"] = "hlsInterstitialEnded";
  143. Events2["INTERSTITIALS_PRIMARY_RESUMED"] = "hlsInterstitialsPrimaryResumed";
  144. Events2["PLAYOUT_LIMIT_REACHED"] = "hlsPlayoutLimitReached";
  145. Events2["EVENT_CUE_ENTER"] = "hlsEventCueEnter";
  146. return Events2;
  147. }({});
  148. var PlaylistContextType = {
  149. MANIFEST: "manifest",
  150. LEVEL: "level",
  151. AUDIO_TRACK: "audioTrack",
  152. SUBTITLE_TRACK: "subtitleTrack"
  153. };
  154. var PlaylistLevelType = {
  155. MAIN: "main",
  156. AUDIO: "audio",
  157. SUBTITLE: "subtitle"
  158. };
  159. var EWMA = class {
  160. // About half of the estimated value will be from the last |halfLife| samples by weight.
  161. constructor(halfLife, estimate = 0, weight = 0) {
  162. this.halfLife = void 0;
  163. this.alpha_ = void 0;
  164. this.estimate_ = void 0;
  165. this.totalWeight_ = void 0;
  166. this.halfLife = halfLife;
  167. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  168. this.estimate_ = estimate;
  169. this.totalWeight_ = weight;
  170. }
  171. sample(weight, value) {
  172. const adjAlpha = Math.pow(this.alpha_, weight);
  173. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  174. this.totalWeight_ += weight;
  175. }
  176. getTotalWeight() {
  177. return this.totalWeight_;
  178. }
  179. getEstimate() {
  180. if (this.alpha_) {
  181. const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  182. if (zeroFactor) {
  183. return this.estimate_ / zeroFactor;
  184. }
  185. }
  186. return this.estimate_;
  187. }
  188. };
  189. var EwmaBandWidthEstimator = class {
  190. constructor(slow, fast, defaultEstimate, defaultTTFB = 100) {
  191. this.defaultEstimate_ = void 0;
  192. this.minWeight_ = void 0;
  193. this.minDelayMs_ = void 0;
  194. this.slow_ = void 0;
  195. this.fast_ = void 0;
  196. this.defaultTTFB_ = void 0;
  197. this.ttfb_ = void 0;
  198. this.defaultEstimate_ = defaultEstimate;
  199. this.minWeight_ = 1e-3;
  200. this.minDelayMs_ = 50;
  201. this.slow_ = new EWMA(slow);
  202. this.fast_ = new EWMA(fast);
  203. this.defaultTTFB_ = defaultTTFB;
  204. this.ttfb_ = new EWMA(slow);
  205. }
  206. update(slow, fast) {
  207. const {
  208. slow_,
  209. fast_,
  210. ttfb_
  211. } = this;
  212. if (slow_.halfLife !== slow) {
  213. this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());
  214. }
  215. if (fast_.halfLife !== fast) {
  216. this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());
  217. }
  218. if (ttfb_.halfLife !== slow) {
  219. this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());
  220. }
  221. }
  222. sample(durationMs, numBytes) {
  223. durationMs = Math.max(durationMs, this.minDelayMs_);
  224. const numBits = 8 * numBytes;
  225. const durationS = durationMs / 1e3;
  226. const bandwidthInBps = numBits / durationS;
  227. this.fast_.sample(durationS, bandwidthInBps);
  228. this.slow_.sample(durationS, bandwidthInBps);
  229. }
  230. sampleTTFB(ttfb) {
  231. const seconds = ttfb / 1e3;
  232. const weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);
  233. this.ttfb_.sample(weight, Math.max(ttfb, 5));
  234. }
  235. canEstimate() {
  236. return this.fast_.getTotalWeight() >= this.minWeight_;
  237. }
  238. getEstimate() {
  239. if (this.canEstimate()) {
  240. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  241. } else {
  242. return this.defaultEstimate_;
  243. }
  244. }
  245. getEstimateTTFB() {
  246. if (this.ttfb_.getTotalWeight() >= this.minWeight_) {
  247. return this.ttfb_.getEstimate();
  248. } else {
  249. return this.defaultTTFB_;
  250. }
  251. }
  252. get defaultEstimate() {
  253. return this.defaultEstimate_;
  254. }
  255. destroy() {
  256. }
  257. };
  258. function _defineProperty(e, r, t) {
  259. return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
  260. value: t,
  261. enumerable: true,
  262. configurable: true,
  263. writable: true
  264. }) : e[r] = t, e;
  265. }
  266. function _extends() {
  267. return _extends = Object.assign ? Object.assign.bind() : function(n) {
  268. for (var e = 1; e < arguments.length; e++) {
  269. var t = arguments[e];
  270. for (var r in t)
  271. ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
  272. }
  273. return n;
  274. }, _extends.apply(null, arguments);
  275. }
  276. function ownKeys(e, r) {
  277. var t = Object.keys(e);
  278. if (Object.getOwnPropertySymbols) {
  279. var o = Object.getOwnPropertySymbols(e);
  280. r && (o = o.filter(function(r2) {
  281. return Object.getOwnPropertyDescriptor(e, r2).enumerable;
  282. })), t.push.apply(t, o);
  283. }
  284. return t;
  285. }
  286. function _objectSpread2(e) {
  287. for (var r = 1; r < arguments.length; r++) {
  288. var t = null != arguments[r] ? arguments[r] : {};
  289. r % 2 ? ownKeys(Object(t), true).forEach(function(r2) {
  290. _defineProperty(e, r2, t[r2]);
  291. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) {
  292. Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
  293. });
  294. }
  295. return e;
  296. }
  297. function _toPrimitive(t, r) {
  298. if ("object" != typeof t || !t)
  299. return t;
  300. var e = t[Symbol.toPrimitive];
  301. if (void 0 !== e) {
  302. var i = e.call(t, r);
  303. if ("object" != typeof i)
  304. return i;
  305. throw new TypeError("@@toPrimitive must return a primitive value.");
  306. }
  307. return ("string" === r ? String : Number)(t);
  308. }
  309. function _toPropertyKey(t) {
  310. var i = _toPrimitive(t, "string");
  311. return "symbol" == typeof i ? i : i + "";
  312. }
  313. var Logger = class {
  314. constructor(label, logger2) {
  315. this.trace = void 0;
  316. this.debug = void 0;
  317. this.log = void 0;
  318. this.warn = void 0;
  319. this.info = void 0;
  320. this.error = void 0;
  321. const lb = `[${label}]:`;
  322. this.trace = noop;
  323. this.debug = logger2.debug.bind(null, lb);
  324. this.log = logger2.log.bind(null, lb);
  325. this.warn = logger2.warn.bind(null, lb);
  326. this.info = logger2.info.bind(null, lb);
  327. this.error = logger2.error.bind(null, lb);
  328. }
  329. };
  330. var noop = function noop2() {
  331. };
  332. var fakeLogger = {
  333. trace: noop,
  334. debug: noop,
  335. log: noop,
  336. warn: noop,
  337. info: noop,
  338. error: noop
  339. };
  340. function createLogger() {
  341. return _extends({}, fakeLogger);
  342. }
  343. function consolePrintFn(type, id) {
  344. const func = self.console[type];
  345. return func ? func.bind(self.console, `${id ? "[" + id + "] " : ""}[${type}] >`) : noop;
  346. }
  347. function getLoggerFn(key, debugConfig, id) {
  348. return debugConfig[key] ? debugConfig[key].bind(debugConfig) : consolePrintFn(key, id);
  349. }
  350. var exportedLogger = createLogger();
  351. function enableLogs(debugConfig, context, id) {
  352. const newLogger = createLogger();
  353. if (typeof console === "object" && debugConfig === true || typeof debugConfig === "object") {
  354. const keys = [
  355. // Remove out from list here to hard-disable a log-level
  356. // 'trace',
  357. "debug",
  358. "log",
  359. "info",
  360. "warn",
  361. "error"
  362. ];
  363. keys.forEach((key) => {
  364. newLogger[key] = getLoggerFn(key, debugConfig, id);
  365. });
  366. try {
  367. newLogger.log(`Debug logs enabled for "${context}" in hls.js version ${"1.6.7"}`);
  368. } catch (e) {
  369. return createLogger();
  370. }
  371. keys.forEach((key) => {
  372. exportedLogger[key] = getLoggerFn(key, debugConfig);
  373. });
  374. } else {
  375. _extends(exportedLogger, newLogger);
  376. }
  377. return newLogger;
  378. }
  379. var logger = exportedLogger;
  380. function getMediaSource(preferManagedMediaSource = true) {
  381. if (typeof self === "undefined")
  382. return void 0;
  383. const mms = (preferManagedMediaSource || !self.MediaSource) && self.ManagedMediaSource;
  384. return mms || self.MediaSource || self.WebKitMediaSource;
  385. }
  386. function isManagedMediaSource(source) {
  387. return typeof self !== "undefined" && source === self.ManagedMediaSource;
  388. }
  389. function isCompatibleTrackChange(currentTracks, requiredTracks) {
  390. const trackNames = Object.keys(currentTracks);
  391. const requiredTrackNames = Object.keys(requiredTracks);
  392. const trackCount = trackNames.length;
  393. const requiredTrackCount = requiredTrackNames.length;
  394. return !trackCount || !requiredTrackCount || trackCount === requiredTrackCount && !trackNames.some((name) => requiredTrackNames.indexOf(name) === -1);
  395. }
  396. function utf8ArrayToStr(array, exitOnNull = false) {
  397. if (typeof TextDecoder !== "undefined") {
  398. const decoder = new TextDecoder("utf-8");
  399. const decoded = decoder.decode(array);
  400. if (exitOnNull) {
  401. const idx = decoded.indexOf("\0");
  402. return idx !== -1 ? decoded.substring(0, idx) : decoded;
  403. }
  404. return decoded.replace(/\0/g, "");
  405. }
  406. const len = array.length;
  407. let c;
  408. let char2;
  409. let char3;
  410. let out = "";
  411. let i = 0;
  412. while (i < len) {
  413. c = array[i++];
  414. if (c === 0 && exitOnNull) {
  415. return out;
  416. } else if (c === 0 || c === 3) {
  417. continue;
  418. }
  419. switch (c >> 4) {
  420. case 0:
  421. case 1:
  422. case 2:
  423. case 3:
  424. case 4:
  425. case 5:
  426. case 6:
  427. case 7:
  428. out += String.fromCharCode(c);
  429. break;
  430. case 12:
  431. case 13:
  432. char2 = array[i++];
  433. out += String.fromCharCode((c & 31) << 6 | char2 & 63);
  434. break;
  435. case 14:
  436. char2 = array[i++];
  437. char3 = array[i++];
  438. out += String.fromCharCode((c & 15) << 12 | (char2 & 63) << 6 | (char3 & 63) << 0);
  439. break;
  440. }
  441. }
  442. return out;
  443. }
  444. var Hex = {
  445. hexDump: function(array) {
  446. let str = "";
  447. for (let i = 0; i < array.length; i++) {
  448. let h = array[i].toString(16);
  449. if (h.length < 2) {
  450. h = "0" + h;
  451. }
  452. str += h;
  453. }
  454. return str;
  455. }
  456. };
  457. function hexToArrayBuffer(str) {
  458. return Uint8Array.from(str.replace(/^0x/, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")).buffer;
  459. }
  460. function getDefaultExportFromCjs(x) {
  461. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
  462. }
  463. var urlToolkit = { exports: {} };
  464. var hasRequiredUrlToolkit;
  465. function requireUrlToolkit() {
  466. if (hasRequiredUrlToolkit)
  467. return urlToolkit.exports;
  468. hasRequiredUrlToolkit = 1;
  469. (function(module, exports) {
  470. (function(root) {
  471. var URL_REGEX = /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/;
  472. var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/;
  473. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  474. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  475. var URLToolkit = {
  476. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  477. // E.g
  478. // With opts.alwaysNormalize = false (default, spec compliant)
  479. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  480. // With opts.alwaysNormalize = true (not spec compliant)
  481. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  482. buildAbsoluteURL: function(baseURL, relativeURL, opts) {
  483. opts = opts || {};
  484. baseURL = baseURL.trim();
  485. relativeURL = relativeURL.trim();
  486. if (!relativeURL) {
  487. if (!opts.alwaysNormalize) {
  488. return baseURL;
  489. }
  490. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  491. if (!basePartsForNormalise) {
  492. throw new Error("Error trying to parse base URL.");
  493. }
  494. basePartsForNormalise.path = URLToolkit.normalizePath(
  495. basePartsForNormalise.path
  496. );
  497. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  498. }
  499. var relativeParts = URLToolkit.parseURL(relativeURL);
  500. if (!relativeParts) {
  501. throw new Error("Error trying to parse relative URL.");
  502. }
  503. if (relativeParts.scheme) {
  504. if (!opts.alwaysNormalize) {
  505. return relativeURL;
  506. }
  507. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  508. return URLToolkit.buildURLFromParts(relativeParts);
  509. }
  510. var baseParts = URLToolkit.parseURL(baseURL);
  511. if (!baseParts) {
  512. throw new Error("Error trying to parse base URL.");
  513. }
  514. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== "/") {
  515. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  516. baseParts.netLoc = pathParts[1];
  517. baseParts.path = pathParts[2];
  518. }
  519. if (baseParts.netLoc && !baseParts.path) {
  520. baseParts.path = "/";
  521. }
  522. var builtParts = {
  523. // 2c) Otherwise, the embedded URL inherits the scheme of
  524. // the base URL.
  525. scheme: baseParts.scheme,
  526. netLoc: relativeParts.netLoc,
  527. path: null,
  528. params: relativeParts.params,
  529. query: relativeParts.query,
  530. fragment: relativeParts.fragment
  531. };
  532. if (!relativeParts.netLoc) {
  533. builtParts.netLoc = baseParts.netLoc;
  534. if (relativeParts.path[0] !== "/") {
  535. if (!relativeParts.path) {
  536. builtParts.path = baseParts.path;
  537. if (!relativeParts.params) {
  538. builtParts.params = baseParts.params;
  539. if (!relativeParts.query) {
  540. builtParts.query = baseParts.query;
  541. }
  542. }
  543. } else {
  544. var baseURLPath = baseParts.path;
  545. var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf("/") + 1) + relativeParts.path;
  546. builtParts.path = URLToolkit.normalizePath(newPath);
  547. }
  548. }
  549. }
  550. if (builtParts.path === null) {
  551. builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
  552. }
  553. return URLToolkit.buildURLFromParts(builtParts);
  554. },
  555. parseURL: function(url) {
  556. var parts = URL_REGEX.exec(url);
  557. if (!parts) {
  558. return null;
  559. }
  560. return {
  561. scheme: parts[1] || "",
  562. netLoc: parts[2] || "",
  563. path: parts[3] || "",
  564. params: parts[4] || "",
  565. query: parts[5] || "",
  566. fragment: parts[6] || ""
  567. };
  568. },
  569. normalizePath: function(path) {
  570. path = path.split("").reverse().join("").replace(SLASH_DOT_REGEX, "");
  571. while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, "")).length) {
  572. }
  573. return path.split("").reverse().join("");
  574. },
  575. buildURLFromParts: function(parts) {
  576. return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
  577. }
  578. };
  579. module.exports = URLToolkit;
  580. })();
  581. })(urlToolkit);
  582. return urlToolkit.exports;
  583. }
  584. var urlToolkitExports = requireUrlToolkit();
  585. var LoadStats = class {
  586. constructor() {
  587. this.aborted = false;
  588. this.loaded = 0;
  589. this.retry = 0;
  590. this.total = 0;
  591. this.chunkCount = 0;
  592. this.bwEstimate = 0;
  593. this.loading = {
  594. start: 0,
  595. first: 0,
  596. end: 0
  597. };
  598. this.parsing = {
  599. start: 0,
  600. end: 0
  601. };
  602. this.buffering = {
  603. start: 0,
  604. first: 0,
  605. end: 0
  606. };
  607. }
  608. };
  609. var ElementaryStreamTypes = {
  610. AUDIO: "audio",
  611. VIDEO: "video",
  612. AUDIOVIDEO: "audiovideo"
  613. };
  614. var BaseSegment = class {
  615. constructor(base) {
  616. this._byteRange = null;
  617. this._url = null;
  618. this._stats = null;
  619. this._streams = null;
  620. this.base = void 0;
  621. this.relurl = void 0;
  622. if (typeof base === "string") {
  623. base = {
  624. url: base
  625. };
  626. }
  627. this.base = base;
  628. makeEnumerable(this, "stats");
  629. }
  630. // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
  631. setByteRange(value, previous) {
  632. const params = value.split("@", 2);
  633. let start;
  634. if (params.length === 1) {
  635. start = (previous == null ? void 0 : previous.byteRangeEndOffset) || 0;
  636. } else {
  637. start = parseInt(params[1]);
  638. }
  639. this._byteRange = [start, parseInt(params[0]) + start];
  640. }
  641. get baseurl() {
  642. return this.base.url;
  643. }
  644. get byteRange() {
  645. if (this._byteRange === null) {
  646. return [];
  647. }
  648. return this._byteRange;
  649. }
  650. get byteRangeStartOffset() {
  651. return this.byteRange[0];
  652. }
  653. get byteRangeEndOffset() {
  654. return this.byteRange[1];
  655. }
  656. get elementaryStreams() {
  657. if (this._streams === null) {
  658. this._streams = {
  659. [ElementaryStreamTypes.AUDIO]: null,
  660. [ElementaryStreamTypes.VIDEO]: null,
  661. [ElementaryStreamTypes.AUDIOVIDEO]: null
  662. };
  663. }
  664. return this._streams;
  665. }
  666. set elementaryStreams(value) {
  667. this._streams = value;
  668. }
  669. get hasStats() {
  670. return this._stats !== null;
  671. }
  672. get hasStreams() {
  673. return this._streams !== null;
  674. }
  675. get stats() {
  676. if (this._stats === null) {
  677. this._stats = new LoadStats();
  678. }
  679. return this._stats;
  680. }
  681. set stats(value) {
  682. this._stats = value;
  683. }
  684. get url() {
  685. if (!this._url && this.baseurl && this.relurl) {
  686. this._url = urlToolkitExports.buildAbsoluteURL(this.baseurl, this.relurl, {
  687. alwaysNormalize: true
  688. });
  689. }
  690. return this._url || "";
  691. }
  692. set url(value) {
  693. this._url = value;
  694. }
  695. clearElementaryStreamInfo() {
  696. const {
  697. elementaryStreams
  698. } = this;
  699. elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
  700. elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
  701. elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
  702. }
  703. };
  704. function isMediaFragment(frag) {
  705. return frag.sn !== "initSegment";
  706. }
  707. var Fragment = class extends BaseSegment {
  708. constructor(type, base) {
  709. super(base);
  710. this._decryptdata = null;
  711. this._programDateTime = null;
  712. this._ref = null;
  713. this._bitrate = void 0;
  714. this.rawProgramDateTime = null;
  715. this.tagList = [];
  716. this.duration = 0;
  717. this.sn = 0;
  718. this.levelkeys = void 0;
  719. this.type = void 0;
  720. this.loader = null;
  721. this.keyLoader = null;
  722. this.level = -1;
  723. this.cc = 0;
  724. this.startPTS = void 0;
  725. this.endPTS = void 0;
  726. this.startDTS = void 0;
  727. this.endDTS = void 0;
  728. this.start = 0;
  729. this.playlistOffset = 0;
  730. this.deltaPTS = void 0;
  731. this.maxStartPTS = void 0;
  732. this.minEndPTS = void 0;
  733. this.data = void 0;
  734. this.bitrateTest = false;
  735. this.title = null;
  736. this.initSegment = null;
  737. this.endList = void 0;
  738. this.gap = void 0;
  739. this.urlId = 0;
  740. this.type = type;
  741. }
  742. get byteLength() {
  743. if (this.hasStats) {
  744. const total = this.stats.total;
  745. if (total) {
  746. return total;
  747. }
  748. }
  749. if (this.byteRange) {
  750. const start = this.byteRange[0];
  751. const end = this.byteRange[1];
  752. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  753. return end - start;
  754. }
  755. }
  756. return null;
  757. }
  758. get bitrate() {
  759. if (this.byteLength) {
  760. return this.byteLength * 8 / this.duration;
  761. }
  762. if (this._bitrate) {
  763. return this._bitrate;
  764. }
  765. return null;
  766. }
  767. set bitrate(value) {
  768. this._bitrate = value;
  769. }
  770. get decryptdata() {
  771. const {
  772. levelkeys
  773. } = this;
  774. if (!levelkeys && !this._decryptdata) {
  775. return null;
  776. }
  777. if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) {
  778. const key = this.levelkeys.identity;
  779. if (key) {
  780. this._decryptdata = key.getDecryptData(this.sn);
  781. } else {
  782. const keyFormats = Object.keys(this.levelkeys);
  783. if (keyFormats.length === 1) {
  784. return this._decryptdata = this.levelkeys[keyFormats[0]].getDecryptData(this.sn);
  785. }
  786. }
  787. }
  788. return this._decryptdata;
  789. }
  790. get end() {
  791. return this.start + this.duration;
  792. }
  793. get endProgramDateTime() {
  794. if (this.programDateTime === null) {
  795. return null;
  796. }
  797. const duration = !isFiniteNumber(this.duration) ? 0 : this.duration;
  798. return this.programDateTime + duration * 1e3;
  799. }
  800. get encrypted() {
  801. var _this$_decryptdata;
  802. if ((_this$_decryptdata = this._decryptdata) != null && _this$_decryptdata.encrypted) {
  803. return true;
  804. } else if (this.levelkeys) {
  805. const keyFormats = Object.keys(this.levelkeys);
  806. const len = keyFormats.length;
  807. if (len > 1 || len === 1 && this.levelkeys[keyFormats[0]].encrypted) {
  808. return true;
  809. }
  810. }
  811. return false;
  812. }
  813. get programDateTime() {
  814. if (this._programDateTime === null && this.rawProgramDateTime) {
  815. this.programDateTime = Date.parse(this.rawProgramDateTime);
  816. }
  817. return this._programDateTime;
  818. }
  819. set programDateTime(value) {
  820. if (!isFiniteNumber(value)) {
  821. this._programDateTime = this.rawProgramDateTime = null;
  822. return;
  823. }
  824. this._programDateTime = value;
  825. }
  826. get ref() {
  827. if (!isMediaFragment(this)) {
  828. return null;
  829. }
  830. if (!this._ref) {
  831. this._ref = {
  832. base: this.base,
  833. start: this.start,
  834. duration: this.duration,
  835. sn: this.sn,
  836. programDateTime: this.programDateTime
  837. };
  838. }
  839. return this._ref;
  840. }
  841. addStart(value) {
  842. this.setStart(this.start + value);
  843. }
  844. setStart(value) {
  845. this.start = value;
  846. if (this._ref) {
  847. this._ref.start = value;
  848. }
  849. }
  850. setDuration(value) {
  851. this.duration = value;
  852. if (this._ref) {
  853. this._ref.duration = value;
  854. }
  855. }
  856. setKeyFormat(keyFormat) {
  857. if (this.levelkeys) {
  858. const key = this.levelkeys[keyFormat];
  859. if (key && !this._decryptdata) {
  860. this._decryptdata = key.getDecryptData(this.sn);
  861. }
  862. }
  863. }
  864. abortRequests() {
  865. var _this$loader, _this$keyLoader;
  866. (_this$loader = this.loader) == null ? void 0 : _this$loader.abort();
  867. (_this$keyLoader = this.keyLoader) == null ? void 0 : _this$keyLoader.abort();
  868. }
  869. setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial = false) {
  870. const {
  871. elementaryStreams
  872. } = this;
  873. const info = elementaryStreams[type];
  874. if (!info) {
  875. elementaryStreams[type] = {
  876. startPTS,
  877. endPTS,
  878. startDTS,
  879. endDTS,
  880. partial
  881. };
  882. return;
  883. }
  884. info.startPTS = Math.min(info.startPTS, startPTS);
  885. info.endPTS = Math.max(info.endPTS, endPTS);
  886. info.startDTS = Math.min(info.startDTS, startDTS);
  887. info.endDTS = Math.max(info.endDTS, endDTS);
  888. }
  889. };
  890. var Part = class extends BaseSegment {
  891. constructor(partAttrs, frag, base, index, previous) {
  892. super(base);
  893. this.fragOffset = 0;
  894. this.duration = 0;
  895. this.gap = false;
  896. this.independent = false;
  897. this.relurl = void 0;
  898. this.fragment = void 0;
  899. this.index = void 0;
  900. this.duration = partAttrs.decimalFloatingPoint("DURATION");
  901. this.gap = partAttrs.bool("GAP");
  902. this.independent = partAttrs.bool("INDEPENDENT");
  903. this.relurl = partAttrs.enumeratedString("URI");
  904. this.fragment = frag;
  905. this.index = index;
  906. const byteRange = partAttrs.enumeratedString("BYTERANGE");
  907. if (byteRange) {
  908. this.setByteRange(byteRange, previous);
  909. }
  910. if (previous) {
  911. this.fragOffset = previous.fragOffset + previous.duration;
  912. }
  913. }
  914. get start() {
  915. return this.fragment.start + this.fragOffset;
  916. }
  917. get end() {
  918. return this.start + this.duration;
  919. }
  920. get loaded() {
  921. const {
  922. elementaryStreams
  923. } = this;
  924. return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
  925. }
  926. };
  927. function getOwnPropertyDescriptorFromPrototypeChain(object, property) {
  928. const prototype = Object.getPrototypeOf(object);
  929. if (prototype) {
  930. const propertyDescriptor = Object.getOwnPropertyDescriptor(prototype, property);
  931. if (propertyDescriptor) {
  932. return propertyDescriptor;
  933. }
  934. return getOwnPropertyDescriptorFromPrototypeChain(prototype, property);
  935. }
  936. }
  937. function makeEnumerable(object, property) {
  938. const d = getOwnPropertyDescriptorFromPrototypeChain(object, property);
  939. if (d) {
  940. d.enumerable = true;
  941. Object.defineProperty(object, property, d);
  942. }
  943. }
  944. var UINT32_MAX$1 = Math.pow(2, 32) - 1;
  945. var push = [].push;
  946. var RemuxerTrackIdConfig = {
  947. video: 1,
  948. audio: 2,
  949. id3: 3,
  950. text: 4
  951. };
  952. function bin2str(data) {
  953. return String.fromCharCode.apply(null, data);
  954. }
  955. function readUint16(buffer, offset) {
  956. const val = buffer[offset] << 8 | buffer[offset + 1];
  957. return val < 0 ? 65536 + val : val;
  958. }
  959. function readUint32(buffer, offset) {
  960. const val = readSint32(buffer, offset);
  961. return val < 0 ? 4294967296 + val : val;
  962. }
  963. function readUint64(buffer, offset) {
  964. let result = readUint32(buffer, offset);
  965. result *= Math.pow(2, 32);
  966. result += readUint32(buffer, offset + 4);
  967. return result;
  968. }
  969. function readSint32(buffer, offset) {
  970. return buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
  971. }
  972. function hasMoofData(data) {
  973. const end = data.byteLength;
  974. for (let i = 0; i < end; ) {
  975. const size = readUint32(data, i);
  976. if (size > 8 && data[i + 4] === 109 && data[i + 5] === 111 && data[i + 6] === 111 && data[i + 7] === 102) {
  977. return true;
  978. }
  979. i = size > 1 ? i + size : end;
  980. }
  981. return false;
  982. }
  983. function findBox(data, path) {
  984. const results = [];
  985. if (!path.length) {
  986. return results;
  987. }
  988. const end = data.byteLength;
  989. for (let i = 0; i < end; ) {
  990. const size = readUint32(data, i);
  991. const type = bin2str(data.subarray(i + 4, i + 8));
  992. const endbox = size > 1 ? i + size : end;
  993. if (type === path[0]) {
  994. if (path.length === 1) {
  995. results.push(data.subarray(i + 8, endbox));
  996. } else {
  997. const subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));
  998. if (subresults.length) {
  999. push.apply(results, subresults);
  1000. }
  1001. }
  1002. }
  1003. i = endbox;
  1004. }
  1005. return results;
  1006. }
  1007. function parseSegmentIndex(sidx) {
  1008. const references = [];
  1009. const version2 = sidx[0];
  1010. let index = 8;
  1011. const timescale = readUint32(sidx, index);
  1012. index += 4;
  1013. let earliestPresentationTime = 0;
  1014. let firstOffset = 0;
  1015. if (version2 === 0) {
  1016. earliestPresentationTime = readUint32(sidx, index);
  1017. firstOffset = readUint32(sidx, index + 4);
  1018. index += 8;
  1019. } else {
  1020. earliestPresentationTime = readUint64(sidx, index);
  1021. firstOffset = readUint64(sidx, index + 8);
  1022. index += 16;
  1023. }
  1024. index += 2;
  1025. let startByte = sidx.length + firstOffset;
  1026. const referencesCount = readUint16(sidx, index);
  1027. index += 2;
  1028. for (let i = 0; i < referencesCount; i++) {
  1029. let referenceIndex = index;
  1030. const referenceInfo = readUint32(sidx, referenceIndex);
  1031. referenceIndex += 4;
  1032. const referenceSize = referenceInfo & 2147483647;
  1033. const referenceType = (referenceInfo & 2147483648) >>> 31;
  1034. if (referenceType === 1) {
  1035. logger.warn("SIDX has hierarchical references (not supported)");
  1036. return null;
  1037. }
  1038. const subsegmentDuration = readUint32(sidx, referenceIndex);
  1039. referenceIndex += 4;
  1040. references.push({
  1041. referenceSize,
  1042. subsegmentDuration,
  1043. // unscaled
  1044. info: {
  1045. duration: subsegmentDuration / timescale,
  1046. start: startByte,
  1047. end: startByte + referenceSize - 1
  1048. }
  1049. });
  1050. startByte += referenceSize;
  1051. referenceIndex += 4;
  1052. index = referenceIndex;
  1053. }
  1054. return {
  1055. earliestPresentationTime,
  1056. timescale,
  1057. version: version2,
  1058. referencesCount,
  1059. references
  1060. };
  1061. }
  1062. function parseInitSegment(initSegment) {
  1063. const result = [];
  1064. const traks = findBox(initSegment, ["moov", "trak"]);
  1065. for (let i = 0; i < traks.length; i++) {
  1066. const trak = traks[i];
  1067. const tkhd = findBox(trak, ["tkhd"])[0];
  1068. if (tkhd) {
  1069. let version2 = tkhd[0];
  1070. const trackId = readUint32(tkhd, version2 === 0 ? 12 : 20);
  1071. const mdhd = findBox(trak, ["mdia", "mdhd"])[0];
  1072. if (mdhd) {
  1073. version2 = mdhd[0];
  1074. const timescale = readUint32(mdhd, version2 === 0 ? 12 : 20);
  1075. const hdlr = findBox(trak, ["mdia", "hdlr"])[0];
  1076. if (hdlr) {
  1077. const hdlrType = bin2str(hdlr.subarray(8, 12));
  1078. const type = {
  1079. soun: ElementaryStreamTypes.AUDIO,
  1080. vide: ElementaryStreamTypes.VIDEO
  1081. }[hdlrType];
  1082. const stsdBox = findBox(trak, ["mdia", "minf", "stbl", "stsd"])[0];
  1083. const stsd = parseStsd(stsdBox);
  1084. if (type) {
  1085. result[trackId] = {
  1086. timescale,
  1087. type,
  1088. stsd
  1089. };
  1090. result[type] = _objectSpread2({
  1091. timescale,
  1092. id: trackId
  1093. }, stsd);
  1094. } else {
  1095. result[trackId] = {
  1096. timescale,
  1097. type: hdlrType,
  1098. stsd
  1099. };
  1100. }
  1101. }
  1102. }
  1103. }
  1104. }
  1105. const trex = findBox(initSegment, ["moov", "mvex", "trex"]);
  1106. trex.forEach((trex2) => {
  1107. const trackId = readUint32(trex2, 4);
  1108. const track = result[trackId];
  1109. if (track) {
  1110. track.default = {
  1111. duration: readUint32(trex2, 12),
  1112. flags: readUint32(trex2, 20)
  1113. };
  1114. }
  1115. });
  1116. return result;
  1117. }
  1118. function parseStsd(stsd) {
  1119. const sampleEntries = stsd.subarray(8);
  1120. const sampleEntriesEnd = sampleEntries.subarray(8 + 78);
  1121. const fourCC = bin2str(sampleEntries.subarray(4, 8));
  1122. let codec = fourCC;
  1123. let supplemental;
  1124. const encrypted = fourCC === "enca" || fourCC === "encv";
  1125. if (encrypted) {
  1126. const encBox = findBox(sampleEntries, [fourCC])[0];
  1127. const encBoxChildren = encBox.subarray(fourCC === "enca" ? 28 : 78);
  1128. const sinfs = findBox(encBoxChildren, ["sinf"]);
  1129. sinfs.forEach((sinf) => {
  1130. const schm = findBox(sinf, ["schm"])[0];
  1131. if (schm) {
  1132. const scheme = bin2str(schm.subarray(4, 8));
  1133. if (scheme === "cbcs" || scheme === "cenc") {
  1134. const frma = findBox(sinf, ["frma"])[0];
  1135. if (frma) {
  1136. codec = bin2str(frma);
  1137. }
  1138. }
  1139. }
  1140. });
  1141. }
  1142. const codecFourCC = codec;
  1143. switch (codec) {
  1144. case "avc1":
  1145. case "avc2":
  1146. case "avc3":
  1147. case "avc4": {
  1148. const avcCBox = findBox(sampleEntriesEnd, ["avcC"])[0];
  1149. if (avcCBox && avcCBox.length > 3) {
  1150. codec += "." + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]);
  1151. supplemental = parseSupplementalDoViCodec(codecFourCC === "avc1" ? "dva1" : "dvav", sampleEntriesEnd);
  1152. }
  1153. break;
  1154. }
  1155. case "mp4a": {
  1156. const codecBox = findBox(sampleEntries, [fourCC])[0];
  1157. const esdsBox = findBox(codecBox.subarray(28), ["esds"])[0];
  1158. if (esdsBox && esdsBox.length > 7) {
  1159. let i = 4;
  1160. if (esdsBox[i++] !== 3) {
  1161. break;
  1162. }
  1163. i = skipBERInteger(esdsBox, i);
  1164. i += 2;
  1165. const flags = esdsBox[i++];
  1166. if (flags & 128) {
  1167. i += 2;
  1168. }
  1169. if (flags & 64) {
  1170. i += esdsBox[i++];
  1171. }
  1172. if (esdsBox[i++] !== 4) {
  1173. break;
  1174. }
  1175. i = skipBERInteger(esdsBox, i);
  1176. const objectType = esdsBox[i++];
  1177. if (objectType === 64) {
  1178. codec += "." + toHex(objectType);
  1179. } else {
  1180. break;
  1181. }
  1182. i += 12;
  1183. if (esdsBox[i++] !== 5) {
  1184. break;
  1185. }
  1186. i = skipBERInteger(esdsBox, i);
  1187. const firstByte = esdsBox[i++];
  1188. let audioObjectType = (firstByte & 248) >> 3;
  1189. if (audioObjectType === 31) {
  1190. audioObjectType += 1 + ((firstByte & 7) << 3) + ((esdsBox[i] & 224) >> 5);
  1191. }
  1192. codec += "." + audioObjectType;
  1193. }
  1194. break;
  1195. }
  1196. case "hvc1":
  1197. case "hev1": {
  1198. const hvcCBox = findBox(sampleEntriesEnd, ["hvcC"])[0];
  1199. if (hvcCBox && hvcCBox.length > 12) {
  1200. const profileByte = hvcCBox[1];
  1201. const profileSpace = ["", "A", "B", "C"][profileByte >> 6];
  1202. const generalProfileIdc = profileByte & 31;
  1203. const profileCompat = readUint32(hvcCBox, 2);
  1204. const tierFlag = (profileByte & 32) >> 5 ? "H" : "L";
  1205. const levelIDC = hvcCBox[12];
  1206. const constraintIndicator = hvcCBox.subarray(6, 12);
  1207. codec += "." + profileSpace + generalProfileIdc;
  1208. codec += "." + reverse32BitInt(profileCompat).toString(16).toUpperCase();
  1209. codec += "." + tierFlag + levelIDC;
  1210. let constraintString = "";
  1211. for (let i = constraintIndicator.length; i--; ) {
  1212. const byte = constraintIndicator[i];
  1213. if (byte || constraintString) {
  1214. const encodedByte = byte.toString(16).toUpperCase();
  1215. constraintString = "." + encodedByte + constraintString;
  1216. }
  1217. }
  1218. codec += constraintString;
  1219. }
  1220. supplemental = parseSupplementalDoViCodec(codecFourCC == "hev1" ? "dvhe" : "dvh1", sampleEntriesEnd);
  1221. break;
  1222. }
  1223. case "dvh1":
  1224. case "dvhe":
  1225. case "dvav":
  1226. case "dva1":
  1227. case "dav1": {
  1228. codec = parseSupplementalDoViCodec(codec, sampleEntriesEnd) || codec;
  1229. break;
  1230. }
  1231. case "vp09": {
  1232. const vpcCBox = findBox(sampleEntriesEnd, ["vpcC"])[0];
  1233. if (vpcCBox && vpcCBox.length > 6) {
  1234. const profile = vpcCBox[4];
  1235. const level = vpcCBox[5];
  1236. const bitDepth = vpcCBox[6] >> 4 & 15;
  1237. codec += "." + addLeadingZero(profile) + "." + addLeadingZero(level) + "." + addLeadingZero(bitDepth);
  1238. }
  1239. break;
  1240. }
  1241. case "av01": {
  1242. const av1CBox = findBox(sampleEntriesEnd, ["av1C"])[0];
  1243. if (av1CBox && av1CBox.length > 2) {
  1244. const profile = av1CBox[1] >>> 5;
  1245. const level = av1CBox[1] & 31;
  1246. const tierFlag = av1CBox[2] >>> 7 ? "H" : "M";
  1247. const highBitDepth = (av1CBox[2] & 64) >> 6;
  1248. const twelveBit = (av1CBox[2] & 32) >> 5;
  1249. const bitDepth = profile === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8;
  1250. const monochrome = (av1CBox[2] & 16) >> 4;
  1251. const chromaSubsamplingX = (av1CBox[2] & 8) >> 3;
  1252. const chromaSubsamplingY = (av1CBox[2] & 4) >> 2;
  1253. const chromaSamplePosition = av1CBox[2] & 3;
  1254. const colorPrimaries = 1;
  1255. const transferCharacteristics = 1;
  1256. const matrixCoefficients = 1;
  1257. const videoFullRangeFlag = 0;
  1258. codec += "." + profile + "." + addLeadingZero(level) + tierFlag + "." + addLeadingZero(bitDepth) + "." + monochrome + "." + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition + "." + addLeadingZero(colorPrimaries) + "." + addLeadingZero(transferCharacteristics) + "." + addLeadingZero(matrixCoefficients) + "." + videoFullRangeFlag;
  1259. supplemental = parseSupplementalDoViCodec("dav1", sampleEntriesEnd);
  1260. }
  1261. break;
  1262. }
  1263. }
  1264. return {
  1265. codec,
  1266. encrypted,
  1267. supplemental
  1268. };
  1269. }
  1270. function parseSupplementalDoViCodec(fourCC, sampleEntriesEnd) {
  1271. const dvvCResult = findBox(sampleEntriesEnd, ["dvvC"]);
  1272. const dvXCBox = dvvCResult.length ? dvvCResult[0] : findBox(sampleEntriesEnd, ["dvcC"])[0];
  1273. if (dvXCBox) {
  1274. const doViProfile = dvXCBox[2] >> 1 & 127;
  1275. const doViLevel = dvXCBox[2] << 5 & 32 | dvXCBox[3] >> 3 & 31;
  1276. return fourCC + "." + addLeadingZero(doViProfile) + "." + addLeadingZero(doViLevel);
  1277. }
  1278. }
  1279. function reverse32BitInt(val) {
  1280. let result = 0;
  1281. for (let i = 0; i < 32; i++) {
  1282. result |= (val >> i & 1) << 32 - 1 - i;
  1283. }
  1284. return result >>> 0;
  1285. }
  1286. function skipBERInteger(bytes, i) {
  1287. const limit = i + 5;
  1288. while (bytes[i++] & 128 && i < limit) {
  1289. }
  1290. return i;
  1291. }
  1292. function toHex(x) {
  1293. return ("0" + x.toString(16).toUpperCase()).slice(-2);
  1294. }
  1295. function addLeadingZero(num) {
  1296. return (num < 10 ? "0" : "") + num;
  1297. }
  1298. function patchEncyptionData(initSegment, decryptdata) {
  1299. if (!initSegment || !decryptdata) {
  1300. return initSegment;
  1301. }
  1302. const keyId = decryptdata.keyId;
  1303. if (keyId && decryptdata.isCommonEncryption) {
  1304. const traks = findBox(initSegment, ["moov", "trak"]);
  1305. traks.forEach((trak) => {
  1306. const stsd = findBox(trak, ["mdia", "minf", "stbl", "stsd"])[0];
  1307. const sampleEntries = stsd.subarray(8);
  1308. let encBoxes = findBox(sampleEntries, ["enca"]);
  1309. const isAudio = encBoxes.length > 0;
  1310. if (!isAudio) {
  1311. encBoxes = findBox(sampleEntries, ["encv"]);
  1312. }
  1313. encBoxes.forEach((enc) => {
  1314. const encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);
  1315. const sinfBoxes = findBox(encBoxChildren, ["sinf"]);
  1316. sinfBoxes.forEach((sinf) => {
  1317. const tenc = parseSinf(sinf);
  1318. if (tenc) {
  1319. const tencKeyId = tenc.subarray(8, 24);
  1320. if (!tencKeyId.some((b) => b !== 0)) {
  1321. logger.log(`[eme] Patching keyId in 'enc${isAudio ? "a" : "v"}>sinf>>tenc' box: ${Hex.hexDump(tencKeyId)} -> ${Hex.hexDump(keyId)}`);
  1322. tenc.set(keyId, 8);
  1323. }
  1324. }
  1325. });
  1326. });
  1327. });
  1328. }
  1329. return initSegment;
  1330. }
  1331. function parseSinf(sinf) {
  1332. const schm = findBox(sinf, ["schm"])[0];
  1333. if (schm) {
  1334. const scheme = bin2str(schm.subarray(4, 8));
  1335. if (scheme === "cbcs" || scheme === "cenc") {
  1336. return findBox(sinf, ["schi", "tenc"])[0];
  1337. }
  1338. }
  1339. return null;
  1340. }
  1341. function getSampleData(data, initData, logger2) {
  1342. const tracks = {};
  1343. const trafs = findBox(data, ["moof", "traf"]);
  1344. for (let i = 0; i < trafs.length; i++) {
  1345. const traf = trafs[i];
  1346. const tfhd = findBox(traf, ["tfhd"])[0];
  1347. const id = readUint32(tfhd, 4);
  1348. const track = initData[id];
  1349. if (!track) {
  1350. continue;
  1351. }
  1352. const trackTimes = tracks[id] || (tracks[id] = {
  1353. start: NaN,
  1354. duration: 0,
  1355. sampleCount: 0,
  1356. timescale: track.timescale,
  1357. type: track.type
  1358. });
  1359. const tfdt = findBox(traf, ["tfdt"])[0];
  1360. if (tfdt) {
  1361. const version2 = tfdt[0];
  1362. let baseTime = readUint32(tfdt, 4);
  1363. if (version2 === 1) {
  1364. if (baseTime === UINT32_MAX$1) {
  1365. logger2.warn(`[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`);
  1366. } else {
  1367. baseTime *= UINT32_MAX$1 + 1;
  1368. baseTime += readUint32(tfdt, 8);
  1369. }
  1370. }
  1371. if (isFiniteNumber(baseTime) && (!isFiniteNumber(trackTimes.start) || baseTime < trackTimes.start)) {
  1372. trackTimes.start = baseTime;
  1373. }
  1374. }
  1375. const trackDefault = track.default;
  1376. const tfhdFlags = readUint32(tfhd, 0) | (trackDefault == null ? void 0 : trackDefault.flags);
  1377. let defaultSampleDuration = (trackDefault == null ? void 0 : trackDefault.duration) || 0;
  1378. if (tfhdFlags & 8) {
  1379. if (tfhdFlags & 2) {
  1380. defaultSampleDuration = readUint32(tfhd, 12);
  1381. } else {
  1382. defaultSampleDuration = readUint32(tfhd, 8);
  1383. }
  1384. }
  1385. const truns = findBox(traf, ["trun"]);
  1386. let sampleDTS = trackTimes.start || 0;
  1387. let rawDuration = 0;
  1388. let sampleDuration = defaultSampleDuration;
  1389. for (let j = 0; j < truns.length; j++) {
  1390. const trun = truns[j];
  1391. const sampleCount = readUint32(trun, 4);
  1392. const sampleIndex = trackTimes.sampleCount;
  1393. trackTimes.sampleCount += sampleCount;
  1394. const dataOffsetPresent = trun[3] & 1;
  1395. const firstSampleFlagsPresent = trun[3] & 4;
  1396. const sampleDurationPresent = trun[2] & 1;
  1397. const sampleSizePresent = trun[2] & 2;
  1398. const sampleFlagsPresent = trun[2] & 4;
  1399. const sampleCompositionTimeOffsetPresent = trun[2] & 8;
  1400. let offset = 8;
  1401. let remaining = sampleCount;
  1402. if (dataOffsetPresent) {
  1403. offset += 4;
  1404. }
  1405. if (firstSampleFlagsPresent && sampleCount) {
  1406. const isNonSyncSample = trun[offset + 1] & 1;
  1407. if (!isNonSyncSample && trackTimes.keyFrameIndex === void 0) {
  1408. trackTimes.keyFrameIndex = sampleIndex;
  1409. }
  1410. offset += 4;
  1411. if (sampleDurationPresent) {
  1412. sampleDuration = readUint32(trun, offset);
  1413. offset += 4;
  1414. } else {
  1415. sampleDuration = defaultSampleDuration;
  1416. }
  1417. if (sampleSizePresent) {
  1418. offset += 4;
  1419. }
  1420. if (sampleCompositionTimeOffsetPresent) {
  1421. offset += 4;
  1422. }
  1423. sampleDTS += sampleDuration;
  1424. rawDuration += sampleDuration;
  1425. remaining--;
  1426. }
  1427. while (remaining--) {
  1428. if (sampleDurationPresent) {
  1429. sampleDuration = readUint32(trun, offset);
  1430. offset += 4;
  1431. } else {
  1432. sampleDuration = defaultSampleDuration;
  1433. }
  1434. if (sampleSizePresent) {
  1435. offset += 4;
  1436. }
  1437. if (sampleFlagsPresent) {
  1438. const isNonSyncSample = trun[offset + 1] & 1;
  1439. if (!isNonSyncSample) {
  1440. if (trackTimes.keyFrameIndex === void 0) {
  1441. trackTimes.keyFrameIndex = trackTimes.sampleCount - (remaining + 1);
  1442. trackTimes.keyFrameStart = sampleDTS;
  1443. }
  1444. }
  1445. offset += 4;
  1446. }
  1447. if (sampleCompositionTimeOffsetPresent) {
  1448. offset += 4;
  1449. }
  1450. sampleDTS += sampleDuration;
  1451. rawDuration += sampleDuration;
  1452. }
  1453. if (!rawDuration && defaultSampleDuration) {
  1454. rawDuration += defaultSampleDuration * sampleCount;
  1455. }
  1456. }
  1457. trackTimes.duration += rawDuration;
  1458. }
  1459. if (!Object.keys(tracks).some((trackId) => tracks[trackId].duration)) {
  1460. let sidxMinStart = Infinity;
  1461. let sidxMaxEnd = 0;
  1462. const sidxs = findBox(data, ["sidx"]);
  1463. for (let i = 0; i < sidxs.length; i++) {
  1464. const sidx = parseSegmentIndex(sidxs[i]);
  1465. if (sidx != null && sidx.references) {
  1466. sidxMinStart = Math.min(sidxMinStart, sidx.earliestPresentationTime / sidx.timescale);
  1467. const subSegmentDuration = sidx.references.reduce((dur, ref) => dur + ref.info.duration || 0, 0);
  1468. sidxMaxEnd = Math.max(sidxMaxEnd, subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale);
  1469. }
  1470. }
  1471. if (sidxMaxEnd && isFiniteNumber(sidxMaxEnd)) {
  1472. Object.keys(tracks).forEach((trackId) => {
  1473. if (!tracks[trackId].duration) {
  1474. tracks[trackId].duration = sidxMaxEnd * tracks[trackId].timescale - tracks[trackId].start;
  1475. }
  1476. });
  1477. }
  1478. }
  1479. return tracks;
  1480. }
  1481. function segmentValidRange(data) {
  1482. const segmentedRange = {
  1483. valid: null,
  1484. remainder: null
  1485. };
  1486. const moofs = findBox(data, ["moof"]);
  1487. if (moofs.length < 2) {
  1488. segmentedRange.remainder = data;
  1489. return segmentedRange;
  1490. }
  1491. const last = moofs[moofs.length - 1];
  1492. segmentedRange.valid = data.slice(0, last.byteOffset - 8);
  1493. segmentedRange.remainder = data.slice(last.byteOffset - 8);
  1494. return segmentedRange;
  1495. }
  1496. function appendUint8Array(data1, data2) {
  1497. const temp = new Uint8Array(data1.length + data2.length);
  1498. temp.set(data1);
  1499. temp.set(data2, data1.length);
  1500. return temp;
  1501. }
  1502. function parseSamples(timeOffset, track) {
  1503. const seiSamples = [];
  1504. const videoData = track.samples;
  1505. const timescale = track.timescale;
  1506. const trackId = track.id;
  1507. let isHEVCFlavor = false;
  1508. const moofs = findBox(videoData, ["moof"]);
  1509. moofs.map((moof) => {
  1510. const moofOffset = moof.byteOffset - 8;
  1511. const trafs = findBox(moof, ["traf"]);
  1512. trafs.map((traf) => {
  1513. const baseTime = findBox(traf, ["tfdt"]).map((tfdt) => {
  1514. const version2 = tfdt[0];
  1515. let result = readUint32(tfdt, 4);
  1516. if (version2 === 1) {
  1517. result *= Math.pow(2, 32);
  1518. result += readUint32(tfdt, 8);
  1519. }
  1520. return result / timescale;
  1521. })[0];
  1522. if (baseTime !== void 0) {
  1523. timeOffset = baseTime;
  1524. }
  1525. return findBox(traf, ["tfhd"]).map((tfhd) => {
  1526. const id = readUint32(tfhd, 4);
  1527. const tfhdFlags = readUint32(tfhd, 0) & 16777215;
  1528. const baseDataOffsetPresent = (tfhdFlags & 1) !== 0;
  1529. const sampleDescriptionIndexPresent = (tfhdFlags & 2) !== 0;
  1530. const defaultSampleDurationPresent = (tfhdFlags & 8) !== 0;
  1531. let defaultSampleDuration = 0;
  1532. const defaultSampleSizePresent = (tfhdFlags & 16) !== 0;
  1533. let defaultSampleSize = 0;
  1534. const defaultSampleFlagsPresent = (tfhdFlags & 32) !== 0;
  1535. let tfhdOffset = 8;
  1536. if (id === trackId) {
  1537. if (baseDataOffsetPresent) {
  1538. tfhdOffset += 8;
  1539. }
  1540. if (sampleDescriptionIndexPresent) {
  1541. tfhdOffset += 4;
  1542. }
  1543. if (defaultSampleDurationPresent) {
  1544. defaultSampleDuration = readUint32(tfhd, tfhdOffset);
  1545. tfhdOffset += 4;
  1546. }
  1547. if (defaultSampleSizePresent) {
  1548. defaultSampleSize = readUint32(tfhd, tfhdOffset);
  1549. tfhdOffset += 4;
  1550. }
  1551. if (defaultSampleFlagsPresent) {
  1552. tfhdOffset += 4;
  1553. }
  1554. if (track.type === "video") {
  1555. isHEVCFlavor = isHEVC(track.codec);
  1556. }
  1557. findBox(traf, ["trun"]).map((trun) => {
  1558. const version2 = trun[0];
  1559. const flags = readUint32(trun, 0) & 16777215;
  1560. const dataOffsetPresent = (flags & 1) !== 0;
  1561. let dataOffset = 0;
  1562. const firstSampleFlagsPresent = (flags & 4) !== 0;
  1563. const sampleDurationPresent = (flags & 256) !== 0;
  1564. let sampleDuration = 0;
  1565. const sampleSizePresent = (flags & 512) !== 0;
  1566. let sampleSize = 0;
  1567. const sampleFlagsPresent = (flags & 1024) !== 0;
  1568. const sampleCompositionOffsetsPresent = (flags & 2048) !== 0;
  1569. let compositionOffset = 0;
  1570. const sampleCount = readUint32(trun, 4);
  1571. let trunOffset = 8;
  1572. if (dataOffsetPresent) {
  1573. dataOffset = readUint32(trun, trunOffset);
  1574. trunOffset += 4;
  1575. }
  1576. if (firstSampleFlagsPresent) {
  1577. trunOffset += 4;
  1578. }
  1579. let sampleOffset = dataOffset + moofOffset;
  1580. for (let ix = 0; ix < sampleCount; ix++) {
  1581. if (sampleDurationPresent) {
  1582. sampleDuration = readUint32(trun, trunOffset);
  1583. trunOffset += 4;
  1584. } else {
  1585. sampleDuration = defaultSampleDuration;
  1586. }
  1587. if (sampleSizePresent) {
  1588. sampleSize = readUint32(trun, trunOffset);
  1589. trunOffset += 4;
  1590. } else {
  1591. sampleSize = defaultSampleSize;
  1592. }
  1593. if (sampleFlagsPresent) {
  1594. trunOffset += 4;
  1595. }
  1596. if (sampleCompositionOffsetsPresent) {
  1597. if (version2 === 0) {
  1598. compositionOffset = readUint32(trun, trunOffset);
  1599. } else {
  1600. compositionOffset = readSint32(trun, trunOffset);
  1601. }
  1602. trunOffset += 4;
  1603. }
  1604. if (track.type === ElementaryStreamTypes.VIDEO) {
  1605. let naluTotalSize = 0;
  1606. while (naluTotalSize < sampleSize) {
  1607. const naluSize = readUint32(videoData, sampleOffset);
  1608. sampleOffset += 4;
  1609. if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {
  1610. const data = videoData.subarray(sampleOffset, sampleOffset + naluSize);
  1611. parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale, seiSamples);
  1612. }
  1613. sampleOffset += naluSize;
  1614. naluTotalSize += naluSize + 4;
  1615. }
  1616. }
  1617. timeOffset += sampleDuration / timescale;
  1618. }
  1619. });
  1620. }
  1621. });
  1622. });
  1623. });
  1624. return seiSamples;
  1625. }
  1626. function isHEVC(codec) {
  1627. if (!codec) {
  1628. return false;
  1629. }
  1630. const baseCodec = codec.substring(0, 4);
  1631. return baseCodec === "hvc1" || baseCodec === "hev1" || // Dolby Vision
  1632. baseCodec === "dvh1" || baseCodec === "dvhe";
  1633. }
  1634. function isSEIMessage(isHEVCFlavor, naluHeader) {
  1635. if (isHEVCFlavor) {
  1636. const naluType = naluHeader >> 1 & 63;
  1637. return naluType === 39 || naluType === 40;
  1638. } else {
  1639. const naluType = naluHeader & 31;
  1640. return naluType === 6;
  1641. }
  1642. }
  1643. function parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) {
  1644. const data = discardEPB(unescapedData);
  1645. let seiPtr = 0;
  1646. seiPtr += headerSize;
  1647. let payloadType = 0;
  1648. let payloadSize = 0;
  1649. let b = 0;
  1650. while (seiPtr < data.length) {
  1651. payloadType = 0;
  1652. do {
  1653. if (seiPtr >= data.length) {
  1654. break;
  1655. }
  1656. b = data[seiPtr++];
  1657. payloadType += b;
  1658. } while (b === 255);
  1659. payloadSize = 0;
  1660. do {
  1661. if (seiPtr >= data.length) {
  1662. break;
  1663. }
  1664. b = data[seiPtr++];
  1665. payloadSize += b;
  1666. } while (b === 255);
  1667. const leftOver = data.length - seiPtr;
  1668. let payPtr = seiPtr;
  1669. if (payloadSize < leftOver) {
  1670. seiPtr += payloadSize;
  1671. } else if (payloadSize > leftOver) {
  1672. logger.error(`Malformed SEI payload. ${payloadSize} is too small, only ${leftOver} bytes left to parse.`);
  1673. break;
  1674. }
  1675. if (payloadType === 4) {
  1676. const countryCode = data[payPtr++];
  1677. if (countryCode === 181) {
  1678. const providerCode = readUint16(data, payPtr);
  1679. payPtr += 2;
  1680. if (providerCode === 49) {
  1681. const userStructure = readUint32(data, payPtr);
  1682. payPtr += 4;
  1683. if (userStructure === 1195456820) {
  1684. const userDataType = data[payPtr++];
  1685. if (userDataType === 3) {
  1686. const firstByte = data[payPtr++];
  1687. const totalCCs = 31 & firstByte;
  1688. const enabled = 64 & firstByte;
  1689. const totalBytes = enabled ? 2 + totalCCs * 3 : 0;
  1690. const byteArray = new Uint8Array(totalBytes);
  1691. if (enabled) {
  1692. byteArray[0] = firstByte;
  1693. for (let i = 1; i < totalBytes; i++) {
  1694. byteArray[i] = data[payPtr++];
  1695. }
  1696. }
  1697. samples.push({
  1698. type: userDataType,
  1699. payloadType,
  1700. pts,
  1701. bytes: byteArray
  1702. });
  1703. }
  1704. }
  1705. }
  1706. }
  1707. } else if (payloadType === 5) {
  1708. if (payloadSize > 16) {
  1709. const uuidStrArray = [];
  1710. for (let i = 0; i < 16; i++) {
  1711. const _b = data[payPtr++].toString(16);
  1712. uuidStrArray.push(_b.length == 1 ? "0" + _b : _b);
  1713. if (i === 3 || i === 5 || i === 7 || i === 9) {
  1714. uuidStrArray.push("-");
  1715. }
  1716. }
  1717. const length = payloadSize - 16;
  1718. const userDataBytes = new Uint8Array(length);
  1719. for (let i = 0; i < length; i++) {
  1720. userDataBytes[i] = data[payPtr++];
  1721. }
  1722. samples.push({
  1723. payloadType,
  1724. pts,
  1725. uuid: uuidStrArray.join(""),
  1726. userData: utf8ArrayToStr(userDataBytes),
  1727. userDataBytes
  1728. });
  1729. }
  1730. }
  1731. }
  1732. }
  1733. function discardEPB(data) {
  1734. const length = data.byteLength;
  1735. const EPBPositions = [];
  1736. let i = 1;
  1737. while (i < length - 2) {
  1738. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 3) {
  1739. EPBPositions.push(i + 2);
  1740. i += 2;
  1741. } else {
  1742. i++;
  1743. }
  1744. }
  1745. if (EPBPositions.length === 0) {
  1746. return data;
  1747. }
  1748. const newLength = length - EPBPositions.length;
  1749. const newData = new Uint8Array(newLength);
  1750. let sourceIndex = 0;
  1751. for (i = 0; i < newLength; sourceIndex++, i++) {
  1752. if (sourceIndex === EPBPositions[0]) {
  1753. sourceIndex++;
  1754. EPBPositions.shift();
  1755. }
  1756. newData[i] = data[sourceIndex];
  1757. }
  1758. return newData;
  1759. }
  1760. function parseEmsg(data) {
  1761. const version2 = data[0];
  1762. let schemeIdUri = "";
  1763. let value = "";
  1764. let timeScale = 0;
  1765. let presentationTimeDelta = 0;
  1766. let presentationTime = 0;
  1767. let eventDuration = 0;
  1768. let id = 0;
  1769. let offset = 0;
  1770. if (version2 === 0) {
  1771. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  1772. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  1773. offset += 1;
  1774. }
  1775. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  1776. offset += 1;
  1777. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  1778. value += bin2str(data.subarray(offset, offset + 1));
  1779. offset += 1;
  1780. }
  1781. value += bin2str(data.subarray(offset, offset + 1));
  1782. offset += 1;
  1783. timeScale = readUint32(data, 12);
  1784. presentationTimeDelta = readUint32(data, 16);
  1785. eventDuration = readUint32(data, 20);
  1786. id = readUint32(data, 24);
  1787. offset = 28;
  1788. } else if (version2 === 1) {
  1789. offset += 4;
  1790. timeScale = readUint32(data, offset);
  1791. offset += 4;
  1792. const leftPresentationTime = readUint32(data, offset);
  1793. offset += 4;
  1794. const rightPresentationTime = readUint32(data, offset);
  1795. offset += 4;
  1796. presentationTime = 2 ** 32 * leftPresentationTime + rightPresentationTime;
  1797. if (!isSafeInteger(presentationTime)) {
  1798. presentationTime = Number.MAX_SAFE_INTEGER;
  1799. logger.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box");
  1800. }
  1801. eventDuration = readUint32(data, offset);
  1802. offset += 4;
  1803. id = readUint32(data, offset);
  1804. offset += 4;
  1805. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  1806. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  1807. offset += 1;
  1808. }
  1809. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  1810. offset += 1;
  1811. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  1812. value += bin2str(data.subarray(offset, offset + 1));
  1813. offset += 1;
  1814. }
  1815. value += bin2str(data.subarray(offset, offset + 1));
  1816. offset += 1;
  1817. }
  1818. const payload = data.subarray(offset, data.byteLength);
  1819. return {
  1820. schemeIdUri,
  1821. value,
  1822. timeScale,
  1823. presentationTime,
  1824. presentationTimeDelta,
  1825. eventDuration,
  1826. id,
  1827. payload
  1828. };
  1829. }
  1830. function mp4Box(type, ...payload) {
  1831. const len = payload.length;
  1832. let size = 8;
  1833. let i = len;
  1834. while (i--) {
  1835. size += payload[i].byteLength;
  1836. }
  1837. const result = new Uint8Array(size);
  1838. result[0] = size >> 24 & 255;
  1839. result[1] = size >> 16 & 255;
  1840. result[2] = size >> 8 & 255;
  1841. result[3] = size & 255;
  1842. result.set(type, 4);
  1843. for (i = 0, size = 8; i < len; i++) {
  1844. result.set(payload[i], size);
  1845. size += payload[i].byteLength;
  1846. }
  1847. return result;
  1848. }
  1849. function mp4pssh(systemId, keyids, data) {
  1850. if (systemId.byteLength !== 16) {
  1851. throw new RangeError("Invalid system id");
  1852. }
  1853. let version2;
  1854. let kids;
  1855. {
  1856. version2 = 0;
  1857. kids = new Uint8Array();
  1858. }
  1859. let kidCount;
  1860. if (version2 > 0) {
  1861. kidCount = new Uint8Array(4);
  1862. if (keyids.length > 0) {
  1863. new DataView(kidCount.buffer).setUint32(0, keyids.length, false);
  1864. }
  1865. } else {
  1866. kidCount = new Uint8Array();
  1867. }
  1868. const dataSize = new Uint8Array(4);
  1869. if (data && data.byteLength > 0) {
  1870. new DataView(dataSize.buffer).setUint32(0, data.byteLength, false);
  1871. }
  1872. return mp4Box(
  1873. [112, 115, 115, 104],
  1874. new Uint8Array([
  1875. version2,
  1876. 0,
  1877. 0,
  1878. 0
  1879. // Flags
  1880. ]),
  1881. systemId,
  1882. // 16 bytes
  1883. kidCount,
  1884. kids,
  1885. dataSize,
  1886. data || new Uint8Array()
  1887. );
  1888. }
  1889. var userAgentHevcSupportIsInaccurate = () => {
  1890. return /\(Windows.+Firefox\//i.test(navigator.userAgent);
  1891. };
  1892. var sampleEntryCodesISO = {
  1893. audio: {
  1894. a3ds: 1,
  1895. "ac-3": 0.95,
  1896. "ac-4": 1,
  1897. alac: 0.9,
  1898. alaw: 1,
  1899. dra1: 1,
  1900. "dts+": 1,
  1901. "dts-": 1,
  1902. dtsc: 1,
  1903. dtse: 1,
  1904. dtsh: 1,
  1905. "ec-3": 0.9,
  1906. enca: 1,
  1907. fLaC: 0.9,
  1908. // MP4-RA listed codec entry for FLAC
  1909. flac: 0.9,
  1910. // legacy browser codec name for FLAC
  1911. FLAC: 0.9,
  1912. // some manifests may list "FLAC" with Apple's tools
  1913. g719: 1,
  1914. g726: 1,
  1915. m4ae: 1,
  1916. mha1: 1,
  1917. mha2: 1,
  1918. mhm1: 1,
  1919. mhm2: 1,
  1920. mlpa: 1,
  1921. mp4a: 1,
  1922. "raw ": 1,
  1923. Opus: 1,
  1924. opus: 1,
  1925. // browsers expect this to be lowercase despite MP4RA says 'Opus'
  1926. samr: 1,
  1927. sawb: 1,
  1928. sawp: 1,
  1929. sevc: 1,
  1930. sqcp: 1,
  1931. ssmv: 1,
  1932. twos: 1,
  1933. ulaw: 1
  1934. },
  1935. video: {
  1936. avc1: 1,
  1937. avc2: 1,
  1938. avc3: 1,
  1939. avc4: 1,
  1940. avcp: 1,
  1941. av01: 0.8,
  1942. dav1: 0.8,
  1943. drac: 1,
  1944. dva1: 1,
  1945. dvav: 1,
  1946. dvh1: 0.7,
  1947. dvhe: 0.7,
  1948. encv: 1,
  1949. hev1: 0.75,
  1950. hvc1: 0.75,
  1951. mjp2: 1,
  1952. mp4v: 1,
  1953. mvc1: 1,
  1954. mvc2: 1,
  1955. mvc3: 1,
  1956. mvc4: 1,
  1957. resv: 1,
  1958. rv60: 1,
  1959. s263: 1,
  1960. svc1: 1,
  1961. svc2: 1,
  1962. "vc-1": 1,
  1963. vp08: 1,
  1964. vp09: 0.9
  1965. },
  1966. text: {
  1967. stpp: 1,
  1968. wvtt: 1
  1969. }
  1970. };
  1971. function isCodecType(codec, type) {
  1972. const typeCodes = sampleEntryCodesISO[type];
  1973. return !!typeCodes && !!typeCodes[codec.slice(0, 4)];
  1974. }
  1975. function areCodecsMediaSourceSupported(codecs, type, preferManagedMediaSource = true) {
  1976. return !codecs.split(",").some((codec) => !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource));
  1977. }
  1978. function isCodecMediaSourceSupported(codec, type, preferManagedMediaSource = true) {
  1979. var _MediaSource$isTypeSu;
  1980. const MediaSource = getMediaSource(preferManagedMediaSource);
  1981. return (_MediaSource$isTypeSu = MediaSource == null ? void 0 : MediaSource.isTypeSupported(mimeTypeForCodec(codec, type))) != null ? _MediaSource$isTypeSu : false;
  1982. }
  1983. function mimeTypeForCodec(codec, type) {
  1984. return `${type}/mp4;codecs=${codec}`;
  1985. }
  1986. function videoCodecPreferenceValue(videoCodec) {
  1987. if (videoCodec) {
  1988. const fourCC = videoCodec.substring(0, 4);
  1989. return sampleEntryCodesISO.video[fourCC];
  1990. }
  1991. return 2;
  1992. }
  1993. function codecsSetSelectionPreferenceValue(codecSet) {
  1994. const limitedHevcSupport = userAgentHevcSupportIsInaccurate();
  1995. return codecSet.split(",").reduce((num, fourCC) => {
  1996. const lowerPriority = limitedHevcSupport && isHEVC(fourCC);
  1997. const preferenceValue = lowerPriority ? 9 : sampleEntryCodesISO.video[fourCC];
  1998. if (preferenceValue) {
  1999. return (preferenceValue * 2 + num) / (num ? 3 : 2);
  2000. }
  2001. return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);
  2002. }, 0);
  2003. }
  2004. var CODEC_COMPATIBLE_NAMES = {};
  2005. function getCodecCompatibleNameLower(lowerCaseCodec, preferManagedMediaSource = true) {
  2006. if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {
  2007. return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];
  2008. }
  2009. const codecsToCheck = {
  2010. // Idealy fLaC and Opus would be first (spec-compliant) but
  2011. // some browsers will report that fLaC is supported then fail.
  2012. // see: https://bugs.chromium.org/p/chromium/issues/detail?id=1422728
  2013. flac: ["flac", "fLaC", "FLAC"],
  2014. opus: ["opus", "Opus"],
  2015. // Replace audio codec info if browser does not support mp4a.40.34,
  2016. // and demuxer can fallback to 'audio/mpeg' or 'audio/mp4;codecs="mp3"'
  2017. "mp4a.40.34": ["mp3"]
  2018. }[lowerCaseCodec];
  2019. for (let i = 0; i < codecsToCheck.length; i++) {
  2020. var _getMediaSource;
  2021. if (isCodecMediaSourceSupported(codecsToCheck[i], "audio", preferManagedMediaSource)) {
  2022. CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i];
  2023. return codecsToCheck[i];
  2024. } else if (codecsToCheck[i] === "mp3" && (_getMediaSource = getMediaSource(preferManagedMediaSource)) != null && _getMediaSource.isTypeSupported("audio/mpeg")) {
  2025. return "";
  2026. }
  2027. }
  2028. return lowerCaseCodec;
  2029. }
  2030. var AUDIO_CODEC_REGEXP = /flac|opus|mp4a\.40\.34/i;
  2031. function getCodecCompatibleName(codec, preferManagedMediaSource = true) {
  2032. return codec.replace(AUDIO_CODEC_REGEXP, (m) => getCodecCompatibleNameLower(m.toLowerCase(), preferManagedMediaSource));
  2033. }
  2034. function replaceVideoCodec(originalCodecs, newVideoCodec) {
  2035. const codecs = [];
  2036. if (originalCodecs) {
  2037. const allCodecs = originalCodecs.split(",");
  2038. for (let i = 0; i < allCodecs.length; i++) {
  2039. if (!isCodecType(allCodecs[i], "video")) {
  2040. codecs.push(allCodecs[i]);
  2041. }
  2042. }
  2043. }
  2044. if (newVideoCodec) {
  2045. codecs.push(newVideoCodec);
  2046. }
  2047. return codecs.join(",");
  2048. }
  2049. function pickMostCompleteCodecName(parsedCodec, levelCodec) {
  2050. if (parsedCodec && (parsedCodec.length > 4 || ["ac-3", "ec-3", "alac", "fLaC", "Opus"].indexOf(parsedCodec) !== -1)) {
  2051. if (isCodecSupportedAsType(parsedCodec, "audio") || isCodecSupportedAsType(parsedCodec, "video")) {
  2052. return parsedCodec;
  2053. }
  2054. }
  2055. if (levelCodec) {
  2056. const levelCodecs = levelCodec.split(",");
  2057. if (levelCodecs.length > 1) {
  2058. if (parsedCodec) {
  2059. for (let i = levelCodecs.length; i--; ) {
  2060. if (levelCodecs[i].substring(0, 4) === parsedCodec.substring(0, 4)) {
  2061. return levelCodecs[i];
  2062. }
  2063. }
  2064. }
  2065. return levelCodecs[0];
  2066. }
  2067. }
  2068. return levelCodec || parsedCodec;
  2069. }
  2070. function isCodecSupportedAsType(codec, type) {
  2071. return isCodecType(codec, type) && isCodecMediaSourceSupported(codec, type);
  2072. }
  2073. function convertAVC1ToAVCOTI(videoCodecs) {
  2074. const codecs = videoCodecs.split(",");
  2075. for (let i = 0; i < codecs.length; i++) {
  2076. const avcdata = codecs[i].split(".");
  2077. if (avcdata.length > 2 && avcdata[0] === "avc1") {
  2078. codecs[i] = `avc1.${parseInt(avcdata[1]).toString(16)}${("000" + parseInt(avcdata[2]).toString(16)).slice(-4)}`;
  2079. }
  2080. }
  2081. return codecs.join(",");
  2082. }
  2083. function fillInMissingAV01Params(videoCodec) {
  2084. if (videoCodec.startsWith("av01.")) {
  2085. const av1params = videoCodec.split(".");
  2086. const placeholders = ["0", "111", "01", "01", "01", "0"];
  2087. for (let i = av1params.length; i > 4 && i < 10; i++) {
  2088. av1params[i] = placeholders[i - 4];
  2089. }
  2090. return av1params.join(".");
  2091. }
  2092. return videoCodec;
  2093. }
  2094. function getM2TSSupportedAudioTypes(preferManagedMediaSource) {
  2095. const MediaSource = getMediaSource(preferManagedMediaSource) || {
  2096. isTypeSupported: () => false
  2097. };
  2098. return {
  2099. mpeg: MediaSource.isTypeSupported("audio/mpeg"),
  2100. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"'),
  2101. ac3: MediaSource.isTypeSupported('audio/mp4; codecs="ac-3"')
  2102. };
  2103. }
  2104. function getCodecsForMimeType(mimeType) {
  2105. return mimeType.replace(/^.+codecs=["']?([^"']+).*$/, "$1");
  2106. }
  2107. var SUPPORTED_INFO_DEFAULT = {
  2108. supported: true,
  2109. configurations: [],
  2110. decodingInfoResults: [{
  2111. supported: true,
  2112. powerEfficient: true,
  2113. smooth: true
  2114. }]
  2115. };
  2116. function getUnsupportedResult(error, configurations) {
  2117. return {
  2118. supported: false,
  2119. configurations,
  2120. decodingInfoResults: [{
  2121. supported: false,
  2122. smooth: false,
  2123. powerEfficient: false
  2124. }],
  2125. error
  2126. };
  2127. }
  2128. function requiresMediaCapabilitiesDecodingInfo(level, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference) {
  2129. const videoCodecs = level.videoCodec;
  2130. const audioGroups = level.audioCodec ? level.audioGroups : null;
  2131. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  2132. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  2133. const maxChannels = channelsPreference ? parseInt(channelsPreference) : audioCodecPreference ? Infinity : 2;
  2134. let audioChannels = null;
  2135. if (audioGroups != null && audioGroups.length) {
  2136. try {
  2137. if (audioGroups.length === 1 && audioGroups[0]) {
  2138. audioChannels = audioTracksByGroup.groups[audioGroups[0]].channels;
  2139. } else {
  2140. audioChannels = audioGroups.reduce((acc, groupId) => {
  2141. if (groupId) {
  2142. const audioTrackGroup = audioTracksByGroup.groups[groupId];
  2143. if (!audioTrackGroup) {
  2144. throw new Error(`Audio track group ${groupId} not found`);
  2145. }
  2146. Object.keys(audioTrackGroup.channels).forEach((key) => {
  2147. acc[key] = (acc[key] || 0) + audioTrackGroup.channels[key];
  2148. });
  2149. }
  2150. return acc;
  2151. }, {
  2152. 2: 0
  2153. });
  2154. }
  2155. } catch (error) {
  2156. return true;
  2157. }
  2158. }
  2159. return videoCodecs !== void 0 && // Force media capabilities check for HEVC to avoid failure on Windows
  2160. (videoCodecs.split(",").some((videoCodec) => isHEVC(videoCodec)) || level.width > 1920 && level.height > 1088 || level.height > 1920 && level.width > 1088 || level.frameRate > Math.max(currentFrameRate, 30) || level.videoRange !== "SDR" && level.videoRange !== currentVideoRange || level.bitrate > Math.max(currentBw, 8e6)) || !!audioChannels && isFiniteNumber(maxChannels) && Object.keys(audioChannels).some((channels) => parseInt(channels) > maxChannels);
  2161. }
  2162. function getMediaDecodingInfoPromise(level, audioTracksByGroup, mediaCapabilities, cache = {}) {
  2163. const videoCodecs = level.videoCodec;
  2164. if (!videoCodecs && !level.audioCodec || !mediaCapabilities) {
  2165. return Promise.resolve(SUPPORTED_INFO_DEFAULT);
  2166. }
  2167. const configurations = [];
  2168. const videoDecodeList = makeVideoConfigurations(level);
  2169. const videoCount = videoDecodeList.length;
  2170. const audioDecodeList = makeAudioConfigurations(level, audioTracksByGroup, videoCount > 0);
  2171. const audioCount = audioDecodeList.length;
  2172. for (let i = videoCount || 1 * audioCount || 1; i--; ) {
  2173. const configuration = {
  2174. type: "media-source"
  2175. };
  2176. if (videoCount) {
  2177. configuration.video = videoDecodeList[i % videoCount];
  2178. }
  2179. if (audioCount) {
  2180. configuration.audio = audioDecodeList[i % audioCount];
  2181. const audioBitrate = configuration.audio.bitrate;
  2182. if (configuration.video && audioBitrate) {
  2183. configuration.video.bitrate -= audioBitrate;
  2184. }
  2185. }
  2186. configurations.push(configuration);
  2187. }
  2188. if (videoCodecs) {
  2189. const ua = navigator.userAgent;
  2190. if (videoCodecs.split(",").some((videoCodec) => isHEVC(videoCodec)) && userAgentHevcSupportIsInaccurate()) {
  2191. return Promise.resolve(getUnsupportedResult(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${ua})`), configurations));
  2192. }
  2193. }
  2194. return Promise.all(configurations.map((configuration) => {
  2195. const decodingInfoKey = getMediaDecodingInfoKey(configuration);
  2196. return cache[decodingInfoKey] || (cache[decodingInfoKey] = mediaCapabilities.decodingInfo(configuration));
  2197. })).then((decodingInfoResults) => ({
  2198. supported: !decodingInfoResults.some((info) => !info.supported),
  2199. configurations,
  2200. decodingInfoResults
  2201. })).catch((error) => ({
  2202. supported: false,
  2203. configurations,
  2204. decodingInfoResults: [],
  2205. error
  2206. }));
  2207. }
  2208. function makeVideoConfigurations(level) {
  2209. var _level$videoCodec;
  2210. const videoCodecs = (_level$videoCodec = level.videoCodec) == null ? void 0 : _level$videoCodec.split(",");
  2211. const bitrate = getVariantDecodingBitrate(level);
  2212. const width = level.width || 640;
  2213. const height = level.height || 480;
  2214. const framerate = level.frameRate || 30;
  2215. const videoRange = level.videoRange.toLowerCase();
  2216. return videoCodecs ? videoCodecs.map((videoCodec) => {
  2217. const videoConfiguration = {
  2218. contentType: mimeTypeForCodec(fillInMissingAV01Params(videoCodec), "video"),
  2219. width,
  2220. height,
  2221. bitrate,
  2222. framerate
  2223. };
  2224. if (videoRange !== "sdr") {
  2225. videoConfiguration.transferFunction = videoRange;
  2226. }
  2227. return videoConfiguration;
  2228. }) : [];
  2229. }
  2230. function makeAudioConfigurations(level, audioTracksByGroup, hasVideo) {
  2231. var _level$audioCodec;
  2232. const audioCodecs = (_level$audioCodec = level.audioCodec) == null ? void 0 : _level$audioCodec.split(",");
  2233. const combinedBitrate = getVariantDecodingBitrate(level);
  2234. if (audioCodecs && level.audioGroups) {
  2235. return level.audioGroups.reduce((configurations, audioGroupId) => {
  2236. var _audioTracksByGroup$g;
  2237. const tracks = audioGroupId ? (_audioTracksByGroup$g = audioTracksByGroup.groups[audioGroupId]) == null ? void 0 : _audioTracksByGroup$g.tracks : null;
  2238. if (tracks) {
  2239. return tracks.reduce((configs, audioTrack) => {
  2240. if (audioTrack.groupId === audioGroupId) {
  2241. const channelsNumber = parseFloat(audioTrack.channels || "");
  2242. audioCodecs.forEach((audioCodec) => {
  2243. const audioConfiguration = {
  2244. contentType: mimeTypeForCodec(audioCodec, "audio"),
  2245. bitrate: hasVideo ? estimatedAudioBitrate(audioCodec, combinedBitrate) : combinedBitrate
  2246. };
  2247. if (channelsNumber) {
  2248. audioConfiguration.channels = "" + channelsNumber;
  2249. }
  2250. configs.push(audioConfiguration);
  2251. });
  2252. }
  2253. return configs;
  2254. }, configurations);
  2255. }
  2256. return configurations;
  2257. }, []);
  2258. }
  2259. return [];
  2260. }
  2261. function estimatedAudioBitrate(audioCodec, levelBitrate) {
  2262. if (levelBitrate <= 1) {
  2263. return 1;
  2264. }
  2265. let audioBitrate = 128e3;
  2266. if (audioCodec === "ec-3") {
  2267. audioBitrate = 768e3;
  2268. } else if (audioCodec === "ac-3") {
  2269. audioBitrate = 64e4;
  2270. }
  2271. return Math.min(levelBitrate / 2, audioBitrate);
  2272. }
  2273. function getVariantDecodingBitrate(level) {
  2274. return Math.ceil(Math.max(level.bitrate * 0.9, level.averageBitrate) / 1e3) * 1e3 || 1;
  2275. }
  2276. function getMediaDecodingInfoKey(config) {
  2277. let key = "";
  2278. const {
  2279. audio,
  2280. video
  2281. } = config;
  2282. if (video) {
  2283. const codec = getCodecsForMimeType(video.contentType);
  2284. key += `${codec}_r${video.height}x${video.width}f${Math.ceil(video.framerate)}${video.transferFunction || "sd"}_${Math.ceil(video.bitrate / 1e5)}`;
  2285. }
  2286. if (audio) {
  2287. const codec = getCodecsForMimeType(audio.contentType);
  2288. key += `${video ? "_" : ""}${codec}_c${audio.channels}`;
  2289. }
  2290. return key;
  2291. }
  2292. var HdcpLevels = ["NONE", "TYPE-0", "TYPE-1", null];
  2293. function isHdcpLevel(value) {
  2294. return HdcpLevels.indexOf(value) > -1;
  2295. }
  2296. var VideoRangeValues = ["SDR", "PQ", "HLG"];
  2297. function isVideoRange(value) {
  2298. return !!value && VideoRangeValues.indexOf(value) > -1;
  2299. }
  2300. var HlsSkip = {
  2301. No: "",
  2302. Yes: "YES",
  2303. v2: "v2"
  2304. };
  2305. function getSkipValue(details) {
  2306. const {
  2307. canSkipUntil,
  2308. canSkipDateRanges,
  2309. age
  2310. } = details;
  2311. const playlistRecentEnough = age < canSkipUntil / 2;
  2312. if (canSkipUntil && playlistRecentEnough) {
  2313. if (canSkipDateRanges) {
  2314. return HlsSkip.v2;
  2315. }
  2316. return HlsSkip.Yes;
  2317. }
  2318. return HlsSkip.No;
  2319. }
  2320. var HlsUrlParameters = class {
  2321. constructor(msn, part, skip) {
  2322. this.msn = void 0;
  2323. this.part = void 0;
  2324. this.skip = void 0;
  2325. this.msn = msn;
  2326. this.part = part;
  2327. this.skip = skip;
  2328. }
  2329. addDirectives(uri) {
  2330. const url = new self.URL(uri);
  2331. if (this.msn !== void 0) {
  2332. url.searchParams.set("_HLS_msn", this.msn.toString());
  2333. }
  2334. if (this.part !== void 0) {
  2335. url.searchParams.set("_HLS_part", this.part.toString());
  2336. }
  2337. if (this.skip) {
  2338. url.searchParams.set("_HLS_skip", this.skip);
  2339. }
  2340. return url.href;
  2341. }
  2342. };
  2343. var Level = class {
  2344. constructor(data) {
  2345. this._attrs = void 0;
  2346. this.audioCodec = void 0;
  2347. this.bitrate = void 0;
  2348. this.codecSet = void 0;
  2349. this.url = void 0;
  2350. this.frameRate = void 0;
  2351. this.height = void 0;
  2352. this.id = void 0;
  2353. this.name = void 0;
  2354. this.supplemental = void 0;
  2355. this.videoCodec = void 0;
  2356. this.width = void 0;
  2357. this.details = void 0;
  2358. this.fragmentError = 0;
  2359. this.loadError = 0;
  2360. this.loaded = void 0;
  2361. this.realBitrate = 0;
  2362. this.supportedPromise = void 0;
  2363. this.supportedResult = void 0;
  2364. this._avgBitrate = 0;
  2365. this._audioGroups = void 0;
  2366. this._subtitleGroups = void 0;
  2367. this._urlId = 0;
  2368. this.url = [data.url];
  2369. this._attrs = [data.attrs];
  2370. this.bitrate = data.bitrate;
  2371. if (data.details) {
  2372. this.details = data.details;
  2373. }
  2374. this.id = data.id || 0;
  2375. this.name = data.name;
  2376. this.width = data.width || 0;
  2377. this.height = data.height || 0;
  2378. this.frameRate = data.attrs.optionalFloat("FRAME-RATE", 0);
  2379. this._avgBitrate = data.attrs.decimalInteger("AVERAGE-BANDWIDTH");
  2380. this.audioCodec = data.audioCodec;
  2381. this.videoCodec = data.videoCodec;
  2382. this.codecSet = [data.videoCodec, data.audioCodec].filter((c) => !!c).map((s) => s.substring(0, 4)).join(",");
  2383. if ("supplemental" in data) {
  2384. var _data$supplemental;
  2385. this.supplemental = data.supplemental;
  2386. const supplementalVideo = (_data$supplemental = data.supplemental) == null ? void 0 : _data$supplemental.videoCodec;
  2387. if (supplementalVideo && supplementalVideo !== data.videoCodec) {
  2388. this.codecSet += `,${supplementalVideo.substring(0, 4)}`;
  2389. }
  2390. }
  2391. this.addGroupId("audio", data.attrs.AUDIO);
  2392. this.addGroupId("text", data.attrs.SUBTITLES);
  2393. }
  2394. get maxBitrate() {
  2395. return Math.max(this.realBitrate, this.bitrate);
  2396. }
  2397. get averageBitrate() {
  2398. return this._avgBitrate || this.realBitrate || this.bitrate;
  2399. }
  2400. get attrs() {
  2401. return this._attrs[0];
  2402. }
  2403. get codecs() {
  2404. return this.attrs.CODECS || "";
  2405. }
  2406. get pathwayId() {
  2407. return this.attrs["PATHWAY-ID"] || ".";
  2408. }
  2409. get videoRange() {
  2410. return this.attrs["VIDEO-RANGE"] || "SDR";
  2411. }
  2412. get score() {
  2413. return this.attrs.optionalFloat("SCORE", 0);
  2414. }
  2415. get uri() {
  2416. return this.url[0] || "";
  2417. }
  2418. hasAudioGroup(groupId) {
  2419. return hasGroup(this._audioGroups, groupId);
  2420. }
  2421. hasSubtitleGroup(groupId) {
  2422. return hasGroup(this._subtitleGroups, groupId);
  2423. }
  2424. get audioGroups() {
  2425. return this._audioGroups;
  2426. }
  2427. get subtitleGroups() {
  2428. return this._subtitleGroups;
  2429. }
  2430. addGroupId(type, groupId) {
  2431. if (!groupId) {
  2432. return;
  2433. }
  2434. if (type === "audio") {
  2435. let audioGroups = this._audioGroups;
  2436. if (!audioGroups) {
  2437. audioGroups = this._audioGroups = [];
  2438. }
  2439. if (audioGroups.indexOf(groupId) === -1) {
  2440. audioGroups.push(groupId);
  2441. }
  2442. } else if (type === "text") {
  2443. let subtitleGroups = this._subtitleGroups;
  2444. if (!subtitleGroups) {
  2445. subtitleGroups = this._subtitleGroups = [];
  2446. }
  2447. if (subtitleGroups.indexOf(groupId) === -1) {
  2448. subtitleGroups.push(groupId);
  2449. }
  2450. }
  2451. }
  2452. // Deprecated methods (retained for backwards compatibility)
  2453. get urlId() {
  2454. return 0;
  2455. }
  2456. set urlId(value) {
  2457. }
  2458. get audioGroupIds() {
  2459. return this.audioGroups ? [this.audioGroupId] : void 0;
  2460. }
  2461. get textGroupIds() {
  2462. return this.subtitleGroups ? [this.textGroupId] : void 0;
  2463. }
  2464. get audioGroupId() {
  2465. var _this$audioGroups;
  2466. return (_this$audioGroups = this.audioGroups) == null ? void 0 : _this$audioGroups[0];
  2467. }
  2468. get textGroupId() {
  2469. var _this$subtitleGroups;
  2470. return (_this$subtitleGroups = this.subtitleGroups) == null ? void 0 : _this$subtitleGroups[0];
  2471. }
  2472. addFallback() {
  2473. }
  2474. };
  2475. function hasGroup(groups, groupId) {
  2476. if (!groupId || !groups) {
  2477. return false;
  2478. }
  2479. return groups.indexOf(groupId) !== -1;
  2480. }
  2481. function isHdrSupported() {
  2482. if (typeof matchMedia === "function") {
  2483. const mediaQueryList = matchMedia("(dynamic-range: high)");
  2484. const badQuery = matchMedia("bad query");
  2485. if (mediaQueryList.media !== badQuery.media) {
  2486. return mediaQueryList.matches === true;
  2487. }
  2488. }
  2489. return false;
  2490. }
  2491. function getVideoSelectionOptions(currentVideoRange, videoPreference) {
  2492. let preferHDR = false;
  2493. let allowedVideoRanges = [];
  2494. if (currentVideoRange) {
  2495. preferHDR = currentVideoRange !== "SDR";
  2496. allowedVideoRanges = [currentVideoRange];
  2497. }
  2498. if (videoPreference) {
  2499. allowedVideoRanges = videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);
  2500. const allowAutoPreferHDR = allowedVideoRanges.join("") !== "SDR" && !videoPreference.videoCodec;
  2501. preferHDR = videoPreference.preferHDR !== void 0 ? videoPreference.preferHDR : allowAutoPreferHDR && isHdrSupported();
  2502. if (!preferHDR) {
  2503. allowedVideoRanges = ["SDR"];
  2504. }
  2505. }
  2506. return {
  2507. preferHDR,
  2508. allowedVideoRanges
  2509. };
  2510. }
  2511. var omitCircularRefsReplacer = (replacer) => {
  2512. const known = /* @__PURE__ */ new WeakSet();
  2513. return (_, value) => {
  2514. if (replacer) {
  2515. value = replacer(_, value);
  2516. }
  2517. if (typeof value === "object" && value !== null) {
  2518. if (known.has(value)) {
  2519. return;
  2520. }
  2521. known.add(value);
  2522. }
  2523. return value;
  2524. };
  2525. };
  2526. var stringify = (object, replacer) => JSON.stringify(object, omitCircularRefsReplacer(replacer));
  2527. function getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference) {
  2528. const codecSets = Object.keys(codecTiers);
  2529. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  2530. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  2531. const videoCodecPreference = videoPreference == null ? void 0 : videoPreference.videoCodec;
  2532. const preferStereo = channelsPreference && parseInt(channelsPreference) === 2;
  2533. let hasStereo = false;
  2534. let hasCurrentVideoRange = false;
  2535. let minHeight = Infinity;
  2536. let minFramerate = Infinity;
  2537. let minBitrate = Infinity;
  2538. let minIndex = Infinity;
  2539. let selectedScore = 0;
  2540. let videoRanges = [];
  2541. const {
  2542. preferHDR,
  2543. allowedVideoRanges
  2544. } = getVideoSelectionOptions(currentVideoRange, videoPreference);
  2545. for (let i = codecSets.length; i--; ) {
  2546. const tier = codecTiers[codecSets[i]];
  2547. hasStereo || (hasStereo = tier.channels[2] > 0);
  2548. minHeight = Math.min(minHeight, tier.minHeight);
  2549. minFramerate = Math.min(minFramerate, tier.minFramerate);
  2550. minBitrate = Math.min(minBitrate, tier.minBitrate);
  2551. const matchingVideoRanges = allowedVideoRanges.filter((range) => tier.videoRanges[range] > 0);
  2552. if (matchingVideoRanges.length > 0) {
  2553. hasCurrentVideoRange = true;
  2554. }
  2555. }
  2556. minHeight = isFiniteNumber(minHeight) ? minHeight : 0;
  2557. minFramerate = isFiniteNumber(minFramerate) ? minFramerate : 0;
  2558. const maxHeight = Math.max(1080, minHeight);
  2559. const maxFramerate = Math.max(30, minFramerate);
  2560. minBitrate = isFiniteNumber(minBitrate) ? minBitrate : currentBw;
  2561. currentBw = Math.max(minBitrate, currentBw);
  2562. if (!hasCurrentVideoRange) {
  2563. currentVideoRange = void 0;
  2564. }
  2565. const hasMultipleSets = codecSets.length > 1;
  2566. const codecSet = codecSets.reduce((selected, candidate) => {
  2567. const candidateTier = codecTiers[candidate];
  2568. if (candidate === selected) {
  2569. return selected;
  2570. }
  2571. videoRanges = hasCurrentVideoRange ? allowedVideoRanges.filter((range) => candidateTier.videoRanges[range] > 0) : [];
  2572. if (hasMultipleSets) {
  2573. if (candidateTier.minBitrate > currentBw) {
  2574. logStartCodecCandidateIgnored(candidate, `min bitrate of ${candidateTier.minBitrate} > current estimate of ${currentBw}`);
  2575. return selected;
  2576. }
  2577. if (!candidateTier.hasDefaultAudio) {
  2578. logStartCodecCandidateIgnored(candidate, `no renditions with default or auto-select sound found`);
  2579. return selected;
  2580. }
  2581. if (audioCodecPreference && candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0) {
  2582. logStartCodecCandidateIgnored(candidate, `audio codec preference "${audioCodecPreference}" not found`);
  2583. return selected;
  2584. }
  2585. if (channelsPreference && !preferStereo) {
  2586. if (!candidateTier.channels[channelsPreference]) {
  2587. logStartCodecCandidateIgnored(candidate, `no renditions with ${channelsPreference} channel sound found (channels options: ${Object.keys(candidateTier.channels)})`);
  2588. return selected;
  2589. }
  2590. } else if ((!audioCodecPreference || preferStereo) && hasStereo && candidateTier.channels["2"] === 0) {
  2591. logStartCodecCandidateIgnored(candidate, `no renditions with stereo sound found`);
  2592. return selected;
  2593. }
  2594. if (candidateTier.minHeight > maxHeight) {
  2595. logStartCodecCandidateIgnored(candidate, `min resolution of ${candidateTier.minHeight} > maximum of ${maxHeight}`);
  2596. return selected;
  2597. }
  2598. if (candidateTier.minFramerate > maxFramerate) {
  2599. logStartCodecCandidateIgnored(candidate, `min framerate of ${candidateTier.minFramerate} > maximum of ${maxFramerate}`);
  2600. return selected;
  2601. }
  2602. if (!videoRanges.some((range) => candidateTier.videoRanges[range] > 0)) {
  2603. logStartCodecCandidateIgnored(candidate, `no variants with VIDEO-RANGE of ${stringify(videoRanges)} found`);
  2604. return selected;
  2605. }
  2606. if (videoCodecPreference && candidate.indexOf(videoCodecPreference.substring(0, 4)) % 5 !== 0) {
  2607. logStartCodecCandidateIgnored(candidate, `video codec preference "${videoCodecPreference}" not found`);
  2608. return selected;
  2609. }
  2610. if (candidateTier.maxScore < selectedScore) {
  2611. logStartCodecCandidateIgnored(candidate, `max score of ${candidateTier.maxScore} < selected max of ${selectedScore}`);
  2612. return selected;
  2613. }
  2614. }
  2615. if (selected && (codecsSetSelectionPreferenceValue(candidate) >= codecsSetSelectionPreferenceValue(selected) || candidateTier.fragmentError > codecTiers[selected].fragmentError)) {
  2616. return selected;
  2617. }
  2618. minIndex = candidateTier.minIndex;
  2619. selectedScore = candidateTier.maxScore;
  2620. return candidate;
  2621. }, void 0);
  2622. return {
  2623. codecSet,
  2624. videoRanges,
  2625. preferHDR,
  2626. minFramerate,
  2627. minBitrate,
  2628. minIndex
  2629. };
  2630. }
  2631. function logStartCodecCandidateIgnored(codeSet, reason) {
  2632. logger.log(`[abr] start candidates with "${codeSet}" ignored because ${reason}`);
  2633. }
  2634. function getAudioTracksByGroup(allAudioTracks) {
  2635. return allAudioTracks.reduce((audioTracksByGroup, track) => {
  2636. let trackGroup = audioTracksByGroup.groups[track.groupId];
  2637. if (!trackGroup) {
  2638. trackGroup = audioTracksByGroup.groups[track.groupId] = {
  2639. tracks: [],
  2640. channels: {
  2641. 2: 0
  2642. },
  2643. hasDefault: false,
  2644. hasAutoSelect: false
  2645. };
  2646. }
  2647. trackGroup.tracks.push(track);
  2648. const channelsKey = track.channels || "2";
  2649. trackGroup.channels[channelsKey] = (trackGroup.channels[channelsKey] || 0) + 1;
  2650. trackGroup.hasDefault = trackGroup.hasDefault || track.default;
  2651. trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;
  2652. if (trackGroup.hasDefault) {
  2653. audioTracksByGroup.hasDefaultAudio = true;
  2654. }
  2655. if (trackGroup.hasAutoSelect) {
  2656. audioTracksByGroup.hasAutoSelectAudio = true;
  2657. }
  2658. return audioTracksByGroup;
  2659. }, {
  2660. hasDefaultAudio: false,
  2661. hasAutoSelectAudio: false,
  2662. groups: {}
  2663. });
  2664. }
  2665. function getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel) {
  2666. return levels.slice(minAutoLevel, maxAutoLevel + 1).reduce((tiers, level, index) => {
  2667. if (!level.codecSet) {
  2668. return tiers;
  2669. }
  2670. const audioGroups = level.audioGroups;
  2671. let tier = tiers[level.codecSet];
  2672. if (!tier) {
  2673. tiers[level.codecSet] = tier = {
  2674. minBitrate: Infinity,
  2675. minHeight: Infinity,
  2676. minFramerate: Infinity,
  2677. minIndex: index,
  2678. maxScore: 0,
  2679. videoRanges: {
  2680. SDR: 0
  2681. },
  2682. channels: {
  2683. "2": 0
  2684. },
  2685. hasDefaultAudio: !audioGroups,
  2686. fragmentError: 0
  2687. };
  2688. }
  2689. tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);
  2690. const lesserWidthOrHeight = Math.min(level.height, level.width);
  2691. tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);
  2692. tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);
  2693. tier.minIndex = Math.min(tier.minIndex, index);
  2694. tier.maxScore = Math.max(tier.maxScore, level.score);
  2695. tier.fragmentError += level.fragmentError;
  2696. tier.videoRanges[level.videoRange] = (tier.videoRanges[level.videoRange] || 0) + 1;
  2697. if (audioGroups) {
  2698. audioGroups.forEach((audioGroupId) => {
  2699. if (!audioGroupId) {
  2700. return;
  2701. }
  2702. const audioGroup = audioTracksByGroup.groups[audioGroupId];
  2703. if (!audioGroup) {
  2704. return;
  2705. }
  2706. tier.hasDefaultAudio = tier.hasDefaultAudio || audioTracksByGroup.hasDefaultAudio ? audioGroup.hasDefault : audioGroup.hasAutoSelect || !audioTracksByGroup.hasDefaultAudio && !audioTracksByGroup.hasAutoSelectAudio;
  2707. Object.keys(audioGroup.channels).forEach((channels) => {
  2708. tier.channels[channels] = (tier.channels[channels] || 0) + audioGroup.channels[channels];
  2709. });
  2710. });
  2711. }
  2712. return tiers;
  2713. }, {});
  2714. }
  2715. function getBasicSelectionOption(option) {
  2716. if (!option) {
  2717. return option;
  2718. }
  2719. const {
  2720. lang,
  2721. assocLang,
  2722. characteristics,
  2723. channels,
  2724. audioCodec
  2725. } = option;
  2726. return {
  2727. lang,
  2728. assocLang,
  2729. characteristics,
  2730. channels,
  2731. audioCodec
  2732. };
  2733. }
  2734. function findMatchingOption(option, tracks, matchPredicate) {
  2735. if ("attrs" in option) {
  2736. const index = tracks.indexOf(option);
  2737. if (index !== -1) {
  2738. return index;
  2739. }
  2740. }
  2741. for (let i = 0; i < tracks.length; i++) {
  2742. const track = tracks[i];
  2743. if (matchesOption(option, track, matchPredicate)) {
  2744. return i;
  2745. }
  2746. }
  2747. return -1;
  2748. }
  2749. function matchesOption(option, track, matchPredicate) {
  2750. const {
  2751. groupId,
  2752. name,
  2753. lang,
  2754. assocLang,
  2755. default: isDefault
  2756. } = option;
  2757. const forced = option.forced;
  2758. return (groupId === void 0 || track.groupId === groupId) && (name === void 0 || track.name === name) && (lang === void 0 || languagesMatch(lang, track.lang)) && (lang === void 0 || track.assocLang === assocLang) && (isDefault === void 0 || track.default === isDefault) && (forced === void 0 || track.forced === forced) && (!("characteristics" in option) || characteristicsMatch(option.characteristics || "", track.characteristics)) && (matchPredicate === void 0 || matchPredicate(option, track));
  2759. }
  2760. function languagesMatch(languageA, languageB = "--") {
  2761. if (languageA.length === languageB.length) {
  2762. return languageA === languageB;
  2763. }
  2764. return languageA.startsWith(languageB) || languageB.startsWith(languageA);
  2765. }
  2766. function characteristicsMatch(characteristicsA, characteristicsB = "") {
  2767. const arrA = characteristicsA.split(",");
  2768. const arrB = characteristicsB.split(",");
  2769. return arrA.length === arrB.length && !arrA.some((el) => arrB.indexOf(el) === -1);
  2770. }
  2771. function audioMatchPredicate(option, track) {
  2772. const {
  2773. audioCodec,
  2774. channels
  2775. } = option;
  2776. return (audioCodec === void 0 || (track.audioCodec || "").substring(0, 4) === audioCodec.substring(0, 4)) && (channels === void 0 || channels === (track.channels || "2"));
  2777. }
  2778. function findClosestLevelWithAudioGroup(option, levels, allAudioTracks, searchIndex, matchPredicate) {
  2779. const currentLevel = levels[searchIndex];
  2780. const variants = levels.reduce((variantMap, level, index) => {
  2781. const uri = level.uri;
  2782. const renditions2 = variantMap[uri] || (variantMap[uri] = []);
  2783. renditions2.push(index);
  2784. return variantMap;
  2785. }, {});
  2786. const renditions = variants[currentLevel.uri];
  2787. if (renditions.length > 1) {
  2788. searchIndex = Math.max.apply(Math, renditions);
  2789. }
  2790. const currentVideoRange = currentLevel.videoRange;
  2791. const currentFrameRate = currentLevel.frameRate;
  2792. const currentVideoCodec = currentLevel.codecSet.substring(0, 4);
  2793. const matchingVideo = searchDownAndUpList(levels, searchIndex, (level) => {
  2794. if (level.videoRange !== currentVideoRange || level.frameRate !== currentFrameRate || level.codecSet.substring(0, 4) !== currentVideoCodec) {
  2795. return false;
  2796. }
  2797. const audioGroups = level.audioGroups;
  2798. const tracks = allAudioTracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  2799. return findMatchingOption(option, tracks, matchPredicate) > -1;
  2800. });
  2801. if (matchingVideo > -1) {
  2802. return matchingVideo;
  2803. }
  2804. return searchDownAndUpList(levels, searchIndex, (level) => {
  2805. const audioGroups = level.audioGroups;
  2806. const tracks = allAudioTracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  2807. return findMatchingOption(option, tracks, matchPredicate) > -1;
  2808. });
  2809. }
  2810. function searchDownAndUpList(arr, searchIndex, predicate) {
  2811. for (let i = searchIndex; i > -1; i--) {
  2812. if (predicate(arr[i])) {
  2813. return i;
  2814. }
  2815. }
  2816. for (let i = searchIndex + 1; i < arr.length; i++) {
  2817. if (predicate(arr[i])) {
  2818. return i;
  2819. }
  2820. }
  2821. return -1;
  2822. }
  2823. function useAlternateAudio(audioTrackUrl, hls) {
  2824. var _hls$loadLevelObj;
  2825. return !!audioTrackUrl && audioTrackUrl !== ((_hls$loadLevelObj = hls.loadLevelObj) == null ? void 0 : _hls$loadLevelObj.uri);
  2826. }
  2827. var AbrController = class extends Logger {
  2828. constructor(_hls) {
  2829. super("abr", _hls.logger);
  2830. this.hls = void 0;
  2831. this.lastLevelLoadSec = 0;
  2832. this.lastLoadedFragLevel = -1;
  2833. this.firstSelection = -1;
  2834. this._nextAutoLevel = -1;
  2835. this.nextAutoLevelKey = "";
  2836. this.audioTracksByGroup = null;
  2837. this.codecTiers = null;
  2838. this.timer = -1;
  2839. this.fragCurrent = null;
  2840. this.partCurrent = null;
  2841. this.bitrateTestDelay = 0;
  2842. this.rebufferNotice = -1;
  2843. this.supportedCache = {};
  2844. this.bwEstimator = void 0;
  2845. this._abandonRulesCheck = (levelLoaded) => {
  2846. var _ref;
  2847. const {
  2848. fragCurrent: frag,
  2849. partCurrent: part,
  2850. hls
  2851. } = this;
  2852. const {
  2853. autoLevelEnabled,
  2854. media
  2855. } = hls;
  2856. if (!frag || !media) {
  2857. return;
  2858. }
  2859. const now2 = performance.now();
  2860. const stats = part ? part.stats : frag.stats;
  2861. const duration = part ? part.duration : frag.duration;
  2862. const timeLoading = now2 - stats.loading.start;
  2863. const minAutoLevel = hls.minAutoLevel;
  2864. const loadingFragForLevel = frag.level;
  2865. const currentAutoLevel = this._nextAutoLevel;
  2866. if (stats.aborted || stats.loaded && stats.loaded === stats.total || loadingFragForLevel <= minAutoLevel) {
  2867. this.clearTimer();
  2868. this._nextAutoLevel = -1;
  2869. return;
  2870. }
  2871. if (!autoLevelEnabled) {
  2872. return;
  2873. }
  2874. const fragBlockingSwitch = currentAutoLevel > -1 && currentAutoLevel !== loadingFragForLevel;
  2875. const levelChange = !!levelLoaded || fragBlockingSwitch;
  2876. if (!levelChange && (media.paused || !media.playbackRate || !media.readyState)) {
  2877. return;
  2878. }
  2879. const bufferInfo = hls.mainForwardBufferInfo;
  2880. if (!levelChange && bufferInfo === null) {
  2881. return;
  2882. }
  2883. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  2884. const playbackRate = Math.abs(media.playbackRate);
  2885. if (timeLoading <= Math.max(ttfbEstimate, 1e3 * (duration / (playbackRate * 2)))) {
  2886. return;
  2887. }
  2888. const bufferStarvationDelay = bufferInfo ? bufferInfo.len / playbackRate : 0;
  2889. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  2890. const loadedFirstByte = stats.loaded && ttfb > -1;
  2891. const bwEstimate = this.getBwEstimate();
  2892. const levels = hls.levels;
  2893. const level = levels[loadingFragForLevel];
  2894. const expectedLen = Math.max(stats.loaded, Math.round(duration * (frag.bitrate || level.averageBitrate) / 8));
  2895. let timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;
  2896. if (timeStreaming < 1 && loadedFirstByte) {
  2897. timeStreaming = Math.min(timeLoading, stats.loaded * 8 / bwEstimate);
  2898. }
  2899. const loadRate = loadedFirstByte ? stats.loaded * 1e3 / timeStreaming : 0;
  2900. const ttfbSeconds = ttfbEstimate / 1e3;
  2901. const fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate + ttfbSeconds;
  2902. if (fragLoadedDelay <= bufferStarvationDelay) {
  2903. return;
  2904. }
  2905. const bwe = loadRate ? loadRate * 8 : bwEstimate;
  2906. const live = ((_ref = (levelLoaded == null ? void 0 : levelLoaded.details) || this.hls.latestLevelDetails) == null ? void 0 : _ref.live) === true;
  2907. const abrBandWidthUpFactor = this.hls.config.abrBandWidthUpFactor;
  2908. let fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
  2909. let nextLoadLevel;
  2910. for (nextLoadLevel = loadingFragForLevel - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  2911. const levelNextBitrate = levels[nextLoadLevel].maxBitrate;
  2912. const requiresLevelLoad = !levels[nextLoadLevel].details || live;
  2913. fragLevelNextLoadedDelay = this.getTimeToLoadFrag(ttfbSeconds, bwe, duration * levelNextBitrate, requiresLevelLoad);
  2914. if (fragLevelNextLoadedDelay < Math.min(bufferStarvationDelay, duration + ttfbSeconds)) {
  2915. break;
  2916. }
  2917. }
  2918. if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
  2919. return;
  2920. }
  2921. if (fragLevelNextLoadedDelay > duration * 10) {
  2922. return;
  2923. }
  2924. if (loadedFirstByte) {
  2925. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  2926. } else {
  2927. this.bwEstimator.sampleTTFB(timeLoading);
  2928. }
  2929. const nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;
  2930. if (this.getBwEstimate() * abrBandWidthUpFactor > nextLoadLevelBitrate) {
  2931. this.resetEstimator(nextLoadLevelBitrate);
  2932. }
  2933. const bestSwitchLevel = this.findBestLevel(nextLoadLevelBitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay, 1, 1);
  2934. if (bestSwitchLevel > -1) {
  2935. nextLoadLevel = bestSwitchLevel;
  2936. }
  2937. this.warn(`Fragment ${frag.sn}${part ? " part " + part.index : ""} of level ${loadingFragForLevel} is loading too slowly;
  2938. Fragment duration: ${frag.duration.toFixed(3)}
  2939. Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s
  2940. Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s
  2941. Estimated load time for down switch fragment: ${fragLevelNextLoadedDelay.toFixed(3)} s
  2942. TTFB estimate: ${ttfb | 0} ms
  2943. Current BW estimate: ${isFiniteNumber(bwEstimate) ? bwEstimate | 0 : "Unknown"} bps
  2944. New BW estimate: ${this.getBwEstimate() | 0} bps
  2945. Switching to level ${nextLoadLevel} @ ${nextLoadLevelBitrate | 0} bps`);
  2946. hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;
  2947. this.clearTimer();
  2948. const abortAndSwitch = () => {
  2949. this.clearTimer();
  2950. if (this.fragCurrent === frag && this.hls.loadLevel === nextLoadLevel && nextLoadLevel > 0) {
  2951. const bufferStarvationDelay2 = this.getStarvationDelay();
  2952. this.warn(`Aborting inflight request ${nextLoadLevel > 0 ? "and switching down" : ""}
  2953. Fragment duration: ${frag.duration.toFixed(3)} s
  2954. Time to underbuffer: ${bufferStarvationDelay2.toFixed(3)} s`);
  2955. frag.abortRequests();
  2956. this.fragCurrent = this.partCurrent = null;
  2957. if (nextLoadLevel > minAutoLevel) {
  2958. let lowestSwitchLevel = this.findBestLevel(this.hls.levels[minAutoLevel].bitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay2, 1, 1);
  2959. if (lowestSwitchLevel === -1) {
  2960. lowestSwitchLevel = minAutoLevel;
  2961. }
  2962. this.hls.nextLoadLevel = this.hls.nextAutoLevel = lowestSwitchLevel;
  2963. this.resetEstimator(this.hls.levels[lowestSwitchLevel].bitrate);
  2964. }
  2965. }
  2966. };
  2967. if (fragBlockingSwitch || fragLoadedDelay > fragLevelNextLoadedDelay * 2) {
  2968. abortAndSwitch();
  2969. } else {
  2970. this.timer = self.setInterval(abortAndSwitch, fragLevelNextLoadedDelay * 1e3);
  2971. }
  2972. hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, {
  2973. frag,
  2974. part,
  2975. stats
  2976. });
  2977. };
  2978. this.hls = _hls;
  2979. this.bwEstimator = this.initEstimator();
  2980. this.registerListeners();
  2981. }
  2982. resetEstimator(abrEwmaDefaultEstimate) {
  2983. if (abrEwmaDefaultEstimate) {
  2984. this.log(`setting initial bwe to ${abrEwmaDefaultEstimate}`);
  2985. this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;
  2986. }
  2987. this.firstSelection = -1;
  2988. this.bwEstimator = this.initEstimator();
  2989. }
  2990. initEstimator() {
  2991. const config = this.hls.config;
  2992. return new EwmaBandWidthEstimator(config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
  2993. }
  2994. registerListeners() {
  2995. const {
  2996. hls
  2997. } = this;
  2998. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  2999. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  3000. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  3001. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  3002. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  3003. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  3004. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  3005. hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  3006. hls.on(Events.ERROR, this.onError, this);
  3007. }
  3008. unregisterListeners() {
  3009. const {
  3010. hls
  3011. } = this;
  3012. if (!hls) {
  3013. return;
  3014. }
  3015. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3016. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  3017. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  3018. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  3019. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  3020. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  3021. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  3022. hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  3023. hls.off(Events.ERROR, this.onError, this);
  3024. }
  3025. destroy() {
  3026. this.unregisterListeners();
  3027. this.clearTimer();
  3028. this.hls = this._abandonRulesCheck = this.supportedCache = null;
  3029. this.fragCurrent = this.partCurrent = null;
  3030. }
  3031. onManifestLoading(event, data) {
  3032. this.lastLoadedFragLevel = -1;
  3033. this.firstSelection = -1;
  3034. this.lastLevelLoadSec = 0;
  3035. this.supportedCache = {};
  3036. this.fragCurrent = this.partCurrent = null;
  3037. this.onLevelsUpdated();
  3038. this.clearTimer();
  3039. }
  3040. onLevelsUpdated() {
  3041. if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {
  3042. this.lastLoadedFragLevel = this.fragCurrent.level;
  3043. }
  3044. this._nextAutoLevel = -1;
  3045. this.onMaxAutoLevelUpdated();
  3046. this.codecTiers = null;
  3047. this.audioTracksByGroup = null;
  3048. }
  3049. onMaxAutoLevelUpdated() {
  3050. this.firstSelection = -1;
  3051. this.nextAutoLevelKey = "";
  3052. }
  3053. onFragLoading(event, data) {
  3054. const frag = data.frag;
  3055. if (this.ignoreFragment(frag)) {
  3056. return;
  3057. }
  3058. if (!frag.bitrateTest) {
  3059. var _data$part;
  3060. this.fragCurrent = frag;
  3061. this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
  3062. }
  3063. this.clearTimer();
  3064. this.timer = self.setInterval(this._abandonRulesCheck, 100);
  3065. }
  3066. onLevelSwitching(event, data) {
  3067. this.clearTimer();
  3068. }
  3069. onError(event, data) {
  3070. if (data.fatal) {
  3071. return;
  3072. }
  3073. switch (data.details) {
  3074. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  3075. case ErrorDetails.BUFFER_APPEND_ERROR:
  3076. this.lastLoadedFragLevel = -1;
  3077. this.firstSelection = -1;
  3078. break;
  3079. case ErrorDetails.FRAG_LOAD_TIMEOUT: {
  3080. const frag = data.frag;
  3081. const {
  3082. fragCurrent,
  3083. partCurrent: part
  3084. } = this;
  3085. if (frag && fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level) {
  3086. const now2 = performance.now();
  3087. const stats = part ? part.stats : frag.stats;
  3088. const timeLoading = now2 - stats.loading.start;
  3089. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  3090. const loadedFirstByte = stats.loaded && ttfb > -1;
  3091. if (loadedFirstByte) {
  3092. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  3093. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  3094. } else {
  3095. this.bwEstimator.sampleTTFB(timeLoading);
  3096. }
  3097. }
  3098. break;
  3099. }
  3100. }
  3101. }
  3102. getTimeToLoadFrag(timeToFirstByteSec, bandwidth, fragSizeBits, isSwitch) {
  3103. const fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;
  3104. const playlistLoadSec = isSwitch ? timeToFirstByteSec + this.lastLevelLoadSec : 0;
  3105. return fragLoadSec + playlistLoadSec;
  3106. }
  3107. onLevelLoaded(event, data) {
  3108. const config = this.hls.config;
  3109. const {
  3110. loading
  3111. } = data.stats;
  3112. const timeLoadingMs = loading.end - loading.first;
  3113. if (isFiniteNumber(timeLoadingMs)) {
  3114. this.lastLevelLoadSec = timeLoadingMs / 1e3;
  3115. }
  3116. if (data.details.live) {
  3117. this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
  3118. } else {
  3119. this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
  3120. }
  3121. if (this.timer > -1) {
  3122. this._abandonRulesCheck(data.levelInfo);
  3123. }
  3124. }
  3125. onFragLoaded(event, {
  3126. frag,
  3127. part
  3128. }) {
  3129. const stats = part ? part.stats : frag.stats;
  3130. if (frag.type === PlaylistLevelType.MAIN) {
  3131. this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);
  3132. }
  3133. if (this.ignoreFragment(frag)) {
  3134. return;
  3135. }
  3136. this.clearTimer();
  3137. if (frag.level === this._nextAutoLevel) {
  3138. this._nextAutoLevel = -1;
  3139. }
  3140. this.firstSelection = -1;
  3141. if (this.hls.config.abrMaxWithRealBitrate) {
  3142. const duration = part ? part.duration : frag.duration;
  3143. const level = this.hls.levels[frag.level];
  3144. const loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
  3145. const loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
  3146. level.loaded = {
  3147. bytes: loadedBytes,
  3148. duration: loadedDuration
  3149. };
  3150. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  3151. }
  3152. if (frag.bitrateTest) {
  3153. const fragBufferedData = {
  3154. stats,
  3155. frag,
  3156. part,
  3157. id: frag.type
  3158. };
  3159. this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);
  3160. frag.bitrateTest = false;
  3161. } else {
  3162. this.lastLoadedFragLevel = frag.level;
  3163. }
  3164. }
  3165. onFragBuffered(event, data) {
  3166. const {
  3167. frag,
  3168. part
  3169. } = data;
  3170. const stats = part != null && part.stats.loaded ? part.stats : frag.stats;
  3171. if (stats.aborted) {
  3172. return;
  3173. }
  3174. if (this.ignoreFragment(frag)) {
  3175. return;
  3176. }
  3177. const processingMs = stats.parsing.end - stats.loading.start - Math.min(stats.loading.first - stats.loading.start, this.bwEstimator.getEstimateTTFB());
  3178. this.bwEstimator.sample(processingMs, stats.loaded);
  3179. stats.bwEstimate = this.getBwEstimate();
  3180. if (frag.bitrateTest) {
  3181. this.bitrateTestDelay = processingMs / 1e3;
  3182. } else {
  3183. this.bitrateTestDelay = 0;
  3184. }
  3185. }
  3186. ignoreFragment(frag) {
  3187. return frag.type !== PlaylistLevelType.MAIN || frag.sn === "initSegment";
  3188. }
  3189. clearTimer() {
  3190. if (this.timer > -1) {
  3191. self.clearInterval(this.timer);
  3192. this.timer = -1;
  3193. }
  3194. }
  3195. get firstAutoLevel() {
  3196. const {
  3197. maxAutoLevel,
  3198. minAutoLevel
  3199. } = this.hls;
  3200. const bwEstimate = this.getBwEstimate();
  3201. const maxStartDelay = this.hls.config.maxStarvationDelay;
  3202. const abrAutoLevel = this.findBestLevel(bwEstimate, minAutoLevel, maxAutoLevel, 0, maxStartDelay, 1, 1);
  3203. if (abrAutoLevel > -1) {
  3204. return abrAutoLevel;
  3205. }
  3206. const firstLevel = this.hls.firstLevel;
  3207. const clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);
  3208. this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${firstLevel} clamped to ${clamped}`);
  3209. return clamped;
  3210. }
  3211. get forcedAutoLevel() {
  3212. if (this.nextAutoLevelKey) {
  3213. return -1;
  3214. }
  3215. return this._nextAutoLevel;
  3216. }
  3217. // return next auto level
  3218. get nextAutoLevel() {
  3219. const forcedAutoLevel = this.forcedAutoLevel;
  3220. const bwEstimator = this.bwEstimator;
  3221. const useEstimate = bwEstimator.canEstimate();
  3222. const loadedFirstFrag = this.lastLoadedFragLevel > -1;
  3223. if (forcedAutoLevel !== -1 && (!useEstimate || !loadedFirstFrag || this.nextAutoLevelKey === this.getAutoLevelKey())) {
  3224. return forcedAutoLevel;
  3225. }
  3226. const nextABRAutoLevel = useEstimate && loadedFirstFrag ? this.getNextABRAutoLevel() : this.firstAutoLevel;
  3227. if (forcedAutoLevel !== -1) {
  3228. const levels = this.hls.levels;
  3229. if (levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) && levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError) {
  3230. return forcedAutoLevel;
  3231. }
  3232. }
  3233. this._nextAutoLevel = nextABRAutoLevel;
  3234. this.nextAutoLevelKey = this.getAutoLevelKey();
  3235. return nextABRAutoLevel;
  3236. }
  3237. getAutoLevelKey() {
  3238. return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`;
  3239. }
  3240. getNextABRAutoLevel() {
  3241. const {
  3242. fragCurrent,
  3243. partCurrent,
  3244. hls
  3245. } = this;
  3246. if (hls.levels.length <= 1) {
  3247. return hls.loadLevel;
  3248. }
  3249. const {
  3250. maxAutoLevel,
  3251. config,
  3252. minAutoLevel
  3253. } = hls;
  3254. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  3255. const avgbw = this.getBwEstimate();
  3256. const bufferStarvationDelay = this.getStarvationDelay();
  3257. let bwFactor = config.abrBandWidthFactor;
  3258. let bwUpFactor = config.abrBandWidthUpFactor;
  3259. if (bufferStarvationDelay) {
  3260. const _bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, 0, bwFactor, bwUpFactor);
  3261. if (_bestLevel >= 0) {
  3262. this.rebufferNotice = -1;
  3263. return _bestLevel;
  3264. }
  3265. }
  3266. let maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
  3267. if (!bufferStarvationDelay) {
  3268. const bitrateTestDelay = this.bitrateTestDelay;
  3269. if (bitrateTestDelay) {
  3270. const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  3271. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  3272. this.info(`bitrate test took ${Math.round(1e3 * bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1e3 * maxStarvationDelay)} ms`);
  3273. bwFactor = bwUpFactor = 1;
  3274. }
  3275. }
  3276. const bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor);
  3277. if (this.rebufferNotice !== bestLevel) {
  3278. this.rebufferNotice = bestLevel;
  3279. this.info(`${bufferStarvationDelay ? "rebuffering expected" : "buffer is empty"}, optimal quality level ${bestLevel}`);
  3280. }
  3281. if (bestLevel > -1) {
  3282. return bestLevel;
  3283. }
  3284. const minLevel = hls.levels[minAutoLevel];
  3285. const autoLevel = hls.loadLevelObj;
  3286. if (autoLevel && (minLevel == null ? void 0 : minLevel.bitrate) < autoLevel.bitrate) {
  3287. return minAutoLevel;
  3288. }
  3289. return hls.loadLevel;
  3290. }
  3291. getStarvationDelay() {
  3292. const hls = this.hls;
  3293. const media = hls.media;
  3294. if (!media) {
  3295. return Infinity;
  3296. }
  3297. const playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1;
  3298. const bufferInfo = hls.mainForwardBufferInfo;
  3299. return (bufferInfo ? bufferInfo.len : 0) / playbackRate;
  3300. }
  3301. getBwEstimate() {
  3302. return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;
  3303. }
  3304. findBestLevel(currentBw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor) {
  3305. var _this$hls$latestLevel;
  3306. const maxFetchDuration = bufferStarvationDelay + maxStarvationDelay;
  3307. const lastLoadedFragLevel = this.lastLoadedFragLevel;
  3308. const selectionBaseLevel = lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;
  3309. const {
  3310. fragCurrent,
  3311. partCurrent
  3312. } = this;
  3313. const {
  3314. levels,
  3315. allAudioTracks,
  3316. loadLevel,
  3317. config
  3318. } = this.hls;
  3319. if (levels.length === 1) {
  3320. return 0;
  3321. }
  3322. const level = levels[selectionBaseLevel];
  3323. const live = !!((_this$hls$latestLevel = this.hls.latestLevelDetails) != null && _this$hls$latestLevel.live);
  3324. const firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;
  3325. let currentCodecSet;
  3326. let currentVideoRange = "SDR";
  3327. let currentFrameRate = (level == null ? void 0 : level.frameRate) || 0;
  3328. const {
  3329. audioPreference,
  3330. videoPreference
  3331. } = config;
  3332. const audioTracksByGroup = this.audioTracksByGroup || (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));
  3333. let minStartIndex = -1;
  3334. if (firstSelection) {
  3335. if (this.firstSelection !== -1) {
  3336. return this.firstSelection;
  3337. }
  3338. const codecTiers = this.codecTiers || (this.codecTiers = getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel));
  3339. const startTier = getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference);
  3340. const {
  3341. codecSet,
  3342. videoRanges,
  3343. minFramerate,
  3344. minBitrate,
  3345. minIndex,
  3346. preferHDR
  3347. } = startTier;
  3348. minStartIndex = minIndex;
  3349. currentCodecSet = codecSet;
  3350. currentVideoRange = preferHDR ? videoRanges[videoRanges.length - 1] : videoRanges[0];
  3351. currentFrameRate = minFramerate;
  3352. currentBw = Math.max(currentBw, minBitrate);
  3353. this.log(`picked start tier ${stringify(startTier)}`);
  3354. } else {
  3355. currentCodecSet = level == null ? void 0 : level.codecSet;
  3356. currentVideoRange = level == null ? void 0 : level.videoRange;
  3357. }
  3358. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  3359. const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1e3;
  3360. const levelsSkipped = [];
  3361. for (let i = maxAutoLevel; i >= minAutoLevel; i--) {
  3362. var _levelInfo$supportedR, _levelInfo$supportedR2;
  3363. const levelInfo = levels[i];
  3364. const upSwitch = i > selectionBaseLevel;
  3365. if (!levelInfo) {
  3366. continue;
  3367. }
  3368. if (config.useMediaCapabilities && !levelInfo.supportedResult && !levelInfo.supportedPromise) {
  3369. const mediaCapabilities = navigator.mediaCapabilities;
  3370. if (typeof (mediaCapabilities == null ? void 0 : mediaCapabilities.decodingInfo) === "function" && requiresMediaCapabilitiesDecodingInfo(levelInfo, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference)) {
  3371. levelInfo.supportedPromise = getMediaDecodingInfoPromise(levelInfo, audioTracksByGroup, mediaCapabilities, this.supportedCache);
  3372. levelInfo.supportedPromise.then((decodingInfo) => {
  3373. if (!this.hls) {
  3374. return;
  3375. }
  3376. levelInfo.supportedResult = decodingInfo;
  3377. const levels2 = this.hls.levels;
  3378. const index = levels2.indexOf(levelInfo);
  3379. if (decodingInfo.error) {
  3380. this.warn(`MediaCapabilities decodingInfo error: "${decodingInfo.error}" for level ${index} ${stringify(decodingInfo)}`);
  3381. } else if (!decodingInfo.supported) {
  3382. this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${index} ${stringify(decodingInfo)}`);
  3383. if (index > -1 && levels2.length > 1) {
  3384. this.log(`Removing unsupported level ${index}`);
  3385. this.hls.removeLevel(index);
  3386. if (this.hls.loadLevel === -1) {
  3387. this.hls.nextLoadLevel = 0;
  3388. }
  3389. }
  3390. } else if (decodingInfo.decodingInfoResults.some((info) => info.smooth === false || info.powerEfficient === false)) {
  3391. this.log(`MediaCapabilities decodingInfo for level ${index} not smooth or powerEfficient: ${stringify(decodingInfo)}`);
  3392. }
  3393. });
  3394. } else {
  3395. levelInfo.supportedResult = SUPPORTED_INFO_DEFAULT;
  3396. }
  3397. }
  3398. if (currentCodecSet && levelInfo.codecSet !== currentCodecSet || currentVideoRange && levelInfo.videoRange !== currentVideoRange || upSwitch && currentFrameRate > levelInfo.frameRate || !upSwitch && currentFrameRate > 0 && currentFrameRate < levelInfo.frameRate || (_levelInfo$supportedR = levelInfo.supportedResult) != null && (_levelInfo$supportedR2 = _levelInfo$supportedR.decodingInfoResults) != null && _levelInfo$supportedR2.some((info) => info.smooth === false)) {
  3399. if (!firstSelection || i !== minStartIndex) {
  3400. levelsSkipped.push(i);
  3401. continue;
  3402. }
  3403. }
  3404. const levelDetails = levelInfo.details;
  3405. const avgDuration = (partCurrent ? levelDetails == null ? void 0 : levelDetails.partTarget : levelDetails == null ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
  3406. let adjustedbw;
  3407. if (!upSwitch) {
  3408. adjustedbw = bwFactor * currentBw;
  3409. } else {
  3410. adjustedbw = bwUpFactor * currentBw;
  3411. }
  3412. const bitrate = currentFragDuration && bufferStarvationDelay >= currentFragDuration * 2 && maxStarvationDelay === 0 ? levelInfo.averageBitrate : levelInfo.maxBitrate;
  3413. const fetchDuration = this.getTimeToLoadFrag(ttfbEstimateSec, adjustedbw, bitrate * avgDuration, levelDetails === void 0);
  3414. const canSwitchWithinTolerance = (
  3415. // if adjusted bw is greater than level bitrate AND
  3416. adjustedbw >= bitrate && // no level change, or new level has no error history
  3417. (i === lastLoadedFragLevel || levelInfo.loadError === 0 && levelInfo.fragmentError === 0) && // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  3418. // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...
  3419. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
  3420. (fetchDuration <= ttfbEstimateSec || !isFiniteNumber(fetchDuration) || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)
  3421. );
  3422. if (canSwitchWithinTolerance) {
  3423. const forcedAutoLevel = this.forcedAutoLevel;
  3424. if (i !== loadLevel && (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)) {
  3425. if (levelsSkipped.length) {
  3426. this.trace(`Skipped level(s) ${levelsSkipped.join(",")} of ${maxAutoLevel} max with CODECS and VIDEO-RANGE:"${levels[levelsSkipped[0]].codecs}" ${levels[levelsSkipped[0]].videoRange}; not compatible with "${currentCodecSet}" ${currentVideoRange}`);
  3427. }
  3428. this.info(`switch candidate:${selectionBaseLevel}->${i} adjustedbw(${Math.round(adjustedbw)})-bitrate=${Math.round(adjustedbw - bitrate)} ttfb:${ttfbEstimateSec.toFixed(1)} avgDuration:${avgDuration.toFixed(1)} maxFetchDuration:${maxFetchDuration.toFixed(1)} fetchDuration:${fetchDuration.toFixed(1)} firstSelection:${firstSelection} codecSet:${levelInfo.codecSet} videoRange:${levelInfo.videoRange} hls.loadLevel:${loadLevel}`);
  3429. }
  3430. if (firstSelection) {
  3431. this.firstSelection = i;
  3432. }
  3433. return i;
  3434. }
  3435. }
  3436. return -1;
  3437. }
  3438. set nextAutoLevel(nextLevel) {
  3439. const value = this.deriveNextAutoLevel(nextLevel);
  3440. if (this._nextAutoLevel !== value) {
  3441. this.nextAutoLevelKey = "";
  3442. this._nextAutoLevel = value;
  3443. }
  3444. }
  3445. deriveNextAutoLevel(nextLevel) {
  3446. const {
  3447. maxAutoLevel,
  3448. minAutoLevel
  3449. } = this.hls;
  3450. return Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);
  3451. }
  3452. };
  3453. var BinarySearch = {
  3454. /**
  3455. * Searches for an item in an array which matches a certain condition.
  3456. * This requires the condition to only match one item in the array,
  3457. * and for the array to be ordered.
  3458. *
  3459. * @param list The array to search.
  3460. * @param comparisonFn
  3461. * Called and provided a candidate item as the first argument.
  3462. * Should return:
  3463. * > -1 if the item should be located at a lower index than the provided item.
  3464. * > 1 if the item should be located at a higher index than the provided item.
  3465. * > 0 if the item is the item you're looking for.
  3466. *
  3467. * @returns the object if found, otherwise returns null
  3468. */
  3469. search: function(list, comparisonFn) {
  3470. let minIndex = 0;
  3471. let maxIndex = list.length - 1;
  3472. let currentIndex = null;
  3473. let currentElement = null;
  3474. while (minIndex <= maxIndex) {
  3475. currentIndex = (minIndex + maxIndex) / 2 | 0;
  3476. currentElement = list[currentIndex];
  3477. const comparisonResult = comparisonFn(currentElement);
  3478. if (comparisonResult > 0) {
  3479. minIndex = currentIndex + 1;
  3480. } else if (comparisonResult < 0) {
  3481. maxIndex = currentIndex - 1;
  3482. } else {
  3483. return currentElement;
  3484. }
  3485. }
  3486. return null;
  3487. }
  3488. };
  3489. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  3490. if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !isFiniteNumber(PDTValue)) {
  3491. return null;
  3492. }
  3493. const startPDT = fragments[0].programDateTime;
  3494. if (PDTValue < (startPDT || 0)) {
  3495. return null;
  3496. }
  3497. const endPDT = fragments[fragments.length - 1].endProgramDateTime;
  3498. if (PDTValue >= (endPDT || 0)) {
  3499. return null;
  3500. }
  3501. for (let seg = 0; seg < fragments.length; ++seg) {
  3502. const frag = fragments[seg];
  3503. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  3504. return frag;
  3505. }
  3506. }
  3507. return null;
  3508. }
  3509. function findFragmentByPTS(fragPrevious, fragments, bufferEnd = 0, maxFragLookUpTolerance = 0, nextFragLookupTolerance = 5e-3) {
  3510. let fragNext = null;
  3511. if (fragPrevious) {
  3512. fragNext = fragments[1 + fragPrevious.sn - fragments[0].sn] || null;
  3513. const bufferEdgeError = fragPrevious.endDTS - bufferEnd;
  3514. if (bufferEdgeError > 0 && bufferEdgeError < 15e-7) {
  3515. bufferEnd += 15e-7;
  3516. }
  3517. if (fragNext && fragPrevious.level !== fragNext.level && fragNext.end <= fragPrevious.end) {
  3518. fragNext = fragments[2 + fragPrevious.sn - fragments[0].sn] || null;
  3519. }
  3520. } else if (bufferEnd === 0 && fragments[0].start === 0) {
  3521. fragNext = fragments[0];
  3522. }
  3523. if (fragNext && ((!fragPrevious || fragPrevious.level === fragNext.level) && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0 || fragmentWithinFastStartSwitch(fragNext, fragPrevious, Math.min(nextFragLookupTolerance, maxFragLookUpTolerance)))) {
  3524. return fragNext;
  3525. }
  3526. const foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  3527. if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {
  3528. return foundFragment;
  3529. }
  3530. return fragNext;
  3531. }
  3532. function fragmentWithinFastStartSwitch(fragNext, fragPrevious, nextFragLookupTolerance) {
  3533. if (fragPrevious && fragPrevious.start === 0 && fragPrevious.level < fragNext.level && (fragPrevious.endPTS || 0) > 0) {
  3534. const firstDuration = fragPrevious.tagList.reduce((duration, tag) => {
  3535. if (tag[0] === "INF") {
  3536. duration += parseFloat(tag[1]);
  3537. }
  3538. return duration;
  3539. }, nextFragLookupTolerance);
  3540. return fragNext.start <= firstDuration;
  3541. }
  3542. return false;
  3543. }
  3544. function fragmentWithinToleranceTest(bufferEnd = 0, maxFragLookUpTolerance = 0, candidate) {
  3545. if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) {
  3546. return 0;
  3547. }
  3548. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  3549. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  3550. return 1;
  3551. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  3552. return -1;
  3553. }
  3554. return 0;
  3555. }
  3556. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  3557. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1e3;
  3558. const endProgramDateTime = candidate.endProgramDateTime || 0;
  3559. return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  3560. }
  3561. function findNearestWithCC(details, cc, pos) {
  3562. if (details) {
  3563. if (details.startCC <= cc && details.endCC >= cc) {
  3564. let fragments = details.fragments;
  3565. const {
  3566. fragmentHint
  3567. } = details;
  3568. if (fragmentHint) {
  3569. fragments = fragments.concat(fragmentHint);
  3570. }
  3571. let closest;
  3572. BinarySearch.search(fragments, (candidate) => {
  3573. if (candidate.cc < cc) {
  3574. return 1;
  3575. }
  3576. if (candidate.cc > cc) {
  3577. return -1;
  3578. }
  3579. closest = candidate;
  3580. if (candidate.end <= pos) {
  3581. return 1;
  3582. }
  3583. if (candidate.start > pos) {
  3584. return -1;
  3585. }
  3586. return 0;
  3587. });
  3588. return closest || null;
  3589. }
  3590. }
  3591. return null;
  3592. }
  3593. function isTimeoutError(error) {
  3594. switch (error.details) {
  3595. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  3596. case ErrorDetails.KEY_LOAD_TIMEOUT:
  3597. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  3598. case ErrorDetails.MANIFEST_LOAD_TIMEOUT:
  3599. return true;
  3600. }
  3601. return false;
  3602. }
  3603. function getRetryConfig(loadPolicy, error) {
  3604. const isTimeout = isTimeoutError(error);
  3605. return loadPolicy.default[`${isTimeout ? "timeout" : "error"}Retry`];
  3606. }
  3607. function getRetryDelay(retryConfig, retryCount) {
  3608. const backoffFactor = retryConfig.backoff === "linear" ? 1 : Math.pow(2, retryCount);
  3609. return Math.min(backoffFactor * retryConfig.retryDelayMs, retryConfig.maxRetryDelayMs);
  3610. }
  3611. function getLoaderConfigWithoutReties(loderConfig) {
  3612. return _objectSpread2(_objectSpread2({}, loderConfig), {
  3613. errorRetry: null,
  3614. timeoutRetry: null
  3615. });
  3616. }
  3617. function shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse) {
  3618. if (!retryConfig) {
  3619. return false;
  3620. }
  3621. const httpStatus = loaderResponse == null ? void 0 : loaderResponse.code;
  3622. const retry = retryCount < retryConfig.maxNumRetry && (retryForHttpStatus(httpStatus) || !!isTimeout);
  3623. return retryConfig.shouldRetry ? retryConfig.shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse, retry) : retry;
  3624. }
  3625. function retryForHttpStatus(httpStatus) {
  3626. return httpStatus === 0 && navigator.onLine === false || !!httpStatus && (httpStatus < 400 || httpStatus > 499);
  3627. }
  3628. var NetworkErrorAction = {
  3629. DoNothing: 0,
  3630. SendEndCallback: 1,
  3631. SendAlternateToPenaltyBox: 2,
  3632. RemoveAlternatePermanently: 3,
  3633. InsertDiscontinuity: 4,
  3634. RetryRequest: 5
  3635. };
  3636. var ErrorActionFlags = {
  3637. None: 0,
  3638. MoveAllAlternatesMatchingHost: 1,
  3639. MoveAllAlternatesMatchingHDCP: 2,
  3640. SwitchToSDR: 4
  3641. };
  3642. var ErrorController = class extends Logger {
  3643. constructor(hls) {
  3644. super("error-controller", hls.logger);
  3645. this.hls = void 0;
  3646. this.playlistError = 0;
  3647. this.penalizedRenditions = {};
  3648. this.hls = hls;
  3649. this.registerListeners();
  3650. }
  3651. registerListeners() {
  3652. const hls = this.hls;
  3653. hls.on(Events.ERROR, this.onError, this);
  3654. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3655. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  3656. }
  3657. unregisterListeners() {
  3658. const hls = this.hls;
  3659. if (!hls) {
  3660. return;
  3661. }
  3662. hls.off(Events.ERROR, this.onError, this);
  3663. hls.off(Events.ERROR, this.onErrorOut, this);
  3664. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3665. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  3666. }
  3667. destroy() {
  3668. this.unregisterListeners();
  3669. this.hls = null;
  3670. this.penalizedRenditions = {};
  3671. }
  3672. startLoad(startPosition) {
  3673. }
  3674. stopLoad() {
  3675. this.playlistError = 0;
  3676. }
  3677. getVariantLevelIndex(frag) {
  3678. return (frag == null ? void 0 : frag.type) === PlaylistLevelType.MAIN ? frag.level : this.hls.loadLevel;
  3679. }
  3680. onManifestLoading() {
  3681. this.playlistError = 0;
  3682. this.penalizedRenditions = {};
  3683. }
  3684. onLevelUpdated() {
  3685. this.playlistError = 0;
  3686. }
  3687. onError(event, data) {
  3688. var _data$frag;
  3689. if (data.fatal) {
  3690. return;
  3691. }
  3692. const hls = this.hls;
  3693. const context = data.context;
  3694. switch (data.details) {
  3695. case ErrorDetails.FRAG_LOAD_ERROR:
  3696. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  3697. case ErrorDetails.KEY_LOAD_ERROR:
  3698. case ErrorDetails.KEY_LOAD_TIMEOUT:
  3699. data.errorAction = this.getFragRetryOrSwitchAction(data);
  3700. return;
  3701. case ErrorDetails.FRAG_PARSING_ERROR:
  3702. if ((_data$frag = data.frag) != null && _data$frag.gap) {
  3703. data.errorAction = createDoNothingErrorAction();
  3704. return;
  3705. }
  3706. case ErrorDetails.FRAG_GAP:
  3707. case ErrorDetails.FRAG_DECRYPT_ERROR: {
  3708. data.errorAction = this.getFragRetryOrSwitchAction(data);
  3709. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  3710. return;
  3711. }
  3712. case ErrorDetails.LEVEL_EMPTY_ERROR:
  3713. case ErrorDetails.LEVEL_PARSING_ERROR:
  3714. {
  3715. var _data$context, _data$context$levelDe;
  3716. const levelIndex = data.parent === PlaylistLevelType.MAIN ? data.level : hls.loadLevel;
  3717. if (data.details === ErrorDetails.LEVEL_EMPTY_ERROR && !!((_data$context = data.context) != null && (_data$context$levelDe = _data$context.levelDetails) != null && _data$context$levelDe.live)) {
  3718. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, levelIndex);
  3719. } else {
  3720. data.levelRetry = false;
  3721. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  3722. }
  3723. }
  3724. return;
  3725. case ErrorDetails.LEVEL_LOAD_ERROR:
  3726. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  3727. if (typeof (context == null ? void 0 : context.level) === "number") {
  3728. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, context.level);
  3729. }
  3730. return;
  3731. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  3732. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  3733. case ErrorDetails.SUBTITLE_LOAD_ERROR:
  3734. case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:
  3735. if (context) {
  3736. const level = hls.loadLevelObj;
  3737. if (level && (context.type === PlaylistContextType.AUDIO_TRACK && level.hasAudioGroup(context.groupId) || context.type === PlaylistContextType.SUBTITLE_TRACK && level.hasSubtitleGroup(context.groupId))) {
  3738. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, hls.loadLevel);
  3739. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  3740. data.errorAction.flags = ErrorActionFlags.MoveAllAlternatesMatchingHost;
  3741. return;
  3742. }
  3743. }
  3744. return;
  3745. case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:
  3746. {
  3747. const level = hls.loadLevelObj;
  3748. const restrictedHdcpLevel = level == null ? void 0 : level.attrs["HDCP-LEVEL"];
  3749. if (restrictedHdcpLevel) {
  3750. data.errorAction = {
  3751. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  3752. flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,
  3753. hdcpLevel: restrictedHdcpLevel
  3754. };
  3755. } else {
  3756. this.keySystemError(data);
  3757. }
  3758. }
  3759. return;
  3760. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  3761. case ErrorDetails.REMUX_ALLOC_ERROR:
  3762. case ErrorDetails.BUFFER_APPEND_ERROR:
  3763. if (!data.errorAction) {
  3764. var _data$level;
  3765. data.errorAction = this.getLevelSwitchAction(data, (_data$level = data.level) != null ? _data$level : hls.loadLevel);
  3766. }
  3767. return;
  3768. case ErrorDetails.INTERNAL_EXCEPTION:
  3769. case ErrorDetails.BUFFER_APPENDING_ERROR:
  3770. case ErrorDetails.BUFFER_FULL_ERROR:
  3771. case ErrorDetails.LEVEL_SWITCH_ERROR:
  3772. case ErrorDetails.BUFFER_STALLED_ERROR:
  3773. case ErrorDetails.BUFFER_SEEK_OVER_HOLE:
  3774. case ErrorDetails.BUFFER_NUDGE_ON_STALL:
  3775. data.errorAction = createDoNothingErrorAction();
  3776. return;
  3777. }
  3778. if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {
  3779. this.keySystemError(data);
  3780. }
  3781. }
  3782. keySystemError(data) {
  3783. const levelIndex = this.getVariantLevelIndex(data.frag);
  3784. data.levelRetry = false;
  3785. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  3786. }
  3787. getPlaylistRetryOrSwitchAction(data, levelIndex) {
  3788. const hls = this.hls;
  3789. const retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);
  3790. const retryCount = this.playlistError++;
  3791. const retry = shouldRetry(retryConfig, retryCount, isTimeoutError(data), data.response);
  3792. if (retry) {
  3793. return {
  3794. action: NetworkErrorAction.RetryRequest,
  3795. flags: ErrorActionFlags.None,
  3796. retryConfig,
  3797. retryCount
  3798. };
  3799. }
  3800. const errorAction = this.getLevelSwitchAction(data, levelIndex);
  3801. if (retryConfig) {
  3802. errorAction.retryConfig = retryConfig;
  3803. errorAction.retryCount = retryCount;
  3804. }
  3805. return errorAction;
  3806. }
  3807. getFragRetryOrSwitchAction(data) {
  3808. const hls = this.hls;
  3809. const variantLevelIndex = this.getVariantLevelIndex(data.frag);
  3810. const level = hls.levels[variantLevelIndex];
  3811. const {
  3812. fragLoadPolicy,
  3813. keyLoadPolicy
  3814. } = hls.config;
  3815. const retryConfig = getRetryConfig(data.details.startsWith("key") ? keyLoadPolicy : fragLoadPolicy, data);
  3816. const fragmentErrors = hls.levels.reduce((acc, level2) => acc + level2.fragmentError, 0);
  3817. if (level) {
  3818. if (data.details !== ErrorDetails.FRAG_GAP) {
  3819. level.fragmentError++;
  3820. }
  3821. const retry = shouldRetry(retryConfig, fragmentErrors, isTimeoutError(data), data.response);
  3822. if (retry) {
  3823. return {
  3824. action: NetworkErrorAction.RetryRequest,
  3825. flags: ErrorActionFlags.None,
  3826. retryConfig,
  3827. retryCount: fragmentErrors
  3828. };
  3829. }
  3830. }
  3831. const errorAction = this.getLevelSwitchAction(data, variantLevelIndex);
  3832. if (retryConfig) {
  3833. errorAction.retryConfig = retryConfig;
  3834. errorAction.retryCount = fragmentErrors;
  3835. }
  3836. return errorAction;
  3837. }
  3838. getLevelSwitchAction(data, levelIndex) {
  3839. const hls = this.hls;
  3840. if (levelIndex === null || levelIndex === void 0) {
  3841. levelIndex = hls.loadLevel;
  3842. }
  3843. const level = this.hls.levels[levelIndex];
  3844. if (level) {
  3845. var _data$frag2, _data$context2;
  3846. const errorDetails = data.details;
  3847. level.loadError++;
  3848. if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {
  3849. level.fragmentError++;
  3850. }
  3851. let nextLevel = -1;
  3852. const {
  3853. levels,
  3854. loadLevel,
  3855. minAutoLevel,
  3856. maxAutoLevel
  3857. } = hls;
  3858. if (!hls.autoLevelEnabled && !hls.config.preserveManualLevelOnError) {
  3859. hls.loadLevel = -1;
  3860. }
  3861. const fragErrorType = (_data$frag2 = data.frag) == null ? void 0 : _data$frag2.type;
  3862. const isAudioCodecError = fragErrorType === PlaylistLevelType.AUDIO && errorDetails === ErrorDetails.FRAG_PARSING_ERROR || data.sourceBufferName === "audio" && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  3863. const findAudioCodecAlternate = isAudioCodecError && levels.some(({
  3864. audioCodec
  3865. }) => level.audioCodec !== audioCodec);
  3866. const isVideoCodecError = data.sourceBufferName === "video" && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  3867. const findVideoCodecAlternate = isVideoCodecError && levels.some(({
  3868. codecSet,
  3869. audioCodec
  3870. }) => level.codecSet !== codecSet && level.audioCodec === audioCodec);
  3871. const {
  3872. type: playlistErrorType,
  3873. groupId: playlistErrorGroupId
  3874. } = (_data$context2 = data.context) != null ? _data$context2 : {};
  3875. for (let i = levels.length; i--; ) {
  3876. const candidate = (i + loadLevel) % levels.length;
  3877. if (candidate !== loadLevel && candidate >= minAutoLevel && candidate <= maxAutoLevel && levels[candidate].loadError === 0) {
  3878. var _level$audioGroups, _level$subtitleGroups;
  3879. const levelCandidate = levels[candidate];
  3880. if (errorDetails === ErrorDetails.FRAG_GAP && fragErrorType === PlaylistLevelType.MAIN && data.frag) {
  3881. const levelDetails = levels[candidate].details;
  3882. if (levelDetails) {
  3883. const fragCandidate = findFragmentByPTS(data.frag, levelDetails.fragments, data.frag.start);
  3884. if (fragCandidate != null && fragCandidate.gap) {
  3885. continue;
  3886. }
  3887. }
  3888. } else if (playlistErrorType === PlaylistContextType.AUDIO_TRACK && levelCandidate.hasAudioGroup(playlistErrorGroupId) || playlistErrorType === PlaylistContextType.SUBTITLE_TRACK && levelCandidate.hasSubtitleGroup(playlistErrorGroupId)) {
  3889. continue;
  3890. } else if (fragErrorType === PlaylistLevelType.AUDIO && (_level$audioGroups = level.audioGroups) != null && _level$audioGroups.some((groupId) => levelCandidate.hasAudioGroup(groupId)) || fragErrorType === PlaylistLevelType.SUBTITLE && (_level$subtitleGroups = level.subtitleGroups) != null && _level$subtitleGroups.some((groupId) => levelCandidate.hasSubtitleGroup(groupId)) || findAudioCodecAlternate && level.audioCodec === levelCandidate.audioCodec || !findAudioCodecAlternate && level.audioCodec !== levelCandidate.audioCodec || findVideoCodecAlternate && level.codecSet === levelCandidate.codecSet) {
  3891. continue;
  3892. }
  3893. nextLevel = candidate;
  3894. break;
  3895. }
  3896. }
  3897. if (nextLevel > -1 && hls.loadLevel !== nextLevel) {
  3898. data.levelRetry = true;
  3899. this.playlistError = 0;
  3900. return {
  3901. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  3902. flags: ErrorActionFlags.None,
  3903. nextAutoLevel: nextLevel
  3904. };
  3905. }
  3906. }
  3907. return {
  3908. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  3909. flags: ErrorActionFlags.MoveAllAlternatesMatchingHost
  3910. };
  3911. }
  3912. onErrorOut(event, data) {
  3913. var _data$errorAction;
  3914. switch ((_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.action) {
  3915. case NetworkErrorAction.DoNothing:
  3916. break;
  3917. case NetworkErrorAction.SendAlternateToPenaltyBox:
  3918. this.sendAlternateToPenaltyBox(data);
  3919. if (!data.errorAction.resolved && data.details !== ErrorDetails.FRAG_GAP) {
  3920. data.fatal = true;
  3921. } else if (/MediaSource readyState: ended/.test(data.error.message)) {
  3922. this.warn(`MediaSource ended after "${data.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`);
  3923. this.hls.recoverMediaError();
  3924. }
  3925. break;
  3926. case NetworkErrorAction.RetryRequest:
  3927. break;
  3928. }
  3929. if (data.fatal) {
  3930. this.hls.stopLoad();
  3931. return;
  3932. }
  3933. }
  3934. sendAlternateToPenaltyBox(data) {
  3935. const hls = this.hls;
  3936. const errorAction = data.errorAction;
  3937. if (!errorAction) {
  3938. return;
  3939. }
  3940. const {
  3941. flags,
  3942. hdcpLevel,
  3943. nextAutoLevel
  3944. } = errorAction;
  3945. switch (flags) {
  3946. case ErrorActionFlags.None:
  3947. this.switchLevel(data, nextAutoLevel);
  3948. break;
  3949. case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:
  3950. if (hdcpLevel) {
  3951. hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];
  3952. errorAction.resolved = true;
  3953. }
  3954. this.warn(`Restricting playback to HDCP-LEVEL of "${hls.maxHdcpLevel}" or lower`);
  3955. break;
  3956. }
  3957. if (!errorAction.resolved) {
  3958. this.switchLevel(data, nextAutoLevel);
  3959. }
  3960. }
  3961. switchLevel(data, levelIndex) {
  3962. if (levelIndex !== void 0 && data.errorAction) {
  3963. this.warn(`switching to level ${levelIndex} after ${data.details}`);
  3964. this.hls.nextAutoLevel = levelIndex;
  3965. data.errorAction.resolved = true;
  3966. this.hls.nextLoadLevel = this.hls.nextAutoLevel;
  3967. if (data.details === ErrorDetails.BUFFER_ADD_CODEC_ERROR && data.mimeType && data.sourceBufferName !== "audiovideo") {
  3968. const codec = getCodecsForMimeType(data.mimeType);
  3969. const levels = this.hls.levels;
  3970. for (let i = levels.length; i--; ) {
  3971. if (levels[i][`${data.sourceBufferName}Codec`] === codec) {
  3972. this.hls.removeLevel(i);
  3973. }
  3974. }
  3975. }
  3976. }
  3977. }
  3978. };
  3979. function createDoNothingErrorAction(resolved) {
  3980. const errorAction = {
  3981. action: NetworkErrorAction.DoNothing,
  3982. flags: ErrorActionFlags.None
  3983. };
  3984. if (resolved) {
  3985. errorAction.resolved = true;
  3986. }
  3987. return errorAction;
  3988. }
  3989. var FragmentState = {
  3990. NOT_LOADED: "NOT_LOADED",
  3991. APPENDING: "APPENDING",
  3992. PARTIAL: "PARTIAL",
  3993. OK: "OK"
  3994. };
  3995. var FragmentTracker = class {
  3996. constructor(hls) {
  3997. this.activePartLists = /* @__PURE__ */ Object.create(null);
  3998. this.endListFragments = /* @__PURE__ */ Object.create(null);
  3999. this.fragments = /* @__PURE__ */ Object.create(null);
  4000. this.timeRanges = /* @__PURE__ */ Object.create(null);
  4001. this.bufferPadding = 0.2;
  4002. this.hls = void 0;
  4003. this.hasGaps = false;
  4004. this.hls = hls;
  4005. this._registerListeners();
  4006. }
  4007. _registerListeners() {
  4008. const {
  4009. hls
  4010. } = this;
  4011. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4012. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  4013. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  4014. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  4015. }
  4016. _unregisterListeners() {
  4017. const {
  4018. hls
  4019. } = this;
  4020. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4021. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  4022. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  4023. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  4024. }
  4025. destroy() {
  4026. this._unregisterListeners();
  4027. this.fragments = // @ts-ignore
  4028. this.activePartLists = // @ts-ignore
  4029. this.endListFragments = this.timeRanges = null;
  4030. }
  4031. /**
  4032. * Return a Fragment or Part with an appended range that matches the position and levelType
  4033. * Otherwise, return null
  4034. */
  4035. getAppendedFrag(position, levelType) {
  4036. const activeParts = this.activePartLists[levelType];
  4037. if (activeParts) {
  4038. for (let i = activeParts.length; i--; ) {
  4039. const activePart = activeParts[i];
  4040. if (!activePart) {
  4041. break;
  4042. }
  4043. const appendedPTS = activePart.end;
  4044. if (activePart.start <= position && appendedPTS !== null && position <= appendedPTS) {
  4045. return activePart;
  4046. }
  4047. }
  4048. }
  4049. return this.getBufferedFrag(position, levelType);
  4050. }
  4051. /**
  4052. * Return a buffered Fragment that matches the position and levelType.
  4053. * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
  4054. * If not found any Fragment, return null
  4055. */
  4056. getBufferedFrag(position, levelType) {
  4057. return this.getFragAtPos(position, levelType, true);
  4058. }
  4059. getFragAtPos(position, levelType, buffered) {
  4060. const {
  4061. fragments
  4062. } = this;
  4063. const keys = Object.keys(fragments);
  4064. for (let i = keys.length; i--; ) {
  4065. const fragmentEntity = fragments[keys[i]];
  4066. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === levelType && (!buffered || fragmentEntity.buffered)) {
  4067. const frag = fragmentEntity.body;
  4068. if (frag.start <= position && position <= frag.end) {
  4069. return frag;
  4070. }
  4071. }
  4072. }
  4073. return null;
  4074. }
  4075. /**
  4076. * Partial fragments effected by coded frame eviction will be removed
  4077. * The browser will unload parts of the buffer to free up memory for new buffer data
  4078. * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)
  4079. */
  4080. detectEvictedFragments(elementaryStream, timeRange, playlistType, appendedPart, removeAppending) {
  4081. if (this.timeRanges) {
  4082. this.timeRanges[elementaryStream] = timeRange;
  4083. }
  4084. const appendedPartSn = (appendedPart == null ? void 0 : appendedPart.fragment.sn) || -1;
  4085. Object.keys(this.fragments).forEach((key) => {
  4086. const fragmentEntity = this.fragments[key];
  4087. if (!fragmentEntity) {
  4088. return;
  4089. }
  4090. if (appendedPartSn >= fragmentEntity.body.sn) {
  4091. return;
  4092. }
  4093. if (!fragmentEntity.buffered && (!fragmentEntity.loaded || removeAppending)) {
  4094. if (fragmentEntity.body.type === playlistType) {
  4095. this.removeFragment(fragmentEntity.body);
  4096. }
  4097. return;
  4098. }
  4099. const esData = fragmentEntity.range[elementaryStream];
  4100. if (!esData) {
  4101. return;
  4102. }
  4103. if (esData.time.length === 0) {
  4104. this.removeFragment(fragmentEntity.body);
  4105. return;
  4106. }
  4107. esData.time.some((time) => {
  4108. const isNotBuffered = !this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
  4109. if (isNotBuffered) {
  4110. this.removeFragment(fragmentEntity.body);
  4111. }
  4112. return isNotBuffered;
  4113. });
  4114. });
  4115. }
  4116. /**
  4117. * Checks if the fragment passed in is loaded in the buffer properly
  4118. * Partially loaded fragments will be registered as a partial fragment
  4119. */
  4120. detectPartialFragments(data) {
  4121. const timeRanges = this.timeRanges;
  4122. if (!timeRanges || data.frag.sn === "initSegment") {
  4123. return;
  4124. }
  4125. const frag = data.frag;
  4126. const fragKey = getFragmentKey(frag);
  4127. const fragmentEntity = this.fragments[fragKey];
  4128. if (!fragmentEntity || fragmentEntity.buffered && frag.gap) {
  4129. return;
  4130. }
  4131. const isFragHint = !frag.relurl;
  4132. Object.keys(timeRanges).forEach((elementaryStream) => {
  4133. const streamInfo = frag.elementaryStreams[elementaryStream];
  4134. if (!streamInfo) {
  4135. return;
  4136. }
  4137. const timeRange = timeRanges[elementaryStream];
  4138. const partial = isFragHint || streamInfo.partial === true;
  4139. fragmentEntity.range[elementaryStream] = this.getBufferedTimes(frag, data.part, partial, timeRange);
  4140. });
  4141. fragmentEntity.loaded = null;
  4142. if (Object.keys(fragmentEntity.range).length) {
  4143. fragmentEntity.buffered = true;
  4144. const endList = fragmentEntity.body.endList = frag.endList || fragmentEntity.body.endList;
  4145. if (endList) {
  4146. this.endListFragments[fragmentEntity.body.type] = fragmentEntity;
  4147. }
  4148. if (!isPartial(fragmentEntity)) {
  4149. this.removeParts(frag.sn - 1, frag.type);
  4150. }
  4151. } else {
  4152. this.removeFragment(fragmentEntity.body);
  4153. }
  4154. }
  4155. removeParts(snToKeep, levelType) {
  4156. const activeParts = this.activePartLists[levelType];
  4157. if (!activeParts) {
  4158. return;
  4159. }
  4160. this.activePartLists[levelType] = filterParts(activeParts, (part) => part.fragment.sn >= snToKeep);
  4161. }
  4162. fragBuffered(frag, force) {
  4163. const fragKey = getFragmentKey(frag);
  4164. let fragmentEntity = this.fragments[fragKey];
  4165. if (!fragmentEntity && force) {
  4166. fragmentEntity = this.fragments[fragKey] = {
  4167. body: frag,
  4168. appendedPTS: null,
  4169. loaded: null,
  4170. buffered: false,
  4171. range: /* @__PURE__ */ Object.create(null)
  4172. };
  4173. if (frag.gap) {
  4174. this.hasGaps = true;
  4175. }
  4176. }
  4177. if (fragmentEntity) {
  4178. fragmentEntity.loaded = null;
  4179. fragmentEntity.buffered = true;
  4180. }
  4181. }
  4182. getBufferedTimes(fragment, part, partial, timeRange) {
  4183. const buffered = {
  4184. time: [],
  4185. partial
  4186. };
  4187. const startPTS = fragment.start;
  4188. const endPTS = fragment.end;
  4189. const minEndPTS = fragment.minEndPTS || endPTS;
  4190. const maxStartPTS = fragment.maxStartPTS || startPTS;
  4191. for (let i = 0; i < timeRange.length; i++) {
  4192. const startTime = timeRange.start(i) - this.bufferPadding;
  4193. const endTime = timeRange.end(i) + this.bufferPadding;
  4194. if (maxStartPTS >= startTime && minEndPTS <= endTime) {
  4195. buffered.time.push({
  4196. startPTS: Math.max(startPTS, timeRange.start(i)),
  4197. endPTS: Math.min(endPTS, timeRange.end(i))
  4198. });
  4199. break;
  4200. } else if (startPTS < endTime && endPTS > startTime) {
  4201. const start = Math.max(startPTS, timeRange.start(i));
  4202. const end = Math.min(endPTS, timeRange.end(i));
  4203. if (end > start) {
  4204. buffered.partial = true;
  4205. buffered.time.push({
  4206. startPTS: start,
  4207. endPTS: end
  4208. });
  4209. }
  4210. } else if (endPTS <= startTime) {
  4211. break;
  4212. }
  4213. }
  4214. return buffered;
  4215. }
  4216. /**
  4217. * Gets the partial fragment for a certain time
  4218. */
  4219. getPartialFragment(time) {
  4220. let bestFragment = null;
  4221. let timePadding;
  4222. let startTime;
  4223. let endTime;
  4224. let bestOverlap = 0;
  4225. const {
  4226. bufferPadding,
  4227. fragments
  4228. } = this;
  4229. Object.keys(fragments).forEach((key) => {
  4230. const fragmentEntity = fragments[key];
  4231. if (!fragmentEntity) {
  4232. return;
  4233. }
  4234. if (isPartial(fragmentEntity)) {
  4235. startTime = fragmentEntity.body.start - bufferPadding;
  4236. endTime = fragmentEntity.body.end + bufferPadding;
  4237. if (time >= startTime && time <= endTime) {
  4238. timePadding = Math.min(time - startTime, endTime - time);
  4239. if (bestOverlap <= timePadding) {
  4240. bestFragment = fragmentEntity.body;
  4241. bestOverlap = timePadding;
  4242. }
  4243. }
  4244. }
  4245. });
  4246. return bestFragment;
  4247. }
  4248. isEndListAppended(type) {
  4249. const lastFragmentEntity = this.endListFragments[type];
  4250. return lastFragmentEntity !== void 0 && (lastFragmentEntity.buffered || isPartial(lastFragmentEntity));
  4251. }
  4252. getState(fragment) {
  4253. const fragKey = getFragmentKey(fragment);
  4254. const fragmentEntity = this.fragments[fragKey];
  4255. if (fragmentEntity) {
  4256. if (!fragmentEntity.buffered) {
  4257. return FragmentState.APPENDING;
  4258. } else if (isPartial(fragmentEntity)) {
  4259. return FragmentState.PARTIAL;
  4260. } else {
  4261. return FragmentState.OK;
  4262. }
  4263. }
  4264. return FragmentState.NOT_LOADED;
  4265. }
  4266. isTimeBuffered(startPTS, endPTS, timeRange) {
  4267. let startTime;
  4268. let endTime;
  4269. for (let i = 0; i < timeRange.length; i++) {
  4270. startTime = timeRange.start(i) - this.bufferPadding;
  4271. endTime = timeRange.end(i) + this.bufferPadding;
  4272. if (startPTS >= startTime && endPTS <= endTime) {
  4273. return true;
  4274. }
  4275. if (endPTS <= startTime) {
  4276. return false;
  4277. }
  4278. }
  4279. return false;
  4280. }
  4281. onManifestLoading() {
  4282. this.removeAllFragments();
  4283. }
  4284. onFragLoaded(event, data) {
  4285. if (data.frag.sn === "initSegment" || data.frag.bitrateTest) {
  4286. return;
  4287. }
  4288. const frag = data.frag;
  4289. const loaded = data.part ? null : data;
  4290. const fragKey = getFragmentKey(frag);
  4291. this.fragments[fragKey] = {
  4292. body: frag,
  4293. appendedPTS: null,
  4294. loaded,
  4295. buffered: false,
  4296. range: /* @__PURE__ */ Object.create(null)
  4297. };
  4298. }
  4299. onBufferAppended(event, data) {
  4300. const {
  4301. frag,
  4302. part,
  4303. timeRanges,
  4304. type
  4305. } = data;
  4306. if (frag.sn === "initSegment") {
  4307. return;
  4308. }
  4309. const playlistType = frag.type;
  4310. if (part) {
  4311. let activeParts = this.activePartLists[playlistType];
  4312. if (!activeParts) {
  4313. this.activePartLists[playlistType] = activeParts = [];
  4314. }
  4315. activeParts.push(part);
  4316. }
  4317. this.timeRanges = timeRanges;
  4318. const timeRange = timeRanges[type];
  4319. this.detectEvictedFragments(type, timeRange, playlistType, part);
  4320. }
  4321. onFragBuffered(event, data) {
  4322. this.detectPartialFragments(data);
  4323. }
  4324. hasFragment(fragment) {
  4325. const fragKey = getFragmentKey(fragment);
  4326. return !!this.fragments[fragKey];
  4327. }
  4328. hasFragments(type) {
  4329. const {
  4330. fragments
  4331. } = this;
  4332. const keys = Object.keys(fragments);
  4333. if (!type) {
  4334. return keys.length > 0;
  4335. }
  4336. for (let i = keys.length; i--; ) {
  4337. const fragmentEntity = fragments[keys[i]];
  4338. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === type) {
  4339. return true;
  4340. }
  4341. }
  4342. return false;
  4343. }
  4344. hasParts(type) {
  4345. var _this$activePartLists;
  4346. return !!((_this$activePartLists = this.activePartLists[type]) != null && _this$activePartLists.length);
  4347. }
  4348. removeFragmentsInRange(start, end, playlistType, withGapOnly, unbufferedOnly) {
  4349. if (withGapOnly && !this.hasGaps) {
  4350. return;
  4351. }
  4352. Object.keys(this.fragments).forEach((key) => {
  4353. const fragmentEntity = this.fragments[key];
  4354. if (!fragmentEntity) {
  4355. return;
  4356. }
  4357. const frag = fragmentEntity.body;
  4358. if (frag.type !== playlistType || withGapOnly && !frag.gap) {
  4359. return;
  4360. }
  4361. if (frag.start < end && frag.end > start && (fragmentEntity.buffered || unbufferedOnly)) {
  4362. this.removeFragment(frag);
  4363. }
  4364. });
  4365. }
  4366. removeFragment(fragment) {
  4367. const fragKey = getFragmentKey(fragment);
  4368. fragment.clearElementaryStreamInfo();
  4369. const activeParts = this.activePartLists[fragment.type];
  4370. if (activeParts) {
  4371. const snToRemove = fragment.sn;
  4372. this.activePartLists[fragment.type] = filterParts(activeParts, (part) => part.fragment.sn !== snToRemove);
  4373. }
  4374. delete this.fragments[fragKey];
  4375. if (fragment.endList) {
  4376. delete this.endListFragments[fragment.type];
  4377. }
  4378. }
  4379. removeAllFragments() {
  4380. var _this$hls, _this$hls$latestLevel;
  4381. this.fragments = /* @__PURE__ */ Object.create(null);
  4382. this.endListFragments = /* @__PURE__ */ Object.create(null);
  4383. this.activePartLists = /* @__PURE__ */ Object.create(null);
  4384. this.hasGaps = false;
  4385. const partlist = (_this$hls = this.hls) == null ? void 0 : (_this$hls$latestLevel = _this$hls.latestLevelDetails) == null ? void 0 : _this$hls$latestLevel.partList;
  4386. if (partlist) {
  4387. partlist.forEach((part) => part.clearElementaryStreamInfo());
  4388. }
  4389. }
  4390. };
  4391. function isPartial(fragmentEntity) {
  4392. var _fragmentEntity$range, _fragmentEntity$range2, _fragmentEntity$range3;
  4393. return fragmentEntity.buffered && (fragmentEntity.body.gap || ((_fragmentEntity$range = fragmentEntity.range.video) == null ? void 0 : _fragmentEntity$range.partial) || ((_fragmentEntity$range2 = fragmentEntity.range.audio) == null ? void 0 : _fragmentEntity$range2.partial) || ((_fragmentEntity$range3 = fragmentEntity.range.audiovideo) == null ? void 0 : _fragmentEntity$range3.partial));
  4394. }
  4395. function getFragmentKey(fragment) {
  4396. return `${fragment.type}_${fragment.level}_${fragment.sn}`;
  4397. }
  4398. function filterParts(partList, predicate) {
  4399. return partList.filter((part) => {
  4400. const keep = predicate(part);
  4401. if (!keep) {
  4402. part.clearElementaryStreamInfo();
  4403. }
  4404. return keep;
  4405. });
  4406. }
  4407. var DecrypterAesMode = {
  4408. cbc: 0,
  4409. ctr: 1
  4410. };
  4411. var AESCrypto = class {
  4412. constructor(subtle, iv, aesMode) {
  4413. this.subtle = void 0;
  4414. this.aesIV = void 0;
  4415. this.aesMode = void 0;
  4416. this.subtle = subtle;
  4417. this.aesIV = iv;
  4418. this.aesMode = aesMode;
  4419. }
  4420. decrypt(data, key) {
  4421. switch (this.aesMode) {
  4422. case DecrypterAesMode.cbc:
  4423. return this.subtle.decrypt({
  4424. name: "AES-CBC",
  4425. iv: this.aesIV
  4426. }, key, data);
  4427. case DecrypterAesMode.ctr:
  4428. return this.subtle.decrypt(
  4429. {
  4430. name: "AES-CTR",
  4431. counter: this.aesIV,
  4432. length: 64
  4433. },
  4434. //64 : NIST SP800-38A standard suggests that the counter should occupy half of the counter block
  4435. key,
  4436. data
  4437. );
  4438. default:
  4439. throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`);
  4440. }
  4441. }
  4442. };
  4443. function removePadding(array) {
  4444. const outputBytes = array.byteLength;
  4445. const paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
  4446. if (paddingBytes) {
  4447. return array.slice(0, outputBytes - paddingBytes);
  4448. }
  4449. return array;
  4450. }
  4451. var AESDecryptor = class {
  4452. constructor() {
  4453. this.rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54];
  4454. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  4455. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  4456. this.sBox = new Uint32Array(256);
  4457. this.invSBox = new Uint32Array(256);
  4458. this.key = new Uint32Array(0);
  4459. this.ksRows = 0;
  4460. this.keySize = 0;
  4461. this.keySchedule = void 0;
  4462. this.invKeySchedule = void 0;
  4463. this.initTable();
  4464. }
  4465. // Using view.getUint32() also swaps the byte order.
  4466. uint8ArrayToUint32Array_(arrayBuffer) {
  4467. const view2 = new DataView(arrayBuffer);
  4468. const newArray = new Uint32Array(4);
  4469. for (let i = 0; i < 4; i++) {
  4470. newArray[i] = view2.getUint32(i * 4);
  4471. }
  4472. return newArray;
  4473. }
  4474. initTable() {
  4475. const sBox = this.sBox;
  4476. const invSBox = this.invSBox;
  4477. const subMix = this.subMix;
  4478. const subMix0 = subMix[0];
  4479. const subMix1 = subMix[1];
  4480. const subMix2 = subMix[2];
  4481. const subMix3 = subMix[3];
  4482. const invSubMix = this.invSubMix;
  4483. const invSubMix0 = invSubMix[0];
  4484. const invSubMix1 = invSubMix[1];
  4485. const invSubMix2 = invSubMix[2];
  4486. const invSubMix3 = invSubMix[3];
  4487. const d = new Uint32Array(256);
  4488. let x = 0;
  4489. let xi = 0;
  4490. let i = 0;
  4491. for (i = 0; i < 256; i++) {
  4492. if (i < 128) {
  4493. d[i] = i << 1;
  4494. } else {
  4495. d[i] = i << 1 ^ 283;
  4496. }
  4497. }
  4498. for (i = 0; i < 256; i++) {
  4499. let sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  4500. sx = sx >>> 8 ^ sx & 255 ^ 99;
  4501. sBox[x] = sx;
  4502. invSBox[sx] = x;
  4503. const x2 = d[x];
  4504. const x4 = d[x2];
  4505. const x8 = d[x4];
  4506. let t = d[sx] * 257 ^ sx * 16843008;
  4507. subMix0[x] = t << 24 | t >>> 8;
  4508. subMix1[x] = t << 16 | t >>> 16;
  4509. subMix2[x] = t << 8 | t >>> 24;
  4510. subMix3[x] = t;
  4511. t = x8 * 16843009 ^ x4 * 65537 ^ x2 * 257 ^ x * 16843008;
  4512. invSubMix0[sx] = t << 24 | t >>> 8;
  4513. invSubMix1[sx] = t << 16 | t >>> 16;
  4514. invSubMix2[sx] = t << 8 | t >>> 24;
  4515. invSubMix3[sx] = t;
  4516. if (!x) {
  4517. x = xi = 1;
  4518. } else {
  4519. x = x2 ^ d[d[d[x8 ^ x2]]];
  4520. xi ^= d[d[xi]];
  4521. }
  4522. }
  4523. }
  4524. expandKey(keyBuffer) {
  4525. const key = this.uint8ArrayToUint32Array_(keyBuffer);
  4526. let sameKey = true;
  4527. let offset = 0;
  4528. while (offset < key.length && sameKey) {
  4529. sameKey = key[offset] === this.key[offset];
  4530. offset++;
  4531. }
  4532. if (sameKey) {
  4533. return;
  4534. }
  4535. this.key = key;
  4536. const keySize = this.keySize = key.length;
  4537. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  4538. throw new Error("Invalid aes key size=" + keySize);
  4539. }
  4540. const ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  4541. let ksRow;
  4542. let invKsRow;
  4543. const keySchedule = this.keySchedule = new Uint32Array(ksRows);
  4544. const invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  4545. const sbox = this.sBox;
  4546. const rcon = this.rcon;
  4547. const invSubMix = this.invSubMix;
  4548. const invSubMix0 = invSubMix[0];
  4549. const invSubMix1 = invSubMix[1];
  4550. const invSubMix2 = invSubMix[2];
  4551. const invSubMix3 = invSubMix[3];
  4552. let prev;
  4553. let t;
  4554. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  4555. if (ksRow < keySize) {
  4556. prev = keySchedule[ksRow] = key[ksRow];
  4557. continue;
  4558. }
  4559. t = prev;
  4560. if (ksRow % keySize === 0) {
  4561. t = t << 8 | t >>> 24;
  4562. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 255] << 16 | sbox[t >>> 8 & 255] << 8 | sbox[t & 255];
  4563. t ^= rcon[ksRow / keySize | 0] << 24;
  4564. } else if (keySize > 6 && ksRow % keySize === 4) {
  4565. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 255] << 16 | sbox[t >>> 8 & 255] << 8 | sbox[t & 255];
  4566. }
  4567. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  4568. }
  4569. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  4570. ksRow = ksRows - invKsRow;
  4571. if (invKsRow & 3) {
  4572. t = keySchedule[ksRow];
  4573. } else {
  4574. t = keySchedule[ksRow - 4];
  4575. }
  4576. if (invKsRow < 4 || ksRow <= 4) {
  4577. invKeySchedule[invKsRow] = t;
  4578. } else {
  4579. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 255]] ^ invSubMix2[sbox[t >>> 8 & 255]] ^ invSubMix3[sbox[t & 255]];
  4580. }
  4581. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  4582. }
  4583. }
  4584. // Adding this as a method greatly improves performance.
  4585. networkToHostOrderSwap(word) {
  4586. return word << 24 | (word & 65280) << 8 | (word & 16711680) >> 8 | word >>> 24;
  4587. }
  4588. decrypt(inputArrayBuffer, offset, aesIV) {
  4589. const nRounds = this.keySize + 6;
  4590. const invKeySchedule = this.invKeySchedule;
  4591. const invSBOX = this.invSBox;
  4592. const invSubMix = this.invSubMix;
  4593. const invSubMix0 = invSubMix[0];
  4594. const invSubMix1 = invSubMix[1];
  4595. const invSubMix2 = invSubMix[2];
  4596. const invSubMix3 = invSubMix[3];
  4597. const initVector = this.uint8ArrayToUint32Array_(aesIV);
  4598. let initVector0 = initVector[0];
  4599. let initVector1 = initVector[1];
  4600. let initVector2 = initVector[2];
  4601. let initVector3 = initVector[3];
  4602. const inputInt32 = new Int32Array(inputArrayBuffer);
  4603. const outputInt32 = new Int32Array(inputInt32.length);
  4604. let t0, t1, t2, t3;
  4605. let s0, s1, s2, s3;
  4606. let inputWords0, inputWords1, inputWords2, inputWords3;
  4607. let ksRow, i;
  4608. const swapWord = this.networkToHostOrderSwap;
  4609. while (offset < inputInt32.length) {
  4610. inputWords0 = swapWord(inputInt32[offset]);
  4611. inputWords1 = swapWord(inputInt32[offset + 1]);
  4612. inputWords2 = swapWord(inputInt32[offset + 2]);
  4613. inputWords3 = swapWord(inputInt32[offset + 3]);
  4614. s0 = inputWords0 ^ invKeySchedule[0];
  4615. s1 = inputWords3 ^ invKeySchedule[1];
  4616. s2 = inputWords2 ^ invKeySchedule[2];
  4617. s3 = inputWords1 ^ invKeySchedule[3];
  4618. ksRow = 4;
  4619. for (i = 1; i < nRounds; i++) {
  4620. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 255] ^ invSubMix2[s2 >> 8 & 255] ^ invSubMix3[s3 & 255] ^ invKeySchedule[ksRow];
  4621. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 255] ^ invSubMix2[s3 >> 8 & 255] ^ invSubMix3[s0 & 255] ^ invKeySchedule[ksRow + 1];
  4622. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 255] ^ invSubMix2[s0 >> 8 & 255] ^ invSubMix3[s1 & 255] ^ invKeySchedule[ksRow + 2];
  4623. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 255] ^ invSubMix2[s1 >> 8 & 255] ^ invSubMix3[s2 & 255] ^ invKeySchedule[ksRow + 3];
  4624. s0 = t0;
  4625. s1 = t1;
  4626. s2 = t2;
  4627. s3 = t3;
  4628. ksRow = ksRow + 4;
  4629. }
  4630. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 255] << 16 ^ invSBOX[s2 >> 8 & 255] << 8 ^ invSBOX[s3 & 255] ^ invKeySchedule[ksRow];
  4631. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 255] << 16 ^ invSBOX[s3 >> 8 & 255] << 8 ^ invSBOX[s0 & 255] ^ invKeySchedule[ksRow + 1];
  4632. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 255] << 16 ^ invSBOX[s0 >> 8 & 255] << 8 ^ invSBOX[s1 & 255] ^ invKeySchedule[ksRow + 2];
  4633. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 255] << 16 ^ invSBOX[s1 >> 8 & 255] << 8 ^ invSBOX[s2 & 255] ^ invKeySchedule[ksRow + 3];
  4634. outputInt32[offset] = swapWord(t0 ^ initVector0);
  4635. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  4636. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  4637. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  4638. initVector0 = inputWords0;
  4639. initVector1 = inputWords1;
  4640. initVector2 = inputWords2;
  4641. initVector3 = inputWords3;
  4642. offset = offset + 4;
  4643. }
  4644. return outputInt32.buffer;
  4645. }
  4646. };
  4647. var FastAESKey = class {
  4648. constructor(subtle, key, aesMode) {
  4649. this.subtle = void 0;
  4650. this.key = void 0;
  4651. this.aesMode = void 0;
  4652. this.subtle = subtle;
  4653. this.key = key;
  4654. this.aesMode = aesMode;
  4655. }
  4656. expandKey() {
  4657. const subtleAlgoName = getSubtleAlgoName(this.aesMode);
  4658. return this.subtle.importKey("raw", this.key, {
  4659. name: subtleAlgoName
  4660. }, false, ["encrypt", "decrypt"]);
  4661. }
  4662. };
  4663. function getSubtleAlgoName(aesMode) {
  4664. switch (aesMode) {
  4665. case DecrypterAesMode.cbc:
  4666. return "AES-CBC";
  4667. case DecrypterAesMode.ctr:
  4668. return "AES-CTR";
  4669. default:
  4670. throw new Error(`[FastAESKey] invalid aes mode ${aesMode}`);
  4671. }
  4672. }
  4673. var CHUNK_SIZE = 16;
  4674. var Decrypter = class {
  4675. constructor(config, {
  4676. removePKCS7Padding = true
  4677. } = {}) {
  4678. this.logEnabled = true;
  4679. this.removePKCS7Padding = void 0;
  4680. this.subtle = null;
  4681. this.softwareDecrypter = null;
  4682. this.key = null;
  4683. this.fastAesKey = null;
  4684. this.remainderData = null;
  4685. this.currentIV = null;
  4686. this.currentResult = null;
  4687. this.useSoftware = void 0;
  4688. this.enableSoftwareAES = void 0;
  4689. this.enableSoftwareAES = config.enableSoftwareAES;
  4690. this.removePKCS7Padding = removePKCS7Padding;
  4691. if (removePKCS7Padding) {
  4692. try {
  4693. const browserCrypto = self.crypto;
  4694. if (browserCrypto) {
  4695. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  4696. }
  4697. } catch (e) {
  4698. }
  4699. }
  4700. this.useSoftware = !this.subtle;
  4701. }
  4702. destroy() {
  4703. this.subtle = null;
  4704. this.softwareDecrypter = null;
  4705. this.key = null;
  4706. this.fastAesKey = null;
  4707. this.remainderData = null;
  4708. this.currentIV = null;
  4709. this.currentResult = null;
  4710. }
  4711. isSync() {
  4712. return this.useSoftware;
  4713. }
  4714. flush() {
  4715. const {
  4716. currentResult,
  4717. remainderData
  4718. } = this;
  4719. if (!currentResult || remainderData) {
  4720. this.reset();
  4721. return null;
  4722. }
  4723. const data = new Uint8Array(currentResult);
  4724. this.reset();
  4725. if (this.removePKCS7Padding) {
  4726. return removePadding(data);
  4727. }
  4728. return data;
  4729. }
  4730. reset() {
  4731. this.currentResult = null;
  4732. this.currentIV = null;
  4733. this.remainderData = null;
  4734. if (this.softwareDecrypter) {
  4735. this.softwareDecrypter = null;
  4736. }
  4737. }
  4738. decrypt(data, key, iv, aesMode) {
  4739. if (this.useSoftware) {
  4740. return new Promise((resolve, reject) => {
  4741. const dataView = ArrayBuffer.isView(data) ? data : new Uint8Array(data);
  4742. this.softwareDecrypt(dataView, key, iv, aesMode);
  4743. const decryptResult = this.flush();
  4744. if (decryptResult) {
  4745. resolve(decryptResult.buffer);
  4746. } else {
  4747. reject(new Error("[softwareDecrypt] Failed to decrypt data"));
  4748. }
  4749. });
  4750. }
  4751. return this.webCryptoDecrypt(new Uint8Array(data), key, iv, aesMode);
  4752. }
  4753. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  4754. // data is handled in the flush() call
  4755. softwareDecrypt(data, key, iv, aesMode) {
  4756. const {
  4757. currentIV,
  4758. currentResult,
  4759. remainderData
  4760. } = this;
  4761. if (aesMode !== DecrypterAesMode.cbc || key.byteLength !== 16) {
  4762. logger.warn("SoftwareDecrypt: can only handle AES-128-CBC");
  4763. return null;
  4764. }
  4765. this.logOnce("JS AES decrypt");
  4766. if (remainderData) {
  4767. data = appendUint8Array(remainderData, data);
  4768. this.remainderData = null;
  4769. }
  4770. const currentChunk = this.getValidChunk(data);
  4771. if (!currentChunk.length) {
  4772. return null;
  4773. }
  4774. if (currentIV) {
  4775. iv = currentIV;
  4776. }
  4777. let softwareDecrypter = this.softwareDecrypter;
  4778. if (!softwareDecrypter) {
  4779. softwareDecrypter = this.softwareDecrypter = new AESDecryptor();
  4780. }
  4781. softwareDecrypter.expandKey(key);
  4782. const result = currentResult;
  4783. this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
  4784. this.currentIV = currentChunk.slice(-16).buffer;
  4785. if (!result) {
  4786. return null;
  4787. }
  4788. return result;
  4789. }
  4790. webCryptoDecrypt(data, key, iv, aesMode) {
  4791. if (this.key !== key || !this.fastAesKey) {
  4792. if (!this.subtle) {
  4793. return Promise.resolve(this.onWebCryptoError(data, key, iv, aesMode));
  4794. }
  4795. this.key = key;
  4796. this.fastAesKey = new FastAESKey(this.subtle, key, aesMode);
  4797. }
  4798. return this.fastAesKey.expandKey().then((aesKey) => {
  4799. if (!this.subtle) {
  4800. return Promise.reject(new Error("web crypto not initialized"));
  4801. }
  4802. this.logOnce("WebCrypto AES decrypt");
  4803. const crypto2 = new AESCrypto(this.subtle, new Uint8Array(iv), aesMode);
  4804. return crypto2.decrypt(data.buffer, aesKey);
  4805. }).catch((err) => {
  4806. logger.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${err.name}: ${err.message}`);
  4807. return this.onWebCryptoError(data, key, iv, aesMode);
  4808. });
  4809. }
  4810. onWebCryptoError(data, key, iv, aesMode) {
  4811. const enableSoftwareAES = this.enableSoftwareAES;
  4812. if (enableSoftwareAES) {
  4813. this.useSoftware = true;
  4814. this.logEnabled = true;
  4815. this.softwareDecrypt(data, key, iv, aesMode);
  4816. const decryptResult = this.flush();
  4817. if (decryptResult) {
  4818. return decryptResult.buffer;
  4819. }
  4820. }
  4821. throw new Error("WebCrypto" + (enableSoftwareAES ? " and softwareDecrypt" : "") + ": failed to decrypt data");
  4822. }
  4823. getValidChunk(data) {
  4824. let currentChunk = data;
  4825. const splitPoint = data.length - data.length % CHUNK_SIZE;
  4826. if (splitPoint !== data.length) {
  4827. currentChunk = data.slice(0, splitPoint);
  4828. this.remainderData = data.slice(splitPoint);
  4829. }
  4830. return currentChunk;
  4831. }
  4832. logOnce(msg) {
  4833. if (!this.logEnabled) {
  4834. return;
  4835. }
  4836. logger.log(`[decrypter]: ${msg}`);
  4837. this.logEnabled = false;
  4838. }
  4839. };
  4840. var MIN_CHUNK_SIZE = Math.pow(2, 17);
  4841. var FragmentLoader = class {
  4842. constructor(config) {
  4843. this.config = void 0;
  4844. this.loader = null;
  4845. this.partLoadTimeout = -1;
  4846. this.config = config;
  4847. }
  4848. destroy() {
  4849. if (this.loader) {
  4850. this.loader.destroy();
  4851. this.loader = null;
  4852. }
  4853. }
  4854. abort() {
  4855. if (this.loader) {
  4856. this.loader.abort();
  4857. }
  4858. }
  4859. load(frag, onProgress) {
  4860. const url = frag.url;
  4861. if (!url) {
  4862. return Promise.reject(new LoadError({
  4863. type: ErrorTypes.NETWORK_ERROR,
  4864. details: ErrorDetails.FRAG_LOAD_ERROR,
  4865. fatal: false,
  4866. frag,
  4867. error: new Error(`Fragment does not have a ${url ? "part list" : "url"}`),
  4868. networkDetails: null
  4869. }));
  4870. }
  4871. this.abort();
  4872. const config = this.config;
  4873. const FragmentILoader = config.fLoader;
  4874. const DefaultILoader = config.loader;
  4875. return new Promise((resolve, reject) => {
  4876. if (this.loader) {
  4877. this.loader.destroy();
  4878. }
  4879. if (frag.gap) {
  4880. if (frag.tagList.some((tags) => tags[0] === "GAP")) {
  4881. reject(createGapLoadError(frag));
  4882. return;
  4883. } else {
  4884. frag.gap = false;
  4885. }
  4886. }
  4887. const loader = this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  4888. const loaderContext = createLoaderContext(frag);
  4889. frag.loader = loader;
  4890. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  4891. const loaderConfig = {
  4892. loadPolicy,
  4893. timeout: loadPolicy.maxLoadTimeMs,
  4894. maxRetry: 0,
  4895. retryDelay: 0,
  4896. maxRetryDelay: 0,
  4897. highWaterMark: frag.sn === "initSegment" ? Infinity : MIN_CHUNK_SIZE
  4898. };
  4899. frag.stats = loader.stats;
  4900. const callbacks = {
  4901. onSuccess: (response, stats, context, networkDetails) => {
  4902. this.resetLoader(frag, loader);
  4903. let payload = response.data;
  4904. if (context.resetIV && frag.decryptdata) {
  4905. frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));
  4906. payload = payload.slice(16);
  4907. }
  4908. resolve({
  4909. frag,
  4910. part: null,
  4911. payload,
  4912. networkDetails
  4913. });
  4914. },
  4915. onError: (response, context, networkDetails, stats) => {
  4916. this.resetLoader(frag, loader);
  4917. reject(new LoadError({
  4918. type: ErrorTypes.NETWORK_ERROR,
  4919. details: ErrorDetails.FRAG_LOAD_ERROR,
  4920. fatal: false,
  4921. frag,
  4922. response: _objectSpread2({
  4923. url,
  4924. data: void 0
  4925. }, response),
  4926. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  4927. networkDetails,
  4928. stats
  4929. }));
  4930. },
  4931. onAbort: (stats, context, networkDetails) => {
  4932. this.resetLoader(frag, loader);
  4933. reject(new LoadError({
  4934. type: ErrorTypes.NETWORK_ERROR,
  4935. details: ErrorDetails.INTERNAL_ABORTED,
  4936. fatal: false,
  4937. frag,
  4938. error: new Error("Aborted"),
  4939. networkDetails,
  4940. stats
  4941. }));
  4942. },
  4943. onTimeout: (stats, context, networkDetails) => {
  4944. this.resetLoader(frag, loader);
  4945. reject(new LoadError({
  4946. type: ErrorTypes.NETWORK_ERROR,
  4947. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  4948. fatal: false,
  4949. frag,
  4950. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  4951. networkDetails,
  4952. stats
  4953. }));
  4954. }
  4955. };
  4956. if (onProgress) {
  4957. callbacks.onProgress = (stats, context, data, networkDetails) => onProgress({
  4958. frag,
  4959. part: null,
  4960. payload: data,
  4961. networkDetails
  4962. });
  4963. }
  4964. loader.load(loaderContext, loaderConfig, callbacks);
  4965. });
  4966. }
  4967. loadPart(frag, part, onProgress) {
  4968. this.abort();
  4969. const config = this.config;
  4970. const FragmentILoader = config.fLoader;
  4971. const DefaultILoader = config.loader;
  4972. return new Promise((resolve, reject) => {
  4973. if (this.loader) {
  4974. this.loader.destroy();
  4975. }
  4976. if (frag.gap || part.gap) {
  4977. reject(createGapLoadError(frag, part));
  4978. return;
  4979. }
  4980. const loader = this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  4981. const loaderContext = createLoaderContext(frag, part);
  4982. frag.loader = loader;
  4983. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  4984. const loaderConfig = {
  4985. loadPolicy,
  4986. timeout: loadPolicy.maxLoadTimeMs,
  4987. maxRetry: 0,
  4988. retryDelay: 0,
  4989. maxRetryDelay: 0,
  4990. highWaterMark: MIN_CHUNK_SIZE
  4991. };
  4992. part.stats = loader.stats;
  4993. loader.load(loaderContext, loaderConfig, {
  4994. onSuccess: (response, stats, context, networkDetails) => {
  4995. this.resetLoader(frag, loader);
  4996. this.updateStatsFromPart(frag, part);
  4997. const partLoadedData = {
  4998. frag,
  4999. part,
  5000. payload: response.data,
  5001. networkDetails
  5002. };
  5003. onProgress(partLoadedData);
  5004. resolve(partLoadedData);
  5005. },
  5006. onError: (response, context, networkDetails, stats) => {
  5007. this.resetLoader(frag, loader);
  5008. reject(new LoadError({
  5009. type: ErrorTypes.NETWORK_ERROR,
  5010. details: ErrorDetails.FRAG_LOAD_ERROR,
  5011. fatal: false,
  5012. frag,
  5013. part,
  5014. response: _objectSpread2({
  5015. url: loaderContext.url,
  5016. data: void 0
  5017. }, response),
  5018. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  5019. networkDetails,
  5020. stats
  5021. }));
  5022. },
  5023. onAbort: (stats, context, networkDetails) => {
  5024. frag.stats.aborted = part.stats.aborted;
  5025. this.resetLoader(frag, loader);
  5026. reject(new LoadError({
  5027. type: ErrorTypes.NETWORK_ERROR,
  5028. details: ErrorDetails.INTERNAL_ABORTED,
  5029. fatal: false,
  5030. frag,
  5031. part,
  5032. error: new Error("Aborted"),
  5033. networkDetails,
  5034. stats
  5035. }));
  5036. },
  5037. onTimeout: (stats, context, networkDetails) => {
  5038. this.resetLoader(frag, loader);
  5039. reject(new LoadError({
  5040. type: ErrorTypes.NETWORK_ERROR,
  5041. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  5042. fatal: false,
  5043. frag,
  5044. part,
  5045. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  5046. networkDetails,
  5047. stats
  5048. }));
  5049. }
  5050. });
  5051. });
  5052. }
  5053. updateStatsFromPart(frag, part) {
  5054. const fragStats = frag.stats;
  5055. const partStats = part.stats;
  5056. const partTotal = partStats.total;
  5057. fragStats.loaded += partStats.loaded;
  5058. if (partTotal) {
  5059. const estTotalParts = Math.round(frag.duration / part.duration);
  5060. const estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
  5061. const estRemainingParts = estTotalParts - estLoadedParts;
  5062. const estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
  5063. fragStats.total = fragStats.loaded + estRemainingBytes;
  5064. } else {
  5065. fragStats.total = Math.max(fragStats.loaded, fragStats.total);
  5066. }
  5067. const fragLoading = fragStats.loading;
  5068. const partLoading = partStats.loading;
  5069. if (fragLoading.start) {
  5070. fragLoading.first += partLoading.first - partLoading.start;
  5071. } else {
  5072. fragLoading.start = partLoading.start;
  5073. fragLoading.first = partLoading.first;
  5074. }
  5075. fragLoading.end = partLoading.end;
  5076. }
  5077. resetLoader(frag, loader) {
  5078. frag.loader = null;
  5079. if (this.loader === loader) {
  5080. self.clearTimeout(this.partLoadTimeout);
  5081. this.loader = null;
  5082. }
  5083. loader.destroy();
  5084. }
  5085. };
  5086. function createLoaderContext(frag, part = null) {
  5087. const segment = part || frag;
  5088. const loaderContext = {
  5089. frag,
  5090. part,
  5091. responseType: "arraybuffer",
  5092. url: segment.url,
  5093. headers: {},
  5094. rangeStart: 0,
  5095. rangeEnd: 0
  5096. };
  5097. const start = segment.byteRangeStartOffset;
  5098. const end = segment.byteRangeEndOffset;
  5099. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  5100. var _frag$decryptdata;
  5101. let byteRangeStart = start;
  5102. let byteRangeEnd = end;
  5103. if (frag.sn === "initSegment" && isMethodFullSegmentAesCbc((_frag$decryptdata = frag.decryptdata) == null ? void 0 : _frag$decryptdata.method)) {
  5104. const fragmentLen = end - start;
  5105. if (fragmentLen % 16) {
  5106. byteRangeEnd = end + (16 - fragmentLen % 16);
  5107. }
  5108. if (start !== 0) {
  5109. loaderContext.resetIV = true;
  5110. byteRangeStart = start - 16;
  5111. }
  5112. }
  5113. loaderContext.rangeStart = byteRangeStart;
  5114. loaderContext.rangeEnd = byteRangeEnd;
  5115. }
  5116. return loaderContext;
  5117. }
  5118. function createGapLoadError(frag, part) {
  5119. const error = new Error(`GAP ${frag.gap ? "tag" : "attribute"} found`);
  5120. const errorData = {
  5121. type: ErrorTypes.MEDIA_ERROR,
  5122. details: ErrorDetails.FRAG_GAP,
  5123. fatal: false,
  5124. frag,
  5125. error,
  5126. networkDetails: null
  5127. };
  5128. if (part) {
  5129. errorData.part = part;
  5130. }
  5131. (part ? part : frag).stats.aborted = true;
  5132. return new LoadError(errorData);
  5133. }
  5134. function isMethodFullSegmentAesCbc(method) {
  5135. return method === "AES-128" || method === "AES-256";
  5136. }
  5137. var LoadError = class extends Error {
  5138. constructor(data) {
  5139. super(data.error.message);
  5140. this.data = void 0;
  5141. this.data = data;
  5142. }
  5143. };
  5144. var TaskLoop = class extends Logger {
  5145. constructor(label, logger2) {
  5146. super(label, logger2);
  5147. this._boundTick = void 0;
  5148. this._tickTimer = null;
  5149. this._tickInterval = null;
  5150. this._tickCallCount = 0;
  5151. this._boundTick = this.tick.bind(this);
  5152. }
  5153. destroy() {
  5154. this.onHandlerDestroying();
  5155. this.onHandlerDestroyed();
  5156. }
  5157. onHandlerDestroying() {
  5158. this.clearNextTick();
  5159. this.clearInterval();
  5160. }
  5161. onHandlerDestroyed() {
  5162. }
  5163. hasInterval() {
  5164. return !!this._tickInterval;
  5165. }
  5166. hasNextTick() {
  5167. return !!this._tickTimer;
  5168. }
  5169. /**
  5170. * @param millis - Interval time (ms)
  5171. * @eturns True when interval has been scheduled, false when already scheduled (no effect)
  5172. */
  5173. setInterval(millis) {
  5174. if (!this._tickInterval) {
  5175. this._tickCallCount = 0;
  5176. this._tickInterval = self.setInterval(this._boundTick, millis);
  5177. return true;
  5178. }
  5179. return false;
  5180. }
  5181. /**
  5182. * @returns True when interval was cleared, false when none was set (no effect)
  5183. */
  5184. clearInterval() {
  5185. if (this._tickInterval) {
  5186. self.clearInterval(this._tickInterval);
  5187. this._tickInterval = null;
  5188. return true;
  5189. }
  5190. return false;
  5191. }
  5192. /**
  5193. * @returns True when timeout was cleared, false when none was set (no effect)
  5194. */
  5195. clearNextTick() {
  5196. if (this._tickTimer) {
  5197. self.clearTimeout(this._tickTimer);
  5198. this._tickTimer = null;
  5199. return true;
  5200. }
  5201. return false;
  5202. }
  5203. /**
  5204. * Will call the subclass doTick implementation in this main loop tick
  5205. * or in the next one (via setTimeout(,0)) in case it has already been called
  5206. * in this tick (in case this is a re-entrant call).
  5207. */
  5208. tick() {
  5209. this._tickCallCount++;
  5210. if (this._tickCallCount === 1) {
  5211. this.doTick();
  5212. if (this._tickCallCount > 1) {
  5213. this.tickImmediate();
  5214. }
  5215. this._tickCallCount = 0;
  5216. }
  5217. }
  5218. tickImmediate() {
  5219. this.clearNextTick();
  5220. this._tickTimer = self.setTimeout(this._boundTick, 0);
  5221. }
  5222. /**
  5223. * For subclass to implement task logic
  5224. * @abstract
  5225. */
  5226. doTick() {
  5227. }
  5228. };
  5229. var ChunkMetadata = class {
  5230. constructor(level, sn, id, size = 0, part = -1, partial = false) {
  5231. this.level = void 0;
  5232. this.sn = void 0;
  5233. this.part = void 0;
  5234. this.id = void 0;
  5235. this.size = void 0;
  5236. this.partial = void 0;
  5237. this.transmuxing = getNewPerformanceTiming();
  5238. this.buffering = {
  5239. audio: getNewPerformanceTiming(),
  5240. video: getNewPerformanceTiming(),
  5241. audiovideo: getNewPerformanceTiming()
  5242. };
  5243. this.level = level;
  5244. this.sn = sn;
  5245. this.id = id;
  5246. this.size = size;
  5247. this.part = part;
  5248. this.partial = partial;
  5249. }
  5250. };
  5251. function getNewPerformanceTiming() {
  5252. return {
  5253. start: 0,
  5254. executeStart: 0,
  5255. executeEnd: 0,
  5256. end: 0
  5257. };
  5258. }
  5259. var noopBuffered = {
  5260. length: 0,
  5261. start: () => 0,
  5262. end: () => 0
  5263. };
  5264. var BufferHelper = class _BufferHelper {
  5265. /**
  5266. * Return true if `media`'s buffered include `position`
  5267. */
  5268. static isBuffered(media, position) {
  5269. if (media) {
  5270. const buffered = _BufferHelper.getBuffered(media);
  5271. for (let i = buffered.length; i--; ) {
  5272. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  5273. return true;
  5274. }
  5275. }
  5276. }
  5277. return false;
  5278. }
  5279. static bufferedRanges(media) {
  5280. if (media) {
  5281. const timeRanges = _BufferHelper.getBuffered(media);
  5282. return _BufferHelper.timeRangesToArray(timeRanges);
  5283. }
  5284. return [];
  5285. }
  5286. static timeRangesToArray(timeRanges) {
  5287. const buffered = [];
  5288. for (let i = 0; i < timeRanges.length; i++) {
  5289. buffered.push({
  5290. start: timeRanges.start(i),
  5291. end: timeRanges.end(i)
  5292. });
  5293. }
  5294. return buffered;
  5295. }
  5296. static bufferInfo(media, pos, maxHoleDuration) {
  5297. if (media) {
  5298. const buffered = _BufferHelper.bufferedRanges(media);
  5299. if (buffered.length) {
  5300. return _BufferHelper.bufferedInfo(buffered, pos, maxHoleDuration);
  5301. }
  5302. }
  5303. return {
  5304. len: 0,
  5305. start: pos,
  5306. end: pos,
  5307. bufferedIndex: -1
  5308. };
  5309. }
  5310. static bufferedInfo(buffered, pos, maxHoleDuration) {
  5311. pos = Math.max(0, pos);
  5312. if (buffered.length > 1) {
  5313. buffered.sort((a, b) => a.start - b.start || b.end - a.end);
  5314. }
  5315. let bufferedIndex = -1;
  5316. let buffered2 = [];
  5317. if (maxHoleDuration) {
  5318. for (let i = 0; i < buffered.length; i++) {
  5319. if (pos >= buffered[i].start && pos <= buffered[i].end) {
  5320. bufferedIndex = i;
  5321. }
  5322. const buf2len = buffered2.length;
  5323. if (buf2len) {
  5324. const buf2end = buffered2[buf2len - 1].end;
  5325. if (buffered[i].start - buf2end < maxHoleDuration) {
  5326. if (buffered[i].end > buf2end) {
  5327. buffered2[buf2len - 1].end = buffered[i].end;
  5328. }
  5329. } else {
  5330. buffered2.push(buffered[i]);
  5331. }
  5332. } else {
  5333. buffered2.push(buffered[i]);
  5334. }
  5335. }
  5336. } else {
  5337. buffered2 = buffered;
  5338. }
  5339. let bufferLen = 0;
  5340. let nextStart;
  5341. let bufferStart = pos;
  5342. let bufferEnd = pos;
  5343. for (let i = 0; i < buffered2.length; i++) {
  5344. const start = buffered2[i].start;
  5345. const end = buffered2[i].end;
  5346. if (bufferedIndex === -1 && pos >= start && pos <= end) {
  5347. bufferedIndex = i;
  5348. }
  5349. if (pos + maxHoleDuration >= start && pos < end) {
  5350. bufferStart = start;
  5351. bufferEnd = end;
  5352. bufferLen = bufferEnd - pos;
  5353. } else if (pos + maxHoleDuration < start) {
  5354. nextStart = start;
  5355. break;
  5356. }
  5357. }
  5358. return {
  5359. len: bufferLen,
  5360. start: bufferStart || 0,
  5361. end: bufferEnd || 0,
  5362. nextStart,
  5363. buffered,
  5364. bufferedIndex
  5365. };
  5366. }
  5367. /**
  5368. * Safe method to get buffered property.
  5369. * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
  5370. */
  5371. static getBuffered(media) {
  5372. try {
  5373. return media.buffered || noopBuffered;
  5374. } catch (e) {
  5375. logger.log("failed to get media.buffered", e);
  5376. return noopBuffered;
  5377. }
  5378. }
  5379. };
  5380. var VARIABLE_REPLACEMENT_REGEX = /\{\$([a-zA-Z0-9-_]+)\}/g;
  5381. function hasVariableReferences(str) {
  5382. return VARIABLE_REPLACEMENT_REGEX.test(str);
  5383. }
  5384. function substituteVariables(parsed, value) {
  5385. if (parsed.variableList !== null || parsed.hasVariableRefs) {
  5386. const variableList = parsed.variableList;
  5387. return value.replace(VARIABLE_REPLACEMENT_REGEX, (variableReference) => {
  5388. const variableName = variableReference.substring(2, variableReference.length - 1);
  5389. const variableValue = variableList == null ? void 0 : variableList[variableName];
  5390. if (variableValue === void 0) {
  5391. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${variableName}"`));
  5392. return variableReference;
  5393. }
  5394. return variableValue;
  5395. });
  5396. }
  5397. return value;
  5398. }
  5399. function addVariableDefinition(parsed, attr, parentUrl) {
  5400. let variableList = parsed.variableList;
  5401. if (!variableList) {
  5402. parsed.variableList = variableList = {};
  5403. }
  5404. let NAME;
  5405. let VALUE;
  5406. if ("QUERYPARAM" in attr) {
  5407. NAME = attr.QUERYPARAM;
  5408. try {
  5409. const searchParams = new self.URL(parentUrl).searchParams;
  5410. if (searchParams.has(NAME)) {
  5411. VALUE = searchParams.get(NAME);
  5412. } else {
  5413. throw new Error(`"${NAME}" does not match any query parameter in URI: "${parentUrl}"`);
  5414. }
  5415. } catch (error) {
  5416. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE QUERYPARAM: ${error.message}`));
  5417. }
  5418. } else {
  5419. NAME = attr.NAME;
  5420. VALUE = attr.VALUE;
  5421. }
  5422. if (NAME in variableList) {
  5423. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${NAME}"`));
  5424. } else {
  5425. variableList[NAME] = VALUE || "";
  5426. }
  5427. }
  5428. function importVariableDefinition(parsed, attr, sourceVariableList) {
  5429. const IMPORT = attr.IMPORT;
  5430. if (sourceVariableList && IMPORT in sourceVariableList) {
  5431. let variableList = parsed.variableList;
  5432. if (!variableList) {
  5433. parsed.variableList = variableList = {};
  5434. }
  5435. variableList[IMPORT] = sourceVariableList[IMPORT];
  5436. } else {
  5437. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${IMPORT}"`));
  5438. }
  5439. }
  5440. var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/;
  5441. var ATTR_LIST_REGEX = /(.+?)=(".*?"|.*?)(?:,|$)/g;
  5442. var AttrList = class _AttrList {
  5443. constructor(attrs, parsed) {
  5444. if (typeof attrs === "string") {
  5445. attrs = _AttrList.parseAttrList(attrs, parsed);
  5446. }
  5447. _extends(this, attrs);
  5448. }
  5449. get clientAttrs() {
  5450. return Object.keys(this).filter((attr) => attr.substring(0, 2) === "X-");
  5451. }
  5452. decimalInteger(attrName) {
  5453. const intValue = parseInt(this[attrName], 10);
  5454. if (intValue > Number.MAX_SAFE_INTEGER) {
  5455. return Infinity;
  5456. }
  5457. return intValue;
  5458. }
  5459. hexadecimalInteger(attrName) {
  5460. if (this[attrName]) {
  5461. let stringValue = (this[attrName] || "0x").slice(2);
  5462. stringValue = (stringValue.length & 1 ? "0" : "") + stringValue;
  5463. const value = new Uint8Array(stringValue.length / 2);
  5464. for (let i = 0; i < stringValue.length / 2; i++) {
  5465. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  5466. }
  5467. return value;
  5468. }
  5469. return null;
  5470. }
  5471. hexadecimalIntegerAsNumber(attrName) {
  5472. const intValue = parseInt(this[attrName], 16);
  5473. if (intValue > Number.MAX_SAFE_INTEGER) {
  5474. return Infinity;
  5475. }
  5476. return intValue;
  5477. }
  5478. decimalFloatingPoint(attrName) {
  5479. return parseFloat(this[attrName]);
  5480. }
  5481. optionalFloat(attrName, defaultValue) {
  5482. const value = this[attrName];
  5483. return value ? parseFloat(value) : defaultValue;
  5484. }
  5485. enumeratedString(attrName) {
  5486. return this[attrName];
  5487. }
  5488. enumeratedStringList(attrName, dict) {
  5489. const attrValue = this[attrName];
  5490. return (attrValue ? attrValue.split(/[ ,]+/) : []).reduce((result, identifier) => {
  5491. result[identifier.toLowerCase()] = true;
  5492. return result;
  5493. }, dict);
  5494. }
  5495. bool(attrName) {
  5496. return this[attrName] === "YES";
  5497. }
  5498. decimalResolution(attrName) {
  5499. const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  5500. if (res === null) {
  5501. return void 0;
  5502. }
  5503. return {
  5504. width: parseInt(res[1], 10),
  5505. height: parseInt(res[2], 10)
  5506. };
  5507. }
  5508. static parseAttrList(input, parsed) {
  5509. let match;
  5510. const attrs = {};
  5511. const quote = '"';
  5512. ATTR_LIST_REGEX.lastIndex = 0;
  5513. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  5514. const name = match[1].trim();
  5515. let value = match[2];
  5516. const quotedString = value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1;
  5517. let hexadecimalSequence = false;
  5518. if (quotedString) {
  5519. value = value.slice(1, -1);
  5520. } else {
  5521. switch (name) {
  5522. case "IV":
  5523. case "SCTE35-CMD":
  5524. case "SCTE35-IN":
  5525. case "SCTE35-OUT":
  5526. hexadecimalSequence = true;
  5527. }
  5528. }
  5529. if (parsed && (quotedString || hexadecimalSequence)) {
  5530. {
  5531. value = substituteVariables(parsed, value);
  5532. }
  5533. } else if (!hexadecimalSequence && !quotedString) {
  5534. switch (name) {
  5535. case "CLOSED-CAPTIONS":
  5536. if (value === "NONE") {
  5537. break;
  5538. }
  5539. case "ALLOWED-CPC":
  5540. case "CLASS":
  5541. case "ASSOC-LANGUAGE":
  5542. case "AUDIO":
  5543. case "BYTERANGE":
  5544. case "CHANNELS":
  5545. case "CHARACTERISTICS":
  5546. case "CODECS":
  5547. case "DATA-ID":
  5548. case "END-DATE":
  5549. case "GROUP-ID":
  5550. case "ID":
  5551. case "IMPORT":
  5552. case "INSTREAM-ID":
  5553. case "KEYFORMAT":
  5554. case "KEYFORMATVERSIONS":
  5555. case "LANGUAGE":
  5556. case "NAME":
  5557. case "PATHWAY-ID":
  5558. case "QUERYPARAM":
  5559. case "RECENTLY-REMOVED-DATERANGES":
  5560. case "SERVER-URI":
  5561. case "STABLE-RENDITION-ID":
  5562. case "STABLE-VARIANT-ID":
  5563. case "START-DATE":
  5564. case "SUBTITLES":
  5565. case "SUPPLEMENTAL-CODECS":
  5566. case "URI":
  5567. case "VALUE":
  5568. case "VIDEO":
  5569. case "X-ASSET-LIST":
  5570. case "X-ASSET-URI":
  5571. logger.warn(`${input}: attribute ${name} is missing quotes`);
  5572. }
  5573. }
  5574. attrs[name] = value;
  5575. }
  5576. return attrs;
  5577. }
  5578. };
  5579. var CLASS_INTERSTITIAL = "com.apple.hls.interstitial";
  5580. function isDateRangeCueAttribute(attrName) {
  5581. return attrName !== "ID" && attrName !== "CLASS" && attrName !== "CUE" && attrName !== "START-DATE" && attrName !== "DURATION" && attrName !== "END-DATE" && attrName !== "END-ON-NEXT";
  5582. }
  5583. function isSCTE35Attribute(attrName) {
  5584. return attrName === "SCTE35-OUT" || attrName === "SCTE35-IN" || attrName === "SCTE35-CMD";
  5585. }
  5586. var DateRange = class {
  5587. constructor(dateRangeAttr, dateRangeWithSameId, tagCount = 0) {
  5588. var _dateRangeWithSameId$;
  5589. this.attr = void 0;
  5590. this.tagAnchor = void 0;
  5591. this.tagOrder = void 0;
  5592. this._startDate = void 0;
  5593. this._endDate = void 0;
  5594. this._dateAtEnd = void 0;
  5595. this._cue = void 0;
  5596. this._badValueForSameId = void 0;
  5597. this.tagAnchor = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagAnchor) || null;
  5598. this.tagOrder = (_dateRangeWithSameId$ = dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagOrder) != null ? _dateRangeWithSameId$ : tagCount;
  5599. if (dateRangeWithSameId) {
  5600. const previousAttr = dateRangeWithSameId.attr;
  5601. for (const key in previousAttr) {
  5602. if (Object.prototype.hasOwnProperty.call(dateRangeAttr, key) && dateRangeAttr[key] !== previousAttr[key]) {
  5603. logger.warn(`DATERANGE tag attribute: "${key}" does not match for tags with ID: "${dateRangeAttr.ID}"`);
  5604. this._badValueForSameId = key;
  5605. break;
  5606. }
  5607. }
  5608. dateRangeAttr = _extends(new AttrList({}), previousAttr, dateRangeAttr);
  5609. }
  5610. this.attr = dateRangeAttr;
  5611. if (dateRangeWithSameId) {
  5612. this._startDate = dateRangeWithSameId._startDate;
  5613. this._cue = dateRangeWithSameId._cue;
  5614. this._endDate = dateRangeWithSameId._endDate;
  5615. this._dateAtEnd = dateRangeWithSameId._dateAtEnd;
  5616. } else {
  5617. this._startDate = new Date(dateRangeAttr["START-DATE"]);
  5618. }
  5619. if ("END-DATE" in this.attr) {
  5620. const endDate = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.endDate) || new Date(this.attr["END-DATE"]);
  5621. if (isFiniteNumber(endDate.getTime())) {
  5622. this._endDate = endDate;
  5623. }
  5624. }
  5625. }
  5626. get id() {
  5627. return this.attr.ID;
  5628. }
  5629. get class() {
  5630. return this.attr.CLASS;
  5631. }
  5632. get cue() {
  5633. const _cue = this._cue;
  5634. if (_cue === void 0) {
  5635. return this._cue = this.attr.enumeratedStringList(this.attr.CUE ? "CUE" : "X-CUE", {
  5636. pre: false,
  5637. post: false,
  5638. once: false
  5639. });
  5640. }
  5641. return _cue;
  5642. }
  5643. get startTime() {
  5644. const {
  5645. tagAnchor
  5646. } = this;
  5647. if (tagAnchor === null || tagAnchor.programDateTime === null) {
  5648. logger.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${tagAnchor}`);
  5649. return NaN;
  5650. }
  5651. return tagAnchor.start + (this.startDate.getTime() - tagAnchor.programDateTime) / 1e3;
  5652. }
  5653. get startDate() {
  5654. return this._startDate;
  5655. }
  5656. get endDate() {
  5657. const dateAtEnd = this._endDate || this._dateAtEnd;
  5658. if (dateAtEnd) {
  5659. return dateAtEnd;
  5660. }
  5661. const duration = this.duration;
  5662. if (duration !== null) {
  5663. return this._dateAtEnd = new Date(this._startDate.getTime() + duration * 1e3);
  5664. }
  5665. return null;
  5666. }
  5667. get duration() {
  5668. if ("DURATION" in this.attr) {
  5669. const duration = this.attr.decimalFloatingPoint("DURATION");
  5670. if (isFiniteNumber(duration)) {
  5671. return duration;
  5672. }
  5673. } else if (this._endDate) {
  5674. return (this._endDate.getTime() - this._startDate.getTime()) / 1e3;
  5675. }
  5676. return null;
  5677. }
  5678. get plannedDuration() {
  5679. if ("PLANNED-DURATION" in this.attr) {
  5680. return this.attr.decimalFloatingPoint("PLANNED-DURATION");
  5681. }
  5682. return null;
  5683. }
  5684. get endOnNext() {
  5685. return this.attr.bool("END-ON-NEXT");
  5686. }
  5687. get isInterstitial() {
  5688. return this.class === CLASS_INTERSTITIAL;
  5689. }
  5690. get isValid() {
  5691. return !!this.id && !this._badValueForSameId && isFiniteNumber(this.startDate.getTime()) && (this.duration === null || this.duration >= 0) && (!this.endOnNext || !!this.class) && (!this.attr.CUE || !this.cue.pre && !this.cue.post || this.cue.pre !== this.cue.post) && (!this.isInterstitial || "X-ASSET-URI" in this.attr || "X-ASSET-LIST" in this.attr);
  5692. }
  5693. };
  5694. var DEFAULT_TARGET_DURATION = 10;
  5695. var LevelDetails = class {
  5696. constructor(baseUrl) {
  5697. this.PTSKnown = false;
  5698. this.alignedSliding = false;
  5699. this.averagetargetduration = void 0;
  5700. this.endCC = 0;
  5701. this.endSN = 0;
  5702. this.fragments = void 0;
  5703. this.fragmentHint = void 0;
  5704. this.partList = null;
  5705. this.dateRanges = void 0;
  5706. this.dateRangeTagCount = 0;
  5707. this.live = true;
  5708. this.requestScheduled = -1;
  5709. this.ageHeader = 0;
  5710. this.advancedDateTime = void 0;
  5711. this.updated = true;
  5712. this.advanced = true;
  5713. this.misses = 0;
  5714. this.startCC = 0;
  5715. this.startSN = 0;
  5716. this.startTimeOffset = null;
  5717. this.targetduration = 0;
  5718. this.totalduration = 0;
  5719. this.type = null;
  5720. this.url = void 0;
  5721. this.m3u8 = "";
  5722. this.version = null;
  5723. this.canBlockReload = false;
  5724. this.canSkipUntil = 0;
  5725. this.canSkipDateRanges = false;
  5726. this.skippedSegments = 0;
  5727. this.recentlyRemovedDateranges = void 0;
  5728. this.partHoldBack = 0;
  5729. this.holdBack = 0;
  5730. this.partTarget = 0;
  5731. this.preloadHint = void 0;
  5732. this.renditionReports = void 0;
  5733. this.tuneInGoal = 0;
  5734. this.deltaUpdateFailed = void 0;
  5735. this.driftStartTime = 0;
  5736. this.driftEndTime = 0;
  5737. this.driftStart = 0;
  5738. this.driftEnd = 0;
  5739. this.encryptedFragments = void 0;
  5740. this.playlistParsingError = null;
  5741. this.variableList = null;
  5742. this.hasVariableRefs = false;
  5743. this.appliedTimelineOffset = void 0;
  5744. this.fragments = [];
  5745. this.encryptedFragments = [];
  5746. this.dateRanges = {};
  5747. this.url = baseUrl;
  5748. }
  5749. reloaded(previous) {
  5750. if (!previous) {
  5751. this.advanced = true;
  5752. this.updated = true;
  5753. return;
  5754. }
  5755. const partSnDiff = this.lastPartSn - previous.lastPartSn;
  5756. const partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
  5757. this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff || !this.live;
  5758. this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
  5759. if (this.updated || this.advanced) {
  5760. this.misses = Math.floor(previous.misses * 0.6);
  5761. } else {
  5762. this.misses = previous.misses + 1;
  5763. }
  5764. }
  5765. get hasProgramDateTime() {
  5766. if (this.fragments.length) {
  5767. return isFiniteNumber(this.fragments[this.fragments.length - 1].programDateTime);
  5768. }
  5769. return false;
  5770. }
  5771. get levelTargetDuration() {
  5772. return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
  5773. }
  5774. get drift() {
  5775. const runTime = this.driftEndTime - this.driftStartTime;
  5776. if (runTime > 0) {
  5777. const runDuration = this.driftEnd - this.driftStart;
  5778. return runDuration * 1e3 / runTime;
  5779. }
  5780. return 1;
  5781. }
  5782. get edge() {
  5783. return this.partEnd || this.fragmentEnd;
  5784. }
  5785. get partEnd() {
  5786. var _this$partList;
  5787. if ((_this$partList = this.partList) != null && _this$partList.length) {
  5788. return this.partList[this.partList.length - 1].end;
  5789. }
  5790. return this.fragmentEnd;
  5791. }
  5792. get fragmentEnd() {
  5793. var _this$fragments;
  5794. if ((_this$fragments = this.fragments) != null && _this$fragments.length) {
  5795. return this.fragments[this.fragments.length - 1].end;
  5796. }
  5797. return 0;
  5798. }
  5799. get fragmentStart() {
  5800. var _this$fragments2;
  5801. if ((_this$fragments2 = this.fragments) != null && _this$fragments2.length) {
  5802. return this.fragments[0].start;
  5803. }
  5804. return 0;
  5805. }
  5806. get age() {
  5807. if (this.advancedDateTime) {
  5808. return Math.max(Date.now() - this.advancedDateTime, 0) / 1e3;
  5809. }
  5810. return 0;
  5811. }
  5812. get lastPartIndex() {
  5813. var _this$partList2;
  5814. if ((_this$partList2 = this.partList) != null && _this$partList2.length) {
  5815. return this.partList[this.partList.length - 1].index;
  5816. }
  5817. return -1;
  5818. }
  5819. get maxPartIndex() {
  5820. const partList = this.partList;
  5821. if (partList) {
  5822. const lastIndex = this.lastPartIndex;
  5823. if (lastIndex !== -1) {
  5824. for (let i = partList.length; i--; ) {
  5825. if (partList[i].index > lastIndex) {
  5826. return partList[i].index;
  5827. }
  5828. }
  5829. return lastIndex;
  5830. }
  5831. }
  5832. return 0;
  5833. }
  5834. get lastPartSn() {
  5835. var _this$partList3;
  5836. if ((_this$partList3 = this.partList) != null && _this$partList3.length) {
  5837. return this.partList[this.partList.length - 1].fragment.sn;
  5838. }
  5839. return this.endSN;
  5840. }
  5841. get expired() {
  5842. if (this.live && this.age && this.misses < 3) {
  5843. const playlistWindowDuration = this.partEnd - this.fragmentStart;
  5844. return this.age > Math.max(playlistWindowDuration, this.totalduration) + this.levelTargetDuration;
  5845. }
  5846. return false;
  5847. }
  5848. };
  5849. function isFullSegmentEncryption(method) {
  5850. return method === "AES-128" || method === "AES-256" || method === "AES-256-CTR";
  5851. }
  5852. function getAesModeFromFullSegmentMethod(method) {
  5853. switch (method) {
  5854. case "AES-128":
  5855. case "AES-256":
  5856. return DecrypterAesMode.cbc;
  5857. case "AES-256-CTR":
  5858. return DecrypterAesMode.ctr;
  5859. default:
  5860. throw new Error(`invalid full segment method ${method}`);
  5861. }
  5862. }
  5863. function base64Decode(base64encodedStr) {
  5864. return Uint8Array.from(atob(base64encodedStr), (c) => c.charCodeAt(0));
  5865. }
  5866. function strToUtf8array(str) {
  5867. return Uint8Array.from(unescape(encodeURIComponent(str)), (c) => c.charCodeAt(0));
  5868. }
  5869. function getKeyIdBytes(str) {
  5870. const keyIdbytes = strToUtf8array(str).subarray(0, 16);
  5871. const paddedkeyIdbytes = new Uint8Array(16);
  5872. paddedkeyIdbytes.set(keyIdbytes, 16 - keyIdbytes.length);
  5873. return paddedkeyIdbytes;
  5874. }
  5875. function changeEndianness(keyId) {
  5876. const swap = function swap2(array, from, to) {
  5877. const cur = array[from];
  5878. array[from] = array[to];
  5879. array[to] = cur;
  5880. };
  5881. swap(keyId, 0, 3);
  5882. swap(keyId, 1, 2);
  5883. swap(keyId, 4, 5);
  5884. swap(keyId, 6, 7);
  5885. }
  5886. function convertDataUriToArrayBytes(uri) {
  5887. const colonsplit = uri.split(":");
  5888. let keydata = null;
  5889. if (colonsplit[0] === "data" && colonsplit.length === 2) {
  5890. const semicolonsplit = colonsplit[1].split(";");
  5891. const commasplit = semicolonsplit[semicolonsplit.length - 1].split(",");
  5892. if (commasplit.length === 2) {
  5893. const isbase64 = commasplit[0] === "base64";
  5894. const data = commasplit[1];
  5895. if (isbase64) {
  5896. semicolonsplit.splice(-1, 1);
  5897. keydata = base64Decode(data);
  5898. } else {
  5899. keydata = getKeyIdBytes(data);
  5900. }
  5901. }
  5902. }
  5903. return keydata;
  5904. }
  5905. var optionalSelf = typeof self !== "undefined" ? self : void 0;
  5906. var KeySystems = {
  5907. CLEARKEY: "org.w3.clearkey",
  5908. FAIRPLAY: "com.apple.fps",
  5909. PLAYREADY: "com.microsoft.playready",
  5910. WIDEVINE: "com.widevine.alpha"
  5911. };
  5912. var KeySystemFormats = {
  5913. CLEARKEY: "org.w3.clearkey",
  5914. FAIRPLAY: "com.apple.streamingkeydelivery",
  5915. PLAYREADY: "com.microsoft.playready",
  5916. WIDEVINE: "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"
  5917. };
  5918. function keySystemFormatToKeySystemDomain(format2) {
  5919. switch (format2) {
  5920. case KeySystemFormats.FAIRPLAY:
  5921. return KeySystems.FAIRPLAY;
  5922. case KeySystemFormats.PLAYREADY:
  5923. return KeySystems.PLAYREADY;
  5924. case KeySystemFormats.WIDEVINE:
  5925. return KeySystems.WIDEVINE;
  5926. case KeySystemFormats.CLEARKEY:
  5927. return KeySystems.CLEARKEY;
  5928. }
  5929. }
  5930. function keySystemDomainToKeySystemFormat(keySystem) {
  5931. switch (keySystem) {
  5932. case KeySystems.FAIRPLAY:
  5933. return KeySystemFormats.FAIRPLAY;
  5934. case KeySystems.PLAYREADY:
  5935. return KeySystemFormats.PLAYREADY;
  5936. case KeySystems.WIDEVINE:
  5937. return KeySystemFormats.WIDEVINE;
  5938. case KeySystems.CLEARKEY:
  5939. return KeySystemFormats.CLEARKEY;
  5940. }
  5941. }
  5942. function getKeySystemsForConfig(config) {
  5943. const {
  5944. drmSystems,
  5945. widevineLicenseUrl
  5946. } = config;
  5947. const keySystemsToAttempt = drmSystems ? [KeySystems.FAIRPLAY, KeySystems.WIDEVINE, KeySystems.PLAYREADY, KeySystems.CLEARKEY].filter((keySystem) => !!drmSystems[keySystem]) : [];
  5948. if (!keySystemsToAttempt[KeySystems.WIDEVINE] && widevineLicenseUrl) {
  5949. keySystemsToAttempt.push(KeySystems.WIDEVINE);
  5950. }
  5951. return keySystemsToAttempt;
  5952. }
  5953. var requestMediaKeySystemAccess = function(_optionalSelf$navigat) {
  5954. if (optionalSelf != null && (_optionalSelf$navigat = optionalSelf.navigator) != null && _optionalSelf$navigat.requestMediaKeySystemAccess) {
  5955. return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);
  5956. } else {
  5957. return null;
  5958. }
  5959. }();
  5960. function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {
  5961. let initDataTypes;
  5962. switch (keySystem) {
  5963. case KeySystems.FAIRPLAY:
  5964. initDataTypes = ["cenc", "sinf"];
  5965. break;
  5966. case KeySystems.WIDEVINE:
  5967. case KeySystems.PLAYREADY:
  5968. initDataTypes = ["cenc"];
  5969. break;
  5970. case KeySystems.CLEARKEY:
  5971. initDataTypes = ["cenc", "keyids"];
  5972. break;
  5973. default:
  5974. throw new Error(`Unknown key-system: ${keySystem}`);
  5975. }
  5976. return createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions);
  5977. }
  5978. function createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions) {
  5979. const baseConfig = {
  5980. initDataTypes,
  5981. persistentState: drmSystemOptions.persistentState || "optional",
  5982. distinctiveIdentifier: drmSystemOptions.distinctiveIdentifier || "optional",
  5983. sessionTypes: drmSystemOptions.sessionTypes || [drmSystemOptions.sessionType || "temporary"],
  5984. audioCapabilities: audioCodecs.map((codec) => ({
  5985. contentType: `audio/mp4; codecs=${codec}`,
  5986. robustness: drmSystemOptions.audioRobustness || "",
  5987. encryptionScheme: drmSystemOptions.audioEncryptionScheme || null
  5988. })),
  5989. videoCapabilities: videoCodecs.map((codec) => ({
  5990. contentType: `video/mp4; codecs=${codec}`,
  5991. robustness: drmSystemOptions.videoRobustness || "",
  5992. encryptionScheme: drmSystemOptions.videoEncryptionScheme || null
  5993. }))
  5994. };
  5995. return [baseConfig];
  5996. }
  5997. function isPersistentSessionType(drmSystemOptions) {
  5998. var _drmSystemOptions$ses;
  5999. return drmSystemOptions.sessionType === "persistent-license" || !!((_drmSystemOptions$ses = drmSystemOptions.sessionTypes) != null && _drmSystemOptions$ses.some((type) => type === "persistent-license"));
  6000. }
  6001. function parsePlayReadyWRM(keyBytes) {
  6002. const keyBytesUtf16 = new Uint16Array(keyBytes.buffer, keyBytes.byteOffset, keyBytes.byteLength / 2);
  6003. const keyByteStr = String.fromCharCode.apply(null, Array.from(keyBytesUtf16));
  6004. const xmlKeyBytes = keyByteStr.substring(keyByteStr.indexOf("<"), keyByteStr.length);
  6005. const parser = new DOMParser();
  6006. const xmlDoc = parser.parseFromString(xmlKeyBytes, "text/xml");
  6007. const keyData = xmlDoc.getElementsByTagName("KID")[0];
  6008. if (keyData) {
  6009. const keyId = keyData.childNodes[0] ? keyData.childNodes[0].nodeValue : keyData.getAttribute("VALUE");
  6010. if (keyId) {
  6011. const keyIdArray = base64Decode(keyId).subarray(0, 16);
  6012. changeEndianness(keyIdArray);
  6013. return keyIdArray;
  6014. }
  6015. }
  6016. return null;
  6017. }
  6018. var keyUriToKeyIdMap = {};
  6019. var LevelKey = class _LevelKey {
  6020. static clearKeyUriToKeyIdMap() {
  6021. keyUriToKeyIdMap = {};
  6022. }
  6023. constructor(method, uri, format2, formatversions = [1], iv = null, keyId) {
  6024. this.uri = void 0;
  6025. this.method = void 0;
  6026. this.keyFormat = void 0;
  6027. this.keyFormatVersions = void 0;
  6028. this.encrypted = void 0;
  6029. this.isCommonEncryption = void 0;
  6030. this.iv = null;
  6031. this.key = null;
  6032. this.keyId = null;
  6033. this.pssh = null;
  6034. this.method = method;
  6035. this.uri = uri;
  6036. this.keyFormat = format2;
  6037. this.keyFormatVersions = formatversions;
  6038. this.iv = iv;
  6039. this.encrypted = method ? method !== "NONE" : false;
  6040. this.isCommonEncryption = this.encrypted && !isFullSegmentEncryption(method);
  6041. if (keyId != null && keyId.startsWith("0x")) {
  6042. this.keyId = new Uint8Array(hexToArrayBuffer(keyId));
  6043. }
  6044. }
  6045. matches(key) {
  6046. var _key$iv, _this$iv;
  6047. return key.uri === this.uri && key.method === this.method && key.encrypted === this.encrypted && key.keyFormat === this.keyFormat && key.keyFormatVersions.join(",") === this.keyFormatVersions.join(",") && ((_key$iv = key.iv) == null ? void 0 : _key$iv.join(",")) === ((_this$iv = this.iv) == null ? void 0 : _this$iv.join(","));
  6048. }
  6049. isSupported() {
  6050. if (this.method) {
  6051. if (isFullSegmentEncryption(this.method) || this.method === "NONE") {
  6052. return true;
  6053. }
  6054. if (this.keyFormat === "identity") {
  6055. return this.method === "SAMPLE-AES";
  6056. } else {
  6057. switch (this.keyFormat) {
  6058. case KeySystemFormats.FAIRPLAY:
  6059. case KeySystemFormats.WIDEVINE:
  6060. case KeySystemFormats.PLAYREADY:
  6061. case KeySystemFormats.CLEARKEY:
  6062. return ["ISO-23001-7", "SAMPLE-AES", "SAMPLE-AES-CENC", "SAMPLE-AES-CTR"].indexOf(this.method) !== -1;
  6063. }
  6064. }
  6065. }
  6066. return false;
  6067. }
  6068. getDecryptData(sn) {
  6069. if (!this.encrypted || !this.uri) {
  6070. return null;
  6071. }
  6072. if (isFullSegmentEncryption(this.method) && this.uri && !this.iv) {
  6073. if (typeof sn !== "number") {
  6074. logger.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`);
  6075. sn = 0;
  6076. }
  6077. const iv = createInitializationVector(sn);
  6078. const decryptdata = new _LevelKey(this.method, this.uri, "identity", this.keyFormatVersions, iv);
  6079. return decryptdata;
  6080. }
  6081. if (this.pssh && this.keyId) {
  6082. return this;
  6083. }
  6084. const keyBytes = convertDataUriToArrayBytes(this.uri);
  6085. if (keyBytes) {
  6086. switch (this.keyFormat) {
  6087. case KeySystemFormats.WIDEVINE:
  6088. this.pssh = keyBytes;
  6089. if (!this.keyId && keyBytes.length >= 22) {
  6090. const offset = keyBytes.length - 22;
  6091. this.keyId = keyBytes.subarray(offset, offset + 16);
  6092. }
  6093. break;
  6094. case KeySystemFormats.PLAYREADY: {
  6095. const PlayReadyKeySystemUUID = new Uint8Array([154, 4, 240, 121, 152, 64, 66, 134, 171, 146, 230, 91, 224, 136, 95, 149]);
  6096. this.pssh = mp4pssh(PlayReadyKeySystemUUID, null, keyBytes);
  6097. this.keyId = parsePlayReadyWRM(keyBytes);
  6098. break;
  6099. }
  6100. default: {
  6101. let keydata = keyBytes.subarray(0, 16);
  6102. if (keydata.length !== 16) {
  6103. const padded = new Uint8Array(16);
  6104. padded.set(keydata, 16 - keydata.length);
  6105. keydata = padded;
  6106. }
  6107. this.keyId = keydata;
  6108. break;
  6109. }
  6110. }
  6111. }
  6112. if (!this.keyId || this.keyId.byteLength !== 16) {
  6113. let keyId = keyUriToKeyIdMap[this.uri];
  6114. if (!keyId) {
  6115. const val = Object.keys(keyUriToKeyIdMap).length % Number.MAX_SAFE_INTEGER;
  6116. keyId = new Uint8Array(16);
  6117. const dv = new DataView(keyId.buffer, 12, 4);
  6118. dv.setUint32(0, val);
  6119. keyUriToKeyIdMap[this.uri] = keyId;
  6120. }
  6121. this.keyId = keyId;
  6122. }
  6123. return this;
  6124. }
  6125. };
  6126. function createInitializationVector(segmentNumber) {
  6127. const uint8View = new Uint8Array(16);
  6128. for (let i = 12; i < 16; i++) {
  6129. uint8View[i] = segmentNumber >> 8 * (15 - i) & 255;
  6130. }
  6131. return uint8View;
  6132. }
  6133. var MASTER_PLAYLIST_REGEX = /#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;
  6134. var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  6135. var IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m;
  6136. var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([
  6137. /#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,
  6138. // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  6139. /(?!#) *(\S[^\r\n]*)/.source,
  6140. // segment URI, group 3 => the URI (note newline is not eaten)
  6141. /#.*/.source
  6142. // All other non-segment oriented tags will match with all groups empty
  6143. ].join("|"), "g");
  6144. var LEVEL_PLAYLIST_REGEX_SLOW = 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("|"));
  6145. var M3U8Parser = class _M3U8Parser {
  6146. static findGroup(groups, mediaGroupId) {
  6147. for (let i = 0; i < groups.length; i++) {
  6148. const group = groups[i];
  6149. if (group.id === mediaGroupId) {
  6150. return group;
  6151. }
  6152. }
  6153. }
  6154. static resolve(url, baseUrl) {
  6155. return urlToolkitExports.buildAbsoluteURL(baseUrl, url, {
  6156. alwaysNormalize: true
  6157. });
  6158. }
  6159. static isMediaPlaylist(str) {
  6160. return IS_MEDIA_PLAYLIST.test(str);
  6161. }
  6162. static parseMasterPlaylist(string, baseurl) {
  6163. const hasVariableRefs = hasVariableReferences(string);
  6164. const parsed = {
  6165. contentSteering: null,
  6166. levels: [],
  6167. playlistParsingError: null,
  6168. sessionData: null,
  6169. sessionKeys: null,
  6170. startTimeOffset: null,
  6171. variableList: null,
  6172. hasVariableRefs
  6173. };
  6174. const levelsWithKnownCodecs = [];
  6175. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  6176. let result;
  6177. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  6178. if (result[1]) {
  6179. var _level$unknownCodecs;
  6180. const attrs = new AttrList(result[1], parsed);
  6181. const uri = substituteVariables(parsed, result[2]);
  6182. const level = {
  6183. attrs,
  6184. bitrate: attrs.decimalInteger("BANDWIDTH") || attrs.decimalInteger("AVERAGE-BANDWIDTH"),
  6185. name: attrs.NAME,
  6186. url: _M3U8Parser.resolve(uri, baseurl)
  6187. };
  6188. const resolution = attrs.decimalResolution("RESOLUTION");
  6189. if (resolution) {
  6190. level.width = resolution.width;
  6191. level.height = resolution.height;
  6192. }
  6193. setCodecs(attrs.CODECS, level);
  6194. const supplementalCodecs = attrs["SUPPLEMENTAL-CODECS"];
  6195. if (supplementalCodecs) {
  6196. level.supplemental = {};
  6197. setCodecs(supplementalCodecs, level.supplemental);
  6198. }
  6199. if (!((_level$unknownCodecs = level.unknownCodecs) != null && _level$unknownCodecs.length)) {
  6200. levelsWithKnownCodecs.push(level);
  6201. }
  6202. parsed.levels.push(level);
  6203. } else if (result[3]) {
  6204. const tag = result[3];
  6205. const attributes = result[4];
  6206. switch (tag) {
  6207. case "SESSION-DATA": {
  6208. const sessionAttrs = new AttrList(attributes, parsed);
  6209. const dataId = sessionAttrs["DATA-ID"];
  6210. if (dataId) {
  6211. if (parsed.sessionData === null) {
  6212. parsed.sessionData = {};
  6213. }
  6214. parsed.sessionData[dataId] = sessionAttrs;
  6215. }
  6216. break;
  6217. }
  6218. case "SESSION-KEY": {
  6219. const sessionKey = parseKey(attributes, baseurl, parsed);
  6220. if (sessionKey.encrypted && sessionKey.isSupported()) {
  6221. if (parsed.sessionKeys === null) {
  6222. parsed.sessionKeys = [];
  6223. }
  6224. parsed.sessionKeys.push(sessionKey);
  6225. } else {
  6226. logger.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${attributes}"`);
  6227. }
  6228. break;
  6229. }
  6230. case "DEFINE": {
  6231. {
  6232. const variableAttributes = new AttrList(attributes, parsed);
  6233. addVariableDefinition(parsed, variableAttributes, baseurl);
  6234. }
  6235. break;
  6236. }
  6237. case "CONTENT-STEERING": {
  6238. const contentSteeringAttributes = new AttrList(attributes, parsed);
  6239. parsed.contentSteering = {
  6240. uri: _M3U8Parser.resolve(contentSteeringAttributes["SERVER-URI"], baseurl),
  6241. pathwayId: contentSteeringAttributes["PATHWAY-ID"] || "."
  6242. };
  6243. break;
  6244. }
  6245. case "START": {
  6246. parsed.startTimeOffset = parseStartTimeOffset(attributes);
  6247. break;
  6248. }
  6249. }
  6250. }
  6251. }
  6252. const stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < parsed.levels.length;
  6253. parsed.levels = stripUnknownCodecLevels ? levelsWithKnownCodecs : parsed.levels;
  6254. if (parsed.levels.length === 0) {
  6255. parsed.playlistParsingError = new Error("no levels found in manifest");
  6256. }
  6257. return parsed;
  6258. }
  6259. static parseMasterPlaylistMedia(string, baseurl, parsed) {
  6260. let result;
  6261. const results = {};
  6262. const levels = parsed.levels;
  6263. const groupsByType = {
  6264. AUDIO: levels.map((level) => ({
  6265. id: level.attrs.AUDIO,
  6266. audioCodec: level.audioCodec
  6267. })),
  6268. SUBTITLES: levels.map((level) => ({
  6269. id: level.attrs.SUBTITLES,
  6270. textCodec: level.textCodec
  6271. })),
  6272. "CLOSED-CAPTIONS": []
  6273. };
  6274. let id = 0;
  6275. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  6276. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  6277. const attrs = new AttrList(result[1], parsed);
  6278. const type = attrs.TYPE;
  6279. if (type) {
  6280. const groups = groupsByType[type];
  6281. const medias = results[type] || [];
  6282. results[type] = medias;
  6283. const lang = attrs.LANGUAGE;
  6284. const assocLang = attrs["ASSOC-LANGUAGE"];
  6285. const channels = attrs.CHANNELS;
  6286. const characteristics = attrs.CHARACTERISTICS;
  6287. const instreamId = attrs["INSTREAM-ID"];
  6288. const media = {
  6289. attrs,
  6290. bitrate: 0,
  6291. id: id++,
  6292. groupId: attrs["GROUP-ID"] || "",
  6293. name: attrs.NAME || lang || "",
  6294. type,
  6295. default: attrs.bool("DEFAULT"),
  6296. autoselect: attrs.bool("AUTOSELECT"),
  6297. forced: attrs.bool("FORCED"),
  6298. lang,
  6299. url: attrs.URI ? _M3U8Parser.resolve(attrs.URI, baseurl) : ""
  6300. };
  6301. if (assocLang) {
  6302. media.assocLang = assocLang;
  6303. }
  6304. if (channels) {
  6305. media.channels = channels;
  6306. }
  6307. if (characteristics) {
  6308. media.characteristics = characteristics;
  6309. }
  6310. if (instreamId) {
  6311. media.instreamId = instreamId;
  6312. }
  6313. if (groups != null && groups.length) {
  6314. const groupCodec = _M3U8Parser.findGroup(groups, media.groupId) || groups[0];
  6315. assignCodec(media, groupCodec, "audioCodec");
  6316. assignCodec(media, groupCodec, "textCodec");
  6317. }
  6318. medias.push(media);
  6319. }
  6320. }
  6321. return results;
  6322. }
  6323. static parseLevelPlaylist(string, baseurl, id, type, levelUrlId, multivariantVariableList) {
  6324. var _LEVEL_PLAYLIST_REGEX;
  6325. const base = {
  6326. url: baseurl
  6327. };
  6328. const level = new LevelDetails(baseurl);
  6329. const fragments = level.fragments;
  6330. const programDateTimes = [];
  6331. let currentInitSegment = null;
  6332. let currentSN = 0;
  6333. let currentPart = 0;
  6334. let totalduration = 0;
  6335. let discontinuityCounter = 0;
  6336. let currentBitrate = 0;
  6337. let prevFrag = null;
  6338. let frag = new Fragment(type, base);
  6339. let result;
  6340. let i;
  6341. let levelkeys;
  6342. let firstPdtIndex = -1;
  6343. let createNextFrag = false;
  6344. let nextByteRange = null;
  6345. let serverControlAttrs;
  6346. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  6347. level.m3u8 = string;
  6348. level.hasVariableRefs = hasVariableReferences(string);
  6349. if (((_LEVEL_PLAYLIST_REGEX = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) == null ? void 0 : _LEVEL_PLAYLIST_REGEX[0]) !== "#EXTM3U") {
  6350. level.playlistParsingError = new Error("Missing format identifier #EXTM3U");
  6351. return level;
  6352. }
  6353. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  6354. if (createNextFrag) {
  6355. createNextFrag = false;
  6356. frag = new Fragment(type, base);
  6357. frag.playlistOffset = totalduration;
  6358. frag.start = totalduration;
  6359. frag.sn = currentSN;
  6360. frag.cc = discontinuityCounter;
  6361. if (currentBitrate) {
  6362. frag.bitrate = currentBitrate;
  6363. }
  6364. frag.level = id;
  6365. if (currentInitSegment) {
  6366. frag.initSegment = currentInitSegment;
  6367. if (currentInitSegment.rawProgramDateTime) {
  6368. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  6369. currentInitSegment.rawProgramDateTime = null;
  6370. }
  6371. if (nextByteRange) {
  6372. frag.setByteRange(nextByteRange);
  6373. nextByteRange = null;
  6374. }
  6375. }
  6376. }
  6377. const duration = result[1];
  6378. if (duration) {
  6379. frag.duration = parseFloat(duration);
  6380. const title = (" " + result[2]).slice(1);
  6381. frag.title = title || null;
  6382. frag.tagList.push(title ? ["INF", duration, title] : ["INF", duration]);
  6383. } else if (result[3]) {
  6384. if (isFiniteNumber(frag.duration)) {
  6385. frag.playlistOffset = totalduration;
  6386. frag.start = totalduration;
  6387. if (levelkeys) {
  6388. setFragLevelKeys(frag, levelkeys, level);
  6389. }
  6390. frag.sn = currentSN;
  6391. frag.level = id;
  6392. frag.cc = discontinuityCounter;
  6393. fragments.push(frag);
  6394. const uri = (" " + result[3]).slice(1);
  6395. frag.relurl = substituteVariables(level, uri);
  6396. assignProgramDateTime(frag, prevFrag, programDateTimes);
  6397. prevFrag = frag;
  6398. totalduration += frag.duration;
  6399. currentSN++;
  6400. currentPart = 0;
  6401. createNextFrag = true;
  6402. }
  6403. } else {
  6404. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  6405. if (!result) {
  6406. logger.warn("No matches on slow regex match for level playlist!");
  6407. continue;
  6408. }
  6409. for (i = 1; i < result.length; i++) {
  6410. if (result[i] !== void 0) {
  6411. break;
  6412. }
  6413. }
  6414. const tag = (" " + result[i]).slice(1);
  6415. const value1 = (" " + result[i + 1]).slice(1);
  6416. const value2 = result[i + 2] ? (" " + result[i + 2]).slice(1) : null;
  6417. switch (tag) {
  6418. case "BYTERANGE":
  6419. if (prevFrag) {
  6420. frag.setByteRange(value1, prevFrag);
  6421. } else {
  6422. frag.setByteRange(value1);
  6423. }
  6424. break;
  6425. case "PROGRAM-DATE-TIME":
  6426. frag.rawProgramDateTime = value1;
  6427. frag.tagList.push(["PROGRAM-DATE-TIME", value1]);
  6428. if (firstPdtIndex === -1) {
  6429. firstPdtIndex = fragments.length;
  6430. }
  6431. break;
  6432. case "PLAYLIST-TYPE":
  6433. if (level.type) {
  6434. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6435. }
  6436. level.type = value1.toUpperCase();
  6437. break;
  6438. case "MEDIA-SEQUENCE":
  6439. if (level.startSN !== 0) {
  6440. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6441. } else if (fragments.length > 0) {
  6442. assignMustAppearBeforeSegmentsError(level, tag, result);
  6443. }
  6444. currentSN = level.startSN = parseInt(value1);
  6445. break;
  6446. case "SKIP": {
  6447. if (level.skippedSegments) {
  6448. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6449. }
  6450. const skipAttrs = new AttrList(value1, level);
  6451. const skippedSegments = skipAttrs.decimalInteger("SKIPPED-SEGMENTS");
  6452. if (isFiniteNumber(skippedSegments)) {
  6453. level.skippedSegments += skippedSegments;
  6454. for (let _i = skippedSegments; _i--; ) {
  6455. fragments.push(null);
  6456. }
  6457. currentSN += skippedSegments;
  6458. }
  6459. const recentlyRemovedDateranges = skipAttrs.enumeratedString("RECENTLY-REMOVED-DATERANGES");
  6460. if (recentlyRemovedDateranges) {
  6461. level.recentlyRemovedDateranges = (level.recentlyRemovedDateranges || []).concat(recentlyRemovedDateranges.split(" "));
  6462. }
  6463. break;
  6464. }
  6465. case "TARGETDURATION":
  6466. if (level.targetduration !== 0) {
  6467. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6468. }
  6469. level.targetduration = Math.max(parseInt(value1), 1);
  6470. break;
  6471. case "VERSION":
  6472. if (level.version !== null) {
  6473. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6474. }
  6475. level.version = parseInt(value1);
  6476. break;
  6477. case "INDEPENDENT-SEGMENTS":
  6478. break;
  6479. case "ENDLIST":
  6480. if (!level.live) {
  6481. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6482. }
  6483. level.live = false;
  6484. break;
  6485. case "#":
  6486. if (value1 || value2) {
  6487. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  6488. }
  6489. break;
  6490. case "DISCONTINUITY":
  6491. discontinuityCounter++;
  6492. frag.tagList.push(["DIS"]);
  6493. break;
  6494. case "GAP":
  6495. frag.gap = true;
  6496. frag.tagList.push([tag]);
  6497. break;
  6498. case "BITRATE":
  6499. frag.tagList.push([tag, value1]);
  6500. currentBitrate = parseInt(value1) * 1e3;
  6501. if (isFiniteNumber(currentBitrate)) {
  6502. frag.bitrate = currentBitrate;
  6503. } else {
  6504. currentBitrate = 0;
  6505. }
  6506. break;
  6507. case "DATERANGE": {
  6508. const dateRangeAttr = new AttrList(value1, level);
  6509. const dateRange = new DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID], level.dateRangeTagCount);
  6510. level.dateRangeTagCount++;
  6511. if (dateRange.isValid || level.skippedSegments) {
  6512. level.dateRanges[dateRange.id] = dateRange;
  6513. } else {
  6514. logger.warn(`Ignoring invalid DATERANGE tag: "${value1}"`);
  6515. }
  6516. frag.tagList.push(["EXT-X-DATERANGE", value1]);
  6517. break;
  6518. }
  6519. case "DEFINE": {
  6520. {
  6521. const variableAttributes = new AttrList(value1, level);
  6522. if ("IMPORT" in variableAttributes) {
  6523. importVariableDefinition(level, variableAttributes, multivariantVariableList);
  6524. } else {
  6525. addVariableDefinition(level, variableAttributes, baseurl);
  6526. }
  6527. }
  6528. break;
  6529. }
  6530. case "DISCONTINUITY-SEQUENCE":
  6531. if (level.startCC !== 0) {
  6532. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6533. } else if (fragments.length > 0) {
  6534. assignMustAppearBeforeSegmentsError(level, tag, result);
  6535. }
  6536. level.startCC = discontinuityCounter = parseInt(value1);
  6537. break;
  6538. case "KEY": {
  6539. const levelKey = parseKey(value1, baseurl, level);
  6540. if (levelKey.isSupported()) {
  6541. if (levelKey.method === "NONE") {
  6542. levelkeys = void 0;
  6543. break;
  6544. }
  6545. if (!levelkeys) {
  6546. levelkeys = {};
  6547. }
  6548. const currentKey = levelkeys[levelKey.keyFormat];
  6549. if (!(currentKey != null && currentKey.matches(levelKey))) {
  6550. if (currentKey) {
  6551. levelkeys = _extends({}, levelkeys);
  6552. }
  6553. levelkeys[levelKey.keyFormat] = levelKey;
  6554. }
  6555. } else {
  6556. logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${value1}"`);
  6557. }
  6558. break;
  6559. }
  6560. case "START":
  6561. level.startTimeOffset = parseStartTimeOffset(value1);
  6562. break;
  6563. case "MAP": {
  6564. const mapAttrs = new AttrList(value1, level);
  6565. if (frag.duration) {
  6566. const init = new Fragment(type, base);
  6567. setInitSegment(init, mapAttrs, id, levelkeys);
  6568. currentInitSegment = init;
  6569. frag.initSegment = currentInitSegment;
  6570. if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) {
  6571. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  6572. }
  6573. } else {
  6574. const end = frag.byteRangeEndOffset;
  6575. if (end) {
  6576. const start = frag.byteRangeStartOffset;
  6577. nextByteRange = `${end - start}@${start}`;
  6578. } else {
  6579. nextByteRange = null;
  6580. }
  6581. setInitSegment(frag, mapAttrs, id, levelkeys);
  6582. currentInitSegment = frag;
  6583. createNextFrag = true;
  6584. }
  6585. currentInitSegment.cc = discontinuityCounter;
  6586. break;
  6587. }
  6588. case "SERVER-CONTROL": {
  6589. if (serverControlAttrs) {
  6590. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6591. }
  6592. serverControlAttrs = new AttrList(value1);
  6593. level.canBlockReload = serverControlAttrs.bool("CAN-BLOCK-RELOAD");
  6594. level.canSkipUntil = serverControlAttrs.optionalFloat("CAN-SKIP-UNTIL", 0);
  6595. level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool("CAN-SKIP-DATERANGES");
  6596. level.partHoldBack = serverControlAttrs.optionalFloat("PART-HOLD-BACK", 0);
  6597. level.holdBack = serverControlAttrs.optionalFloat("HOLD-BACK", 0);
  6598. break;
  6599. }
  6600. case "PART-INF": {
  6601. if (level.partTarget) {
  6602. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6603. }
  6604. const partInfAttrs = new AttrList(value1);
  6605. level.partTarget = partInfAttrs.decimalFloatingPoint("PART-TARGET");
  6606. break;
  6607. }
  6608. case "PART": {
  6609. let partList = level.partList;
  6610. if (!partList) {
  6611. partList = level.partList = [];
  6612. }
  6613. const previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : void 0;
  6614. const index = currentPart++;
  6615. const partAttrs = new AttrList(value1, level);
  6616. const part = new Part(partAttrs, frag, base, index, previousFragmentPart);
  6617. partList.push(part);
  6618. frag.duration += part.duration;
  6619. break;
  6620. }
  6621. case "PRELOAD-HINT": {
  6622. const preloadHintAttrs = new AttrList(value1, level);
  6623. level.preloadHint = preloadHintAttrs;
  6624. break;
  6625. }
  6626. case "RENDITION-REPORT": {
  6627. const renditionReportAttrs = new AttrList(value1, level);
  6628. level.renditionReports = level.renditionReports || [];
  6629. level.renditionReports.push(renditionReportAttrs);
  6630. break;
  6631. }
  6632. default:
  6633. logger.warn(`line parsed but not handled: ${result}`);
  6634. break;
  6635. }
  6636. }
  6637. }
  6638. if (prevFrag && !prevFrag.relurl) {
  6639. fragments.pop();
  6640. totalduration -= prevFrag.duration;
  6641. if (level.partList) {
  6642. level.fragmentHint = prevFrag;
  6643. }
  6644. } else if (level.partList) {
  6645. assignProgramDateTime(frag, prevFrag, programDateTimes);
  6646. frag.cc = discontinuityCounter;
  6647. level.fragmentHint = frag;
  6648. if (levelkeys) {
  6649. setFragLevelKeys(frag, levelkeys, level);
  6650. }
  6651. }
  6652. if (!level.targetduration) {
  6653. level.playlistParsingError = new Error(`#EXT-X-TARGETDURATION is required`);
  6654. }
  6655. const fragmentLength = fragments.length;
  6656. const firstFragment = fragments[0];
  6657. const lastFragment = fragments[fragmentLength - 1];
  6658. totalduration += level.skippedSegments * level.targetduration;
  6659. if (totalduration > 0 && fragmentLength && lastFragment) {
  6660. level.averagetargetduration = totalduration / fragmentLength;
  6661. const lastSn = lastFragment.sn;
  6662. level.endSN = lastSn !== "initSegment" ? lastSn : 0;
  6663. if (!level.live) {
  6664. lastFragment.endList = true;
  6665. }
  6666. if (firstFragment && level.startCC === void 0) {
  6667. level.startCC = firstFragment.cc;
  6668. }
  6669. if (firstPdtIndex > 0) {
  6670. backfillProgramDateTimes(fragments, firstPdtIndex);
  6671. if (firstFragment) {
  6672. programDateTimes.unshift(firstFragment);
  6673. }
  6674. }
  6675. } else {
  6676. level.endSN = 0;
  6677. level.startCC = 0;
  6678. }
  6679. if (level.fragmentHint) {
  6680. totalduration += level.fragmentHint.duration;
  6681. }
  6682. level.totalduration = totalduration;
  6683. if (programDateTimes.length && level.dateRangeTagCount && firstFragment) {
  6684. mapDateRanges(programDateTimes, level);
  6685. }
  6686. level.endCC = discontinuityCounter;
  6687. return level;
  6688. }
  6689. };
  6690. function mapDateRanges(programDateTimes, details) {
  6691. const programDateTimeCount = programDateTimes.length;
  6692. if (!programDateTimeCount) {
  6693. return;
  6694. }
  6695. const lastProgramDateTime = programDateTimes[programDateTimeCount - 1];
  6696. const playlistEnd = details.live ? Infinity : details.totalduration;
  6697. const dateRangeIds = Object.keys(details.dateRanges);
  6698. for (let i = dateRangeIds.length; i--; ) {
  6699. const dateRange = details.dateRanges[dateRangeIds[i]];
  6700. const startDateTime = dateRange.startDate.getTime();
  6701. dateRange.tagAnchor = lastProgramDateTime.ref;
  6702. for (let j = programDateTimeCount; j--; ) {
  6703. const fragIndex = findFragmentWithStartDate(details, startDateTime, programDateTimes, j, playlistEnd);
  6704. if (fragIndex !== -1) {
  6705. dateRange.tagAnchor = details.fragments[fragIndex].ref;
  6706. break;
  6707. }
  6708. }
  6709. }
  6710. }
  6711. function findFragmentWithStartDate(details, startDateTime, programDateTimes, index, endTime) {
  6712. const pdtFragment = programDateTimes[index];
  6713. if (pdtFragment) {
  6714. const pdtStart = pdtFragment.programDateTime;
  6715. if (startDateTime >= pdtStart || index === 0) {
  6716. var _programDateTimes;
  6717. const durationBetweenPdt = (((_programDateTimes = programDateTimes[index + 1]) == null ? void 0 : _programDateTimes.start) || endTime) - pdtFragment.start;
  6718. if (startDateTime <= pdtStart + durationBetweenPdt * 1e3) {
  6719. const startIndex = programDateTimes[index].sn - details.startSN;
  6720. const fragments = details.fragments;
  6721. if (fragments.length > programDateTimes.length) {
  6722. const endSegment = programDateTimes[index + 1] || fragments[fragments.length - 1];
  6723. const endIndex = endSegment.sn - details.startSN;
  6724. for (let i = endIndex; i > startIndex; i--) {
  6725. const fragStartDateTime = fragments[i].programDateTime;
  6726. if (startDateTime >= fragStartDateTime && startDateTime < fragStartDateTime + fragments[i].duration * 1e3) {
  6727. return i;
  6728. }
  6729. }
  6730. }
  6731. return startIndex;
  6732. }
  6733. }
  6734. }
  6735. return -1;
  6736. }
  6737. function parseKey(keyTagAttributes, baseurl, parsed) {
  6738. var _keyAttrs$METHOD, _keyAttrs$KEYFORMAT;
  6739. const keyAttrs = new AttrList(keyTagAttributes, parsed);
  6740. const decryptmethod = (_keyAttrs$METHOD = keyAttrs.METHOD) != null ? _keyAttrs$METHOD : "";
  6741. const decrypturi = keyAttrs.URI;
  6742. const decryptiv = keyAttrs.hexadecimalInteger("IV");
  6743. const decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;
  6744. const decryptkeyformat = (_keyAttrs$KEYFORMAT = keyAttrs.KEYFORMAT) != null ? _keyAttrs$KEYFORMAT : "identity";
  6745. if (decrypturi && keyAttrs.IV && !decryptiv) {
  6746. logger.error(`Invalid IV: ${keyAttrs.IV}`);
  6747. }
  6748. const resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : "";
  6749. const keyFormatVersions = (decryptkeyformatversions ? decryptkeyformatversions : "1").split("/").map(Number).filter(Number.isFinite);
  6750. return new LevelKey(decryptmethod, resolvedUri, decryptkeyformat, keyFormatVersions, decryptiv, keyAttrs.KEYID);
  6751. }
  6752. function parseStartTimeOffset(startAttributes) {
  6753. const startAttrs = new AttrList(startAttributes);
  6754. const startTimeOffset = startAttrs.decimalFloatingPoint("TIME-OFFSET");
  6755. if (isFiniteNumber(startTimeOffset)) {
  6756. return startTimeOffset;
  6757. }
  6758. return null;
  6759. }
  6760. function setCodecs(codecsAttributeValue, level) {
  6761. let codecs = (codecsAttributeValue || "").split(/[ ,]+/).filter((c) => c);
  6762. ["video", "audio", "text"].forEach((type) => {
  6763. const filtered = codecs.filter((codec) => isCodecType(codec, type));
  6764. if (filtered.length) {
  6765. level[`${type}Codec`] = filtered.map((c) => c.split("/")[0]).join(",");
  6766. codecs = codecs.filter((codec) => filtered.indexOf(codec) === -1);
  6767. }
  6768. });
  6769. level.unknownCodecs = codecs;
  6770. }
  6771. function assignCodec(media, groupItem, codecProperty) {
  6772. const codecValue = groupItem[codecProperty];
  6773. if (codecValue) {
  6774. media[codecProperty] = codecValue;
  6775. }
  6776. }
  6777. function backfillProgramDateTimes(fragments, firstPdtIndex) {
  6778. let fragPrev = fragments[firstPdtIndex];
  6779. for (let i = firstPdtIndex; i--; ) {
  6780. const frag = fragments[i];
  6781. if (!frag) {
  6782. return;
  6783. }
  6784. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1e3;
  6785. fragPrev = frag;
  6786. }
  6787. }
  6788. function assignProgramDateTime(frag, prevFrag, programDateTimes) {
  6789. if (frag.rawProgramDateTime) {
  6790. programDateTimes.push(frag);
  6791. } else if (prevFrag != null && prevFrag.programDateTime) {
  6792. frag.programDateTime = prevFrag.endProgramDateTime;
  6793. }
  6794. }
  6795. function setInitSegment(frag, mapAttrs, id, levelkeys) {
  6796. frag.relurl = mapAttrs.URI;
  6797. if (mapAttrs.BYTERANGE) {
  6798. frag.setByteRange(mapAttrs.BYTERANGE);
  6799. }
  6800. frag.level = id;
  6801. frag.sn = "initSegment";
  6802. if (levelkeys) {
  6803. frag.levelkeys = levelkeys;
  6804. }
  6805. frag.initSegment = null;
  6806. }
  6807. function setFragLevelKeys(frag, levelkeys, level) {
  6808. frag.levelkeys = levelkeys;
  6809. const {
  6810. encryptedFragments
  6811. } = level;
  6812. if ((!encryptedFragments.length || encryptedFragments[encryptedFragments.length - 1].levelkeys !== levelkeys) && Object.keys(levelkeys).some((format2) => levelkeys[format2].isCommonEncryption)) {
  6813. encryptedFragments.push(frag);
  6814. }
  6815. }
  6816. function assignMultipleMediaPlaylistTagOccuranceError(level, tag, result) {
  6817. level.playlistParsingError = new Error(`#EXT-X-${tag} must not appear more than once (${result[0]})`);
  6818. }
  6819. function assignMustAppearBeforeSegmentsError(level, tag, result) {
  6820. level.playlistParsingError = new Error(`#EXT-X-${tag} must appear before the first Media Segment (${result[0]})`);
  6821. }
  6822. function updateFromToPTS(fragFrom, fragTo) {
  6823. const fragToPTS = fragTo.startPTS;
  6824. if (isFiniteNumber(fragToPTS)) {
  6825. let duration = 0;
  6826. let frag;
  6827. if (fragTo.sn > fragFrom.sn) {
  6828. duration = fragToPTS - fragFrom.start;
  6829. frag = fragFrom;
  6830. } else {
  6831. duration = fragFrom.start - fragToPTS;
  6832. frag = fragTo;
  6833. }
  6834. if (frag.duration !== duration) {
  6835. frag.setDuration(duration);
  6836. }
  6837. } else if (fragTo.sn > fragFrom.sn) {
  6838. const contiguous = fragFrom.cc === fragTo.cc;
  6839. if (contiguous && fragFrom.minEndPTS) {
  6840. fragTo.setStart(fragFrom.start + (fragFrom.minEndPTS - fragFrom.start));
  6841. } else {
  6842. fragTo.setStart(fragFrom.start + fragFrom.duration);
  6843. }
  6844. } else {
  6845. fragTo.setStart(Math.max(fragFrom.start - fragTo.duration, 0));
  6846. }
  6847. }
  6848. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  6849. const parsedMediaDuration = endPTS - startPTS;
  6850. if (parsedMediaDuration <= 0) {
  6851. logger.warn("Fragment should have a positive duration", frag);
  6852. endPTS = startPTS + frag.duration;
  6853. endDTS = startDTS + frag.duration;
  6854. }
  6855. let maxStartPTS = startPTS;
  6856. let minEndPTS = endPTS;
  6857. const fragStartPts = frag.startPTS;
  6858. const fragEndPts = frag.endPTS;
  6859. if (isFiniteNumber(fragStartPts)) {
  6860. const deltaPTS = Math.abs(fragStartPts - startPTS);
  6861. if (!isFiniteNumber(frag.deltaPTS)) {
  6862. frag.deltaPTS = deltaPTS;
  6863. } else {
  6864. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  6865. }
  6866. maxStartPTS = Math.max(startPTS, fragStartPts);
  6867. startPTS = Math.min(startPTS, fragStartPts);
  6868. startDTS = Math.min(startDTS, frag.startDTS);
  6869. minEndPTS = Math.min(endPTS, fragEndPts);
  6870. endPTS = Math.max(endPTS, fragEndPts);
  6871. endDTS = Math.max(endDTS, frag.endDTS);
  6872. }
  6873. const drift = startPTS - frag.start;
  6874. if (frag.start !== 0) {
  6875. frag.setStart(startPTS);
  6876. }
  6877. frag.setDuration(endPTS - frag.start);
  6878. frag.startPTS = startPTS;
  6879. frag.maxStartPTS = maxStartPTS;
  6880. frag.startDTS = startDTS;
  6881. frag.endPTS = endPTS;
  6882. frag.minEndPTS = minEndPTS;
  6883. frag.endDTS = endDTS;
  6884. const sn = frag.sn;
  6885. if (!details || sn < details.startSN || sn > details.endSN) {
  6886. return 0;
  6887. }
  6888. let i;
  6889. const fragIdx = sn - details.startSN;
  6890. const fragments = details.fragments;
  6891. fragments[fragIdx] = frag;
  6892. for (i = fragIdx; i > 0; i--) {
  6893. updateFromToPTS(fragments[i], fragments[i - 1]);
  6894. }
  6895. for (i = fragIdx; i < fragments.length - 1; i++) {
  6896. updateFromToPTS(fragments[i], fragments[i + 1]);
  6897. }
  6898. if (details.fragmentHint) {
  6899. updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
  6900. }
  6901. details.PTSKnown = details.alignedSliding = true;
  6902. return drift;
  6903. }
  6904. function mergeDetails(oldDetails, newDetails) {
  6905. if (oldDetails === newDetails) {
  6906. return;
  6907. }
  6908. let currentInitSegment = null;
  6909. const oldFragments = oldDetails.fragments;
  6910. for (let i = oldFragments.length - 1; i >= 0; i--) {
  6911. const oldInit = oldFragments[i].initSegment;
  6912. if (oldInit) {
  6913. currentInitSegment = oldInit;
  6914. break;
  6915. }
  6916. }
  6917. if (oldDetails.fragmentHint) {
  6918. delete oldDetails.fragmentHint.endPTS;
  6919. }
  6920. let PTSFrag;
  6921. mapFragmentIntersection(oldDetails, newDetails, (oldFrag, newFrag, newFragIndex, newFragments2) => {
  6922. if ((!newDetails.startCC || newDetails.skippedSegments) && newFrag.cc !== oldFrag.cc) {
  6923. const ccOffset = oldFrag.cc - newFrag.cc;
  6924. for (let i = newFragIndex; i < newFragments2.length; i++) {
  6925. newFragments2[i].cc += ccOffset;
  6926. }
  6927. newDetails.endCC = newFragments2[newFragments2.length - 1].cc;
  6928. }
  6929. if (isFiniteNumber(oldFrag.startPTS) && isFiniteNumber(oldFrag.endPTS)) {
  6930. newFrag.setStart(newFrag.startPTS = oldFrag.startPTS);
  6931. newFrag.startDTS = oldFrag.startDTS;
  6932. newFrag.maxStartPTS = oldFrag.maxStartPTS;
  6933. newFrag.endPTS = oldFrag.endPTS;
  6934. newFrag.endDTS = oldFrag.endDTS;
  6935. newFrag.minEndPTS = oldFrag.minEndPTS;
  6936. newFrag.setDuration(oldFrag.endPTS - oldFrag.startPTS);
  6937. if (newFrag.duration) {
  6938. PTSFrag = newFrag;
  6939. }
  6940. newDetails.PTSKnown = newDetails.alignedSliding = true;
  6941. }
  6942. if (oldFrag.hasStreams) {
  6943. newFrag.elementaryStreams = oldFrag.elementaryStreams;
  6944. }
  6945. newFrag.loader = oldFrag.loader;
  6946. if (oldFrag.hasStats) {
  6947. newFrag.stats = oldFrag.stats;
  6948. }
  6949. if (oldFrag.initSegment) {
  6950. newFrag.initSegment = oldFrag.initSegment;
  6951. currentInitSegment = oldFrag.initSegment;
  6952. }
  6953. });
  6954. const newFragments = newDetails.fragments;
  6955. const fragmentsToCheck = newDetails.fragmentHint ? newFragments.concat(newDetails.fragmentHint) : newFragments;
  6956. if (currentInitSegment) {
  6957. fragmentsToCheck.forEach((frag) => {
  6958. var _currentInitSegment;
  6959. if (frag && (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) == null ? void 0 : _currentInitSegment.relurl))) {
  6960. frag.initSegment = currentInitSegment;
  6961. }
  6962. });
  6963. }
  6964. if (newDetails.skippedSegments) {
  6965. newDetails.deltaUpdateFailed = newFragments.some((frag) => !frag);
  6966. if (newDetails.deltaUpdateFailed) {
  6967. logger.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");
  6968. for (let i = newDetails.skippedSegments; i--; ) {
  6969. newFragments.shift();
  6970. }
  6971. newDetails.startSN = newFragments[0].sn;
  6972. } else {
  6973. if (newDetails.canSkipDateRanges) {
  6974. newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails);
  6975. }
  6976. const programDateTimes = oldDetails.fragments.filter((frag) => frag.rawProgramDateTime);
  6977. if (oldDetails.hasProgramDateTime && !newDetails.hasProgramDateTime) {
  6978. for (let i = 1; i < fragmentsToCheck.length; i++) {
  6979. if (fragmentsToCheck[i].programDateTime === null) {
  6980. assignProgramDateTime(fragmentsToCheck[i], fragmentsToCheck[i - 1], programDateTimes);
  6981. }
  6982. }
  6983. }
  6984. mapDateRanges(programDateTimes, newDetails);
  6985. }
  6986. newDetails.endCC = newFragments[newFragments.length - 1].cc;
  6987. }
  6988. if (!newDetails.startCC) {
  6989. var _fragPriorToNewStart$;
  6990. const fragPriorToNewStart = getFragmentWithSN(oldDetails, newDetails.startSN - 1);
  6991. newDetails.startCC = (_fragPriorToNewStart$ = fragPriorToNewStart == null ? void 0 : fragPriorToNewStart.cc) != null ? _fragPriorToNewStart$ : newFragments[0].cc;
  6992. }
  6993. mapPartIntersection(oldDetails.partList, newDetails.partList, (oldPart, newPart) => {
  6994. newPart.elementaryStreams = oldPart.elementaryStreams;
  6995. newPart.stats = oldPart.stats;
  6996. });
  6997. if (PTSFrag) {
  6998. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  6999. } else {
  7000. adjustSliding(oldDetails, newDetails);
  7001. }
  7002. if (newFragments.length) {
  7003. newDetails.totalduration = newDetails.edge - newFragments[0].start;
  7004. }
  7005. newDetails.driftStartTime = oldDetails.driftStartTime;
  7006. newDetails.driftStart = oldDetails.driftStart;
  7007. const advancedDateTime = newDetails.advancedDateTime;
  7008. if (newDetails.advanced && advancedDateTime) {
  7009. const edge = newDetails.edge;
  7010. if (!newDetails.driftStart) {
  7011. newDetails.driftStartTime = advancedDateTime;
  7012. newDetails.driftStart = edge;
  7013. }
  7014. newDetails.driftEndTime = advancedDateTime;
  7015. newDetails.driftEnd = edge;
  7016. } else {
  7017. newDetails.driftEndTime = oldDetails.driftEndTime;
  7018. newDetails.driftEnd = oldDetails.driftEnd;
  7019. newDetails.advancedDateTime = oldDetails.advancedDateTime;
  7020. }
  7021. if (newDetails.requestScheduled === -1) {
  7022. newDetails.requestScheduled = oldDetails.requestScheduled;
  7023. }
  7024. }
  7025. function mergeDateRanges(oldDateRanges, newDetails) {
  7026. const {
  7027. dateRanges: deltaDateRanges,
  7028. recentlyRemovedDateranges
  7029. } = newDetails;
  7030. const dateRanges = _extends({}, oldDateRanges);
  7031. if (recentlyRemovedDateranges) {
  7032. recentlyRemovedDateranges.forEach((id) => {
  7033. delete dateRanges[id];
  7034. });
  7035. }
  7036. const mergeIds = Object.keys(dateRanges);
  7037. const mergeCount = mergeIds.length;
  7038. if (mergeCount) {
  7039. Object.keys(deltaDateRanges).forEach((id) => {
  7040. const mergedDateRange = dateRanges[id];
  7041. const dateRange = new DateRange(deltaDateRanges[id].attr, mergedDateRange);
  7042. if (dateRange.isValid) {
  7043. dateRanges[id] = dateRange;
  7044. if (!mergedDateRange) {
  7045. dateRange.tagOrder += mergeCount;
  7046. }
  7047. } else {
  7048. logger.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${stringify(deltaDateRanges[id].attr)}"`);
  7049. }
  7050. });
  7051. }
  7052. return dateRanges;
  7053. }
  7054. function mapPartIntersection(oldParts, newParts, intersectionFn) {
  7055. if (oldParts && newParts) {
  7056. let delta = 0;
  7057. for (let i = 0, len = oldParts.length; i <= len; i++) {
  7058. const oldPart = oldParts[i];
  7059. const newPart = newParts[i + delta];
  7060. if (oldPart && newPart && oldPart.index === newPart.index && oldPart.fragment.sn === newPart.fragment.sn) {
  7061. intersectionFn(oldPart, newPart);
  7062. } else {
  7063. delta--;
  7064. }
  7065. }
  7066. }
  7067. }
  7068. function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
  7069. const skippedSegments = newDetails.skippedSegments;
  7070. const start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
  7071. const end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
  7072. const delta = newDetails.startSN - oldDetails.startSN;
  7073. const newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  7074. const oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
  7075. for (let i = start; i <= end; i++) {
  7076. const oldFrag = oldFrags[delta + i];
  7077. let newFrag = newFrags[i];
  7078. if (skippedSegments && !newFrag && oldFrag) {
  7079. newFrag = newDetails.fragments[i] = oldFrag;
  7080. }
  7081. if (oldFrag && newFrag) {
  7082. intersectionFn(oldFrag, newFrag, i, newFrags);
  7083. if (oldFrag.url && oldFrag.url !== newFrag.url) {
  7084. newDetails.playlistParsingError = getSequenceError(`media sequence mismatch ${newFrag.sn}:`, oldDetails, newDetails, oldFrag, newFrag);
  7085. return;
  7086. } else if (oldFrag.cc !== newFrag.cc) {
  7087. newDetails.playlistParsingError = getSequenceError(`discontinuity sequence mismatch (${oldFrag.cc}!=${newFrag.cc})`, oldDetails, newDetails, oldFrag, newFrag);
  7088. return;
  7089. }
  7090. }
  7091. }
  7092. }
  7093. function getSequenceError(message, oldDetails, newDetails, oldFrag, newFrag) {
  7094. return new Error(`${message} ${newFrag.url}
  7095. Playlist starting @${oldDetails.startSN}
  7096. ${oldDetails.m3u8}
  7097. Playlist starting @${newDetails.startSN}
  7098. ${newDetails.m3u8}`);
  7099. }
  7100. function adjustSliding(oldDetails, newDetails, matchingStableVariantOrRendition = true) {
  7101. const delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
  7102. const oldFragments = oldDetails.fragments;
  7103. const advancedOrStable = delta >= 0;
  7104. let sliding = 0;
  7105. if (advancedOrStable && delta < oldFragments.length) {
  7106. sliding = oldFragments[delta].start;
  7107. } else if (advancedOrStable && newDetails.startSN === oldDetails.endSN + 1) {
  7108. sliding = oldDetails.fragmentEnd;
  7109. } else if (advancedOrStable && matchingStableVariantOrRendition) {
  7110. sliding = oldDetails.fragmentStart + delta * newDetails.levelTargetDuration;
  7111. } else if (!newDetails.skippedSegments && newDetails.fragmentStart === 0) {
  7112. sliding = oldDetails.fragmentStart;
  7113. } else {
  7114. return;
  7115. }
  7116. addSliding(newDetails, sliding);
  7117. }
  7118. function addSliding(details, sliding) {
  7119. if (sliding) {
  7120. const fragments = details.fragments;
  7121. for (let i = details.skippedSegments; i < fragments.length; i++) {
  7122. fragments[i].addStart(sliding);
  7123. }
  7124. if (details.fragmentHint) {
  7125. details.fragmentHint.addStart(sliding);
  7126. }
  7127. }
  7128. }
  7129. function computeReloadInterval(newDetails, distanceToLiveEdgeMs = Infinity) {
  7130. let reloadInterval = 1e3 * newDetails.targetduration;
  7131. if (newDetails.updated) {
  7132. const fragments = newDetails.fragments;
  7133. const liveEdgeMaxTargetDurations = 4;
  7134. if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) {
  7135. const lastSegmentDuration = fragments[fragments.length - 1].duration * 1e3;
  7136. if (lastSegmentDuration < reloadInterval) {
  7137. reloadInterval = lastSegmentDuration;
  7138. }
  7139. }
  7140. } else {
  7141. reloadInterval /= 2;
  7142. }
  7143. return Math.round(reloadInterval);
  7144. }
  7145. function getFragmentWithSN(details, sn, fragCurrent) {
  7146. if (!details) {
  7147. return null;
  7148. }
  7149. let fragment = details.fragments[sn - details.startSN];
  7150. if (fragment) {
  7151. return fragment;
  7152. }
  7153. fragment = details.fragmentHint;
  7154. if (fragment && fragment.sn === sn) {
  7155. return fragment;
  7156. }
  7157. if (sn < details.startSN && fragCurrent && fragCurrent.sn === sn) {
  7158. return fragCurrent;
  7159. }
  7160. return null;
  7161. }
  7162. function getPartWith(details, sn, partIndex) {
  7163. if (!details) {
  7164. return null;
  7165. }
  7166. return findPart(details.partList, sn, partIndex);
  7167. }
  7168. function findPart(partList, sn, partIndex) {
  7169. if (partList) {
  7170. for (let i = partList.length; i--; ) {
  7171. const part = partList[i];
  7172. if (part.index === partIndex && part.fragment.sn === sn) {
  7173. return part;
  7174. }
  7175. }
  7176. }
  7177. return null;
  7178. }
  7179. function reassignFragmentLevelIndexes(levels) {
  7180. levels.forEach((level, index) => {
  7181. var _level$details;
  7182. (_level$details = level.details) == null ? void 0 : _level$details.fragments.forEach((fragment) => {
  7183. fragment.level = index;
  7184. if (fragment.initSegment) {
  7185. fragment.initSegment.level = index;
  7186. }
  7187. });
  7188. });
  7189. }
  7190. function findFirstFragWithCC(fragments, cc) {
  7191. for (let i = 0, len = fragments.length; i < len; i++) {
  7192. var _fragments$i;
  7193. if (((_fragments$i = fragments[i]) == null ? void 0 : _fragments$i.cc) === cc) {
  7194. return fragments[i];
  7195. }
  7196. }
  7197. return null;
  7198. }
  7199. function shouldAlignOnDiscontinuities(refDetails, details) {
  7200. if (refDetails) {
  7201. if (details.startCC < refDetails.endCC && details.endCC > refDetails.startCC) {
  7202. return true;
  7203. }
  7204. }
  7205. return false;
  7206. }
  7207. function adjustFragmentStart(frag, sliding) {
  7208. if (frag) {
  7209. const start = frag.start + sliding;
  7210. frag.start = frag.startPTS = start;
  7211. frag.endPTS = start + frag.duration;
  7212. }
  7213. }
  7214. function adjustSlidingStart(sliding, details) {
  7215. const fragments = details.fragments;
  7216. for (let i = 0, len = fragments.length; i < len; i++) {
  7217. adjustFragmentStart(fragments[i], sliding);
  7218. }
  7219. if (details.fragmentHint) {
  7220. adjustFragmentStart(details.fragmentHint, sliding);
  7221. }
  7222. details.alignedSliding = true;
  7223. }
  7224. function alignStream(switchDetails, details) {
  7225. if (!switchDetails) {
  7226. return;
  7227. }
  7228. alignDiscontinuities(details, switchDetails);
  7229. if (!details.alignedSliding && switchDetails) {
  7230. alignMediaPlaylistByPDT(details, switchDetails);
  7231. }
  7232. if (!details.alignedSliding && switchDetails && !details.skippedSegments) {
  7233. adjustSliding(switchDetails, details, false);
  7234. }
  7235. }
  7236. function alignDiscontinuities(details, refDetails) {
  7237. if (!shouldAlignOnDiscontinuities(refDetails, details)) {
  7238. return;
  7239. }
  7240. const targetCC = Math.min(refDetails.endCC, details.endCC);
  7241. const refFrag = findFirstFragWithCC(refDetails.fragments, targetCC);
  7242. const frag = findFirstFragWithCC(details.fragments, targetCC);
  7243. if (!refFrag || !frag) {
  7244. return;
  7245. }
  7246. logger.log(`Aligning playlist at start of dicontinuity sequence ${targetCC}`);
  7247. const delta = refFrag.start - frag.start;
  7248. adjustSlidingStart(delta, details);
  7249. }
  7250. function alignMediaPlaylistByPDT(details, refDetails) {
  7251. if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
  7252. return;
  7253. }
  7254. const fragments = details.fragments;
  7255. const refFragments = refDetails.fragments;
  7256. if (!fragments.length || !refFragments.length) {
  7257. return;
  7258. }
  7259. let refFrag;
  7260. let frag;
  7261. const targetCC = Math.min(refDetails.endCC, details.endCC);
  7262. if (refDetails.startCC < targetCC && details.startCC < targetCC) {
  7263. refFrag = findFirstFragWithCC(refFragments, targetCC);
  7264. frag = findFirstFragWithCC(fragments, targetCC);
  7265. }
  7266. if (!refFrag || !frag) {
  7267. refFrag = refFragments[Math.floor(refFragments.length / 2)];
  7268. frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.floor(fragments.length / 2)];
  7269. }
  7270. const refPDT = refFrag.programDateTime;
  7271. const targetPDT = frag.programDateTime;
  7272. if (!refPDT || !targetPDT) {
  7273. return;
  7274. }
  7275. const delta = (targetPDT - refPDT) / 1e3 - (frag.start - refFrag.start);
  7276. adjustSlidingStart(delta, details);
  7277. }
  7278. var TimeRanges = {
  7279. toString: function(r) {
  7280. let log = "";
  7281. const len = r.length;
  7282. for (let i = 0; i < len; i++) {
  7283. log += `[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;
  7284. }
  7285. return log;
  7286. }
  7287. };
  7288. var State = {
  7289. STOPPED: "STOPPED",
  7290. IDLE: "IDLE",
  7291. KEY_LOADING: "KEY_LOADING",
  7292. FRAG_LOADING: "FRAG_LOADING",
  7293. FRAG_LOADING_WAITING_RETRY: "FRAG_LOADING_WAITING_RETRY",
  7294. WAITING_TRACK: "WAITING_TRACK",
  7295. PARSING: "PARSING",
  7296. PARSED: "PARSED",
  7297. ENDED: "ENDED",
  7298. ERROR: "ERROR",
  7299. WAITING_INIT_PTS: "WAITING_INIT_PTS",
  7300. WAITING_LEVEL: "WAITING_LEVEL"
  7301. };
  7302. var BaseStreamController = class extends TaskLoop {
  7303. constructor(hls, fragmentTracker, keyLoader, logPrefix, playlistType) {
  7304. super(logPrefix, hls.logger);
  7305. this.hls = void 0;
  7306. this.fragPrevious = null;
  7307. this.fragCurrent = null;
  7308. this.fragmentTracker = void 0;
  7309. this.transmuxer = null;
  7310. this._state = State.STOPPED;
  7311. this.playlistType = void 0;
  7312. this.media = null;
  7313. this.mediaBuffer = null;
  7314. this.config = void 0;
  7315. this.bitrateTest = false;
  7316. this.lastCurrentTime = 0;
  7317. this.nextLoadPosition = 0;
  7318. this.startPosition = 0;
  7319. this.startTimeOffset = null;
  7320. this.retryDate = 0;
  7321. this.levels = null;
  7322. this.fragmentLoader = void 0;
  7323. this.keyLoader = void 0;
  7324. this.levelLastLoaded = null;
  7325. this.startFragRequested = false;
  7326. this.decrypter = void 0;
  7327. this.initPTS = [];
  7328. this.buffering = true;
  7329. this.loadingParts = false;
  7330. this.loopSn = void 0;
  7331. this.onMediaSeeking = () => {
  7332. const {
  7333. config,
  7334. fragCurrent,
  7335. media,
  7336. mediaBuffer,
  7337. state
  7338. } = this;
  7339. const currentTime = media ? media.currentTime : 0;
  7340. const bufferInfo = BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config.maxBufferHole);
  7341. const noFowardBuffer = !bufferInfo.len;
  7342. this.log(`Media seeking to ${isFiniteNumber(currentTime) ? currentTime.toFixed(3) : currentTime}, state: ${state}, ${noFowardBuffer ? "out of" : "in"} buffer`);
  7343. if (this.state === State.ENDED) {
  7344. this.resetLoadingState();
  7345. } else if (fragCurrent) {
  7346. const tolerance = config.maxFragLookUpTolerance;
  7347. const fragStartOffset = fragCurrent.start - tolerance;
  7348. const fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  7349. if (noFowardBuffer || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) {
  7350. const pastFragment = currentTime > fragEndOffset;
  7351. if (currentTime < fragStartOffset || pastFragment) {
  7352. if (pastFragment && fragCurrent.loader) {
  7353. this.log(`Cancelling fragment load for seek (sn: ${fragCurrent.sn})`);
  7354. fragCurrent.abortRequests();
  7355. this.resetLoadingState();
  7356. }
  7357. this.fragPrevious = null;
  7358. }
  7359. }
  7360. }
  7361. if (media) {
  7362. this.fragmentTracker.removeFragmentsInRange(currentTime, Infinity, this.playlistType, true);
  7363. const lastCurrentTime = this.lastCurrentTime;
  7364. if (currentTime > lastCurrentTime) {
  7365. this.lastCurrentTime = currentTime;
  7366. }
  7367. if (!this.loadingParts) {
  7368. const bufferEnd = Math.max(bufferInfo.end, currentTime);
  7369. const shouldLoadParts = this.shouldLoadParts(this.getLevelDetails(), bufferEnd);
  7370. if (shouldLoadParts) {
  7371. this.log(`LL-Part loading ON after seeking to ${currentTime.toFixed(2)} with buffer @${bufferEnd.toFixed(2)}`);
  7372. this.loadingParts = shouldLoadParts;
  7373. }
  7374. }
  7375. }
  7376. if (!this.hls.hasEnoughToStart) {
  7377. this.log(`Setting ${noFowardBuffer ? "startPosition" : "nextLoadPosition"} to ${currentTime} for seek without enough to start`);
  7378. this.nextLoadPosition = currentTime;
  7379. if (noFowardBuffer) {
  7380. this.startPosition = currentTime;
  7381. }
  7382. }
  7383. this.tickImmediate();
  7384. };
  7385. this.onMediaEnded = () => {
  7386. this.log(`setting startPosition to 0 because media ended`);
  7387. this.startPosition = this.lastCurrentTime = 0;
  7388. };
  7389. this.playlistType = playlistType;
  7390. this.hls = hls;
  7391. this.fragmentLoader = new FragmentLoader(hls.config);
  7392. this.keyLoader = keyLoader;
  7393. this.fragmentTracker = fragmentTracker;
  7394. this.config = hls.config;
  7395. this.decrypter = new Decrypter(hls.config);
  7396. }
  7397. registerListeners() {
  7398. const {
  7399. hls
  7400. } = this;
  7401. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  7402. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  7403. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  7404. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  7405. hls.on(Events.ERROR, this.onError, this);
  7406. }
  7407. unregisterListeners() {
  7408. const {
  7409. hls
  7410. } = this;
  7411. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  7412. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  7413. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  7414. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  7415. hls.off(Events.ERROR, this.onError, this);
  7416. }
  7417. doTick() {
  7418. this.onTickEnd();
  7419. }
  7420. onTickEnd() {
  7421. }
  7422. startLoad(startPosition) {
  7423. }
  7424. stopLoad() {
  7425. if (this.state === State.STOPPED) {
  7426. return;
  7427. }
  7428. this.fragmentLoader.abort();
  7429. this.keyLoader.abort(this.playlistType);
  7430. const frag = this.fragCurrent;
  7431. if (frag != null && frag.loader) {
  7432. frag.abortRequests();
  7433. this.fragmentTracker.removeFragment(frag);
  7434. }
  7435. this.resetTransmuxer();
  7436. this.fragCurrent = null;
  7437. this.fragPrevious = null;
  7438. this.clearInterval();
  7439. this.clearNextTick();
  7440. this.state = State.STOPPED;
  7441. }
  7442. get startPositionValue() {
  7443. const {
  7444. nextLoadPosition,
  7445. startPosition
  7446. } = this;
  7447. if (startPosition === -1 && nextLoadPosition) {
  7448. return nextLoadPosition;
  7449. }
  7450. return startPosition;
  7451. }
  7452. get bufferingEnabled() {
  7453. return this.buffering;
  7454. }
  7455. pauseBuffering() {
  7456. this.buffering = false;
  7457. }
  7458. resumeBuffering() {
  7459. this.buffering = true;
  7460. }
  7461. get inFlightFrag() {
  7462. return {
  7463. frag: this.fragCurrent,
  7464. state: this.state
  7465. };
  7466. }
  7467. _streamEnded(bufferInfo, levelDetails) {
  7468. if (levelDetails.live || !this.media) {
  7469. return false;
  7470. }
  7471. const bufferEnd = bufferInfo.end || 0;
  7472. const timelineStart = this.config.timelineOffset || 0;
  7473. if (bufferEnd <= timelineStart) {
  7474. return false;
  7475. }
  7476. const bufferedRanges = bufferInfo.buffered;
  7477. if (this.config.maxBufferHole && bufferedRanges && bufferedRanges.length > 1) {
  7478. bufferInfo = BufferHelper.bufferedInfo(bufferedRanges, bufferInfo.start, 0);
  7479. }
  7480. const nextStart = bufferInfo.nextStart;
  7481. const hasSecondBufferedRange = nextStart && nextStart > timelineStart && nextStart < levelDetails.edge;
  7482. if (hasSecondBufferedRange) {
  7483. return false;
  7484. }
  7485. if (this.media.currentTime < bufferInfo.start) {
  7486. return false;
  7487. }
  7488. const partList = levelDetails.partList;
  7489. if (partList != null && partList.length) {
  7490. const lastPart = partList[partList.length - 1];
  7491. const lastPartBuffered = BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2);
  7492. return lastPartBuffered;
  7493. }
  7494. const playlistType = levelDetails.fragments[levelDetails.fragments.length - 1].type;
  7495. return this.fragmentTracker.isEndListAppended(playlistType);
  7496. }
  7497. getLevelDetails() {
  7498. if (this.levels && this.levelLastLoaded !== null) {
  7499. var _this$levelLastLoaded;
  7500. return (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details;
  7501. }
  7502. }
  7503. get timelineOffset() {
  7504. const configuredTimelineOffset = this.config.timelineOffset;
  7505. if (configuredTimelineOffset) {
  7506. var _this$getLevelDetails;
  7507. return ((_this$getLevelDetails = this.getLevelDetails()) == null ? void 0 : _this$getLevelDetails.appliedTimelineOffset) || configuredTimelineOffset;
  7508. }
  7509. return 0;
  7510. }
  7511. onMediaAttached(event, data) {
  7512. const media = this.media = this.mediaBuffer = data.media;
  7513. media.removeEventListener("seeking", this.onMediaSeeking);
  7514. media.removeEventListener("ended", this.onMediaEnded);
  7515. media.addEventListener("seeking", this.onMediaSeeking);
  7516. media.addEventListener("ended", this.onMediaEnded);
  7517. const config = this.config;
  7518. if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
  7519. this.startLoad(config.startPosition);
  7520. }
  7521. }
  7522. onMediaDetaching(event, data) {
  7523. const transferringMedia = !!data.transferMedia;
  7524. const media = this.media;
  7525. if (media === null) {
  7526. return;
  7527. }
  7528. if (media.ended) {
  7529. this.log("MSE detaching and video ended, reset startPosition");
  7530. this.startPosition = this.lastCurrentTime = 0;
  7531. }
  7532. media.removeEventListener("seeking", this.onMediaSeeking);
  7533. media.removeEventListener("ended", this.onMediaEnded);
  7534. if (this.keyLoader && !transferringMedia) {
  7535. this.keyLoader.detach();
  7536. }
  7537. this.media = this.mediaBuffer = null;
  7538. this.loopSn = void 0;
  7539. if (transferringMedia) {
  7540. this.resetLoadingState();
  7541. this.resetTransmuxer();
  7542. return;
  7543. }
  7544. this.loadingParts = false;
  7545. this.fragmentTracker.removeAllFragments();
  7546. this.stopLoad();
  7547. }
  7548. onManifestLoading() {
  7549. this.initPTS = [];
  7550. this.levels = this.levelLastLoaded = this.fragCurrent = null;
  7551. this.lastCurrentTime = this.startPosition = 0;
  7552. this.startFragRequested = false;
  7553. }
  7554. onError(event, data) {
  7555. }
  7556. onManifestLoaded(event, data) {
  7557. this.startTimeOffset = data.startTimeOffset;
  7558. }
  7559. onHandlerDestroying() {
  7560. this.stopLoad();
  7561. if (this.transmuxer) {
  7562. this.transmuxer.destroy();
  7563. this.transmuxer = null;
  7564. }
  7565. super.onHandlerDestroying();
  7566. this.hls = this.onMediaSeeking = this.onMediaEnded = null;
  7567. }
  7568. onHandlerDestroyed() {
  7569. this.state = State.STOPPED;
  7570. if (this.fragmentLoader) {
  7571. this.fragmentLoader.destroy();
  7572. }
  7573. if (this.keyLoader) {
  7574. this.keyLoader.destroy();
  7575. }
  7576. if (this.decrypter) {
  7577. this.decrypter.destroy();
  7578. }
  7579. this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null;
  7580. super.onHandlerDestroyed();
  7581. }
  7582. loadFragment(frag, level, targetBufferTime) {
  7583. this.startFragRequested = true;
  7584. this._loadFragForPlayback(frag, level, targetBufferTime);
  7585. }
  7586. _loadFragForPlayback(fragment, level, targetBufferTime) {
  7587. const progressCallback = (data) => {
  7588. const frag = data.frag;
  7589. if (this.fragContextChanged(frag)) {
  7590. this.warn(`${frag.type} sn: ${frag.sn}${data.part ? " part: " + data.part.index : ""} of ${this.fragInfo(frag, false, data.part)}) was dropped during download.`);
  7591. this.fragmentTracker.removeFragment(frag);
  7592. return;
  7593. }
  7594. frag.stats.chunkCount++;
  7595. this._handleFragmentLoadProgress(data);
  7596. };
  7597. this._doFragLoad(fragment, level, targetBufferTime, progressCallback).then((data) => {
  7598. if (!data) {
  7599. return;
  7600. }
  7601. const state = this.state;
  7602. const frag = data.frag;
  7603. if (this.fragContextChanged(frag)) {
  7604. if (state === State.FRAG_LOADING || !this.fragCurrent && state === State.PARSING) {
  7605. this.fragmentTracker.removeFragment(frag);
  7606. this.state = State.IDLE;
  7607. }
  7608. return;
  7609. }
  7610. if ("payload" in data) {
  7611. this.log(`Loaded ${frag.type} sn: ${frag.sn} of ${this.playlistLabel()} ${frag.level}`);
  7612. this.hls.trigger(Events.FRAG_LOADED, data);
  7613. }
  7614. this._handleFragmentLoadComplete(data);
  7615. }).catch((reason) => {
  7616. if (this.state === State.STOPPED || this.state === State.ERROR) {
  7617. return;
  7618. }
  7619. this.warn(`Frag error: ${(reason == null ? void 0 : reason.message) || reason}`);
  7620. this.resetFragmentLoading(fragment);
  7621. });
  7622. }
  7623. clearTrackerIfNeeded(frag) {
  7624. var _this$mediaBuffer;
  7625. const {
  7626. fragmentTracker
  7627. } = this;
  7628. const fragState = fragmentTracker.getState(frag);
  7629. if (fragState === FragmentState.APPENDING) {
  7630. const playlistType = frag.type;
  7631. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  7632. const minForwardBufferLength = Math.max(frag.duration, bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength);
  7633. const backtrackFragment = this.backtrackFragment;
  7634. const backtracked = backtrackFragment ? frag.sn - backtrackFragment.sn : 0;
  7635. if (backtracked === 1 || this.reduceMaxBufferLength(minForwardBufferLength, frag.duration)) {
  7636. fragmentTracker.removeFragment(frag);
  7637. }
  7638. } else if (((_this$mediaBuffer = this.mediaBuffer) == null ? void 0 : _this$mediaBuffer.buffered.length) === 0) {
  7639. fragmentTracker.removeAllFragments();
  7640. } else if (fragmentTracker.hasParts(frag.type)) {
  7641. fragmentTracker.detectPartialFragments({
  7642. frag,
  7643. part: null,
  7644. stats: frag.stats,
  7645. id: frag.type
  7646. });
  7647. if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {
  7648. fragmentTracker.removeFragment(frag);
  7649. }
  7650. }
  7651. }
  7652. checkLiveUpdate(details) {
  7653. if (details.updated && !details.live) {
  7654. const lastFragment = details.fragments[details.fragments.length - 1];
  7655. this.fragmentTracker.detectPartialFragments({
  7656. frag: lastFragment,
  7657. part: null,
  7658. stats: lastFragment.stats,
  7659. id: lastFragment.type
  7660. });
  7661. }
  7662. if (!details.fragments[0]) {
  7663. details.deltaUpdateFailed = true;
  7664. }
  7665. }
  7666. waitForLive(levelInfo) {
  7667. const details = levelInfo.details;
  7668. return (details == null ? void 0 : details.live) && details.type !== "EVENT" && (this.levelLastLoaded !== levelInfo || details.expired);
  7669. }
  7670. flushMainBuffer(startOffset, endOffset, type = null) {
  7671. if (!(startOffset - endOffset)) {
  7672. return;
  7673. }
  7674. const flushScope = {
  7675. startOffset,
  7676. endOffset,
  7677. type
  7678. };
  7679. this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);
  7680. }
  7681. _loadInitSegment(fragment, level) {
  7682. this._doFragLoad(fragment, level).then((data) => {
  7683. const frag = data == null ? void 0 : data.frag;
  7684. if (!frag || this.fragContextChanged(frag) || !this.levels) {
  7685. throw new Error("init load aborted");
  7686. }
  7687. return data;
  7688. }).then((data) => {
  7689. const {
  7690. hls
  7691. } = this;
  7692. const {
  7693. frag,
  7694. payload
  7695. } = data;
  7696. const decryptData = frag.decryptdata;
  7697. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
  7698. const startTime = self.performance.now();
  7699. return this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch((err) => {
  7700. hls.trigger(Events.ERROR, {
  7701. type: ErrorTypes.MEDIA_ERROR,
  7702. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  7703. fatal: false,
  7704. error: err,
  7705. reason: err.message,
  7706. frag
  7707. });
  7708. throw err;
  7709. }).then((decryptedData) => {
  7710. const endTime = self.performance.now();
  7711. hls.trigger(Events.FRAG_DECRYPTED, {
  7712. frag,
  7713. payload: decryptedData,
  7714. stats: {
  7715. tstart: startTime,
  7716. tdecrypt: endTime
  7717. }
  7718. });
  7719. data.payload = decryptedData;
  7720. return this.completeInitSegmentLoad(data);
  7721. });
  7722. }
  7723. return this.completeInitSegmentLoad(data);
  7724. }).catch((reason) => {
  7725. if (this.state === State.STOPPED || this.state === State.ERROR) {
  7726. return;
  7727. }
  7728. this.warn(reason);
  7729. this.resetFragmentLoading(fragment);
  7730. });
  7731. }
  7732. completeInitSegmentLoad(data) {
  7733. const {
  7734. levels
  7735. } = this;
  7736. if (!levels) {
  7737. throw new Error("init load aborted, missing levels");
  7738. }
  7739. const stats = data.frag.stats;
  7740. if (this.state !== State.STOPPED) {
  7741. this.state = State.IDLE;
  7742. }
  7743. data.frag.data = new Uint8Array(data.payload);
  7744. stats.parsing.start = stats.buffering.start = self.performance.now();
  7745. stats.parsing.end = stats.buffering.end = self.performance.now();
  7746. this.tick();
  7747. }
  7748. fragContextChanged(frag) {
  7749. const {
  7750. fragCurrent
  7751. } = this;
  7752. return !frag || !fragCurrent || frag.sn !== fragCurrent.sn || frag.level !== fragCurrent.level;
  7753. }
  7754. fragBufferedComplete(frag, part) {
  7755. const media = this.mediaBuffer ? this.mediaBuffer : this.media;
  7756. this.log(`Buffered ${frag.type} sn: ${frag.sn}${part ? " part: " + part.index : ""} of ${this.fragInfo(frag, false, part)} > buffer:${media ? TimeRanges.toString(BufferHelper.getBuffered(media)) : "(detached)"})`);
  7757. if (isMediaFragment(frag)) {
  7758. var _this$levels;
  7759. if (frag.type !== PlaylistLevelType.SUBTITLE) {
  7760. const el = frag.elementaryStreams;
  7761. if (!Object.keys(el).some((type) => !!el[type])) {
  7762. this.state = State.IDLE;
  7763. return;
  7764. }
  7765. }
  7766. const level = (_this$levels = this.levels) == null ? void 0 : _this$levels[frag.level];
  7767. if (level != null && level.fragmentError) {
  7768. this.log(`Resetting level fragment error count of ${level.fragmentError} on frag buffered`);
  7769. level.fragmentError = 0;
  7770. }
  7771. }
  7772. this.state = State.IDLE;
  7773. }
  7774. _handleFragmentLoadComplete(fragLoadedEndData) {
  7775. const {
  7776. transmuxer
  7777. } = this;
  7778. if (!transmuxer) {
  7779. return;
  7780. }
  7781. const {
  7782. frag,
  7783. part,
  7784. partsLoaded
  7785. } = fragLoadedEndData;
  7786. const complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some((fragLoaded) => !fragLoaded);
  7787. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
  7788. transmuxer.flush(chunkMeta);
  7789. }
  7790. _handleFragmentLoadProgress(frag) {
  7791. }
  7792. _doFragLoad(frag, level, targetBufferTime = null, progressCallback) {
  7793. var _frag$decryptdata;
  7794. this.fragCurrent = frag;
  7795. const details = level == null ? void 0 : level.details;
  7796. if (!this.levels || !details) {
  7797. throw new Error(`frag load aborted, missing level${details ? "" : " detail"}s`);
  7798. }
  7799. let keyLoadingPromise = null;
  7800. if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) != null && _frag$decryptdata.key)) {
  7801. this.log(`Loading key for ${frag.sn} of [${details.startSN}-${details.endSN}], ${this.playlistLabel()} ${frag.level}`);
  7802. this.state = State.KEY_LOADING;
  7803. this.fragCurrent = frag;
  7804. keyLoadingPromise = this.keyLoader.load(frag).then((keyLoadedData) => {
  7805. if (!this.fragContextChanged(keyLoadedData.frag)) {
  7806. this.hls.trigger(Events.KEY_LOADED, keyLoadedData);
  7807. if (this.state === State.KEY_LOADING) {
  7808. this.state = State.IDLE;
  7809. }
  7810. return keyLoadedData;
  7811. }
  7812. });
  7813. this.hls.trigger(Events.KEY_LOADING, {
  7814. frag
  7815. });
  7816. if (this.fragCurrent === null) {
  7817. keyLoadingPromise = Promise.reject(new Error(`frag load aborted, context changed in KEY_LOADING`));
  7818. }
  7819. } else if (!frag.encrypted) {
  7820. keyLoadingPromise = this.keyLoader.loadClear(frag, details.encryptedFragments, this.startFragRequested);
  7821. if (keyLoadingPromise) {
  7822. this.log(`[eme] blocking frag load until media-keys acquired`);
  7823. }
  7824. }
  7825. const fragPrevious = this.fragPrevious;
  7826. if (isMediaFragment(frag) && (!fragPrevious || frag.sn !== fragPrevious.sn)) {
  7827. const shouldLoadParts = this.shouldLoadParts(level.details, frag.end);
  7828. if (shouldLoadParts !== this.loadingParts) {
  7829. this.log(`LL-Part loading ${shouldLoadParts ? "ON" : "OFF"} loading sn ${fragPrevious == null ? void 0 : fragPrevious.sn}->${frag.sn}`);
  7830. this.loadingParts = shouldLoadParts;
  7831. }
  7832. }
  7833. targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
  7834. if (this.loadingParts && isMediaFragment(frag)) {
  7835. const partList = details.partList;
  7836. if (partList && progressCallback) {
  7837. if (targetBufferTime > frag.end && details.fragmentHint) {
  7838. frag = details.fragmentHint;
  7839. }
  7840. const partIndex = this.getNextPart(partList, frag, targetBufferTime);
  7841. if (partIndex > -1) {
  7842. const part = partList[partIndex];
  7843. frag = this.fragCurrent = part.fragment;
  7844. this.log(`Loading ${frag.type} sn: ${frag.sn} part: ${part.index} (${partIndex}/${partList.length - 1}) of ${this.fragInfo(frag, false, part)}) cc: ${frag.cc} [${details.startSN}-${details.endSN}], target: ${parseFloat(targetBufferTime.toFixed(3))}`);
  7845. this.nextLoadPosition = part.start + part.duration;
  7846. this.state = State.FRAG_LOADING;
  7847. let _result;
  7848. if (keyLoadingPromise) {
  7849. _result = keyLoadingPromise.then((keyLoadedData) => {
  7850. if (!keyLoadedData || this.fragContextChanged(keyLoadedData.frag)) {
  7851. return null;
  7852. }
  7853. return this.doFragPartsLoad(frag, part, level, progressCallback);
  7854. }).catch((error) => this.handleFragLoadError(error));
  7855. } else {
  7856. _result = this.doFragPartsLoad(frag, part, level, progressCallback).catch((error) => this.handleFragLoadError(error));
  7857. }
  7858. this.hls.trigger(Events.FRAG_LOADING, {
  7859. frag,
  7860. part,
  7861. targetBufferTime
  7862. });
  7863. if (this.fragCurrent === null) {
  7864. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING parts`));
  7865. }
  7866. return _result;
  7867. } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
  7868. return Promise.resolve(null);
  7869. }
  7870. }
  7871. }
  7872. if (isMediaFragment(frag) && this.loadingParts) {
  7873. this.log(`LL-Part loading OFF after next part miss @${targetBufferTime.toFixed(2)}`);
  7874. this.loadingParts = false;
  7875. } else if (!frag.url) {
  7876. return Promise.resolve(null);
  7877. }
  7878. this.log(`Loading ${frag.type} sn: ${frag.sn} of ${this.fragInfo(frag, false)}) cc: ${frag.cc} ${details ? "[" + details.startSN + "-" + details.endSN + "]" : ""}, target: ${parseFloat(targetBufferTime.toFixed(3))}`);
  7879. if (isFiniteNumber(frag.sn) && !this.bitrateTest) {
  7880. this.nextLoadPosition = frag.start + frag.duration;
  7881. }
  7882. this.state = State.FRAG_LOADING;
  7883. const dataOnProgress = this.config.progressive;
  7884. let result;
  7885. if (dataOnProgress && keyLoadingPromise) {
  7886. result = keyLoadingPromise.then((keyLoadedData) => {
  7887. if (!keyLoadedData || this.fragContextChanged(keyLoadedData == null ? void 0 : keyLoadedData.frag)) {
  7888. return null;
  7889. }
  7890. return this.fragmentLoader.load(frag, progressCallback);
  7891. }).catch((error) => this.handleFragLoadError(error));
  7892. } else {
  7893. result = Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : void 0), keyLoadingPromise]).then(([fragLoadedData]) => {
  7894. if (!dataOnProgress && fragLoadedData && progressCallback) {
  7895. progressCallback(fragLoadedData);
  7896. }
  7897. return fragLoadedData;
  7898. }).catch((error) => this.handleFragLoadError(error));
  7899. }
  7900. this.hls.trigger(Events.FRAG_LOADING, {
  7901. frag,
  7902. targetBufferTime
  7903. });
  7904. if (this.fragCurrent === null) {
  7905. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING`));
  7906. }
  7907. return result;
  7908. }
  7909. doFragPartsLoad(frag, fromPart, level, progressCallback) {
  7910. return new Promise((resolve, reject) => {
  7911. var _level$details;
  7912. const partsLoaded = [];
  7913. const initialPartList = (_level$details = level.details) == null ? void 0 : _level$details.partList;
  7914. const loadPart = (part) => {
  7915. this.fragmentLoader.loadPart(frag, part, progressCallback).then((partLoadedData) => {
  7916. partsLoaded[part.index] = partLoadedData;
  7917. const loadedPart = partLoadedData.part;
  7918. this.hls.trigger(Events.FRAG_LOADED, partLoadedData);
  7919. const nextPart = getPartWith(level.details, frag.sn, part.index + 1) || findPart(initialPartList, frag.sn, part.index + 1);
  7920. if (nextPart) {
  7921. loadPart(nextPart);
  7922. } else {
  7923. return resolve({
  7924. frag,
  7925. part: loadedPart,
  7926. partsLoaded
  7927. });
  7928. }
  7929. }).catch(reject);
  7930. };
  7931. loadPart(fromPart);
  7932. });
  7933. }
  7934. handleFragLoadError(error) {
  7935. if ("data" in error) {
  7936. const data = error.data;
  7937. if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) {
  7938. this.handleFragLoadAborted(data.frag, data.part);
  7939. } else {
  7940. this.hls.trigger(Events.ERROR, data);
  7941. }
  7942. } else {
  7943. this.hls.trigger(Events.ERROR, {
  7944. type: ErrorTypes.OTHER_ERROR,
  7945. details: ErrorDetails.INTERNAL_EXCEPTION,
  7946. err: error,
  7947. error,
  7948. fatal: true
  7949. });
  7950. }
  7951. return null;
  7952. }
  7953. _handleTransmuxerFlush(chunkMeta) {
  7954. const context = this.getCurrentContext(chunkMeta);
  7955. if (!context || this.state !== State.PARSING) {
  7956. if (!this.fragCurrent && this.state !== State.STOPPED && this.state !== State.ERROR) {
  7957. this.state = State.IDLE;
  7958. }
  7959. return;
  7960. }
  7961. const {
  7962. frag,
  7963. part,
  7964. level
  7965. } = context;
  7966. const now2 = self.performance.now();
  7967. frag.stats.parsing.end = now2;
  7968. if (part) {
  7969. part.stats.parsing.end = now2;
  7970. }
  7971. const levelDetails = this.getLevelDetails();
  7972. const loadingPartsAtEdge = levelDetails && frag.sn > levelDetails.endSN;
  7973. const shouldLoadParts = loadingPartsAtEdge || this.shouldLoadParts(levelDetails, frag.end);
  7974. if (shouldLoadParts !== this.loadingParts) {
  7975. this.log(`LL-Part loading ${shouldLoadParts ? "ON" : "OFF"} after parsing segment ending @${frag.end.toFixed(2)}`);
  7976. this.loadingParts = shouldLoadParts;
  7977. }
  7978. this.updateLevelTiming(frag, part, level, chunkMeta.partial);
  7979. }
  7980. shouldLoadParts(details, bufferEnd) {
  7981. if (this.config.lowLatencyMode) {
  7982. if (!details) {
  7983. return this.loadingParts;
  7984. }
  7985. if (details != null && details.partList) {
  7986. var _details$fragmentHint;
  7987. const firstPart = details.partList[0];
  7988. const safePartStart = firstPart.end + (((_details$fragmentHint = details.fragmentHint) == null ? void 0 : _details$fragmentHint.duration) || 0);
  7989. if (bufferEnd >= safePartStart) {
  7990. var _this$media;
  7991. const playhead = this.hls.hasEnoughToStart ? ((_this$media = this.media) == null ? void 0 : _this$media.currentTime) || this.lastCurrentTime : this.getLoadPosition();
  7992. if (playhead > firstPart.start - firstPart.fragment.duration) {
  7993. return true;
  7994. }
  7995. }
  7996. }
  7997. }
  7998. return false;
  7999. }
  8000. getCurrentContext(chunkMeta) {
  8001. const {
  8002. levels,
  8003. fragCurrent
  8004. } = this;
  8005. const {
  8006. level: levelIndex,
  8007. sn,
  8008. part: partIndex
  8009. } = chunkMeta;
  8010. if (!(levels != null && levels[levelIndex])) {
  8011. this.warn(`Levels object was unset while buffering fragment ${sn} of ${this.playlistLabel()} ${levelIndex}. The current chunk will not be buffered.`);
  8012. return null;
  8013. }
  8014. const level = levels[levelIndex];
  8015. const levelDetails = level.details;
  8016. const part = partIndex > -1 ? getPartWith(levelDetails, sn, partIndex) : null;
  8017. const frag = part ? part.fragment : getFragmentWithSN(levelDetails, sn, fragCurrent);
  8018. if (!frag) {
  8019. return null;
  8020. }
  8021. if (fragCurrent && fragCurrent !== frag) {
  8022. frag.stats = fragCurrent.stats;
  8023. }
  8024. return {
  8025. frag,
  8026. part,
  8027. level
  8028. };
  8029. }
  8030. bufferFragmentData(data, frag, part, chunkMeta, noBacktracking) {
  8031. var _buffer;
  8032. if (!data || this.state !== State.PARSING) {
  8033. return;
  8034. }
  8035. const {
  8036. data1,
  8037. data2
  8038. } = data;
  8039. let buffer = data1;
  8040. if (data1 && data2) {
  8041. buffer = appendUint8Array(data1, data2);
  8042. }
  8043. if (!((_buffer = buffer) != null && _buffer.length)) {
  8044. return;
  8045. }
  8046. const offsetTimestamp = this.initPTS[frag.cc];
  8047. const offset = offsetTimestamp ? -offsetTimestamp.baseTime / offsetTimestamp.timescale : void 0;
  8048. const segment = {
  8049. type: data.type,
  8050. frag,
  8051. part,
  8052. chunkMeta,
  8053. offset,
  8054. parent: frag.type,
  8055. data: buffer
  8056. };
  8057. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  8058. if (data.dropped && data.independent && !part) {
  8059. if (noBacktracking) {
  8060. return;
  8061. }
  8062. this.flushBufferGap(frag);
  8063. }
  8064. }
  8065. flushBufferGap(frag) {
  8066. const media = this.media;
  8067. if (!media) {
  8068. return;
  8069. }
  8070. if (!BufferHelper.isBuffered(media, media.currentTime)) {
  8071. this.flushMainBuffer(0, frag.start);
  8072. return;
  8073. }
  8074. const currentTime = media.currentTime;
  8075. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  8076. const fragDuration = frag.duration;
  8077. const segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
  8078. const start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
  8079. if (frag.start - start > segmentFraction) {
  8080. this.flushMainBuffer(start, frag.start);
  8081. }
  8082. }
  8083. getFwdBufferInfo(bufferable, type) {
  8084. var _this$media2;
  8085. const pos = this.getLoadPosition();
  8086. if (!isFiniteNumber(pos)) {
  8087. return null;
  8088. }
  8089. const backwardSeek = this.lastCurrentTime > pos;
  8090. const maxBufferHole = backwardSeek || (_this$media2 = this.media) != null && _this$media2.paused ? 0 : this.config.maxBufferHole;
  8091. return this.getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole);
  8092. }
  8093. getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole) {
  8094. const bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);
  8095. if (bufferInfo.len === 0 && bufferInfo.nextStart !== void 0) {
  8096. const bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
  8097. if (bufferedFragAtPos && (bufferInfo.nextStart <= bufferedFragAtPos.end || bufferedFragAtPos.gap)) {
  8098. const gapDuration = Math.max(Math.min(bufferInfo.nextStart, bufferedFragAtPos.end) - pos, maxBufferHole);
  8099. return BufferHelper.bufferInfo(bufferable, pos, gapDuration);
  8100. }
  8101. }
  8102. return bufferInfo;
  8103. }
  8104. getMaxBufferLength(levelBitrate) {
  8105. const {
  8106. config
  8107. } = this;
  8108. let maxBufLen;
  8109. if (levelBitrate) {
  8110. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  8111. } else {
  8112. maxBufLen = config.maxBufferLength;
  8113. }
  8114. return Math.min(maxBufLen, config.maxMaxBufferLength);
  8115. }
  8116. reduceMaxBufferLength(threshold, fragDuration) {
  8117. const config = this.config;
  8118. const minLength = Math.max(Math.min(threshold - fragDuration, config.maxBufferLength), fragDuration);
  8119. const reducedLength = Math.max(threshold - fragDuration * 3, config.maxMaxBufferLength / 2, minLength);
  8120. if (reducedLength >= minLength) {
  8121. config.maxMaxBufferLength = reducedLength;
  8122. this.warn(`Reduce max buffer length to ${reducedLength}s`);
  8123. return true;
  8124. }
  8125. return false;
  8126. }
  8127. getAppendedFrag(position, playlistType = PlaylistLevelType.MAIN) {
  8128. var _this$fragmentTracker;
  8129. const fragOrPart = (_this$fragmentTracker = this.fragmentTracker) == null ? void 0 : _this$fragmentTracker.getAppendedFrag(position, playlistType);
  8130. if (fragOrPart && "fragment" in fragOrPart) {
  8131. return fragOrPart.fragment;
  8132. }
  8133. return fragOrPart;
  8134. }
  8135. getNextFragment(pos, levelDetails) {
  8136. const fragments = levelDetails.fragments;
  8137. const fragLen = fragments.length;
  8138. if (!fragLen) {
  8139. return null;
  8140. }
  8141. const {
  8142. config
  8143. } = this;
  8144. const start = fragments[0].start;
  8145. const canLoadParts = config.lowLatencyMode && !!levelDetails.partList;
  8146. let frag = null;
  8147. if (levelDetails.live) {
  8148. const initialLiveManifestSize = config.initialLiveManifestSize;
  8149. if (fragLen < initialLiveManifestSize) {
  8150. this.warn(`Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`);
  8151. return null;
  8152. }
  8153. if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1 || pos < start) {
  8154. var _frag;
  8155. if (canLoadParts && !this.loadingParts) {
  8156. this.log(`LL-Part loading ON for initial live fragment`);
  8157. this.loadingParts = true;
  8158. }
  8159. frag = this.getInitialLiveFragment(levelDetails);
  8160. const mainStart = this.hls.startPosition;
  8161. const liveSyncPosition = this.hls.liveSyncPosition;
  8162. const startPosition = frag ? (mainStart !== -1 && mainStart >= start ? mainStart : liveSyncPosition) || frag.start : pos;
  8163. this.log(`Setting startPosition to ${startPosition} to match start frag at live edge. mainStart: ${mainStart} liveSyncPosition: ${liveSyncPosition} frag.start: ${(_frag = frag) == null ? void 0 : _frag.start}`);
  8164. this.startPosition = this.nextLoadPosition = startPosition;
  8165. }
  8166. } else if (pos <= start) {
  8167. frag = fragments[0];
  8168. }
  8169. if (!frag) {
  8170. const end = this.loadingParts ? levelDetails.partEnd : levelDetails.fragmentEnd;
  8171. frag = this.getFragmentAtPosition(pos, end, levelDetails);
  8172. }
  8173. let programFrag = this.filterReplacedPrimary(frag, levelDetails);
  8174. if (!programFrag && frag) {
  8175. const curSNIdx = frag.sn - levelDetails.startSN;
  8176. programFrag = this.filterReplacedPrimary(fragments[curSNIdx + 1] || null, levelDetails);
  8177. }
  8178. return this.mapToInitFragWhenRequired(programFrag);
  8179. }
  8180. isLoopLoading(frag, targetBufferTime) {
  8181. const trackerState = this.fragmentTracker.getState(frag);
  8182. return (trackerState === FragmentState.OK || trackerState === FragmentState.PARTIAL && !!frag.gap) && this.nextLoadPosition > targetBufferTime;
  8183. }
  8184. getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, playlistType, maxBufLen) {
  8185. let nextFragment = null;
  8186. if (frag.gap) {
  8187. nextFragment = this.getNextFragment(this.nextLoadPosition, levelDetails);
  8188. if (nextFragment && !nextFragment.gap && bufferInfo.nextStart) {
  8189. const nextbufferInfo = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, bufferInfo.nextStart, playlistType, 0);
  8190. if (nextbufferInfo !== null && bufferInfo.len + nextbufferInfo.len >= maxBufLen) {
  8191. const sn = nextFragment.sn;
  8192. if (this.loopSn !== sn) {
  8193. this.log(`buffer full after gaps in "${playlistType}" playlist starting at sn: ${sn}`);
  8194. this.loopSn = sn;
  8195. }
  8196. return null;
  8197. }
  8198. }
  8199. }
  8200. this.loopSn = void 0;
  8201. return nextFragment;
  8202. }
  8203. get primaryPrefetch() {
  8204. if (interstitialsEnabled(this.hls.config)) {
  8205. var _this$hls$interstitia, _this$hls$interstitia2;
  8206. const playingInterstitial = (_this$hls$interstitia = this.hls.interstitialsManager) == null ? void 0 : (_this$hls$interstitia2 = _this$hls$interstitia.playingItem) == null ? void 0 : _this$hls$interstitia2.event;
  8207. if (playingInterstitial) {
  8208. return true;
  8209. }
  8210. }
  8211. return false;
  8212. }
  8213. filterReplacedPrimary(frag, details) {
  8214. if (!frag) {
  8215. return frag;
  8216. }
  8217. if (interstitialsEnabled(this.hls.config) && frag.type !== PlaylistLevelType.SUBTITLE) {
  8218. const interstitials = this.hls.interstitialsManager;
  8219. const bufferingItem = interstitials == null ? void 0 : interstitials.bufferingItem;
  8220. if (bufferingItem) {
  8221. const bufferingInterstitial = bufferingItem.event;
  8222. if (bufferingInterstitial) {
  8223. if (bufferingInterstitial.appendInPlace || Math.abs(frag.start - bufferingItem.start) > 1 || bufferingItem.start === 0) {
  8224. return null;
  8225. }
  8226. } else {
  8227. if (frag.end <= bufferingItem.start && (details == null ? void 0 : details.live) === false) {
  8228. return null;
  8229. }
  8230. if (frag.start > bufferingItem.end && bufferingItem.nextEvent) {
  8231. if (bufferingItem.nextEvent.appendInPlace || frag.start - bufferingItem.end > 1) {
  8232. return null;
  8233. }
  8234. }
  8235. }
  8236. }
  8237. const playerQueue = interstitials == null ? void 0 : interstitials.playerQueue;
  8238. if (playerQueue) {
  8239. for (let i = playerQueue.length; i--; ) {
  8240. const interstitial = playerQueue[i].interstitial;
  8241. if (interstitial.appendInPlace && frag.start >= interstitial.startTime && frag.end <= interstitial.resumeTime) {
  8242. return null;
  8243. }
  8244. }
  8245. }
  8246. }
  8247. return frag;
  8248. }
  8249. mapToInitFragWhenRequired(frag) {
  8250. if (frag != null && frag.initSegment && !(frag != null && frag.initSegment.data) && !this.bitrateTest) {
  8251. return frag.initSegment;
  8252. }
  8253. return frag;
  8254. }
  8255. getNextPart(partList, frag, targetBufferTime) {
  8256. let nextPart = -1;
  8257. let contiguous = false;
  8258. let independentAttrOmitted = true;
  8259. for (let i = 0, len = partList.length; i < len; i++) {
  8260. const part = partList[i];
  8261. independentAttrOmitted = independentAttrOmitted && !part.independent;
  8262. if (nextPart > -1 && targetBufferTime < part.start) {
  8263. break;
  8264. }
  8265. const loaded = part.loaded;
  8266. if (loaded) {
  8267. nextPart = -1;
  8268. } else if ((contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
  8269. nextPart = i;
  8270. }
  8271. contiguous = loaded;
  8272. }
  8273. return nextPart;
  8274. }
  8275. loadedEndOfParts(partList, targetBufferTime) {
  8276. const lastPart = partList[partList.length - 1];
  8277. return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
  8278. }
  8279. /*
  8280. This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
  8281. "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
  8282. start and end times for each fragment in the playlist (after which this method will not need to be called).
  8283. */
  8284. getInitialLiveFragment(levelDetails) {
  8285. const fragments = levelDetails.fragments;
  8286. const fragPrevious = this.fragPrevious;
  8287. let frag = null;
  8288. if (fragPrevious) {
  8289. if (levelDetails.hasProgramDateTime) {
  8290. this.log(`Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`);
  8291. frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
  8292. }
  8293. if (!frag) {
  8294. const targetSN = fragPrevious.sn + 1;
  8295. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  8296. const fragNext = fragments[targetSN - levelDetails.startSN];
  8297. if (fragPrevious.cc === fragNext.cc) {
  8298. frag = fragNext;
  8299. this.log(`Live playlist, switching playlist, load frag with next SN: ${frag.sn}`);
  8300. }
  8301. }
  8302. if (!frag) {
  8303. frag = findNearestWithCC(levelDetails, fragPrevious.cc, fragPrevious.end);
  8304. if (frag) {
  8305. this.log(`Live playlist, switching playlist, load frag with same CC: ${frag.sn}`);
  8306. }
  8307. }
  8308. }
  8309. } else {
  8310. const liveStart = this.hls.liveSyncPosition;
  8311. if (liveStart !== null) {
  8312. frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
  8313. }
  8314. }
  8315. return frag;
  8316. }
  8317. /*
  8318. This method finds the best matching fragment given the provided position.
  8319. */
  8320. getFragmentAtPosition(bufferEnd, end, levelDetails) {
  8321. const {
  8322. config
  8323. } = this;
  8324. let {
  8325. fragPrevious
  8326. } = this;
  8327. let {
  8328. fragments,
  8329. endSN
  8330. } = levelDetails;
  8331. const {
  8332. fragmentHint
  8333. } = levelDetails;
  8334. const {
  8335. maxFragLookUpTolerance
  8336. } = config;
  8337. const partList = levelDetails.partList;
  8338. const loadingParts = !!(this.loadingParts && partList != null && partList.length && fragmentHint);
  8339. if (loadingParts && fragmentHint && !this.bitrateTest && partList[partList.length - 1].fragment.sn === fragmentHint.sn) {
  8340. fragments = fragments.concat(fragmentHint);
  8341. endSN = fragmentHint.sn;
  8342. }
  8343. let frag;
  8344. if (bufferEnd < end) {
  8345. var _this$media3;
  8346. const backwardSeek = bufferEnd < this.lastCurrentTime;
  8347. const lookupTolerance = backwardSeek || bufferEnd > end - maxFragLookUpTolerance || (_this$media3 = this.media) != null && _this$media3.paused || !this.startFragRequested ? 0 : maxFragLookUpTolerance;
  8348. frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);
  8349. } else {
  8350. frag = fragments[fragments.length - 1];
  8351. }
  8352. if (frag) {
  8353. const curSNIdx = frag.sn - levelDetails.startSN;
  8354. const fragState = this.fragmentTracker.getState(frag);
  8355. if (fragState === FragmentState.OK || fragState === FragmentState.PARTIAL && frag.gap) {
  8356. fragPrevious = frag;
  8357. }
  8358. if (fragPrevious && frag.sn === fragPrevious.sn && (!loadingParts || partList[0].fragment.sn > frag.sn || !levelDetails.live && !loadingParts)) {
  8359. const sameLevel = fragPrevious && frag.level === fragPrevious.level;
  8360. if (sameLevel) {
  8361. const nextFrag = fragments[curSNIdx + 1];
  8362. if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== FragmentState.OK) {
  8363. frag = nextFrag;
  8364. } else {
  8365. frag = null;
  8366. }
  8367. }
  8368. }
  8369. }
  8370. return frag;
  8371. }
  8372. alignPlaylists(details, previousDetails, switchDetails) {
  8373. const length = details.fragments.length;
  8374. if (!length) {
  8375. this.warn(`No fragments in live playlist`);
  8376. return 0;
  8377. }
  8378. const slidingStart = details.fragmentStart;
  8379. const firstLevelLoad = !previousDetails;
  8380. const aligned = details.alignedSliding && isFiniteNumber(slidingStart);
  8381. if (firstLevelLoad || !aligned && !slidingStart) {
  8382. alignStream(switchDetails, details);
  8383. const alignedSlidingStart = details.fragmentStart;
  8384. this.log(`Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${previousDetails ? previousDetails.startSN : "na"}->${details.startSN} fragments: ${length}`);
  8385. return alignedSlidingStart;
  8386. }
  8387. return slidingStart;
  8388. }
  8389. waitForCdnTuneIn(details) {
  8390. const advancePartLimit = 3;
  8391. return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
  8392. }
  8393. setStartPosition(details, sliding) {
  8394. let startPosition = this.startPosition;
  8395. if (startPosition < sliding) {
  8396. startPosition = -1;
  8397. }
  8398. const timelineOffset = this.timelineOffset;
  8399. if (startPosition === -1) {
  8400. const offsetInMultivariantPlaylist = this.startTimeOffset !== null;
  8401. const startTimeOffset = offsetInMultivariantPlaylist ? this.startTimeOffset : details.startTimeOffset;
  8402. if (startTimeOffset !== null && isFiniteNumber(startTimeOffset)) {
  8403. startPosition = sliding + startTimeOffset;
  8404. if (startTimeOffset < 0) {
  8405. startPosition += details.edge;
  8406. }
  8407. startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
  8408. this.log(`Setting startPosition to ${startPosition} for start time offset ${startTimeOffset} found in ${offsetInMultivariantPlaylist ? "multivariant" : "media"} playlist`);
  8409. this.startPosition = startPosition;
  8410. } else if (details.live) {
  8411. startPosition = this.hls.liveSyncPosition || sliding;
  8412. this.log(`Setting startPosition to -1 to start at live edge ${startPosition}`);
  8413. this.startPosition = -1;
  8414. } else {
  8415. this.log(`setting startPosition to 0 by default`);
  8416. this.startPosition = startPosition = 0;
  8417. }
  8418. this.lastCurrentTime = startPosition + timelineOffset;
  8419. }
  8420. this.nextLoadPosition = startPosition + timelineOffset;
  8421. }
  8422. getLoadPosition() {
  8423. var _this$hls;
  8424. const {
  8425. media
  8426. } = this;
  8427. let pos = 0;
  8428. if ((_this$hls = this.hls) != null && _this$hls.hasEnoughToStart && media) {
  8429. pos = media.currentTime;
  8430. } else if (this.nextLoadPosition >= 0) {
  8431. pos = this.nextLoadPosition;
  8432. }
  8433. return pos;
  8434. }
  8435. handleFragLoadAborted(frag, part) {
  8436. if (this.transmuxer && frag.type === this.playlistType && isMediaFragment(frag) && frag.stats.aborted) {
  8437. this.log(`Fragment ${frag.sn}${part ? " part " + part.index : ""} of ${this.playlistLabel()} ${frag.level} was aborted`);
  8438. this.resetFragmentLoading(frag);
  8439. }
  8440. }
  8441. resetFragmentLoading(frag) {
  8442. if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) {
  8443. this.state = State.IDLE;
  8444. }
  8445. }
  8446. onFragmentOrKeyLoadError(filterType, data) {
  8447. if (data.chunkMeta && !data.frag) {
  8448. const context = this.getCurrentContext(data.chunkMeta);
  8449. if (context) {
  8450. data.frag = context.frag;
  8451. }
  8452. }
  8453. const frag = data.frag;
  8454. if (!frag || frag.type !== filterType || !this.levels) {
  8455. return;
  8456. }
  8457. if (this.fragContextChanged(frag)) {
  8458. var _this$fragCurrent;
  8459. this.warn(`Frag load error must match current frag to retry ${frag.url} > ${(_this$fragCurrent = this.fragCurrent) == null ? void 0 : _this$fragCurrent.url}`);
  8460. return;
  8461. }
  8462. const gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;
  8463. if (gapTagEncountered) {
  8464. this.fragmentTracker.fragBuffered(frag, true);
  8465. }
  8466. const errorAction = data.errorAction;
  8467. const {
  8468. action,
  8469. flags,
  8470. retryCount = 0,
  8471. retryConfig
  8472. } = errorAction || {};
  8473. const couldRetry = !!errorAction && !!retryConfig;
  8474. const retry = couldRetry && action === NetworkErrorAction.RetryRequest;
  8475. const noAlternate = couldRetry && !errorAction.resolved && flags === ErrorActionFlags.MoveAllAlternatesMatchingHost;
  8476. if (!retry && noAlternate && isMediaFragment(frag) && !frag.endList) {
  8477. this.resetFragmentErrors(filterType);
  8478. this.treatAsGap(frag);
  8479. errorAction.resolved = true;
  8480. } else if ((retry || noAlternate) && retryCount < retryConfig.maxNumRetry) {
  8481. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  8482. const delay = getRetryDelay(retryConfig, retryCount);
  8483. this.warn(`Fragment ${frag.sn} of ${filterType} ${frag.level} errored with ${data.details}, retrying loading ${retryCount + 1}/${retryConfig.maxNumRetry} in ${delay}ms`);
  8484. errorAction.resolved = true;
  8485. this.retryDate = self.performance.now() + delay;
  8486. this.state = State.FRAG_LOADING_WAITING_RETRY;
  8487. } else if (retryConfig && errorAction) {
  8488. this.resetFragmentErrors(filterType);
  8489. if (retryCount < retryConfig.maxNumRetry) {
  8490. if (!gapTagEncountered && action !== NetworkErrorAction.RemoveAlternatePermanently) {
  8491. errorAction.resolved = true;
  8492. }
  8493. } else {
  8494. this.warn(`${data.details} reached or exceeded max retry (${retryCount})`);
  8495. return;
  8496. }
  8497. } else if (action === NetworkErrorAction.SendAlternateToPenaltyBox) {
  8498. this.state = State.WAITING_LEVEL;
  8499. } else {
  8500. this.state = State.ERROR;
  8501. }
  8502. this.tickImmediate();
  8503. }
  8504. reduceLengthAndFlushBuffer(data) {
  8505. if (this.state === State.PARSING || this.state === State.PARSED) {
  8506. const frag = data.frag;
  8507. const playlistType = data.parent;
  8508. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  8509. const buffered = bufferedInfo && bufferedInfo.len > 0.5;
  8510. if (buffered) {
  8511. this.reduceMaxBufferLength(bufferedInfo.len, (frag == null ? void 0 : frag.duration) || 10);
  8512. }
  8513. const flushBuffer = !buffered;
  8514. if (flushBuffer) {
  8515. this.warn(`Buffer full error while media.currentTime is not buffered, flush ${playlistType} buffer`);
  8516. }
  8517. if (frag) {
  8518. this.fragmentTracker.removeFragment(frag);
  8519. this.nextLoadPosition = frag.start;
  8520. }
  8521. this.resetLoadingState();
  8522. return flushBuffer;
  8523. }
  8524. return false;
  8525. }
  8526. resetFragmentErrors(filterType) {
  8527. if (filterType === PlaylistLevelType.AUDIO) {
  8528. this.fragCurrent = null;
  8529. }
  8530. if (!this.hls.hasEnoughToStart) {
  8531. this.startFragRequested = false;
  8532. }
  8533. if (this.state !== State.STOPPED) {
  8534. this.state = State.IDLE;
  8535. }
  8536. }
  8537. afterBufferFlushed(media, bufferType, playlistType) {
  8538. if (!media) {
  8539. return;
  8540. }
  8541. const bufferedTimeRanges = BufferHelper.getBuffered(media);
  8542. this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
  8543. if (this.state === State.ENDED) {
  8544. this.resetLoadingState();
  8545. }
  8546. }
  8547. resetLoadingState() {
  8548. this.log("Reset loading state");
  8549. this.fragCurrent = null;
  8550. this.fragPrevious = null;
  8551. if (this.state !== State.STOPPED) {
  8552. this.state = State.IDLE;
  8553. }
  8554. }
  8555. resetStartWhenNotLoaded(level) {
  8556. if (!this.hls.hasEnoughToStart) {
  8557. this.startFragRequested = false;
  8558. const details = level ? level.details : null;
  8559. if (details != null && details.live) {
  8560. this.log(`resetting startPosition for live start`);
  8561. this.startPosition = -1;
  8562. this.setStartPosition(details, details.fragmentStart);
  8563. this.resetLoadingState();
  8564. } else {
  8565. this.nextLoadPosition = this.startPosition;
  8566. }
  8567. }
  8568. }
  8569. resetWhenMissingContext(chunkMeta) {
  8570. this.warn(`The loading context changed while buffering fragment ${chunkMeta.sn} of ${this.playlistLabel()} ${chunkMeta.level}. This chunk will not be buffered.`);
  8571. this.removeUnbufferedFrags();
  8572. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  8573. this.resetLoadingState();
  8574. }
  8575. removeUnbufferedFrags(start = 0) {
  8576. this.fragmentTracker.removeFragmentsInRange(start, Infinity, this.playlistType, false, true);
  8577. }
  8578. updateLevelTiming(frag, part, level, partial) {
  8579. const details = level.details;
  8580. if (!details) {
  8581. this.warn("level.details undefined");
  8582. return;
  8583. }
  8584. const parsed = Object.keys(frag.elementaryStreams).reduce((result, type) => {
  8585. const info = frag.elementaryStreams[type];
  8586. if (info) {
  8587. const parsedDuration = info.endPTS - info.startPTS;
  8588. if (parsedDuration <= 0) {
  8589. this.warn(`Could not parse fragment ${frag.sn} ${type} duration reliably (${parsedDuration})`);
  8590. return result || false;
  8591. }
  8592. const drift = partial ? 0 : updateFragPTSDTS(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
  8593. this.hls.trigger(Events.LEVEL_PTS_UPDATED, {
  8594. details,
  8595. level,
  8596. drift,
  8597. type,
  8598. frag,
  8599. start: info.startPTS,
  8600. end: info.endPTS
  8601. });
  8602. return true;
  8603. }
  8604. return result;
  8605. }, false);
  8606. if (!parsed) {
  8607. var _this$transmuxer;
  8608. if (level.fragmentError === 0) {
  8609. this.treatAsGap(frag, level);
  8610. }
  8611. if (((_this$transmuxer = this.transmuxer) == null ? void 0 : _this$transmuxer.error) === null) {
  8612. const error = new Error(`Found no media in fragment ${frag.sn} of ${this.playlistLabel()} ${frag.level} resetting transmuxer to fallback to playlist timing`);
  8613. this.warn(error.message);
  8614. this.hls.trigger(Events.ERROR, {
  8615. type: ErrorTypes.MEDIA_ERROR,
  8616. details: ErrorDetails.FRAG_PARSING_ERROR,
  8617. fatal: false,
  8618. error,
  8619. frag,
  8620. reason: `Found no media in msn ${frag.sn} of ${this.playlistLabel()} "${level.url}"`
  8621. });
  8622. if (!this.hls) {
  8623. return;
  8624. }
  8625. this.resetTransmuxer();
  8626. }
  8627. }
  8628. this.state = State.PARSED;
  8629. this.log(`Parsed ${frag.type} sn: ${frag.sn}${part ? " part: " + part.index : ""} of ${this.fragInfo(frag, false, part)})`);
  8630. this.hls.trigger(Events.FRAG_PARSED, {
  8631. frag,
  8632. part
  8633. });
  8634. }
  8635. playlistLabel() {
  8636. return this.playlistType === PlaylistLevelType.MAIN ? "level" : "track";
  8637. }
  8638. fragInfo(frag, pts = true, part) {
  8639. var _ref, _ref2;
  8640. return `${this.playlistLabel()} ${frag.level} (${part ? "part" : "frag"}:[${((_ref = pts && !part ? frag.startPTS : (part || frag).start) != null ? _ref : NaN).toFixed(3)}-${((_ref2 = pts && !part ? frag.endPTS : (part || frag).end) != null ? _ref2 : NaN).toFixed(3)}]${part && frag.type === "main" ? "INDEPENDENT=" + (part.independent ? "YES" : "NO") : ""}`;
  8641. }
  8642. treatAsGap(frag, level) {
  8643. if (level) {
  8644. level.fragmentError++;
  8645. }
  8646. frag.gap = true;
  8647. this.fragmentTracker.removeFragment(frag);
  8648. this.fragmentTracker.fragBuffered(frag, true);
  8649. }
  8650. resetTransmuxer() {
  8651. var _this$transmuxer2;
  8652. (_this$transmuxer2 = this.transmuxer) == null ? void 0 : _this$transmuxer2.reset();
  8653. }
  8654. recoverWorkerError(data) {
  8655. if (data.event === "demuxerWorker") {
  8656. this.fragmentTracker.removeAllFragments();
  8657. if (this.transmuxer) {
  8658. this.transmuxer.destroy();
  8659. this.transmuxer = null;
  8660. }
  8661. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  8662. this.resetLoadingState();
  8663. }
  8664. }
  8665. set state(nextState) {
  8666. const previousState = this._state;
  8667. if (previousState !== nextState) {
  8668. this._state = nextState;
  8669. this.log(`${previousState}->${nextState}`);
  8670. }
  8671. }
  8672. get state() {
  8673. return this._state;
  8674. }
  8675. };
  8676. function interstitialsEnabled(config) {
  8677. return !!config.interstitialsController && config.enableInterstitialPlayback !== false;
  8678. }
  8679. var ChunkCache = class {
  8680. constructor() {
  8681. this.chunks = [];
  8682. this.dataLength = 0;
  8683. }
  8684. push(chunk) {
  8685. this.chunks.push(chunk);
  8686. this.dataLength += chunk.length;
  8687. }
  8688. flush() {
  8689. const {
  8690. chunks,
  8691. dataLength
  8692. } = this;
  8693. let result;
  8694. if (!chunks.length) {
  8695. return new Uint8Array(0);
  8696. } else if (chunks.length === 1) {
  8697. result = chunks[0];
  8698. } else {
  8699. result = concatUint8Arrays(chunks, dataLength);
  8700. }
  8701. this.reset();
  8702. return result;
  8703. }
  8704. reset() {
  8705. this.chunks.length = 0;
  8706. this.dataLength = 0;
  8707. }
  8708. };
  8709. function concatUint8Arrays(chunks, dataLength) {
  8710. const result = new Uint8Array(dataLength);
  8711. let offset = 0;
  8712. for (let i = 0; i < chunks.length; i++) {
  8713. const chunk = chunks[i];
  8714. result.set(chunk, offset);
  8715. offset += chunk.length;
  8716. }
  8717. return result;
  8718. }
  8719. var eventemitter3 = { exports: {} };
  8720. var hasRequiredEventemitter3;
  8721. function requireEventemitter3() {
  8722. if (hasRequiredEventemitter3)
  8723. return eventemitter3.exports;
  8724. hasRequiredEventemitter3 = 1;
  8725. (function(module) {
  8726. var has = Object.prototype.hasOwnProperty, prefix = "~";
  8727. function Events2() {
  8728. }
  8729. if (Object.create) {
  8730. Events2.prototype = /* @__PURE__ */ Object.create(null);
  8731. if (!new Events2().__proto__)
  8732. prefix = false;
  8733. }
  8734. function EE(fn, context, once) {
  8735. this.fn = fn;
  8736. this.context = context;
  8737. this.once = once || false;
  8738. }
  8739. function addListener(emitter, event, fn, context, once) {
  8740. if (typeof fn !== "function") {
  8741. throw new TypeError("The listener must be a function");
  8742. }
  8743. var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
  8744. if (!emitter._events[evt])
  8745. emitter._events[evt] = listener, emitter._eventsCount++;
  8746. else if (!emitter._events[evt].fn)
  8747. emitter._events[evt].push(listener);
  8748. else
  8749. emitter._events[evt] = [emitter._events[evt], listener];
  8750. return emitter;
  8751. }
  8752. function clearEvent(emitter, evt) {
  8753. if (--emitter._eventsCount === 0)
  8754. emitter._events = new Events2();
  8755. else
  8756. delete emitter._events[evt];
  8757. }
  8758. function EventEmitter2() {
  8759. this._events = new Events2();
  8760. this._eventsCount = 0;
  8761. }
  8762. EventEmitter2.prototype.eventNames = function eventNames() {
  8763. var names = [], events, name;
  8764. if (this._eventsCount === 0)
  8765. return names;
  8766. for (name in events = this._events) {
  8767. if (has.call(events, name))
  8768. names.push(prefix ? name.slice(1) : name);
  8769. }
  8770. if (Object.getOwnPropertySymbols) {
  8771. return names.concat(Object.getOwnPropertySymbols(events));
  8772. }
  8773. return names;
  8774. };
  8775. EventEmitter2.prototype.listeners = function listeners(event) {
  8776. var evt = prefix ? prefix + event : event, handlers = this._events[evt];
  8777. if (!handlers)
  8778. return [];
  8779. if (handlers.fn)
  8780. return [handlers.fn];
  8781. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  8782. ee[i] = handlers[i].fn;
  8783. }
  8784. return ee;
  8785. };
  8786. EventEmitter2.prototype.listenerCount = function listenerCount(event) {
  8787. var evt = prefix ? prefix + event : event, listeners = this._events[evt];
  8788. if (!listeners)
  8789. return 0;
  8790. if (listeners.fn)
  8791. return 1;
  8792. return listeners.length;
  8793. };
  8794. EventEmitter2.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  8795. var evt = prefix ? prefix + event : event;
  8796. if (!this._events[evt])
  8797. return false;
  8798. var listeners = this._events[evt], len = arguments.length, args, i;
  8799. if (listeners.fn) {
  8800. if (listeners.once)
  8801. this.removeListener(event, listeners.fn, void 0, true);
  8802. switch (len) {
  8803. case 1:
  8804. return listeners.fn.call(listeners.context), true;
  8805. case 2:
  8806. return listeners.fn.call(listeners.context, a1), true;
  8807. case 3:
  8808. return listeners.fn.call(listeners.context, a1, a2), true;
  8809. case 4:
  8810. return listeners.fn.call(listeners.context, a1, a2, a3), true;
  8811. case 5:
  8812. return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  8813. case 6:
  8814. return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  8815. }
  8816. for (i = 1, args = new Array(len - 1); i < len; i++) {
  8817. args[i - 1] = arguments[i];
  8818. }
  8819. listeners.fn.apply(listeners.context, args);
  8820. } else {
  8821. var length = listeners.length, j;
  8822. for (i = 0; i < length; i++) {
  8823. if (listeners[i].once)
  8824. this.removeListener(event, listeners[i].fn, void 0, true);
  8825. switch (len) {
  8826. case 1:
  8827. listeners[i].fn.call(listeners[i].context);
  8828. break;
  8829. case 2:
  8830. listeners[i].fn.call(listeners[i].context, a1);
  8831. break;
  8832. case 3:
  8833. listeners[i].fn.call(listeners[i].context, a1, a2);
  8834. break;
  8835. case 4:
  8836. listeners[i].fn.call(listeners[i].context, a1, a2, a3);
  8837. break;
  8838. default:
  8839. if (!args)
  8840. for (j = 1, args = new Array(len - 1); j < len; j++) {
  8841. args[j - 1] = arguments[j];
  8842. }
  8843. listeners[i].fn.apply(listeners[i].context, args);
  8844. }
  8845. }
  8846. }
  8847. return true;
  8848. };
  8849. EventEmitter2.prototype.on = function on(event, fn, context) {
  8850. return addListener(this, event, fn, context, false);
  8851. };
  8852. EventEmitter2.prototype.once = function once(event, fn, context) {
  8853. return addListener(this, event, fn, context, true);
  8854. };
  8855. EventEmitter2.prototype.removeListener = function removeListener(event, fn, context, once) {
  8856. var evt = prefix ? prefix + event : event;
  8857. if (!this._events[evt])
  8858. return this;
  8859. if (!fn) {
  8860. clearEvent(this, evt);
  8861. return this;
  8862. }
  8863. var listeners = this._events[evt];
  8864. if (listeners.fn) {
  8865. if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
  8866. clearEvent(this, evt);
  8867. }
  8868. } else {
  8869. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  8870. if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
  8871. events.push(listeners[i]);
  8872. }
  8873. }
  8874. if (events.length)
  8875. this._events[evt] = events.length === 1 ? events[0] : events;
  8876. else
  8877. clearEvent(this, evt);
  8878. }
  8879. return this;
  8880. };
  8881. EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) {
  8882. var evt;
  8883. if (event) {
  8884. evt = prefix ? prefix + event : event;
  8885. if (this._events[evt])
  8886. clearEvent(this, evt);
  8887. } else {
  8888. this._events = new Events2();
  8889. this._eventsCount = 0;
  8890. }
  8891. return this;
  8892. };
  8893. EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
  8894. EventEmitter2.prototype.addListener = EventEmitter2.prototype.on;
  8895. EventEmitter2.prefixed = prefix;
  8896. EventEmitter2.EventEmitter = EventEmitter2;
  8897. {
  8898. module.exports = EventEmitter2;
  8899. }
  8900. })(eventemitter3);
  8901. return eventemitter3.exports;
  8902. }
  8903. var eventemitter3Exports = requireEventemitter3();
  8904. var EventEmitter = getDefaultExportFromCjs(eventemitter3Exports);
  8905. var version = "1.6.7";
  8906. var workerStore = {};
  8907. function hasUMDWorker() {
  8908. return typeof __HLS_WORKER_BUNDLE__ === "function";
  8909. }
  8910. function injectWorker() {
  8911. const workerContext = workerStore[version];
  8912. if (workerContext) {
  8913. workerContext.clientCount++;
  8914. return workerContext;
  8915. }
  8916. const blob = new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`], {
  8917. type: "text/javascript"
  8918. });
  8919. const objectURL = self.URL.createObjectURL(blob);
  8920. const worker = new self.Worker(objectURL);
  8921. const result = {
  8922. worker,
  8923. objectURL,
  8924. clientCount: 1
  8925. };
  8926. workerStore[version] = result;
  8927. return result;
  8928. }
  8929. function loadWorker(path) {
  8930. const workerContext = workerStore[path];
  8931. if (workerContext) {
  8932. workerContext.clientCount++;
  8933. return workerContext;
  8934. }
  8935. const scriptURL = new self.URL(path, self.location.href).href;
  8936. const worker = new self.Worker(scriptURL);
  8937. const result = {
  8938. worker,
  8939. scriptURL,
  8940. clientCount: 1
  8941. };
  8942. workerStore[path] = result;
  8943. return result;
  8944. }
  8945. function removeWorkerFromStore(path) {
  8946. const workerContext = workerStore[path || version];
  8947. if (workerContext) {
  8948. const clientCount = workerContext.clientCount--;
  8949. if (clientCount === 1) {
  8950. const {
  8951. worker,
  8952. objectURL
  8953. } = workerContext;
  8954. delete workerStore[path || version];
  8955. if (objectURL) {
  8956. self.URL.revokeObjectURL(objectURL);
  8957. }
  8958. worker.terminate();
  8959. }
  8960. }
  8961. }
  8962. function isId3Footer(data, offset) {
  8963. if (offset + 10 <= data.length) {
  8964. if (data[offset] === 51 && data[offset + 1] === 68 && data[offset + 2] === 73) {
  8965. if (data[offset + 3] < 255 && data[offset + 4] < 255) {
  8966. if (data[offset + 6] < 128 && data[offset + 7] < 128 && data[offset + 8] < 128 && data[offset + 9] < 128) {
  8967. return true;
  8968. }
  8969. }
  8970. }
  8971. }
  8972. return false;
  8973. }
  8974. function isId3Header(data, offset) {
  8975. if (offset + 10 <= data.length) {
  8976. if (data[offset] === 73 && data[offset + 1] === 68 && data[offset + 2] === 51) {
  8977. if (data[offset + 3] < 255 && data[offset + 4] < 255) {
  8978. if (data[offset + 6] < 128 && data[offset + 7] < 128 && data[offset + 8] < 128 && data[offset + 9] < 128) {
  8979. return true;
  8980. }
  8981. }
  8982. }
  8983. }
  8984. return false;
  8985. }
  8986. function readId3Size(data, offset) {
  8987. let size = 0;
  8988. size = (data[offset] & 127) << 21;
  8989. size |= (data[offset + 1] & 127) << 14;
  8990. size |= (data[offset + 2] & 127) << 7;
  8991. size |= data[offset + 3] & 127;
  8992. return size;
  8993. }
  8994. function getId3Data(data, offset) {
  8995. const front = offset;
  8996. let length = 0;
  8997. while (isId3Header(data, offset)) {
  8998. length += 10;
  8999. const size = readId3Size(data, offset + 6);
  9000. length += size;
  9001. if (isId3Footer(data, offset + 10)) {
  9002. length += 10;
  9003. }
  9004. offset += length;
  9005. }
  9006. if (length > 0) {
  9007. return data.subarray(front, front + length);
  9008. }
  9009. return void 0;
  9010. }
  9011. function getAudioConfig(observer, data, offset, manifestCodec) {
  9012. const adtsSamplingRates = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350];
  9013. const byte2 = data[offset + 2];
  9014. const adtsSamplingIndex = byte2 >> 2 & 15;
  9015. if (adtsSamplingIndex > 12) {
  9016. const error = new Error(`invalid ADTS sampling index:${adtsSamplingIndex}`);
  9017. observer.emit(Events.ERROR, Events.ERROR, {
  9018. type: ErrorTypes.MEDIA_ERROR,
  9019. details: ErrorDetails.FRAG_PARSING_ERROR,
  9020. fatal: true,
  9021. error,
  9022. reason: error.message
  9023. });
  9024. return;
  9025. }
  9026. const adtsObjectType = (byte2 >> 6 & 3) + 1;
  9027. const channelCount = data[offset + 3] >> 6 & 3 | (byte2 & 1) << 2;
  9028. const codec = "mp4a.40." + adtsObjectType;
  9029. const samplerate = adtsSamplingRates[adtsSamplingIndex];
  9030. let aacSampleIndex = adtsSamplingIndex;
  9031. if (adtsObjectType === 5 || adtsObjectType === 29) {
  9032. aacSampleIndex -= 3;
  9033. }
  9034. const config = [adtsObjectType << 3 | (aacSampleIndex & 14) >> 1, (aacSampleIndex & 1) << 7 | channelCount << 3];
  9035. logger.log(`manifest codec:${manifestCodec}, parsed codec:${codec}, channels:${channelCount}, rate:${samplerate} (ADTS object type:${adtsObjectType} sampling index:${adtsSamplingIndex})`);
  9036. return {
  9037. config,
  9038. samplerate,
  9039. channelCount,
  9040. codec,
  9041. parsedCodec: codec,
  9042. manifestCodec
  9043. };
  9044. }
  9045. function isHeaderPattern$1(data, offset) {
  9046. return data[offset] === 255 && (data[offset + 1] & 246) === 240;
  9047. }
  9048. function getHeaderLength(data, offset) {
  9049. return data[offset + 1] & 1 ? 7 : 9;
  9050. }
  9051. function getFullFrameLength(data, offset) {
  9052. return (data[offset + 3] & 3) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 224) >>> 5;
  9053. }
  9054. function canGetFrameLength(data, offset) {
  9055. return offset + 5 < data.length;
  9056. }
  9057. function isHeader$1(data, offset) {
  9058. return offset + 1 < data.length && isHeaderPattern$1(data, offset);
  9059. }
  9060. function canParse$1(data, offset) {
  9061. return canGetFrameLength(data, offset) && isHeaderPattern$1(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
  9062. }
  9063. function probe$1(data, offset) {
  9064. if (isHeader$1(data, offset)) {
  9065. const headerLength = getHeaderLength(data, offset);
  9066. if (offset + headerLength >= data.length) {
  9067. return false;
  9068. }
  9069. const frameLength = getFullFrameLength(data, offset);
  9070. if (frameLength <= headerLength) {
  9071. return false;
  9072. }
  9073. const newOffset = offset + frameLength;
  9074. return newOffset === data.length || isHeader$1(data, newOffset);
  9075. }
  9076. return false;
  9077. }
  9078. function initTrackConfig(track, observer, data, offset, audioCodec) {
  9079. if (!track.samplerate) {
  9080. const config = getAudioConfig(observer, data, offset, audioCodec);
  9081. if (!config) {
  9082. return;
  9083. }
  9084. _extends(track, config);
  9085. }
  9086. }
  9087. function getFrameDuration(samplerate) {
  9088. return 1024 * 9e4 / samplerate;
  9089. }
  9090. function parseFrameHeader(data, offset) {
  9091. const headerLength = getHeaderLength(data, offset);
  9092. if (offset + headerLength <= data.length) {
  9093. const frameLength = getFullFrameLength(data, offset) - headerLength;
  9094. if (frameLength > 0) {
  9095. return {
  9096. headerLength,
  9097. frameLength
  9098. };
  9099. }
  9100. }
  9101. }
  9102. function appendFrame$2(track, data, offset, pts, frameIndex) {
  9103. const frameDuration = getFrameDuration(track.samplerate);
  9104. const stamp = pts + frameIndex * frameDuration;
  9105. const header = parseFrameHeader(data, offset);
  9106. let unit;
  9107. if (header) {
  9108. const {
  9109. frameLength,
  9110. headerLength
  9111. } = header;
  9112. const _length = headerLength + frameLength;
  9113. const missing = Math.max(0, offset + _length - data.length);
  9114. if (missing) {
  9115. unit = new Uint8Array(_length - headerLength);
  9116. unit.set(data.subarray(offset + headerLength, data.length), 0);
  9117. } else {
  9118. unit = data.subarray(offset + headerLength, offset + _length);
  9119. }
  9120. const _sample = {
  9121. unit,
  9122. pts: stamp
  9123. };
  9124. if (!missing) {
  9125. track.samples.push(_sample);
  9126. }
  9127. return {
  9128. sample: _sample,
  9129. length: _length,
  9130. missing
  9131. };
  9132. }
  9133. const length = data.length - offset;
  9134. unit = new Uint8Array(length);
  9135. unit.set(data.subarray(offset, data.length), 0);
  9136. const sample = {
  9137. unit,
  9138. pts: stamp
  9139. };
  9140. return {
  9141. sample,
  9142. length,
  9143. missing: -1
  9144. };
  9145. }
  9146. function canParseId3(data, offset) {
  9147. return isId3Header(data, offset) && readId3Size(data, offset + 6) + 10 <= data.length - offset;
  9148. }
  9149. function toArrayBuffer(view2) {
  9150. if (view2 instanceof ArrayBuffer) {
  9151. return view2;
  9152. } else {
  9153. if (view2.byteOffset == 0 && view2.byteLength == view2.buffer.byteLength) {
  9154. return view2.buffer;
  9155. }
  9156. return new Uint8Array(view2).buffer;
  9157. }
  9158. }
  9159. function toUint8(data, offset = 0, length = Infinity) {
  9160. return view(data, offset, length, Uint8Array);
  9161. }
  9162. function view(data, offset, length, Type) {
  9163. const buffer = unsafeGetArrayBuffer(data);
  9164. let bytesPerElement = 1;
  9165. if ("BYTES_PER_ELEMENT" in Type) {
  9166. bytesPerElement = Type.BYTES_PER_ELEMENT;
  9167. }
  9168. const dataOffset = isArrayBufferView(data) ? data.byteOffset : 0;
  9169. const dataEnd = (dataOffset + data.byteLength) / bytesPerElement;
  9170. const rawStart = (dataOffset + offset) / bytesPerElement;
  9171. const start = Math.floor(Math.max(0, Math.min(rawStart, dataEnd)));
  9172. const end = Math.floor(Math.min(start + Math.max(length, 0), dataEnd));
  9173. return new Type(buffer, start, end - start);
  9174. }
  9175. function unsafeGetArrayBuffer(view2) {
  9176. if (view2 instanceof ArrayBuffer) {
  9177. return view2;
  9178. } else {
  9179. return view2.buffer;
  9180. }
  9181. }
  9182. function isArrayBufferView(obj) {
  9183. return obj && obj.buffer instanceof ArrayBuffer && obj.byteLength !== void 0 && obj.byteOffset !== void 0;
  9184. }
  9185. function decodeId3ImageFrame(frame) {
  9186. const metadataFrame = {
  9187. key: frame.type,
  9188. description: "",
  9189. data: "",
  9190. mimeType: null,
  9191. pictureType: null
  9192. };
  9193. const utf8Encoding = 3;
  9194. if (frame.size < 2) {
  9195. return void 0;
  9196. }
  9197. if (frame.data[0] !== utf8Encoding) {
  9198. console.log("Ignore frame with unrecognized character encoding");
  9199. return void 0;
  9200. }
  9201. const mimeTypeEndIndex = frame.data.subarray(1).indexOf(0);
  9202. if (mimeTypeEndIndex === -1) {
  9203. return void 0;
  9204. }
  9205. const mimeType = utf8ArrayToStr(toUint8(frame.data, 1, mimeTypeEndIndex));
  9206. const pictureType = frame.data[2 + mimeTypeEndIndex];
  9207. const descriptionEndIndex = frame.data.subarray(3 + mimeTypeEndIndex).indexOf(0);
  9208. if (descriptionEndIndex === -1) {
  9209. return void 0;
  9210. }
  9211. const description = utf8ArrayToStr(toUint8(frame.data, 3 + mimeTypeEndIndex, descriptionEndIndex));
  9212. let data;
  9213. if (mimeType === "-->") {
  9214. data = utf8ArrayToStr(toUint8(frame.data, 4 + mimeTypeEndIndex + descriptionEndIndex));
  9215. } else {
  9216. data = toArrayBuffer(frame.data.subarray(4 + mimeTypeEndIndex + descriptionEndIndex));
  9217. }
  9218. metadataFrame.mimeType = mimeType;
  9219. metadataFrame.pictureType = pictureType;
  9220. metadataFrame.description = description;
  9221. metadataFrame.data = data;
  9222. return metadataFrame;
  9223. }
  9224. function decodeId3PrivFrame(frame) {
  9225. if (frame.size < 2) {
  9226. return void 0;
  9227. }
  9228. const owner = utf8ArrayToStr(frame.data, true);
  9229. const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  9230. return {
  9231. key: frame.type,
  9232. info: owner,
  9233. data: privateData.buffer
  9234. };
  9235. }
  9236. function decodeId3TextFrame(frame) {
  9237. if (frame.size < 2) {
  9238. return void 0;
  9239. }
  9240. if (frame.type === "TXXX") {
  9241. let index = 1;
  9242. const description = utf8ArrayToStr(frame.data.subarray(index), true);
  9243. index += description.length + 1;
  9244. const value = utf8ArrayToStr(frame.data.subarray(index));
  9245. return {
  9246. key: frame.type,
  9247. info: description,
  9248. data: value
  9249. };
  9250. }
  9251. const text = utf8ArrayToStr(frame.data.subarray(1));
  9252. return {
  9253. key: frame.type,
  9254. info: "",
  9255. data: text
  9256. };
  9257. }
  9258. function decodeId3UrlFrame(frame) {
  9259. if (frame.type === "WXXX") {
  9260. if (frame.size < 2) {
  9261. return void 0;
  9262. }
  9263. let index = 1;
  9264. const description = utf8ArrayToStr(frame.data.subarray(index), true);
  9265. index += description.length + 1;
  9266. const value = utf8ArrayToStr(frame.data.subarray(index));
  9267. return {
  9268. key: frame.type,
  9269. info: description,
  9270. data: value
  9271. };
  9272. }
  9273. const url = utf8ArrayToStr(frame.data);
  9274. return {
  9275. key: frame.type,
  9276. info: "",
  9277. data: url
  9278. };
  9279. }
  9280. function decodeId3Frame(frame) {
  9281. if (frame.type === "PRIV") {
  9282. return decodeId3PrivFrame(frame);
  9283. } else if (frame.type[0] === "W") {
  9284. return decodeId3UrlFrame(frame);
  9285. } else if (frame.type === "APIC") {
  9286. return decodeId3ImageFrame(frame);
  9287. }
  9288. return decodeId3TextFrame(frame);
  9289. }
  9290. function getId3FrameData(data) {
  9291. const type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  9292. const size = readId3Size(data, 4);
  9293. const offset = 10;
  9294. return {
  9295. type,
  9296. size,
  9297. data: data.subarray(offset, offset + size)
  9298. };
  9299. }
  9300. var HEADER_FOOTER_SIZE = 10;
  9301. var FRAME_SIZE = 10;
  9302. function getId3Frames(id3Data) {
  9303. let offset = 0;
  9304. const frames = [];
  9305. while (isId3Header(id3Data, offset)) {
  9306. const size = readId3Size(id3Data, offset + 6);
  9307. if (id3Data[offset + 5] >> 6 & 1) {
  9308. offset += HEADER_FOOTER_SIZE;
  9309. }
  9310. offset += HEADER_FOOTER_SIZE;
  9311. const end = offset + size;
  9312. while (offset + FRAME_SIZE < end) {
  9313. const frameData = getId3FrameData(id3Data.subarray(offset));
  9314. const frame = decodeId3Frame(frameData);
  9315. if (frame) {
  9316. frames.push(frame);
  9317. }
  9318. offset += frameData.size + HEADER_FOOTER_SIZE;
  9319. }
  9320. if (isId3Footer(id3Data, offset)) {
  9321. offset += HEADER_FOOTER_SIZE;
  9322. }
  9323. }
  9324. return frames;
  9325. }
  9326. function isId3TimestampFrame(frame) {
  9327. return frame && frame.key === "PRIV" && frame.info === "com.apple.streaming.transportStreamTimestamp";
  9328. }
  9329. function readId3Timestamp(timeStampFrame) {
  9330. if (timeStampFrame.data.byteLength === 8) {
  9331. const data = new Uint8Array(timeStampFrame.data);
  9332. const pts33Bit = data[3] & 1;
  9333. let timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  9334. timestamp /= 45;
  9335. if (pts33Bit) {
  9336. timestamp += 4772185884e-2;
  9337. }
  9338. return Math.round(timestamp);
  9339. }
  9340. return void 0;
  9341. }
  9342. function getId3Timestamp(data) {
  9343. const frames = getId3Frames(data);
  9344. for (let i = 0; i < frames.length; i++) {
  9345. const frame = frames[i];
  9346. if (isId3TimestampFrame(frame)) {
  9347. return readId3Timestamp(frame);
  9348. }
  9349. }
  9350. return void 0;
  9351. }
  9352. var MetadataSchema = function(MetadataSchema2) {
  9353. MetadataSchema2["audioId3"] = "org.id3";
  9354. MetadataSchema2["dateRange"] = "com.apple.quicktime.HLS";
  9355. MetadataSchema2["emsg"] = "https://aomedia.org/emsg/ID3";
  9356. MetadataSchema2["misbklv"] = "urn:misb:KLV:bin:1910.1";
  9357. return MetadataSchema2;
  9358. }({});
  9359. function dummyTrack(type = "", inputTimeScale = 9e4) {
  9360. return {
  9361. type,
  9362. id: -1,
  9363. pid: -1,
  9364. inputTimeScale,
  9365. sequenceNumber: -1,
  9366. samples: [],
  9367. dropped: 0
  9368. };
  9369. }
  9370. var BaseAudioDemuxer = class {
  9371. constructor() {
  9372. this._audioTrack = void 0;
  9373. this._id3Track = void 0;
  9374. this.frameIndex = 0;
  9375. this.cachedData = null;
  9376. this.basePTS = null;
  9377. this.initPTS = null;
  9378. this.lastPTS = null;
  9379. }
  9380. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  9381. this._id3Track = {
  9382. type: "id3",
  9383. id: 3,
  9384. pid: -1,
  9385. inputTimeScale: 9e4,
  9386. sequenceNumber: 0,
  9387. samples: [],
  9388. dropped: 0
  9389. };
  9390. }
  9391. resetTimeStamp(deaultTimestamp) {
  9392. this.initPTS = deaultTimestamp;
  9393. this.resetContiguity();
  9394. }
  9395. resetContiguity() {
  9396. this.basePTS = null;
  9397. this.lastPTS = null;
  9398. this.frameIndex = 0;
  9399. }
  9400. canParse(data, offset) {
  9401. return false;
  9402. }
  9403. appendFrame(track, data, offset) {
  9404. }
  9405. // feed incoming data to the front of the parsing pipeline
  9406. demux(data, timeOffset) {
  9407. if (this.cachedData) {
  9408. data = appendUint8Array(this.cachedData, data);
  9409. this.cachedData = null;
  9410. }
  9411. let id3Data = getId3Data(data, 0);
  9412. let offset = id3Data ? id3Data.length : 0;
  9413. let lastDataIndex;
  9414. const track = this._audioTrack;
  9415. const id3Track = this._id3Track;
  9416. const timestamp = id3Data ? getId3Timestamp(id3Data) : void 0;
  9417. const length = data.length;
  9418. if (this.basePTS === null || this.frameIndex === 0 && isFiniteNumber(timestamp)) {
  9419. this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);
  9420. this.lastPTS = this.basePTS;
  9421. }
  9422. if (this.lastPTS === null) {
  9423. this.lastPTS = this.basePTS;
  9424. }
  9425. if (id3Data && id3Data.length > 0) {
  9426. id3Track.samples.push({
  9427. pts: this.lastPTS,
  9428. dts: this.lastPTS,
  9429. data: id3Data,
  9430. type: MetadataSchema.audioId3,
  9431. duration: Number.POSITIVE_INFINITY
  9432. });
  9433. }
  9434. while (offset < length) {
  9435. if (this.canParse(data, offset)) {
  9436. const frame = this.appendFrame(track, data, offset);
  9437. if (frame) {
  9438. this.frameIndex++;
  9439. this.lastPTS = frame.sample.pts;
  9440. offset += frame.length;
  9441. lastDataIndex = offset;
  9442. } else {
  9443. offset = length;
  9444. }
  9445. } else if (canParseId3(data, offset)) {
  9446. id3Data = getId3Data(data, offset);
  9447. id3Track.samples.push({
  9448. pts: this.lastPTS,
  9449. dts: this.lastPTS,
  9450. data: id3Data,
  9451. type: MetadataSchema.audioId3,
  9452. duration: Number.POSITIVE_INFINITY
  9453. });
  9454. offset += id3Data.length;
  9455. lastDataIndex = offset;
  9456. } else {
  9457. offset++;
  9458. }
  9459. if (offset === length && lastDataIndex !== length) {
  9460. const partialData = data.slice(lastDataIndex);
  9461. if (this.cachedData) {
  9462. this.cachedData = appendUint8Array(this.cachedData, partialData);
  9463. } else {
  9464. this.cachedData = partialData;
  9465. }
  9466. }
  9467. }
  9468. return {
  9469. audioTrack: track,
  9470. videoTrack: dummyTrack(),
  9471. id3Track,
  9472. textTrack: dummyTrack()
  9473. };
  9474. }
  9475. demuxSampleAes(data, keyData, timeOffset) {
  9476. return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`));
  9477. }
  9478. flush(timeOffset) {
  9479. const cachedData = this.cachedData;
  9480. if (cachedData) {
  9481. this.cachedData = null;
  9482. this.demux(cachedData, 0);
  9483. }
  9484. return {
  9485. audioTrack: this._audioTrack,
  9486. videoTrack: dummyTrack(),
  9487. id3Track: this._id3Track,
  9488. textTrack: dummyTrack()
  9489. };
  9490. }
  9491. destroy() {
  9492. this.cachedData = null;
  9493. this._audioTrack = this._id3Track = void 0;
  9494. }
  9495. };
  9496. var initPTSFn = (timestamp, timeOffset, initPTS) => {
  9497. if (isFiniteNumber(timestamp)) {
  9498. return timestamp * 90;
  9499. }
  9500. const init90kHz = initPTS ? initPTS.baseTime * 9e4 / initPTS.timescale : 0;
  9501. return timeOffset * 9e4 + init90kHz;
  9502. };
  9503. var chromeVersion$1 = null;
  9504. var BitratesMap = [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];
  9505. var SamplingRateMap = [44100, 48e3, 32e3, 22050, 24e3, 16e3, 11025, 12e3, 8e3];
  9506. var SamplesCoefficients = [
  9507. // MPEG 2.5
  9508. [
  9509. 0,
  9510. // Reserved
  9511. 72,
  9512. // Layer3
  9513. 144,
  9514. // Layer2
  9515. 12
  9516. // Layer1
  9517. ],
  9518. // Reserved
  9519. [
  9520. 0,
  9521. // Reserved
  9522. 0,
  9523. // Layer3
  9524. 0,
  9525. // Layer2
  9526. 0
  9527. // Layer1
  9528. ],
  9529. // MPEG 2
  9530. [
  9531. 0,
  9532. // Reserved
  9533. 72,
  9534. // Layer3
  9535. 144,
  9536. // Layer2
  9537. 12
  9538. // Layer1
  9539. ],
  9540. // MPEG 1
  9541. [
  9542. 0,
  9543. // Reserved
  9544. 144,
  9545. // Layer3
  9546. 144,
  9547. // Layer2
  9548. 12
  9549. // Layer1
  9550. ]
  9551. ];
  9552. var BytesInSlot = [
  9553. 0,
  9554. // Reserved
  9555. 1,
  9556. // Layer3
  9557. 1,
  9558. // Layer2
  9559. 4
  9560. // Layer1
  9561. ];
  9562. function appendFrame$1(track, data, offset, pts, frameIndex) {
  9563. if (offset + 24 > data.length) {
  9564. return;
  9565. }
  9566. const header = parseHeader(data, offset);
  9567. if (header && offset + header.frameLength <= data.length) {
  9568. const frameDuration = header.samplesPerFrame * 9e4 / header.sampleRate;
  9569. const stamp = pts + frameIndex * frameDuration;
  9570. const sample = {
  9571. unit: data.subarray(offset, offset + header.frameLength),
  9572. pts: stamp,
  9573. dts: stamp
  9574. };
  9575. track.config = [];
  9576. track.channelCount = header.channelCount;
  9577. track.samplerate = header.sampleRate;
  9578. track.samples.push(sample);
  9579. return {
  9580. sample,
  9581. length: header.frameLength,
  9582. missing: 0
  9583. };
  9584. }
  9585. }
  9586. function parseHeader(data, offset) {
  9587. const mpegVersion = data[offset + 1] >> 3 & 3;
  9588. const mpegLayer = data[offset + 1] >> 1 & 3;
  9589. const bitRateIndex = data[offset + 2] >> 4 & 15;
  9590. const sampleRateIndex = data[offset + 2] >> 2 & 3;
  9591. if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
  9592. const paddingBit = data[offset + 2] >> 1 & 1;
  9593. const channelMode = data[offset + 3] >> 6;
  9594. const columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
  9595. const bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1e3;
  9596. const columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
  9597. const sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
  9598. const channelCount = channelMode === 3 ? 1 : 2;
  9599. const sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
  9600. const bytesInSlot = BytesInSlot[mpegLayer];
  9601. const samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  9602. const frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
  9603. if (chromeVersion$1 === null) {
  9604. const userAgent = navigator.userAgent || "";
  9605. const result = userAgent.match(/Chrome\/(\d+)/i);
  9606. chromeVersion$1 = result ? parseInt(result[1]) : 0;
  9607. }
  9608. const needChromeFix = !!chromeVersion$1 && chromeVersion$1 <= 87;
  9609. if (needChromeFix && mpegLayer === 2 && bitRate >= 224e3 && channelMode === 0) {
  9610. data[offset + 3] = data[offset + 3] | 128;
  9611. }
  9612. return {
  9613. sampleRate,
  9614. channelCount,
  9615. frameLength,
  9616. samplesPerFrame
  9617. };
  9618. }
  9619. }
  9620. function isHeaderPattern(data, offset) {
  9621. return data[offset] === 255 && (data[offset + 1] & 224) === 224 && (data[offset + 1] & 6) !== 0;
  9622. }
  9623. function isHeader(data, offset) {
  9624. return offset + 1 < data.length && isHeaderPattern(data, offset);
  9625. }
  9626. function canParse(data, offset) {
  9627. const headerSize = 4;
  9628. return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
  9629. }
  9630. function probe(data, offset) {
  9631. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  9632. const headerLength = 4;
  9633. const header = parseHeader(data, offset);
  9634. let frameLength = headerLength;
  9635. if (header != null && header.frameLength) {
  9636. frameLength = header.frameLength;
  9637. }
  9638. const newOffset = offset + frameLength;
  9639. return newOffset === data.length || isHeader(data, newOffset);
  9640. }
  9641. return false;
  9642. }
  9643. var AACDemuxer = class extends BaseAudioDemuxer {
  9644. constructor(observer, config) {
  9645. super();
  9646. this.observer = void 0;
  9647. this.config = void 0;
  9648. this.observer = observer;
  9649. this.config = config;
  9650. }
  9651. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  9652. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  9653. this._audioTrack = {
  9654. container: "audio/adts",
  9655. type: "audio",
  9656. id: 2,
  9657. pid: -1,
  9658. sequenceNumber: 0,
  9659. segmentCodec: "aac",
  9660. samples: [],
  9661. manifestCodec: audioCodec,
  9662. duration: trackDuration,
  9663. inputTimeScale: 9e4,
  9664. dropped: 0
  9665. };
  9666. }
  9667. // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
  9668. static probe(data, logger2) {
  9669. if (!data) {
  9670. return false;
  9671. }
  9672. const id3Data = getId3Data(data, 0);
  9673. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  9674. if (probe(data, offset)) {
  9675. return false;
  9676. }
  9677. for (let length = data.length; offset < length; offset++) {
  9678. if (probe$1(data, offset)) {
  9679. logger2.log("ADTS sync word found !");
  9680. return true;
  9681. }
  9682. }
  9683. return false;
  9684. }
  9685. canParse(data, offset) {
  9686. return canParse$1(data, offset);
  9687. }
  9688. appendFrame(track, data, offset) {
  9689. initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  9690. const frame = appendFrame$2(track, data, offset, this.basePTS, this.frameIndex);
  9691. if (frame && frame.missing === 0) {
  9692. return frame;
  9693. }
  9694. }
  9695. };
  9696. var getAudioBSID = (data, offset) => {
  9697. let bsid = 0;
  9698. let numBits = 5;
  9699. offset += numBits;
  9700. const temp = new Uint32Array(1);
  9701. const mask = new Uint32Array(1);
  9702. const byte = new Uint8Array(1);
  9703. while (numBits > 0) {
  9704. byte[0] = data[offset];
  9705. const bits = Math.min(numBits, 8);
  9706. const shift = 8 - bits;
  9707. mask[0] = 4278190080 >>> 24 + shift << shift;
  9708. temp[0] = (byte[0] & mask[0]) >> shift;
  9709. bsid = !bsid ? temp[0] : bsid << bits | temp[0];
  9710. offset += 1;
  9711. numBits -= bits;
  9712. }
  9713. return bsid;
  9714. };
  9715. var AC3Demuxer = class extends BaseAudioDemuxer {
  9716. constructor(observer) {
  9717. super();
  9718. this.observer = void 0;
  9719. this.observer = observer;
  9720. }
  9721. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  9722. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  9723. this._audioTrack = {
  9724. container: "audio/ac-3",
  9725. type: "audio",
  9726. id: 2,
  9727. pid: -1,
  9728. sequenceNumber: 0,
  9729. segmentCodec: "ac3",
  9730. samples: [],
  9731. manifestCodec: audioCodec,
  9732. duration: trackDuration,
  9733. inputTimeScale: 9e4,
  9734. dropped: 0
  9735. };
  9736. }
  9737. canParse(data, offset) {
  9738. return offset + 64 < data.length;
  9739. }
  9740. appendFrame(track, data, offset) {
  9741. const frameLength = appendFrame(track, data, offset, this.basePTS, this.frameIndex);
  9742. if (frameLength !== -1) {
  9743. const sample = track.samples[track.samples.length - 1];
  9744. return {
  9745. sample,
  9746. length: frameLength,
  9747. missing: 0
  9748. };
  9749. }
  9750. }
  9751. static probe(data) {
  9752. if (!data) {
  9753. return false;
  9754. }
  9755. const id3Data = getId3Data(data, 0);
  9756. if (!id3Data) {
  9757. return false;
  9758. }
  9759. const offset = id3Data.length;
  9760. if (data[offset] === 11 && data[offset + 1] === 119 && getId3Timestamp(id3Data) !== void 0 && // check the bsid to confirm ac-3
  9761. getAudioBSID(data, offset) < 16) {
  9762. return true;
  9763. }
  9764. return false;
  9765. }
  9766. };
  9767. function appendFrame(track, data, start, pts, frameIndex) {
  9768. if (start + 8 > data.length) {
  9769. return -1;
  9770. }
  9771. if (data[start] !== 11 || data[start + 1] !== 119) {
  9772. return -1;
  9773. }
  9774. const samplingRateCode = data[start + 4] >> 6;
  9775. if (samplingRateCode >= 3) {
  9776. return -1;
  9777. }
  9778. const samplingRateMap = [48e3, 44100, 32e3];
  9779. const sampleRate = samplingRateMap[samplingRateCode];
  9780. const frameSizeCode = data[start + 4] & 63;
  9781. const frameSizeMap = [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];
  9782. const frameLength = frameSizeMap[frameSizeCode * 3 + samplingRateCode] * 2;
  9783. if (start + frameLength > data.length) {
  9784. return -1;
  9785. }
  9786. const channelMode = data[start + 6] >> 5;
  9787. let skipCount = 0;
  9788. if (channelMode === 2) {
  9789. skipCount += 2;
  9790. } else {
  9791. if (channelMode & 1 && channelMode !== 1) {
  9792. skipCount += 2;
  9793. }
  9794. if (channelMode & 4) {
  9795. skipCount += 2;
  9796. }
  9797. }
  9798. const lfeon = (data[start + 6] << 8 | data[start + 7]) >> 12 - skipCount & 1;
  9799. const channelsMap = [2, 1, 2, 3, 3, 4, 4, 5];
  9800. const channelCount = channelsMap[channelMode] + lfeon;
  9801. const bsid = data[start + 5] >> 3;
  9802. const bsmod = data[start + 5] & 7;
  9803. const config = new Uint8Array([samplingRateCode << 6 | bsid << 1 | bsmod >> 2, (bsmod & 3) << 6 | channelMode << 3 | lfeon << 2 | frameSizeCode >> 4, frameSizeCode << 4 & 224]);
  9804. const frameDuration = 1536 / sampleRate * 9e4;
  9805. const stamp = pts + frameIndex * frameDuration;
  9806. const unit = data.subarray(start, start + frameLength);
  9807. track.config = config;
  9808. track.channelCount = channelCount;
  9809. track.samplerate = sampleRate;
  9810. track.samples.push({
  9811. unit,
  9812. pts: stamp
  9813. });
  9814. return frameLength;
  9815. }
  9816. var MP3Demuxer = class extends BaseAudioDemuxer {
  9817. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  9818. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  9819. this._audioTrack = {
  9820. container: "audio/mpeg",
  9821. type: "audio",
  9822. id: 2,
  9823. pid: -1,
  9824. sequenceNumber: 0,
  9825. segmentCodec: "mp3",
  9826. samples: [],
  9827. manifestCodec: audioCodec,
  9828. duration: trackDuration,
  9829. inputTimeScale: 9e4,
  9830. dropped: 0
  9831. };
  9832. }
  9833. static probe(data) {
  9834. if (!data) {
  9835. return false;
  9836. }
  9837. const id3Data = getId3Data(data, 0);
  9838. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  9839. if (id3Data && data[offset] === 11 && data[offset + 1] === 119 && getId3Timestamp(id3Data) !== void 0 && // check the bsid to confirm ac-3 or ec-3 (not mp3)
  9840. getAudioBSID(data, offset) <= 16) {
  9841. return false;
  9842. }
  9843. for (let length = data.length; offset < length; offset++) {
  9844. if (probe(data, offset)) {
  9845. logger.log("MPEG Audio sync word found !");
  9846. return true;
  9847. }
  9848. }
  9849. return false;
  9850. }
  9851. canParse(data, offset) {
  9852. return canParse(data, offset);
  9853. }
  9854. appendFrame(track, data, offset) {
  9855. if (this.basePTS === null) {
  9856. return;
  9857. }
  9858. return appendFrame$1(track, data, offset, this.basePTS, this.frameIndex);
  9859. }
  9860. };
  9861. var emsgSchemePattern = /\/emsg[-/]ID3/i;
  9862. var MP4Demuxer = class {
  9863. constructor(observer, config) {
  9864. this.remainderData = null;
  9865. this.timeOffset = 0;
  9866. this.config = void 0;
  9867. this.videoTrack = void 0;
  9868. this.audioTrack = void 0;
  9869. this.id3Track = void 0;
  9870. this.txtTrack = void 0;
  9871. this.config = config;
  9872. }
  9873. resetTimeStamp() {
  9874. }
  9875. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  9876. const videoTrack = this.videoTrack = dummyTrack("video", 1);
  9877. const audioTrack = this.audioTrack = dummyTrack("audio", 1);
  9878. const captionTrack = this.txtTrack = dummyTrack("text", 1);
  9879. this.id3Track = dummyTrack("id3", 1);
  9880. this.timeOffset = 0;
  9881. if (!(initSegment != null && initSegment.byteLength)) {
  9882. return;
  9883. }
  9884. const initData = parseInitSegment(initSegment);
  9885. if (initData.video) {
  9886. const {
  9887. id,
  9888. timescale,
  9889. codec,
  9890. supplemental
  9891. } = initData.video;
  9892. videoTrack.id = id;
  9893. videoTrack.timescale = captionTrack.timescale = timescale;
  9894. videoTrack.codec = codec;
  9895. videoTrack.supplemental = supplemental;
  9896. }
  9897. if (initData.audio) {
  9898. const {
  9899. id,
  9900. timescale,
  9901. codec
  9902. } = initData.audio;
  9903. audioTrack.id = id;
  9904. audioTrack.timescale = timescale;
  9905. audioTrack.codec = codec;
  9906. }
  9907. captionTrack.id = RemuxerTrackIdConfig.text;
  9908. videoTrack.sampleDuration = 0;
  9909. videoTrack.duration = audioTrack.duration = trackDuration;
  9910. }
  9911. resetContiguity() {
  9912. this.remainderData = null;
  9913. }
  9914. static probe(data) {
  9915. return hasMoofData(data);
  9916. }
  9917. demux(data, timeOffset) {
  9918. this.timeOffset = timeOffset;
  9919. let videoSamples = data;
  9920. const videoTrack = this.videoTrack;
  9921. const textTrack = this.txtTrack;
  9922. if (this.config.progressive) {
  9923. if (this.remainderData) {
  9924. videoSamples = appendUint8Array(this.remainderData, data);
  9925. }
  9926. const segmentedData = segmentValidRange(videoSamples);
  9927. this.remainderData = segmentedData.remainder;
  9928. videoTrack.samples = segmentedData.valid || new Uint8Array();
  9929. } else {
  9930. videoTrack.samples = videoSamples;
  9931. }
  9932. const id3Track = this.extractID3Track(videoTrack, timeOffset);
  9933. textTrack.samples = parseSamples(timeOffset, videoTrack);
  9934. return {
  9935. videoTrack,
  9936. audioTrack: this.audioTrack,
  9937. id3Track,
  9938. textTrack: this.txtTrack
  9939. };
  9940. }
  9941. flush() {
  9942. const timeOffset = this.timeOffset;
  9943. const videoTrack = this.videoTrack;
  9944. const textTrack = this.txtTrack;
  9945. videoTrack.samples = this.remainderData || new Uint8Array();
  9946. this.remainderData = null;
  9947. const id3Track = this.extractID3Track(videoTrack, this.timeOffset);
  9948. textTrack.samples = parseSamples(timeOffset, videoTrack);
  9949. return {
  9950. videoTrack,
  9951. audioTrack: dummyTrack(),
  9952. id3Track,
  9953. textTrack: dummyTrack()
  9954. };
  9955. }
  9956. extractID3Track(videoTrack, timeOffset) {
  9957. const id3Track = this.id3Track;
  9958. if (videoTrack.samples.length) {
  9959. const emsgs = findBox(videoTrack.samples, ["emsg"]);
  9960. if (emsgs) {
  9961. emsgs.forEach((data) => {
  9962. const emsgInfo = parseEmsg(data);
  9963. if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {
  9964. const pts = getEmsgStartTime(emsgInfo, timeOffset);
  9965. let duration = emsgInfo.eventDuration === 4294967295 ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale;
  9966. if (duration <= 1e-3) {
  9967. duration = Number.POSITIVE_INFINITY;
  9968. }
  9969. const payload = emsgInfo.payload;
  9970. id3Track.samples.push({
  9971. data: payload,
  9972. len: payload.byteLength,
  9973. dts: pts,
  9974. pts,
  9975. type: MetadataSchema.emsg,
  9976. duration
  9977. });
  9978. } else if (this.config.enableEmsgKLVMetadata && emsgInfo.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")) {
  9979. const pts = getEmsgStartTime(emsgInfo, timeOffset);
  9980. id3Track.samples.push({
  9981. data: emsgInfo.payload,
  9982. len: emsgInfo.payload.byteLength,
  9983. dts: pts,
  9984. pts,
  9985. type: MetadataSchema.misbklv,
  9986. duration: Number.POSITIVE_INFINITY
  9987. });
  9988. }
  9989. });
  9990. }
  9991. }
  9992. return id3Track;
  9993. }
  9994. demuxSampleAes(data, keyData, timeOffset) {
  9995. return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"));
  9996. }
  9997. destroy() {
  9998. this.config = null;
  9999. this.remainderData = null;
  10000. this.videoTrack = this.audioTrack = this.id3Track = this.txtTrack = void 0;
  10001. }
  10002. };
  10003. function getEmsgStartTime(emsgInfo, timeOffset) {
  10004. return isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;
  10005. }
  10006. var SampleAesDecrypter = class {
  10007. constructor(observer, config, keyData) {
  10008. this.keyData = void 0;
  10009. this.decrypter = void 0;
  10010. this.keyData = keyData;
  10011. this.decrypter = new Decrypter(config, {
  10012. removePKCS7Padding: false
  10013. });
  10014. }
  10015. decryptBuffer(encryptedData) {
  10016. return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, DecrypterAesMode.cbc);
  10017. }
  10018. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  10019. decryptAacSample(samples, sampleIndex, callback) {
  10020. const curUnit = samples[sampleIndex].unit;
  10021. if (curUnit.length <= 16) {
  10022. return;
  10023. }
  10024. const encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  10025. const encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  10026. this.decryptBuffer(encryptedBuffer).then((decryptedBuffer) => {
  10027. const decryptedData = new Uint8Array(decryptedBuffer);
  10028. curUnit.set(decryptedData, 16);
  10029. if (!this.decrypter.isSync()) {
  10030. this.decryptAacSamples(samples, sampleIndex + 1, callback);
  10031. }
  10032. });
  10033. }
  10034. decryptAacSamples(samples, sampleIndex, callback) {
  10035. for (; ; sampleIndex++) {
  10036. if (sampleIndex >= samples.length) {
  10037. callback();
  10038. return;
  10039. }
  10040. if (samples[sampleIndex].unit.length < 32) {
  10041. continue;
  10042. }
  10043. this.decryptAacSample(samples, sampleIndex, callback);
  10044. if (!this.decrypter.isSync()) {
  10045. return;
  10046. }
  10047. }
  10048. }
  10049. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  10050. getAvcEncryptedData(decodedData) {
  10051. const encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  10052. const encryptedData = new Int8Array(encryptedDataLen);
  10053. let outputPos = 0;
  10054. for (let inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) {
  10055. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  10056. }
  10057. return encryptedData;
  10058. }
  10059. getAvcDecryptedUnit(decodedData, decryptedData) {
  10060. const uint8DecryptedData = new Uint8Array(decryptedData);
  10061. let inputPos = 0;
  10062. for (let outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) {
  10063. decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
  10064. }
  10065. return decodedData;
  10066. }
  10067. decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit) {
  10068. const decodedData = discardEPB(curUnit.data);
  10069. const encryptedData = this.getAvcEncryptedData(decodedData);
  10070. this.decryptBuffer(encryptedData.buffer).then((decryptedBuffer) => {
  10071. curUnit.data = this.getAvcDecryptedUnit(decodedData, decryptedBuffer);
  10072. if (!this.decrypter.isSync()) {
  10073. this.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  10074. }
  10075. });
  10076. }
  10077. decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  10078. if (samples instanceof Uint8Array) {
  10079. throw new Error("Cannot decrypt samples of type Uint8Array");
  10080. }
  10081. for (; ; sampleIndex++, unitIndex = 0) {
  10082. if (sampleIndex >= samples.length) {
  10083. callback();
  10084. return;
  10085. }
  10086. const curUnits = samples[sampleIndex].units;
  10087. for (; ; unitIndex++) {
  10088. if (unitIndex >= curUnits.length) {
  10089. break;
  10090. }
  10091. const curUnit = curUnits[unitIndex];
  10092. if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  10093. continue;
  10094. }
  10095. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit);
  10096. if (!this.decrypter.isSync()) {
  10097. return;
  10098. }
  10099. }
  10100. }
  10101. }
  10102. };
  10103. var BaseVideoParser = class {
  10104. constructor() {
  10105. this.VideoSample = null;
  10106. }
  10107. createVideoSample(key, pts, dts) {
  10108. return {
  10109. key,
  10110. frame: false,
  10111. pts,
  10112. dts,
  10113. units: [],
  10114. length: 0
  10115. };
  10116. }
  10117. getLastNalUnit(samples) {
  10118. var _VideoSample;
  10119. let VideoSample = this.VideoSample;
  10120. let lastUnit;
  10121. if (!VideoSample || VideoSample.units.length === 0) {
  10122. VideoSample = samples[samples.length - 1];
  10123. }
  10124. if ((_VideoSample = VideoSample) != null && _VideoSample.units) {
  10125. const units = VideoSample.units;
  10126. lastUnit = units[units.length - 1];
  10127. }
  10128. return lastUnit;
  10129. }
  10130. pushAccessUnit(VideoSample, videoTrack) {
  10131. if (VideoSample.units.length && VideoSample.frame) {
  10132. if (VideoSample.pts === void 0) {
  10133. const samples = videoTrack.samples;
  10134. const nbSamples = samples.length;
  10135. if (nbSamples) {
  10136. const lastSample = samples[nbSamples - 1];
  10137. VideoSample.pts = lastSample.pts;
  10138. VideoSample.dts = lastSample.dts;
  10139. } else {
  10140. videoTrack.dropped++;
  10141. return;
  10142. }
  10143. }
  10144. videoTrack.samples.push(VideoSample);
  10145. }
  10146. }
  10147. parseNALu(track, array, endOfSegment) {
  10148. const len = array.byteLength;
  10149. let state = track.naluState || 0;
  10150. const lastState = state;
  10151. const units = [];
  10152. let i = 0;
  10153. let value;
  10154. let overflow;
  10155. let unitType;
  10156. let lastUnitStart = -1;
  10157. let lastUnitType = 0;
  10158. if (state === -1) {
  10159. lastUnitStart = 0;
  10160. lastUnitType = this.getNALuType(array, 0);
  10161. state = 0;
  10162. i = 1;
  10163. }
  10164. while (i < len) {
  10165. value = array[i++];
  10166. if (!state) {
  10167. state = value ? 0 : 1;
  10168. continue;
  10169. }
  10170. if (state === 1) {
  10171. state = value ? 0 : 2;
  10172. continue;
  10173. }
  10174. if (!value) {
  10175. state = 3;
  10176. } else if (value === 1) {
  10177. overflow = i - state - 1;
  10178. if (lastUnitStart >= 0) {
  10179. const unit = {
  10180. data: array.subarray(lastUnitStart, overflow),
  10181. type: lastUnitType
  10182. };
  10183. units.push(unit);
  10184. } else {
  10185. const lastUnit = this.getLastNalUnit(track.samples);
  10186. if (lastUnit) {
  10187. if (lastState && i <= 4 - lastState) {
  10188. if (lastUnit.state) {
  10189. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  10190. }
  10191. }
  10192. if (overflow > 0) {
  10193. lastUnit.data = appendUint8Array(lastUnit.data, array.subarray(0, overflow));
  10194. lastUnit.state = 0;
  10195. }
  10196. }
  10197. }
  10198. if (i < len) {
  10199. unitType = this.getNALuType(array, i);
  10200. lastUnitStart = i;
  10201. lastUnitType = unitType;
  10202. state = 0;
  10203. } else {
  10204. state = -1;
  10205. }
  10206. } else {
  10207. state = 0;
  10208. }
  10209. }
  10210. if (lastUnitStart >= 0 && state >= 0) {
  10211. const unit = {
  10212. data: array.subarray(lastUnitStart, len),
  10213. type: lastUnitType,
  10214. state
  10215. };
  10216. units.push(unit);
  10217. }
  10218. if (units.length === 0) {
  10219. const lastUnit = this.getLastNalUnit(track.samples);
  10220. if (lastUnit) {
  10221. lastUnit.data = appendUint8Array(lastUnit.data, array);
  10222. }
  10223. }
  10224. track.naluState = state;
  10225. return units;
  10226. }
  10227. };
  10228. var ExpGolomb = class {
  10229. constructor(data) {
  10230. this.data = void 0;
  10231. this.bytesAvailable = void 0;
  10232. this.word = void 0;
  10233. this.bitsAvailable = void 0;
  10234. this.data = data;
  10235. this.bytesAvailable = data.byteLength;
  10236. this.word = 0;
  10237. this.bitsAvailable = 0;
  10238. }
  10239. // ():void
  10240. loadWord() {
  10241. const data = this.data;
  10242. const bytesAvailable = this.bytesAvailable;
  10243. const position = data.byteLength - bytesAvailable;
  10244. const workingBytes = new Uint8Array(4);
  10245. const availableBytes = Math.min(4, bytesAvailable);
  10246. if (availableBytes === 0) {
  10247. throw new Error("no bytes available");
  10248. }
  10249. workingBytes.set(data.subarray(position, position + availableBytes));
  10250. this.word = new DataView(workingBytes.buffer).getUint32(0);
  10251. this.bitsAvailable = availableBytes * 8;
  10252. this.bytesAvailable -= availableBytes;
  10253. }
  10254. // (count:int):void
  10255. skipBits(count) {
  10256. let skipBytes;
  10257. count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);
  10258. if (this.bitsAvailable > count) {
  10259. this.word <<= count;
  10260. this.bitsAvailable -= count;
  10261. } else {
  10262. count -= this.bitsAvailable;
  10263. skipBytes = count >> 3;
  10264. count -= skipBytes << 3;
  10265. this.bytesAvailable -= skipBytes;
  10266. this.loadWord();
  10267. this.word <<= count;
  10268. this.bitsAvailable -= count;
  10269. }
  10270. }
  10271. // (size:int):uint
  10272. readBits(size) {
  10273. let bits = Math.min(this.bitsAvailable, size);
  10274. const valu = this.word >>> 32 - bits;
  10275. if (size > 32) {
  10276. logger.error("Cannot read more than 32 bits at a time");
  10277. }
  10278. this.bitsAvailable -= bits;
  10279. if (this.bitsAvailable > 0) {
  10280. this.word <<= bits;
  10281. } else if (this.bytesAvailable > 0) {
  10282. this.loadWord();
  10283. } else {
  10284. throw new Error("no bits available");
  10285. }
  10286. bits = size - bits;
  10287. if (bits > 0 && this.bitsAvailable) {
  10288. return valu << bits | this.readBits(bits);
  10289. } else {
  10290. return valu;
  10291. }
  10292. }
  10293. // ():uint
  10294. skipLZ() {
  10295. let leadingZeroCount;
  10296. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  10297. if ((this.word & 2147483648 >>> leadingZeroCount) !== 0) {
  10298. this.word <<= leadingZeroCount;
  10299. this.bitsAvailable -= leadingZeroCount;
  10300. return leadingZeroCount;
  10301. }
  10302. }
  10303. this.loadWord();
  10304. return leadingZeroCount + this.skipLZ();
  10305. }
  10306. // ():void
  10307. skipUEG() {
  10308. this.skipBits(1 + this.skipLZ());
  10309. }
  10310. // ():void
  10311. skipEG() {
  10312. this.skipBits(1 + this.skipLZ());
  10313. }
  10314. // ():uint
  10315. readUEG() {
  10316. const clz = this.skipLZ();
  10317. return this.readBits(clz + 1) - 1;
  10318. }
  10319. // ():int
  10320. readEG() {
  10321. const valu = this.readUEG();
  10322. if (1 & valu) {
  10323. return 1 + valu >>> 1;
  10324. } else {
  10325. return -1 * (valu >>> 1);
  10326. }
  10327. }
  10328. // Some convenience functions
  10329. // :Boolean
  10330. readBoolean() {
  10331. return this.readBits(1) === 1;
  10332. }
  10333. // ():int
  10334. readUByte() {
  10335. return this.readBits(8);
  10336. }
  10337. // ():int
  10338. readUShort() {
  10339. return this.readBits(16);
  10340. }
  10341. // ():int
  10342. readUInt() {
  10343. return this.readBits(32);
  10344. }
  10345. };
  10346. var AvcVideoParser = class extends BaseVideoParser {
  10347. parsePES(track, textTrack, pes, endOfSegment) {
  10348. const units = this.parseNALu(track, pes.data, endOfSegment);
  10349. let VideoSample = this.VideoSample;
  10350. let push2;
  10351. let spsfound = false;
  10352. pes.data = null;
  10353. if (VideoSample && units.length && !track.audFound) {
  10354. this.pushAccessUnit(VideoSample, track);
  10355. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  10356. }
  10357. units.forEach((unit) => {
  10358. var _VideoSample2, _VideoSample3;
  10359. switch (unit.type) {
  10360. case 1: {
  10361. let iskey = false;
  10362. push2 = true;
  10363. const data = unit.data;
  10364. if (spsfound && data.length > 4) {
  10365. const sliceType = this.readSliceType(data);
  10366. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  10367. iskey = true;
  10368. }
  10369. }
  10370. if (iskey) {
  10371. var _VideoSample;
  10372. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  10373. this.pushAccessUnit(VideoSample, track);
  10374. VideoSample = this.VideoSample = null;
  10375. }
  10376. }
  10377. if (!VideoSample) {
  10378. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  10379. }
  10380. VideoSample.frame = true;
  10381. VideoSample.key = iskey;
  10382. break;
  10383. }
  10384. case 5:
  10385. push2 = true;
  10386. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  10387. this.pushAccessUnit(VideoSample, track);
  10388. VideoSample = this.VideoSample = null;
  10389. }
  10390. if (!VideoSample) {
  10391. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  10392. }
  10393. VideoSample.key = true;
  10394. VideoSample.frame = true;
  10395. break;
  10396. case 6: {
  10397. push2 = true;
  10398. parseSEIMessageFromNALu(unit.data, 1, pes.pts, textTrack.samples);
  10399. break;
  10400. }
  10401. case 7: {
  10402. var _track$pixelRatio, _track$pixelRatio2;
  10403. push2 = true;
  10404. spsfound = true;
  10405. const sps = unit.data;
  10406. const config = this.readSPS(sps);
  10407. if (!track.sps || track.width !== config.width || track.height !== config.height || ((_track$pixelRatio = track.pixelRatio) == null ? void 0 : _track$pixelRatio[0]) !== config.pixelRatio[0] || ((_track$pixelRatio2 = track.pixelRatio) == null ? void 0 : _track$pixelRatio2[1]) !== config.pixelRatio[1]) {
  10408. track.width = config.width;
  10409. track.height = config.height;
  10410. track.pixelRatio = config.pixelRatio;
  10411. track.sps = [sps];
  10412. const codecarray = sps.subarray(1, 4);
  10413. let codecstring = "avc1.";
  10414. for (let i = 0; i < 3; i++) {
  10415. let h = codecarray[i].toString(16);
  10416. if (h.length < 2) {
  10417. h = "0" + h;
  10418. }
  10419. codecstring += h;
  10420. }
  10421. track.codec = codecstring;
  10422. }
  10423. break;
  10424. }
  10425. case 8:
  10426. push2 = true;
  10427. track.pps = [unit.data];
  10428. break;
  10429. case 9:
  10430. push2 = true;
  10431. track.audFound = true;
  10432. if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
  10433. this.pushAccessUnit(VideoSample, track);
  10434. VideoSample = null;
  10435. }
  10436. if (!VideoSample) {
  10437. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  10438. }
  10439. break;
  10440. case 12:
  10441. push2 = true;
  10442. break;
  10443. default:
  10444. push2 = false;
  10445. break;
  10446. }
  10447. if (VideoSample && push2) {
  10448. const units2 = VideoSample.units;
  10449. units2.push(unit);
  10450. }
  10451. });
  10452. if (endOfSegment && VideoSample) {
  10453. this.pushAccessUnit(VideoSample, track);
  10454. this.VideoSample = null;
  10455. }
  10456. }
  10457. getNALuType(data, offset) {
  10458. return data[offset] & 31;
  10459. }
  10460. readSliceType(data) {
  10461. const eg = new ExpGolomb(data);
  10462. eg.readUByte();
  10463. eg.readUEG();
  10464. return eg.readUEG();
  10465. }
  10466. /**
  10467. * The scaling list is optionally transmitted as part of a sequence parameter
  10468. * set and is not relevant to transmuxing.
  10469. * @param count the number of entries in this scaling list
  10470. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  10471. */
  10472. skipScalingList(count, reader) {
  10473. let lastScale = 8;
  10474. let nextScale = 8;
  10475. let deltaScale;
  10476. for (let j = 0; j < count; j++) {
  10477. if (nextScale !== 0) {
  10478. deltaScale = reader.readEG();
  10479. nextScale = (lastScale + deltaScale + 256) % 256;
  10480. }
  10481. lastScale = nextScale === 0 ? lastScale : nextScale;
  10482. }
  10483. }
  10484. /**
  10485. * Read a sequence parameter set and return some interesting video
  10486. * properties. A sequence parameter set is the H264 metadata that
  10487. * describes the properties of upcoming video frames.
  10488. * @returns an object with configuration parsed from the
  10489. * sequence parameter set, including the dimensions of the
  10490. * associated video frames.
  10491. */
  10492. readSPS(sps) {
  10493. const eg = new ExpGolomb(sps);
  10494. let frameCropLeftOffset = 0;
  10495. let frameCropRightOffset = 0;
  10496. let frameCropTopOffset = 0;
  10497. let frameCropBottomOffset = 0;
  10498. let numRefFramesInPicOrderCntCycle;
  10499. let scalingListCount;
  10500. let i;
  10501. const readUByte = eg.readUByte.bind(eg);
  10502. const readBits = eg.readBits.bind(eg);
  10503. const readUEG = eg.readUEG.bind(eg);
  10504. const readBoolean = eg.readBoolean.bind(eg);
  10505. const skipBits = eg.skipBits.bind(eg);
  10506. const skipEG = eg.skipEG.bind(eg);
  10507. const skipUEG = eg.skipUEG.bind(eg);
  10508. const skipScalingList = this.skipScalingList.bind(this);
  10509. readUByte();
  10510. const profileIdc = readUByte();
  10511. readBits(5);
  10512. skipBits(3);
  10513. readUByte();
  10514. skipUEG();
  10515. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  10516. const chromaFormatIdc = readUEG();
  10517. if (chromaFormatIdc === 3) {
  10518. skipBits(1);
  10519. }
  10520. skipUEG();
  10521. skipUEG();
  10522. skipBits(1);
  10523. if (readBoolean()) {
  10524. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  10525. for (i = 0; i < scalingListCount; i++) {
  10526. if (readBoolean()) {
  10527. if (i < 6) {
  10528. skipScalingList(16, eg);
  10529. } else {
  10530. skipScalingList(64, eg);
  10531. }
  10532. }
  10533. }
  10534. }
  10535. }
  10536. skipUEG();
  10537. const picOrderCntType = readUEG();
  10538. if (picOrderCntType === 0) {
  10539. readUEG();
  10540. } else if (picOrderCntType === 1) {
  10541. skipBits(1);
  10542. skipEG();
  10543. skipEG();
  10544. numRefFramesInPicOrderCntCycle = readUEG();
  10545. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  10546. skipEG();
  10547. }
  10548. }
  10549. skipUEG();
  10550. skipBits(1);
  10551. const picWidthInMbsMinus1 = readUEG();
  10552. const picHeightInMapUnitsMinus1 = readUEG();
  10553. const frameMbsOnlyFlag = readBits(1);
  10554. if (frameMbsOnlyFlag === 0) {
  10555. skipBits(1);
  10556. }
  10557. skipBits(1);
  10558. if (readBoolean()) {
  10559. frameCropLeftOffset = readUEG();
  10560. frameCropRightOffset = readUEG();
  10561. frameCropTopOffset = readUEG();
  10562. frameCropBottomOffset = readUEG();
  10563. }
  10564. let pixelRatio = [1, 1];
  10565. if (readBoolean()) {
  10566. if (readBoolean()) {
  10567. const aspectRatioIdc = readUByte();
  10568. switch (aspectRatioIdc) {
  10569. case 1:
  10570. pixelRatio = [1, 1];
  10571. break;
  10572. case 2:
  10573. pixelRatio = [12, 11];
  10574. break;
  10575. case 3:
  10576. pixelRatio = [10, 11];
  10577. break;
  10578. case 4:
  10579. pixelRatio = [16, 11];
  10580. break;
  10581. case 5:
  10582. pixelRatio = [40, 33];
  10583. break;
  10584. case 6:
  10585. pixelRatio = [24, 11];
  10586. break;
  10587. case 7:
  10588. pixelRatio = [20, 11];
  10589. break;
  10590. case 8:
  10591. pixelRatio = [32, 11];
  10592. break;
  10593. case 9:
  10594. pixelRatio = [80, 33];
  10595. break;
  10596. case 10:
  10597. pixelRatio = [18, 11];
  10598. break;
  10599. case 11:
  10600. pixelRatio = [15, 11];
  10601. break;
  10602. case 12:
  10603. pixelRatio = [64, 33];
  10604. break;
  10605. case 13:
  10606. pixelRatio = [160, 99];
  10607. break;
  10608. case 14:
  10609. pixelRatio = [4, 3];
  10610. break;
  10611. case 15:
  10612. pixelRatio = [3, 2];
  10613. break;
  10614. case 16:
  10615. pixelRatio = [2, 1];
  10616. break;
  10617. case 255: {
  10618. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  10619. break;
  10620. }
  10621. }
  10622. }
  10623. }
  10624. return {
  10625. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  10626. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  10627. pixelRatio
  10628. };
  10629. }
  10630. };
  10631. var HevcVideoParser = class extends BaseVideoParser {
  10632. constructor(...args) {
  10633. super(...args);
  10634. this.initVPS = null;
  10635. }
  10636. parsePES(track, textTrack, pes, endOfSegment) {
  10637. const units = this.parseNALu(track, pes.data, endOfSegment);
  10638. let VideoSample = this.VideoSample;
  10639. let push2;
  10640. let spsfound = false;
  10641. pes.data = null;
  10642. if (VideoSample && units.length && !track.audFound) {
  10643. this.pushAccessUnit(VideoSample, track);
  10644. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  10645. }
  10646. units.forEach((unit) => {
  10647. var _VideoSample2, _VideoSample3;
  10648. switch (unit.type) {
  10649. case 0:
  10650. case 1:
  10651. case 2:
  10652. case 3:
  10653. case 4:
  10654. case 5:
  10655. case 6:
  10656. case 7:
  10657. case 8:
  10658. case 9:
  10659. if (!VideoSample) {
  10660. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  10661. }
  10662. VideoSample.frame = true;
  10663. push2 = true;
  10664. break;
  10665. case 16:
  10666. case 17:
  10667. case 18:
  10668. case 21:
  10669. push2 = true;
  10670. if (spsfound) {
  10671. var _VideoSample;
  10672. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  10673. this.pushAccessUnit(VideoSample, track);
  10674. VideoSample = this.VideoSample = null;
  10675. }
  10676. }
  10677. if (!VideoSample) {
  10678. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  10679. }
  10680. VideoSample.key = true;
  10681. VideoSample.frame = true;
  10682. break;
  10683. case 19:
  10684. case 20:
  10685. push2 = true;
  10686. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  10687. this.pushAccessUnit(VideoSample, track);
  10688. VideoSample = this.VideoSample = null;
  10689. }
  10690. if (!VideoSample) {
  10691. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  10692. }
  10693. VideoSample.key = true;
  10694. VideoSample.frame = true;
  10695. break;
  10696. case 39:
  10697. push2 = true;
  10698. parseSEIMessageFromNALu(
  10699. unit.data,
  10700. 2,
  10701. // NALu header size
  10702. pes.pts,
  10703. textTrack.samples
  10704. );
  10705. break;
  10706. case 32:
  10707. push2 = true;
  10708. if (!track.vps) {
  10709. if (typeof track.params !== "object") {
  10710. track.params = {};
  10711. }
  10712. track.params = _extends(track.params, this.readVPS(unit.data));
  10713. this.initVPS = unit.data;
  10714. }
  10715. track.vps = [unit.data];
  10716. break;
  10717. case 33:
  10718. push2 = true;
  10719. spsfound = true;
  10720. if (track.vps !== void 0 && track.vps[0] !== this.initVPS && track.sps !== void 0 && !this.matchSPS(track.sps[0], unit.data)) {
  10721. this.initVPS = track.vps[0];
  10722. track.sps = track.pps = void 0;
  10723. }
  10724. if (!track.sps) {
  10725. const config = this.readSPS(unit.data);
  10726. track.width = config.width;
  10727. track.height = config.height;
  10728. track.pixelRatio = config.pixelRatio;
  10729. track.codec = config.codecString;
  10730. track.sps = [];
  10731. if (typeof track.params !== "object") {
  10732. track.params = {};
  10733. }
  10734. for (const prop in config.params) {
  10735. track.params[prop] = config.params[prop];
  10736. }
  10737. }
  10738. this.pushParameterSet(track.sps, unit.data, track.vps);
  10739. if (!VideoSample) {
  10740. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  10741. }
  10742. VideoSample.key = true;
  10743. break;
  10744. case 34:
  10745. push2 = true;
  10746. if (typeof track.params === "object") {
  10747. if (!track.pps) {
  10748. track.pps = [];
  10749. const config = this.readPPS(unit.data);
  10750. for (const prop in config) {
  10751. track.params[prop] = config[prop];
  10752. }
  10753. }
  10754. this.pushParameterSet(track.pps, unit.data, track.vps);
  10755. }
  10756. break;
  10757. case 35:
  10758. push2 = true;
  10759. track.audFound = true;
  10760. if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
  10761. this.pushAccessUnit(VideoSample, track);
  10762. VideoSample = null;
  10763. }
  10764. if (!VideoSample) {
  10765. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  10766. }
  10767. break;
  10768. default:
  10769. push2 = false;
  10770. break;
  10771. }
  10772. if (VideoSample && push2) {
  10773. const units2 = VideoSample.units;
  10774. units2.push(unit);
  10775. }
  10776. });
  10777. if (endOfSegment && VideoSample) {
  10778. this.pushAccessUnit(VideoSample, track);
  10779. this.VideoSample = null;
  10780. }
  10781. }
  10782. pushParameterSet(parameterSets, data, vps) {
  10783. if (vps && vps[0] === this.initVPS || !vps && !parameterSets.length) {
  10784. parameterSets.push(data);
  10785. }
  10786. }
  10787. getNALuType(data, offset) {
  10788. return (data[offset] & 126) >>> 1;
  10789. }
  10790. ebsp2rbsp(arr) {
  10791. const dst = new Uint8Array(arr.byteLength);
  10792. let dstIdx = 0;
  10793. for (let i = 0; i < arr.byteLength; i++) {
  10794. if (i >= 2) {
  10795. if (arr[i] === 3 && arr[i - 1] === 0 && arr[i - 2] === 0) {
  10796. continue;
  10797. }
  10798. }
  10799. dst[dstIdx] = arr[i];
  10800. dstIdx++;
  10801. }
  10802. return new Uint8Array(dst.buffer, 0, dstIdx);
  10803. }
  10804. pushAccessUnit(VideoSample, videoTrack) {
  10805. super.pushAccessUnit(VideoSample, videoTrack);
  10806. if (this.initVPS) {
  10807. this.initVPS = null;
  10808. }
  10809. }
  10810. readVPS(vps) {
  10811. const eg = new ExpGolomb(vps);
  10812. eg.readUByte();
  10813. eg.readUByte();
  10814. eg.readBits(4);
  10815. eg.skipBits(2);
  10816. eg.readBits(6);
  10817. const max_sub_layers_minus1 = eg.readBits(3);
  10818. const temporal_id_nesting_flag = eg.readBoolean();
  10819. return {
  10820. numTemporalLayers: max_sub_layers_minus1 + 1,
  10821. temporalIdNested: temporal_id_nesting_flag
  10822. };
  10823. }
  10824. readSPS(sps) {
  10825. const eg = new ExpGolomb(this.ebsp2rbsp(sps));
  10826. eg.readUByte();
  10827. eg.readUByte();
  10828. eg.readBits(4);
  10829. const max_sub_layers_minus1 = eg.readBits(3);
  10830. eg.readBoolean();
  10831. const general_profile_space = eg.readBits(2);
  10832. const general_tier_flag = eg.readBoolean();
  10833. const general_profile_idc = eg.readBits(5);
  10834. const general_profile_compatibility_flags_1 = eg.readUByte();
  10835. const general_profile_compatibility_flags_2 = eg.readUByte();
  10836. const general_profile_compatibility_flags_3 = eg.readUByte();
  10837. const general_profile_compatibility_flags_4 = eg.readUByte();
  10838. const general_constraint_indicator_flags_1 = eg.readUByte();
  10839. const general_constraint_indicator_flags_2 = eg.readUByte();
  10840. const general_constraint_indicator_flags_3 = eg.readUByte();
  10841. const general_constraint_indicator_flags_4 = eg.readUByte();
  10842. const general_constraint_indicator_flags_5 = eg.readUByte();
  10843. const general_constraint_indicator_flags_6 = eg.readUByte();
  10844. const general_level_idc = eg.readUByte();
  10845. const sub_layer_profile_present_flags = [];
  10846. const sub_layer_level_present_flags = [];
  10847. for (let i = 0; i < max_sub_layers_minus1; i++) {
  10848. sub_layer_profile_present_flags.push(eg.readBoolean());
  10849. sub_layer_level_present_flags.push(eg.readBoolean());
  10850. }
  10851. if (max_sub_layers_minus1 > 0) {
  10852. for (let i = max_sub_layers_minus1; i < 8; i++) {
  10853. eg.readBits(2);
  10854. }
  10855. }
  10856. for (let i = 0; i < max_sub_layers_minus1; i++) {
  10857. if (sub_layer_profile_present_flags[i]) {
  10858. eg.readUByte();
  10859. eg.readUByte();
  10860. eg.readUByte();
  10861. eg.readUByte();
  10862. eg.readUByte();
  10863. eg.readUByte();
  10864. eg.readUByte();
  10865. eg.readUByte();
  10866. eg.readUByte();
  10867. eg.readUByte();
  10868. eg.readUByte();
  10869. }
  10870. if (sub_layer_level_present_flags[i]) {
  10871. eg.readUByte();
  10872. }
  10873. }
  10874. eg.readUEG();
  10875. const chroma_format_idc = eg.readUEG();
  10876. if (chroma_format_idc == 3) {
  10877. eg.skipBits(1);
  10878. }
  10879. const pic_width_in_luma_samples = eg.readUEG();
  10880. const pic_height_in_luma_samples = eg.readUEG();
  10881. const conformance_window_flag = eg.readBoolean();
  10882. let pic_left_offset = 0, pic_right_offset = 0, pic_top_offset = 0, pic_bottom_offset = 0;
  10883. if (conformance_window_flag) {
  10884. pic_left_offset += eg.readUEG();
  10885. pic_right_offset += eg.readUEG();
  10886. pic_top_offset += eg.readUEG();
  10887. pic_bottom_offset += eg.readUEG();
  10888. }
  10889. const bit_depth_luma_minus8 = eg.readUEG();
  10890. const bit_depth_chroma_minus8 = eg.readUEG();
  10891. const log2_max_pic_order_cnt_lsb_minus4 = eg.readUEG();
  10892. const sub_layer_ordering_info_present_flag = eg.readBoolean();
  10893. for (let i = sub_layer_ordering_info_present_flag ? 0 : max_sub_layers_minus1; i <= max_sub_layers_minus1; i++) {
  10894. eg.skipUEG();
  10895. eg.skipUEG();
  10896. eg.skipUEG();
  10897. }
  10898. eg.skipUEG();
  10899. eg.skipUEG();
  10900. eg.skipUEG();
  10901. eg.skipUEG();
  10902. eg.skipUEG();
  10903. eg.skipUEG();
  10904. const scaling_list_enabled_flag = eg.readBoolean();
  10905. if (scaling_list_enabled_flag) {
  10906. const sps_scaling_list_data_present_flag = eg.readBoolean();
  10907. if (sps_scaling_list_data_present_flag) {
  10908. for (let sizeId = 0; sizeId < 4; sizeId++) {
  10909. for (let matrixId = 0; matrixId < (sizeId === 3 ? 2 : 6); matrixId++) {
  10910. const scaling_list_pred_mode_flag = eg.readBoolean();
  10911. if (!scaling_list_pred_mode_flag) {
  10912. eg.readUEG();
  10913. } else {
  10914. const coefNum = Math.min(64, 1 << 4 + (sizeId << 1));
  10915. if (sizeId > 1) {
  10916. eg.readEG();
  10917. }
  10918. for (let i = 0; i < coefNum; i++) {
  10919. eg.readEG();
  10920. }
  10921. }
  10922. }
  10923. }
  10924. }
  10925. }
  10926. eg.readBoolean();
  10927. eg.readBoolean();
  10928. const pcm_enabled_flag = eg.readBoolean();
  10929. if (pcm_enabled_flag) {
  10930. eg.readUByte();
  10931. eg.skipUEG();
  10932. eg.skipUEG();
  10933. eg.readBoolean();
  10934. }
  10935. const num_short_term_ref_pic_sets = eg.readUEG();
  10936. let num_delta_pocs = 0;
  10937. for (let i = 0; i < num_short_term_ref_pic_sets; i++) {
  10938. let inter_ref_pic_set_prediction_flag = false;
  10939. if (i !== 0) {
  10940. inter_ref_pic_set_prediction_flag = eg.readBoolean();
  10941. }
  10942. if (inter_ref_pic_set_prediction_flag) {
  10943. if (i === num_short_term_ref_pic_sets) {
  10944. eg.readUEG();
  10945. }
  10946. eg.readBoolean();
  10947. eg.readUEG();
  10948. let next_num_delta_pocs = 0;
  10949. for (let j = 0; j <= num_delta_pocs; j++) {
  10950. const used_by_curr_pic_flag = eg.readBoolean();
  10951. let use_delta_flag = false;
  10952. if (!used_by_curr_pic_flag) {
  10953. use_delta_flag = eg.readBoolean();
  10954. }
  10955. if (used_by_curr_pic_flag || use_delta_flag) {
  10956. next_num_delta_pocs++;
  10957. }
  10958. }
  10959. num_delta_pocs = next_num_delta_pocs;
  10960. } else {
  10961. const num_negative_pics = eg.readUEG();
  10962. const num_positive_pics = eg.readUEG();
  10963. num_delta_pocs = num_negative_pics + num_positive_pics;
  10964. for (let j = 0; j < num_negative_pics; j++) {
  10965. eg.readUEG();
  10966. eg.readBoolean();
  10967. }
  10968. for (let j = 0; j < num_positive_pics; j++) {
  10969. eg.readUEG();
  10970. eg.readBoolean();
  10971. }
  10972. }
  10973. }
  10974. const long_term_ref_pics_present_flag = eg.readBoolean();
  10975. if (long_term_ref_pics_present_flag) {
  10976. const num_long_term_ref_pics_sps = eg.readUEG();
  10977. for (let i = 0; i < num_long_term_ref_pics_sps; i++) {
  10978. for (let j = 0; j < log2_max_pic_order_cnt_lsb_minus4 + 4; j++) {
  10979. eg.readBits(1);
  10980. }
  10981. eg.readBits(1);
  10982. }
  10983. }
  10984. let min_spatial_segmentation_idc = 0;
  10985. let sar_width = 1, sar_height = 1;
  10986. let fps_fixed = true, fps_den = 1, fps_num = 0;
  10987. eg.readBoolean();
  10988. eg.readBoolean();
  10989. let default_display_window_flag = false;
  10990. const vui_parameters_present_flag = eg.readBoolean();
  10991. if (vui_parameters_present_flag) {
  10992. const aspect_ratio_info_present_flag = eg.readBoolean();
  10993. if (aspect_ratio_info_present_flag) {
  10994. const aspect_ratio_idc = eg.readUByte();
  10995. const sar_width_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2];
  10996. const sar_height_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
  10997. if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) {
  10998. sar_width = sar_width_table[aspect_ratio_idc - 1];
  10999. sar_height = sar_height_table[aspect_ratio_idc - 1];
  11000. } else if (aspect_ratio_idc === 255) {
  11001. sar_width = eg.readBits(16);
  11002. sar_height = eg.readBits(16);
  11003. }
  11004. }
  11005. const overscan_info_present_flag = eg.readBoolean();
  11006. if (overscan_info_present_flag) {
  11007. eg.readBoolean();
  11008. }
  11009. const video_signal_type_present_flag = eg.readBoolean();
  11010. if (video_signal_type_present_flag) {
  11011. eg.readBits(3);
  11012. eg.readBoolean();
  11013. const colour_description_present_flag = eg.readBoolean();
  11014. if (colour_description_present_flag) {
  11015. eg.readUByte();
  11016. eg.readUByte();
  11017. eg.readUByte();
  11018. }
  11019. }
  11020. const chroma_loc_info_present_flag = eg.readBoolean();
  11021. if (chroma_loc_info_present_flag) {
  11022. eg.readUEG();
  11023. eg.readUEG();
  11024. }
  11025. eg.readBoolean();
  11026. eg.readBoolean();
  11027. eg.readBoolean();
  11028. default_display_window_flag = eg.readBoolean();
  11029. if (default_display_window_flag) {
  11030. pic_left_offset += eg.readUEG();
  11031. pic_right_offset += eg.readUEG();
  11032. pic_top_offset += eg.readUEG();
  11033. pic_bottom_offset += eg.readUEG();
  11034. }
  11035. const vui_timing_info_present_flag = eg.readBoolean();
  11036. if (vui_timing_info_present_flag) {
  11037. fps_den = eg.readBits(32);
  11038. fps_num = eg.readBits(32);
  11039. const vui_poc_proportional_to_timing_flag = eg.readBoolean();
  11040. if (vui_poc_proportional_to_timing_flag) {
  11041. eg.readUEG();
  11042. }
  11043. const vui_hrd_parameters_present_flag = eg.readBoolean();
  11044. if (vui_hrd_parameters_present_flag) {
  11045. const nal_hrd_parameters_present_flag = eg.readBoolean();
  11046. const vcl_hrd_parameters_present_flag = eg.readBoolean();
  11047. let sub_pic_hrd_params_present_flag = false;
  11048. if (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag) {
  11049. sub_pic_hrd_params_present_flag = eg.readBoolean();
  11050. if (sub_pic_hrd_params_present_flag) {
  11051. eg.readUByte();
  11052. eg.readBits(5);
  11053. eg.readBoolean();
  11054. eg.readBits(5);
  11055. }
  11056. eg.readBits(4);
  11057. eg.readBits(4);
  11058. if (sub_pic_hrd_params_present_flag) {
  11059. eg.readBits(4);
  11060. }
  11061. eg.readBits(5);
  11062. eg.readBits(5);
  11063. eg.readBits(5);
  11064. }
  11065. for (let i = 0; i <= max_sub_layers_minus1; i++) {
  11066. fps_fixed = eg.readBoolean();
  11067. const fixed_pic_rate_within_cvs_flag = fps_fixed || eg.readBoolean();
  11068. let low_delay_hrd_flag = false;
  11069. if (fixed_pic_rate_within_cvs_flag) {
  11070. eg.readEG();
  11071. } else {
  11072. low_delay_hrd_flag = eg.readBoolean();
  11073. }
  11074. const cpb_cnt = low_delay_hrd_flag ? 1 : eg.readUEG() + 1;
  11075. if (nal_hrd_parameters_present_flag) {
  11076. for (let j = 0; j < cpb_cnt; j++) {
  11077. eg.readUEG();
  11078. eg.readUEG();
  11079. if (sub_pic_hrd_params_present_flag) {
  11080. eg.readUEG();
  11081. eg.readUEG();
  11082. }
  11083. eg.skipBits(1);
  11084. }
  11085. }
  11086. if (vcl_hrd_parameters_present_flag) {
  11087. for (let j = 0; j < cpb_cnt; j++) {
  11088. eg.readUEG();
  11089. eg.readUEG();
  11090. if (sub_pic_hrd_params_present_flag) {
  11091. eg.readUEG();
  11092. eg.readUEG();
  11093. }
  11094. eg.skipBits(1);
  11095. }
  11096. }
  11097. }
  11098. }
  11099. }
  11100. const bitstream_restriction_flag = eg.readBoolean();
  11101. if (bitstream_restriction_flag) {
  11102. eg.readBoolean();
  11103. eg.readBoolean();
  11104. eg.readBoolean();
  11105. min_spatial_segmentation_idc = eg.readUEG();
  11106. }
  11107. }
  11108. let width = pic_width_in_luma_samples, height = pic_height_in_luma_samples;
  11109. if (conformance_window_flag || default_display_window_flag) {
  11110. let chroma_scale_w = 1, chroma_scale_h = 1;
  11111. if (chroma_format_idc === 1) {
  11112. chroma_scale_w = chroma_scale_h = 2;
  11113. } else if (chroma_format_idc == 2) {
  11114. chroma_scale_w = 2;
  11115. }
  11116. width = pic_width_in_luma_samples - chroma_scale_w * pic_right_offset - chroma_scale_w * pic_left_offset;
  11117. height = pic_height_in_luma_samples - chroma_scale_h * pic_bottom_offset - chroma_scale_h * pic_top_offset;
  11118. }
  11119. const profile_space_string = general_profile_space ? ["A", "B", "C"][general_profile_space] : "";
  11120. const profile_compatibility_buf = general_profile_compatibility_flags_1 << 24 | general_profile_compatibility_flags_2 << 16 | general_profile_compatibility_flags_3 << 8 | general_profile_compatibility_flags_4;
  11121. let profile_compatibility_rev = 0;
  11122. for (let i = 0; i < 32; i++) {
  11123. profile_compatibility_rev = (profile_compatibility_rev | (profile_compatibility_buf >> i & 1) << 31 - i) >>> 0;
  11124. }
  11125. let profile_compatibility_flags_string = profile_compatibility_rev.toString(16);
  11126. if (general_profile_idc === 1 && profile_compatibility_flags_string === "2") {
  11127. profile_compatibility_flags_string = "6";
  11128. }
  11129. const tier_flag_string = general_tier_flag ? "H" : "L";
  11130. return {
  11131. codecString: `hvc1.${profile_space_string}${general_profile_idc}.${profile_compatibility_flags_string}.${tier_flag_string}${general_level_idc}.B0`,
  11132. params: {
  11133. general_tier_flag,
  11134. general_profile_idc,
  11135. general_profile_space,
  11136. general_profile_compatibility_flags: [general_profile_compatibility_flags_1, general_profile_compatibility_flags_2, general_profile_compatibility_flags_3, general_profile_compatibility_flags_4],
  11137. general_constraint_indicator_flags: [general_constraint_indicator_flags_1, general_constraint_indicator_flags_2, general_constraint_indicator_flags_3, general_constraint_indicator_flags_4, general_constraint_indicator_flags_5, general_constraint_indicator_flags_6],
  11138. general_level_idc,
  11139. bit_depth: bit_depth_luma_minus8 + 8,
  11140. bit_depth_luma_minus8,
  11141. bit_depth_chroma_minus8,
  11142. min_spatial_segmentation_idc,
  11143. chroma_format_idc,
  11144. frame_rate: {
  11145. fixed: fps_fixed,
  11146. fps: fps_num / fps_den
  11147. }
  11148. },
  11149. width,
  11150. height,
  11151. pixelRatio: [sar_width, sar_height]
  11152. };
  11153. }
  11154. readPPS(pps) {
  11155. const eg = new ExpGolomb(this.ebsp2rbsp(pps));
  11156. eg.readUByte();
  11157. eg.readUByte();
  11158. eg.skipUEG();
  11159. eg.skipUEG();
  11160. eg.skipBits(2);
  11161. eg.skipBits(3);
  11162. eg.skipBits(2);
  11163. eg.skipUEG();
  11164. eg.skipUEG();
  11165. eg.skipEG();
  11166. eg.skipBits(2);
  11167. const cu_qp_delta_enabled_flag = eg.readBoolean();
  11168. if (cu_qp_delta_enabled_flag) {
  11169. eg.skipUEG();
  11170. }
  11171. eg.skipEG();
  11172. eg.skipEG();
  11173. eg.skipBits(4);
  11174. const tiles_enabled_flag = eg.readBoolean();
  11175. const entropy_coding_sync_enabled_flag = eg.readBoolean();
  11176. let parallelismType = 1;
  11177. if (entropy_coding_sync_enabled_flag && tiles_enabled_flag) {
  11178. parallelismType = 0;
  11179. } else if (entropy_coding_sync_enabled_flag) {
  11180. parallelismType = 3;
  11181. } else if (tiles_enabled_flag) {
  11182. parallelismType = 2;
  11183. }
  11184. return {
  11185. parallelismType
  11186. };
  11187. }
  11188. matchSPS(sps1, sps2) {
  11189. return String.fromCharCode.apply(null, sps1).substr(3) === String.fromCharCode.apply(null, sps2).substr(3);
  11190. }
  11191. };
  11192. var PACKET_LENGTH = 188;
  11193. var TSDemuxer = class _TSDemuxer {
  11194. constructor(observer, config, typeSupported, logger2) {
  11195. this.logger = void 0;
  11196. this.observer = void 0;
  11197. this.config = void 0;
  11198. this.typeSupported = void 0;
  11199. this.sampleAes = null;
  11200. this.pmtParsed = false;
  11201. this.audioCodec = void 0;
  11202. this.videoCodec = void 0;
  11203. this._pmtId = -1;
  11204. this._videoTrack = void 0;
  11205. this._audioTrack = void 0;
  11206. this._id3Track = void 0;
  11207. this._txtTrack = void 0;
  11208. this.aacOverFlow = null;
  11209. this.remainderData = null;
  11210. this.videoParser = void 0;
  11211. this.observer = observer;
  11212. this.config = config;
  11213. this.typeSupported = typeSupported;
  11214. this.logger = logger2;
  11215. this.videoParser = null;
  11216. }
  11217. static probe(data, logger2) {
  11218. const syncOffset = _TSDemuxer.syncOffset(data);
  11219. if (syncOffset > 0) {
  11220. logger2.warn(`MPEG2-TS detected but first sync word found @ offset ${syncOffset}`);
  11221. }
  11222. return syncOffset !== -1;
  11223. }
  11224. static syncOffset(data) {
  11225. const length = data.length;
  11226. let scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;
  11227. let i = 0;
  11228. while (i < scanwindow) {
  11229. let foundPat = false;
  11230. let packetStart = -1;
  11231. let tsPackets = 0;
  11232. for (let j = i; j < length; j += PACKET_LENGTH) {
  11233. if (data[j] === 71 && (length - j === PACKET_LENGTH || data[j + PACKET_LENGTH] === 71)) {
  11234. tsPackets++;
  11235. if (packetStart === -1) {
  11236. packetStart = j;
  11237. if (packetStart !== 0) {
  11238. scanwindow = Math.min(packetStart + PACKET_LENGTH * 99, data.length - PACKET_LENGTH) + 1;
  11239. }
  11240. }
  11241. if (!foundPat) {
  11242. foundPat = parsePID(data, j) === 0;
  11243. }
  11244. if (foundPat && tsPackets > 1 && (packetStart === 0 && tsPackets > 2 || j + PACKET_LENGTH > scanwindow)) {
  11245. return packetStart;
  11246. }
  11247. } else if (tsPackets) {
  11248. return -1;
  11249. } else {
  11250. break;
  11251. }
  11252. }
  11253. i++;
  11254. }
  11255. return -1;
  11256. }
  11257. /**
  11258. * Creates a track model internal to demuxer used to drive remuxing input
  11259. */
  11260. static createTrack(type, duration) {
  11261. return {
  11262. container: type === "video" || type === "audio" ? "video/mp2t" : void 0,
  11263. type,
  11264. id: RemuxerTrackIdConfig[type],
  11265. pid: -1,
  11266. inputTimeScale: 9e4,
  11267. sequenceNumber: 0,
  11268. samples: [],
  11269. dropped: 0,
  11270. duration: type === "audio" ? duration : void 0
  11271. };
  11272. }
  11273. /**
  11274. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  11275. * Resets all internal track instances of the demuxer.
  11276. */
  11277. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  11278. this.pmtParsed = false;
  11279. this._pmtId = -1;
  11280. this._videoTrack = _TSDemuxer.createTrack("video");
  11281. this._videoTrack.duration = trackDuration;
  11282. this._audioTrack = _TSDemuxer.createTrack("audio", trackDuration);
  11283. this._id3Track = _TSDemuxer.createTrack("id3");
  11284. this._txtTrack = _TSDemuxer.createTrack("text");
  11285. this._audioTrack.segmentCodec = "aac";
  11286. this.aacOverFlow = null;
  11287. this.remainderData = null;
  11288. this.audioCodec = audioCodec;
  11289. this.videoCodec = videoCodec;
  11290. }
  11291. resetTimeStamp() {
  11292. }
  11293. resetContiguity() {
  11294. const {
  11295. _audioTrack,
  11296. _videoTrack,
  11297. _id3Track
  11298. } = this;
  11299. if (_audioTrack) {
  11300. _audioTrack.pesData = null;
  11301. }
  11302. if (_videoTrack) {
  11303. _videoTrack.pesData = null;
  11304. }
  11305. if (_id3Track) {
  11306. _id3Track.pesData = null;
  11307. }
  11308. this.aacOverFlow = null;
  11309. this.remainderData = null;
  11310. }
  11311. demux(data, timeOffset, isSampleAes = false, flush = false) {
  11312. if (!isSampleAes) {
  11313. this.sampleAes = null;
  11314. }
  11315. let pes;
  11316. const videoTrack = this._videoTrack;
  11317. const audioTrack = this._audioTrack;
  11318. const id3Track = this._id3Track;
  11319. const textTrack = this._txtTrack;
  11320. let videoPid = videoTrack.pid;
  11321. let videoData = videoTrack.pesData;
  11322. let audioPid = audioTrack.pid;
  11323. let id3Pid = id3Track.pid;
  11324. let audioData = audioTrack.pesData;
  11325. let id3Data = id3Track.pesData;
  11326. let unknownPID = null;
  11327. let pmtParsed = this.pmtParsed;
  11328. let pmtId = this._pmtId;
  11329. let len = data.length;
  11330. if (this.remainderData) {
  11331. data = appendUint8Array(this.remainderData, data);
  11332. len = data.length;
  11333. this.remainderData = null;
  11334. }
  11335. if (len < PACKET_LENGTH && !flush) {
  11336. this.remainderData = data;
  11337. return {
  11338. audioTrack,
  11339. videoTrack,
  11340. id3Track,
  11341. textTrack
  11342. };
  11343. }
  11344. const syncOffset = Math.max(0, _TSDemuxer.syncOffset(data));
  11345. len -= (len - syncOffset) % PACKET_LENGTH;
  11346. if (len < data.byteLength && !flush) {
  11347. this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
  11348. }
  11349. let tsPacketErrors = 0;
  11350. for (let start = syncOffset; start < len; start += PACKET_LENGTH) {
  11351. if (data[start] === 71) {
  11352. const stt = !!(data[start + 1] & 64);
  11353. const pid = parsePID(data, start);
  11354. const atf = (data[start + 3] & 48) >> 4;
  11355. let offset;
  11356. if (atf > 1) {
  11357. offset = start + 5 + data[start + 4];
  11358. if (offset === start + PACKET_LENGTH) {
  11359. continue;
  11360. }
  11361. } else {
  11362. offset = start + 4;
  11363. }
  11364. switch (pid) {
  11365. case videoPid:
  11366. if (stt) {
  11367. if (videoData && (pes = parsePES(videoData, this.logger))) {
  11368. if (this.videoParser === null) {
  11369. switch (videoTrack.segmentCodec) {
  11370. case "avc":
  11371. this.videoParser = new AvcVideoParser();
  11372. break;
  11373. case "hevc":
  11374. {
  11375. this.videoParser = new HevcVideoParser();
  11376. }
  11377. break;
  11378. }
  11379. }
  11380. if (this.videoParser !== null) {
  11381. this.videoParser.parsePES(videoTrack, textTrack, pes, false);
  11382. }
  11383. }
  11384. videoData = {
  11385. data: [],
  11386. size: 0
  11387. };
  11388. }
  11389. if (videoData) {
  11390. videoData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  11391. videoData.size += start + PACKET_LENGTH - offset;
  11392. }
  11393. break;
  11394. case audioPid:
  11395. if (stt) {
  11396. if (audioData && (pes = parsePES(audioData, this.logger))) {
  11397. switch (audioTrack.segmentCodec) {
  11398. case "aac":
  11399. this.parseAACPES(audioTrack, pes);
  11400. break;
  11401. case "mp3":
  11402. this.parseMPEGPES(audioTrack, pes);
  11403. break;
  11404. case "ac3":
  11405. {
  11406. this.parseAC3PES(audioTrack, pes);
  11407. }
  11408. break;
  11409. }
  11410. }
  11411. audioData = {
  11412. data: [],
  11413. size: 0
  11414. };
  11415. }
  11416. if (audioData) {
  11417. audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  11418. audioData.size += start + PACKET_LENGTH - offset;
  11419. }
  11420. break;
  11421. case id3Pid:
  11422. if (stt) {
  11423. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  11424. this.parseID3PES(id3Track, pes);
  11425. }
  11426. id3Data = {
  11427. data: [],
  11428. size: 0
  11429. };
  11430. }
  11431. if (id3Data) {
  11432. id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));
  11433. id3Data.size += start + PACKET_LENGTH - offset;
  11434. }
  11435. break;
  11436. case 0:
  11437. if (stt) {
  11438. offset += data[offset] + 1;
  11439. }
  11440. pmtId = this._pmtId = parsePAT(data, offset);
  11441. break;
  11442. case pmtId: {
  11443. if (stt) {
  11444. offset += data[offset] + 1;
  11445. }
  11446. const parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes, this.observer, this.logger);
  11447. videoPid = parsedPIDs.videoPid;
  11448. if (videoPid > 0) {
  11449. videoTrack.pid = videoPid;
  11450. videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;
  11451. }
  11452. audioPid = parsedPIDs.audioPid;
  11453. if (audioPid > 0) {
  11454. audioTrack.pid = audioPid;
  11455. audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;
  11456. }
  11457. id3Pid = parsedPIDs.id3Pid;
  11458. if (id3Pid > 0) {
  11459. id3Track.pid = id3Pid;
  11460. }
  11461. if (unknownPID !== null && !pmtParsed) {
  11462. this.logger.warn(`MPEG-TS PMT found at ${start} after unknown PID '${unknownPID}'. Backtracking to sync byte @${syncOffset} to parse all TS packets.`);
  11463. unknownPID = null;
  11464. start = syncOffset - 188;
  11465. }
  11466. pmtParsed = this.pmtParsed = true;
  11467. break;
  11468. }
  11469. case 17:
  11470. case 8191:
  11471. break;
  11472. default:
  11473. unknownPID = pid;
  11474. break;
  11475. }
  11476. } else {
  11477. tsPacketErrors++;
  11478. }
  11479. }
  11480. if (tsPacketErrors > 0) {
  11481. emitParsingError(this.observer, new Error(`Found ${tsPacketErrors} TS packet/s that do not start with 0x47`), void 0, this.logger);
  11482. }
  11483. videoTrack.pesData = videoData;
  11484. audioTrack.pesData = audioData;
  11485. id3Track.pesData = id3Data;
  11486. const demuxResult = {
  11487. audioTrack,
  11488. videoTrack,
  11489. id3Track,
  11490. textTrack
  11491. };
  11492. if (flush) {
  11493. this.extractRemainingSamples(demuxResult);
  11494. }
  11495. return demuxResult;
  11496. }
  11497. flush() {
  11498. const {
  11499. remainderData
  11500. } = this;
  11501. this.remainderData = null;
  11502. let result;
  11503. if (remainderData) {
  11504. result = this.demux(remainderData, -1, false, true);
  11505. } else {
  11506. result = {
  11507. videoTrack: this._videoTrack,
  11508. audioTrack: this._audioTrack,
  11509. id3Track: this._id3Track,
  11510. textTrack: this._txtTrack
  11511. };
  11512. }
  11513. this.extractRemainingSamples(result);
  11514. if (this.sampleAes) {
  11515. return this.decrypt(result, this.sampleAes);
  11516. }
  11517. return result;
  11518. }
  11519. extractRemainingSamples(demuxResult) {
  11520. const {
  11521. audioTrack,
  11522. videoTrack,
  11523. id3Track,
  11524. textTrack
  11525. } = demuxResult;
  11526. const videoData = videoTrack.pesData;
  11527. const audioData = audioTrack.pesData;
  11528. const id3Data = id3Track.pesData;
  11529. let pes;
  11530. if (videoData && (pes = parsePES(videoData, this.logger))) {
  11531. if (this.videoParser === null) {
  11532. switch (videoTrack.segmentCodec) {
  11533. case "avc":
  11534. this.videoParser = new AvcVideoParser();
  11535. break;
  11536. case "hevc":
  11537. {
  11538. this.videoParser = new HevcVideoParser();
  11539. }
  11540. break;
  11541. }
  11542. }
  11543. if (this.videoParser !== null) {
  11544. this.videoParser.parsePES(videoTrack, textTrack, pes, true);
  11545. videoTrack.pesData = null;
  11546. }
  11547. } else {
  11548. videoTrack.pesData = videoData;
  11549. }
  11550. if (audioData && (pes = parsePES(audioData, this.logger))) {
  11551. switch (audioTrack.segmentCodec) {
  11552. case "aac":
  11553. this.parseAACPES(audioTrack, pes);
  11554. break;
  11555. case "mp3":
  11556. this.parseMPEGPES(audioTrack, pes);
  11557. break;
  11558. case "ac3":
  11559. {
  11560. this.parseAC3PES(audioTrack, pes);
  11561. }
  11562. break;
  11563. }
  11564. audioTrack.pesData = null;
  11565. } else {
  11566. if (audioData != null && audioData.size) {
  11567. this.logger.log("last AAC PES packet truncated,might overlap between fragments");
  11568. }
  11569. audioTrack.pesData = audioData;
  11570. }
  11571. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  11572. this.parseID3PES(id3Track, pes);
  11573. id3Track.pesData = null;
  11574. } else {
  11575. id3Track.pesData = id3Data;
  11576. }
  11577. }
  11578. demuxSampleAes(data, keyData, timeOffset) {
  11579. const demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
  11580. const sampleAes = this.sampleAes = new SampleAesDecrypter(this.observer, this.config, keyData);
  11581. return this.decrypt(demuxResult, sampleAes);
  11582. }
  11583. decrypt(demuxResult, sampleAes) {
  11584. return new Promise((resolve) => {
  11585. const {
  11586. audioTrack,
  11587. videoTrack
  11588. } = demuxResult;
  11589. if (audioTrack.samples && audioTrack.segmentCodec === "aac") {
  11590. sampleAes.decryptAacSamples(audioTrack.samples, 0, () => {
  11591. if (videoTrack.samples) {
  11592. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  11593. resolve(demuxResult);
  11594. });
  11595. } else {
  11596. resolve(demuxResult);
  11597. }
  11598. });
  11599. } else if (videoTrack.samples) {
  11600. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  11601. resolve(demuxResult);
  11602. });
  11603. }
  11604. });
  11605. }
  11606. destroy() {
  11607. if (this.observer) {
  11608. this.observer.removeAllListeners();
  11609. }
  11610. this.config = this.logger = this.observer = null;
  11611. this.aacOverFlow = this.videoParser = this.remainderData = this.sampleAes = null;
  11612. this._videoTrack = this._audioTrack = this._id3Track = this._txtTrack = void 0;
  11613. }
  11614. parseAACPES(track, pes) {
  11615. let startOffset = 0;
  11616. const aacOverFlow = this.aacOverFlow;
  11617. let data = pes.data;
  11618. if (aacOverFlow) {
  11619. this.aacOverFlow = null;
  11620. const frameMissingBytes = aacOverFlow.missing;
  11621. const sampleLength = aacOverFlow.sample.unit.byteLength;
  11622. if (frameMissingBytes === -1) {
  11623. data = appendUint8Array(aacOverFlow.sample.unit, data);
  11624. } else {
  11625. const frameOverflowBytes = sampleLength - frameMissingBytes;
  11626. aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
  11627. track.samples.push(aacOverFlow.sample);
  11628. startOffset = aacOverFlow.missing;
  11629. }
  11630. }
  11631. let offset;
  11632. let len;
  11633. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  11634. if (isHeader$1(data, offset)) {
  11635. break;
  11636. }
  11637. }
  11638. if (offset !== startOffset) {
  11639. let reason;
  11640. const recoverable = offset < len - 1;
  11641. if (recoverable) {
  11642. reason = `AAC PES did not start with ADTS header,offset:${offset}`;
  11643. } else {
  11644. reason = "No ADTS header found in AAC PES";
  11645. }
  11646. emitParsingError(this.observer, new Error(reason), recoverable, this.logger);
  11647. if (!recoverable) {
  11648. return;
  11649. }
  11650. }
  11651. initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  11652. let pts;
  11653. if (pes.pts !== void 0) {
  11654. pts = pes.pts;
  11655. } else if (aacOverFlow) {
  11656. const frameDuration = getFrameDuration(track.samplerate);
  11657. pts = aacOverFlow.sample.pts + frameDuration;
  11658. } else {
  11659. this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");
  11660. return;
  11661. }
  11662. let frameIndex = 0;
  11663. let frame;
  11664. while (offset < len) {
  11665. frame = appendFrame$2(track, data, offset, pts, frameIndex);
  11666. offset += frame.length;
  11667. if (!frame.missing) {
  11668. frameIndex++;
  11669. for (; offset < len - 1; offset++) {
  11670. if (isHeader$1(data, offset)) {
  11671. break;
  11672. }
  11673. }
  11674. } else {
  11675. this.aacOverFlow = frame;
  11676. break;
  11677. }
  11678. }
  11679. }
  11680. parseMPEGPES(track, pes) {
  11681. const data = pes.data;
  11682. const length = data.length;
  11683. let frameIndex = 0;
  11684. let offset = 0;
  11685. const pts = pes.pts;
  11686. if (pts === void 0) {
  11687. this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");
  11688. return;
  11689. }
  11690. while (offset < length) {
  11691. if (isHeader(data, offset)) {
  11692. const frame = appendFrame$1(track, data, offset, pts, frameIndex);
  11693. if (frame) {
  11694. offset += frame.length;
  11695. frameIndex++;
  11696. } else {
  11697. break;
  11698. }
  11699. } else {
  11700. offset++;
  11701. }
  11702. }
  11703. }
  11704. parseAC3PES(track, pes) {
  11705. {
  11706. const data = pes.data;
  11707. const pts = pes.pts;
  11708. if (pts === void 0) {
  11709. this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");
  11710. return;
  11711. }
  11712. const length = data.length;
  11713. let frameIndex = 0;
  11714. let offset = 0;
  11715. let parsed;
  11716. while (offset < length && (parsed = appendFrame(track, data, offset, pts, frameIndex++)) > 0) {
  11717. offset += parsed;
  11718. }
  11719. }
  11720. }
  11721. parseID3PES(id3Track, pes) {
  11722. if (pes.pts === void 0) {
  11723. this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");
  11724. return;
  11725. }
  11726. const id3Sample = _extends({}, pes, {
  11727. type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,
  11728. duration: Number.POSITIVE_INFINITY
  11729. });
  11730. id3Track.samples.push(id3Sample);
  11731. }
  11732. };
  11733. function parsePID(data, offset) {
  11734. return ((data[offset + 1] & 31) << 8) + data[offset + 2];
  11735. }
  11736. function parsePAT(data, offset) {
  11737. return (data[offset + 10] & 31) << 8 | data[offset + 11];
  11738. }
  11739. function parsePMT(data, offset, typeSupported, isSampleAes, observer, logger2) {
  11740. const result = {
  11741. audioPid: -1,
  11742. videoPid: -1,
  11743. id3Pid: -1,
  11744. segmentVideoCodec: "avc",
  11745. segmentAudioCodec: "aac"
  11746. };
  11747. const sectionLength = (data[offset + 1] & 15) << 8 | data[offset + 2];
  11748. const tableEnd = offset + 3 + sectionLength - 4;
  11749. const programInfoLength = (data[offset + 10] & 15) << 8 | data[offset + 11];
  11750. offset += 12 + programInfoLength;
  11751. while (offset < tableEnd) {
  11752. const pid = parsePID(data, offset);
  11753. const esInfoLength = (data[offset + 3] & 15) << 8 | data[offset + 4];
  11754. switch (data[offset]) {
  11755. case 207:
  11756. if (!isSampleAes) {
  11757. logEncryptedSamplesFoundInUnencryptedStream("ADTS AAC", logger2);
  11758. break;
  11759. }
  11760. case 15:
  11761. if (result.audioPid === -1) {
  11762. result.audioPid = pid;
  11763. }
  11764. break;
  11765. case 21:
  11766. if (result.id3Pid === -1) {
  11767. result.id3Pid = pid;
  11768. }
  11769. break;
  11770. case 219:
  11771. if (!isSampleAes) {
  11772. logEncryptedSamplesFoundInUnencryptedStream("H.264", logger2);
  11773. break;
  11774. }
  11775. case 27:
  11776. if (result.videoPid === -1) {
  11777. result.videoPid = pid;
  11778. }
  11779. break;
  11780. case 3:
  11781. case 4:
  11782. if (!typeSupported.mpeg && !typeSupported.mp3) {
  11783. logger2.log("MPEG audio found, not supported in this browser");
  11784. } else if (result.audioPid === -1) {
  11785. result.audioPid = pid;
  11786. result.segmentAudioCodec = "mp3";
  11787. }
  11788. break;
  11789. case 193:
  11790. if (!isSampleAes) {
  11791. logEncryptedSamplesFoundInUnencryptedStream("AC-3", logger2);
  11792. break;
  11793. }
  11794. case 129:
  11795. {
  11796. if (!typeSupported.ac3) {
  11797. logger2.log("AC-3 audio found, not supported in this browser");
  11798. } else if (result.audioPid === -1) {
  11799. result.audioPid = pid;
  11800. result.segmentAudioCodec = "ac3";
  11801. }
  11802. }
  11803. break;
  11804. case 6:
  11805. if (result.audioPid === -1 && esInfoLength > 0) {
  11806. let parsePos = offset + 5;
  11807. let remaining = esInfoLength;
  11808. while (remaining > 2) {
  11809. const descriptorId = data[parsePos];
  11810. switch (descriptorId) {
  11811. case 106:
  11812. {
  11813. if (typeSupported.ac3 !== true) {
  11814. logger2.log("AC-3 audio found, not supported in this browser for now");
  11815. } else {
  11816. result.audioPid = pid;
  11817. result.segmentAudioCodec = "ac3";
  11818. }
  11819. }
  11820. break;
  11821. }
  11822. const descriptorLen = data[parsePos + 1] + 2;
  11823. parsePos += descriptorLen;
  11824. remaining -= descriptorLen;
  11825. }
  11826. }
  11827. break;
  11828. case 194:
  11829. case 135:
  11830. emitParsingError(observer, new Error("Unsupported EC-3 in M2TS found"), void 0, logger2);
  11831. return result;
  11832. case 36:
  11833. {
  11834. if (result.videoPid === -1) {
  11835. result.videoPid = pid;
  11836. result.segmentVideoCodec = "hevc";
  11837. logger2.log("HEVC in M2TS found");
  11838. }
  11839. }
  11840. break;
  11841. }
  11842. offset += esInfoLength + 5;
  11843. }
  11844. return result;
  11845. }
  11846. function emitParsingError(observer, error, levelRetry, logger2) {
  11847. logger2.warn(`parsing error: ${error.message}`);
  11848. observer.emit(Events.ERROR, Events.ERROR, {
  11849. type: ErrorTypes.MEDIA_ERROR,
  11850. details: ErrorDetails.FRAG_PARSING_ERROR,
  11851. fatal: false,
  11852. levelRetry,
  11853. error,
  11854. reason: error.message
  11855. });
  11856. }
  11857. function logEncryptedSamplesFoundInUnencryptedStream(type, logger2) {
  11858. logger2.log(`${type} with AES-128-CBC encryption found in unencrypted stream`);
  11859. }
  11860. function parsePES(stream, logger2) {
  11861. let i = 0;
  11862. let frag;
  11863. let pesLen;
  11864. let pesHdrLen;
  11865. let pesPts;
  11866. let pesDts;
  11867. const data = stream.data;
  11868. if (!stream || stream.size === 0) {
  11869. return null;
  11870. }
  11871. while (data[0].length < 19 && data.length > 1) {
  11872. data[0] = appendUint8Array(data[0], data[1]);
  11873. data.splice(1, 1);
  11874. }
  11875. frag = data[0];
  11876. const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  11877. if (pesPrefix === 1) {
  11878. pesLen = (frag[4] << 8) + frag[5];
  11879. if (pesLen && pesLen > stream.size - 6) {
  11880. return null;
  11881. }
  11882. const pesFlags = frag[7];
  11883. if (pesFlags & 192) {
  11884. pesPts = (frag[9] & 14) * 536870912 + // 1 << 29
  11885. (frag[10] & 255) * 4194304 + // 1 << 22
  11886. (frag[11] & 254) * 16384 + // 1 << 14
  11887. (frag[12] & 255) * 128 + // 1 << 7
  11888. (frag[13] & 254) / 2;
  11889. if (pesFlags & 64) {
  11890. pesDts = (frag[14] & 14) * 536870912 + // 1 << 29
  11891. (frag[15] & 255) * 4194304 + // 1 << 22
  11892. (frag[16] & 254) * 16384 + // 1 << 14
  11893. (frag[17] & 255) * 128 + // 1 << 7
  11894. (frag[18] & 254) / 2;
  11895. if (pesPts - pesDts > 60 * 9e4) {
  11896. logger2.warn(`${Math.round((pesPts - pesDts) / 9e4)}s delta between PTS and DTS, align them`);
  11897. pesPts = pesDts;
  11898. }
  11899. } else {
  11900. pesDts = pesPts;
  11901. }
  11902. }
  11903. pesHdrLen = frag[8];
  11904. let payloadStartOffset = pesHdrLen + 9;
  11905. if (stream.size <= payloadStartOffset) {
  11906. return null;
  11907. }
  11908. stream.size -= payloadStartOffset;
  11909. const pesData = new Uint8Array(stream.size);
  11910. for (let j = 0, dataLen = data.length; j < dataLen; j++) {
  11911. frag = data[j];
  11912. let len = frag.byteLength;
  11913. if (payloadStartOffset) {
  11914. if (payloadStartOffset > len) {
  11915. payloadStartOffset -= len;
  11916. continue;
  11917. } else {
  11918. frag = frag.subarray(payloadStartOffset);
  11919. len -= payloadStartOffset;
  11920. payloadStartOffset = 0;
  11921. }
  11922. }
  11923. pesData.set(frag, i);
  11924. i += len;
  11925. }
  11926. if (pesLen) {
  11927. pesLen -= pesHdrLen + 3;
  11928. }
  11929. return {
  11930. data: pesData,
  11931. pts: pesPts,
  11932. dts: pesDts,
  11933. len: pesLen
  11934. };
  11935. }
  11936. return null;
  11937. }
  11938. var AAC = class {
  11939. static getSilentFrame(codec, channelCount) {
  11940. switch (codec) {
  11941. case "mp4a.40.2":
  11942. if (channelCount === 1) {
  11943. return new Uint8Array([0, 200, 0, 128, 35, 128]);
  11944. } else if (channelCount === 2) {
  11945. return new Uint8Array([33, 0, 73, 144, 2, 25, 0, 35, 128]);
  11946. } else if (channelCount === 3) {
  11947. return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 142]);
  11948. } else if (channelCount === 4) {
  11949. return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 128, 44, 128, 8, 2, 56]);
  11950. } else if (channelCount === 5) {
  11951. return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 56]);
  11952. } else if (channelCount === 6) {
  11953. 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]);
  11954. }
  11955. break;
  11956. default:
  11957. if (channelCount === 1) {
  11958. 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]);
  11959. } else if (channelCount === 2) {
  11960. 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]);
  11961. } else if (channelCount === 3) {
  11962. 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]);
  11963. }
  11964. break;
  11965. }
  11966. return void 0;
  11967. }
  11968. };
  11969. var UINT32_MAX = Math.pow(2, 32) - 1;
  11970. var MP4 = class _MP4 {
  11971. static init() {
  11972. _MP4.types = {
  11973. avc1: [],
  11974. // codingname
  11975. avcC: [],
  11976. hvc1: [],
  11977. hvcC: [],
  11978. btrt: [],
  11979. dinf: [],
  11980. dref: [],
  11981. esds: [],
  11982. ftyp: [],
  11983. hdlr: [],
  11984. mdat: [],
  11985. mdhd: [],
  11986. mdia: [],
  11987. mfhd: [],
  11988. minf: [],
  11989. moof: [],
  11990. moov: [],
  11991. mp4a: [],
  11992. ".mp3": [],
  11993. dac3: [],
  11994. "ac-3": [],
  11995. mvex: [],
  11996. mvhd: [],
  11997. pasp: [],
  11998. sdtp: [],
  11999. stbl: [],
  12000. stco: [],
  12001. stsc: [],
  12002. stsd: [],
  12003. stsz: [],
  12004. stts: [],
  12005. tfdt: [],
  12006. tfhd: [],
  12007. traf: [],
  12008. trak: [],
  12009. trun: [],
  12010. trex: [],
  12011. tkhd: [],
  12012. vmhd: [],
  12013. smhd: []
  12014. };
  12015. let i;
  12016. for (i in _MP4.types) {
  12017. if (_MP4.types.hasOwnProperty(i)) {
  12018. _MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  12019. }
  12020. }
  12021. const videoHdlr = new Uint8Array([
  12022. 0,
  12023. // version 0
  12024. 0,
  12025. 0,
  12026. 0,
  12027. // flags
  12028. 0,
  12029. 0,
  12030. 0,
  12031. 0,
  12032. // pre_defined
  12033. 118,
  12034. 105,
  12035. 100,
  12036. 101,
  12037. // handler_type: 'vide'
  12038. 0,
  12039. 0,
  12040. 0,
  12041. 0,
  12042. // reserved
  12043. 0,
  12044. 0,
  12045. 0,
  12046. 0,
  12047. // reserved
  12048. 0,
  12049. 0,
  12050. 0,
  12051. 0,
  12052. // reserved
  12053. 86,
  12054. 105,
  12055. 100,
  12056. 101,
  12057. 111,
  12058. 72,
  12059. 97,
  12060. 110,
  12061. 100,
  12062. 108,
  12063. 101,
  12064. 114,
  12065. 0
  12066. // name: 'VideoHandler'
  12067. ]);
  12068. const audioHdlr = new Uint8Array([
  12069. 0,
  12070. // version 0
  12071. 0,
  12072. 0,
  12073. 0,
  12074. // flags
  12075. 0,
  12076. 0,
  12077. 0,
  12078. 0,
  12079. // pre_defined
  12080. 115,
  12081. 111,
  12082. 117,
  12083. 110,
  12084. // handler_type: 'soun'
  12085. 0,
  12086. 0,
  12087. 0,
  12088. 0,
  12089. // reserved
  12090. 0,
  12091. 0,
  12092. 0,
  12093. 0,
  12094. // reserved
  12095. 0,
  12096. 0,
  12097. 0,
  12098. 0,
  12099. // reserved
  12100. 83,
  12101. 111,
  12102. 117,
  12103. 110,
  12104. 100,
  12105. 72,
  12106. 97,
  12107. 110,
  12108. 100,
  12109. 108,
  12110. 101,
  12111. 114,
  12112. 0
  12113. // name: 'SoundHandler'
  12114. ]);
  12115. _MP4.HDLR_TYPES = {
  12116. video: videoHdlr,
  12117. audio: audioHdlr
  12118. };
  12119. const dref = new Uint8Array([
  12120. 0,
  12121. // version 0
  12122. 0,
  12123. 0,
  12124. 0,
  12125. // flags
  12126. 0,
  12127. 0,
  12128. 0,
  12129. 1,
  12130. // entry_count
  12131. 0,
  12132. 0,
  12133. 0,
  12134. 12,
  12135. // entry_size
  12136. 117,
  12137. 114,
  12138. 108,
  12139. 32,
  12140. // 'url' type
  12141. 0,
  12142. // version 0
  12143. 0,
  12144. 0,
  12145. 1
  12146. // entry_flags
  12147. ]);
  12148. const stco = new Uint8Array([
  12149. 0,
  12150. // version
  12151. 0,
  12152. 0,
  12153. 0,
  12154. // flags
  12155. 0,
  12156. 0,
  12157. 0,
  12158. 0
  12159. // entry_count
  12160. ]);
  12161. _MP4.STTS = _MP4.STSC = _MP4.STCO = stco;
  12162. _MP4.STSZ = new Uint8Array([
  12163. 0,
  12164. // version
  12165. 0,
  12166. 0,
  12167. 0,
  12168. // flags
  12169. 0,
  12170. 0,
  12171. 0,
  12172. 0,
  12173. // sample_size
  12174. 0,
  12175. 0,
  12176. 0,
  12177. 0
  12178. // sample_count
  12179. ]);
  12180. _MP4.VMHD = new Uint8Array([
  12181. 0,
  12182. // version
  12183. 0,
  12184. 0,
  12185. 1,
  12186. // flags
  12187. 0,
  12188. 0,
  12189. // graphicsmode
  12190. 0,
  12191. 0,
  12192. 0,
  12193. 0,
  12194. 0,
  12195. 0
  12196. // opcolor
  12197. ]);
  12198. _MP4.SMHD = new Uint8Array([
  12199. 0,
  12200. // version
  12201. 0,
  12202. 0,
  12203. 0,
  12204. // flags
  12205. 0,
  12206. 0,
  12207. // balance
  12208. 0,
  12209. 0
  12210. // reserved
  12211. ]);
  12212. _MP4.STSD = new Uint8Array([
  12213. 0,
  12214. // version 0
  12215. 0,
  12216. 0,
  12217. 0,
  12218. // flags
  12219. 0,
  12220. 0,
  12221. 0,
  12222. 1
  12223. ]);
  12224. const majorBrand = new Uint8Array([105, 115, 111, 109]);
  12225. const avc1Brand = new Uint8Array([97, 118, 99, 49]);
  12226. const minorVersion = new Uint8Array([0, 0, 0, 1]);
  12227. _MP4.FTYP = _MP4.box(_MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  12228. _MP4.DINF = _MP4.box(_MP4.types.dinf, _MP4.box(_MP4.types.dref, dref));
  12229. }
  12230. static box(type, ...payload) {
  12231. let size = 8;
  12232. let i = payload.length;
  12233. const len = i;
  12234. while (i--) {
  12235. size += payload[i].byteLength;
  12236. }
  12237. const result = new Uint8Array(size);
  12238. result[0] = size >> 24 & 255;
  12239. result[1] = size >> 16 & 255;
  12240. result[2] = size >> 8 & 255;
  12241. result[3] = size & 255;
  12242. result.set(type, 4);
  12243. for (i = 0, size = 8; i < len; i++) {
  12244. result.set(payload[i], size);
  12245. size += payload[i].byteLength;
  12246. }
  12247. return result;
  12248. }
  12249. static hdlr(type) {
  12250. return _MP4.box(_MP4.types.hdlr, _MP4.HDLR_TYPES[type]);
  12251. }
  12252. static mdat(data) {
  12253. return _MP4.box(_MP4.types.mdat, data);
  12254. }
  12255. static mdhd(timescale, duration) {
  12256. duration *= timescale;
  12257. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  12258. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  12259. return _MP4.box(_MP4.types.mdhd, new Uint8Array([
  12260. 1,
  12261. // version 1
  12262. 0,
  12263. 0,
  12264. 0,
  12265. // flags
  12266. 0,
  12267. 0,
  12268. 0,
  12269. 0,
  12270. 0,
  12271. 0,
  12272. 0,
  12273. 2,
  12274. // creation_time
  12275. 0,
  12276. 0,
  12277. 0,
  12278. 0,
  12279. 0,
  12280. 0,
  12281. 0,
  12282. 3,
  12283. // modification_time
  12284. timescale >> 24 & 255,
  12285. timescale >> 16 & 255,
  12286. timescale >> 8 & 255,
  12287. timescale & 255,
  12288. // timescale
  12289. upperWordDuration >> 24,
  12290. upperWordDuration >> 16 & 255,
  12291. upperWordDuration >> 8 & 255,
  12292. upperWordDuration & 255,
  12293. lowerWordDuration >> 24,
  12294. lowerWordDuration >> 16 & 255,
  12295. lowerWordDuration >> 8 & 255,
  12296. lowerWordDuration & 255,
  12297. 85,
  12298. 196,
  12299. // 'und' language (undetermined)
  12300. 0,
  12301. 0
  12302. ]));
  12303. }
  12304. static mdia(track) {
  12305. return _MP4.box(_MP4.types.mdia, _MP4.mdhd(track.timescale || 0, track.duration || 0), _MP4.hdlr(track.type), _MP4.minf(track));
  12306. }
  12307. static mfhd(sequenceNumber) {
  12308. return _MP4.box(_MP4.types.mfhd, new Uint8Array([
  12309. 0,
  12310. 0,
  12311. 0,
  12312. 0,
  12313. // flags
  12314. sequenceNumber >> 24,
  12315. sequenceNumber >> 16 & 255,
  12316. sequenceNumber >> 8 & 255,
  12317. sequenceNumber & 255
  12318. // sequence_number
  12319. ]));
  12320. }
  12321. static minf(track) {
  12322. if (track.type === "audio") {
  12323. return _MP4.box(_MP4.types.minf, _MP4.box(_MP4.types.smhd, _MP4.SMHD), _MP4.DINF, _MP4.stbl(track));
  12324. } else {
  12325. return _MP4.box(_MP4.types.minf, _MP4.box(_MP4.types.vmhd, _MP4.VMHD), _MP4.DINF, _MP4.stbl(track));
  12326. }
  12327. }
  12328. static moof(sn, baseMediaDecodeTime, track) {
  12329. return _MP4.box(_MP4.types.moof, _MP4.mfhd(sn), _MP4.traf(track, baseMediaDecodeTime));
  12330. }
  12331. static moov(tracks) {
  12332. let i = tracks.length;
  12333. const boxes = [];
  12334. while (i--) {
  12335. boxes[i] = _MP4.trak(tracks[i]);
  12336. }
  12337. return _MP4.box.apply(null, [_MP4.types.moov, _MP4.mvhd(tracks[0].timescale || 0, tracks[0].duration || 0)].concat(boxes).concat(_MP4.mvex(tracks)));
  12338. }
  12339. static mvex(tracks) {
  12340. let i = tracks.length;
  12341. const boxes = [];
  12342. while (i--) {
  12343. boxes[i] = _MP4.trex(tracks[i]);
  12344. }
  12345. return _MP4.box.apply(null, [_MP4.types.mvex, ...boxes]);
  12346. }
  12347. static mvhd(timescale, duration) {
  12348. duration *= timescale;
  12349. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  12350. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  12351. const bytes = new Uint8Array([
  12352. 1,
  12353. // version 1
  12354. 0,
  12355. 0,
  12356. 0,
  12357. // flags
  12358. 0,
  12359. 0,
  12360. 0,
  12361. 0,
  12362. 0,
  12363. 0,
  12364. 0,
  12365. 2,
  12366. // creation_time
  12367. 0,
  12368. 0,
  12369. 0,
  12370. 0,
  12371. 0,
  12372. 0,
  12373. 0,
  12374. 3,
  12375. // modification_time
  12376. timescale >> 24 & 255,
  12377. timescale >> 16 & 255,
  12378. timescale >> 8 & 255,
  12379. timescale & 255,
  12380. // timescale
  12381. upperWordDuration >> 24,
  12382. upperWordDuration >> 16 & 255,
  12383. upperWordDuration >> 8 & 255,
  12384. upperWordDuration & 255,
  12385. lowerWordDuration >> 24,
  12386. lowerWordDuration >> 16 & 255,
  12387. lowerWordDuration >> 8 & 255,
  12388. lowerWordDuration & 255,
  12389. 0,
  12390. 1,
  12391. 0,
  12392. 0,
  12393. // 1.0 rate
  12394. 1,
  12395. 0,
  12396. // 1.0 volume
  12397. 0,
  12398. 0,
  12399. // reserved
  12400. 0,
  12401. 0,
  12402. 0,
  12403. 0,
  12404. // reserved
  12405. 0,
  12406. 0,
  12407. 0,
  12408. 0,
  12409. // reserved
  12410. 0,
  12411. 1,
  12412. 0,
  12413. 0,
  12414. 0,
  12415. 0,
  12416. 0,
  12417. 0,
  12418. 0,
  12419. 0,
  12420. 0,
  12421. 0,
  12422. 0,
  12423. 0,
  12424. 0,
  12425. 0,
  12426. 0,
  12427. 1,
  12428. 0,
  12429. 0,
  12430. 0,
  12431. 0,
  12432. 0,
  12433. 0,
  12434. 0,
  12435. 0,
  12436. 0,
  12437. 0,
  12438. 0,
  12439. 0,
  12440. 0,
  12441. 0,
  12442. 64,
  12443. 0,
  12444. 0,
  12445. 0,
  12446. // transformation: unity matrix
  12447. 0,
  12448. 0,
  12449. 0,
  12450. 0,
  12451. 0,
  12452. 0,
  12453. 0,
  12454. 0,
  12455. 0,
  12456. 0,
  12457. 0,
  12458. 0,
  12459. 0,
  12460. 0,
  12461. 0,
  12462. 0,
  12463. 0,
  12464. 0,
  12465. 0,
  12466. 0,
  12467. 0,
  12468. 0,
  12469. 0,
  12470. 0,
  12471. // pre_defined
  12472. 255,
  12473. 255,
  12474. 255,
  12475. 255
  12476. // next_track_ID
  12477. ]);
  12478. return _MP4.box(_MP4.types.mvhd, bytes);
  12479. }
  12480. static sdtp(track) {
  12481. const samples = track.samples || [];
  12482. const bytes = new Uint8Array(4 + samples.length);
  12483. let i;
  12484. let flags;
  12485. for (i = 0; i < samples.length; i++) {
  12486. flags = samples[i].flags;
  12487. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  12488. }
  12489. return _MP4.box(_MP4.types.sdtp, bytes);
  12490. }
  12491. static stbl(track) {
  12492. return _MP4.box(_MP4.types.stbl, _MP4.stsd(track), _MP4.box(_MP4.types.stts, _MP4.STTS), _MP4.box(_MP4.types.stsc, _MP4.STSC), _MP4.box(_MP4.types.stsz, _MP4.STSZ), _MP4.box(_MP4.types.stco, _MP4.STCO));
  12493. }
  12494. static avc1(track) {
  12495. let sps = [];
  12496. let pps = [];
  12497. let i;
  12498. let data;
  12499. let len;
  12500. for (i = 0; i < track.sps.length; i++) {
  12501. data = track.sps[i];
  12502. len = data.byteLength;
  12503. sps.push(len >>> 8 & 255);
  12504. sps.push(len & 255);
  12505. sps = sps.concat(Array.prototype.slice.call(data));
  12506. }
  12507. for (i = 0; i < track.pps.length; i++) {
  12508. data = track.pps[i];
  12509. len = data.byteLength;
  12510. pps.push(len >>> 8 & 255);
  12511. pps.push(len & 255);
  12512. pps = pps.concat(Array.prototype.slice.call(data));
  12513. }
  12514. const avcc = _MP4.box(_MP4.types.avcC, new Uint8Array([
  12515. 1,
  12516. // version
  12517. sps[3],
  12518. // profile
  12519. sps[4],
  12520. // profile compat
  12521. sps[5],
  12522. // level
  12523. 252 | 3,
  12524. // lengthSizeMinusOne, hard-coded to 4 bytes
  12525. 224 | track.sps.length
  12526. // 3bit reserved (111) + numOfSequenceParameterSets
  12527. ].concat(sps).concat([
  12528. track.pps.length
  12529. // numOfPictureParameterSets
  12530. ]).concat(pps)));
  12531. const width = track.width;
  12532. const height = track.height;
  12533. const hSpacing = track.pixelRatio[0];
  12534. const vSpacing = track.pixelRatio[1];
  12535. return _MP4.box(
  12536. _MP4.types.avc1,
  12537. new Uint8Array([
  12538. 0,
  12539. 0,
  12540. 0,
  12541. // reserved
  12542. 0,
  12543. 0,
  12544. 0,
  12545. // reserved
  12546. 0,
  12547. 1,
  12548. // data_reference_index
  12549. 0,
  12550. 0,
  12551. // pre_defined
  12552. 0,
  12553. 0,
  12554. // reserved
  12555. 0,
  12556. 0,
  12557. 0,
  12558. 0,
  12559. 0,
  12560. 0,
  12561. 0,
  12562. 0,
  12563. 0,
  12564. 0,
  12565. 0,
  12566. 0,
  12567. // pre_defined
  12568. width >> 8 & 255,
  12569. width & 255,
  12570. // width
  12571. height >> 8 & 255,
  12572. height & 255,
  12573. // height
  12574. 0,
  12575. 72,
  12576. 0,
  12577. 0,
  12578. // horizresolution
  12579. 0,
  12580. 72,
  12581. 0,
  12582. 0,
  12583. // vertresolution
  12584. 0,
  12585. 0,
  12586. 0,
  12587. 0,
  12588. // reserved
  12589. 0,
  12590. 1,
  12591. // frame_count
  12592. 18,
  12593. 100,
  12594. 97,
  12595. 105,
  12596. 108,
  12597. // dailymotion/hls.js
  12598. 121,
  12599. 109,
  12600. 111,
  12601. 116,
  12602. 105,
  12603. 111,
  12604. 110,
  12605. 47,
  12606. 104,
  12607. 108,
  12608. 115,
  12609. 46,
  12610. 106,
  12611. 115,
  12612. 0,
  12613. 0,
  12614. 0,
  12615. 0,
  12616. 0,
  12617. 0,
  12618. 0,
  12619. 0,
  12620. 0,
  12621. 0,
  12622. 0,
  12623. 0,
  12624. 0,
  12625. // compressorname
  12626. 0,
  12627. 24,
  12628. // depth = 24
  12629. 17,
  12630. 17
  12631. ]),
  12632. // pre_defined = -1
  12633. avcc,
  12634. _MP4.box(_MP4.types.btrt, new Uint8Array([
  12635. 0,
  12636. 28,
  12637. 156,
  12638. 128,
  12639. // bufferSizeDB
  12640. 0,
  12641. 45,
  12642. 198,
  12643. 192,
  12644. // maxBitrate
  12645. 0,
  12646. 45,
  12647. 198,
  12648. 192
  12649. ])),
  12650. // avgBitrate
  12651. _MP4.box(_MP4.types.pasp, new Uint8Array([
  12652. hSpacing >> 24,
  12653. // hSpacing
  12654. hSpacing >> 16 & 255,
  12655. hSpacing >> 8 & 255,
  12656. hSpacing & 255,
  12657. vSpacing >> 24,
  12658. // vSpacing
  12659. vSpacing >> 16 & 255,
  12660. vSpacing >> 8 & 255,
  12661. vSpacing & 255
  12662. ]))
  12663. );
  12664. }
  12665. static esds(track) {
  12666. const config = track.config;
  12667. return new Uint8Array([
  12668. 0,
  12669. // version 0
  12670. 0,
  12671. 0,
  12672. 0,
  12673. // flags
  12674. 3,
  12675. // descriptor_type
  12676. 25,
  12677. // length
  12678. 0,
  12679. 1,
  12680. // es_id
  12681. 0,
  12682. // stream_priority
  12683. 4,
  12684. // descriptor_type
  12685. 17,
  12686. // length
  12687. 64,
  12688. // codec : mpeg4_audio
  12689. 21,
  12690. // stream_type
  12691. 0,
  12692. 0,
  12693. 0,
  12694. // buffer_size
  12695. 0,
  12696. 0,
  12697. 0,
  12698. 0,
  12699. // maxBitrate
  12700. 0,
  12701. 0,
  12702. 0,
  12703. 0,
  12704. // avgBitrate
  12705. 5,
  12706. // descriptor_type
  12707. 2,
  12708. // length
  12709. ...config,
  12710. 6,
  12711. 1,
  12712. 2
  12713. // GASpecificConfig)); // length + audio config descriptor
  12714. ]);
  12715. }
  12716. static audioStsd(track) {
  12717. const samplerate = track.samplerate || 0;
  12718. return new Uint8Array([
  12719. 0,
  12720. 0,
  12721. 0,
  12722. // reserved
  12723. 0,
  12724. 0,
  12725. 0,
  12726. // reserved
  12727. 0,
  12728. 1,
  12729. // data_reference_index
  12730. 0,
  12731. 0,
  12732. 0,
  12733. 0,
  12734. 0,
  12735. 0,
  12736. 0,
  12737. 0,
  12738. // reserved
  12739. 0,
  12740. track.channelCount || 0,
  12741. // channelcount
  12742. 0,
  12743. 16,
  12744. // sampleSize:16bits
  12745. 0,
  12746. 0,
  12747. 0,
  12748. 0,
  12749. // reserved2
  12750. samplerate >> 8 & 255,
  12751. samplerate & 255,
  12752. //
  12753. 0,
  12754. 0
  12755. ]);
  12756. }
  12757. static mp4a(track) {
  12758. return _MP4.box(_MP4.types.mp4a, _MP4.audioStsd(track), _MP4.box(_MP4.types.esds, _MP4.esds(track)));
  12759. }
  12760. static mp3(track) {
  12761. return _MP4.box(_MP4.types[".mp3"], _MP4.audioStsd(track));
  12762. }
  12763. static ac3(track) {
  12764. return _MP4.box(_MP4.types["ac-3"], _MP4.audioStsd(track), _MP4.box(_MP4.types.dac3, track.config));
  12765. }
  12766. static stsd(track) {
  12767. const {
  12768. segmentCodec
  12769. } = track;
  12770. if (track.type === "audio") {
  12771. if (segmentCodec === "aac") {
  12772. return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.mp4a(track));
  12773. }
  12774. if (segmentCodec === "ac3" && track.config) {
  12775. return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.ac3(track));
  12776. }
  12777. if (segmentCodec === "mp3" && track.codec === "mp3") {
  12778. return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.mp3(track));
  12779. }
  12780. } else {
  12781. if (track.pps && track.sps) {
  12782. if (segmentCodec === "avc") {
  12783. return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.avc1(track));
  12784. }
  12785. if (segmentCodec === "hevc" && track.vps) {
  12786. return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.hvc1(track));
  12787. }
  12788. } else {
  12789. throw new Error(`video track missing pps or sps`);
  12790. }
  12791. }
  12792. throw new Error(`unsupported ${track.type} segment codec (${segmentCodec}/${track.codec})`);
  12793. }
  12794. static tkhd(track) {
  12795. const id = track.id;
  12796. const duration = (track.duration || 0) * (track.timescale || 0);
  12797. const width = track.width || 0;
  12798. const height = track.height || 0;
  12799. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  12800. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  12801. return _MP4.box(_MP4.types.tkhd, new Uint8Array([
  12802. 1,
  12803. // version 1
  12804. 0,
  12805. 0,
  12806. 7,
  12807. // flags
  12808. 0,
  12809. 0,
  12810. 0,
  12811. 0,
  12812. 0,
  12813. 0,
  12814. 0,
  12815. 2,
  12816. // creation_time
  12817. 0,
  12818. 0,
  12819. 0,
  12820. 0,
  12821. 0,
  12822. 0,
  12823. 0,
  12824. 3,
  12825. // modification_time
  12826. id >> 24 & 255,
  12827. id >> 16 & 255,
  12828. id >> 8 & 255,
  12829. id & 255,
  12830. // track_ID
  12831. 0,
  12832. 0,
  12833. 0,
  12834. 0,
  12835. // reserved
  12836. upperWordDuration >> 24,
  12837. upperWordDuration >> 16 & 255,
  12838. upperWordDuration >> 8 & 255,
  12839. upperWordDuration & 255,
  12840. lowerWordDuration >> 24,
  12841. lowerWordDuration >> 16 & 255,
  12842. lowerWordDuration >> 8 & 255,
  12843. lowerWordDuration & 255,
  12844. 0,
  12845. 0,
  12846. 0,
  12847. 0,
  12848. 0,
  12849. 0,
  12850. 0,
  12851. 0,
  12852. // reserved
  12853. 0,
  12854. 0,
  12855. // layer
  12856. 0,
  12857. 0,
  12858. // alternate_group
  12859. 0,
  12860. 0,
  12861. // non-audio track volume
  12862. 0,
  12863. 0,
  12864. // reserved
  12865. 0,
  12866. 1,
  12867. 0,
  12868. 0,
  12869. 0,
  12870. 0,
  12871. 0,
  12872. 0,
  12873. 0,
  12874. 0,
  12875. 0,
  12876. 0,
  12877. 0,
  12878. 0,
  12879. 0,
  12880. 0,
  12881. 0,
  12882. 1,
  12883. 0,
  12884. 0,
  12885. 0,
  12886. 0,
  12887. 0,
  12888. 0,
  12889. 0,
  12890. 0,
  12891. 0,
  12892. 0,
  12893. 0,
  12894. 0,
  12895. 0,
  12896. 0,
  12897. 64,
  12898. 0,
  12899. 0,
  12900. 0,
  12901. // transformation: unity matrix
  12902. width >> 8 & 255,
  12903. width & 255,
  12904. 0,
  12905. 0,
  12906. // width
  12907. height >> 8 & 255,
  12908. height & 255,
  12909. 0,
  12910. 0
  12911. // height
  12912. ]));
  12913. }
  12914. static traf(track, baseMediaDecodeTime) {
  12915. const sampleDependencyTable = _MP4.sdtp(track);
  12916. const id = track.id;
  12917. const upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  12918. const lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  12919. return _MP4.box(
  12920. _MP4.types.traf,
  12921. _MP4.box(_MP4.types.tfhd, new Uint8Array([
  12922. 0,
  12923. // version 0
  12924. 0,
  12925. 0,
  12926. 0,
  12927. // flags
  12928. id >> 24,
  12929. id >> 16 & 255,
  12930. id >> 8 & 255,
  12931. id & 255
  12932. // track_ID
  12933. ])),
  12934. _MP4.box(_MP4.types.tfdt, new Uint8Array([
  12935. 1,
  12936. // version 1
  12937. 0,
  12938. 0,
  12939. 0,
  12940. // flags
  12941. upperWordBaseMediaDecodeTime >> 24,
  12942. upperWordBaseMediaDecodeTime >> 16 & 255,
  12943. upperWordBaseMediaDecodeTime >> 8 & 255,
  12944. upperWordBaseMediaDecodeTime & 255,
  12945. lowerWordBaseMediaDecodeTime >> 24,
  12946. lowerWordBaseMediaDecodeTime >> 16 & 255,
  12947. lowerWordBaseMediaDecodeTime >> 8 & 255,
  12948. lowerWordBaseMediaDecodeTime & 255
  12949. ])),
  12950. _MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd
  12951. 20 + // tfdt
  12952. 8 + // traf header
  12953. 16 + // mfhd
  12954. 8 + // moof header
  12955. 8),
  12956. // mdat header
  12957. sampleDependencyTable
  12958. );
  12959. }
  12960. /**
  12961. * Generate a track box.
  12962. * @param track a track definition
  12963. */
  12964. static trak(track) {
  12965. track.duration = track.duration || 4294967295;
  12966. return _MP4.box(_MP4.types.trak, _MP4.tkhd(track), _MP4.mdia(track));
  12967. }
  12968. static trex(track) {
  12969. const id = track.id;
  12970. return _MP4.box(_MP4.types.trex, new Uint8Array([
  12971. 0,
  12972. // version 0
  12973. 0,
  12974. 0,
  12975. 0,
  12976. // flags
  12977. id >> 24,
  12978. id >> 16 & 255,
  12979. id >> 8 & 255,
  12980. id & 255,
  12981. // track_ID
  12982. 0,
  12983. 0,
  12984. 0,
  12985. 1,
  12986. // default_sample_description_index
  12987. 0,
  12988. 0,
  12989. 0,
  12990. 0,
  12991. // default_sample_duration
  12992. 0,
  12993. 0,
  12994. 0,
  12995. 0,
  12996. // default_sample_size
  12997. 0,
  12998. 1,
  12999. 0,
  13000. 1
  13001. // default_sample_flags
  13002. ]));
  13003. }
  13004. static trun(track, offset) {
  13005. const samples = track.samples || [];
  13006. const len = samples.length;
  13007. const arraylen = 12 + 16 * len;
  13008. const array = new Uint8Array(arraylen);
  13009. let i;
  13010. let sample;
  13011. let duration;
  13012. let size;
  13013. let flags;
  13014. let cts;
  13015. offset += 8 + arraylen;
  13016. array.set([
  13017. track.type === "video" ? 1 : 0,
  13018. // version 1 for video with signed-int sample_composition_time_offset
  13019. 0,
  13020. 15,
  13021. 1,
  13022. // flags
  13023. len >>> 24 & 255,
  13024. len >>> 16 & 255,
  13025. len >>> 8 & 255,
  13026. len & 255,
  13027. // sample_count
  13028. offset >>> 24 & 255,
  13029. offset >>> 16 & 255,
  13030. offset >>> 8 & 255,
  13031. offset & 255
  13032. // data_offset
  13033. ], 0);
  13034. for (i = 0; i < len; i++) {
  13035. sample = samples[i];
  13036. duration = sample.duration;
  13037. size = sample.size;
  13038. flags = sample.flags;
  13039. cts = sample.cts;
  13040. array.set([
  13041. duration >>> 24 & 255,
  13042. duration >>> 16 & 255,
  13043. duration >>> 8 & 255,
  13044. duration & 255,
  13045. // sample_duration
  13046. size >>> 24 & 255,
  13047. size >>> 16 & 255,
  13048. size >>> 8 & 255,
  13049. size & 255,
  13050. // sample_size
  13051. flags.isLeading << 2 | flags.dependsOn,
  13052. flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync,
  13053. flags.degradPrio & 240 << 8,
  13054. flags.degradPrio & 15,
  13055. // sample_flags
  13056. cts >>> 24 & 255,
  13057. cts >>> 16 & 255,
  13058. cts >>> 8 & 255,
  13059. cts & 255
  13060. // sample_composition_time_offset
  13061. ], 12 + 16 * i);
  13062. }
  13063. return _MP4.box(_MP4.types.trun, array);
  13064. }
  13065. static initSegment(tracks) {
  13066. if (!_MP4.types) {
  13067. _MP4.init();
  13068. }
  13069. const movie = _MP4.moov(tracks);
  13070. const result = appendUint8Array(_MP4.FTYP, movie);
  13071. return result;
  13072. }
  13073. static hvc1(track) {
  13074. const ps = track.params;
  13075. const units = [track.vps, track.sps, track.pps];
  13076. const NALuLengthSize = 4;
  13077. const config = new Uint8Array([1, ps.general_profile_space << 6 | (ps.general_tier_flag ? 32 : 0) | ps.general_profile_idc, ps.general_profile_compatibility_flags[0], ps.general_profile_compatibility_flags[1], ps.general_profile_compatibility_flags[2], ps.general_profile_compatibility_flags[3], ps.general_constraint_indicator_flags[0], ps.general_constraint_indicator_flags[1], ps.general_constraint_indicator_flags[2], ps.general_constraint_indicator_flags[3], ps.general_constraint_indicator_flags[4], ps.general_constraint_indicator_flags[5], ps.general_level_idc, 240 | ps.min_spatial_segmentation_idc >> 8, 255 & ps.min_spatial_segmentation_idc, 252 | ps.parallelismType, 252 | ps.chroma_format_idc, 248 | ps.bit_depth_luma_minus8, 248 | ps.bit_depth_chroma_minus8, 0, parseInt(ps.frame_rate.fps), NALuLengthSize - 1 | ps.temporal_id_nested << 2 | ps.num_temporal_layers << 3 | (ps.frame_rate.fixed ? 64 : 0), units.length]);
  13078. let length = config.length;
  13079. for (let i = 0; i < units.length; i += 1) {
  13080. length += 3;
  13081. for (let j = 0; j < units[i].length; j += 1) {
  13082. length += 2 + units[i][j].length;
  13083. }
  13084. }
  13085. const hvcC = new Uint8Array(length);
  13086. hvcC.set(config, 0);
  13087. length = config.length;
  13088. const iMax = units.length - 1;
  13089. for (let i = 0; i < units.length; i += 1) {
  13090. hvcC.set(new Uint8Array([32 + i | (i === iMax ? 128 : 0), 0, units[i].length]), length);
  13091. length += 3;
  13092. for (let j = 0; j < units[i].length; j += 1) {
  13093. hvcC.set(new Uint8Array([units[i][j].length >> 8, units[i][j].length & 255]), length);
  13094. length += 2;
  13095. hvcC.set(units[i][j], length);
  13096. length += units[i][j].length;
  13097. }
  13098. }
  13099. const hvcc = _MP4.box(_MP4.types.hvcC, hvcC);
  13100. const width = track.width;
  13101. const height = track.height;
  13102. const hSpacing = track.pixelRatio[0];
  13103. const vSpacing = track.pixelRatio[1];
  13104. return _MP4.box(
  13105. _MP4.types.hvc1,
  13106. new Uint8Array([
  13107. 0,
  13108. 0,
  13109. 0,
  13110. // reserved
  13111. 0,
  13112. 0,
  13113. 0,
  13114. // reserved
  13115. 0,
  13116. 1,
  13117. // data_reference_index
  13118. 0,
  13119. 0,
  13120. // pre_defined
  13121. 0,
  13122. 0,
  13123. // reserved
  13124. 0,
  13125. 0,
  13126. 0,
  13127. 0,
  13128. 0,
  13129. 0,
  13130. 0,
  13131. 0,
  13132. 0,
  13133. 0,
  13134. 0,
  13135. 0,
  13136. // pre_defined
  13137. width >> 8 & 255,
  13138. width & 255,
  13139. // width
  13140. height >> 8 & 255,
  13141. height & 255,
  13142. // height
  13143. 0,
  13144. 72,
  13145. 0,
  13146. 0,
  13147. // horizresolution
  13148. 0,
  13149. 72,
  13150. 0,
  13151. 0,
  13152. // vertresolution
  13153. 0,
  13154. 0,
  13155. 0,
  13156. 0,
  13157. // reserved
  13158. 0,
  13159. 1,
  13160. // frame_count
  13161. 18,
  13162. 100,
  13163. 97,
  13164. 105,
  13165. 108,
  13166. // dailymotion/hls.js
  13167. 121,
  13168. 109,
  13169. 111,
  13170. 116,
  13171. 105,
  13172. 111,
  13173. 110,
  13174. 47,
  13175. 104,
  13176. 108,
  13177. 115,
  13178. 46,
  13179. 106,
  13180. 115,
  13181. 0,
  13182. 0,
  13183. 0,
  13184. 0,
  13185. 0,
  13186. 0,
  13187. 0,
  13188. 0,
  13189. 0,
  13190. 0,
  13191. 0,
  13192. 0,
  13193. 0,
  13194. // compressorname
  13195. 0,
  13196. 24,
  13197. // depth = 24
  13198. 17,
  13199. 17
  13200. ]),
  13201. // pre_defined = -1
  13202. hvcc,
  13203. _MP4.box(_MP4.types.btrt, new Uint8Array([
  13204. 0,
  13205. 28,
  13206. 156,
  13207. 128,
  13208. // bufferSizeDB
  13209. 0,
  13210. 45,
  13211. 198,
  13212. 192,
  13213. // maxBitrate
  13214. 0,
  13215. 45,
  13216. 198,
  13217. 192
  13218. ])),
  13219. // avgBitrate
  13220. _MP4.box(_MP4.types.pasp, new Uint8Array([
  13221. hSpacing >> 24,
  13222. // hSpacing
  13223. hSpacing >> 16 & 255,
  13224. hSpacing >> 8 & 255,
  13225. hSpacing & 255,
  13226. vSpacing >> 24,
  13227. // vSpacing
  13228. vSpacing >> 16 & 255,
  13229. vSpacing >> 8 & 255,
  13230. vSpacing & 255
  13231. ]))
  13232. );
  13233. }
  13234. };
  13235. MP4.types = void 0;
  13236. MP4.HDLR_TYPES = void 0;
  13237. MP4.STTS = void 0;
  13238. MP4.STSC = void 0;
  13239. MP4.STCO = void 0;
  13240. MP4.STSZ = void 0;
  13241. MP4.VMHD = void 0;
  13242. MP4.SMHD = void 0;
  13243. MP4.STSD = void 0;
  13244. MP4.FTYP = void 0;
  13245. MP4.DINF = void 0;
  13246. var MPEG_TS_CLOCK_FREQ_HZ = 9e4;
  13247. function toTimescaleFromBase(baseTime, destScale, srcBase = 1, round = false) {
  13248. const result = baseTime * destScale * srcBase;
  13249. return round ? Math.round(result) : result;
  13250. }
  13251. function toTimescaleFromScale(baseTime, destScale, srcScale = 1, round = false) {
  13252. return toTimescaleFromBase(baseTime, destScale, 1 / srcScale, round);
  13253. }
  13254. function toMsFromMpegTsClock(baseTime, round = false) {
  13255. return toTimescaleFromBase(baseTime, 1e3, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
  13256. }
  13257. function toMpegTsClockFromTimescale(baseTime, srcScale = 1) {
  13258. return toTimescaleFromBase(baseTime, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
  13259. }
  13260. var MAX_SILENT_FRAME_DURATION = 10 * 1e3;
  13261. var AAC_SAMPLES_PER_FRAME = 1024;
  13262. var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
  13263. var AC3_SAMPLES_PER_FRAME = 1536;
  13264. var chromeVersion = null;
  13265. var safariWebkitVersion = null;
  13266. function createMp4Sample(isKeyframe, duration, size, cts) {
  13267. return {
  13268. duration,
  13269. size,
  13270. cts,
  13271. flags: {
  13272. isLeading: 0,
  13273. isDependedOn: 0,
  13274. hasRedundancy: 0,
  13275. degradPrio: 0,
  13276. dependsOn: isKeyframe ? 2 : 1,
  13277. isNonSync: isKeyframe ? 0 : 1
  13278. }
  13279. };
  13280. }
  13281. var MP4Remuxer = class extends Logger {
  13282. constructor(observer, config, typeSupported, logger2) {
  13283. super("mp4-remuxer", logger2);
  13284. this.observer = void 0;
  13285. this.config = void 0;
  13286. this.typeSupported = void 0;
  13287. this.ISGenerated = false;
  13288. this._initPTS = null;
  13289. this._initDTS = null;
  13290. this.nextVideoTs = null;
  13291. this.nextAudioTs = null;
  13292. this.videoSampleDuration = null;
  13293. this.isAudioContiguous = false;
  13294. this.isVideoContiguous = false;
  13295. this.videoTrackConfig = void 0;
  13296. this.observer = observer;
  13297. this.config = config;
  13298. this.typeSupported = typeSupported;
  13299. this.ISGenerated = false;
  13300. if (chromeVersion === null) {
  13301. const userAgent = navigator.userAgent || "";
  13302. const result = userAgent.match(/Chrome\/(\d+)/i);
  13303. chromeVersion = result ? parseInt(result[1]) : 0;
  13304. }
  13305. if (safariWebkitVersion === null) {
  13306. const result = navigator.userAgent.match(/Safari\/(\d+)/i);
  13307. safariWebkitVersion = result ? parseInt(result[1]) : 0;
  13308. }
  13309. }
  13310. destroy() {
  13311. this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;
  13312. }
  13313. resetTimeStamp(defaultTimeStamp) {
  13314. this.log("initPTS & initDTS reset");
  13315. this._initPTS = this._initDTS = defaultTimeStamp;
  13316. }
  13317. resetNextTimestamp() {
  13318. this.log("reset next timestamp");
  13319. this.isVideoContiguous = false;
  13320. this.isAudioContiguous = false;
  13321. }
  13322. resetInitSegment() {
  13323. this.log("ISGenerated flag reset");
  13324. this.ISGenerated = false;
  13325. this.videoTrackConfig = void 0;
  13326. }
  13327. getVideoStartPts(videoSamples) {
  13328. let rolloverDetected = false;
  13329. const firstPts = videoSamples[0].pts;
  13330. const startPTS = videoSamples.reduce((minPTS, sample) => {
  13331. let pts = sample.pts;
  13332. let delta = pts - minPTS;
  13333. if (delta < -4294967296) {
  13334. rolloverDetected = true;
  13335. pts = normalizePts(pts, firstPts);
  13336. delta = pts - minPTS;
  13337. }
  13338. if (delta > 0) {
  13339. return minPTS;
  13340. }
  13341. return pts;
  13342. }, firstPts);
  13343. if (rolloverDetected) {
  13344. this.debug("PTS rollover detected");
  13345. }
  13346. return startPTS;
  13347. }
  13348. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
  13349. let video;
  13350. let audio;
  13351. let initSegment;
  13352. let text;
  13353. let id3;
  13354. let independent;
  13355. let audioTimeOffset = timeOffset;
  13356. let videoTimeOffset = timeOffset;
  13357. const hasAudio = audioTrack.pid > -1;
  13358. const hasVideo = videoTrack.pid > -1;
  13359. const length = videoTrack.samples.length;
  13360. const enoughAudioSamples = audioTrack.samples.length > 0;
  13361. const enoughVideoSamples = flush && length > 0 || length > 1;
  13362. const canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
  13363. if (canRemuxAvc) {
  13364. if (this.ISGenerated) {
  13365. var _videoTrack$pixelRati, _config$pixelRatio, _videoTrack$pixelRati2, _config$pixelRatio2;
  13366. const config = this.videoTrackConfig;
  13367. if (config && (videoTrack.width !== config.width || videoTrack.height !== config.height || ((_videoTrack$pixelRati = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati[0]) !== ((_config$pixelRatio = config.pixelRatio) == null ? void 0 : _config$pixelRatio[0]) || ((_videoTrack$pixelRati2 = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati2[1]) !== ((_config$pixelRatio2 = config.pixelRatio) == null ? void 0 : _config$pixelRatio2[1])) || !config && enoughVideoSamples || this.nextAudioTs === null && enoughAudioSamples) {
  13368. this.resetInitSegment();
  13369. }
  13370. }
  13371. if (!this.ISGenerated) {
  13372. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  13373. }
  13374. const isVideoContiguous = this.isVideoContiguous;
  13375. let firstKeyFrameIndex = -1;
  13376. let firstKeyFramePTS;
  13377. if (enoughVideoSamples) {
  13378. firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
  13379. if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
  13380. independent = true;
  13381. if (firstKeyFrameIndex > 0) {
  13382. this.warn(`Dropped ${firstKeyFrameIndex} out of ${length} video samples due to a missing keyframe`);
  13383. const startPTS = this.getVideoStartPts(videoTrack.samples);
  13384. videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
  13385. videoTrack.dropped += firstKeyFrameIndex;
  13386. videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale;
  13387. firstKeyFramePTS = videoTimeOffset;
  13388. } else if (firstKeyFrameIndex === -1) {
  13389. this.warn(`No keyframe found out of ${length} video samples`);
  13390. independent = false;
  13391. }
  13392. }
  13393. }
  13394. if (this.ISGenerated) {
  13395. if (enoughAudioSamples && enoughVideoSamples) {
  13396. const startPTS = this.getVideoStartPts(videoTrack.samples);
  13397. const tsDelta = normalizePts(audioTrack.samples[0].pts, startPTS) - startPTS;
  13398. const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
  13399. audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
  13400. videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
  13401. }
  13402. if (enoughAudioSamples) {
  13403. if (!audioTrack.samplerate) {
  13404. this.warn("regenerate InitSegment as audio detected");
  13405. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  13406. }
  13407. audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : void 0);
  13408. if (enoughVideoSamples) {
  13409. const audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;
  13410. if (!videoTrack.inputTimeScale) {
  13411. this.warn("regenerate InitSegment as video detected");
  13412. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  13413. }
  13414. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
  13415. }
  13416. } else if (enoughVideoSamples) {
  13417. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
  13418. }
  13419. if (video) {
  13420. video.firstKeyFrame = firstKeyFrameIndex;
  13421. video.independent = firstKeyFrameIndex !== -1;
  13422. video.firstKeyFramePTS = firstKeyFramePTS;
  13423. }
  13424. }
  13425. }
  13426. if (this.ISGenerated && this._initPTS && this._initDTS) {
  13427. if (id3Track.samples.length) {
  13428. id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS);
  13429. }
  13430. if (textTrack.samples.length) {
  13431. text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS);
  13432. }
  13433. }
  13434. return {
  13435. audio,
  13436. video,
  13437. initSegment,
  13438. independent,
  13439. text,
  13440. id3
  13441. };
  13442. }
  13443. generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset) {
  13444. const audioSamples = audioTrack.samples;
  13445. const videoSamples = videoTrack.samples;
  13446. const typeSupported = this.typeSupported;
  13447. const tracks = {};
  13448. const _initPTS = this._initPTS;
  13449. let computePTSDTS = !_initPTS || accurateTimeOffset;
  13450. let container = "audio/mp4";
  13451. let initPTS;
  13452. let initDTS;
  13453. let timescale;
  13454. let trackId;
  13455. if (computePTSDTS) {
  13456. initPTS = initDTS = Infinity;
  13457. }
  13458. if (audioTrack.config && audioSamples.length) {
  13459. audioTrack.timescale = audioTrack.samplerate;
  13460. switch (audioTrack.segmentCodec) {
  13461. case "mp3":
  13462. if (typeSupported.mpeg) {
  13463. container = "audio/mpeg";
  13464. audioTrack.codec = "";
  13465. } else if (typeSupported.mp3) {
  13466. audioTrack.codec = "mp3";
  13467. }
  13468. break;
  13469. case "ac3":
  13470. audioTrack.codec = "ac-3";
  13471. break;
  13472. }
  13473. tracks.audio = {
  13474. id: "audio",
  13475. container,
  13476. codec: audioTrack.codec,
  13477. initSegment: audioTrack.segmentCodec === "mp3" && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]),
  13478. metadata: {
  13479. channelCount: audioTrack.channelCount
  13480. }
  13481. };
  13482. if (computePTSDTS) {
  13483. trackId = audioTrack.id;
  13484. timescale = audioTrack.inputTimeScale;
  13485. if (!_initPTS || timescale !== _initPTS.timescale) {
  13486. initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
  13487. } else {
  13488. computePTSDTS = false;
  13489. }
  13490. }
  13491. }
  13492. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  13493. videoTrack.timescale = videoTrack.inputTimeScale;
  13494. tracks.video = {
  13495. id: "main",
  13496. container: "video/mp4",
  13497. codec: videoTrack.codec,
  13498. initSegment: MP4.initSegment([videoTrack]),
  13499. metadata: {
  13500. width: videoTrack.width,
  13501. height: videoTrack.height
  13502. }
  13503. };
  13504. if (computePTSDTS) {
  13505. trackId = videoTrack.id;
  13506. timescale = videoTrack.inputTimeScale;
  13507. if (!_initPTS || timescale !== _initPTS.timescale) {
  13508. const startPTS = this.getVideoStartPts(videoSamples);
  13509. const startOffset = Math.round(timescale * timeOffset);
  13510. initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
  13511. initPTS = Math.min(initPTS, startPTS - startOffset);
  13512. } else {
  13513. computePTSDTS = false;
  13514. }
  13515. }
  13516. this.videoTrackConfig = {
  13517. width: videoTrack.width,
  13518. height: videoTrack.height,
  13519. pixelRatio: videoTrack.pixelRatio
  13520. };
  13521. }
  13522. if (Object.keys(tracks).length) {
  13523. this.ISGenerated = true;
  13524. if (computePTSDTS) {
  13525. this._initPTS = {
  13526. baseTime: initPTS,
  13527. timescale
  13528. };
  13529. this._initDTS = {
  13530. baseTime: initDTS,
  13531. timescale
  13532. };
  13533. } else {
  13534. initPTS = timescale = void 0;
  13535. }
  13536. return {
  13537. tracks,
  13538. initPTS,
  13539. timescale,
  13540. trackId
  13541. };
  13542. }
  13543. }
  13544. remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
  13545. const timeScale = track.inputTimeScale;
  13546. const inputSamples = track.samples;
  13547. const outputSamples = [];
  13548. const nbSamples = inputSamples.length;
  13549. const initPTS = this._initPTS;
  13550. const initTime = initPTS.baseTime * timeScale / initPTS.timescale;
  13551. let nextVideoTs = this.nextVideoTs;
  13552. let offset = 8;
  13553. let mp4SampleDuration = this.videoSampleDuration;
  13554. let firstDTS;
  13555. let lastDTS;
  13556. let minPTS = Number.POSITIVE_INFINITY;
  13557. let maxPTS = Number.NEGATIVE_INFINITY;
  13558. let sortSamples = false;
  13559. if (!contiguous || nextVideoTs === null) {
  13560. const pts = initTime + timeOffset * timeScale;
  13561. const cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts);
  13562. if (chromeVersion && nextVideoTs !== null && Math.abs(pts - cts - (nextVideoTs + initTime)) < 15e3) {
  13563. contiguous = true;
  13564. } else {
  13565. nextVideoTs = pts - cts - initTime;
  13566. }
  13567. }
  13568. const nextVideoPts = nextVideoTs + initTime;
  13569. for (let i = 0; i < nbSamples; i++) {
  13570. const sample = inputSamples[i];
  13571. sample.pts = normalizePts(sample.pts, nextVideoPts);
  13572. sample.dts = normalizePts(sample.dts, nextVideoPts);
  13573. if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
  13574. sortSamples = true;
  13575. }
  13576. }
  13577. if (sortSamples) {
  13578. inputSamples.sort(function(a, b) {
  13579. const deltadts = a.dts - b.dts;
  13580. const deltapts = a.pts - b.pts;
  13581. return deltadts || deltapts;
  13582. });
  13583. }
  13584. firstDTS = inputSamples[0].dts;
  13585. lastDTS = inputSamples[inputSamples.length - 1].dts;
  13586. const inputDuration = lastDTS - firstDTS;
  13587. const averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track.inputTimeScale / 30;
  13588. if (contiguous) {
  13589. const delta = firstDTS - nextVideoPts;
  13590. const foundHole = delta > averageSampleDuration;
  13591. const foundOverlap = delta < -1;
  13592. if (foundHole || foundOverlap) {
  13593. if (foundHole) {
  13594. this.warn(`${(track.segmentCodec || "").toUpperCase()}: ${toMsFromMpegTsClock(delta, true)} ms (${delta}dts) hole between fragments detected at ${timeOffset.toFixed(3)}`);
  13595. } else {
  13596. this.warn(`${(track.segmentCodec || "").toUpperCase()}: ${toMsFromMpegTsClock(-delta, true)} ms (${delta}dts) overlapping between fragments detected at ${timeOffset.toFixed(3)}`);
  13597. }
  13598. if (!foundOverlap || nextVideoPts >= inputSamples[0].pts || chromeVersion) {
  13599. firstDTS = nextVideoPts;
  13600. const firstPTS = inputSamples[0].pts - delta;
  13601. if (foundHole) {
  13602. inputSamples[0].dts = firstDTS;
  13603. inputSamples[0].pts = firstPTS;
  13604. } else {
  13605. let isPTSOrderRetained = true;
  13606. for (let i = 0; i < inputSamples.length; i++) {
  13607. if (inputSamples[i].dts > firstPTS && isPTSOrderRetained) {
  13608. break;
  13609. }
  13610. const prevPTS = inputSamples[i].pts;
  13611. inputSamples[i].dts -= delta;
  13612. inputSamples[i].pts -= delta;
  13613. if (i < inputSamples.length - 1) {
  13614. const nextSamplePTS = inputSamples[i + 1].pts;
  13615. const currentSamplePTS = inputSamples[i].pts;
  13616. const currentOrder = nextSamplePTS <= currentSamplePTS;
  13617. const prevOrder = nextSamplePTS <= prevPTS;
  13618. isPTSOrderRetained = currentOrder == prevOrder;
  13619. }
  13620. }
  13621. }
  13622. this.log(`Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(firstPTS, true)}/${toMsFromMpegTsClock(firstDTS, true)}, delta: ${toMsFromMpegTsClock(delta, true)} ms`);
  13623. }
  13624. }
  13625. }
  13626. firstDTS = Math.max(0, firstDTS);
  13627. let nbNalu = 0;
  13628. let naluLen = 0;
  13629. let dtsStep = firstDTS;
  13630. for (let i = 0; i < nbSamples; i++) {
  13631. const sample = inputSamples[i];
  13632. const units = sample.units;
  13633. const nbUnits = units.length;
  13634. let sampleLen = 0;
  13635. for (let j = 0; j < nbUnits; j++) {
  13636. sampleLen += units[j].data.length;
  13637. }
  13638. naluLen += sampleLen;
  13639. nbNalu += nbUnits;
  13640. sample.length = sampleLen;
  13641. if (sample.dts < dtsStep) {
  13642. sample.dts = dtsStep;
  13643. dtsStep += averageSampleDuration / 4 | 0 || 1;
  13644. } else {
  13645. dtsStep = sample.dts;
  13646. }
  13647. minPTS = Math.min(sample.pts, minPTS);
  13648. maxPTS = Math.max(sample.pts, maxPTS);
  13649. }
  13650. lastDTS = inputSamples[nbSamples - 1].dts;
  13651. const mdatSize = naluLen + 4 * nbNalu + 8;
  13652. let mdat;
  13653. try {
  13654. mdat = new Uint8Array(mdatSize);
  13655. } catch (err) {
  13656. this.observer.emit(Events.ERROR, Events.ERROR, {
  13657. type: ErrorTypes.MUX_ERROR,
  13658. details: ErrorDetails.REMUX_ALLOC_ERROR,
  13659. fatal: false,
  13660. error: err,
  13661. bytes: mdatSize,
  13662. reason: `fail allocating video mdat ${mdatSize}`
  13663. });
  13664. return;
  13665. }
  13666. const view2 = new DataView(mdat.buffer);
  13667. view2.setUint32(0, mdatSize);
  13668. mdat.set(MP4.types.mdat, 4);
  13669. let stretchedLastFrame = false;
  13670. let minDtsDelta = Number.POSITIVE_INFINITY;
  13671. let minPtsDelta = Number.POSITIVE_INFINITY;
  13672. let maxDtsDelta = Number.NEGATIVE_INFINITY;
  13673. let maxPtsDelta = Number.NEGATIVE_INFINITY;
  13674. for (let i = 0; i < nbSamples; i++) {
  13675. const VideoSample = inputSamples[i];
  13676. const VideoSampleUnits = VideoSample.units;
  13677. let mp4SampleLength = 0;
  13678. for (let j = 0, nbUnits = VideoSampleUnits.length; j < nbUnits; j++) {
  13679. const unit = VideoSampleUnits[j];
  13680. const unitData = unit.data;
  13681. const unitDataLen = unit.data.byteLength;
  13682. view2.setUint32(offset, unitDataLen);
  13683. offset += 4;
  13684. mdat.set(unitData, offset);
  13685. offset += unitDataLen;
  13686. mp4SampleLength += 4 + unitDataLen;
  13687. }
  13688. let ptsDelta;
  13689. if (i < nbSamples - 1) {
  13690. mp4SampleDuration = inputSamples[i + 1].dts - VideoSample.dts;
  13691. ptsDelta = inputSamples[i + 1].pts - VideoSample.pts;
  13692. } else {
  13693. const config = this.config;
  13694. const lastFrameDuration = i > 0 ? VideoSample.dts - inputSamples[i - 1].dts : averageSampleDuration;
  13695. ptsDelta = i > 0 ? VideoSample.pts - inputSamples[i - 1].pts : averageSampleDuration;
  13696. if (config.stretchShortVideoTrack && this.nextAudioTs !== null) {
  13697. const gapTolerance = Math.floor(config.maxBufferHole * timeScale);
  13698. const deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioTs + initTime) - VideoSample.pts;
  13699. if (deltaToFrameEnd > gapTolerance) {
  13700. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  13701. if (mp4SampleDuration < 0) {
  13702. mp4SampleDuration = lastFrameDuration;
  13703. } else {
  13704. stretchedLastFrame = true;
  13705. }
  13706. this.log(`It is approximately ${deltaToFrameEnd / 90} ms to the next segment; using duration ${mp4SampleDuration / 90} ms for the last video frame.`);
  13707. } else {
  13708. mp4SampleDuration = lastFrameDuration;
  13709. }
  13710. } else {
  13711. mp4SampleDuration = lastFrameDuration;
  13712. }
  13713. }
  13714. const compositionTimeOffset = Math.round(VideoSample.pts - VideoSample.dts);
  13715. minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);
  13716. maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);
  13717. minPtsDelta = Math.min(minPtsDelta, ptsDelta);
  13718. maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);
  13719. outputSamples.push(createMp4Sample(VideoSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
  13720. }
  13721. if (outputSamples.length) {
  13722. if (chromeVersion) {
  13723. if (chromeVersion < 70) {
  13724. const flags = outputSamples[0].flags;
  13725. flags.dependsOn = 2;
  13726. flags.isNonSync = 0;
  13727. }
  13728. } else if (safariWebkitVersion) {
  13729. if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) {
  13730. this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");
  13731. let dts = firstDTS;
  13732. for (let i = 0, len = outputSamples.length; i < len; i++) {
  13733. const nextDts = dts + outputSamples[i].duration;
  13734. const pts = dts + outputSamples[i].cts;
  13735. if (i < len - 1) {
  13736. const nextPts = nextDts + outputSamples[i + 1].cts;
  13737. outputSamples[i].duration = nextPts - pts;
  13738. } else {
  13739. outputSamples[i].duration = i ? outputSamples[i - 1].duration : averageSampleDuration;
  13740. }
  13741. outputSamples[i].cts = 0;
  13742. dts = nextDts;
  13743. }
  13744. }
  13745. }
  13746. }
  13747. mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration;
  13748. const endDTS = lastDTS + mp4SampleDuration;
  13749. this.nextVideoTs = nextVideoTs = endDTS - initTime;
  13750. this.videoSampleDuration = mp4SampleDuration;
  13751. this.isVideoContiguous = true;
  13752. const moof = MP4.moof(track.sequenceNumber++, firstDTS, _extends(track, {
  13753. samples: outputSamples
  13754. }));
  13755. const type = "video";
  13756. const data = {
  13757. data1: moof,
  13758. data2: mdat,
  13759. startPTS: (minPTS - initTime) / timeScale,
  13760. endPTS: (maxPTS + mp4SampleDuration - initTime) / timeScale,
  13761. startDTS: (firstDTS - initTime) / timeScale,
  13762. endDTS: nextVideoTs / timeScale,
  13763. type,
  13764. hasAudio: false,
  13765. hasVideo: true,
  13766. nb: outputSamples.length,
  13767. dropped: track.dropped
  13768. };
  13769. track.samples = [];
  13770. track.dropped = 0;
  13771. return data;
  13772. }
  13773. getSamplesPerFrame(track) {
  13774. switch (track.segmentCodec) {
  13775. case "mp3":
  13776. return MPEG_AUDIO_SAMPLE_PER_FRAME;
  13777. case "ac3":
  13778. return AC3_SAMPLES_PER_FRAME;
  13779. default:
  13780. return AAC_SAMPLES_PER_FRAME;
  13781. }
  13782. }
  13783. remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
  13784. const inputTimeScale = track.inputTimeScale;
  13785. const mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  13786. const scaleFactor = inputTimeScale / mp4timeScale;
  13787. const mp4SampleDuration = this.getSamplesPerFrame(track);
  13788. const inputSampleDuration = mp4SampleDuration * scaleFactor;
  13789. const initPTS = this._initPTS;
  13790. const rawMPEG = track.segmentCodec === "mp3" && this.typeSupported.mpeg;
  13791. const outputSamples = [];
  13792. const alignedWithVideo = videoTimeOffset !== void 0;
  13793. let inputSamples = track.samples;
  13794. let offset = rawMPEG ? 0 : 8;
  13795. let nextAudioTs = this.nextAudioTs || -1;
  13796. const initTime = initPTS.baseTime * inputTimeScale / initPTS.timescale;
  13797. const timeOffsetMpegTS = initTime + timeOffset * inputTimeScale;
  13798. this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioTs > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - (nextAudioTs + initTime)) < 9e3 || Math.abs(normalizePts(inputSamples[0].pts, timeOffsetMpegTS) - (nextAudioTs + initTime)) < 20 * inputSampleDuration);
  13799. inputSamples.forEach(function(sample) {
  13800. sample.pts = normalizePts(sample.pts, timeOffsetMpegTS);
  13801. });
  13802. if (!contiguous || nextAudioTs < 0) {
  13803. inputSamples = inputSamples.filter((sample) => sample.pts >= 0);
  13804. if (!inputSamples.length) {
  13805. return;
  13806. }
  13807. if (videoTimeOffset === 0) {
  13808. nextAudioTs = 0;
  13809. } else if (accurateTimeOffset && !alignedWithVideo) {
  13810. nextAudioTs = Math.max(0, timeOffsetMpegTS - initTime);
  13811. } else {
  13812. nextAudioTs = inputSamples[0].pts - initTime;
  13813. }
  13814. }
  13815. if (track.segmentCodec === "aac") {
  13816. const maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  13817. for (let i = 0, nextPts = nextAudioTs + initTime; i < inputSamples.length; i++) {
  13818. const sample = inputSamples[i];
  13819. const pts = sample.pts;
  13820. const delta = pts - nextPts;
  13821. const duration = Math.abs(1e3 * delta / inputTimeScale);
  13822. if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
  13823. if (i === 0) {
  13824. this.warn(`Audio frame @ ${(pts / inputTimeScale).toFixed(3)}s overlaps marker by ${Math.round(1e3 * delta / inputTimeScale)} ms.`);
  13825. this.nextAudioTs = nextAudioTs = pts - initTime;
  13826. nextPts = pts;
  13827. }
  13828. } else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
  13829. let missing = Math.round(delta / inputSampleDuration);
  13830. nextPts = pts - missing * inputSampleDuration;
  13831. while (nextPts < 0 && missing && inputSampleDuration) {
  13832. missing--;
  13833. nextPts += inputSampleDuration;
  13834. }
  13835. if (i === 0) {
  13836. this.nextAudioTs = nextAudioTs = nextPts - initTime;
  13837. }
  13838. this.warn(`Injecting ${missing} audio frames @ ${((nextPts - initTime) / inputTimeScale).toFixed(3)}s due to ${Math.round(1e3 * delta / inputTimeScale)} ms gap.`);
  13839. for (let j = 0; j < missing; j++) {
  13840. let fillFrame = AAC.getSilentFrame(track.parsedCodec || track.manifestCodec || track.codec, track.channelCount);
  13841. if (!fillFrame) {
  13842. this.log("Unable to get silent frame for given audio codec; duplicating last frame instead.");
  13843. fillFrame = sample.unit.subarray();
  13844. }
  13845. inputSamples.splice(i, 0, {
  13846. unit: fillFrame,
  13847. pts: nextPts
  13848. });
  13849. nextPts += inputSampleDuration;
  13850. i++;
  13851. }
  13852. }
  13853. sample.pts = nextPts;
  13854. nextPts += inputSampleDuration;
  13855. }
  13856. }
  13857. let firstPTS = null;
  13858. let lastPTS = null;
  13859. let mdat;
  13860. let mdatSize = 0;
  13861. let sampleLength = inputSamples.length;
  13862. while (sampleLength--) {
  13863. mdatSize += inputSamples[sampleLength].unit.byteLength;
  13864. }
  13865. for (let j = 0, _nbSamples = inputSamples.length; j < _nbSamples; j++) {
  13866. const audioSample = inputSamples[j];
  13867. const unit = audioSample.unit;
  13868. let pts = audioSample.pts;
  13869. if (lastPTS !== null) {
  13870. const prevSample = outputSamples[j - 1];
  13871. prevSample.duration = Math.round((pts - lastPTS) / scaleFactor);
  13872. } else {
  13873. if (contiguous && track.segmentCodec === "aac") {
  13874. pts = nextAudioTs + initTime;
  13875. }
  13876. firstPTS = pts;
  13877. if (mdatSize > 0) {
  13878. mdatSize += offset;
  13879. try {
  13880. mdat = new Uint8Array(mdatSize);
  13881. } catch (err) {
  13882. this.observer.emit(Events.ERROR, Events.ERROR, {
  13883. type: ErrorTypes.MUX_ERROR,
  13884. details: ErrorDetails.REMUX_ALLOC_ERROR,
  13885. fatal: false,
  13886. error: err,
  13887. bytes: mdatSize,
  13888. reason: `fail allocating audio mdat ${mdatSize}`
  13889. });
  13890. return;
  13891. }
  13892. if (!rawMPEG) {
  13893. const view2 = new DataView(mdat.buffer);
  13894. view2.setUint32(0, mdatSize);
  13895. mdat.set(MP4.types.mdat, 4);
  13896. }
  13897. } else {
  13898. return;
  13899. }
  13900. }
  13901. mdat.set(unit, offset);
  13902. const unitLen = unit.byteLength;
  13903. offset += unitLen;
  13904. outputSamples.push(createMp4Sample(true, mp4SampleDuration, unitLen, 0));
  13905. lastPTS = pts;
  13906. }
  13907. const nbSamples = outputSamples.length;
  13908. if (!nbSamples) {
  13909. return;
  13910. }
  13911. const lastSample = outputSamples[outputSamples.length - 1];
  13912. nextAudioTs = lastPTS - initTime;
  13913. this.nextAudioTs = nextAudioTs + scaleFactor * lastSample.duration;
  13914. const moof = rawMPEG ? new Uint8Array(0) : MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
  13915. samples: outputSamples
  13916. }));
  13917. track.samples = [];
  13918. const start = (firstPTS - initTime) / inputTimeScale;
  13919. const end = nextAudioTs / inputTimeScale;
  13920. const type = "audio";
  13921. const audioData = {
  13922. data1: moof,
  13923. data2: mdat,
  13924. startPTS: start,
  13925. endPTS: end,
  13926. startDTS: start,
  13927. endDTS: end,
  13928. type,
  13929. hasAudio: true,
  13930. hasVideo: false,
  13931. nb: nbSamples
  13932. };
  13933. this.isAudioContiguous = true;
  13934. return audioData;
  13935. }
  13936. };
  13937. function normalizePts(value, reference) {
  13938. let offset;
  13939. if (reference === null) {
  13940. return value;
  13941. }
  13942. if (reference < value) {
  13943. offset = -8589934592;
  13944. } else {
  13945. offset = 8589934592;
  13946. }
  13947. while (Math.abs(value - reference) > 4294967296) {
  13948. value += offset;
  13949. }
  13950. return value;
  13951. }
  13952. function findKeyframeIndex(samples) {
  13953. for (let i = 0; i < samples.length; i++) {
  13954. if (samples[i].key) {
  13955. return i;
  13956. }
  13957. }
  13958. return -1;
  13959. }
  13960. function flushTextTrackMetadataCueSamples(track, timeOffset, initPTS, initDTS) {
  13961. const length = track.samples.length;
  13962. if (!length) {
  13963. return;
  13964. }
  13965. const inputTimeScale = track.inputTimeScale;
  13966. for (let index = 0; index < length; index++) {
  13967. const sample = track.samples[index];
  13968. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  13969. sample.dts = normalizePts(sample.dts - initDTS.baseTime * inputTimeScale / initDTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  13970. }
  13971. const samples = track.samples;
  13972. track.samples = [];
  13973. return {
  13974. samples
  13975. };
  13976. }
  13977. function flushTextTrackUserdataCueSamples(track, timeOffset, initPTS) {
  13978. const length = track.samples.length;
  13979. if (!length) {
  13980. return;
  13981. }
  13982. const inputTimeScale = track.inputTimeScale;
  13983. for (let index = 0; index < length; index++) {
  13984. const sample = track.samples[index];
  13985. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  13986. }
  13987. track.samples.sort((a, b) => a.pts - b.pts);
  13988. const samples = track.samples;
  13989. track.samples = [];
  13990. return {
  13991. samples
  13992. };
  13993. }
  13994. var PassThroughRemuxer = class extends Logger {
  13995. constructor(observer, config, typeSupported, logger2) {
  13996. super("passthrough-remuxer", logger2);
  13997. this.emitInitSegment = false;
  13998. this.audioCodec = void 0;
  13999. this.videoCodec = void 0;
  14000. this.initData = void 0;
  14001. this.initPTS = null;
  14002. this.initTracks = void 0;
  14003. this.lastEndTime = null;
  14004. this.isVideoContiguous = false;
  14005. }
  14006. destroy() {
  14007. }
  14008. resetTimeStamp(defaultInitPTS) {
  14009. this.lastEndTime = null;
  14010. const initPTS = this.initPTS;
  14011. if (initPTS && defaultInitPTS) {
  14012. if (initPTS.baseTime === defaultInitPTS.baseTime && initPTS.timescale === defaultInitPTS.timescale) {
  14013. return;
  14014. }
  14015. }
  14016. this.initPTS = defaultInitPTS;
  14017. }
  14018. resetNextTimestamp() {
  14019. this.isVideoContiguous = false;
  14020. this.lastEndTime = null;
  14021. }
  14022. resetInitSegment(initSegment, audioCodec, videoCodec, decryptdata) {
  14023. this.audioCodec = audioCodec;
  14024. this.videoCodec = videoCodec;
  14025. this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));
  14026. this.emitInitSegment = true;
  14027. }
  14028. generateInitSegment(initSegment) {
  14029. let {
  14030. audioCodec,
  14031. videoCodec
  14032. } = this;
  14033. if (!(initSegment != null && initSegment.byteLength)) {
  14034. this.initTracks = void 0;
  14035. this.initData = void 0;
  14036. return;
  14037. }
  14038. const initData = this.initData = parseInitSegment(initSegment);
  14039. if (initData.audio) {
  14040. audioCodec = getParsedTrackCodec(initData.audio, ElementaryStreamTypes.AUDIO, this);
  14041. }
  14042. if (initData.video) {
  14043. videoCodec = getParsedTrackCodec(initData.video, ElementaryStreamTypes.VIDEO, this);
  14044. }
  14045. const tracks = {};
  14046. if (initData.audio && initData.video) {
  14047. tracks.audiovideo = {
  14048. container: "video/mp4",
  14049. codec: audioCodec + "," + videoCodec,
  14050. supplemental: initData.video.supplemental,
  14051. initSegment,
  14052. id: "main"
  14053. };
  14054. } else if (initData.audio) {
  14055. tracks.audio = {
  14056. container: "audio/mp4",
  14057. codec: audioCodec,
  14058. initSegment,
  14059. id: "audio"
  14060. };
  14061. } else if (initData.video) {
  14062. tracks.video = {
  14063. container: "video/mp4",
  14064. codec: videoCodec,
  14065. supplemental: initData.video.supplemental,
  14066. initSegment,
  14067. id: "main"
  14068. };
  14069. } else {
  14070. this.warn("initSegment does not contain moov or trak boxes.");
  14071. }
  14072. this.initTracks = tracks;
  14073. }
  14074. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset) {
  14075. var _initData, _initData2;
  14076. let {
  14077. initPTS,
  14078. lastEndTime
  14079. } = this;
  14080. const result = {
  14081. audio: void 0,
  14082. video: void 0,
  14083. text: textTrack,
  14084. id3: id3Track,
  14085. initSegment: void 0
  14086. };
  14087. if (!isFiniteNumber(lastEndTime)) {
  14088. lastEndTime = this.lastEndTime = timeOffset || 0;
  14089. }
  14090. const data = videoTrack.samples;
  14091. if (!(data != null && data.length)) {
  14092. return result;
  14093. }
  14094. const initSegment = {
  14095. initPTS: void 0,
  14096. timescale: void 0,
  14097. trackId: void 0
  14098. };
  14099. let initData = this.initData;
  14100. if (!((_initData = initData) != null && _initData.length)) {
  14101. this.generateInitSegment(data);
  14102. initData = this.initData;
  14103. }
  14104. if (!((_initData2 = initData) != null && _initData2.length)) {
  14105. this.warn("Failed to generate initSegment.");
  14106. return result;
  14107. }
  14108. if (this.emitInitSegment) {
  14109. initSegment.tracks = this.initTracks;
  14110. this.emitInitSegment = false;
  14111. }
  14112. const trackSampleData = getSampleData(data, initData, this);
  14113. const audioSampleTimestamps = initData.audio ? trackSampleData[initData.audio.id] : null;
  14114. const videoSampleTimestamps = initData.video ? trackSampleData[initData.video.id] : null;
  14115. const videoStartTime = toStartEndOrDefault(videoSampleTimestamps, Infinity);
  14116. const audioStartTime = toStartEndOrDefault(audioSampleTimestamps, Infinity);
  14117. const videoEndTime = toStartEndOrDefault(videoSampleTimestamps, 0, true);
  14118. const audioEndTime = toStartEndOrDefault(audioSampleTimestamps, 0, true);
  14119. let baseOffsetSamples;
  14120. let decodeTime = timeOffset;
  14121. let duration = 0;
  14122. if (audioSampleTimestamps && (!videoSampleTimestamps || !initPTS && audioStartTime < videoStartTime || initPTS && initPTS.trackId === initData.audio.id)) {
  14123. initSegment.trackId = initData.audio.id;
  14124. baseOffsetSamples = audioSampleTimestamps;
  14125. duration = audioEndTime - audioStartTime;
  14126. } else if (videoSampleTimestamps) {
  14127. initSegment.trackId = initData.video.id;
  14128. baseOffsetSamples = videoSampleTimestamps;
  14129. duration = videoEndTime - videoStartTime;
  14130. }
  14131. if (baseOffsetSamples) {
  14132. const timescale = baseOffsetSamples.timescale;
  14133. decodeTime = baseOffsetSamples.start / timescale;
  14134. initSegment.initPTS = baseOffsetSamples.start - timeOffset * timescale;
  14135. initSegment.timescale = timescale;
  14136. if (!initPTS) {
  14137. this.initPTS = initPTS = {
  14138. baseTime: initSegment.initPTS,
  14139. timescale,
  14140. trackId: initSegment.trackId
  14141. };
  14142. }
  14143. }
  14144. if ((accurateTimeOffset || !initPTS) && (isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) || initSegment.timescale !== initPTS.timescale)) {
  14145. initSegment.initPTS = decodeTime - timeOffset;
  14146. initSegment.timescale = 1;
  14147. if (initPTS && initPTS.timescale === 1) {
  14148. this.warn(`Adjusting initPTS @${timeOffset} from ${initPTS.baseTime / initPTS.timescale} to ${initSegment.initPTS}`);
  14149. }
  14150. this.initPTS = initPTS = {
  14151. baseTime: initSegment.initPTS,
  14152. timescale: 1
  14153. };
  14154. }
  14155. const startTime = audioTrack ? decodeTime - initPTS.baseTime / initPTS.timescale : lastEndTime;
  14156. const endTime = startTime + duration;
  14157. if (duration > 0) {
  14158. this.lastEndTime = endTime;
  14159. } else {
  14160. this.warn("Duration parsed from mp4 should be greater than zero");
  14161. this.resetNextTimestamp();
  14162. }
  14163. const hasAudio = !!initData.audio;
  14164. const hasVideo = !!initData.video;
  14165. let type = "";
  14166. if (hasAudio) {
  14167. type += "audio";
  14168. }
  14169. if (hasVideo) {
  14170. type += "video";
  14171. }
  14172. const track = {
  14173. data1: data,
  14174. startPTS: startTime,
  14175. startDTS: startTime,
  14176. endPTS: endTime,
  14177. endDTS: endTime,
  14178. type,
  14179. hasAudio,
  14180. hasVideo,
  14181. nb: 1,
  14182. dropped: 0
  14183. };
  14184. result.audio = hasAudio && !hasVideo ? track : void 0;
  14185. result.video = hasVideo ? track : void 0;
  14186. const videoSampleCount = videoSampleTimestamps == null ? void 0 : videoSampleTimestamps.sampleCount;
  14187. if (videoSampleCount) {
  14188. const firstKeyFrame = videoSampleTimestamps.keyFrameIndex;
  14189. const independent = firstKeyFrame !== -1;
  14190. track.nb = videoSampleCount;
  14191. track.dropped = firstKeyFrame === 0 || this.isVideoContiguous ? 0 : independent ? firstKeyFrame : videoSampleCount;
  14192. track.independent = independent;
  14193. track.firstKeyFrame = firstKeyFrame;
  14194. if (independent && videoSampleTimestamps.keyFrameStart) {
  14195. track.firstKeyFramePTS = (videoSampleTimestamps.keyFrameStart - initPTS.baseTime) / initPTS.timescale;
  14196. }
  14197. if (!this.isVideoContiguous) {
  14198. result.independent = independent;
  14199. }
  14200. this.isVideoContiguous || (this.isVideoContiguous = independent);
  14201. if (track.dropped) {
  14202. this.warn(`fmp4 does not start with IDR: firstIDR ${firstKeyFrame}/${videoSampleCount} dropped: ${track.dropped} start: ${track.firstKeyFramePTS || "NA"}`);
  14203. }
  14204. }
  14205. result.initSegment = initSegment;
  14206. result.id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, initPTS, initPTS);
  14207. if (textTrack.samples.length) {
  14208. result.text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, initPTS);
  14209. }
  14210. return result;
  14211. }
  14212. };
  14213. function toStartEndOrDefault(trackTimes, defaultValue, end = false) {
  14214. return (trackTimes == null ? void 0 : trackTimes.start) !== void 0 ? (trackTimes.start + (end ? trackTimes.duration : 0)) / trackTimes.timescale : defaultValue;
  14215. }
  14216. function isInvalidInitPts(initPTS, startDTS, timeOffset, duration) {
  14217. if (initPTS === null) {
  14218. return true;
  14219. }
  14220. const minDuration = Math.max(duration, 1);
  14221. const startTime = startDTS - initPTS.baseTime / initPTS.timescale;
  14222. return Math.abs(startTime - timeOffset) > minDuration;
  14223. }
  14224. function getParsedTrackCodec(track, type, logger2) {
  14225. const parsedCodec = track == null ? void 0 : track.codec;
  14226. if (parsedCodec && parsedCodec.length > 4) {
  14227. return parsedCodec;
  14228. }
  14229. if (type === ElementaryStreamTypes.AUDIO) {
  14230. if (parsedCodec === "ec-3" || parsedCodec === "ac-3" || parsedCodec === "alac") {
  14231. return parsedCodec;
  14232. }
  14233. if (parsedCodec === "fLaC" || parsedCodec === "Opus") {
  14234. const preferManagedMediaSource = false;
  14235. return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);
  14236. }
  14237. logger2.warn(`Unhandled audio codec "${parsedCodec}" in mp4 MAP`);
  14238. return parsedCodec || "mp4a";
  14239. }
  14240. logger2.warn(`Unhandled video codec "${parsedCodec}" in mp4 MAP`);
  14241. return parsedCodec || "avc1";
  14242. }
  14243. var now;
  14244. try {
  14245. now = self.performance.now.bind(self.performance);
  14246. } catch (err) {
  14247. now = Date.now;
  14248. }
  14249. var muxConfig = [{
  14250. demux: MP4Demuxer,
  14251. remux: PassThroughRemuxer
  14252. }, {
  14253. demux: TSDemuxer,
  14254. remux: MP4Remuxer
  14255. }, {
  14256. demux: AACDemuxer,
  14257. remux: MP4Remuxer
  14258. }, {
  14259. demux: MP3Demuxer,
  14260. remux: MP4Remuxer
  14261. }];
  14262. {
  14263. muxConfig.splice(2, 0, {
  14264. demux: AC3Demuxer,
  14265. remux: MP4Remuxer
  14266. });
  14267. }
  14268. var Transmuxer = class {
  14269. constructor(observer, typeSupported, config, vendor, id, logger2) {
  14270. this.asyncResult = false;
  14271. this.logger = void 0;
  14272. this.observer = void 0;
  14273. this.typeSupported = void 0;
  14274. this.config = void 0;
  14275. this.id = void 0;
  14276. this.demuxer = void 0;
  14277. this.remuxer = void 0;
  14278. this.decrypter = void 0;
  14279. this.probe = void 0;
  14280. this.decryptionPromise = null;
  14281. this.transmuxConfig = void 0;
  14282. this.currentTransmuxState = void 0;
  14283. this.observer = observer;
  14284. this.typeSupported = typeSupported;
  14285. this.config = config;
  14286. this.id = id;
  14287. this.logger = logger2;
  14288. }
  14289. configure(transmuxConfig) {
  14290. this.transmuxConfig = transmuxConfig;
  14291. if (this.decrypter) {
  14292. this.decrypter.reset();
  14293. }
  14294. }
  14295. push(data, decryptdata, chunkMeta, state) {
  14296. const stats = chunkMeta.transmuxing;
  14297. stats.executeStart = now();
  14298. let uintData = new Uint8Array(data);
  14299. const {
  14300. currentTransmuxState,
  14301. transmuxConfig
  14302. } = this;
  14303. if (state) {
  14304. this.currentTransmuxState = state;
  14305. }
  14306. const {
  14307. contiguous,
  14308. discontinuity,
  14309. trackSwitch,
  14310. accurateTimeOffset,
  14311. timeOffset,
  14312. initSegmentChange
  14313. } = state || currentTransmuxState;
  14314. const {
  14315. audioCodec,
  14316. videoCodec,
  14317. defaultInitPts,
  14318. duration,
  14319. initSegmentData
  14320. } = transmuxConfig;
  14321. const keyData = getEncryptionType(uintData, decryptdata);
  14322. if (keyData && isFullSegmentEncryption(keyData.method)) {
  14323. const decrypter = this.getDecrypter();
  14324. const aesMode = getAesModeFromFullSegmentMethod(keyData.method);
  14325. if (decrypter.isSync()) {
  14326. let decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode);
  14327. const loadingParts = chunkMeta.part > -1;
  14328. if (loadingParts) {
  14329. const _data = decrypter.flush();
  14330. decryptedData = _data ? _data.buffer : _data;
  14331. }
  14332. if (!decryptedData) {
  14333. stats.executeEnd = now();
  14334. return emptyResult(chunkMeta);
  14335. }
  14336. uintData = new Uint8Array(decryptedData);
  14337. } else {
  14338. this.asyncResult = true;
  14339. this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode).then((decryptedData) => {
  14340. const result2 = this.push(decryptedData, null, chunkMeta);
  14341. this.decryptionPromise = null;
  14342. return result2;
  14343. });
  14344. return this.decryptionPromise;
  14345. }
  14346. }
  14347. const resetMuxers = this.needsProbing(discontinuity, trackSwitch);
  14348. if (resetMuxers) {
  14349. const error = this.configureTransmuxer(uintData);
  14350. if (error) {
  14351. this.logger.warn(`[transmuxer] ${error.message}`);
  14352. this.observer.emit(Events.ERROR, Events.ERROR, {
  14353. type: ErrorTypes.MEDIA_ERROR,
  14354. details: ErrorDetails.FRAG_PARSING_ERROR,
  14355. fatal: false,
  14356. error,
  14357. reason: error.message
  14358. });
  14359. stats.executeEnd = now();
  14360. return emptyResult(chunkMeta);
  14361. }
  14362. }
  14363. if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {
  14364. this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration, decryptdata);
  14365. }
  14366. if (discontinuity || initSegmentChange || resetMuxers) {
  14367. this.resetInitialTimestamp(defaultInitPts);
  14368. }
  14369. if (!contiguous) {
  14370. this.resetContiguity();
  14371. }
  14372. const result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  14373. this.asyncResult = isPromise(result);
  14374. const currentState = this.currentTransmuxState;
  14375. currentState.contiguous = true;
  14376. currentState.discontinuity = false;
  14377. currentState.trackSwitch = false;
  14378. stats.executeEnd = now();
  14379. return result;
  14380. }
  14381. // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
  14382. flush(chunkMeta) {
  14383. const stats = chunkMeta.transmuxing;
  14384. stats.executeStart = now();
  14385. const {
  14386. decrypter,
  14387. currentTransmuxState,
  14388. decryptionPromise
  14389. } = this;
  14390. if (decryptionPromise) {
  14391. this.asyncResult = true;
  14392. return decryptionPromise.then(() => {
  14393. return this.flush(chunkMeta);
  14394. });
  14395. }
  14396. const transmuxResults = [];
  14397. const {
  14398. timeOffset
  14399. } = currentTransmuxState;
  14400. if (decrypter) {
  14401. const decryptedData = decrypter.flush();
  14402. if (decryptedData) {
  14403. transmuxResults.push(this.push(decryptedData.buffer, null, chunkMeta));
  14404. }
  14405. }
  14406. const {
  14407. demuxer,
  14408. remuxer
  14409. } = this;
  14410. if (!demuxer || !remuxer) {
  14411. stats.executeEnd = now();
  14412. const emptyResults = [emptyResult(chunkMeta)];
  14413. if (this.asyncResult) {
  14414. return Promise.resolve(emptyResults);
  14415. }
  14416. return emptyResults;
  14417. }
  14418. const demuxResultOrPromise = demuxer.flush(timeOffset);
  14419. if (isPromise(demuxResultOrPromise)) {
  14420. this.asyncResult = true;
  14421. return demuxResultOrPromise.then((demuxResult) => {
  14422. this.flushRemux(transmuxResults, demuxResult, chunkMeta);
  14423. return transmuxResults;
  14424. });
  14425. }
  14426. this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
  14427. if (this.asyncResult) {
  14428. return Promise.resolve(transmuxResults);
  14429. }
  14430. return transmuxResults;
  14431. }
  14432. flushRemux(transmuxResults, demuxResult, chunkMeta) {
  14433. const {
  14434. audioTrack,
  14435. videoTrack,
  14436. id3Track,
  14437. textTrack
  14438. } = demuxResult;
  14439. const {
  14440. accurateTimeOffset,
  14441. timeOffset
  14442. } = this.currentTransmuxState;
  14443. this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${chunkMeta.sn}${chunkMeta.part > -1 ? " part: " + chunkMeta.part : ""} of ${this.id === PlaylistLevelType.MAIN ? "level" : "track"} ${chunkMeta.level}`);
  14444. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
  14445. transmuxResults.push({
  14446. remuxResult,
  14447. chunkMeta
  14448. });
  14449. chunkMeta.transmuxing.executeEnd = now();
  14450. }
  14451. resetInitialTimestamp(defaultInitPts) {
  14452. const {
  14453. demuxer,
  14454. remuxer
  14455. } = this;
  14456. if (!demuxer || !remuxer) {
  14457. return;
  14458. }
  14459. demuxer.resetTimeStamp(defaultInitPts);
  14460. remuxer.resetTimeStamp(defaultInitPts);
  14461. }
  14462. resetContiguity() {
  14463. const {
  14464. demuxer,
  14465. remuxer
  14466. } = this;
  14467. if (!demuxer || !remuxer) {
  14468. return;
  14469. }
  14470. demuxer.resetContiguity();
  14471. remuxer.resetNextTimestamp();
  14472. }
  14473. resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration, decryptdata) {
  14474. const {
  14475. demuxer,
  14476. remuxer
  14477. } = this;
  14478. if (!demuxer || !remuxer) {
  14479. return;
  14480. }
  14481. demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration);
  14482. remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, decryptdata);
  14483. }
  14484. destroy() {
  14485. if (this.demuxer) {
  14486. this.demuxer.destroy();
  14487. this.demuxer = void 0;
  14488. }
  14489. if (this.remuxer) {
  14490. this.remuxer.destroy();
  14491. this.remuxer = void 0;
  14492. }
  14493. }
  14494. transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
  14495. let result;
  14496. if (keyData && keyData.method === "SAMPLE-AES") {
  14497. result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  14498. } else {
  14499. result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
  14500. }
  14501. return result;
  14502. }
  14503. transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
  14504. const {
  14505. audioTrack,
  14506. videoTrack,
  14507. id3Track,
  14508. textTrack
  14509. } = this.demuxer.demux(data, timeOffset, false, !this.config.progressive);
  14510. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
  14511. return {
  14512. remuxResult,
  14513. chunkMeta
  14514. };
  14515. }
  14516. transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
  14517. return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then((demuxResult) => {
  14518. const remuxResult = this.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, this.id);
  14519. return {
  14520. remuxResult,
  14521. chunkMeta
  14522. };
  14523. });
  14524. }
  14525. configureTransmuxer(data) {
  14526. const {
  14527. config,
  14528. observer,
  14529. typeSupported
  14530. } = this;
  14531. let mux;
  14532. for (let i = 0, len = muxConfig.length; i < len; i++) {
  14533. var _muxConfig$i$demux;
  14534. if ((_muxConfig$i$demux = muxConfig[i].demux) != null && _muxConfig$i$demux.probe(data, this.logger)) {
  14535. mux = muxConfig[i];
  14536. break;
  14537. }
  14538. }
  14539. if (!mux) {
  14540. return new Error("Failed to find demuxer by probing fragment data");
  14541. }
  14542. const demuxer = this.demuxer;
  14543. const remuxer = this.remuxer;
  14544. const Remuxer = mux.remux;
  14545. const Demuxer = mux.demux;
  14546. if (!remuxer || !(remuxer instanceof Remuxer)) {
  14547. this.remuxer = new Remuxer(observer, config, typeSupported, this.logger);
  14548. }
  14549. if (!demuxer || !(demuxer instanceof Demuxer)) {
  14550. this.demuxer = new Demuxer(observer, config, typeSupported, this.logger);
  14551. this.probe = Demuxer.probe;
  14552. }
  14553. }
  14554. needsProbing(discontinuity, trackSwitch) {
  14555. return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
  14556. }
  14557. getDecrypter() {
  14558. let decrypter = this.decrypter;
  14559. if (!decrypter) {
  14560. decrypter = this.decrypter = new Decrypter(this.config);
  14561. }
  14562. return decrypter;
  14563. }
  14564. };
  14565. function getEncryptionType(data, decryptData) {
  14566. let encryptionType = null;
  14567. if (data.byteLength > 0 && (decryptData == null ? void 0 : decryptData.key) != null && decryptData.iv !== null && decryptData.method != null) {
  14568. encryptionType = decryptData;
  14569. }
  14570. return encryptionType;
  14571. }
  14572. var emptyResult = (chunkMeta) => ({
  14573. remuxResult: {},
  14574. chunkMeta
  14575. });
  14576. function isPromise(p) {
  14577. return "then" in p && p.then instanceof Function;
  14578. }
  14579. var TransmuxConfig = class {
  14580. constructor(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
  14581. this.audioCodec = void 0;
  14582. this.videoCodec = void 0;
  14583. this.initSegmentData = void 0;
  14584. this.duration = void 0;
  14585. this.defaultInitPts = void 0;
  14586. this.audioCodec = audioCodec;
  14587. this.videoCodec = videoCodec;
  14588. this.initSegmentData = initSegmentData;
  14589. this.duration = duration;
  14590. this.defaultInitPts = defaultInitPts || null;
  14591. }
  14592. };
  14593. var TransmuxState = class {
  14594. constructor(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) {
  14595. this.discontinuity = void 0;
  14596. this.contiguous = void 0;
  14597. this.accurateTimeOffset = void 0;
  14598. this.trackSwitch = void 0;
  14599. this.timeOffset = void 0;
  14600. this.initSegmentChange = void 0;
  14601. this.discontinuity = discontinuity;
  14602. this.contiguous = contiguous;
  14603. this.accurateTimeOffset = accurateTimeOffset;
  14604. this.trackSwitch = trackSwitch;
  14605. this.timeOffset = timeOffset;
  14606. this.initSegmentChange = initSegmentChange;
  14607. }
  14608. };
  14609. var transmuxerInstanceCount = 0;
  14610. var TransmuxerInterface = class {
  14611. constructor(_hls, id, onTransmuxComplete, onFlush) {
  14612. this.error = null;
  14613. this.hls = void 0;
  14614. this.id = void 0;
  14615. this.instanceNo = transmuxerInstanceCount++;
  14616. this.observer = void 0;
  14617. this.frag = null;
  14618. this.part = null;
  14619. this.useWorker = void 0;
  14620. this.workerContext = null;
  14621. this.transmuxer = null;
  14622. this.onTransmuxComplete = void 0;
  14623. this.onFlush = void 0;
  14624. this.onWorkerMessage = (event) => {
  14625. const data = event.data;
  14626. const hls = this.hls;
  14627. if (!hls || !(data != null && data.event) || data.instanceNo !== this.instanceNo) {
  14628. return;
  14629. }
  14630. switch (data.event) {
  14631. case "init": {
  14632. var _this$workerContext;
  14633. const objectURL = (_this$workerContext = this.workerContext) == null ? void 0 : _this$workerContext.objectURL;
  14634. if (objectURL) {
  14635. self.URL.revokeObjectURL(objectURL);
  14636. }
  14637. break;
  14638. }
  14639. case "transmuxComplete": {
  14640. this.handleTransmuxComplete(data.data);
  14641. break;
  14642. }
  14643. case "flush": {
  14644. this.onFlush(data.data);
  14645. break;
  14646. }
  14647. case "workerLog": {
  14648. if (hls.logger[data.data.logType]) {
  14649. hls.logger[data.data.logType](data.data.message);
  14650. }
  14651. break;
  14652. }
  14653. default: {
  14654. data.data = data.data || {};
  14655. data.data.frag = this.frag;
  14656. data.data.part = this.part;
  14657. data.data.id = this.id;
  14658. hls.trigger(data.event, data.data);
  14659. break;
  14660. }
  14661. }
  14662. };
  14663. this.onWorkerError = (event) => {
  14664. if (!this.hls) {
  14665. return;
  14666. }
  14667. const error = new Error(`${event.message} (${event.filename}:${event.lineno})`);
  14668. this.hls.config.enableWorker = false;
  14669. this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`);
  14670. this.hls.trigger(Events.ERROR, {
  14671. type: ErrorTypes.OTHER_ERROR,
  14672. details: ErrorDetails.INTERNAL_EXCEPTION,
  14673. fatal: false,
  14674. event: "demuxerWorker",
  14675. error
  14676. });
  14677. };
  14678. const config = _hls.config;
  14679. this.hls = _hls;
  14680. this.id = id;
  14681. this.useWorker = !!config.enableWorker;
  14682. this.onTransmuxComplete = onTransmuxComplete;
  14683. this.onFlush = onFlush;
  14684. const forwardMessage = (ev, data) => {
  14685. data = data || {};
  14686. data.frag = this.frag || void 0;
  14687. if (ev === Events.ERROR) {
  14688. data = data;
  14689. data.parent = this.id;
  14690. data.part = this.part;
  14691. this.error = data.error;
  14692. }
  14693. this.hls.trigger(ev, data);
  14694. };
  14695. this.observer = new EventEmitter();
  14696. this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  14697. this.observer.on(Events.ERROR, forwardMessage);
  14698. const m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
  14699. if (this.useWorker && typeof Worker !== "undefined") {
  14700. const logger2 = this.hls.logger;
  14701. const canCreateWorker = config.workerPath || hasUMDWorker();
  14702. if (canCreateWorker) {
  14703. try {
  14704. if (config.workerPath) {
  14705. logger2.log(`loading Web Worker ${config.workerPath} for "${id}"`);
  14706. this.workerContext = loadWorker(config.workerPath);
  14707. } else {
  14708. logger2.log(`injecting Web Worker for "${id}"`);
  14709. this.workerContext = injectWorker();
  14710. }
  14711. const {
  14712. worker
  14713. } = this.workerContext;
  14714. worker.addEventListener("message", this.onWorkerMessage);
  14715. worker.addEventListener("error", this.onWorkerError);
  14716. worker.postMessage({
  14717. instanceNo: this.instanceNo,
  14718. cmd: "init",
  14719. typeSupported: m2tsTypeSupported,
  14720. id,
  14721. config: stringify(config)
  14722. });
  14723. } catch (err) {
  14724. logger2.warn(`Error setting up "${id}" Web Worker, fallback to inline`, err);
  14725. this.terminateWorker();
  14726. this.error = null;
  14727. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, "", id, _hls.logger);
  14728. }
  14729. return;
  14730. }
  14731. }
  14732. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, "", id, _hls.logger);
  14733. }
  14734. reset() {
  14735. this.frag = null;
  14736. this.part = null;
  14737. if (this.workerContext) {
  14738. const instanceNo = this.instanceNo;
  14739. this.instanceNo = transmuxerInstanceCount++;
  14740. const config = this.hls.config;
  14741. const m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
  14742. this.workerContext.worker.postMessage({
  14743. instanceNo: this.instanceNo,
  14744. cmd: "reset",
  14745. resetNo: instanceNo,
  14746. typeSupported: m2tsTypeSupported,
  14747. id: this.id,
  14748. config: stringify(config)
  14749. });
  14750. }
  14751. }
  14752. terminateWorker() {
  14753. if (this.workerContext) {
  14754. const {
  14755. worker
  14756. } = this.workerContext;
  14757. this.workerContext = null;
  14758. worker.removeEventListener("message", this.onWorkerMessage);
  14759. worker.removeEventListener("error", this.onWorkerError);
  14760. removeWorkerFromStore(this.hls.config.workerPath);
  14761. }
  14762. }
  14763. destroy() {
  14764. if (this.workerContext) {
  14765. this.terminateWorker();
  14766. this.onWorkerMessage = this.onWorkerError = null;
  14767. } else {
  14768. const transmuxer = this.transmuxer;
  14769. if (transmuxer) {
  14770. transmuxer.destroy();
  14771. this.transmuxer = null;
  14772. }
  14773. }
  14774. const observer = this.observer;
  14775. if (observer) {
  14776. observer.removeAllListeners();
  14777. }
  14778. this.frag = null;
  14779. this.part = null;
  14780. this.observer = null;
  14781. this.hls = null;
  14782. }
  14783. push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
  14784. var _frag$initSegment, _lastFrag$initSegment;
  14785. chunkMeta.transmuxing.start = self.performance.now();
  14786. const {
  14787. instanceNo,
  14788. transmuxer
  14789. } = this;
  14790. const timeOffset = part ? part.start : frag.start;
  14791. const decryptdata = frag.decryptdata;
  14792. const lastFrag = this.frag;
  14793. const discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  14794. const trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
  14795. const snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
  14796. const partDiff = this.part ? chunkMeta.part - this.part.index : -1;
  14797. const progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag == null ? void 0 : lastFrag.stats.chunkCount);
  14798. const contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0));
  14799. const now2 = self.performance.now();
  14800. if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
  14801. frag.stats.parsing.start = now2;
  14802. }
  14803. if (part && (partDiff || !contiguous)) {
  14804. part.stats.parsing.start = now2;
  14805. }
  14806. const initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) == null ? void 0 : _lastFrag$initSegment.url));
  14807. const state = new TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange);
  14808. if (!contiguous || discontinuity || initSegmentChange) {
  14809. this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${frag.type} sn: ${chunkMeta.sn}${chunkMeta.part > -1 ? " part: " + chunkMeta.part : ""} ${this.id === PlaylistLevelType.MAIN ? "level" : "track"}: ${chunkMeta.level} id: ${chunkMeta.id}
  14810. discontinuity: ${discontinuity}
  14811. trackSwitch: ${trackSwitch}
  14812. contiguous: ${contiguous}
  14813. accurateTimeOffset: ${accurateTimeOffset}
  14814. timeOffset: ${timeOffset}
  14815. initSegmentChange: ${initSegmentChange}`);
  14816. const config = new TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
  14817. this.configureTransmuxer(config);
  14818. }
  14819. this.frag = frag;
  14820. this.part = part;
  14821. if (this.workerContext) {
  14822. this.workerContext.worker.postMessage({
  14823. instanceNo,
  14824. cmd: "demux",
  14825. data,
  14826. decryptdata,
  14827. chunkMeta,
  14828. state
  14829. }, data instanceof ArrayBuffer ? [data] : []);
  14830. } else if (transmuxer) {
  14831. const transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
  14832. if (isPromise(transmuxResult)) {
  14833. transmuxResult.then((data2) => {
  14834. this.handleTransmuxComplete(data2);
  14835. }).catch((error) => {
  14836. this.transmuxerError(error, chunkMeta, "transmuxer-interface push error");
  14837. });
  14838. } else {
  14839. this.handleTransmuxComplete(transmuxResult);
  14840. }
  14841. }
  14842. }
  14843. flush(chunkMeta) {
  14844. chunkMeta.transmuxing.start = self.performance.now();
  14845. const {
  14846. instanceNo,
  14847. transmuxer
  14848. } = this;
  14849. if (this.workerContext) {
  14850. this.workerContext.worker.postMessage({
  14851. instanceNo,
  14852. cmd: "flush",
  14853. chunkMeta
  14854. });
  14855. } else if (transmuxer) {
  14856. const transmuxResult = transmuxer.flush(chunkMeta);
  14857. if (isPromise(transmuxResult)) {
  14858. transmuxResult.then((data) => {
  14859. this.handleFlushResult(data, chunkMeta);
  14860. }).catch((error) => {
  14861. this.transmuxerError(error, chunkMeta, "transmuxer-interface flush error");
  14862. });
  14863. } else {
  14864. this.handleFlushResult(transmuxResult, chunkMeta);
  14865. }
  14866. }
  14867. }
  14868. transmuxerError(error, chunkMeta, reason) {
  14869. if (!this.hls) {
  14870. return;
  14871. }
  14872. this.error = error;
  14873. this.hls.trigger(Events.ERROR, {
  14874. type: ErrorTypes.MEDIA_ERROR,
  14875. details: ErrorDetails.FRAG_PARSING_ERROR,
  14876. chunkMeta,
  14877. frag: this.frag || void 0,
  14878. part: this.part || void 0,
  14879. fatal: false,
  14880. error,
  14881. err: error,
  14882. reason
  14883. });
  14884. }
  14885. handleFlushResult(results, chunkMeta) {
  14886. results.forEach((result) => {
  14887. this.handleTransmuxComplete(result);
  14888. });
  14889. this.onFlush(chunkMeta);
  14890. }
  14891. configureTransmuxer(config) {
  14892. const {
  14893. instanceNo,
  14894. transmuxer
  14895. } = this;
  14896. if (this.workerContext) {
  14897. this.workerContext.worker.postMessage({
  14898. instanceNo,
  14899. cmd: "configure",
  14900. config
  14901. });
  14902. } else if (transmuxer) {
  14903. transmuxer.configure(config);
  14904. }
  14905. }
  14906. handleTransmuxComplete(result) {
  14907. result.chunkMeta.transmuxing.end = self.performance.now();
  14908. this.onTransmuxComplete(result);
  14909. }
  14910. };
  14911. var TICK_INTERVAL$3 = 100;
  14912. var AudioStreamController = class extends BaseStreamController {
  14913. constructor(hls, fragmentTracker, keyLoader) {
  14914. super(hls, fragmentTracker, keyLoader, "audio-stream-controller", PlaylistLevelType.AUDIO);
  14915. this.mainAnchor = null;
  14916. this.mainFragLoading = null;
  14917. this.audioOnly = false;
  14918. this.bufferedTrack = null;
  14919. this.switchingTrack = null;
  14920. this.trackId = -1;
  14921. this.waitingData = null;
  14922. this.mainDetails = null;
  14923. this.flushing = false;
  14924. this.bufferFlushed = false;
  14925. this.cachedTrackLoadedData = null;
  14926. this.registerListeners();
  14927. }
  14928. onHandlerDestroying() {
  14929. this.unregisterListeners();
  14930. super.onHandlerDestroying();
  14931. this.resetItem();
  14932. }
  14933. resetItem() {
  14934. this.mainDetails = this.mainAnchor = this.mainFragLoading = this.bufferedTrack = this.switchingTrack = this.waitingData = this.cachedTrackLoadedData = null;
  14935. }
  14936. registerListeners() {
  14937. super.registerListeners();
  14938. const {
  14939. hls
  14940. } = this;
  14941. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  14942. hls.on(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  14943. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  14944. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  14945. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  14946. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  14947. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  14948. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  14949. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  14950. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  14951. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  14952. }
  14953. unregisterListeners() {
  14954. const {
  14955. hls
  14956. } = this;
  14957. if (!hls) {
  14958. return;
  14959. }
  14960. super.unregisterListeners();
  14961. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  14962. hls.off(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  14963. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  14964. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  14965. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  14966. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  14967. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  14968. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  14969. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  14970. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  14971. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  14972. }
  14973. // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value
  14974. onInitPtsFound(event, {
  14975. frag,
  14976. id,
  14977. initPTS,
  14978. timescale
  14979. }) {
  14980. if (id === PlaylistLevelType.MAIN) {
  14981. const cc = frag.cc;
  14982. const inFlightFrag = this.fragCurrent;
  14983. this.initPTS[cc] = {
  14984. baseTime: initPTS,
  14985. timescale
  14986. };
  14987. this.log(`InitPTS for cc: ${cc} found from main: ${initPTS}/${timescale}`);
  14988. this.mainAnchor = frag;
  14989. if (this.state === State.WAITING_INIT_PTS) {
  14990. const waitingData = this.waitingData;
  14991. if (!waitingData && !this.loadingParts || waitingData && waitingData.frag.cc !== cc) {
  14992. this.syncWithAnchor(frag, waitingData == null ? void 0 : waitingData.frag);
  14993. }
  14994. } else if (!this.hls.hasEnoughToStart && inFlightFrag && inFlightFrag.cc !== cc) {
  14995. inFlightFrag.abortRequests();
  14996. this.syncWithAnchor(frag, inFlightFrag);
  14997. } else if (this.state === State.IDLE) {
  14998. this.tick();
  14999. }
  15000. }
  15001. }
  15002. getLoadPosition() {
  15003. if (!this.startFragRequested && this.nextLoadPosition >= 0) {
  15004. return this.nextLoadPosition;
  15005. }
  15006. return super.getLoadPosition();
  15007. }
  15008. syncWithAnchor(mainAnchor, waitingToAppend) {
  15009. var _this$mainFragLoading;
  15010. const mainFragLoading = ((_this$mainFragLoading = this.mainFragLoading) == null ? void 0 : _this$mainFragLoading.frag) || null;
  15011. if (waitingToAppend) {
  15012. if ((mainFragLoading == null ? void 0 : mainFragLoading.cc) === waitingToAppend.cc) {
  15013. return;
  15014. }
  15015. }
  15016. const targetDiscontinuity = (mainFragLoading || mainAnchor).cc;
  15017. const trackDetails = this.getLevelDetails();
  15018. const pos = this.getLoadPosition();
  15019. const syncFrag = findNearestWithCC(trackDetails, targetDiscontinuity, pos);
  15020. if (syncFrag) {
  15021. this.log(`Syncing with main frag at ${syncFrag.start} cc ${syncFrag.cc}`);
  15022. this.startFragRequested = false;
  15023. this.nextLoadPosition = syncFrag.start;
  15024. this.resetLoadingState();
  15025. if (this.state === State.IDLE) {
  15026. this.doTickIdle();
  15027. }
  15028. }
  15029. }
  15030. startLoad(startPosition, skipSeekToStartPosition) {
  15031. if (!this.levels) {
  15032. this.startPosition = startPosition;
  15033. this.state = State.STOPPED;
  15034. return;
  15035. }
  15036. const lastCurrentTime = this.lastCurrentTime;
  15037. this.stopLoad();
  15038. this.setInterval(TICK_INTERVAL$3);
  15039. if (lastCurrentTime > 0 && startPosition === -1) {
  15040. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  15041. startPosition = lastCurrentTime;
  15042. this.state = State.IDLE;
  15043. } else {
  15044. this.state = State.WAITING_TRACK;
  15045. }
  15046. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  15047. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  15048. this.tick();
  15049. }
  15050. doTick() {
  15051. switch (this.state) {
  15052. case State.IDLE:
  15053. this.doTickIdle();
  15054. break;
  15055. case State.WAITING_TRACK: {
  15056. const {
  15057. levels,
  15058. trackId
  15059. } = this;
  15060. const currenTrack = levels == null ? void 0 : levels[trackId];
  15061. const details = currenTrack == null ? void 0 : currenTrack.details;
  15062. if (details && !this.waitForLive(currenTrack)) {
  15063. if (this.waitForCdnTuneIn(details)) {
  15064. break;
  15065. }
  15066. this.state = State.WAITING_INIT_PTS;
  15067. }
  15068. break;
  15069. }
  15070. case State.FRAG_LOADING_WAITING_RETRY: {
  15071. var _this$media;
  15072. const now2 = performance.now();
  15073. const retryDate = this.retryDate;
  15074. if (!retryDate || now2 >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  15075. const {
  15076. levels,
  15077. trackId
  15078. } = this;
  15079. this.log("RetryDate reached, switch back to IDLE state");
  15080. this.resetStartWhenNotLoaded((levels == null ? void 0 : levels[trackId]) || null);
  15081. this.state = State.IDLE;
  15082. }
  15083. break;
  15084. }
  15085. case State.WAITING_INIT_PTS: {
  15086. const waitingData = this.waitingData;
  15087. if (waitingData) {
  15088. const {
  15089. frag,
  15090. part,
  15091. cache,
  15092. complete
  15093. } = waitingData;
  15094. const mainAnchor = this.mainAnchor;
  15095. if (this.initPTS[frag.cc] !== void 0) {
  15096. this.waitingData = null;
  15097. this.state = State.FRAG_LOADING;
  15098. const payload = cache.flush().buffer;
  15099. const data = {
  15100. frag,
  15101. part,
  15102. payload,
  15103. networkDetails: null
  15104. };
  15105. this._handleFragmentLoadProgress(data);
  15106. if (complete) {
  15107. super._handleFragmentLoadComplete(data);
  15108. }
  15109. } else if (mainAnchor && mainAnchor.cc !== waitingData.frag.cc) {
  15110. this.syncWithAnchor(mainAnchor, waitingData.frag);
  15111. }
  15112. } else {
  15113. this.state = State.IDLE;
  15114. }
  15115. }
  15116. }
  15117. this.onTickEnd();
  15118. }
  15119. resetLoadingState() {
  15120. const waitingData = this.waitingData;
  15121. if (waitingData) {
  15122. this.fragmentTracker.removeFragment(waitingData.frag);
  15123. this.waitingData = null;
  15124. }
  15125. super.resetLoadingState();
  15126. }
  15127. onTickEnd() {
  15128. const {
  15129. media
  15130. } = this;
  15131. if (!(media != null && media.readyState)) {
  15132. return;
  15133. }
  15134. this.lastCurrentTime = media.currentTime;
  15135. }
  15136. doTickIdle() {
  15137. var _this$mainFragLoading2;
  15138. const {
  15139. hls,
  15140. levels,
  15141. media,
  15142. trackId
  15143. } = this;
  15144. const config = hls.config;
  15145. if (!this.buffering || !media && !this.primaryPrefetch && (this.startFragRequested || !config.startFragPrefetch) || !(levels != null && levels[trackId])) {
  15146. return;
  15147. }
  15148. const levelInfo = levels[trackId];
  15149. const trackDetails = levelInfo.details;
  15150. if (!trackDetails || this.waitForLive(levelInfo) || this.waitForCdnTuneIn(trackDetails)) {
  15151. this.state = State.WAITING_TRACK;
  15152. this.startFragRequested = false;
  15153. return;
  15154. }
  15155. const bufferable = this.mediaBuffer ? this.mediaBuffer : this.media;
  15156. if (this.bufferFlushed && bufferable) {
  15157. this.bufferFlushed = false;
  15158. this.afterBufferFlushed(bufferable, ElementaryStreamTypes.AUDIO, PlaylistLevelType.AUDIO);
  15159. }
  15160. const bufferInfo = this.getFwdBufferInfo(bufferable, PlaylistLevelType.AUDIO);
  15161. if (bufferInfo === null) {
  15162. return;
  15163. }
  15164. if (!this.switchingTrack && this._streamEnded(bufferInfo, trackDetails)) {
  15165. hls.trigger(Events.BUFFER_EOS, {
  15166. type: "audio"
  15167. });
  15168. this.state = State.ENDED;
  15169. return;
  15170. }
  15171. const bufferLen = bufferInfo.len;
  15172. const maxBufLen = hls.maxBufferLength;
  15173. const fragments = trackDetails.fragments;
  15174. const start = fragments[0].start;
  15175. const loadPosition = this.getLoadPosition();
  15176. const targetBufferTime = this.flushing ? loadPosition : bufferInfo.end;
  15177. if (this.switchingTrack && media) {
  15178. const pos = loadPosition;
  15179. if (trackDetails.PTSKnown && pos < start) {
  15180. if (bufferInfo.end > start || bufferInfo.nextStart) {
  15181. this.log("Alt audio track ahead of main track, seek to start of alt audio track");
  15182. media.currentTime = start + 0.05;
  15183. }
  15184. }
  15185. }
  15186. if (bufferLen >= maxBufLen && !this.switchingTrack && targetBufferTime < fragments[fragments.length - 1].start) {
  15187. return;
  15188. }
  15189. let frag = this.getNextFragment(targetBufferTime, trackDetails);
  15190. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  15191. frag = this.getNextFragmentLoopLoading(frag, trackDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  15192. }
  15193. if (!frag) {
  15194. this.bufferFlushed = true;
  15195. return;
  15196. }
  15197. let mainFragLoading = ((_this$mainFragLoading2 = this.mainFragLoading) == null ? void 0 : _this$mainFragLoading2.frag) || null;
  15198. if (!this.audioOnly && this.startFragRequested && mainFragLoading && isMediaFragment(frag) && !frag.endList && (!trackDetails.live || !this.loadingParts && targetBufferTime < this.hls.liveSyncPosition)) {
  15199. if (this.fragmentTracker.getState(mainFragLoading) === FragmentState.OK) {
  15200. this.mainFragLoading = mainFragLoading = null;
  15201. }
  15202. if (mainFragLoading && isMediaFragment(mainFragLoading)) {
  15203. if (frag.start > mainFragLoading.end) {
  15204. const mainFragAtPos = this.fragmentTracker.getFragAtPos(targetBufferTime, PlaylistLevelType.MAIN);
  15205. if (mainFragAtPos && mainFragAtPos.end > mainFragLoading.end) {
  15206. mainFragLoading = mainFragAtPos;
  15207. this.mainFragLoading = {
  15208. frag: mainFragAtPos,
  15209. targetBufferTime: null
  15210. };
  15211. }
  15212. }
  15213. const atBufferSyncLimit = frag.start > mainFragLoading.end;
  15214. if (atBufferSyncLimit) {
  15215. return;
  15216. }
  15217. }
  15218. }
  15219. this.loadFragment(frag, levelInfo, targetBufferTime);
  15220. }
  15221. onMediaDetaching(event, data) {
  15222. this.bufferFlushed = this.flushing = false;
  15223. super.onMediaDetaching(event, data);
  15224. }
  15225. onAudioTracksUpdated(event, {
  15226. audioTracks
  15227. }) {
  15228. this.resetTransmuxer();
  15229. this.levels = audioTracks.map((mediaPlaylist) => new Level(mediaPlaylist));
  15230. }
  15231. onAudioTrackSwitching(event, data) {
  15232. const altAudio = !!data.url;
  15233. this.trackId = data.id;
  15234. const {
  15235. fragCurrent
  15236. } = this;
  15237. if (fragCurrent) {
  15238. fragCurrent.abortRequests();
  15239. this.removeUnbufferedFrags(fragCurrent.start);
  15240. }
  15241. this.resetLoadingState();
  15242. if (altAudio) {
  15243. this.switchingTrack = data;
  15244. this.flushAudioIfNeeded(data);
  15245. if (this.state !== State.STOPPED) {
  15246. this.setInterval(TICK_INTERVAL$3);
  15247. this.state = State.IDLE;
  15248. this.tick();
  15249. }
  15250. } else {
  15251. this.resetTransmuxer();
  15252. this.switchingTrack = null;
  15253. this.bufferedTrack = data;
  15254. this.clearInterval();
  15255. }
  15256. }
  15257. onManifestLoading() {
  15258. super.onManifestLoading();
  15259. this.bufferFlushed = this.flushing = this.audioOnly = false;
  15260. this.resetItem();
  15261. this.trackId = -1;
  15262. }
  15263. onLevelLoaded(event, data) {
  15264. this.mainDetails = data.details;
  15265. const cachedTrackLoadedData = this.cachedTrackLoadedData;
  15266. if (cachedTrackLoadedData) {
  15267. this.cachedTrackLoadedData = null;
  15268. this.onAudioTrackLoaded(Events.AUDIO_TRACK_LOADED, cachedTrackLoadedData);
  15269. }
  15270. }
  15271. onAudioTrackLoaded(event, data) {
  15272. var _trackLevel$details;
  15273. const {
  15274. levels
  15275. } = this;
  15276. const {
  15277. details: newDetails,
  15278. id: trackId,
  15279. groupId,
  15280. track
  15281. } = data;
  15282. if (!levels) {
  15283. this.warn(`Audio tracks reset while loading track ${trackId} "${track.name}" of "${groupId}"`);
  15284. return;
  15285. }
  15286. const mainDetails = this.mainDetails;
  15287. if (!mainDetails || newDetails.endCC > mainDetails.endCC || mainDetails.expired) {
  15288. this.cachedTrackLoadedData = data;
  15289. if (this.state !== State.STOPPED) {
  15290. this.state = State.WAITING_TRACK;
  15291. }
  15292. return;
  15293. }
  15294. this.cachedTrackLoadedData = null;
  15295. this.log(`Audio track ${trackId} "${track.name}" of "${groupId}" loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""},duration:${newDetails.totalduration}`);
  15296. const trackLevel = levels[trackId];
  15297. let sliding = 0;
  15298. if (newDetails.live || (_trackLevel$details = trackLevel.details) != null && _trackLevel$details.live) {
  15299. this.checkLiveUpdate(newDetails);
  15300. if (newDetails.deltaUpdateFailed) {
  15301. return;
  15302. }
  15303. if (trackLevel.details) {
  15304. var _this$levelLastLoaded;
  15305. sliding = this.alignPlaylists(newDetails, trackLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  15306. }
  15307. if (!newDetails.alignedSliding) {
  15308. alignDiscontinuities(newDetails, mainDetails);
  15309. if (!newDetails.alignedSliding) {
  15310. alignMediaPlaylistByPDT(newDetails, mainDetails);
  15311. }
  15312. sliding = newDetails.fragmentStart;
  15313. }
  15314. }
  15315. trackLevel.details = newDetails;
  15316. this.levelLastLoaded = trackLevel;
  15317. if (!this.startFragRequested) {
  15318. this.setStartPosition(mainDetails, sliding);
  15319. }
  15320. this.hls.trigger(Events.AUDIO_TRACK_UPDATED, {
  15321. details: newDetails,
  15322. id: trackId,
  15323. groupId: data.groupId
  15324. });
  15325. if (this.state === State.WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) {
  15326. this.state = State.IDLE;
  15327. }
  15328. this.tick();
  15329. }
  15330. _handleFragmentLoadProgress(data) {
  15331. var _frag$initSegment;
  15332. const frag = data.frag;
  15333. const {
  15334. part,
  15335. payload
  15336. } = data;
  15337. const {
  15338. config,
  15339. trackId,
  15340. levels
  15341. } = this;
  15342. if (!levels) {
  15343. this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  15344. return;
  15345. }
  15346. const track = levels[trackId];
  15347. if (!track) {
  15348. this.warn("Audio track is undefined on fragment load progress");
  15349. return;
  15350. }
  15351. const details = track.details;
  15352. if (!details) {
  15353. this.warn("Audio track details undefined on fragment load progress");
  15354. this.removeUnbufferedFrags(frag.start);
  15355. return;
  15356. }
  15357. const audioCodec = config.defaultAudioCodec || track.audioCodec || "mp4a.40.2";
  15358. let transmuxer = this.transmuxer;
  15359. if (!transmuxer) {
  15360. transmuxer = this.transmuxer = new TransmuxerInterface(this.hls, PlaylistLevelType.AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  15361. }
  15362. const initPTS = this.initPTS[frag.cc];
  15363. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  15364. if (initPTS !== void 0) {
  15365. const accurateTimeOffset = false;
  15366. const partIndex = part ? part.index : -1;
  15367. const partial = partIndex !== -1;
  15368. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  15369. transmuxer.push(payload, initSegmentData, audioCodec, "", frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  15370. } else {
  15371. this.log(`Unknown video PTS for cc ${frag.cc}, waiting for video PTS before demuxing audio frag ${frag.sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);
  15372. const {
  15373. cache
  15374. } = this.waitingData = this.waitingData || {
  15375. frag,
  15376. part,
  15377. cache: new ChunkCache(),
  15378. complete: false
  15379. };
  15380. cache.push(new Uint8Array(payload));
  15381. if (this.state !== State.STOPPED) {
  15382. this.state = State.WAITING_INIT_PTS;
  15383. }
  15384. }
  15385. }
  15386. _handleFragmentLoadComplete(fragLoadedData) {
  15387. if (this.waitingData) {
  15388. this.waitingData.complete = true;
  15389. return;
  15390. }
  15391. super._handleFragmentLoadComplete(fragLoadedData);
  15392. }
  15393. onBufferReset() {
  15394. this.mediaBuffer = null;
  15395. }
  15396. onBufferCreated(event, data) {
  15397. this.bufferFlushed = this.flushing = false;
  15398. const audioTrack = data.tracks.audio;
  15399. if (audioTrack) {
  15400. this.mediaBuffer = audioTrack.buffer || null;
  15401. }
  15402. }
  15403. onFragLoading(event, data) {
  15404. if (!this.audioOnly && data.frag.type === PlaylistLevelType.MAIN && isMediaFragment(data.frag)) {
  15405. this.mainFragLoading = data;
  15406. if (this.state === State.IDLE) {
  15407. this.tick();
  15408. }
  15409. }
  15410. }
  15411. onFragBuffered(event, data) {
  15412. const {
  15413. frag,
  15414. part
  15415. } = data;
  15416. if (frag.type !== PlaylistLevelType.AUDIO) {
  15417. if (!this.audioOnly && frag.type === PlaylistLevelType.MAIN && !frag.elementaryStreams.video && !frag.elementaryStreams.audiovideo) {
  15418. this.audioOnly = true;
  15419. this.mainFragLoading = null;
  15420. }
  15421. return;
  15422. }
  15423. if (this.fragContextChanged(frag)) {
  15424. this.warn(`Fragment ${frag.sn}${part ? " p: " + part.index : ""} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack ? this.switchingTrack.name : "false"}`);
  15425. return;
  15426. }
  15427. if (isMediaFragment(frag)) {
  15428. this.fragPrevious = frag;
  15429. const track = this.switchingTrack;
  15430. if (track) {
  15431. this.bufferedTrack = track;
  15432. this.switchingTrack = null;
  15433. this.hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, track));
  15434. }
  15435. }
  15436. this.fragBufferedComplete(frag, part);
  15437. if (this.media) {
  15438. this.tick();
  15439. }
  15440. }
  15441. onError(event, data) {
  15442. var _data$context;
  15443. if (data.fatal) {
  15444. this.state = State.ERROR;
  15445. return;
  15446. }
  15447. switch (data.details) {
  15448. case ErrorDetails.FRAG_GAP:
  15449. case ErrorDetails.FRAG_PARSING_ERROR:
  15450. case ErrorDetails.FRAG_DECRYPT_ERROR:
  15451. case ErrorDetails.FRAG_LOAD_ERROR:
  15452. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  15453. case ErrorDetails.KEY_LOAD_ERROR:
  15454. case ErrorDetails.KEY_LOAD_TIMEOUT:
  15455. this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO, data);
  15456. break;
  15457. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  15458. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  15459. case ErrorDetails.LEVEL_PARSING_ERROR:
  15460. if (!data.levelRetry && this.state === State.WAITING_TRACK && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.AUDIO_TRACK) {
  15461. this.state = State.IDLE;
  15462. }
  15463. break;
  15464. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  15465. case ErrorDetails.BUFFER_APPEND_ERROR:
  15466. if (data.parent !== "audio") {
  15467. return;
  15468. }
  15469. if (!this.reduceLengthAndFlushBuffer(data)) {
  15470. this.resetLoadingState();
  15471. }
  15472. break;
  15473. case ErrorDetails.BUFFER_FULL_ERROR:
  15474. if (data.parent !== "audio") {
  15475. return;
  15476. }
  15477. if (this.reduceLengthAndFlushBuffer(data)) {
  15478. this.bufferedTrack = null;
  15479. super.flushMainBuffer(0, Number.POSITIVE_INFINITY, "audio");
  15480. }
  15481. break;
  15482. case ErrorDetails.INTERNAL_EXCEPTION:
  15483. this.recoverWorkerError(data);
  15484. break;
  15485. }
  15486. }
  15487. onBufferFlushing(event, {
  15488. type
  15489. }) {
  15490. if (type !== ElementaryStreamTypes.VIDEO) {
  15491. this.flushing = true;
  15492. }
  15493. }
  15494. onBufferFlushed(event, {
  15495. type
  15496. }) {
  15497. if (type !== ElementaryStreamTypes.VIDEO) {
  15498. this.flushing = false;
  15499. this.bufferFlushed = true;
  15500. if (this.state === State.ENDED) {
  15501. this.state = State.IDLE;
  15502. }
  15503. const mediaBuffer = this.mediaBuffer || this.media;
  15504. if (mediaBuffer) {
  15505. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.AUDIO);
  15506. this.tick();
  15507. }
  15508. }
  15509. }
  15510. _handleTransmuxComplete(transmuxResult) {
  15511. var _id3$samples;
  15512. const id = "audio";
  15513. const {
  15514. hls
  15515. } = this;
  15516. const {
  15517. remuxResult,
  15518. chunkMeta
  15519. } = transmuxResult;
  15520. const context = this.getCurrentContext(chunkMeta);
  15521. if (!context) {
  15522. this.resetWhenMissingContext(chunkMeta);
  15523. return;
  15524. }
  15525. const {
  15526. frag,
  15527. part,
  15528. level
  15529. } = context;
  15530. const {
  15531. details
  15532. } = level;
  15533. const {
  15534. audio,
  15535. text,
  15536. id3,
  15537. initSegment
  15538. } = remuxResult;
  15539. if (this.fragContextChanged(frag) || !details) {
  15540. this.fragmentTracker.removeFragment(frag);
  15541. return;
  15542. }
  15543. this.state = State.PARSING;
  15544. if (this.switchingTrack && audio) {
  15545. this.completeAudioSwitch(this.switchingTrack);
  15546. }
  15547. if (initSegment != null && initSegment.tracks) {
  15548. const mapFragment = frag.initSegment || frag;
  15549. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  15550. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  15551. frag: mapFragment,
  15552. id,
  15553. tracks: initSegment.tracks
  15554. });
  15555. }
  15556. if (audio) {
  15557. const {
  15558. startPTS,
  15559. endPTS,
  15560. startDTS,
  15561. endDTS
  15562. } = audio;
  15563. if (part) {
  15564. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  15565. startPTS,
  15566. endPTS,
  15567. startDTS,
  15568. endDTS
  15569. };
  15570. }
  15571. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  15572. this.bufferFragmentData(audio, frag, part, chunkMeta);
  15573. }
  15574. if (id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  15575. const emittedID3 = _extends({
  15576. id,
  15577. frag,
  15578. details
  15579. }, id3);
  15580. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  15581. }
  15582. if (text) {
  15583. const emittedText = _extends({
  15584. id,
  15585. frag,
  15586. details
  15587. }, text);
  15588. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  15589. }
  15590. }
  15591. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  15592. if (this.state !== State.PARSING) {
  15593. return;
  15594. }
  15595. if (tracks.video) {
  15596. delete tracks.video;
  15597. }
  15598. if (tracks.audiovideo) {
  15599. delete tracks.audiovideo;
  15600. }
  15601. if (!tracks.audio) {
  15602. return;
  15603. }
  15604. const track = tracks.audio;
  15605. track.id = PlaylistLevelType.AUDIO;
  15606. const variantAudioCodecs = currentLevel.audioCodec;
  15607. this.log(`Init audio buffer, container:${track.container}, codecs[level/parsed]=[${variantAudioCodecs}/${track.codec}]`);
  15608. if (variantAudioCodecs && variantAudioCodecs.split(",").length === 1) {
  15609. track.levelCodec = variantAudioCodecs;
  15610. }
  15611. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  15612. const initSegment = track.initSegment;
  15613. if (initSegment != null && initSegment.byteLength) {
  15614. const segment = {
  15615. type: "audio",
  15616. frag,
  15617. part: null,
  15618. chunkMeta,
  15619. parent: frag.type,
  15620. data: initSegment
  15621. };
  15622. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  15623. }
  15624. this.tickImmediate();
  15625. }
  15626. loadFragment(frag, track, targetBufferTime) {
  15627. const fragState = this.fragmentTracker.getState(frag);
  15628. if (this.switchingTrack || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  15629. var _track$details;
  15630. if (!isMediaFragment(frag)) {
  15631. this._loadInitSegment(frag, track);
  15632. } else if ((_track$details = track.details) != null && _track$details.live && !this.initPTS[frag.cc]) {
  15633. this.log(`Waiting for video PTS in continuity counter ${frag.cc} of live stream before loading audio fragment ${frag.sn} of level ${this.trackId}`);
  15634. this.state = State.WAITING_INIT_PTS;
  15635. const mainDetails = this.mainDetails;
  15636. if (mainDetails && mainDetails.fragmentStart !== track.details.fragmentStart) {
  15637. alignMediaPlaylistByPDT(track.details, mainDetails);
  15638. }
  15639. } else {
  15640. super.loadFragment(frag, track, targetBufferTime);
  15641. }
  15642. } else {
  15643. this.clearTrackerIfNeeded(frag);
  15644. }
  15645. }
  15646. flushAudioIfNeeded(switchingTrack) {
  15647. if (this.media && this.bufferedTrack) {
  15648. const {
  15649. name,
  15650. lang,
  15651. assocLang,
  15652. characteristics,
  15653. audioCodec,
  15654. channels
  15655. } = this.bufferedTrack;
  15656. if (!matchesOption({
  15657. name,
  15658. lang,
  15659. assocLang,
  15660. characteristics,
  15661. audioCodec,
  15662. channels
  15663. }, switchingTrack, audioMatchPredicate)) {
  15664. if (useAlternateAudio(switchingTrack.url, this.hls)) {
  15665. this.log("Switching audio track : flushing all audio");
  15666. super.flushMainBuffer(0, Number.POSITIVE_INFINITY, "audio");
  15667. this.bufferedTrack = null;
  15668. } else {
  15669. this.bufferedTrack = switchingTrack;
  15670. }
  15671. }
  15672. }
  15673. }
  15674. completeAudioSwitch(switchingTrack) {
  15675. const {
  15676. hls
  15677. } = this;
  15678. this.flushAudioIfNeeded(switchingTrack);
  15679. this.bufferedTrack = switchingTrack;
  15680. this.switchingTrack = null;
  15681. hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, switchingTrack));
  15682. }
  15683. };
  15684. var BasePlaylistController = class extends Logger {
  15685. constructor(hls, logPrefix) {
  15686. super(logPrefix, hls.logger);
  15687. this.hls = void 0;
  15688. this.canLoad = false;
  15689. this.timer = -1;
  15690. this.hls = hls;
  15691. }
  15692. destroy() {
  15693. this.clearTimer();
  15694. this.hls = this.log = this.warn = null;
  15695. }
  15696. clearTimer() {
  15697. if (this.timer !== -1) {
  15698. self.clearTimeout(this.timer);
  15699. this.timer = -1;
  15700. }
  15701. }
  15702. startLoad() {
  15703. this.canLoad = true;
  15704. this.loadPlaylist();
  15705. }
  15706. stopLoad() {
  15707. this.canLoad = false;
  15708. this.clearTimer();
  15709. }
  15710. switchParams(playlistUri, previous, current) {
  15711. const renditionReports = previous == null ? void 0 : previous.renditionReports;
  15712. if (renditionReports) {
  15713. let foundIndex = -1;
  15714. for (let i = 0; i < renditionReports.length; i++) {
  15715. const attr = renditionReports[i];
  15716. let uri;
  15717. try {
  15718. uri = new self.URL(attr.URI, previous.url).href;
  15719. } catch (error) {
  15720. this.warn(`Could not construct new URL for Rendition Report: ${error}`);
  15721. uri = attr.URI || "";
  15722. }
  15723. if (uri === playlistUri) {
  15724. foundIndex = i;
  15725. break;
  15726. } else if (uri === playlistUri.substring(0, uri.length)) {
  15727. foundIndex = i;
  15728. }
  15729. }
  15730. if (foundIndex !== -1) {
  15731. const attr = renditionReports[foundIndex];
  15732. const msn = parseInt(attr["LAST-MSN"]) || (previous == null ? void 0 : previous.lastPartSn);
  15733. let part = parseInt(attr["LAST-PART"]) || (previous == null ? void 0 : previous.lastPartIndex);
  15734. if (this.hls.config.lowLatencyMode) {
  15735. const currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
  15736. if (part >= 0 && currentGoal > previous.partTarget) {
  15737. part += 1;
  15738. }
  15739. }
  15740. const skip = current && getSkipValue(current);
  15741. return new HlsUrlParameters(msn, part >= 0 ? part : void 0, skip);
  15742. }
  15743. }
  15744. }
  15745. loadPlaylist(hlsUrlParameters) {
  15746. this.clearTimer();
  15747. }
  15748. loadingPlaylist(playlist, hlsUrlParameters) {
  15749. this.clearTimer();
  15750. }
  15751. shouldLoadPlaylist(playlist) {
  15752. return this.canLoad && !!playlist && !!playlist.url && (!playlist.details || playlist.details.live);
  15753. }
  15754. getUrlWithDirectives(uri, hlsUrlParameters) {
  15755. if (hlsUrlParameters) {
  15756. try {
  15757. return hlsUrlParameters.addDirectives(uri);
  15758. } catch (error) {
  15759. this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`);
  15760. }
  15761. }
  15762. return uri;
  15763. }
  15764. playlistLoaded(index, data, previousDetails) {
  15765. const {
  15766. details,
  15767. stats
  15768. } = data;
  15769. const now2 = self.performance.now();
  15770. const elapsed = stats.loading.first ? Math.max(0, now2 - stats.loading.first) : 0;
  15771. details.advancedDateTime = Date.now() - elapsed;
  15772. const timelineOffset = this.hls.config.timelineOffset;
  15773. if (timelineOffset !== details.appliedTimelineOffset) {
  15774. const offset = Math.max(timelineOffset || 0, 0);
  15775. details.appliedTimelineOffset = offset;
  15776. details.fragments.forEach((frag) => {
  15777. frag.start = frag.playlistOffset + offset;
  15778. });
  15779. }
  15780. if (details.live || previousDetails != null && previousDetails.live) {
  15781. const levelOrTrack = "levelInfo" in data ? data.levelInfo : data.track;
  15782. details.reloaded(previousDetails);
  15783. if (previousDetails && details.fragments.length > 0) {
  15784. mergeDetails(previousDetails, details);
  15785. const error = details.playlistParsingError;
  15786. if (error) {
  15787. this.warn(error);
  15788. const hls = this.hls;
  15789. if (!hls.config.ignorePlaylistParsingErrors) {
  15790. var _details$fragments$;
  15791. const {
  15792. networkDetails
  15793. } = data;
  15794. hls.trigger(Events.ERROR, {
  15795. type: ErrorTypes.NETWORK_ERROR,
  15796. details: ErrorDetails.LEVEL_PARSING_ERROR,
  15797. fatal: false,
  15798. url: details.url,
  15799. error,
  15800. reason: error.message,
  15801. level: data.level || void 0,
  15802. parent: (_details$fragments$ = details.fragments[0]) == null ? void 0 : _details$fragments$.type,
  15803. networkDetails,
  15804. stats
  15805. });
  15806. return;
  15807. }
  15808. details.playlistParsingError = null;
  15809. }
  15810. }
  15811. if (details.requestScheduled === -1) {
  15812. details.requestScheduled = stats.loading.start;
  15813. }
  15814. const bufferInfo = this.hls.mainForwardBufferInfo;
  15815. const position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;
  15816. const distanceToLiveEdgeMs = (details.edge - position) * 1e3;
  15817. const reloadInterval = computeReloadInterval(details, distanceToLiveEdgeMs);
  15818. if (details.requestScheduled + reloadInterval < now2) {
  15819. details.requestScheduled = now2;
  15820. } else {
  15821. details.requestScheduled += reloadInterval;
  15822. }
  15823. this.log(`live playlist ${index} ${details.advanced ? "REFRESHED " + details.lastPartSn + "-" + details.lastPartIndex : details.updated ? "UPDATED" : "MISSED"}`);
  15824. if (!this.canLoad || !details.live) {
  15825. return;
  15826. }
  15827. let deliveryDirectives;
  15828. let msn = void 0;
  15829. let part = void 0;
  15830. if (details.canBlockReload && details.endSN && details.advanced) {
  15831. const lowLatencyMode = this.hls.config.lowLatencyMode;
  15832. const lastPartSn = details.lastPartSn;
  15833. const endSn = details.endSN;
  15834. const lastPartIndex = details.lastPartIndex;
  15835. const hasParts = lastPartIndex !== -1;
  15836. const atLastPartOfSegment = lastPartSn === endSn;
  15837. if (hasParts) {
  15838. if (atLastPartOfSegment) {
  15839. msn = endSn + 1;
  15840. part = lowLatencyMode ? 0 : lastPartIndex;
  15841. } else {
  15842. msn = lastPartSn;
  15843. part = lowLatencyMode ? lastPartIndex + 1 : details.maxPartIndex;
  15844. }
  15845. } else {
  15846. msn = endSn + 1;
  15847. }
  15848. const lastAdvanced = details.age;
  15849. const cdnAge = lastAdvanced + details.ageHeader;
  15850. let currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
  15851. if (currentGoal > 0) {
  15852. if (cdnAge > details.targetduration * 3) {
  15853. this.log(`Playlist last advanced ${lastAdvanced.toFixed(2)}s ago. Omitting segment and part directives.`);
  15854. msn = void 0;
  15855. part = void 0;
  15856. } else if (previousDetails != null && previousDetails.tuneInGoal && cdnAge - details.partTarget > previousDetails.tuneInGoal) {
  15857. this.warn(`CDN Tune-in goal increased from: ${previousDetails.tuneInGoal} to: ${currentGoal} with playlist age: ${details.age}`);
  15858. currentGoal = 0;
  15859. } else {
  15860. const segments = Math.floor(currentGoal / details.targetduration);
  15861. msn += segments;
  15862. if (part !== void 0) {
  15863. const parts = Math.round(currentGoal % details.targetduration / details.partTarget);
  15864. part += parts;
  15865. }
  15866. this.log(`CDN Tune-in age: ${details.ageHeader}s last advanced ${lastAdvanced.toFixed(2)}s goal: ${currentGoal} skip sn ${segments} to part ${part}`);
  15867. }
  15868. details.tuneInGoal = currentGoal;
  15869. }
  15870. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  15871. if (lowLatencyMode || !atLastPartOfSegment) {
  15872. details.requestScheduled = now2;
  15873. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  15874. return;
  15875. }
  15876. } else if (details.canBlockReload || details.canSkipUntil) {
  15877. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  15878. }
  15879. if (deliveryDirectives && msn !== void 0 && details.canBlockReload) {
  15880. details.requestScheduled = stats.loading.first + Math.max(reloadInterval - elapsed * 2, reloadInterval / 2);
  15881. }
  15882. this.scheduleLoading(levelOrTrack, deliveryDirectives, details);
  15883. } else {
  15884. this.clearTimer();
  15885. }
  15886. }
  15887. scheduleLoading(levelOrTrack, deliveryDirectives, updatedDetails) {
  15888. const details = updatedDetails || levelOrTrack.details;
  15889. if (!details) {
  15890. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  15891. return;
  15892. }
  15893. const now2 = self.performance.now();
  15894. const requestScheduled = details.requestScheduled;
  15895. if (now2 >= requestScheduled) {
  15896. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  15897. return;
  15898. }
  15899. const estimatedTimeUntilUpdate = requestScheduled - now2;
  15900. this.log(`reload live playlist ${levelOrTrack.name || levelOrTrack.bitrate + "bps"} in ${Math.round(estimatedTimeUntilUpdate)} ms`);
  15901. this.clearTimer();
  15902. this.timer = self.setTimeout(() => this.loadingPlaylist(levelOrTrack, deliveryDirectives), estimatedTimeUntilUpdate);
  15903. }
  15904. getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
  15905. let skip = getSkipValue(details);
  15906. if (previousDeliveryDirectives != null && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
  15907. msn = previousDeliveryDirectives.msn;
  15908. part = previousDeliveryDirectives.part;
  15909. skip = HlsSkip.No;
  15910. }
  15911. return new HlsUrlParameters(msn, part, skip);
  15912. }
  15913. checkRetry(errorEvent) {
  15914. const errorDetails = errorEvent.details;
  15915. const isTimeout = isTimeoutError(errorEvent);
  15916. const errorAction = errorEvent.errorAction;
  15917. const {
  15918. action,
  15919. retryCount = 0,
  15920. retryConfig
  15921. } = errorAction || {};
  15922. const retry = !!errorAction && !!retryConfig && (action === NetworkErrorAction.RetryRequest || !errorAction.resolved && action === NetworkErrorAction.SendAlternateToPenaltyBox);
  15923. if (retry) {
  15924. var _errorEvent$context;
  15925. if (retryCount >= retryConfig.maxNumRetry) {
  15926. return false;
  15927. }
  15928. if (isTimeout && (_errorEvent$context = errorEvent.context) != null && _errorEvent$context.deliveryDirectives) {
  15929. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" without delivery-directives`);
  15930. this.loadPlaylist();
  15931. } else {
  15932. const delay = getRetryDelay(retryConfig, retryCount);
  15933. this.clearTimer();
  15934. this.timer = self.setTimeout(() => this.loadPlaylist(), delay);
  15935. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" in ${delay}ms`);
  15936. }
  15937. errorEvent.levelRetry = true;
  15938. errorAction.resolved = true;
  15939. }
  15940. return retry;
  15941. }
  15942. };
  15943. function subtitleOptionsIdentical(trackList1, trackList2) {
  15944. if (trackList1.length !== trackList2.length) {
  15945. return false;
  15946. }
  15947. for (let i = 0; i < trackList1.length; i++) {
  15948. if (!mediaAttributesIdentical(trackList1[i].attrs, trackList2[i].attrs)) {
  15949. return false;
  15950. }
  15951. }
  15952. return true;
  15953. }
  15954. function mediaAttributesIdentical(attrs1, attrs2, customAttributes) {
  15955. const stableRenditionId = attrs1["STABLE-RENDITION-ID"];
  15956. if (stableRenditionId && !customAttributes) {
  15957. return stableRenditionId === attrs2["STABLE-RENDITION-ID"];
  15958. }
  15959. return !(customAttributes || ["LANGUAGE", "NAME", "CHARACTERISTICS", "AUTOSELECT", "DEFAULT", "FORCED", "ASSOC-LANGUAGE"]).some((subtitleAttribute) => attrs1[subtitleAttribute] !== attrs2[subtitleAttribute]);
  15960. }
  15961. function subtitleTrackMatchesTextTrack(subtitleTrack, textTrack) {
  15962. return textTrack.label.toLowerCase() === subtitleTrack.name.toLowerCase() && (!textTrack.language || textTrack.language.toLowerCase() === (subtitleTrack.lang || "").toLowerCase());
  15963. }
  15964. var AudioTrackController = class extends BasePlaylistController {
  15965. constructor(hls) {
  15966. super(hls, "audio-track-controller");
  15967. this.tracks = [];
  15968. this.groupIds = null;
  15969. this.tracksInGroup = [];
  15970. this.trackId = -1;
  15971. this.currentTrack = null;
  15972. this.selectDefaultTrack = true;
  15973. this.registerListeners();
  15974. }
  15975. registerListeners() {
  15976. const {
  15977. hls
  15978. } = this;
  15979. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  15980. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  15981. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  15982. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  15983. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  15984. hls.on(Events.ERROR, this.onError, this);
  15985. }
  15986. unregisterListeners() {
  15987. const {
  15988. hls
  15989. } = this;
  15990. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  15991. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  15992. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  15993. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  15994. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  15995. hls.off(Events.ERROR, this.onError, this);
  15996. }
  15997. destroy() {
  15998. this.unregisterListeners();
  15999. this.tracks.length = 0;
  16000. this.tracksInGroup.length = 0;
  16001. this.currentTrack = null;
  16002. super.destroy();
  16003. }
  16004. onManifestLoading() {
  16005. this.tracks = [];
  16006. this.tracksInGroup = [];
  16007. this.groupIds = null;
  16008. this.currentTrack = null;
  16009. this.trackId = -1;
  16010. this.selectDefaultTrack = true;
  16011. }
  16012. onManifestParsed(event, data) {
  16013. this.tracks = data.audioTracks || [];
  16014. }
  16015. onAudioTrackLoaded(event, data) {
  16016. const {
  16017. id,
  16018. groupId,
  16019. details
  16020. } = data;
  16021. const trackInActiveGroup = this.tracksInGroup[id];
  16022. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  16023. this.warn(`Audio track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
  16024. return;
  16025. }
  16026. const curDetails = trackInActiveGroup.details;
  16027. trackInActiveGroup.details = data.details;
  16028. this.log(`Audio track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
  16029. if (id === this.trackId) {
  16030. this.playlistLoaded(id, data, curDetails);
  16031. }
  16032. }
  16033. onLevelLoading(event, data) {
  16034. this.switchLevel(data.level);
  16035. }
  16036. onLevelSwitching(event, data) {
  16037. this.switchLevel(data.level);
  16038. }
  16039. switchLevel(levelIndex) {
  16040. const levelInfo = this.hls.levels[levelIndex];
  16041. if (!levelInfo) {
  16042. return;
  16043. }
  16044. const audioGroups = levelInfo.audioGroups || null;
  16045. const currentGroups = this.groupIds;
  16046. let currentTrack = this.currentTrack;
  16047. if (!audioGroups || (currentGroups == null ? void 0 : currentGroups.length) !== (audioGroups == null ? void 0 : audioGroups.length) || audioGroups != null && audioGroups.some((groupId) => (currentGroups == null ? void 0 : currentGroups.indexOf(groupId)) === -1)) {
  16048. this.groupIds = audioGroups;
  16049. this.trackId = -1;
  16050. this.currentTrack = null;
  16051. const audioTracks = this.tracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  16052. if (audioTracks.length) {
  16053. if (this.selectDefaultTrack && !audioTracks.some((track) => track.default)) {
  16054. this.selectDefaultTrack = false;
  16055. }
  16056. audioTracks.forEach((track, i) => {
  16057. track.id = i;
  16058. });
  16059. } else if (!currentTrack && !this.tracksInGroup.length) {
  16060. return;
  16061. }
  16062. this.tracksInGroup = audioTracks;
  16063. const audioPreference = this.hls.config.audioPreference;
  16064. if (!currentTrack && audioPreference) {
  16065. const groupIndex = findMatchingOption(audioPreference, audioTracks, audioMatchPredicate);
  16066. if (groupIndex > -1) {
  16067. currentTrack = audioTracks[groupIndex];
  16068. } else {
  16069. const allIndex = findMatchingOption(audioPreference, this.tracks);
  16070. currentTrack = this.tracks[allIndex];
  16071. }
  16072. }
  16073. let trackId = this.findTrackId(currentTrack);
  16074. if (trackId === -1 && currentTrack) {
  16075. trackId = this.findTrackId(null);
  16076. }
  16077. const audioTracksUpdated = {
  16078. audioTracks
  16079. };
  16080. this.log(`Updating audio tracks, ${audioTracks.length} track(s) found in group(s): ${audioGroups == null ? void 0 : audioGroups.join(",")}`);
  16081. this.hls.trigger(Events.AUDIO_TRACKS_UPDATED, audioTracksUpdated);
  16082. const selectedTrackId = this.trackId;
  16083. if (trackId !== -1 && selectedTrackId === -1) {
  16084. this.setAudioTrack(trackId);
  16085. } else if (audioTracks.length && selectedTrackId === -1) {
  16086. var _this$groupIds;
  16087. const error = new Error(`No audio track selected for current audio group-ID(s): ${(_this$groupIds = this.groupIds) == null ? void 0 : _this$groupIds.join(",")} track count: ${audioTracks.length}`);
  16088. this.warn(error.message);
  16089. this.hls.trigger(Events.ERROR, {
  16090. type: ErrorTypes.MEDIA_ERROR,
  16091. details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,
  16092. fatal: true,
  16093. error
  16094. });
  16095. }
  16096. }
  16097. }
  16098. onError(event, data) {
  16099. if (data.fatal || !data.context) {
  16100. return;
  16101. }
  16102. if (data.context.type === PlaylistContextType.AUDIO_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  16103. this.checkRetry(data);
  16104. }
  16105. }
  16106. get allAudioTracks() {
  16107. return this.tracks;
  16108. }
  16109. get audioTracks() {
  16110. return this.tracksInGroup;
  16111. }
  16112. get audioTrack() {
  16113. return this.trackId;
  16114. }
  16115. set audioTrack(newId) {
  16116. this.selectDefaultTrack = false;
  16117. this.setAudioTrack(newId);
  16118. }
  16119. setAudioOption(audioOption) {
  16120. const hls = this.hls;
  16121. hls.config.audioPreference = audioOption;
  16122. if (audioOption) {
  16123. const allAudioTracks = this.allAudioTracks;
  16124. this.selectDefaultTrack = false;
  16125. if (allAudioTracks.length) {
  16126. const currentTrack = this.currentTrack;
  16127. if (currentTrack && matchesOption(audioOption, currentTrack, audioMatchPredicate)) {
  16128. return currentTrack;
  16129. }
  16130. const groupIndex = findMatchingOption(audioOption, this.tracksInGroup, audioMatchPredicate);
  16131. if (groupIndex > -1) {
  16132. const track = this.tracksInGroup[groupIndex];
  16133. this.setAudioTrack(groupIndex);
  16134. return track;
  16135. } else if (currentTrack) {
  16136. let searchIndex = hls.loadLevel;
  16137. if (searchIndex === -1) {
  16138. searchIndex = hls.firstAutoLevel;
  16139. }
  16140. const switchIndex = findClosestLevelWithAudioGroup(audioOption, hls.levels, allAudioTracks, searchIndex, audioMatchPredicate);
  16141. if (switchIndex === -1) {
  16142. return null;
  16143. }
  16144. hls.nextLoadLevel = switchIndex;
  16145. }
  16146. if (audioOption.channels || audioOption.audioCodec) {
  16147. const withoutCodecAndChannelsMatch = findMatchingOption(audioOption, allAudioTracks);
  16148. if (withoutCodecAndChannelsMatch > -1) {
  16149. return allAudioTracks[withoutCodecAndChannelsMatch];
  16150. }
  16151. }
  16152. }
  16153. }
  16154. return null;
  16155. }
  16156. setAudioTrack(newId) {
  16157. const tracks = this.tracksInGroup;
  16158. if (newId < 0 || newId >= tracks.length) {
  16159. this.warn(`Invalid audio track id: ${newId}`);
  16160. return;
  16161. }
  16162. this.selectDefaultTrack = false;
  16163. const lastTrack = this.currentTrack;
  16164. const track = tracks[newId];
  16165. const trackLoaded = track.details && !track.details.live;
  16166. if (newId === this.trackId && track === lastTrack && trackLoaded) {
  16167. return;
  16168. }
  16169. this.log(`Switching to audio-track ${newId} "${track.name}" lang:${track.lang} group:${track.groupId} channels:${track.channels}`);
  16170. this.trackId = newId;
  16171. this.currentTrack = track;
  16172. this.hls.trigger(Events.AUDIO_TRACK_SWITCHING, _objectSpread2({}, track));
  16173. if (trackLoaded) {
  16174. return;
  16175. }
  16176. const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
  16177. this.loadPlaylist(hlsUrlParameters);
  16178. }
  16179. findTrackId(currentTrack) {
  16180. const audioTracks = this.tracksInGroup;
  16181. for (let i = 0; i < audioTracks.length; i++) {
  16182. const track = audioTracks[i];
  16183. if (this.selectDefaultTrack && !track.default) {
  16184. continue;
  16185. }
  16186. if (!currentTrack || matchesOption(currentTrack, track, audioMatchPredicate)) {
  16187. return i;
  16188. }
  16189. }
  16190. if (currentTrack) {
  16191. const {
  16192. name,
  16193. lang,
  16194. assocLang,
  16195. characteristics,
  16196. audioCodec,
  16197. channels
  16198. } = currentTrack;
  16199. for (let i = 0; i < audioTracks.length; i++) {
  16200. const track = audioTracks[i];
  16201. if (matchesOption({
  16202. name,
  16203. lang,
  16204. assocLang,
  16205. characteristics,
  16206. audioCodec,
  16207. channels
  16208. }, track, audioMatchPredicate)) {
  16209. return i;
  16210. }
  16211. }
  16212. for (let i = 0; i < audioTracks.length; i++) {
  16213. const track = audioTracks[i];
  16214. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE", "ASSOC-LANGUAGE", "CHARACTERISTICS"])) {
  16215. return i;
  16216. }
  16217. }
  16218. for (let i = 0; i < audioTracks.length; i++) {
  16219. const track = audioTracks[i];
  16220. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE"])) {
  16221. return i;
  16222. }
  16223. }
  16224. }
  16225. return -1;
  16226. }
  16227. loadPlaylist(hlsUrlParameters) {
  16228. super.loadPlaylist();
  16229. const audioTrack = this.currentTrack;
  16230. if (!this.shouldLoadPlaylist(audioTrack)) {
  16231. return;
  16232. }
  16233. if (useAlternateAudio(audioTrack.url, this.hls)) {
  16234. this.scheduleLoading(audioTrack, hlsUrlParameters);
  16235. }
  16236. }
  16237. loadingPlaylist(audioTrack, hlsUrlParameters) {
  16238. super.loadingPlaylist(audioTrack, hlsUrlParameters);
  16239. const id = audioTrack.id;
  16240. const groupId = audioTrack.groupId;
  16241. const url = this.getUrlWithDirectives(audioTrack.url, hlsUrlParameters);
  16242. const details = audioTrack.details;
  16243. const age = details == null ? void 0 : details.age;
  16244. this.log(`Loading audio-track ${id} "${audioTrack.name}" lang:${audioTrack.lang} group:${groupId}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== void 0 ? " at sn " + hlsUrlParameters.msn + " part " + hlsUrlParameters.part : ""}${age && details.live ? " age " + age.toFixed(1) + (details.type ? " " + details.type || "" : "") : ""} ${url}`);
  16245. this.hls.trigger(Events.AUDIO_TRACK_LOADING, {
  16246. url,
  16247. id,
  16248. groupId,
  16249. deliveryDirectives: hlsUrlParameters || null,
  16250. track: audioTrack
  16251. });
  16252. }
  16253. };
  16254. var BufferOperationQueue = class {
  16255. constructor(sourceBufferReference) {
  16256. this.tracks = void 0;
  16257. this.queues = {
  16258. video: [],
  16259. audio: [],
  16260. audiovideo: []
  16261. };
  16262. this.tracks = sourceBufferReference;
  16263. }
  16264. destroy() {
  16265. this.tracks = this.queues = null;
  16266. }
  16267. append(operation, type, pending) {
  16268. if (this.queues === null || this.tracks === null) {
  16269. return;
  16270. }
  16271. const queue = this.queues[type];
  16272. queue.push(operation);
  16273. if (queue.length === 1 && !pending) {
  16274. this.executeNext(type);
  16275. }
  16276. }
  16277. appendBlocker(type) {
  16278. return new Promise((resolve) => {
  16279. const operation = {
  16280. label: "async-blocker",
  16281. execute: resolve,
  16282. onStart: () => {
  16283. },
  16284. onComplete: () => {
  16285. },
  16286. onError: () => {
  16287. }
  16288. };
  16289. this.append(operation, type);
  16290. });
  16291. }
  16292. prependBlocker(type) {
  16293. return new Promise((resolve) => {
  16294. if (this.queues) {
  16295. const operation = {
  16296. label: "async-blocker-prepend",
  16297. execute: resolve,
  16298. onStart: () => {
  16299. },
  16300. onComplete: () => {
  16301. },
  16302. onError: () => {
  16303. }
  16304. };
  16305. this.queues[type].unshift(operation);
  16306. }
  16307. });
  16308. }
  16309. removeBlockers() {
  16310. if (this.queues === null) {
  16311. return;
  16312. }
  16313. [this.queues.video, this.queues.audio, this.queues.audiovideo].forEach((queue) => {
  16314. var _queue$;
  16315. const label = (_queue$ = queue[0]) == null ? void 0 : _queue$.label;
  16316. if (label === "async-blocker" || label === "async-blocker-prepend") {
  16317. queue[0].execute();
  16318. queue.splice(0, 1);
  16319. }
  16320. });
  16321. }
  16322. unblockAudio(op) {
  16323. if (this.queues === null) {
  16324. return;
  16325. }
  16326. const queue = this.queues.audio;
  16327. if (queue[0] === op) {
  16328. this.shiftAndExecuteNext("audio");
  16329. }
  16330. }
  16331. executeNext(type) {
  16332. if (this.queues === null || this.tracks === null) {
  16333. return;
  16334. }
  16335. const queue = this.queues[type];
  16336. if (queue.length) {
  16337. const operation = queue[0];
  16338. try {
  16339. operation.execute();
  16340. } catch (error) {
  16341. var _this$tracks$type;
  16342. operation.onError(error);
  16343. if (this.queues === null || this.tracks === null) {
  16344. return;
  16345. }
  16346. const sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  16347. if (!(sb != null && sb.updating)) {
  16348. this.shiftAndExecuteNext(type);
  16349. }
  16350. }
  16351. }
  16352. }
  16353. shiftAndExecuteNext(type) {
  16354. if (this.queues === null) {
  16355. return;
  16356. }
  16357. this.queues[type].shift();
  16358. this.executeNext(type);
  16359. }
  16360. current(type) {
  16361. var _this$queues;
  16362. return ((_this$queues = this.queues) == null ? void 0 : _this$queues[type][0]) || null;
  16363. }
  16364. toString() {
  16365. const {
  16366. queues,
  16367. tracks
  16368. } = this;
  16369. if (queues === null || tracks === null) {
  16370. return `<destroyed>`;
  16371. }
  16372. return `
  16373. ${this.list("video")}
  16374. ${this.list("audio")}
  16375. ${this.list("audiovideo")}}`;
  16376. }
  16377. list(type) {
  16378. var _this$queues2, _this$tracks;
  16379. return (_this$queues2 = this.queues) != null && _this$queues2[type] || (_this$tracks = this.tracks) != null && _this$tracks[type] ? `${type}: (${this.listSbInfo(type)}) ${this.listOps(type)}` : "";
  16380. }
  16381. listSbInfo(type) {
  16382. var _this$tracks2;
  16383. const track = (_this$tracks2 = this.tracks) == null ? void 0 : _this$tracks2[type];
  16384. const sb = track == null ? void 0 : track.buffer;
  16385. if (!sb) {
  16386. return "none";
  16387. }
  16388. return `SourceBuffer${sb.updating ? " updating" : ""}${track.ended ? " ended" : ""}${track.ending ? " ending" : ""}`;
  16389. }
  16390. listOps(type) {
  16391. var _this$queues3;
  16392. return ((_this$queues3 = this.queues) == null ? void 0 : _this$queues3[type].map((op) => op.label).join(", ")) || "";
  16393. }
  16394. };
  16395. var VIDEO_CODEC_PROFILE_REPLACE = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;
  16396. var TRACK_REMOVED_ERROR_NAME = "HlsJsTrackRemovedError";
  16397. var HlsJsTrackRemovedError = class extends Error {
  16398. constructor(message) {
  16399. super(message);
  16400. this.name = TRACK_REMOVED_ERROR_NAME;
  16401. }
  16402. };
  16403. var BufferController = class extends Logger {
  16404. constructor(hls, fragmentTracker) {
  16405. super("buffer-controller", hls.logger);
  16406. this.hls = void 0;
  16407. this.fragmentTracker = void 0;
  16408. this.details = null;
  16409. this._objectUrl = null;
  16410. this.operationQueue = null;
  16411. this.bufferCodecEventsTotal = 0;
  16412. this.media = null;
  16413. this.mediaSource = null;
  16414. this.lastMpegAudioChunk = null;
  16415. this.blockedAudioAppend = null;
  16416. this.lastVideoAppendEnd = 0;
  16417. this.appendSource = void 0;
  16418. this.transferData = void 0;
  16419. this.overrides = void 0;
  16420. this.appendErrors = {
  16421. audio: 0,
  16422. video: 0,
  16423. audiovideo: 0
  16424. };
  16425. this.tracks = {};
  16426. this.sourceBuffers = [[null, null], [null, null]];
  16427. this._onEndStreaming = (event) => {
  16428. var _this$mediaSource;
  16429. if (!this.hls) {
  16430. return;
  16431. }
  16432. if (((_this$mediaSource = this.mediaSource) == null ? void 0 : _this$mediaSource.readyState) !== "open") {
  16433. return;
  16434. }
  16435. this.hls.pauseBuffering();
  16436. };
  16437. this._onStartStreaming = (event) => {
  16438. if (!this.hls) {
  16439. return;
  16440. }
  16441. this.hls.resumeBuffering();
  16442. };
  16443. this._onMediaSourceOpen = (e) => {
  16444. const {
  16445. media,
  16446. mediaSource
  16447. } = this;
  16448. if (e) {
  16449. this.log("Media source opened");
  16450. }
  16451. if (!media || !mediaSource) {
  16452. return;
  16453. }
  16454. mediaSource.removeEventListener("sourceopen", this._onMediaSourceOpen);
  16455. media.removeEventListener("emptied", this._onMediaEmptied);
  16456. this.updateDuration();
  16457. this.hls.trigger(Events.MEDIA_ATTACHED, {
  16458. media,
  16459. mediaSource
  16460. });
  16461. if (this.mediaSource !== null) {
  16462. this.checkPendingTracks();
  16463. }
  16464. };
  16465. this._onMediaSourceClose = () => {
  16466. this.log("Media source closed");
  16467. };
  16468. this._onMediaSourceEnded = () => {
  16469. this.log("Media source ended");
  16470. };
  16471. this._onMediaEmptied = () => {
  16472. const {
  16473. mediaSrc,
  16474. _objectUrl
  16475. } = this;
  16476. if (mediaSrc !== _objectUrl) {
  16477. this.error(`Media element src was set while attaching MediaSource (${_objectUrl} > ${mediaSrc})`);
  16478. }
  16479. };
  16480. this.hls = hls;
  16481. this.fragmentTracker = fragmentTracker;
  16482. this.appendSource = isManagedMediaSource(getMediaSource(hls.config.preferManagedMediaSource));
  16483. this.initTracks();
  16484. this.registerListeners();
  16485. }
  16486. hasSourceTypes() {
  16487. return Object.keys(this.tracks).length > 0;
  16488. }
  16489. destroy() {
  16490. this.unregisterListeners();
  16491. this.details = null;
  16492. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  16493. this.transferData = this.overrides = void 0;
  16494. if (this.operationQueue) {
  16495. this.operationQueue.destroy();
  16496. this.operationQueue = null;
  16497. }
  16498. this.hls = this.fragmentTracker = null;
  16499. this._onMediaSourceOpen = this._onMediaSourceClose = null;
  16500. this._onMediaSourceEnded = null;
  16501. this._onStartStreaming = this._onEndStreaming = null;
  16502. }
  16503. registerListeners() {
  16504. const {
  16505. hls
  16506. } = this;
  16507. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  16508. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  16509. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16510. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  16511. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  16512. hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  16513. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  16514. hls.on(Events.BUFFER_EOS, this.onBufferEos, this);
  16515. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  16516. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  16517. hls.on(Events.FRAG_PARSED, this.onFragParsed, this);
  16518. hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);
  16519. hls.on(Events.ERROR, this.onError, this);
  16520. }
  16521. unregisterListeners() {
  16522. const {
  16523. hls
  16524. } = this;
  16525. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  16526. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  16527. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16528. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  16529. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  16530. hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  16531. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  16532. hls.off(Events.BUFFER_EOS, this.onBufferEos, this);
  16533. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  16534. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  16535. hls.off(Events.FRAG_PARSED, this.onFragParsed, this);
  16536. hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);
  16537. hls.off(Events.ERROR, this.onError, this);
  16538. }
  16539. transferMedia() {
  16540. const {
  16541. media,
  16542. mediaSource
  16543. } = this;
  16544. if (!media) {
  16545. return null;
  16546. }
  16547. const tracks = {};
  16548. if (this.operationQueue) {
  16549. const updating = this.isUpdating();
  16550. if (!updating) {
  16551. this.operationQueue.removeBlockers();
  16552. }
  16553. const queued = this.isQueued();
  16554. if (updating || queued) {
  16555. this.warn(`Transfering MediaSource with${queued ? " operations in queue" : ""}${updating ? " updating SourceBuffer(s)" : ""} ${this.operationQueue}`);
  16556. }
  16557. this.operationQueue.destroy();
  16558. }
  16559. const transferData = this.transferData;
  16560. if (!this.sourceBufferCount && transferData && transferData.mediaSource === mediaSource) {
  16561. _extends(tracks, transferData.tracks);
  16562. } else {
  16563. this.sourceBuffers.forEach((tuple) => {
  16564. const [type] = tuple;
  16565. if (type) {
  16566. tracks[type] = _extends({}, this.tracks[type]);
  16567. this.removeBuffer(type);
  16568. }
  16569. tuple[0] = tuple[1] = null;
  16570. });
  16571. }
  16572. return {
  16573. media,
  16574. mediaSource,
  16575. tracks
  16576. };
  16577. }
  16578. initTracks() {
  16579. const tracks = {};
  16580. this.sourceBuffers = [[null, null], [null, null]];
  16581. this.tracks = tracks;
  16582. this.resetQueue();
  16583. this.resetAppendErrors();
  16584. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  16585. this.lastVideoAppendEnd = 0;
  16586. }
  16587. onManifestLoading() {
  16588. this.bufferCodecEventsTotal = 0;
  16589. this.details = null;
  16590. }
  16591. onManifestParsed(event, data) {
  16592. var _this$transferData;
  16593. let codecEvents = 2;
  16594. if (data.audio && !data.video || !data.altAudio) {
  16595. codecEvents = 1;
  16596. }
  16597. this.bufferCodecEventsTotal = codecEvents;
  16598. this.log(`${codecEvents} bufferCodec event(s) expected.`);
  16599. if ((_this$transferData = this.transferData) != null && _this$transferData.mediaSource && this.sourceBufferCount && codecEvents) {
  16600. this.bufferCreated();
  16601. }
  16602. }
  16603. onMediaAttaching(event, data) {
  16604. const media = this.media = data.media;
  16605. const MediaSource = getMediaSource(this.appendSource);
  16606. this.transferData = this.overrides = void 0;
  16607. if (media && MediaSource) {
  16608. const transferringMedia = !!data.mediaSource;
  16609. if (transferringMedia || data.overrides) {
  16610. this.transferData = data;
  16611. this.overrides = data.overrides;
  16612. }
  16613. const ms = this.mediaSource = data.mediaSource || new MediaSource();
  16614. this.assignMediaSource(ms);
  16615. if (transferringMedia) {
  16616. this._objectUrl = media.src;
  16617. this.attachTransferred();
  16618. } else {
  16619. const objectUrl = this._objectUrl = self.URL.createObjectURL(ms);
  16620. if (this.appendSource) {
  16621. try {
  16622. media.removeAttribute("src");
  16623. const MMS = self.ManagedMediaSource;
  16624. media.disableRemotePlayback = media.disableRemotePlayback || MMS && ms instanceof MMS;
  16625. removeSourceChildren(media);
  16626. addSource(media, objectUrl);
  16627. media.load();
  16628. } catch (error) {
  16629. media.src = objectUrl;
  16630. }
  16631. } else {
  16632. media.src = objectUrl;
  16633. }
  16634. }
  16635. media.addEventListener("emptied", this._onMediaEmptied);
  16636. }
  16637. }
  16638. assignMediaSource(ms) {
  16639. var _this$transferData2, _ms$constructor;
  16640. this.log(`${((_this$transferData2 = this.transferData) == null ? void 0 : _this$transferData2.mediaSource) === ms ? "transferred" : "created"} media source: ${(_ms$constructor = ms.constructor) == null ? void 0 : _ms$constructor.name}`);
  16641. ms.addEventListener("sourceopen", this._onMediaSourceOpen);
  16642. ms.addEventListener("sourceended", this._onMediaSourceEnded);
  16643. ms.addEventListener("sourceclose", this._onMediaSourceClose);
  16644. if (this.appendSource) {
  16645. ms.addEventListener("startstreaming", this._onStartStreaming);
  16646. ms.addEventListener("endstreaming", this._onEndStreaming);
  16647. }
  16648. }
  16649. attachTransferred() {
  16650. const media = this.media;
  16651. const data = this.transferData;
  16652. if (!data || !media) {
  16653. return;
  16654. }
  16655. const requiredTracks = this.tracks;
  16656. const transferredTracks = data.tracks;
  16657. const trackNames = transferredTracks ? Object.keys(transferredTracks) : null;
  16658. const trackCount = trackNames ? trackNames.length : 0;
  16659. const mediaSourceOpenCallback = () => {
  16660. if (this.media && this.mediaSourceOpenOrEnded) {
  16661. this._onMediaSourceOpen();
  16662. }
  16663. };
  16664. if (transferredTracks && trackNames && trackCount) {
  16665. if (!this.tracksReady) {
  16666. this.hls.config.startFragPrefetch = true;
  16667. this.log(`attachTransferred: waiting for SourceBuffer track info`);
  16668. return;
  16669. }
  16670. this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
  16671. required tracks: ${stringify(requiredTracks, (key, value) => key === "initSegment" ? void 0 : value)};
  16672. transfer tracks: ${stringify(transferredTracks, (key, value) => key === "initSegment" ? void 0 : value)}}`);
  16673. if (!isCompatibleTrackChange(transferredTracks, requiredTracks)) {
  16674. data.mediaSource = null;
  16675. data.tracks = void 0;
  16676. const currentTime = media.currentTime;
  16677. const details = this.details;
  16678. const startTime = Math.max(currentTime, (details == null ? void 0 : details.fragments[0].start) || 0);
  16679. if (startTime - currentTime > 1) {
  16680. this.log(`attachTransferred: waiting for playback to reach new tracks start time ${currentTime} -> ${startTime}`);
  16681. return;
  16682. }
  16683. this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(transferredTracks)}"->"${Object.keys(requiredTracks)}") start time: ${startTime} currentTime: ${currentTime}`);
  16684. this.onMediaDetaching(Events.MEDIA_DETACHING, {});
  16685. this.onMediaAttaching(Events.MEDIA_ATTACHING, data);
  16686. media.currentTime = startTime;
  16687. return;
  16688. }
  16689. this.transferData = void 0;
  16690. trackNames.forEach((trackName) => {
  16691. const type = trackName;
  16692. const track = transferredTracks[type];
  16693. if (track) {
  16694. const sb = track.buffer;
  16695. if (sb) {
  16696. const fragmentTracker = this.fragmentTracker;
  16697. const playlistType = track.id;
  16698. if (fragmentTracker.hasFragments(playlistType) || fragmentTracker.hasParts(playlistType)) {
  16699. const bufferedTimeRanges = BufferHelper.getBuffered(sb);
  16700. fragmentTracker.detectEvictedFragments(type, bufferedTimeRanges, playlistType, null, true);
  16701. }
  16702. const sbIndex = sourceBufferNameToIndex(type);
  16703. const sbTuple = [type, sb];
  16704. this.sourceBuffers[sbIndex] = sbTuple;
  16705. if (sb.updating && this.operationQueue) {
  16706. this.operationQueue.prependBlocker(type);
  16707. }
  16708. this.trackSourceBuffer(type, track);
  16709. }
  16710. }
  16711. });
  16712. mediaSourceOpenCallback();
  16713. this.bufferCreated();
  16714. } else {
  16715. this.log(`attachTransferred: MediaSource w/o SourceBuffers`);
  16716. mediaSourceOpenCallback();
  16717. }
  16718. }
  16719. get mediaSourceOpenOrEnded() {
  16720. var _this$mediaSource2;
  16721. const readyState = (_this$mediaSource2 = this.mediaSource) == null ? void 0 : _this$mediaSource2.readyState;
  16722. return readyState === "open" || readyState === "ended";
  16723. }
  16724. onMediaDetaching(event, data) {
  16725. const transferringMedia = !!data.transferMedia;
  16726. this.transferData = this.overrides = void 0;
  16727. const {
  16728. media,
  16729. mediaSource,
  16730. _objectUrl
  16731. } = this;
  16732. if (mediaSource) {
  16733. this.log(`media source ${transferringMedia ? "transferring" : "detaching"}`);
  16734. if (transferringMedia) {
  16735. this.sourceBuffers.forEach(([type]) => {
  16736. if (type) {
  16737. this.removeBuffer(type);
  16738. }
  16739. });
  16740. this.resetQueue();
  16741. } else {
  16742. if (this.mediaSourceOpenOrEnded) {
  16743. const open = mediaSource.readyState === "open";
  16744. try {
  16745. const sourceBuffers = mediaSource.sourceBuffers;
  16746. for (let i = sourceBuffers.length; i--; ) {
  16747. if (open) {
  16748. sourceBuffers[i].abort();
  16749. }
  16750. mediaSource.removeSourceBuffer(sourceBuffers[i]);
  16751. }
  16752. if (open) {
  16753. mediaSource.endOfStream();
  16754. }
  16755. } catch (err) {
  16756. this.warn(`onMediaDetaching: ${err.message} while calling endOfStream`);
  16757. }
  16758. }
  16759. if (this.sourceBufferCount) {
  16760. this.onBufferReset();
  16761. }
  16762. }
  16763. mediaSource.removeEventListener("sourceopen", this._onMediaSourceOpen);
  16764. mediaSource.removeEventListener("sourceended", this._onMediaSourceEnded);
  16765. mediaSource.removeEventListener("sourceclose", this._onMediaSourceClose);
  16766. if (this.appendSource) {
  16767. mediaSource.removeEventListener("startstreaming", this._onStartStreaming);
  16768. mediaSource.removeEventListener("endstreaming", this._onEndStreaming);
  16769. }
  16770. this.mediaSource = null;
  16771. this._objectUrl = null;
  16772. }
  16773. if (media) {
  16774. media.removeEventListener("emptied", this._onMediaEmptied);
  16775. if (!transferringMedia) {
  16776. if (_objectUrl) {
  16777. self.URL.revokeObjectURL(_objectUrl);
  16778. }
  16779. if (this.mediaSrc === _objectUrl) {
  16780. media.removeAttribute("src");
  16781. if (this.appendSource) {
  16782. removeSourceChildren(media);
  16783. }
  16784. media.load();
  16785. } else {
  16786. this.warn("media|source.src was changed by a third party - skip cleanup");
  16787. }
  16788. }
  16789. this.media = null;
  16790. }
  16791. this.hls.trigger(Events.MEDIA_DETACHED, data);
  16792. }
  16793. onBufferReset() {
  16794. this.sourceBuffers.forEach(([type]) => {
  16795. if (type) {
  16796. this.resetBuffer(type);
  16797. }
  16798. });
  16799. this.initTracks();
  16800. }
  16801. resetBuffer(type) {
  16802. var _this$tracks$type;
  16803. const sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  16804. this.removeBuffer(type);
  16805. if (sb) {
  16806. try {
  16807. var _this$mediaSource3;
  16808. if ((_this$mediaSource3 = this.mediaSource) != null && _this$mediaSource3.sourceBuffers.length) {
  16809. this.mediaSource.removeSourceBuffer(sb);
  16810. }
  16811. } catch (err) {
  16812. this.warn(`onBufferReset ${type}`, err);
  16813. }
  16814. }
  16815. delete this.tracks[type];
  16816. }
  16817. removeBuffer(type) {
  16818. this.removeBufferListeners(type);
  16819. this.sourceBuffers[sourceBufferNameToIndex(type)] = [null, null];
  16820. const track = this.tracks[type];
  16821. if (track) {
  16822. track.buffer = void 0;
  16823. }
  16824. }
  16825. resetQueue() {
  16826. if (this.operationQueue) {
  16827. this.operationQueue.destroy();
  16828. }
  16829. this.operationQueue = new BufferOperationQueue(this.tracks);
  16830. }
  16831. onBufferCodecs(event, data) {
  16832. const tracks = this.tracks;
  16833. const trackNames = Object.keys(data);
  16834. this.log(`BUFFER_CODECS: "${trackNames}" (current SB count ${this.sourceBufferCount})`);
  16835. const unmuxedToMuxed = "audiovideo" in data && (tracks.audio || tracks.video) || tracks.audiovideo && ("audio" in data || "video" in data);
  16836. const muxedToUnmuxed = !unmuxedToMuxed && this.sourceBufferCount && this.media && trackNames.some((sbName) => !tracks[sbName]);
  16837. if (unmuxedToMuxed || muxedToUnmuxed) {
  16838. this.warn(`Unsupported transition between "${Object.keys(tracks)}" and "${trackNames}" SourceBuffers`);
  16839. return;
  16840. }
  16841. trackNames.forEach((trackName) => {
  16842. var _this$transferData3, _this$transferData3$t, _trackCodec;
  16843. const parsedTrack = data[trackName];
  16844. const {
  16845. id,
  16846. codec,
  16847. levelCodec,
  16848. container,
  16849. metadata,
  16850. supplemental
  16851. } = parsedTrack;
  16852. let track = tracks[trackName];
  16853. const transferredTrack = (_this$transferData3 = this.transferData) == null ? void 0 : (_this$transferData3$t = _this$transferData3.tracks) == null ? void 0 : _this$transferData3$t[trackName];
  16854. const sbTrack = transferredTrack != null && transferredTrack.buffer ? transferredTrack : track;
  16855. const sbCodec = (sbTrack == null ? void 0 : sbTrack.pendingCodec) || (sbTrack == null ? void 0 : sbTrack.codec);
  16856. const trackLevelCodec = sbTrack == null ? void 0 : sbTrack.levelCodec;
  16857. if (!track) {
  16858. track = tracks[trackName] = {
  16859. buffer: void 0,
  16860. listeners: [],
  16861. codec,
  16862. supplemental,
  16863. container,
  16864. levelCodec,
  16865. metadata,
  16866. id
  16867. };
  16868. }
  16869. const currentCodecFull = pickMostCompleteCodecName(sbCodec, trackLevelCodec);
  16870. const currentCodec = currentCodecFull == null ? void 0 : currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE, "$1");
  16871. let trackCodec = pickMostCompleteCodecName(codec, levelCodec);
  16872. const nextCodec = (_trackCodec = trackCodec) == null ? void 0 : _trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE, "$1");
  16873. if (trackCodec && currentCodecFull && currentCodec !== nextCodec) {
  16874. if (trackName.slice(0, 5) === "audio") {
  16875. trackCodec = getCodecCompatibleName(trackCodec, this.appendSource);
  16876. }
  16877. this.log(`switching codec ${sbCodec} to ${trackCodec}`);
  16878. if (trackCodec !== (track.pendingCodec || track.codec)) {
  16879. track.pendingCodec = trackCodec;
  16880. }
  16881. track.container = container;
  16882. this.appendChangeType(trackName, container, trackCodec);
  16883. }
  16884. });
  16885. if (this.tracksReady || this.sourceBufferCount) {
  16886. data.tracks = this.sourceBufferTracks;
  16887. }
  16888. if (this.sourceBufferCount) {
  16889. return;
  16890. }
  16891. if (this.mediaSourceOpenOrEnded) {
  16892. this.checkPendingTracks();
  16893. }
  16894. }
  16895. get sourceBufferTracks() {
  16896. return Object.keys(this.tracks).reduce((baseTracks, type) => {
  16897. const track = this.tracks[type];
  16898. baseTracks[type] = {
  16899. id: track.id,
  16900. container: track.container,
  16901. codec: track.codec,
  16902. levelCodec: track.levelCodec
  16903. };
  16904. return baseTracks;
  16905. }, {});
  16906. }
  16907. appendChangeType(type, container, codec) {
  16908. const mimeType = `${container};codecs=${codec}`;
  16909. const operation = {
  16910. label: `change-type=${mimeType}`,
  16911. execute: () => {
  16912. const track = this.tracks[type];
  16913. if (track) {
  16914. const sb = track.buffer;
  16915. if (sb != null && sb.changeType) {
  16916. this.log(`changing ${type} sourceBuffer type to ${mimeType}`);
  16917. sb.changeType(mimeType);
  16918. track.codec = codec;
  16919. track.container = container;
  16920. }
  16921. }
  16922. this.shiftAndExecuteNext(type);
  16923. },
  16924. onStart: () => {
  16925. },
  16926. onComplete: () => {
  16927. },
  16928. onError: (error) => {
  16929. this.warn(`Failed to change ${type} SourceBuffer type`, error);
  16930. }
  16931. };
  16932. this.append(operation, type, this.isPending(this.tracks[type]));
  16933. }
  16934. blockAudio(partOrFrag) {
  16935. var _this$fragmentTracker;
  16936. const pStart = partOrFrag.start;
  16937. const pTime = pStart + partOrFrag.duration * 0.05;
  16938. const atGap = ((_this$fragmentTracker = this.fragmentTracker.getAppendedFrag(pStart, PlaylistLevelType.MAIN)) == null ? void 0 : _this$fragmentTracker.gap) === true;
  16939. if (atGap) {
  16940. return;
  16941. }
  16942. const op = {
  16943. label: "block-audio",
  16944. execute: () => {
  16945. var _this$fragmentTracker2;
  16946. const videoTrack = this.tracks.video;
  16947. if (this.lastVideoAppendEnd > pTime || videoTrack != null && videoTrack.buffer && BufferHelper.isBuffered(videoTrack.buffer, pTime) || ((_this$fragmentTracker2 = this.fragmentTracker.getAppendedFrag(pTime, PlaylistLevelType.MAIN)) == null ? void 0 : _this$fragmentTracker2.gap) === true) {
  16948. this.blockedAudioAppend = null;
  16949. this.shiftAndExecuteNext("audio");
  16950. }
  16951. },
  16952. onStart: () => {
  16953. },
  16954. onComplete: () => {
  16955. },
  16956. onError: (error) => {
  16957. this.warn("Error executing block-audio operation", error);
  16958. }
  16959. };
  16960. this.blockedAudioAppend = {
  16961. op,
  16962. frag: partOrFrag
  16963. };
  16964. this.append(op, "audio", true);
  16965. }
  16966. unblockAudio() {
  16967. const {
  16968. blockedAudioAppend,
  16969. operationQueue
  16970. } = this;
  16971. if (blockedAudioAppend && operationQueue) {
  16972. this.blockedAudioAppend = null;
  16973. operationQueue.unblockAudio(blockedAudioAppend.op);
  16974. }
  16975. }
  16976. onBufferAppending(event, eventData) {
  16977. const {
  16978. tracks
  16979. } = this;
  16980. const {
  16981. data,
  16982. type,
  16983. parent,
  16984. frag,
  16985. part,
  16986. chunkMeta,
  16987. offset
  16988. } = eventData;
  16989. const chunkStats = chunkMeta.buffering[type];
  16990. const {
  16991. sn,
  16992. cc
  16993. } = frag;
  16994. const bufferAppendingStart = self.performance.now();
  16995. chunkStats.start = bufferAppendingStart;
  16996. const fragBuffering = frag.stats.buffering;
  16997. const partBuffering = part ? part.stats.buffering : null;
  16998. if (fragBuffering.start === 0) {
  16999. fragBuffering.start = bufferAppendingStart;
  17000. }
  17001. if (partBuffering && partBuffering.start === 0) {
  17002. partBuffering.start = bufferAppendingStart;
  17003. }
  17004. const audioTrack = tracks.audio;
  17005. let checkTimestampOffset = false;
  17006. if (type === "audio" && (audioTrack == null ? void 0 : audioTrack.container) === "audio/mpeg") {
  17007. checkTimestampOffset = !this.lastMpegAudioChunk || chunkMeta.id === 1 || this.lastMpegAudioChunk.sn !== chunkMeta.sn;
  17008. this.lastMpegAudioChunk = chunkMeta;
  17009. }
  17010. const videoTrack = tracks.video;
  17011. const videoSb = videoTrack == null ? void 0 : videoTrack.buffer;
  17012. if (videoSb && sn !== "initSegment") {
  17013. const partOrFrag = part || frag;
  17014. const blockedAudioAppend = this.blockedAudioAppend;
  17015. if (type === "audio" && parent !== "main" && !this.blockedAudioAppend) {
  17016. const pStart = partOrFrag.start;
  17017. const pTime = pStart + partOrFrag.duration * 0.05;
  17018. const vbuffered = videoSb.buffered;
  17019. const vappending = this.currentOp("video");
  17020. if (!vbuffered.length && !vappending) {
  17021. this.blockAudio(partOrFrag);
  17022. } else if (!vappending && !BufferHelper.isBuffered(videoSb, pTime) && this.lastVideoAppendEnd < pTime) {
  17023. this.blockAudio(partOrFrag);
  17024. }
  17025. } else if (type === "video") {
  17026. const videoAppendEnd = partOrFrag.end;
  17027. if (blockedAudioAppend) {
  17028. const audioStart = blockedAudioAppend.frag.start;
  17029. if (videoAppendEnd > audioStart || videoAppendEnd < this.lastVideoAppendEnd || BufferHelper.isBuffered(videoSb, audioStart)) {
  17030. this.unblockAudio();
  17031. }
  17032. }
  17033. this.lastVideoAppendEnd = videoAppendEnd;
  17034. }
  17035. }
  17036. const fragStart = (part || frag).start;
  17037. const operation = {
  17038. label: `append-${type}`,
  17039. execute: () => {
  17040. var _this$tracks$type2;
  17041. chunkStats.executeStart = self.performance.now();
  17042. const sb = (_this$tracks$type2 = this.tracks[type]) == null ? void 0 : _this$tracks$type2.buffer;
  17043. if (sb) {
  17044. if (checkTimestampOffset) {
  17045. this.updateTimestampOffset(sb, fragStart, 0.1, type, sn, cc);
  17046. } else if (offset !== void 0 && isFiniteNumber(offset)) {
  17047. this.updateTimestampOffset(sb, offset, 1e-6, type, sn, cc);
  17048. }
  17049. }
  17050. this.appendExecutor(data, type);
  17051. },
  17052. onStart: () => {
  17053. },
  17054. onComplete: () => {
  17055. const end = self.performance.now();
  17056. chunkStats.executeEnd = chunkStats.end = end;
  17057. if (fragBuffering.first === 0) {
  17058. fragBuffering.first = end;
  17059. }
  17060. if (partBuffering && partBuffering.first === 0) {
  17061. partBuffering.first = end;
  17062. }
  17063. const timeRanges = {};
  17064. this.sourceBuffers.forEach(([type2, sb]) => {
  17065. if (type2) {
  17066. timeRanges[type2] = BufferHelper.getBuffered(sb);
  17067. }
  17068. });
  17069. this.appendErrors[type] = 0;
  17070. if (type === "audio" || type === "video") {
  17071. this.appendErrors.audiovideo = 0;
  17072. } else {
  17073. this.appendErrors.audio = 0;
  17074. this.appendErrors.video = 0;
  17075. }
  17076. this.hls.trigger(Events.BUFFER_APPENDED, {
  17077. type,
  17078. frag,
  17079. part,
  17080. chunkMeta,
  17081. parent: frag.type,
  17082. timeRanges
  17083. });
  17084. },
  17085. onError: (error) => {
  17086. var _this$media;
  17087. const event2 = {
  17088. type: ErrorTypes.MEDIA_ERROR,
  17089. parent: frag.type,
  17090. details: ErrorDetails.BUFFER_APPEND_ERROR,
  17091. sourceBufferName: type,
  17092. frag,
  17093. part,
  17094. chunkMeta,
  17095. error,
  17096. err: error,
  17097. fatal: false
  17098. };
  17099. const mediaError = (_this$media = this.media) == null ? void 0 : _this$media.error;
  17100. if (error.code === DOMException.QUOTA_EXCEEDED_ERR || error.name == "QuotaExceededError" || `quota` in error) {
  17101. event2.details = ErrorDetails.BUFFER_FULL_ERROR;
  17102. } else if (error.code === DOMException.INVALID_STATE_ERR && this.mediaSourceOpenOrEnded && !mediaError) {
  17103. event2.errorAction = createDoNothingErrorAction(true);
  17104. } else if (error.name === TRACK_REMOVED_ERROR_NAME && this.sourceBufferCount === 0) {
  17105. event2.errorAction = createDoNothingErrorAction(true);
  17106. } else {
  17107. const appendErrorCount = ++this.appendErrors[type];
  17108. this.warn(`Failed ${appendErrorCount}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${type}" sourceBuffer (${mediaError ? mediaError : "no media error"})`);
  17109. if (appendErrorCount >= this.hls.config.appendErrorMaxRetry || !!mediaError) {
  17110. event2.fatal = true;
  17111. }
  17112. }
  17113. this.hls.trigger(Events.ERROR, event2);
  17114. }
  17115. };
  17116. this.append(operation, type, this.isPending(this.tracks[type]));
  17117. }
  17118. getFlushOp(type, start, end) {
  17119. this.log(`queuing "${type}" remove ${start}-${end}`);
  17120. return {
  17121. label: "remove",
  17122. execute: () => {
  17123. this.removeExecutor(type, start, end);
  17124. },
  17125. onStart: () => {
  17126. },
  17127. onComplete: () => {
  17128. this.hls.trigger(Events.BUFFER_FLUSHED, {
  17129. type
  17130. });
  17131. },
  17132. onError: (error) => {
  17133. this.warn(`Failed to remove ${start}-${end} from "${type}" SourceBuffer`, error);
  17134. }
  17135. };
  17136. }
  17137. onBufferFlushing(event, data) {
  17138. const {
  17139. type,
  17140. startOffset,
  17141. endOffset
  17142. } = data;
  17143. if (type) {
  17144. this.append(this.getFlushOp(type, startOffset, endOffset), type);
  17145. } else {
  17146. this.sourceBuffers.forEach(([type2]) => {
  17147. if (type2) {
  17148. this.append(this.getFlushOp(type2, startOffset, endOffset), type2);
  17149. }
  17150. });
  17151. }
  17152. }
  17153. onFragParsed(event, data) {
  17154. const {
  17155. frag,
  17156. part
  17157. } = data;
  17158. const buffersAppendedTo = [];
  17159. const elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
  17160. if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {
  17161. buffersAppendedTo.push("audiovideo");
  17162. } else {
  17163. if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {
  17164. buffersAppendedTo.push("audio");
  17165. }
  17166. if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {
  17167. buffersAppendedTo.push("video");
  17168. }
  17169. }
  17170. const onUnblocked = () => {
  17171. const now2 = self.performance.now();
  17172. frag.stats.buffering.end = now2;
  17173. if (part) {
  17174. part.stats.buffering.end = now2;
  17175. }
  17176. const stats = part ? part.stats : frag.stats;
  17177. this.hls.trigger(Events.FRAG_BUFFERED, {
  17178. frag,
  17179. part,
  17180. stats,
  17181. id: frag.type
  17182. });
  17183. };
  17184. if (buffersAppendedTo.length === 0) {
  17185. this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${frag.type} level: ${frag.level} sn: ${frag.sn}`);
  17186. }
  17187. this.blockBuffers(onUnblocked, buffersAppendedTo).catch((error) => {
  17188. this.warn(`Fragment buffered callback ${error}`);
  17189. this.stepOperationQueue(this.sourceBufferTypes);
  17190. });
  17191. }
  17192. onFragChanged(event, data) {
  17193. this.trimBuffers();
  17194. }
  17195. get bufferedToEnd() {
  17196. return this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type]) => {
  17197. var _this$tracks$type3, _this$tracks$type4;
  17198. return type && (!((_this$tracks$type3 = this.tracks[type]) != null && _this$tracks$type3.ended) || ((_this$tracks$type4 = this.tracks[type]) == null ? void 0 : _this$tracks$type4.ending));
  17199. });
  17200. }
  17201. // on BUFFER_EOS mark matching sourcebuffer(s) as "ending" and "ended" and queue endOfStream after remaining operations(s)
  17202. // an undefined data.type will mark all buffers as EOS.
  17203. onBufferEos(event, data) {
  17204. var _this$overrides;
  17205. this.sourceBuffers.forEach(([type]) => {
  17206. if (type) {
  17207. const track = this.tracks[type];
  17208. if (!data.type || data.type === type) {
  17209. track.ending = true;
  17210. if (!track.ended) {
  17211. track.ended = true;
  17212. this.log(`${type} buffer reached EOS`);
  17213. }
  17214. }
  17215. }
  17216. });
  17217. const allowEndOfStream = ((_this$overrides = this.overrides) == null ? void 0 : _this$overrides.endOfStream) !== false;
  17218. const allTracksEnding = this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type]) => {
  17219. var _this$tracks$type5;
  17220. return type && !((_this$tracks$type5 = this.tracks[type]) != null && _this$tracks$type5.ended);
  17221. });
  17222. if (allTracksEnding) {
  17223. if (allowEndOfStream) {
  17224. this.log(`Queueing EOS`);
  17225. this.blockUntilOpen(() => {
  17226. this.tracksEnded();
  17227. const {
  17228. mediaSource
  17229. } = this;
  17230. if (!mediaSource || mediaSource.readyState !== "open") {
  17231. if (mediaSource) {
  17232. this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${mediaSource.readyState}`);
  17233. }
  17234. return;
  17235. }
  17236. this.log(`Calling mediaSource.endOfStream()`);
  17237. mediaSource.endOfStream();
  17238. this.hls.trigger(Events.BUFFERED_TO_END, void 0);
  17239. });
  17240. } else {
  17241. this.tracksEnded();
  17242. this.hls.trigger(Events.BUFFERED_TO_END, void 0);
  17243. }
  17244. }
  17245. }
  17246. tracksEnded() {
  17247. this.sourceBuffers.forEach(([type]) => {
  17248. if (type !== null) {
  17249. const track = this.tracks[type];
  17250. if (track) {
  17251. track.ending = false;
  17252. }
  17253. }
  17254. });
  17255. }
  17256. onLevelUpdated(event, {
  17257. details
  17258. }) {
  17259. if (!details.fragments.length) {
  17260. return;
  17261. }
  17262. this.details = details;
  17263. this.updateDuration();
  17264. }
  17265. updateDuration() {
  17266. this.blockUntilOpen(() => {
  17267. const durationAndRange = this.getDurationAndRange();
  17268. if (!durationAndRange) {
  17269. return;
  17270. }
  17271. this.updateMediaSource(durationAndRange);
  17272. });
  17273. }
  17274. onError(event, data) {
  17275. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && data.frag) {
  17276. var _data$errorAction;
  17277. const nextAutoLevel = (_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.nextAutoLevel;
  17278. if (isFiniteNumber(nextAutoLevel) && nextAutoLevel !== data.frag.level) {
  17279. this.resetAppendErrors();
  17280. }
  17281. }
  17282. }
  17283. resetAppendErrors() {
  17284. this.appendErrors = {
  17285. audio: 0,
  17286. video: 0,
  17287. audiovideo: 0
  17288. };
  17289. }
  17290. trimBuffers() {
  17291. const {
  17292. hls,
  17293. details,
  17294. media
  17295. } = this;
  17296. if (!media || details === null) {
  17297. return;
  17298. }
  17299. if (!this.sourceBufferCount) {
  17300. return;
  17301. }
  17302. const config = hls.config;
  17303. const currentTime = media.currentTime;
  17304. const targetDuration = details.levelTargetDuration;
  17305. const backBufferLength = details.live && config.liveBackBufferLength !== null ? config.liveBackBufferLength : config.backBufferLength;
  17306. if (isFiniteNumber(backBufferLength) && backBufferLength >= 0) {
  17307. const maxBackBufferLength = Math.max(backBufferLength, targetDuration);
  17308. const targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
  17309. this.flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition);
  17310. }
  17311. if (isFiniteNumber(config.frontBufferFlushThreshold) && config.frontBufferFlushThreshold > 0) {
  17312. const frontBufferLength = Math.max(config.maxBufferLength, config.frontBufferFlushThreshold);
  17313. const maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);
  17314. const targetFrontBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration + maxFrontBufferLength;
  17315. this.flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition);
  17316. }
  17317. }
  17318. flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition) {
  17319. this.sourceBuffers.forEach(([type, sb]) => {
  17320. if (sb) {
  17321. const buffered = BufferHelper.getBuffered(sb);
  17322. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  17323. var _this$details;
  17324. this.hls.trigger(Events.BACK_BUFFER_REACHED, {
  17325. bufferEnd: targetBackBufferPosition
  17326. });
  17327. const track = this.tracks[type];
  17328. if ((_this$details = this.details) != null && _this$details.live) {
  17329. this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {
  17330. bufferEnd: targetBackBufferPosition
  17331. });
  17332. } else if (track != null && track.ended) {
  17333. this.log(`Cannot flush ${type} back buffer while SourceBuffer is in ended state`);
  17334. return;
  17335. }
  17336. this.hls.trigger(Events.BUFFER_FLUSHING, {
  17337. startOffset: 0,
  17338. endOffset: targetBackBufferPosition,
  17339. type
  17340. });
  17341. }
  17342. }
  17343. });
  17344. }
  17345. flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition) {
  17346. this.sourceBuffers.forEach(([type, sb]) => {
  17347. if (sb) {
  17348. const buffered = BufferHelper.getBuffered(sb);
  17349. const numBufferedRanges = buffered.length;
  17350. if (numBufferedRanges < 2) {
  17351. return;
  17352. }
  17353. const bufferStart = buffered.start(numBufferedRanges - 1);
  17354. const bufferEnd = buffered.end(numBufferedRanges - 1);
  17355. if (targetFrontBufferPosition > bufferStart || currentTime >= bufferStart && currentTime <= bufferEnd) {
  17356. return;
  17357. }
  17358. this.hls.trigger(Events.BUFFER_FLUSHING, {
  17359. startOffset: bufferStart,
  17360. endOffset: Infinity,
  17361. type
  17362. });
  17363. }
  17364. });
  17365. }
  17366. /**
  17367. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  17368. * 'liveDurationInfinity` is set to `true`
  17369. * More details: https://github.com/video-dev/hls.js/issues/355
  17370. */
  17371. getDurationAndRange() {
  17372. var _this$overrides2;
  17373. const {
  17374. details,
  17375. mediaSource
  17376. } = this;
  17377. if (!details || !this.media || (mediaSource == null ? void 0 : mediaSource.readyState) !== "open") {
  17378. return null;
  17379. }
  17380. const playlistEnd = details.edge;
  17381. if (details.live && this.hls.config.liveDurationInfinity) {
  17382. const len = details.fragments.length;
  17383. if (len && details.live && !!mediaSource.setLiveSeekableRange) {
  17384. const start = Math.max(0, details.fragmentStart);
  17385. const end = Math.max(start, playlistEnd);
  17386. return {
  17387. duration: Infinity,
  17388. start,
  17389. end
  17390. };
  17391. }
  17392. return {
  17393. duration: Infinity
  17394. };
  17395. }
  17396. const overrideDuration = (_this$overrides2 = this.overrides) == null ? void 0 : _this$overrides2.duration;
  17397. if (overrideDuration) {
  17398. if (!isFiniteNumber(overrideDuration)) {
  17399. return null;
  17400. }
  17401. return {
  17402. duration: overrideDuration
  17403. };
  17404. }
  17405. const mediaDuration = this.media.duration;
  17406. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : 0;
  17407. if (playlistEnd > msDuration && playlistEnd > mediaDuration || !isFiniteNumber(mediaDuration)) {
  17408. return {
  17409. duration: playlistEnd
  17410. };
  17411. }
  17412. return null;
  17413. }
  17414. updateMediaSource({
  17415. duration,
  17416. start,
  17417. end
  17418. }) {
  17419. const mediaSource = this.mediaSource;
  17420. if (!this.media || !mediaSource || mediaSource.readyState !== "open") {
  17421. return;
  17422. }
  17423. if (mediaSource.duration !== duration) {
  17424. if (isFiniteNumber(duration)) {
  17425. this.log(`Updating MediaSource duration to ${duration.toFixed(3)}`);
  17426. }
  17427. mediaSource.duration = duration;
  17428. }
  17429. if (start !== void 0 && end !== void 0) {
  17430. this.log(`MediaSource duration is set to ${mediaSource.duration}. Setting seekable range to ${start}-${end}.`);
  17431. mediaSource.setLiveSeekableRange(start, end);
  17432. }
  17433. }
  17434. get tracksReady() {
  17435. const pendingTrackCount = this.pendingTrackCount;
  17436. return pendingTrackCount > 0 && (pendingTrackCount >= this.bufferCodecEventsTotal || this.isPending(this.tracks.audiovideo));
  17437. }
  17438. checkPendingTracks() {
  17439. const {
  17440. bufferCodecEventsTotal,
  17441. pendingTrackCount,
  17442. tracks
  17443. } = this;
  17444. this.log(`checkPendingTracks (pending: ${pendingTrackCount} codec events expected: ${bufferCodecEventsTotal}) ${stringify(tracks)}`);
  17445. if (this.tracksReady) {
  17446. var _this$transferData4;
  17447. const transferredTracks = (_this$transferData4 = this.transferData) == null ? void 0 : _this$transferData4.tracks;
  17448. if (transferredTracks && Object.keys(transferredTracks).length) {
  17449. this.attachTransferred();
  17450. } else {
  17451. this.createSourceBuffers();
  17452. }
  17453. }
  17454. }
  17455. bufferCreated() {
  17456. if (this.sourceBufferCount) {
  17457. const tracks = {};
  17458. this.sourceBuffers.forEach(([type, buffer]) => {
  17459. if (type) {
  17460. const track = this.tracks[type];
  17461. tracks[type] = {
  17462. buffer,
  17463. container: track.container,
  17464. codec: track.codec,
  17465. supplemental: track.supplemental,
  17466. levelCodec: track.levelCodec,
  17467. id: track.id,
  17468. metadata: track.metadata
  17469. };
  17470. }
  17471. });
  17472. this.hls.trigger(Events.BUFFER_CREATED, {
  17473. tracks
  17474. });
  17475. this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`);
  17476. this.sourceBuffers.forEach(([type]) => {
  17477. this.executeNext(type);
  17478. });
  17479. } else {
  17480. const error = new Error("could not create source buffer for media codec(s)");
  17481. this.hls.trigger(Events.ERROR, {
  17482. type: ErrorTypes.MEDIA_ERROR,
  17483. details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,
  17484. fatal: true,
  17485. error,
  17486. reason: error.message
  17487. });
  17488. }
  17489. }
  17490. createSourceBuffers() {
  17491. const {
  17492. tracks,
  17493. sourceBuffers,
  17494. mediaSource
  17495. } = this;
  17496. if (!mediaSource) {
  17497. throw new Error("createSourceBuffers called when mediaSource was null");
  17498. }
  17499. for (const trackName in tracks) {
  17500. const type = trackName;
  17501. const track = tracks[type];
  17502. if (this.isPending(track)) {
  17503. const codec = this.getTrackCodec(track, type);
  17504. const mimeType = `${track.container};codecs=${codec}`;
  17505. track.codec = codec;
  17506. this.log(`creating sourceBuffer(${mimeType})${this.currentOp(type) ? " Queued" : ""} ${stringify(track)}`);
  17507. try {
  17508. const sb = mediaSource.addSourceBuffer(mimeType);
  17509. const sbIndex = sourceBufferNameToIndex(type);
  17510. const sbTuple = [type, sb];
  17511. sourceBuffers[sbIndex] = sbTuple;
  17512. track.buffer = sb;
  17513. } catch (error) {
  17514. var _this$operationQueue;
  17515. this.error(`error while trying to add sourceBuffer: ${error.message}`);
  17516. this.shiftAndExecuteNext(type);
  17517. (_this$operationQueue = this.operationQueue) == null ? void 0 : _this$operationQueue.removeBlockers();
  17518. delete this.tracks[type];
  17519. this.hls.trigger(Events.ERROR, {
  17520. type: ErrorTypes.MEDIA_ERROR,
  17521. details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,
  17522. fatal: false,
  17523. error,
  17524. sourceBufferName: type,
  17525. mimeType,
  17526. parent: track.id
  17527. });
  17528. return;
  17529. }
  17530. this.trackSourceBuffer(type, track);
  17531. }
  17532. }
  17533. this.bufferCreated();
  17534. }
  17535. getTrackCodec(track, trackName) {
  17536. const supplementalCodec = track.supplemental;
  17537. let trackCodec = track.codec;
  17538. if (supplementalCodec && (trackName === "video" || trackName === "audiovideo") && areCodecsMediaSourceSupported(supplementalCodec, "video")) {
  17539. trackCodec = replaceVideoCodec(trackCodec, supplementalCodec);
  17540. }
  17541. const codec = pickMostCompleteCodecName(trackCodec, track.levelCodec);
  17542. if (codec) {
  17543. if (trackName.slice(0, 5) === "audio") {
  17544. return getCodecCompatibleName(codec, this.appendSource);
  17545. }
  17546. return codec;
  17547. }
  17548. return "";
  17549. }
  17550. trackSourceBuffer(type, track) {
  17551. const buffer = track.buffer;
  17552. if (!buffer) {
  17553. return;
  17554. }
  17555. const codec = this.getTrackCodec(track, type);
  17556. this.tracks[type] = {
  17557. buffer,
  17558. codec,
  17559. container: track.container,
  17560. levelCodec: track.levelCodec,
  17561. supplemental: track.supplemental,
  17562. metadata: track.metadata,
  17563. id: track.id,
  17564. listeners: []
  17565. };
  17566. this.removeBufferListeners(type);
  17567. this.addBufferListener(type, "updatestart", this.onSBUpdateStart);
  17568. this.addBufferListener(type, "updateend", this.onSBUpdateEnd);
  17569. this.addBufferListener(type, "error", this.onSBUpdateError);
  17570. if (this.appendSource) {
  17571. this.addBufferListener(type, "bufferedchange", (type2, event) => {
  17572. const removedRanges = event.removedRanges;
  17573. if (removedRanges != null && removedRanges.length) {
  17574. this.hls.trigger(Events.BUFFER_FLUSHED, {
  17575. type: type2
  17576. });
  17577. }
  17578. });
  17579. }
  17580. }
  17581. get mediaSrc() {
  17582. var _this$media2, _this$media2$querySel;
  17583. const media = ((_this$media2 = this.media) == null ? void 0 : (_this$media2$querySel = _this$media2.querySelector) == null ? void 0 : _this$media2$querySel.call(_this$media2, "source")) || this.media;
  17584. return media == null ? void 0 : media.src;
  17585. }
  17586. onSBUpdateStart(type) {
  17587. const operation = this.currentOp(type);
  17588. if (!operation) {
  17589. return;
  17590. }
  17591. operation.onStart();
  17592. }
  17593. onSBUpdateEnd(type) {
  17594. var _this$mediaSource4;
  17595. if (((_this$mediaSource4 = this.mediaSource) == null ? void 0 : _this$mediaSource4.readyState) === "closed") {
  17596. this.resetBuffer(type);
  17597. return;
  17598. }
  17599. const operation = this.currentOp(type);
  17600. if (!operation) {
  17601. return;
  17602. }
  17603. operation.onComplete();
  17604. this.shiftAndExecuteNext(type);
  17605. }
  17606. onSBUpdateError(type, event) {
  17607. var _this$mediaSource5;
  17608. const error = new Error(`${type} SourceBuffer error. MediaSource readyState: ${(_this$mediaSource5 = this.mediaSource) == null ? void 0 : _this$mediaSource5.readyState}`);
  17609. this.error(`${error}`, event);
  17610. this.hls.trigger(Events.ERROR, {
  17611. type: ErrorTypes.MEDIA_ERROR,
  17612. details: ErrorDetails.BUFFER_APPENDING_ERROR,
  17613. sourceBufferName: type,
  17614. error,
  17615. fatal: false
  17616. });
  17617. const operation = this.currentOp(type);
  17618. if (operation) {
  17619. operation.onError(error);
  17620. }
  17621. }
  17622. updateTimestampOffset(sb, timestampOffset, tolerance, type, sn, cc) {
  17623. const delta = timestampOffset - sb.timestampOffset;
  17624. if (Math.abs(delta) >= tolerance) {
  17625. this.log(`Updating ${type} SourceBuffer timestampOffset to ${timestampOffset} (sn: ${sn} cc: ${cc})`);
  17626. sb.timestampOffset = timestampOffset;
  17627. }
  17628. }
  17629. // This method must result in an updateend event; if remove is not called, onSBUpdateEnd must be called manually
  17630. removeExecutor(type, startOffset, endOffset) {
  17631. const {
  17632. media,
  17633. mediaSource
  17634. } = this;
  17635. const track = this.tracks[type];
  17636. const sb = track == null ? void 0 : track.buffer;
  17637. if (!media || !mediaSource || !sb) {
  17638. this.warn(`Attempting to remove from the ${type} SourceBuffer, but it does not exist`);
  17639. this.shiftAndExecuteNext(type);
  17640. return;
  17641. }
  17642. const mediaDuration = isFiniteNumber(media.duration) ? media.duration : Infinity;
  17643. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : Infinity;
  17644. const removeStart = Math.max(0, startOffset);
  17645. const removeEnd = Math.min(endOffset, mediaDuration, msDuration);
  17646. if (removeEnd > removeStart && (!track.ending || track.ended)) {
  17647. track.ended = false;
  17648. this.log(`Removing [${removeStart},${removeEnd}] from the ${type} SourceBuffer`);
  17649. sb.remove(removeStart, removeEnd);
  17650. } else {
  17651. this.shiftAndExecuteNext(type);
  17652. }
  17653. }
  17654. // This method must result in an updateend event; if append is not called, onSBUpdateEnd must be called manually
  17655. appendExecutor(data, type) {
  17656. const track = this.tracks[type];
  17657. const sb = track == null ? void 0 : track.buffer;
  17658. if (!sb) {
  17659. throw new HlsJsTrackRemovedError(`Attempting to append to the ${type} SourceBuffer, but it does not exist`);
  17660. }
  17661. track.ending = false;
  17662. track.ended = false;
  17663. sb.appendBuffer(data);
  17664. }
  17665. blockUntilOpen(callback) {
  17666. if (this.isUpdating() || this.isQueued()) {
  17667. this.blockBuffers(callback).catch((error) => {
  17668. this.warn(`SourceBuffer blocked callback ${error}`);
  17669. this.stepOperationQueue(this.sourceBufferTypes);
  17670. });
  17671. } else {
  17672. try {
  17673. callback();
  17674. } catch (error) {
  17675. this.warn(`Callback run without blocking ${this.operationQueue} ${error}`);
  17676. }
  17677. }
  17678. }
  17679. isUpdating() {
  17680. return this.sourceBuffers.some(([type, sb]) => type && sb.updating);
  17681. }
  17682. isQueued() {
  17683. return this.sourceBuffers.some(([type]) => type && !!this.currentOp(type));
  17684. }
  17685. isPending(track) {
  17686. return !!track && !track.buffer;
  17687. }
  17688. // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
  17689. // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
  17690. // upon completion, since we already do it here
  17691. blockBuffers(onUnblocked, bufferNames = this.sourceBufferTypes) {
  17692. if (!bufferNames.length) {
  17693. this.log("Blocking operation requested, but no SourceBuffers exist");
  17694. return Promise.resolve().then(onUnblocked);
  17695. }
  17696. const {
  17697. operationQueue
  17698. } = this;
  17699. const blockingOperations = bufferNames.map((type) => this.appendBlocker(type));
  17700. const audioBlocked = bufferNames.length > 1 && !!this.blockedAudioAppend;
  17701. if (audioBlocked) {
  17702. this.unblockAudio();
  17703. }
  17704. return Promise.all(blockingOperations).then((result) => {
  17705. if (operationQueue !== this.operationQueue) {
  17706. return;
  17707. }
  17708. onUnblocked();
  17709. this.stepOperationQueue(this.sourceBufferTypes);
  17710. });
  17711. }
  17712. stepOperationQueue(bufferNames) {
  17713. bufferNames.forEach((type) => {
  17714. var _this$tracks$type6;
  17715. const sb = (_this$tracks$type6 = this.tracks[type]) == null ? void 0 : _this$tracks$type6.buffer;
  17716. if (!sb || sb.updating) {
  17717. return;
  17718. }
  17719. this.shiftAndExecuteNext(type);
  17720. });
  17721. }
  17722. append(operation, type, pending) {
  17723. if (this.operationQueue) {
  17724. this.operationQueue.append(operation, type, pending);
  17725. }
  17726. }
  17727. appendBlocker(type) {
  17728. if (this.operationQueue) {
  17729. return this.operationQueue.appendBlocker(type);
  17730. }
  17731. }
  17732. currentOp(type) {
  17733. if (this.operationQueue) {
  17734. return this.operationQueue.current(type);
  17735. }
  17736. return null;
  17737. }
  17738. executeNext(type) {
  17739. if (type && this.operationQueue) {
  17740. this.operationQueue.executeNext(type);
  17741. }
  17742. }
  17743. shiftAndExecuteNext(type) {
  17744. if (this.operationQueue) {
  17745. this.operationQueue.shiftAndExecuteNext(type);
  17746. }
  17747. }
  17748. get pendingTrackCount() {
  17749. return Object.keys(this.tracks).reduce((acc, type) => acc + (this.isPending(this.tracks[type]) ? 1 : 0), 0);
  17750. }
  17751. get sourceBufferCount() {
  17752. return this.sourceBuffers.reduce((acc, [type]) => acc + (type ? 1 : 0), 0);
  17753. }
  17754. get sourceBufferTypes() {
  17755. return this.sourceBuffers.map(([type]) => type).filter((type) => !!type);
  17756. }
  17757. addBufferListener(type, event, fn) {
  17758. const track = this.tracks[type];
  17759. if (!track) {
  17760. return;
  17761. }
  17762. const buffer = track.buffer;
  17763. if (!buffer) {
  17764. return;
  17765. }
  17766. const listener = fn.bind(this, type);
  17767. track.listeners.push({
  17768. event,
  17769. listener
  17770. });
  17771. buffer.addEventListener(event, listener);
  17772. }
  17773. removeBufferListeners(type) {
  17774. const track = this.tracks[type];
  17775. if (!track) {
  17776. return;
  17777. }
  17778. const buffer = track.buffer;
  17779. if (!buffer) {
  17780. return;
  17781. }
  17782. track.listeners.forEach((l) => {
  17783. buffer.removeEventListener(l.event, l.listener);
  17784. });
  17785. track.listeners.length = 0;
  17786. }
  17787. };
  17788. function removeSourceChildren(node) {
  17789. const sourceChildren = node.querySelectorAll("source");
  17790. [].slice.call(sourceChildren).forEach((source) => {
  17791. node.removeChild(source);
  17792. });
  17793. }
  17794. function addSource(media, url) {
  17795. const source = self.document.createElement("source");
  17796. source.type = "video/mp4";
  17797. source.src = url;
  17798. media.appendChild(source);
  17799. }
  17800. function sourceBufferNameToIndex(type) {
  17801. return type === "audio" ? 1 : 0;
  17802. }
  17803. var CapLevelController = class _CapLevelController {
  17804. constructor(hls) {
  17805. this.hls = void 0;
  17806. this.autoLevelCapping = void 0;
  17807. this.firstLevel = void 0;
  17808. this.media = void 0;
  17809. this.restrictedLevels = void 0;
  17810. this.timer = void 0;
  17811. this.clientRect = void 0;
  17812. this.streamController = void 0;
  17813. this.hls = hls;
  17814. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  17815. this.firstLevel = -1;
  17816. this.media = null;
  17817. this.restrictedLevels = [];
  17818. this.timer = void 0;
  17819. this.clientRect = null;
  17820. this.registerListeners();
  17821. }
  17822. setStreamController(streamController) {
  17823. this.streamController = streamController;
  17824. }
  17825. destroy() {
  17826. if (this.hls) {
  17827. this.unregisterListener();
  17828. }
  17829. if (this.timer) {
  17830. this.stopCapping();
  17831. }
  17832. this.media = null;
  17833. this.clientRect = null;
  17834. this.hls = this.streamController = null;
  17835. }
  17836. registerListeners() {
  17837. const {
  17838. hls
  17839. } = this;
  17840. hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  17841. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  17842. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  17843. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  17844. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  17845. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  17846. }
  17847. unregisterListener() {
  17848. const {
  17849. hls
  17850. } = this;
  17851. hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  17852. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  17853. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  17854. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  17855. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  17856. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  17857. }
  17858. onFpsDropLevelCapping(event, data) {
  17859. const level = this.hls.levels[data.droppedLevel];
  17860. if (this.isLevelAllowed(level)) {
  17861. this.restrictedLevels.push({
  17862. bitrate: level.bitrate,
  17863. height: level.height,
  17864. width: level.width
  17865. });
  17866. }
  17867. }
  17868. onMediaAttaching(event, data) {
  17869. this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  17870. this.clientRect = null;
  17871. if (this.timer && this.hls.levels.length) {
  17872. this.detectPlayerSize();
  17873. }
  17874. }
  17875. onManifestParsed(event, data) {
  17876. const hls = this.hls;
  17877. this.restrictedLevels = [];
  17878. this.firstLevel = data.firstLevel;
  17879. if (hls.config.capLevelToPlayerSize && data.video) {
  17880. this.startCapping();
  17881. }
  17882. }
  17883. onLevelsUpdated(event, data) {
  17884. if (this.timer && isFiniteNumber(this.autoLevelCapping)) {
  17885. this.detectPlayerSize();
  17886. }
  17887. }
  17888. // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  17889. // to the first level
  17890. onBufferCodecs(event, data) {
  17891. const hls = this.hls;
  17892. if (hls.config.capLevelToPlayerSize && data.video) {
  17893. this.startCapping();
  17894. }
  17895. }
  17896. onMediaDetaching() {
  17897. this.stopCapping();
  17898. this.media = null;
  17899. }
  17900. detectPlayerSize() {
  17901. if (this.media) {
  17902. if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {
  17903. this.clientRect = null;
  17904. return;
  17905. }
  17906. const levels = this.hls.levels;
  17907. if (levels.length) {
  17908. const hls = this.hls;
  17909. const maxLevel = this.getMaxLevel(levels.length - 1);
  17910. if (maxLevel !== this.autoLevelCapping) {
  17911. hls.logger.log(`Setting autoLevelCapping to ${maxLevel}: ${levels[maxLevel].height}p@${levels[maxLevel].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`);
  17912. }
  17913. hls.autoLevelCapping = maxLevel;
  17914. if (hls.autoLevelEnabled && hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
  17915. this.streamController.nextLevelSwitch();
  17916. }
  17917. this.autoLevelCapping = hls.autoLevelCapping;
  17918. }
  17919. }
  17920. }
  17921. /*
  17922. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  17923. */
  17924. getMaxLevel(capLevelIndex) {
  17925. const levels = this.hls.levels;
  17926. if (!levels.length) {
  17927. return -1;
  17928. }
  17929. const validLevels = levels.filter((level, index) => this.isLevelAllowed(level) && index <= capLevelIndex);
  17930. this.clientRect = null;
  17931. return _CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  17932. }
  17933. startCapping() {
  17934. if (this.timer) {
  17935. return;
  17936. }
  17937. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  17938. self.clearInterval(this.timer);
  17939. this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1e3);
  17940. this.detectPlayerSize();
  17941. }
  17942. stopCapping() {
  17943. this.restrictedLevels = [];
  17944. this.firstLevel = -1;
  17945. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  17946. if (this.timer) {
  17947. self.clearInterval(this.timer);
  17948. this.timer = void 0;
  17949. }
  17950. }
  17951. getDimensions() {
  17952. if (this.clientRect) {
  17953. return this.clientRect;
  17954. }
  17955. const media = this.media;
  17956. const boundsRect = {
  17957. width: 0,
  17958. height: 0
  17959. };
  17960. if (media) {
  17961. const clientRect = media.getBoundingClientRect();
  17962. boundsRect.width = clientRect.width;
  17963. boundsRect.height = clientRect.height;
  17964. if (!boundsRect.width && !boundsRect.height) {
  17965. boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
  17966. boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
  17967. }
  17968. }
  17969. this.clientRect = boundsRect;
  17970. return boundsRect;
  17971. }
  17972. get mediaWidth() {
  17973. return this.getDimensions().width * this.contentScaleFactor;
  17974. }
  17975. get mediaHeight() {
  17976. return this.getDimensions().height * this.contentScaleFactor;
  17977. }
  17978. get contentScaleFactor() {
  17979. let pixelRatio = 1;
  17980. if (!this.hls.config.ignoreDevicePixelRatio) {
  17981. try {
  17982. pixelRatio = self.devicePixelRatio;
  17983. } catch (e) {
  17984. }
  17985. }
  17986. return Math.min(pixelRatio, this.hls.config.maxDevicePixelRatio);
  17987. }
  17988. isLevelAllowed(level) {
  17989. const restrictedLevels = this.restrictedLevels;
  17990. return !restrictedLevels.some((restrictedLevel) => {
  17991. return level.bitrate === restrictedLevel.bitrate && level.width === restrictedLevel.width && level.height === restrictedLevel.height;
  17992. });
  17993. }
  17994. static getMaxLevelByMediaSize(levels, width, height) {
  17995. if (!(levels != null && levels.length)) {
  17996. return -1;
  17997. }
  17998. const atGreatestBandwidth = (curLevel, nextLevel) => {
  17999. if (!nextLevel) {
  18000. return true;
  18001. }
  18002. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  18003. };
  18004. let maxLevelIndex = levels.length - 1;
  18005. const squareSize = Math.max(width, height);
  18006. for (let i = 0; i < levels.length; i += 1) {
  18007. const level = levels[i];
  18008. if ((level.width >= squareSize || level.height >= squareSize) && atGreatestBandwidth(level, levels[i + 1])) {
  18009. maxLevelIndex = i;
  18010. break;
  18011. }
  18012. }
  18013. return maxLevelIndex;
  18014. }
  18015. };
  18016. var CmObjectType = {
  18017. /**
  18018. * text file, such as a manifest or playlist
  18019. */
  18020. MANIFEST: "m",
  18021. /**
  18022. * audio only
  18023. */
  18024. AUDIO: "a",
  18025. /**
  18026. * video only
  18027. */
  18028. VIDEO: "v",
  18029. /**
  18030. * muxed audio and video
  18031. */
  18032. MUXED: "av",
  18033. /**
  18034. * init segment
  18035. */
  18036. INIT: "i",
  18037. /**
  18038. * caption or subtitle
  18039. */
  18040. CAPTION: "c",
  18041. /**
  18042. * ISOBMFF timed text track
  18043. */
  18044. TIMED_TEXT: "tt",
  18045. /**
  18046. * cryptographic key, license or certificate.
  18047. */
  18048. KEY: "k",
  18049. /**
  18050. * other
  18051. */
  18052. OTHER: "o"
  18053. };
  18054. var CmcdObjectType = CmObjectType;
  18055. var CmStreamingFormat = {
  18056. /**
  18057. * HTTP Live Streaming (HLS)
  18058. */
  18059. HLS: "h"
  18060. };
  18061. var CmcdStreamingFormat = CmStreamingFormat;
  18062. var CMCD_OBJECT = "CMCD-Object";
  18063. var CMCD_REQUEST = "CMCD-Request";
  18064. var CMCD_SESSION = "CMCD-Session";
  18065. var CMCD_STATUS = "CMCD-Status";
  18066. var CmcdHeaderField = {
  18067. /**
  18068. * keys whose values vary with the object being requested.
  18069. */
  18070. OBJECT: CMCD_OBJECT,
  18071. /**
  18072. * keys whose values vary with each request.
  18073. */
  18074. REQUEST: CMCD_REQUEST,
  18075. /**
  18076. * keys whose values are expected to be invariant over the life of the session.
  18077. */
  18078. SESSION: CMCD_SESSION,
  18079. /**
  18080. * keys whose values do not vary with every request or object.
  18081. */
  18082. STATUS: CMCD_STATUS
  18083. };
  18084. var CmcdHeaderMap = {
  18085. [CmcdHeaderField.OBJECT]: ["br", "ab", "d", "ot", "tb", "tpb", "lb", "tab", "lab", "url"],
  18086. [CmcdHeaderField.REQUEST]: ["pb", "bl", "tbl", "dl", "ltc", "mtp", "nor", "nrr", "rc", "sn", "sta", "su", "ttfb", "ttfbb", "ttlb", "cmsdd", "cmsds", "smrt", "df", "cs"],
  18087. [CmcdHeaderField.SESSION]: ["cid", "pr", "sf", "sid", "st", "v", "msd"],
  18088. [CmcdHeaderField.STATUS]: ["bs", "bsd", "cdn", "rtp", "bg", "pt", "ec", "e"]
  18089. };
  18090. var SfItem = class _SfItem {
  18091. constructor(value, params) {
  18092. if (Array.isArray(value)) {
  18093. value = value.map((v) => v instanceof _SfItem ? v : new _SfItem(v));
  18094. }
  18095. this.value = value;
  18096. this.params = params;
  18097. }
  18098. };
  18099. var DICT = "Dict";
  18100. function format(value) {
  18101. if (Array.isArray(value)) {
  18102. return JSON.stringify(value);
  18103. }
  18104. if (value instanceof Map) {
  18105. return "Map{}";
  18106. }
  18107. if (value instanceof Set) {
  18108. return "Set{}";
  18109. }
  18110. if (typeof value === "object") {
  18111. return JSON.stringify(value);
  18112. }
  18113. return String(value);
  18114. }
  18115. function throwError(action, src, type, cause) {
  18116. return new Error(`failed to ${action} "${format(src)}" as ${type}`, {
  18117. cause
  18118. });
  18119. }
  18120. function serializeError(src, type, cause) {
  18121. return throwError("serialize", src, type, cause);
  18122. }
  18123. var SfToken = class {
  18124. constructor(description) {
  18125. this.description = description;
  18126. }
  18127. };
  18128. var BARE_ITEM = "Bare Item";
  18129. var BOOLEAN = "Boolean";
  18130. function serializeBoolean(value) {
  18131. if (typeof value !== "boolean") {
  18132. throw serializeError(value, BOOLEAN);
  18133. }
  18134. return value ? "?1" : "?0";
  18135. }
  18136. function encodeBase64(binary) {
  18137. return btoa(String.fromCharCode(...binary));
  18138. }
  18139. var BYTES = "Byte Sequence";
  18140. function serializeByteSequence(value) {
  18141. if (ArrayBuffer.isView(value) === false) {
  18142. throw serializeError(value, BYTES);
  18143. }
  18144. return `:${encodeBase64(value)}:`;
  18145. }
  18146. var INTEGER = "Integer";
  18147. function isInvalidInt(value) {
  18148. return value < -999999999999999 || 999999999999999 < value;
  18149. }
  18150. function serializeInteger(value) {
  18151. if (isInvalidInt(value)) {
  18152. throw serializeError(value, INTEGER);
  18153. }
  18154. return value.toString();
  18155. }
  18156. function serializeDate(value) {
  18157. return `@${serializeInteger(value.getTime() / 1e3)}`;
  18158. }
  18159. function roundToEven(value, precision) {
  18160. if (value < 0) {
  18161. return -roundToEven(-value, precision);
  18162. }
  18163. const decimalShift = Math.pow(10, precision);
  18164. const isEquidistant = Math.abs(value * decimalShift % 1 - 0.5) < Number.EPSILON;
  18165. if (isEquidistant) {
  18166. const flooredValue = Math.floor(value * decimalShift);
  18167. return (flooredValue % 2 === 0 ? flooredValue : flooredValue + 1) / decimalShift;
  18168. } else {
  18169. return Math.round(value * decimalShift) / decimalShift;
  18170. }
  18171. }
  18172. var DECIMAL = "Decimal";
  18173. function serializeDecimal(value) {
  18174. const roundedValue = roundToEven(value, 3);
  18175. if (Math.floor(Math.abs(roundedValue)).toString().length > 12) {
  18176. throw serializeError(value, DECIMAL);
  18177. }
  18178. const stringValue = roundedValue.toString();
  18179. return stringValue.includes(".") ? stringValue : `${stringValue}.0`;
  18180. }
  18181. var STRING = "String";
  18182. var STRING_REGEX = /[\x00-\x1f\x7f]+/;
  18183. function serializeString(value) {
  18184. if (STRING_REGEX.test(value)) {
  18185. throw serializeError(value, STRING);
  18186. }
  18187. return `"${value.replace(/\\/g, `\\\\`).replace(/"/g, `\\"`)}"`;
  18188. }
  18189. function symbolToStr(symbol) {
  18190. return symbol.description || symbol.toString().slice(7, -1);
  18191. }
  18192. var TOKEN = "Token";
  18193. function serializeToken(token) {
  18194. const value = symbolToStr(token);
  18195. if (/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(value) === false) {
  18196. throw serializeError(value, TOKEN);
  18197. }
  18198. return value;
  18199. }
  18200. function serializeBareItem(value) {
  18201. switch (typeof value) {
  18202. case "number":
  18203. if (!isFiniteNumber(value)) {
  18204. throw serializeError(value, BARE_ITEM);
  18205. }
  18206. if (Number.isInteger(value)) {
  18207. return serializeInteger(value);
  18208. }
  18209. return serializeDecimal(value);
  18210. case "string":
  18211. return serializeString(value);
  18212. case "symbol":
  18213. return serializeToken(value);
  18214. case "boolean":
  18215. return serializeBoolean(value);
  18216. case "object":
  18217. if (value instanceof Date) {
  18218. return serializeDate(value);
  18219. }
  18220. if (value instanceof Uint8Array) {
  18221. return serializeByteSequence(value);
  18222. }
  18223. if (value instanceof SfToken) {
  18224. return serializeToken(value);
  18225. }
  18226. default:
  18227. throw serializeError(value, BARE_ITEM);
  18228. }
  18229. }
  18230. var KEY = "Key";
  18231. function serializeKey(value) {
  18232. if (/^[a-z*][a-z0-9\-_.*]*$/.test(value) === false) {
  18233. throw serializeError(value, KEY);
  18234. }
  18235. return value;
  18236. }
  18237. function serializeParams(params) {
  18238. if (params == null) {
  18239. return "";
  18240. }
  18241. return Object.entries(params).map(([key, value]) => {
  18242. if (value === true) {
  18243. return `;${serializeKey(key)}`;
  18244. }
  18245. return `;${serializeKey(key)}=${serializeBareItem(value)}`;
  18246. }).join("");
  18247. }
  18248. function serializeItem(value) {
  18249. if (value instanceof SfItem) {
  18250. return `${serializeBareItem(value.value)}${serializeParams(value.params)}`;
  18251. } else {
  18252. return serializeBareItem(value);
  18253. }
  18254. }
  18255. function serializeInnerList(value) {
  18256. return `(${value.value.map(serializeItem).join(" ")})${serializeParams(value.params)}`;
  18257. }
  18258. function serializeDict(dict, options = {
  18259. whitespace: true
  18260. }) {
  18261. if (typeof dict !== "object") {
  18262. throw serializeError(dict, DICT);
  18263. }
  18264. const entries = dict instanceof Map ? dict.entries() : Object.entries(dict);
  18265. const optionalWhiteSpace = (options === null || options === void 0 ? void 0 : options.whitespace) ? " " : "";
  18266. return Array.from(entries).map(([key, item]) => {
  18267. if (item instanceof SfItem === false) {
  18268. item = new SfItem(item);
  18269. }
  18270. let output = serializeKey(key);
  18271. if (item.value === true) {
  18272. output += serializeParams(item.params);
  18273. } else {
  18274. output += "=";
  18275. if (Array.isArray(item.value)) {
  18276. output += serializeInnerList(item);
  18277. } else {
  18278. output += serializeItem(item);
  18279. }
  18280. }
  18281. return output;
  18282. }).join(`,${optionalWhiteSpace}`);
  18283. }
  18284. function encodeSfDict(value, options) {
  18285. return serializeDict(value, options);
  18286. }
  18287. function isTokenField(key) {
  18288. return ["ot", "sf", "st", "e", "sta"].includes(key);
  18289. }
  18290. function isValid(value) {
  18291. if (typeof value === "number") {
  18292. return isFiniteNumber(value);
  18293. }
  18294. return value != null && value !== "" && value !== false;
  18295. }
  18296. function urlToRelativePath(url, base) {
  18297. const to = new URL(url);
  18298. const from = new URL(base);
  18299. if (to.origin !== from.origin) {
  18300. return url;
  18301. }
  18302. const toPath = to.pathname.split("/").slice(1);
  18303. const fromPath = from.pathname.split("/").slice(1, -1);
  18304. while (toPath[0] === fromPath[0]) {
  18305. toPath.shift();
  18306. fromPath.shift();
  18307. }
  18308. while (fromPath.length) {
  18309. fromPath.shift();
  18310. toPath.unshift("..");
  18311. }
  18312. return toPath.join("/");
  18313. }
  18314. var toRounded = (value) => Math.round(value);
  18315. var toUrlSafe = (value, options) => {
  18316. if (options === null || options === void 0 ? void 0 : options.baseUrl) {
  18317. value = urlToRelativePath(value, options.baseUrl);
  18318. }
  18319. return encodeURIComponent(value);
  18320. };
  18321. var toHundred = (value) => toRounded(value / 100) * 100;
  18322. var CmcdFormatters = {
  18323. /**
  18324. * Bitrate (kbps) rounded integer
  18325. */
  18326. br: toRounded,
  18327. /**
  18328. * Duration (milliseconds) rounded integer
  18329. */
  18330. d: toRounded,
  18331. /**
  18332. * Buffer Length (milliseconds) rounded nearest 100ms
  18333. */
  18334. bl: toHundred,
  18335. /**
  18336. * Deadline (milliseconds) rounded nearest 100ms
  18337. */
  18338. dl: toHundred,
  18339. /**
  18340. * Measured Throughput (kbps) rounded nearest 100kbps
  18341. */
  18342. mtp: toHundred,
  18343. /**
  18344. * Next Object Request URL encoded
  18345. */
  18346. nor: toUrlSafe,
  18347. /**
  18348. * Requested maximum throughput (kbps) rounded nearest 100kbps
  18349. */
  18350. rtp: toHundred,
  18351. /**
  18352. * Top Bitrate (kbps) rounded integer
  18353. */
  18354. tb: toRounded
  18355. };
  18356. function processCmcd(obj, options) {
  18357. const results = {};
  18358. if (obj == null || typeof obj !== "object") {
  18359. return results;
  18360. }
  18361. const keys = Object.keys(obj).sort();
  18362. const formatters = _extends({}, CmcdFormatters, options === null || options === void 0 ? void 0 : options.formatters);
  18363. const filter = options === null || options === void 0 ? void 0 : options.filter;
  18364. keys.forEach((key) => {
  18365. if ((filter === null || filter === void 0 ? void 0 : filter(key)) === false) {
  18366. return;
  18367. }
  18368. let value = obj[key];
  18369. const formatter = formatters[key];
  18370. if (formatter) {
  18371. value = formatter(value, options);
  18372. }
  18373. if (key === "v" && value === 1) {
  18374. return;
  18375. }
  18376. if (key == "pr" && value === 1) {
  18377. return;
  18378. }
  18379. if (!isValid(value)) {
  18380. return;
  18381. }
  18382. if (isTokenField(key) && typeof value === "string") {
  18383. value = new SfToken(value);
  18384. }
  18385. results[key] = value;
  18386. });
  18387. return results;
  18388. }
  18389. function encodeCmcd(cmcd, options = {}) {
  18390. if (!cmcd) {
  18391. return "";
  18392. }
  18393. return encodeSfDict(processCmcd(cmcd, options), _extends({
  18394. whitespace: false
  18395. }, options));
  18396. }
  18397. function toCmcdHeaders(cmcd, options = {}) {
  18398. const result = {};
  18399. if (!cmcd) {
  18400. return result;
  18401. }
  18402. const entries = Object.entries(cmcd);
  18403. const headerMap = Object.entries(CmcdHeaderMap).concat(Object.entries((options === null || options === void 0 ? void 0 : options.customHeaderMap) || {}));
  18404. const shards = entries.reduce((acc, entry) => {
  18405. var _a, _b;
  18406. const [key, value] = entry;
  18407. const field = ((_a = headerMap.find((entry2) => entry2[1].includes(key))) === null || _a === void 0 ? void 0 : _a[0]) || CmcdHeaderField.REQUEST;
  18408. (_b = acc[field]) !== null && _b !== void 0 ? _b : acc[field] = {};
  18409. acc[field][key] = value;
  18410. return acc;
  18411. }, {});
  18412. return Object.entries(shards).reduce((acc, [field, value]) => {
  18413. acc[field] = encodeCmcd(value, options);
  18414. return acc;
  18415. }, result);
  18416. }
  18417. function appendCmcdHeaders(headers, cmcd, options) {
  18418. return _extends(headers, toCmcdHeaders(cmcd, options));
  18419. }
  18420. var CMCD_PARAM = "CMCD";
  18421. function toCmcdQuery(cmcd, options = {}) {
  18422. if (!cmcd) {
  18423. return "";
  18424. }
  18425. const params = encodeCmcd(cmcd, options);
  18426. return `${CMCD_PARAM}=${encodeURIComponent(params)}`;
  18427. }
  18428. var REGEX = /CMCD=[^&#]+/;
  18429. function appendCmcdQuery(url, cmcd, options) {
  18430. const query = toCmcdQuery(cmcd, options);
  18431. if (!query) {
  18432. return url;
  18433. }
  18434. if (REGEX.test(url)) {
  18435. return url.replace(REGEX, query);
  18436. }
  18437. const separator = url.includes("?") ? "&" : "?";
  18438. return `${url}${separator}${query}`;
  18439. }
  18440. var CMCDController = class {
  18441. constructor(hls) {
  18442. this.hls = void 0;
  18443. this.config = void 0;
  18444. this.media = void 0;
  18445. this.sid = void 0;
  18446. this.cid = void 0;
  18447. this.useHeaders = false;
  18448. this.includeKeys = void 0;
  18449. this.initialized = false;
  18450. this.starved = false;
  18451. this.buffering = true;
  18452. this.audioBuffer = void 0;
  18453. this.videoBuffer = void 0;
  18454. this.onWaiting = () => {
  18455. if (this.initialized) {
  18456. this.starved = true;
  18457. }
  18458. this.buffering = true;
  18459. };
  18460. this.onPlaying = () => {
  18461. if (!this.initialized) {
  18462. this.initialized = true;
  18463. }
  18464. this.buffering = false;
  18465. };
  18466. this.applyPlaylistData = (context) => {
  18467. try {
  18468. this.apply(context, {
  18469. ot: CmcdObjectType.MANIFEST,
  18470. su: !this.initialized
  18471. });
  18472. } catch (error) {
  18473. this.hls.logger.warn("Could not generate manifest CMCD data.", error);
  18474. }
  18475. };
  18476. this.applyFragmentData = (context) => {
  18477. try {
  18478. const {
  18479. frag,
  18480. part
  18481. } = context;
  18482. const level = this.hls.levels[frag.level];
  18483. const ot = this.getObjectType(frag);
  18484. const data = {
  18485. d: (part || frag).duration * 1e3,
  18486. ot
  18487. };
  18488. if (ot === CmcdObjectType.VIDEO || ot === CmcdObjectType.AUDIO || ot == CmcdObjectType.MUXED) {
  18489. data.br = level.bitrate / 1e3;
  18490. data.tb = this.getTopBandwidth(ot) / 1e3;
  18491. data.bl = this.getBufferLength(ot);
  18492. }
  18493. const next = part ? this.getNextPart(part) : this.getNextFrag(frag);
  18494. if (next != null && next.url && next.url !== frag.url) {
  18495. data.nor = next.url;
  18496. }
  18497. this.apply(context, data);
  18498. } catch (error) {
  18499. this.hls.logger.warn("Could not generate segment CMCD data.", error);
  18500. }
  18501. };
  18502. this.hls = hls;
  18503. const config = this.config = hls.config;
  18504. const {
  18505. cmcd
  18506. } = config;
  18507. if (cmcd != null) {
  18508. config.pLoader = this.createPlaylistLoader();
  18509. config.fLoader = this.createFragmentLoader();
  18510. this.sid = cmcd.sessionId || hls.sessionId;
  18511. this.cid = cmcd.contentId;
  18512. this.useHeaders = cmcd.useHeaders === true;
  18513. this.includeKeys = cmcd.includeKeys;
  18514. this.registerListeners();
  18515. }
  18516. }
  18517. registerListeners() {
  18518. const hls = this.hls;
  18519. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18520. hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  18521. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  18522. }
  18523. unregisterListeners() {
  18524. const hls = this.hls;
  18525. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18526. hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  18527. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  18528. }
  18529. destroy() {
  18530. this.unregisterListeners();
  18531. this.onMediaDetached();
  18532. this.hls = this.config = this.audioBuffer = this.videoBuffer = null;
  18533. this.onWaiting = this.onPlaying = this.media = null;
  18534. }
  18535. onMediaAttached(event, data) {
  18536. this.media = data.media;
  18537. this.media.addEventListener("waiting", this.onWaiting);
  18538. this.media.addEventListener("playing", this.onPlaying);
  18539. }
  18540. onMediaDetached() {
  18541. if (!this.media) {
  18542. return;
  18543. }
  18544. this.media.removeEventListener("waiting", this.onWaiting);
  18545. this.media.removeEventListener("playing", this.onPlaying);
  18546. this.media = null;
  18547. }
  18548. onBufferCreated(event, data) {
  18549. var _data$tracks$audio, _data$tracks$video;
  18550. this.audioBuffer = (_data$tracks$audio = data.tracks.audio) == null ? void 0 : _data$tracks$audio.buffer;
  18551. this.videoBuffer = (_data$tracks$video = data.tracks.video) == null ? void 0 : _data$tracks$video.buffer;
  18552. }
  18553. /**
  18554. * Create baseline CMCD data
  18555. */
  18556. createData() {
  18557. var _this$media;
  18558. return {
  18559. v: 1,
  18560. sf: CmcdStreamingFormat.HLS,
  18561. sid: this.sid,
  18562. cid: this.cid,
  18563. pr: (_this$media = this.media) == null ? void 0 : _this$media.playbackRate,
  18564. mtp: this.hls.bandwidthEstimate / 1e3
  18565. };
  18566. }
  18567. /**
  18568. * Apply CMCD data to a request.
  18569. */
  18570. apply(context, data = {}) {
  18571. _extends(data, this.createData());
  18572. const isVideo = data.ot === CmcdObjectType.INIT || data.ot === CmcdObjectType.VIDEO || data.ot === CmcdObjectType.MUXED;
  18573. if (this.starved && isVideo) {
  18574. data.bs = true;
  18575. data.su = true;
  18576. this.starved = false;
  18577. }
  18578. if (data.su == null) {
  18579. data.su = this.buffering;
  18580. }
  18581. const {
  18582. includeKeys
  18583. } = this;
  18584. if (includeKeys) {
  18585. data = Object.keys(data).reduce((acc, key) => {
  18586. includeKeys.includes(key) && (acc[key] = data[key]);
  18587. return acc;
  18588. }, {});
  18589. }
  18590. const options = {
  18591. baseUrl: context.url
  18592. };
  18593. if (this.useHeaders) {
  18594. if (!context.headers) {
  18595. context.headers = {};
  18596. }
  18597. appendCmcdHeaders(context.headers, data, options);
  18598. } else {
  18599. context.url = appendCmcdQuery(context.url, data, options);
  18600. }
  18601. }
  18602. getNextFrag(fragment) {
  18603. var _this$hls$levels$frag;
  18604. const levelDetails = (_this$hls$levels$frag = this.hls.levels[fragment.level]) == null ? void 0 : _this$hls$levels$frag.details;
  18605. if (levelDetails) {
  18606. const index = fragment.sn - levelDetails.startSN;
  18607. return levelDetails.fragments[index + 1];
  18608. }
  18609. return void 0;
  18610. }
  18611. getNextPart(part) {
  18612. var _this$hls$levels$frag2, _this$hls$levels$frag3;
  18613. const {
  18614. index,
  18615. fragment
  18616. } = part;
  18617. const partList = (_this$hls$levels$frag2 = this.hls.levels[fragment.level]) == null ? void 0 : (_this$hls$levels$frag3 = _this$hls$levels$frag2.details) == null ? void 0 : _this$hls$levels$frag3.partList;
  18618. if (partList) {
  18619. const {
  18620. sn
  18621. } = fragment;
  18622. for (let i = partList.length - 1; i >= 0; i--) {
  18623. const p = partList[i];
  18624. if (p.index === index && p.fragment.sn === sn) {
  18625. return partList[i + 1];
  18626. }
  18627. }
  18628. }
  18629. return void 0;
  18630. }
  18631. /**
  18632. * The CMCD object type.
  18633. */
  18634. getObjectType(fragment) {
  18635. const {
  18636. type
  18637. } = fragment;
  18638. if (type === "subtitle") {
  18639. return CmcdObjectType.TIMED_TEXT;
  18640. }
  18641. if (fragment.sn === "initSegment") {
  18642. return CmcdObjectType.INIT;
  18643. }
  18644. if (type === "audio") {
  18645. return CmcdObjectType.AUDIO;
  18646. }
  18647. if (type === "main") {
  18648. if (!this.hls.audioTracks.length) {
  18649. return CmcdObjectType.MUXED;
  18650. }
  18651. return CmcdObjectType.VIDEO;
  18652. }
  18653. return void 0;
  18654. }
  18655. /**
  18656. * Get the highest bitrate.
  18657. */
  18658. getTopBandwidth(type) {
  18659. let bitrate = 0;
  18660. let levels;
  18661. const hls = this.hls;
  18662. if (type === CmcdObjectType.AUDIO) {
  18663. levels = hls.audioTracks;
  18664. } else {
  18665. const max = hls.maxAutoLevel;
  18666. const len = max > -1 ? max + 1 : hls.levels.length;
  18667. levels = hls.levels.slice(0, len);
  18668. }
  18669. levels.forEach((level) => {
  18670. if (level.bitrate > bitrate) {
  18671. bitrate = level.bitrate;
  18672. }
  18673. });
  18674. return bitrate > 0 ? bitrate : NaN;
  18675. }
  18676. /**
  18677. * Get the buffer length for a media type in milliseconds
  18678. */
  18679. getBufferLength(type) {
  18680. const media = this.media;
  18681. const buffer = type === CmcdObjectType.AUDIO ? this.audioBuffer : this.videoBuffer;
  18682. if (!buffer || !media) {
  18683. return NaN;
  18684. }
  18685. const info = BufferHelper.bufferInfo(buffer, media.currentTime, this.config.maxBufferHole);
  18686. return info.len * 1e3;
  18687. }
  18688. /**
  18689. * Create a playlist loader
  18690. */
  18691. createPlaylistLoader() {
  18692. const {
  18693. pLoader
  18694. } = this.config;
  18695. const apply = this.applyPlaylistData;
  18696. const Ctor = pLoader || this.config.loader;
  18697. return class CmcdPlaylistLoader {
  18698. constructor(config) {
  18699. this.loader = void 0;
  18700. this.loader = new Ctor(config);
  18701. }
  18702. get stats() {
  18703. return this.loader.stats;
  18704. }
  18705. get context() {
  18706. return this.loader.context;
  18707. }
  18708. destroy() {
  18709. this.loader.destroy();
  18710. }
  18711. abort() {
  18712. this.loader.abort();
  18713. }
  18714. load(context, config, callbacks) {
  18715. apply(context);
  18716. this.loader.load(context, config, callbacks);
  18717. }
  18718. };
  18719. }
  18720. /**
  18721. * Create a playlist loader
  18722. */
  18723. createFragmentLoader() {
  18724. const {
  18725. fLoader
  18726. } = this.config;
  18727. const apply = this.applyFragmentData;
  18728. const Ctor = fLoader || this.config.loader;
  18729. return class CmcdFragmentLoader {
  18730. constructor(config) {
  18731. this.loader = void 0;
  18732. this.loader = new Ctor(config);
  18733. }
  18734. get stats() {
  18735. return this.loader.stats;
  18736. }
  18737. get context() {
  18738. return this.loader.context;
  18739. }
  18740. destroy() {
  18741. this.loader.destroy();
  18742. }
  18743. abort() {
  18744. this.loader.abort();
  18745. }
  18746. load(context, config, callbacks) {
  18747. apply(context);
  18748. this.loader.load(context, config, callbacks);
  18749. }
  18750. };
  18751. }
  18752. };
  18753. var PATHWAY_PENALTY_DURATION_MS = 3e5;
  18754. var ContentSteeringController = class extends Logger {
  18755. constructor(hls) {
  18756. super("content-steering", hls.logger);
  18757. this.hls = void 0;
  18758. this.loader = null;
  18759. this.uri = null;
  18760. this.pathwayId = ".";
  18761. this._pathwayPriority = null;
  18762. this.timeToLoad = 300;
  18763. this.reloadTimer = -1;
  18764. this.updated = 0;
  18765. this.started = false;
  18766. this.enabled = true;
  18767. this.levels = null;
  18768. this.audioTracks = null;
  18769. this.subtitleTracks = null;
  18770. this.penalizedPathways = {};
  18771. this.hls = hls;
  18772. this.registerListeners();
  18773. }
  18774. registerListeners() {
  18775. const hls = this.hls;
  18776. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18777. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  18778. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  18779. hls.on(Events.ERROR, this.onError, this);
  18780. }
  18781. unregisterListeners() {
  18782. const hls = this.hls;
  18783. if (!hls) {
  18784. return;
  18785. }
  18786. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18787. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  18788. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  18789. hls.off(Events.ERROR, this.onError, this);
  18790. }
  18791. pathways() {
  18792. return (this.levels || []).reduce((pathways, level) => {
  18793. if (pathways.indexOf(level.pathwayId) === -1) {
  18794. pathways.push(level.pathwayId);
  18795. }
  18796. return pathways;
  18797. }, []);
  18798. }
  18799. get pathwayPriority() {
  18800. return this._pathwayPriority;
  18801. }
  18802. set pathwayPriority(pathwayPriority) {
  18803. this.updatePathwayPriority(pathwayPriority);
  18804. }
  18805. startLoad() {
  18806. this.started = true;
  18807. this.clearTimeout();
  18808. if (this.enabled && this.uri) {
  18809. if (this.updated) {
  18810. const ttl = this.timeToLoad * 1e3 - (performance.now() - this.updated);
  18811. if (ttl > 0) {
  18812. this.scheduleRefresh(this.uri, ttl);
  18813. return;
  18814. }
  18815. }
  18816. this.loadSteeringManifest(this.uri);
  18817. }
  18818. }
  18819. stopLoad() {
  18820. this.started = false;
  18821. if (this.loader) {
  18822. this.loader.destroy();
  18823. this.loader = null;
  18824. }
  18825. this.clearTimeout();
  18826. }
  18827. clearTimeout() {
  18828. if (this.reloadTimer !== -1) {
  18829. self.clearTimeout(this.reloadTimer);
  18830. this.reloadTimer = -1;
  18831. }
  18832. }
  18833. destroy() {
  18834. this.unregisterListeners();
  18835. this.stopLoad();
  18836. this.hls = null;
  18837. this.levels = this.audioTracks = this.subtitleTracks = null;
  18838. }
  18839. removeLevel(levelToRemove) {
  18840. const levels = this.levels;
  18841. if (levels) {
  18842. this.levels = levels.filter((level) => level !== levelToRemove);
  18843. }
  18844. }
  18845. onManifestLoading() {
  18846. this.stopLoad();
  18847. this.enabled = true;
  18848. this.timeToLoad = 300;
  18849. this.updated = 0;
  18850. this.uri = null;
  18851. this.pathwayId = ".";
  18852. this.levels = this.audioTracks = this.subtitleTracks = null;
  18853. }
  18854. onManifestLoaded(event, data) {
  18855. const {
  18856. contentSteering
  18857. } = data;
  18858. if (contentSteering === null) {
  18859. return;
  18860. }
  18861. this.pathwayId = contentSteering.pathwayId;
  18862. this.uri = contentSteering.uri;
  18863. if (this.started) {
  18864. this.startLoad();
  18865. }
  18866. }
  18867. onManifestParsed(event, data) {
  18868. this.audioTracks = data.audioTracks;
  18869. this.subtitleTracks = data.subtitleTracks;
  18870. }
  18871. onError(event, data) {
  18872. const {
  18873. errorAction
  18874. } = data;
  18875. if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox && errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost) {
  18876. const levels = this.levels;
  18877. let pathwayPriority = this._pathwayPriority;
  18878. let errorPathway = this.pathwayId;
  18879. if (data.context) {
  18880. const {
  18881. groupId,
  18882. pathwayId,
  18883. type
  18884. } = data.context;
  18885. if (groupId && levels) {
  18886. errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway);
  18887. } else if (pathwayId) {
  18888. errorPathway = pathwayId;
  18889. }
  18890. }
  18891. if (!(errorPathway in this.penalizedPathways)) {
  18892. this.penalizedPathways[errorPathway] = performance.now();
  18893. }
  18894. if (!pathwayPriority && levels) {
  18895. pathwayPriority = this.pathways();
  18896. }
  18897. if (pathwayPriority && pathwayPriority.length > 1) {
  18898. this.updatePathwayPriority(pathwayPriority);
  18899. errorAction.resolved = this.pathwayId !== errorPathway;
  18900. }
  18901. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && !data.fatal) {
  18902. errorAction.resolved = true;
  18903. } else if (!errorAction.resolved) {
  18904. this.warn(`Could not resolve ${data.details} ("${data.error.message}") with content-steering for Pathway: ${errorPathway} levels: ${levels ? levels.length : levels} priorities: ${stringify(pathwayPriority)} penalized: ${stringify(this.penalizedPathways)}`);
  18905. }
  18906. }
  18907. }
  18908. filterParsedLevels(levels) {
  18909. this.levels = levels;
  18910. let pathwayLevels = this.getLevelsForPathway(this.pathwayId);
  18911. if (pathwayLevels.length === 0) {
  18912. const pathwayId = levels[0].pathwayId;
  18913. this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${pathwayId}"`);
  18914. pathwayLevels = this.getLevelsForPathway(pathwayId);
  18915. this.pathwayId = pathwayId;
  18916. }
  18917. if (pathwayLevels.length !== levels.length) {
  18918. this.log(`Found ${pathwayLevels.length}/${levels.length} levels in Pathway "${this.pathwayId}"`);
  18919. }
  18920. return pathwayLevels;
  18921. }
  18922. getLevelsForPathway(pathwayId) {
  18923. if (this.levels === null) {
  18924. return [];
  18925. }
  18926. return this.levels.filter((level) => pathwayId === level.pathwayId);
  18927. }
  18928. updatePathwayPriority(pathwayPriority) {
  18929. this._pathwayPriority = pathwayPriority;
  18930. let levels;
  18931. const penalizedPathways = this.penalizedPathways;
  18932. const now2 = performance.now();
  18933. Object.keys(penalizedPathways).forEach((pathwayId) => {
  18934. if (now2 - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {
  18935. delete penalizedPathways[pathwayId];
  18936. }
  18937. });
  18938. for (let i = 0; i < pathwayPriority.length; i++) {
  18939. const pathwayId = pathwayPriority[i];
  18940. if (pathwayId in penalizedPathways) {
  18941. continue;
  18942. }
  18943. if (pathwayId === this.pathwayId) {
  18944. return;
  18945. }
  18946. const selectedIndex = this.hls.nextLoadLevel;
  18947. const selectedLevel = this.hls.levels[selectedIndex];
  18948. levels = this.getLevelsForPathway(pathwayId);
  18949. if (levels.length > 0) {
  18950. this.log(`Setting Pathway to "${pathwayId}"`);
  18951. this.pathwayId = pathwayId;
  18952. reassignFragmentLevelIndexes(levels);
  18953. this.hls.trigger(Events.LEVELS_UPDATED, {
  18954. levels
  18955. });
  18956. const levelAfterChange = this.hls.levels[selectedIndex];
  18957. if (selectedLevel && levelAfterChange && this.levels) {
  18958. if (levelAfterChange.attrs["STABLE-VARIANT-ID"] !== selectedLevel.attrs["STABLE-VARIANT-ID"] && levelAfterChange.bitrate !== selectedLevel.bitrate) {
  18959. this.log(`Unstable Pathways change from bitrate ${selectedLevel.bitrate} to ${levelAfterChange.bitrate}`);
  18960. }
  18961. this.hls.nextLoadLevel = selectedIndex;
  18962. }
  18963. break;
  18964. }
  18965. }
  18966. }
  18967. getPathwayForGroupId(groupId, type, defaultPathway) {
  18968. const levels = this.getLevelsForPathway(defaultPathway).concat(this.levels || []);
  18969. for (let i = 0; i < levels.length; i++) {
  18970. if (type === PlaylistContextType.AUDIO_TRACK && levels[i].hasAudioGroup(groupId) || type === PlaylistContextType.SUBTITLE_TRACK && levels[i].hasSubtitleGroup(groupId)) {
  18971. return levels[i].pathwayId;
  18972. }
  18973. }
  18974. return defaultPathway;
  18975. }
  18976. clonePathways(pathwayClones) {
  18977. const levels = this.levels;
  18978. if (!levels) {
  18979. return;
  18980. }
  18981. const audioGroupCloneMap = {};
  18982. const subtitleGroupCloneMap = {};
  18983. pathwayClones.forEach((pathwayClone) => {
  18984. const {
  18985. ID: cloneId,
  18986. "BASE-ID": baseId,
  18987. "URI-REPLACEMENT": uriReplacement
  18988. } = pathwayClone;
  18989. if (levels.some((level) => level.pathwayId === cloneId)) {
  18990. return;
  18991. }
  18992. const clonedVariants = this.getLevelsForPathway(baseId).map((baseLevel) => {
  18993. const attributes = new AttrList(baseLevel.attrs);
  18994. attributes["PATHWAY-ID"] = cloneId;
  18995. const clonedAudioGroupId = attributes.AUDIO && `${attributes.AUDIO}_clone_${cloneId}`;
  18996. const clonedSubtitleGroupId = attributes.SUBTITLES && `${attributes.SUBTITLES}_clone_${cloneId}`;
  18997. if (clonedAudioGroupId) {
  18998. audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;
  18999. attributes.AUDIO = clonedAudioGroupId;
  19000. }
  19001. if (clonedSubtitleGroupId) {
  19002. subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;
  19003. attributes.SUBTITLES = clonedSubtitleGroupId;
  19004. }
  19005. const url = performUriReplacement(baseLevel.uri, attributes["STABLE-VARIANT-ID"], "PER-VARIANT-URIS", uriReplacement);
  19006. const clonedLevel = new Level({
  19007. attrs: attributes,
  19008. audioCodec: baseLevel.audioCodec,
  19009. bitrate: baseLevel.bitrate,
  19010. height: baseLevel.height,
  19011. name: baseLevel.name,
  19012. url,
  19013. videoCodec: baseLevel.videoCodec,
  19014. width: baseLevel.width
  19015. });
  19016. if (baseLevel.audioGroups) {
  19017. for (let i = 1; i < baseLevel.audioGroups.length; i++) {
  19018. clonedLevel.addGroupId("audio", `${baseLevel.audioGroups[i]}_clone_${cloneId}`);
  19019. }
  19020. }
  19021. if (baseLevel.subtitleGroups) {
  19022. for (let i = 1; i < baseLevel.subtitleGroups.length; i++) {
  19023. clonedLevel.addGroupId("text", `${baseLevel.subtitleGroups[i]}_clone_${cloneId}`);
  19024. }
  19025. }
  19026. return clonedLevel;
  19027. });
  19028. levels.push(...clonedVariants);
  19029. cloneRenditionGroups(this.audioTracks, audioGroupCloneMap, uriReplacement, cloneId);
  19030. cloneRenditionGroups(this.subtitleTracks, subtitleGroupCloneMap, uriReplacement, cloneId);
  19031. });
  19032. }
  19033. loadSteeringManifest(uri) {
  19034. const config = this.hls.config;
  19035. const Loader = config.loader;
  19036. if (this.loader) {
  19037. this.loader.destroy();
  19038. }
  19039. this.loader = new Loader(config);
  19040. let url;
  19041. try {
  19042. url = new self.URL(uri);
  19043. } catch (error) {
  19044. this.enabled = false;
  19045. this.log(`Failed to parse Steering Manifest URI: ${uri}`);
  19046. return;
  19047. }
  19048. if (url.protocol !== "data:") {
  19049. const throughput = (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;
  19050. url.searchParams.set("_HLS_pathway", this.pathwayId);
  19051. url.searchParams.set("_HLS_throughput", "" + throughput);
  19052. }
  19053. const context = {
  19054. responseType: "json",
  19055. url: url.href
  19056. };
  19057. const loadPolicy = config.steeringManifestLoadPolicy.default;
  19058. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  19059. const loaderConfig = {
  19060. loadPolicy,
  19061. timeout: loadPolicy.maxLoadTimeMs,
  19062. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  19063. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  19064. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  19065. };
  19066. const callbacks = {
  19067. onSuccess: (response, stats, context2, networkDetails) => {
  19068. this.log(`Loaded steering manifest: "${url}"`);
  19069. const steeringData = response.data;
  19070. if ((steeringData == null ? void 0 : steeringData.VERSION) !== 1) {
  19071. this.log(`Steering VERSION ${steeringData.VERSION} not supported!`);
  19072. return;
  19073. }
  19074. this.updated = performance.now();
  19075. this.timeToLoad = steeringData.TTL;
  19076. const {
  19077. "RELOAD-URI": reloadUri,
  19078. "PATHWAY-CLONES": pathwayClones,
  19079. "PATHWAY-PRIORITY": pathwayPriority
  19080. } = steeringData;
  19081. if (reloadUri) {
  19082. try {
  19083. this.uri = new self.URL(reloadUri, url).href;
  19084. } catch (error) {
  19085. this.enabled = false;
  19086. this.log(`Failed to parse Steering Manifest RELOAD-URI: ${reloadUri}`);
  19087. return;
  19088. }
  19089. }
  19090. this.scheduleRefresh(this.uri || context2.url);
  19091. if (pathwayClones) {
  19092. this.clonePathways(pathwayClones);
  19093. }
  19094. const loadedSteeringData = {
  19095. steeringManifest: steeringData,
  19096. url: url.toString()
  19097. };
  19098. this.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);
  19099. if (pathwayPriority) {
  19100. this.updatePathwayPriority(pathwayPriority);
  19101. }
  19102. },
  19103. onError: (error, context2, networkDetails, stats) => {
  19104. this.log(`Error loading steering manifest: ${error.code} ${error.text} (${context2.url})`);
  19105. this.stopLoad();
  19106. if (error.code === 410) {
  19107. this.enabled = false;
  19108. this.log(`Steering manifest ${context2.url} no longer available`);
  19109. return;
  19110. }
  19111. let ttl = this.timeToLoad * 1e3;
  19112. if (error.code === 429) {
  19113. const loader = this.loader;
  19114. if (typeof (loader == null ? void 0 : loader.getResponseHeader) === "function") {
  19115. const retryAfter = loader.getResponseHeader("Retry-After");
  19116. if (retryAfter) {
  19117. ttl = parseFloat(retryAfter) * 1e3;
  19118. }
  19119. }
  19120. this.log(`Steering manifest ${context2.url} rate limited`);
  19121. return;
  19122. }
  19123. this.scheduleRefresh(this.uri || context2.url, ttl);
  19124. },
  19125. onTimeout: (stats, context2, networkDetails) => {
  19126. this.log(`Timeout loading steering manifest (${context2.url})`);
  19127. this.scheduleRefresh(this.uri || context2.url);
  19128. }
  19129. };
  19130. this.log(`Requesting steering manifest: ${url}`);
  19131. this.loader.load(context, loaderConfig, callbacks);
  19132. }
  19133. scheduleRefresh(uri, ttlMs = this.timeToLoad * 1e3) {
  19134. this.clearTimeout();
  19135. this.reloadTimer = self.setTimeout(() => {
  19136. var _this$hls;
  19137. const media = (_this$hls = this.hls) == null ? void 0 : _this$hls.media;
  19138. if (media && !media.ended) {
  19139. this.loadSteeringManifest(uri);
  19140. return;
  19141. }
  19142. this.scheduleRefresh(uri, this.timeToLoad * 1e3);
  19143. }, ttlMs);
  19144. }
  19145. };
  19146. function cloneRenditionGroups(tracks, groupCloneMap, uriReplacement, cloneId) {
  19147. if (!tracks) {
  19148. return;
  19149. }
  19150. Object.keys(groupCloneMap).forEach((audioGroupId) => {
  19151. const clonedTracks = tracks.filter((track) => track.groupId === audioGroupId).map((track) => {
  19152. const clonedTrack = _extends({}, track);
  19153. clonedTrack.details = void 0;
  19154. clonedTrack.attrs = new AttrList(clonedTrack.attrs);
  19155. clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(track.url, track.attrs["STABLE-RENDITION-ID"], "PER-RENDITION-URIS", uriReplacement);
  19156. clonedTrack.groupId = clonedTrack.attrs["GROUP-ID"] = groupCloneMap[audioGroupId];
  19157. clonedTrack.attrs["PATHWAY-ID"] = cloneId;
  19158. return clonedTrack;
  19159. });
  19160. tracks.push(...clonedTracks);
  19161. });
  19162. }
  19163. function performUriReplacement(uri, stableId, perOptionKey, uriReplacement) {
  19164. const {
  19165. HOST: host,
  19166. PARAMS: params,
  19167. [perOptionKey]: perOptionUris
  19168. } = uriReplacement;
  19169. let perVariantUri;
  19170. if (stableId) {
  19171. perVariantUri = perOptionUris == null ? void 0 : perOptionUris[stableId];
  19172. if (perVariantUri) {
  19173. uri = perVariantUri;
  19174. }
  19175. }
  19176. const url = new self.URL(uri);
  19177. if (host && !perVariantUri) {
  19178. url.host = host;
  19179. }
  19180. if (params) {
  19181. Object.keys(params).sort().forEach((key) => {
  19182. if (key) {
  19183. url.searchParams.set(key, params[key]);
  19184. }
  19185. });
  19186. }
  19187. return url.href;
  19188. }
  19189. function addEventListener(el, type, listener) {
  19190. removeEventListener(el, type, listener);
  19191. el.addEventListener(type, listener);
  19192. }
  19193. function removeEventListener(el, type, listener) {
  19194. el.removeEventListener(type, listener);
  19195. }
  19196. var EMEController = class _EMEController extends Logger {
  19197. constructor(hls) {
  19198. super("eme", hls.logger);
  19199. this.hls = void 0;
  19200. this.config = void 0;
  19201. this.media = null;
  19202. this.keyFormatPromise = null;
  19203. this.keySystemAccessPromises = {};
  19204. this._requestLicenseFailureCount = 0;
  19205. this.mediaKeySessions = [];
  19206. this.keyIdToKeySessionPromise = {};
  19207. this.mediaKeys = null;
  19208. this.setMediaKeysQueue = _EMEController.CDMCleanupPromise ? [_EMEController.CDMCleanupPromise] : [];
  19209. this.onWaitingForKey = (event) => {
  19210. this.log(`"${event.type}" event`);
  19211. };
  19212. this.hls = hls;
  19213. this.config = hls.config;
  19214. this.registerListeners();
  19215. }
  19216. destroy() {
  19217. this.onDestroying();
  19218. this.onMediaDetached();
  19219. const config = this.config;
  19220. config.requestMediaKeySystemAccessFunc = null;
  19221. config.licenseXhrSetup = config.licenseResponseCallback = void 0;
  19222. config.drmSystems = config.drmSystemOptions = {};
  19223. this.hls = this.config = this.keyIdToKeySessionPromise = null;
  19224. this.onWaitingForKey = null;
  19225. }
  19226. registerListeners() {
  19227. this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  19228. this.hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  19229. this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  19230. this.hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  19231. this.hls.on(Events.DESTROYING, this.onDestroying, this);
  19232. }
  19233. unregisterListeners() {
  19234. this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  19235. this.hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  19236. this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  19237. this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  19238. this.hls.off(Events.DESTROYING, this.onDestroying, this);
  19239. }
  19240. getLicenseServerUrl(keySystem) {
  19241. const {
  19242. drmSystems,
  19243. widevineLicenseUrl
  19244. } = this.config;
  19245. const keySystemConfiguration = drmSystems[keySystem];
  19246. if (keySystemConfiguration) {
  19247. return keySystemConfiguration.licenseUrl;
  19248. }
  19249. if (keySystem === KeySystems.WIDEVINE && widevineLicenseUrl) {
  19250. return widevineLicenseUrl;
  19251. }
  19252. }
  19253. getLicenseServerUrlOrThrow(keySystem) {
  19254. const url = this.getLicenseServerUrl(keySystem);
  19255. if (url === void 0) {
  19256. throw new Error(`no license server URL configured for key-system "${keySystem}"`);
  19257. }
  19258. return url;
  19259. }
  19260. getServerCertificateUrl(keySystem) {
  19261. const {
  19262. drmSystems
  19263. } = this.config;
  19264. const keySystemConfiguration = drmSystems[keySystem];
  19265. if (keySystemConfiguration) {
  19266. return keySystemConfiguration.serverCertificateUrl;
  19267. } else {
  19268. this.log(`No Server Certificate in config.drmSystems["${keySystem}"]`);
  19269. }
  19270. }
  19271. attemptKeySystemAccess(keySystemsToAttempt) {
  19272. const levels = this.hls.levels;
  19273. const uniqueCodec = (value, i, a) => !!value && a.indexOf(value) === i;
  19274. const audioCodecs = levels.map((level) => level.audioCodec).filter(uniqueCodec);
  19275. const videoCodecs = levels.map((level) => level.videoCodec).filter(uniqueCodec);
  19276. if (audioCodecs.length + videoCodecs.length === 0) {
  19277. videoCodecs.push("avc1.42e01e");
  19278. }
  19279. return new Promise((resolve, reject) => {
  19280. const attempt = (keySystems) => {
  19281. const keySystem = keySystems.shift();
  19282. this.getMediaKeysPromise(keySystem, audioCodecs, videoCodecs).then((mediaKeys) => resolve({
  19283. keySystem,
  19284. mediaKeys
  19285. })).catch((error) => {
  19286. if (keySystems.length) {
  19287. attempt(keySystems);
  19288. } else if (error instanceof EMEKeyError) {
  19289. reject(error);
  19290. } else {
  19291. reject(new EMEKeyError({
  19292. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19293. details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,
  19294. error,
  19295. fatal: true
  19296. }, error.message));
  19297. }
  19298. });
  19299. };
  19300. attempt(keySystemsToAttempt);
  19301. });
  19302. }
  19303. requestMediaKeySystemAccess(keySystem, supportedConfigurations) {
  19304. const {
  19305. requestMediaKeySystemAccessFunc
  19306. } = this.config;
  19307. if (!(typeof requestMediaKeySystemAccessFunc === "function")) {
  19308. let errMessage = `Configured requestMediaKeySystemAccess is not a function ${requestMediaKeySystemAccessFunc}`;
  19309. if (requestMediaKeySystemAccess === null && self.location.protocol === "http:") {
  19310. errMessage = `navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`;
  19311. }
  19312. return Promise.reject(new Error(errMessage));
  19313. }
  19314. return requestMediaKeySystemAccessFunc(keySystem, supportedConfigurations);
  19315. }
  19316. getMediaKeysPromise(keySystem, audioCodecs, videoCodecs) {
  19317. const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this.config.drmSystemOptions);
  19318. const keySystemAccessPromises = this.keySystemAccessPromises[keySystem];
  19319. let keySystemAccess = keySystemAccessPromises == null ? void 0 : keySystemAccessPromises.keySystemAccess;
  19320. if (!keySystemAccess) {
  19321. this.log(`Requesting encrypted media "${keySystem}" key-system access with config: ${stringify(mediaKeySystemConfigs)}`);
  19322. keySystemAccess = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);
  19323. const _keySystemAccessPromises = this.keySystemAccessPromises[keySystem] = {
  19324. keySystemAccess
  19325. };
  19326. keySystemAccess.catch((error) => {
  19327. this.log(`Failed to obtain access to key-system "${keySystem}": ${error}`);
  19328. });
  19329. return keySystemAccess.then((mediaKeySystemAccess) => {
  19330. this.log(`Access for key-system "${mediaKeySystemAccess.keySystem}" obtained`);
  19331. const certificateRequest = this.fetchServerCertificate(keySystem);
  19332. this.log(`Create media-keys for "${keySystem}"`);
  19333. _keySystemAccessPromises.mediaKeys = mediaKeySystemAccess.createMediaKeys().then((mediaKeys) => {
  19334. this.log(`Media-keys created for "${keySystem}"`);
  19335. _keySystemAccessPromises.hasMediaKeys = true;
  19336. return certificateRequest.then((certificate) => {
  19337. if (certificate) {
  19338. return this.setMediaKeysServerCertificate(mediaKeys, keySystem, certificate);
  19339. }
  19340. return mediaKeys;
  19341. });
  19342. });
  19343. _keySystemAccessPromises.mediaKeys.catch((error) => {
  19344. this.error(`Failed to create media-keys for "${keySystem}"}: ${error}`);
  19345. });
  19346. return _keySystemAccessPromises.mediaKeys;
  19347. });
  19348. }
  19349. return keySystemAccess.then(() => keySystemAccessPromises.mediaKeys);
  19350. }
  19351. createMediaKeySessionContext({
  19352. decryptdata,
  19353. keySystem,
  19354. mediaKeys
  19355. }) {
  19356. this.log(`Creating key-system session "${keySystem}" keyId: ${Hex.hexDump(decryptdata.keyId || [])}`);
  19357. const mediaKeysSession = mediaKeys.createSession();
  19358. const mediaKeySessionContext = {
  19359. decryptdata,
  19360. keySystem,
  19361. mediaKeys,
  19362. mediaKeysSession,
  19363. keyStatus: "status-pending"
  19364. };
  19365. this.mediaKeySessions.push(mediaKeySessionContext);
  19366. return mediaKeySessionContext;
  19367. }
  19368. renewKeySession(mediaKeySessionContext) {
  19369. const decryptdata = mediaKeySessionContext.decryptdata;
  19370. if (decryptdata.pssh) {
  19371. const keySessionContext = this.createMediaKeySessionContext(mediaKeySessionContext);
  19372. const keyId = this.getKeyIdString(decryptdata);
  19373. const scheme = "cenc";
  19374. this.keyIdToKeySessionPromise[keyId] = this.generateRequestWithPreferredKeySession(keySessionContext, scheme, decryptdata.pssh.buffer, "expired");
  19375. } else {
  19376. this.warn(`Could not renew expired session. Missing pssh initData.`);
  19377. }
  19378. this.removeSession(mediaKeySessionContext);
  19379. }
  19380. getKeyIdString(decryptdata) {
  19381. if (!decryptdata) {
  19382. throw new Error("Could not read keyId of undefined decryptdata");
  19383. }
  19384. if (decryptdata.keyId === null) {
  19385. throw new Error("keyId is null");
  19386. }
  19387. return Hex.hexDump(decryptdata.keyId);
  19388. }
  19389. updateKeySession(mediaKeySessionContext, data) {
  19390. var _mediaKeySessionConte;
  19391. const keySession = mediaKeySessionContext.mediaKeysSession;
  19392. this.log(`Updating key-session "${keySession.sessionId}" for keyID ${Hex.hexDump(((_mediaKeySessionConte = mediaKeySessionContext.decryptdata) == null ? void 0 : _mediaKeySessionConte.keyId) || [])}
  19393. } (data length: ${data ? data.byteLength : data})`);
  19394. return keySession.update(data);
  19395. }
  19396. getSelectedKeySystemFormats() {
  19397. return Object.keys(this.keySystemAccessPromises).map((keySystem) => ({
  19398. keySystem,
  19399. hasMediaKeys: this.keySystemAccessPromises[keySystem].hasMediaKeys
  19400. })).filter(({
  19401. hasMediaKeys
  19402. }) => !!hasMediaKeys).map(({
  19403. keySystem
  19404. }) => keySystemDomainToKeySystemFormat(keySystem)).filter((keySystem) => !!keySystem);
  19405. }
  19406. getKeySystemAccess(keySystemsToAttempt) {
  19407. return this.getKeySystemSelectionPromise(keySystemsToAttempt).then(({
  19408. keySystem,
  19409. mediaKeys
  19410. }) => {
  19411. return this.attemptSetMediaKeys(keySystem, mediaKeys);
  19412. });
  19413. }
  19414. selectKeySystem(keySystemsToAttempt) {
  19415. return new Promise((resolve, reject) => {
  19416. return this.getKeySystemSelectionPromise(keySystemsToAttempt).then(({
  19417. keySystem
  19418. }) => {
  19419. const keySystemFormat = keySystemDomainToKeySystemFormat(keySystem);
  19420. if (keySystemFormat) {
  19421. resolve(keySystemFormat);
  19422. } else {
  19423. reject(new Error(`Unable to find format for key-system "${keySystem}"`));
  19424. }
  19425. }).catch(reject);
  19426. });
  19427. }
  19428. selectKeySystemFormat(frag) {
  19429. const keyFormats = Object.keys(frag.levelkeys || {});
  19430. if (!this.keyFormatPromise) {
  19431. this.log(`Selecting key-system from fragment (sn: ${frag.sn} ${frag.type}: ${frag.level}) key formats ${keyFormats.join(", ")}`);
  19432. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  19433. }
  19434. return this.keyFormatPromise;
  19435. }
  19436. getKeyFormatPromise(keyFormats) {
  19437. const keySystemsInConfig = getKeySystemsForConfig(this.config);
  19438. const keySystemsToAttempt = keyFormats.map(keySystemFormatToKeySystemDomain).filter((value) => !!value && keySystemsInConfig.indexOf(value) !== -1);
  19439. return this.selectKeySystem(keySystemsToAttempt);
  19440. }
  19441. loadKey(data) {
  19442. const decryptdata = data.keyInfo.decryptdata;
  19443. const keyId = this.getKeyIdString(decryptdata);
  19444. const keyDetails = `(keyId: ${keyId} format: "${decryptdata.keyFormat}" method: ${decryptdata.method} uri: ${decryptdata.uri})`;
  19445. this.log(`Starting session for key ${keyDetails}`);
  19446. let keyContextPromise = this.keyIdToKeySessionPromise[keyId];
  19447. if (!keyContextPromise) {
  19448. keyContextPromise = this.getKeySystemForKeyPromise(decryptdata).then(({
  19449. keySystem,
  19450. mediaKeys
  19451. }) => {
  19452. this.throwIfDestroyed();
  19453. this.log(`Handle encrypted media sn: ${data.frag.sn} ${data.frag.type}: ${data.frag.level} using key ${keyDetails}`);
  19454. return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => {
  19455. this.throwIfDestroyed();
  19456. return this.createMediaKeySessionContext({
  19457. keySystem,
  19458. mediaKeys,
  19459. decryptdata
  19460. });
  19461. });
  19462. });
  19463. const keySessionContextPromise = this.keyIdToKeySessionPromise[keyId] = keyContextPromise.then((keySessionContext) => {
  19464. const scheme = "cenc";
  19465. const initData = decryptdata.pssh ? decryptdata.pssh.buffer : null;
  19466. return this.generateRequestWithPreferredKeySession(keySessionContext, scheme, initData, "playlist-key");
  19467. });
  19468. keySessionContextPromise.catch((error) => this.handleError(error));
  19469. }
  19470. return keyContextPromise;
  19471. }
  19472. throwIfDestroyed(message = "Invalid state") {
  19473. if (!this.hls) {
  19474. throw new Error("invalid state");
  19475. }
  19476. }
  19477. handleError(error) {
  19478. if (!this.hls) {
  19479. return;
  19480. }
  19481. this.error(error.message);
  19482. if (error instanceof EMEKeyError) {
  19483. this.hls.trigger(Events.ERROR, error.data);
  19484. } else {
  19485. this.hls.trigger(Events.ERROR, {
  19486. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19487. details: ErrorDetails.KEY_SYSTEM_NO_KEYS,
  19488. error,
  19489. fatal: true
  19490. });
  19491. }
  19492. }
  19493. getKeySystemForKeyPromise(decryptdata) {
  19494. const keyId = this.getKeyIdString(decryptdata);
  19495. const mediaKeySessionContext = this.keyIdToKeySessionPromise[keyId];
  19496. if (!mediaKeySessionContext) {
  19497. const keySystem = keySystemFormatToKeySystemDomain(decryptdata.keyFormat);
  19498. const keySystemsToAttempt = keySystem ? [keySystem] : getKeySystemsForConfig(this.config);
  19499. return this.attemptKeySystemAccess(keySystemsToAttempt);
  19500. }
  19501. return mediaKeySessionContext;
  19502. }
  19503. getKeySystemSelectionPromise(keySystemsToAttempt) {
  19504. if (!keySystemsToAttempt.length) {
  19505. keySystemsToAttempt = getKeySystemsForConfig(this.config);
  19506. }
  19507. if (keySystemsToAttempt.length === 0) {
  19508. throw new EMEKeyError({
  19509. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19510. details: ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,
  19511. fatal: true
  19512. }, `Missing key-system license configuration options ${stringify({
  19513. drmSystems: this.config.drmSystems
  19514. })}`);
  19515. }
  19516. return this.attemptKeySystemAccess(keySystemsToAttempt);
  19517. }
  19518. attemptSetMediaKeys(keySystem, mediaKeys) {
  19519. if (this.mediaKeys === mediaKeys) {
  19520. return Promise.resolve();
  19521. }
  19522. const queue = this.setMediaKeysQueue.slice();
  19523. this.log(`Setting media-keys for "${keySystem}"`);
  19524. const setMediaKeysPromise = Promise.all(queue).then(() => {
  19525. if (!this.media) {
  19526. this.mediaKeys = null;
  19527. throw new Error("Attempted to set mediaKeys without media element attached");
  19528. }
  19529. return this.media.setMediaKeys(mediaKeys);
  19530. });
  19531. this.mediaKeys = mediaKeys;
  19532. this.setMediaKeysQueue.push(setMediaKeysPromise);
  19533. return setMediaKeysPromise.then(() => {
  19534. this.log(`Media-keys set for "${keySystem}"`);
  19535. queue.push(setMediaKeysPromise);
  19536. this.setMediaKeysQueue = this.setMediaKeysQueue.filter((p) => queue.indexOf(p) === -1);
  19537. });
  19538. }
  19539. generateRequestWithPreferredKeySession(context, initDataType, initData, reason) {
  19540. var _this$config$drmSyste, _this$config$drmSyste2;
  19541. const generateRequestFilter = (_this$config$drmSyste = this.config.drmSystems) == null ? void 0 : (_this$config$drmSyste2 = _this$config$drmSyste[context.keySystem]) == null ? void 0 : _this$config$drmSyste2.generateRequest;
  19542. if (generateRequestFilter) {
  19543. try {
  19544. const mappedInitData = generateRequestFilter.call(this.hls, initDataType, initData, context);
  19545. if (!mappedInitData) {
  19546. throw new Error("Invalid response from configured generateRequest filter");
  19547. }
  19548. initDataType = mappedInitData.initDataType;
  19549. initData = mappedInitData.initData ? mappedInitData.initData : null;
  19550. context.decryptdata.pssh = initData ? new Uint8Array(initData) : null;
  19551. } catch (error) {
  19552. var _this$hls;
  19553. this.warn(error.message);
  19554. if ((_this$hls = this.hls) != null && _this$hls.config.debug) {
  19555. throw error;
  19556. }
  19557. }
  19558. }
  19559. if (initData === null) {
  19560. this.log(`Skipping key-session request for "${reason}" (no initData)`);
  19561. return Promise.resolve(context);
  19562. }
  19563. const keyId = this.getKeyIdString(context.decryptdata);
  19564. this.log(`Generating key-session request for "${reason}": ${keyId} (init data type: ${initDataType} length: ${initData ? initData.byteLength : null})`);
  19565. const licenseStatus = new EventEmitter();
  19566. const onmessage = context._onmessage = (event) => {
  19567. const keySession = context.mediaKeysSession;
  19568. if (!keySession) {
  19569. licenseStatus.emit("error", new Error("invalid state"));
  19570. return;
  19571. }
  19572. const {
  19573. messageType,
  19574. message
  19575. } = event;
  19576. this.log(`"${messageType}" message event for session "${keySession.sessionId}" message size: ${message.byteLength}`);
  19577. if (messageType === "license-request" || messageType === "license-renewal") {
  19578. this.renewLicense(context, message).catch((error) => {
  19579. if (licenseStatus.eventNames().length) {
  19580. licenseStatus.emit("error", error);
  19581. } else {
  19582. this.handleError(error);
  19583. }
  19584. });
  19585. } else if (messageType === "license-release") {
  19586. if (context.keySystem === KeySystems.FAIRPLAY) {
  19587. this.updateKeySession(context, strToUtf8array("acknowledged"));
  19588. this.removeSession(context);
  19589. }
  19590. } else {
  19591. this.warn(`unhandled media key message type "${messageType}"`);
  19592. }
  19593. };
  19594. const onkeystatuseschange = context._onkeystatuseschange = (event) => {
  19595. const keySession = context.mediaKeysSession;
  19596. if (!keySession) {
  19597. licenseStatus.emit("error", new Error("invalid state"));
  19598. return;
  19599. }
  19600. this.onKeyStatusChange(context);
  19601. const keyStatus = context.keyStatus;
  19602. licenseStatus.emit("keyStatus", keyStatus);
  19603. if (keyStatus === "expired") {
  19604. this.warn(`${context.keySystem} expired for key ${keyId}`);
  19605. this.renewKeySession(context);
  19606. }
  19607. };
  19608. addEventListener(context.mediaKeysSession, "message", onmessage);
  19609. addEventListener(context.mediaKeysSession, "keystatuseschange", onkeystatuseschange);
  19610. const keyUsablePromise = new Promise((resolve, reject) => {
  19611. licenseStatus.on("error", reject);
  19612. licenseStatus.on("keyStatus", (keyStatus) => {
  19613. if (keyStatus.startsWith("usable")) {
  19614. resolve();
  19615. } else if (keyStatus === "output-restricted") {
  19616. reject(new EMEKeyError({
  19617. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19618. details: ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,
  19619. fatal: false
  19620. }, "HDCP level output restricted"));
  19621. } else if (keyStatus === "internal-error") {
  19622. reject(new EMEKeyError({
  19623. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19624. details: ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR,
  19625. fatal: true
  19626. }, `key status changed to "${keyStatus}"`));
  19627. } else if (keyStatus === "expired") {
  19628. reject(new Error("key expired while generating request"));
  19629. } else {
  19630. this.warn(`unhandled key status change "${keyStatus}"`);
  19631. }
  19632. });
  19633. });
  19634. return context.mediaKeysSession.generateRequest(initDataType, initData).then(() => {
  19635. var _context$mediaKeysSes;
  19636. this.log(`Request generated for key-session "${(_context$mediaKeysSes = context.mediaKeysSession) == null ? void 0 : _context$mediaKeysSes.sessionId}" keyId: ${keyId}`);
  19637. }).catch((error) => {
  19638. throw new EMEKeyError({
  19639. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19640. details: ErrorDetails.KEY_SYSTEM_NO_SESSION,
  19641. error,
  19642. fatal: false
  19643. }, `Error generating key-session request: ${error}`);
  19644. }).then(() => keyUsablePromise).catch((error) => {
  19645. licenseStatus.removeAllListeners();
  19646. this.removeSession(context);
  19647. throw error;
  19648. }).then(() => {
  19649. licenseStatus.removeAllListeners();
  19650. return context;
  19651. });
  19652. }
  19653. onKeyStatusChange(mediaKeySessionContext) {
  19654. mediaKeySessionContext.mediaKeysSession.keyStatuses.forEach((status2, keyId) => {
  19655. if (typeof keyId === "string" && typeof status2 === "object") {
  19656. const temp = keyId;
  19657. keyId = status2;
  19658. status2 = temp;
  19659. }
  19660. this.log(`key status change "${status2}" for keyStatuses keyId: ${Hex.hexDump("buffer" in keyId ? new Uint8Array(keyId.buffer, keyId.byteOffset, keyId.byteLength) : new Uint8Array(keyId))} session keyId: ${Hex.hexDump(new Uint8Array(mediaKeySessionContext.decryptdata.keyId || []))} uri: ${mediaKeySessionContext.decryptdata.uri}`);
  19661. mediaKeySessionContext.keyStatus = status2;
  19662. });
  19663. }
  19664. fetchServerCertificate(keySystem) {
  19665. const config = this.config;
  19666. const Loader = config.loader;
  19667. const certLoader = new Loader(config);
  19668. const url = this.getServerCertificateUrl(keySystem);
  19669. if (!url) {
  19670. return Promise.resolve();
  19671. }
  19672. this.log(`Fetching server certificate for "${keySystem}"`);
  19673. return new Promise((resolve, reject) => {
  19674. const loaderContext = {
  19675. responseType: "arraybuffer",
  19676. url
  19677. };
  19678. const loadPolicy = config.certLoadPolicy.default;
  19679. const loaderConfig = {
  19680. loadPolicy,
  19681. timeout: loadPolicy.maxLoadTimeMs,
  19682. maxRetry: 0,
  19683. retryDelay: 0,
  19684. maxRetryDelay: 0
  19685. };
  19686. const loaderCallbacks = {
  19687. onSuccess: (response, stats, context, networkDetails) => {
  19688. resolve(response.data);
  19689. },
  19690. onError: (response, contex, networkDetails, stats) => {
  19691. reject(new EMEKeyError({
  19692. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19693. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  19694. fatal: true,
  19695. networkDetails,
  19696. response: _objectSpread2({
  19697. url: loaderContext.url,
  19698. data: void 0
  19699. }, response)
  19700. }, `"${keySystem}" certificate request failed (${url}). Status: ${response.code} (${response.text})`));
  19701. },
  19702. onTimeout: (stats, context, networkDetails) => {
  19703. reject(new EMEKeyError({
  19704. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19705. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  19706. fatal: true,
  19707. networkDetails,
  19708. response: {
  19709. url: loaderContext.url,
  19710. data: void 0
  19711. }
  19712. }, `"${keySystem}" certificate request timed out (${url})`));
  19713. },
  19714. onAbort: (stats, context, networkDetails) => {
  19715. reject(new Error("aborted"));
  19716. }
  19717. };
  19718. certLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  19719. });
  19720. }
  19721. setMediaKeysServerCertificate(mediaKeys, keySystem, cert) {
  19722. return new Promise((resolve, reject) => {
  19723. mediaKeys.setServerCertificate(cert).then((success) => {
  19724. this.log(`setServerCertificate ${success ? "success" : "not supported by CDM"} (${cert == null ? void 0 : cert.byteLength}) on "${keySystem}"`);
  19725. resolve(mediaKeys);
  19726. }).catch((error) => {
  19727. reject(new EMEKeyError({
  19728. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19729. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,
  19730. error,
  19731. fatal: true
  19732. }, error.message));
  19733. });
  19734. });
  19735. }
  19736. renewLicense(context, keyMessage) {
  19737. return this.requestLicense(context, new Uint8Array(keyMessage)).then((data) => {
  19738. return this.updateKeySession(context, new Uint8Array(data)).catch((error) => {
  19739. throw new EMEKeyError({
  19740. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19741. details: ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,
  19742. error,
  19743. fatal: true
  19744. }, error.message);
  19745. });
  19746. });
  19747. }
  19748. unpackPlayReadyKeyMessage(xhr, licenseChallenge) {
  19749. const xmlString = String.fromCharCode.apply(null, new Uint16Array(licenseChallenge.buffer));
  19750. if (!xmlString.includes("PlayReadyKeyMessage")) {
  19751. xhr.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  19752. return licenseChallenge;
  19753. }
  19754. const keyMessageXml = new DOMParser().parseFromString(xmlString, "application/xml");
  19755. const headers = keyMessageXml.querySelectorAll("HttpHeader");
  19756. if (headers.length > 0) {
  19757. let header;
  19758. for (let i = 0, len = headers.length; i < len; i++) {
  19759. var _header$querySelector, _header$querySelector2;
  19760. header = headers[i];
  19761. const name = (_header$querySelector = header.querySelector("name")) == null ? void 0 : _header$querySelector.textContent;
  19762. const value = (_header$querySelector2 = header.querySelector("value")) == null ? void 0 : _header$querySelector2.textContent;
  19763. if (name && value) {
  19764. xhr.setRequestHeader(name, value);
  19765. }
  19766. }
  19767. }
  19768. const challengeElement = keyMessageXml.querySelector("Challenge");
  19769. const challengeText = challengeElement == null ? void 0 : challengeElement.textContent;
  19770. if (!challengeText) {
  19771. throw new Error(`Cannot find <Challenge> in key message`);
  19772. }
  19773. return strToUtf8array(atob(challengeText));
  19774. }
  19775. setupLicenseXHR(xhr, url, keysListItem, licenseChallenge) {
  19776. const licenseXhrSetup = this.config.licenseXhrSetup;
  19777. if (!licenseXhrSetup) {
  19778. xhr.open("POST", url, true);
  19779. return Promise.resolve({
  19780. xhr,
  19781. licenseChallenge
  19782. });
  19783. }
  19784. return Promise.resolve().then(() => {
  19785. if (!keysListItem.decryptdata) {
  19786. throw new Error("Key removed");
  19787. }
  19788. return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);
  19789. }).catch((error) => {
  19790. if (!keysListItem.decryptdata) {
  19791. throw error;
  19792. }
  19793. xhr.open("POST", url, true);
  19794. return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);
  19795. }).then((licenseXhrSetupResult) => {
  19796. if (!xhr.readyState) {
  19797. xhr.open("POST", url, true);
  19798. }
  19799. const finalLicenseChallenge = licenseXhrSetupResult ? licenseXhrSetupResult : licenseChallenge;
  19800. return {
  19801. xhr,
  19802. licenseChallenge: finalLicenseChallenge
  19803. };
  19804. });
  19805. }
  19806. requestLicense(keySessionContext, licenseChallenge) {
  19807. const keyLoadPolicy = this.config.keyLoadPolicy.default;
  19808. return new Promise((resolve, reject) => {
  19809. const url = this.getLicenseServerUrlOrThrow(keySessionContext.keySystem);
  19810. this.log(`Sending license request to URL: ${url}`);
  19811. const xhr = new XMLHttpRequest();
  19812. xhr.responseType = "arraybuffer";
  19813. xhr.onreadystatechange = () => {
  19814. if (!this.hls || !keySessionContext.mediaKeysSession) {
  19815. return reject(new Error("invalid state"));
  19816. }
  19817. if (xhr.readyState === 4) {
  19818. if (xhr.status === 200) {
  19819. this._requestLicenseFailureCount = 0;
  19820. let data = xhr.response;
  19821. this.log(`License received ${data instanceof ArrayBuffer ? data.byteLength : data}`);
  19822. const licenseResponseCallback = this.config.licenseResponseCallback;
  19823. if (licenseResponseCallback) {
  19824. try {
  19825. data = licenseResponseCallback.call(this.hls, xhr, url, keySessionContext);
  19826. } catch (error) {
  19827. this.error(error);
  19828. }
  19829. }
  19830. resolve(data);
  19831. } else {
  19832. const retryConfig = keyLoadPolicy.errorRetry;
  19833. const maxNumRetry = retryConfig ? retryConfig.maxNumRetry : 0;
  19834. this._requestLicenseFailureCount++;
  19835. if (this._requestLicenseFailureCount > maxNumRetry || xhr.status >= 400 && xhr.status < 500) {
  19836. reject(new EMEKeyError({
  19837. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19838. details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  19839. fatal: true,
  19840. networkDetails: xhr,
  19841. response: {
  19842. url,
  19843. data: void 0,
  19844. code: xhr.status,
  19845. text: xhr.statusText
  19846. }
  19847. }, `License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`));
  19848. } else {
  19849. const attemptsLeft = maxNumRetry - this._requestLicenseFailureCount + 1;
  19850. this.warn(`Retrying license request, ${attemptsLeft} attempts left`);
  19851. this.requestLicense(keySessionContext, licenseChallenge).then(resolve, reject);
  19852. }
  19853. }
  19854. }
  19855. };
  19856. if (keySessionContext.licenseXhr && keySessionContext.licenseXhr.readyState !== XMLHttpRequest.DONE) {
  19857. keySessionContext.licenseXhr.abort();
  19858. }
  19859. keySessionContext.licenseXhr = xhr;
  19860. this.setupLicenseXHR(xhr, url, keySessionContext, licenseChallenge).then(({
  19861. xhr: xhr2,
  19862. licenseChallenge: licenseChallenge2
  19863. }) => {
  19864. if (keySessionContext.keySystem == KeySystems.PLAYREADY) {
  19865. licenseChallenge2 = this.unpackPlayReadyKeyMessage(xhr2, licenseChallenge2);
  19866. }
  19867. xhr2.send(licenseChallenge2);
  19868. });
  19869. });
  19870. }
  19871. onDestroying() {
  19872. this.unregisterListeners();
  19873. this._clear();
  19874. }
  19875. onMediaAttached(event, data) {
  19876. if (!this.config.emeEnabled) {
  19877. return;
  19878. }
  19879. const media = data.media;
  19880. this.media = media;
  19881. addEventListener(media, "waitingforkey", this.onWaitingForKey);
  19882. }
  19883. onMediaDetached() {
  19884. const media = this.media;
  19885. if (media) {
  19886. removeEventListener(media, "waitingforkey", this.onWaitingForKey);
  19887. this.media = null;
  19888. this.mediaKeys = null;
  19889. }
  19890. }
  19891. _clear() {
  19892. var _media$setMediaKeys;
  19893. this._requestLicenseFailureCount = 0;
  19894. this.keyIdToKeySessionPromise = {};
  19895. if (!this.mediaKeys && !this.mediaKeySessions.length) {
  19896. return;
  19897. }
  19898. const media = this.media;
  19899. const mediaKeysList = this.mediaKeySessions.slice();
  19900. this.mediaKeySessions = [];
  19901. this.mediaKeys = null;
  19902. LevelKey.clearKeyUriToKeyIdMap();
  19903. const keySessionCount = mediaKeysList.length;
  19904. _EMEController.CDMCleanupPromise = Promise.all(mediaKeysList.map((mediaKeySessionContext) => this.removeSession(mediaKeySessionContext)).concat(media == null ? void 0 : (_media$setMediaKeys = media.setMediaKeys(null)) == null ? void 0 : _media$setMediaKeys.catch((error) => {
  19905. var _this$hls2;
  19906. this.log(`Could not clear media keys: ${error}`);
  19907. (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.trigger(Events.ERROR, {
  19908. type: ErrorTypes.OTHER_ERROR,
  19909. details: ErrorDetails.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,
  19910. fatal: false,
  19911. error: new Error(`Could not clear media keys: ${error}`)
  19912. });
  19913. }))).catch((error) => {
  19914. var _this$hls3;
  19915. this.log(`Could not close sessions and clear media keys: ${error}`);
  19916. (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.trigger(Events.ERROR, {
  19917. type: ErrorTypes.OTHER_ERROR,
  19918. details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
  19919. fatal: false,
  19920. error: new Error(`Could not close sessions and clear media keys: ${error}`)
  19921. });
  19922. }).then(() => {
  19923. if (keySessionCount) {
  19924. this.log("finished closing key sessions and clearing media keys");
  19925. }
  19926. });
  19927. }
  19928. onManifestLoading() {
  19929. this.keyFormatPromise = null;
  19930. }
  19931. onManifestLoaded(event, {
  19932. sessionKeys
  19933. }) {
  19934. if (!sessionKeys || !this.config.emeEnabled) {
  19935. return;
  19936. }
  19937. if (!this.keyFormatPromise) {
  19938. const keyFormats = sessionKeys.reduce((formats, sessionKey) => {
  19939. if (formats.indexOf(sessionKey.keyFormat) === -1) {
  19940. formats.push(sessionKey.keyFormat);
  19941. }
  19942. return formats;
  19943. }, []);
  19944. this.log(`Selecting key-system from session-keys ${keyFormats.join(", ")}`);
  19945. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  19946. }
  19947. }
  19948. removeSession(mediaKeySessionContext) {
  19949. const {
  19950. mediaKeysSession,
  19951. licenseXhr
  19952. } = mediaKeySessionContext;
  19953. if (mediaKeysSession) {
  19954. this.log(`Remove licenses and keys and close session ${mediaKeysSession.sessionId}`);
  19955. if (mediaKeySessionContext._onmessage) {
  19956. mediaKeysSession.removeEventListener("message", mediaKeySessionContext._onmessage);
  19957. mediaKeySessionContext._onmessage = void 0;
  19958. }
  19959. if (mediaKeySessionContext._onkeystatuseschange) {
  19960. mediaKeysSession.removeEventListener("keystatuseschange", mediaKeySessionContext._onkeystatuseschange);
  19961. mediaKeySessionContext._onkeystatuseschange = void 0;
  19962. }
  19963. if (licenseXhr && licenseXhr.readyState !== XMLHttpRequest.DONE) {
  19964. licenseXhr.abort();
  19965. }
  19966. mediaKeySessionContext.mediaKeysSession = mediaKeySessionContext.decryptdata = mediaKeySessionContext.licenseXhr = void 0;
  19967. const index = this.mediaKeySessions.indexOf(mediaKeySessionContext);
  19968. if (index > -1) {
  19969. this.mediaKeySessions.splice(index, 1);
  19970. }
  19971. const {
  19972. drmSystemOptions
  19973. } = this.config;
  19974. const removePromise = isPersistentSessionType(drmSystemOptions) ? new Promise((resolve, reject) => {
  19975. self.setTimeout(() => reject(new Error(`MediaKeySession.remove() timeout`)), 8e3);
  19976. mediaKeysSession.remove().then(resolve);
  19977. }) : Promise.resolve();
  19978. return removePromise.catch((error) => {
  19979. var _this$hls4;
  19980. this.log(`Could not remove session: ${error}`);
  19981. (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.trigger(Events.ERROR, {
  19982. type: ErrorTypes.OTHER_ERROR,
  19983. details: ErrorDetails.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,
  19984. fatal: false,
  19985. error: new Error(`Could not remove session: ${error}`)
  19986. });
  19987. }).then(() => {
  19988. return mediaKeysSession.close();
  19989. }).catch((error) => {
  19990. var _this$hls5;
  19991. this.log(`Could not close session: ${error}`);
  19992. (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.trigger(Events.ERROR, {
  19993. type: ErrorTypes.OTHER_ERROR,
  19994. details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
  19995. fatal: false,
  19996. error: new Error(`Could not close session: ${error}`)
  19997. });
  19998. });
  19999. }
  20000. }
  20001. };
  20002. EMEController.CDMCleanupPromise = void 0;
  20003. var EMEKeyError = class extends Error {
  20004. constructor(data, message) {
  20005. super(message);
  20006. this.data = void 0;
  20007. data.error || (data.error = new Error(message));
  20008. this.data = data;
  20009. data.err = data.error;
  20010. }
  20011. };
  20012. var FPSController = class {
  20013. constructor(hls) {
  20014. this.hls = void 0;
  20015. this.isVideoPlaybackQualityAvailable = false;
  20016. this.timer = void 0;
  20017. this.media = null;
  20018. this.lastTime = void 0;
  20019. this.lastDroppedFrames = 0;
  20020. this.lastDecodedFrames = 0;
  20021. this.streamController = void 0;
  20022. this.hls = hls;
  20023. this.registerListeners();
  20024. }
  20025. setStreamController(streamController) {
  20026. this.streamController = streamController;
  20027. }
  20028. registerListeners() {
  20029. this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  20030. this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  20031. }
  20032. unregisterListeners() {
  20033. this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  20034. this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  20035. }
  20036. destroy() {
  20037. if (this.timer) {
  20038. clearInterval(this.timer);
  20039. }
  20040. this.unregisterListeners();
  20041. this.isVideoPlaybackQualityAvailable = false;
  20042. this.media = null;
  20043. }
  20044. onMediaAttaching(event, data) {
  20045. const config = this.hls.config;
  20046. if (config.capLevelOnFPSDrop) {
  20047. const media = data.media instanceof self.HTMLVideoElement ? data.media : null;
  20048. this.media = media;
  20049. if (media && typeof media.getVideoPlaybackQuality === "function") {
  20050. this.isVideoPlaybackQualityAvailable = true;
  20051. }
  20052. self.clearInterval(this.timer);
  20053. this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  20054. }
  20055. }
  20056. onMediaDetaching() {
  20057. this.media = null;
  20058. }
  20059. checkFPS(video, decodedFrames, droppedFrames) {
  20060. const currentTime = performance.now();
  20061. if (decodedFrames) {
  20062. if (this.lastTime) {
  20063. const currentPeriod = currentTime - this.lastTime;
  20064. const currentDropped = droppedFrames - this.lastDroppedFrames;
  20065. const currentDecoded = decodedFrames - this.lastDecodedFrames;
  20066. const droppedFPS = 1e3 * currentDropped / currentPeriod;
  20067. const hls = this.hls;
  20068. hls.trigger(Events.FPS_DROP, {
  20069. currentDropped,
  20070. currentDecoded,
  20071. totalDroppedFrames: droppedFrames
  20072. });
  20073. if (droppedFPS > 0) {
  20074. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  20075. let currentLevel = hls.currentLevel;
  20076. hls.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: " + currentLevel);
  20077. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  20078. currentLevel = currentLevel - 1;
  20079. hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {
  20080. level: currentLevel,
  20081. droppedLevel: hls.currentLevel
  20082. });
  20083. hls.autoLevelCapping = currentLevel;
  20084. this.streamController.nextLevelSwitch();
  20085. }
  20086. }
  20087. }
  20088. }
  20089. this.lastTime = currentTime;
  20090. this.lastDroppedFrames = droppedFrames;
  20091. this.lastDecodedFrames = decodedFrames;
  20092. }
  20093. }
  20094. checkFPSInterval() {
  20095. const video = this.media;
  20096. if (video) {
  20097. if (this.isVideoPlaybackQualityAvailable) {
  20098. const videoPlaybackQuality = video.getVideoPlaybackQuality();
  20099. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  20100. } else {
  20101. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  20102. }
  20103. }
  20104. }
  20105. };
  20106. function sendAddTrackEvent(track, videoEl) {
  20107. let event;
  20108. try {
  20109. event = new Event("addtrack");
  20110. } catch (err) {
  20111. event = document.createEvent("Event");
  20112. event.initEvent("addtrack", false, false);
  20113. }
  20114. event.track = track;
  20115. videoEl.dispatchEvent(event);
  20116. }
  20117. function addCueToTrack(track, cue) {
  20118. const mode = track.mode;
  20119. if (mode === "disabled") {
  20120. track.mode = "hidden";
  20121. }
  20122. if (track.cues && !track.cues.getCueById(cue.id)) {
  20123. try {
  20124. track.addCue(cue);
  20125. if (!track.cues.getCueById(cue.id)) {
  20126. throw new Error(`addCue is failed for: ${cue}`);
  20127. }
  20128. } catch (err) {
  20129. logger.debug(`[texttrack-utils]: ${err}`);
  20130. try {
  20131. const textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);
  20132. textTrackCue.id = cue.id;
  20133. track.addCue(textTrackCue);
  20134. } catch (err2) {
  20135. logger.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${err2}`);
  20136. }
  20137. }
  20138. }
  20139. if (mode === "disabled") {
  20140. track.mode = mode;
  20141. }
  20142. }
  20143. function clearCurrentCues(track, enterHandler) {
  20144. const mode = track.mode;
  20145. if (mode === "disabled") {
  20146. track.mode = "hidden";
  20147. }
  20148. if (track.cues) {
  20149. for (let i = track.cues.length; i--; ) {
  20150. if (enterHandler) {
  20151. track.cues[i].removeEventListener("enter", enterHandler);
  20152. }
  20153. track.removeCue(track.cues[i]);
  20154. }
  20155. }
  20156. if (mode === "disabled") {
  20157. track.mode = mode;
  20158. }
  20159. }
  20160. function removeCuesInRange(track, start, end, predicate) {
  20161. const mode = track.mode;
  20162. if (mode === "disabled") {
  20163. track.mode = "hidden";
  20164. }
  20165. if (track.cues && track.cues.length > 0) {
  20166. const cues = getCuesInRange(track.cues, start, end);
  20167. for (let i = 0; i < cues.length; i++) {
  20168. if (!predicate || predicate(cues[i])) {
  20169. track.removeCue(cues[i]);
  20170. }
  20171. }
  20172. }
  20173. if (mode === "disabled") {
  20174. track.mode = mode;
  20175. }
  20176. }
  20177. function getFirstCueIndexFromTime(cues, time) {
  20178. if (time <= cues[0].startTime) {
  20179. return 0;
  20180. }
  20181. const len = cues.length - 1;
  20182. if (time > cues[len].endTime) {
  20183. return -1;
  20184. }
  20185. let left = 0;
  20186. let right = len;
  20187. let mid;
  20188. while (left <= right) {
  20189. mid = Math.floor((right + left) / 2);
  20190. if (time < cues[mid].startTime) {
  20191. right = mid - 1;
  20192. } else if (time > cues[mid].startTime && left < len) {
  20193. left = mid + 1;
  20194. } else {
  20195. return mid;
  20196. }
  20197. }
  20198. return cues[left].startTime - time < time - cues[right].startTime ? left : right;
  20199. }
  20200. function getCuesInRange(cues, start, end) {
  20201. const cuesFound = [];
  20202. const firstCueInRange = getFirstCueIndexFromTime(cues, start);
  20203. if (firstCueInRange > -1) {
  20204. for (let i = firstCueInRange, len = cues.length; i < len; i++) {
  20205. const cue = cues[i];
  20206. if (cue.startTime >= start && cue.endTime <= end) {
  20207. cuesFound.push(cue);
  20208. } else if (cue.startTime > end) {
  20209. return cuesFound;
  20210. }
  20211. }
  20212. }
  20213. return cuesFound;
  20214. }
  20215. function filterSubtitleTracks(textTrackList) {
  20216. const tracks = [];
  20217. for (let i = 0; i < textTrackList.length; i++) {
  20218. const track = textTrackList[i];
  20219. if ((track.kind === "subtitles" || track.kind === "captions") && track.label) {
  20220. tracks.push(textTrackList[i]);
  20221. }
  20222. }
  20223. return tracks;
  20224. }
  20225. var SubtitleTrackController = class extends BasePlaylistController {
  20226. constructor(hls) {
  20227. super(hls, "subtitle-track-controller");
  20228. this.media = null;
  20229. this.tracks = [];
  20230. this.groupIds = null;
  20231. this.tracksInGroup = [];
  20232. this.trackId = -1;
  20233. this.currentTrack = null;
  20234. this.selectDefaultTrack = true;
  20235. this.queuedDefaultTrack = -1;
  20236. this.useTextTrackPolling = false;
  20237. this.subtitlePollingInterval = -1;
  20238. this._subtitleDisplay = true;
  20239. this.asyncPollTrackChange = () => this.pollTrackChange(0);
  20240. this.onTextTracksChanged = () => {
  20241. if (!this.useTextTrackPolling) {
  20242. self.clearInterval(this.subtitlePollingInterval);
  20243. }
  20244. if (!this.media || !this.hls.config.renderTextTracksNatively) {
  20245. return;
  20246. }
  20247. let textTrack = null;
  20248. const tracks = filterSubtitleTracks(this.media.textTracks);
  20249. for (let i = 0; i < tracks.length; i++) {
  20250. if (tracks[i].mode === "hidden") {
  20251. textTrack = tracks[i];
  20252. } else if (tracks[i].mode === "showing") {
  20253. textTrack = tracks[i];
  20254. break;
  20255. }
  20256. }
  20257. const trackId = this.findTrackForTextTrack(textTrack);
  20258. if (this.subtitleTrack !== trackId) {
  20259. this.setSubtitleTrack(trackId);
  20260. }
  20261. };
  20262. this.registerListeners();
  20263. }
  20264. destroy() {
  20265. this.unregisterListeners();
  20266. this.tracks.length = 0;
  20267. this.tracksInGroup.length = 0;
  20268. this.currentTrack = null;
  20269. this.onTextTracksChanged = this.asyncPollTrackChange = null;
  20270. super.destroy();
  20271. }
  20272. get subtitleDisplay() {
  20273. return this._subtitleDisplay;
  20274. }
  20275. set subtitleDisplay(value) {
  20276. this._subtitleDisplay = value;
  20277. if (this.trackId > -1) {
  20278. this.toggleTrackModes();
  20279. }
  20280. }
  20281. registerListeners() {
  20282. const {
  20283. hls
  20284. } = this;
  20285. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  20286. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  20287. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  20288. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  20289. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  20290. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  20291. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  20292. hls.on(Events.ERROR, this.onError, this);
  20293. }
  20294. unregisterListeners() {
  20295. const {
  20296. hls
  20297. } = this;
  20298. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  20299. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  20300. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  20301. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  20302. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  20303. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  20304. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  20305. hls.off(Events.ERROR, this.onError, this);
  20306. }
  20307. // Listen for subtitle track change, then extract the current track ID.
  20308. onMediaAttached(event, data) {
  20309. this.media = data.media;
  20310. if (!this.media) {
  20311. return;
  20312. }
  20313. if (this.queuedDefaultTrack > -1) {
  20314. this.subtitleTrack = this.queuedDefaultTrack;
  20315. this.queuedDefaultTrack = -1;
  20316. }
  20317. this.useTextTrackPolling = !(this.media.textTracks && "onchange" in this.media.textTracks);
  20318. if (this.useTextTrackPolling) {
  20319. this.pollTrackChange(500);
  20320. } else {
  20321. this.media.textTracks.addEventListener("change", this.asyncPollTrackChange);
  20322. }
  20323. }
  20324. pollTrackChange(timeout) {
  20325. self.clearInterval(this.subtitlePollingInterval);
  20326. this.subtitlePollingInterval = self.setInterval(this.onTextTracksChanged, timeout);
  20327. }
  20328. onMediaDetaching(event, data) {
  20329. const media = this.media;
  20330. if (!media) {
  20331. return;
  20332. }
  20333. const transferringMedia = !!data.transferMedia;
  20334. self.clearInterval(this.subtitlePollingInterval);
  20335. if (!this.useTextTrackPolling) {
  20336. media.textTracks.removeEventListener("change", this.asyncPollTrackChange);
  20337. }
  20338. if (this.trackId > -1) {
  20339. this.queuedDefaultTrack = this.trackId;
  20340. }
  20341. this.subtitleTrack = -1;
  20342. this.media = null;
  20343. if (transferringMedia) {
  20344. return;
  20345. }
  20346. const textTracks = filterSubtitleTracks(media.textTracks);
  20347. textTracks.forEach((track) => {
  20348. clearCurrentCues(track);
  20349. });
  20350. }
  20351. onManifestLoading() {
  20352. this.tracks = [];
  20353. this.groupIds = null;
  20354. this.tracksInGroup = [];
  20355. this.trackId = -1;
  20356. this.currentTrack = null;
  20357. this.selectDefaultTrack = true;
  20358. }
  20359. // Fired whenever a new manifest is loaded.
  20360. onManifestParsed(event, data) {
  20361. this.tracks = data.subtitleTracks;
  20362. }
  20363. onSubtitleTrackLoaded(event, data) {
  20364. const {
  20365. id,
  20366. groupId,
  20367. details
  20368. } = data;
  20369. const trackInActiveGroup = this.tracksInGroup[id];
  20370. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  20371. this.warn(`Subtitle track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
  20372. return;
  20373. }
  20374. const curDetails = trackInActiveGroup.details;
  20375. trackInActiveGroup.details = data.details;
  20376. this.log(`Subtitle track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
  20377. if (id === this.trackId) {
  20378. this.playlistLoaded(id, data, curDetails);
  20379. }
  20380. }
  20381. onLevelLoading(event, data) {
  20382. this.switchLevel(data.level);
  20383. }
  20384. onLevelSwitching(event, data) {
  20385. this.switchLevel(data.level);
  20386. }
  20387. switchLevel(levelIndex) {
  20388. const levelInfo = this.hls.levels[levelIndex];
  20389. if (!levelInfo) {
  20390. return;
  20391. }
  20392. const subtitleGroups = levelInfo.subtitleGroups || null;
  20393. const currentGroups = this.groupIds;
  20394. let currentTrack = this.currentTrack;
  20395. if (!subtitleGroups || (currentGroups == null ? void 0 : currentGroups.length) !== (subtitleGroups == null ? void 0 : subtitleGroups.length) || subtitleGroups != null && subtitleGroups.some((groupId) => (currentGroups == null ? void 0 : currentGroups.indexOf(groupId)) === -1)) {
  20396. this.groupIds = subtitleGroups;
  20397. this.trackId = -1;
  20398. this.currentTrack = null;
  20399. const subtitleTracks = this.tracks.filter((track) => !subtitleGroups || subtitleGroups.indexOf(track.groupId) !== -1);
  20400. if (subtitleTracks.length) {
  20401. if (this.selectDefaultTrack && !subtitleTracks.some((track) => track.default)) {
  20402. this.selectDefaultTrack = false;
  20403. }
  20404. subtitleTracks.forEach((track, i) => {
  20405. track.id = i;
  20406. });
  20407. } else if (!currentTrack && !this.tracksInGroup.length) {
  20408. return;
  20409. }
  20410. this.tracksInGroup = subtitleTracks;
  20411. const subtitlePreference = this.hls.config.subtitlePreference;
  20412. if (!currentTrack && subtitlePreference) {
  20413. this.selectDefaultTrack = false;
  20414. const groupIndex = findMatchingOption(subtitlePreference, subtitleTracks);
  20415. if (groupIndex > -1) {
  20416. currentTrack = subtitleTracks[groupIndex];
  20417. } else {
  20418. const allIndex = findMatchingOption(subtitlePreference, this.tracks);
  20419. currentTrack = this.tracks[allIndex];
  20420. }
  20421. }
  20422. let trackId = this.findTrackId(currentTrack);
  20423. if (trackId === -1 && currentTrack) {
  20424. trackId = this.findTrackId(null);
  20425. }
  20426. const subtitleTracksUpdated = {
  20427. subtitleTracks
  20428. };
  20429. this.log(`Updating subtitle tracks, ${subtitleTracks.length} track(s) found in "${subtitleGroups == null ? void 0 : subtitleGroups.join(",")}" group-id`);
  20430. this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);
  20431. if (trackId !== -1 && this.trackId === -1) {
  20432. this.setSubtitleTrack(trackId);
  20433. }
  20434. }
  20435. }
  20436. findTrackId(currentTrack) {
  20437. const tracks = this.tracksInGroup;
  20438. const selectDefault = this.selectDefaultTrack;
  20439. for (let i = 0; i < tracks.length; i++) {
  20440. const track = tracks[i];
  20441. if (selectDefault && !track.default || !selectDefault && !currentTrack) {
  20442. continue;
  20443. }
  20444. if (!currentTrack || matchesOption(track, currentTrack)) {
  20445. return i;
  20446. }
  20447. }
  20448. if (currentTrack) {
  20449. for (let i = 0; i < tracks.length; i++) {
  20450. const track = tracks[i];
  20451. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE", "ASSOC-LANGUAGE", "CHARACTERISTICS"])) {
  20452. return i;
  20453. }
  20454. }
  20455. for (let i = 0; i < tracks.length; i++) {
  20456. const track = tracks[i];
  20457. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE"])) {
  20458. return i;
  20459. }
  20460. }
  20461. }
  20462. return -1;
  20463. }
  20464. findTrackForTextTrack(textTrack) {
  20465. if (textTrack) {
  20466. const tracks = this.tracksInGroup;
  20467. for (let i = 0; i < tracks.length; i++) {
  20468. const track = tracks[i];
  20469. if (subtitleTrackMatchesTextTrack(track, textTrack)) {
  20470. return i;
  20471. }
  20472. }
  20473. }
  20474. return -1;
  20475. }
  20476. onError(event, data) {
  20477. if (data.fatal || !data.context) {
  20478. return;
  20479. }
  20480. if (data.context.type === PlaylistContextType.SUBTITLE_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  20481. this.checkRetry(data);
  20482. }
  20483. }
  20484. get allSubtitleTracks() {
  20485. return this.tracks;
  20486. }
  20487. /** get alternate subtitle tracks list from playlist **/
  20488. get subtitleTracks() {
  20489. return this.tracksInGroup;
  20490. }
  20491. /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/
  20492. get subtitleTrack() {
  20493. return this.trackId;
  20494. }
  20495. set subtitleTrack(newId) {
  20496. this.selectDefaultTrack = false;
  20497. this.setSubtitleTrack(newId);
  20498. }
  20499. setSubtitleOption(subtitleOption) {
  20500. this.hls.config.subtitlePreference = subtitleOption;
  20501. if (subtitleOption) {
  20502. if (subtitleOption.id === -1) {
  20503. this.setSubtitleTrack(-1);
  20504. return null;
  20505. }
  20506. const allSubtitleTracks = this.allSubtitleTracks;
  20507. this.selectDefaultTrack = false;
  20508. if (allSubtitleTracks.length) {
  20509. const currentTrack = this.currentTrack;
  20510. if (currentTrack && matchesOption(subtitleOption, currentTrack)) {
  20511. return currentTrack;
  20512. }
  20513. const groupIndex = findMatchingOption(subtitleOption, this.tracksInGroup);
  20514. if (groupIndex > -1) {
  20515. const track = this.tracksInGroup[groupIndex];
  20516. this.setSubtitleTrack(groupIndex);
  20517. return track;
  20518. } else if (currentTrack) {
  20519. return null;
  20520. } else {
  20521. const allIndex = findMatchingOption(subtitleOption, allSubtitleTracks);
  20522. if (allIndex > -1) {
  20523. return allSubtitleTracks[allIndex];
  20524. }
  20525. }
  20526. }
  20527. }
  20528. return null;
  20529. }
  20530. loadPlaylist(hlsUrlParameters) {
  20531. super.loadPlaylist();
  20532. if (this.shouldLoadPlaylist(this.currentTrack)) {
  20533. this.scheduleLoading(this.currentTrack, hlsUrlParameters);
  20534. }
  20535. }
  20536. loadingPlaylist(currentTrack, hlsUrlParameters) {
  20537. super.loadingPlaylist(currentTrack, hlsUrlParameters);
  20538. const id = currentTrack.id;
  20539. const groupId = currentTrack.groupId;
  20540. const url = this.getUrlWithDirectives(currentTrack.url, hlsUrlParameters);
  20541. const details = currentTrack.details;
  20542. const age = details == null ? void 0 : details.age;
  20543. this.log(`Loading subtitle ${id} "${currentTrack.name}" lang:${currentTrack.lang} group:${groupId}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== void 0 ? " at sn " + hlsUrlParameters.msn + " part " + hlsUrlParameters.part : ""}${age && details.live ? " age " + age.toFixed(1) + (details.type ? " " + details.type || "" : "") : ""} ${url}`);
  20544. this.hls.trigger(Events.SUBTITLE_TRACK_LOADING, {
  20545. url,
  20546. id,
  20547. groupId,
  20548. deliveryDirectives: hlsUrlParameters || null,
  20549. track: currentTrack
  20550. });
  20551. }
  20552. /**
  20553. * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
  20554. * This operates on the DOM textTracks.
  20555. * A value of -1 will disable all subtitle tracks.
  20556. */
  20557. toggleTrackModes() {
  20558. const {
  20559. media
  20560. } = this;
  20561. if (!media) {
  20562. return;
  20563. }
  20564. const textTracks = filterSubtitleTracks(media.textTracks);
  20565. const currentTrack = this.currentTrack;
  20566. let nextTrack;
  20567. if (currentTrack) {
  20568. nextTrack = textTracks.filter((textTrack) => subtitleTrackMatchesTextTrack(currentTrack, textTrack))[0];
  20569. if (!nextTrack) {
  20570. this.warn(`Unable to find subtitle TextTrack with name "${currentTrack.name}" and language "${currentTrack.lang}"`);
  20571. }
  20572. }
  20573. [].slice.call(textTracks).forEach((track) => {
  20574. if (track.mode !== "disabled" && track !== nextTrack) {
  20575. track.mode = "disabled";
  20576. }
  20577. });
  20578. if (nextTrack) {
  20579. const mode = this.subtitleDisplay ? "showing" : "hidden";
  20580. if (nextTrack.mode !== mode) {
  20581. nextTrack.mode = mode;
  20582. }
  20583. }
  20584. }
  20585. /**
  20586. * This method is responsible for validating the subtitle index and periodically reloading if live.
  20587. * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
  20588. */
  20589. setSubtitleTrack(newId) {
  20590. const tracks = this.tracksInGroup;
  20591. if (!this.media) {
  20592. this.queuedDefaultTrack = newId;
  20593. return;
  20594. }
  20595. if (newId < -1 || newId >= tracks.length || !isFiniteNumber(newId)) {
  20596. this.warn(`Invalid subtitle track id: ${newId}`);
  20597. return;
  20598. }
  20599. this.selectDefaultTrack = false;
  20600. const lastTrack = this.currentTrack;
  20601. const track = tracks[newId] || null;
  20602. this.trackId = newId;
  20603. this.currentTrack = track;
  20604. this.toggleTrackModes();
  20605. if (!track) {
  20606. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  20607. id: newId
  20608. });
  20609. return;
  20610. }
  20611. const trackLoaded = !!track.details && !track.details.live;
  20612. if (newId === this.trackId && track === lastTrack && trackLoaded) {
  20613. return;
  20614. }
  20615. this.log(`Switching to subtitle-track ${newId}` + (track ? ` "${track.name}" lang:${track.lang} group:${track.groupId}` : ""));
  20616. const {
  20617. id,
  20618. groupId = "",
  20619. name,
  20620. type,
  20621. url
  20622. } = track;
  20623. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  20624. id,
  20625. groupId,
  20626. name,
  20627. type,
  20628. url
  20629. });
  20630. const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
  20631. this.loadPlaylist(hlsUrlParameters);
  20632. }
  20633. };
  20634. function uuid() {
  20635. try {
  20636. return crypto.randomUUID();
  20637. } catch (error) {
  20638. try {
  20639. const url = URL.createObjectURL(new Blob());
  20640. const uuid2 = url.toString();
  20641. URL.revokeObjectURL(url);
  20642. return uuid2.slice(uuid2.lastIndexOf("/") + 1);
  20643. } catch (error2) {
  20644. let dt = (/* @__PURE__ */ new Date()).getTime();
  20645. const uuid2 = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
  20646. const r = (dt + Math.random() * 16) % 16 | 0;
  20647. dt = Math.floor(dt / 16);
  20648. return (c == "x" ? r : r & 3 | 8).toString(16);
  20649. });
  20650. return uuid2;
  20651. }
  20652. }
  20653. }
  20654. function hash(text) {
  20655. let hash2 = 5381;
  20656. let i = text.length;
  20657. while (i) {
  20658. hash2 = hash2 * 33 ^ text.charCodeAt(--i);
  20659. }
  20660. return (hash2 >>> 0).toString();
  20661. }
  20662. var ALIGNED_END_THRESHOLD_SECONDS = 0.025;
  20663. var TimelineOccupancy = function(TimelineOccupancy2) {
  20664. TimelineOccupancy2[TimelineOccupancy2["Point"] = 0] = "Point";
  20665. TimelineOccupancy2[TimelineOccupancy2["Range"] = 1] = "Range";
  20666. return TimelineOccupancy2;
  20667. }({});
  20668. function generateAssetIdentifier(interstitial, uri, assetListIndex) {
  20669. return `${interstitial.identifier}-${assetListIndex + 1}-${hash(uri)}`;
  20670. }
  20671. var InterstitialEvent = class {
  20672. constructor(dateRange, base) {
  20673. this.base = void 0;
  20674. this._duration = null;
  20675. this._timelineStart = null;
  20676. this.appendInPlaceDisabled = void 0;
  20677. this.appendInPlaceStarted = void 0;
  20678. this.dateRange = void 0;
  20679. this.hasPlayed = false;
  20680. this.cumulativeDuration = 0;
  20681. this.resumeOffset = NaN;
  20682. this.playoutLimit = NaN;
  20683. this.restrictions = {
  20684. skip: false,
  20685. jump: false
  20686. };
  20687. this.snapOptions = {
  20688. out: false,
  20689. in: false
  20690. };
  20691. this.assetList = [];
  20692. this.assetListLoader = void 0;
  20693. this.assetListResponse = null;
  20694. this.resumeAnchor = void 0;
  20695. this.error = void 0;
  20696. this.resetOnResume = void 0;
  20697. this.base = base;
  20698. this.dateRange = dateRange;
  20699. this.setDateRange(dateRange);
  20700. }
  20701. setDateRange(dateRange) {
  20702. this.dateRange = dateRange;
  20703. this.resumeOffset = dateRange.attr.optionalFloat("X-RESUME-OFFSET", this.resumeOffset);
  20704. this.playoutLimit = dateRange.attr.optionalFloat("X-PLAYOUT-LIMIT", this.playoutLimit);
  20705. this.restrictions = dateRange.attr.enumeratedStringList("X-RESTRICT", this.restrictions);
  20706. this.snapOptions = dateRange.attr.enumeratedStringList("X-SNAP", this.snapOptions);
  20707. }
  20708. reset() {
  20709. var _this$assetListLoader;
  20710. this.appendInPlaceStarted = false;
  20711. (_this$assetListLoader = this.assetListLoader) == null ? void 0 : _this$assetListLoader.destroy();
  20712. this.assetListLoader = void 0;
  20713. if (!this.supplementsPrimary) {
  20714. this.assetListResponse = null;
  20715. this.assetList = [];
  20716. this._duration = null;
  20717. }
  20718. }
  20719. isAssetPastPlayoutLimit(assetIndex) {
  20720. var _this$assetList$asset;
  20721. if (assetIndex > 0 && assetIndex >= this.assetList.length) {
  20722. return true;
  20723. }
  20724. const playoutLimit = this.playoutLimit;
  20725. if (assetIndex <= 0 || isNaN(playoutLimit)) {
  20726. return false;
  20727. }
  20728. if (playoutLimit === 0) {
  20729. return true;
  20730. }
  20731. const assetOffset = ((_this$assetList$asset = this.assetList[assetIndex]) == null ? void 0 : _this$assetList$asset.startOffset) || 0;
  20732. return assetOffset > playoutLimit;
  20733. }
  20734. findAssetIndex(asset) {
  20735. const index = this.assetList.indexOf(asset);
  20736. return index;
  20737. }
  20738. get identifier() {
  20739. return this.dateRange.id;
  20740. }
  20741. get startDate() {
  20742. return this.dateRange.startDate;
  20743. }
  20744. get startTime() {
  20745. const startTime = this.dateRange.startTime;
  20746. if (this.snapOptions.out) {
  20747. const frag = this.dateRange.tagAnchor;
  20748. if (frag) {
  20749. return getSnapToFragmentTime(startTime, frag);
  20750. }
  20751. }
  20752. return startTime;
  20753. }
  20754. get startOffset() {
  20755. return this.cue.pre ? 0 : this.startTime;
  20756. }
  20757. get startIsAligned() {
  20758. if (this.startTime === 0 || this.snapOptions.out) {
  20759. return true;
  20760. }
  20761. const frag = this.dateRange.tagAnchor;
  20762. if (frag) {
  20763. const startTime = this.dateRange.startTime;
  20764. const snappedStart = getSnapToFragmentTime(startTime, frag);
  20765. return startTime - snappedStart < 0.1;
  20766. }
  20767. return false;
  20768. }
  20769. get resumptionOffset() {
  20770. const resumeOffset = this.resumeOffset;
  20771. const offset = isFiniteNumber(resumeOffset) ? resumeOffset : this.duration;
  20772. return this.cumulativeDuration + offset;
  20773. }
  20774. get resumeTime() {
  20775. const resumeTime = this.startOffset + this.resumptionOffset;
  20776. if (this.snapOptions.in) {
  20777. const frag = this.resumeAnchor;
  20778. if (frag) {
  20779. return getSnapToFragmentTime(resumeTime, frag);
  20780. }
  20781. }
  20782. return resumeTime;
  20783. }
  20784. get appendInPlace() {
  20785. if (this.appendInPlaceStarted) {
  20786. return true;
  20787. }
  20788. if (this.appendInPlaceDisabled) {
  20789. return false;
  20790. }
  20791. if (!this.cue.once && !this.cue.pre && // preroll starts at startPosition before startPosition is known (live)
  20792. this.startIsAligned && (isNaN(this.playoutLimit) && isNaN(this.resumeOffset) || this.resumeOffset && this.duration && Math.abs(this.resumeOffset - this.duration) < ALIGNED_END_THRESHOLD_SECONDS)) {
  20793. return true;
  20794. }
  20795. return false;
  20796. }
  20797. set appendInPlace(value) {
  20798. if (this.appendInPlaceStarted) {
  20799. this.resetOnResume = !value;
  20800. return;
  20801. }
  20802. this.appendInPlaceDisabled = !value;
  20803. }
  20804. // Extended timeline start time
  20805. get timelineStart() {
  20806. if (this._timelineStart !== null) {
  20807. return this._timelineStart;
  20808. }
  20809. return this.startTime;
  20810. }
  20811. set timelineStart(value) {
  20812. this._timelineStart = value;
  20813. }
  20814. get duration() {
  20815. const playoutLimit = this.playoutLimit;
  20816. let duration;
  20817. if (this._duration !== null) {
  20818. duration = this._duration;
  20819. } else if (this.dateRange.duration) {
  20820. duration = this.dateRange.duration;
  20821. } else {
  20822. duration = this.dateRange.plannedDuration || 0;
  20823. }
  20824. if (!isNaN(playoutLimit) && playoutLimit < duration) {
  20825. duration = playoutLimit;
  20826. }
  20827. return duration;
  20828. }
  20829. set duration(value) {
  20830. this._duration = value;
  20831. }
  20832. get cue() {
  20833. return this.dateRange.cue;
  20834. }
  20835. get timelineOccupancy() {
  20836. if (this.dateRange.attr["X-TIMELINE-OCCUPIES"] === "RANGE") {
  20837. return TimelineOccupancy.Range;
  20838. }
  20839. return TimelineOccupancy.Point;
  20840. }
  20841. get supplementsPrimary() {
  20842. return this.dateRange.attr["X-TIMELINE-STYLE"] === "PRIMARY";
  20843. }
  20844. get contentMayVary() {
  20845. return this.dateRange.attr["X-CONTENT-MAY-VARY"] !== "NO";
  20846. }
  20847. get assetUrl() {
  20848. return this.dateRange.attr["X-ASSET-URI"];
  20849. }
  20850. get assetListUrl() {
  20851. return this.dateRange.attr["X-ASSET-LIST"];
  20852. }
  20853. get baseUrl() {
  20854. return this.base.url;
  20855. }
  20856. get assetListLoaded() {
  20857. return this.assetList.length > 0 || this.assetListResponse !== null;
  20858. }
  20859. toString() {
  20860. return eventToString(this);
  20861. }
  20862. };
  20863. function getSnapToFragmentTime(time, frag) {
  20864. return time - frag.start < frag.duration / 2 && !(Math.abs(time - (frag.start + frag.duration)) < ALIGNED_END_THRESHOLD_SECONDS) ? frag.start : frag.start + frag.duration;
  20865. }
  20866. function getInterstitialUrl(uri, sessionId, baseUrl) {
  20867. const url = new self.URL(uri, baseUrl);
  20868. if (url.protocol !== "data:") {
  20869. url.searchParams.set("_HLS_primary_id", sessionId);
  20870. }
  20871. return url;
  20872. }
  20873. function getNextAssetIndex(interstitial, assetListIndex) {
  20874. while ((_interstitial$assetLi = interstitial.assetList[++assetListIndex]) != null && _interstitial$assetLi.error) {
  20875. var _interstitial$assetLi;
  20876. }
  20877. return assetListIndex;
  20878. }
  20879. function eventToString(interstitial) {
  20880. return `["${interstitial.identifier}" ${interstitial.cue.pre ? "<pre>" : interstitial.cue.post ? "<post>" : ""}${interstitial.timelineStart.toFixed(2)}-${interstitial.resumeTime.toFixed(2)}]`;
  20881. }
  20882. function eventAssetToString(asset) {
  20883. const start = asset.timelineStart;
  20884. const duration = asset.duration || 0;
  20885. return `["${asset.identifier}" ${start.toFixed(2)}-${(start + duration).toFixed(2)}]`;
  20886. }
  20887. var HlsAssetPlayer = class {
  20888. constructor(HlsPlayerClass, userConfig, interstitial, assetItem) {
  20889. this.hls = void 0;
  20890. this.interstitial = void 0;
  20891. this.assetItem = void 0;
  20892. this.tracks = null;
  20893. this.hasDetails = false;
  20894. this.mediaAttached = null;
  20895. this._currentTime = void 0;
  20896. this._bufferedEosTime = void 0;
  20897. this.checkPlayout = () => {
  20898. if (this.reachedPlayout(this.currentTime)) {
  20899. this.hls.trigger(Events.PLAYOUT_LIMIT_REACHED, {});
  20900. }
  20901. };
  20902. const hls = this.hls = new HlsPlayerClass(userConfig);
  20903. this.interstitial = interstitial;
  20904. this.assetItem = assetItem;
  20905. let uri = assetItem.uri;
  20906. try {
  20907. uri = getInterstitialUrl(uri, userConfig.primarySessionId).href;
  20908. } catch (error) {
  20909. }
  20910. hls.loadSource(uri);
  20911. const detailsLoaded = () => {
  20912. this.hasDetails = true;
  20913. };
  20914. hls.once(Events.LEVEL_LOADED, detailsLoaded);
  20915. hls.once(Events.AUDIO_TRACK_LOADED, detailsLoaded);
  20916. hls.once(Events.SUBTITLE_TRACK_LOADED, detailsLoaded);
  20917. hls.on(Events.MEDIA_ATTACHING, (name, {
  20918. media
  20919. }) => {
  20920. this.removeMediaListeners();
  20921. this.mediaAttached = media;
  20922. const event = this.interstitial;
  20923. if (event.playoutLimit) {
  20924. media.addEventListener("timeupdate", this.checkPlayout);
  20925. if (this.appendInPlace) {
  20926. hls.on(Events.BUFFER_APPENDED, () => {
  20927. const bufferedEnd = this.bufferedEnd;
  20928. if (this.reachedPlayout(bufferedEnd)) {
  20929. this._bufferedEosTime = bufferedEnd;
  20930. hls.trigger(Events.BUFFERED_TO_END, void 0);
  20931. }
  20932. });
  20933. }
  20934. }
  20935. });
  20936. }
  20937. get appendInPlace() {
  20938. var _this$interstitial;
  20939. return ((_this$interstitial = this.interstitial) == null ? void 0 : _this$interstitial.appendInPlace) || false;
  20940. }
  20941. bufferedInPlaceToEnd(media) {
  20942. var _this$hls;
  20943. if (!this.appendInPlace) {
  20944. return false;
  20945. }
  20946. if ((_this$hls = this.hls) != null && _this$hls.bufferedToEnd) {
  20947. return true;
  20948. }
  20949. if (!media || !this._bufferedEosTime) {
  20950. return false;
  20951. }
  20952. const start = this.timelineOffset;
  20953. const bufferInfo = BufferHelper.bufferInfo(media, start, 0);
  20954. const bufferedEnd = this.getAssetTime(bufferInfo.end);
  20955. return bufferedEnd >= this._bufferedEosTime - 0.02;
  20956. }
  20957. reachedPlayout(time) {
  20958. const interstitial = this.interstitial;
  20959. const playoutLimit = interstitial.playoutLimit;
  20960. return this.startOffset + time >= playoutLimit;
  20961. }
  20962. get destroyed() {
  20963. var _this$hls2;
  20964. return !((_this$hls2 = this.hls) != null && _this$hls2.userConfig);
  20965. }
  20966. get assetId() {
  20967. return this.assetItem.identifier;
  20968. }
  20969. get interstitialId() {
  20970. return this.assetItem.parentIdentifier;
  20971. }
  20972. get media() {
  20973. var _this$hls3;
  20974. return ((_this$hls3 = this.hls) == null ? void 0 : _this$hls3.media) || null;
  20975. }
  20976. get bufferedEnd() {
  20977. const media = this.media || this.mediaAttached;
  20978. if (!media) {
  20979. if (this._bufferedEosTime) {
  20980. return this._bufferedEosTime;
  20981. }
  20982. return this.currentTime;
  20983. }
  20984. const bufferInfo = BufferHelper.bufferInfo(media, media.currentTime, 1e-3);
  20985. return this.getAssetTime(bufferInfo.end);
  20986. }
  20987. get currentTime() {
  20988. const media = this.media || this.mediaAttached;
  20989. if (!media) {
  20990. return this._currentTime || 0;
  20991. }
  20992. return this.getAssetTime(media.currentTime);
  20993. }
  20994. get duration() {
  20995. const duration = this.assetItem.duration;
  20996. if (!duration) {
  20997. return 0;
  20998. }
  20999. return duration;
  21000. }
  21001. get remaining() {
  21002. const duration = this.duration;
  21003. if (!duration) {
  21004. return 0;
  21005. }
  21006. return Math.max(0, duration - this.currentTime);
  21007. }
  21008. get startOffset() {
  21009. return this.assetItem.startOffset;
  21010. }
  21011. get timelineOffset() {
  21012. var _this$hls4;
  21013. return ((_this$hls4 = this.hls) == null ? void 0 : _this$hls4.config.timelineOffset) || 0;
  21014. }
  21015. set timelineOffset(value) {
  21016. const timelineOffset = this.timelineOffset;
  21017. if (value !== timelineOffset) {
  21018. const diff = value - timelineOffset;
  21019. if (Math.abs(diff) > 1 / 9e4) {
  21020. if (this.hasDetails) {
  21021. throw new Error(`Cannot set timelineOffset after playlists are loaded`);
  21022. }
  21023. this.hls.config.timelineOffset = value;
  21024. }
  21025. }
  21026. }
  21027. getAssetTime(time) {
  21028. const timelineOffset = this.timelineOffset;
  21029. const duration = this.duration;
  21030. return Math.min(Math.max(0, time - timelineOffset), duration);
  21031. }
  21032. removeMediaListeners() {
  21033. const media = this.mediaAttached;
  21034. if (media) {
  21035. this._currentTime = media.currentTime;
  21036. this.bufferSnapShot();
  21037. media.removeEventListener("timeupdate", this.checkPlayout);
  21038. }
  21039. }
  21040. bufferSnapShot() {
  21041. if (this.mediaAttached) {
  21042. var _this$hls5;
  21043. if ((_this$hls5 = this.hls) != null && _this$hls5.bufferedToEnd) {
  21044. this._bufferedEosTime = this.bufferedEnd;
  21045. }
  21046. }
  21047. }
  21048. destroy() {
  21049. this.removeMediaListeners();
  21050. this.hls.destroy();
  21051. this.hls = this.interstitial = null;
  21052. this.tracks = this.mediaAttached = this.checkPlayout = null;
  21053. }
  21054. attachMedia(data) {
  21055. this.hls.attachMedia(data);
  21056. }
  21057. detachMedia() {
  21058. this.removeMediaListeners();
  21059. this.mediaAttached = null;
  21060. this.hls.detachMedia();
  21061. }
  21062. resumeBuffering() {
  21063. this.hls.resumeBuffering();
  21064. }
  21065. pauseBuffering() {
  21066. this.hls.pauseBuffering();
  21067. }
  21068. transferMedia() {
  21069. this.bufferSnapShot();
  21070. return this.hls.transferMedia();
  21071. }
  21072. resetDetails() {
  21073. const hls = this.hls;
  21074. if (this.hasDetails) {
  21075. hls.stopLoad();
  21076. const deleteDetails = (obj) => delete obj.details;
  21077. hls.levels.forEach(deleteDetails);
  21078. hls.allAudioTracks.forEach(deleteDetails);
  21079. hls.allSubtitleTracks.forEach(deleteDetails);
  21080. this.hasDetails = false;
  21081. }
  21082. }
  21083. on(event, listener, context) {
  21084. this.hls.on(event, listener);
  21085. }
  21086. once(event, listener, context) {
  21087. this.hls.once(event, listener);
  21088. }
  21089. off(event, listener, context) {
  21090. this.hls.off(event, listener);
  21091. }
  21092. toString() {
  21093. var _this$hls6;
  21094. return `HlsAssetPlayer: ${eventAssetToString(this.assetItem)} ${(_this$hls6 = this.hls) == null ? void 0 : _this$hls6.sessionId} ${this.appendInPlace ? "append-in-place" : ""}`;
  21095. }
  21096. };
  21097. var ABUTTING_THRESHOLD_SECONDS = 0.033;
  21098. var InterstitialsSchedule = class extends Logger {
  21099. constructor(onScheduleUpdate, logger2) {
  21100. super("interstitials-sched", logger2);
  21101. this.onScheduleUpdate = void 0;
  21102. this.eventMap = {};
  21103. this.events = null;
  21104. this.items = null;
  21105. this.durations = {
  21106. primary: 0,
  21107. playout: 0,
  21108. integrated: 0
  21109. };
  21110. this.onScheduleUpdate = onScheduleUpdate;
  21111. }
  21112. destroy() {
  21113. this.reset();
  21114. this.onScheduleUpdate = null;
  21115. }
  21116. reset() {
  21117. this.eventMap = {};
  21118. this.setDurations(0, 0, 0);
  21119. if (this.events) {
  21120. this.events.forEach((interstitial) => interstitial.reset());
  21121. }
  21122. this.events = this.items = null;
  21123. }
  21124. resetErrorsInRange(start, end) {
  21125. if (this.events) {
  21126. return this.events.reduce((count, interstitial) => {
  21127. if (start <= interstitial.startOffset && end > interstitial.startOffset) {
  21128. delete interstitial.error;
  21129. return count + 1;
  21130. }
  21131. return count;
  21132. }, 0);
  21133. }
  21134. return 0;
  21135. }
  21136. get duration() {
  21137. const items = this.items;
  21138. return items ? items[items.length - 1].end : 0;
  21139. }
  21140. get length() {
  21141. return this.items ? this.items.length : 0;
  21142. }
  21143. getEvent(identifier) {
  21144. return identifier ? this.eventMap[identifier] || null : null;
  21145. }
  21146. hasEvent(identifier) {
  21147. return identifier in this.eventMap;
  21148. }
  21149. findItemIndex(item, time) {
  21150. if (item.event) {
  21151. return this.findEventIndex(item.event.identifier);
  21152. }
  21153. let index = -1;
  21154. if (item.nextEvent) {
  21155. index = this.findEventIndex(item.nextEvent.identifier) - 1;
  21156. } else if (item.previousEvent) {
  21157. index = this.findEventIndex(item.previousEvent.identifier) + 1;
  21158. }
  21159. const items = this.items;
  21160. if (items) {
  21161. if (!items[index]) {
  21162. if (time === void 0) {
  21163. time = item.start;
  21164. }
  21165. index = this.findItemIndexAtTime(time);
  21166. }
  21167. while (index >= 0 && (_items$index = items[index]) != null && _items$index.event) {
  21168. var _items$index;
  21169. index--;
  21170. }
  21171. }
  21172. return index;
  21173. }
  21174. findItemIndexAtTime(timelinePos, timelineType) {
  21175. const items = this.items;
  21176. if (items) {
  21177. for (let i = 0; i < items.length; i++) {
  21178. let timeRange = items[i];
  21179. if (timelineType && timelineType !== "primary") {
  21180. timeRange = timeRange[timelineType];
  21181. }
  21182. if (timelinePos === timeRange.start || timelinePos > timeRange.start && timelinePos < timeRange.end) {
  21183. return i;
  21184. }
  21185. }
  21186. }
  21187. return -1;
  21188. }
  21189. findJumpRestrictedIndex(startIndex, endIndex) {
  21190. const items = this.items;
  21191. if (items) {
  21192. for (let i = startIndex; i <= endIndex; i++) {
  21193. if (!items[i]) {
  21194. break;
  21195. }
  21196. const event = items[i].event;
  21197. if (event != null && event.restrictions.jump && !event.appendInPlace) {
  21198. return i;
  21199. }
  21200. }
  21201. }
  21202. return -1;
  21203. }
  21204. findEventIndex(identifier) {
  21205. const items = this.items;
  21206. if (items) {
  21207. for (let i = items.length; i--; ) {
  21208. var _items$i$event;
  21209. if (((_items$i$event = items[i].event) == null ? void 0 : _items$i$event.identifier) === identifier) {
  21210. return i;
  21211. }
  21212. }
  21213. }
  21214. return -1;
  21215. }
  21216. findAssetIndex(event, timelinePos) {
  21217. const assetList = event.assetList;
  21218. const length = assetList.length;
  21219. if (length > 1) {
  21220. for (let i = 0; i < length; i++) {
  21221. const asset = assetList[i];
  21222. if (!asset.error) {
  21223. const timelineStart = asset.timelineStart;
  21224. if (timelinePos === timelineStart || timelinePos > timelineStart && timelinePos < timelineStart + (asset.duration || 0)) {
  21225. return i;
  21226. }
  21227. }
  21228. }
  21229. }
  21230. return 0;
  21231. }
  21232. get assetIdAtEnd() {
  21233. var _this$items, _this$items2;
  21234. const interstitialAtEnd = (_this$items = this.items) == null ? void 0 : (_this$items2 = _this$items[this.length - 1]) == null ? void 0 : _this$items2.event;
  21235. if (interstitialAtEnd) {
  21236. const assetList = interstitialAtEnd.assetList;
  21237. const assetAtEnd = assetList[assetList.length - 1];
  21238. if (assetAtEnd) {
  21239. return assetAtEnd.identifier;
  21240. }
  21241. }
  21242. return null;
  21243. }
  21244. parseInterstitialDateRanges(mediaSelection, enableAppendInPlace) {
  21245. const details = mediaSelection.main.details;
  21246. const {
  21247. dateRanges
  21248. } = details;
  21249. const previousInterstitialEvents = this.events;
  21250. const interstitialEvents = this.parseDateRanges(dateRanges, {
  21251. url: details.url
  21252. }, enableAppendInPlace);
  21253. const ids = Object.keys(dateRanges);
  21254. const removedInterstitials = previousInterstitialEvents ? previousInterstitialEvents.filter((event) => !ids.includes(event.identifier)) : [];
  21255. if (interstitialEvents.length) {
  21256. interstitialEvents.sort((a, b) => {
  21257. const aPre = a.cue.pre;
  21258. const aPost = a.cue.post;
  21259. const bPre = b.cue.pre;
  21260. const bPost = b.cue.post;
  21261. if (aPre && !bPre) {
  21262. return -1;
  21263. }
  21264. if (bPre && !aPre) {
  21265. return 1;
  21266. }
  21267. if (aPost && !bPost) {
  21268. return 1;
  21269. }
  21270. if (bPost && !aPost) {
  21271. return -1;
  21272. }
  21273. if (!aPre && !bPre && !aPost && !bPost) {
  21274. const startA = a.startTime;
  21275. const startB = b.startTime;
  21276. if (startA !== startB) {
  21277. return startA - startB;
  21278. }
  21279. }
  21280. return a.dateRange.tagOrder - b.dateRange.tagOrder;
  21281. });
  21282. }
  21283. this.events = interstitialEvents;
  21284. removedInterstitials.forEach((interstitial) => {
  21285. this.removeEvent(interstitial);
  21286. });
  21287. this.updateSchedule(mediaSelection, removedInterstitials);
  21288. }
  21289. updateSchedule(mediaSelection, removedInterstitials = []) {
  21290. const events = this.events || [];
  21291. if (events.length || removedInterstitials.length || this.length < 2) {
  21292. const currentItems = this.items;
  21293. const updatedItems = this.parseSchedule(events, mediaSelection);
  21294. const updated = removedInterstitials.length || (currentItems == null ? void 0 : currentItems.length) !== updatedItems.length || updatedItems.some((item, i) => {
  21295. return Math.abs(item.playout.start - currentItems[i].playout.start) > 5e-3 || Math.abs(item.playout.end - currentItems[i].playout.end) > 5e-3;
  21296. });
  21297. if (updated) {
  21298. this.items = updatedItems;
  21299. this.onScheduleUpdate(removedInterstitials, currentItems);
  21300. }
  21301. }
  21302. }
  21303. parseDateRanges(dateRanges, baseData, enableAppendInPlace) {
  21304. const interstitialEvents = [];
  21305. const ids = Object.keys(dateRanges);
  21306. for (let i = 0; i < ids.length; i++) {
  21307. const id = ids[i];
  21308. const dateRange = dateRanges[id];
  21309. if (dateRange.isInterstitial) {
  21310. let interstitial = this.eventMap[id];
  21311. if (interstitial) {
  21312. interstitial.setDateRange(dateRange);
  21313. } else {
  21314. interstitial = new InterstitialEvent(dateRange, baseData);
  21315. this.eventMap[id] = interstitial;
  21316. if (enableAppendInPlace === false) {
  21317. interstitial.appendInPlace = enableAppendInPlace;
  21318. }
  21319. }
  21320. interstitialEvents.push(interstitial);
  21321. }
  21322. }
  21323. return interstitialEvents;
  21324. }
  21325. parseSchedule(interstitialEvents, mediaSelection) {
  21326. const schedule = [];
  21327. const details = mediaSelection.main.details;
  21328. const primaryDuration = details.live ? Infinity : details.edge;
  21329. let playoutDuration = 0;
  21330. interstitialEvents = interstitialEvents.filter((event) => !event.error && !(event.cue.once && event.hasPlayed));
  21331. if (interstitialEvents.length) {
  21332. this.resolveOffsets(interstitialEvents, mediaSelection);
  21333. let primaryPosition = 0;
  21334. let integratedTime = 0;
  21335. interstitialEvents.forEach((interstitial, i) => {
  21336. const preroll = interstitial.cue.pre;
  21337. const postroll = interstitial.cue.post;
  21338. const previousEvent = interstitialEvents[i - 1] || null;
  21339. const appendInPlace = interstitial.appendInPlace;
  21340. const eventStart = postroll ? primaryDuration : interstitial.startOffset;
  21341. const interstitialDuration = interstitial.duration;
  21342. const timelineDuration = interstitial.timelineOccupancy === TimelineOccupancy.Range ? interstitialDuration : 0;
  21343. const resumptionOffset = interstitial.resumptionOffset;
  21344. const inSameStartTimeSequence = (previousEvent == null ? void 0 : previousEvent.startTime) === eventStart;
  21345. const start = eventStart + interstitial.cumulativeDuration;
  21346. let end = appendInPlace ? start + interstitialDuration : eventStart + resumptionOffset;
  21347. if (preroll || !postroll && eventStart <= 0) {
  21348. const integratedStart = integratedTime;
  21349. integratedTime += timelineDuration;
  21350. interstitial.timelineStart = start;
  21351. const playoutStart = playoutDuration;
  21352. playoutDuration += interstitialDuration;
  21353. schedule.push({
  21354. event: interstitial,
  21355. start,
  21356. end,
  21357. playout: {
  21358. start: playoutStart,
  21359. end: playoutDuration
  21360. },
  21361. integrated: {
  21362. start: integratedStart,
  21363. end: integratedTime
  21364. }
  21365. });
  21366. } else if (eventStart <= primaryDuration) {
  21367. if (!inSameStartTimeSequence) {
  21368. const segmentDuration = eventStart - primaryPosition;
  21369. if (segmentDuration > ABUTTING_THRESHOLD_SECONDS) {
  21370. const timelineStart = primaryPosition;
  21371. const _integratedStart = integratedTime;
  21372. integratedTime += segmentDuration;
  21373. const _playoutStart = playoutDuration;
  21374. playoutDuration += segmentDuration;
  21375. const primarySegment = {
  21376. previousEvent: interstitialEvents[i - 1] || null,
  21377. nextEvent: interstitial,
  21378. start: timelineStart,
  21379. end: timelineStart + segmentDuration,
  21380. playout: {
  21381. start: _playoutStart,
  21382. end: playoutDuration
  21383. },
  21384. integrated: {
  21385. start: _integratedStart,
  21386. end: integratedTime
  21387. }
  21388. };
  21389. schedule.push(primarySegment);
  21390. } else if (segmentDuration > 0 && previousEvent) {
  21391. previousEvent.cumulativeDuration += segmentDuration;
  21392. schedule[schedule.length - 1].end = eventStart;
  21393. }
  21394. }
  21395. if (postroll) {
  21396. end = start;
  21397. }
  21398. interstitial.timelineStart = start;
  21399. const integratedStart = integratedTime;
  21400. integratedTime += timelineDuration;
  21401. const playoutStart = playoutDuration;
  21402. playoutDuration += interstitialDuration;
  21403. schedule.push({
  21404. event: interstitial,
  21405. start,
  21406. end,
  21407. playout: {
  21408. start: playoutStart,
  21409. end: playoutDuration
  21410. },
  21411. integrated: {
  21412. start: integratedStart,
  21413. end: integratedTime
  21414. }
  21415. });
  21416. } else {
  21417. return;
  21418. }
  21419. const resumeTime = interstitial.resumeTime;
  21420. if (postroll || resumeTime > primaryDuration) {
  21421. primaryPosition = primaryDuration;
  21422. } else {
  21423. primaryPosition = resumeTime;
  21424. }
  21425. });
  21426. if (primaryPosition < primaryDuration) {
  21427. var _schedule;
  21428. const timelineStart = primaryPosition;
  21429. const integratedStart = integratedTime;
  21430. const segmentDuration = primaryDuration - primaryPosition;
  21431. integratedTime += segmentDuration;
  21432. const playoutStart = playoutDuration;
  21433. playoutDuration += segmentDuration;
  21434. schedule.push({
  21435. previousEvent: ((_schedule = schedule[schedule.length - 1]) == null ? void 0 : _schedule.event) || null,
  21436. nextEvent: null,
  21437. start: primaryPosition,
  21438. end: timelineStart + segmentDuration,
  21439. playout: {
  21440. start: playoutStart,
  21441. end: playoutDuration
  21442. },
  21443. integrated: {
  21444. start: integratedStart,
  21445. end: integratedTime
  21446. }
  21447. });
  21448. }
  21449. this.setDurations(primaryDuration, playoutDuration, integratedTime);
  21450. } else {
  21451. const start = 0;
  21452. schedule.push({
  21453. previousEvent: null,
  21454. nextEvent: null,
  21455. start,
  21456. end: primaryDuration,
  21457. playout: {
  21458. start,
  21459. end: primaryDuration
  21460. },
  21461. integrated: {
  21462. start,
  21463. end: primaryDuration
  21464. }
  21465. });
  21466. this.setDurations(primaryDuration, primaryDuration, primaryDuration);
  21467. }
  21468. return schedule;
  21469. }
  21470. setDurations(primary, playout, integrated) {
  21471. this.durations = {
  21472. primary,
  21473. playout,
  21474. integrated
  21475. };
  21476. }
  21477. resolveOffsets(interstitialEvents, mediaSelection) {
  21478. const details = mediaSelection.main.details;
  21479. const primaryDuration = details.live ? Infinity : details.edge;
  21480. let cumulativeDuration = 0;
  21481. let lastScheduledStart = -1;
  21482. interstitialEvents.forEach((interstitial, i) => {
  21483. const preroll = interstitial.cue.pre;
  21484. const postroll = interstitial.cue.post;
  21485. const eventStart = preroll ? 0 : postroll ? primaryDuration : interstitial.startTime;
  21486. this.updateAssetDurations(interstitial);
  21487. const inSameStartTimeSequence = lastScheduledStart === eventStart;
  21488. if (inSameStartTimeSequence) {
  21489. interstitial.cumulativeDuration = cumulativeDuration;
  21490. } else {
  21491. cumulativeDuration = 0;
  21492. lastScheduledStart = eventStart;
  21493. }
  21494. if (!postroll && interstitial.snapOptions.in) {
  21495. interstitial.resumeAnchor = findFragmentByPTS(null, details.fragments, interstitial.startOffset + interstitial.resumptionOffset, 0, 0) || void 0;
  21496. }
  21497. if (interstitial.appendInPlace && !interstitial.appendInPlaceStarted) {
  21498. const alignedSegmentStart = this.primaryCanResumeInPlaceAt(interstitial, mediaSelection);
  21499. if (!alignedSegmentStart) {
  21500. interstitial.appendInPlace = false;
  21501. }
  21502. }
  21503. if (!interstitial.appendInPlace && i + 1 < interstitialEvents.length) {
  21504. const timeBetween = interstitialEvents[i + 1].startTime - interstitialEvents[i].resumeTime;
  21505. if (timeBetween < ABUTTING_THRESHOLD_SECONDS) {
  21506. interstitialEvents[i + 1].appendInPlace = false;
  21507. if (interstitialEvents[i + 1].appendInPlace) {
  21508. this.warn(`Could not change append strategy for abutting event ${interstitial}`);
  21509. }
  21510. }
  21511. }
  21512. const resumeOffset = isFiniteNumber(interstitial.resumeOffset) ? interstitial.resumeOffset : interstitial.duration;
  21513. cumulativeDuration += resumeOffset;
  21514. });
  21515. }
  21516. primaryCanResumeInPlaceAt(interstitial, mediaSelection) {
  21517. const resumeTime = interstitial.resumeTime;
  21518. const resumesInPlaceAt = interstitial.startTime + interstitial.resumptionOffset;
  21519. if (Math.abs(resumeTime - resumesInPlaceAt) > ALIGNED_END_THRESHOLD_SECONDS) {
  21520. this.log(`"${interstitial.identifier}" resumption ${resumeTime} not aligned with estimated timeline end ${resumesInPlaceAt}`);
  21521. return false;
  21522. }
  21523. if (!mediaSelection) {
  21524. this.log(`"${interstitial.identifier}" resumption ${resumeTime} can not be aligned with media (none selected)`);
  21525. return false;
  21526. }
  21527. const playlists = Object.keys(mediaSelection);
  21528. return !playlists.some((playlistType) => {
  21529. const details = mediaSelection[playlistType].details;
  21530. const playlistEnd = details.edge;
  21531. if (resumeTime >= playlistEnd) {
  21532. this.log(`"${interstitial.identifier}" resumption ${resumeTime} past ${playlistType} playlist end ${playlistEnd}`);
  21533. return false;
  21534. }
  21535. const startFragment = findFragmentByPTS(null, details.fragments, resumeTime);
  21536. if (!startFragment) {
  21537. this.log(`"${interstitial.identifier}" resumption ${resumeTime} does not align with any fragments in ${playlistType} playlist (${details.fragStart}-${details.fragmentEnd})`);
  21538. return true;
  21539. }
  21540. const allowance = playlistType === "audio" ? 0.175 : 0;
  21541. const alignedWithSegment = Math.abs(startFragment.start - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance || Math.abs(startFragment.end - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance;
  21542. if (!alignedWithSegment) {
  21543. this.log(`"${interstitial.identifier}" resumption ${resumeTime} not aligned with ${playlistType} fragment bounds (${startFragment.start}-${startFragment.end} sn: ${startFragment.sn} cc: ${startFragment.cc})`);
  21544. return true;
  21545. }
  21546. return false;
  21547. });
  21548. }
  21549. updateAssetDurations(interstitial) {
  21550. if (!interstitial.assetListLoaded) {
  21551. return;
  21552. }
  21553. const eventStart = interstitial.timelineStart;
  21554. let sumDuration = 0;
  21555. let hasUnknownDuration = false;
  21556. let hasErrors = false;
  21557. interstitial.assetList.forEach((asset, i) => {
  21558. const timelineStart = eventStart + sumDuration;
  21559. asset.startOffset = sumDuration;
  21560. asset.timelineStart = timelineStart;
  21561. hasUnknownDuration || (hasUnknownDuration = asset.duration === null);
  21562. hasErrors || (hasErrors = !!asset.error);
  21563. const duration = asset.error ? 0 : asset.duration || 0;
  21564. sumDuration += duration;
  21565. });
  21566. if (hasUnknownDuration && !hasErrors) {
  21567. interstitial.duration = Math.max(sumDuration, interstitial.duration);
  21568. } else {
  21569. interstitial.duration = sumDuration;
  21570. }
  21571. }
  21572. removeEvent(interstitial) {
  21573. interstitial.reset();
  21574. delete this.eventMap[interstitial.identifier];
  21575. }
  21576. };
  21577. function segmentToString(segment) {
  21578. return `[${segment.event ? '"' + segment.event.identifier + '"' : "primary"}: ${segment.start.toFixed(2)}-${segment.end.toFixed(2)}]`;
  21579. }
  21580. var AssetListLoader = class {
  21581. constructor(hls) {
  21582. this.hls = void 0;
  21583. this.hls = hls;
  21584. }
  21585. destroy() {
  21586. this.hls = null;
  21587. }
  21588. loadAssetList(interstitial, hlsStartOffset) {
  21589. const assetListUrl = interstitial.assetListUrl;
  21590. let url;
  21591. try {
  21592. url = getInterstitialUrl(assetListUrl, this.hls.sessionId, interstitial.baseUrl);
  21593. } catch (error) {
  21594. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_ERROR, error, assetListUrl);
  21595. this.hls.trigger(Events.ERROR, errorData);
  21596. return;
  21597. }
  21598. if (hlsStartOffset && url.protocol !== "data:") {
  21599. url.searchParams.set("_HLS_start_offset", "" + hlsStartOffset);
  21600. }
  21601. const config = this.hls.config;
  21602. const Loader = config.loader;
  21603. const loader = new Loader(config);
  21604. const context = {
  21605. responseType: "json",
  21606. url: url.href
  21607. };
  21608. const loadPolicy = config.interstitialAssetListLoadPolicy.default;
  21609. const loaderConfig = {
  21610. loadPolicy,
  21611. timeout: loadPolicy.maxLoadTimeMs,
  21612. maxRetry: 0,
  21613. retryDelay: 0,
  21614. maxRetryDelay: 0
  21615. };
  21616. const callbacks = {
  21617. onSuccess: (response, stats, context2, networkDetails) => {
  21618. const assetListResponse = response.data;
  21619. const assets = assetListResponse == null ? void 0 : assetListResponse.ASSETS;
  21620. if (!Array.isArray(assets)) {
  21621. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_PARSING_ERROR, new Error(`Invalid interstitial asset list`), context2.url, stats, networkDetails);
  21622. this.hls.trigger(Events.ERROR, errorData);
  21623. return;
  21624. }
  21625. interstitial.assetListResponse = assetListResponse;
  21626. this.hls.trigger(Events.ASSET_LIST_LOADED, {
  21627. event: interstitial,
  21628. assetListResponse,
  21629. networkDetails
  21630. });
  21631. },
  21632. onError: (error, context2, networkDetails, stats) => {
  21633. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_ERROR, new Error(`Error loading X-ASSET-LIST: HTTP status ${error.code} ${error.text} (${context2.url})`), context2.url, stats, networkDetails);
  21634. this.hls.trigger(Events.ERROR, errorData);
  21635. },
  21636. onTimeout: (stats, context2, networkDetails) => {
  21637. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_TIMEOUT, new Error(`Timeout loading X-ASSET-LIST (${context2.url})`), context2.url, stats, networkDetails);
  21638. this.hls.trigger(Events.ERROR, errorData);
  21639. }
  21640. };
  21641. loader.load(context, loaderConfig, callbacks);
  21642. this.hls.trigger(Events.ASSET_LIST_LOADING, {
  21643. event: interstitial
  21644. });
  21645. return loader;
  21646. }
  21647. assignAssetListError(interstitial, details, error, url, stats, networkDetails) {
  21648. interstitial.error = error;
  21649. return {
  21650. type: ErrorTypes.NETWORK_ERROR,
  21651. details,
  21652. fatal: false,
  21653. interstitial,
  21654. url,
  21655. error,
  21656. networkDetails,
  21657. stats
  21658. };
  21659. }
  21660. };
  21661. function playWithCatch(media) {
  21662. media == null ? void 0 : media.play().catch(() => {
  21663. });
  21664. }
  21665. var InterstitialsController = class extends Logger {
  21666. constructor(hls, HlsPlayerClass) {
  21667. super("interstitials", hls.logger);
  21668. this.HlsPlayerClass = void 0;
  21669. this.hls = void 0;
  21670. this.assetListLoader = void 0;
  21671. this.mediaSelection = null;
  21672. this.altSelection = null;
  21673. this.media = null;
  21674. this.detachedData = null;
  21675. this.requiredTracks = null;
  21676. this.manager = null;
  21677. this.playerQueue = [];
  21678. this.bufferedPos = -1;
  21679. this.timelinePos = -1;
  21680. this.schedule = void 0;
  21681. this.playingItem = null;
  21682. this.bufferingItem = null;
  21683. this.waitingItem = null;
  21684. this.endedItem = null;
  21685. this.playingAsset = null;
  21686. this.endedAsset = null;
  21687. this.bufferingAsset = null;
  21688. this.shouldPlay = false;
  21689. this.onPlay = () => {
  21690. this.shouldPlay = true;
  21691. };
  21692. this.onPause = () => {
  21693. this.shouldPlay = false;
  21694. };
  21695. this.onSeeking = () => {
  21696. const currentTime = this.currentTime;
  21697. if (currentTime === void 0 || this.playbackDisabled) {
  21698. return;
  21699. }
  21700. const diff = currentTime - this.timelinePos;
  21701. const roundingError = Math.abs(diff) < 1 / 7056e5;
  21702. if (roundingError) {
  21703. return;
  21704. }
  21705. const backwardSeek = diff <= -0.01;
  21706. this.timelinePos = currentTime;
  21707. this.bufferedPos = currentTime;
  21708. const playingItem = this.playingItem;
  21709. if (!playingItem) {
  21710. this.checkBuffer();
  21711. return;
  21712. }
  21713. if (backwardSeek) {
  21714. const resetCount = this.schedule.resetErrorsInRange(currentTime, currentTime - diff);
  21715. if (resetCount) {
  21716. this.updateSchedule();
  21717. }
  21718. }
  21719. this.checkBuffer();
  21720. if (backwardSeek && currentTime < playingItem.start || currentTime >= playingItem.end) {
  21721. var _this$media;
  21722. const scheduleIndex = this.schedule.findItemIndexAtTime(this.timelinePos);
  21723. if (!this.isInterstitial(playingItem) && (_this$media = this.media) != null && _this$media.paused) {
  21724. this.shouldPlay = false;
  21725. }
  21726. if (!backwardSeek) {
  21727. const playingIndex = this.findItemIndex(playingItem);
  21728. if (scheduleIndex > playingIndex) {
  21729. const jumpIndex = this.schedule.findJumpRestrictedIndex(playingIndex + 1, scheduleIndex);
  21730. if (jumpIndex > playingIndex) {
  21731. this.setSchedulePosition(jumpIndex);
  21732. return;
  21733. }
  21734. }
  21735. }
  21736. this.setSchedulePosition(scheduleIndex);
  21737. return;
  21738. }
  21739. const playingAsset = this.playingAsset;
  21740. if (!playingAsset) {
  21741. if (this.playingLastItem && this.isInterstitial(playingItem)) {
  21742. const restartAsset = playingItem.event.assetList[0];
  21743. if (restartAsset) {
  21744. this.endedItem = this.playingItem;
  21745. this.playingItem = null;
  21746. this.setScheduleToAssetAtTime(currentTime, restartAsset);
  21747. }
  21748. }
  21749. return;
  21750. }
  21751. const start = playingAsset.timelineStart;
  21752. const duration = playingAsset.duration || 0;
  21753. if (backwardSeek && currentTime < start || currentTime >= start + duration) {
  21754. this.setScheduleToAssetAtTime(currentTime, playingAsset);
  21755. }
  21756. };
  21757. this.onTimeupdate = () => {
  21758. const currentTime = this.currentTime;
  21759. if (currentTime === void 0 || this.playbackDisabled) {
  21760. return;
  21761. }
  21762. if (currentTime > this.timelinePos) {
  21763. this.timelinePos = currentTime;
  21764. if (currentTime > this.bufferedPos) {
  21765. this.checkBuffer();
  21766. }
  21767. } else {
  21768. return;
  21769. }
  21770. const playingItem = this.playingItem;
  21771. if (!playingItem || this.playingLastItem) {
  21772. return;
  21773. }
  21774. if (currentTime >= playingItem.end) {
  21775. this.timelinePos = playingItem.end;
  21776. const playingIndex = this.findItemIndex(playingItem);
  21777. this.setSchedulePosition(playingIndex + 1);
  21778. }
  21779. const playingAsset = this.playingAsset;
  21780. if (!playingAsset) {
  21781. return;
  21782. }
  21783. const end = playingAsset.timelineStart + (playingAsset.duration || 0);
  21784. if (currentTime >= end) {
  21785. this.setScheduleToAssetAtTime(currentTime, playingAsset);
  21786. }
  21787. };
  21788. this.onScheduleUpdate = (removedInterstitials, previousItems) => {
  21789. const schedule = this.schedule;
  21790. const playingItem = this.playingItem;
  21791. const interstitialEvents = schedule.events || [];
  21792. const scheduleItems = schedule.items || [];
  21793. const durations = schedule.durations;
  21794. const removedIds = removedInterstitials.map((interstitial) => interstitial.identifier);
  21795. const interstitialsUpdated = !!(interstitialEvents.length || removedIds.length);
  21796. if (interstitialsUpdated || previousItems) {
  21797. this.log(`INTERSTITIALS_UPDATED (${interstitialEvents.length}): ${interstitialEvents}
  21798. Schedule: ${scheduleItems.map((seg) => segmentToString(seg))} pos: ${this.timelinePos}`);
  21799. }
  21800. if (removedIds.length) {
  21801. this.log(`Removed events ${removedIds}`);
  21802. }
  21803. this.playerQueue.forEach((player) => {
  21804. if (player.interstitial.appendInPlace) {
  21805. const timelineStart = player.assetItem.timelineStart;
  21806. const diff = player.timelineOffset - timelineStart;
  21807. if (diff) {
  21808. try {
  21809. player.timelineOffset = timelineStart;
  21810. } catch (e) {
  21811. if (Math.abs(diff) > ALIGNED_END_THRESHOLD_SECONDS) {
  21812. this.warn(`${e} ("${player.assetId}" ${player.timelineOffset}->${timelineStart})`);
  21813. }
  21814. }
  21815. }
  21816. }
  21817. });
  21818. let trimInPlaceForPlayout = null;
  21819. if (playingItem) {
  21820. const updatedPlayingItem = this.updateItem(playingItem, this.timelinePos);
  21821. if (this.itemsMatch(playingItem, updatedPlayingItem)) {
  21822. this.playingItem = updatedPlayingItem;
  21823. this.waitingItem = this.endedItem = null;
  21824. trimInPlaceForPlayout = () => this.trimInPlace(updatedPlayingItem, playingItem);
  21825. }
  21826. } else {
  21827. this.waitingItem = this.updateItem(this.waitingItem);
  21828. this.endedItem = this.updateItem(this.endedItem);
  21829. }
  21830. const bufferingItem = this.bufferingItem;
  21831. if (bufferingItem) {
  21832. const updatedBufferingItem = this.updateItem(bufferingItem, this.bufferedPos);
  21833. if (this.itemsMatch(bufferingItem, updatedBufferingItem)) {
  21834. this.bufferingItem = updatedBufferingItem;
  21835. trimInPlaceForPlayout || (trimInPlaceForPlayout = () => this.trimInPlace(updatedBufferingItem, bufferingItem));
  21836. } else if (bufferingItem.event) {
  21837. this.bufferingItem = this.playingItem;
  21838. this.clearInterstitial(bufferingItem.event, null);
  21839. }
  21840. }
  21841. removedInterstitials.forEach((interstitial) => {
  21842. interstitial.assetList.forEach((asset) => {
  21843. this.clearAssetPlayer(asset.identifier, null);
  21844. });
  21845. });
  21846. if (interstitialsUpdated || previousItems) {
  21847. this.hls.trigger(Events.INTERSTITIALS_UPDATED, {
  21848. events: interstitialEvents.slice(0),
  21849. schedule: scheduleItems.slice(0),
  21850. durations,
  21851. removedIds
  21852. });
  21853. if (this.isInterstitial(playingItem) && removedIds.includes(playingItem.event.identifier)) {
  21854. this.warn(`Interstitial "${playingItem.event.identifier}" removed while playing`);
  21855. this.primaryFallback(playingItem.event);
  21856. return;
  21857. }
  21858. if (trimInPlaceForPlayout) {
  21859. trimInPlaceForPlayout();
  21860. }
  21861. this.checkBuffer();
  21862. }
  21863. };
  21864. this.hls = hls;
  21865. this.HlsPlayerClass = HlsPlayerClass;
  21866. this.assetListLoader = new AssetListLoader(hls);
  21867. this.schedule = new InterstitialsSchedule(this.onScheduleUpdate, hls.logger);
  21868. this.registerListeners();
  21869. }
  21870. registerListeners() {
  21871. const hls = this.hls;
  21872. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  21873. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  21874. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  21875. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21876. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  21877. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  21878. hls.on(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);
  21879. hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  21880. hls.on(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);
  21881. hls.on(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);
  21882. hls.on(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);
  21883. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  21884. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  21885. hls.on(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);
  21886. hls.on(Events.MEDIA_ENDED, this.onMediaEnded, this);
  21887. hls.on(Events.ERROR, this.onError, this);
  21888. hls.on(Events.DESTROYING, this.onDestroying, this);
  21889. }
  21890. unregisterListeners() {
  21891. const hls = this.hls;
  21892. if (!hls) {
  21893. return;
  21894. }
  21895. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  21896. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  21897. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  21898. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21899. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  21900. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  21901. hls.off(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);
  21902. hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  21903. hls.off(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);
  21904. hls.off(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);
  21905. hls.off(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);
  21906. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  21907. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  21908. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  21909. hls.off(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);
  21910. hls.off(Events.MEDIA_ENDED, this.onMediaEnded, this);
  21911. hls.off(Events.ERROR, this.onError, this);
  21912. hls.off(Events.DESTROYING, this.onDestroying, this);
  21913. }
  21914. startLoad() {
  21915. this.resumeBuffering();
  21916. }
  21917. stopLoad() {
  21918. this.pauseBuffering();
  21919. }
  21920. resumeBuffering() {
  21921. var _this$getBufferingPla;
  21922. (_this$getBufferingPla = this.getBufferingPlayer()) == null ? void 0 : _this$getBufferingPla.resumeBuffering();
  21923. }
  21924. pauseBuffering() {
  21925. var _this$getBufferingPla2;
  21926. (_this$getBufferingPla2 = this.getBufferingPlayer()) == null ? void 0 : _this$getBufferingPla2.pauseBuffering();
  21927. }
  21928. destroy() {
  21929. this.unregisterListeners();
  21930. this.stopLoad();
  21931. if (this.assetListLoader) {
  21932. this.assetListLoader.destroy();
  21933. }
  21934. this.emptyPlayerQueue();
  21935. this.clearScheduleState();
  21936. if (this.schedule) {
  21937. this.schedule.destroy();
  21938. }
  21939. this.media = this.detachedData = this.mediaSelection = this.requiredTracks = this.altSelection = this.manager = null;
  21940. this.hls = this.HlsPlayerClass = this.schedule = this.log = null;
  21941. this.assetListLoader = null;
  21942. this.onPlay = this.onPause = this.onSeeking = this.onTimeupdate = null;
  21943. this.onScheduleUpdate = null;
  21944. }
  21945. onDestroying() {
  21946. const media = this.primaryMedia || this.media;
  21947. if (media) {
  21948. this.removeMediaListeners(media);
  21949. }
  21950. }
  21951. removeMediaListeners(media) {
  21952. removeEventListener(media, "play", this.onPlay);
  21953. removeEventListener(media, "pause", this.onPause);
  21954. removeEventListener(media, "seeking", this.onSeeking);
  21955. removeEventListener(media, "timeupdate", this.onTimeupdate);
  21956. }
  21957. onMediaAttaching(event, data) {
  21958. const media = this.media = data.media;
  21959. addEventListener(media, "seeking", this.onSeeking);
  21960. addEventListener(media, "timeupdate", this.onTimeupdate);
  21961. addEventListener(media, "play", this.onPlay);
  21962. addEventListener(media, "pause", this.onPause);
  21963. }
  21964. onMediaAttached(event, data) {
  21965. const playingItem = this.effectivePlayingItem;
  21966. const detachedMedia = this.detachedData;
  21967. this.detachedData = null;
  21968. if (playingItem === null) {
  21969. this.checkStart();
  21970. } else if (!detachedMedia) {
  21971. this.clearScheduleState();
  21972. const playingIndex = this.findItemIndex(playingItem);
  21973. this.setSchedulePosition(playingIndex);
  21974. }
  21975. }
  21976. clearScheduleState() {
  21977. this.playingItem = this.bufferingItem = this.waitingItem = this.endedItem = this.playingAsset = this.endedAsset = this.bufferingAsset = null;
  21978. }
  21979. onMediaDetaching(event, data) {
  21980. const transferringMedia = !!data.transferMedia;
  21981. const media = this.media;
  21982. this.media = null;
  21983. if (transferringMedia) {
  21984. return;
  21985. }
  21986. if (media) {
  21987. this.removeMediaListeners(media);
  21988. }
  21989. if (this.detachedData) {
  21990. const player = this.getBufferingPlayer();
  21991. if (player) {
  21992. this.playingAsset = this.endedAsset = this.bufferingAsset = this.bufferingItem = this.waitingItem = this.detachedData = null;
  21993. player.detachMedia();
  21994. }
  21995. this.shouldPlay = false;
  21996. }
  21997. }
  21998. get interstitialsManager() {
  21999. if (!this.manager) {
  22000. if (!this.hls) {
  22001. return null;
  22002. }
  22003. const c = this;
  22004. const effectiveBufferingItem = () => c.bufferingItem || c.waitingItem;
  22005. const getAssetPlayer = (asset) => asset ? c.getAssetPlayer(asset.identifier) : asset;
  22006. const getMappedTime = (item, timelineType, asset, controllerField, assetPlayerField) => {
  22007. if (item) {
  22008. let time = item[timelineType].start;
  22009. const interstitial = item.event;
  22010. if (interstitial) {
  22011. if (timelineType === "playout" || interstitial.timelineOccupancy !== TimelineOccupancy.Point) {
  22012. const assetPlayer = getAssetPlayer(asset);
  22013. if ((assetPlayer == null ? void 0 : assetPlayer.interstitial) === interstitial) {
  22014. time += assetPlayer.assetItem.startOffset + assetPlayer[assetPlayerField];
  22015. }
  22016. }
  22017. } else {
  22018. const value = controllerField === "bufferedPos" ? getBufferedEnd() : c[controllerField];
  22019. time += value - item.start;
  22020. }
  22021. return time;
  22022. }
  22023. return 0;
  22024. };
  22025. const findMappedTime = (primaryTime, timelineType) => {
  22026. if (primaryTime !== 0 && timelineType !== "primary" && c.schedule.length) {
  22027. var _c$schedule$items;
  22028. const index = c.schedule.findItemIndexAtTime(primaryTime);
  22029. const item = (_c$schedule$items = c.schedule.items) == null ? void 0 : _c$schedule$items[index];
  22030. if (item) {
  22031. const diff = item[timelineType].start - item.start;
  22032. return primaryTime + diff;
  22033. }
  22034. }
  22035. return primaryTime;
  22036. };
  22037. const getBufferedEnd = () => {
  22038. const value = c.bufferedPos;
  22039. if (value === Number.MAX_VALUE) {
  22040. return getMappedDuration("primary");
  22041. }
  22042. return Math.max(value, 0);
  22043. };
  22044. const getMappedDuration = (timelineType) => {
  22045. var _c$primaryDetails;
  22046. if ((_c$primaryDetails = c.primaryDetails) != null && _c$primaryDetails.live) {
  22047. return c.primaryDetails.edge;
  22048. }
  22049. return c.schedule.durations[timelineType];
  22050. };
  22051. const seekTo = (time, timelineType) => {
  22052. var _item$event, _c$schedule$items2;
  22053. const item = c.effectivePlayingItem;
  22054. if (item != null && (_item$event = item.event) != null && _item$event.restrictions.skip) {
  22055. return;
  22056. }
  22057. c.log(`seek to ${time} "${timelineType}"`);
  22058. const playingItem = c.effectivePlayingItem;
  22059. const targetIndex = c.schedule.findItemIndexAtTime(time, timelineType);
  22060. const targetItem = (_c$schedule$items2 = c.schedule.items) == null ? void 0 : _c$schedule$items2[targetIndex];
  22061. const bufferingPlayer = c.getBufferingPlayer();
  22062. const bufferingInterstitial = bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial;
  22063. const appendInPlace = bufferingInterstitial == null ? void 0 : bufferingInterstitial.appendInPlace;
  22064. const seekInItem = playingItem && c.itemsMatch(playingItem, targetItem);
  22065. if (playingItem && (appendInPlace || seekInItem)) {
  22066. const assetPlayer = getAssetPlayer(c.playingAsset);
  22067. const media = (assetPlayer == null ? void 0 : assetPlayer.media) || c.primaryMedia;
  22068. if (media) {
  22069. const currentTime = timelineType === "primary" ? media.currentTime : getMappedTime(playingItem, timelineType, c.playingAsset, "timelinePos", "currentTime");
  22070. const diff = time - currentTime;
  22071. const seekToTime = (appendInPlace ? currentTime : media.currentTime) + diff;
  22072. if (seekToTime >= 0 && (!assetPlayer || appendInPlace || seekToTime <= assetPlayer.duration)) {
  22073. media.currentTime = seekToTime;
  22074. return;
  22075. }
  22076. }
  22077. }
  22078. if (targetItem) {
  22079. let seekToTime = time;
  22080. if (timelineType !== "primary") {
  22081. const primarySegmentStart = targetItem[timelineType].start;
  22082. const diff = time - primarySegmentStart;
  22083. seekToTime = targetItem.start + diff;
  22084. }
  22085. const targetIsPrimary = !c.isInterstitial(targetItem);
  22086. if ((!c.isInterstitial(playingItem) || playingItem.event.appendInPlace) && (targetIsPrimary || targetItem.event.appendInPlace)) {
  22087. const media = c.media || (appendInPlace ? bufferingPlayer == null ? void 0 : bufferingPlayer.media : null);
  22088. if (media) {
  22089. media.currentTime = seekToTime;
  22090. }
  22091. } else if (playingItem) {
  22092. const playingIndex = c.findItemIndex(playingItem);
  22093. if (targetIndex > playingIndex) {
  22094. const jumpIndex = c.schedule.findJumpRestrictedIndex(playingIndex + 1, targetIndex);
  22095. if (jumpIndex > playingIndex) {
  22096. c.setSchedulePosition(jumpIndex);
  22097. return;
  22098. }
  22099. }
  22100. let assetIndex = 0;
  22101. if (targetIsPrimary) {
  22102. c.timelinePos = seekToTime;
  22103. c.checkBuffer();
  22104. } else {
  22105. var _targetItem$event;
  22106. const assetList = targetItem == null ? void 0 : (_targetItem$event = targetItem.event) == null ? void 0 : _targetItem$event.assetList;
  22107. if (assetList) {
  22108. const eventTime = time - (targetItem[timelineType] || targetItem).start;
  22109. for (let i = assetList.length; i--; ) {
  22110. const asset = assetList[i];
  22111. if (asset.duration && eventTime >= asset.startOffset && eventTime < asset.startOffset + asset.duration) {
  22112. assetIndex = i;
  22113. break;
  22114. }
  22115. }
  22116. }
  22117. }
  22118. c.setSchedulePosition(targetIndex, assetIndex);
  22119. }
  22120. }
  22121. };
  22122. const getActiveInterstitial = () => {
  22123. const playingItem = c.effectivePlayingItem;
  22124. if (c.isInterstitial(playingItem)) {
  22125. return playingItem;
  22126. }
  22127. const bufferingItem = effectiveBufferingItem();
  22128. if (c.isInterstitial(bufferingItem)) {
  22129. return bufferingItem;
  22130. }
  22131. return null;
  22132. };
  22133. const interstitialPlayer = {
  22134. get currentTime() {
  22135. const interstitialItem = getActiveInterstitial();
  22136. const playingItem = c.effectivePlayingItem;
  22137. if (playingItem && playingItem === interstitialItem) {
  22138. return getMappedTime(playingItem, "playout", c.effectivePlayingAsset, "timelinePos", "currentTime") - playingItem.playout.start;
  22139. }
  22140. return 0;
  22141. },
  22142. set currentTime(time) {
  22143. const interstitialItem = getActiveInterstitial();
  22144. const playingItem = c.effectivePlayingItem;
  22145. if (playingItem && playingItem === interstitialItem) {
  22146. seekTo(time + playingItem.playout.start, "playout");
  22147. }
  22148. },
  22149. get duration() {
  22150. const interstitialItem = getActiveInterstitial();
  22151. if (interstitialItem) {
  22152. return interstitialItem.playout.end - interstitialItem.playout.start;
  22153. }
  22154. return 0;
  22155. },
  22156. get assetPlayers() {
  22157. var _getActiveInterstitia;
  22158. const assetList = (_getActiveInterstitia = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia.event.assetList;
  22159. if (assetList) {
  22160. return assetList.map((asset) => c.getAssetPlayer(asset.identifier));
  22161. }
  22162. return [];
  22163. },
  22164. get playingIndex() {
  22165. var _getActiveInterstitia2;
  22166. const interstitial = (_getActiveInterstitia2 = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia2.event;
  22167. if (interstitial && c.effectivePlayingAsset) {
  22168. return interstitial.findAssetIndex(c.effectivePlayingAsset);
  22169. }
  22170. return -1;
  22171. },
  22172. get scheduleItem() {
  22173. return getActiveInterstitial();
  22174. }
  22175. };
  22176. this.manager = {
  22177. get events() {
  22178. var _c$schedule, _c$schedule$events;
  22179. return ((_c$schedule = c.schedule) == null ? void 0 : (_c$schedule$events = _c$schedule.events) == null ? void 0 : _c$schedule$events.slice(0)) || [];
  22180. },
  22181. get schedule() {
  22182. var _c$schedule2, _c$schedule2$items;
  22183. return ((_c$schedule2 = c.schedule) == null ? void 0 : (_c$schedule2$items = _c$schedule2.items) == null ? void 0 : _c$schedule2$items.slice(0)) || [];
  22184. },
  22185. get interstitialPlayer() {
  22186. if (getActiveInterstitial()) {
  22187. return interstitialPlayer;
  22188. }
  22189. return null;
  22190. },
  22191. get playerQueue() {
  22192. return c.playerQueue.slice(0);
  22193. },
  22194. get bufferingAsset() {
  22195. return c.bufferingAsset;
  22196. },
  22197. get bufferingItem() {
  22198. return effectiveBufferingItem();
  22199. },
  22200. get bufferingIndex() {
  22201. const item = effectiveBufferingItem();
  22202. return c.findItemIndex(item);
  22203. },
  22204. get playingAsset() {
  22205. return c.effectivePlayingAsset;
  22206. },
  22207. get playingItem() {
  22208. return c.effectivePlayingItem;
  22209. },
  22210. get playingIndex() {
  22211. const item = c.effectivePlayingItem;
  22212. return c.findItemIndex(item);
  22213. },
  22214. primary: {
  22215. get bufferedEnd() {
  22216. return getBufferedEnd();
  22217. },
  22218. get currentTime() {
  22219. const timelinePos = c.timelinePos;
  22220. return timelinePos > 0 ? timelinePos : 0;
  22221. },
  22222. set currentTime(time) {
  22223. seekTo(time, "primary");
  22224. },
  22225. get duration() {
  22226. return getMappedDuration("primary");
  22227. },
  22228. get seekableStart() {
  22229. var _c$primaryDetails2;
  22230. return ((_c$primaryDetails2 = c.primaryDetails) == null ? void 0 : _c$primaryDetails2.fragmentStart) || 0;
  22231. }
  22232. },
  22233. integrated: {
  22234. get bufferedEnd() {
  22235. return getMappedTime(effectiveBufferingItem(), "integrated", c.bufferingAsset, "bufferedPos", "bufferedEnd");
  22236. },
  22237. get currentTime() {
  22238. return getMappedTime(c.effectivePlayingItem, "integrated", c.effectivePlayingAsset, "timelinePos", "currentTime");
  22239. },
  22240. set currentTime(time) {
  22241. seekTo(time, "integrated");
  22242. },
  22243. get duration() {
  22244. return getMappedDuration("integrated");
  22245. },
  22246. get seekableStart() {
  22247. var _c$primaryDetails3;
  22248. return findMappedTime(((_c$primaryDetails3 = c.primaryDetails) == null ? void 0 : _c$primaryDetails3.fragmentStart) || 0, "integrated");
  22249. }
  22250. },
  22251. skip: () => {
  22252. const item = c.effectivePlayingItem;
  22253. const event = item == null ? void 0 : item.event;
  22254. if (event && !event.restrictions.skip) {
  22255. const index = c.findItemIndex(item);
  22256. if (event.appendInPlace) {
  22257. const time = item.playout.start + item.event.duration;
  22258. seekTo(time + 1e-3, "playout");
  22259. } else {
  22260. c.advanceAfterAssetEnded(event, index, Infinity);
  22261. }
  22262. }
  22263. }
  22264. };
  22265. }
  22266. return this.manager;
  22267. }
  22268. // Schedule getters
  22269. get effectivePlayingItem() {
  22270. return this.waitingItem || this.playingItem || this.endedItem;
  22271. }
  22272. get effectivePlayingAsset() {
  22273. return this.playingAsset || this.endedAsset;
  22274. }
  22275. get playingLastItem() {
  22276. var _this$schedule;
  22277. const playingItem = this.playingItem;
  22278. const items = (_this$schedule = this.schedule) == null ? void 0 : _this$schedule.items;
  22279. if (!this.playbackStarted || !playingItem || !items) {
  22280. return false;
  22281. }
  22282. return this.findItemIndex(playingItem) === items.length - 1;
  22283. }
  22284. get playbackStarted() {
  22285. return this.effectivePlayingItem !== null;
  22286. }
  22287. // Media getters and event callbacks
  22288. get currentTime() {
  22289. var _this$bufferingItem, _this$bufferingItem$e, _media;
  22290. if (this.mediaSelection === null) {
  22291. return void 0;
  22292. }
  22293. const queuedForPlayback = this.waitingItem || this.playingItem;
  22294. if (this.isInterstitial(queuedForPlayback) && !queuedForPlayback.event.appendInPlace) {
  22295. return void 0;
  22296. }
  22297. let media = this.media;
  22298. if (!media && (_this$bufferingItem = this.bufferingItem) != null && (_this$bufferingItem$e = _this$bufferingItem.event) != null && _this$bufferingItem$e.appendInPlace) {
  22299. media = this.primaryMedia;
  22300. }
  22301. const currentTime = (_media = media) == null ? void 0 : _media.currentTime;
  22302. if (currentTime === void 0 || !isFiniteNumber(currentTime)) {
  22303. return void 0;
  22304. }
  22305. return currentTime;
  22306. }
  22307. get primaryMedia() {
  22308. var _this$detachedData;
  22309. return this.media || ((_this$detachedData = this.detachedData) == null ? void 0 : _this$detachedData.media) || null;
  22310. }
  22311. isInterstitial(item) {
  22312. return !!(item != null && item.event);
  22313. }
  22314. retreiveMediaSource(assetId, toSegment) {
  22315. const player = this.getAssetPlayer(assetId);
  22316. if (player) {
  22317. this.transferMediaFromPlayer(player, toSegment);
  22318. }
  22319. }
  22320. transferMediaFromPlayer(player, toSegment) {
  22321. const appendInPlace = player.interstitial.appendInPlace;
  22322. const playerMedia = player.media;
  22323. if (appendInPlace && playerMedia === this.primaryMedia) {
  22324. this.bufferingAsset = null;
  22325. if (!toSegment || this.isInterstitial(toSegment) && !toSegment.event.appendInPlace) {
  22326. if (toSegment && playerMedia) {
  22327. this.detachedData = {
  22328. media: playerMedia
  22329. };
  22330. return;
  22331. }
  22332. }
  22333. const attachMediaSourceData = player.transferMedia();
  22334. this.log(`transfer MediaSource from ${player} ${stringify(attachMediaSourceData)}`);
  22335. this.detachedData = attachMediaSourceData;
  22336. } else if (toSegment && playerMedia) {
  22337. this.shouldPlay || (this.shouldPlay = !playerMedia.paused);
  22338. }
  22339. }
  22340. transferMediaTo(player, media) {
  22341. var _this$detachedData2, _attachMediaSourceDat;
  22342. if (player.media === media) {
  22343. return;
  22344. }
  22345. let attachMediaSourceData = null;
  22346. const primaryPlayer = this.hls;
  22347. const isAssetPlayer = player !== primaryPlayer;
  22348. const appendInPlace = isAssetPlayer && player.interstitial.appendInPlace;
  22349. const detachedMediaSource = (_this$detachedData2 = this.detachedData) == null ? void 0 : _this$detachedData2.mediaSource;
  22350. let logFromSource;
  22351. if (primaryPlayer.media) {
  22352. if (appendInPlace) {
  22353. attachMediaSourceData = primaryPlayer.transferMedia();
  22354. this.detachedData = attachMediaSourceData;
  22355. }
  22356. logFromSource = `Primary`;
  22357. } else if (detachedMediaSource) {
  22358. const bufferingPlayer = this.getBufferingPlayer();
  22359. if (bufferingPlayer) {
  22360. attachMediaSourceData = bufferingPlayer.transferMedia();
  22361. logFromSource = `${bufferingPlayer}`;
  22362. } else {
  22363. logFromSource = `detached MediaSource`;
  22364. }
  22365. } else {
  22366. logFromSource = `detached media`;
  22367. }
  22368. if (!attachMediaSourceData) {
  22369. if (detachedMediaSource) {
  22370. attachMediaSourceData = this.detachedData;
  22371. this.log(`using detachedData: MediaSource ${stringify(attachMediaSourceData)}`);
  22372. } else if (!this.detachedData || primaryPlayer.media === media) {
  22373. const playerQueue = this.playerQueue;
  22374. if (playerQueue.length > 1) {
  22375. playerQueue.forEach((queuedPlayer) => {
  22376. if (isAssetPlayer && queuedPlayer.interstitial.appendInPlace !== appendInPlace) {
  22377. const interstitial = queuedPlayer.interstitial;
  22378. this.clearInterstitial(queuedPlayer.interstitial, null);
  22379. interstitial.appendInPlace = false;
  22380. if (interstitial.appendInPlace) {
  22381. this.warn(`Could not change append strategy for queued assets ${interstitial}`);
  22382. }
  22383. }
  22384. });
  22385. }
  22386. this.hls.detachMedia();
  22387. this.detachedData = {
  22388. media
  22389. };
  22390. }
  22391. }
  22392. const transferring = attachMediaSourceData && "mediaSource" in attachMediaSourceData && ((_attachMediaSourceDat = attachMediaSourceData.mediaSource) == null ? void 0 : _attachMediaSourceDat.readyState) !== "closed";
  22393. const dataToAttach = transferring && attachMediaSourceData ? attachMediaSourceData : media;
  22394. this.log(`${transferring ? "transfering MediaSource" : "attaching media"} to ${isAssetPlayer ? player : "Primary"} from ${logFromSource}`);
  22395. if (dataToAttach === attachMediaSourceData) {
  22396. const isAssetAtEndOfSchedule = isAssetPlayer && player.assetId === this.schedule.assetIdAtEnd;
  22397. dataToAttach.overrides = {
  22398. duration: this.schedule.duration,
  22399. endOfStream: !isAssetPlayer || isAssetAtEndOfSchedule,
  22400. cueRemoval: !isAssetPlayer
  22401. };
  22402. }
  22403. player.attachMedia(dataToAttach);
  22404. }
  22405. onInterstitialCueEnter() {
  22406. this.onTimeupdate();
  22407. }
  22408. // Scheduling methods
  22409. checkStart() {
  22410. const schedule = this.schedule;
  22411. const interstitialEvents = schedule.events;
  22412. if (!interstitialEvents || this.playbackDisabled || !this.media) {
  22413. return;
  22414. }
  22415. if (this.bufferedPos === -1) {
  22416. this.bufferedPos = 0;
  22417. }
  22418. const timelinePos = this.timelinePos;
  22419. const effectivePlayingItem = this.effectivePlayingItem;
  22420. if (timelinePos === -1) {
  22421. const startPosition = this.hls.startPosition;
  22422. this.timelinePos = startPosition;
  22423. if (interstitialEvents.length && interstitialEvents[0].cue.pre) {
  22424. const index = schedule.findEventIndex(interstitialEvents[0].identifier);
  22425. this.setSchedulePosition(index);
  22426. } else if (startPosition >= 0 || !this.primaryLive) {
  22427. const start = this.timelinePos = startPosition > 0 ? startPosition : 0;
  22428. const index = schedule.findItemIndexAtTime(start);
  22429. this.setSchedulePosition(index);
  22430. }
  22431. } else if (effectivePlayingItem && !this.playingItem) {
  22432. const index = schedule.findItemIndex(effectivePlayingItem);
  22433. this.setSchedulePosition(index);
  22434. }
  22435. }
  22436. advanceAfterAssetEnded(interstitial, index, assetListIndex) {
  22437. const nextAssetIndex = getNextAssetIndex(interstitial, assetListIndex);
  22438. if (!interstitial.isAssetPastPlayoutLimit(nextAssetIndex)) {
  22439. this.setSchedulePosition(index, nextAssetIndex);
  22440. } else {
  22441. const scheduleItems = this.schedule.items;
  22442. if (scheduleItems) {
  22443. const nextIndex = index + 1;
  22444. const scheduleLength = scheduleItems.length;
  22445. if (nextIndex >= scheduleLength) {
  22446. this.setSchedulePosition(-1);
  22447. return;
  22448. }
  22449. const resumptionTime = interstitial.resumeTime;
  22450. if (this.timelinePos < resumptionTime) {
  22451. this.timelinePos = resumptionTime;
  22452. this.checkBuffer();
  22453. }
  22454. this.setSchedulePosition(nextIndex);
  22455. }
  22456. }
  22457. }
  22458. setScheduleToAssetAtTime(time, playingAsset) {
  22459. const schedule = this.schedule;
  22460. const parentIdentifier = playingAsset.parentIdentifier;
  22461. const interstitial = schedule.getEvent(parentIdentifier);
  22462. if (interstitial) {
  22463. const itemIndex = schedule.findEventIndex(parentIdentifier);
  22464. const assetListIndex = schedule.findAssetIndex(interstitial, time);
  22465. this.advanceAfterAssetEnded(interstitial, itemIndex, assetListIndex - 1);
  22466. }
  22467. }
  22468. setSchedulePosition(index, assetListIndex) {
  22469. const scheduleItems = this.schedule.items;
  22470. if (!scheduleItems || this.playbackDisabled) {
  22471. return;
  22472. }
  22473. this.log(`setSchedulePosition ${index}, ${assetListIndex}`);
  22474. const scheduledItem = index >= 0 ? scheduleItems[index] : null;
  22475. const currentItem = this.playingItem;
  22476. const playingLastItem = this.playingLastItem;
  22477. if (this.isInterstitial(currentItem)) {
  22478. var _interstitial$assetLi;
  22479. const interstitial = currentItem.event;
  22480. const playingAsset = this.playingAsset;
  22481. const assetId = playingAsset == null ? void 0 : playingAsset.identifier;
  22482. const player = assetId ? this.getAssetPlayer(assetId) : null;
  22483. if (player && assetId && (!this.eventItemsMatch(currentItem, scheduledItem) || assetListIndex !== void 0 && assetId !== ((_interstitial$assetLi = interstitial.assetList) == null ? void 0 : _interstitial$assetLi[assetListIndex].identifier))) {
  22484. var _this$detachedData3;
  22485. const playingAssetListIndex = interstitial.findAssetIndex(playingAsset);
  22486. this.log(`INTERSTITIAL_ASSET_ENDED ${playingAssetListIndex + 1}/${interstitial.assetList.length} ${eventAssetToString(playingAsset)}`);
  22487. this.endedAsset = playingAsset;
  22488. this.playingAsset = null;
  22489. this.hls.trigger(Events.INTERSTITIAL_ASSET_ENDED, {
  22490. asset: playingAsset,
  22491. assetListIndex: playingAssetListIndex,
  22492. event: interstitial,
  22493. schedule: scheduleItems.slice(0),
  22494. scheduleIndex: index,
  22495. player
  22496. });
  22497. if (currentItem !== this.playingItem) {
  22498. if (this.itemsMatch(currentItem, this.playingItem) && !this.playingAsset) {
  22499. this.advanceAfterAssetEnded(interstitial, this.findItemIndex(this.playingItem), playingAssetListIndex);
  22500. }
  22501. return;
  22502. }
  22503. this.retreiveMediaSource(assetId, scheduledItem);
  22504. if (player.media && !((_this$detachedData3 = this.detachedData) != null && _this$detachedData3.mediaSource)) {
  22505. player.detachMedia();
  22506. }
  22507. }
  22508. if (!this.eventItemsMatch(currentItem, scheduledItem)) {
  22509. this.endedItem = currentItem;
  22510. this.playingItem = null;
  22511. this.log(`INTERSTITIAL_ENDED ${interstitial} ${segmentToString(currentItem)}`);
  22512. interstitial.hasPlayed = true;
  22513. this.hls.trigger(Events.INTERSTITIAL_ENDED, {
  22514. event: interstitial,
  22515. schedule: scheduleItems.slice(0),
  22516. scheduleIndex: index
  22517. });
  22518. if (interstitial.cue.once) {
  22519. this.updateSchedule();
  22520. const items = this.schedule.items;
  22521. if (scheduledItem && items) {
  22522. const updatedIndex = this.findItemIndex(scheduledItem);
  22523. this.advanceSchedule(updatedIndex, items, assetListIndex, currentItem, playingLastItem);
  22524. }
  22525. return;
  22526. }
  22527. }
  22528. }
  22529. this.advanceSchedule(index, scheduleItems, assetListIndex, currentItem, playingLastItem);
  22530. }
  22531. advanceSchedule(index, scheduleItems, assetListIndex, currentItem, playedLastItem) {
  22532. const scheduledItem = index >= 0 ? scheduleItems[index] : null;
  22533. const media = this.primaryMedia;
  22534. const playerQueue = this.playerQueue;
  22535. if (playerQueue.length) {
  22536. playerQueue.forEach((player) => {
  22537. const interstitial = player.interstitial;
  22538. const queuedIndex = this.schedule.findEventIndex(interstitial.identifier);
  22539. if (queuedIndex < index || queuedIndex > index + 1) {
  22540. this.clearInterstitial(interstitial, scheduledItem);
  22541. }
  22542. });
  22543. }
  22544. if (this.isInterstitial(scheduledItem)) {
  22545. this.timelinePos = Math.min(Math.max(this.timelinePos, scheduledItem.start), scheduledItem.end);
  22546. const interstitial = scheduledItem.event;
  22547. if (assetListIndex === void 0) {
  22548. assetListIndex = this.schedule.findAssetIndex(interstitial, this.timelinePos);
  22549. const assetIndexCandidate = getNextAssetIndex(interstitial, assetListIndex - 1);
  22550. if (interstitial.isAssetPastPlayoutLimit(assetIndexCandidate)) {
  22551. this.advanceAfterAssetEnded(interstitial, index, assetListIndex);
  22552. return;
  22553. }
  22554. assetListIndex = assetIndexCandidate;
  22555. }
  22556. const waitingItem = this.waitingItem;
  22557. if (!this.assetsBuffered(scheduledItem, media)) {
  22558. this.setBufferingItem(scheduledItem);
  22559. }
  22560. let player = this.preloadAssets(interstitial, assetListIndex);
  22561. if (!this.eventItemsMatch(scheduledItem, waitingItem || currentItem)) {
  22562. this.waitingItem = scheduledItem;
  22563. this.log(`INTERSTITIAL_STARTED ${segmentToString(scheduledItem)} ${interstitial.appendInPlace ? "append in place" : ""}`);
  22564. this.hls.trigger(Events.INTERSTITIAL_STARTED, {
  22565. event: interstitial,
  22566. schedule: scheduleItems.slice(0),
  22567. scheduleIndex: index
  22568. });
  22569. }
  22570. if (!interstitial.assetListLoaded) {
  22571. this.log(`Waiting for ASSET-LIST to complete loading ${interstitial}`);
  22572. return;
  22573. }
  22574. if (interstitial.assetListLoader) {
  22575. interstitial.assetListLoader.destroy();
  22576. interstitial.assetListLoader = void 0;
  22577. }
  22578. if (!media) {
  22579. this.log(`Waiting for attachMedia to start Interstitial ${interstitial}`);
  22580. return;
  22581. }
  22582. this.waitingItem = this.endedItem = null;
  22583. this.playingItem = scheduledItem;
  22584. const assetItem = interstitial.assetList[assetListIndex];
  22585. if (!assetItem) {
  22586. const nextItem = scheduleItems[index + 1];
  22587. const _media2 = this.media;
  22588. if (nextItem && _media2 && !this.isInterstitial(nextItem) && _media2.currentTime < nextItem.start) {
  22589. _media2.currentTime = this.timelinePos = nextItem.start;
  22590. }
  22591. this.advanceAfterAssetEnded(interstitial, index, assetListIndex || 0);
  22592. return;
  22593. }
  22594. if (!player) {
  22595. player = this.getAssetPlayer(assetItem.identifier);
  22596. }
  22597. if (player === null || player.destroyed) {
  22598. const assetListLength = interstitial.assetList.length;
  22599. this.warn(`asset ${assetListIndex + 1}/${assetListLength} player destroyed ${interstitial}`);
  22600. player = this.createAssetPlayer(interstitial, assetItem, assetListIndex);
  22601. }
  22602. if (!this.eventItemsMatch(scheduledItem, this.bufferingItem)) {
  22603. if (interstitial.appendInPlace && this.isAssetBuffered(assetItem)) {
  22604. return;
  22605. }
  22606. }
  22607. this.startAssetPlayer(player, assetListIndex, scheduleItems, index, media);
  22608. if (this.shouldPlay) {
  22609. playWithCatch(player.media);
  22610. }
  22611. } else if (scheduledItem !== null) {
  22612. this.resumePrimary(scheduledItem, index, currentItem);
  22613. if (this.shouldPlay) {
  22614. playWithCatch(this.hls.media);
  22615. }
  22616. } else if (playedLastItem && this.isInterstitial(currentItem)) {
  22617. this.endedItem = null;
  22618. this.playingItem = currentItem;
  22619. if (!currentItem.event.appendInPlace) {
  22620. this.attachPrimary(this.schedule.durations.primary, null);
  22621. }
  22622. }
  22623. }
  22624. get playbackDisabled() {
  22625. return this.hls.config.enableInterstitialPlayback === false;
  22626. }
  22627. get primaryDetails() {
  22628. var _this$mediaSelection, _this$mediaSelection$;
  22629. return (_this$mediaSelection = this.mediaSelection) == null ? void 0 : (_this$mediaSelection$ = _this$mediaSelection.main) == null ? void 0 : _this$mediaSelection$.details;
  22630. }
  22631. get primaryLive() {
  22632. var _this$primaryDetails;
  22633. return !!((_this$primaryDetails = this.primaryDetails) != null && _this$primaryDetails.live);
  22634. }
  22635. resumePrimary(scheduledItem, index, fromItem) {
  22636. var _this$detachedData4;
  22637. this.playingItem = scheduledItem;
  22638. this.playingAsset = this.endedAsset = null;
  22639. this.waitingItem = this.endedItem = null;
  22640. this.bufferedToItem(scheduledItem);
  22641. this.log(`resuming ${segmentToString(scheduledItem)}`);
  22642. if (!((_this$detachedData4 = this.detachedData) != null && _this$detachedData4.mediaSource)) {
  22643. let timelinePos = this.timelinePos;
  22644. if (timelinePos < scheduledItem.start || timelinePos >= scheduledItem.end) {
  22645. timelinePos = this.getPrimaryResumption(scheduledItem, index);
  22646. this.timelinePos = timelinePos;
  22647. }
  22648. this.attachPrimary(timelinePos, scheduledItem);
  22649. }
  22650. if (!fromItem) {
  22651. return;
  22652. }
  22653. const scheduleItems = this.schedule.items;
  22654. if (!scheduleItems) {
  22655. return;
  22656. }
  22657. this.log(`INTERSTITIALS_PRIMARY_RESUMED ${segmentToString(scheduledItem)}`);
  22658. this.hls.trigger(Events.INTERSTITIALS_PRIMARY_RESUMED, {
  22659. schedule: scheduleItems.slice(0),
  22660. scheduleIndex: index
  22661. });
  22662. this.checkBuffer();
  22663. }
  22664. getPrimaryResumption(scheduledItem, index) {
  22665. const itemStart = scheduledItem.start;
  22666. if (this.primaryLive) {
  22667. const details = this.primaryDetails;
  22668. if (index === 0) {
  22669. return this.hls.startPosition;
  22670. } else if (details && (itemStart < details.fragmentStart || itemStart > details.edge)) {
  22671. return this.hls.liveSyncPosition || -1;
  22672. }
  22673. }
  22674. return itemStart;
  22675. }
  22676. isAssetBuffered(asset) {
  22677. const player = this.getAssetPlayer(asset.identifier);
  22678. if (player != null && player.hls) {
  22679. return player.hls.bufferedToEnd;
  22680. }
  22681. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);
  22682. return bufferInfo.end + 1 >= asset.timelineStart + (asset.duration || 0);
  22683. }
  22684. attachPrimary(timelinePos, item, skipSeekToStartPosition) {
  22685. if (item) {
  22686. this.setBufferingItem(item);
  22687. } else {
  22688. this.bufferingItem = this.playingItem;
  22689. }
  22690. this.bufferingAsset = null;
  22691. const media = this.primaryMedia;
  22692. if (!media) {
  22693. return;
  22694. }
  22695. const hls = this.hls;
  22696. if (hls.media) {
  22697. this.checkBuffer();
  22698. } else {
  22699. this.transferMediaTo(hls, media);
  22700. if (skipSeekToStartPosition) {
  22701. this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);
  22702. }
  22703. }
  22704. if (!skipSeekToStartPosition) {
  22705. this.timelinePos = timelinePos;
  22706. this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);
  22707. }
  22708. }
  22709. startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition) {
  22710. var _hls$mainForwardBuffe;
  22711. const hls = this.hls;
  22712. if (!hls.loadingEnabled || !hls.media || Math.abs((((_hls$mainForwardBuffe = hls.mainForwardBufferInfo) == null ? void 0 : _hls$mainForwardBuffe.start) || hls.media.currentTime) - timelinePos) > 0.5) {
  22713. hls.startLoad(timelinePos, skipSeekToStartPosition);
  22714. } else if (!hls.bufferingEnabled) {
  22715. hls.resumeBuffering();
  22716. }
  22717. }
  22718. // HLS.js event callbacks
  22719. onManifestLoading() {
  22720. this.stopLoad();
  22721. this.schedule.reset();
  22722. this.emptyPlayerQueue();
  22723. this.clearScheduleState();
  22724. this.shouldPlay = false;
  22725. this.bufferedPos = this.timelinePos = -1;
  22726. this.mediaSelection = this.altSelection = this.manager = this.requiredTracks = null;
  22727. this.hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  22728. this.hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  22729. }
  22730. onLevelUpdated(event, data) {
  22731. if (data.level === -1) {
  22732. return;
  22733. }
  22734. const main = this.hls.levels[data.level];
  22735. const currentSelection = _objectSpread2(_objectSpread2({}, this.mediaSelection || this.altSelection), {}, {
  22736. main
  22737. });
  22738. this.mediaSelection = currentSelection;
  22739. this.schedule.parseInterstitialDateRanges(currentSelection, this.hls.config.interstitialAppendInPlace);
  22740. if (!this.effectivePlayingItem && this.schedule.items) {
  22741. this.checkStart();
  22742. }
  22743. }
  22744. onAudioTrackUpdated(event, data) {
  22745. const audio = this.hls.audioTracks[data.id];
  22746. const previousSelection = this.mediaSelection;
  22747. if (!previousSelection) {
  22748. this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {
  22749. audio
  22750. });
  22751. return;
  22752. }
  22753. const currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {
  22754. audio
  22755. });
  22756. this.mediaSelection = currentSelection;
  22757. }
  22758. onSubtitleTrackUpdated(event, data) {
  22759. const subtitles = this.hls.subtitleTracks[data.id];
  22760. const previousSelection = this.mediaSelection;
  22761. if (!previousSelection) {
  22762. this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {
  22763. subtitles
  22764. });
  22765. return;
  22766. }
  22767. const currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {
  22768. subtitles
  22769. });
  22770. this.mediaSelection = currentSelection;
  22771. }
  22772. onAudioTrackSwitching(event, data) {
  22773. const audioOption = getBasicSelectionOption(data);
  22774. this.playerQueue.forEach((player) => player.hls.setAudioOption(data) || player.hls.setAudioOption(audioOption));
  22775. }
  22776. onSubtitleTrackSwitch(event, data) {
  22777. const subtitleOption = getBasicSelectionOption(data);
  22778. this.playerQueue.forEach((player) => player.hls.setSubtitleOption(data) || data.id !== -1 && player.hls.setSubtitleOption(subtitleOption));
  22779. }
  22780. onBufferCodecs(event, data) {
  22781. const requiredTracks = data.tracks;
  22782. if (requiredTracks) {
  22783. this.requiredTracks = requiredTracks;
  22784. }
  22785. }
  22786. onBufferAppended(event, data) {
  22787. this.checkBuffer();
  22788. }
  22789. onBufferFlushed(event, data) {
  22790. const playingItem = this.playingItem;
  22791. if (playingItem && !this.itemsMatch(playingItem, this.bufferingItem) && !this.isInterstitial(playingItem)) {
  22792. const timelinePos = this.timelinePos;
  22793. this.bufferedPos = timelinePos;
  22794. this.checkBuffer();
  22795. }
  22796. }
  22797. onBufferedToEnd(event) {
  22798. const interstitialEvents = this.schedule.events;
  22799. if (this.bufferedPos < Number.MAX_VALUE && interstitialEvents) {
  22800. for (let i = 0; i < interstitialEvents.length; i++) {
  22801. const interstitial = interstitialEvents[i];
  22802. if (interstitial.cue.post) {
  22803. var _this$schedule$items;
  22804. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  22805. const item = (_this$schedule$items = this.schedule.items) == null ? void 0 : _this$schedule$items[scheduleIndex];
  22806. if (this.isInterstitial(item) && this.eventItemsMatch(item, this.bufferingItem)) {
  22807. this.bufferedToItem(item, 0);
  22808. }
  22809. break;
  22810. }
  22811. }
  22812. this.bufferedPos = Number.MAX_VALUE;
  22813. }
  22814. }
  22815. onMediaEnded(event) {
  22816. const playingItem = this.playingItem;
  22817. if (!this.playingLastItem && playingItem) {
  22818. const playingIndex = this.findItemIndex(playingItem);
  22819. this.setSchedulePosition(playingIndex + 1);
  22820. } else {
  22821. this.shouldPlay = false;
  22822. }
  22823. }
  22824. updateItem(previousItem, time) {
  22825. const items = this.schedule.items;
  22826. if (previousItem && items) {
  22827. const index = this.findItemIndex(previousItem, time);
  22828. return items[index] || null;
  22829. }
  22830. return null;
  22831. }
  22832. trimInPlace(updatedItem, itemBeforeUpdate) {
  22833. if (this.isInterstitial(updatedItem) && updatedItem.event.appendInPlace && itemBeforeUpdate.end - updatedItem.end > 0.25) {
  22834. updatedItem.event.assetList.forEach((asset, index) => {
  22835. if (updatedItem.event.isAssetPastPlayoutLimit(index)) {
  22836. this.clearAssetPlayer(asset.identifier, null);
  22837. }
  22838. });
  22839. const flushStart = updatedItem.end + 0.25;
  22840. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, flushStart, 0);
  22841. if (bufferInfo.end > flushStart || (bufferInfo.nextStart || 0) > flushStart) {
  22842. this.attachPrimary(flushStart, null);
  22843. this.flushFrontBuffer(flushStart);
  22844. }
  22845. }
  22846. }
  22847. itemsMatch(a, b) {
  22848. return !!b && (a === b || a.event && b.event && this.eventItemsMatch(a, b) || !a.event && !b.event && this.findItemIndex(a) === this.findItemIndex(b));
  22849. }
  22850. eventItemsMatch(a, b) {
  22851. var _b$event;
  22852. return !!b && (a === b || a.event.identifier === ((_b$event = b.event) == null ? void 0 : _b$event.identifier));
  22853. }
  22854. findItemIndex(item, time) {
  22855. return item ? this.schedule.findItemIndex(item, time) : -1;
  22856. }
  22857. updateSchedule() {
  22858. const mediaSelection = this.mediaSelection;
  22859. if (!mediaSelection) {
  22860. return;
  22861. }
  22862. this.schedule.updateSchedule(mediaSelection, []);
  22863. }
  22864. // Schedule buffer control
  22865. checkBuffer(starved) {
  22866. const items = this.schedule.items;
  22867. if (!items) {
  22868. return;
  22869. }
  22870. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);
  22871. if (starved) {
  22872. this.bufferedPos = this.timelinePos;
  22873. }
  22874. starved || (starved = bufferInfo.len < 1);
  22875. this.updateBufferedPos(bufferInfo.end, items, starved);
  22876. }
  22877. updateBufferedPos(bufferEnd, items, bufferIsEmpty) {
  22878. const schedule = this.schedule;
  22879. const bufferingItem = this.bufferingItem;
  22880. if (this.bufferedPos > bufferEnd) {
  22881. return;
  22882. }
  22883. if (items.length === 1 && this.itemsMatch(items[0], bufferingItem)) {
  22884. this.bufferedPos = bufferEnd;
  22885. return;
  22886. }
  22887. const playingItem = this.playingItem;
  22888. const playingIndex = this.findItemIndex(playingItem);
  22889. let bufferEndIndex = schedule.findItemIndexAtTime(bufferEnd);
  22890. if (this.bufferedPos < bufferEnd) {
  22891. var _nextItemToBuffer$eve, _bufferingItem$event;
  22892. const bufferingIndex = this.findItemIndex(bufferingItem);
  22893. const nextToBufferIndex = Math.min(bufferingIndex + 1, items.length - 1);
  22894. const nextItemToBuffer = items[nextToBufferIndex];
  22895. if (bufferEndIndex === -1 && bufferingItem && bufferEnd >= bufferingItem.end || (_nextItemToBuffer$eve = nextItemToBuffer.event) != null && _nextItemToBuffer$eve.appendInPlace && bufferEnd + 0.01 >= nextItemToBuffer.start) {
  22896. bufferEndIndex = nextToBufferIndex;
  22897. }
  22898. if (nextToBufferIndex - playingIndex > 1 && (bufferingItem == null ? void 0 : (_bufferingItem$event = bufferingItem.event) == null ? void 0 : _bufferingItem$event.appendInPlace) === false) {
  22899. return;
  22900. }
  22901. this.bufferedPos = bufferEnd;
  22902. if (bufferEndIndex > bufferingIndex && bufferEndIndex > playingIndex) {
  22903. this.bufferedToItem(nextItemToBuffer);
  22904. } else {
  22905. const details = this.primaryDetails;
  22906. if (this.primaryLive && details && bufferEnd > details.edge - details.targetduration && nextItemToBuffer.start < details.edge + this.hls.config.interstitialLiveLookAhead && this.isInterstitial(nextItemToBuffer)) {
  22907. this.preloadAssets(nextItemToBuffer.event, 0);
  22908. }
  22909. }
  22910. } else if (bufferIsEmpty && playingItem && !this.itemsMatch(playingItem, bufferingItem)) {
  22911. if (bufferEndIndex === playingIndex) {
  22912. this.bufferedToItem(playingItem);
  22913. } else if (bufferEndIndex === playingIndex + 1) {
  22914. this.bufferedToItem(items[bufferEndIndex]);
  22915. }
  22916. }
  22917. }
  22918. assetsBuffered(item, media) {
  22919. const assetList = item.event.assetList;
  22920. if (assetList.length === 0) {
  22921. return false;
  22922. }
  22923. return !item.event.assetList.some((asset) => {
  22924. const player = this.getAssetPlayer(asset.identifier);
  22925. return !(player != null && player.bufferedInPlaceToEnd(media));
  22926. });
  22927. }
  22928. setBufferingItem(item) {
  22929. const bufferingLast = this.bufferingItem;
  22930. const schedule = this.schedule;
  22931. if (!this.itemsMatch(item, bufferingLast)) {
  22932. const {
  22933. items,
  22934. events
  22935. } = schedule;
  22936. if (!items || !events) {
  22937. return bufferingLast;
  22938. }
  22939. const isInterstitial = this.isInterstitial(item);
  22940. const bufferingPlayer = this.getBufferingPlayer();
  22941. this.bufferingItem = item;
  22942. this.bufferedPos = Math.max(item.start, Math.min(item.end, this.timelinePos));
  22943. const timeRemaining = bufferingPlayer ? bufferingPlayer.remaining : bufferingLast ? bufferingLast.end - this.timelinePos : 0;
  22944. this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${segmentToString(item)}` + (bufferingLast ? ` (${timeRemaining.toFixed(2)} remaining)` : ""));
  22945. if (!this.playbackDisabled) {
  22946. if (isInterstitial) {
  22947. item.event.assetList.forEach((asset) => {
  22948. const player = this.getAssetPlayer(asset.identifier);
  22949. if (player) {
  22950. player.resumeBuffering();
  22951. }
  22952. });
  22953. } else {
  22954. this.hls.resumeBuffering();
  22955. this.playerQueue.forEach((player) => player.pauseBuffering());
  22956. }
  22957. }
  22958. this.hls.trigger(Events.INTERSTITIALS_BUFFERED_TO_BOUNDARY, {
  22959. events: events.slice(0),
  22960. schedule: items.slice(0),
  22961. bufferingIndex: this.findItemIndex(item),
  22962. playingIndex: this.findItemIndex(this.playingItem)
  22963. });
  22964. } else if (this.bufferingItem !== item) {
  22965. this.bufferingItem = item;
  22966. }
  22967. return bufferingLast;
  22968. }
  22969. bufferedToItem(item, assetListIndex = 0) {
  22970. const bufferingLast = this.setBufferingItem(item);
  22971. if (this.playbackDisabled) {
  22972. return;
  22973. }
  22974. if (this.isInterstitial(item)) {
  22975. this.bufferedToEvent(item, assetListIndex);
  22976. } else if (bufferingLast !== null) {
  22977. this.bufferingAsset = null;
  22978. const detachedData = this.detachedData;
  22979. if (detachedData) {
  22980. if (detachedData.mediaSource) {
  22981. const skipSeekToStartPosition = true;
  22982. this.attachPrimary(item.start, item, skipSeekToStartPosition);
  22983. } else {
  22984. this.preloadPrimary(item);
  22985. }
  22986. } else {
  22987. this.preloadPrimary(item);
  22988. }
  22989. }
  22990. }
  22991. preloadPrimary(item) {
  22992. const index = this.findItemIndex(item);
  22993. const timelinePos = this.getPrimaryResumption(item, index);
  22994. this.startLoadingPrimaryAt(timelinePos);
  22995. }
  22996. bufferedToEvent(item, assetListIndex) {
  22997. const interstitial = item.event;
  22998. const neverLoaded = interstitial.assetList.length === 0 && !interstitial.assetListLoader;
  22999. const playOnce = interstitial.cue.once;
  23000. if (neverLoaded || !playOnce) {
  23001. const player = this.preloadAssets(interstitial, assetListIndex);
  23002. if (player != null && player.interstitial.appendInPlace) {
  23003. const assetItem = interstitial.assetList[assetListIndex];
  23004. const media = this.primaryMedia;
  23005. if (assetItem && media) {
  23006. this.bufferAssetPlayer(player, media);
  23007. }
  23008. }
  23009. }
  23010. }
  23011. preloadAssets(interstitial, assetListIndex) {
  23012. const uri = interstitial.assetUrl;
  23013. const assetListLength = interstitial.assetList.length;
  23014. const neverLoaded = assetListLength === 0 && !interstitial.assetListLoader;
  23015. const playOnce = interstitial.cue.once;
  23016. if (neverLoaded) {
  23017. const timelineStart = interstitial.timelineStart;
  23018. if (interstitial.appendInPlace) {
  23019. var _playingItem$nextEven;
  23020. const playingItem = this.playingItem;
  23021. if (!this.isInterstitial(playingItem) && (playingItem == null ? void 0 : (_playingItem$nextEven = playingItem.nextEvent) == null ? void 0 : _playingItem$nextEven.identifier) === interstitial.identifier) {
  23022. this.flushFrontBuffer(timelineStart + 0.25);
  23023. }
  23024. }
  23025. let hlsStartOffset;
  23026. let liveStartPosition = 0;
  23027. if (!this.playingItem && this.primaryLive) {
  23028. liveStartPosition = this.hls.startPosition;
  23029. if (liveStartPosition === -1) {
  23030. liveStartPosition = this.hls.liveSyncPosition || 0;
  23031. }
  23032. }
  23033. if (liveStartPosition && !(interstitial.cue.pre || interstitial.cue.post)) {
  23034. const startOffset = liveStartPosition - timelineStart;
  23035. if (startOffset > 0) {
  23036. hlsStartOffset = Math.round(startOffset * 1e3) / 1e3;
  23037. }
  23038. }
  23039. this.log(`Load interstitial asset ${assetListIndex + 1}/${uri ? 1 : assetListLength} ${interstitial}${hlsStartOffset ? ` live-start: ${liveStartPosition} start-offset: ${hlsStartOffset}` : ""}`);
  23040. if (uri) {
  23041. return this.createAsset(interstitial, 0, 0, timelineStart, interstitial.duration, uri);
  23042. }
  23043. const assetListLoader = this.assetListLoader.loadAssetList(interstitial, hlsStartOffset);
  23044. if (assetListLoader) {
  23045. interstitial.assetListLoader = assetListLoader;
  23046. }
  23047. } else if (!playOnce && assetListLength) {
  23048. for (let i = assetListIndex; i < assetListLength; i++) {
  23049. const asset = interstitial.assetList[i];
  23050. const playerIndex = this.getAssetPlayerQueueIndex(asset.identifier);
  23051. if ((playerIndex === -1 || this.playerQueue[playerIndex].destroyed) && !asset.error) {
  23052. this.createAssetPlayer(interstitial, asset, i);
  23053. }
  23054. }
  23055. return this.getAssetPlayer(interstitial.assetList[assetListIndex].identifier);
  23056. }
  23057. return null;
  23058. }
  23059. flushFrontBuffer(startOffset) {
  23060. const requiredTracks = this.requiredTracks;
  23061. if (!requiredTracks) {
  23062. return;
  23063. }
  23064. this.log(`Removing front buffer starting at ${startOffset}`);
  23065. const sourceBufferNames = Object.keys(requiredTracks);
  23066. sourceBufferNames.forEach((type) => {
  23067. this.hls.trigger(Events.BUFFER_FLUSHING, {
  23068. startOffset,
  23069. endOffset: Infinity,
  23070. type
  23071. });
  23072. });
  23073. }
  23074. // Interstitial Asset Player control
  23075. getAssetPlayerQueueIndex(assetId) {
  23076. const playerQueue = this.playerQueue;
  23077. for (let i = 0; i < playerQueue.length; i++) {
  23078. if (assetId === playerQueue[i].assetId) {
  23079. return i;
  23080. }
  23081. }
  23082. return -1;
  23083. }
  23084. getAssetPlayer(assetId) {
  23085. const index = this.getAssetPlayerQueueIndex(assetId);
  23086. return this.playerQueue[index] || null;
  23087. }
  23088. getBufferingPlayer() {
  23089. const {
  23090. playerQueue,
  23091. primaryMedia
  23092. } = this;
  23093. if (primaryMedia) {
  23094. for (let i = 0; i < playerQueue.length; i++) {
  23095. if (playerQueue[i].media === primaryMedia) {
  23096. return playerQueue[i];
  23097. }
  23098. }
  23099. }
  23100. return null;
  23101. }
  23102. createAsset(interstitial, assetListIndex, startOffset, timelineStart, duration, uri) {
  23103. const assetItem = {
  23104. parentIdentifier: interstitial.identifier,
  23105. identifier: generateAssetIdentifier(interstitial, uri, assetListIndex),
  23106. duration,
  23107. startOffset,
  23108. timelineStart,
  23109. uri
  23110. };
  23111. return this.createAssetPlayer(interstitial, assetItem, assetListIndex);
  23112. }
  23113. createAssetPlayer(interstitial, assetItem, assetListIndex) {
  23114. const primary = this.hls;
  23115. const userConfig = primary.userConfig;
  23116. let videoPreference = userConfig.videoPreference;
  23117. const currentLevel = primary.loadLevelObj || primary.levels[primary.currentLevel];
  23118. if (videoPreference || currentLevel) {
  23119. videoPreference = _extends({}, videoPreference);
  23120. if (currentLevel.videoCodec) {
  23121. videoPreference.videoCodec = currentLevel.videoCodec;
  23122. }
  23123. if (currentLevel.videoRange) {
  23124. videoPreference.allowedVideoRanges = [currentLevel.videoRange];
  23125. }
  23126. }
  23127. const selectedAudio = primary.audioTracks[primary.audioTrack];
  23128. const selectedSubtitle = primary.subtitleTracks[primary.subtitleTrack];
  23129. let startPosition = 0;
  23130. if (this.primaryLive || interstitial.appendInPlace) {
  23131. const timePastStart = this.timelinePos - assetItem.timelineStart;
  23132. if (timePastStart > 1) {
  23133. const duration = assetItem.duration;
  23134. if (duration && timePastStart < duration) {
  23135. startPosition = timePastStart;
  23136. }
  23137. }
  23138. }
  23139. const assetId = assetItem.identifier;
  23140. const playerConfig = _objectSpread2(_objectSpread2({}, userConfig), {}, {
  23141. autoStartLoad: true,
  23142. startFragPrefetch: true,
  23143. primarySessionId: primary.sessionId,
  23144. assetPlayerId: assetId,
  23145. abrEwmaDefaultEstimate: primary.bandwidthEstimate,
  23146. interstitialsController: void 0,
  23147. startPosition,
  23148. liveDurationInfinity: false,
  23149. testBandwidth: false,
  23150. videoPreference,
  23151. audioPreference: selectedAudio || userConfig.audioPreference,
  23152. subtitlePreference: selectedSubtitle || userConfig.subtitlePreference
  23153. });
  23154. if (interstitial.appendInPlace) {
  23155. interstitial.appendInPlaceStarted = true;
  23156. if (assetItem.timelineStart) {
  23157. playerConfig.timelineOffset = assetItem.timelineStart;
  23158. }
  23159. }
  23160. const cmcd = playerConfig.cmcd;
  23161. if (cmcd != null && cmcd.sessionId && cmcd.contentId) {
  23162. playerConfig.cmcd = _extends({}, cmcd, {
  23163. contentId: hash(assetItem.uri)
  23164. });
  23165. }
  23166. if (this.getAssetPlayer(assetId)) {
  23167. this.warn(`Duplicate date range identifier ${interstitial} and asset ${assetId}`);
  23168. }
  23169. const player = new HlsAssetPlayer(this.HlsPlayerClass, playerConfig, interstitial, assetItem);
  23170. this.playerQueue.push(player);
  23171. interstitial.assetList[assetListIndex] = assetItem;
  23172. const updateAssetPlayerDetails = (details) => {
  23173. if (details.live) {
  23174. const error = new Error(`Interstitials MUST be VOD assets ${interstitial}`);
  23175. const errorData = {
  23176. fatal: true,
  23177. type: ErrorTypes.OTHER_ERROR,
  23178. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  23179. error
  23180. };
  23181. this.handleAssetItemError(errorData, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, error.message);
  23182. return;
  23183. }
  23184. const duration = details.edge - details.fragmentStart;
  23185. const currentAssetDuration = assetItem.duration;
  23186. if (currentAssetDuration === null || duration > currentAssetDuration) {
  23187. this.log(`Interstitial asset "${assetId}" duration change ${currentAssetDuration} > ${duration}`);
  23188. assetItem.duration = duration;
  23189. this.updateSchedule();
  23190. }
  23191. };
  23192. player.on(Events.LEVEL_UPDATED, (event, {
  23193. details
  23194. }) => updateAssetPlayerDetails(details));
  23195. player.on(Events.LEVEL_PTS_UPDATED, (event, {
  23196. details
  23197. }) => updateAssetPlayerDetails(details));
  23198. const onBufferCodecs = (event, data) => {
  23199. const inQueuPlayer = this.getAssetPlayer(assetId);
  23200. if (inQueuPlayer && data.tracks) {
  23201. inQueuPlayer.off(Events.BUFFER_CODECS, onBufferCodecs);
  23202. inQueuPlayer.tracks = data.tracks;
  23203. const media = this.primaryMedia;
  23204. if (this.bufferingAsset === inQueuPlayer.assetItem && media && !inQueuPlayer.media) {
  23205. this.bufferAssetPlayer(inQueuPlayer, media);
  23206. }
  23207. }
  23208. };
  23209. player.on(Events.BUFFER_CODECS, onBufferCodecs);
  23210. const bufferedToEnd = () => {
  23211. var _this$schedule$items2;
  23212. const inQueuPlayer = this.getAssetPlayer(assetId);
  23213. this.log(`buffered to end of asset ${inQueuPlayer}`);
  23214. if (!inQueuPlayer) {
  23215. return;
  23216. }
  23217. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  23218. const item = (_this$schedule$items2 = this.schedule.items) == null ? void 0 : _this$schedule$items2[scheduleIndex];
  23219. if (this.isInterstitial(item)) {
  23220. const assetListIndex2 = interstitial.findAssetIndex(assetItem);
  23221. const nextAssetIndex = getNextAssetIndex(interstitial, assetListIndex2);
  23222. if (!interstitial.isAssetPastPlayoutLimit(nextAssetIndex)) {
  23223. this.bufferedToItem(item, nextAssetIndex);
  23224. } else {
  23225. var _this$schedule$items3;
  23226. const nextItem = (_this$schedule$items3 = this.schedule.items) == null ? void 0 : _this$schedule$items3[scheduleIndex + 1];
  23227. if (nextItem) {
  23228. this.bufferedToItem(nextItem);
  23229. }
  23230. }
  23231. }
  23232. };
  23233. player.on(Events.BUFFERED_TO_END, bufferedToEnd);
  23234. const endedWithAssetIndex = (assetIndex) => {
  23235. return () => {
  23236. const inQueuPlayer = this.getAssetPlayer(assetId);
  23237. if (!inQueuPlayer) {
  23238. return;
  23239. }
  23240. this.shouldPlay = true;
  23241. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  23242. this.advanceAfterAssetEnded(interstitial, scheduleIndex, assetIndex);
  23243. };
  23244. };
  23245. player.once(Events.MEDIA_ENDED, endedWithAssetIndex(assetListIndex));
  23246. player.once(Events.PLAYOUT_LIMIT_REACHED, endedWithAssetIndex(Infinity));
  23247. player.on(Events.ERROR, (event, data) => {
  23248. const inQueuPlayer = this.getAssetPlayer(assetId);
  23249. if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {
  23250. if (inQueuPlayer != null && inQueuPlayer.media) {
  23251. const assetCurrentTime = inQueuPlayer.currentTime;
  23252. const distanceFromEnd = inQueuPlayer.duration - assetCurrentTime;
  23253. if (assetCurrentTime && interstitial.appendInPlace && distanceFromEnd / inQueuPlayer.media.playbackRate < 0.5) {
  23254. this.log(`Advancing buffer past end of asset ${assetId} ${interstitial} at ${inQueuPlayer.media.currentTime}`);
  23255. bufferedToEnd();
  23256. } else {
  23257. this.warn(`Stalled at ${assetCurrentTime} of ${assetCurrentTime + distanceFromEnd} in asset ${assetId} ${interstitial}`);
  23258. this.onTimeupdate();
  23259. this.checkBuffer(true);
  23260. }
  23261. }
  23262. return;
  23263. }
  23264. this.handleAssetItemError(data, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, `Asset player error ${data.error} ${interstitial}`);
  23265. });
  23266. player.on(Events.DESTROYING, () => {
  23267. const inQueuPlayer = this.getAssetPlayer(assetId);
  23268. if (!inQueuPlayer) {
  23269. return;
  23270. }
  23271. const error = new Error(`Asset player destroyed unexpectedly ${assetId}`);
  23272. const errorData = {
  23273. fatal: true,
  23274. type: ErrorTypes.OTHER_ERROR,
  23275. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  23276. error
  23277. };
  23278. this.handleAssetItemError(errorData, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, error.message);
  23279. });
  23280. this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${eventAssetToString(assetItem)}`);
  23281. this.hls.trigger(Events.INTERSTITIAL_ASSET_PLAYER_CREATED, {
  23282. asset: assetItem,
  23283. assetListIndex,
  23284. event: interstitial,
  23285. player
  23286. });
  23287. return player;
  23288. }
  23289. clearInterstitial(interstitial, toSegment) {
  23290. interstitial.assetList.forEach((asset) => {
  23291. this.clearAssetPlayer(asset.identifier, toSegment);
  23292. });
  23293. interstitial.reset();
  23294. }
  23295. resetAssetPlayer(assetId) {
  23296. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  23297. if (playerIndex !== -1) {
  23298. this.log(`reset asset player "${assetId}" after error`);
  23299. const player = this.playerQueue[playerIndex];
  23300. this.transferMediaFromPlayer(player, null);
  23301. player.resetDetails();
  23302. }
  23303. }
  23304. clearAssetPlayer(assetId, toSegment) {
  23305. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  23306. if (playerIndex !== -1) {
  23307. this.log(`clear asset player "${assetId}" toSegment: ${toSegment ? segmentToString(toSegment) : toSegment}`);
  23308. const player = this.playerQueue[playerIndex];
  23309. this.transferMediaFromPlayer(player, toSegment);
  23310. this.playerQueue.splice(playerIndex, 1);
  23311. player.destroy();
  23312. }
  23313. }
  23314. emptyPlayerQueue() {
  23315. let player;
  23316. while (player = this.playerQueue.pop()) {
  23317. player.destroy();
  23318. }
  23319. this.playerQueue = [];
  23320. }
  23321. startAssetPlayer(player, assetListIndex, scheduleItems, scheduleIndex, media) {
  23322. const {
  23323. interstitial,
  23324. assetItem,
  23325. assetId
  23326. } = player;
  23327. const assetListLength = interstitial.assetList.length;
  23328. const playingAsset = this.playingAsset;
  23329. this.endedAsset = null;
  23330. this.playingAsset = assetItem;
  23331. if (!playingAsset || playingAsset.identifier !== assetId) {
  23332. if (playingAsset) {
  23333. this.clearAssetPlayer(playingAsset.identifier, scheduleItems[scheduleIndex]);
  23334. delete playingAsset.error;
  23335. }
  23336. this.log(`INTERSTITIAL_ASSET_STARTED ${assetListIndex + 1}/${assetListLength} ${eventAssetToString(assetItem)}`);
  23337. this.hls.trigger(Events.INTERSTITIAL_ASSET_STARTED, {
  23338. asset: assetItem,
  23339. assetListIndex,
  23340. event: interstitial,
  23341. schedule: scheduleItems.slice(0),
  23342. scheduleIndex,
  23343. player
  23344. });
  23345. }
  23346. this.bufferAssetPlayer(player, media);
  23347. }
  23348. bufferAssetPlayer(player, media) {
  23349. var _this$schedule$items4, _this$detachedData5;
  23350. const {
  23351. interstitial,
  23352. assetItem
  23353. } = player;
  23354. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  23355. const item = (_this$schedule$items4 = this.schedule.items) == null ? void 0 : _this$schedule$items4[scheduleIndex];
  23356. if (!item) {
  23357. return;
  23358. }
  23359. this.setBufferingItem(item);
  23360. this.bufferingAsset = assetItem;
  23361. const bufferingPlayer = this.getBufferingPlayer();
  23362. if (bufferingPlayer === player) {
  23363. return;
  23364. }
  23365. const appendInPlaceNext = interstitial.appendInPlace;
  23366. if (appendInPlaceNext && (bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial.appendInPlace) === false) {
  23367. return;
  23368. }
  23369. const activeTracks = (bufferingPlayer == null ? void 0 : bufferingPlayer.tracks) || ((_this$detachedData5 = this.detachedData) == null ? void 0 : _this$detachedData5.tracks) || this.requiredTracks;
  23370. if (appendInPlaceNext && assetItem !== this.playingAsset) {
  23371. if (!player.tracks) {
  23372. return;
  23373. }
  23374. if (activeTracks && !isCompatibleTrackChange(activeTracks, player.tracks)) {
  23375. const error = new Error(`Asset ${eventAssetToString(assetItem)} SourceBuffer tracks ('${Object.keys(player.tracks)}') are not compatible with primary content tracks ('${Object.keys(activeTracks)}')`);
  23376. const errorData = {
  23377. fatal: true,
  23378. type: ErrorTypes.OTHER_ERROR,
  23379. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  23380. error
  23381. };
  23382. const assetListIndex = interstitial.findAssetIndex(assetItem);
  23383. this.handleAssetItemError(errorData, interstitial, scheduleIndex, assetListIndex, error.message);
  23384. return;
  23385. }
  23386. }
  23387. this.transferMediaTo(player, media);
  23388. }
  23389. handleAssetItemError(data, interstitial, scheduleIndex, assetListIndex, errorMessage) {
  23390. if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {
  23391. return;
  23392. }
  23393. const assetItem = interstitial.assetList[assetListIndex];
  23394. this.warn(`INTERSTITIAL_ASSET_ERROR ${assetItem ? eventAssetToString(assetItem) : assetItem} ${data.error}`);
  23395. const assetId = assetItem == null ? void 0 : assetItem.identifier;
  23396. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  23397. const player = this.playerQueue[playerIndex] || null;
  23398. const items = this.schedule.items;
  23399. const interstitialAssetError = _extends({}, data, {
  23400. fatal: false,
  23401. errorAction: createDoNothingErrorAction(true),
  23402. asset: assetItem,
  23403. assetListIndex,
  23404. event: interstitial,
  23405. schedule: items,
  23406. scheduleIndex,
  23407. player
  23408. });
  23409. this.hls.trigger(Events.INTERSTITIAL_ASSET_ERROR, interstitialAssetError);
  23410. if (!data.fatal) {
  23411. return;
  23412. }
  23413. const playingAsset = this.playingAsset;
  23414. const error = new Error(errorMessage);
  23415. if (assetItem) {
  23416. this.clearAssetPlayer(assetId, null);
  23417. assetItem.error = error;
  23418. }
  23419. if (!interstitial.assetList.some((asset) => !asset.error)) {
  23420. interstitial.error = error;
  23421. } else {
  23422. for (let i = assetListIndex; i < interstitial.assetList.length; i++) {
  23423. this.resetAssetPlayer(interstitial.assetList[i].identifier);
  23424. }
  23425. this.updateSchedule();
  23426. }
  23427. if (interstitial.error) {
  23428. this.primaryFallback(interstitial);
  23429. } else if (playingAsset && playingAsset.identifier === assetId) {
  23430. this.advanceAfterAssetEnded(interstitial, scheduleIndex, assetListIndex);
  23431. }
  23432. }
  23433. primaryFallback(interstitial) {
  23434. const flushStart = interstitial.timelineStart;
  23435. const playingItem = this.effectivePlayingItem;
  23436. this.updateSchedule();
  23437. if (playingItem) {
  23438. this.log(`Fallback to primary from event "${interstitial.identifier}" start: ${flushStart} pos: ${this.timelinePos} playing: ${playingItem ? segmentToString(playingItem) : "<none>"} error: ${interstitial.error}`);
  23439. let timelinePos = this.timelinePos;
  23440. if (timelinePos === -1) {
  23441. timelinePos = this.hls.startPosition;
  23442. }
  23443. const newPlayingItem = this.updateItem(playingItem, timelinePos);
  23444. if (this.itemsMatch(playingItem, newPlayingItem)) {
  23445. this.clearInterstitial(interstitial, null);
  23446. }
  23447. if (interstitial.appendInPlace) {
  23448. this.attachPrimary(flushStart, null);
  23449. this.flushFrontBuffer(flushStart);
  23450. }
  23451. const scheduleIndex = this.schedule.findItemIndexAtTime(timelinePos);
  23452. this.setSchedulePosition(scheduleIndex);
  23453. } else {
  23454. this.checkStart();
  23455. }
  23456. }
  23457. // Asset List loading
  23458. onAssetListLoaded(event, data) {
  23459. var _this$bufferingItem2;
  23460. const interstitial = data.event;
  23461. const interstitialId = interstitial.identifier;
  23462. const assets = data.assetListResponse.ASSETS;
  23463. if (!this.schedule.hasEvent(interstitialId)) {
  23464. return;
  23465. }
  23466. const eventStart = interstitial.timelineStart;
  23467. const previousDuration = interstitial.duration;
  23468. let sumDuration = 0;
  23469. assets.forEach((asset, assetListIndex) => {
  23470. const duration = parseFloat(asset.DURATION);
  23471. this.createAsset(interstitial, assetListIndex, sumDuration, eventStart + sumDuration, duration, asset.URI);
  23472. sumDuration += duration;
  23473. });
  23474. interstitial.duration = sumDuration;
  23475. this.log(`Loaded asset-list with duration: ${sumDuration} (was: ${previousDuration}) ${interstitial}`);
  23476. const waitingItem = this.waitingItem;
  23477. const waitingForItem = (waitingItem == null ? void 0 : waitingItem.event.identifier) === interstitialId;
  23478. this.updateSchedule();
  23479. const bufferingEvent = (_this$bufferingItem2 = this.bufferingItem) == null ? void 0 : _this$bufferingItem2.event;
  23480. if (waitingForItem) {
  23481. var _this$schedule$items5;
  23482. const scheduleIndex = this.schedule.findEventIndex(interstitialId);
  23483. const item = (_this$schedule$items5 = this.schedule.items) == null ? void 0 : _this$schedule$items5[scheduleIndex];
  23484. if (item) {
  23485. if (!this.playingItem && this.timelinePos > item.end) {
  23486. const index = this.schedule.findItemIndexAtTime(this.timelinePos);
  23487. if (index !== scheduleIndex) {
  23488. interstitial.error = new Error(`Interstitial no longer within playback range ${this.timelinePos} ${interstitial}`);
  23489. this.primaryFallback(interstitial);
  23490. return;
  23491. }
  23492. }
  23493. this.setBufferingItem(item);
  23494. }
  23495. this.setSchedulePosition(scheduleIndex);
  23496. } else if ((bufferingEvent == null ? void 0 : bufferingEvent.identifier) === interstitialId && bufferingEvent.appendInPlace) {
  23497. const assetItem = interstitial.assetList[0];
  23498. const player = this.getAssetPlayer(assetItem.identifier);
  23499. const media = this.primaryMedia;
  23500. if (assetItem && player && media) {
  23501. this.bufferAssetPlayer(player, media);
  23502. }
  23503. }
  23504. }
  23505. onError(event, data) {
  23506. switch (data.details) {
  23507. case ErrorDetails.ASSET_LIST_PARSING_ERROR:
  23508. case ErrorDetails.ASSET_LIST_LOAD_ERROR:
  23509. case ErrorDetails.ASSET_LIST_LOAD_TIMEOUT: {
  23510. const interstitial = data.interstitial;
  23511. if (interstitial) {
  23512. this.primaryFallback(interstitial);
  23513. }
  23514. break;
  23515. }
  23516. case ErrorDetails.BUFFER_STALLED_ERROR: {
  23517. this.onTimeupdate();
  23518. this.checkBuffer(true);
  23519. break;
  23520. }
  23521. }
  23522. }
  23523. };
  23524. var TICK_INTERVAL$2 = 500;
  23525. var SubtitleStreamController = class extends BaseStreamController {
  23526. constructor(hls, fragmentTracker, keyLoader) {
  23527. super(hls, fragmentTracker, keyLoader, "subtitle-stream-controller", PlaylistLevelType.SUBTITLE);
  23528. this.currentTrackId = -1;
  23529. this.tracksBuffered = [];
  23530. this.mainDetails = null;
  23531. this.registerListeners();
  23532. }
  23533. onHandlerDestroying() {
  23534. this.unregisterListeners();
  23535. super.onHandlerDestroying();
  23536. this.mainDetails = null;
  23537. }
  23538. registerListeners() {
  23539. super.registerListeners();
  23540. const {
  23541. hls
  23542. } = this;
  23543. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  23544. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  23545. hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  23546. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  23547. hls.on(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  23548. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  23549. }
  23550. unregisterListeners() {
  23551. super.unregisterListeners();
  23552. const {
  23553. hls
  23554. } = this;
  23555. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  23556. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  23557. hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  23558. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  23559. hls.off(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  23560. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  23561. }
  23562. startLoad(startPosition, skipSeekToStartPosition) {
  23563. this.stopLoad();
  23564. this.state = State.IDLE;
  23565. this.setInterval(TICK_INTERVAL$2);
  23566. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  23567. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  23568. this.tick();
  23569. }
  23570. onManifestLoading() {
  23571. super.onManifestLoading();
  23572. this.mainDetails = null;
  23573. }
  23574. onMediaDetaching(event, data) {
  23575. this.tracksBuffered = [];
  23576. super.onMediaDetaching(event, data);
  23577. }
  23578. onLevelLoaded(event, data) {
  23579. this.mainDetails = data.details;
  23580. }
  23581. onSubtitleFragProcessed(event, data) {
  23582. const {
  23583. frag,
  23584. success
  23585. } = data;
  23586. if (!this.fragContextChanged(frag)) {
  23587. if (isMediaFragment(frag)) {
  23588. this.fragPrevious = frag;
  23589. }
  23590. this.state = State.IDLE;
  23591. }
  23592. if (!success) {
  23593. return;
  23594. }
  23595. const buffered = this.tracksBuffered[this.currentTrackId];
  23596. if (!buffered) {
  23597. return;
  23598. }
  23599. let timeRange;
  23600. const fragStart = frag.start;
  23601. for (let i = 0; i < buffered.length; i++) {
  23602. if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
  23603. timeRange = buffered[i];
  23604. break;
  23605. }
  23606. }
  23607. const fragEnd = frag.start + frag.duration;
  23608. if (timeRange) {
  23609. timeRange.end = fragEnd;
  23610. } else {
  23611. timeRange = {
  23612. start: fragStart,
  23613. end: fragEnd
  23614. };
  23615. buffered.push(timeRange);
  23616. }
  23617. this.fragmentTracker.fragBuffered(frag);
  23618. this.fragBufferedComplete(frag, null);
  23619. if (this.media) {
  23620. this.tick();
  23621. }
  23622. }
  23623. onBufferFlushing(event, data) {
  23624. const {
  23625. startOffset,
  23626. endOffset
  23627. } = data;
  23628. if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) {
  23629. const endOffsetSubtitles = endOffset - 1;
  23630. if (endOffsetSubtitles <= 0) {
  23631. return;
  23632. }
  23633. data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles);
  23634. this.tracksBuffered.forEach((buffered) => {
  23635. for (let i = 0; i < buffered.length; ) {
  23636. if (buffered[i].end <= endOffsetSubtitles) {
  23637. buffered.shift();
  23638. continue;
  23639. } else if (buffered[i].start < endOffsetSubtitles) {
  23640. buffered[i].start = endOffsetSubtitles;
  23641. } else {
  23642. break;
  23643. }
  23644. i++;
  23645. }
  23646. });
  23647. this.fragmentTracker.removeFragmentsInRange(startOffset, endOffsetSubtitles, PlaylistLevelType.SUBTITLE);
  23648. }
  23649. }
  23650. // If something goes wrong, proceed to next frag, if we were processing one.
  23651. onError(event, data) {
  23652. const frag = data.frag;
  23653. if ((frag == null ? void 0 : frag.type) === PlaylistLevelType.SUBTITLE) {
  23654. if (data.details === ErrorDetails.FRAG_GAP) {
  23655. this.fragmentTracker.fragBuffered(frag, true);
  23656. }
  23657. if (this.fragCurrent) {
  23658. this.fragCurrent.abortRequests();
  23659. }
  23660. if (this.state !== State.STOPPED) {
  23661. this.state = State.IDLE;
  23662. }
  23663. }
  23664. }
  23665. // Got all new subtitle levels.
  23666. onSubtitleTracksUpdated(event, {
  23667. subtitleTracks
  23668. }) {
  23669. if (this.levels && subtitleOptionsIdentical(this.levels, subtitleTracks)) {
  23670. this.levels = subtitleTracks.map((mediaPlaylist) => new Level(mediaPlaylist));
  23671. return;
  23672. }
  23673. this.tracksBuffered = [];
  23674. this.levels = subtitleTracks.map((mediaPlaylist) => {
  23675. const level = new Level(mediaPlaylist);
  23676. this.tracksBuffered[level.id] = [];
  23677. return level;
  23678. });
  23679. this.fragmentTracker.removeFragmentsInRange(0, Number.POSITIVE_INFINITY, PlaylistLevelType.SUBTITLE);
  23680. this.fragPrevious = null;
  23681. this.mediaBuffer = null;
  23682. }
  23683. onSubtitleTrackSwitch(event, data) {
  23684. var _this$levels;
  23685. this.currentTrackId = data.id;
  23686. if (!((_this$levels = this.levels) != null && _this$levels.length) || this.currentTrackId === -1) {
  23687. this.clearInterval();
  23688. return;
  23689. }
  23690. const currentTrack = this.levels[this.currentTrackId];
  23691. if (currentTrack != null && currentTrack.details) {
  23692. this.mediaBuffer = this.mediaBufferTimeRanges;
  23693. } else {
  23694. this.mediaBuffer = null;
  23695. }
  23696. if (currentTrack && this.state !== State.STOPPED) {
  23697. this.setInterval(TICK_INTERVAL$2);
  23698. }
  23699. }
  23700. // Got a new set of subtitle fragments.
  23701. onSubtitleTrackLoaded(event, data) {
  23702. var _track$details;
  23703. const {
  23704. currentTrackId,
  23705. levels
  23706. } = this;
  23707. const {
  23708. details: newDetails,
  23709. id: trackId
  23710. } = data;
  23711. if (!levels) {
  23712. this.warn(`Subtitle tracks were reset while loading level ${trackId}`);
  23713. return;
  23714. }
  23715. const track = levels[trackId];
  23716. if (trackId >= levels.length || !track) {
  23717. return;
  23718. }
  23719. this.log(`Subtitle track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""},duration:${newDetails.totalduration}`);
  23720. this.mediaBuffer = this.mediaBufferTimeRanges;
  23721. let sliding = 0;
  23722. if (newDetails.live || (_track$details = track.details) != null && _track$details.live) {
  23723. if (newDetails.deltaUpdateFailed) {
  23724. return;
  23725. }
  23726. const mainDetails = this.mainDetails;
  23727. if (!mainDetails) {
  23728. this.startFragRequested = false;
  23729. return;
  23730. }
  23731. const mainSlidingStartFragment = mainDetails.fragments[0];
  23732. if (!track.details) {
  23733. if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {
  23734. alignMediaPlaylistByPDT(newDetails, mainDetails);
  23735. sliding = newDetails.fragmentStart;
  23736. } else if (mainSlidingStartFragment) {
  23737. sliding = mainSlidingStartFragment.start;
  23738. addSliding(newDetails, sliding);
  23739. }
  23740. } else {
  23741. var _this$levelLastLoaded;
  23742. sliding = this.alignPlaylists(newDetails, track.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  23743. if (sliding === 0 && mainSlidingStartFragment) {
  23744. sliding = mainSlidingStartFragment.start;
  23745. addSliding(newDetails, sliding);
  23746. }
  23747. }
  23748. if (mainDetails && !this.startFragRequested) {
  23749. this.setStartPosition(mainDetails, sliding);
  23750. }
  23751. }
  23752. track.details = newDetails;
  23753. this.levelLastLoaded = track;
  23754. if (trackId !== currentTrackId) {
  23755. return;
  23756. }
  23757. this.hls.trigger(Events.SUBTITLE_TRACK_UPDATED, {
  23758. details: newDetails,
  23759. id: trackId,
  23760. groupId: data.groupId
  23761. });
  23762. this.tick();
  23763. if (newDetails.live && !this.fragCurrent && this.media && this.state === State.IDLE) {
  23764. const foundFrag = findFragmentByPTS(null, newDetails.fragments, this.media.currentTime, 0);
  23765. if (!foundFrag) {
  23766. this.warn("Subtitle playlist not aligned with playback");
  23767. track.details = void 0;
  23768. }
  23769. }
  23770. }
  23771. _handleFragmentLoadComplete(fragLoadedData) {
  23772. const {
  23773. frag,
  23774. payload
  23775. } = fragLoadedData;
  23776. const decryptData = frag.decryptdata;
  23777. const hls = this.hls;
  23778. if (this.fragContextChanged(frag)) {
  23779. return;
  23780. }
  23781. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
  23782. const startTime = performance.now();
  23783. this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch((err) => {
  23784. hls.trigger(Events.ERROR, {
  23785. type: ErrorTypes.MEDIA_ERROR,
  23786. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  23787. fatal: false,
  23788. error: err,
  23789. reason: err.message,
  23790. frag
  23791. });
  23792. throw err;
  23793. }).then((decryptedData) => {
  23794. const endTime = performance.now();
  23795. hls.trigger(Events.FRAG_DECRYPTED, {
  23796. frag,
  23797. payload: decryptedData,
  23798. stats: {
  23799. tstart: startTime,
  23800. tdecrypt: endTime
  23801. }
  23802. });
  23803. }).catch((err) => {
  23804. this.warn(`${err.name}: ${err.message}`);
  23805. this.state = State.IDLE;
  23806. });
  23807. }
  23808. }
  23809. doTick() {
  23810. if (!this.media) {
  23811. this.state = State.IDLE;
  23812. return;
  23813. }
  23814. if (this.state === State.IDLE) {
  23815. const {
  23816. currentTrackId,
  23817. levels
  23818. } = this;
  23819. const track = levels == null ? void 0 : levels[currentTrackId];
  23820. if (!track || !levels.length || !track.details) {
  23821. return;
  23822. }
  23823. if (this.waitForLive(track)) {
  23824. return;
  23825. }
  23826. const {
  23827. config
  23828. } = this;
  23829. const currentTime = this.getLoadPosition();
  23830. const bufferedInfo = BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId] || [], currentTime, config.maxBufferHole);
  23831. const {
  23832. end: targetBufferTime,
  23833. len: bufferLen
  23834. } = bufferedInfo;
  23835. const trackDetails = track.details;
  23836. const maxBufLen = this.hls.maxBufferLength + trackDetails.levelTargetDuration;
  23837. if (bufferLen > maxBufLen) {
  23838. return;
  23839. }
  23840. const fragments = trackDetails.fragments;
  23841. const fragLen = fragments.length;
  23842. const end = trackDetails.edge;
  23843. let foundFrag = null;
  23844. const fragPrevious = this.fragPrevious;
  23845. if (targetBufferTime < end) {
  23846. const tolerance = config.maxFragLookUpTolerance;
  23847. const lookupTolerance = targetBufferTime > end - tolerance ? 0 : tolerance;
  23848. foundFrag = findFragmentByPTS(fragPrevious, fragments, Math.max(fragments[0].start, targetBufferTime), lookupTolerance);
  23849. if (!foundFrag && fragPrevious && fragPrevious.start < fragments[0].start) {
  23850. foundFrag = fragments[0];
  23851. }
  23852. } else {
  23853. foundFrag = fragments[fragLen - 1];
  23854. }
  23855. foundFrag = this.filterReplacedPrimary(foundFrag, track.details);
  23856. if (!foundFrag) {
  23857. return;
  23858. }
  23859. const curSNIdx = foundFrag.sn - trackDetails.startSN;
  23860. const prevFrag = fragments[curSNIdx - 1];
  23861. if (prevFrag && prevFrag.cc === foundFrag.cc && this.fragmentTracker.getState(prevFrag) === FragmentState.NOT_LOADED) {
  23862. foundFrag = prevFrag;
  23863. }
  23864. if (this.fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) {
  23865. const fragToLoad = this.mapToInitFragWhenRequired(foundFrag);
  23866. if (fragToLoad) {
  23867. this.loadFragment(fragToLoad, track, targetBufferTime);
  23868. }
  23869. }
  23870. }
  23871. }
  23872. loadFragment(frag, level, targetBufferTime) {
  23873. if (!isMediaFragment(frag)) {
  23874. this._loadInitSegment(frag, level);
  23875. } else {
  23876. super.loadFragment(frag, level, targetBufferTime);
  23877. }
  23878. }
  23879. get mediaBufferTimeRanges() {
  23880. return new BufferableInstance(this.tracksBuffered[this.currentTrackId] || []);
  23881. }
  23882. };
  23883. var BufferableInstance = class {
  23884. constructor(timeranges) {
  23885. this.buffered = void 0;
  23886. const getRange = (name, index, length) => {
  23887. index = index >>> 0;
  23888. if (index > length - 1) {
  23889. throw new DOMException(`Failed to execute '${name}' on 'TimeRanges': The index provided (${index}) is greater than the maximum bound (${length})`);
  23890. }
  23891. return timeranges[index][name];
  23892. };
  23893. this.buffered = {
  23894. get length() {
  23895. return timeranges.length;
  23896. },
  23897. end(index) {
  23898. return getRange("end", index, timeranges.length);
  23899. },
  23900. start(index) {
  23901. return getRange("start", index, timeranges.length);
  23902. }
  23903. };
  23904. }
  23905. };
  23906. var specialCea608CharsCodes = {
  23907. 42: 225,
  23908. // lowercase a, acute accent
  23909. 92: 233,
  23910. // lowercase e, acute accent
  23911. 94: 237,
  23912. // lowercase i, acute accent
  23913. 95: 243,
  23914. // lowercase o, acute accent
  23915. 96: 250,
  23916. // lowercase u, acute accent
  23917. 123: 231,
  23918. // lowercase c with cedilla
  23919. 124: 247,
  23920. // division symbol
  23921. 125: 209,
  23922. // uppercase N tilde
  23923. 126: 241,
  23924. // lowercase n tilde
  23925. 127: 9608,
  23926. // Full block
  23927. // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  23928. // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
  23929. // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
  23930. 128: 174,
  23931. // Registered symbol (R)
  23932. 129: 176,
  23933. // degree sign
  23934. 130: 189,
  23935. // 1/2 symbol
  23936. 131: 191,
  23937. // Inverted (open) question mark
  23938. 132: 8482,
  23939. // Trademark symbol (TM)
  23940. 133: 162,
  23941. // Cents symbol
  23942. 134: 163,
  23943. // Pounds sterling
  23944. 135: 9834,
  23945. // Music 8'th note
  23946. 136: 224,
  23947. // lowercase a, grave accent
  23948. 137: 32,
  23949. // transparent space (regular)
  23950. 138: 232,
  23951. // lowercase e, grave accent
  23952. 139: 226,
  23953. // lowercase a, circumflex accent
  23954. 140: 234,
  23955. // lowercase e, circumflex accent
  23956. 141: 238,
  23957. // lowercase i, circumflex accent
  23958. 142: 244,
  23959. // lowercase o, circumflex accent
  23960. 143: 251,
  23961. // lowercase u, circumflex accent
  23962. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  23963. // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
  23964. 144: 193,
  23965. // capital letter A with acute
  23966. 145: 201,
  23967. // capital letter E with acute
  23968. 146: 211,
  23969. // capital letter O with acute
  23970. 147: 218,
  23971. // capital letter U with acute
  23972. 148: 220,
  23973. // capital letter U with diaresis
  23974. 149: 252,
  23975. // lowercase letter U with diaeresis
  23976. 150: 8216,
  23977. // opening single quote
  23978. 151: 161,
  23979. // inverted exclamation mark
  23980. 152: 42,
  23981. // asterisk
  23982. 153: 8217,
  23983. // closing single quote
  23984. 154: 9473,
  23985. // box drawings heavy horizontal
  23986. 155: 169,
  23987. // copyright sign
  23988. 156: 8480,
  23989. // Service mark
  23990. 157: 8226,
  23991. // (round) bullet
  23992. 158: 8220,
  23993. // Left double quotation mark
  23994. 159: 8221,
  23995. // Right double quotation mark
  23996. 160: 192,
  23997. // uppercase A, grave accent
  23998. 161: 194,
  23999. // uppercase A, circumflex
  24000. 162: 199,
  24001. // uppercase C with cedilla
  24002. 163: 200,
  24003. // uppercase E, grave accent
  24004. 164: 202,
  24005. // uppercase E, circumflex
  24006. 165: 203,
  24007. // capital letter E with diaresis
  24008. 166: 235,
  24009. // lowercase letter e with diaresis
  24010. 167: 206,
  24011. // uppercase I, circumflex
  24012. 168: 207,
  24013. // uppercase I, with diaresis
  24014. 169: 239,
  24015. // lowercase i, with diaresis
  24016. 170: 212,
  24017. // uppercase O, circumflex
  24018. 171: 217,
  24019. // uppercase U, grave accent
  24020. 172: 249,
  24021. // lowercase u, grave accent
  24022. 173: 219,
  24023. // uppercase U, circumflex
  24024. 174: 171,
  24025. // left-pointing double angle quotation mark
  24026. 175: 187,
  24027. // right-pointing double angle quotation mark
  24028. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  24029. // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
  24030. 176: 195,
  24031. // Uppercase A, tilde
  24032. 177: 227,
  24033. // Lowercase a, tilde
  24034. 178: 205,
  24035. // Uppercase I, acute accent
  24036. 179: 204,
  24037. // Uppercase I, grave accent
  24038. 180: 236,
  24039. // Lowercase i, grave accent
  24040. 181: 210,
  24041. // Uppercase O, grave accent
  24042. 182: 242,
  24043. // Lowercase o, grave accent
  24044. 183: 213,
  24045. // Uppercase O, tilde
  24046. 184: 245,
  24047. // Lowercase o, tilde
  24048. 185: 123,
  24049. // Open curly brace
  24050. 186: 125,
  24051. // Closing curly brace
  24052. 187: 92,
  24053. // Backslash
  24054. 188: 94,
  24055. // Caret
  24056. 189: 95,
  24057. // Underscore
  24058. 190: 124,
  24059. // Pipe (vertical line)
  24060. 191: 8764,
  24061. // Tilde operator
  24062. 192: 196,
  24063. // Uppercase A, umlaut
  24064. 193: 228,
  24065. // Lowercase A, umlaut
  24066. 194: 214,
  24067. // Uppercase O, umlaut
  24068. 195: 246,
  24069. // Lowercase o, umlaut
  24070. 196: 223,
  24071. // Esszett (sharp S)
  24072. 197: 165,
  24073. // Yen symbol
  24074. 198: 164,
  24075. // Generic currency sign
  24076. 199: 9475,
  24077. // Box drawings heavy vertical
  24078. 200: 197,
  24079. // Uppercase A, ring
  24080. 201: 229,
  24081. // Lowercase A, ring
  24082. 202: 216,
  24083. // Uppercase O, stroke
  24084. 203: 248,
  24085. // Lowercase o, strok
  24086. 204: 9487,
  24087. // Box drawings heavy down and right
  24088. 205: 9491,
  24089. // Box drawings heavy down and left
  24090. 206: 9495,
  24091. // Box drawings heavy up and right
  24092. 207: 9499
  24093. // Box drawings heavy up and left
  24094. };
  24095. var getCharForByte = (byte) => String.fromCharCode(specialCea608CharsCodes[byte] || byte);
  24096. var NR_ROWS = 15;
  24097. var NR_COLS = 100;
  24098. var rowsLowCh1 = {
  24099. 17: 1,
  24100. 18: 3,
  24101. 21: 5,
  24102. 22: 7,
  24103. 23: 9,
  24104. 16: 11,
  24105. 19: 12,
  24106. 20: 14
  24107. };
  24108. var rowsHighCh1 = {
  24109. 17: 2,
  24110. 18: 4,
  24111. 21: 6,
  24112. 22: 8,
  24113. 23: 10,
  24114. 19: 13,
  24115. 20: 15
  24116. };
  24117. var rowsLowCh2 = {
  24118. 25: 1,
  24119. 26: 3,
  24120. 29: 5,
  24121. 30: 7,
  24122. 31: 9,
  24123. 24: 11,
  24124. 27: 12,
  24125. 28: 14
  24126. };
  24127. var rowsHighCh2 = {
  24128. 25: 2,
  24129. 26: 4,
  24130. 29: 6,
  24131. 30: 8,
  24132. 31: 10,
  24133. 27: 13,
  24134. 28: 15
  24135. };
  24136. var backgroundColors = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "black", "transparent"];
  24137. var CaptionsLogger = class {
  24138. constructor() {
  24139. this.time = null;
  24140. this.verboseLevel = 0;
  24141. }
  24142. log(severity, msg) {
  24143. if (this.verboseLevel >= severity) {
  24144. const m = typeof msg === "function" ? msg() : msg;
  24145. logger.log(`${this.time} [${severity}] ${m}`);
  24146. }
  24147. }
  24148. };
  24149. var numArrayToHexArray = function numArrayToHexArray2(numArray) {
  24150. const hexArray = [];
  24151. for (let j = 0; j < numArray.length; j++) {
  24152. hexArray.push(numArray[j].toString(16));
  24153. }
  24154. return hexArray;
  24155. };
  24156. var PenState = class {
  24157. constructor() {
  24158. this.foreground = "white";
  24159. this.underline = false;
  24160. this.italics = false;
  24161. this.background = "black";
  24162. this.flash = false;
  24163. }
  24164. reset() {
  24165. this.foreground = "white";
  24166. this.underline = false;
  24167. this.italics = false;
  24168. this.background = "black";
  24169. this.flash = false;
  24170. }
  24171. setStyles(styles) {
  24172. const attribs = ["foreground", "underline", "italics", "background", "flash"];
  24173. for (let i = 0; i < attribs.length; i++) {
  24174. const style = attribs[i];
  24175. if (styles.hasOwnProperty(style)) {
  24176. this[style] = styles[style];
  24177. }
  24178. }
  24179. }
  24180. isDefault() {
  24181. return this.foreground === "white" && !this.underline && !this.italics && this.background === "black" && !this.flash;
  24182. }
  24183. equals(other) {
  24184. return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
  24185. }
  24186. copy(newPenState) {
  24187. this.foreground = newPenState.foreground;
  24188. this.underline = newPenState.underline;
  24189. this.italics = newPenState.italics;
  24190. this.background = newPenState.background;
  24191. this.flash = newPenState.flash;
  24192. }
  24193. toString() {
  24194. return "color=" + this.foreground + ", underline=" + this.underline + ", italics=" + this.italics + ", background=" + this.background + ", flash=" + this.flash;
  24195. }
  24196. };
  24197. var StyledUnicodeChar = class {
  24198. constructor() {
  24199. this.uchar = " ";
  24200. this.penState = new PenState();
  24201. }
  24202. reset() {
  24203. this.uchar = " ";
  24204. this.penState.reset();
  24205. }
  24206. setChar(uchar, newPenState) {
  24207. this.uchar = uchar;
  24208. this.penState.copy(newPenState);
  24209. }
  24210. setPenState(newPenState) {
  24211. this.penState.copy(newPenState);
  24212. }
  24213. equals(other) {
  24214. return this.uchar === other.uchar && this.penState.equals(other.penState);
  24215. }
  24216. copy(newChar) {
  24217. this.uchar = newChar.uchar;
  24218. this.penState.copy(newChar.penState);
  24219. }
  24220. isEmpty() {
  24221. return this.uchar === " " && this.penState.isDefault();
  24222. }
  24223. };
  24224. var Row = class {
  24225. constructor(logger2) {
  24226. this.chars = [];
  24227. this.pos = 0;
  24228. this.currPenState = new PenState();
  24229. this.cueStartTime = null;
  24230. this.logger = void 0;
  24231. for (let i = 0; i < NR_COLS; i++) {
  24232. this.chars.push(new StyledUnicodeChar());
  24233. }
  24234. this.logger = logger2;
  24235. }
  24236. equals(other) {
  24237. for (let i = 0; i < NR_COLS; i++) {
  24238. if (!this.chars[i].equals(other.chars[i])) {
  24239. return false;
  24240. }
  24241. }
  24242. return true;
  24243. }
  24244. copy(other) {
  24245. for (let i = 0; i < NR_COLS; i++) {
  24246. this.chars[i].copy(other.chars[i]);
  24247. }
  24248. }
  24249. isEmpty() {
  24250. let empty = true;
  24251. for (let i = 0; i < NR_COLS; i++) {
  24252. if (!this.chars[i].isEmpty()) {
  24253. empty = false;
  24254. break;
  24255. }
  24256. }
  24257. return empty;
  24258. }
  24259. /**
  24260. * Set the cursor to a valid column.
  24261. */
  24262. setCursor(absPos) {
  24263. if (this.pos !== absPos) {
  24264. this.pos = absPos;
  24265. }
  24266. if (this.pos < 0) {
  24267. this.logger.log(3, "Negative cursor position " + this.pos);
  24268. this.pos = 0;
  24269. } else if (this.pos > NR_COLS) {
  24270. this.logger.log(3, "Too large cursor position " + this.pos);
  24271. this.pos = NR_COLS;
  24272. }
  24273. }
  24274. /**
  24275. * Move the cursor relative to current position.
  24276. */
  24277. moveCursor(relPos) {
  24278. const newPos = this.pos + relPos;
  24279. if (relPos > 1) {
  24280. for (let i = this.pos + 1; i < newPos + 1; i++) {
  24281. this.chars[i].setPenState(this.currPenState);
  24282. }
  24283. }
  24284. this.setCursor(newPos);
  24285. }
  24286. /**
  24287. * Backspace, move one step back and clear character.
  24288. */
  24289. backSpace() {
  24290. this.moveCursor(-1);
  24291. this.chars[this.pos].setChar(" ", this.currPenState);
  24292. }
  24293. insertChar(byte) {
  24294. if (byte >= 144) {
  24295. this.backSpace();
  24296. }
  24297. const char = getCharForByte(byte);
  24298. if (this.pos >= NR_COLS) {
  24299. this.logger.log(0, () => "Cannot insert " + byte.toString(16) + " (" + char + ") at position " + this.pos + ". Skipping it!");
  24300. return;
  24301. }
  24302. this.chars[this.pos].setChar(char, this.currPenState);
  24303. this.moveCursor(1);
  24304. }
  24305. clearFromPos(startPos) {
  24306. let i;
  24307. for (i = startPos; i < NR_COLS; i++) {
  24308. this.chars[i].reset();
  24309. }
  24310. }
  24311. clear() {
  24312. this.clearFromPos(0);
  24313. this.pos = 0;
  24314. this.currPenState.reset();
  24315. }
  24316. clearToEndOfRow() {
  24317. this.clearFromPos(this.pos);
  24318. }
  24319. getTextString() {
  24320. const chars = [];
  24321. let empty = true;
  24322. for (let i = 0; i < NR_COLS; i++) {
  24323. const char = this.chars[i].uchar;
  24324. if (char !== " ") {
  24325. empty = false;
  24326. }
  24327. chars.push(char);
  24328. }
  24329. if (empty) {
  24330. return "";
  24331. } else {
  24332. return chars.join("");
  24333. }
  24334. }
  24335. setPenStyles(styles) {
  24336. this.currPenState.setStyles(styles);
  24337. const currChar = this.chars[this.pos];
  24338. currChar.setPenState(this.currPenState);
  24339. }
  24340. };
  24341. var CaptionScreen = class {
  24342. constructor(logger2) {
  24343. this.rows = [];
  24344. this.currRow = NR_ROWS - 1;
  24345. this.nrRollUpRows = null;
  24346. this.lastOutputScreen = null;
  24347. this.logger = void 0;
  24348. for (let i = 0; i < NR_ROWS; i++) {
  24349. this.rows.push(new Row(logger2));
  24350. }
  24351. this.logger = logger2;
  24352. }
  24353. reset() {
  24354. for (let i = 0; i < NR_ROWS; i++) {
  24355. this.rows[i].clear();
  24356. }
  24357. this.currRow = NR_ROWS - 1;
  24358. }
  24359. equals(other) {
  24360. let equal = true;
  24361. for (let i = 0; i < NR_ROWS; i++) {
  24362. if (!this.rows[i].equals(other.rows[i])) {
  24363. equal = false;
  24364. break;
  24365. }
  24366. }
  24367. return equal;
  24368. }
  24369. copy(other) {
  24370. for (let i = 0; i < NR_ROWS; i++) {
  24371. this.rows[i].copy(other.rows[i]);
  24372. }
  24373. }
  24374. isEmpty() {
  24375. let empty = true;
  24376. for (let i = 0; i < NR_ROWS; i++) {
  24377. if (!this.rows[i].isEmpty()) {
  24378. empty = false;
  24379. break;
  24380. }
  24381. }
  24382. return empty;
  24383. }
  24384. backSpace() {
  24385. const row = this.rows[this.currRow];
  24386. row.backSpace();
  24387. }
  24388. clearToEndOfRow() {
  24389. const row = this.rows[this.currRow];
  24390. row.clearToEndOfRow();
  24391. }
  24392. /**
  24393. * Insert a character (without styling) in the current row.
  24394. */
  24395. insertChar(char) {
  24396. const row = this.rows[this.currRow];
  24397. row.insertChar(char);
  24398. }
  24399. setPen(styles) {
  24400. const row = this.rows[this.currRow];
  24401. row.setPenStyles(styles);
  24402. }
  24403. moveCursor(relPos) {
  24404. const row = this.rows[this.currRow];
  24405. row.moveCursor(relPos);
  24406. }
  24407. setCursor(absPos) {
  24408. this.logger.log(2, "setCursor: " + absPos);
  24409. const row = this.rows[this.currRow];
  24410. row.setCursor(absPos);
  24411. }
  24412. setPAC(pacData) {
  24413. this.logger.log(2, () => "pacData = " + stringify(pacData));
  24414. let newRow = pacData.row - 1;
  24415. if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
  24416. newRow = this.nrRollUpRows - 1;
  24417. }
  24418. if (this.nrRollUpRows && this.currRow !== newRow) {
  24419. for (let i = 0; i < NR_ROWS; i++) {
  24420. this.rows[i].clear();
  24421. }
  24422. const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  24423. const lastOutputScreen = this.lastOutputScreen;
  24424. if (lastOutputScreen) {
  24425. const prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
  24426. const time = this.logger.time;
  24427. if (prevLineTime !== null && time !== null && prevLineTime < time) {
  24428. for (let i = 0; i < this.nrRollUpRows; i++) {
  24429. this.rows[newRow - this.nrRollUpRows + i + 1].copy(lastOutputScreen.rows[topRowIndex + i]);
  24430. }
  24431. }
  24432. }
  24433. }
  24434. this.currRow = newRow;
  24435. const row = this.rows[this.currRow];
  24436. if (pacData.indent !== null) {
  24437. const indent = pacData.indent;
  24438. const prevPos = Math.max(indent - 1, 0);
  24439. row.setCursor(pacData.indent);
  24440. pacData.color = row.chars[prevPos].penState.foreground;
  24441. }
  24442. const styles = {
  24443. foreground: pacData.color,
  24444. underline: pacData.underline,
  24445. italics: pacData.italics,
  24446. background: "black",
  24447. flash: false
  24448. };
  24449. this.setPen(styles);
  24450. }
  24451. /**
  24452. * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
  24453. */
  24454. setBkgData(bkgData) {
  24455. this.logger.log(2, () => "bkgData = " + stringify(bkgData));
  24456. this.backSpace();
  24457. this.setPen(bkgData);
  24458. this.insertChar(32);
  24459. }
  24460. setRollUpRows(nrRows) {
  24461. this.nrRollUpRows = nrRows;
  24462. }
  24463. rollUp() {
  24464. if (this.nrRollUpRows === null) {
  24465. this.logger.log(3, "roll_up but nrRollUpRows not set yet");
  24466. return;
  24467. }
  24468. this.logger.log(1, () => this.getDisplayText());
  24469. const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  24470. const topRow = this.rows.splice(topRowIndex, 1)[0];
  24471. topRow.clear();
  24472. this.rows.splice(this.currRow, 0, topRow);
  24473. this.logger.log(2, "Rolling up");
  24474. }
  24475. /**
  24476. * Get all non-empty rows with as unicode text.
  24477. */
  24478. getDisplayText(asOneRow) {
  24479. asOneRow = asOneRow || false;
  24480. const displayText = [];
  24481. let text = "";
  24482. let rowNr = -1;
  24483. for (let i = 0; i < NR_ROWS; i++) {
  24484. const rowText = this.rows[i].getTextString();
  24485. if (rowText) {
  24486. rowNr = i + 1;
  24487. if (asOneRow) {
  24488. displayText.push("Row " + rowNr + ": '" + rowText + "'");
  24489. } else {
  24490. displayText.push(rowText.trim());
  24491. }
  24492. }
  24493. }
  24494. if (displayText.length > 0) {
  24495. if (asOneRow) {
  24496. text = "[" + displayText.join(" | ") + "]";
  24497. } else {
  24498. text = displayText.join("\n");
  24499. }
  24500. }
  24501. return text;
  24502. }
  24503. getTextAndFormat() {
  24504. return this.rows;
  24505. }
  24506. };
  24507. var Cea608Channel = class {
  24508. constructor(channelNumber, outputFilter, logger2) {
  24509. this.chNr = void 0;
  24510. this.outputFilter = void 0;
  24511. this.mode = void 0;
  24512. this.verbose = void 0;
  24513. this.displayedMemory = void 0;
  24514. this.nonDisplayedMemory = void 0;
  24515. this.lastOutputScreen = void 0;
  24516. this.currRollUpRow = void 0;
  24517. this.writeScreen = void 0;
  24518. this.cueStartTime = void 0;
  24519. this.logger = void 0;
  24520. this.chNr = channelNumber;
  24521. this.outputFilter = outputFilter;
  24522. this.mode = null;
  24523. this.verbose = 0;
  24524. this.displayedMemory = new CaptionScreen(logger2);
  24525. this.nonDisplayedMemory = new CaptionScreen(logger2);
  24526. this.lastOutputScreen = new CaptionScreen(logger2);
  24527. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  24528. this.writeScreen = this.displayedMemory;
  24529. this.mode = null;
  24530. this.cueStartTime = null;
  24531. this.logger = logger2;
  24532. }
  24533. reset() {
  24534. this.mode = null;
  24535. this.displayedMemory.reset();
  24536. this.nonDisplayedMemory.reset();
  24537. this.lastOutputScreen.reset();
  24538. this.outputFilter.reset();
  24539. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  24540. this.writeScreen = this.displayedMemory;
  24541. this.mode = null;
  24542. this.cueStartTime = null;
  24543. }
  24544. getHandler() {
  24545. return this.outputFilter;
  24546. }
  24547. setHandler(newHandler) {
  24548. this.outputFilter = newHandler;
  24549. }
  24550. setPAC(pacData) {
  24551. this.writeScreen.setPAC(pacData);
  24552. }
  24553. setBkgData(bkgData) {
  24554. this.writeScreen.setBkgData(bkgData);
  24555. }
  24556. setMode(newMode) {
  24557. if (newMode === this.mode) {
  24558. return;
  24559. }
  24560. this.mode = newMode;
  24561. this.logger.log(2, () => "MODE=" + newMode);
  24562. if (this.mode === "MODE_POP-ON") {
  24563. this.writeScreen = this.nonDisplayedMemory;
  24564. } else {
  24565. this.writeScreen = this.displayedMemory;
  24566. this.writeScreen.reset();
  24567. }
  24568. if (this.mode !== "MODE_ROLL-UP") {
  24569. this.displayedMemory.nrRollUpRows = null;
  24570. this.nonDisplayedMemory.nrRollUpRows = null;
  24571. }
  24572. this.mode = newMode;
  24573. }
  24574. insertChars(chars) {
  24575. for (let i = 0; i < chars.length; i++) {
  24576. this.writeScreen.insertChar(chars[i]);
  24577. }
  24578. const screen = this.writeScreen === this.displayedMemory ? "DISP" : "NON_DISP";
  24579. this.logger.log(2, () => screen + ": " + this.writeScreen.getDisplayText(true));
  24580. if (this.mode === "MODE_PAINT-ON" || this.mode === "MODE_ROLL-UP") {
  24581. this.logger.log(1, () => "DISPLAYED: " + this.displayedMemory.getDisplayText(true));
  24582. this.outputDataUpdate();
  24583. }
  24584. }
  24585. ccRCL() {
  24586. this.logger.log(2, "RCL - Resume Caption Loading");
  24587. this.setMode("MODE_POP-ON");
  24588. }
  24589. ccBS() {
  24590. this.logger.log(2, "BS - BackSpace");
  24591. if (this.mode === "MODE_TEXT") {
  24592. return;
  24593. }
  24594. this.writeScreen.backSpace();
  24595. if (this.writeScreen === this.displayedMemory) {
  24596. this.outputDataUpdate();
  24597. }
  24598. }
  24599. ccAOF() {
  24600. }
  24601. ccAON() {
  24602. }
  24603. ccDER() {
  24604. this.logger.log(2, "DER- Delete to End of Row");
  24605. this.writeScreen.clearToEndOfRow();
  24606. this.outputDataUpdate();
  24607. }
  24608. ccRU(nrRows) {
  24609. this.logger.log(2, "RU(" + nrRows + ") - Roll Up");
  24610. this.writeScreen = this.displayedMemory;
  24611. this.setMode("MODE_ROLL-UP");
  24612. this.writeScreen.setRollUpRows(nrRows);
  24613. }
  24614. ccFON() {
  24615. this.logger.log(2, "FON - Flash On");
  24616. this.writeScreen.setPen({
  24617. flash: true
  24618. });
  24619. }
  24620. ccRDC() {
  24621. this.logger.log(2, "RDC - Resume Direct Captioning");
  24622. this.setMode("MODE_PAINT-ON");
  24623. }
  24624. ccTR() {
  24625. this.logger.log(2, "TR");
  24626. this.setMode("MODE_TEXT");
  24627. }
  24628. ccRTD() {
  24629. this.logger.log(2, "RTD");
  24630. this.setMode("MODE_TEXT");
  24631. }
  24632. ccEDM() {
  24633. this.logger.log(2, "EDM - Erase Displayed Memory");
  24634. this.displayedMemory.reset();
  24635. this.outputDataUpdate(true);
  24636. }
  24637. ccCR() {
  24638. this.logger.log(2, "CR - Carriage Return");
  24639. this.writeScreen.rollUp();
  24640. this.outputDataUpdate(true);
  24641. }
  24642. ccENM() {
  24643. this.logger.log(2, "ENM - Erase Non-displayed Memory");
  24644. this.nonDisplayedMemory.reset();
  24645. }
  24646. ccEOC() {
  24647. this.logger.log(2, "EOC - End Of Caption");
  24648. if (this.mode === "MODE_POP-ON") {
  24649. const tmp = this.displayedMemory;
  24650. this.displayedMemory = this.nonDisplayedMemory;
  24651. this.nonDisplayedMemory = tmp;
  24652. this.writeScreen = this.nonDisplayedMemory;
  24653. this.logger.log(1, () => "DISP: " + this.displayedMemory.getDisplayText());
  24654. }
  24655. this.outputDataUpdate(true);
  24656. }
  24657. ccTO(nrCols) {
  24658. this.logger.log(2, "TO(" + nrCols + ") - Tab Offset");
  24659. this.writeScreen.moveCursor(nrCols);
  24660. }
  24661. ccMIDROW(secondByte) {
  24662. const styles = {
  24663. flash: false
  24664. };
  24665. styles.underline = secondByte % 2 === 1;
  24666. styles.italics = secondByte >= 46;
  24667. if (!styles.italics) {
  24668. const colorIndex = Math.floor(secondByte / 2) - 16;
  24669. const colors = ["white", "green", "blue", "cyan", "red", "yellow", "magenta"];
  24670. styles.foreground = colors[colorIndex];
  24671. } else {
  24672. styles.foreground = "white";
  24673. }
  24674. this.logger.log(2, "MIDROW: " + stringify(styles));
  24675. this.writeScreen.setPen(styles);
  24676. }
  24677. outputDataUpdate(dispatch = false) {
  24678. const time = this.logger.time;
  24679. if (time === null) {
  24680. return;
  24681. }
  24682. if (this.outputFilter) {
  24683. if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
  24684. this.cueStartTime = time;
  24685. } else {
  24686. if (!this.displayedMemory.equals(this.lastOutputScreen)) {
  24687. this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);
  24688. if (dispatch && this.outputFilter.dispatchCue) {
  24689. this.outputFilter.dispatchCue();
  24690. }
  24691. this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;
  24692. }
  24693. }
  24694. this.lastOutputScreen.copy(this.displayedMemory);
  24695. }
  24696. }
  24697. cueSplitAtTime(t) {
  24698. if (this.outputFilter) {
  24699. if (!this.displayedMemory.isEmpty()) {
  24700. if (this.outputFilter.newCue) {
  24701. this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
  24702. }
  24703. this.cueStartTime = t;
  24704. }
  24705. }
  24706. }
  24707. };
  24708. var Cea608Parser = class {
  24709. constructor(field, out1, out2) {
  24710. this.channels = void 0;
  24711. this.currentChannel = 0;
  24712. this.cmdHistory = createCmdHistory();
  24713. this.logger = void 0;
  24714. const logger2 = this.logger = new CaptionsLogger();
  24715. this.channels = [null, new Cea608Channel(field, out1, logger2), new Cea608Channel(field + 1, out2, logger2)];
  24716. }
  24717. getHandler(channel) {
  24718. return this.channels[channel].getHandler();
  24719. }
  24720. setHandler(channel, newHandler) {
  24721. this.channels[channel].setHandler(newHandler);
  24722. }
  24723. /**
  24724. * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
  24725. */
  24726. addData(time, byteList) {
  24727. this.logger.time = time;
  24728. for (let i = 0; i < byteList.length; i += 2) {
  24729. const a = byteList[i] & 127;
  24730. const b = byteList[i + 1] & 127;
  24731. let cmdFound = false;
  24732. let charsFound = null;
  24733. if (a === 0 && b === 0) {
  24734. continue;
  24735. } else {
  24736. this.logger.log(3, () => "[" + numArrayToHexArray([byteList[i], byteList[i + 1]]) + "] -> (" + numArrayToHexArray([a, b]) + ")");
  24737. }
  24738. const cmdHistory = this.cmdHistory;
  24739. const isControlCode = a >= 16 && a <= 31;
  24740. if (isControlCode) {
  24741. if (hasCmdRepeated(a, b, cmdHistory)) {
  24742. setLastCmd(null, null, cmdHistory);
  24743. this.logger.log(3, () => "Repeated command (" + numArrayToHexArray([a, b]) + ") is dropped");
  24744. continue;
  24745. }
  24746. setLastCmd(a, b, this.cmdHistory);
  24747. cmdFound = this.parseCmd(a, b);
  24748. if (!cmdFound) {
  24749. cmdFound = this.parseMidrow(a, b);
  24750. }
  24751. if (!cmdFound) {
  24752. cmdFound = this.parsePAC(a, b);
  24753. }
  24754. if (!cmdFound) {
  24755. cmdFound = this.parseBackgroundAttributes(a, b);
  24756. }
  24757. } else {
  24758. setLastCmd(null, null, cmdHistory);
  24759. }
  24760. if (!cmdFound) {
  24761. charsFound = this.parseChars(a, b);
  24762. if (charsFound) {
  24763. const currChNr = this.currentChannel;
  24764. if (currChNr && currChNr > 0) {
  24765. const channel = this.channels[currChNr];
  24766. channel.insertChars(charsFound);
  24767. } else {
  24768. this.logger.log(2, "No channel found yet. TEXT-MODE?");
  24769. }
  24770. }
  24771. }
  24772. if (!cmdFound && !charsFound) {
  24773. this.logger.log(2, () => "Couldn't parse cleaned data " + numArrayToHexArray([a, b]) + " orig: " + numArrayToHexArray([byteList[i], byteList[i + 1]]));
  24774. }
  24775. }
  24776. }
  24777. /**
  24778. * Parse Command.
  24779. * @returns True if a command was found
  24780. */
  24781. parseCmd(a, b) {
  24782. const cond1 = (a === 20 || a === 28 || a === 21 || a === 29) && b >= 32 && b <= 47;
  24783. const cond2 = (a === 23 || a === 31) && b >= 33 && b <= 35;
  24784. if (!(cond1 || cond2)) {
  24785. return false;
  24786. }
  24787. const chNr = a === 20 || a === 21 || a === 23 ? 1 : 2;
  24788. const channel = this.channels[chNr];
  24789. if (a === 20 || a === 21 || a === 28 || a === 29) {
  24790. if (b === 32) {
  24791. channel.ccRCL();
  24792. } else if (b === 33) {
  24793. channel.ccBS();
  24794. } else if (b === 34) {
  24795. channel.ccAOF();
  24796. } else if (b === 35) {
  24797. channel.ccAON();
  24798. } else if (b === 36) {
  24799. channel.ccDER();
  24800. } else if (b === 37) {
  24801. channel.ccRU(2);
  24802. } else if (b === 38) {
  24803. channel.ccRU(3);
  24804. } else if (b === 39) {
  24805. channel.ccRU(4);
  24806. } else if (b === 40) {
  24807. channel.ccFON();
  24808. } else if (b === 41) {
  24809. channel.ccRDC();
  24810. } else if (b === 42) {
  24811. channel.ccTR();
  24812. } else if (b === 43) {
  24813. channel.ccRTD();
  24814. } else if (b === 44) {
  24815. channel.ccEDM();
  24816. } else if (b === 45) {
  24817. channel.ccCR();
  24818. } else if (b === 46) {
  24819. channel.ccENM();
  24820. } else if (b === 47) {
  24821. channel.ccEOC();
  24822. }
  24823. } else {
  24824. channel.ccTO(b - 32);
  24825. }
  24826. this.currentChannel = chNr;
  24827. return true;
  24828. }
  24829. /**
  24830. * Parse midrow styling command
  24831. */
  24832. parseMidrow(a, b) {
  24833. let chNr = 0;
  24834. if ((a === 17 || a === 25) && b >= 32 && b <= 47) {
  24835. if (a === 17) {
  24836. chNr = 1;
  24837. } else {
  24838. chNr = 2;
  24839. }
  24840. if (chNr !== this.currentChannel) {
  24841. this.logger.log(0, "Mismatch channel in midrow parsing");
  24842. return false;
  24843. }
  24844. const channel = this.channels[chNr];
  24845. if (!channel) {
  24846. return false;
  24847. }
  24848. channel.ccMIDROW(b);
  24849. this.logger.log(3, () => "MIDROW (" + numArrayToHexArray([a, b]) + ")");
  24850. return true;
  24851. }
  24852. return false;
  24853. }
  24854. /**
  24855. * Parse Preable Access Codes (Table 53).
  24856. * @returns {Boolean} Tells if PAC found
  24857. */
  24858. parsePAC(a, b) {
  24859. let row;
  24860. const case1 = (a >= 17 && a <= 23 || a >= 25 && a <= 31) && b >= 64 && b <= 127;
  24861. const case2 = (a === 16 || a === 24) && b >= 64 && b <= 95;
  24862. if (!(case1 || case2)) {
  24863. return false;
  24864. }
  24865. const chNr = a <= 23 ? 1 : 2;
  24866. if (b >= 64 && b <= 95) {
  24867. row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
  24868. } else {
  24869. row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
  24870. }
  24871. const channel = this.channels[chNr];
  24872. if (!channel) {
  24873. return false;
  24874. }
  24875. channel.setPAC(this.interpretPAC(row, b));
  24876. this.currentChannel = chNr;
  24877. return true;
  24878. }
  24879. /**
  24880. * Interpret the second byte of the pac, and return the information.
  24881. * @returns pacData with style parameters
  24882. */
  24883. interpretPAC(row, byte) {
  24884. let pacIndex;
  24885. const pacData = {
  24886. color: null,
  24887. italics: false,
  24888. indent: null,
  24889. underline: false,
  24890. row
  24891. };
  24892. if (byte > 95) {
  24893. pacIndex = byte - 96;
  24894. } else {
  24895. pacIndex = byte - 64;
  24896. }
  24897. pacData.underline = (pacIndex & 1) === 1;
  24898. if (pacIndex <= 13) {
  24899. pacData.color = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "white"][Math.floor(pacIndex / 2)];
  24900. } else if (pacIndex <= 15) {
  24901. pacData.italics = true;
  24902. pacData.color = "white";
  24903. } else {
  24904. pacData.indent = Math.floor((pacIndex - 16) / 2) * 4;
  24905. }
  24906. return pacData;
  24907. }
  24908. /**
  24909. * Parse characters.
  24910. * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
  24911. */
  24912. parseChars(a, b) {
  24913. let channelNr;
  24914. let charCodes = null;
  24915. let charCode1 = null;
  24916. if (a >= 25) {
  24917. channelNr = 2;
  24918. charCode1 = a - 8;
  24919. } else {
  24920. channelNr = 1;
  24921. charCode1 = a;
  24922. }
  24923. if (charCode1 >= 17 && charCode1 <= 19) {
  24924. let oneCode;
  24925. if (charCode1 === 17) {
  24926. oneCode = b + 80;
  24927. } else if (charCode1 === 18) {
  24928. oneCode = b + 112;
  24929. } else {
  24930. oneCode = b + 144;
  24931. }
  24932. this.logger.log(2, () => "Special char '" + getCharForByte(oneCode) + "' in channel " + channelNr);
  24933. charCodes = [oneCode];
  24934. } else if (a >= 32 && a <= 127) {
  24935. charCodes = b === 0 ? [a] : [a, b];
  24936. }
  24937. if (charCodes) {
  24938. this.logger.log(3, () => "Char codes = " + numArrayToHexArray(charCodes).join(","));
  24939. }
  24940. return charCodes;
  24941. }
  24942. /**
  24943. * Parse extended background attributes as well as new foreground color black.
  24944. * @returns True if background attributes are found
  24945. */
  24946. parseBackgroundAttributes(a, b) {
  24947. const case1 = (a === 16 || a === 24) && b >= 32 && b <= 47;
  24948. const case2 = (a === 23 || a === 31) && b >= 45 && b <= 47;
  24949. if (!(case1 || case2)) {
  24950. return false;
  24951. }
  24952. let index;
  24953. const bkgData = {};
  24954. if (a === 16 || a === 24) {
  24955. index = Math.floor((b - 32) / 2);
  24956. bkgData.background = backgroundColors[index];
  24957. if (b % 2 === 1) {
  24958. bkgData.background = bkgData.background + "_semi";
  24959. }
  24960. } else if (b === 45) {
  24961. bkgData.background = "transparent";
  24962. } else {
  24963. bkgData.foreground = "black";
  24964. if (b === 47) {
  24965. bkgData.underline = true;
  24966. }
  24967. }
  24968. const chNr = a <= 23 ? 1 : 2;
  24969. const channel = this.channels[chNr];
  24970. channel.setBkgData(bkgData);
  24971. return true;
  24972. }
  24973. /**
  24974. * Reset state of parser and its channels.
  24975. */
  24976. reset() {
  24977. for (let i = 0; i < Object.keys(this.channels).length; i++) {
  24978. const channel = this.channels[i];
  24979. if (channel) {
  24980. channel.reset();
  24981. }
  24982. }
  24983. setLastCmd(null, null, this.cmdHistory);
  24984. }
  24985. /**
  24986. * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
  24987. */
  24988. cueSplitAtTime(t) {
  24989. for (let i = 0; i < this.channels.length; i++) {
  24990. const channel = this.channels[i];
  24991. if (channel) {
  24992. channel.cueSplitAtTime(t);
  24993. }
  24994. }
  24995. }
  24996. };
  24997. function setLastCmd(a, b, cmdHistory) {
  24998. cmdHistory.a = a;
  24999. cmdHistory.b = b;
  25000. }
  25001. function hasCmdRepeated(a, b, cmdHistory) {
  25002. return cmdHistory.a === a && cmdHistory.b === b;
  25003. }
  25004. function createCmdHistory() {
  25005. return {
  25006. a: null,
  25007. b: null
  25008. };
  25009. }
  25010. var VTTCue = function() {
  25011. if (optionalSelf != null && optionalSelf.VTTCue) {
  25012. return self.VTTCue;
  25013. }
  25014. const AllowedDirections = ["", "lr", "rl"];
  25015. const AllowedAlignments = ["start", "middle", "end", "left", "right"];
  25016. function isAllowedValue(allowed, value) {
  25017. if (typeof value !== "string") {
  25018. return false;
  25019. }
  25020. if (!Array.isArray(allowed)) {
  25021. return false;
  25022. }
  25023. const lcValue = value.toLowerCase();
  25024. if (~allowed.indexOf(lcValue)) {
  25025. return lcValue;
  25026. }
  25027. return false;
  25028. }
  25029. function findDirectionSetting(value) {
  25030. return isAllowedValue(AllowedDirections, value);
  25031. }
  25032. function findAlignSetting(value) {
  25033. return isAllowedValue(AllowedAlignments, value);
  25034. }
  25035. function extend(obj, ...rest) {
  25036. let i = 1;
  25037. for (; i < arguments.length; i++) {
  25038. const cobj = arguments[i];
  25039. for (const p in cobj) {
  25040. obj[p] = cobj[p];
  25041. }
  25042. }
  25043. return obj;
  25044. }
  25045. function VTTCue2(startTime, endTime, text) {
  25046. const cue = this;
  25047. const baseObj = {
  25048. enumerable: true
  25049. };
  25050. cue.hasBeenReset = false;
  25051. let _id = "";
  25052. let _pauseOnExit = false;
  25053. let _startTime = startTime;
  25054. let _endTime = endTime;
  25055. let _text = text;
  25056. let _region = null;
  25057. let _vertical = "";
  25058. let _snapToLines = true;
  25059. let _line = "auto";
  25060. let _lineAlign = "start";
  25061. let _position = 50;
  25062. let _positionAlign = "middle";
  25063. let _size = 50;
  25064. let _align = "middle";
  25065. Object.defineProperty(cue, "id", extend({}, baseObj, {
  25066. get: function() {
  25067. return _id;
  25068. },
  25069. set: function(value) {
  25070. _id = "" + value;
  25071. }
  25072. }));
  25073. Object.defineProperty(cue, "pauseOnExit", extend({}, baseObj, {
  25074. get: function() {
  25075. return _pauseOnExit;
  25076. },
  25077. set: function(value) {
  25078. _pauseOnExit = !!value;
  25079. }
  25080. }));
  25081. Object.defineProperty(cue, "startTime", extend({}, baseObj, {
  25082. get: function() {
  25083. return _startTime;
  25084. },
  25085. set: function(value) {
  25086. if (typeof value !== "number") {
  25087. throw new TypeError("Start time must be set to a number.");
  25088. }
  25089. _startTime = value;
  25090. this.hasBeenReset = true;
  25091. }
  25092. }));
  25093. Object.defineProperty(cue, "endTime", extend({}, baseObj, {
  25094. get: function() {
  25095. return _endTime;
  25096. },
  25097. set: function(value) {
  25098. if (typeof value !== "number") {
  25099. throw new TypeError("End time must be set to a number.");
  25100. }
  25101. _endTime = value;
  25102. this.hasBeenReset = true;
  25103. }
  25104. }));
  25105. Object.defineProperty(cue, "text", extend({}, baseObj, {
  25106. get: function() {
  25107. return _text;
  25108. },
  25109. set: function(value) {
  25110. _text = "" + value;
  25111. this.hasBeenReset = true;
  25112. }
  25113. }));
  25114. Object.defineProperty(cue, "region", extend({}, baseObj, {
  25115. get: function() {
  25116. return _region;
  25117. },
  25118. set: function(value) {
  25119. _region = value;
  25120. this.hasBeenReset = true;
  25121. }
  25122. }));
  25123. Object.defineProperty(cue, "vertical", extend({}, baseObj, {
  25124. get: function() {
  25125. return _vertical;
  25126. },
  25127. set: function(value) {
  25128. const setting = findDirectionSetting(value);
  25129. if (setting === false) {
  25130. throw new SyntaxError("An invalid or illegal string was specified.");
  25131. }
  25132. _vertical = setting;
  25133. this.hasBeenReset = true;
  25134. }
  25135. }));
  25136. Object.defineProperty(cue, "snapToLines", extend({}, baseObj, {
  25137. get: function() {
  25138. return _snapToLines;
  25139. },
  25140. set: function(value) {
  25141. _snapToLines = !!value;
  25142. this.hasBeenReset = true;
  25143. }
  25144. }));
  25145. Object.defineProperty(cue, "line", extend({}, baseObj, {
  25146. get: function() {
  25147. return _line;
  25148. },
  25149. set: function(value) {
  25150. if (typeof value !== "number" && value !== "auto") {
  25151. throw new SyntaxError("An invalid number or illegal string was specified.");
  25152. }
  25153. _line = value;
  25154. this.hasBeenReset = true;
  25155. }
  25156. }));
  25157. Object.defineProperty(cue, "lineAlign", extend({}, baseObj, {
  25158. get: function() {
  25159. return _lineAlign;
  25160. },
  25161. set: function(value) {
  25162. const setting = findAlignSetting(value);
  25163. if (!setting) {
  25164. throw new SyntaxError("An invalid or illegal string was specified.");
  25165. }
  25166. _lineAlign = setting;
  25167. this.hasBeenReset = true;
  25168. }
  25169. }));
  25170. Object.defineProperty(cue, "position", extend({}, baseObj, {
  25171. get: function() {
  25172. return _position;
  25173. },
  25174. set: function(value) {
  25175. if (value < 0 || value > 100) {
  25176. throw new Error("Position must be between 0 and 100.");
  25177. }
  25178. _position = value;
  25179. this.hasBeenReset = true;
  25180. }
  25181. }));
  25182. Object.defineProperty(cue, "positionAlign", extend({}, baseObj, {
  25183. get: function() {
  25184. return _positionAlign;
  25185. },
  25186. set: function(value) {
  25187. const setting = findAlignSetting(value);
  25188. if (!setting) {
  25189. throw new SyntaxError("An invalid or illegal string was specified.");
  25190. }
  25191. _positionAlign = setting;
  25192. this.hasBeenReset = true;
  25193. }
  25194. }));
  25195. Object.defineProperty(cue, "size", extend({}, baseObj, {
  25196. get: function() {
  25197. return _size;
  25198. },
  25199. set: function(value) {
  25200. if (value < 0 || value > 100) {
  25201. throw new Error("Size must be between 0 and 100.");
  25202. }
  25203. _size = value;
  25204. this.hasBeenReset = true;
  25205. }
  25206. }));
  25207. Object.defineProperty(cue, "align", extend({}, baseObj, {
  25208. get: function() {
  25209. return _align;
  25210. },
  25211. set: function(value) {
  25212. const setting = findAlignSetting(value);
  25213. if (!setting) {
  25214. throw new SyntaxError("An invalid or illegal string was specified.");
  25215. }
  25216. _align = setting;
  25217. this.hasBeenReset = true;
  25218. }
  25219. }));
  25220. cue.displayState = void 0;
  25221. }
  25222. VTTCue2.prototype.getCueAsHTML = function() {
  25223. const WebVTT = self.WebVTT;
  25224. return WebVTT.convertCueToDOMTree(self, this.text);
  25225. };
  25226. return VTTCue2;
  25227. }();
  25228. var StringDecoder = class {
  25229. decode(data, options) {
  25230. if (!data) {
  25231. return "";
  25232. }
  25233. if (typeof data !== "string") {
  25234. throw new Error("Error - expected string data.");
  25235. }
  25236. return decodeURIComponent(encodeURIComponent(data));
  25237. }
  25238. };
  25239. function parseTimeStamp(input) {
  25240. function computeSeconds(h, m2, s, f) {
  25241. return (h | 0) * 3600 + (m2 | 0) * 60 + (s | 0) + parseFloat(f || 0);
  25242. }
  25243. const m = input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);
  25244. if (!m) {
  25245. return null;
  25246. }
  25247. if (parseFloat(m[2]) > 59) {
  25248. return computeSeconds(m[2], m[3], 0, m[4]);
  25249. }
  25250. return computeSeconds(m[1], m[2], m[3], m[4]);
  25251. }
  25252. var Settings = class {
  25253. constructor() {
  25254. this.values = /* @__PURE__ */ Object.create(null);
  25255. }
  25256. // Only accept the first assignment to any key.
  25257. set(k, v) {
  25258. if (!this.get(k) && v !== "") {
  25259. this.values[k] = v;
  25260. }
  25261. }
  25262. // Return the value for a key, or a default value.
  25263. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  25264. // a number of possible default values as properties where 'defaultKey' is
  25265. // the key of the property that will be chosen; otherwise it's assumed to be
  25266. // a single value.
  25267. get(k, dflt, defaultKey) {
  25268. if (defaultKey) {
  25269. return this.has(k) ? this.values[k] : dflt[defaultKey];
  25270. }
  25271. return this.has(k) ? this.values[k] : dflt;
  25272. }
  25273. // Check whether we have a value for a key.
  25274. has(k) {
  25275. return k in this.values;
  25276. }
  25277. // Accept a setting if its one of the given alternatives.
  25278. alt(k, v, a) {
  25279. for (let n = 0; n < a.length; ++n) {
  25280. if (v === a[n]) {
  25281. this.set(k, v);
  25282. break;
  25283. }
  25284. }
  25285. }
  25286. // Accept a setting if its a valid (signed) integer.
  25287. integer(k, v) {
  25288. if (/^-?\d+$/.test(v)) {
  25289. this.set(k, parseInt(v, 10));
  25290. }
  25291. }
  25292. // Accept a setting if its a valid percentage.
  25293. percent(k, v) {
  25294. if (/^([\d]{1,3})(\.[\d]*)?%$/.test(v)) {
  25295. const percent = parseFloat(v);
  25296. if (percent >= 0 && percent <= 100) {
  25297. this.set(k, percent);
  25298. return true;
  25299. }
  25300. }
  25301. return false;
  25302. }
  25303. };
  25304. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  25305. const groups = groupDelim ? input.split(groupDelim) : [input];
  25306. for (const i in groups) {
  25307. if (typeof groups[i] !== "string") {
  25308. continue;
  25309. }
  25310. const kv = groups[i].split(keyValueDelim);
  25311. if (kv.length !== 2) {
  25312. continue;
  25313. }
  25314. const k = kv[0];
  25315. const v = kv[1];
  25316. callback(k, v);
  25317. }
  25318. }
  25319. var defaults = new VTTCue(0, 0, "");
  25320. var center = defaults.align === "middle" ? "middle" : "center";
  25321. function parseCue(input, cue, regionList) {
  25322. const oInput = input;
  25323. function consumeTimeStamp() {
  25324. const ts = parseTimeStamp(input);
  25325. if (ts === null) {
  25326. throw new Error("Malformed timestamp: " + oInput);
  25327. }
  25328. input = input.replace(/^[^\sa-zA-Z-]+/, "");
  25329. return ts;
  25330. }
  25331. function consumeCueSettings(input2, cue2) {
  25332. const settings = new Settings();
  25333. parseOptions(input2, function(k, v) {
  25334. let vals;
  25335. switch (k) {
  25336. case "region":
  25337. for (let i = regionList.length - 1; i >= 0; i--) {
  25338. if (regionList[i].id === v) {
  25339. settings.set(k, regionList[i].region);
  25340. break;
  25341. }
  25342. }
  25343. break;
  25344. case "vertical":
  25345. settings.alt(k, v, ["rl", "lr"]);
  25346. break;
  25347. case "line":
  25348. vals = v.split(",");
  25349. settings.integer(k, vals[0]);
  25350. if (settings.percent(k, vals[0])) {
  25351. settings.set("snapToLines", false);
  25352. }
  25353. settings.alt(k, vals[0], ["auto"]);
  25354. if (vals.length === 2) {
  25355. settings.alt("lineAlign", vals[1], ["start", center, "end"]);
  25356. }
  25357. break;
  25358. case "position":
  25359. vals = v.split(",");
  25360. settings.percent(k, vals[0]);
  25361. if (vals.length === 2) {
  25362. settings.alt("positionAlign", vals[1], ["start", center, "end", "line-left", "line-right", "auto"]);
  25363. }
  25364. break;
  25365. case "size":
  25366. settings.percent(k, v);
  25367. break;
  25368. case "align":
  25369. settings.alt(k, v, ["start", center, "end", "left", "right"]);
  25370. break;
  25371. }
  25372. }, /:/, /\s/);
  25373. cue2.region = settings.get("region", null);
  25374. cue2.vertical = settings.get("vertical", "");
  25375. let line = settings.get("line", "auto");
  25376. if (line === "auto" && defaults.line === -1) {
  25377. line = -1;
  25378. }
  25379. cue2.line = line;
  25380. cue2.lineAlign = settings.get("lineAlign", "start");
  25381. cue2.snapToLines = settings.get("snapToLines", true);
  25382. cue2.size = settings.get("size", 100);
  25383. cue2.align = settings.get("align", center);
  25384. let position = settings.get("position", "auto");
  25385. if (position === "auto" && defaults.position === 50) {
  25386. position = cue2.align === "start" || cue2.align === "left" ? 0 : cue2.align === "end" || cue2.align === "right" ? 100 : 50;
  25387. }
  25388. cue2.position = position;
  25389. }
  25390. function skipWhitespace() {
  25391. input = input.replace(/^\s+/, "");
  25392. }
  25393. skipWhitespace();
  25394. cue.startTime = consumeTimeStamp();
  25395. skipWhitespace();
  25396. if (input.slice(0, 3) !== "-->") {
  25397. throw new Error("Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
  25398. }
  25399. input = input.slice(3);
  25400. skipWhitespace();
  25401. cue.endTime = consumeTimeStamp();
  25402. skipWhitespace();
  25403. consumeCueSettings(input, cue);
  25404. }
  25405. function fixLineBreaks(input) {
  25406. return input.replace(/<br(?: \/)?>/gi, "\n");
  25407. }
  25408. var VTTParser = class {
  25409. constructor() {
  25410. this.state = "INITIAL";
  25411. this.buffer = "";
  25412. this.decoder = new StringDecoder();
  25413. this.regionList = [];
  25414. this.cue = null;
  25415. this.oncue = void 0;
  25416. this.onparsingerror = void 0;
  25417. this.onflush = void 0;
  25418. }
  25419. parse(data) {
  25420. const _this = this;
  25421. if (data) {
  25422. _this.buffer += _this.decoder.decode(data, {
  25423. stream: true
  25424. });
  25425. }
  25426. function collectNextLine() {
  25427. let buffer = _this.buffer;
  25428. let pos = 0;
  25429. buffer = fixLineBreaks(buffer);
  25430. while (pos < buffer.length && buffer[pos] !== "\r" && buffer[pos] !== "\n") {
  25431. ++pos;
  25432. }
  25433. const line = buffer.slice(0, pos);
  25434. if (buffer[pos] === "\r") {
  25435. ++pos;
  25436. }
  25437. if (buffer[pos] === "\n") {
  25438. ++pos;
  25439. }
  25440. _this.buffer = buffer.slice(pos);
  25441. return line;
  25442. }
  25443. function parseHeader2(input) {
  25444. parseOptions(input, function(k, v) {
  25445. }, /:/);
  25446. }
  25447. try {
  25448. let line = "";
  25449. if (_this.state === "INITIAL") {
  25450. if (!/\r\n|\n/.test(_this.buffer)) {
  25451. return this;
  25452. }
  25453. line = collectNextLine();
  25454. const m = line.match(/^()?WEBVTT([ \t].*)?$/);
  25455. if (!(m != null && m[0])) {
  25456. throw new Error("Malformed WebVTT signature.");
  25457. }
  25458. _this.state = "HEADER";
  25459. }
  25460. let alreadyCollectedLine = false;
  25461. while (_this.buffer) {
  25462. if (!/\r\n|\n/.test(_this.buffer)) {
  25463. return this;
  25464. }
  25465. if (!alreadyCollectedLine) {
  25466. line = collectNextLine();
  25467. } else {
  25468. alreadyCollectedLine = false;
  25469. }
  25470. switch (_this.state) {
  25471. case "HEADER":
  25472. if (/:/.test(line)) {
  25473. parseHeader2(line);
  25474. } else if (!line) {
  25475. _this.state = "ID";
  25476. }
  25477. continue;
  25478. case "NOTE":
  25479. if (!line) {
  25480. _this.state = "ID";
  25481. }
  25482. continue;
  25483. case "ID":
  25484. if (/^NOTE($|[ \t])/.test(line)) {
  25485. _this.state = "NOTE";
  25486. break;
  25487. }
  25488. if (!line) {
  25489. continue;
  25490. }
  25491. _this.cue = new VTTCue(0, 0, "");
  25492. _this.state = "CUE";
  25493. if (line.indexOf("-->") === -1) {
  25494. _this.cue.id = line;
  25495. continue;
  25496. }
  25497. case "CUE":
  25498. if (!_this.cue) {
  25499. _this.state = "BADCUE";
  25500. continue;
  25501. }
  25502. try {
  25503. parseCue(line, _this.cue, _this.regionList);
  25504. } catch (e) {
  25505. _this.cue = null;
  25506. _this.state = "BADCUE";
  25507. continue;
  25508. }
  25509. _this.state = "CUETEXT";
  25510. continue;
  25511. case "CUETEXT":
  25512. {
  25513. const hasSubstring = line.indexOf("-->") !== -1;
  25514. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  25515. if (_this.oncue && _this.cue) {
  25516. _this.oncue(_this.cue);
  25517. }
  25518. _this.cue = null;
  25519. _this.state = "ID";
  25520. continue;
  25521. }
  25522. if (_this.cue === null) {
  25523. continue;
  25524. }
  25525. if (_this.cue.text) {
  25526. _this.cue.text += "\n";
  25527. }
  25528. _this.cue.text += line;
  25529. }
  25530. continue;
  25531. case "BADCUE":
  25532. if (!line) {
  25533. _this.state = "ID";
  25534. }
  25535. }
  25536. }
  25537. } catch (e) {
  25538. if (_this.state === "CUETEXT" && _this.cue && _this.oncue) {
  25539. _this.oncue(_this.cue);
  25540. }
  25541. _this.cue = null;
  25542. _this.state = _this.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
  25543. }
  25544. return this;
  25545. }
  25546. flush() {
  25547. const _this = this;
  25548. try {
  25549. if (_this.cue || _this.state === "HEADER") {
  25550. _this.buffer += "\n\n";
  25551. _this.parse();
  25552. }
  25553. if (_this.state === "INITIAL" || _this.state === "BADWEBVTT") {
  25554. throw new Error("Malformed WebVTT signature.");
  25555. }
  25556. } catch (e) {
  25557. if (_this.onparsingerror) {
  25558. _this.onparsingerror(e);
  25559. }
  25560. }
  25561. if (_this.onflush) {
  25562. _this.onflush();
  25563. }
  25564. return this;
  25565. }
  25566. };
  25567. var LINEBREAKS = /\r\n|\n\r|\n|\r/g;
  25568. var startsWith = function startsWith2(inputString, searchString, position = 0) {
  25569. return inputString.slice(position, position + searchString.length) === searchString;
  25570. };
  25571. var cueString2millis = function cueString2millis2(timeString) {
  25572. let ts = parseInt(timeString.slice(-3));
  25573. const secs = parseInt(timeString.slice(-6, -4));
  25574. const mins = parseInt(timeString.slice(-9, -7));
  25575. const hours = timeString.length > 9 ? parseInt(timeString.substring(0, timeString.indexOf(":"))) : 0;
  25576. if (!isFiniteNumber(ts) || !isFiniteNumber(secs) || !isFiniteNumber(mins) || !isFiniteNumber(hours)) {
  25577. throw Error(`Malformed X-TIMESTAMP-MAP: Local:${timeString}`);
  25578. }
  25579. ts += 1e3 * secs;
  25580. ts += 60 * 1e3 * mins;
  25581. ts += 60 * 60 * 1e3 * hours;
  25582. return ts;
  25583. };
  25584. function generateCueId(startTime, endTime, text) {
  25585. return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);
  25586. }
  25587. var calculateOffset = function calculateOffset2(vttCCs, cc, presentationTime) {
  25588. let currCC = vttCCs[cc];
  25589. let prevCC = vttCCs[currCC.prevCC];
  25590. if (!prevCC || !prevCC.new && currCC.new) {
  25591. vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
  25592. currCC.new = false;
  25593. return;
  25594. }
  25595. while ((_prevCC = prevCC) != null && _prevCC.new) {
  25596. var _prevCC;
  25597. vttCCs.ccOffset += currCC.start - prevCC.start;
  25598. currCC.new = false;
  25599. currCC = prevCC;
  25600. prevCC = vttCCs[currCC.prevCC];
  25601. }
  25602. vttCCs.presentationOffset = presentationTime;
  25603. };
  25604. function parseWebVTT(vttByteArray, initPTS, vttCCs, cc, timeOffset, callBack, errorCallBack) {
  25605. const parser = new VTTParser();
  25606. const vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, "\n").split("\n");
  25607. const cues = [];
  25608. const init90kHz = initPTS ? toMpegTsClockFromTimescale(initPTS.baseTime, initPTS.timescale) : 0;
  25609. let cueTime = "00:00.000";
  25610. let timestampMapMPEGTS = 0;
  25611. let timestampMapLOCAL = 0;
  25612. let parsingError;
  25613. let inHeader = true;
  25614. parser.oncue = function(cue) {
  25615. const currCC = vttCCs[cc];
  25616. let cueOffset = vttCCs.ccOffset;
  25617. const webVttMpegTsMapOffset = (timestampMapMPEGTS - init90kHz) / 9e4;
  25618. if (currCC != null && currCC.new) {
  25619. if (timestampMapLOCAL !== void 0) {
  25620. cueOffset = vttCCs.ccOffset = currCC.start;
  25621. } else {
  25622. calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);
  25623. }
  25624. }
  25625. if (webVttMpegTsMapOffset) {
  25626. if (!initPTS) {
  25627. parsingError = new Error("Missing initPTS for VTT MPEGTS");
  25628. return;
  25629. }
  25630. cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;
  25631. }
  25632. const duration = cue.endTime - cue.startTime;
  25633. const startTime = normalizePts((cue.startTime + cueOffset - timestampMapLOCAL) * 9e4, timeOffset * 9e4) / 9e4;
  25634. cue.startTime = Math.max(startTime, 0);
  25635. cue.endTime = Math.max(startTime + duration, 0);
  25636. const text = cue.text.trim();
  25637. cue.text = decodeURIComponent(encodeURIComponent(text));
  25638. if (!cue.id) {
  25639. cue.id = generateCueId(cue.startTime, cue.endTime, text);
  25640. }
  25641. if (cue.endTime > 0) {
  25642. cues.push(cue);
  25643. }
  25644. };
  25645. parser.onparsingerror = function(error) {
  25646. parsingError = error;
  25647. };
  25648. parser.onflush = function() {
  25649. if (parsingError) {
  25650. errorCallBack(parsingError);
  25651. return;
  25652. }
  25653. callBack(cues);
  25654. };
  25655. vttLines.forEach((line) => {
  25656. if (inHeader) {
  25657. if (startsWith(line, "X-TIMESTAMP-MAP=")) {
  25658. inHeader = false;
  25659. line.slice(16).split(",").forEach((timestamp) => {
  25660. if (startsWith(timestamp, "LOCAL:")) {
  25661. cueTime = timestamp.slice(6);
  25662. } else if (startsWith(timestamp, "MPEGTS:")) {
  25663. timestampMapMPEGTS = parseInt(timestamp.slice(7));
  25664. }
  25665. });
  25666. try {
  25667. timestampMapLOCAL = cueString2millis(cueTime) / 1e3;
  25668. } catch (error) {
  25669. parsingError = error;
  25670. }
  25671. return;
  25672. } else if (line === "") {
  25673. inHeader = false;
  25674. }
  25675. }
  25676. parser.parse(line + "\n");
  25677. });
  25678. parser.flush();
  25679. }
  25680. var IMSC1_CODEC = "stpp.ttml.im1t";
  25681. var HMSF_REGEX = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/;
  25682. var TIME_UNIT_REGEX = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/;
  25683. var textAlignToLineAlign = {
  25684. left: "start",
  25685. center: "center",
  25686. right: "end",
  25687. start: "start",
  25688. end: "end"
  25689. };
  25690. function parseIMSC1(payload, initPTS, callBack, errorCallBack) {
  25691. const results = findBox(new Uint8Array(payload), ["mdat"]);
  25692. if (results.length === 0) {
  25693. errorCallBack(new Error("Could not parse IMSC1 mdat"));
  25694. return;
  25695. }
  25696. const ttmlList = results.map((mdat) => utf8ArrayToStr(mdat));
  25697. const syncTime = toTimescaleFromScale(initPTS.baseTime, 1, initPTS.timescale);
  25698. try {
  25699. ttmlList.forEach((ttml) => callBack(parseTTML(ttml, syncTime)));
  25700. } catch (error) {
  25701. errorCallBack(error);
  25702. }
  25703. }
  25704. function parseTTML(ttml, syncTime) {
  25705. const parser = new DOMParser();
  25706. const xmlDoc = parser.parseFromString(ttml, "text/xml");
  25707. const tt = xmlDoc.getElementsByTagName("tt")[0];
  25708. if (!tt) {
  25709. throw new Error("Invalid ttml");
  25710. }
  25711. const defaultRateInfo = {
  25712. frameRate: 30,
  25713. subFrameRate: 1,
  25714. frameRateMultiplier: 0,
  25715. tickRate: 0
  25716. };
  25717. const rateInfo = Object.keys(defaultRateInfo).reduce((result, key) => {
  25718. result[key] = tt.getAttribute(`ttp:${key}`) || defaultRateInfo[key];
  25719. return result;
  25720. }, {});
  25721. const trim = tt.getAttribute("xml:space") !== "preserve";
  25722. const styleElements = collectionToDictionary(getElementCollection(tt, "styling", "style"));
  25723. const regionElements = collectionToDictionary(getElementCollection(tt, "layout", "region"));
  25724. const cueElements = getElementCollection(tt, "body", "[begin]");
  25725. return [].map.call(cueElements, (cueElement) => {
  25726. const cueText = getTextContent(cueElement, trim);
  25727. if (!cueText || !cueElement.hasAttribute("begin")) {
  25728. return null;
  25729. }
  25730. const startTime = parseTtmlTime(cueElement.getAttribute("begin"), rateInfo);
  25731. const duration = parseTtmlTime(cueElement.getAttribute("dur"), rateInfo);
  25732. let endTime = parseTtmlTime(cueElement.getAttribute("end"), rateInfo);
  25733. if (startTime === null) {
  25734. throw timestampParsingError(cueElement);
  25735. }
  25736. if (endTime === null) {
  25737. if (duration === null) {
  25738. throw timestampParsingError(cueElement);
  25739. }
  25740. endTime = startTime + duration;
  25741. }
  25742. const cue = new VTTCue(startTime - syncTime, endTime - syncTime, cueText);
  25743. cue.id = generateCueId(cue.startTime, cue.endTime, cue.text);
  25744. const region = regionElements[cueElement.getAttribute("region")];
  25745. const style = styleElements[cueElement.getAttribute("style")];
  25746. const styles = getTtmlStyles(region, style, styleElements);
  25747. const {
  25748. textAlign
  25749. } = styles;
  25750. if (textAlign) {
  25751. const lineAlign = textAlignToLineAlign[textAlign];
  25752. if (lineAlign) {
  25753. cue.lineAlign = lineAlign;
  25754. }
  25755. cue.align = textAlign;
  25756. }
  25757. _extends(cue, styles);
  25758. return cue;
  25759. }).filter((cue) => cue !== null);
  25760. }
  25761. function getElementCollection(fromElement, parentName, childName) {
  25762. const parent = fromElement.getElementsByTagName(parentName)[0];
  25763. if (parent) {
  25764. return [].slice.call(parent.querySelectorAll(childName));
  25765. }
  25766. return [];
  25767. }
  25768. function collectionToDictionary(elementsWithId) {
  25769. return elementsWithId.reduce((dict, element) => {
  25770. const id = element.getAttribute("xml:id");
  25771. if (id) {
  25772. dict[id] = element;
  25773. }
  25774. return dict;
  25775. }, {});
  25776. }
  25777. function getTextContent(element, trim) {
  25778. return [].slice.call(element.childNodes).reduce((str, node, i) => {
  25779. var _node$childNodes;
  25780. if (node.nodeName === "br" && i) {
  25781. return str + "\n";
  25782. }
  25783. if ((_node$childNodes = node.childNodes) != null && _node$childNodes.length) {
  25784. return getTextContent(node, trim);
  25785. } else if (trim) {
  25786. return str + node.textContent.trim().replace(/\s+/g, " ");
  25787. }
  25788. return str + node.textContent;
  25789. }, "");
  25790. }
  25791. function getTtmlStyles(region, style, styleElements) {
  25792. const ttsNs = "http://www.w3.org/ns/ttml#styling";
  25793. let regionStyle = null;
  25794. const styleAttributes = [
  25795. "displayAlign",
  25796. "textAlign",
  25797. "color",
  25798. "backgroundColor",
  25799. "fontSize",
  25800. "fontFamily"
  25801. // 'fontWeight',
  25802. // 'lineHeight',
  25803. // 'wrapOption',
  25804. // 'fontStyle',
  25805. // 'direction',
  25806. // 'writingMode'
  25807. ];
  25808. const regionStyleName = region != null && region.hasAttribute("style") ? region.getAttribute("style") : null;
  25809. if (regionStyleName && styleElements.hasOwnProperty(regionStyleName)) {
  25810. regionStyle = styleElements[regionStyleName];
  25811. }
  25812. return styleAttributes.reduce((styles, name) => {
  25813. const value = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name) || getAttributeNS(regionStyle, ttsNs, name);
  25814. if (value) {
  25815. styles[name] = value;
  25816. }
  25817. return styles;
  25818. }, {});
  25819. }
  25820. function getAttributeNS(element, ns, name) {
  25821. if (!element) {
  25822. return null;
  25823. }
  25824. return element.hasAttributeNS(ns, name) ? element.getAttributeNS(ns, name) : null;
  25825. }
  25826. function timestampParsingError(node) {
  25827. return new Error(`Could not parse ttml timestamp ${node}`);
  25828. }
  25829. function parseTtmlTime(timeAttributeValue, rateInfo) {
  25830. if (!timeAttributeValue) {
  25831. return null;
  25832. }
  25833. let seconds = parseTimeStamp(timeAttributeValue);
  25834. if (seconds === null) {
  25835. if (HMSF_REGEX.test(timeAttributeValue)) {
  25836. seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);
  25837. } else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {
  25838. seconds = parseTimeUnits(timeAttributeValue, rateInfo);
  25839. }
  25840. }
  25841. return seconds;
  25842. }
  25843. function parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) {
  25844. const m = HMSF_REGEX.exec(timeAttributeValue);
  25845. const frames = (m[4] | 0) + (m[5] | 0) / rateInfo.subFrameRate;
  25846. return (m[1] | 0) * 3600 + (m[2] | 0) * 60 + (m[3] | 0) + frames / rateInfo.frameRate;
  25847. }
  25848. function parseTimeUnits(timeAttributeValue, rateInfo) {
  25849. const m = TIME_UNIT_REGEX.exec(timeAttributeValue);
  25850. const value = Number(m[1]);
  25851. const unit = m[2];
  25852. switch (unit) {
  25853. case "h":
  25854. return value * 3600;
  25855. case "m":
  25856. return value * 60;
  25857. case "ms":
  25858. return value * 1e3;
  25859. case "f":
  25860. return value / rateInfo.frameRate;
  25861. case "t":
  25862. return value / rateInfo.tickRate;
  25863. }
  25864. return value;
  25865. }
  25866. var OutputFilter = class {
  25867. constructor(timelineController, trackName) {
  25868. this.timelineController = void 0;
  25869. this.cueRanges = [];
  25870. this.trackName = void 0;
  25871. this.startTime = null;
  25872. this.endTime = null;
  25873. this.screen = null;
  25874. this.timelineController = timelineController;
  25875. this.trackName = trackName;
  25876. }
  25877. dispatchCue() {
  25878. if (this.startTime === null) {
  25879. return;
  25880. }
  25881. this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);
  25882. this.startTime = null;
  25883. }
  25884. newCue(startTime, endTime, screen) {
  25885. if (this.startTime === null || this.startTime > startTime) {
  25886. this.startTime = startTime;
  25887. }
  25888. this.endTime = endTime;
  25889. this.screen = screen;
  25890. this.timelineController.createCaptionsTrack(this.trackName);
  25891. }
  25892. reset() {
  25893. this.cueRanges = [];
  25894. this.startTime = null;
  25895. }
  25896. };
  25897. var TimelineController = class {
  25898. constructor(hls) {
  25899. this.hls = void 0;
  25900. this.media = null;
  25901. this.config = void 0;
  25902. this.enabled = true;
  25903. this.Cues = void 0;
  25904. this.textTracks = [];
  25905. this.tracks = [];
  25906. this.initPTS = [];
  25907. this.unparsedVttFrags = [];
  25908. this.captionsTracks = {};
  25909. this.nonNativeCaptionsTracks = {};
  25910. this.cea608Parser1 = void 0;
  25911. this.cea608Parser2 = void 0;
  25912. this.lastCc = -1;
  25913. this.lastSn = -1;
  25914. this.lastPartIndex = -1;
  25915. this.prevCC = -1;
  25916. this.vttCCs = newVTTCCs();
  25917. this.captionsProperties = void 0;
  25918. this.hls = hls;
  25919. this.config = hls.config;
  25920. this.Cues = hls.config.cueHandler;
  25921. this.captionsProperties = {
  25922. textTrack1: {
  25923. label: this.config.captionsTextTrack1Label,
  25924. languageCode: this.config.captionsTextTrack1LanguageCode
  25925. },
  25926. textTrack2: {
  25927. label: this.config.captionsTextTrack2Label,
  25928. languageCode: this.config.captionsTextTrack2LanguageCode
  25929. },
  25930. textTrack3: {
  25931. label: this.config.captionsTextTrack3Label,
  25932. languageCode: this.config.captionsTextTrack3LanguageCode
  25933. },
  25934. textTrack4: {
  25935. label: this.config.captionsTextTrack4Label,
  25936. languageCode: this.config.captionsTextTrack4LanguageCode
  25937. }
  25938. };
  25939. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  25940. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  25941. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  25942. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  25943. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  25944. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  25945. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  25946. hls.on(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  25947. hls.on(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  25948. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  25949. hls.on(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  25950. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  25951. }
  25952. destroy() {
  25953. const {
  25954. hls
  25955. } = this;
  25956. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  25957. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  25958. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  25959. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  25960. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  25961. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  25962. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  25963. hls.off(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  25964. hls.off(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  25965. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  25966. hls.off(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  25967. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  25968. this.hls = this.config = this.media = null;
  25969. this.cea608Parser1 = this.cea608Parser2 = void 0;
  25970. }
  25971. initCea608Parsers() {
  25972. const channel1 = new OutputFilter(this, "textTrack1");
  25973. const channel2 = new OutputFilter(this, "textTrack2");
  25974. const channel3 = new OutputFilter(this, "textTrack3");
  25975. const channel4 = new OutputFilter(this, "textTrack4");
  25976. this.cea608Parser1 = new Cea608Parser(1, channel1, channel2);
  25977. this.cea608Parser2 = new Cea608Parser(3, channel3, channel4);
  25978. }
  25979. addCues(trackName, startTime, endTime, screen, cueRanges) {
  25980. let merged = false;
  25981. for (let i = cueRanges.length; i--; ) {
  25982. const cueRange = cueRanges[i];
  25983. const overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
  25984. if (overlap >= 0) {
  25985. cueRange[0] = Math.min(cueRange[0], startTime);
  25986. cueRange[1] = Math.max(cueRange[1], endTime);
  25987. merged = true;
  25988. if (overlap / (endTime - startTime) > 0.5) {
  25989. return;
  25990. }
  25991. }
  25992. }
  25993. if (!merged) {
  25994. cueRanges.push([startTime, endTime]);
  25995. }
  25996. if (this.config.renderTextTracksNatively) {
  25997. const track = this.captionsTracks[trackName];
  25998. this.Cues.newCue(track, startTime, endTime, screen);
  25999. } else {
  26000. const cues = this.Cues.newCue(null, startTime, endTime, screen);
  26001. this.hls.trigger(Events.CUES_PARSED, {
  26002. type: "captions",
  26003. cues,
  26004. track: trackName
  26005. });
  26006. }
  26007. }
  26008. // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
  26009. onInitPtsFound(event, {
  26010. frag,
  26011. id,
  26012. initPTS,
  26013. timescale
  26014. }) {
  26015. const {
  26016. unparsedVttFrags
  26017. } = this;
  26018. if (id === PlaylistLevelType.MAIN) {
  26019. this.initPTS[frag.cc] = {
  26020. baseTime: initPTS,
  26021. timescale
  26022. };
  26023. }
  26024. if (unparsedVttFrags.length) {
  26025. this.unparsedVttFrags = [];
  26026. unparsedVttFrags.forEach((data) => {
  26027. if (this.initPTS[data.frag.cc]) {
  26028. this.onFragLoaded(Events.FRAG_LOADED, data);
  26029. } else {
  26030. this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  26031. success: false,
  26032. frag: data.frag,
  26033. error: new Error("Subtitle discontinuity domain does not match main")
  26034. });
  26035. }
  26036. });
  26037. }
  26038. }
  26039. getExistingTrack(label, language) {
  26040. const {
  26041. media
  26042. } = this;
  26043. if (media) {
  26044. for (let i = 0; i < media.textTracks.length; i++) {
  26045. const textTrack = media.textTracks[i];
  26046. if (canReuseVttTextTrack(textTrack, {
  26047. name: label,
  26048. lang: language,
  26049. characteristics: "transcribes-spoken-dialog,describes-music-and-sound"
  26050. })) {
  26051. return textTrack;
  26052. }
  26053. }
  26054. }
  26055. return null;
  26056. }
  26057. createCaptionsTrack(trackName) {
  26058. if (this.config.renderTextTracksNatively) {
  26059. this.createNativeTrack(trackName);
  26060. } else {
  26061. this.createNonNativeTrack(trackName);
  26062. }
  26063. }
  26064. createNativeTrack(trackName) {
  26065. if (this.captionsTracks[trackName]) {
  26066. return;
  26067. }
  26068. const {
  26069. captionsProperties,
  26070. captionsTracks,
  26071. media
  26072. } = this;
  26073. const {
  26074. label,
  26075. languageCode
  26076. } = captionsProperties[trackName];
  26077. const existingTrack = this.getExistingTrack(label, languageCode);
  26078. if (!existingTrack) {
  26079. const textTrack = this.createTextTrack("captions", label, languageCode);
  26080. if (textTrack) {
  26081. textTrack[trackName] = true;
  26082. captionsTracks[trackName] = textTrack;
  26083. }
  26084. } else {
  26085. captionsTracks[trackName] = existingTrack;
  26086. clearCurrentCues(captionsTracks[trackName]);
  26087. sendAddTrackEvent(captionsTracks[trackName], media);
  26088. }
  26089. }
  26090. createNonNativeTrack(trackName) {
  26091. if (this.nonNativeCaptionsTracks[trackName]) {
  26092. return;
  26093. }
  26094. const trackProperties = this.captionsProperties[trackName];
  26095. if (!trackProperties) {
  26096. return;
  26097. }
  26098. const label = trackProperties.label;
  26099. const track = {
  26100. _id: trackName,
  26101. label,
  26102. kind: "captions",
  26103. default: trackProperties.media ? !!trackProperties.media.default : false,
  26104. closedCaptions: trackProperties.media
  26105. };
  26106. this.nonNativeCaptionsTracks[trackName] = track;
  26107. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  26108. tracks: [track]
  26109. });
  26110. }
  26111. createTextTrack(kind, label, lang) {
  26112. const media = this.media;
  26113. if (!media) {
  26114. return;
  26115. }
  26116. return media.addTextTrack(kind, label, lang);
  26117. }
  26118. onMediaAttaching(event, data) {
  26119. this.media = data.media;
  26120. if (!data.mediaSource) {
  26121. this._cleanTracks();
  26122. }
  26123. }
  26124. onMediaDetaching(event, data) {
  26125. const transferringMedia = !!data.transferMedia;
  26126. this.media = null;
  26127. if (transferringMedia) {
  26128. return;
  26129. }
  26130. const {
  26131. captionsTracks
  26132. } = this;
  26133. Object.keys(captionsTracks).forEach((trackName) => {
  26134. clearCurrentCues(captionsTracks[trackName]);
  26135. delete captionsTracks[trackName];
  26136. });
  26137. this.nonNativeCaptionsTracks = {};
  26138. }
  26139. onManifestLoading() {
  26140. this.lastCc = -1;
  26141. this.lastSn = -1;
  26142. this.lastPartIndex = -1;
  26143. this.prevCC = -1;
  26144. this.vttCCs = newVTTCCs();
  26145. this._cleanTracks();
  26146. this.tracks = [];
  26147. this.captionsTracks = {};
  26148. this.nonNativeCaptionsTracks = {};
  26149. this.textTracks = [];
  26150. this.unparsedVttFrags = [];
  26151. this.initPTS = [];
  26152. if (this.cea608Parser1 && this.cea608Parser2) {
  26153. this.cea608Parser1.reset();
  26154. this.cea608Parser2.reset();
  26155. }
  26156. }
  26157. _cleanTracks() {
  26158. const {
  26159. media
  26160. } = this;
  26161. if (!media) {
  26162. return;
  26163. }
  26164. const textTracks = media.textTracks;
  26165. if (textTracks) {
  26166. for (let i = 0; i < textTracks.length; i++) {
  26167. clearCurrentCues(textTracks[i]);
  26168. }
  26169. }
  26170. }
  26171. onSubtitleTracksUpdated(event, data) {
  26172. const tracks = data.subtitleTracks || [];
  26173. const hasIMSC1 = tracks.some((track) => track.textCodec === IMSC1_CODEC);
  26174. if (this.config.enableWebVTT || hasIMSC1 && this.config.enableIMSC1) {
  26175. const listIsIdentical = subtitleOptionsIdentical(this.tracks, tracks);
  26176. if (listIsIdentical) {
  26177. this.tracks = tracks;
  26178. return;
  26179. }
  26180. this.textTracks = [];
  26181. this.tracks = tracks;
  26182. if (this.config.renderTextTracksNatively) {
  26183. const media = this.media;
  26184. const inUseTracks = media ? filterSubtitleTracks(media.textTracks) : null;
  26185. this.tracks.forEach((track, index) => {
  26186. let textTrack;
  26187. if (inUseTracks) {
  26188. let inUseTrack = null;
  26189. for (let i = 0; i < inUseTracks.length; i++) {
  26190. if (inUseTracks[i] && canReuseVttTextTrack(inUseTracks[i], track)) {
  26191. inUseTrack = inUseTracks[i];
  26192. inUseTracks[i] = null;
  26193. break;
  26194. }
  26195. }
  26196. if (inUseTrack) {
  26197. textTrack = inUseTrack;
  26198. }
  26199. }
  26200. if (textTrack) {
  26201. clearCurrentCues(textTrack);
  26202. } else {
  26203. const textTrackKind = captionsOrSubtitlesFromCharacteristics(track);
  26204. textTrack = this.createTextTrack(textTrackKind, track.name, track.lang);
  26205. if (textTrack) {
  26206. textTrack.mode = "disabled";
  26207. }
  26208. }
  26209. if (textTrack) {
  26210. this.textTracks.push(textTrack);
  26211. }
  26212. });
  26213. if (inUseTracks != null && inUseTracks.length) {
  26214. const unusedTextTracks = inUseTracks.filter((t) => t !== null).map((t) => t.label);
  26215. if (unusedTextTracks.length) {
  26216. this.hls.logger.warn(`Media element contains unused subtitle tracks: ${unusedTextTracks.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`);
  26217. }
  26218. }
  26219. } else if (this.tracks.length) {
  26220. const tracksList = this.tracks.map((track) => {
  26221. return {
  26222. label: track.name,
  26223. kind: track.type.toLowerCase(),
  26224. default: track.default,
  26225. subtitleTrack: track
  26226. };
  26227. });
  26228. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  26229. tracks: tracksList
  26230. });
  26231. }
  26232. }
  26233. }
  26234. onManifestLoaded(event, data) {
  26235. if (this.config.enableCEA708Captions && data.captions) {
  26236. data.captions.forEach((captionsTrack) => {
  26237. const instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);
  26238. if (!instreamIdMatch) {
  26239. return;
  26240. }
  26241. const trackName = `textTrack${instreamIdMatch[1]}`;
  26242. const trackProperties = this.captionsProperties[trackName];
  26243. if (!trackProperties) {
  26244. return;
  26245. }
  26246. trackProperties.label = captionsTrack.name;
  26247. if (captionsTrack.lang) {
  26248. trackProperties.languageCode = captionsTrack.lang;
  26249. }
  26250. trackProperties.media = captionsTrack;
  26251. });
  26252. }
  26253. }
  26254. closedCaptionsForLevel(frag) {
  26255. const level = this.hls.levels[frag.level];
  26256. return level == null ? void 0 : level.attrs["CLOSED-CAPTIONS"];
  26257. }
  26258. onFragLoading(event, data) {
  26259. if (this.enabled && data.frag.type === PlaylistLevelType.MAIN) {
  26260. var _data$part$index, _data$part;
  26261. const {
  26262. cea608Parser1,
  26263. cea608Parser2,
  26264. lastSn
  26265. } = this;
  26266. const {
  26267. cc,
  26268. sn
  26269. } = data.frag;
  26270. const partIndex = (_data$part$index = (_data$part = data.part) == null ? void 0 : _data$part.index) != null ? _data$part$index : -1;
  26271. if (cea608Parser1 && cea608Parser2) {
  26272. if (sn !== lastSn + 1 || sn === lastSn && partIndex !== this.lastPartIndex + 1 || cc !== this.lastCc) {
  26273. cea608Parser1.reset();
  26274. cea608Parser2.reset();
  26275. }
  26276. }
  26277. this.lastCc = cc;
  26278. this.lastSn = sn;
  26279. this.lastPartIndex = partIndex;
  26280. }
  26281. }
  26282. onFragLoaded(event, data) {
  26283. const {
  26284. frag,
  26285. payload
  26286. } = data;
  26287. if (frag.type === PlaylistLevelType.SUBTITLE) {
  26288. if (payload.byteLength) {
  26289. const decryptData = frag.decryptdata;
  26290. const decrypted = "stats" in data;
  26291. if (decryptData == null || !decryptData.encrypted || decrypted) {
  26292. const trackPlaylistMedia = this.tracks[frag.level];
  26293. const vttCCs = this.vttCCs;
  26294. if (!vttCCs[frag.cc]) {
  26295. vttCCs[frag.cc] = {
  26296. start: frag.start,
  26297. prevCC: this.prevCC,
  26298. new: true
  26299. };
  26300. this.prevCC = frag.cc;
  26301. }
  26302. if (trackPlaylistMedia && trackPlaylistMedia.textCodec === IMSC1_CODEC) {
  26303. this._parseIMSC1(frag, payload);
  26304. } else {
  26305. this._parseVTTs(data);
  26306. }
  26307. }
  26308. } else {
  26309. this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  26310. success: false,
  26311. frag,
  26312. error: new Error("Empty subtitle payload")
  26313. });
  26314. }
  26315. }
  26316. }
  26317. _parseIMSC1(frag, payload) {
  26318. const hls = this.hls;
  26319. parseIMSC1(payload, this.initPTS[frag.cc], (cues) => {
  26320. this._appendCues(cues, frag.level);
  26321. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  26322. success: true,
  26323. frag
  26324. });
  26325. }, (error) => {
  26326. hls.logger.log(`Failed to parse IMSC1: ${error}`);
  26327. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  26328. success: false,
  26329. frag,
  26330. error
  26331. });
  26332. });
  26333. }
  26334. _parseVTTs(data) {
  26335. var _frag$initSegment;
  26336. const {
  26337. frag,
  26338. payload
  26339. } = data;
  26340. const {
  26341. initPTS,
  26342. unparsedVttFrags
  26343. } = this;
  26344. const maxAvCC = initPTS.length - 1;
  26345. if (!initPTS[frag.cc] && maxAvCC === -1) {
  26346. unparsedVttFrags.push(data);
  26347. return;
  26348. }
  26349. const hls = this.hls;
  26350. const payloadWebVTT = (_frag$initSegment = frag.initSegment) != null && _frag$initSegment.data ? appendUint8Array(frag.initSegment.data, new Uint8Array(payload)).buffer : payload;
  26351. parseWebVTT(payloadWebVTT, this.initPTS[frag.cc], this.vttCCs, frag.cc, frag.start, (cues) => {
  26352. this._appendCues(cues, frag.level);
  26353. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  26354. success: true,
  26355. frag
  26356. });
  26357. }, (error) => {
  26358. const missingInitPTS = error.message === "Missing initPTS for VTT MPEGTS";
  26359. if (missingInitPTS) {
  26360. unparsedVttFrags.push(data);
  26361. } else {
  26362. this._fallbackToIMSC1(frag, payload);
  26363. }
  26364. hls.logger.log(`Failed to parse VTT cue: ${error}`);
  26365. if (missingInitPTS && maxAvCC > frag.cc) {
  26366. return;
  26367. }
  26368. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  26369. success: false,
  26370. frag,
  26371. error
  26372. });
  26373. });
  26374. }
  26375. _fallbackToIMSC1(frag, payload) {
  26376. const trackPlaylistMedia = this.tracks[frag.level];
  26377. if (!trackPlaylistMedia.textCodec) {
  26378. parseIMSC1(payload, this.initPTS[frag.cc], () => {
  26379. trackPlaylistMedia.textCodec = IMSC1_CODEC;
  26380. this._parseIMSC1(frag, payload);
  26381. }, () => {
  26382. trackPlaylistMedia.textCodec = "wvtt";
  26383. });
  26384. }
  26385. }
  26386. _appendCues(cues, fragLevel) {
  26387. const hls = this.hls;
  26388. if (this.config.renderTextTracksNatively) {
  26389. const textTrack = this.textTracks[fragLevel];
  26390. if (!textTrack || textTrack.mode === "disabled") {
  26391. return;
  26392. }
  26393. cues.forEach((cue) => addCueToTrack(textTrack, cue));
  26394. } else {
  26395. const currentTrack = this.tracks[fragLevel];
  26396. if (!currentTrack) {
  26397. return;
  26398. }
  26399. const track = currentTrack.default ? "default" : "subtitles" + fragLevel;
  26400. hls.trigger(Events.CUES_PARSED, {
  26401. type: "subtitles",
  26402. cues,
  26403. track
  26404. });
  26405. }
  26406. }
  26407. onFragDecrypted(event, data) {
  26408. const {
  26409. frag
  26410. } = data;
  26411. if (frag.type === PlaylistLevelType.SUBTITLE) {
  26412. this.onFragLoaded(Events.FRAG_LOADED, data);
  26413. }
  26414. }
  26415. onSubtitleTracksCleared() {
  26416. this.tracks = [];
  26417. this.captionsTracks = {};
  26418. }
  26419. onFragParsingUserdata(event, data) {
  26420. if (!this.enabled || !this.config.enableCEA708Captions) {
  26421. return;
  26422. }
  26423. const {
  26424. frag,
  26425. samples
  26426. } = data;
  26427. if (frag.type === PlaylistLevelType.MAIN && this.closedCaptionsForLevel(frag) === "NONE") {
  26428. return;
  26429. }
  26430. for (let i = 0; i < samples.length; i++) {
  26431. const ccBytes = samples[i].bytes;
  26432. if (ccBytes) {
  26433. if (!this.cea608Parser1) {
  26434. this.initCea608Parsers();
  26435. }
  26436. const ccdatas = this.extractCea608Data(ccBytes);
  26437. this.cea608Parser1.addData(samples[i].pts, ccdatas[0]);
  26438. this.cea608Parser2.addData(samples[i].pts, ccdatas[1]);
  26439. }
  26440. }
  26441. }
  26442. onBufferFlushing(event, {
  26443. startOffset,
  26444. endOffset,
  26445. endOffsetSubtitles,
  26446. type
  26447. }) {
  26448. const {
  26449. media
  26450. } = this;
  26451. if (!media || media.currentTime < endOffset) {
  26452. return;
  26453. }
  26454. if (!type || type === "video") {
  26455. const {
  26456. captionsTracks
  26457. } = this;
  26458. Object.keys(captionsTracks).forEach((trackName) => removeCuesInRange(captionsTracks[trackName], startOffset, endOffset));
  26459. }
  26460. if (this.config.renderTextTracksNatively) {
  26461. if (startOffset === 0 && endOffsetSubtitles !== void 0) {
  26462. const {
  26463. textTracks
  26464. } = this;
  26465. Object.keys(textTracks).forEach((trackName) => removeCuesInRange(textTracks[trackName], startOffset, endOffsetSubtitles));
  26466. }
  26467. }
  26468. }
  26469. extractCea608Data(byteArray) {
  26470. const actualCCBytes = [[], []];
  26471. const count = byteArray[0] & 31;
  26472. let position = 2;
  26473. for (let j = 0; j < count; j++) {
  26474. const tmpByte = byteArray[position++];
  26475. const ccbyte1 = 127 & byteArray[position++];
  26476. const ccbyte2 = 127 & byteArray[position++];
  26477. if (ccbyte1 === 0 && ccbyte2 === 0) {
  26478. continue;
  26479. }
  26480. const ccValid = (4 & tmpByte) !== 0;
  26481. if (ccValid) {
  26482. const ccType = 3 & tmpByte;
  26483. if (0 === ccType || 1 === ccType) {
  26484. actualCCBytes[ccType].push(ccbyte1);
  26485. actualCCBytes[ccType].push(ccbyte2);
  26486. }
  26487. }
  26488. }
  26489. return actualCCBytes;
  26490. }
  26491. };
  26492. function captionsOrSubtitlesFromCharacteristics(track) {
  26493. if (track.characteristics) {
  26494. if (/transcribes-spoken-dialog/gi.test(track.characteristics) && /describes-music-and-sound/gi.test(track.characteristics)) {
  26495. return "captions";
  26496. }
  26497. }
  26498. return "subtitles";
  26499. }
  26500. function canReuseVttTextTrack(inUseTrack, manifestTrack) {
  26501. return !!inUseTrack && inUseTrack.kind === captionsOrSubtitlesFromCharacteristics(manifestTrack) && subtitleTrackMatchesTextTrack(manifestTrack, inUseTrack);
  26502. }
  26503. function intersection(x1, x2, y1, y2) {
  26504. return Math.min(x2, y2) - Math.max(x1, y1);
  26505. }
  26506. function newVTTCCs() {
  26507. return {
  26508. ccOffset: 0,
  26509. presentationOffset: 0,
  26510. 0: {
  26511. start: 0,
  26512. prevCC: -1,
  26513. new: true
  26514. }
  26515. };
  26516. }
  26517. var WHITESPACE_CHAR = /\s/;
  26518. var Cues = {
  26519. newCue(track, startTime, endTime, captionScreen) {
  26520. const result = [];
  26521. let row;
  26522. let cue;
  26523. let indenting;
  26524. let indent;
  26525. let text;
  26526. const Cue = self.VTTCue || self.TextTrackCue;
  26527. for (let r = 0; r < captionScreen.rows.length; r++) {
  26528. row = captionScreen.rows[r];
  26529. indenting = true;
  26530. indent = 0;
  26531. text = "";
  26532. if (!row.isEmpty()) {
  26533. var _track$cues;
  26534. for (let c = 0; c < row.chars.length; c++) {
  26535. if (WHITESPACE_CHAR.test(row.chars[c].uchar) && indenting) {
  26536. indent++;
  26537. } else {
  26538. text += row.chars[c].uchar;
  26539. indenting = false;
  26540. }
  26541. }
  26542. row.cueStartTime = startTime;
  26543. if (startTime === endTime) {
  26544. endTime += 1e-4;
  26545. }
  26546. if (indent >= 16) {
  26547. indent--;
  26548. } else {
  26549. indent++;
  26550. }
  26551. const cueText = fixLineBreaks(text.trim());
  26552. const id = generateCueId(startTime, endTime, cueText);
  26553. if (!(track != null && (_track$cues = track.cues) != null && _track$cues.getCueById(id))) {
  26554. cue = new Cue(startTime, endTime, cueText);
  26555. cue.id = id;
  26556. cue.line = r + 1;
  26557. cue.align = "left";
  26558. cue.position = 10 + Math.min(80, Math.floor(indent * 8 / 32) * 10);
  26559. result.push(cue);
  26560. }
  26561. }
  26562. }
  26563. if (track && result.length) {
  26564. result.sort((cueA, cueB) => {
  26565. if (cueA.line === "auto" || cueB.line === "auto") {
  26566. return 0;
  26567. }
  26568. if (cueA.line > 8 && cueB.line > 8) {
  26569. return cueB.line - cueA.line;
  26570. }
  26571. return cueA.line - cueB.line;
  26572. });
  26573. result.forEach((cue2) => addCueToTrack(track, cue2));
  26574. }
  26575. return result;
  26576. }
  26577. };
  26578. function fetchSupported() {
  26579. if (
  26580. // @ts-ignore
  26581. self.fetch && self.AbortController && self.ReadableStream && self.Request
  26582. ) {
  26583. try {
  26584. new self.ReadableStream({});
  26585. return true;
  26586. } catch (e) {
  26587. }
  26588. }
  26589. return false;
  26590. }
  26591. var BYTERANGE = /(\d+)-(\d+)\/(\d+)/;
  26592. var FetchLoader = class {
  26593. constructor(config) {
  26594. this.fetchSetup = void 0;
  26595. this.requestTimeout = void 0;
  26596. this.request = null;
  26597. this.response = null;
  26598. this.controller = void 0;
  26599. this.context = null;
  26600. this.config = null;
  26601. this.callbacks = null;
  26602. this.stats = void 0;
  26603. this.loader = null;
  26604. this.fetchSetup = config.fetchSetup || getRequest;
  26605. this.controller = new self.AbortController();
  26606. this.stats = new LoadStats();
  26607. }
  26608. destroy() {
  26609. this.loader = this.callbacks = this.context = this.config = this.request = null;
  26610. this.abortInternal();
  26611. this.response = null;
  26612. this.fetchSetup = this.controller = this.stats = null;
  26613. }
  26614. abortInternal() {
  26615. if (this.controller && !this.stats.loading.end) {
  26616. this.stats.aborted = true;
  26617. this.controller.abort();
  26618. }
  26619. }
  26620. abort() {
  26621. var _this$callbacks;
  26622. this.abortInternal();
  26623. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  26624. this.callbacks.onAbort(this.stats, this.context, this.response);
  26625. }
  26626. }
  26627. load(context, config, callbacks) {
  26628. const stats = this.stats;
  26629. if (stats.loading.start) {
  26630. throw new Error("Loader can only be used once.");
  26631. }
  26632. stats.loading.start = self.performance.now();
  26633. const initParams = getRequestParameters(context, this.controller.signal);
  26634. const isArrayBuffer = context.responseType === "arraybuffer";
  26635. const LENGTH = isArrayBuffer ? "byteLength" : "length";
  26636. const {
  26637. maxTimeToFirstByteMs,
  26638. maxLoadTimeMs
  26639. } = config.loadPolicy;
  26640. this.context = context;
  26641. this.config = config;
  26642. this.callbacks = callbacks;
  26643. this.request = this.fetchSetup(context, initParams);
  26644. self.clearTimeout(this.requestTimeout);
  26645. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  26646. this.requestTimeout = self.setTimeout(() => {
  26647. if (this.callbacks) {
  26648. this.abortInternal();
  26649. this.callbacks.onTimeout(stats, context, this.response);
  26650. }
  26651. }, config.timeout);
  26652. const fetchPromise = isPromise(this.request) ? this.request.then(self.fetch) : self.fetch(this.request);
  26653. fetchPromise.then((response) => {
  26654. var _this$callbacks2;
  26655. this.response = this.loader = response;
  26656. const first = Math.max(self.performance.now(), stats.loading.start);
  26657. self.clearTimeout(this.requestTimeout);
  26658. config.timeout = maxLoadTimeMs;
  26659. this.requestTimeout = self.setTimeout(() => {
  26660. if (this.callbacks) {
  26661. this.abortInternal();
  26662. this.callbacks.onTimeout(stats, context, this.response);
  26663. }
  26664. }, maxLoadTimeMs - (first - stats.loading.start));
  26665. if (!response.ok) {
  26666. const {
  26667. status: status2,
  26668. statusText
  26669. } = response;
  26670. throw new FetchError(statusText || "fetch, bad network response", status2, response);
  26671. }
  26672. stats.loading.first = first;
  26673. stats.total = getContentLength(response.headers) || stats.total;
  26674. const onProgress = (_this$callbacks2 = this.callbacks) == null ? void 0 : _this$callbacks2.onProgress;
  26675. if (onProgress && isFiniteNumber(config.highWaterMark)) {
  26676. return this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
  26677. }
  26678. if (isArrayBuffer) {
  26679. return response.arrayBuffer();
  26680. }
  26681. if (context.responseType === "json") {
  26682. return response.json();
  26683. }
  26684. return response.text();
  26685. }).then((responseData) => {
  26686. var _this$callbacks3, _this$callbacks4;
  26687. const response = this.response;
  26688. if (!response) {
  26689. throw new Error("loader destroyed");
  26690. }
  26691. self.clearTimeout(this.requestTimeout);
  26692. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  26693. const total = responseData[LENGTH];
  26694. if (total) {
  26695. stats.loaded = stats.total = total;
  26696. }
  26697. const loaderResponse = {
  26698. url: response.url,
  26699. data: responseData,
  26700. code: response.status
  26701. };
  26702. const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  26703. if (onProgress && !isFiniteNumber(config.highWaterMark)) {
  26704. onProgress(stats, context, responseData, response);
  26705. }
  26706. (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(loaderResponse, stats, context, response);
  26707. }).catch((error) => {
  26708. var _this$callbacks5;
  26709. self.clearTimeout(this.requestTimeout);
  26710. if (stats.aborted) {
  26711. return;
  26712. }
  26713. const code = !error ? 0 : error.code || 0;
  26714. const text = !error ? null : error.message;
  26715. (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({
  26716. code,
  26717. text
  26718. }, context, error ? error.details : null, stats);
  26719. });
  26720. }
  26721. getCacheAge() {
  26722. let result = null;
  26723. if (this.response) {
  26724. const ageHeader = this.response.headers.get("age");
  26725. result = ageHeader ? parseFloat(ageHeader) : null;
  26726. }
  26727. return result;
  26728. }
  26729. getResponseHeader(name) {
  26730. return this.response ? this.response.headers.get(name) : null;
  26731. }
  26732. loadProgressively(response, stats, context, highWaterMark = 0, onProgress) {
  26733. const chunkCache = new ChunkCache();
  26734. const reader = response.body.getReader();
  26735. const pump = () => {
  26736. return reader.read().then((data) => {
  26737. if (data.done) {
  26738. if (chunkCache.dataLength) {
  26739. onProgress(stats, context, chunkCache.flush().buffer, response);
  26740. }
  26741. return Promise.resolve(new ArrayBuffer(0));
  26742. }
  26743. const chunk = data.value;
  26744. const len = chunk.length;
  26745. stats.loaded += len;
  26746. if (len < highWaterMark || chunkCache.dataLength) {
  26747. chunkCache.push(chunk);
  26748. if (chunkCache.dataLength >= highWaterMark) {
  26749. onProgress(stats, context, chunkCache.flush().buffer, response);
  26750. }
  26751. } else {
  26752. onProgress(stats, context, chunk.buffer, response);
  26753. }
  26754. return pump();
  26755. }).catch(() => {
  26756. return Promise.reject();
  26757. });
  26758. };
  26759. return pump();
  26760. }
  26761. };
  26762. function getRequestParameters(context, signal) {
  26763. const initParams = {
  26764. method: "GET",
  26765. mode: "cors",
  26766. credentials: "same-origin",
  26767. signal,
  26768. headers: new self.Headers(_extends({}, context.headers))
  26769. };
  26770. if (context.rangeEnd) {
  26771. initParams.headers.set("Range", "bytes=" + context.rangeStart + "-" + String(context.rangeEnd - 1));
  26772. }
  26773. return initParams;
  26774. }
  26775. function getByteRangeLength(byteRangeHeader) {
  26776. const result = BYTERANGE.exec(byteRangeHeader);
  26777. if (result) {
  26778. return parseInt(result[2]) - parseInt(result[1]) + 1;
  26779. }
  26780. }
  26781. function getContentLength(headers) {
  26782. const contentRange = headers.get("Content-Range");
  26783. if (contentRange) {
  26784. const byteRangeLength = getByteRangeLength(contentRange);
  26785. if (isFiniteNumber(byteRangeLength)) {
  26786. return byteRangeLength;
  26787. }
  26788. }
  26789. const contentLength = headers.get("Content-Length");
  26790. if (contentLength) {
  26791. return parseInt(contentLength);
  26792. }
  26793. }
  26794. function getRequest(context, initParams) {
  26795. return new self.Request(context.url, initParams);
  26796. }
  26797. var FetchError = class extends Error {
  26798. constructor(message, code, details) {
  26799. super(message);
  26800. this.code = void 0;
  26801. this.details = void 0;
  26802. this.code = code;
  26803. this.details = details;
  26804. }
  26805. };
  26806. var AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/im;
  26807. var XhrLoader = class {
  26808. constructor(config) {
  26809. this.xhrSetup = void 0;
  26810. this.requestTimeout = void 0;
  26811. this.retryTimeout = void 0;
  26812. this.retryDelay = void 0;
  26813. this.config = null;
  26814. this.callbacks = null;
  26815. this.context = null;
  26816. this.loader = null;
  26817. this.stats = void 0;
  26818. this.xhrSetup = config ? config.xhrSetup || null : null;
  26819. this.stats = new LoadStats();
  26820. this.retryDelay = 0;
  26821. }
  26822. destroy() {
  26823. this.callbacks = null;
  26824. this.abortInternal();
  26825. this.loader = null;
  26826. this.config = null;
  26827. this.context = null;
  26828. this.xhrSetup = null;
  26829. }
  26830. abortInternal() {
  26831. const loader = this.loader;
  26832. self.clearTimeout(this.requestTimeout);
  26833. self.clearTimeout(this.retryTimeout);
  26834. if (loader) {
  26835. loader.onreadystatechange = null;
  26836. loader.onprogress = null;
  26837. if (loader.readyState !== 4) {
  26838. this.stats.aborted = true;
  26839. loader.abort();
  26840. }
  26841. }
  26842. }
  26843. abort() {
  26844. var _this$callbacks;
  26845. this.abortInternal();
  26846. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  26847. this.callbacks.onAbort(this.stats, this.context, this.loader);
  26848. }
  26849. }
  26850. load(context, config, callbacks) {
  26851. if (this.stats.loading.start) {
  26852. throw new Error("Loader can only be used once.");
  26853. }
  26854. this.stats.loading.start = self.performance.now();
  26855. this.context = context;
  26856. this.config = config;
  26857. this.callbacks = callbacks;
  26858. this.loadInternal();
  26859. }
  26860. loadInternal() {
  26861. const {
  26862. config,
  26863. context
  26864. } = this;
  26865. if (!config || !context) {
  26866. return;
  26867. }
  26868. const xhr = this.loader = new self.XMLHttpRequest();
  26869. const stats = this.stats;
  26870. stats.loading.first = 0;
  26871. stats.loaded = 0;
  26872. stats.aborted = false;
  26873. const xhrSetup = this.xhrSetup;
  26874. if (xhrSetup) {
  26875. Promise.resolve().then(() => {
  26876. if (this.loader !== xhr || this.stats.aborted)
  26877. return;
  26878. return xhrSetup(xhr, context.url);
  26879. }).catch((error) => {
  26880. if (this.loader !== xhr || this.stats.aborted)
  26881. return;
  26882. xhr.open("GET", context.url, true);
  26883. return xhrSetup(xhr, context.url);
  26884. }).then(() => {
  26885. if (this.loader !== xhr || this.stats.aborted)
  26886. return;
  26887. this.openAndSendXhr(xhr, context, config);
  26888. }).catch((error) => {
  26889. var _this$callbacks2;
  26890. (_this$callbacks2 = this.callbacks) == null ? void 0 : _this$callbacks2.onError({
  26891. code: xhr.status,
  26892. text: error.message
  26893. }, context, xhr, stats);
  26894. return;
  26895. });
  26896. } else {
  26897. this.openAndSendXhr(xhr, context, config);
  26898. }
  26899. }
  26900. openAndSendXhr(xhr, context, config) {
  26901. if (!xhr.readyState) {
  26902. xhr.open("GET", context.url, true);
  26903. }
  26904. const headers = context.headers;
  26905. const {
  26906. maxTimeToFirstByteMs,
  26907. maxLoadTimeMs
  26908. } = config.loadPolicy;
  26909. if (headers) {
  26910. for (const header in headers) {
  26911. xhr.setRequestHeader(header, headers[header]);
  26912. }
  26913. }
  26914. if (context.rangeEnd) {
  26915. xhr.setRequestHeader("Range", "bytes=" + context.rangeStart + "-" + (context.rangeEnd - 1));
  26916. }
  26917. xhr.onreadystatechange = this.readystatechange.bind(this);
  26918. xhr.onprogress = this.loadprogress.bind(this);
  26919. xhr.responseType = context.responseType;
  26920. self.clearTimeout(this.requestTimeout);
  26921. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  26922. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
  26923. xhr.send();
  26924. }
  26925. readystatechange() {
  26926. const {
  26927. context,
  26928. loader: xhr,
  26929. stats
  26930. } = this;
  26931. if (!context || !xhr) {
  26932. return;
  26933. }
  26934. const readyState = xhr.readyState;
  26935. const config = this.config;
  26936. if (stats.aborted) {
  26937. return;
  26938. }
  26939. if (readyState >= 2) {
  26940. if (stats.loading.first === 0) {
  26941. stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
  26942. if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {
  26943. self.clearTimeout(this.requestTimeout);
  26944. config.timeout = config.loadPolicy.maxLoadTimeMs;
  26945. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.loadPolicy.maxLoadTimeMs - (stats.loading.first - stats.loading.start));
  26946. }
  26947. }
  26948. if (readyState === 4) {
  26949. self.clearTimeout(this.requestTimeout);
  26950. xhr.onreadystatechange = null;
  26951. xhr.onprogress = null;
  26952. const status2 = xhr.status;
  26953. const useResponseText = xhr.responseType === "text" ? xhr.responseText : null;
  26954. if (status2 >= 200 && status2 < 300) {
  26955. const data = useResponseText != null ? useResponseText : xhr.response;
  26956. if (data != null) {
  26957. var _this$callbacks3, _this$callbacks4;
  26958. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  26959. const len = xhr.responseType === "arraybuffer" ? data.byteLength : data.length;
  26960. stats.loaded = stats.total = len;
  26961. stats.bwEstimate = stats.total * 8e3 / (stats.loading.end - stats.loading.first);
  26962. const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  26963. if (onProgress) {
  26964. onProgress(stats, context, data, xhr);
  26965. }
  26966. const _response = {
  26967. url: xhr.responseURL,
  26968. data,
  26969. code: status2
  26970. };
  26971. (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(_response, stats, context, xhr);
  26972. return;
  26973. }
  26974. }
  26975. const retryConfig = config.loadPolicy.errorRetry;
  26976. const retryCount = stats.retry;
  26977. const response = {
  26978. url: context.url,
  26979. data: void 0,
  26980. code: status2
  26981. };
  26982. if (shouldRetry(retryConfig, retryCount, false, response)) {
  26983. this.retry(retryConfig);
  26984. } else {
  26985. var _this$callbacks5;
  26986. logger.error(`${status2} while loading ${context.url}`);
  26987. (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({
  26988. code: status2,
  26989. text: xhr.statusText
  26990. }, context, xhr, stats);
  26991. }
  26992. }
  26993. }
  26994. }
  26995. loadtimeout() {
  26996. if (!this.config)
  26997. return;
  26998. const retryConfig = this.config.loadPolicy.timeoutRetry;
  26999. const retryCount = this.stats.retry;
  27000. if (shouldRetry(retryConfig, retryCount, true)) {
  27001. this.retry(retryConfig);
  27002. } else {
  27003. var _this$context;
  27004. logger.warn(`timeout while loading ${(_this$context = this.context) == null ? void 0 : _this$context.url}`);
  27005. const callbacks = this.callbacks;
  27006. if (callbacks) {
  27007. this.abortInternal();
  27008. callbacks.onTimeout(this.stats, this.context, this.loader);
  27009. }
  27010. }
  27011. }
  27012. retry(retryConfig) {
  27013. const {
  27014. context,
  27015. stats
  27016. } = this;
  27017. this.retryDelay = getRetryDelay(retryConfig, stats.retry);
  27018. stats.retry++;
  27019. logger.warn(`${status ? "HTTP Status " + status : "Timeout"} while loading ${context == null ? void 0 : context.url}, retrying ${stats.retry}/${retryConfig.maxNumRetry} in ${this.retryDelay}ms`);
  27020. this.abortInternal();
  27021. this.loader = null;
  27022. self.clearTimeout(this.retryTimeout);
  27023. this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  27024. }
  27025. loadprogress(event) {
  27026. const stats = this.stats;
  27027. stats.loaded = event.loaded;
  27028. if (event.lengthComputable) {
  27029. stats.total = event.total;
  27030. }
  27031. }
  27032. getCacheAge() {
  27033. let result = null;
  27034. if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
  27035. const ageHeader = this.loader.getResponseHeader("age");
  27036. result = ageHeader ? parseFloat(ageHeader) : null;
  27037. }
  27038. return result;
  27039. }
  27040. getResponseHeader(name) {
  27041. if (this.loader && new RegExp(`^${name}:\\s*[\\d.]+\\s*$`, "im").test(this.loader.getAllResponseHeaders())) {
  27042. return this.loader.getResponseHeader(name);
  27043. }
  27044. return null;
  27045. }
  27046. };
  27047. var defaultLoadPolicy = {
  27048. maxTimeToFirstByteMs: 8e3,
  27049. maxLoadTimeMs: 2e4,
  27050. timeoutRetry: null,
  27051. errorRetry: null
  27052. };
  27053. var hlsDefaultConfig = _objectSpread2(_objectSpread2({
  27054. autoStartLoad: true,
  27055. // used by stream-controller
  27056. startPosition: -1,
  27057. // used by stream-controller
  27058. defaultAudioCodec: void 0,
  27059. // used by stream-controller
  27060. debug: false,
  27061. // used by logger
  27062. capLevelOnFPSDrop: false,
  27063. // used by fps-controller
  27064. capLevelToPlayerSize: false,
  27065. // used by cap-level-controller
  27066. ignoreDevicePixelRatio: false,
  27067. // used by cap-level-controller
  27068. maxDevicePixelRatio: Number.POSITIVE_INFINITY,
  27069. // used by cap-level-controller
  27070. preferManagedMediaSource: true,
  27071. initialLiveManifestSize: 1,
  27072. // used by stream-controller
  27073. maxBufferLength: 30,
  27074. // used by stream-controller
  27075. backBufferLength: Infinity,
  27076. // used by buffer-controller
  27077. frontBufferFlushThreshold: Infinity,
  27078. startOnSegmentBoundary: false,
  27079. // used by stream-controller
  27080. maxBufferSize: 60 * 1e3 * 1e3,
  27081. // used by stream-controller
  27082. maxFragLookUpTolerance: 0.25,
  27083. // used by stream-controller
  27084. maxBufferHole: 0.1,
  27085. // used by stream-controller and gap-controller
  27086. detectStallWithCurrentTimeMs: 1250,
  27087. // used by gap-controller
  27088. highBufferWatchdogPeriod: 2,
  27089. // used by gap-controller
  27090. nudgeOffset: 0.1,
  27091. // used by gap-controller
  27092. nudgeMaxRetry: 3,
  27093. // used by gap-controller
  27094. nudgeOnVideoHole: true,
  27095. // used by gap-controller
  27096. liveSyncMode: "edge",
  27097. // used by stream-controller
  27098. liveSyncDurationCount: 3,
  27099. // used by latency-controller
  27100. liveSyncOnStallIncrease: 1,
  27101. // used by latency-controller
  27102. liveMaxLatencyDurationCount: Infinity,
  27103. // used by latency-controller
  27104. liveSyncDuration: void 0,
  27105. // used by latency-controller
  27106. liveMaxLatencyDuration: void 0,
  27107. // used by latency-controller
  27108. maxLiveSyncPlaybackRate: 1,
  27109. // used by latency-controller
  27110. liveDurationInfinity: false,
  27111. // used by buffer-controller
  27112. /**
  27113. * @deprecated use backBufferLength
  27114. */
  27115. liveBackBufferLength: null,
  27116. // used by buffer-controller
  27117. maxMaxBufferLength: 600,
  27118. // used by stream-controller
  27119. enableWorker: true,
  27120. // used by transmuxer
  27121. workerPath: null,
  27122. // used by transmuxer
  27123. enableSoftwareAES: true,
  27124. // used by decrypter
  27125. startLevel: void 0,
  27126. // used by level-controller
  27127. startFragPrefetch: false,
  27128. // used by stream-controller
  27129. fpsDroppedMonitoringPeriod: 5e3,
  27130. // used by fps-controller
  27131. fpsDroppedMonitoringThreshold: 0.2,
  27132. // used by fps-controller
  27133. appendErrorMaxRetry: 3,
  27134. // used by buffer-controller
  27135. ignorePlaylistParsingErrors: false,
  27136. loader: XhrLoader,
  27137. // loader: FetchLoader,
  27138. fLoader: void 0,
  27139. // used by fragment-loader
  27140. pLoader: void 0,
  27141. // used by playlist-loader
  27142. xhrSetup: void 0,
  27143. // used by xhr-loader
  27144. licenseXhrSetup: void 0,
  27145. // used by eme-controller
  27146. licenseResponseCallback: void 0,
  27147. // used by eme-controller
  27148. abrController: AbrController,
  27149. bufferController: BufferController,
  27150. capLevelController: CapLevelController,
  27151. errorController: ErrorController,
  27152. fpsController: FPSController,
  27153. stretchShortVideoTrack: false,
  27154. // used by mp4-remuxer
  27155. maxAudioFramesDrift: 1,
  27156. // used by mp4-remuxer
  27157. forceKeyFrameOnDiscontinuity: true,
  27158. // used by ts-demuxer
  27159. abrEwmaFastLive: 3,
  27160. // used by abr-controller
  27161. abrEwmaSlowLive: 9,
  27162. // used by abr-controller
  27163. abrEwmaFastVoD: 3,
  27164. // used by abr-controller
  27165. abrEwmaSlowVoD: 9,
  27166. // used by abr-controller
  27167. abrEwmaDefaultEstimate: 5e5,
  27168. // 500 kbps // used by abr-controller
  27169. abrEwmaDefaultEstimateMax: 5e6,
  27170. // 5 mbps
  27171. abrBandWidthFactor: 0.95,
  27172. // used by abr-controller
  27173. abrBandWidthUpFactor: 0.7,
  27174. // used by abr-controller
  27175. abrMaxWithRealBitrate: false,
  27176. // used by abr-controller
  27177. maxStarvationDelay: 4,
  27178. // used by abr-controller
  27179. maxLoadingDelay: 4,
  27180. // used by abr-controller
  27181. minAutoBitrate: 0,
  27182. // used by hls
  27183. emeEnabled: false,
  27184. // used by eme-controller
  27185. widevineLicenseUrl: void 0,
  27186. // used by eme-controller
  27187. drmSystems: {},
  27188. // used by eme-controller
  27189. drmSystemOptions: {},
  27190. // used by eme-controller
  27191. requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess,
  27192. // used by eme-controller
  27193. requireKeySystemAccessOnStart: false,
  27194. // used by eme-controller
  27195. testBandwidth: true,
  27196. progressive: false,
  27197. lowLatencyMode: true,
  27198. cmcd: void 0,
  27199. enableDateRangeMetadataCues: true,
  27200. enableEmsgMetadataCues: true,
  27201. enableEmsgKLVMetadata: false,
  27202. enableID3MetadataCues: true,
  27203. enableInterstitialPlayback: true,
  27204. interstitialAppendInPlace: true,
  27205. interstitialLiveLookAhead: 10,
  27206. useMediaCapabilities: true,
  27207. preserveManualLevelOnError: false,
  27208. certLoadPolicy: {
  27209. default: defaultLoadPolicy
  27210. },
  27211. keyLoadPolicy: {
  27212. default: {
  27213. maxTimeToFirstByteMs: 8e3,
  27214. maxLoadTimeMs: 2e4,
  27215. timeoutRetry: {
  27216. maxNumRetry: 1,
  27217. retryDelayMs: 1e3,
  27218. maxRetryDelayMs: 2e4,
  27219. backoff: "linear"
  27220. },
  27221. errorRetry: {
  27222. maxNumRetry: 8,
  27223. retryDelayMs: 1e3,
  27224. maxRetryDelayMs: 2e4,
  27225. backoff: "linear"
  27226. }
  27227. }
  27228. },
  27229. manifestLoadPolicy: {
  27230. default: {
  27231. maxTimeToFirstByteMs: Infinity,
  27232. maxLoadTimeMs: 2e4,
  27233. timeoutRetry: {
  27234. maxNumRetry: 2,
  27235. retryDelayMs: 0,
  27236. maxRetryDelayMs: 0
  27237. },
  27238. errorRetry: {
  27239. maxNumRetry: 1,
  27240. retryDelayMs: 1e3,
  27241. maxRetryDelayMs: 8e3
  27242. }
  27243. }
  27244. },
  27245. playlistLoadPolicy: {
  27246. default: {
  27247. maxTimeToFirstByteMs: 1e4,
  27248. maxLoadTimeMs: 2e4,
  27249. timeoutRetry: {
  27250. maxNumRetry: 2,
  27251. retryDelayMs: 0,
  27252. maxRetryDelayMs: 0
  27253. },
  27254. errorRetry: {
  27255. maxNumRetry: 2,
  27256. retryDelayMs: 1e3,
  27257. maxRetryDelayMs: 8e3
  27258. }
  27259. }
  27260. },
  27261. fragLoadPolicy: {
  27262. default: {
  27263. maxTimeToFirstByteMs: 1e4,
  27264. maxLoadTimeMs: 12e4,
  27265. timeoutRetry: {
  27266. maxNumRetry: 4,
  27267. retryDelayMs: 0,
  27268. maxRetryDelayMs: 0
  27269. },
  27270. errorRetry: {
  27271. maxNumRetry: 6,
  27272. retryDelayMs: 1e3,
  27273. maxRetryDelayMs: 8e3
  27274. }
  27275. }
  27276. },
  27277. steeringManifestLoadPolicy: {
  27278. default: {
  27279. maxTimeToFirstByteMs: 1e4,
  27280. maxLoadTimeMs: 2e4,
  27281. timeoutRetry: {
  27282. maxNumRetry: 2,
  27283. retryDelayMs: 0,
  27284. maxRetryDelayMs: 0
  27285. },
  27286. errorRetry: {
  27287. maxNumRetry: 1,
  27288. retryDelayMs: 1e3,
  27289. maxRetryDelayMs: 8e3
  27290. }
  27291. }
  27292. },
  27293. interstitialAssetListLoadPolicy: {
  27294. default: {
  27295. maxTimeToFirstByteMs: 1e4,
  27296. maxLoadTimeMs: 3e4,
  27297. timeoutRetry: {
  27298. maxNumRetry: 0,
  27299. retryDelayMs: 0,
  27300. maxRetryDelayMs: 0
  27301. },
  27302. errorRetry: {
  27303. maxNumRetry: 0,
  27304. retryDelayMs: 1e3,
  27305. maxRetryDelayMs: 8e3
  27306. }
  27307. }
  27308. },
  27309. // These default settings are deprecated in favor of the above policies
  27310. // and are maintained for backwards compatibility
  27311. manifestLoadingTimeOut: 1e4,
  27312. manifestLoadingMaxRetry: 1,
  27313. manifestLoadingRetryDelay: 1e3,
  27314. manifestLoadingMaxRetryTimeout: 64e3,
  27315. levelLoadingTimeOut: 1e4,
  27316. levelLoadingMaxRetry: 4,
  27317. levelLoadingRetryDelay: 1e3,
  27318. levelLoadingMaxRetryTimeout: 64e3,
  27319. fragLoadingTimeOut: 2e4,
  27320. fragLoadingMaxRetry: 6,
  27321. fragLoadingRetryDelay: 1e3,
  27322. fragLoadingMaxRetryTimeout: 64e3
  27323. }, timelineConfig()), {}, {
  27324. subtitleStreamController: SubtitleStreamController,
  27325. subtitleTrackController: SubtitleTrackController,
  27326. timelineController: TimelineController,
  27327. audioStreamController: AudioStreamController,
  27328. audioTrackController: AudioTrackController,
  27329. emeController: EMEController,
  27330. cmcdController: CMCDController,
  27331. contentSteeringController: ContentSteeringController,
  27332. interstitialsController: InterstitialsController
  27333. });
  27334. function timelineConfig() {
  27335. return {
  27336. cueHandler: Cues,
  27337. // used by timeline-controller
  27338. enableWebVTT: true,
  27339. // used by timeline-controller
  27340. enableIMSC1: true,
  27341. // used by timeline-controller
  27342. enableCEA708Captions: true,
  27343. // used by timeline-controller
  27344. captionsTextTrack1Label: "English",
  27345. // used by timeline-controller
  27346. captionsTextTrack1LanguageCode: "en",
  27347. // used by timeline-controller
  27348. captionsTextTrack2Label: "Spanish",
  27349. // used by timeline-controller
  27350. captionsTextTrack2LanguageCode: "es",
  27351. // used by timeline-controller
  27352. captionsTextTrack3Label: "Unknown CC",
  27353. // used by timeline-controller
  27354. captionsTextTrack3LanguageCode: "",
  27355. // used by timeline-controller
  27356. captionsTextTrack4Label: "Unknown CC",
  27357. // used by timeline-controller
  27358. captionsTextTrack4LanguageCode: "",
  27359. // used by timeline-controller
  27360. renderTextTracksNatively: true
  27361. };
  27362. }
  27363. function mergeConfig(defaultConfig, userConfig, logger2) {
  27364. if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
  27365. throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  27366. }
  27367. if (userConfig.liveMaxLatencyDurationCount !== void 0 && (userConfig.liveSyncDurationCount === void 0 || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
  27368. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  27369. }
  27370. if (userConfig.liveMaxLatencyDuration !== void 0 && (userConfig.liveSyncDuration === void 0 || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
  27371. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  27372. }
  27373. const defaultsCopy = deepCpy(defaultConfig);
  27374. const deprecatedSettingTypes = ["manifest", "level", "frag"];
  27375. const deprecatedSettings = ["TimeOut", "MaxRetry", "RetryDelay", "MaxRetryTimeout"];
  27376. deprecatedSettingTypes.forEach((type) => {
  27377. const policyName = `${type === "level" ? "playlist" : type}LoadPolicy`;
  27378. const policyNotSet = userConfig[policyName] === void 0;
  27379. const report = [];
  27380. deprecatedSettings.forEach((setting) => {
  27381. const deprecatedSetting = `${type}Loading${setting}`;
  27382. const value = userConfig[deprecatedSetting];
  27383. if (value !== void 0 && policyNotSet) {
  27384. report.push(deprecatedSetting);
  27385. const settings = defaultsCopy[policyName].default;
  27386. userConfig[policyName] = {
  27387. default: settings
  27388. };
  27389. switch (setting) {
  27390. case "TimeOut":
  27391. settings.maxLoadTimeMs = value;
  27392. settings.maxTimeToFirstByteMs = value;
  27393. break;
  27394. case "MaxRetry":
  27395. settings.errorRetry.maxNumRetry = value;
  27396. settings.timeoutRetry.maxNumRetry = value;
  27397. break;
  27398. case "RetryDelay":
  27399. settings.errorRetry.retryDelayMs = value;
  27400. settings.timeoutRetry.retryDelayMs = value;
  27401. break;
  27402. case "MaxRetryTimeout":
  27403. settings.errorRetry.maxRetryDelayMs = value;
  27404. settings.timeoutRetry.maxRetryDelayMs = value;
  27405. break;
  27406. }
  27407. }
  27408. });
  27409. if (report.length) {
  27410. logger2.warn(`hls.js config: "${report.join('", "')}" setting(s) are deprecated, use "${policyName}": ${stringify(userConfig[policyName])}`);
  27411. }
  27412. });
  27413. return _objectSpread2(_objectSpread2({}, defaultsCopy), userConfig);
  27414. }
  27415. function deepCpy(obj) {
  27416. if (obj && typeof obj === "object") {
  27417. if (Array.isArray(obj)) {
  27418. return obj.map(deepCpy);
  27419. }
  27420. return Object.keys(obj).reduce((result, key) => {
  27421. result[key] = deepCpy(obj[key]);
  27422. return result;
  27423. }, {});
  27424. }
  27425. return obj;
  27426. }
  27427. function enableStreamingMode(config, logger2) {
  27428. const currentLoader = config.loader;
  27429. if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {
  27430. logger2.log("[config]: Custom loader detected, cannot enable progressive streaming");
  27431. config.progressive = false;
  27432. } else {
  27433. const canStreamProgressively = fetchSupported();
  27434. if (canStreamProgressively) {
  27435. config.loader = FetchLoader;
  27436. config.progressive = true;
  27437. config.enableSoftwareAES = true;
  27438. logger2.log("[config]: Progressive streaming enabled, using FetchLoader");
  27439. }
  27440. }
  27441. }
  27442. var MAX_START_GAP_JUMP = 2;
  27443. var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
  27444. var SKIP_BUFFER_RANGE_START = 0.05;
  27445. var TICK_INTERVAL$1 = 100;
  27446. var GapController = class extends TaskLoop {
  27447. constructor(hls, fragmentTracker) {
  27448. super("gap-controller", hls.logger);
  27449. this.hls = null;
  27450. this.fragmentTracker = null;
  27451. this.media = null;
  27452. this.mediaSource = void 0;
  27453. this.nudgeRetry = 0;
  27454. this.stallReported = false;
  27455. this.stalled = null;
  27456. this.moved = false;
  27457. this.seeking = false;
  27458. this.buffered = {};
  27459. this.lastCurrentTime = 0;
  27460. this.ended = 0;
  27461. this.waiting = 0;
  27462. this.onMediaPlaying = () => {
  27463. this.ended = 0;
  27464. this.waiting = 0;
  27465. };
  27466. this.onMediaWaiting = () => {
  27467. var _this$media;
  27468. if ((_this$media = this.media) != null && _this$media.seeking) {
  27469. return;
  27470. }
  27471. this.waiting = self.performance.now();
  27472. this.tick();
  27473. };
  27474. this.onMediaEnded = () => {
  27475. if (this.hls) {
  27476. var _this$media2;
  27477. this.ended = ((_this$media2 = this.media) == null ? void 0 : _this$media2.currentTime) || 1;
  27478. this.hls.trigger(Events.MEDIA_ENDED, {
  27479. stalled: false
  27480. });
  27481. }
  27482. };
  27483. this.hls = hls;
  27484. this.fragmentTracker = fragmentTracker;
  27485. this.registerListeners();
  27486. }
  27487. registerListeners() {
  27488. const {
  27489. hls
  27490. } = this;
  27491. if (hls) {
  27492. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  27493. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  27494. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  27495. }
  27496. }
  27497. unregisterListeners() {
  27498. const {
  27499. hls
  27500. } = this;
  27501. if (hls) {
  27502. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  27503. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  27504. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  27505. }
  27506. }
  27507. destroy() {
  27508. super.destroy();
  27509. this.unregisterListeners();
  27510. this.media = this.hls = this.fragmentTracker = null;
  27511. this.mediaSource = void 0;
  27512. }
  27513. onMediaAttached(event, data) {
  27514. this.setInterval(TICK_INTERVAL$1);
  27515. this.mediaSource = data.mediaSource;
  27516. const media = this.media = data.media;
  27517. addEventListener(media, "playing", this.onMediaPlaying);
  27518. addEventListener(media, "waiting", this.onMediaWaiting);
  27519. addEventListener(media, "ended", this.onMediaEnded);
  27520. }
  27521. onMediaDetaching(event, data) {
  27522. this.clearInterval();
  27523. const {
  27524. media
  27525. } = this;
  27526. if (media) {
  27527. removeEventListener(media, "playing", this.onMediaPlaying);
  27528. removeEventListener(media, "waiting", this.onMediaWaiting);
  27529. removeEventListener(media, "ended", this.onMediaEnded);
  27530. this.media = null;
  27531. }
  27532. this.mediaSource = void 0;
  27533. }
  27534. onBufferAppended(event, data) {
  27535. this.buffered = data.timeRanges;
  27536. }
  27537. get hasBuffered() {
  27538. return Object.keys(this.buffered).length > 0;
  27539. }
  27540. tick() {
  27541. var _this$media3;
  27542. if (!((_this$media3 = this.media) != null && _this$media3.readyState) || !this.hasBuffered) {
  27543. return;
  27544. }
  27545. const currentTime = this.media.currentTime;
  27546. this.poll(currentTime, this.lastCurrentTime);
  27547. this.lastCurrentTime = currentTime;
  27548. }
  27549. /**
  27550. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  27551. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  27552. *
  27553. * @param lastCurrentTime - Previously read playhead position
  27554. */
  27555. poll(currentTime, lastCurrentTime) {
  27556. var _this$hls, _this$hls2;
  27557. const config = (_this$hls = this.hls) == null ? void 0 : _this$hls.config;
  27558. if (!config) {
  27559. return;
  27560. }
  27561. const media = this.media;
  27562. if (!media) {
  27563. return;
  27564. }
  27565. const {
  27566. seeking
  27567. } = media;
  27568. const seeked = this.seeking && !seeking;
  27569. const beginSeek = !this.seeking && seeking;
  27570. const pausedEndedOrHalted = media.paused && !seeking || media.ended || media.playbackRate === 0;
  27571. this.seeking = seeking;
  27572. if (currentTime !== lastCurrentTime) {
  27573. if (lastCurrentTime) {
  27574. this.ended = 0;
  27575. }
  27576. this.moved = true;
  27577. if (!seeking) {
  27578. this.nudgeRetry = 0;
  27579. if (config.nudgeOnVideoHole && !pausedEndedOrHalted && currentTime > lastCurrentTime) {
  27580. this.nudgeOnVideoHole(currentTime, lastCurrentTime);
  27581. }
  27582. }
  27583. if (this.waiting === 0) {
  27584. this.stallResolved(currentTime);
  27585. }
  27586. return;
  27587. }
  27588. if (beginSeek || seeked) {
  27589. if (seeked) {
  27590. this.stallResolved(currentTime);
  27591. }
  27592. return;
  27593. }
  27594. if (pausedEndedOrHalted) {
  27595. this.nudgeRetry = 0;
  27596. this.stallResolved(currentTime);
  27597. if (!this.ended && media.ended && this.hls) {
  27598. this.ended = currentTime || 1;
  27599. this.hls.trigger(Events.MEDIA_ENDED, {
  27600. stalled: false
  27601. });
  27602. }
  27603. return;
  27604. }
  27605. if (!BufferHelper.getBuffered(media).length) {
  27606. this.nudgeRetry = 0;
  27607. return;
  27608. }
  27609. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  27610. const nextStart = bufferInfo.nextStart || 0;
  27611. const fragmentTracker = this.fragmentTracker;
  27612. if (seeking && fragmentTracker && this.hls) {
  27613. const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, currentTime);
  27614. const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;
  27615. const noBufferHole = !nextStart || inFlightDependency || nextStart - currentTime > MAX_START_GAP_JUMP && !fragmentTracker.getPartialFragment(currentTime);
  27616. if (hasEnoughBuffer || noBufferHole) {
  27617. return;
  27618. }
  27619. this.moved = false;
  27620. }
  27621. const levelDetails = (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.latestLevelDetails;
  27622. if (!this.moved && this.stalled !== null && fragmentTracker) {
  27623. const isBuffered = bufferInfo.len > 0;
  27624. if (!isBuffered && !nextStart) {
  27625. return;
  27626. }
  27627. const startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
  27628. const isLive = !!(levelDetails != null && levelDetails.live);
  27629. const maxStartGapJump = isLive ? levelDetails.targetduration * 2 : MAX_START_GAP_JUMP;
  27630. const partialOrGap = fragmentTracker.getPartialFragment(currentTime);
  27631. if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {
  27632. if (!media.paused) {
  27633. this._trySkipBufferHole(partialOrGap);
  27634. }
  27635. return;
  27636. }
  27637. }
  27638. const detectStallWithCurrentTimeMs = config.detectStallWithCurrentTimeMs;
  27639. const tnow = self.performance.now();
  27640. const tWaiting = this.waiting;
  27641. let stalled = this.stalled;
  27642. if (stalled === null) {
  27643. if (tWaiting > 0 && tnow - tWaiting < detectStallWithCurrentTimeMs) {
  27644. stalled = this.stalled = tWaiting;
  27645. } else {
  27646. this.stalled = tnow;
  27647. return;
  27648. }
  27649. }
  27650. const stalledDuration = tnow - stalled;
  27651. if (!seeking && (stalledDuration >= detectStallWithCurrentTimeMs || tWaiting) && this.hls) {
  27652. var _this$mediaSource;
  27653. if (((_this$mediaSource = this.mediaSource) == null ? void 0 : _this$mediaSource.readyState) === "ended" && !(levelDetails != null && levelDetails.live) && Math.abs(currentTime - ((levelDetails == null ? void 0 : levelDetails.edge) || 0)) < 1) {
  27654. if (this.ended) {
  27655. return;
  27656. }
  27657. this.ended = currentTime || 1;
  27658. this.hls.trigger(Events.MEDIA_ENDED, {
  27659. stalled: true
  27660. });
  27661. return;
  27662. }
  27663. this._reportStall(bufferInfo);
  27664. if (!this.media || !this.hls) {
  27665. return;
  27666. }
  27667. }
  27668. const bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  27669. this._tryFixBufferStall(bufferedWithHoles, stalledDuration, currentTime);
  27670. }
  27671. stallResolved(currentTime) {
  27672. const stalled = this.stalled;
  27673. if (stalled && this.hls) {
  27674. this.stalled = null;
  27675. if (this.stallReported) {
  27676. const stalledDuration = self.performance.now() - stalled;
  27677. this.log(`playback not stuck anymore @${currentTime}, after ${Math.round(stalledDuration)}ms`);
  27678. this.stallReported = false;
  27679. this.waiting = 0;
  27680. this.hls.trigger(Events.STALL_RESOLVED, {});
  27681. }
  27682. }
  27683. }
  27684. nudgeOnVideoHole(currentTime, lastCurrentTime) {
  27685. var _this$buffered$audio;
  27686. const videoSourceBuffered = this.buffered.video;
  27687. if (this.hls && this.media && this.fragmentTracker && (_this$buffered$audio = this.buffered.audio) != null && _this$buffered$audio.length && videoSourceBuffered && videoSourceBuffered.length > 1 && currentTime > videoSourceBuffered.end(0)) {
  27688. const audioBufferInfo = BufferHelper.bufferedInfo(BufferHelper.timeRangesToArray(this.buffered.audio), currentTime, 0);
  27689. if (audioBufferInfo.len > 1 && lastCurrentTime >= audioBufferInfo.start) {
  27690. const videoTimes = BufferHelper.timeRangesToArray(videoSourceBuffered);
  27691. const lastBufferedIndex = BufferHelper.bufferedInfo(videoTimes, lastCurrentTime, 0).bufferedIndex;
  27692. if (lastBufferedIndex > -1 && lastBufferedIndex < videoTimes.length - 1) {
  27693. const bufferedIndex = BufferHelper.bufferedInfo(videoTimes, currentTime, 0).bufferedIndex;
  27694. const holeStart = videoTimes[lastBufferedIndex].end;
  27695. const holeEnd = videoTimes[lastBufferedIndex + 1].start;
  27696. if ((bufferedIndex === -1 || bufferedIndex > lastBufferedIndex) && holeEnd - holeStart < 1 && // `maxBufferHole` may be too small and setting it to 0 should not disable this feature
  27697. currentTime - holeStart < 2) {
  27698. const error = new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${currentTime} hole: ${holeStart} -> ${holeEnd} buffered index: ${bufferedIndex}`);
  27699. this.warn(error.message);
  27700. this.media.currentTime += 1e-6;
  27701. const frag = this.fragmentTracker.getPartialFragment(currentTime) || void 0;
  27702. const bufferInfo = BufferHelper.bufferInfo(this.media, currentTime, 0);
  27703. this.hls.trigger(Events.ERROR, {
  27704. type: ErrorTypes.MEDIA_ERROR,
  27705. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  27706. fatal: false,
  27707. error,
  27708. reason: error.message,
  27709. frag,
  27710. buffer: bufferInfo.len,
  27711. bufferInfo
  27712. });
  27713. }
  27714. }
  27715. }
  27716. }
  27717. }
  27718. /**
  27719. * Detects and attempts to fix known buffer stalling issues.
  27720. * @param bufferInfo - The properties of the current buffer.
  27721. * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
  27722. * @private
  27723. */
  27724. _tryFixBufferStall(bufferInfo, stalledDurationMs, currentTime) {
  27725. var _this$hls3, _this$hls4;
  27726. const {
  27727. fragmentTracker,
  27728. media
  27729. } = this;
  27730. const config = (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.config;
  27731. if (!media || !fragmentTracker || !config) {
  27732. return;
  27733. }
  27734. const levelDetails = (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.latestLevelDetails;
  27735. const partial = fragmentTracker.getPartialFragment(currentTime);
  27736. if (partial || levelDetails != null && levelDetails.live && currentTime < levelDetails.fragmentStart) {
  27737. const targetTime = this._trySkipBufferHole(partial);
  27738. if (targetTime || !this.media) {
  27739. return;
  27740. }
  27741. }
  27742. const bufferedRanges = bufferInfo.buffered;
  27743. const adjacentTraversal = this.adjacentTraversal(bufferInfo, currentTime);
  27744. if ((bufferedRanges && bufferedRanges.length > 1 && bufferInfo.len > config.maxBufferHole || bufferInfo.nextStart && (bufferInfo.nextStart - currentTime < config.maxBufferHole || adjacentTraversal)) && (stalledDurationMs > config.highBufferWatchdogPeriod * 1e3 || this.waiting)) {
  27745. this.warn("Trying to nudge playhead over buffer-hole");
  27746. this._tryNudgeBuffer(bufferInfo);
  27747. }
  27748. }
  27749. adjacentTraversal(bufferInfo, currentTime) {
  27750. const fragmentTracker = this.fragmentTracker;
  27751. const nextStart = bufferInfo.nextStart;
  27752. if (fragmentTracker && nextStart) {
  27753. const current = fragmentTracker.getFragAtPos(currentTime, PlaylistLevelType.MAIN);
  27754. const next = fragmentTracker.getFragAtPos(nextStart, PlaylistLevelType.MAIN);
  27755. if (current && next) {
  27756. return next.sn - current.sn < 2;
  27757. }
  27758. }
  27759. return false;
  27760. }
  27761. /**
  27762. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  27763. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  27764. * @private
  27765. */
  27766. _reportStall(bufferInfo) {
  27767. const {
  27768. hls,
  27769. media,
  27770. stallReported,
  27771. stalled
  27772. } = this;
  27773. if (!stallReported && stalled !== null && media && hls) {
  27774. this.stallReported = true;
  27775. const error = new Error(`Playback stalling at @${media.currentTime} due to low buffer (${stringify(bufferInfo)})`);
  27776. this.warn(error.message);
  27777. hls.trigger(Events.ERROR, {
  27778. type: ErrorTypes.MEDIA_ERROR,
  27779. details: ErrorDetails.BUFFER_STALLED_ERROR,
  27780. fatal: false,
  27781. error,
  27782. buffer: bufferInfo.len,
  27783. bufferInfo,
  27784. stalled: {
  27785. start: stalled
  27786. }
  27787. });
  27788. }
  27789. }
  27790. /**
  27791. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  27792. * @param partial - The partial fragment found at the current time (where playback is stalling).
  27793. * @private
  27794. */
  27795. _trySkipBufferHole(partial) {
  27796. var _this$hls5;
  27797. const {
  27798. fragmentTracker,
  27799. media
  27800. } = this;
  27801. const config = (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.config;
  27802. if (!media || !fragmentTracker || !config) {
  27803. return 0;
  27804. }
  27805. const currentTime = media.currentTime;
  27806. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  27807. const startTime = currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;
  27808. if (startTime && this.hls) {
  27809. const bufferStarved = bufferInfo.len <= config.maxBufferHole;
  27810. const waiting = bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;
  27811. const gapLength = startTime - currentTime;
  27812. if (gapLength > 0 && (bufferStarved || waiting)) {
  27813. if (gapLength > config.maxBufferHole) {
  27814. let startGap = false;
  27815. if (currentTime === 0) {
  27816. const startFrag = fragmentTracker.getAppendedFrag(0, PlaylistLevelType.MAIN);
  27817. if (startFrag && startTime < startFrag.end) {
  27818. startGap = true;
  27819. }
  27820. }
  27821. if (!startGap) {
  27822. const startProvisioned = partial || fragmentTracker.getAppendedFrag(currentTime, PlaylistLevelType.MAIN);
  27823. if (startProvisioned) {
  27824. var _this$hls$loadLevelOb;
  27825. if (!((_this$hls$loadLevelOb = this.hls.loadLevelObj) != null && _this$hls$loadLevelOb.details)) {
  27826. return 0;
  27827. }
  27828. const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, startTime);
  27829. if (inFlightDependency) {
  27830. return 0;
  27831. }
  27832. let moreToLoad = false;
  27833. let pos = startProvisioned.end;
  27834. while (pos < startTime) {
  27835. const provisioned = fragmentTracker.getAppendedFrag(pos, PlaylistLevelType.MAIN) || fragmentTracker.getPartialFragment(pos);
  27836. if (provisioned) {
  27837. pos += provisioned.duration;
  27838. } else {
  27839. moreToLoad = true;
  27840. break;
  27841. }
  27842. }
  27843. if (moreToLoad) {
  27844. return 0;
  27845. }
  27846. }
  27847. }
  27848. }
  27849. const targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
  27850. this.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`);
  27851. this.moved = true;
  27852. media.currentTime = targetTime;
  27853. if (!(partial != null && partial.gap)) {
  27854. const error = new Error(`fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`);
  27855. this.hls.trigger(Events.ERROR, {
  27856. type: ErrorTypes.MEDIA_ERROR,
  27857. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  27858. fatal: false,
  27859. error,
  27860. reason: error.message,
  27861. frag: partial || void 0,
  27862. buffer: bufferInfo.len,
  27863. bufferInfo
  27864. });
  27865. }
  27866. return targetTime;
  27867. }
  27868. }
  27869. return 0;
  27870. }
  27871. /**
  27872. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  27873. * @private
  27874. */
  27875. _tryNudgeBuffer(bufferInfo) {
  27876. const {
  27877. hls,
  27878. media,
  27879. nudgeRetry
  27880. } = this;
  27881. const config = hls == null ? void 0 : hls.config;
  27882. if (!media || !config) {
  27883. return 0;
  27884. }
  27885. const currentTime = media.currentTime;
  27886. this.nudgeRetry++;
  27887. if (nudgeRetry < config.nudgeMaxRetry) {
  27888. const targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;
  27889. const error = new Error(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`);
  27890. this.warn(error.message);
  27891. media.currentTime = targetTime;
  27892. hls.trigger(Events.ERROR, {
  27893. type: ErrorTypes.MEDIA_ERROR,
  27894. details: ErrorDetails.BUFFER_NUDGE_ON_STALL,
  27895. error,
  27896. fatal: false,
  27897. buffer: bufferInfo.len,
  27898. bufferInfo
  27899. });
  27900. } else {
  27901. const error = new Error(`Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`);
  27902. this.error(error.message);
  27903. hls.trigger(Events.ERROR, {
  27904. type: ErrorTypes.MEDIA_ERROR,
  27905. details: ErrorDetails.BUFFER_STALLED_ERROR,
  27906. error,
  27907. fatal: true,
  27908. buffer: bufferInfo.len,
  27909. bufferInfo
  27910. });
  27911. }
  27912. }
  27913. };
  27914. function getInFlightDependency(inFlightFragments, currentTime) {
  27915. const main = inFlight(inFlightFragments.main);
  27916. if (main && main.start <= currentTime) {
  27917. return main;
  27918. }
  27919. const audio = inFlight(inFlightFragments.audio);
  27920. if (audio && audio.start <= currentTime) {
  27921. return audio;
  27922. }
  27923. return null;
  27924. }
  27925. function inFlight(inFlightData) {
  27926. if (!inFlightData) {
  27927. return null;
  27928. }
  27929. switch (inFlightData.state) {
  27930. case State.IDLE:
  27931. case State.STOPPED:
  27932. case State.ENDED:
  27933. case State.ERROR:
  27934. return null;
  27935. }
  27936. return inFlightData.frag;
  27937. }
  27938. var MIN_CUE_DURATION = 0.25;
  27939. function getCueClass() {
  27940. if (typeof self === "undefined")
  27941. return void 0;
  27942. return self.VTTCue || self.TextTrackCue;
  27943. }
  27944. function createCueWithDataFields(Cue, startTime, endTime, data, type) {
  27945. let cue = new Cue(startTime, endTime, "");
  27946. try {
  27947. cue.value = data;
  27948. if (type) {
  27949. cue.type = type;
  27950. }
  27951. } catch (e) {
  27952. cue = new Cue(startTime, endTime, stringify(type ? _objectSpread2({
  27953. type
  27954. }, data) : data));
  27955. }
  27956. return cue;
  27957. }
  27958. var MAX_CUE_ENDTIME = (() => {
  27959. const Cue = getCueClass();
  27960. try {
  27961. Cue && new Cue(0, Number.POSITIVE_INFINITY, "");
  27962. } catch (e) {
  27963. return Number.MAX_VALUE;
  27964. }
  27965. return Number.POSITIVE_INFINITY;
  27966. })();
  27967. var ID3TrackController = class {
  27968. constructor(hls) {
  27969. this.hls = void 0;
  27970. this.id3Track = null;
  27971. this.media = null;
  27972. this.dateRangeCuesAppended = {};
  27973. this.removeCues = true;
  27974. this.onEventCueEnter = () => {
  27975. if (!this.hls) {
  27976. return;
  27977. }
  27978. this.hls.trigger(Events.EVENT_CUE_ENTER, {});
  27979. };
  27980. this.hls = hls;
  27981. this._registerListeners();
  27982. }
  27983. destroy() {
  27984. this._unregisterListeners();
  27985. this.id3Track = null;
  27986. this.media = null;
  27987. this.dateRangeCuesAppended = {};
  27988. this.hls = this.onEventCueEnter = null;
  27989. }
  27990. _registerListeners() {
  27991. const {
  27992. hls
  27993. } = this;
  27994. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  27995. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  27996. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  27997. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  27998. hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  27999. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  28000. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  28001. hls.on(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  28002. }
  28003. _unregisterListeners() {
  28004. const {
  28005. hls
  28006. } = this;
  28007. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  28008. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  28009. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  28010. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  28011. hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  28012. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  28013. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  28014. hls.off(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  28015. }
  28016. // Add ID3 metatadata text track.
  28017. onMediaAttaching(event, data) {
  28018. var _data$overrides;
  28019. this.media = data.media;
  28020. if (((_data$overrides = data.overrides) == null ? void 0 : _data$overrides.cueRemoval) === false) {
  28021. this.removeCues = false;
  28022. }
  28023. }
  28024. onMediaAttached() {
  28025. const details = this.hls.latestLevelDetails;
  28026. if (details) {
  28027. this.updateDateRangeCues(details);
  28028. }
  28029. }
  28030. onMediaDetaching(event, data) {
  28031. this.media = null;
  28032. const transferringMedia = !!data.transferMedia;
  28033. if (transferringMedia) {
  28034. return;
  28035. }
  28036. if (this.id3Track) {
  28037. if (this.removeCues) {
  28038. clearCurrentCues(this.id3Track, this.onEventCueEnter);
  28039. }
  28040. this.id3Track = null;
  28041. }
  28042. this.dateRangeCuesAppended = {};
  28043. }
  28044. onManifestLoading() {
  28045. this.dateRangeCuesAppended = {};
  28046. }
  28047. createTrack(media) {
  28048. const track = this.getID3Track(media.textTracks);
  28049. track.mode = "hidden";
  28050. return track;
  28051. }
  28052. getID3Track(textTracks) {
  28053. if (!this.media) {
  28054. return;
  28055. }
  28056. for (let i = 0; i < textTracks.length; i++) {
  28057. const textTrack = textTracks[i];
  28058. if (textTrack.kind === "metadata" && textTrack.label === "id3") {
  28059. sendAddTrackEvent(textTrack, this.media);
  28060. return textTrack;
  28061. }
  28062. }
  28063. return this.media.addTextTrack("metadata", "id3");
  28064. }
  28065. onFragParsingMetadata(event, data) {
  28066. if (!this.media) {
  28067. return;
  28068. }
  28069. const {
  28070. hls: {
  28071. config: {
  28072. enableEmsgMetadataCues,
  28073. enableID3MetadataCues
  28074. }
  28075. }
  28076. } = this;
  28077. if (!enableEmsgMetadataCues && !enableID3MetadataCues) {
  28078. return;
  28079. }
  28080. const {
  28081. samples
  28082. } = data;
  28083. if (!this.id3Track) {
  28084. this.id3Track = this.createTrack(this.media);
  28085. }
  28086. const Cue = getCueClass();
  28087. if (!Cue) {
  28088. return;
  28089. }
  28090. for (let i = 0; i < samples.length; i++) {
  28091. const type = samples[i].type;
  28092. if (type === MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) {
  28093. continue;
  28094. }
  28095. const frames = getId3Frames(samples[i].data);
  28096. if (frames) {
  28097. const startTime = samples[i].pts;
  28098. let endTime = startTime + samples[i].duration;
  28099. if (endTime > MAX_CUE_ENDTIME) {
  28100. endTime = MAX_CUE_ENDTIME;
  28101. }
  28102. const timeDiff = endTime - startTime;
  28103. if (timeDiff <= 0) {
  28104. endTime = startTime + MIN_CUE_DURATION;
  28105. }
  28106. for (let j = 0; j < frames.length; j++) {
  28107. const frame = frames[j];
  28108. if (!isId3TimestampFrame(frame)) {
  28109. this.updateId3CueEnds(startTime, type);
  28110. const cue = createCueWithDataFields(Cue, startTime, endTime, frame, type);
  28111. if (cue) {
  28112. this.id3Track.addCue(cue);
  28113. }
  28114. }
  28115. }
  28116. }
  28117. }
  28118. }
  28119. updateId3CueEnds(startTime, type) {
  28120. var _this$id3Track;
  28121. const cues = (_this$id3Track = this.id3Track) == null ? void 0 : _this$id3Track.cues;
  28122. if (cues) {
  28123. for (let i = cues.length; i--; ) {
  28124. const cue = cues[i];
  28125. if (cue.type === type && cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {
  28126. cue.endTime = startTime;
  28127. }
  28128. }
  28129. }
  28130. }
  28131. onBufferFlushing(event, {
  28132. startOffset,
  28133. endOffset,
  28134. type
  28135. }) {
  28136. const {
  28137. id3Track,
  28138. hls
  28139. } = this;
  28140. if (!hls) {
  28141. return;
  28142. }
  28143. const {
  28144. config: {
  28145. enableEmsgMetadataCues,
  28146. enableID3MetadataCues
  28147. }
  28148. } = hls;
  28149. if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {
  28150. let predicate;
  28151. if (type === "audio") {
  28152. predicate = (cue) => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues;
  28153. } else if (type === "video") {
  28154. predicate = (cue) => cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  28155. } else {
  28156. predicate = (cue) => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  28157. }
  28158. removeCuesInRange(id3Track, startOffset, endOffset, predicate);
  28159. }
  28160. }
  28161. onLevelUpdated(event, {
  28162. details
  28163. }) {
  28164. this.updateDateRangeCues(details, true);
  28165. }
  28166. onLevelPtsUpdated(event, data) {
  28167. if (Math.abs(data.drift) > 0.01) {
  28168. this.updateDateRangeCues(data.details);
  28169. }
  28170. }
  28171. updateDateRangeCues(details, removeOldCues) {
  28172. if (!this.media || !details.hasProgramDateTime || !this.hls.config.enableDateRangeMetadataCues) {
  28173. return;
  28174. }
  28175. const {
  28176. id3Track
  28177. } = this;
  28178. const {
  28179. dateRanges
  28180. } = details;
  28181. const ids = Object.keys(dateRanges);
  28182. let dateRangeCuesAppended = this.dateRangeCuesAppended;
  28183. if (id3Track && removeOldCues) {
  28184. var _id3Track$cues;
  28185. if ((_id3Track$cues = id3Track.cues) != null && _id3Track$cues.length) {
  28186. const idsToRemove = Object.keys(dateRangeCuesAppended).filter((id) => !ids.includes(id));
  28187. for (let i = idsToRemove.length; i--; ) {
  28188. const id = idsToRemove[i];
  28189. const cues = dateRangeCuesAppended[id].cues;
  28190. delete dateRangeCuesAppended[id];
  28191. Object.keys(cues).forEach((key) => {
  28192. try {
  28193. const cue = cues[key];
  28194. cue.removeEventListener("enter", this.onEventCueEnter);
  28195. id3Track.removeCue(cue);
  28196. } catch (e) {
  28197. }
  28198. });
  28199. }
  28200. } else {
  28201. dateRangeCuesAppended = this.dateRangeCuesAppended = {};
  28202. }
  28203. }
  28204. const lastFragment = details.fragments[details.fragments.length - 1];
  28205. if (ids.length === 0 || !isFiniteNumber(lastFragment == null ? void 0 : lastFragment.programDateTime)) {
  28206. return;
  28207. }
  28208. if (!this.id3Track) {
  28209. this.id3Track = this.createTrack(this.media);
  28210. }
  28211. const Cue = getCueClass();
  28212. for (let i = 0; i < ids.length; i++) {
  28213. const id = ids[i];
  28214. const dateRange = dateRanges[id];
  28215. const startTime = dateRange.startTime;
  28216. const appendedDateRangeCues = dateRangeCuesAppended[id];
  28217. const cues = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.cues) || {};
  28218. let durationKnown = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.durationKnown) || false;
  28219. let endTime = MAX_CUE_ENDTIME;
  28220. const {
  28221. duration,
  28222. endDate
  28223. } = dateRange;
  28224. if (endDate && duration !== null) {
  28225. endTime = startTime + duration;
  28226. durationKnown = true;
  28227. } else if (dateRange.endOnNext && !durationKnown) {
  28228. const nextDateRangeWithSameClass = ids.reduce((candidateDateRange, id2) => {
  28229. if (id2 !== dateRange.id) {
  28230. const otherDateRange = dateRanges[id2];
  28231. if (otherDateRange.class === dateRange.class && otherDateRange.startDate > dateRange.startDate && (!candidateDateRange || dateRange.startDate < candidateDateRange.startDate)) {
  28232. return otherDateRange;
  28233. }
  28234. }
  28235. return candidateDateRange;
  28236. }, null);
  28237. if (nextDateRangeWithSameClass) {
  28238. endTime = nextDateRangeWithSameClass.startTime;
  28239. durationKnown = true;
  28240. }
  28241. }
  28242. const attributes = Object.keys(dateRange.attr);
  28243. for (let j = 0; j < attributes.length; j++) {
  28244. const key = attributes[j];
  28245. if (!isDateRangeCueAttribute(key)) {
  28246. continue;
  28247. }
  28248. const cue = cues[key];
  28249. if (cue) {
  28250. if (durationKnown && !appendedDateRangeCues.durationKnown) {
  28251. cue.endTime = endTime;
  28252. } else if (Math.abs(cue.startTime - startTime) > 0.01) {
  28253. cue.startTime = startTime;
  28254. cue.endTime = endTime;
  28255. }
  28256. } else if (Cue) {
  28257. let data = dateRange.attr[key];
  28258. if (isSCTE35Attribute(key)) {
  28259. data = hexToArrayBuffer(data);
  28260. }
  28261. const payload = {
  28262. key,
  28263. data
  28264. };
  28265. const _cue = createCueWithDataFields(Cue, startTime, endTime, payload, MetadataSchema.dateRange);
  28266. if (_cue) {
  28267. _cue.id = id;
  28268. this.id3Track.addCue(_cue);
  28269. cues[key] = _cue;
  28270. if (this.hls.config.interstitialsController) {
  28271. if (key === "X-ASSET-LIST" || key === "X-ASSET-URL") {
  28272. _cue.addEventListener("enter", this.onEventCueEnter);
  28273. }
  28274. }
  28275. }
  28276. }
  28277. }
  28278. dateRangeCuesAppended[id] = {
  28279. cues,
  28280. dateRange,
  28281. durationKnown
  28282. };
  28283. }
  28284. }
  28285. };
  28286. var LatencyController = class {
  28287. constructor(hls) {
  28288. this.hls = void 0;
  28289. this.config = void 0;
  28290. this.media = null;
  28291. this.currentTime = 0;
  28292. this.stallCount = 0;
  28293. this._latency = null;
  28294. this._targetLatencyUpdated = false;
  28295. this.onTimeupdate = () => {
  28296. const {
  28297. media
  28298. } = this;
  28299. const levelDetails = this.levelDetails;
  28300. if (!media || !levelDetails) {
  28301. return;
  28302. }
  28303. this.currentTime = media.currentTime;
  28304. const latency = this.computeLatency();
  28305. if (latency === null) {
  28306. return;
  28307. }
  28308. this._latency = latency;
  28309. const {
  28310. lowLatencyMode,
  28311. maxLiveSyncPlaybackRate
  28312. } = this.config;
  28313. if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1 || !levelDetails.live) {
  28314. return;
  28315. }
  28316. const targetLatency = this.targetLatency;
  28317. if (targetLatency === null) {
  28318. return;
  28319. }
  28320. const distanceFromTarget = latency - targetLatency;
  28321. const liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
  28322. const inLiveRange = distanceFromTarget < liveMinLatencyDuration;
  28323. if (inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
  28324. const max = Math.min(2, Math.max(1, maxLiveSyncPlaybackRate));
  28325. const rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
  28326. const playbackRate = Math.min(max, Math.max(1, rate));
  28327. this.changeMediaPlaybackRate(media, playbackRate);
  28328. } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
  28329. this.changeMediaPlaybackRate(media, 1);
  28330. }
  28331. };
  28332. this.hls = hls;
  28333. this.config = hls.config;
  28334. this.registerListeners();
  28335. }
  28336. get levelDetails() {
  28337. var _this$hls;
  28338. return ((_this$hls = this.hls) == null ? void 0 : _this$hls.latestLevelDetails) || null;
  28339. }
  28340. get latency() {
  28341. return this._latency || 0;
  28342. }
  28343. get maxLatency() {
  28344. const {
  28345. config
  28346. } = this;
  28347. if (config.liveMaxLatencyDuration !== void 0) {
  28348. return config.liveMaxLatencyDuration;
  28349. }
  28350. const levelDetails = this.levelDetails;
  28351. return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
  28352. }
  28353. get targetLatency() {
  28354. const levelDetails = this.levelDetails;
  28355. if (levelDetails === null || this.hls === null) {
  28356. return null;
  28357. }
  28358. const {
  28359. holdBack,
  28360. partHoldBack,
  28361. targetduration
  28362. } = levelDetails;
  28363. const {
  28364. liveSyncDuration,
  28365. liveSyncDurationCount,
  28366. lowLatencyMode
  28367. } = this.config;
  28368. const userConfig = this.hls.userConfig;
  28369. let targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
  28370. if (this._targetLatencyUpdated || userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
  28371. targetLatency = liveSyncDuration !== void 0 ? liveSyncDuration : liveSyncDurationCount * targetduration;
  28372. }
  28373. const maxLiveSyncOnStallIncrease = targetduration;
  28374. return targetLatency + Math.min(this.stallCount * this.config.liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
  28375. }
  28376. set targetLatency(latency) {
  28377. this.stallCount = 0;
  28378. this.config.liveSyncDuration = latency;
  28379. this._targetLatencyUpdated = true;
  28380. }
  28381. get liveSyncPosition() {
  28382. const liveEdge = this.estimateLiveEdge();
  28383. const targetLatency = this.targetLatency;
  28384. if (liveEdge === null || targetLatency === null) {
  28385. return null;
  28386. }
  28387. const levelDetails = this.levelDetails;
  28388. if (levelDetails === null) {
  28389. return null;
  28390. }
  28391. const edge = levelDetails.edge;
  28392. const syncPosition = liveEdge - targetLatency - this.edgeStalled;
  28393. const min = edge - levelDetails.totalduration;
  28394. const max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
  28395. return Math.min(Math.max(min, syncPosition), max);
  28396. }
  28397. get drift() {
  28398. const levelDetails = this.levelDetails;
  28399. if (levelDetails === null) {
  28400. return 1;
  28401. }
  28402. return levelDetails.drift;
  28403. }
  28404. get edgeStalled() {
  28405. const levelDetails = this.levelDetails;
  28406. if (levelDetails === null) {
  28407. return 0;
  28408. }
  28409. const maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
  28410. return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
  28411. }
  28412. get forwardBufferLength() {
  28413. const {
  28414. media
  28415. } = this;
  28416. const levelDetails = this.levelDetails;
  28417. if (!media || !levelDetails) {
  28418. return 0;
  28419. }
  28420. const bufferedRanges = media.buffered.length;
  28421. return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime;
  28422. }
  28423. destroy() {
  28424. this.unregisterListeners();
  28425. this.onMediaDetaching();
  28426. this.hls = null;
  28427. }
  28428. registerListeners() {
  28429. const {
  28430. hls
  28431. } = this;
  28432. if (!hls) {
  28433. return;
  28434. }
  28435. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  28436. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  28437. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  28438. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  28439. hls.on(Events.ERROR, this.onError, this);
  28440. }
  28441. unregisterListeners() {
  28442. const {
  28443. hls
  28444. } = this;
  28445. if (!hls) {
  28446. return;
  28447. }
  28448. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  28449. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  28450. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  28451. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  28452. hls.off(Events.ERROR, this.onError, this);
  28453. }
  28454. onMediaAttached(event, data) {
  28455. this.media = data.media;
  28456. this.media.addEventListener("timeupdate", this.onTimeupdate);
  28457. }
  28458. onMediaDetaching() {
  28459. if (this.media) {
  28460. this.media.removeEventListener("timeupdate", this.onTimeupdate);
  28461. this.media = null;
  28462. }
  28463. }
  28464. onManifestLoading() {
  28465. this._latency = null;
  28466. this.stallCount = 0;
  28467. }
  28468. onLevelUpdated(event, {
  28469. details
  28470. }) {
  28471. if (details.advanced) {
  28472. this.onTimeupdate();
  28473. }
  28474. if (!details.live && this.media) {
  28475. this.media.removeEventListener("timeupdate", this.onTimeupdate);
  28476. }
  28477. }
  28478. onError(event, data) {
  28479. var _this$levelDetails;
  28480. if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {
  28481. return;
  28482. }
  28483. this.stallCount++;
  28484. if (this.hls && (_this$levelDetails = this.levelDetails) != null && _this$levelDetails.live) {
  28485. this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency");
  28486. }
  28487. }
  28488. changeMediaPlaybackRate(media, playbackRate) {
  28489. var _this$hls2, _this$targetLatency;
  28490. if (media.playbackRate === playbackRate) {
  28491. return;
  28492. }
  28493. (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(_this$targetLatency = this.targetLatency) == null ? void 0 : _this$targetLatency.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${media.playbackRate} to ${playbackRate}`);
  28494. media.playbackRate = playbackRate;
  28495. }
  28496. estimateLiveEdge() {
  28497. const levelDetails = this.levelDetails;
  28498. if (levelDetails === null) {
  28499. return null;
  28500. }
  28501. return levelDetails.edge + levelDetails.age;
  28502. }
  28503. computeLatency() {
  28504. const liveEdge = this.estimateLiveEdge();
  28505. if (liveEdge === null) {
  28506. return null;
  28507. }
  28508. return liveEdge - this.currentTime;
  28509. }
  28510. };
  28511. var LevelController = class extends BasePlaylistController {
  28512. constructor(hls, contentSteeringController) {
  28513. super(hls, "level-controller");
  28514. this._levels = [];
  28515. this._firstLevel = -1;
  28516. this._maxAutoLevel = -1;
  28517. this._startLevel = void 0;
  28518. this.currentLevel = null;
  28519. this.currentLevelIndex = -1;
  28520. this.manualLevelIndex = -1;
  28521. this.steering = void 0;
  28522. this.onParsedComplete = void 0;
  28523. this.steering = contentSteeringController;
  28524. this._registerListeners();
  28525. }
  28526. _registerListeners() {
  28527. const {
  28528. hls
  28529. } = this;
  28530. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  28531. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  28532. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  28533. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  28534. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  28535. hls.on(Events.ERROR, this.onError, this);
  28536. }
  28537. _unregisterListeners() {
  28538. const {
  28539. hls
  28540. } = this;
  28541. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  28542. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  28543. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  28544. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  28545. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  28546. hls.off(Events.ERROR, this.onError, this);
  28547. }
  28548. destroy() {
  28549. this._unregisterListeners();
  28550. this.steering = null;
  28551. this.resetLevels();
  28552. super.destroy();
  28553. }
  28554. stopLoad() {
  28555. const levels = this._levels;
  28556. levels.forEach((level) => {
  28557. level.loadError = 0;
  28558. level.fragmentError = 0;
  28559. });
  28560. super.stopLoad();
  28561. }
  28562. resetLevels() {
  28563. this._startLevel = void 0;
  28564. this.manualLevelIndex = -1;
  28565. this.currentLevelIndex = -1;
  28566. this.currentLevel = null;
  28567. this._levels = [];
  28568. this._maxAutoLevel = -1;
  28569. }
  28570. onManifestLoading(event, data) {
  28571. this.resetLevels();
  28572. }
  28573. onManifestLoaded(event, data) {
  28574. const preferManagedMediaSource = this.hls.config.preferManagedMediaSource;
  28575. const levels = [];
  28576. const redundantSet = {};
  28577. const generatePathwaySet = {};
  28578. let resolutionFound = false;
  28579. let videoCodecFound = false;
  28580. let audioCodecFound = false;
  28581. data.levels.forEach((levelParsed) => {
  28582. const attributes = levelParsed.attrs;
  28583. let {
  28584. audioCodec,
  28585. videoCodec
  28586. } = levelParsed;
  28587. if (audioCodec) {
  28588. levelParsed.audioCodec = audioCodec = getCodecCompatibleName(audioCodec, preferManagedMediaSource) || void 0;
  28589. }
  28590. if (videoCodec) {
  28591. videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);
  28592. }
  28593. const {
  28594. width,
  28595. height,
  28596. unknownCodecs
  28597. } = levelParsed;
  28598. let unknownUnsupportedCodecCount = unknownCodecs ? unknownCodecs.length : 0;
  28599. if (unknownCodecs) {
  28600. for (let i = unknownUnsupportedCodecCount; i--; ) {
  28601. const unknownCodec = unknownCodecs[i];
  28602. if (this.isAudioSupported(unknownCodec)) {
  28603. levelParsed.audioCodec = audioCodec = audioCodec ? `${audioCodec},${unknownCodec}` : unknownCodec;
  28604. unknownUnsupportedCodecCount--;
  28605. sampleEntryCodesISO.audio[audioCodec.substring(0, 4)] = 2;
  28606. } else if (this.isVideoSupported(unknownCodec)) {
  28607. levelParsed.videoCodec = videoCodec = videoCodec ? `${videoCodec},${unknownCodec}` : unknownCodec;
  28608. unknownUnsupportedCodecCount--;
  28609. sampleEntryCodesISO.video[videoCodec.substring(0, 4)] = 2;
  28610. }
  28611. }
  28612. }
  28613. resolutionFound || (resolutionFound = !!(width && height));
  28614. videoCodecFound || (videoCodecFound = !!videoCodec);
  28615. audioCodecFound || (audioCodecFound = !!audioCodec);
  28616. if (unknownUnsupportedCodecCount || audioCodec && !this.isAudioSupported(audioCodec) || videoCodec && !this.isVideoSupported(videoCodec)) {
  28617. this.log(`Some or all CODECS not supported "${attributes.CODECS}"`);
  28618. return;
  28619. }
  28620. const {
  28621. CODECS,
  28622. "FRAME-RATE": FRAMERATE,
  28623. "HDCP-LEVEL": HDCP,
  28624. "PATHWAY-ID": PATHWAY,
  28625. RESOLUTION,
  28626. "VIDEO-RANGE": VIDEO_RANGE
  28627. } = attributes;
  28628. const contentSteeringPrefix = `${PATHWAY || "."}-`;
  28629. const levelKey = `${contentSteeringPrefix}${levelParsed.bitrate}-${RESOLUTION}-${FRAMERATE}-${CODECS}-${VIDEO_RANGE}-${HDCP}`;
  28630. if (!redundantSet[levelKey]) {
  28631. const level = this.createLevel(levelParsed);
  28632. redundantSet[levelKey] = level;
  28633. generatePathwaySet[levelKey] = 1;
  28634. levels.push(level);
  28635. } else if (redundantSet[levelKey].uri !== levelParsed.url && !levelParsed.attrs["PATHWAY-ID"]) {
  28636. const pathwayCount = generatePathwaySet[levelKey] += 1;
  28637. levelParsed.attrs["PATHWAY-ID"] = new Array(pathwayCount + 1).join(".");
  28638. const level = this.createLevel(levelParsed);
  28639. redundantSet[levelKey] = level;
  28640. levels.push(level);
  28641. } else {
  28642. redundantSet[levelKey].addGroupId("audio", attributes.AUDIO);
  28643. redundantSet[levelKey].addGroupId("text", attributes.SUBTITLES);
  28644. }
  28645. });
  28646. this.filterAndSortMediaOptions(levels, data, resolutionFound, videoCodecFound, audioCodecFound);
  28647. }
  28648. createLevel(levelParsed) {
  28649. const level = new Level(levelParsed);
  28650. const supplemental = levelParsed.supplemental;
  28651. if (supplemental != null && supplemental.videoCodec && !this.isVideoSupported(supplemental.videoCodec)) {
  28652. const error = new Error(`SUPPLEMENTAL-CODECS not supported "${supplemental.videoCodec}"`);
  28653. this.log(error.message);
  28654. level.supportedResult = getUnsupportedResult(error, []);
  28655. }
  28656. return level;
  28657. }
  28658. isAudioSupported(codec) {
  28659. return areCodecsMediaSourceSupported(codec, "audio", this.hls.config.preferManagedMediaSource);
  28660. }
  28661. isVideoSupported(codec) {
  28662. return areCodecsMediaSourceSupported(codec, "video", this.hls.config.preferManagedMediaSource);
  28663. }
  28664. filterAndSortMediaOptions(filteredLevels, data, resolutionFound, videoCodecFound, audioCodecFound) {
  28665. let audioTracks = [];
  28666. let subtitleTracks = [];
  28667. let levels = filteredLevels;
  28668. if ((resolutionFound || videoCodecFound) && audioCodecFound) {
  28669. levels = levels.filter(({
  28670. videoCodec,
  28671. videoRange,
  28672. width,
  28673. height
  28674. }) => (!!videoCodec || !!(width && height)) && isVideoRange(videoRange));
  28675. }
  28676. if (levels.length === 0) {
  28677. Promise.resolve().then(() => {
  28678. if (this.hls) {
  28679. let message = "no level with compatible codecs found in manifest";
  28680. let reason = message;
  28681. if (data.levels.length) {
  28682. reason = `one or more CODECS in variant not supported: ${stringify(data.levels.map((level) => level.attrs.CODECS).filter((value, index, array) => array.indexOf(value) === index))}`;
  28683. this.warn(reason);
  28684. message += ` (${reason})`;
  28685. }
  28686. const error = new Error(message);
  28687. this.hls.trigger(Events.ERROR, {
  28688. type: ErrorTypes.MEDIA_ERROR,
  28689. details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  28690. fatal: true,
  28691. url: data.url,
  28692. error,
  28693. reason
  28694. });
  28695. }
  28696. });
  28697. return;
  28698. }
  28699. if (data.audioTracks) {
  28700. audioTracks = data.audioTracks.filter((track) => !track.audioCodec || this.isAudioSupported(track.audioCodec));
  28701. assignTrackIdsByGroup(audioTracks);
  28702. }
  28703. if (data.subtitles) {
  28704. subtitleTracks = data.subtitles;
  28705. assignTrackIdsByGroup(subtitleTracks);
  28706. }
  28707. const unsortedLevels = levels.slice(0);
  28708. levels.sort((a, b) => {
  28709. if (a.attrs["HDCP-LEVEL"] !== b.attrs["HDCP-LEVEL"]) {
  28710. return (a.attrs["HDCP-LEVEL"] || "") > (b.attrs["HDCP-LEVEL"] || "") ? 1 : -1;
  28711. }
  28712. if (resolutionFound && a.height !== b.height) {
  28713. return a.height - b.height;
  28714. }
  28715. if (a.frameRate !== b.frameRate) {
  28716. return a.frameRate - b.frameRate;
  28717. }
  28718. if (a.videoRange !== b.videoRange) {
  28719. return VideoRangeValues.indexOf(a.videoRange) - VideoRangeValues.indexOf(b.videoRange);
  28720. }
  28721. if (a.videoCodec !== b.videoCodec) {
  28722. const valueA = videoCodecPreferenceValue(a.videoCodec);
  28723. const valueB = videoCodecPreferenceValue(b.videoCodec);
  28724. if (valueA !== valueB) {
  28725. return valueB - valueA;
  28726. }
  28727. }
  28728. if (a.uri === b.uri && a.codecSet !== b.codecSet) {
  28729. const valueA = codecsSetSelectionPreferenceValue(a.codecSet);
  28730. const valueB = codecsSetSelectionPreferenceValue(b.codecSet);
  28731. if (valueA !== valueB) {
  28732. return valueB - valueA;
  28733. }
  28734. }
  28735. if (a.averageBitrate !== b.averageBitrate) {
  28736. return a.averageBitrate - b.averageBitrate;
  28737. }
  28738. return 0;
  28739. });
  28740. let firstLevelInPlaylist = unsortedLevels[0];
  28741. if (this.steering) {
  28742. levels = this.steering.filterParsedLevels(levels);
  28743. if (levels.length !== unsortedLevels.length) {
  28744. for (let i = 0; i < unsortedLevels.length; i++) {
  28745. if (unsortedLevels[i].pathwayId === levels[0].pathwayId) {
  28746. firstLevelInPlaylist = unsortedLevels[i];
  28747. break;
  28748. }
  28749. }
  28750. }
  28751. }
  28752. this._levels = levels;
  28753. for (let i = 0; i < levels.length; i++) {
  28754. if (levels[i] === firstLevelInPlaylist) {
  28755. var _this$hls$userConfig;
  28756. this._firstLevel = i;
  28757. const firstLevelBitrate = firstLevelInPlaylist.bitrate;
  28758. const bandwidthEstimate = this.hls.bandwidthEstimate;
  28759. this.log(`manifest loaded, ${levels.length} level(s) found, first bitrate: ${firstLevelBitrate}`);
  28760. if (((_this$hls$userConfig = this.hls.userConfig) == null ? void 0 : _this$hls$userConfig.abrEwmaDefaultEstimate) === void 0) {
  28761. const startingBwEstimate = Math.min(firstLevelBitrate, this.hls.config.abrEwmaDefaultEstimateMax);
  28762. if (startingBwEstimate > bandwidthEstimate && bandwidthEstimate === this.hls.abrEwmaDefaultEstimate) {
  28763. this.hls.bandwidthEstimate = startingBwEstimate;
  28764. }
  28765. }
  28766. break;
  28767. }
  28768. }
  28769. const audioOnly = audioCodecFound && !videoCodecFound;
  28770. const config = this.hls.config;
  28771. const altAudioEnabled = !!(config.audioStreamController && config.audioTrackController);
  28772. const edata = {
  28773. levels,
  28774. audioTracks,
  28775. subtitleTracks,
  28776. sessionData: data.sessionData,
  28777. sessionKeys: data.sessionKeys,
  28778. firstLevel: this._firstLevel,
  28779. stats: data.stats,
  28780. audio: audioCodecFound,
  28781. video: videoCodecFound,
  28782. altAudio: altAudioEnabled && !audioOnly && audioTracks.some((t) => !!t.url)
  28783. };
  28784. this.hls.trigger(Events.MANIFEST_PARSED, edata);
  28785. }
  28786. get levels() {
  28787. if (this._levels.length === 0) {
  28788. return null;
  28789. }
  28790. return this._levels;
  28791. }
  28792. get loadLevelObj() {
  28793. return this.currentLevel;
  28794. }
  28795. get level() {
  28796. return this.currentLevelIndex;
  28797. }
  28798. set level(newLevel) {
  28799. const levels = this._levels;
  28800. if (levels.length === 0) {
  28801. return;
  28802. }
  28803. if (newLevel < 0 || newLevel >= levels.length) {
  28804. const error = new Error("invalid level idx");
  28805. const fatal = newLevel < 0;
  28806. this.hls.trigger(Events.ERROR, {
  28807. type: ErrorTypes.OTHER_ERROR,
  28808. details: ErrorDetails.LEVEL_SWITCH_ERROR,
  28809. level: newLevel,
  28810. fatal,
  28811. error,
  28812. reason: error.message
  28813. });
  28814. if (fatal) {
  28815. return;
  28816. }
  28817. newLevel = Math.min(newLevel, levels.length - 1);
  28818. }
  28819. const lastLevelIndex = this.currentLevelIndex;
  28820. const lastLevel = this.currentLevel;
  28821. const lastPathwayId = lastLevel ? lastLevel.attrs["PATHWAY-ID"] : void 0;
  28822. const level = levels[newLevel];
  28823. const pathwayId = level.attrs["PATHWAY-ID"];
  28824. this.currentLevelIndex = newLevel;
  28825. this.currentLevel = level;
  28826. if (lastLevelIndex === newLevel && lastLevel && lastPathwayId === pathwayId) {
  28827. return;
  28828. }
  28829. this.log(`Switching to level ${newLevel} (${level.height ? level.height + "p " : ""}${level.videoRange ? level.videoRange + " " : ""}${level.codecSet ? level.codecSet + " " : ""}@${level.bitrate})${pathwayId ? " with Pathway " + pathwayId : ""} from level ${lastLevelIndex}${lastPathwayId ? " with Pathway " + lastPathwayId : ""}`);
  28830. const levelSwitchingData = {
  28831. level: newLevel,
  28832. attrs: level.attrs,
  28833. details: level.details,
  28834. bitrate: level.bitrate,
  28835. averageBitrate: level.averageBitrate,
  28836. maxBitrate: level.maxBitrate,
  28837. realBitrate: level.realBitrate,
  28838. width: level.width,
  28839. height: level.height,
  28840. codecSet: level.codecSet,
  28841. audioCodec: level.audioCodec,
  28842. videoCodec: level.videoCodec,
  28843. audioGroups: level.audioGroups,
  28844. subtitleGroups: level.subtitleGroups,
  28845. loaded: level.loaded,
  28846. loadError: level.loadError,
  28847. fragmentError: level.fragmentError,
  28848. name: level.name,
  28849. id: level.id,
  28850. uri: level.uri,
  28851. url: level.url,
  28852. urlId: 0,
  28853. audioGroupIds: level.audioGroupIds,
  28854. textGroupIds: level.textGroupIds
  28855. };
  28856. this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);
  28857. const levelDetails = level.details;
  28858. if (!levelDetails || levelDetails.live) {
  28859. const hlsUrlParameters = this.switchParams(level.uri, lastLevel == null ? void 0 : lastLevel.details, levelDetails);
  28860. this.loadPlaylist(hlsUrlParameters);
  28861. }
  28862. }
  28863. get manualLevel() {
  28864. return this.manualLevelIndex;
  28865. }
  28866. set manualLevel(newLevel) {
  28867. this.manualLevelIndex = newLevel;
  28868. if (this._startLevel === void 0) {
  28869. this._startLevel = newLevel;
  28870. }
  28871. if (newLevel !== -1) {
  28872. this.level = newLevel;
  28873. }
  28874. }
  28875. get firstLevel() {
  28876. return this._firstLevel;
  28877. }
  28878. set firstLevel(newLevel) {
  28879. this._firstLevel = newLevel;
  28880. }
  28881. get startLevel() {
  28882. if (this._startLevel === void 0) {
  28883. const configStartLevel = this.hls.config.startLevel;
  28884. if (configStartLevel !== void 0) {
  28885. return configStartLevel;
  28886. }
  28887. return this.hls.firstAutoLevel;
  28888. }
  28889. return this._startLevel;
  28890. }
  28891. set startLevel(newLevel) {
  28892. this._startLevel = newLevel;
  28893. }
  28894. get pathways() {
  28895. if (this.steering) {
  28896. return this.steering.pathways();
  28897. }
  28898. return [];
  28899. }
  28900. get pathwayPriority() {
  28901. if (this.steering) {
  28902. return this.steering.pathwayPriority;
  28903. }
  28904. return null;
  28905. }
  28906. set pathwayPriority(pathwayPriority) {
  28907. if (this.steering) {
  28908. const pathwaysList = this.steering.pathways();
  28909. const filteredPathwayPriority = pathwayPriority.filter((pathwayId) => {
  28910. return pathwaysList.indexOf(pathwayId) !== -1;
  28911. });
  28912. if (pathwayPriority.length < 1) {
  28913. this.warn(`pathwayPriority ${pathwayPriority} should contain at least one pathway from list: ${pathwaysList}`);
  28914. return;
  28915. }
  28916. this.steering.pathwayPriority = filteredPathwayPriority;
  28917. }
  28918. }
  28919. onError(event, data) {
  28920. if (data.fatal || !data.context) {
  28921. return;
  28922. }
  28923. if (data.context.type === PlaylistContextType.LEVEL && data.context.level === this.level) {
  28924. this.checkRetry(data);
  28925. }
  28926. }
  28927. // reset errors on the successful load of a fragment
  28928. onFragBuffered(event, {
  28929. frag
  28930. }) {
  28931. if (frag !== void 0 && frag.type === PlaylistLevelType.MAIN) {
  28932. const el = frag.elementaryStreams;
  28933. if (!Object.keys(el).some((type) => !!el[type])) {
  28934. return;
  28935. }
  28936. const level = this._levels[frag.level];
  28937. if (level != null && level.loadError) {
  28938. this.log(`Resetting level error count of ${level.loadError} on frag buffered`);
  28939. level.loadError = 0;
  28940. }
  28941. }
  28942. }
  28943. onLevelLoaded(event, data) {
  28944. var _data$deliveryDirecti2;
  28945. const {
  28946. level,
  28947. details
  28948. } = data;
  28949. const curLevel = data.levelInfo;
  28950. if (!curLevel) {
  28951. var _data$deliveryDirecti;
  28952. this.warn(`Invalid level index ${level}`);
  28953. if ((_data$deliveryDirecti = data.deliveryDirectives) != null && _data$deliveryDirecti.skip) {
  28954. details.deltaUpdateFailed = true;
  28955. }
  28956. return;
  28957. }
  28958. if (curLevel === this.currentLevel || data.withoutMultiVariant) {
  28959. if (curLevel.fragmentError === 0) {
  28960. curLevel.loadError = 0;
  28961. }
  28962. let previousDetails = curLevel.details;
  28963. if (previousDetails === data.details && previousDetails.advanced) {
  28964. previousDetails = void 0;
  28965. }
  28966. this.playlistLoaded(level, data, previousDetails);
  28967. } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) != null && _data$deliveryDirecti2.skip) {
  28968. details.deltaUpdateFailed = true;
  28969. }
  28970. }
  28971. loadPlaylist(hlsUrlParameters) {
  28972. super.loadPlaylist();
  28973. if (this.shouldLoadPlaylist(this.currentLevel)) {
  28974. this.scheduleLoading(this.currentLevel, hlsUrlParameters);
  28975. }
  28976. }
  28977. loadingPlaylist(currentLevel, hlsUrlParameters) {
  28978. super.loadingPlaylist(currentLevel, hlsUrlParameters);
  28979. const url = this.getUrlWithDirectives(currentLevel.uri, hlsUrlParameters);
  28980. const currentLevelIndex = this.currentLevelIndex;
  28981. const pathwayId = currentLevel.attrs["PATHWAY-ID"];
  28982. const details = currentLevel.details;
  28983. const age = details == null ? void 0 : details.age;
  28984. this.log(`Loading level index ${currentLevelIndex}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== void 0 ? " at sn " + hlsUrlParameters.msn + " part " + hlsUrlParameters.part : ""}${pathwayId ? " Pathway " + pathwayId : ""}${age && details.live ? " age " + age.toFixed(1) + (details.type ? " " + details.type || "" : "") : ""} ${url}`);
  28985. this.hls.trigger(Events.LEVEL_LOADING, {
  28986. url,
  28987. level: currentLevelIndex,
  28988. levelInfo: currentLevel,
  28989. pathwayId: currentLevel.attrs["PATHWAY-ID"],
  28990. id: 0,
  28991. // Deprecated Level urlId
  28992. deliveryDirectives: hlsUrlParameters || null
  28993. });
  28994. }
  28995. get nextLoadLevel() {
  28996. if (this.manualLevelIndex !== -1) {
  28997. return this.manualLevelIndex;
  28998. } else {
  28999. return this.hls.nextAutoLevel;
  29000. }
  29001. }
  29002. set nextLoadLevel(nextLevel) {
  29003. this.level = nextLevel;
  29004. if (this.manualLevelIndex === -1) {
  29005. this.hls.nextAutoLevel = nextLevel;
  29006. }
  29007. }
  29008. removeLevel(levelIndex) {
  29009. var _this$currentLevel;
  29010. if (this._levels.length === 1) {
  29011. return;
  29012. }
  29013. const levels = this._levels.filter((level, index) => {
  29014. if (index !== levelIndex) {
  29015. return true;
  29016. }
  29017. if (this.steering) {
  29018. this.steering.removeLevel(level);
  29019. }
  29020. if (level === this.currentLevel) {
  29021. this.currentLevel = null;
  29022. this.currentLevelIndex = -1;
  29023. if (level.details) {
  29024. level.details.fragments.forEach((f) => f.level = -1);
  29025. }
  29026. }
  29027. return false;
  29028. });
  29029. reassignFragmentLevelIndexes(levels);
  29030. this._levels = levels;
  29031. if (this.currentLevelIndex > -1 && (_this$currentLevel = this.currentLevel) != null && _this$currentLevel.details) {
  29032. this.currentLevelIndex = this.currentLevel.details.fragments[0].level;
  29033. }
  29034. if (this.manualLevelIndex > -1) {
  29035. this.manualLevelIndex = this.currentLevelIndex;
  29036. }
  29037. const maxLevel = levels.length - 1;
  29038. this._firstLevel = Math.min(this._firstLevel, maxLevel);
  29039. if (this._startLevel) {
  29040. this._startLevel = Math.min(this._startLevel, maxLevel);
  29041. }
  29042. this.hls.trigger(Events.LEVELS_UPDATED, {
  29043. levels
  29044. });
  29045. }
  29046. onLevelsUpdated(event, {
  29047. levels
  29048. }) {
  29049. this._levels = levels;
  29050. }
  29051. checkMaxAutoUpdated() {
  29052. const {
  29053. autoLevelCapping,
  29054. maxAutoLevel,
  29055. maxHdcpLevel
  29056. } = this.hls;
  29057. if (this._maxAutoLevel !== maxAutoLevel) {
  29058. this._maxAutoLevel = maxAutoLevel;
  29059. this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {
  29060. autoLevelCapping,
  29061. levels: this.levels,
  29062. maxAutoLevel,
  29063. minAutoLevel: this.hls.minAutoLevel,
  29064. maxHdcpLevel
  29065. });
  29066. }
  29067. }
  29068. };
  29069. function assignTrackIdsByGroup(tracks) {
  29070. const groups = {};
  29071. tracks.forEach((track) => {
  29072. const groupId = track.groupId || "";
  29073. track.id = groups[groupId] = groups[groupId] || 0;
  29074. groups[groupId]++;
  29075. });
  29076. }
  29077. function getSourceBuffer() {
  29078. return self.SourceBuffer || self.WebKitSourceBuffer;
  29079. }
  29080. function isMSESupported() {
  29081. const mediaSource = getMediaSource();
  29082. if (!mediaSource) {
  29083. return false;
  29084. }
  29085. const sourceBuffer = getSourceBuffer();
  29086. return !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === "function" && typeof sourceBuffer.prototype.remove === "function";
  29087. }
  29088. function isSupported() {
  29089. if (!isMSESupported()) {
  29090. return false;
  29091. }
  29092. const mediaSource = getMediaSource();
  29093. return typeof (mediaSource == null ? void 0 : mediaSource.isTypeSupported) === "function" && (["avc1.42E01E,mp4a.40.2", "av01.0.01M.08", "vp09.00.50.08"].some((codecsForVideoContainer) => mediaSource.isTypeSupported(mimeTypeForCodec(codecsForVideoContainer, "video"))) || ["mp4a.40.2", "fLaC"].some((codecForAudioContainer) => mediaSource.isTypeSupported(mimeTypeForCodec(codecForAudioContainer, "audio"))));
  29094. }
  29095. function changeTypeSupported() {
  29096. var _sourceBuffer$prototy;
  29097. const sourceBuffer = getSourceBuffer();
  29098. return typeof (sourceBuffer == null ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) == null ? void 0 : _sourceBuffer$prototy.changeType) === "function";
  29099. }
  29100. var TICK_INTERVAL = 100;
  29101. var StreamController = class extends BaseStreamController {
  29102. constructor(hls, fragmentTracker, keyLoader) {
  29103. super(hls, fragmentTracker, keyLoader, "stream-controller", PlaylistLevelType.MAIN);
  29104. this.audioCodecSwap = false;
  29105. this.level = -1;
  29106. this._forceStartLoad = false;
  29107. this._hasEnoughToStart = false;
  29108. this.altAudio = 0;
  29109. this.audioOnly = false;
  29110. this.fragPlaying = null;
  29111. this.fragLastKbps = 0;
  29112. this.couldBacktrack = false;
  29113. this.backtrackFragment = null;
  29114. this.audioCodecSwitch = false;
  29115. this.videoBuffer = null;
  29116. this.onMediaPlaying = () => {
  29117. this.tick();
  29118. };
  29119. this.onMediaSeeked = () => {
  29120. const media = this.media;
  29121. const currentTime = media ? media.currentTime : null;
  29122. if (currentTime === null || !isFiniteNumber(currentTime)) {
  29123. return;
  29124. }
  29125. this.log(`Media seeked to ${currentTime.toFixed(3)}`);
  29126. if (!this.getBufferedFrag(currentTime)) {
  29127. return;
  29128. }
  29129. const bufferInfo = this.getFwdBufferInfoAtPos(media, currentTime, PlaylistLevelType.MAIN, 0);
  29130. if (bufferInfo === null || bufferInfo.len === 0) {
  29131. this.warn(`Main forward buffer length at ${currentTime} on "seeked" event ${bufferInfo ? bufferInfo.len : "empty"})`);
  29132. return;
  29133. }
  29134. this.tick();
  29135. };
  29136. this.registerListeners();
  29137. }
  29138. registerListeners() {
  29139. super.registerListeners();
  29140. const {
  29141. hls
  29142. } = this;
  29143. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  29144. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  29145. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  29146. hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  29147. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  29148. hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  29149. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  29150. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  29151. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  29152. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  29153. }
  29154. unregisterListeners() {
  29155. super.unregisterListeners();
  29156. const {
  29157. hls
  29158. } = this;
  29159. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  29160. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  29161. hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  29162. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  29163. hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  29164. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  29165. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  29166. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  29167. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  29168. }
  29169. onHandlerDestroying() {
  29170. this.onMediaPlaying = this.onMediaSeeked = null;
  29171. this.unregisterListeners();
  29172. super.onHandlerDestroying();
  29173. }
  29174. startLoad(startPosition, skipSeekToStartPosition) {
  29175. if (this.levels) {
  29176. const {
  29177. lastCurrentTime,
  29178. hls
  29179. } = this;
  29180. this.stopLoad();
  29181. this.setInterval(TICK_INTERVAL);
  29182. this.level = -1;
  29183. if (!this.startFragRequested) {
  29184. let startLevel = hls.startLevel;
  29185. if (startLevel === -1) {
  29186. if (hls.config.testBandwidth && this.levels.length > 1) {
  29187. startLevel = 0;
  29188. this.bitrateTest = true;
  29189. } else {
  29190. startLevel = hls.firstAutoLevel;
  29191. }
  29192. }
  29193. hls.nextLoadLevel = startLevel;
  29194. this.level = hls.loadLevel;
  29195. this._hasEnoughToStart = !!skipSeekToStartPosition;
  29196. }
  29197. if (lastCurrentTime > 0 && startPosition === -1 && !skipSeekToStartPosition) {
  29198. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  29199. startPosition = lastCurrentTime;
  29200. }
  29201. this.state = State.IDLE;
  29202. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  29203. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  29204. this.tick();
  29205. } else {
  29206. this._forceStartLoad = true;
  29207. this.state = State.STOPPED;
  29208. }
  29209. }
  29210. stopLoad() {
  29211. this._forceStartLoad = false;
  29212. super.stopLoad();
  29213. }
  29214. doTick() {
  29215. switch (this.state) {
  29216. case State.WAITING_LEVEL: {
  29217. const {
  29218. levels,
  29219. level
  29220. } = this;
  29221. const currentLevel = levels == null ? void 0 : levels[level];
  29222. const details = currentLevel == null ? void 0 : currentLevel.details;
  29223. if (details && (!details.live || this.levelLastLoaded === currentLevel && !this.waitForLive(currentLevel))) {
  29224. if (this.waitForCdnTuneIn(details)) {
  29225. break;
  29226. }
  29227. this.state = State.IDLE;
  29228. break;
  29229. } else if (this.hls.nextLoadLevel !== this.level) {
  29230. this.state = State.IDLE;
  29231. break;
  29232. }
  29233. break;
  29234. }
  29235. case State.FRAG_LOADING_WAITING_RETRY:
  29236. {
  29237. var _this$media;
  29238. const now2 = self.performance.now();
  29239. const retryDate = this.retryDate;
  29240. if (!retryDate || now2 >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  29241. const {
  29242. levels,
  29243. level
  29244. } = this;
  29245. const currentLevel = levels == null ? void 0 : levels[level];
  29246. this.resetStartWhenNotLoaded(currentLevel || null);
  29247. this.state = State.IDLE;
  29248. }
  29249. }
  29250. break;
  29251. }
  29252. if (this.state === State.IDLE) {
  29253. this.doTickIdle();
  29254. }
  29255. this.onTickEnd();
  29256. }
  29257. onTickEnd() {
  29258. var _this$media2;
  29259. super.onTickEnd();
  29260. if ((_this$media2 = this.media) != null && _this$media2.readyState && this.media.seeking === false) {
  29261. this.lastCurrentTime = this.media.currentTime;
  29262. }
  29263. this.checkFragmentChanged();
  29264. }
  29265. doTickIdle() {
  29266. const {
  29267. hls,
  29268. levelLastLoaded,
  29269. levels,
  29270. media
  29271. } = this;
  29272. if (levelLastLoaded === null || !media && !this.primaryPrefetch && (this.startFragRequested || !hls.config.startFragPrefetch)) {
  29273. return;
  29274. }
  29275. if (this.altAudio && this.audioOnly) {
  29276. return;
  29277. }
  29278. const level = this.buffering ? hls.nextLoadLevel : hls.loadLevel;
  29279. if (!(levels != null && levels[level])) {
  29280. return;
  29281. }
  29282. const levelInfo = levels[level];
  29283. const bufferInfo = this.getMainFwdBufferInfo();
  29284. if (bufferInfo === null) {
  29285. return;
  29286. }
  29287. const lastDetails = this.getLevelDetails();
  29288. if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {
  29289. const data = {};
  29290. if (this.altAudio === 2) {
  29291. data.type = "video";
  29292. }
  29293. this.hls.trigger(Events.BUFFER_EOS, data);
  29294. this.state = State.ENDED;
  29295. return;
  29296. }
  29297. if (!this.buffering) {
  29298. return;
  29299. }
  29300. if (hls.loadLevel !== level && hls.manualLevel === -1) {
  29301. this.log(`Adapting to level ${level} from level ${this.level}`);
  29302. }
  29303. this.level = hls.nextLoadLevel = level;
  29304. const levelDetails = levelInfo.details;
  29305. if (!levelDetails || this.state === State.WAITING_LEVEL || this.waitForLive(levelInfo)) {
  29306. this.level = level;
  29307. this.state = State.WAITING_LEVEL;
  29308. this.startFragRequested = false;
  29309. return;
  29310. }
  29311. const bufferLen = bufferInfo.len;
  29312. const maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);
  29313. if (bufferLen >= maxBufLen) {
  29314. return;
  29315. }
  29316. if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) {
  29317. this.backtrackFragment = null;
  29318. }
  29319. const targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end;
  29320. let frag = this.getNextFragment(targetBufferTime, levelDetails);
  29321. if (this.couldBacktrack && !this.fragPrevious && frag && isMediaFragment(frag) && this.fragmentTracker.getState(frag) !== FragmentState.OK) {
  29322. var _this$backtrackFragme;
  29323. const backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn;
  29324. const fragIdx = backtrackSn - levelDetails.startSN;
  29325. const backtrackFrag = levelDetails.fragments[fragIdx - 1];
  29326. if (backtrackFrag && frag.cc === backtrackFrag.cc) {
  29327. frag = backtrackFrag;
  29328. this.fragmentTracker.removeFragment(backtrackFrag);
  29329. }
  29330. } else if (this.backtrackFragment && bufferInfo.len) {
  29331. this.backtrackFragment = null;
  29332. }
  29333. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  29334. const gapStart = frag.gap;
  29335. if (!gapStart) {
  29336. const type = this.audioOnly && !this.altAudio ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
  29337. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  29338. if (mediaBuffer) {
  29339. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  29340. }
  29341. }
  29342. frag = this.getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  29343. }
  29344. if (!frag) {
  29345. return;
  29346. }
  29347. if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
  29348. frag = frag.initSegment;
  29349. }
  29350. this.loadFragment(frag, levelInfo, targetBufferTime);
  29351. }
  29352. loadFragment(frag, level, targetBufferTime) {
  29353. const fragState = this.fragmentTracker.getState(frag);
  29354. if (fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  29355. if (!isMediaFragment(frag)) {
  29356. this._loadInitSegment(frag, level);
  29357. } else if (this.bitrateTest) {
  29358. this.log(`Fragment ${frag.sn} of level ${frag.level} is being downloaded to test bitrate and will not be buffered`);
  29359. this._loadBitrateTestFrag(frag, level);
  29360. } else {
  29361. super.loadFragment(frag, level, targetBufferTime);
  29362. }
  29363. } else {
  29364. this.clearTrackerIfNeeded(frag);
  29365. }
  29366. }
  29367. getBufferedFrag(position) {
  29368. return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
  29369. }
  29370. followingBufferedFrag(frag) {
  29371. if (frag) {
  29372. return this.getBufferedFrag(frag.end + 0.5);
  29373. }
  29374. return null;
  29375. }
  29376. /*
  29377. on immediate level switch :
  29378. - pause playback if playing
  29379. - cancel any pending load request
  29380. - and trigger a buffer flush
  29381. */
  29382. immediateLevelSwitch() {
  29383. this.abortCurrentFrag();
  29384. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  29385. }
  29386. /**
  29387. * try to switch ASAP without breaking video playback:
  29388. * in order to ensure smooth but quick level switching,
  29389. * we need to find the next flushable buffer range
  29390. * we should take into account new segment fetch time
  29391. */
  29392. nextLevelSwitch() {
  29393. const {
  29394. levels,
  29395. media
  29396. } = this;
  29397. if (media != null && media.readyState) {
  29398. let fetchdelay;
  29399. const fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
  29400. if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
  29401. this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
  29402. }
  29403. const levelDetails = this.getLevelDetails();
  29404. if (levelDetails != null && levelDetails.live) {
  29405. const bufferInfo = this.getMainFwdBufferInfo();
  29406. if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {
  29407. return;
  29408. }
  29409. }
  29410. if (!media.paused && levels) {
  29411. const nextLevelId = this.hls.nextLoadLevel;
  29412. const nextLevel = levels[nextLevelId];
  29413. const fragLastKbps = this.fragLastKbps;
  29414. if (fragLastKbps && this.fragCurrent) {
  29415. fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1e3 * fragLastKbps) + 1;
  29416. } else {
  29417. fetchdelay = 0;
  29418. }
  29419. } else {
  29420. fetchdelay = 0;
  29421. }
  29422. const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  29423. if (bufferedFrag) {
  29424. const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
  29425. if (nextBufferedFrag) {
  29426. this.abortCurrentFrag();
  29427. const maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
  29428. const fragDuration = nextBufferedFrag.duration;
  29429. const startPts = Math.max(bufferedFrag.end, maxStart + Math.min(Math.max(fragDuration - this.config.maxFragLookUpTolerance, fragDuration * (this.couldBacktrack ? 0.5 : 0.125)), fragDuration * (this.couldBacktrack ? 0.75 : 0.25)));
  29430. this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
  29431. }
  29432. }
  29433. }
  29434. }
  29435. abortCurrentFrag() {
  29436. const fragCurrent = this.fragCurrent;
  29437. this.fragCurrent = null;
  29438. this.backtrackFragment = null;
  29439. if (fragCurrent) {
  29440. fragCurrent.abortRequests();
  29441. this.fragmentTracker.removeFragment(fragCurrent);
  29442. }
  29443. switch (this.state) {
  29444. case State.KEY_LOADING:
  29445. case State.FRAG_LOADING:
  29446. case State.FRAG_LOADING_WAITING_RETRY:
  29447. case State.PARSING:
  29448. case State.PARSED:
  29449. this.state = State.IDLE;
  29450. break;
  29451. }
  29452. this.nextLoadPosition = this.getLoadPosition();
  29453. }
  29454. flushMainBuffer(startOffset, endOffset) {
  29455. super.flushMainBuffer(startOffset, endOffset, this.altAudio === 2 ? "video" : null);
  29456. }
  29457. onMediaAttached(event, data) {
  29458. super.onMediaAttached(event, data);
  29459. const media = data.media;
  29460. addEventListener(media, "playing", this.onMediaPlaying);
  29461. addEventListener(media, "seeked", this.onMediaSeeked);
  29462. }
  29463. onMediaDetaching(event, data) {
  29464. const {
  29465. media
  29466. } = this;
  29467. if (media) {
  29468. removeEventListener(media, "playing", this.onMediaPlaying);
  29469. removeEventListener(media, "seeked", this.onMediaSeeked);
  29470. }
  29471. this.videoBuffer = null;
  29472. this.fragPlaying = null;
  29473. super.onMediaDetaching(event, data);
  29474. const transferringMedia = !!data.transferMedia;
  29475. if (transferringMedia) {
  29476. return;
  29477. }
  29478. this._hasEnoughToStart = false;
  29479. }
  29480. onManifestLoading() {
  29481. super.onManifestLoading();
  29482. this.log("Trigger BUFFER_RESET");
  29483. this.hls.trigger(Events.BUFFER_RESET, void 0);
  29484. this.couldBacktrack = false;
  29485. this.fragLastKbps = 0;
  29486. this.fragPlaying = this.backtrackFragment = null;
  29487. this.altAudio = 0;
  29488. this.audioOnly = false;
  29489. }
  29490. onManifestParsed(event, data) {
  29491. let aac = false;
  29492. let heaac = false;
  29493. data.levels.forEach((level) => {
  29494. const codec = level.audioCodec;
  29495. if (codec) {
  29496. aac = aac || codec.indexOf("mp4a.40.2") !== -1;
  29497. heaac = heaac || codec.indexOf("mp4a.40.5") !== -1;
  29498. }
  29499. });
  29500. this.audioCodecSwitch = aac && heaac && !changeTypeSupported();
  29501. if (this.audioCodecSwitch) {
  29502. this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC");
  29503. }
  29504. this.levels = data.levels;
  29505. this.startFragRequested = false;
  29506. }
  29507. onLevelLoading(event, data) {
  29508. const {
  29509. levels
  29510. } = this;
  29511. if (!levels || this.state !== State.IDLE) {
  29512. return;
  29513. }
  29514. const level = data.levelInfo;
  29515. if (!level.details || level.details.live && (this.levelLastLoaded !== level || level.details.expired) || this.waitForCdnTuneIn(level.details)) {
  29516. this.state = State.WAITING_LEVEL;
  29517. }
  29518. }
  29519. onLevelLoaded(event, data) {
  29520. var _curLevel$details;
  29521. const {
  29522. levels,
  29523. startFragRequested
  29524. } = this;
  29525. const newLevelId = data.level;
  29526. const newDetails = data.details;
  29527. const duration = newDetails.totalduration;
  29528. if (!levels) {
  29529. this.warn(`Levels were reset while loading level ${newLevelId}`);
  29530. return;
  29531. }
  29532. this.log(`Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""}, cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration}`);
  29533. const curLevel = data.levelInfo;
  29534. const fragCurrent = this.fragCurrent;
  29535. if (fragCurrent && (this.state === State.FRAG_LOADING || this.state === State.FRAG_LOADING_WAITING_RETRY)) {
  29536. if (fragCurrent.level !== data.level && fragCurrent.loader) {
  29537. this.abortCurrentFrag();
  29538. }
  29539. }
  29540. let sliding = 0;
  29541. if (newDetails.live || (_curLevel$details = curLevel.details) != null && _curLevel$details.live) {
  29542. var _this$levelLastLoaded;
  29543. this.checkLiveUpdate(newDetails);
  29544. if (newDetails.deltaUpdateFailed) {
  29545. return;
  29546. }
  29547. sliding = this.alignPlaylists(newDetails, curLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  29548. }
  29549. curLevel.details = newDetails;
  29550. this.levelLastLoaded = curLevel;
  29551. if (!startFragRequested) {
  29552. this.setStartPosition(newDetails, sliding);
  29553. }
  29554. this.hls.trigger(Events.LEVEL_UPDATED, {
  29555. details: newDetails,
  29556. level: newLevelId
  29557. });
  29558. if (this.state === State.WAITING_LEVEL) {
  29559. if (this.waitForCdnTuneIn(newDetails)) {
  29560. return;
  29561. }
  29562. this.state = State.IDLE;
  29563. }
  29564. if (startFragRequested && newDetails.live) {
  29565. this.synchronizeToLiveEdge(newDetails);
  29566. }
  29567. this.tick();
  29568. }
  29569. synchronizeToLiveEdge(levelDetails) {
  29570. const {
  29571. config,
  29572. media
  29573. } = this;
  29574. if (!media) {
  29575. return;
  29576. }
  29577. const liveSyncPosition = this.hls.liveSyncPosition;
  29578. const currentTime = this.getLoadPosition();
  29579. const start = levelDetails.fragmentStart;
  29580. const end = levelDetails.edge;
  29581. const withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end;
  29582. if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
  29583. const maxLatency = config.liveMaxLatencyDuration !== void 0 ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  29584. if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
  29585. if (!this._hasEnoughToStart) {
  29586. this.nextLoadPosition = liveSyncPosition;
  29587. }
  29588. if (media.readyState) {
  29589. this.warn(`Playback: ${currentTime.toFixed(3)} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);
  29590. if (this.config.liveSyncMode === "buffered") {
  29591. var _bufferInfo$buffered;
  29592. const bufferInfo = BufferHelper.bufferInfo(media, liveSyncPosition, 0);
  29593. if (!(bufferInfo != null && (_bufferInfo$buffered = bufferInfo.buffered) != null && _bufferInfo$buffered.length)) {
  29594. media.currentTime = liveSyncPosition;
  29595. return;
  29596. }
  29597. const isLiveSyncInBuffer = bufferInfo.start <= currentTime;
  29598. if (isLiveSyncInBuffer) {
  29599. media.currentTime = liveSyncPosition;
  29600. return;
  29601. }
  29602. const {
  29603. nextStart
  29604. } = BufferHelper.bufferedInfo(bufferInfo.buffered, currentTime, 0);
  29605. if (nextStart) {
  29606. media.currentTime = nextStart;
  29607. }
  29608. } else {
  29609. media.currentTime = liveSyncPosition;
  29610. }
  29611. }
  29612. }
  29613. }
  29614. }
  29615. _handleFragmentLoadProgress(data) {
  29616. var _frag$initSegment;
  29617. const frag = data.frag;
  29618. const {
  29619. part,
  29620. payload
  29621. } = data;
  29622. const {
  29623. levels
  29624. } = this;
  29625. if (!levels) {
  29626. this.warn(`Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  29627. return;
  29628. }
  29629. const currentLevel = levels[frag.level];
  29630. if (!currentLevel) {
  29631. this.warn(`Level ${frag.level} not found on progress`);
  29632. return;
  29633. }
  29634. const details = currentLevel.details;
  29635. if (!details) {
  29636. this.warn(`Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`);
  29637. this.fragmentTracker.removeFragment(frag);
  29638. return;
  29639. }
  29640. const videoCodec = currentLevel.videoCodec;
  29641. const accurateTimeOffset = details.PTSKnown || !details.live;
  29642. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  29643. const audioCodec = this._getAudioCodec(currentLevel);
  29644. const transmuxer = this.transmuxer = this.transmuxer || new TransmuxerInterface(this.hls, PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  29645. const partIndex = part ? part.index : -1;
  29646. const partial = partIndex !== -1;
  29647. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  29648. const initPTS = this.initPTS[frag.cc];
  29649. transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  29650. }
  29651. onAudioTrackSwitching(event, data) {
  29652. const hls = this.hls;
  29653. const fromAltAudio = this.altAudio === 2;
  29654. const altAudio = useAlternateAudio(data.url, hls);
  29655. if (!altAudio) {
  29656. if (this.mediaBuffer !== this.media) {
  29657. this.log("Switching on main audio, use media.buffered to schedule main fragment loading");
  29658. this.mediaBuffer = this.media;
  29659. const fragCurrent = this.fragCurrent;
  29660. if (fragCurrent) {
  29661. this.log("Switching to main audio track, cancel main fragment load");
  29662. fragCurrent.abortRequests();
  29663. this.fragmentTracker.removeFragment(fragCurrent);
  29664. }
  29665. this.resetTransmuxer();
  29666. this.resetLoadingState();
  29667. } else if (this.audioOnly) {
  29668. this.resetTransmuxer();
  29669. }
  29670. if (fromAltAudio) {
  29671. this.fragmentTracker.removeAllFragments();
  29672. hls.once(Events.BUFFER_FLUSHED, () => {
  29673. var _this$hls;
  29674. (_this$hls = this.hls) == null ? void 0 : _this$hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  29675. });
  29676. hls.trigger(Events.BUFFER_FLUSHING, {
  29677. startOffset: 0,
  29678. endOffset: Number.POSITIVE_INFINITY,
  29679. type: null
  29680. });
  29681. return;
  29682. }
  29683. hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  29684. } else {
  29685. this.altAudio = 1;
  29686. }
  29687. }
  29688. onAudioTrackSwitched(event, data) {
  29689. const altAudio = useAlternateAudio(data.url, this.hls);
  29690. if (altAudio) {
  29691. const videoBuffer = this.videoBuffer;
  29692. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  29693. this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading");
  29694. this.mediaBuffer = videoBuffer;
  29695. }
  29696. }
  29697. this.altAudio = altAudio ? 2 : 0;
  29698. this.tick();
  29699. }
  29700. onBufferCreated(event, data) {
  29701. const tracks = data.tracks;
  29702. let mediaTrack;
  29703. let name;
  29704. let alternate = false;
  29705. for (const type in tracks) {
  29706. const track = tracks[type];
  29707. if (track.id === "main") {
  29708. name = type;
  29709. mediaTrack = track;
  29710. if (type === "video") {
  29711. const videoTrack = tracks[type];
  29712. if (videoTrack) {
  29713. this.videoBuffer = videoTrack.buffer;
  29714. }
  29715. }
  29716. } else {
  29717. alternate = true;
  29718. }
  29719. }
  29720. if (alternate && mediaTrack) {
  29721. this.log(`Alternate track found, use ${name}.buffered to schedule main fragment loading`);
  29722. this.mediaBuffer = mediaTrack.buffer;
  29723. } else {
  29724. this.mediaBuffer = this.media;
  29725. }
  29726. }
  29727. onFragBuffered(event, data) {
  29728. const {
  29729. frag,
  29730. part
  29731. } = data;
  29732. const bufferedMainFragment = frag.type === PlaylistLevelType.MAIN;
  29733. if (bufferedMainFragment) {
  29734. if (this.fragContextChanged(frag)) {
  29735. this.warn(`Fragment ${frag.sn}${part ? " p: " + part.index : ""} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}`);
  29736. if (this.state === State.PARSED) {
  29737. this.state = State.IDLE;
  29738. }
  29739. return;
  29740. }
  29741. const stats = part ? part.stats : frag.stats;
  29742. this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
  29743. if (isMediaFragment(frag)) {
  29744. this.fragPrevious = frag;
  29745. }
  29746. this.fragBufferedComplete(frag, part);
  29747. }
  29748. const media = this.media;
  29749. if (!media) {
  29750. return;
  29751. }
  29752. if (!this._hasEnoughToStart && BufferHelper.getBuffered(media).length) {
  29753. this._hasEnoughToStart = true;
  29754. this.seekToStartPos();
  29755. }
  29756. if (bufferedMainFragment) {
  29757. this.tick();
  29758. }
  29759. }
  29760. get hasEnoughToStart() {
  29761. return this._hasEnoughToStart;
  29762. }
  29763. onError(event, data) {
  29764. var _data$context;
  29765. if (data.fatal) {
  29766. this.state = State.ERROR;
  29767. return;
  29768. }
  29769. switch (data.details) {
  29770. case ErrorDetails.FRAG_GAP:
  29771. case ErrorDetails.FRAG_PARSING_ERROR:
  29772. case ErrorDetails.FRAG_DECRYPT_ERROR:
  29773. case ErrorDetails.FRAG_LOAD_ERROR:
  29774. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  29775. case ErrorDetails.KEY_LOAD_ERROR:
  29776. case ErrorDetails.KEY_LOAD_TIMEOUT:
  29777. this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);
  29778. break;
  29779. case ErrorDetails.LEVEL_LOAD_ERROR:
  29780. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  29781. case ErrorDetails.LEVEL_PARSING_ERROR:
  29782. if (!data.levelRetry && this.state === State.WAITING_LEVEL && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.LEVEL) {
  29783. this.state = State.IDLE;
  29784. }
  29785. break;
  29786. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  29787. case ErrorDetails.BUFFER_APPEND_ERROR:
  29788. if (data.parent !== "main") {
  29789. return;
  29790. }
  29791. if (this.reduceLengthAndFlushBuffer(data)) {
  29792. this.resetLoadingState();
  29793. }
  29794. break;
  29795. case ErrorDetails.BUFFER_FULL_ERROR:
  29796. if (data.parent !== "main") {
  29797. return;
  29798. }
  29799. if (this.reduceLengthAndFlushBuffer(data)) {
  29800. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  29801. }
  29802. break;
  29803. case ErrorDetails.INTERNAL_EXCEPTION:
  29804. this.recoverWorkerError(data);
  29805. break;
  29806. }
  29807. }
  29808. onFragLoadEmergencyAborted() {
  29809. this.state = State.IDLE;
  29810. if (!this._hasEnoughToStart) {
  29811. this.startFragRequested = false;
  29812. this.nextLoadPosition = this.lastCurrentTime;
  29813. }
  29814. this.tickImmediate();
  29815. }
  29816. onBufferFlushed(event, {
  29817. type
  29818. }) {
  29819. if (type !== ElementaryStreamTypes.AUDIO || !this.altAudio) {
  29820. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  29821. if (mediaBuffer) {
  29822. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  29823. this.tick();
  29824. }
  29825. }
  29826. }
  29827. onLevelsUpdated(event, data) {
  29828. if (this.level > -1 && this.fragCurrent) {
  29829. this.level = this.fragCurrent.level;
  29830. if (this.level === -1) {
  29831. this.resetWhenMissingContext(this.fragCurrent);
  29832. }
  29833. }
  29834. this.levels = data.levels;
  29835. }
  29836. swapAudioCodec() {
  29837. this.audioCodecSwap = !this.audioCodecSwap;
  29838. }
  29839. /**
  29840. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  29841. */
  29842. seekToStartPos() {
  29843. const {
  29844. media
  29845. } = this;
  29846. if (!media) {
  29847. return;
  29848. }
  29849. const currentTime = media.currentTime;
  29850. let startPosition = this.startPosition;
  29851. if (startPosition >= 0 && currentTime < startPosition) {
  29852. if (media.seeking) {
  29853. this.log(`could not seek to ${startPosition}, already seeking at ${currentTime}`);
  29854. return;
  29855. }
  29856. const timelineOffset = this.timelineOffset;
  29857. if (timelineOffset && startPosition) {
  29858. startPosition += timelineOffset;
  29859. }
  29860. const details = this.getLevelDetails();
  29861. const buffered = BufferHelper.getBuffered(media);
  29862. const bufferStart = buffered.length ? buffered.start(0) : 0;
  29863. const delta = bufferStart - startPosition;
  29864. const skipTolerance = Math.max(this.config.maxBufferHole, this.config.maxFragLookUpTolerance);
  29865. if (this.config.startOnSegmentBoundary || delta > 0 && (delta < skipTolerance || this.loadingParts && delta < 2 * ((details == null ? void 0 : details.partTarget) || 0))) {
  29866. this.log(`adjusting start position by ${delta} to match buffer start`);
  29867. startPosition += delta;
  29868. this.startPosition = startPosition;
  29869. }
  29870. if (currentTime < startPosition) {
  29871. this.log(`seek to target start position ${startPosition} from current time ${currentTime} buffer start ${bufferStart}`);
  29872. media.currentTime = startPosition;
  29873. }
  29874. }
  29875. }
  29876. _getAudioCodec(currentLevel) {
  29877. let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  29878. if (this.audioCodecSwap && audioCodec) {
  29879. this.log("Swapping audio codec");
  29880. if (audioCodec.indexOf("mp4a.40.5") !== -1) {
  29881. audioCodec = "mp4a.40.2";
  29882. } else {
  29883. audioCodec = "mp4a.40.5";
  29884. }
  29885. }
  29886. return audioCodec;
  29887. }
  29888. _loadBitrateTestFrag(fragment, level) {
  29889. fragment.bitrateTest = true;
  29890. this._doFragLoad(fragment, level).then((data) => {
  29891. const {
  29892. hls
  29893. } = this;
  29894. const frag = data == null ? void 0 : data.frag;
  29895. if (!frag || this.fragContextChanged(frag)) {
  29896. return;
  29897. }
  29898. level.fragmentError = 0;
  29899. this.state = State.IDLE;
  29900. this.startFragRequested = false;
  29901. this.bitrateTest = false;
  29902. const stats = frag.stats;
  29903. stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
  29904. hls.trigger(Events.FRAG_LOADED, data);
  29905. frag.bitrateTest = false;
  29906. });
  29907. }
  29908. _handleTransmuxComplete(transmuxResult) {
  29909. var _id3$samples;
  29910. const id = this.playlistType;
  29911. const {
  29912. hls
  29913. } = this;
  29914. const {
  29915. remuxResult,
  29916. chunkMeta
  29917. } = transmuxResult;
  29918. const context = this.getCurrentContext(chunkMeta);
  29919. if (!context) {
  29920. this.resetWhenMissingContext(chunkMeta);
  29921. return;
  29922. }
  29923. const {
  29924. frag,
  29925. part,
  29926. level
  29927. } = context;
  29928. const {
  29929. video,
  29930. text,
  29931. id3,
  29932. initSegment
  29933. } = remuxResult;
  29934. const {
  29935. details
  29936. } = level;
  29937. const audio = this.altAudio ? void 0 : remuxResult.audio;
  29938. if (this.fragContextChanged(frag)) {
  29939. this.fragmentTracker.removeFragment(frag);
  29940. return;
  29941. }
  29942. this.state = State.PARSING;
  29943. if (initSegment) {
  29944. if (initSegment != null && initSegment.tracks) {
  29945. const mapFragment = frag.initSegment || frag;
  29946. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  29947. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  29948. frag: mapFragment,
  29949. id,
  29950. tracks: initSegment.tracks
  29951. });
  29952. }
  29953. const baseTime = initSegment.initPTS;
  29954. const timescale = initSegment.timescale;
  29955. const initPTS = this.initPTS[frag.cc];
  29956. if (isFiniteNumber(baseTime) && (!initPTS || initPTS.baseTime !== baseTime || initPTS.timescale !== timescale)) {
  29957. this.initPTS[frag.cc] = {
  29958. baseTime,
  29959. timescale
  29960. };
  29961. hls.trigger(Events.INIT_PTS_FOUND, {
  29962. frag,
  29963. id,
  29964. initPTS: baseTime,
  29965. timescale
  29966. });
  29967. }
  29968. }
  29969. if (video && details) {
  29970. if (audio && video.type === "audiovideo") {
  29971. this.logMuxedErr(frag);
  29972. }
  29973. const prevFrag = details.fragments[frag.sn - 1 - details.startSN];
  29974. const isFirstFragment = frag.sn === details.startSN;
  29975. const isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;
  29976. if (remuxResult.independent !== false) {
  29977. const {
  29978. startPTS,
  29979. endPTS,
  29980. startDTS,
  29981. endDTS
  29982. } = video;
  29983. if (part) {
  29984. part.elementaryStreams[video.type] = {
  29985. startPTS,
  29986. endPTS,
  29987. startDTS,
  29988. endDTS
  29989. };
  29990. } else {
  29991. if (video.firstKeyFrame && video.independent && chunkMeta.id === 1 && !isFirstInDiscontinuity) {
  29992. this.couldBacktrack = true;
  29993. }
  29994. if (video.dropped && video.independent) {
  29995. const bufferInfo = this.getMainFwdBufferInfo();
  29996. const targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole;
  29997. const startTime = video.firstKeyFramePTS ? video.firstKeyFramePTS : startPTS;
  29998. if (!isFirstFragment && targetBufferTime < startTime - this.config.maxBufferHole && !isFirstInDiscontinuity) {
  29999. this.backtrack(frag);
  30000. return;
  30001. } else if (isFirstInDiscontinuity) {
  30002. frag.gap = true;
  30003. }
  30004. frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
  30005. } else if (isFirstFragment && startPTS - (details.appliedTimelineOffset || 0) > MAX_START_GAP_JUMP) {
  30006. frag.gap = true;
  30007. }
  30008. }
  30009. frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
  30010. if (this.backtrackFragment) {
  30011. this.backtrackFragment = frag;
  30012. }
  30013. this.bufferFragmentData(video, frag, part, chunkMeta, isFirstFragment || isFirstInDiscontinuity);
  30014. } else if (isFirstFragment || isFirstInDiscontinuity) {
  30015. frag.gap = true;
  30016. } else {
  30017. this.backtrack(frag);
  30018. return;
  30019. }
  30020. }
  30021. if (audio) {
  30022. const {
  30023. startPTS,
  30024. endPTS,
  30025. startDTS,
  30026. endDTS
  30027. } = audio;
  30028. if (part) {
  30029. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  30030. startPTS,
  30031. endPTS,
  30032. startDTS,
  30033. endDTS
  30034. };
  30035. }
  30036. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  30037. this.bufferFragmentData(audio, frag, part, chunkMeta);
  30038. }
  30039. if (details && id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  30040. const emittedID3 = {
  30041. id,
  30042. frag,
  30043. details,
  30044. samples: id3.samples
  30045. };
  30046. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  30047. }
  30048. if (details && text) {
  30049. const emittedText = {
  30050. id,
  30051. frag,
  30052. details,
  30053. samples: text.samples
  30054. };
  30055. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  30056. }
  30057. }
  30058. logMuxedErr(frag) {
  30059. this.warn(`${isMediaFragment(frag) ? "Media" : "Init"} segment with muxed audiovideo where only video expected: ${frag.url}`);
  30060. }
  30061. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  30062. if (this.state !== State.PARSING) {
  30063. return;
  30064. }
  30065. this.audioOnly = !!tracks.audio && !tracks.video;
  30066. if (this.altAudio && !this.audioOnly) {
  30067. delete tracks.audio;
  30068. if (tracks.audiovideo) {
  30069. this.logMuxedErr(frag);
  30070. }
  30071. }
  30072. const {
  30073. audio,
  30074. video,
  30075. audiovideo
  30076. } = tracks;
  30077. if (audio) {
  30078. const levelCodec = currentLevel.audioCodec;
  30079. let audioCodec = pickMostCompleteCodecName(audio.codec, levelCodec);
  30080. if (audioCodec === "mp4a") {
  30081. audioCodec = "mp4a.40.5";
  30082. }
  30083. const ua = navigator.userAgent.toLowerCase();
  30084. if (this.audioCodecSwitch) {
  30085. if (audioCodec) {
  30086. if (audioCodec.indexOf("mp4a.40.5") !== -1) {
  30087. audioCodec = "mp4a.40.2";
  30088. } else {
  30089. audioCodec = "mp4a.40.5";
  30090. }
  30091. }
  30092. const audioMetadata = audio.metadata;
  30093. if (audioMetadata && "channelCount" in audioMetadata && (audioMetadata.channelCount || 1) !== 1 && ua.indexOf("firefox") === -1) {
  30094. audioCodec = "mp4a.40.5";
  30095. }
  30096. }
  30097. if (audioCodec && audioCodec.indexOf("mp4a.40.5") !== -1 && ua.indexOf("android") !== -1 && audio.container !== "audio/mpeg") {
  30098. audioCodec = "mp4a.40.2";
  30099. this.log(`Android: force audio codec to ${audioCodec}`);
  30100. }
  30101. if (levelCodec && levelCodec !== audioCodec) {
  30102. this.log(`Swapping manifest audio codec "${levelCodec}" for "${audioCodec}"`);
  30103. }
  30104. audio.levelCodec = audioCodec;
  30105. audio.id = PlaylistLevelType.MAIN;
  30106. this.log(`Init audio buffer, container:${audio.container}, codecs[selected/level/parsed]=[${audioCodec || ""}/${levelCodec || ""}/${audio.codec}]`);
  30107. delete tracks.audiovideo;
  30108. }
  30109. if (video) {
  30110. video.levelCodec = currentLevel.videoCodec;
  30111. video.id = PlaylistLevelType.MAIN;
  30112. const parsedVideoCodec = video.codec;
  30113. if ((parsedVideoCodec == null ? void 0 : parsedVideoCodec.length) === 4) {
  30114. switch (parsedVideoCodec) {
  30115. case "hvc1":
  30116. case "hev1":
  30117. video.codec = "hvc1.1.6.L120.90";
  30118. break;
  30119. case "av01":
  30120. video.codec = "av01.0.04M.08";
  30121. break;
  30122. case "avc1":
  30123. video.codec = "avc1.42e01e";
  30124. break;
  30125. }
  30126. }
  30127. this.log(`Init video buffer, container:${video.container}, codecs[level/parsed]=[${currentLevel.videoCodec || ""}/${parsedVideoCodec}]${video.codec !== parsedVideoCodec ? " parsed-corrected=" + video.codec : ""}${video.supplemental ? " supplemental=" + video.supplemental : ""}`);
  30128. delete tracks.audiovideo;
  30129. }
  30130. if (audiovideo) {
  30131. this.log(`Init audiovideo buffer, container:${audiovideo.container}, codecs[level/parsed]=[${currentLevel.codecs}/${audiovideo.codec}]`);
  30132. delete tracks.video;
  30133. delete tracks.audio;
  30134. }
  30135. const trackTypes = Object.keys(tracks);
  30136. if (trackTypes.length) {
  30137. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  30138. if (!this.hls) {
  30139. return;
  30140. }
  30141. trackTypes.forEach((trackName) => {
  30142. const track = tracks[trackName];
  30143. const initSegment = track.initSegment;
  30144. if (initSegment != null && initSegment.byteLength) {
  30145. this.hls.trigger(Events.BUFFER_APPENDING, {
  30146. type: trackName,
  30147. data: initSegment,
  30148. frag,
  30149. part: null,
  30150. chunkMeta,
  30151. parent: frag.type
  30152. });
  30153. }
  30154. });
  30155. }
  30156. this.tickImmediate();
  30157. }
  30158. getMainFwdBufferInfo() {
  30159. const bufferOutput = this.mediaBuffer && this.altAudio === 2 ? this.mediaBuffer : this.media;
  30160. return this.getFwdBufferInfo(bufferOutput, PlaylistLevelType.MAIN);
  30161. }
  30162. get maxBufferLength() {
  30163. const {
  30164. levels,
  30165. level
  30166. } = this;
  30167. const levelInfo = levels == null ? void 0 : levels[level];
  30168. if (!levelInfo) {
  30169. return this.config.maxBufferLength;
  30170. }
  30171. return this.getMaxBufferLength(levelInfo.maxBitrate);
  30172. }
  30173. backtrack(frag) {
  30174. this.couldBacktrack = true;
  30175. this.backtrackFragment = frag;
  30176. this.resetTransmuxer();
  30177. this.flushBufferGap(frag);
  30178. this.fragmentTracker.removeFragment(frag);
  30179. this.fragPrevious = null;
  30180. this.nextLoadPosition = frag.start;
  30181. this.state = State.IDLE;
  30182. }
  30183. checkFragmentChanged() {
  30184. const video = this.media;
  30185. let fragPlayingCurrent = null;
  30186. if (video && video.readyState > 1 && video.seeking === false) {
  30187. const currentTime = video.currentTime;
  30188. if (BufferHelper.isBuffered(video, currentTime)) {
  30189. fragPlayingCurrent = this.getAppendedFrag(currentTime);
  30190. } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
  30191. fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
  30192. }
  30193. if (fragPlayingCurrent) {
  30194. this.backtrackFragment = null;
  30195. const fragPlaying = this.fragPlaying;
  30196. const fragCurrentLevel = fragPlayingCurrent.level;
  30197. if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel) {
  30198. this.fragPlaying = fragPlayingCurrent;
  30199. this.hls.trigger(Events.FRAG_CHANGED, {
  30200. frag: fragPlayingCurrent
  30201. });
  30202. if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
  30203. this.hls.trigger(Events.LEVEL_SWITCHED, {
  30204. level: fragCurrentLevel
  30205. });
  30206. }
  30207. }
  30208. }
  30209. }
  30210. }
  30211. get nextLevel() {
  30212. const frag = this.nextBufferedFrag;
  30213. if (frag) {
  30214. return frag.level;
  30215. }
  30216. return -1;
  30217. }
  30218. get currentFrag() {
  30219. var _this$media3;
  30220. if (this.fragPlaying) {
  30221. return this.fragPlaying;
  30222. }
  30223. const currentTime = ((_this$media3 = this.media) == null ? void 0 : _this$media3.currentTime) || this.lastCurrentTime;
  30224. if (isFiniteNumber(currentTime)) {
  30225. return this.getAppendedFrag(currentTime);
  30226. }
  30227. return null;
  30228. }
  30229. get currentProgramDateTime() {
  30230. var _this$media4;
  30231. const currentTime = ((_this$media4 = this.media) == null ? void 0 : _this$media4.currentTime) || this.lastCurrentTime;
  30232. if (isFiniteNumber(currentTime)) {
  30233. const details = this.getLevelDetails();
  30234. const frag = this.currentFrag || (details ? findFragmentByPTS(null, details.fragments, currentTime) : null);
  30235. if (frag) {
  30236. const programDateTime = frag.programDateTime;
  30237. if (programDateTime !== null) {
  30238. const epocMs = programDateTime + (currentTime - frag.start) * 1e3;
  30239. return new Date(epocMs);
  30240. }
  30241. }
  30242. }
  30243. return null;
  30244. }
  30245. get currentLevel() {
  30246. const frag = this.currentFrag;
  30247. if (frag) {
  30248. return frag.level;
  30249. }
  30250. return -1;
  30251. }
  30252. get nextBufferedFrag() {
  30253. const frag = this.currentFrag;
  30254. if (frag) {
  30255. return this.followingBufferedFrag(frag);
  30256. }
  30257. return null;
  30258. }
  30259. get forceStartLoad() {
  30260. return this._forceStartLoad;
  30261. }
  30262. };
  30263. var KeyLoader = class {
  30264. constructor(config) {
  30265. this.config = void 0;
  30266. this.keyUriToKeyInfo = {};
  30267. this.emeController = null;
  30268. this.config = config;
  30269. }
  30270. abort(type) {
  30271. for (const uri in this.keyUriToKeyInfo) {
  30272. const loader = this.keyUriToKeyInfo[uri].loader;
  30273. if (loader) {
  30274. var _loader$context;
  30275. if (type && type !== ((_loader$context = loader.context) == null ? void 0 : _loader$context.frag.type)) {
  30276. return;
  30277. }
  30278. loader.abort();
  30279. }
  30280. }
  30281. }
  30282. detach() {
  30283. for (const uri in this.keyUriToKeyInfo) {
  30284. const keyInfo = this.keyUriToKeyInfo[uri];
  30285. if (keyInfo.mediaKeySessionContext || keyInfo.decryptdata.isCommonEncryption) {
  30286. delete this.keyUriToKeyInfo[uri];
  30287. }
  30288. }
  30289. }
  30290. destroy() {
  30291. this.detach();
  30292. for (const uri in this.keyUriToKeyInfo) {
  30293. const loader = this.keyUriToKeyInfo[uri].loader;
  30294. if (loader) {
  30295. loader.destroy();
  30296. }
  30297. }
  30298. this.keyUriToKeyInfo = {};
  30299. }
  30300. createKeyLoadError(frag, details = ErrorDetails.KEY_LOAD_ERROR, error, networkDetails, response) {
  30301. return new LoadError({
  30302. type: ErrorTypes.NETWORK_ERROR,
  30303. details,
  30304. fatal: false,
  30305. frag,
  30306. response,
  30307. error,
  30308. networkDetails
  30309. });
  30310. }
  30311. loadClear(loadingFrag, encryptedFragments, startFragRequested) {
  30312. if (this.emeController && this.config.emeEnabled && !this.emeController.getSelectedKeySystemFormats().length) {
  30313. if (encryptedFragments.length) {
  30314. for (let i = 0, l = encryptedFragments.length; i < l; i++) {
  30315. const frag = encryptedFragments[i];
  30316. if (loadingFrag.cc <= frag.cc && (!isMediaFragment(loadingFrag) || !isMediaFragment(frag) || loadingFrag.sn < frag.sn) || !startFragRequested && i == l - 1) {
  30317. return this.emeController.selectKeySystemFormat(frag).then((keySystemFormat) => {
  30318. if (!this.emeController) {
  30319. return;
  30320. }
  30321. frag.setKeyFormat(keySystemFormat);
  30322. const keySystem = keySystemFormatToKeySystemDomain(keySystemFormat);
  30323. if (keySystem) {
  30324. return this.emeController.getKeySystemAccess([keySystem]);
  30325. }
  30326. });
  30327. }
  30328. }
  30329. }
  30330. if (this.config.requireKeySystemAccessOnStart) {
  30331. const keySystemsInConfig = getKeySystemsForConfig(this.config);
  30332. if (keySystemsInConfig.length) {
  30333. return this.emeController.getKeySystemAccess(keySystemsInConfig);
  30334. }
  30335. }
  30336. }
  30337. return null;
  30338. }
  30339. load(frag) {
  30340. if (!frag.decryptdata && frag.encrypted && this.emeController && this.config.emeEnabled) {
  30341. return this.emeController.selectKeySystemFormat(frag).then((keySystemFormat) => {
  30342. return this.loadInternal(frag, keySystemFormat);
  30343. });
  30344. }
  30345. return this.loadInternal(frag);
  30346. }
  30347. loadInternal(frag, keySystemFormat) {
  30348. var _keyInfo, _keyInfo2;
  30349. if (keySystemFormat) {
  30350. frag.setKeyFormat(keySystemFormat);
  30351. }
  30352. const decryptdata = frag.decryptdata;
  30353. if (!decryptdata) {
  30354. const error = new Error(keySystemFormat ? `Expected frag.decryptdata to be defined after setting format ${keySystemFormat}` : "Missing decryption data on fragment in onKeyLoading");
  30355. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error));
  30356. }
  30357. const uri = decryptdata.uri;
  30358. if (!uri) {
  30359. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Invalid key URI: "${uri}"`)));
  30360. }
  30361. let keyInfo = this.keyUriToKeyInfo[uri];
  30362. if ((_keyInfo = keyInfo) != null && _keyInfo.decryptdata.key) {
  30363. decryptdata.key = keyInfo.decryptdata.key;
  30364. return Promise.resolve({
  30365. frag,
  30366. keyInfo
  30367. });
  30368. }
  30369. if ((_keyInfo2 = keyInfo) != null && _keyInfo2.keyLoadPromise) {
  30370. var _keyInfo$mediaKeySess;
  30371. switch ((_keyInfo$mediaKeySess = keyInfo.mediaKeySessionContext) == null ? void 0 : _keyInfo$mediaKeySess.keyStatus) {
  30372. case void 0:
  30373. case "status-pending":
  30374. case "usable":
  30375. case "usable-in-future":
  30376. return keyInfo.keyLoadPromise.then((keyLoadedData) => {
  30377. decryptdata.key = keyLoadedData.keyInfo.decryptdata.key;
  30378. return {
  30379. frag,
  30380. keyInfo
  30381. };
  30382. });
  30383. }
  30384. }
  30385. keyInfo = this.keyUriToKeyInfo[uri] = {
  30386. decryptdata,
  30387. keyLoadPromise: null,
  30388. loader: null,
  30389. mediaKeySessionContext: null
  30390. };
  30391. switch (decryptdata.method) {
  30392. case "ISO-23001-7":
  30393. case "SAMPLE-AES":
  30394. case "SAMPLE-AES-CENC":
  30395. case "SAMPLE-AES-CTR":
  30396. if (decryptdata.keyFormat === "identity") {
  30397. return this.loadKeyHTTP(keyInfo, frag);
  30398. }
  30399. return this.loadKeyEME(keyInfo, frag);
  30400. case "AES-128":
  30401. case "AES-256":
  30402. case "AES-256-CTR":
  30403. return this.loadKeyHTTP(keyInfo, frag);
  30404. default:
  30405. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Key supplied with unsupported METHOD: "${decryptdata.method}"`)));
  30406. }
  30407. }
  30408. loadKeyEME(keyInfo, frag) {
  30409. const keyLoadedData = {
  30410. frag,
  30411. keyInfo
  30412. };
  30413. if (this.emeController && this.config.emeEnabled) {
  30414. const keySessionContextPromise = this.emeController.loadKey(keyLoadedData);
  30415. if (keySessionContextPromise) {
  30416. return (keyInfo.keyLoadPromise = keySessionContextPromise.then((keySessionContext) => {
  30417. keyInfo.mediaKeySessionContext = keySessionContext;
  30418. return keyLoadedData;
  30419. })).catch((error) => {
  30420. keyInfo.keyLoadPromise = null;
  30421. throw error;
  30422. });
  30423. }
  30424. }
  30425. return Promise.resolve(keyLoadedData);
  30426. }
  30427. loadKeyHTTP(keyInfo, frag) {
  30428. const config = this.config;
  30429. const Loader = config.loader;
  30430. const keyLoader = new Loader(config);
  30431. frag.keyLoader = keyInfo.loader = keyLoader;
  30432. return keyInfo.keyLoadPromise = new Promise((resolve, reject) => {
  30433. const loaderContext = {
  30434. keyInfo,
  30435. frag,
  30436. responseType: "arraybuffer",
  30437. url: keyInfo.decryptdata.uri
  30438. };
  30439. const loadPolicy = config.keyLoadPolicy.default;
  30440. const loaderConfig = {
  30441. loadPolicy,
  30442. timeout: loadPolicy.maxLoadTimeMs,
  30443. maxRetry: 0,
  30444. retryDelay: 0,
  30445. maxRetryDelay: 0
  30446. };
  30447. const loaderCallbacks = {
  30448. onSuccess: (response, stats, context, networkDetails) => {
  30449. const {
  30450. frag: frag2,
  30451. keyInfo: keyInfo2,
  30452. url: uri
  30453. } = context;
  30454. if (!frag2.decryptdata || keyInfo2 !== this.keyUriToKeyInfo[uri]) {
  30455. return reject(this.createKeyLoadError(frag2, ErrorDetails.KEY_LOAD_ERROR, new Error("after key load, decryptdata unset or changed"), networkDetails));
  30456. }
  30457. keyInfo2.decryptdata.key = frag2.decryptdata.key = new Uint8Array(response.data);
  30458. frag2.keyLoader = null;
  30459. keyInfo2.loader = null;
  30460. resolve({
  30461. frag: frag2,
  30462. keyInfo: keyInfo2
  30463. });
  30464. },
  30465. onError: (response, context, networkDetails, stats) => {
  30466. this.resetLoader(context);
  30467. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`HTTP Error ${response.code} loading key ${response.text}`), networkDetails, _objectSpread2({
  30468. url: loaderContext.url,
  30469. data: void 0
  30470. }, response)));
  30471. },
  30472. onTimeout: (stats, context, networkDetails) => {
  30473. this.resetLoader(context);
  30474. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_TIMEOUT, new Error("key loading timed out"), networkDetails));
  30475. },
  30476. onAbort: (stats, context, networkDetails) => {
  30477. this.resetLoader(context);
  30478. reject(this.createKeyLoadError(frag, ErrorDetails.INTERNAL_ABORTED, new Error("key loading aborted"), networkDetails));
  30479. }
  30480. };
  30481. keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  30482. });
  30483. }
  30484. resetLoader(context) {
  30485. const {
  30486. frag,
  30487. keyInfo,
  30488. url: uri
  30489. } = context;
  30490. const loader = keyInfo.loader;
  30491. if (frag.keyLoader === loader) {
  30492. frag.keyLoader = null;
  30493. keyInfo.loader = null;
  30494. }
  30495. delete this.keyUriToKeyInfo[uri];
  30496. if (loader) {
  30497. loader.destroy();
  30498. }
  30499. }
  30500. };
  30501. function mapContextToLevelType(context) {
  30502. const {
  30503. type
  30504. } = context;
  30505. switch (type) {
  30506. case PlaylistContextType.AUDIO_TRACK:
  30507. return PlaylistLevelType.AUDIO;
  30508. case PlaylistContextType.SUBTITLE_TRACK:
  30509. return PlaylistLevelType.SUBTITLE;
  30510. default:
  30511. return PlaylistLevelType.MAIN;
  30512. }
  30513. }
  30514. function getResponseUrl(response, context) {
  30515. let url = response.url;
  30516. if (url === void 0 || url.indexOf("data:") === 0) {
  30517. url = context.url;
  30518. }
  30519. return url;
  30520. }
  30521. var PlaylistLoader = class {
  30522. constructor(hls) {
  30523. this.hls = void 0;
  30524. this.loaders = /* @__PURE__ */ Object.create(null);
  30525. this.variableList = null;
  30526. this.onManifestLoaded = this.checkAutostartLoad;
  30527. this.hls = hls;
  30528. this.registerListeners();
  30529. }
  30530. startLoad(startPosition) {
  30531. }
  30532. stopLoad() {
  30533. this.destroyInternalLoaders();
  30534. }
  30535. registerListeners() {
  30536. const {
  30537. hls
  30538. } = this;
  30539. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  30540. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  30541. hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  30542. hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  30543. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  30544. }
  30545. unregisterListeners() {
  30546. const {
  30547. hls
  30548. } = this;
  30549. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  30550. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  30551. hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  30552. hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  30553. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  30554. }
  30555. /**
  30556. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  30557. */
  30558. createInternalLoader(context) {
  30559. const config = this.hls.config;
  30560. const PLoader = config.pLoader;
  30561. const Loader = config.loader;
  30562. const InternalLoader = PLoader || Loader;
  30563. const loader = new InternalLoader(config);
  30564. this.loaders[context.type] = loader;
  30565. return loader;
  30566. }
  30567. getInternalLoader(context) {
  30568. return this.loaders[context.type];
  30569. }
  30570. resetInternalLoader(contextType) {
  30571. if (this.loaders[contextType]) {
  30572. delete this.loaders[contextType];
  30573. }
  30574. }
  30575. /**
  30576. * Call `destroy` on all internal loader instances mapped (one per context type)
  30577. */
  30578. destroyInternalLoaders() {
  30579. for (const contextType in this.loaders) {
  30580. const loader = this.loaders[contextType];
  30581. if (loader) {
  30582. loader.destroy();
  30583. }
  30584. this.resetInternalLoader(contextType);
  30585. }
  30586. }
  30587. destroy() {
  30588. this.variableList = null;
  30589. this.unregisterListeners();
  30590. this.destroyInternalLoaders();
  30591. }
  30592. onManifestLoading(event, data) {
  30593. const {
  30594. url
  30595. } = data;
  30596. this.variableList = null;
  30597. this.load({
  30598. id: null,
  30599. level: 0,
  30600. responseType: "text",
  30601. type: PlaylistContextType.MANIFEST,
  30602. url,
  30603. deliveryDirectives: null,
  30604. levelOrTrack: null
  30605. });
  30606. }
  30607. onLevelLoading(event, data) {
  30608. const {
  30609. id,
  30610. level,
  30611. pathwayId,
  30612. url,
  30613. deliveryDirectives,
  30614. levelInfo
  30615. } = data;
  30616. this.load({
  30617. id,
  30618. level,
  30619. pathwayId,
  30620. responseType: "text",
  30621. type: PlaylistContextType.LEVEL,
  30622. url,
  30623. deliveryDirectives,
  30624. levelOrTrack: levelInfo
  30625. });
  30626. }
  30627. onAudioTrackLoading(event, data) {
  30628. const {
  30629. id,
  30630. groupId,
  30631. url,
  30632. deliveryDirectives,
  30633. track
  30634. } = data;
  30635. this.load({
  30636. id,
  30637. groupId,
  30638. level: null,
  30639. responseType: "text",
  30640. type: PlaylistContextType.AUDIO_TRACK,
  30641. url,
  30642. deliveryDirectives,
  30643. levelOrTrack: track
  30644. });
  30645. }
  30646. onSubtitleTrackLoading(event, data) {
  30647. const {
  30648. id,
  30649. groupId,
  30650. url,
  30651. deliveryDirectives,
  30652. track
  30653. } = data;
  30654. this.load({
  30655. id,
  30656. groupId,
  30657. level: null,
  30658. responseType: "text",
  30659. type: PlaylistContextType.SUBTITLE_TRACK,
  30660. url,
  30661. deliveryDirectives,
  30662. levelOrTrack: track
  30663. });
  30664. }
  30665. onLevelsUpdated(event, data) {
  30666. const loader = this.loaders[PlaylistContextType.LEVEL];
  30667. if (loader) {
  30668. const context = loader.context;
  30669. if (context && !data.levels.some((lvl) => lvl === context.levelOrTrack)) {
  30670. loader.abort();
  30671. delete this.loaders[PlaylistContextType.LEVEL];
  30672. }
  30673. }
  30674. }
  30675. load(context) {
  30676. var _context$deliveryDire;
  30677. const config = this.hls.config;
  30678. let loader = this.getInternalLoader(context);
  30679. if (loader) {
  30680. const logger2 = this.hls.logger;
  30681. const loaderContext = loader.context;
  30682. if (loaderContext && loaderContext.levelOrTrack === context.levelOrTrack && (loaderContext.url === context.url || loaderContext.deliveryDirectives && !context.deliveryDirectives)) {
  30683. if (loaderContext.url === context.url) {
  30684. logger2.log(`[playlist-loader]: ignore ${context.url} ongoing request`);
  30685. } else {
  30686. logger2.log(`[playlist-loader]: ignore ${context.url} in favor of ${loaderContext.url}`);
  30687. }
  30688. return;
  30689. }
  30690. logger2.log(`[playlist-loader]: aborting previous loader for type: ${context.type}`);
  30691. loader.abort();
  30692. }
  30693. let loadPolicy;
  30694. if (context.type === PlaylistContextType.MANIFEST) {
  30695. loadPolicy = config.manifestLoadPolicy.default;
  30696. } else {
  30697. loadPolicy = _extends({}, config.playlistLoadPolicy.default, {
  30698. timeoutRetry: null,
  30699. errorRetry: null
  30700. });
  30701. }
  30702. loader = this.createInternalLoader(context);
  30703. if (isFiniteNumber((_context$deliveryDire = context.deliveryDirectives) == null ? void 0 : _context$deliveryDire.part)) {
  30704. let levelDetails;
  30705. if (context.type === PlaylistContextType.LEVEL && context.level !== null) {
  30706. levelDetails = this.hls.levels[context.level].details;
  30707. } else if (context.type === PlaylistContextType.AUDIO_TRACK && context.id !== null) {
  30708. levelDetails = this.hls.audioTracks[context.id].details;
  30709. } else if (context.type === PlaylistContextType.SUBTITLE_TRACK && context.id !== null) {
  30710. levelDetails = this.hls.subtitleTracks[context.id].details;
  30711. }
  30712. if (levelDetails) {
  30713. const partTarget = levelDetails.partTarget;
  30714. const targetDuration = levelDetails.targetduration;
  30715. if (partTarget && targetDuration) {
  30716. const maxLowLatencyPlaylistRefresh = Math.max(partTarget * 3, targetDuration * 0.8) * 1e3;
  30717. loadPolicy = _extends({}, loadPolicy, {
  30718. maxTimeToFirstByteMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs),
  30719. maxLoadTimeMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs)
  30720. });
  30721. }
  30722. }
  30723. }
  30724. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  30725. const loaderConfig = {
  30726. loadPolicy,
  30727. timeout: loadPolicy.maxLoadTimeMs,
  30728. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  30729. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  30730. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  30731. };
  30732. const loaderCallbacks = {
  30733. onSuccess: (response, stats, context2, networkDetails) => {
  30734. const loader2 = this.getInternalLoader(context2);
  30735. this.resetInternalLoader(context2.type);
  30736. const string = response.data;
  30737. if (string.indexOf("#EXTM3U") !== 0) {
  30738. this.handleManifestParsingError(response, context2, new Error("no EXTM3U delimiter"), networkDetails || null, stats);
  30739. return;
  30740. }
  30741. stats.parsing.start = performance.now();
  30742. if (M3U8Parser.isMediaPlaylist(string) || context2.type !== PlaylistContextType.MANIFEST) {
  30743. this.handleTrackOrLevelPlaylist(response, stats, context2, networkDetails || null, loader2);
  30744. } else {
  30745. this.handleMasterPlaylist(response, stats, context2, networkDetails);
  30746. }
  30747. },
  30748. onError: (response, context2, networkDetails, stats) => {
  30749. this.handleNetworkError(context2, networkDetails, false, response, stats);
  30750. },
  30751. onTimeout: (stats, context2, networkDetails) => {
  30752. this.handleNetworkError(context2, networkDetails, true, void 0, stats);
  30753. }
  30754. };
  30755. loader.load(context, loaderConfig, loaderCallbacks);
  30756. }
  30757. checkAutostartLoad() {
  30758. if (!this.hls) {
  30759. return;
  30760. }
  30761. const {
  30762. config: {
  30763. autoStartLoad,
  30764. startPosition
  30765. },
  30766. forceStartLoad
  30767. } = this.hls;
  30768. if (autoStartLoad || forceStartLoad) {
  30769. this.hls.logger.log(`${autoStartLoad ? "auto" : "force"} startLoad with configured startPosition ${startPosition}`);
  30770. this.hls.startLoad(startPosition);
  30771. }
  30772. }
  30773. handleMasterPlaylist(response, stats, context, networkDetails) {
  30774. const hls = this.hls;
  30775. const string = response.data;
  30776. const url = getResponseUrl(response, context);
  30777. const parsedResult = M3U8Parser.parseMasterPlaylist(string, url);
  30778. if (parsedResult.playlistParsingError) {
  30779. this.handleManifestParsingError(response, context, parsedResult.playlistParsingError, networkDetails, stats);
  30780. return;
  30781. }
  30782. const {
  30783. contentSteering,
  30784. levels,
  30785. sessionData,
  30786. sessionKeys,
  30787. startTimeOffset,
  30788. variableList
  30789. } = parsedResult;
  30790. this.variableList = variableList;
  30791. const {
  30792. AUDIO: audioTracks = [],
  30793. SUBTITLES: subtitles,
  30794. "CLOSED-CAPTIONS": captions
  30795. } = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult);
  30796. if (audioTracks.length) {
  30797. const embeddedAudioFound = audioTracks.some((audioTrack) => !audioTrack.url);
  30798. if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  30799. this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one");
  30800. audioTracks.unshift({
  30801. type: "main",
  30802. name: "main",
  30803. groupId: "main",
  30804. default: false,
  30805. autoselect: false,
  30806. forced: false,
  30807. id: -1,
  30808. attrs: new AttrList({}),
  30809. bitrate: 0,
  30810. url: ""
  30811. });
  30812. }
  30813. }
  30814. hls.trigger(Events.MANIFEST_LOADED, {
  30815. levels,
  30816. audioTracks,
  30817. subtitles,
  30818. captions,
  30819. contentSteering,
  30820. url,
  30821. stats,
  30822. networkDetails,
  30823. sessionData,
  30824. sessionKeys,
  30825. startTimeOffset,
  30826. variableList
  30827. });
  30828. }
  30829. handleTrackOrLevelPlaylist(response, stats, context, networkDetails, loader) {
  30830. const hls = this.hls;
  30831. const {
  30832. id,
  30833. level,
  30834. type
  30835. } = context;
  30836. const url = getResponseUrl(response, context);
  30837. const levelId = isFiniteNumber(level) ? level : isFiniteNumber(id) ? id : 0;
  30838. const levelType = mapContextToLevelType(context);
  30839. const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, 0, this.variableList);
  30840. if (type === PlaylistContextType.MANIFEST) {
  30841. const singleLevel = {
  30842. attrs: new AttrList({}),
  30843. bitrate: 0,
  30844. details: levelDetails,
  30845. name: "",
  30846. url
  30847. };
  30848. levelDetails.requestScheduled = stats.loading.start + computeReloadInterval(levelDetails, 0);
  30849. hls.trigger(Events.MANIFEST_LOADED, {
  30850. levels: [singleLevel],
  30851. audioTracks: [],
  30852. url,
  30853. stats,
  30854. networkDetails,
  30855. sessionData: null,
  30856. sessionKeys: null,
  30857. contentSteering: null,
  30858. startTimeOffset: null,
  30859. variableList: null
  30860. });
  30861. }
  30862. stats.parsing.end = performance.now();
  30863. context.levelDetails = levelDetails;
  30864. this.handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader);
  30865. }
  30866. handleManifestParsingError(response, context, error, networkDetails, stats) {
  30867. this.hls.trigger(Events.ERROR, {
  30868. type: ErrorTypes.NETWORK_ERROR,
  30869. details: ErrorDetails.MANIFEST_PARSING_ERROR,
  30870. fatal: context.type === PlaylistContextType.MANIFEST,
  30871. url: response.url,
  30872. err: error,
  30873. error,
  30874. reason: error.message,
  30875. response,
  30876. context,
  30877. networkDetails,
  30878. stats
  30879. });
  30880. }
  30881. handleNetworkError(context, networkDetails, timeout = false, response, stats) {
  30882. let message = `A network ${timeout ? "timeout" : "error" + (response ? " (status " + response.code + ")" : "")} occurred while loading ${context.type}`;
  30883. if (context.type === PlaylistContextType.LEVEL) {
  30884. message += `: ${context.level} id: ${context.id}`;
  30885. } else if (context.type === PlaylistContextType.AUDIO_TRACK || context.type === PlaylistContextType.SUBTITLE_TRACK) {
  30886. message += ` id: ${context.id} group-id: "${context.groupId}"`;
  30887. }
  30888. const error = new Error(message);
  30889. this.hls.logger.warn(`[playlist-loader]: ${message}`);
  30890. let details = ErrorDetails.UNKNOWN;
  30891. let fatal = false;
  30892. const loader = this.getInternalLoader(context);
  30893. switch (context.type) {
  30894. case PlaylistContextType.MANIFEST:
  30895. details = timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR;
  30896. fatal = true;
  30897. break;
  30898. case PlaylistContextType.LEVEL:
  30899. details = timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR;
  30900. fatal = false;
  30901. break;
  30902. case PlaylistContextType.AUDIO_TRACK:
  30903. details = timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  30904. fatal = false;
  30905. break;
  30906. case PlaylistContextType.SUBTITLE_TRACK:
  30907. details = timeout ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_LOAD_ERROR;
  30908. fatal = false;
  30909. break;
  30910. }
  30911. if (loader) {
  30912. this.resetInternalLoader(context.type);
  30913. }
  30914. const errorData = {
  30915. type: ErrorTypes.NETWORK_ERROR,
  30916. details,
  30917. fatal,
  30918. url: context.url,
  30919. loader,
  30920. context,
  30921. error,
  30922. networkDetails,
  30923. stats
  30924. };
  30925. if (response) {
  30926. const url = (networkDetails == null ? void 0 : networkDetails.url) || context.url;
  30927. errorData.response = _objectSpread2({
  30928. url,
  30929. data: void 0
  30930. }, response);
  30931. }
  30932. this.hls.trigger(Events.ERROR, errorData);
  30933. }
  30934. handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader) {
  30935. const hls = this.hls;
  30936. const {
  30937. type,
  30938. level,
  30939. id,
  30940. groupId,
  30941. deliveryDirectives
  30942. } = context;
  30943. const url = getResponseUrl(response, context);
  30944. const parent = mapContextToLevelType(context);
  30945. const levelIndex = typeof context.level === "number" && parent === PlaylistLevelType.MAIN ? level : void 0;
  30946. if (!levelDetails.fragments.length) {
  30947. const _error = levelDetails.playlistParsingError = new Error("No Segments found in Playlist");
  30948. hls.trigger(Events.ERROR, {
  30949. type: ErrorTypes.NETWORK_ERROR,
  30950. details: ErrorDetails.LEVEL_EMPTY_ERROR,
  30951. fatal: false,
  30952. url,
  30953. error: _error,
  30954. reason: _error.message,
  30955. response,
  30956. context,
  30957. level: levelIndex,
  30958. parent,
  30959. networkDetails,
  30960. stats
  30961. });
  30962. return;
  30963. }
  30964. if (!levelDetails.targetduration) {
  30965. levelDetails.playlistParsingError = new Error("Missing Target Duration");
  30966. }
  30967. const error = levelDetails.playlistParsingError;
  30968. if (error) {
  30969. this.hls.logger.warn(error);
  30970. if (!hls.config.ignorePlaylistParsingErrors) {
  30971. hls.trigger(Events.ERROR, {
  30972. type: ErrorTypes.NETWORK_ERROR,
  30973. details: ErrorDetails.LEVEL_PARSING_ERROR,
  30974. fatal: false,
  30975. url,
  30976. error,
  30977. reason: error.message,
  30978. response,
  30979. context,
  30980. level: levelIndex,
  30981. parent,
  30982. networkDetails,
  30983. stats
  30984. });
  30985. return;
  30986. }
  30987. levelDetails.playlistParsingError = null;
  30988. }
  30989. if (levelDetails.live && loader) {
  30990. if (loader.getCacheAge) {
  30991. levelDetails.ageHeader = loader.getCacheAge() || 0;
  30992. }
  30993. if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
  30994. levelDetails.ageHeader = 0;
  30995. }
  30996. }
  30997. switch (type) {
  30998. case PlaylistContextType.MANIFEST:
  30999. case PlaylistContextType.LEVEL:
  31000. hls.trigger(Events.LEVEL_LOADED, {
  31001. details: levelDetails,
  31002. levelInfo: context.levelOrTrack || hls.levels[0],
  31003. level: levelIndex || 0,
  31004. id: id || 0,
  31005. stats,
  31006. networkDetails,
  31007. deliveryDirectives,
  31008. withoutMultiVariant: type === PlaylistContextType.MANIFEST
  31009. });
  31010. break;
  31011. case PlaylistContextType.AUDIO_TRACK:
  31012. hls.trigger(Events.AUDIO_TRACK_LOADED, {
  31013. details: levelDetails,
  31014. track: context.levelOrTrack,
  31015. id: id || 0,
  31016. groupId: groupId || "",
  31017. stats,
  31018. networkDetails,
  31019. deliveryDirectives
  31020. });
  31021. break;
  31022. case PlaylistContextType.SUBTITLE_TRACK:
  31023. hls.trigger(Events.SUBTITLE_TRACK_LOADED, {
  31024. details: levelDetails,
  31025. track: context.levelOrTrack,
  31026. id: id || 0,
  31027. groupId: groupId || "",
  31028. stats,
  31029. networkDetails,
  31030. deliveryDirectives
  31031. });
  31032. break;
  31033. }
  31034. }
  31035. };
  31036. var Hls = class _Hls {
  31037. /**
  31038. * Get the video-dev/hls.js package version.
  31039. */
  31040. static get version() {
  31041. return version;
  31042. }
  31043. /**
  31044. * Check if the required MediaSource Extensions are available.
  31045. */
  31046. static isMSESupported() {
  31047. return isMSESupported();
  31048. }
  31049. /**
  31050. * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.
  31051. */
  31052. static isSupported() {
  31053. return isSupported();
  31054. }
  31055. /**
  31056. * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).
  31057. */
  31058. static getMediaSource() {
  31059. return getMediaSource();
  31060. }
  31061. static get Events() {
  31062. return Events;
  31063. }
  31064. static get MetadataSchema() {
  31065. return MetadataSchema;
  31066. }
  31067. static get ErrorTypes() {
  31068. return ErrorTypes;
  31069. }
  31070. static get ErrorDetails() {
  31071. return ErrorDetails;
  31072. }
  31073. /**
  31074. * Get the default configuration applied to new instances.
  31075. */
  31076. static get DefaultConfig() {
  31077. if (!_Hls.defaultConfig) {
  31078. return hlsDefaultConfig;
  31079. }
  31080. return _Hls.defaultConfig;
  31081. }
  31082. /**
  31083. * Replace the default configuration applied to new instances.
  31084. */
  31085. static set DefaultConfig(defaultConfig) {
  31086. _Hls.defaultConfig = defaultConfig;
  31087. }
  31088. /**
  31089. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  31090. * @param userConfig - Configuration options applied over `Hls.DefaultConfig`
  31091. */
  31092. constructor(userConfig = {}) {
  31093. this.config = void 0;
  31094. this.userConfig = void 0;
  31095. this.logger = void 0;
  31096. this.coreComponents = void 0;
  31097. this.networkControllers = void 0;
  31098. this._emitter = new EventEmitter();
  31099. this._autoLevelCapping = -1;
  31100. this._maxHdcpLevel = null;
  31101. this.abrController = void 0;
  31102. this.bufferController = void 0;
  31103. this.capLevelController = void 0;
  31104. this.latencyController = void 0;
  31105. this.levelController = void 0;
  31106. this.streamController = void 0;
  31107. this.audioStreamController = void 0;
  31108. this.subtititleStreamController = void 0;
  31109. this.audioTrackController = void 0;
  31110. this.subtitleTrackController = void 0;
  31111. this.interstitialsController = void 0;
  31112. this.gapController = void 0;
  31113. this.emeController = void 0;
  31114. this.cmcdController = void 0;
  31115. this._media = null;
  31116. this._url = null;
  31117. this._sessionId = void 0;
  31118. this.triggeringException = void 0;
  31119. this.started = false;
  31120. const logger2 = this.logger = enableLogs(userConfig.debug || false, "Hls instance", userConfig.assetPlayerId);
  31121. const config = this.config = mergeConfig(_Hls.DefaultConfig, userConfig, logger2);
  31122. this.userConfig = userConfig;
  31123. if (config.progressive) {
  31124. enableStreamingMode(config, logger2);
  31125. }
  31126. const {
  31127. abrController: _AbrController,
  31128. bufferController: _BufferController,
  31129. capLevelController: _CapLevelController,
  31130. errorController: _ErrorController,
  31131. fpsController: _FpsController
  31132. } = config;
  31133. const errorController = new _ErrorController(this);
  31134. const abrController = this.abrController = new _AbrController(this);
  31135. const fragmentTracker = new FragmentTracker(this);
  31136. const _InterstitialsController = config.interstitialsController;
  31137. const interstitialsController = _InterstitialsController ? this.interstitialsController = new _InterstitialsController(this, _Hls) : null;
  31138. const bufferController = this.bufferController = new _BufferController(this, fragmentTracker);
  31139. const capLevelController = this.capLevelController = new _CapLevelController(this);
  31140. const fpsController = new _FpsController(this);
  31141. const playListLoader = new PlaylistLoader(this);
  31142. const _ContentSteeringController = config.contentSteeringController;
  31143. const contentSteering = _ContentSteeringController ? new _ContentSteeringController(this) : null;
  31144. const levelController = this.levelController = new LevelController(this, contentSteering);
  31145. const id3TrackController = new ID3TrackController(this);
  31146. const keyLoader = new KeyLoader(this.config);
  31147. const streamController = this.streamController = new StreamController(this, fragmentTracker, keyLoader);
  31148. const gapController = this.gapController = new GapController(this, fragmentTracker);
  31149. capLevelController.setStreamController(streamController);
  31150. fpsController.setStreamController(streamController);
  31151. const networkControllers = [playListLoader, levelController, streamController];
  31152. if (interstitialsController) {
  31153. networkControllers.splice(1, 0, interstitialsController);
  31154. }
  31155. if (contentSteering) {
  31156. networkControllers.splice(1, 0, contentSteering);
  31157. }
  31158. this.networkControllers = networkControllers;
  31159. const coreComponents = [abrController, bufferController, gapController, capLevelController, fpsController, id3TrackController, fragmentTracker];
  31160. this.audioTrackController = this.createController(config.audioTrackController, networkControllers);
  31161. const AudioStreamControllerClass = config.audioStreamController;
  31162. if (AudioStreamControllerClass) {
  31163. networkControllers.push(this.audioStreamController = new AudioStreamControllerClass(this, fragmentTracker, keyLoader));
  31164. }
  31165. this.subtitleTrackController = this.createController(config.subtitleTrackController, networkControllers);
  31166. const SubtitleStreamControllerClass = config.subtitleStreamController;
  31167. if (SubtitleStreamControllerClass) {
  31168. networkControllers.push(this.subtititleStreamController = new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader));
  31169. }
  31170. this.createController(config.timelineController, coreComponents);
  31171. keyLoader.emeController = this.emeController = this.createController(config.emeController, coreComponents);
  31172. this.cmcdController = this.createController(config.cmcdController, coreComponents);
  31173. this.latencyController = this.createController(LatencyController, coreComponents);
  31174. this.coreComponents = coreComponents;
  31175. networkControllers.push(errorController);
  31176. const onErrorOut = errorController.onErrorOut;
  31177. if (typeof onErrorOut === "function") {
  31178. this.on(Events.ERROR, onErrorOut, errorController);
  31179. }
  31180. this.on(Events.MANIFEST_LOADED, playListLoader.onManifestLoaded, playListLoader);
  31181. }
  31182. createController(ControllerClass, components) {
  31183. if (ControllerClass) {
  31184. const controllerInstance = new ControllerClass(this);
  31185. if (components) {
  31186. components.push(controllerInstance);
  31187. }
  31188. return controllerInstance;
  31189. }
  31190. return null;
  31191. }
  31192. // Delegate the EventEmitter through the public API of Hls.js
  31193. on(event, listener, context = this) {
  31194. this._emitter.on(event, listener, context);
  31195. }
  31196. once(event, listener, context = this) {
  31197. this._emitter.once(event, listener, context);
  31198. }
  31199. removeAllListeners(event) {
  31200. this._emitter.removeAllListeners(event);
  31201. }
  31202. off(event, listener, context = this, once) {
  31203. this._emitter.off(event, listener, context, once);
  31204. }
  31205. listeners(event) {
  31206. return this._emitter.listeners(event);
  31207. }
  31208. emit(event, name, eventObject) {
  31209. return this._emitter.emit(event, name, eventObject);
  31210. }
  31211. trigger(event, eventObject) {
  31212. if (this.config.debug) {
  31213. return this.emit(event, event, eventObject);
  31214. } else {
  31215. try {
  31216. return this.emit(event, event, eventObject);
  31217. } catch (error) {
  31218. this.logger.error("An internal error happened while handling event " + event + '. Error message: "' + error.message + '". Here is a stacktrace:', error);
  31219. if (!this.triggeringException) {
  31220. this.triggeringException = true;
  31221. const fatal = event === Events.ERROR;
  31222. this.trigger(Events.ERROR, {
  31223. type: ErrorTypes.OTHER_ERROR,
  31224. details: ErrorDetails.INTERNAL_EXCEPTION,
  31225. fatal,
  31226. event,
  31227. error
  31228. });
  31229. this.triggeringException = false;
  31230. }
  31231. }
  31232. }
  31233. return false;
  31234. }
  31235. listenerCount(event) {
  31236. return this._emitter.listenerCount(event);
  31237. }
  31238. /**
  31239. * Dispose of the instance
  31240. */
  31241. destroy() {
  31242. this.logger.log("destroy");
  31243. this.trigger(Events.DESTROYING, void 0);
  31244. this.detachMedia();
  31245. this.removeAllListeners();
  31246. this._autoLevelCapping = -1;
  31247. this._url = null;
  31248. this.networkControllers.forEach((component) => component.destroy());
  31249. this.networkControllers.length = 0;
  31250. this.coreComponents.forEach((component) => component.destroy());
  31251. this.coreComponents.length = 0;
  31252. const config = this.config;
  31253. config.xhrSetup = config.fetchSetup = void 0;
  31254. this.userConfig = null;
  31255. }
  31256. /**
  31257. * Attaches Hls.js to a media element
  31258. */
  31259. attachMedia(data) {
  31260. if (!data || "media" in data && !data.media) {
  31261. const error = new Error(`attachMedia failed: invalid argument (${data})`);
  31262. this.trigger(Events.ERROR, {
  31263. type: ErrorTypes.OTHER_ERROR,
  31264. details: ErrorDetails.ATTACH_MEDIA_ERROR,
  31265. fatal: true,
  31266. error
  31267. });
  31268. return;
  31269. }
  31270. this.logger.log(`attachMedia`);
  31271. if (this._media) {
  31272. this.logger.warn(`media must be detached before attaching`);
  31273. this.detachMedia();
  31274. }
  31275. const attachMediaSource = "media" in data;
  31276. const media = attachMediaSource ? data.media : data;
  31277. const attachingData = attachMediaSource ? data : {
  31278. media
  31279. };
  31280. this._media = media;
  31281. this.trigger(Events.MEDIA_ATTACHING, attachingData);
  31282. }
  31283. /**
  31284. * Detach Hls.js from the media
  31285. */
  31286. detachMedia() {
  31287. this.logger.log("detachMedia");
  31288. this.trigger(Events.MEDIA_DETACHING, {});
  31289. this._media = null;
  31290. }
  31291. /**
  31292. * Detach HTMLMediaElement, MediaSource, and SourceBuffers without reset, for attaching to another instance
  31293. */
  31294. transferMedia() {
  31295. this._media = null;
  31296. const transferMedia = this.bufferController.transferMedia();
  31297. this.trigger(Events.MEDIA_DETACHING, {
  31298. transferMedia
  31299. });
  31300. return transferMedia;
  31301. }
  31302. /**
  31303. * Set the source URL. Can be relative or absolute.
  31304. */
  31305. loadSource(url) {
  31306. this.stopLoad();
  31307. const media = this.media;
  31308. const loadedSource = this._url;
  31309. const loadingSource = this._url = urlToolkitExports.buildAbsoluteURL(self.location.href, url, {
  31310. alwaysNormalize: true
  31311. });
  31312. this._autoLevelCapping = -1;
  31313. this._maxHdcpLevel = null;
  31314. this.logger.log(`loadSource:${loadingSource}`);
  31315. if (media && loadedSource && (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())) {
  31316. this.detachMedia();
  31317. this.attachMedia(media);
  31318. }
  31319. this.trigger(Events.MANIFEST_LOADING, {
  31320. url
  31321. });
  31322. }
  31323. /**
  31324. * Gets the currently loaded URL
  31325. */
  31326. get url() {
  31327. return this._url;
  31328. }
  31329. /**
  31330. * Whether or not enough has been buffered to seek to start position or use `media.currentTime` to determine next load position
  31331. */
  31332. get hasEnoughToStart() {
  31333. return this.streamController.hasEnoughToStart;
  31334. }
  31335. /**
  31336. * Get the startPosition set on startLoad(position) or on autostart with config.startPosition
  31337. */
  31338. get startPosition() {
  31339. return this.streamController.startPositionValue;
  31340. }
  31341. /**
  31342. * Start loading data from the stream source.
  31343. * Depending on default config, client starts loading automatically when a source is set.
  31344. *
  31345. * @param startPosition - Set the start position to stream from.
  31346. * Defaults to -1 (None: starts from earliest point)
  31347. */
  31348. startLoad(startPosition = -1, skipSeekToStartPosition) {
  31349. this.logger.log(`startLoad(${startPosition + (skipSeekToStartPosition ? ", <skip seek to start>" : "")})`);
  31350. this.started = true;
  31351. this.resumeBuffering();
  31352. for (let i = 0; i < this.networkControllers.length; i++) {
  31353. this.networkControllers[i].startLoad(startPosition, skipSeekToStartPosition);
  31354. if (!this.started || !this.networkControllers) {
  31355. break;
  31356. }
  31357. }
  31358. }
  31359. /**
  31360. * Stop loading of any stream data.
  31361. */
  31362. stopLoad() {
  31363. this.logger.log("stopLoad");
  31364. this.started = false;
  31365. for (let i = 0; i < this.networkControllers.length; i++) {
  31366. this.networkControllers[i].stopLoad();
  31367. if (this.started || !this.networkControllers) {
  31368. break;
  31369. }
  31370. }
  31371. }
  31372. /**
  31373. * Returns whether loading, toggled with `startLoad()` and `stopLoad()`, is active or not`.
  31374. */
  31375. get loadingEnabled() {
  31376. return this.started;
  31377. }
  31378. /**
  31379. * Returns state of fragment loading toggled by calling `pauseBuffering()` and `resumeBuffering()`.
  31380. */
  31381. get bufferingEnabled() {
  31382. return this.streamController.bufferingEnabled;
  31383. }
  31384. /**
  31385. * Resumes stream controller segment loading after `pauseBuffering` has been called.
  31386. */
  31387. resumeBuffering() {
  31388. if (!this.bufferingEnabled) {
  31389. this.logger.log(`resume buffering`);
  31390. this.networkControllers.forEach((controller) => {
  31391. if (controller.resumeBuffering) {
  31392. controller.resumeBuffering();
  31393. }
  31394. });
  31395. }
  31396. }
  31397. /**
  31398. * Prevents stream controller from loading new segments until `resumeBuffering` is called.
  31399. * This allows for media buffering to be paused without interupting playlist loading.
  31400. */
  31401. pauseBuffering() {
  31402. if (this.bufferingEnabled) {
  31403. this.logger.log(`pause buffering`);
  31404. this.networkControllers.forEach((controller) => {
  31405. if (controller.pauseBuffering) {
  31406. controller.pauseBuffering();
  31407. }
  31408. });
  31409. }
  31410. }
  31411. get inFlightFragments() {
  31412. const inFlightData = {
  31413. [PlaylistLevelType.MAIN]: this.streamController.inFlightFrag
  31414. };
  31415. if (this.audioStreamController) {
  31416. inFlightData[PlaylistLevelType.AUDIO] = this.audioStreamController.inFlightFrag;
  31417. }
  31418. if (this.subtititleStreamController) {
  31419. inFlightData[PlaylistLevelType.SUBTITLE] = this.subtititleStreamController.inFlightFrag;
  31420. }
  31421. return inFlightData;
  31422. }
  31423. /**
  31424. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  31425. */
  31426. swapAudioCodec() {
  31427. this.logger.log("swapAudioCodec");
  31428. this.streamController.swapAudioCodec();
  31429. }
  31430. /**
  31431. * When the media-element fails, this allows to detach and then re-attach it
  31432. * as one call (convenience method).
  31433. *
  31434. * Automatic recovery of media-errors by this process is configurable.
  31435. */
  31436. recoverMediaError() {
  31437. this.logger.log("recoverMediaError");
  31438. const media = this._media;
  31439. const time = media == null ? void 0 : media.currentTime;
  31440. this.detachMedia();
  31441. if (media) {
  31442. this.attachMedia(media);
  31443. if (time) {
  31444. this.startLoad(time);
  31445. }
  31446. }
  31447. }
  31448. removeLevel(levelIndex) {
  31449. this.levelController.removeLevel(levelIndex);
  31450. }
  31451. /**
  31452. * @returns a UUID for this player instance
  31453. */
  31454. get sessionId() {
  31455. let _sessionId = this._sessionId;
  31456. if (!_sessionId) {
  31457. _sessionId = this._sessionId = uuid();
  31458. }
  31459. return _sessionId;
  31460. }
  31461. /**
  31462. * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH
  31463. */
  31464. get levels() {
  31465. const levels = this.levelController.levels;
  31466. return levels ? levels : [];
  31467. }
  31468. /**
  31469. * @returns LevelDetails of last loaded level (variant) or `null` prior to loading a media playlist.
  31470. */
  31471. get latestLevelDetails() {
  31472. return this.streamController.getLevelDetails() || null;
  31473. }
  31474. /**
  31475. * @returns Level object of selected level (variant) or `null` prior to selecting a level or once the level is removed.
  31476. */
  31477. get loadLevelObj() {
  31478. return this.levelController.loadLevelObj;
  31479. }
  31480. /**
  31481. * Index of quality level (variant) currently played
  31482. */
  31483. get currentLevel() {
  31484. return this.streamController.currentLevel;
  31485. }
  31486. /**
  31487. * Set quality level index immediately. This will flush the current buffer to replace the quality asap. That means playback will interrupt at least shortly to re-buffer and re-sync eventually. Set to -1 for automatic level selection.
  31488. */
  31489. set currentLevel(newLevel) {
  31490. this.logger.log(`set currentLevel:${newLevel}`);
  31491. this.levelController.manualLevel = newLevel;
  31492. this.streamController.immediateLevelSwitch();
  31493. }
  31494. /**
  31495. * Index of next quality level loaded as scheduled by stream controller.
  31496. */
  31497. get nextLevel() {
  31498. return this.streamController.nextLevel;
  31499. }
  31500. /**
  31501. * Set quality level index for next loaded data.
  31502. * This will switch the video quality asap, without interrupting playback.
  31503. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  31504. * @param newLevel - Pass -1 for automatic level selection
  31505. */
  31506. set nextLevel(newLevel) {
  31507. this.logger.log(`set nextLevel:${newLevel}`);
  31508. this.levelController.manualLevel = newLevel;
  31509. this.streamController.nextLevelSwitch();
  31510. }
  31511. /**
  31512. * Return the quality level of the currently or last (of none is loaded currently) segment
  31513. */
  31514. get loadLevel() {
  31515. return this.levelController.level;
  31516. }
  31517. /**
  31518. * Set quality level index for next loaded data in a conservative way.
  31519. * This will switch the quality without flushing, but interrupt current loading.
  31520. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  31521. * @param newLevel - Pass -1 for automatic level selection
  31522. */
  31523. set loadLevel(newLevel) {
  31524. this.logger.log(`set loadLevel:${newLevel}`);
  31525. this.levelController.manualLevel = newLevel;
  31526. }
  31527. /**
  31528. * get next quality level loaded
  31529. */
  31530. get nextLoadLevel() {
  31531. return this.levelController.nextLoadLevel;
  31532. }
  31533. /**
  31534. * Set quality level of next loaded segment in a fully "non-destructive" way.
  31535. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  31536. */
  31537. set nextLoadLevel(level) {
  31538. this.levelController.nextLoadLevel = level;
  31539. }
  31540. /**
  31541. * Return "first level": like a default level, if not set,
  31542. * falls back to index of first level referenced in manifest
  31543. */
  31544. get firstLevel() {
  31545. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  31546. }
  31547. /**
  31548. * Sets "first-level", see getter.
  31549. */
  31550. set firstLevel(newLevel) {
  31551. this.logger.log(`set firstLevel:${newLevel}`);
  31552. this.levelController.firstLevel = newLevel;
  31553. }
  31554. /**
  31555. * Return the desired start level for the first fragment that will be loaded.
  31556. * The default value of -1 indicates automatic start level selection.
  31557. * Setting hls.nextAutoLevel without setting a startLevel will result in
  31558. * the nextAutoLevel value being used for one fragment load.
  31559. */
  31560. get startLevel() {
  31561. const startLevel = this.levelController.startLevel;
  31562. if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {
  31563. return this.abrController.forcedAutoLevel;
  31564. }
  31565. return startLevel;
  31566. }
  31567. /**
  31568. * set start level (level of first fragment that will be played back)
  31569. * if not overrided by user, first level appearing in manifest will be used as start level
  31570. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  31571. * (determined from download of first segment)
  31572. */
  31573. set startLevel(newLevel) {
  31574. this.logger.log(`set startLevel:${newLevel}`);
  31575. if (newLevel !== -1) {
  31576. newLevel = Math.max(newLevel, this.minAutoLevel);
  31577. }
  31578. this.levelController.startLevel = newLevel;
  31579. }
  31580. /**
  31581. * Whether level capping is enabled.
  31582. * Default value is set via `config.capLevelToPlayerSize`.
  31583. */
  31584. get capLevelToPlayerSize() {
  31585. return this.config.capLevelToPlayerSize;
  31586. }
  31587. /**
  31588. * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.
  31589. */
  31590. set capLevelToPlayerSize(shouldStartCapping) {
  31591. const newCapLevelToPlayerSize = !!shouldStartCapping;
  31592. if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
  31593. if (newCapLevelToPlayerSize) {
  31594. this.capLevelController.startCapping();
  31595. } else {
  31596. this.capLevelController.stopCapping();
  31597. this.autoLevelCapping = -1;
  31598. this.streamController.nextLevelSwitch();
  31599. }
  31600. this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
  31601. }
  31602. }
  31603. /**
  31604. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  31605. */
  31606. get autoLevelCapping() {
  31607. return this._autoLevelCapping;
  31608. }
  31609. /**
  31610. * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.
  31611. */
  31612. get bandwidthEstimate() {
  31613. const {
  31614. bwEstimator
  31615. } = this.abrController;
  31616. if (!bwEstimator) {
  31617. return NaN;
  31618. }
  31619. return bwEstimator.getEstimate();
  31620. }
  31621. set bandwidthEstimate(abrEwmaDefaultEstimate) {
  31622. this.abrController.resetEstimator(abrEwmaDefaultEstimate);
  31623. }
  31624. get abrEwmaDefaultEstimate() {
  31625. const {
  31626. bwEstimator
  31627. } = this.abrController;
  31628. if (!bwEstimator) {
  31629. return NaN;
  31630. }
  31631. return bwEstimator.defaultEstimate;
  31632. }
  31633. /**
  31634. * get time to first byte estimate
  31635. * @type {number}
  31636. */
  31637. get ttfbEstimate() {
  31638. const {
  31639. bwEstimator
  31640. } = this.abrController;
  31641. if (!bwEstimator) {
  31642. return NaN;
  31643. }
  31644. return bwEstimator.getEstimateTTFB();
  31645. }
  31646. /**
  31647. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  31648. */
  31649. set autoLevelCapping(newLevel) {
  31650. if (this._autoLevelCapping !== newLevel) {
  31651. this.logger.log(`set autoLevelCapping:${newLevel}`);
  31652. this._autoLevelCapping = newLevel;
  31653. this.levelController.checkMaxAutoUpdated();
  31654. }
  31655. }
  31656. get maxHdcpLevel() {
  31657. return this._maxHdcpLevel;
  31658. }
  31659. set maxHdcpLevel(value) {
  31660. if (isHdcpLevel(value) && this._maxHdcpLevel !== value) {
  31661. this._maxHdcpLevel = value;
  31662. this.levelController.checkMaxAutoUpdated();
  31663. }
  31664. }
  31665. /**
  31666. * True when automatic level selection enabled
  31667. */
  31668. get autoLevelEnabled() {
  31669. return this.levelController.manualLevel === -1;
  31670. }
  31671. /**
  31672. * Level set manually (if any)
  31673. */
  31674. get manualLevel() {
  31675. return this.levelController.manualLevel;
  31676. }
  31677. /**
  31678. * min level selectable in auto mode according to config.minAutoBitrate
  31679. */
  31680. get minAutoLevel() {
  31681. const {
  31682. levels,
  31683. config: {
  31684. minAutoBitrate
  31685. }
  31686. } = this;
  31687. if (!levels)
  31688. return 0;
  31689. const len = levels.length;
  31690. for (let i = 0; i < len; i++) {
  31691. if (levels[i].maxBitrate >= minAutoBitrate) {
  31692. return i;
  31693. }
  31694. }
  31695. return 0;
  31696. }
  31697. /**
  31698. * max level selectable in auto mode according to autoLevelCapping
  31699. */
  31700. get maxAutoLevel() {
  31701. const {
  31702. levels,
  31703. autoLevelCapping,
  31704. maxHdcpLevel
  31705. } = this;
  31706. let maxAutoLevel;
  31707. if (autoLevelCapping === -1 && levels != null && levels.length) {
  31708. maxAutoLevel = levels.length - 1;
  31709. } else {
  31710. maxAutoLevel = autoLevelCapping;
  31711. }
  31712. if (maxHdcpLevel) {
  31713. for (let i = maxAutoLevel; i--; ) {
  31714. const hdcpLevel = levels[i].attrs["HDCP-LEVEL"];
  31715. if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {
  31716. return i;
  31717. }
  31718. }
  31719. }
  31720. return maxAutoLevel;
  31721. }
  31722. get firstAutoLevel() {
  31723. return this.abrController.firstAutoLevel;
  31724. }
  31725. /**
  31726. * next automatically selected quality level
  31727. */
  31728. get nextAutoLevel() {
  31729. return this.abrController.nextAutoLevel;
  31730. }
  31731. /**
  31732. * this setter is used to force next auto level.
  31733. * this is useful to force a switch down in auto mode:
  31734. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  31735. * forced value is valid for one fragment. upon successful frag loading at forced level,
  31736. * this value will be resetted to -1 by ABR controller.
  31737. */
  31738. set nextAutoLevel(nextLevel) {
  31739. this.abrController.nextAutoLevel = nextLevel;
  31740. }
  31741. /**
  31742. * get the datetime value relative to media.currentTime for the active level Program Date Time if present
  31743. */
  31744. get playingDate() {
  31745. return this.streamController.currentProgramDateTime;
  31746. }
  31747. get mainForwardBufferInfo() {
  31748. return this.streamController.getMainFwdBufferInfo();
  31749. }
  31750. get maxBufferLength() {
  31751. return this.streamController.maxBufferLength;
  31752. }
  31753. /**
  31754. * Find and select the best matching audio track, making a level switch when a Group change is necessary.
  31755. * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found.
  31756. */
  31757. setAudioOption(audioOption) {
  31758. var _this$audioTrackContr;
  31759. return ((_this$audioTrackContr = this.audioTrackController) == null ? void 0 : _this$audioTrackContr.setAudioOption(audioOption)) || null;
  31760. }
  31761. /**
  31762. * Find and select the best matching subtitle track, making a level switch when a Group change is necessary.
  31763. * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found.
  31764. */
  31765. setSubtitleOption(subtitleOption) {
  31766. var _this$subtitleTrackCo;
  31767. return ((_this$subtitleTrackCo = this.subtitleTrackController) == null ? void 0 : _this$subtitleTrackCo.setSubtitleOption(subtitleOption)) || null;
  31768. }
  31769. /**
  31770. * Get the complete list of audio tracks across all media groups
  31771. */
  31772. get allAudioTracks() {
  31773. const audioTrackController = this.audioTrackController;
  31774. return audioTrackController ? audioTrackController.allAudioTracks : [];
  31775. }
  31776. /**
  31777. * Get the list of selectable audio tracks
  31778. */
  31779. get audioTracks() {
  31780. const audioTrackController = this.audioTrackController;
  31781. return audioTrackController ? audioTrackController.audioTracks : [];
  31782. }
  31783. /**
  31784. * index of the selected audio track (index in audio track lists)
  31785. */
  31786. get audioTrack() {
  31787. const audioTrackController = this.audioTrackController;
  31788. return audioTrackController ? audioTrackController.audioTrack : -1;
  31789. }
  31790. /**
  31791. * selects an audio track, based on its index in audio track lists
  31792. */
  31793. set audioTrack(audioTrackId) {
  31794. const audioTrackController = this.audioTrackController;
  31795. if (audioTrackController) {
  31796. audioTrackController.audioTrack = audioTrackId;
  31797. }
  31798. }
  31799. /**
  31800. * get the complete list of subtitle tracks across all media groups
  31801. */
  31802. get allSubtitleTracks() {
  31803. const subtitleTrackController = this.subtitleTrackController;
  31804. return subtitleTrackController ? subtitleTrackController.allSubtitleTracks : [];
  31805. }
  31806. /**
  31807. * get alternate subtitle tracks list from playlist
  31808. */
  31809. get subtitleTracks() {
  31810. const subtitleTrackController = this.subtitleTrackController;
  31811. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  31812. }
  31813. /**
  31814. * index of the selected subtitle track (index in subtitle track lists)
  31815. */
  31816. get subtitleTrack() {
  31817. const subtitleTrackController = this.subtitleTrackController;
  31818. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  31819. }
  31820. get media() {
  31821. return this._media;
  31822. }
  31823. /**
  31824. * select an subtitle track, based on its index in subtitle track lists
  31825. */
  31826. set subtitleTrack(subtitleTrackId) {
  31827. const subtitleTrackController = this.subtitleTrackController;
  31828. if (subtitleTrackController) {
  31829. subtitleTrackController.subtitleTrack = subtitleTrackId;
  31830. }
  31831. }
  31832. /**
  31833. * Whether subtitle display is enabled or not
  31834. */
  31835. get subtitleDisplay() {
  31836. const subtitleTrackController = this.subtitleTrackController;
  31837. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  31838. }
  31839. /**
  31840. * Enable/disable subtitle display rendering
  31841. */
  31842. set subtitleDisplay(value) {
  31843. const subtitleTrackController = this.subtitleTrackController;
  31844. if (subtitleTrackController) {
  31845. subtitleTrackController.subtitleDisplay = value;
  31846. }
  31847. }
  31848. /**
  31849. * get mode for Low-Latency HLS loading
  31850. */
  31851. get lowLatencyMode() {
  31852. return this.config.lowLatencyMode;
  31853. }
  31854. /**
  31855. * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
  31856. */
  31857. set lowLatencyMode(mode) {
  31858. this.config.lowLatencyMode = mode;
  31859. }
  31860. /**
  31861. * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
  31862. * @returns null prior to loading live Playlist
  31863. */
  31864. get liveSyncPosition() {
  31865. return this.latencyController.liveSyncPosition;
  31866. }
  31867. /**
  31868. * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
  31869. * @returns 0 before first playlist is loaded
  31870. */
  31871. get latency() {
  31872. return this.latencyController.latency;
  31873. }
  31874. /**
  31875. * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
  31876. * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
  31877. * @returns 0 before first playlist is loaded
  31878. */
  31879. get maxLatency() {
  31880. return this.latencyController.maxLatency;
  31881. }
  31882. /**
  31883. * target distance from the edge as calculated by the latency controller
  31884. */
  31885. get targetLatency() {
  31886. return this.latencyController.targetLatency;
  31887. }
  31888. set targetLatency(latency) {
  31889. this.latencyController.targetLatency = latency;
  31890. }
  31891. /**
  31892. * the rate at which the edge of the current live playlist is advancing or 1 if there is none
  31893. */
  31894. get drift() {
  31895. return this.latencyController.drift;
  31896. }
  31897. /**
  31898. * set to true when startLoad is called before MANIFEST_PARSED event
  31899. */
  31900. get forceStartLoad() {
  31901. return this.streamController.forceStartLoad;
  31902. }
  31903. /**
  31904. * ContentSteering pathways getter
  31905. */
  31906. get pathways() {
  31907. return this.levelController.pathways;
  31908. }
  31909. /**
  31910. * ContentSteering pathwayPriority getter/setter
  31911. */
  31912. get pathwayPriority() {
  31913. return this.levelController.pathwayPriority;
  31914. }
  31915. set pathwayPriority(pathwayPriority) {
  31916. this.levelController.pathwayPriority = pathwayPriority;
  31917. }
  31918. /**
  31919. * returns true when all SourceBuffers are buffered to the end
  31920. */
  31921. get bufferedToEnd() {
  31922. var _this$bufferControlle;
  31923. return !!((_this$bufferControlle = this.bufferController) != null && _this$bufferControlle.bufferedToEnd);
  31924. }
  31925. /**
  31926. * returns Interstitials Program Manager
  31927. */
  31928. get interstitialsManager() {
  31929. var _this$interstitialsCo;
  31930. return ((_this$interstitialsCo = this.interstitialsController) == null ? void 0 : _this$interstitialsCo.interstitialsManager) || null;
  31931. }
  31932. /**
  31933. * returns mediaCapabilities.decodingInfo for a variant/rendition
  31934. */
  31935. getMediaDecodingInfo(level, audioTracks = this.allAudioTracks) {
  31936. const audioTracksByGroup = getAudioTracksByGroup(audioTracks);
  31937. return getMediaDecodingInfoPromise(level, audioTracksByGroup, navigator.mediaCapabilities);
  31938. }
  31939. };
  31940. Hls.defaultConfig = void 0;
  31941. export {
  31942. AbrController,
  31943. AttrList,
  31944. AudioStreamController,
  31945. AudioTrackController,
  31946. BasePlaylistController,
  31947. BaseSegment,
  31948. BaseStreamController,
  31949. BufferController,
  31950. CMCDController,
  31951. CapLevelController,
  31952. ChunkMetadata,
  31953. ContentSteeringController,
  31954. Cues,
  31955. DateRange,
  31956. EMEController,
  31957. ErrorActionFlags,
  31958. ErrorController,
  31959. ErrorDetails,
  31960. ErrorTypes,
  31961. Events,
  31962. FPSController,
  31963. FetchLoader,
  31964. Fragment,
  31965. Hls,
  31966. HlsSkip,
  31967. HlsUrlParameters,
  31968. KeySystemFormats,
  31969. KeySystems,
  31970. Level,
  31971. LevelDetails,
  31972. LevelKey,
  31973. LoadStats,
  31974. M3U8Parser,
  31975. MetadataSchema,
  31976. NetworkErrorAction,
  31977. Part,
  31978. PlaylistLevelType,
  31979. SubtitleStreamController,
  31980. SubtitleTrackController,
  31981. TimelineController,
  31982. XhrLoader,
  31983. Hls as default,
  31984. fetchSupported,
  31985. getMediaSource,
  31986. isMSESupported,
  31987. isSupported,
  31988. requestMediaKeySystemAccess
  31989. };
  31990. //# sourceMappingURL=hls__js.js.map