hls_js.js 1022 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899
  1. import {
  2. init_define_process_env_UNI_STAT_TITLE_JSON
  3. } from "./chunk-ON7YJ3LY.js";
  4. // dep:hls_js
  5. init_define_process_env_UNI_STAT_TITLE_JSON();
  6. // ../../../../../../../../Desktop/项目/直播/liveH5-v3/node_modules/hls.js/dist/hls.mjs
  7. init_define_process_env_UNI_STAT_TITLE_JSON();
  8. var isFiniteNumber = Number.isFinite || function(value) {
  9. return typeof value === "number" && isFinite(value);
  10. };
  11. var isSafeInteger = Number.isSafeInteger || function(value) {
  12. return typeof value === "number" && Math.abs(value) <= MAX_SAFE_INTEGER;
  13. };
  14. var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  15. var ErrorTypes = function(ErrorTypes2) {
  16. ErrorTypes2["NETWORK_ERROR"] = "networkError";
  17. ErrorTypes2["MEDIA_ERROR"] = "mediaError";
  18. ErrorTypes2["KEY_SYSTEM_ERROR"] = "keySystemError";
  19. ErrorTypes2["MUX_ERROR"] = "muxError";
  20. ErrorTypes2["OTHER_ERROR"] = "otherError";
  21. return ErrorTypes2;
  22. }({});
  23. var ErrorDetails = function(ErrorDetails2) {
  24. ErrorDetails2["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
  25. ErrorDetails2["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
  26. ErrorDetails2["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
  27. ErrorDetails2["KEY_SYSTEM_NO_CONFIGURED_LICENSE"] = "keySystemNoConfiguredLicense";
  28. ErrorDetails2["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
  29. ErrorDetails2["KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED"] = "keySystemServerCertificateRequestFailed";
  30. ErrorDetails2["KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED"] = "keySystemServerCertificateUpdateFailed";
  31. ErrorDetails2["KEY_SYSTEM_SESSION_UPDATE_FAILED"] = "keySystemSessionUpdateFailed";
  32. ErrorDetails2["KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED"] = "keySystemStatusOutputRestricted";
  33. ErrorDetails2["KEY_SYSTEM_STATUS_INTERNAL_ERROR"] = "keySystemStatusInternalError";
  34. ErrorDetails2["KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR"] = "keySystemDestroyMediaKeysError";
  35. ErrorDetails2["KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR"] = "keySystemDestroyCloseSessionError";
  36. ErrorDetails2["KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR"] = "keySystemDestroyRemoveSessionError";
  37. ErrorDetails2["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
  38. ErrorDetails2["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
  39. ErrorDetails2["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
  40. ErrorDetails2["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
  41. ErrorDetails2["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
  42. ErrorDetails2["LEVEL_LOAD_ERROR"] = "levelLoadError";
  43. ErrorDetails2["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
  44. ErrorDetails2["LEVEL_PARSING_ERROR"] = "levelParsingError";
  45. ErrorDetails2["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
  46. ErrorDetails2["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
  47. ErrorDetails2["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
  48. ErrorDetails2["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
  49. ErrorDetails2["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
  50. ErrorDetails2["FRAG_LOAD_ERROR"] = "fragLoadError";
  51. ErrorDetails2["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
  52. ErrorDetails2["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
  53. ErrorDetails2["FRAG_PARSING_ERROR"] = "fragParsingError";
  54. ErrorDetails2["FRAG_GAP"] = "fragGap";
  55. ErrorDetails2["REMUX_ALLOC_ERROR"] = "remuxAllocError";
  56. ErrorDetails2["KEY_LOAD_ERROR"] = "keyLoadError";
  57. ErrorDetails2["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
  58. ErrorDetails2["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
  59. ErrorDetails2["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
  60. ErrorDetails2["BUFFER_APPEND_ERROR"] = "bufferAppendError";
  61. ErrorDetails2["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
  62. ErrorDetails2["BUFFER_STALLED_ERROR"] = "bufferStalledError";
  63. ErrorDetails2["BUFFER_FULL_ERROR"] = "bufferFullError";
  64. ErrorDetails2["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
  65. ErrorDetails2["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
  66. ErrorDetails2["ASSET_LIST_LOAD_ERROR"] = "assetListLoadError";
  67. ErrorDetails2["ASSET_LIST_LOAD_TIMEOUT"] = "assetListLoadTimeout";
  68. ErrorDetails2["ASSET_LIST_PARSING_ERROR"] = "assetListParsingError";
  69. ErrorDetails2["INTERSTITIAL_ASSET_ITEM_ERROR"] = "interstitialAssetItemError";
  70. ErrorDetails2["INTERNAL_EXCEPTION"] = "internalException";
  71. ErrorDetails2["INTERNAL_ABORTED"] = "aborted";
  72. ErrorDetails2["ATTACH_MEDIA_ERROR"] = "attachMediaError";
  73. ErrorDetails2["UNKNOWN"] = "unknown";
  74. return ErrorDetails2;
  75. }({});
  76. var Events = function(Events2) {
  77. Events2["MEDIA_ATTACHING"] = "hlsMediaAttaching";
  78. Events2["MEDIA_ATTACHED"] = "hlsMediaAttached";
  79. Events2["MEDIA_DETACHING"] = "hlsMediaDetaching";
  80. Events2["MEDIA_DETACHED"] = "hlsMediaDetached";
  81. Events2["MEDIA_ENDED"] = "hlsMediaEnded";
  82. Events2["STALL_RESOLVED"] = "hlsStallResolved";
  83. Events2["BUFFER_RESET"] = "hlsBufferReset";
  84. Events2["BUFFER_CODECS"] = "hlsBufferCodecs";
  85. Events2["BUFFER_CREATED"] = "hlsBufferCreated";
  86. Events2["BUFFER_APPENDING"] = "hlsBufferAppending";
  87. Events2["BUFFER_APPENDED"] = "hlsBufferAppended";
  88. Events2["BUFFER_EOS"] = "hlsBufferEos";
  89. Events2["BUFFERED_TO_END"] = "hlsBufferedToEnd";
  90. Events2["BUFFER_FLUSHING"] = "hlsBufferFlushing";
  91. Events2["BUFFER_FLUSHED"] = "hlsBufferFlushed";
  92. Events2["MANIFEST_LOADING"] = "hlsManifestLoading";
  93. Events2["MANIFEST_LOADED"] = "hlsManifestLoaded";
  94. Events2["MANIFEST_PARSED"] = "hlsManifestParsed";
  95. Events2["LEVEL_SWITCHING"] = "hlsLevelSwitching";
  96. Events2["LEVEL_SWITCHED"] = "hlsLevelSwitched";
  97. Events2["LEVEL_LOADING"] = "hlsLevelLoading";
  98. Events2["LEVEL_LOADED"] = "hlsLevelLoaded";
  99. Events2["LEVEL_UPDATED"] = "hlsLevelUpdated";
  100. Events2["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
  101. Events2["LEVELS_UPDATED"] = "hlsLevelsUpdated";
  102. Events2["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
  103. Events2["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
  104. Events2["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
  105. Events2["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
  106. Events2["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
  107. Events2["AUDIO_TRACK_UPDATED"] = "hlsAudioTrackUpdated";
  108. Events2["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
  109. Events2["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
  110. Events2["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
  111. Events2["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
  112. Events2["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
  113. Events2["SUBTITLE_TRACK_UPDATED"] = "hlsSubtitleTrackUpdated";
  114. Events2["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
  115. Events2["CUES_PARSED"] = "hlsCuesParsed";
  116. Events2["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
  117. Events2["INIT_PTS_FOUND"] = "hlsInitPtsFound";
  118. Events2["FRAG_LOADING"] = "hlsFragLoading";
  119. Events2["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
  120. Events2["FRAG_LOADED"] = "hlsFragLoaded";
  121. Events2["FRAG_DECRYPTED"] = "hlsFragDecrypted";
  122. Events2["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
  123. Events2["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
  124. Events2["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
  125. Events2["FRAG_PARSED"] = "hlsFragParsed";
  126. Events2["FRAG_BUFFERED"] = "hlsFragBuffered";
  127. Events2["FRAG_CHANGED"] = "hlsFragChanged";
  128. Events2["FPS_DROP"] = "hlsFpsDrop";
  129. Events2["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
  130. Events2["MAX_AUTO_LEVEL_UPDATED"] = "hlsMaxAutoLevelUpdated";
  131. Events2["ERROR"] = "hlsError";
  132. Events2["DESTROYING"] = "hlsDestroying";
  133. Events2["KEY_LOADING"] = "hlsKeyLoading";
  134. Events2["KEY_LOADED"] = "hlsKeyLoaded";
  135. Events2["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
  136. Events2["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
  137. Events2["STEERING_MANIFEST_LOADED"] = "hlsSteeringManifestLoaded";
  138. Events2["ASSET_LIST_LOADING"] = "hlsAssetListLoading";
  139. Events2["ASSET_LIST_LOADED"] = "hlsAssetListLoaded";
  140. Events2["INTERSTITIALS_UPDATED"] = "hlsInterstitialsUpdated";
  141. Events2["INTERSTITIALS_BUFFERED_TO_BOUNDARY"] = "hlsInterstitialsBufferedToBoundary";
  142. Events2["INTERSTITIAL_ASSET_PLAYER_CREATED"] = "hlsInterstitialAssetPlayerCreated";
  143. Events2["INTERSTITIAL_STARTED"] = "hlsInterstitialStarted";
  144. Events2["INTERSTITIAL_ASSET_STARTED"] = "hlsInterstitialAssetStarted";
  145. Events2["INTERSTITIAL_ASSET_ENDED"] = "hlsInterstitialAssetEnded";
  146. Events2["INTERSTITIAL_ASSET_ERROR"] = "hlsInterstitialAssetError";
  147. Events2["INTERSTITIAL_ENDED"] = "hlsInterstitialEnded";
  148. Events2["INTERSTITIALS_PRIMARY_RESUMED"] = "hlsInterstitialsPrimaryResumed";
  149. Events2["PLAYOUT_LIMIT_REACHED"] = "hlsPlayoutLimitReached";
  150. Events2["EVENT_CUE_ENTER"] = "hlsEventCueEnter";
  151. return Events2;
  152. }({});
  153. var PlaylistContextType = {
  154. MANIFEST: "manifest",
  155. LEVEL: "level",
  156. AUDIO_TRACK: "audioTrack",
  157. SUBTITLE_TRACK: "subtitleTrack"
  158. };
  159. var PlaylistLevelType = {
  160. MAIN: "main",
  161. AUDIO: "audio",
  162. SUBTITLE: "subtitle"
  163. };
  164. var EWMA = class {
  165. constructor(halfLife, estimate = 0, weight = 0) {
  166. this.halfLife = void 0;
  167. this.alpha_ = void 0;
  168. this.estimate_ = void 0;
  169. this.totalWeight_ = void 0;
  170. this.halfLife = halfLife;
  171. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  172. this.estimate_ = estimate;
  173. this.totalWeight_ = weight;
  174. }
  175. sample(weight, value) {
  176. const adjAlpha = Math.pow(this.alpha_, weight);
  177. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  178. this.totalWeight_ += weight;
  179. }
  180. getTotalWeight() {
  181. return this.totalWeight_;
  182. }
  183. getEstimate() {
  184. if (this.alpha_) {
  185. const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  186. if (zeroFactor) {
  187. return this.estimate_ / zeroFactor;
  188. }
  189. }
  190. return this.estimate_;
  191. }
  192. };
  193. var EwmaBandWidthEstimator = class {
  194. constructor(slow, fast, defaultEstimate, defaultTTFB = 100) {
  195. this.defaultEstimate_ = void 0;
  196. this.minWeight_ = void 0;
  197. this.minDelayMs_ = void 0;
  198. this.slow_ = void 0;
  199. this.fast_ = void 0;
  200. this.defaultTTFB_ = void 0;
  201. this.ttfb_ = void 0;
  202. this.defaultEstimate_ = defaultEstimate;
  203. this.minWeight_ = 1e-3;
  204. this.minDelayMs_ = 50;
  205. this.slow_ = new EWMA(slow);
  206. this.fast_ = new EWMA(fast);
  207. this.defaultTTFB_ = defaultTTFB;
  208. this.ttfb_ = new EWMA(slow);
  209. }
  210. update(slow, fast) {
  211. const {
  212. slow_,
  213. fast_,
  214. ttfb_
  215. } = this;
  216. if (slow_.halfLife !== slow) {
  217. this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());
  218. }
  219. if (fast_.halfLife !== fast) {
  220. this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());
  221. }
  222. if (ttfb_.halfLife !== slow) {
  223. this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());
  224. }
  225. }
  226. sample(durationMs, numBytes) {
  227. durationMs = Math.max(durationMs, this.minDelayMs_);
  228. const numBits = 8 * numBytes;
  229. const durationS = durationMs / 1e3;
  230. const bandwidthInBps = numBits / durationS;
  231. this.fast_.sample(durationS, bandwidthInBps);
  232. this.slow_.sample(durationS, bandwidthInBps);
  233. }
  234. sampleTTFB(ttfb) {
  235. const seconds = ttfb / 1e3;
  236. const weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);
  237. this.ttfb_.sample(weight, Math.max(ttfb, 5));
  238. }
  239. canEstimate() {
  240. return this.fast_.getTotalWeight() >= this.minWeight_;
  241. }
  242. getEstimate() {
  243. if (this.canEstimate()) {
  244. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  245. } else {
  246. return this.defaultEstimate_;
  247. }
  248. }
  249. getEstimateTTFB() {
  250. if (this.ttfb_.getTotalWeight() >= this.minWeight_) {
  251. return this.ttfb_.getEstimate();
  252. } else {
  253. return this.defaultTTFB_;
  254. }
  255. }
  256. get defaultEstimate() {
  257. return this.defaultEstimate_;
  258. }
  259. destroy() {
  260. }
  261. };
  262. function _defineProperty(e, r, t) {
  263. return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
  264. value: t,
  265. enumerable: true,
  266. configurable: true,
  267. writable: true
  268. }) : e[r] = t, e;
  269. }
  270. function _extends() {
  271. return _extends = Object.assign ? Object.assign.bind() : function(n) {
  272. for (var e = 1; e < arguments.length; e++) {
  273. var t = arguments[e];
  274. for (var r in t)
  275. ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
  276. }
  277. return n;
  278. }, _extends.apply(null, arguments);
  279. }
  280. function ownKeys(e, r) {
  281. var t = Object.keys(e);
  282. if (Object.getOwnPropertySymbols) {
  283. var o = Object.getOwnPropertySymbols(e);
  284. r && (o = o.filter(function(r2) {
  285. return Object.getOwnPropertyDescriptor(e, r2).enumerable;
  286. })), t.push.apply(t, o);
  287. }
  288. return t;
  289. }
  290. function _objectSpread2(e) {
  291. for (var r = 1; r < arguments.length; r++) {
  292. var t = arguments[r] != null ? arguments[r] : {};
  293. r % 2 ? ownKeys(Object(t), true).forEach(function(r2) {
  294. _defineProperty(e, r2, t[r2]);
  295. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) {
  296. Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
  297. });
  298. }
  299. return e;
  300. }
  301. function _toPrimitive(t, r) {
  302. if (typeof t != "object" || !t)
  303. return t;
  304. var e = t[Symbol.toPrimitive];
  305. if (e !== void 0) {
  306. var i = e.call(t, r);
  307. if (typeof i != "object")
  308. return i;
  309. throw new TypeError("@@toPrimitive must return a primitive value.");
  310. }
  311. return (r === "string" ? String : Number)(t);
  312. }
  313. function _toPropertyKey(t) {
  314. var i = _toPrimitive(t, "string");
  315. return typeof i == "symbol" ? i : i + "";
  316. }
  317. var Logger = class {
  318. constructor(label, logger2) {
  319. this.trace = void 0;
  320. this.debug = void 0;
  321. this.log = void 0;
  322. this.warn = void 0;
  323. this.info = void 0;
  324. this.error = void 0;
  325. const lb = `[${label}]:`;
  326. this.trace = noop;
  327. this.debug = logger2.debug.bind(null, lb);
  328. this.log = logger2.log.bind(null, lb);
  329. this.warn = logger2.warn.bind(null, lb);
  330. this.info = logger2.info.bind(null, lb);
  331. this.error = logger2.error.bind(null, lb);
  332. }
  333. };
  334. var noop = function noop2() {
  335. };
  336. var fakeLogger = {
  337. trace: noop,
  338. debug: noop,
  339. log: noop,
  340. warn: noop,
  341. info: noop,
  342. error: noop
  343. };
  344. function createLogger() {
  345. return _extends({}, fakeLogger);
  346. }
  347. function consolePrintFn(type, id) {
  348. const func = self.console[type];
  349. return func ? func.bind(self.console, `${id ? "[" + id + "] " : ""}[${type}] >`) : noop;
  350. }
  351. function getLoggerFn(key, debugConfig, id) {
  352. return debugConfig[key] ? debugConfig[key].bind(debugConfig) : consolePrintFn(key, id);
  353. }
  354. var exportedLogger = createLogger();
  355. function enableLogs(debugConfig, context, id) {
  356. const newLogger = createLogger();
  357. if (typeof console === "object" && debugConfig === true || typeof debugConfig === "object") {
  358. const keys = [
  359. "debug",
  360. "log",
  361. "info",
  362. "warn",
  363. "error"
  364. ];
  365. keys.forEach((key) => {
  366. newLogger[key] = getLoggerFn(key, debugConfig, id);
  367. });
  368. try {
  369. newLogger.log(`Debug logs enabled for "${context}" in hls.js version ${"1.6.7"}`);
  370. } catch (e) {
  371. return createLogger();
  372. }
  373. keys.forEach((key) => {
  374. exportedLogger[key] = getLoggerFn(key, debugConfig);
  375. });
  376. } else {
  377. _extends(exportedLogger, newLogger);
  378. }
  379. return newLogger;
  380. }
  381. var logger = exportedLogger;
  382. function getMediaSource(preferManagedMediaSource = true) {
  383. if (typeof self === "undefined")
  384. return void 0;
  385. const mms = (preferManagedMediaSource || !self.MediaSource) && self.ManagedMediaSource;
  386. return mms || self.MediaSource || self.WebKitMediaSource;
  387. }
  388. function isManagedMediaSource(source) {
  389. return typeof self !== "undefined" && source === self.ManagedMediaSource;
  390. }
  391. function isCompatibleTrackChange(currentTracks, requiredTracks) {
  392. const trackNames = Object.keys(currentTracks);
  393. const requiredTrackNames = Object.keys(requiredTracks);
  394. const trackCount = trackNames.length;
  395. const requiredTrackCount = requiredTrackNames.length;
  396. return !trackCount || !requiredTrackCount || trackCount === requiredTrackCount && !trackNames.some((name) => requiredTrackNames.indexOf(name) === -1);
  397. }
  398. function utf8ArrayToStr(array, exitOnNull = false) {
  399. if (typeof TextDecoder !== "undefined") {
  400. const decoder = new TextDecoder("utf-8");
  401. const decoded = decoder.decode(array);
  402. if (exitOnNull) {
  403. const idx = decoded.indexOf("\0");
  404. return idx !== -1 ? decoded.substring(0, idx) : decoded;
  405. }
  406. return decoded.replace(/\0/g, "");
  407. }
  408. const len = array.length;
  409. let c;
  410. let char2;
  411. let char3;
  412. let out = "";
  413. let i = 0;
  414. while (i < len) {
  415. c = array[i++];
  416. if (c === 0 && exitOnNull) {
  417. return out;
  418. } else if (c === 0 || c === 3) {
  419. continue;
  420. }
  421. switch (c >> 4) {
  422. case 0:
  423. case 1:
  424. case 2:
  425. case 3:
  426. case 4:
  427. case 5:
  428. case 6:
  429. case 7:
  430. out += String.fromCharCode(c);
  431. break;
  432. case 12:
  433. case 13:
  434. char2 = array[i++];
  435. out += String.fromCharCode((c & 31) << 6 | char2 & 63);
  436. break;
  437. case 14:
  438. char2 = array[i++];
  439. char3 = array[i++];
  440. out += String.fromCharCode((c & 15) << 12 | (char2 & 63) << 6 | (char3 & 63) << 0);
  441. break;
  442. }
  443. }
  444. return out;
  445. }
  446. var Hex = {
  447. hexDump: function(array) {
  448. let str = "";
  449. for (let i = 0; i < array.length; i++) {
  450. let h = array[i].toString(16);
  451. if (h.length < 2) {
  452. h = "0" + h;
  453. }
  454. str += h;
  455. }
  456. return str;
  457. }
  458. };
  459. function hexToArrayBuffer(str) {
  460. return Uint8Array.from(str.replace(/^0x/, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")).buffer;
  461. }
  462. function getDefaultExportFromCjs(x) {
  463. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
  464. }
  465. var urlToolkit = { exports: {} };
  466. var hasRequiredUrlToolkit;
  467. function requireUrlToolkit() {
  468. if (hasRequiredUrlToolkit)
  469. return urlToolkit.exports;
  470. hasRequiredUrlToolkit = 1;
  471. (function(module, exports) {
  472. (function(root) {
  473. var URL_REGEX = /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/;
  474. var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/;
  475. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  476. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  477. var URLToolkit = {
  478. buildAbsoluteURL: function(baseURL, relativeURL, opts) {
  479. opts = opts || {};
  480. baseURL = baseURL.trim();
  481. relativeURL = relativeURL.trim();
  482. if (!relativeURL) {
  483. if (!opts.alwaysNormalize) {
  484. return baseURL;
  485. }
  486. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  487. if (!basePartsForNormalise) {
  488. throw new Error("Error trying to parse base URL.");
  489. }
  490. basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
  491. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  492. }
  493. var relativeParts = URLToolkit.parseURL(relativeURL);
  494. if (!relativeParts) {
  495. throw new Error("Error trying to parse relative URL.");
  496. }
  497. if (relativeParts.scheme) {
  498. if (!opts.alwaysNormalize) {
  499. return relativeURL;
  500. }
  501. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  502. return URLToolkit.buildURLFromParts(relativeParts);
  503. }
  504. var baseParts = URLToolkit.parseURL(baseURL);
  505. if (!baseParts) {
  506. throw new Error("Error trying to parse base URL.");
  507. }
  508. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== "/") {
  509. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  510. baseParts.netLoc = pathParts[1];
  511. baseParts.path = pathParts[2];
  512. }
  513. if (baseParts.netLoc && !baseParts.path) {
  514. baseParts.path = "/";
  515. }
  516. var builtParts = {
  517. scheme: baseParts.scheme,
  518. netLoc: relativeParts.netLoc,
  519. path: null,
  520. params: relativeParts.params,
  521. query: relativeParts.query,
  522. fragment: relativeParts.fragment
  523. };
  524. if (!relativeParts.netLoc) {
  525. builtParts.netLoc = baseParts.netLoc;
  526. if (relativeParts.path[0] !== "/") {
  527. if (!relativeParts.path) {
  528. builtParts.path = baseParts.path;
  529. if (!relativeParts.params) {
  530. builtParts.params = baseParts.params;
  531. if (!relativeParts.query) {
  532. builtParts.query = baseParts.query;
  533. }
  534. }
  535. } else {
  536. var baseURLPath = baseParts.path;
  537. var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf("/") + 1) + relativeParts.path;
  538. builtParts.path = URLToolkit.normalizePath(newPath);
  539. }
  540. }
  541. }
  542. if (builtParts.path === null) {
  543. builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
  544. }
  545. return URLToolkit.buildURLFromParts(builtParts);
  546. },
  547. parseURL: function(url) {
  548. var parts = URL_REGEX.exec(url);
  549. if (!parts) {
  550. return null;
  551. }
  552. return {
  553. scheme: parts[1] || "",
  554. netLoc: parts[2] || "",
  555. path: parts[3] || "",
  556. params: parts[4] || "",
  557. query: parts[5] || "",
  558. fragment: parts[6] || ""
  559. };
  560. },
  561. normalizePath: function(path) {
  562. path = path.split("").reverse().join("").replace(SLASH_DOT_REGEX, "");
  563. while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, "")).length) {
  564. }
  565. return path.split("").reverse().join("");
  566. },
  567. buildURLFromParts: function(parts) {
  568. return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
  569. }
  570. };
  571. module.exports = URLToolkit;
  572. })();
  573. })(urlToolkit);
  574. return urlToolkit.exports;
  575. }
  576. var urlToolkitExports = requireUrlToolkit();
  577. var LoadStats = class {
  578. constructor() {
  579. this.aborted = false;
  580. this.loaded = 0;
  581. this.retry = 0;
  582. this.total = 0;
  583. this.chunkCount = 0;
  584. this.bwEstimate = 0;
  585. this.loading = {
  586. start: 0,
  587. first: 0,
  588. end: 0
  589. };
  590. this.parsing = {
  591. start: 0,
  592. end: 0
  593. };
  594. this.buffering = {
  595. start: 0,
  596. first: 0,
  597. end: 0
  598. };
  599. }
  600. };
  601. var ElementaryStreamTypes = {
  602. AUDIO: "audio",
  603. VIDEO: "video",
  604. AUDIOVIDEO: "audiovideo"
  605. };
  606. var BaseSegment = class {
  607. constructor(base) {
  608. this._byteRange = null;
  609. this._url = null;
  610. this._stats = null;
  611. this._streams = null;
  612. this.base = void 0;
  613. this.relurl = void 0;
  614. if (typeof base === "string") {
  615. base = {
  616. url: base
  617. };
  618. }
  619. this.base = base;
  620. makeEnumerable(this, "stats");
  621. }
  622. setByteRange(value, previous) {
  623. const params = value.split("@", 2);
  624. let start;
  625. if (params.length === 1) {
  626. start = (previous == null ? void 0 : previous.byteRangeEndOffset) || 0;
  627. } else {
  628. start = parseInt(params[1]);
  629. }
  630. this._byteRange = [start, parseInt(params[0]) + start];
  631. }
  632. get baseurl() {
  633. return this.base.url;
  634. }
  635. get byteRange() {
  636. if (this._byteRange === null) {
  637. return [];
  638. }
  639. return this._byteRange;
  640. }
  641. get byteRangeStartOffset() {
  642. return this.byteRange[0];
  643. }
  644. get byteRangeEndOffset() {
  645. return this.byteRange[1];
  646. }
  647. get elementaryStreams() {
  648. if (this._streams === null) {
  649. this._streams = {
  650. [ElementaryStreamTypes.AUDIO]: null,
  651. [ElementaryStreamTypes.VIDEO]: null,
  652. [ElementaryStreamTypes.AUDIOVIDEO]: null
  653. };
  654. }
  655. return this._streams;
  656. }
  657. set elementaryStreams(value) {
  658. this._streams = value;
  659. }
  660. get hasStats() {
  661. return this._stats !== null;
  662. }
  663. get hasStreams() {
  664. return this._streams !== null;
  665. }
  666. get stats() {
  667. if (this._stats === null) {
  668. this._stats = new LoadStats();
  669. }
  670. return this._stats;
  671. }
  672. set stats(value) {
  673. this._stats = value;
  674. }
  675. get url() {
  676. if (!this._url && this.baseurl && this.relurl) {
  677. this._url = urlToolkitExports.buildAbsoluteURL(this.baseurl, this.relurl, {
  678. alwaysNormalize: true
  679. });
  680. }
  681. return this._url || "";
  682. }
  683. set url(value) {
  684. this._url = value;
  685. }
  686. clearElementaryStreamInfo() {
  687. const {
  688. elementaryStreams
  689. } = this;
  690. elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
  691. elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
  692. elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
  693. }
  694. };
  695. function isMediaFragment(frag) {
  696. return frag.sn !== "initSegment";
  697. }
  698. var Fragment = class extends BaseSegment {
  699. constructor(type, base) {
  700. super(base);
  701. this._decryptdata = null;
  702. this._programDateTime = null;
  703. this._ref = null;
  704. this._bitrate = void 0;
  705. this.rawProgramDateTime = null;
  706. this.tagList = [];
  707. this.duration = 0;
  708. this.sn = 0;
  709. this.levelkeys = void 0;
  710. this.type = void 0;
  711. this.loader = null;
  712. this.keyLoader = null;
  713. this.level = -1;
  714. this.cc = 0;
  715. this.startPTS = void 0;
  716. this.endPTS = void 0;
  717. this.startDTS = void 0;
  718. this.endDTS = void 0;
  719. this.start = 0;
  720. this.playlistOffset = 0;
  721. this.deltaPTS = void 0;
  722. this.maxStartPTS = void 0;
  723. this.minEndPTS = void 0;
  724. this.data = void 0;
  725. this.bitrateTest = false;
  726. this.title = null;
  727. this.initSegment = null;
  728. this.endList = void 0;
  729. this.gap = void 0;
  730. this.urlId = 0;
  731. this.type = type;
  732. }
  733. get byteLength() {
  734. if (this.hasStats) {
  735. const total = this.stats.total;
  736. if (total) {
  737. return total;
  738. }
  739. }
  740. if (this.byteRange) {
  741. const start = this.byteRange[0];
  742. const end = this.byteRange[1];
  743. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  744. return end - start;
  745. }
  746. }
  747. return null;
  748. }
  749. get bitrate() {
  750. if (this.byteLength) {
  751. return this.byteLength * 8 / this.duration;
  752. }
  753. if (this._bitrate) {
  754. return this._bitrate;
  755. }
  756. return null;
  757. }
  758. set bitrate(value) {
  759. this._bitrate = value;
  760. }
  761. get decryptdata() {
  762. const {
  763. levelkeys
  764. } = this;
  765. if (!levelkeys && !this._decryptdata) {
  766. return null;
  767. }
  768. if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) {
  769. const key = this.levelkeys.identity;
  770. if (key) {
  771. this._decryptdata = key.getDecryptData(this.sn);
  772. } else {
  773. const keyFormats = Object.keys(this.levelkeys);
  774. if (keyFormats.length === 1) {
  775. return this._decryptdata = this.levelkeys[keyFormats[0]].getDecryptData(this.sn);
  776. }
  777. }
  778. }
  779. return this._decryptdata;
  780. }
  781. get end() {
  782. return this.start + this.duration;
  783. }
  784. get endProgramDateTime() {
  785. if (this.programDateTime === null) {
  786. return null;
  787. }
  788. const duration = !isFiniteNumber(this.duration) ? 0 : this.duration;
  789. return this.programDateTime + duration * 1e3;
  790. }
  791. get encrypted() {
  792. var _this$_decryptdata;
  793. if ((_this$_decryptdata = this._decryptdata) != null && _this$_decryptdata.encrypted) {
  794. return true;
  795. } else if (this.levelkeys) {
  796. const keyFormats = Object.keys(this.levelkeys);
  797. const len = keyFormats.length;
  798. if (len > 1 || len === 1 && this.levelkeys[keyFormats[0]].encrypted) {
  799. return true;
  800. }
  801. }
  802. return false;
  803. }
  804. get programDateTime() {
  805. if (this._programDateTime === null && this.rawProgramDateTime) {
  806. this.programDateTime = Date.parse(this.rawProgramDateTime);
  807. }
  808. return this._programDateTime;
  809. }
  810. set programDateTime(value) {
  811. if (!isFiniteNumber(value)) {
  812. this._programDateTime = this.rawProgramDateTime = null;
  813. return;
  814. }
  815. this._programDateTime = value;
  816. }
  817. get ref() {
  818. if (!isMediaFragment(this)) {
  819. return null;
  820. }
  821. if (!this._ref) {
  822. this._ref = {
  823. base: this.base,
  824. start: this.start,
  825. duration: this.duration,
  826. sn: this.sn,
  827. programDateTime: this.programDateTime
  828. };
  829. }
  830. return this._ref;
  831. }
  832. addStart(value) {
  833. this.setStart(this.start + value);
  834. }
  835. setStart(value) {
  836. this.start = value;
  837. if (this._ref) {
  838. this._ref.start = value;
  839. }
  840. }
  841. setDuration(value) {
  842. this.duration = value;
  843. if (this._ref) {
  844. this._ref.duration = value;
  845. }
  846. }
  847. setKeyFormat(keyFormat) {
  848. if (this.levelkeys) {
  849. const key = this.levelkeys[keyFormat];
  850. if (key && !this._decryptdata) {
  851. this._decryptdata = key.getDecryptData(this.sn);
  852. }
  853. }
  854. }
  855. abortRequests() {
  856. var _this$loader, _this$keyLoader;
  857. (_this$loader = this.loader) == null ? void 0 : _this$loader.abort();
  858. (_this$keyLoader = this.keyLoader) == null ? void 0 : _this$keyLoader.abort();
  859. }
  860. setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial = false) {
  861. const {
  862. elementaryStreams
  863. } = this;
  864. const info = elementaryStreams[type];
  865. if (!info) {
  866. elementaryStreams[type] = {
  867. startPTS,
  868. endPTS,
  869. startDTS,
  870. endDTS,
  871. partial
  872. };
  873. return;
  874. }
  875. info.startPTS = Math.min(info.startPTS, startPTS);
  876. info.endPTS = Math.max(info.endPTS, endPTS);
  877. info.startDTS = Math.min(info.startDTS, startDTS);
  878. info.endDTS = Math.max(info.endDTS, endDTS);
  879. }
  880. };
  881. var Part = class extends BaseSegment {
  882. constructor(partAttrs, frag, base, index, previous) {
  883. super(base);
  884. this.fragOffset = 0;
  885. this.duration = 0;
  886. this.gap = false;
  887. this.independent = false;
  888. this.relurl = void 0;
  889. this.fragment = void 0;
  890. this.index = void 0;
  891. this.duration = partAttrs.decimalFloatingPoint("DURATION");
  892. this.gap = partAttrs.bool("GAP");
  893. this.independent = partAttrs.bool("INDEPENDENT");
  894. this.relurl = partAttrs.enumeratedString("URI");
  895. this.fragment = frag;
  896. this.index = index;
  897. const byteRange = partAttrs.enumeratedString("BYTERANGE");
  898. if (byteRange) {
  899. this.setByteRange(byteRange, previous);
  900. }
  901. if (previous) {
  902. this.fragOffset = previous.fragOffset + previous.duration;
  903. }
  904. }
  905. get start() {
  906. return this.fragment.start + this.fragOffset;
  907. }
  908. get end() {
  909. return this.start + this.duration;
  910. }
  911. get loaded() {
  912. const {
  913. elementaryStreams
  914. } = this;
  915. return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
  916. }
  917. };
  918. function getOwnPropertyDescriptorFromPrototypeChain(object, property) {
  919. const prototype = Object.getPrototypeOf(object);
  920. if (prototype) {
  921. const propertyDescriptor = Object.getOwnPropertyDescriptor(prototype, property);
  922. if (propertyDescriptor) {
  923. return propertyDescriptor;
  924. }
  925. return getOwnPropertyDescriptorFromPrototypeChain(prototype, property);
  926. }
  927. }
  928. function makeEnumerable(object, property) {
  929. const d = getOwnPropertyDescriptorFromPrototypeChain(object, property);
  930. if (d) {
  931. d.enumerable = true;
  932. Object.defineProperty(object, property, d);
  933. }
  934. }
  935. var UINT32_MAX$1 = Math.pow(2, 32) - 1;
  936. var push = [].push;
  937. var RemuxerTrackIdConfig = {
  938. video: 1,
  939. audio: 2,
  940. id3: 3,
  941. text: 4
  942. };
  943. function bin2str(data) {
  944. return String.fromCharCode.apply(null, data);
  945. }
  946. function readUint16(buffer, offset) {
  947. const val = buffer[offset] << 8 | buffer[offset + 1];
  948. return val < 0 ? 65536 + val : val;
  949. }
  950. function readUint32(buffer, offset) {
  951. const val = readSint32(buffer, offset);
  952. return val < 0 ? 4294967296 + val : val;
  953. }
  954. function readUint64(buffer, offset) {
  955. let result = readUint32(buffer, offset);
  956. result *= Math.pow(2, 32);
  957. result += readUint32(buffer, offset + 4);
  958. return result;
  959. }
  960. function readSint32(buffer, offset) {
  961. return buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
  962. }
  963. function hasMoofData(data) {
  964. const end = data.byteLength;
  965. for (let i = 0; i < end; ) {
  966. const size = readUint32(data, i);
  967. if (size > 8 && data[i + 4] === 109 && data[i + 5] === 111 && data[i + 6] === 111 && data[i + 7] === 102) {
  968. return true;
  969. }
  970. i = size > 1 ? i + size : end;
  971. }
  972. return false;
  973. }
  974. function findBox(data, path) {
  975. const results = [];
  976. if (!path.length) {
  977. return results;
  978. }
  979. const end = data.byteLength;
  980. for (let i = 0; i < end; ) {
  981. const size = readUint32(data, i);
  982. const type = bin2str(data.subarray(i + 4, i + 8));
  983. const endbox = size > 1 ? i + size : end;
  984. if (type === path[0]) {
  985. if (path.length === 1) {
  986. results.push(data.subarray(i + 8, endbox));
  987. } else {
  988. const subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));
  989. if (subresults.length) {
  990. push.apply(results, subresults);
  991. }
  992. }
  993. }
  994. i = endbox;
  995. }
  996. return results;
  997. }
  998. function parseSegmentIndex(sidx) {
  999. const references = [];
  1000. const version2 = sidx[0];
  1001. let index = 8;
  1002. const timescale = readUint32(sidx, index);
  1003. index += 4;
  1004. let earliestPresentationTime = 0;
  1005. let firstOffset = 0;
  1006. if (version2 === 0) {
  1007. earliestPresentationTime = readUint32(sidx, index);
  1008. firstOffset = readUint32(sidx, index + 4);
  1009. index += 8;
  1010. } else {
  1011. earliestPresentationTime = readUint64(sidx, index);
  1012. firstOffset = readUint64(sidx, index + 8);
  1013. index += 16;
  1014. }
  1015. index += 2;
  1016. let startByte = sidx.length + firstOffset;
  1017. const referencesCount = readUint16(sidx, index);
  1018. index += 2;
  1019. for (let i = 0; i < referencesCount; i++) {
  1020. let referenceIndex = index;
  1021. const referenceInfo = readUint32(sidx, referenceIndex);
  1022. referenceIndex += 4;
  1023. const referenceSize = referenceInfo & 2147483647;
  1024. const referenceType = (referenceInfo & 2147483648) >>> 31;
  1025. if (referenceType === 1) {
  1026. logger.warn("SIDX has hierarchical references (not supported)");
  1027. return null;
  1028. }
  1029. const subsegmentDuration = readUint32(sidx, referenceIndex);
  1030. referenceIndex += 4;
  1031. references.push({
  1032. referenceSize,
  1033. subsegmentDuration,
  1034. info: {
  1035. duration: subsegmentDuration / timescale,
  1036. start: startByte,
  1037. end: startByte + referenceSize - 1
  1038. }
  1039. });
  1040. startByte += referenceSize;
  1041. referenceIndex += 4;
  1042. index = referenceIndex;
  1043. }
  1044. return {
  1045. earliestPresentationTime,
  1046. timescale,
  1047. version: version2,
  1048. referencesCount,
  1049. references
  1050. };
  1051. }
  1052. function parseInitSegment(initSegment) {
  1053. const result = [];
  1054. const traks = findBox(initSegment, ["moov", "trak"]);
  1055. for (let i = 0; i < traks.length; i++) {
  1056. const trak = traks[i];
  1057. const tkhd = findBox(trak, ["tkhd"])[0];
  1058. if (tkhd) {
  1059. let version2 = tkhd[0];
  1060. const trackId = readUint32(tkhd, version2 === 0 ? 12 : 20);
  1061. const mdhd = findBox(trak, ["mdia", "mdhd"])[0];
  1062. if (mdhd) {
  1063. version2 = mdhd[0];
  1064. const timescale = readUint32(mdhd, version2 === 0 ? 12 : 20);
  1065. const hdlr = findBox(trak, ["mdia", "hdlr"])[0];
  1066. if (hdlr) {
  1067. const hdlrType = bin2str(hdlr.subarray(8, 12));
  1068. const type = {
  1069. soun: ElementaryStreamTypes.AUDIO,
  1070. vide: ElementaryStreamTypes.VIDEO
  1071. }[hdlrType];
  1072. const stsdBox = findBox(trak, ["mdia", "minf", "stbl", "stsd"])[0];
  1073. const stsd = parseStsd(stsdBox);
  1074. if (type) {
  1075. result[trackId] = {
  1076. timescale,
  1077. type,
  1078. stsd
  1079. };
  1080. result[type] = _objectSpread2({
  1081. timescale,
  1082. id: trackId
  1083. }, stsd);
  1084. } else {
  1085. result[trackId] = {
  1086. timescale,
  1087. type: hdlrType,
  1088. stsd
  1089. };
  1090. }
  1091. }
  1092. }
  1093. }
  1094. }
  1095. const trex = findBox(initSegment, ["moov", "mvex", "trex"]);
  1096. trex.forEach((trex2) => {
  1097. const trackId = readUint32(trex2, 4);
  1098. const track = result[trackId];
  1099. if (track) {
  1100. track.default = {
  1101. duration: readUint32(trex2, 12),
  1102. flags: readUint32(trex2, 20)
  1103. };
  1104. }
  1105. });
  1106. return result;
  1107. }
  1108. function parseStsd(stsd) {
  1109. const sampleEntries = stsd.subarray(8);
  1110. const sampleEntriesEnd = sampleEntries.subarray(8 + 78);
  1111. const fourCC = bin2str(sampleEntries.subarray(4, 8));
  1112. let codec = fourCC;
  1113. let supplemental;
  1114. const encrypted = fourCC === "enca" || fourCC === "encv";
  1115. if (encrypted) {
  1116. const encBox = findBox(sampleEntries, [fourCC])[0];
  1117. const encBoxChildren = encBox.subarray(fourCC === "enca" ? 28 : 78);
  1118. const sinfs = findBox(encBoxChildren, ["sinf"]);
  1119. sinfs.forEach((sinf) => {
  1120. const schm = findBox(sinf, ["schm"])[0];
  1121. if (schm) {
  1122. const scheme = bin2str(schm.subarray(4, 8));
  1123. if (scheme === "cbcs" || scheme === "cenc") {
  1124. const frma = findBox(sinf, ["frma"])[0];
  1125. if (frma) {
  1126. codec = bin2str(frma);
  1127. }
  1128. }
  1129. }
  1130. });
  1131. }
  1132. const codecFourCC = codec;
  1133. switch (codec) {
  1134. case "avc1":
  1135. case "avc2":
  1136. case "avc3":
  1137. case "avc4": {
  1138. const avcCBox = findBox(sampleEntriesEnd, ["avcC"])[0];
  1139. if (avcCBox && avcCBox.length > 3) {
  1140. codec += "." + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]);
  1141. supplemental = parseSupplementalDoViCodec(codecFourCC === "avc1" ? "dva1" : "dvav", sampleEntriesEnd);
  1142. }
  1143. break;
  1144. }
  1145. case "mp4a": {
  1146. const codecBox = findBox(sampleEntries, [fourCC])[0];
  1147. const esdsBox = findBox(codecBox.subarray(28), ["esds"])[0];
  1148. if (esdsBox && esdsBox.length > 7) {
  1149. let i = 4;
  1150. if (esdsBox[i++] !== 3) {
  1151. break;
  1152. }
  1153. i = skipBERInteger(esdsBox, i);
  1154. i += 2;
  1155. const flags = esdsBox[i++];
  1156. if (flags & 128) {
  1157. i += 2;
  1158. }
  1159. if (flags & 64) {
  1160. i += esdsBox[i++];
  1161. }
  1162. if (esdsBox[i++] !== 4) {
  1163. break;
  1164. }
  1165. i = skipBERInteger(esdsBox, i);
  1166. const objectType = esdsBox[i++];
  1167. if (objectType === 64) {
  1168. codec += "." + toHex(objectType);
  1169. } else {
  1170. break;
  1171. }
  1172. i += 12;
  1173. if (esdsBox[i++] !== 5) {
  1174. break;
  1175. }
  1176. i = skipBERInteger(esdsBox, i);
  1177. const firstByte = esdsBox[i++];
  1178. let audioObjectType = (firstByte & 248) >> 3;
  1179. if (audioObjectType === 31) {
  1180. audioObjectType += 1 + ((firstByte & 7) << 3) + ((esdsBox[i] & 224) >> 5);
  1181. }
  1182. codec += "." + audioObjectType;
  1183. }
  1184. break;
  1185. }
  1186. case "hvc1":
  1187. case "hev1": {
  1188. const hvcCBox = findBox(sampleEntriesEnd, ["hvcC"])[0];
  1189. if (hvcCBox && hvcCBox.length > 12) {
  1190. const profileByte = hvcCBox[1];
  1191. const profileSpace = ["", "A", "B", "C"][profileByte >> 6];
  1192. const generalProfileIdc = profileByte & 31;
  1193. const profileCompat = readUint32(hvcCBox, 2);
  1194. const tierFlag = (profileByte & 32) >> 5 ? "H" : "L";
  1195. const levelIDC = hvcCBox[12];
  1196. const constraintIndicator = hvcCBox.subarray(6, 12);
  1197. codec += "." + profileSpace + generalProfileIdc;
  1198. codec += "." + reverse32BitInt(profileCompat).toString(16).toUpperCase();
  1199. codec += "." + tierFlag + levelIDC;
  1200. let constraintString = "";
  1201. for (let i = constraintIndicator.length; i--; ) {
  1202. const byte = constraintIndicator[i];
  1203. if (byte || constraintString) {
  1204. const encodedByte = byte.toString(16).toUpperCase();
  1205. constraintString = "." + encodedByte + constraintString;
  1206. }
  1207. }
  1208. codec += constraintString;
  1209. }
  1210. supplemental = parseSupplementalDoViCodec(codecFourCC == "hev1" ? "dvhe" : "dvh1", sampleEntriesEnd);
  1211. break;
  1212. }
  1213. case "dvh1":
  1214. case "dvhe":
  1215. case "dvav":
  1216. case "dva1":
  1217. case "dav1": {
  1218. codec = parseSupplementalDoViCodec(codec, sampleEntriesEnd) || codec;
  1219. break;
  1220. }
  1221. case "vp09": {
  1222. const vpcCBox = findBox(sampleEntriesEnd, ["vpcC"])[0];
  1223. if (vpcCBox && vpcCBox.length > 6) {
  1224. const profile = vpcCBox[4];
  1225. const level = vpcCBox[5];
  1226. const bitDepth = vpcCBox[6] >> 4 & 15;
  1227. codec += "." + addLeadingZero(profile) + "." + addLeadingZero(level) + "." + addLeadingZero(bitDepth);
  1228. }
  1229. break;
  1230. }
  1231. case "av01": {
  1232. const av1CBox = findBox(sampleEntriesEnd, ["av1C"])[0];
  1233. if (av1CBox && av1CBox.length > 2) {
  1234. const profile = av1CBox[1] >>> 5;
  1235. const level = av1CBox[1] & 31;
  1236. const tierFlag = av1CBox[2] >>> 7 ? "H" : "M";
  1237. const highBitDepth = (av1CBox[2] & 64) >> 6;
  1238. const twelveBit = (av1CBox[2] & 32) >> 5;
  1239. const bitDepth = profile === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8;
  1240. const monochrome = (av1CBox[2] & 16) >> 4;
  1241. const chromaSubsamplingX = (av1CBox[2] & 8) >> 3;
  1242. const chromaSubsamplingY = (av1CBox[2] & 4) >> 2;
  1243. const chromaSamplePosition = av1CBox[2] & 3;
  1244. const colorPrimaries = 1;
  1245. const transferCharacteristics = 1;
  1246. const matrixCoefficients = 1;
  1247. const videoFullRangeFlag = 0;
  1248. codec += "." + profile + "." + addLeadingZero(level) + tierFlag + "." + addLeadingZero(bitDepth) + "." + monochrome + "." + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition + "." + addLeadingZero(colorPrimaries) + "." + addLeadingZero(transferCharacteristics) + "." + addLeadingZero(matrixCoefficients) + "." + videoFullRangeFlag;
  1249. supplemental = parseSupplementalDoViCodec("dav1", sampleEntriesEnd);
  1250. }
  1251. break;
  1252. }
  1253. }
  1254. return {
  1255. codec,
  1256. encrypted,
  1257. supplemental
  1258. };
  1259. }
  1260. function parseSupplementalDoViCodec(fourCC, sampleEntriesEnd) {
  1261. const dvvCResult = findBox(sampleEntriesEnd, ["dvvC"]);
  1262. const dvXCBox = dvvCResult.length ? dvvCResult[0] : findBox(sampleEntriesEnd, ["dvcC"])[0];
  1263. if (dvXCBox) {
  1264. const doViProfile = dvXCBox[2] >> 1 & 127;
  1265. const doViLevel = dvXCBox[2] << 5 & 32 | dvXCBox[3] >> 3 & 31;
  1266. return fourCC + "." + addLeadingZero(doViProfile) + "." + addLeadingZero(doViLevel);
  1267. }
  1268. }
  1269. function reverse32BitInt(val) {
  1270. let result = 0;
  1271. for (let i = 0; i < 32; i++) {
  1272. result |= (val >> i & 1) << 32 - 1 - i;
  1273. }
  1274. return result >>> 0;
  1275. }
  1276. function skipBERInteger(bytes, i) {
  1277. const limit = i + 5;
  1278. while (bytes[i++] & 128 && i < limit) {
  1279. }
  1280. return i;
  1281. }
  1282. function toHex(x) {
  1283. return ("0" + x.toString(16).toUpperCase()).slice(-2);
  1284. }
  1285. function addLeadingZero(num) {
  1286. return (num < 10 ? "0" : "") + num;
  1287. }
  1288. function patchEncyptionData(initSegment, decryptdata) {
  1289. if (!initSegment || !decryptdata) {
  1290. return initSegment;
  1291. }
  1292. const keyId = decryptdata.keyId;
  1293. if (keyId && decryptdata.isCommonEncryption) {
  1294. const traks = findBox(initSegment, ["moov", "trak"]);
  1295. traks.forEach((trak) => {
  1296. const stsd = findBox(trak, ["mdia", "minf", "stbl", "stsd"])[0];
  1297. const sampleEntries = stsd.subarray(8);
  1298. let encBoxes = findBox(sampleEntries, ["enca"]);
  1299. const isAudio = encBoxes.length > 0;
  1300. if (!isAudio) {
  1301. encBoxes = findBox(sampleEntries, ["encv"]);
  1302. }
  1303. encBoxes.forEach((enc) => {
  1304. const encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);
  1305. const sinfBoxes = findBox(encBoxChildren, ["sinf"]);
  1306. sinfBoxes.forEach((sinf) => {
  1307. const tenc = parseSinf(sinf);
  1308. if (tenc) {
  1309. const tencKeyId = tenc.subarray(8, 24);
  1310. if (!tencKeyId.some((b) => b !== 0)) {
  1311. logger.log(`[eme] Patching keyId in 'enc${isAudio ? "a" : "v"}>sinf>>tenc' box: ${Hex.hexDump(tencKeyId)} -> ${Hex.hexDump(keyId)}`);
  1312. tenc.set(keyId, 8);
  1313. }
  1314. }
  1315. });
  1316. });
  1317. });
  1318. }
  1319. return initSegment;
  1320. }
  1321. function parseSinf(sinf) {
  1322. const schm = findBox(sinf, ["schm"])[0];
  1323. if (schm) {
  1324. const scheme = bin2str(schm.subarray(4, 8));
  1325. if (scheme === "cbcs" || scheme === "cenc") {
  1326. return findBox(sinf, ["schi", "tenc"])[0];
  1327. }
  1328. }
  1329. return null;
  1330. }
  1331. function getSampleData(data, initData, logger2) {
  1332. const tracks = {};
  1333. const trafs = findBox(data, ["moof", "traf"]);
  1334. for (let i = 0; i < trafs.length; i++) {
  1335. const traf = trafs[i];
  1336. const tfhd = findBox(traf, ["tfhd"])[0];
  1337. const id = readUint32(tfhd, 4);
  1338. const track = initData[id];
  1339. if (!track) {
  1340. continue;
  1341. }
  1342. const trackTimes = tracks[id] || (tracks[id] = {
  1343. start: NaN,
  1344. duration: 0,
  1345. sampleCount: 0,
  1346. timescale: track.timescale,
  1347. type: track.type
  1348. });
  1349. const tfdt = findBox(traf, ["tfdt"])[0];
  1350. if (tfdt) {
  1351. const version2 = tfdt[0];
  1352. let baseTime = readUint32(tfdt, 4);
  1353. if (version2 === 1) {
  1354. if (baseTime === UINT32_MAX$1) {
  1355. logger2.warn(`[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`);
  1356. } else {
  1357. baseTime *= UINT32_MAX$1 + 1;
  1358. baseTime += readUint32(tfdt, 8);
  1359. }
  1360. }
  1361. if (isFiniteNumber(baseTime) && (!isFiniteNumber(trackTimes.start) || baseTime < trackTimes.start)) {
  1362. trackTimes.start = baseTime;
  1363. }
  1364. }
  1365. const trackDefault = track.default;
  1366. const tfhdFlags = readUint32(tfhd, 0) | (trackDefault == null ? void 0 : trackDefault.flags);
  1367. let defaultSampleDuration = (trackDefault == null ? void 0 : trackDefault.duration) || 0;
  1368. if (tfhdFlags & 8) {
  1369. if (tfhdFlags & 2) {
  1370. defaultSampleDuration = readUint32(tfhd, 12);
  1371. } else {
  1372. defaultSampleDuration = readUint32(tfhd, 8);
  1373. }
  1374. }
  1375. const truns = findBox(traf, ["trun"]);
  1376. let sampleDTS = trackTimes.start || 0;
  1377. let rawDuration = 0;
  1378. let sampleDuration = defaultSampleDuration;
  1379. for (let j = 0; j < truns.length; j++) {
  1380. const trun = truns[j];
  1381. const sampleCount = readUint32(trun, 4);
  1382. const sampleIndex = trackTimes.sampleCount;
  1383. trackTimes.sampleCount += sampleCount;
  1384. const dataOffsetPresent = trun[3] & 1;
  1385. const firstSampleFlagsPresent = trun[3] & 4;
  1386. const sampleDurationPresent = trun[2] & 1;
  1387. const sampleSizePresent = trun[2] & 2;
  1388. const sampleFlagsPresent = trun[2] & 4;
  1389. const sampleCompositionTimeOffsetPresent = trun[2] & 8;
  1390. let offset = 8;
  1391. let remaining = sampleCount;
  1392. if (dataOffsetPresent) {
  1393. offset += 4;
  1394. }
  1395. if (firstSampleFlagsPresent && sampleCount) {
  1396. const isNonSyncSample = trun[offset + 1] & 1;
  1397. if (!isNonSyncSample && trackTimes.keyFrameIndex === void 0) {
  1398. trackTimes.keyFrameIndex = sampleIndex;
  1399. }
  1400. offset += 4;
  1401. if (sampleDurationPresent) {
  1402. sampleDuration = readUint32(trun, offset);
  1403. offset += 4;
  1404. } else {
  1405. sampleDuration = defaultSampleDuration;
  1406. }
  1407. if (sampleSizePresent) {
  1408. offset += 4;
  1409. }
  1410. if (sampleCompositionTimeOffsetPresent) {
  1411. offset += 4;
  1412. }
  1413. sampleDTS += sampleDuration;
  1414. rawDuration += sampleDuration;
  1415. remaining--;
  1416. }
  1417. while (remaining--) {
  1418. if (sampleDurationPresent) {
  1419. sampleDuration = readUint32(trun, offset);
  1420. offset += 4;
  1421. } else {
  1422. sampleDuration = defaultSampleDuration;
  1423. }
  1424. if (sampleSizePresent) {
  1425. offset += 4;
  1426. }
  1427. if (sampleFlagsPresent) {
  1428. const isNonSyncSample = trun[offset + 1] & 1;
  1429. if (!isNonSyncSample) {
  1430. if (trackTimes.keyFrameIndex === void 0) {
  1431. trackTimes.keyFrameIndex = trackTimes.sampleCount - (remaining + 1);
  1432. trackTimes.keyFrameStart = sampleDTS;
  1433. }
  1434. }
  1435. offset += 4;
  1436. }
  1437. if (sampleCompositionTimeOffsetPresent) {
  1438. offset += 4;
  1439. }
  1440. sampleDTS += sampleDuration;
  1441. rawDuration += sampleDuration;
  1442. }
  1443. if (!rawDuration && defaultSampleDuration) {
  1444. rawDuration += defaultSampleDuration * sampleCount;
  1445. }
  1446. }
  1447. trackTimes.duration += rawDuration;
  1448. }
  1449. if (!Object.keys(tracks).some((trackId) => tracks[trackId].duration)) {
  1450. let sidxMinStart = Infinity;
  1451. let sidxMaxEnd = 0;
  1452. const sidxs = findBox(data, ["sidx"]);
  1453. for (let i = 0; i < sidxs.length; i++) {
  1454. const sidx = parseSegmentIndex(sidxs[i]);
  1455. if (sidx != null && sidx.references) {
  1456. sidxMinStart = Math.min(sidxMinStart, sidx.earliestPresentationTime / sidx.timescale);
  1457. const subSegmentDuration = sidx.references.reduce((dur, ref) => dur + ref.info.duration || 0, 0);
  1458. sidxMaxEnd = Math.max(sidxMaxEnd, subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale);
  1459. }
  1460. }
  1461. if (sidxMaxEnd && isFiniteNumber(sidxMaxEnd)) {
  1462. Object.keys(tracks).forEach((trackId) => {
  1463. if (!tracks[trackId].duration) {
  1464. tracks[trackId].duration = sidxMaxEnd * tracks[trackId].timescale - tracks[trackId].start;
  1465. }
  1466. });
  1467. }
  1468. }
  1469. return tracks;
  1470. }
  1471. function segmentValidRange(data) {
  1472. const segmentedRange = {
  1473. valid: null,
  1474. remainder: null
  1475. };
  1476. const moofs = findBox(data, ["moof"]);
  1477. if (moofs.length < 2) {
  1478. segmentedRange.remainder = data;
  1479. return segmentedRange;
  1480. }
  1481. const last = moofs[moofs.length - 1];
  1482. segmentedRange.valid = data.slice(0, last.byteOffset - 8);
  1483. segmentedRange.remainder = data.slice(last.byteOffset - 8);
  1484. return segmentedRange;
  1485. }
  1486. function appendUint8Array(data1, data2) {
  1487. const temp = new Uint8Array(data1.length + data2.length);
  1488. temp.set(data1);
  1489. temp.set(data2, data1.length);
  1490. return temp;
  1491. }
  1492. function parseSamples(timeOffset, track) {
  1493. const seiSamples = [];
  1494. const videoData = track.samples;
  1495. const timescale = track.timescale;
  1496. const trackId = track.id;
  1497. let isHEVCFlavor = false;
  1498. const moofs = findBox(videoData, ["moof"]);
  1499. moofs.map((moof) => {
  1500. const moofOffset = moof.byteOffset - 8;
  1501. const trafs = findBox(moof, ["traf"]);
  1502. trafs.map((traf) => {
  1503. const baseTime = findBox(traf, ["tfdt"]).map((tfdt) => {
  1504. const version2 = tfdt[0];
  1505. let result = readUint32(tfdt, 4);
  1506. if (version2 === 1) {
  1507. result *= Math.pow(2, 32);
  1508. result += readUint32(tfdt, 8);
  1509. }
  1510. return result / timescale;
  1511. })[0];
  1512. if (baseTime !== void 0) {
  1513. timeOffset = baseTime;
  1514. }
  1515. return findBox(traf, ["tfhd"]).map((tfhd) => {
  1516. const id = readUint32(tfhd, 4);
  1517. const tfhdFlags = readUint32(tfhd, 0) & 16777215;
  1518. const baseDataOffsetPresent = (tfhdFlags & 1) !== 0;
  1519. const sampleDescriptionIndexPresent = (tfhdFlags & 2) !== 0;
  1520. const defaultSampleDurationPresent = (tfhdFlags & 8) !== 0;
  1521. let defaultSampleDuration = 0;
  1522. const defaultSampleSizePresent = (tfhdFlags & 16) !== 0;
  1523. let defaultSampleSize = 0;
  1524. const defaultSampleFlagsPresent = (tfhdFlags & 32) !== 0;
  1525. let tfhdOffset = 8;
  1526. if (id === trackId) {
  1527. if (baseDataOffsetPresent) {
  1528. tfhdOffset += 8;
  1529. }
  1530. if (sampleDescriptionIndexPresent) {
  1531. tfhdOffset += 4;
  1532. }
  1533. if (defaultSampleDurationPresent) {
  1534. defaultSampleDuration = readUint32(tfhd, tfhdOffset);
  1535. tfhdOffset += 4;
  1536. }
  1537. if (defaultSampleSizePresent) {
  1538. defaultSampleSize = readUint32(tfhd, tfhdOffset);
  1539. tfhdOffset += 4;
  1540. }
  1541. if (defaultSampleFlagsPresent) {
  1542. tfhdOffset += 4;
  1543. }
  1544. if (track.type === "video") {
  1545. isHEVCFlavor = isHEVC(track.codec);
  1546. }
  1547. findBox(traf, ["trun"]).map((trun) => {
  1548. const version2 = trun[0];
  1549. const flags = readUint32(trun, 0) & 16777215;
  1550. const dataOffsetPresent = (flags & 1) !== 0;
  1551. let dataOffset = 0;
  1552. const firstSampleFlagsPresent = (flags & 4) !== 0;
  1553. const sampleDurationPresent = (flags & 256) !== 0;
  1554. let sampleDuration = 0;
  1555. const sampleSizePresent = (flags & 512) !== 0;
  1556. let sampleSize = 0;
  1557. const sampleFlagsPresent = (flags & 1024) !== 0;
  1558. const sampleCompositionOffsetsPresent = (flags & 2048) !== 0;
  1559. let compositionOffset = 0;
  1560. const sampleCount = readUint32(trun, 4);
  1561. let trunOffset = 8;
  1562. if (dataOffsetPresent) {
  1563. dataOffset = readUint32(trun, trunOffset);
  1564. trunOffset += 4;
  1565. }
  1566. if (firstSampleFlagsPresent) {
  1567. trunOffset += 4;
  1568. }
  1569. let sampleOffset = dataOffset + moofOffset;
  1570. for (let ix = 0; ix < sampleCount; ix++) {
  1571. if (sampleDurationPresent) {
  1572. sampleDuration = readUint32(trun, trunOffset);
  1573. trunOffset += 4;
  1574. } else {
  1575. sampleDuration = defaultSampleDuration;
  1576. }
  1577. if (sampleSizePresent) {
  1578. sampleSize = readUint32(trun, trunOffset);
  1579. trunOffset += 4;
  1580. } else {
  1581. sampleSize = defaultSampleSize;
  1582. }
  1583. if (sampleFlagsPresent) {
  1584. trunOffset += 4;
  1585. }
  1586. if (sampleCompositionOffsetsPresent) {
  1587. if (version2 === 0) {
  1588. compositionOffset = readUint32(trun, trunOffset);
  1589. } else {
  1590. compositionOffset = readSint32(trun, trunOffset);
  1591. }
  1592. trunOffset += 4;
  1593. }
  1594. if (track.type === ElementaryStreamTypes.VIDEO) {
  1595. let naluTotalSize = 0;
  1596. while (naluTotalSize < sampleSize) {
  1597. const naluSize = readUint32(videoData, sampleOffset);
  1598. sampleOffset += 4;
  1599. if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {
  1600. const data = videoData.subarray(sampleOffset, sampleOffset + naluSize);
  1601. parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale, seiSamples);
  1602. }
  1603. sampleOffset += naluSize;
  1604. naluTotalSize += naluSize + 4;
  1605. }
  1606. }
  1607. timeOffset += sampleDuration / timescale;
  1608. }
  1609. });
  1610. }
  1611. });
  1612. });
  1613. });
  1614. return seiSamples;
  1615. }
  1616. function isHEVC(codec) {
  1617. if (!codec) {
  1618. return false;
  1619. }
  1620. const baseCodec = codec.substring(0, 4);
  1621. return baseCodec === "hvc1" || baseCodec === "hev1" || baseCodec === "dvh1" || baseCodec === "dvhe";
  1622. }
  1623. function isSEIMessage(isHEVCFlavor, naluHeader) {
  1624. if (isHEVCFlavor) {
  1625. const naluType = naluHeader >> 1 & 63;
  1626. return naluType === 39 || naluType === 40;
  1627. } else {
  1628. const naluType = naluHeader & 31;
  1629. return naluType === 6;
  1630. }
  1631. }
  1632. function parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) {
  1633. const data = discardEPB(unescapedData);
  1634. let seiPtr = 0;
  1635. seiPtr += headerSize;
  1636. let payloadType = 0;
  1637. let payloadSize = 0;
  1638. let b = 0;
  1639. while (seiPtr < data.length) {
  1640. payloadType = 0;
  1641. do {
  1642. if (seiPtr >= data.length) {
  1643. break;
  1644. }
  1645. b = data[seiPtr++];
  1646. payloadType += b;
  1647. } while (b === 255);
  1648. payloadSize = 0;
  1649. do {
  1650. if (seiPtr >= data.length) {
  1651. break;
  1652. }
  1653. b = data[seiPtr++];
  1654. payloadSize += b;
  1655. } while (b === 255);
  1656. const leftOver = data.length - seiPtr;
  1657. let payPtr = seiPtr;
  1658. if (payloadSize < leftOver) {
  1659. seiPtr += payloadSize;
  1660. } else if (payloadSize > leftOver) {
  1661. logger.error(`Malformed SEI payload. ${payloadSize} is too small, only ${leftOver} bytes left to parse.`);
  1662. break;
  1663. }
  1664. if (payloadType === 4) {
  1665. const countryCode = data[payPtr++];
  1666. if (countryCode === 181) {
  1667. const providerCode = readUint16(data, payPtr);
  1668. payPtr += 2;
  1669. if (providerCode === 49) {
  1670. const userStructure = readUint32(data, payPtr);
  1671. payPtr += 4;
  1672. if (userStructure === 1195456820) {
  1673. const userDataType = data[payPtr++];
  1674. if (userDataType === 3) {
  1675. const firstByte = data[payPtr++];
  1676. const totalCCs = 31 & firstByte;
  1677. const enabled = 64 & firstByte;
  1678. const totalBytes = enabled ? 2 + totalCCs * 3 : 0;
  1679. const byteArray = new Uint8Array(totalBytes);
  1680. if (enabled) {
  1681. byteArray[0] = firstByte;
  1682. for (let i = 1; i < totalBytes; i++) {
  1683. byteArray[i] = data[payPtr++];
  1684. }
  1685. }
  1686. samples.push({
  1687. type: userDataType,
  1688. payloadType,
  1689. pts,
  1690. bytes: byteArray
  1691. });
  1692. }
  1693. }
  1694. }
  1695. }
  1696. } else if (payloadType === 5) {
  1697. if (payloadSize > 16) {
  1698. const uuidStrArray = [];
  1699. for (let i = 0; i < 16; i++) {
  1700. const _b = data[payPtr++].toString(16);
  1701. uuidStrArray.push(_b.length == 1 ? "0" + _b : _b);
  1702. if (i === 3 || i === 5 || i === 7 || i === 9) {
  1703. uuidStrArray.push("-");
  1704. }
  1705. }
  1706. const length = payloadSize - 16;
  1707. const userDataBytes = new Uint8Array(length);
  1708. for (let i = 0; i < length; i++) {
  1709. userDataBytes[i] = data[payPtr++];
  1710. }
  1711. samples.push({
  1712. payloadType,
  1713. pts,
  1714. uuid: uuidStrArray.join(""),
  1715. userData: utf8ArrayToStr(userDataBytes),
  1716. userDataBytes
  1717. });
  1718. }
  1719. }
  1720. }
  1721. }
  1722. function discardEPB(data) {
  1723. const length = data.byteLength;
  1724. const EPBPositions = [];
  1725. let i = 1;
  1726. while (i < length - 2) {
  1727. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 3) {
  1728. EPBPositions.push(i + 2);
  1729. i += 2;
  1730. } else {
  1731. i++;
  1732. }
  1733. }
  1734. if (EPBPositions.length === 0) {
  1735. return data;
  1736. }
  1737. const newLength = length - EPBPositions.length;
  1738. const newData = new Uint8Array(newLength);
  1739. let sourceIndex = 0;
  1740. for (i = 0; i < newLength; sourceIndex++, i++) {
  1741. if (sourceIndex === EPBPositions[0]) {
  1742. sourceIndex++;
  1743. EPBPositions.shift();
  1744. }
  1745. newData[i] = data[sourceIndex];
  1746. }
  1747. return newData;
  1748. }
  1749. function parseEmsg(data) {
  1750. const version2 = data[0];
  1751. let schemeIdUri = "";
  1752. let value = "";
  1753. let timeScale = 0;
  1754. let presentationTimeDelta = 0;
  1755. let presentationTime = 0;
  1756. let eventDuration = 0;
  1757. let id = 0;
  1758. let offset = 0;
  1759. if (version2 === 0) {
  1760. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  1761. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  1762. offset += 1;
  1763. }
  1764. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  1765. offset += 1;
  1766. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  1767. value += bin2str(data.subarray(offset, offset + 1));
  1768. offset += 1;
  1769. }
  1770. value += bin2str(data.subarray(offset, offset + 1));
  1771. offset += 1;
  1772. timeScale = readUint32(data, 12);
  1773. presentationTimeDelta = readUint32(data, 16);
  1774. eventDuration = readUint32(data, 20);
  1775. id = readUint32(data, 24);
  1776. offset = 28;
  1777. } else if (version2 === 1) {
  1778. offset += 4;
  1779. timeScale = readUint32(data, offset);
  1780. offset += 4;
  1781. const leftPresentationTime = readUint32(data, offset);
  1782. offset += 4;
  1783. const rightPresentationTime = readUint32(data, offset);
  1784. offset += 4;
  1785. presentationTime = 2 ** 32 * leftPresentationTime + rightPresentationTime;
  1786. if (!isSafeInteger(presentationTime)) {
  1787. presentationTime = Number.MAX_SAFE_INTEGER;
  1788. logger.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box");
  1789. }
  1790. eventDuration = readUint32(data, offset);
  1791. offset += 4;
  1792. id = readUint32(data, offset);
  1793. offset += 4;
  1794. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  1795. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  1796. offset += 1;
  1797. }
  1798. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  1799. offset += 1;
  1800. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  1801. value += bin2str(data.subarray(offset, offset + 1));
  1802. offset += 1;
  1803. }
  1804. value += bin2str(data.subarray(offset, offset + 1));
  1805. offset += 1;
  1806. }
  1807. const payload = data.subarray(offset, data.byteLength);
  1808. return {
  1809. schemeIdUri,
  1810. value,
  1811. timeScale,
  1812. presentationTime,
  1813. presentationTimeDelta,
  1814. eventDuration,
  1815. id,
  1816. payload
  1817. };
  1818. }
  1819. function mp4Box(type, ...payload) {
  1820. const len = payload.length;
  1821. let size = 8;
  1822. let i = len;
  1823. while (i--) {
  1824. size += payload[i].byteLength;
  1825. }
  1826. const result = new Uint8Array(size);
  1827. result[0] = size >> 24 & 255;
  1828. result[1] = size >> 16 & 255;
  1829. result[2] = size >> 8 & 255;
  1830. result[3] = size & 255;
  1831. result.set(type, 4);
  1832. for (i = 0, size = 8; i < len; i++) {
  1833. result.set(payload[i], size);
  1834. size += payload[i].byteLength;
  1835. }
  1836. return result;
  1837. }
  1838. function mp4pssh(systemId, keyids, data) {
  1839. if (systemId.byteLength !== 16) {
  1840. throw new RangeError("Invalid system id");
  1841. }
  1842. let version2;
  1843. let kids;
  1844. {
  1845. version2 = 0;
  1846. kids = new Uint8Array();
  1847. }
  1848. let kidCount;
  1849. if (version2 > 0) {
  1850. kidCount = new Uint8Array(4);
  1851. if (keyids.length > 0) {
  1852. new DataView(kidCount.buffer).setUint32(0, keyids.length, false);
  1853. }
  1854. } else {
  1855. kidCount = new Uint8Array();
  1856. }
  1857. const dataSize = new Uint8Array(4);
  1858. if (data && data.byteLength > 0) {
  1859. new DataView(dataSize.buffer).setUint32(0, data.byteLength, false);
  1860. }
  1861. return mp4Box([112, 115, 115, 104], new Uint8Array([
  1862. version2,
  1863. 0,
  1864. 0,
  1865. 0
  1866. ]), systemId, kidCount, kids, dataSize, data || new Uint8Array());
  1867. }
  1868. var userAgentHevcSupportIsInaccurate = () => {
  1869. return /\(Windows.+Firefox\//i.test(navigator.userAgent);
  1870. };
  1871. var sampleEntryCodesISO = {
  1872. audio: {
  1873. a3ds: 1,
  1874. "ac-3": 0.95,
  1875. "ac-4": 1,
  1876. alac: 0.9,
  1877. alaw: 1,
  1878. dra1: 1,
  1879. "dts+": 1,
  1880. "dts-": 1,
  1881. dtsc: 1,
  1882. dtse: 1,
  1883. dtsh: 1,
  1884. "ec-3": 0.9,
  1885. enca: 1,
  1886. fLaC: 0.9,
  1887. flac: 0.9,
  1888. FLAC: 0.9,
  1889. g719: 1,
  1890. g726: 1,
  1891. m4ae: 1,
  1892. mha1: 1,
  1893. mha2: 1,
  1894. mhm1: 1,
  1895. mhm2: 1,
  1896. mlpa: 1,
  1897. mp4a: 1,
  1898. "raw ": 1,
  1899. Opus: 1,
  1900. opus: 1,
  1901. samr: 1,
  1902. sawb: 1,
  1903. sawp: 1,
  1904. sevc: 1,
  1905. sqcp: 1,
  1906. ssmv: 1,
  1907. twos: 1,
  1908. ulaw: 1
  1909. },
  1910. video: {
  1911. avc1: 1,
  1912. avc2: 1,
  1913. avc3: 1,
  1914. avc4: 1,
  1915. avcp: 1,
  1916. av01: 0.8,
  1917. dav1: 0.8,
  1918. drac: 1,
  1919. dva1: 1,
  1920. dvav: 1,
  1921. dvh1: 0.7,
  1922. dvhe: 0.7,
  1923. encv: 1,
  1924. hev1: 0.75,
  1925. hvc1: 0.75,
  1926. mjp2: 1,
  1927. mp4v: 1,
  1928. mvc1: 1,
  1929. mvc2: 1,
  1930. mvc3: 1,
  1931. mvc4: 1,
  1932. resv: 1,
  1933. rv60: 1,
  1934. s263: 1,
  1935. svc1: 1,
  1936. svc2: 1,
  1937. "vc-1": 1,
  1938. vp08: 1,
  1939. vp09: 0.9
  1940. },
  1941. text: {
  1942. stpp: 1,
  1943. wvtt: 1
  1944. }
  1945. };
  1946. function isCodecType(codec, type) {
  1947. const typeCodes = sampleEntryCodesISO[type];
  1948. return !!typeCodes && !!typeCodes[codec.slice(0, 4)];
  1949. }
  1950. function areCodecsMediaSourceSupported(codecs, type, preferManagedMediaSource = true) {
  1951. return !codecs.split(",").some((codec) => !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource));
  1952. }
  1953. function isCodecMediaSourceSupported(codec, type, preferManagedMediaSource = true) {
  1954. var _MediaSource$isTypeSu;
  1955. const MediaSource = getMediaSource(preferManagedMediaSource);
  1956. return (_MediaSource$isTypeSu = MediaSource == null ? void 0 : MediaSource.isTypeSupported(mimeTypeForCodec(codec, type))) != null ? _MediaSource$isTypeSu : false;
  1957. }
  1958. function mimeTypeForCodec(codec, type) {
  1959. return `${type}/mp4;codecs=${codec}`;
  1960. }
  1961. function videoCodecPreferenceValue(videoCodec) {
  1962. if (videoCodec) {
  1963. const fourCC = videoCodec.substring(0, 4);
  1964. return sampleEntryCodesISO.video[fourCC];
  1965. }
  1966. return 2;
  1967. }
  1968. function codecsSetSelectionPreferenceValue(codecSet) {
  1969. const limitedHevcSupport = userAgentHevcSupportIsInaccurate();
  1970. return codecSet.split(",").reduce((num, fourCC) => {
  1971. const lowerPriority = limitedHevcSupport && isHEVC(fourCC);
  1972. const preferenceValue = lowerPriority ? 9 : sampleEntryCodesISO.video[fourCC];
  1973. if (preferenceValue) {
  1974. return (preferenceValue * 2 + num) / (num ? 3 : 2);
  1975. }
  1976. return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);
  1977. }, 0);
  1978. }
  1979. var CODEC_COMPATIBLE_NAMES = {};
  1980. function getCodecCompatibleNameLower(lowerCaseCodec, preferManagedMediaSource = true) {
  1981. if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {
  1982. return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];
  1983. }
  1984. const codecsToCheck = {
  1985. flac: ["flac", "fLaC", "FLAC"],
  1986. opus: ["opus", "Opus"],
  1987. "mp4a.40.34": ["mp3"]
  1988. }[lowerCaseCodec];
  1989. for (let i = 0; i < codecsToCheck.length; i++) {
  1990. var _getMediaSource;
  1991. if (isCodecMediaSourceSupported(codecsToCheck[i], "audio", preferManagedMediaSource)) {
  1992. CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i];
  1993. return codecsToCheck[i];
  1994. } else if (codecsToCheck[i] === "mp3" && (_getMediaSource = getMediaSource(preferManagedMediaSource)) != null && _getMediaSource.isTypeSupported("audio/mpeg")) {
  1995. return "";
  1996. }
  1997. }
  1998. return lowerCaseCodec;
  1999. }
  2000. var AUDIO_CODEC_REGEXP = /flac|opus|mp4a\.40\.34/i;
  2001. function getCodecCompatibleName(codec, preferManagedMediaSource = true) {
  2002. return codec.replace(AUDIO_CODEC_REGEXP, (m) => getCodecCompatibleNameLower(m.toLowerCase(), preferManagedMediaSource));
  2003. }
  2004. function replaceVideoCodec(originalCodecs, newVideoCodec) {
  2005. const codecs = [];
  2006. if (originalCodecs) {
  2007. const allCodecs = originalCodecs.split(",");
  2008. for (let i = 0; i < allCodecs.length; i++) {
  2009. if (!isCodecType(allCodecs[i], "video")) {
  2010. codecs.push(allCodecs[i]);
  2011. }
  2012. }
  2013. }
  2014. if (newVideoCodec) {
  2015. codecs.push(newVideoCodec);
  2016. }
  2017. return codecs.join(",");
  2018. }
  2019. function pickMostCompleteCodecName(parsedCodec, levelCodec) {
  2020. if (parsedCodec && (parsedCodec.length > 4 || ["ac-3", "ec-3", "alac", "fLaC", "Opus"].indexOf(parsedCodec) !== -1)) {
  2021. if (isCodecSupportedAsType(parsedCodec, "audio") || isCodecSupportedAsType(parsedCodec, "video")) {
  2022. return parsedCodec;
  2023. }
  2024. }
  2025. if (levelCodec) {
  2026. const levelCodecs = levelCodec.split(",");
  2027. if (levelCodecs.length > 1) {
  2028. if (parsedCodec) {
  2029. for (let i = levelCodecs.length; i--; ) {
  2030. if (levelCodecs[i].substring(0, 4) === parsedCodec.substring(0, 4)) {
  2031. return levelCodecs[i];
  2032. }
  2033. }
  2034. }
  2035. return levelCodecs[0];
  2036. }
  2037. }
  2038. return levelCodec || parsedCodec;
  2039. }
  2040. function isCodecSupportedAsType(codec, type) {
  2041. return isCodecType(codec, type) && isCodecMediaSourceSupported(codec, type);
  2042. }
  2043. function convertAVC1ToAVCOTI(videoCodecs) {
  2044. const codecs = videoCodecs.split(",");
  2045. for (let i = 0; i < codecs.length; i++) {
  2046. const avcdata = codecs[i].split(".");
  2047. if (avcdata.length > 2 && avcdata[0] === "avc1") {
  2048. codecs[i] = `avc1.${parseInt(avcdata[1]).toString(16)}${("000" + parseInt(avcdata[2]).toString(16)).slice(-4)}`;
  2049. }
  2050. }
  2051. return codecs.join(",");
  2052. }
  2053. function fillInMissingAV01Params(videoCodec) {
  2054. if (videoCodec.startsWith("av01.")) {
  2055. const av1params = videoCodec.split(".");
  2056. const placeholders = ["0", "111", "01", "01", "01", "0"];
  2057. for (let i = av1params.length; i > 4 && i < 10; i++) {
  2058. av1params[i] = placeholders[i - 4];
  2059. }
  2060. return av1params.join(".");
  2061. }
  2062. return videoCodec;
  2063. }
  2064. function getM2TSSupportedAudioTypes(preferManagedMediaSource) {
  2065. const MediaSource = getMediaSource(preferManagedMediaSource) || {
  2066. isTypeSupported: () => false
  2067. };
  2068. return {
  2069. mpeg: MediaSource.isTypeSupported("audio/mpeg"),
  2070. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"'),
  2071. ac3: MediaSource.isTypeSupported('audio/mp4; codecs="ac-3"')
  2072. };
  2073. }
  2074. function getCodecsForMimeType(mimeType) {
  2075. return mimeType.replace(/^.+codecs=["']?([^"']+).*$/, "$1");
  2076. }
  2077. var SUPPORTED_INFO_DEFAULT = {
  2078. supported: true,
  2079. configurations: [],
  2080. decodingInfoResults: [{
  2081. supported: true,
  2082. powerEfficient: true,
  2083. smooth: true
  2084. }]
  2085. };
  2086. function getUnsupportedResult(error, configurations) {
  2087. return {
  2088. supported: false,
  2089. configurations,
  2090. decodingInfoResults: [{
  2091. supported: false,
  2092. smooth: false,
  2093. powerEfficient: false
  2094. }],
  2095. error
  2096. };
  2097. }
  2098. function requiresMediaCapabilitiesDecodingInfo(level, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference) {
  2099. const videoCodecs = level.videoCodec;
  2100. const audioGroups = level.audioCodec ? level.audioGroups : null;
  2101. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  2102. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  2103. const maxChannels = channelsPreference ? parseInt(channelsPreference) : audioCodecPreference ? Infinity : 2;
  2104. let audioChannels = null;
  2105. if (audioGroups != null && audioGroups.length) {
  2106. try {
  2107. if (audioGroups.length === 1 && audioGroups[0]) {
  2108. audioChannels = audioTracksByGroup.groups[audioGroups[0]].channels;
  2109. } else {
  2110. audioChannels = audioGroups.reduce((acc, groupId) => {
  2111. if (groupId) {
  2112. const audioTrackGroup = audioTracksByGroup.groups[groupId];
  2113. if (!audioTrackGroup) {
  2114. throw new Error(`Audio track group ${groupId} not found`);
  2115. }
  2116. Object.keys(audioTrackGroup.channels).forEach((key) => {
  2117. acc[key] = (acc[key] || 0) + audioTrackGroup.channels[key];
  2118. });
  2119. }
  2120. return acc;
  2121. }, {
  2122. 2: 0
  2123. });
  2124. }
  2125. } catch (error) {
  2126. return true;
  2127. }
  2128. }
  2129. return videoCodecs !== void 0 && (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);
  2130. }
  2131. function getMediaDecodingInfoPromise(level, audioTracksByGroup, mediaCapabilities, cache = {}) {
  2132. const videoCodecs = level.videoCodec;
  2133. if (!videoCodecs && !level.audioCodec || !mediaCapabilities) {
  2134. return Promise.resolve(SUPPORTED_INFO_DEFAULT);
  2135. }
  2136. const configurations = [];
  2137. const videoDecodeList = makeVideoConfigurations(level);
  2138. const videoCount = videoDecodeList.length;
  2139. const audioDecodeList = makeAudioConfigurations(level, audioTracksByGroup, videoCount > 0);
  2140. const audioCount = audioDecodeList.length;
  2141. for (let i = videoCount || 1 * audioCount || 1; i--; ) {
  2142. const configuration = {
  2143. type: "media-source"
  2144. };
  2145. if (videoCount) {
  2146. configuration.video = videoDecodeList[i % videoCount];
  2147. }
  2148. if (audioCount) {
  2149. configuration.audio = audioDecodeList[i % audioCount];
  2150. const audioBitrate = configuration.audio.bitrate;
  2151. if (configuration.video && audioBitrate) {
  2152. configuration.video.bitrate -= audioBitrate;
  2153. }
  2154. }
  2155. configurations.push(configuration);
  2156. }
  2157. if (videoCodecs) {
  2158. const ua = navigator.userAgent;
  2159. if (videoCodecs.split(",").some((videoCodec) => isHEVC(videoCodec)) && userAgentHevcSupportIsInaccurate()) {
  2160. return Promise.resolve(getUnsupportedResult(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${ua})`), configurations));
  2161. }
  2162. }
  2163. return Promise.all(configurations.map((configuration) => {
  2164. const decodingInfoKey = getMediaDecodingInfoKey(configuration);
  2165. return cache[decodingInfoKey] || (cache[decodingInfoKey] = mediaCapabilities.decodingInfo(configuration));
  2166. })).then((decodingInfoResults) => ({
  2167. supported: !decodingInfoResults.some((info) => !info.supported),
  2168. configurations,
  2169. decodingInfoResults
  2170. })).catch((error) => ({
  2171. supported: false,
  2172. configurations,
  2173. decodingInfoResults: [],
  2174. error
  2175. }));
  2176. }
  2177. function makeVideoConfigurations(level) {
  2178. var _level$videoCodec;
  2179. const videoCodecs = (_level$videoCodec = level.videoCodec) == null ? void 0 : _level$videoCodec.split(",");
  2180. const bitrate = getVariantDecodingBitrate(level);
  2181. const width = level.width || 640;
  2182. const height = level.height || 480;
  2183. const framerate = level.frameRate || 30;
  2184. const videoRange = level.videoRange.toLowerCase();
  2185. return videoCodecs ? videoCodecs.map((videoCodec) => {
  2186. const videoConfiguration = {
  2187. contentType: mimeTypeForCodec(fillInMissingAV01Params(videoCodec), "video"),
  2188. width,
  2189. height,
  2190. bitrate,
  2191. framerate
  2192. };
  2193. if (videoRange !== "sdr") {
  2194. videoConfiguration.transferFunction = videoRange;
  2195. }
  2196. return videoConfiguration;
  2197. }) : [];
  2198. }
  2199. function makeAudioConfigurations(level, audioTracksByGroup, hasVideo) {
  2200. var _level$audioCodec;
  2201. const audioCodecs = (_level$audioCodec = level.audioCodec) == null ? void 0 : _level$audioCodec.split(",");
  2202. const combinedBitrate = getVariantDecodingBitrate(level);
  2203. if (audioCodecs && level.audioGroups) {
  2204. return level.audioGroups.reduce((configurations, audioGroupId) => {
  2205. var _audioTracksByGroup$g;
  2206. const tracks = audioGroupId ? (_audioTracksByGroup$g = audioTracksByGroup.groups[audioGroupId]) == null ? void 0 : _audioTracksByGroup$g.tracks : null;
  2207. if (tracks) {
  2208. return tracks.reduce((configs, audioTrack) => {
  2209. if (audioTrack.groupId === audioGroupId) {
  2210. const channelsNumber = parseFloat(audioTrack.channels || "");
  2211. audioCodecs.forEach((audioCodec) => {
  2212. const audioConfiguration = {
  2213. contentType: mimeTypeForCodec(audioCodec, "audio"),
  2214. bitrate: hasVideo ? estimatedAudioBitrate(audioCodec, combinedBitrate) : combinedBitrate
  2215. };
  2216. if (channelsNumber) {
  2217. audioConfiguration.channels = "" + channelsNumber;
  2218. }
  2219. configs.push(audioConfiguration);
  2220. });
  2221. }
  2222. return configs;
  2223. }, configurations);
  2224. }
  2225. return configurations;
  2226. }, []);
  2227. }
  2228. return [];
  2229. }
  2230. function estimatedAudioBitrate(audioCodec, levelBitrate) {
  2231. if (levelBitrate <= 1) {
  2232. return 1;
  2233. }
  2234. let audioBitrate = 128e3;
  2235. if (audioCodec === "ec-3") {
  2236. audioBitrate = 768e3;
  2237. } else if (audioCodec === "ac-3") {
  2238. audioBitrate = 64e4;
  2239. }
  2240. return Math.min(levelBitrate / 2, audioBitrate);
  2241. }
  2242. function getVariantDecodingBitrate(level) {
  2243. return Math.ceil(Math.max(level.bitrate * 0.9, level.averageBitrate) / 1e3) * 1e3 || 1;
  2244. }
  2245. function getMediaDecodingInfoKey(config) {
  2246. let key = "";
  2247. const {
  2248. audio,
  2249. video
  2250. } = config;
  2251. if (video) {
  2252. const codec = getCodecsForMimeType(video.contentType);
  2253. key += `${codec}_r${video.height}x${video.width}f${Math.ceil(video.framerate)}${video.transferFunction || "sd"}_${Math.ceil(video.bitrate / 1e5)}`;
  2254. }
  2255. if (audio) {
  2256. const codec = getCodecsForMimeType(audio.contentType);
  2257. key += `${video ? "_" : ""}${codec}_c${audio.channels}`;
  2258. }
  2259. return key;
  2260. }
  2261. var HdcpLevels = ["NONE", "TYPE-0", "TYPE-1", null];
  2262. function isHdcpLevel(value) {
  2263. return HdcpLevels.indexOf(value) > -1;
  2264. }
  2265. var VideoRangeValues = ["SDR", "PQ", "HLG"];
  2266. function isVideoRange(value) {
  2267. return !!value && VideoRangeValues.indexOf(value) > -1;
  2268. }
  2269. var HlsSkip = {
  2270. No: "",
  2271. Yes: "YES",
  2272. v2: "v2"
  2273. };
  2274. function getSkipValue(details) {
  2275. const {
  2276. canSkipUntil,
  2277. canSkipDateRanges,
  2278. age
  2279. } = details;
  2280. const playlistRecentEnough = age < canSkipUntil / 2;
  2281. if (canSkipUntil && playlistRecentEnough) {
  2282. if (canSkipDateRanges) {
  2283. return HlsSkip.v2;
  2284. }
  2285. return HlsSkip.Yes;
  2286. }
  2287. return HlsSkip.No;
  2288. }
  2289. var HlsUrlParameters = class {
  2290. constructor(msn, part, skip) {
  2291. this.msn = void 0;
  2292. this.part = void 0;
  2293. this.skip = void 0;
  2294. this.msn = msn;
  2295. this.part = part;
  2296. this.skip = skip;
  2297. }
  2298. addDirectives(uri) {
  2299. const url = new self.URL(uri);
  2300. if (this.msn !== void 0) {
  2301. url.searchParams.set("_HLS_msn", this.msn.toString());
  2302. }
  2303. if (this.part !== void 0) {
  2304. url.searchParams.set("_HLS_part", this.part.toString());
  2305. }
  2306. if (this.skip) {
  2307. url.searchParams.set("_HLS_skip", this.skip);
  2308. }
  2309. return url.href;
  2310. }
  2311. };
  2312. var Level = class {
  2313. constructor(data) {
  2314. this._attrs = void 0;
  2315. this.audioCodec = void 0;
  2316. this.bitrate = void 0;
  2317. this.codecSet = void 0;
  2318. this.url = void 0;
  2319. this.frameRate = void 0;
  2320. this.height = void 0;
  2321. this.id = void 0;
  2322. this.name = void 0;
  2323. this.supplemental = void 0;
  2324. this.videoCodec = void 0;
  2325. this.width = void 0;
  2326. this.details = void 0;
  2327. this.fragmentError = 0;
  2328. this.loadError = 0;
  2329. this.loaded = void 0;
  2330. this.realBitrate = 0;
  2331. this.supportedPromise = void 0;
  2332. this.supportedResult = void 0;
  2333. this._avgBitrate = 0;
  2334. this._audioGroups = void 0;
  2335. this._subtitleGroups = void 0;
  2336. this._urlId = 0;
  2337. this.url = [data.url];
  2338. this._attrs = [data.attrs];
  2339. this.bitrate = data.bitrate;
  2340. if (data.details) {
  2341. this.details = data.details;
  2342. }
  2343. this.id = data.id || 0;
  2344. this.name = data.name;
  2345. this.width = data.width || 0;
  2346. this.height = data.height || 0;
  2347. this.frameRate = data.attrs.optionalFloat("FRAME-RATE", 0);
  2348. this._avgBitrate = data.attrs.decimalInteger("AVERAGE-BANDWIDTH");
  2349. this.audioCodec = data.audioCodec;
  2350. this.videoCodec = data.videoCodec;
  2351. this.codecSet = [data.videoCodec, data.audioCodec].filter((c) => !!c).map((s) => s.substring(0, 4)).join(",");
  2352. if ("supplemental" in data) {
  2353. var _data$supplemental;
  2354. this.supplemental = data.supplemental;
  2355. const supplementalVideo = (_data$supplemental = data.supplemental) == null ? void 0 : _data$supplemental.videoCodec;
  2356. if (supplementalVideo && supplementalVideo !== data.videoCodec) {
  2357. this.codecSet += `,${supplementalVideo.substring(0, 4)}`;
  2358. }
  2359. }
  2360. this.addGroupId("audio", data.attrs.AUDIO);
  2361. this.addGroupId("text", data.attrs.SUBTITLES);
  2362. }
  2363. get maxBitrate() {
  2364. return Math.max(this.realBitrate, this.bitrate);
  2365. }
  2366. get averageBitrate() {
  2367. return this._avgBitrate || this.realBitrate || this.bitrate;
  2368. }
  2369. get attrs() {
  2370. return this._attrs[0];
  2371. }
  2372. get codecs() {
  2373. return this.attrs.CODECS || "";
  2374. }
  2375. get pathwayId() {
  2376. return this.attrs["PATHWAY-ID"] || ".";
  2377. }
  2378. get videoRange() {
  2379. return this.attrs["VIDEO-RANGE"] || "SDR";
  2380. }
  2381. get score() {
  2382. return this.attrs.optionalFloat("SCORE", 0);
  2383. }
  2384. get uri() {
  2385. return this.url[0] || "";
  2386. }
  2387. hasAudioGroup(groupId) {
  2388. return hasGroup(this._audioGroups, groupId);
  2389. }
  2390. hasSubtitleGroup(groupId) {
  2391. return hasGroup(this._subtitleGroups, groupId);
  2392. }
  2393. get audioGroups() {
  2394. return this._audioGroups;
  2395. }
  2396. get subtitleGroups() {
  2397. return this._subtitleGroups;
  2398. }
  2399. addGroupId(type, groupId) {
  2400. if (!groupId) {
  2401. return;
  2402. }
  2403. if (type === "audio") {
  2404. let audioGroups = this._audioGroups;
  2405. if (!audioGroups) {
  2406. audioGroups = this._audioGroups = [];
  2407. }
  2408. if (audioGroups.indexOf(groupId) === -1) {
  2409. audioGroups.push(groupId);
  2410. }
  2411. } else if (type === "text") {
  2412. let subtitleGroups = this._subtitleGroups;
  2413. if (!subtitleGroups) {
  2414. subtitleGroups = this._subtitleGroups = [];
  2415. }
  2416. if (subtitleGroups.indexOf(groupId) === -1) {
  2417. subtitleGroups.push(groupId);
  2418. }
  2419. }
  2420. }
  2421. get urlId() {
  2422. return 0;
  2423. }
  2424. set urlId(value) {
  2425. }
  2426. get audioGroupIds() {
  2427. return this.audioGroups ? [this.audioGroupId] : void 0;
  2428. }
  2429. get textGroupIds() {
  2430. return this.subtitleGroups ? [this.textGroupId] : void 0;
  2431. }
  2432. get audioGroupId() {
  2433. var _this$audioGroups;
  2434. return (_this$audioGroups = this.audioGroups) == null ? void 0 : _this$audioGroups[0];
  2435. }
  2436. get textGroupId() {
  2437. var _this$subtitleGroups;
  2438. return (_this$subtitleGroups = this.subtitleGroups) == null ? void 0 : _this$subtitleGroups[0];
  2439. }
  2440. addFallback() {
  2441. }
  2442. };
  2443. function hasGroup(groups, groupId) {
  2444. if (!groupId || !groups) {
  2445. return false;
  2446. }
  2447. return groups.indexOf(groupId) !== -1;
  2448. }
  2449. function isHdrSupported() {
  2450. if (typeof matchMedia === "function") {
  2451. const mediaQueryList = matchMedia("(dynamic-range: high)");
  2452. const badQuery = matchMedia("bad query");
  2453. if (mediaQueryList.media !== badQuery.media) {
  2454. return mediaQueryList.matches === true;
  2455. }
  2456. }
  2457. return false;
  2458. }
  2459. function getVideoSelectionOptions(currentVideoRange, videoPreference) {
  2460. let preferHDR = false;
  2461. let allowedVideoRanges = [];
  2462. if (currentVideoRange) {
  2463. preferHDR = currentVideoRange !== "SDR";
  2464. allowedVideoRanges = [currentVideoRange];
  2465. }
  2466. if (videoPreference) {
  2467. allowedVideoRanges = videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);
  2468. const allowAutoPreferHDR = allowedVideoRanges.join("") !== "SDR" && !videoPreference.videoCodec;
  2469. preferHDR = videoPreference.preferHDR !== void 0 ? videoPreference.preferHDR : allowAutoPreferHDR && isHdrSupported();
  2470. if (!preferHDR) {
  2471. allowedVideoRanges = ["SDR"];
  2472. }
  2473. }
  2474. return {
  2475. preferHDR,
  2476. allowedVideoRanges
  2477. };
  2478. }
  2479. var omitCircularRefsReplacer = (replacer) => {
  2480. const known = /* @__PURE__ */ new WeakSet();
  2481. return (_, value) => {
  2482. if (replacer) {
  2483. value = replacer(_, value);
  2484. }
  2485. if (typeof value === "object" && value !== null) {
  2486. if (known.has(value)) {
  2487. return;
  2488. }
  2489. known.add(value);
  2490. }
  2491. return value;
  2492. };
  2493. };
  2494. var stringify = (object, replacer) => JSON.stringify(object, omitCircularRefsReplacer(replacer));
  2495. function getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference) {
  2496. const codecSets = Object.keys(codecTiers);
  2497. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  2498. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  2499. const videoCodecPreference = videoPreference == null ? void 0 : videoPreference.videoCodec;
  2500. const preferStereo = channelsPreference && parseInt(channelsPreference) === 2;
  2501. let hasStereo = false;
  2502. let hasCurrentVideoRange = false;
  2503. let minHeight = Infinity;
  2504. let minFramerate = Infinity;
  2505. let minBitrate = Infinity;
  2506. let minIndex = Infinity;
  2507. let selectedScore = 0;
  2508. let videoRanges = [];
  2509. const {
  2510. preferHDR,
  2511. allowedVideoRanges
  2512. } = getVideoSelectionOptions(currentVideoRange, videoPreference);
  2513. for (let i = codecSets.length; i--; ) {
  2514. const tier = codecTiers[codecSets[i]];
  2515. hasStereo || (hasStereo = tier.channels[2] > 0);
  2516. minHeight = Math.min(minHeight, tier.minHeight);
  2517. minFramerate = Math.min(minFramerate, tier.minFramerate);
  2518. minBitrate = Math.min(minBitrate, tier.minBitrate);
  2519. const matchingVideoRanges = allowedVideoRanges.filter((range) => tier.videoRanges[range] > 0);
  2520. if (matchingVideoRanges.length > 0) {
  2521. hasCurrentVideoRange = true;
  2522. }
  2523. }
  2524. minHeight = isFiniteNumber(minHeight) ? minHeight : 0;
  2525. minFramerate = isFiniteNumber(minFramerate) ? minFramerate : 0;
  2526. const maxHeight = Math.max(1080, minHeight);
  2527. const maxFramerate = Math.max(30, minFramerate);
  2528. minBitrate = isFiniteNumber(minBitrate) ? minBitrate : currentBw;
  2529. currentBw = Math.max(minBitrate, currentBw);
  2530. if (!hasCurrentVideoRange) {
  2531. currentVideoRange = void 0;
  2532. }
  2533. const hasMultipleSets = codecSets.length > 1;
  2534. const codecSet = codecSets.reduce((selected, candidate) => {
  2535. const candidateTier = codecTiers[candidate];
  2536. if (candidate === selected) {
  2537. return selected;
  2538. }
  2539. videoRanges = hasCurrentVideoRange ? allowedVideoRanges.filter((range) => candidateTier.videoRanges[range] > 0) : [];
  2540. if (hasMultipleSets) {
  2541. if (candidateTier.minBitrate > currentBw) {
  2542. logStartCodecCandidateIgnored(candidate, `min bitrate of ${candidateTier.minBitrate} > current estimate of ${currentBw}`);
  2543. return selected;
  2544. }
  2545. if (!candidateTier.hasDefaultAudio) {
  2546. logStartCodecCandidateIgnored(candidate, `no renditions with default or auto-select sound found`);
  2547. return selected;
  2548. }
  2549. if (audioCodecPreference && candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0) {
  2550. logStartCodecCandidateIgnored(candidate, `audio codec preference "${audioCodecPreference}" not found`);
  2551. return selected;
  2552. }
  2553. if (channelsPreference && !preferStereo) {
  2554. if (!candidateTier.channels[channelsPreference]) {
  2555. logStartCodecCandidateIgnored(candidate, `no renditions with ${channelsPreference} channel sound found (channels options: ${Object.keys(candidateTier.channels)})`);
  2556. return selected;
  2557. }
  2558. } else if ((!audioCodecPreference || preferStereo) && hasStereo && candidateTier.channels["2"] === 0) {
  2559. logStartCodecCandidateIgnored(candidate, `no renditions with stereo sound found`);
  2560. return selected;
  2561. }
  2562. if (candidateTier.minHeight > maxHeight) {
  2563. logStartCodecCandidateIgnored(candidate, `min resolution of ${candidateTier.minHeight} > maximum of ${maxHeight}`);
  2564. return selected;
  2565. }
  2566. if (candidateTier.minFramerate > maxFramerate) {
  2567. logStartCodecCandidateIgnored(candidate, `min framerate of ${candidateTier.minFramerate} > maximum of ${maxFramerate}`);
  2568. return selected;
  2569. }
  2570. if (!videoRanges.some((range) => candidateTier.videoRanges[range] > 0)) {
  2571. logStartCodecCandidateIgnored(candidate, `no variants with VIDEO-RANGE of ${stringify(videoRanges)} found`);
  2572. return selected;
  2573. }
  2574. if (videoCodecPreference && candidate.indexOf(videoCodecPreference.substring(0, 4)) % 5 !== 0) {
  2575. logStartCodecCandidateIgnored(candidate, `video codec preference "${videoCodecPreference}" not found`);
  2576. return selected;
  2577. }
  2578. if (candidateTier.maxScore < selectedScore) {
  2579. logStartCodecCandidateIgnored(candidate, `max score of ${candidateTier.maxScore} < selected max of ${selectedScore}`);
  2580. return selected;
  2581. }
  2582. }
  2583. if (selected && (codecsSetSelectionPreferenceValue(candidate) >= codecsSetSelectionPreferenceValue(selected) || candidateTier.fragmentError > codecTiers[selected].fragmentError)) {
  2584. return selected;
  2585. }
  2586. minIndex = candidateTier.minIndex;
  2587. selectedScore = candidateTier.maxScore;
  2588. return candidate;
  2589. }, void 0);
  2590. return {
  2591. codecSet,
  2592. videoRanges,
  2593. preferHDR,
  2594. minFramerate,
  2595. minBitrate,
  2596. minIndex
  2597. };
  2598. }
  2599. function logStartCodecCandidateIgnored(codeSet, reason) {
  2600. logger.log(`[abr] start candidates with "${codeSet}" ignored because ${reason}`);
  2601. }
  2602. function getAudioTracksByGroup(allAudioTracks) {
  2603. return allAudioTracks.reduce((audioTracksByGroup, track) => {
  2604. let trackGroup = audioTracksByGroup.groups[track.groupId];
  2605. if (!trackGroup) {
  2606. trackGroup = audioTracksByGroup.groups[track.groupId] = {
  2607. tracks: [],
  2608. channels: {
  2609. 2: 0
  2610. },
  2611. hasDefault: false,
  2612. hasAutoSelect: false
  2613. };
  2614. }
  2615. trackGroup.tracks.push(track);
  2616. const channelsKey = track.channels || "2";
  2617. trackGroup.channels[channelsKey] = (trackGroup.channels[channelsKey] || 0) + 1;
  2618. trackGroup.hasDefault = trackGroup.hasDefault || track.default;
  2619. trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;
  2620. if (trackGroup.hasDefault) {
  2621. audioTracksByGroup.hasDefaultAudio = true;
  2622. }
  2623. if (trackGroup.hasAutoSelect) {
  2624. audioTracksByGroup.hasAutoSelectAudio = true;
  2625. }
  2626. return audioTracksByGroup;
  2627. }, {
  2628. hasDefaultAudio: false,
  2629. hasAutoSelectAudio: false,
  2630. groups: {}
  2631. });
  2632. }
  2633. function getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel) {
  2634. return levels.slice(minAutoLevel, maxAutoLevel + 1).reduce((tiers, level, index) => {
  2635. if (!level.codecSet) {
  2636. return tiers;
  2637. }
  2638. const audioGroups = level.audioGroups;
  2639. let tier = tiers[level.codecSet];
  2640. if (!tier) {
  2641. tiers[level.codecSet] = tier = {
  2642. minBitrate: Infinity,
  2643. minHeight: Infinity,
  2644. minFramerate: Infinity,
  2645. minIndex: index,
  2646. maxScore: 0,
  2647. videoRanges: {
  2648. SDR: 0
  2649. },
  2650. channels: {
  2651. "2": 0
  2652. },
  2653. hasDefaultAudio: !audioGroups,
  2654. fragmentError: 0
  2655. };
  2656. }
  2657. tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);
  2658. const lesserWidthOrHeight = Math.min(level.height, level.width);
  2659. tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);
  2660. tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);
  2661. tier.minIndex = Math.min(tier.minIndex, index);
  2662. tier.maxScore = Math.max(tier.maxScore, level.score);
  2663. tier.fragmentError += level.fragmentError;
  2664. tier.videoRanges[level.videoRange] = (tier.videoRanges[level.videoRange] || 0) + 1;
  2665. if (audioGroups) {
  2666. audioGroups.forEach((audioGroupId) => {
  2667. if (!audioGroupId) {
  2668. return;
  2669. }
  2670. const audioGroup = audioTracksByGroup.groups[audioGroupId];
  2671. if (!audioGroup) {
  2672. return;
  2673. }
  2674. tier.hasDefaultAudio = tier.hasDefaultAudio || audioTracksByGroup.hasDefaultAudio ? audioGroup.hasDefault : audioGroup.hasAutoSelect || !audioTracksByGroup.hasDefaultAudio && !audioTracksByGroup.hasAutoSelectAudio;
  2675. Object.keys(audioGroup.channels).forEach((channels) => {
  2676. tier.channels[channels] = (tier.channels[channels] || 0) + audioGroup.channels[channels];
  2677. });
  2678. });
  2679. }
  2680. return tiers;
  2681. }, {});
  2682. }
  2683. function getBasicSelectionOption(option) {
  2684. if (!option) {
  2685. return option;
  2686. }
  2687. const {
  2688. lang,
  2689. assocLang,
  2690. characteristics,
  2691. channels,
  2692. audioCodec
  2693. } = option;
  2694. return {
  2695. lang,
  2696. assocLang,
  2697. characteristics,
  2698. channels,
  2699. audioCodec
  2700. };
  2701. }
  2702. function findMatchingOption(option, tracks, matchPredicate) {
  2703. if ("attrs" in option) {
  2704. const index = tracks.indexOf(option);
  2705. if (index !== -1) {
  2706. return index;
  2707. }
  2708. }
  2709. for (let i = 0; i < tracks.length; i++) {
  2710. const track = tracks[i];
  2711. if (matchesOption(option, track, matchPredicate)) {
  2712. return i;
  2713. }
  2714. }
  2715. return -1;
  2716. }
  2717. function matchesOption(option, track, matchPredicate) {
  2718. const {
  2719. groupId,
  2720. name,
  2721. lang,
  2722. assocLang,
  2723. default: isDefault
  2724. } = option;
  2725. const forced = option.forced;
  2726. 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));
  2727. }
  2728. function languagesMatch(languageA, languageB = "--") {
  2729. if (languageA.length === languageB.length) {
  2730. return languageA === languageB;
  2731. }
  2732. return languageA.startsWith(languageB) || languageB.startsWith(languageA);
  2733. }
  2734. function characteristicsMatch(characteristicsA, characteristicsB = "") {
  2735. const arrA = characteristicsA.split(",");
  2736. const arrB = characteristicsB.split(",");
  2737. return arrA.length === arrB.length && !arrA.some((el) => arrB.indexOf(el) === -1);
  2738. }
  2739. function audioMatchPredicate(option, track) {
  2740. const {
  2741. audioCodec,
  2742. channels
  2743. } = option;
  2744. return (audioCodec === void 0 || (track.audioCodec || "").substring(0, 4) === audioCodec.substring(0, 4)) && (channels === void 0 || channels === (track.channels || "2"));
  2745. }
  2746. function findClosestLevelWithAudioGroup(option, levels, allAudioTracks, searchIndex, matchPredicate) {
  2747. const currentLevel = levels[searchIndex];
  2748. const variants = levels.reduce((variantMap, level, index) => {
  2749. const uri = level.uri;
  2750. const renditions2 = variantMap[uri] || (variantMap[uri] = []);
  2751. renditions2.push(index);
  2752. return variantMap;
  2753. }, {});
  2754. const renditions = variants[currentLevel.uri];
  2755. if (renditions.length > 1) {
  2756. searchIndex = Math.max.apply(Math, renditions);
  2757. }
  2758. const currentVideoRange = currentLevel.videoRange;
  2759. const currentFrameRate = currentLevel.frameRate;
  2760. const currentVideoCodec = currentLevel.codecSet.substring(0, 4);
  2761. const matchingVideo = searchDownAndUpList(levels, searchIndex, (level) => {
  2762. if (level.videoRange !== currentVideoRange || level.frameRate !== currentFrameRate || level.codecSet.substring(0, 4) !== currentVideoCodec) {
  2763. return false;
  2764. }
  2765. const audioGroups = level.audioGroups;
  2766. const tracks = allAudioTracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  2767. return findMatchingOption(option, tracks, matchPredicate) > -1;
  2768. });
  2769. if (matchingVideo > -1) {
  2770. return matchingVideo;
  2771. }
  2772. return searchDownAndUpList(levels, searchIndex, (level) => {
  2773. const audioGroups = level.audioGroups;
  2774. const tracks = allAudioTracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  2775. return findMatchingOption(option, tracks, matchPredicate) > -1;
  2776. });
  2777. }
  2778. function searchDownAndUpList(arr, searchIndex, predicate) {
  2779. for (let i = searchIndex; i > -1; i--) {
  2780. if (predicate(arr[i])) {
  2781. return i;
  2782. }
  2783. }
  2784. for (let i = searchIndex + 1; i < arr.length; i++) {
  2785. if (predicate(arr[i])) {
  2786. return i;
  2787. }
  2788. }
  2789. return -1;
  2790. }
  2791. function useAlternateAudio(audioTrackUrl, hls) {
  2792. var _hls$loadLevelObj;
  2793. return !!audioTrackUrl && audioTrackUrl !== ((_hls$loadLevelObj = hls.loadLevelObj) == null ? void 0 : _hls$loadLevelObj.uri);
  2794. }
  2795. var AbrController = class extends Logger {
  2796. constructor(_hls) {
  2797. super("abr", _hls.logger);
  2798. this.hls = void 0;
  2799. this.lastLevelLoadSec = 0;
  2800. this.lastLoadedFragLevel = -1;
  2801. this.firstSelection = -1;
  2802. this._nextAutoLevel = -1;
  2803. this.nextAutoLevelKey = "";
  2804. this.audioTracksByGroup = null;
  2805. this.codecTiers = null;
  2806. this.timer = -1;
  2807. this.fragCurrent = null;
  2808. this.partCurrent = null;
  2809. this.bitrateTestDelay = 0;
  2810. this.rebufferNotice = -1;
  2811. this.supportedCache = {};
  2812. this.bwEstimator = void 0;
  2813. this._abandonRulesCheck = (levelLoaded) => {
  2814. var _ref;
  2815. const {
  2816. fragCurrent: frag,
  2817. partCurrent: part,
  2818. hls
  2819. } = this;
  2820. const {
  2821. autoLevelEnabled,
  2822. media
  2823. } = hls;
  2824. if (!frag || !media) {
  2825. return;
  2826. }
  2827. const now2 = performance.now();
  2828. const stats = part ? part.stats : frag.stats;
  2829. const duration = part ? part.duration : frag.duration;
  2830. const timeLoading = now2 - stats.loading.start;
  2831. const minAutoLevel = hls.minAutoLevel;
  2832. const loadingFragForLevel = frag.level;
  2833. const currentAutoLevel = this._nextAutoLevel;
  2834. if (stats.aborted || stats.loaded && stats.loaded === stats.total || loadingFragForLevel <= minAutoLevel) {
  2835. this.clearTimer();
  2836. this._nextAutoLevel = -1;
  2837. return;
  2838. }
  2839. if (!autoLevelEnabled) {
  2840. return;
  2841. }
  2842. const fragBlockingSwitch = currentAutoLevel > -1 && currentAutoLevel !== loadingFragForLevel;
  2843. const levelChange = !!levelLoaded || fragBlockingSwitch;
  2844. if (!levelChange && (media.paused || !media.playbackRate || !media.readyState)) {
  2845. return;
  2846. }
  2847. const bufferInfo = hls.mainForwardBufferInfo;
  2848. if (!levelChange && bufferInfo === null) {
  2849. return;
  2850. }
  2851. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  2852. const playbackRate = Math.abs(media.playbackRate);
  2853. if (timeLoading <= Math.max(ttfbEstimate, 1e3 * (duration / (playbackRate * 2)))) {
  2854. return;
  2855. }
  2856. const bufferStarvationDelay = bufferInfo ? bufferInfo.len / playbackRate : 0;
  2857. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  2858. const loadedFirstByte = stats.loaded && ttfb > -1;
  2859. const bwEstimate = this.getBwEstimate();
  2860. const levels = hls.levels;
  2861. const level = levels[loadingFragForLevel];
  2862. const expectedLen = Math.max(stats.loaded, Math.round(duration * (frag.bitrate || level.averageBitrate) / 8));
  2863. let timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;
  2864. if (timeStreaming < 1 && loadedFirstByte) {
  2865. timeStreaming = Math.min(timeLoading, stats.loaded * 8 / bwEstimate);
  2866. }
  2867. const loadRate = loadedFirstByte ? stats.loaded * 1e3 / timeStreaming : 0;
  2868. const ttfbSeconds = ttfbEstimate / 1e3;
  2869. const fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate + ttfbSeconds;
  2870. if (fragLoadedDelay <= bufferStarvationDelay) {
  2871. return;
  2872. }
  2873. const bwe = loadRate ? loadRate * 8 : bwEstimate;
  2874. const live = ((_ref = (levelLoaded == null ? void 0 : levelLoaded.details) || this.hls.latestLevelDetails) == null ? void 0 : _ref.live) === true;
  2875. const abrBandWidthUpFactor = this.hls.config.abrBandWidthUpFactor;
  2876. let fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
  2877. let nextLoadLevel;
  2878. for (nextLoadLevel = loadingFragForLevel - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  2879. const levelNextBitrate = levels[nextLoadLevel].maxBitrate;
  2880. const requiresLevelLoad = !levels[nextLoadLevel].details || live;
  2881. fragLevelNextLoadedDelay = this.getTimeToLoadFrag(ttfbSeconds, bwe, duration * levelNextBitrate, requiresLevelLoad);
  2882. if (fragLevelNextLoadedDelay < Math.min(bufferStarvationDelay, duration + ttfbSeconds)) {
  2883. break;
  2884. }
  2885. }
  2886. if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
  2887. return;
  2888. }
  2889. if (fragLevelNextLoadedDelay > duration * 10) {
  2890. return;
  2891. }
  2892. if (loadedFirstByte) {
  2893. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  2894. } else {
  2895. this.bwEstimator.sampleTTFB(timeLoading);
  2896. }
  2897. const nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;
  2898. if (this.getBwEstimate() * abrBandWidthUpFactor > nextLoadLevelBitrate) {
  2899. this.resetEstimator(nextLoadLevelBitrate);
  2900. }
  2901. const bestSwitchLevel = this.findBestLevel(nextLoadLevelBitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay, 1, 1);
  2902. if (bestSwitchLevel > -1) {
  2903. nextLoadLevel = bestSwitchLevel;
  2904. }
  2905. this.warn(`Fragment ${frag.sn}${part ? " part " + part.index : ""} of level ${loadingFragForLevel} is loading too slowly;
  2906. Fragment duration: ${frag.duration.toFixed(3)}
  2907. Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s
  2908. Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s
  2909. Estimated load time for down switch fragment: ${fragLevelNextLoadedDelay.toFixed(3)} s
  2910. TTFB estimate: ${ttfb | 0} ms
  2911. Current BW estimate: ${isFiniteNumber(bwEstimate) ? bwEstimate | 0 : "Unknown"} bps
  2912. New BW estimate: ${this.getBwEstimate() | 0} bps
  2913. Switching to level ${nextLoadLevel} @ ${nextLoadLevelBitrate | 0} bps`);
  2914. hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;
  2915. this.clearTimer();
  2916. const abortAndSwitch = () => {
  2917. this.clearTimer();
  2918. if (this.fragCurrent === frag && this.hls.loadLevel === nextLoadLevel && nextLoadLevel > 0) {
  2919. const bufferStarvationDelay2 = this.getStarvationDelay();
  2920. this.warn(`Aborting inflight request ${nextLoadLevel > 0 ? "and switching down" : ""}
  2921. Fragment duration: ${frag.duration.toFixed(3)} s
  2922. Time to underbuffer: ${bufferStarvationDelay2.toFixed(3)} s`);
  2923. frag.abortRequests();
  2924. this.fragCurrent = this.partCurrent = null;
  2925. if (nextLoadLevel > minAutoLevel) {
  2926. let lowestSwitchLevel = this.findBestLevel(this.hls.levels[minAutoLevel].bitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay2, 1, 1);
  2927. if (lowestSwitchLevel === -1) {
  2928. lowestSwitchLevel = minAutoLevel;
  2929. }
  2930. this.hls.nextLoadLevel = this.hls.nextAutoLevel = lowestSwitchLevel;
  2931. this.resetEstimator(this.hls.levels[lowestSwitchLevel].bitrate);
  2932. }
  2933. }
  2934. };
  2935. if (fragBlockingSwitch || fragLoadedDelay > fragLevelNextLoadedDelay * 2) {
  2936. abortAndSwitch();
  2937. } else {
  2938. this.timer = self.setInterval(abortAndSwitch, fragLevelNextLoadedDelay * 1e3);
  2939. }
  2940. hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, {
  2941. frag,
  2942. part,
  2943. stats
  2944. });
  2945. };
  2946. this.hls = _hls;
  2947. this.bwEstimator = this.initEstimator();
  2948. this.registerListeners();
  2949. }
  2950. resetEstimator(abrEwmaDefaultEstimate) {
  2951. if (abrEwmaDefaultEstimate) {
  2952. this.log(`setting initial bwe to ${abrEwmaDefaultEstimate}`);
  2953. this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;
  2954. }
  2955. this.firstSelection = -1;
  2956. this.bwEstimator = this.initEstimator();
  2957. }
  2958. initEstimator() {
  2959. const config = this.hls.config;
  2960. return new EwmaBandWidthEstimator(config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
  2961. }
  2962. registerListeners() {
  2963. const {
  2964. hls
  2965. } = this;
  2966. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  2967. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  2968. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  2969. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  2970. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  2971. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  2972. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  2973. hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  2974. hls.on(Events.ERROR, this.onError, this);
  2975. }
  2976. unregisterListeners() {
  2977. const {
  2978. hls
  2979. } = this;
  2980. if (!hls) {
  2981. return;
  2982. }
  2983. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  2984. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  2985. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  2986. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  2987. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  2988. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  2989. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  2990. hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  2991. hls.off(Events.ERROR, this.onError, this);
  2992. }
  2993. destroy() {
  2994. this.unregisterListeners();
  2995. this.clearTimer();
  2996. this.hls = this._abandonRulesCheck = this.supportedCache = null;
  2997. this.fragCurrent = this.partCurrent = null;
  2998. }
  2999. onManifestLoading(event, data) {
  3000. this.lastLoadedFragLevel = -1;
  3001. this.firstSelection = -1;
  3002. this.lastLevelLoadSec = 0;
  3003. this.supportedCache = {};
  3004. this.fragCurrent = this.partCurrent = null;
  3005. this.onLevelsUpdated();
  3006. this.clearTimer();
  3007. }
  3008. onLevelsUpdated() {
  3009. if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {
  3010. this.lastLoadedFragLevel = this.fragCurrent.level;
  3011. }
  3012. this._nextAutoLevel = -1;
  3013. this.onMaxAutoLevelUpdated();
  3014. this.codecTiers = null;
  3015. this.audioTracksByGroup = null;
  3016. }
  3017. onMaxAutoLevelUpdated() {
  3018. this.firstSelection = -1;
  3019. this.nextAutoLevelKey = "";
  3020. }
  3021. onFragLoading(event, data) {
  3022. const frag = data.frag;
  3023. if (this.ignoreFragment(frag)) {
  3024. return;
  3025. }
  3026. if (!frag.bitrateTest) {
  3027. var _data$part;
  3028. this.fragCurrent = frag;
  3029. this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
  3030. }
  3031. this.clearTimer();
  3032. this.timer = self.setInterval(this._abandonRulesCheck, 100);
  3033. }
  3034. onLevelSwitching(event, data) {
  3035. this.clearTimer();
  3036. }
  3037. onError(event, data) {
  3038. if (data.fatal) {
  3039. return;
  3040. }
  3041. switch (data.details) {
  3042. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  3043. case ErrorDetails.BUFFER_APPEND_ERROR:
  3044. this.lastLoadedFragLevel = -1;
  3045. this.firstSelection = -1;
  3046. break;
  3047. case ErrorDetails.FRAG_LOAD_TIMEOUT: {
  3048. const frag = data.frag;
  3049. const {
  3050. fragCurrent,
  3051. partCurrent: part
  3052. } = this;
  3053. if (frag && fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level) {
  3054. const now2 = performance.now();
  3055. const stats = part ? part.stats : frag.stats;
  3056. const timeLoading = now2 - stats.loading.start;
  3057. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  3058. const loadedFirstByte = stats.loaded && ttfb > -1;
  3059. if (loadedFirstByte) {
  3060. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  3061. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  3062. } else {
  3063. this.bwEstimator.sampleTTFB(timeLoading);
  3064. }
  3065. }
  3066. break;
  3067. }
  3068. }
  3069. }
  3070. getTimeToLoadFrag(timeToFirstByteSec, bandwidth, fragSizeBits, isSwitch) {
  3071. const fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;
  3072. const playlistLoadSec = isSwitch ? timeToFirstByteSec + this.lastLevelLoadSec : 0;
  3073. return fragLoadSec + playlistLoadSec;
  3074. }
  3075. onLevelLoaded(event, data) {
  3076. const config = this.hls.config;
  3077. const {
  3078. loading
  3079. } = data.stats;
  3080. const timeLoadingMs = loading.end - loading.first;
  3081. if (isFiniteNumber(timeLoadingMs)) {
  3082. this.lastLevelLoadSec = timeLoadingMs / 1e3;
  3083. }
  3084. if (data.details.live) {
  3085. this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
  3086. } else {
  3087. this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
  3088. }
  3089. if (this.timer > -1) {
  3090. this._abandonRulesCheck(data.levelInfo);
  3091. }
  3092. }
  3093. onFragLoaded(event, {
  3094. frag,
  3095. part
  3096. }) {
  3097. const stats = part ? part.stats : frag.stats;
  3098. if (frag.type === PlaylistLevelType.MAIN) {
  3099. this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);
  3100. }
  3101. if (this.ignoreFragment(frag)) {
  3102. return;
  3103. }
  3104. this.clearTimer();
  3105. if (frag.level === this._nextAutoLevel) {
  3106. this._nextAutoLevel = -1;
  3107. }
  3108. this.firstSelection = -1;
  3109. if (this.hls.config.abrMaxWithRealBitrate) {
  3110. const duration = part ? part.duration : frag.duration;
  3111. const level = this.hls.levels[frag.level];
  3112. const loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
  3113. const loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
  3114. level.loaded = {
  3115. bytes: loadedBytes,
  3116. duration: loadedDuration
  3117. };
  3118. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  3119. }
  3120. if (frag.bitrateTest) {
  3121. const fragBufferedData = {
  3122. stats,
  3123. frag,
  3124. part,
  3125. id: frag.type
  3126. };
  3127. this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);
  3128. frag.bitrateTest = false;
  3129. } else {
  3130. this.lastLoadedFragLevel = frag.level;
  3131. }
  3132. }
  3133. onFragBuffered(event, data) {
  3134. const {
  3135. frag,
  3136. part
  3137. } = data;
  3138. const stats = part != null && part.stats.loaded ? part.stats : frag.stats;
  3139. if (stats.aborted) {
  3140. return;
  3141. }
  3142. if (this.ignoreFragment(frag)) {
  3143. return;
  3144. }
  3145. const processingMs = stats.parsing.end - stats.loading.start - Math.min(stats.loading.first - stats.loading.start, this.bwEstimator.getEstimateTTFB());
  3146. this.bwEstimator.sample(processingMs, stats.loaded);
  3147. stats.bwEstimate = this.getBwEstimate();
  3148. if (frag.bitrateTest) {
  3149. this.bitrateTestDelay = processingMs / 1e3;
  3150. } else {
  3151. this.bitrateTestDelay = 0;
  3152. }
  3153. }
  3154. ignoreFragment(frag) {
  3155. return frag.type !== PlaylistLevelType.MAIN || frag.sn === "initSegment";
  3156. }
  3157. clearTimer() {
  3158. if (this.timer > -1) {
  3159. self.clearInterval(this.timer);
  3160. this.timer = -1;
  3161. }
  3162. }
  3163. get firstAutoLevel() {
  3164. const {
  3165. maxAutoLevel,
  3166. minAutoLevel
  3167. } = this.hls;
  3168. const bwEstimate = this.getBwEstimate();
  3169. const maxStartDelay = this.hls.config.maxStarvationDelay;
  3170. const abrAutoLevel = this.findBestLevel(bwEstimate, minAutoLevel, maxAutoLevel, 0, maxStartDelay, 1, 1);
  3171. if (abrAutoLevel > -1) {
  3172. return abrAutoLevel;
  3173. }
  3174. const firstLevel = this.hls.firstLevel;
  3175. const clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);
  3176. this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${firstLevel} clamped to ${clamped}`);
  3177. return clamped;
  3178. }
  3179. get forcedAutoLevel() {
  3180. if (this.nextAutoLevelKey) {
  3181. return -1;
  3182. }
  3183. return this._nextAutoLevel;
  3184. }
  3185. get nextAutoLevel() {
  3186. const forcedAutoLevel = this.forcedAutoLevel;
  3187. const bwEstimator = this.bwEstimator;
  3188. const useEstimate = bwEstimator.canEstimate();
  3189. const loadedFirstFrag = this.lastLoadedFragLevel > -1;
  3190. if (forcedAutoLevel !== -1 && (!useEstimate || !loadedFirstFrag || this.nextAutoLevelKey === this.getAutoLevelKey())) {
  3191. return forcedAutoLevel;
  3192. }
  3193. const nextABRAutoLevel = useEstimate && loadedFirstFrag ? this.getNextABRAutoLevel() : this.firstAutoLevel;
  3194. if (forcedAutoLevel !== -1) {
  3195. const levels = this.hls.levels;
  3196. if (levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) && levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError) {
  3197. return forcedAutoLevel;
  3198. }
  3199. }
  3200. this._nextAutoLevel = nextABRAutoLevel;
  3201. this.nextAutoLevelKey = this.getAutoLevelKey();
  3202. return nextABRAutoLevel;
  3203. }
  3204. getAutoLevelKey() {
  3205. return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`;
  3206. }
  3207. getNextABRAutoLevel() {
  3208. const {
  3209. fragCurrent,
  3210. partCurrent,
  3211. hls
  3212. } = this;
  3213. if (hls.levels.length <= 1) {
  3214. return hls.loadLevel;
  3215. }
  3216. const {
  3217. maxAutoLevel,
  3218. config,
  3219. minAutoLevel
  3220. } = hls;
  3221. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  3222. const avgbw = this.getBwEstimate();
  3223. const bufferStarvationDelay = this.getStarvationDelay();
  3224. let bwFactor = config.abrBandWidthFactor;
  3225. let bwUpFactor = config.abrBandWidthUpFactor;
  3226. if (bufferStarvationDelay) {
  3227. const _bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, 0, bwFactor, bwUpFactor);
  3228. if (_bestLevel >= 0) {
  3229. this.rebufferNotice = -1;
  3230. return _bestLevel;
  3231. }
  3232. }
  3233. let maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
  3234. if (!bufferStarvationDelay) {
  3235. const bitrateTestDelay = this.bitrateTestDelay;
  3236. if (bitrateTestDelay) {
  3237. const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  3238. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  3239. this.info(`bitrate test took ${Math.round(1e3 * bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1e3 * maxStarvationDelay)} ms`);
  3240. bwFactor = bwUpFactor = 1;
  3241. }
  3242. }
  3243. const bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor);
  3244. if (this.rebufferNotice !== bestLevel) {
  3245. this.rebufferNotice = bestLevel;
  3246. this.info(`${bufferStarvationDelay ? "rebuffering expected" : "buffer is empty"}, optimal quality level ${bestLevel}`);
  3247. }
  3248. if (bestLevel > -1) {
  3249. return bestLevel;
  3250. }
  3251. const minLevel = hls.levels[minAutoLevel];
  3252. const autoLevel = hls.loadLevelObj;
  3253. if (autoLevel && (minLevel == null ? void 0 : minLevel.bitrate) < autoLevel.bitrate) {
  3254. return minAutoLevel;
  3255. }
  3256. return hls.loadLevel;
  3257. }
  3258. getStarvationDelay() {
  3259. const hls = this.hls;
  3260. const media = hls.media;
  3261. if (!media) {
  3262. return Infinity;
  3263. }
  3264. const playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1;
  3265. const bufferInfo = hls.mainForwardBufferInfo;
  3266. return (bufferInfo ? bufferInfo.len : 0) / playbackRate;
  3267. }
  3268. getBwEstimate() {
  3269. return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;
  3270. }
  3271. findBestLevel(currentBw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor) {
  3272. var _this$hls$latestLevel;
  3273. const maxFetchDuration = bufferStarvationDelay + maxStarvationDelay;
  3274. const lastLoadedFragLevel = this.lastLoadedFragLevel;
  3275. const selectionBaseLevel = lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;
  3276. const {
  3277. fragCurrent,
  3278. partCurrent
  3279. } = this;
  3280. const {
  3281. levels,
  3282. allAudioTracks,
  3283. loadLevel,
  3284. config
  3285. } = this.hls;
  3286. if (levels.length === 1) {
  3287. return 0;
  3288. }
  3289. const level = levels[selectionBaseLevel];
  3290. const live = !!((_this$hls$latestLevel = this.hls.latestLevelDetails) != null && _this$hls$latestLevel.live);
  3291. const firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;
  3292. let currentCodecSet;
  3293. let currentVideoRange = "SDR";
  3294. let currentFrameRate = (level == null ? void 0 : level.frameRate) || 0;
  3295. const {
  3296. audioPreference,
  3297. videoPreference
  3298. } = config;
  3299. const audioTracksByGroup = this.audioTracksByGroup || (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));
  3300. let minStartIndex = -1;
  3301. if (firstSelection) {
  3302. if (this.firstSelection !== -1) {
  3303. return this.firstSelection;
  3304. }
  3305. const codecTiers = this.codecTiers || (this.codecTiers = getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel));
  3306. const startTier = getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference);
  3307. const {
  3308. codecSet,
  3309. videoRanges,
  3310. minFramerate,
  3311. minBitrate,
  3312. minIndex,
  3313. preferHDR
  3314. } = startTier;
  3315. minStartIndex = minIndex;
  3316. currentCodecSet = codecSet;
  3317. currentVideoRange = preferHDR ? videoRanges[videoRanges.length - 1] : videoRanges[0];
  3318. currentFrameRate = minFramerate;
  3319. currentBw = Math.max(currentBw, minBitrate);
  3320. this.log(`picked start tier ${stringify(startTier)}`);
  3321. } else {
  3322. currentCodecSet = level == null ? void 0 : level.codecSet;
  3323. currentVideoRange = level == null ? void 0 : level.videoRange;
  3324. }
  3325. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  3326. const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1e3;
  3327. const levelsSkipped = [];
  3328. for (let i = maxAutoLevel; i >= minAutoLevel; i--) {
  3329. var _levelInfo$supportedR, _levelInfo$supportedR2;
  3330. const levelInfo = levels[i];
  3331. const upSwitch = i > selectionBaseLevel;
  3332. if (!levelInfo) {
  3333. continue;
  3334. }
  3335. if (config.useMediaCapabilities && !levelInfo.supportedResult && !levelInfo.supportedPromise) {
  3336. const mediaCapabilities = navigator.mediaCapabilities;
  3337. if (typeof (mediaCapabilities == null ? void 0 : mediaCapabilities.decodingInfo) === "function" && requiresMediaCapabilitiesDecodingInfo(levelInfo, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference)) {
  3338. levelInfo.supportedPromise = getMediaDecodingInfoPromise(levelInfo, audioTracksByGroup, mediaCapabilities, this.supportedCache);
  3339. levelInfo.supportedPromise.then((decodingInfo) => {
  3340. if (!this.hls) {
  3341. return;
  3342. }
  3343. levelInfo.supportedResult = decodingInfo;
  3344. const levels2 = this.hls.levels;
  3345. const index = levels2.indexOf(levelInfo);
  3346. if (decodingInfo.error) {
  3347. this.warn(`MediaCapabilities decodingInfo error: "${decodingInfo.error}" for level ${index} ${stringify(decodingInfo)}`);
  3348. } else if (!decodingInfo.supported) {
  3349. this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${index} ${stringify(decodingInfo)}`);
  3350. if (index > -1 && levels2.length > 1) {
  3351. this.log(`Removing unsupported level ${index}`);
  3352. this.hls.removeLevel(index);
  3353. if (this.hls.loadLevel === -1) {
  3354. this.hls.nextLoadLevel = 0;
  3355. }
  3356. }
  3357. } else if (decodingInfo.decodingInfoResults.some((info) => info.smooth === false || info.powerEfficient === false)) {
  3358. this.log(`MediaCapabilities decodingInfo for level ${index} not smooth or powerEfficient: ${stringify(decodingInfo)}`);
  3359. }
  3360. });
  3361. } else {
  3362. levelInfo.supportedResult = SUPPORTED_INFO_DEFAULT;
  3363. }
  3364. }
  3365. 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)) {
  3366. if (!firstSelection || i !== minStartIndex) {
  3367. levelsSkipped.push(i);
  3368. continue;
  3369. }
  3370. }
  3371. const levelDetails = levelInfo.details;
  3372. const avgDuration = (partCurrent ? levelDetails == null ? void 0 : levelDetails.partTarget : levelDetails == null ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
  3373. let adjustedbw;
  3374. if (!upSwitch) {
  3375. adjustedbw = bwFactor * currentBw;
  3376. } else {
  3377. adjustedbw = bwUpFactor * currentBw;
  3378. }
  3379. const bitrate = currentFragDuration && bufferStarvationDelay >= currentFragDuration * 2 && maxStarvationDelay === 0 ? levelInfo.averageBitrate : levelInfo.maxBitrate;
  3380. const fetchDuration = this.getTimeToLoadFrag(ttfbEstimateSec, adjustedbw, bitrate * avgDuration, levelDetails === void 0);
  3381. const canSwitchWithinTolerance = adjustedbw >= bitrate && (i === lastLoadedFragLevel || levelInfo.loadError === 0 && levelInfo.fragmentError === 0) && (fetchDuration <= ttfbEstimateSec || !isFiniteNumber(fetchDuration) || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration);
  3382. if (canSwitchWithinTolerance) {
  3383. const forcedAutoLevel = this.forcedAutoLevel;
  3384. if (i !== loadLevel && (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)) {
  3385. if (levelsSkipped.length) {
  3386. 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}`);
  3387. }
  3388. 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}`);
  3389. }
  3390. if (firstSelection) {
  3391. this.firstSelection = i;
  3392. }
  3393. return i;
  3394. }
  3395. }
  3396. return -1;
  3397. }
  3398. set nextAutoLevel(nextLevel) {
  3399. const value = this.deriveNextAutoLevel(nextLevel);
  3400. if (this._nextAutoLevel !== value) {
  3401. this.nextAutoLevelKey = "";
  3402. this._nextAutoLevel = value;
  3403. }
  3404. }
  3405. deriveNextAutoLevel(nextLevel) {
  3406. const {
  3407. maxAutoLevel,
  3408. minAutoLevel
  3409. } = this.hls;
  3410. return Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);
  3411. }
  3412. };
  3413. var BinarySearch = {
  3414. search: function(list, comparisonFn) {
  3415. let minIndex = 0;
  3416. let maxIndex = list.length - 1;
  3417. let currentIndex = null;
  3418. let currentElement = null;
  3419. while (minIndex <= maxIndex) {
  3420. currentIndex = (minIndex + maxIndex) / 2 | 0;
  3421. currentElement = list[currentIndex];
  3422. const comparisonResult = comparisonFn(currentElement);
  3423. if (comparisonResult > 0) {
  3424. minIndex = currentIndex + 1;
  3425. } else if (comparisonResult < 0) {
  3426. maxIndex = currentIndex - 1;
  3427. } else {
  3428. return currentElement;
  3429. }
  3430. }
  3431. return null;
  3432. }
  3433. };
  3434. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  3435. if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !isFiniteNumber(PDTValue)) {
  3436. return null;
  3437. }
  3438. const startPDT = fragments[0].programDateTime;
  3439. if (PDTValue < (startPDT || 0)) {
  3440. return null;
  3441. }
  3442. const endPDT = fragments[fragments.length - 1].endProgramDateTime;
  3443. if (PDTValue >= (endPDT || 0)) {
  3444. return null;
  3445. }
  3446. for (let seg = 0; seg < fragments.length; ++seg) {
  3447. const frag = fragments[seg];
  3448. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  3449. return frag;
  3450. }
  3451. }
  3452. return null;
  3453. }
  3454. function findFragmentByPTS(fragPrevious, fragments, bufferEnd = 0, maxFragLookUpTolerance = 0, nextFragLookupTolerance = 5e-3) {
  3455. let fragNext = null;
  3456. if (fragPrevious) {
  3457. fragNext = fragments[1 + fragPrevious.sn - fragments[0].sn] || null;
  3458. const bufferEdgeError = fragPrevious.endDTS - bufferEnd;
  3459. if (bufferEdgeError > 0 && bufferEdgeError < 15e-7) {
  3460. bufferEnd += 15e-7;
  3461. }
  3462. if (fragNext && fragPrevious.level !== fragNext.level && fragNext.end <= fragPrevious.end) {
  3463. fragNext = fragments[2 + fragPrevious.sn - fragments[0].sn] || null;
  3464. }
  3465. } else if (bufferEnd === 0 && fragments[0].start === 0) {
  3466. fragNext = fragments[0];
  3467. }
  3468. if (fragNext && ((!fragPrevious || fragPrevious.level === fragNext.level) && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0 || fragmentWithinFastStartSwitch(fragNext, fragPrevious, Math.min(nextFragLookupTolerance, maxFragLookUpTolerance)))) {
  3469. return fragNext;
  3470. }
  3471. const foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  3472. if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {
  3473. return foundFragment;
  3474. }
  3475. return fragNext;
  3476. }
  3477. function fragmentWithinFastStartSwitch(fragNext, fragPrevious, nextFragLookupTolerance) {
  3478. if (fragPrevious && fragPrevious.start === 0 && fragPrevious.level < fragNext.level && (fragPrevious.endPTS || 0) > 0) {
  3479. const firstDuration = fragPrevious.tagList.reduce((duration, tag) => {
  3480. if (tag[0] === "INF") {
  3481. duration += parseFloat(tag[1]);
  3482. }
  3483. return duration;
  3484. }, nextFragLookupTolerance);
  3485. return fragNext.start <= firstDuration;
  3486. }
  3487. return false;
  3488. }
  3489. function fragmentWithinToleranceTest(bufferEnd = 0, maxFragLookUpTolerance = 0, candidate) {
  3490. if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) {
  3491. return 0;
  3492. }
  3493. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  3494. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  3495. return 1;
  3496. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  3497. return -1;
  3498. }
  3499. return 0;
  3500. }
  3501. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  3502. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1e3;
  3503. const endProgramDateTime = candidate.endProgramDateTime || 0;
  3504. return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  3505. }
  3506. function findNearestWithCC(details, cc, pos) {
  3507. if (details) {
  3508. if (details.startCC <= cc && details.endCC >= cc) {
  3509. let fragments = details.fragments;
  3510. const {
  3511. fragmentHint
  3512. } = details;
  3513. if (fragmentHint) {
  3514. fragments = fragments.concat(fragmentHint);
  3515. }
  3516. let closest;
  3517. BinarySearch.search(fragments, (candidate) => {
  3518. if (candidate.cc < cc) {
  3519. return 1;
  3520. }
  3521. if (candidate.cc > cc) {
  3522. return -1;
  3523. }
  3524. closest = candidate;
  3525. if (candidate.end <= pos) {
  3526. return 1;
  3527. }
  3528. if (candidate.start > pos) {
  3529. return -1;
  3530. }
  3531. return 0;
  3532. });
  3533. return closest || null;
  3534. }
  3535. }
  3536. return null;
  3537. }
  3538. function isTimeoutError(error) {
  3539. switch (error.details) {
  3540. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  3541. case ErrorDetails.KEY_LOAD_TIMEOUT:
  3542. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  3543. case ErrorDetails.MANIFEST_LOAD_TIMEOUT:
  3544. return true;
  3545. }
  3546. return false;
  3547. }
  3548. function getRetryConfig(loadPolicy, error) {
  3549. const isTimeout = isTimeoutError(error);
  3550. return loadPolicy.default[`${isTimeout ? "timeout" : "error"}Retry`];
  3551. }
  3552. function getRetryDelay(retryConfig, retryCount) {
  3553. const backoffFactor = retryConfig.backoff === "linear" ? 1 : Math.pow(2, retryCount);
  3554. return Math.min(backoffFactor * retryConfig.retryDelayMs, retryConfig.maxRetryDelayMs);
  3555. }
  3556. function getLoaderConfigWithoutReties(loderConfig) {
  3557. return _objectSpread2(_objectSpread2({}, loderConfig), {
  3558. errorRetry: null,
  3559. timeoutRetry: null
  3560. });
  3561. }
  3562. function shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse) {
  3563. if (!retryConfig) {
  3564. return false;
  3565. }
  3566. const httpStatus = loaderResponse == null ? void 0 : loaderResponse.code;
  3567. const retry = retryCount < retryConfig.maxNumRetry && (retryForHttpStatus(httpStatus) || !!isTimeout);
  3568. return retryConfig.shouldRetry ? retryConfig.shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse, retry) : retry;
  3569. }
  3570. function retryForHttpStatus(httpStatus) {
  3571. return httpStatus === 0 && navigator.onLine === false || !!httpStatus && (httpStatus < 400 || httpStatus > 499);
  3572. }
  3573. var NetworkErrorAction = {
  3574. DoNothing: 0,
  3575. SendEndCallback: 1,
  3576. SendAlternateToPenaltyBox: 2,
  3577. RemoveAlternatePermanently: 3,
  3578. InsertDiscontinuity: 4,
  3579. RetryRequest: 5
  3580. };
  3581. var ErrorActionFlags = {
  3582. None: 0,
  3583. MoveAllAlternatesMatchingHost: 1,
  3584. MoveAllAlternatesMatchingHDCP: 2,
  3585. SwitchToSDR: 4
  3586. };
  3587. var ErrorController = class extends Logger {
  3588. constructor(hls) {
  3589. super("error-controller", hls.logger);
  3590. this.hls = void 0;
  3591. this.playlistError = 0;
  3592. this.penalizedRenditions = {};
  3593. this.hls = hls;
  3594. this.registerListeners();
  3595. }
  3596. registerListeners() {
  3597. const hls = this.hls;
  3598. hls.on(Events.ERROR, this.onError, this);
  3599. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3600. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  3601. }
  3602. unregisterListeners() {
  3603. const hls = this.hls;
  3604. if (!hls) {
  3605. return;
  3606. }
  3607. hls.off(Events.ERROR, this.onError, this);
  3608. hls.off(Events.ERROR, this.onErrorOut, this);
  3609. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3610. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  3611. }
  3612. destroy() {
  3613. this.unregisterListeners();
  3614. this.hls = null;
  3615. this.penalizedRenditions = {};
  3616. }
  3617. startLoad(startPosition) {
  3618. }
  3619. stopLoad() {
  3620. this.playlistError = 0;
  3621. }
  3622. getVariantLevelIndex(frag) {
  3623. return (frag == null ? void 0 : frag.type) === PlaylistLevelType.MAIN ? frag.level : this.hls.loadLevel;
  3624. }
  3625. onManifestLoading() {
  3626. this.playlistError = 0;
  3627. this.penalizedRenditions = {};
  3628. }
  3629. onLevelUpdated() {
  3630. this.playlistError = 0;
  3631. }
  3632. onError(event, data) {
  3633. var _data$frag;
  3634. if (data.fatal) {
  3635. return;
  3636. }
  3637. const hls = this.hls;
  3638. const context = data.context;
  3639. switch (data.details) {
  3640. case ErrorDetails.FRAG_LOAD_ERROR:
  3641. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  3642. case ErrorDetails.KEY_LOAD_ERROR:
  3643. case ErrorDetails.KEY_LOAD_TIMEOUT:
  3644. data.errorAction = this.getFragRetryOrSwitchAction(data);
  3645. return;
  3646. case ErrorDetails.FRAG_PARSING_ERROR:
  3647. if ((_data$frag = data.frag) != null && _data$frag.gap) {
  3648. data.errorAction = createDoNothingErrorAction();
  3649. return;
  3650. }
  3651. case ErrorDetails.FRAG_GAP:
  3652. case ErrorDetails.FRAG_DECRYPT_ERROR: {
  3653. data.errorAction = this.getFragRetryOrSwitchAction(data);
  3654. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  3655. return;
  3656. }
  3657. case ErrorDetails.LEVEL_EMPTY_ERROR:
  3658. case ErrorDetails.LEVEL_PARSING_ERROR:
  3659. {
  3660. var _data$context, _data$context$levelDe;
  3661. const levelIndex = data.parent === PlaylistLevelType.MAIN ? data.level : hls.loadLevel;
  3662. if (data.details === ErrorDetails.LEVEL_EMPTY_ERROR && !!((_data$context = data.context) != null && (_data$context$levelDe = _data$context.levelDetails) != null && _data$context$levelDe.live)) {
  3663. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, levelIndex);
  3664. } else {
  3665. data.levelRetry = false;
  3666. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  3667. }
  3668. }
  3669. return;
  3670. case ErrorDetails.LEVEL_LOAD_ERROR:
  3671. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  3672. if (typeof (context == null ? void 0 : context.level) === "number") {
  3673. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, context.level);
  3674. }
  3675. return;
  3676. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  3677. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  3678. case ErrorDetails.SUBTITLE_LOAD_ERROR:
  3679. case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:
  3680. if (context) {
  3681. const level = hls.loadLevelObj;
  3682. if (level && (context.type === PlaylistContextType.AUDIO_TRACK && level.hasAudioGroup(context.groupId) || context.type === PlaylistContextType.SUBTITLE_TRACK && level.hasSubtitleGroup(context.groupId))) {
  3683. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, hls.loadLevel);
  3684. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  3685. data.errorAction.flags = ErrorActionFlags.MoveAllAlternatesMatchingHost;
  3686. return;
  3687. }
  3688. }
  3689. return;
  3690. case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:
  3691. {
  3692. const level = hls.loadLevelObj;
  3693. const restrictedHdcpLevel = level == null ? void 0 : level.attrs["HDCP-LEVEL"];
  3694. if (restrictedHdcpLevel) {
  3695. data.errorAction = {
  3696. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  3697. flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,
  3698. hdcpLevel: restrictedHdcpLevel
  3699. };
  3700. } else {
  3701. this.keySystemError(data);
  3702. }
  3703. }
  3704. return;
  3705. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  3706. case ErrorDetails.REMUX_ALLOC_ERROR:
  3707. case ErrorDetails.BUFFER_APPEND_ERROR:
  3708. if (!data.errorAction) {
  3709. var _data$level;
  3710. data.errorAction = this.getLevelSwitchAction(data, (_data$level = data.level) != null ? _data$level : hls.loadLevel);
  3711. }
  3712. return;
  3713. case ErrorDetails.INTERNAL_EXCEPTION:
  3714. case ErrorDetails.BUFFER_APPENDING_ERROR:
  3715. case ErrorDetails.BUFFER_FULL_ERROR:
  3716. case ErrorDetails.LEVEL_SWITCH_ERROR:
  3717. case ErrorDetails.BUFFER_STALLED_ERROR:
  3718. case ErrorDetails.BUFFER_SEEK_OVER_HOLE:
  3719. case ErrorDetails.BUFFER_NUDGE_ON_STALL:
  3720. data.errorAction = createDoNothingErrorAction();
  3721. return;
  3722. }
  3723. if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {
  3724. this.keySystemError(data);
  3725. }
  3726. }
  3727. keySystemError(data) {
  3728. const levelIndex = this.getVariantLevelIndex(data.frag);
  3729. data.levelRetry = false;
  3730. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  3731. }
  3732. getPlaylistRetryOrSwitchAction(data, levelIndex) {
  3733. const hls = this.hls;
  3734. const retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);
  3735. const retryCount = this.playlistError++;
  3736. const retry = shouldRetry(retryConfig, retryCount, isTimeoutError(data), data.response);
  3737. if (retry) {
  3738. return {
  3739. action: NetworkErrorAction.RetryRequest,
  3740. flags: ErrorActionFlags.None,
  3741. retryConfig,
  3742. retryCount
  3743. };
  3744. }
  3745. const errorAction = this.getLevelSwitchAction(data, levelIndex);
  3746. if (retryConfig) {
  3747. errorAction.retryConfig = retryConfig;
  3748. errorAction.retryCount = retryCount;
  3749. }
  3750. return errorAction;
  3751. }
  3752. getFragRetryOrSwitchAction(data) {
  3753. const hls = this.hls;
  3754. const variantLevelIndex = this.getVariantLevelIndex(data.frag);
  3755. const level = hls.levels[variantLevelIndex];
  3756. const {
  3757. fragLoadPolicy,
  3758. keyLoadPolicy
  3759. } = hls.config;
  3760. const retryConfig = getRetryConfig(data.details.startsWith("key") ? keyLoadPolicy : fragLoadPolicy, data);
  3761. const fragmentErrors = hls.levels.reduce((acc, level2) => acc + level2.fragmentError, 0);
  3762. if (level) {
  3763. if (data.details !== ErrorDetails.FRAG_GAP) {
  3764. level.fragmentError++;
  3765. }
  3766. const retry = shouldRetry(retryConfig, fragmentErrors, isTimeoutError(data), data.response);
  3767. if (retry) {
  3768. return {
  3769. action: NetworkErrorAction.RetryRequest,
  3770. flags: ErrorActionFlags.None,
  3771. retryConfig,
  3772. retryCount: fragmentErrors
  3773. };
  3774. }
  3775. }
  3776. const errorAction = this.getLevelSwitchAction(data, variantLevelIndex);
  3777. if (retryConfig) {
  3778. errorAction.retryConfig = retryConfig;
  3779. errorAction.retryCount = fragmentErrors;
  3780. }
  3781. return errorAction;
  3782. }
  3783. getLevelSwitchAction(data, levelIndex) {
  3784. const hls = this.hls;
  3785. if (levelIndex === null || levelIndex === void 0) {
  3786. levelIndex = hls.loadLevel;
  3787. }
  3788. const level = this.hls.levels[levelIndex];
  3789. if (level) {
  3790. var _data$frag2, _data$context2;
  3791. const errorDetails = data.details;
  3792. level.loadError++;
  3793. if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {
  3794. level.fragmentError++;
  3795. }
  3796. let nextLevel = -1;
  3797. const {
  3798. levels,
  3799. loadLevel,
  3800. minAutoLevel,
  3801. maxAutoLevel
  3802. } = hls;
  3803. if (!hls.autoLevelEnabled && !hls.config.preserveManualLevelOnError) {
  3804. hls.loadLevel = -1;
  3805. }
  3806. const fragErrorType = (_data$frag2 = data.frag) == null ? void 0 : _data$frag2.type;
  3807. const isAudioCodecError = fragErrorType === PlaylistLevelType.AUDIO && errorDetails === ErrorDetails.FRAG_PARSING_ERROR || data.sourceBufferName === "audio" && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  3808. const findAudioCodecAlternate = isAudioCodecError && levels.some(({
  3809. audioCodec
  3810. }) => level.audioCodec !== audioCodec);
  3811. const isVideoCodecError = data.sourceBufferName === "video" && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  3812. const findVideoCodecAlternate = isVideoCodecError && levels.some(({
  3813. codecSet,
  3814. audioCodec
  3815. }) => level.codecSet !== codecSet && level.audioCodec === audioCodec);
  3816. const {
  3817. type: playlistErrorType,
  3818. groupId: playlistErrorGroupId
  3819. } = (_data$context2 = data.context) != null ? _data$context2 : {};
  3820. for (let i = levels.length; i--; ) {
  3821. const candidate = (i + loadLevel) % levels.length;
  3822. if (candidate !== loadLevel && candidate >= minAutoLevel && candidate <= maxAutoLevel && levels[candidate].loadError === 0) {
  3823. var _level$audioGroups, _level$subtitleGroups;
  3824. const levelCandidate = levels[candidate];
  3825. if (errorDetails === ErrorDetails.FRAG_GAP && fragErrorType === PlaylistLevelType.MAIN && data.frag) {
  3826. const levelDetails = levels[candidate].details;
  3827. if (levelDetails) {
  3828. const fragCandidate = findFragmentByPTS(data.frag, levelDetails.fragments, data.frag.start);
  3829. if (fragCandidate != null && fragCandidate.gap) {
  3830. continue;
  3831. }
  3832. }
  3833. } else if (playlistErrorType === PlaylistContextType.AUDIO_TRACK && levelCandidate.hasAudioGroup(playlistErrorGroupId) || playlistErrorType === PlaylistContextType.SUBTITLE_TRACK && levelCandidate.hasSubtitleGroup(playlistErrorGroupId)) {
  3834. continue;
  3835. } 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) {
  3836. continue;
  3837. }
  3838. nextLevel = candidate;
  3839. break;
  3840. }
  3841. }
  3842. if (nextLevel > -1 && hls.loadLevel !== nextLevel) {
  3843. data.levelRetry = true;
  3844. this.playlistError = 0;
  3845. return {
  3846. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  3847. flags: ErrorActionFlags.None,
  3848. nextAutoLevel: nextLevel
  3849. };
  3850. }
  3851. }
  3852. return {
  3853. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  3854. flags: ErrorActionFlags.MoveAllAlternatesMatchingHost
  3855. };
  3856. }
  3857. onErrorOut(event, data) {
  3858. var _data$errorAction;
  3859. switch ((_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.action) {
  3860. case NetworkErrorAction.DoNothing:
  3861. break;
  3862. case NetworkErrorAction.SendAlternateToPenaltyBox:
  3863. this.sendAlternateToPenaltyBox(data);
  3864. if (!data.errorAction.resolved && data.details !== ErrorDetails.FRAG_GAP) {
  3865. data.fatal = true;
  3866. } else if (/MediaSource readyState: ended/.test(data.error.message)) {
  3867. this.warn(`MediaSource ended after "${data.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`);
  3868. this.hls.recoverMediaError();
  3869. }
  3870. break;
  3871. case NetworkErrorAction.RetryRequest:
  3872. break;
  3873. }
  3874. if (data.fatal) {
  3875. this.hls.stopLoad();
  3876. return;
  3877. }
  3878. }
  3879. sendAlternateToPenaltyBox(data) {
  3880. const hls = this.hls;
  3881. const errorAction = data.errorAction;
  3882. if (!errorAction) {
  3883. return;
  3884. }
  3885. const {
  3886. flags,
  3887. hdcpLevel,
  3888. nextAutoLevel
  3889. } = errorAction;
  3890. switch (flags) {
  3891. case ErrorActionFlags.None:
  3892. this.switchLevel(data, nextAutoLevel);
  3893. break;
  3894. case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:
  3895. if (hdcpLevel) {
  3896. hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];
  3897. errorAction.resolved = true;
  3898. }
  3899. this.warn(`Restricting playback to HDCP-LEVEL of "${hls.maxHdcpLevel}" or lower`);
  3900. break;
  3901. }
  3902. if (!errorAction.resolved) {
  3903. this.switchLevel(data, nextAutoLevel);
  3904. }
  3905. }
  3906. switchLevel(data, levelIndex) {
  3907. if (levelIndex !== void 0 && data.errorAction) {
  3908. this.warn(`switching to level ${levelIndex} after ${data.details}`);
  3909. this.hls.nextAutoLevel = levelIndex;
  3910. data.errorAction.resolved = true;
  3911. this.hls.nextLoadLevel = this.hls.nextAutoLevel;
  3912. if (data.details === ErrorDetails.BUFFER_ADD_CODEC_ERROR && data.mimeType && data.sourceBufferName !== "audiovideo") {
  3913. const codec = getCodecsForMimeType(data.mimeType);
  3914. const levels = this.hls.levels;
  3915. for (let i = levels.length; i--; ) {
  3916. if (levels[i][`${data.sourceBufferName}Codec`] === codec) {
  3917. this.hls.removeLevel(i);
  3918. }
  3919. }
  3920. }
  3921. }
  3922. }
  3923. };
  3924. function createDoNothingErrorAction(resolved) {
  3925. const errorAction = {
  3926. action: NetworkErrorAction.DoNothing,
  3927. flags: ErrorActionFlags.None
  3928. };
  3929. if (resolved) {
  3930. errorAction.resolved = true;
  3931. }
  3932. return errorAction;
  3933. }
  3934. var FragmentState = {
  3935. NOT_LOADED: "NOT_LOADED",
  3936. APPENDING: "APPENDING",
  3937. PARTIAL: "PARTIAL",
  3938. OK: "OK"
  3939. };
  3940. var FragmentTracker = class {
  3941. constructor(hls) {
  3942. this.activePartLists = /* @__PURE__ */ Object.create(null);
  3943. this.endListFragments = /* @__PURE__ */ Object.create(null);
  3944. this.fragments = /* @__PURE__ */ Object.create(null);
  3945. this.timeRanges = /* @__PURE__ */ Object.create(null);
  3946. this.bufferPadding = 0.2;
  3947. this.hls = void 0;
  3948. this.hasGaps = false;
  3949. this.hls = hls;
  3950. this._registerListeners();
  3951. }
  3952. _registerListeners() {
  3953. const {
  3954. hls
  3955. } = this;
  3956. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3957. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  3958. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  3959. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  3960. }
  3961. _unregisterListeners() {
  3962. const {
  3963. hls
  3964. } = this;
  3965. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3966. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  3967. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  3968. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  3969. }
  3970. destroy() {
  3971. this._unregisterListeners();
  3972. this.fragments = this.activePartLists = this.endListFragments = this.timeRanges = null;
  3973. }
  3974. getAppendedFrag(position, levelType) {
  3975. const activeParts = this.activePartLists[levelType];
  3976. if (activeParts) {
  3977. for (let i = activeParts.length; i--; ) {
  3978. const activePart = activeParts[i];
  3979. if (!activePart) {
  3980. break;
  3981. }
  3982. const appendedPTS = activePart.end;
  3983. if (activePart.start <= position && appendedPTS !== null && position <= appendedPTS) {
  3984. return activePart;
  3985. }
  3986. }
  3987. }
  3988. return this.getBufferedFrag(position, levelType);
  3989. }
  3990. getBufferedFrag(position, levelType) {
  3991. return this.getFragAtPos(position, levelType, true);
  3992. }
  3993. getFragAtPos(position, levelType, buffered) {
  3994. const {
  3995. fragments
  3996. } = this;
  3997. const keys = Object.keys(fragments);
  3998. for (let i = keys.length; i--; ) {
  3999. const fragmentEntity = fragments[keys[i]];
  4000. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === levelType && (!buffered || fragmentEntity.buffered)) {
  4001. const frag = fragmentEntity.body;
  4002. if (frag.start <= position && position <= frag.end) {
  4003. return frag;
  4004. }
  4005. }
  4006. }
  4007. return null;
  4008. }
  4009. detectEvictedFragments(elementaryStream, timeRange, playlistType, appendedPart, removeAppending) {
  4010. if (this.timeRanges) {
  4011. this.timeRanges[elementaryStream] = timeRange;
  4012. }
  4013. const appendedPartSn = (appendedPart == null ? void 0 : appendedPart.fragment.sn) || -1;
  4014. Object.keys(this.fragments).forEach((key) => {
  4015. const fragmentEntity = this.fragments[key];
  4016. if (!fragmentEntity) {
  4017. return;
  4018. }
  4019. if (appendedPartSn >= fragmentEntity.body.sn) {
  4020. return;
  4021. }
  4022. if (!fragmentEntity.buffered && (!fragmentEntity.loaded || removeAppending)) {
  4023. if (fragmentEntity.body.type === playlistType) {
  4024. this.removeFragment(fragmentEntity.body);
  4025. }
  4026. return;
  4027. }
  4028. const esData = fragmentEntity.range[elementaryStream];
  4029. if (!esData) {
  4030. return;
  4031. }
  4032. if (esData.time.length === 0) {
  4033. this.removeFragment(fragmentEntity.body);
  4034. return;
  4035. }
  4036. esData.time.some((time) => {
  4037. const isNotBuffered = !this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
  4038. if (isNotBuffered) {
  4039. this.removeFragment(fragmentEntity.body);
  4040. }
  4041. return isNotBuffered;
  4042. });
  4043. });
  4044. }
  4045. detectPartialFragments(data) {
  4046. const timeRanges = this.timeRanges;
  4047. if (!timeRanges || data.frag.sn === "initSegment") {
  4048. return;
  4049. }
  4050. const frag = data.frag;
  4051. const fragKey = getFragmentKey(frag);
  4052. const fragmentEntity = this.fragments[fragKey];
  4053. if (!fragmentEntity || fragmentEntity.buffered && frag.gap) {
  4054. return;
  4055. }
  4056. const isFragHint = !frag.relurl;
  4057. Object.keys(timeRanges).forEach((elementaryStream) => {
  4058. const streamInfo = frag.elementaryStreams[elementaryStream];
  4059. if (!streamInfo) {
  4060. return;
  4061. }
  4062. const timeRange = timeRanges[elementaryStream];
  4063. const partial = isFragHint || streamInfo.partial === true;
  4064. fragmentEntity.range[elementaryStream] = this.getBufferedTimes(frag, data.part, partial, timeRange);
  4065. });
  4066. fragmentEntity.loaded = null;
  4067. if (Object.keys(fragmentEntity.range).length) {
  4068. fragmentEntity.buffered = true;
  4069. const endList = fragmentEntity.body.endList = frag.endList || fragmentEntity.body.endList;
  4070. if (endList) {
  4071. this.endListFragments[fragmentEntity.body.type] = fragmentEntity;
  4072. }
  4073. if (!isPartial(fragmentEntity)) {
  4074. this.removeParts(frag.sn - 1, frag.type);
  4075. }
  4076. } else {
  4077. this.removeFragment(fragmentEntity.body);
  4078. }
  4079. }
  4080. removeParts(snToKeep, levelType) {
  4081. const activeParts = this.activePartLists[levelType];
  4082. if (!activeParts) {
  4083. return;
  4084. }
  4085. this.activePartLists[levelType] = filterParts(activeParts, (part) => part.fragment.sn >= snToKeep);
  4086. }
  4087. fragBuffered(frag, force) {
  4088. const fragKey = getFragmentKey(frag);
  4089. let fragmentEntity = this.fragments[fragKey];
  4090. if (!fragmentEntity && force) {
  4091. fragmentEntity = this.fragments[fragKey] = {
  4092. body: frag,
  4093. appendedPTS: null,
  4094. loaded: null,
  4095. buffered: false,
  4096. range: /* @__PURE__ */ Object.create(null)
  4097. };
  4098. if (frag.gap) {
  4099. this.hasGaps = true;
  4100. }
  4101. }
  4102. if (fragmentEntity) {
  4103. fragmentEntity.loaded = null;
  4104. fragmentEntity.buffered = true;
  4105. }
  4106. }
  4107. getBufferedTimes(fragment, part, partial, timeRange) {
  4108. const buffered = {
  4109. time: [],
  4110. partial
  4111. };
  4112. const startPTS = fragment.start;
  4113. const endPTS = fragment.end;
  4114. const minEndPTS = fragment.minEndPTS || endPTS;
  4115. const maxStartPTS = fragment.maxStartPTS || startPTS;
  4116. for (let i = 0; i < timeRange.length; i++) {
  4117. const startTime = timeRange.start(i) - this.bufferPadding;
  4118. const endTime = timeRange.end(i) + this.bufferPadding;
  4119. if (maxStartPTS >= startTime && minEndPTS <= endTime) {
  4120. buffered.time.push({
  4121. startPTS: Math.max(startPTS, timeRange.start(i)),
  4122. endPTS: Math.min(endPTS, timeRange.end(i))
  4123. });
  4124. break;
  4125. } else if (startPTS < endTime && endPTS > startTime) {
  4126. const start = Math.max(startPTS, timeRange.start(i));
  4127. const end = Math.min(endPTS, timeRange.end(i));
  4128. if (end > start) {
  4129. buffered.partial = true;
  4130. buffered.time.push({
  4131. startPTS: start,
  4132. endPTS: end
  4133. });
  4134. }
  4135. } else if (endPTS <= startTime) {
  4136. break;
  4137. }
  4138. }
  4139. return buffered;
  4140. }
  4141. getPartialFragment(time) {
  4142. let bestFragment = null;
  4143. let timePadding;
  4144. let startTime;
  4145. let endTime;
  4146. let bestOverlap = 0;
  4147. const {
  4148. bufferPadding,
  4149. fragments
  4150. } = this;
  4151. Object.keys(fragments).forEach((key) => {
  4152. const fragmentEntity = fragments[key];
  4153. if (!fragmentEntity) {
  4154. return;
  4155. }
  4156. if (isPartial(fragmentEntity)) {
  4157. startTime = fragmentEntity.body.start - bufferPadding;
  4158. endTime = fragmentEntity.body.end + bufferPadding;
  4159. if (time >= startTime && time <= endTime) {
  4160. timePadding = Math.min(time - startTime, endTime - time);
  4161. if (bestOverlap <= timePadding) {
  4162. bestFragment = fragmentEntity.body;
  4163. bestOverlap = timePadding;
  4164. }
  4165. }
  4166. }
  4167. });
  4168. return bestFragment;
  4169. }
  4170. isEndListAppended(type) {
  4171. const lastFragmentEntity = this.endListFragments[type];
  4172. return lastFragmentEntity !== void 0 && (lastFragmentEntity.buffered || isPartial(lastFragmentEntity));
  4173. }
  4174. getState(fragment) {
  4175. const fragKey = getFragmentKey(fragment);
  4176. const fragmentEntity = this.fragments[fragKey];
  4177. if (fragmentEntity) {
  4178. if (!fragmentEntity.buffered) {
  4179. return FragmentState.APPENDING;
  4180. } else if (isPartial(fragmentEntity)) {
  4181. return FragmentState.PARTIAL;
  4182. } else {
  4183. return FragmentState.OK;
  4184. }
  4185. }
  4186. return FragmentState.NOT_LOADED;
  4187. }
  4188. isTimeBuffered(startPTS, endPTS, timeRange) {
  4189. let startTime;
  4190. let endTime;
  4191. for (let i = 0; i < timeRange.length; i++) {
  4192. startTime = timeRange.start(i) - this.bufferPadding;
  4193. endTime = timeRange.end(i) + this.bufferPadding;
  4194. if (startPTS >= startTime && endPTS <= endTime) {
  4195. return true;
  4196. }
  4197. if (endPTS <= startTime) {
  4198. return false;
  4199. }
  4200. }
  4201. return false;
  4202. }
  4203. onManifestLoading() {
  4204. this.removeAllFragments();
  4205. }
  4206. onFragLoaded(event, data) {
  4207. if (data.frag.sn === "initSegment" || data.frag.bitrateTest) {
  4208. return;
  4209. }
  4210. const frag = data.frag;
  4211. const loaded = data.part ? null : data;
  4212. const fragKey = getFragmentKey(frag);
  4213. this.fragments[fragKey] = {
  4214. body: frag,
  4215. appendedPTS: null,
  4216. loaded,
  4217. buffered: false,
  4218. range: /* @__PURE__ */ Object.create(null)
  4219. };
  4220. }
  4221. onBufferAppended(event, data) {
  4222. const {
  4223. frag,
  4224. part,
  4225. timeRanges,
  4226. type
  4227. } = data;
  4228. if (frag.sn === "initSegment") {
  4229. return;
  4230. }
  4231. const playlistType = frag.type;
  4232. if (part) {
  4233. let activeParts = this.activePartLists[playlistType];
  4234. if (!activeParts) {
  4235. this.activePartLists[playlistType] = activeParts = [];
  4236. }
  4237. activeParts.push(part);
  4238. }
  4239. this.timeRanges = timeRanges;
  4240. const timeRange = timeRanges[type];
  4241. this.detectEvictedFragments(type, timeRange, playlistType, part);
  4242. }
  4243. onFragBuffered(event, data) {
  4244. this.detectPartialFragments(data);
  4245. }
  4246. hasFragment(fragment) {
  4247. const fragKey = getFragmentKey(fragment);
  4248. return !!this.fragments[fragKey];
  4249. }
  4250. hasFragments(type) {
  4251. const {
  4252. fragments
  4253. } = this;
  4254. const keys = Object.keys(fragments);
  4255. if (!type) {
  4256. return keys.length > 0;
  4257. }
  4258. for (let i = keys.length; i--; ) {
  4259. const fragmentEntity = fragments[keys[i]];
  4260. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === type) {
  4261. return true;
  4262. }
  4263. }
  4264. return false;
  4265. }
  4266. hasParts(type) {
  4267. var _this$activePartLists;
  4268. return !!((_this$activePartLists = this.activePartLists[type]) != null && _this$activePartLists.length);
  4269. }
  4270. removeFragmentsInRange(start, end, playlistType, withGapOnly, unbufferedOnly) {
  4271. if (withGapOnly && !this.hasGaps) {
  4272. return;
  4273. }
  4274. Object.keys(this.fragments).forEach((key) => {
  4275. const fragmentEntity = this.fragments[key];
  4276. if (!fragmentEntity) {
  4277. return;
  4278. }
  4279. const frag = fragmentEntity.body;
  4280. if (frag.type !== playlistType || withGapOnly && !frag.gap) {
  4281. return;
  4282. }
  4283. if (frag.start < end && frag.end > start && (fragmentEntity.buffered || unbufferedOnly)) {
  4284. this.removeFragment(frag);
  4285. }
  4286. });
  4287. }
  4288. removeFragment(fragment) {
  4289. const fragKey = getFragmentKey(fragment);
  4290. fragment.clearElementaryStreamInfo();
  4291. const activeParts = this.activePartLists[fragment.type];
  4292. if (activeParts) {
  4293. const snToRemove = fragment.sn;
  4294. this.activePartLists[fragment.type] = filterParts(activeParts, (part) => part.fragment.sn !== snToRemove);
  4295. }
  4296. delete this.fragments[fragKey];
  4297. if (fragment.endList) {
  4298. delete this.endListFragments[fragment.type];
  4299. }
  4300. }
  4301. removeAllFragments() {
  4302. var _this$hls, _this$hls$latestLevel;
  4303. this.fragments = /* @__PURE__ */ Object.create(null);
  4304. this.endListFragments = /* @__PURE__ */ Object.create(null);
  4305. this.activePartLists = /* @__PURE__ */ Object.create(null);
  4306. this.hasGaps = false;
  4307. const partlist = (_this$hls = this.hls) == null ? void 0 : (_this$hls$latestLevel = _this$hls.latestLevelDetails) == null ? void 0 : _this$hls$latestLevel.partList;
  4308. if (partlist) {
  4309. partlist.forEach((part) => part.clearElementaryStreamInfo());
  4310. }
  4311. }
  4312. };
  4313. function isPartial(fragmentEntity) {
  4314. var _fragmentEntity$range, _fragmentEntity$range2, _fragmentEntity$range3;
  4315. 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));
  4316. }
  4317. function getFragmentKey(fragment) {
  4318. return `${fragment.type}_${fragment.level}_${fragment.sn}`;
  4319. }
  4320. function filterParts(partList, predicate) {
  4321. return partList.filter((part) => {
  4322. const keep = predicate(part);
  4323. if (!keep) {
  4324. part.clearElementaryStreamInfo();
  4325. }
  4326. return keep;
  4327. });
  4328. }
  4329. var DecrypterAesMode = {
  4330. cbc: 0,
  4331. ctr: 1
  4332. };
  4333. var AESCrypto = class {
  4334. constructor(subtle, iv, aesMode) {
  4335. this.subtle = void 0;
  4336. this.aesIV = void 0;
  4337. this.aesMode = void 0;
  4338. this.subtle = subtle;
  4339. this.aesIV = iv;
  4340. this.aesMode = aesMode;
  4341. }
  4342. decrypt(data, key) {
  4343. switch (this.aesMode) {
  4344. case DecrypterAesMode.cbc:
  4345. return this.subtle.decrypt({
  4346. name: "AES-CBC",
  4347. iv: this.aesIV
  4348. }, key, data);
  4349. case DecrypterAesMode.ctr:
  4350. return this.subtle.decrypt({
  4351. name: "AES-CTR",
  4352. counter: this.aesIV,
  4353. length: 64
  4354. }, key, data);
  4355. default:
  4356. throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`);
  4357. }
  4358. }
  4359. };
  4360. function removePadding(array) {
  4361. const outputBytes = array.byteLength;
  4362. const paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
  4363. if (paddingBytes) {
  4364. return array.slice(0, outputBytes - paddingBytes);
  4365. }
  4366. return array;
  4367. }
  4368. var AESDecryptor = class {
  4369. constructor() {
  4370. this.rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54];
  4371. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  4372. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  4373. this.sBox = new Uint32Array(256);
  4374. this.invSBox = new Uint32Array(256);
  4375. this.key = new Uint32Array(0);
  4376. this.ksRows = 0;
  4377. this.keySize = 0;
  4378. this.keySchedule = void 0;
  4379. this.invKeySchedule = void 0;
  4380. this.initTable();
  4381. }
  4382. uint8ArrayToUint32Array_(arrayBuffer) {
  4383. const view2 = new DataView(arrayBuffer);
  4384. const newArray = new Uint32Array(4);
  4385. for (let i = 0; i < 4; i++) {
  4386. newArray[i] = view2.getUint32(i * 4);
  4387. }
  4388. return newArray;
  4389. }
  4390. initTable() {
  4391. const sBox = this.sBox;
  4392. const invSBox = this.invSBox;
  4393. const subMix = this.subMix;
  4394. const subMix0 = subMix[0];
  4395. const subMix1 = subMix[1];
  4396. const subMix2 = subMix[2];
  4397. const subMix3 = subMix[3];
  4398. const invSubMix = this.invSubMix;
  4399. const invSubMix0 = invSubMix[0];
  4400. const invSubMix1 = invSubMix[1];
  4401. const invSubMix2 = invSubMix[2];
  4402. const invSubMix3 = invSubMix[3];
  4403. const d = new Uint32Array(256);
  4404. let x = 0;
  4405. let xi = 0;
  4406. let i = 0;
  4407. for (i = 0; i < 256; i++) {
  4408. if (i < 128) {
  4409. d[i] = i << 1;
  4410. } else {
  4411. d[i] = i << 1 ^ 283;
  4412. }
  4413. }
  4414. for (i = 0; i < 256; i++) {
  4415. let sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  4416. sx = sx >>> 8 ^ sx & 255 ^ 99;
  4417. sBox[x] = sx;
  4418. invSBox[sx] = x;
  4419. const x2 = d[x];
  4420. const x4 = d[x2];
  4421. const x8 = d[x4];
  4422. let t = d[sx] * 257 ^ sx * 16843008;
  4423. subMix0[x] = t << 24 | t >>> 8;
  4424. subMix1[x] = t << 16 | t >>> 16;
  4425. subMix2[x] = t << 8 | t >>> 24;
  4426. subMix3[x] = t;
  4427. t = x8 * 16843009 ^ x4 * 65537 ^ x2 * 257 ^ x * 16843008;
  4428. invSubMix0[sx] = t << 24 | t >>> 8;
  4429. invSubMix1[sx] = t << 16 | t >>> 16;
  4430. invSubMix2[sx] = t << 8 | t >>> 24;
  4431. invSubMix3[sx] = t;
  4432. if (!x) {
  4433. x = xi = 1;
  4434. } else {
  4435. x = x2 ^ d[d[d[x8 ^ x2]]];
  4436. xi ^= d[d[xi]];
  4437. }
  4438. }
  4439. }
  4440. expandKey(keyBuffer) {
  4441. const key = this.uint8ArrayToUint32Array_(keyBuffer);
  4442. let sameKey = true;
  4443. let offset = 0;
  4444. while (offset < key.length && sameKey) {
  4445. sameKey = key[offset] === this.key[offset];
  4446. offset++;
  4447. }
  4448. if (sameKey) {
  4449. return;
  4450. }
  4451. this.key = key;
  4452. const keySize = this.keySize = key.length;
  4453. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  4454. throw new Error("Invalid aes key size=" + keySize);
  4455. }
  4456. const ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  4457. let ksRow;
  4458. let invKsRow;
  4459. const keySchedule = this.keySchedule = new Uint32Array(ksRows);
  4460. const invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  4461. const sbox = this.sBox;
  4462. const rcon = this.rcon;
  4463. const invSubMix = this.invSubMix;
  4464. const invSubMix0 = invSubMix[0];
  4465. const invSubMix1 = invSubMix[1];
  4466. const invSubMix2 = invSubMix[2];
  4467. const invSubMix3 = invSubMix[3];
  4468. let prev;
  4469. let t;
  4470. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  4471. if (ksRow < keySize) {
  4472. prev = keySchedule[ksRow] = key[ksRow];
  4473. continue;
  4474. }
  4475. t = prev;
  4476. if (ksRow % keySize === 0) {
  4477. t = t << 8 | t >>> 24;
  4478. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 255] << 16 | sbox[t >>> 8 & 255] << 8 | sbox[t & 255];
  4479. t ^= rcon[ksRow / keySize | 0] << 24;
  4480. } else if (keySize > 6 && ksRow % keySize === 4) {
  4481. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 255] << 16 | sbox[t >>> 8 & 255] << 8 | sbox[t & 255];
  4482. }
  4483. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  4484. }
  4485. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  4486. ksRow = ksRows - invKsRow;
  4487. if (invKsRow & 3) {
  4488. t = keySchedule[ksRow];
  4489. } else {
  4490. t = keySchedule[ksRow - 4];
  4491. }
  4492. if (invKsRow < 4 || ksRow <= 4) {
  4493. invKeySchedule[invKsRow] = t;
  4494. } else {
  4495. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 255]] ^ invSubMix2[sbox[t >>> 8 & 255]] ^ invSubMix3[sbox[t & 255]];
  4496. }
  4497. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  4498. }
  4499. }
  4500. networkToHostOrderSwap(word) {
  4501. return word << 24 | (word & 65280) << 8 | (word & 16711680) >> 8 | word >>> 24;
  4502. }
  4503. decrypt(inputArrayBuffer, offset, aesIV) {
  4504. const nRounds = this.keySize + 6;
  4505. const invKeySchedule = this.invKeySchedule;
  4506. const invSBOX = this.invSBox;
  4507. const invSubMix = this.invSubMix;
  4508. const invSubMix0 = invSubMix[0];
  4509. const invSubMix1 = invSubMix[1];
  4510. const invSubMix2 = invSubMix[2];
  4511. const invSubMix3 = invSubMix[3];
  4512. const initVector = this.uint8ArrayToUint32Array_(aesIV);
  4513. let initVector0 = initVector[0];
  4514. let initVector1 = initVector[1];
  4515. let initVector2 = initVector[2];
  4516. let initVector3 = initVector[3];
  4517. const inputInt32 = new Int32Array(inputArrayBuffer);
  4518. const outputInt32 = new Int32Array(inputInt32.length);
  4519. let t0, t1, t2, t3;
  4520. let s0, s1, s2, s3;
  4521. let inputWords0, inputWords1, inputWords2, inputWords3;
  4522. let ksRow, i;
  4523. const swapWord = this.networkToHostOrderSwap;
  4524. while (offset < inputInt32.length) {
  4525. inputWords0 = swapWord(inputInt32[offset]);
  4526. inputWords1 = swapWord(inputInt32[offset + 1]);
  4527. inputWords2 = swapWord(inputInt32[offset + 2]);
  4528. inputWords3 = swapWord(inputInt32[offset + 3]);
  4529. s0 = inputWords0 ^ invKeySchedule[0];
  4530. s1 = inputWords3 ^ invKeySchedule[1];
  4531. s2 = inputWords2 ^ invKeySchedule[2];
  4532. s3 = inputWords1 ^ invKeySchedule[3];
  4533. ksRow = 4;
  4534. for (i = 1; i < nRounds; i++) {
  4535. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 255] ^ invSubMix2[s2 >> 8 & 255] ^ invSubMix3[s3 & 255] ^ invKeySchedule[ksRow];
  4536. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 255] ^ invSubMix2[s3 >> 8 & 255] ^ invSubMix3[s0 & 255] ^ invKeySchedule[ksRow + 1];
  4537. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 255] ^ invSubMix2[s0 >> 8 & 255] ^ invSubMix3[s1 & 255] ^ invKeySchedule[ksRow + 2];
  4538. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 255] ^ invSubMix2[s1 >> 8 & 255] ^ invSubMix3[s2 & 255] ^ invKeySchedule[ksRow + 3];
  4539. s0 = t0;
  4540. s1 = t1;
  4541. s2 = t2;
  4542. s3 = t3;
  4543. ksRow = ksRow + 4;
  4544. }
  4545. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 255] << 16 ^ invSBOX[s2 >> 8 & 255] << 8 ^ invSBOX[s3 & 255] ^ invKeySchedule[ksRow];
  4546. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 255] << 16 ^ invSBOX[s3 >> 8 & 255] << 8 ^ invSBOX[s0 & 255] ^ invKeySchedule[ksRow + 1];
  4547. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 255] << 16 ^ invSBOX[s0 >> 8 & 255] << 8 ^ invSBOX[s1 & 255] ^ invKeySchedule[ksRow + 2];
  4548. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 255] << 16 ^ invSBOX[s1 >> 8 & 255] << 8 ^ invSBOX[s2 & 255] ^ invKeySchedule[ksRow + 3];
  4549. outputInt32[offset] = swapWord(t0 ^ initVector0);
  4550. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  4551. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  4552. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  4553. initVector0 = inputWords0;
  4554. initVector1 = inputWords1;
  4555. initVector2 = inputWords2;
  4556. initVector3 = inputWords3;
  4557. offset = offset + 4;
  4558. }
  4559. return outputInt32.buffer;
  4560. }
  4561. };
  4562. var FastAESKey = class {
  4563. constructor(subtle, key, aesMode) {
  4564. this.subtle = void 0;
  4565. this.key = void 0;
  4566. this.aesMode = void 0;
  4567. this.subtle = subtle;
  4568. this.key = key;
  4569. this.aesMode = aesMode;
  4570. }
  4571. expandKey() {
  4572. const subtleAlgoName = getSubtleAlgoName(this.aesMode);
  4573. return this.subtle.importKey("raw", this.key, {
  4574. name: subtleAlgoName
  4575. }, false, ["encrypt", "decrypt"]);
  4576. }
  4577. };
  4578. function getSubtleAlgoName(aesMode) {
  4579. switch (aesMode) {
  4580. case DecrypterAesMode.cbc:
  4581. return "AES-CBC";
  4582. case DecrypterAesMode.ctr:
  4583. return "AES-CTR";
  4584. default:
  4585. throw new Error(`[FastAESKey] invalid aes mode ${aesMode}`);
  4586. }
  4587. }
  4588. var CHUNK_SIZE = 16;
  4589. var Decrypter = class {
  4590. constructor(config, {
  4591. removePKCS7Padding = true
  4592. } = {}) {
  4593. this.logEnabled = true;
  4594. this.removePKCS7Padding = void 0;
  4595. this.subtle = null;
  4596. this.softwareDecrypter = null;
  4597. this.key = null;
  4598. this.fastAesKey = null;
  4599. this.remainderData = null;
  4600. this.currentIV = null;
  4601. this.currentResult = null;
  4602. this.useSoftware = void 0;
  4603. this.enableSoftwareAES = void 0;
  4604. this.enableSoftwareAES = config.enableSoftwareAES;
  4605. this.removePKCS7Padding = removePKCS7Padding;
  4606. if (removePKCS7Padding) {
  4607. try {
  4608. const browserCrypto = self.crypto;
  4609. if (browserCrypto) {
  4610. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  4611. }
  4612. } catch (e) {
  4613. }
  4614. }
  4615. this.useSoftware = !this.subtle;
  4616. }
  4617. destroy() {
  4618. this.subtle = null;
  4619. this.softwareDecrypter = null;
  4620. this.key = null;
  4621. this.fastAesKey = null;
  4622. this.remainderData = null;
  4623. this.currentIV = null;
  4624. this.currentResult = null;
  4625. }
  4626. isSync() {
  4627. return this.useSoftware;
  4628. }
  4629. flush() {
  4630. const {
  4631. currentResult,
  4632. remainderData
  4633. } = this;
  4634. if (!currentResult || remainderData) {
  4635. this.reset();
  4636. return null;
  4637. }
  4638. const data = new Uint8Array(currentResult);
  4639. this.reset();
  4640. if (this.removePKCS7Padding) {
  4641. return removePadding(data);
  4642. }
  4643. return data;
  4644. }
  4645. reset() {
  4646. this.currentResult = null;
  4647. this.currentIV = null;
  4648. this.remainderData = null;
  4649. if (this.softwareDecrypter) {
  4650. this.softwareDecrypter = null;
  4651. }
  4652. }
  4653. decrypt(data, key, iv, aesMode) {
  4654. if (this.useSoftware) {
  4655. return new Promise((resolve, reject) => {
  4656. const dataView = ArrayBuffer.isView(data) ? data : new Uint8Array(data);
  4657. this.softwareDecrypt(dataView, key, iv, aesMode);
  4658. const decryptResult = this.flush();
  4659. if (decryptResult) {
  4660. resolve(decryptResult.buffer);
  4661. } else {
  4662. reject(new Error("[softwareDecrypt] Failed to decrypt data"));
  4663. }
  4664. });
  4665. }
  4666. return this.webCryptoDecrypt(new Uint8Array(data), key, iv, aesMode);
  4667. }
  4668. softwareDecrypt(data, key, iv, aesMode) {
  4669. const {
  4670. currentIV,
  4671. currentResult,
  4672. remainderData
  4673. } = this;
  4674. if (aesMode !== DecrypterAesMode.cbc || key.byteLength !== 16) {
  4675. logger.warn("SoftwareDecrypt: can only handle AES-128-CBC");
  4676. return null;
  4677. }
  4678. this.logOnce("JS AES decrypt");
  4679. if (remainderData) {
  4680. data = appendUint8Array(remainderData, data);
  4681. this.remainderData = null;
  4682. }
  4683. const currentChunk = this.getValidChunk(data);
  4684. if (!currentChunk.length) {
  4685. return null;
  4686. }
  4687. if (currentIV) {
  4688. iv = currentIV;
  4689. }
  4690. let softwareDecrypter = this.softwareDecrypter;
  4691. if (!softwareDecrypter) {
  4692. softwareDecrypter = this.softwareDecrypter = new AESDecryptor();
  4693. }
  4694. softwareDecrypter.expandKey(key);
  4695. const result = currentResult;
  4696. this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
  4697. this.currentIV = currentChunk.slice(-16).buffer;
  4698. if (!result) {
  4699. return null;
  4700. }
  4701. return result;
  4702. }
  4703. webCryptoDecrypt(data, key, iv, aesMode) {
  4704. if (this.key !== key || !this.fastAesKey) {
  4705. if (!this.subtle) {
  4706. return Promise.resolve(this.onWebCryptoError(data, key, iv, aesMode));
  4707. }
  4708. this.key = key;
  4709. this.fastAesKey = new FastAESKey(this.subtle, key, aesMode);
  4710. }
  4711. return this.fastAesKey.expandKey().then((aesKey) => {
  4712. if (!this.subtle) {
  4713. return Promise.reject(new Error("web crypto not initialized"));
  4714. }
  4715. this.logOnce("WebCrypto AES decrypt");
  4716. const crypto2 = new AESCrypto(this.subtle, new Uint8Array(iv), aesMode);
  4717. return crypto2.decrypt(data.buffer, aesKey);
  4718. }).catch((err) => {
  4719. logger.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${err.name}: ${err.message}`);
  4720. return this.onWebCryptoError(data, key, iv, aesMode);
  4721. });
  4722. }
  4723. onWebCryptoError(data, key, iv, aesMode) {
  4724. const enableSoftwareAES = this.enableSoftwareAES;
  4725. if (enableSoftwareAES) {
  4726. this.useSoftware = true;
  4727. this.logEnabled = true;
  4728. this.softwareDecrypt(data, key, iv, aesMode);
  4729. const decryptResult = this.flush();
  4730. if (decryptResult) {
  4731. return decryptResult.buffer;
  4732. }
  4733. }
  4734. throw new Error("WebCrypto" + (enableSoftwareAES ? " and softwareDecrypt" : "") + ": failed to decrypt data");
  4735. }
  4736. getValidChunk(data) {
  4737. let currentChunk = data;
  4738. const splitPoint = data.length - data.length % CHUNK_SIZE;
  4739. if (splitPoint !== data.length) {
  4740. currentChunk = data.slice(0, splitPoint);
  4741. this.remainderData = data.slice(splitPoint);
  4742. }
  4743. return currentChunk;
  4744. }
  4745. logOnce(msg) {
  4746. if (!this.logEnabled) {
  4747. return;
  4748. }
  4749. logger.log(`[decrypter]: ${msg}`);
  4750. this.logEnabled = false;
  4751. }
  4752. };
  4753. var MIN_CHUNK_SIZE = Math.pow(2, 17);
  4754. var FragmentLoader = class {
  4755. constructor(config) {
  4756. this.config = void 0;
  4757. this.loader = null;
  4758. this.partLoadTimeout = -1;
  4759. this.config = config;
  4760. }
  4761. destroy() {
  4762. if (this.loader) {
  4763. this.loader.destroy();
  4764. this.loader = null;
  4765. }
  4766. }
  4767. abort() {
  4768. if (this.loader) {
  4769. this.loader.abort();
  4770. }
  4771. }
  4772. load(frag, onProgress) {
  4773. const url = frag.url;
  4774. if (!url) {
  4775. return Promise.reject(new LoadError({
  4776. type: ErrorTypes.NETWORK_ERROR,
  4777. details: ErrorDetails.FRAG_LOAD_ERROR,
  4778. fatal: false,
  4779. frag,
  4780. error: new Error(`Fragment does not have a ${url ? "part list" : "url"}`),
  4781. networkDetails: null
  4782. }));
  4783. }
  4784. this.abort();
  4785. const config = this.config;
  4786. const FragmentILoader = config.fLoader;
  4787. const DefaultILoader = config.loader;
  4788. return new Promise((resolve, reject) => {
  4789. if (this.loader) {
  4790. this.loader.destroy();
  4791. }
  4792. if (frag.gap) {
  4793. if (frag.tagList.some((tags) => tags[0] === "GAP")) {
  4794. reject(createGapLoadError(frag));
  4795. return;
  4796. } else {
  4797. frag.gap = false;
  4798. }
  4799. }
  4800. const loader = this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  4801. const loaderContext = createLoaderContext(frag);
  4802. frag.loader = loader;
  4803. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  4804. const loaderConfig = {
  4805. loadPolicy,
  4806. timeout: loadPolicy.maxLoadTimeMs,
  4807. maxRetry: 0,
  4808. retryDelay: 0,
  4809. maxRetryDelay: 0,
  4810. highWaterMark: frag.sn === "initSegment" ? Infinity : MIN_CHUNK_SIZE
  4811. };
  4812. frag.stats = loader.stats;
  4813. const callbacks = {
  4814. onSuccess: (response, stats, context, networkDetails) => {
  4815. this.resetLoader(frag, loader);
  4816. let payload = response.data;
  4817. if (context.resetIV && frag.decryptdata) {
  4818. frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));
  4819. payload = payload.slice(16);
  4820. }
  4821. resolve({
  4822. frag,
  4823. part: null,
  4824. payload,
  4825. networkDetails
  4826. });
  4827. },
  4828. onError: (response, context, networkDetails, stats) => {
  4829. this.resetLoader(frag, loader);
  4830. reject(new LoadError({
  4831. type: ErrorTypes.NETWORK_ERROR,
  4832. details: ErrorDetails.FRAG_LOAD_ERROR,
  4833. fatal: false,
  4834. frag,
  4835. response: _objectSpread2({
  4836. url,
  4837. data: void 0
  4838. }, response),
  4839. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  4840. networkDetails,
  4841. stats
  4842. }));
  4843. },
  4844. onAbort: (stats, context, networkDetails) => {
  4845. this.resetLoader(frag, loader);
  4846. reject(new LoadError({
  4847. type: ErrorTypes.NETWORK_ERROR,
  4848. details: ErrorDetails.INTERNAL_ABORTED,
  4849. fatal: false,
  4850. frag,
  4851. error: new Error("Aborted"),
  4852. networkDetails,
  4853. stats
  4854. }));
  4855. },
  4856. onTimeout: (stats, context, networkDetails) => {
  4857. this.resetLoader(frag, loader);
  4858. reject(new LoadError({
  4859. type: ErrorTypes.NETWORK_ERROR,
  4860. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  4861. fatal: false,
  4862. frag,
  4863. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  4864. networkDetails,
  4865. stats
  4866. }));
  4867. }
  4868. };
  4869. if (onProgress) {
  4870. callbacks.onProgress = (stats, context, data, networkDetails) => onProgress({
  4871. frag,
  4872. part: null,
  4873. payload: data,
  4874. networkDetails
  4875. });
  4876. }
  4877. loader.load(loaderContext, loaderConfig, callbacks);
  4878. });
  4879. }
  4880. loadPart(frag, part, onProgress) {
  4881. this.abort();
  4882. const config = this.config;
  4883. const FragmentILoader = config.fLoader;
  4884. const DefaultILoader = config.loader;
  4885. return new Promise((resolve, reject) => {
  4886. if (this.loader) {
  4887. this.loader.destroy();
  4888. }
  4889. if (frag.gap || part.gap) {
  4890. reject(createGapLoadError(frag, part));
  4891. return;
  4892. }
  4893. const loader = this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  4894. const loaderContext = createLoaderContext(frag, part);
  4895. frag.loader = loader;
  4896. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  4897. const loaderConfig = {
  4898. loadPolicy,
  4899. timeout: loadPolicy.maxLoadTimeMs,
  4900. maxRetry: 0,
  4901. retryDelay: 0,
  4902. maxRetryDelay: 0,
  4903. highWaterMark: MIN_CHUNK_SIZE
  4904. };
  4905. part.stats = loader.stats;
  4906. loader.load(loaderContext, loaderConfig, {
  4907. onSuccess: (response, stats, context, networkDetails) => {
  4908. this.resetLoader(frag, loader);
  4909. this.updateStatsFromPart(frag, part);
  4910. const partLoadedData = {
  4911. frag,
  4912. part,
  4913. payload: response.data,
  4914. networkDetails
  4915. };
  4916. onProgress(partLoadedData);
  4917. resolve(partLoadedData);
  4918. },
  4919. onError: (response, context, networkDetails, stats) => {
  4920. this.resetLoader(frag, loader);
  4921. reject(new LoadError({
  4922. type: ErrorTypes.NETWORK_ERROR,
  4923. details: ErrorDetails.FRAG_LOAD_ERROR,
  4924. fatal: false,
  4925. frag,
  4926. part,
  4927. response: _objectSpread2({
  4928. url: loaderContext.url,
  4929. data: void 0
  4930. }, response),
  4931. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  4932. networkDetails,
  4933. stats
  4934. }));
  4935. },
  4936. onAbort: (stats, context, networkDetails) => {
  4937. frag.stats.aborted = part.stats.aborted;
  4938. this.resetLoader(frag, loader);
  4939. reject(new LoadError({
  4940. type: ErrorTypes.NETWORK_ERROR,
  4941. details: ErrorDetails.INTERNAL_ABORTED,
  4942. fatal: false,
  4943. frag,
  4944. part,
  4945. error: new Error("Aborted"),
  4946. networkDetails,
  4947. stats
  4948. }));
  4949. },
  4950. onTimeout: (stats, context, networkDetails) => {
  4951. this.resetLoader(frag, loader);
  4952. reject(new LoadError({
  4953. type: ErrorTypes.NETWORK_ERROR,
  4954. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  4955. fatal: false,
  4956. frag,
  4957. part,
  4958. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  4959. networkDetails,
  4960. stats
  4961. }));
  4962. }
  4963. });
  4964. });
  4965. }
  4966. updateStatsFromPart(frag, part) {
  4967. const fragStats = frag.stats;
  4968. const partStats = part.stats;
  4969. const partTotal = partStats.total;
  4970. fragStats.loaded += partStats.loaded;
  4971. if (partTotal) {
  4972. const estTotalParts = Math.round(frag.duration / part.duration);
  4973. const estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
  4974. const estRemainingParts = estTotalParts - estLoadedParts;
  4975. const estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
  4976. fragStats.total = fragStats.loaded + estRemainingBytes;
  4977. } else {
  4978. fragStats.total = Math.max(fragStats.loaded, fragStats.total);
  4979. }
  4980. const fragLoading = fragStats.loading;
  4981. const partLoading = partStats.loading;
  4982. if (fragLoading.start) {
  4983. fragLoading.first += partLoading.first - partLoading.start;
  4984. } else {
  4985. fragLoading.start = partLoading.start;
  4986. fragLoading.first = partLoading.first;
  4987. }
  4988. fragLoading.end = partLoading.end;
  4989. }
  4990. resetLoader(frag, loader) {
  4991. frag.loader = null;
  4992. if (this.loader === loader) {
  4993. self.clearTimeout(this.partLoadTimeout);
  4994. this.loader = null;
  4995. }
  4996. loader.destroy();
  4997. }
  4998. };
  4999. function createLoaderContext(frag, part = null) {
  5000. const segment = part || frag;
  5001. const loaderContext = {
  5002. frag,
  5003. part,
  5004. responseType: "arraybuffer",
  5005. url: segment.url,
  5006. headers: {},
  5007. rangeStart: 0,
  5008. rangeEnd: 0
  5009. };
  5010. const start = segment.byteRangeStartOffset;
  5011. const end = segment.byteRangeEndOffset;
  5012. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  5013. var _frag$decryptdata;
  5014. let byteRangeStart = start;
  5015. let byteRangeEnd = end;
  5016. if (frag.sn === "initSegment" && isMethodFullSegmentAesCbc((_frag$decryptdata = frag.decryptdata) == null ? void 0 : _frag$decryptdata.method)) {
  5017. const fragmentLen = end - start;
  5018. if (fragmentLen % 16) {
  5019. byteRangeEnd = end + (16 - fragmentLen % 16);
  5020. }
  5021. if (start !== 0) {
  5022. loaderContext.resetIV = true;
  5023. byteRangeStart = start - 16;
  5024. }
  5025. }
  5026. loaderContext.rangeStart = byteRangeStart;
  5027. loaderContext.rangeEnd = byteRangeEnd;
  5028. }
  5029. return loaderContext;
  5030. }
  5031. function createGapLoadError(frag, part) {
  5032. const error = new Error(`GAP ${frag.gap ? "tag" : "attribute"} found`);
  5033. const errorData = {
  5034. type: ErrorTypes.MEDIA_ERROR,
  5035. details: ErrorDetails.FRAG_GAP,
  5036. fatal: false,
  5037. frag,
  5038. error,
  5039. networkDetails: null
  5040. };
  5041. if (part) {
  5042. errorData.part = part;
  5043. }
  5044. (part ? part : frag).stats.aborted = true;
  5045. return new LoadError(errorData);
  5046. }
  5047. function isMethodFullSegmentAesCbc(method) {
  5048. return method === "AES-128" || method === "AES-256";
  5049. }
  5050. var LoadError = class extends Error {
  5051. constructor(data) {
  5052. super(data.error.message);
  5053. this.data = void 0;
  5054. this.data = data;
  5055. }
  5056. };
  5057. var TaskLoop = class extends Logger {
  5058. constructor(label, logger2) {
  5059. super(label, logger2);
  5060. this._boundTick = void 0;
  5061. this._tickTimer = null;
  5062. this._tickInterval = null;
  5063. this._tickCallCount = 0;
  5064. this._boundTick = this.tick.bind(this);
  5065. }
  5066. destroy() {
  5067. this.onHandlerDestroying();
  5068. this.onHandlerDestroyed();
  5069. }
  5070. onHandlerDestroying() {
  5071. this.clearNextTick();
  5072. this.clearInterval();
  5073. }
  5074. onHandlerDestroyed() {
  5075. }
  5076. hasInterval() {
  5077. return !!this._tickInterval;
  5078. }
  5079. hasNextTick() {
  5080. return !!this._tickTimer;
  5081. }
  5082. setInterval(millis) {
  5083. if (!this._tickInterval) {
  5084. this._tickCallCount = 0;
  5085. this._tickInterval = self.setInterval(this._boundTick, millis);
  5086. return true;
  5087. }
  5088. return false;
  5089. }
  5090. clearInterval() {
  5091. if (this._tickInterval) {
  5092. self.clearInterval(this._tickInterval);
  5093. this._tickInterval = null;
  5094. return true;
  5095. }
  5096. return false;
  5097. }
  5098. clearNextTick() {
  5099. if (this._tickTimer) {
  5100. self.clearTimeout(this._tickTimer);
  5101. this._tickTimer = null;
  5102. return true;
  5103. }
  5104. return false;
  5105. }
  5106. tick() {
  5107. this._tickCallCount++;
  5108. if (this._tickCallCount === 1) {
  5109. this.doTick();
  5110. if (this._tickCallCount > 1) {
  5111. this.tickImmediate();
  5112. }
  5113. this._tickCallCount = 0;
  5114. }
  5115. }
  5116. tickImmediate() {
  5117. this.clearNextTick();
  5118. this._tickTimer = self.setTimeout(this._boundTick, 0);
  5119. }
  5120. doTick() {
  5121. }
  5122. };
  5123. var ChunkMetadata = class {
  5124. constructor(level, sn, id, size = 0, part = -1, partial = false) {
  5125. this.level = void 0;
  5126. this.sn = void 0;
  5127. this.part = void 0;
  5128. this.id = void 0;
  5129. this.size = void 0;
  5130. this.partial = void 0;
  5131. this.transmuxing = getNewPerformanceTiming();
  5132. this.buffering = {
  5133. audio: getNewPerformanceTiming(),
  5134. video: getNewPerformanceTiming(),
  5135. audiovideo: getNewPerformanceTiming()
  5136. };
  5137. this.level = level;
  5138. this.sn = sn;
  5139. this.id = id;
  5140. this.size = size;
  5141. this.part = part;
  5142. this.partial = partial;
  5143. }
  5144. };
  5145. function getNewPerformanceTiming() {
  5146. return {
  5147. start: 0,
  5148. executeStart: 0,
  5149. executeEnd: 0,
  5150. end: 0
  5151. };
  5152. }
  5153. var noopBuffered = {
  5154. length: 0,
  5155. start: () => 0,
  5156. end: () => 0
  5157. };
  5158. var BufferHelper = class {
  5159. static isBuffered(media, position) {
  5160. if (media) {
  5161. const buffered = BufferHelper.getBuffered(media);
  5162. for (let i = buffered.length; i--; ) {
  5163. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  5164. return true;
  5165. }
  5166. }
  5167. }
  5168. return false;
  5169. }
  5170. static bufferedRanges(media) {
  5171. if (media) {
  5172. const timeRanges = BufferHelper.getBuffered(media);
  5173. return BufferHelper.timeRangesToArray(timeRanges);
  5174. }
  5175. return [];
  5176. }
  5177. static timeRangesToArray(timeRanges) {
  5178. const buffered = [];
  5179. for (let i = 0; i < timeRanges.length; i++) {
  5180. buffered.push({
  5181. start: timeRanges.start(i),
  5182. end: timeRanges.end(i)
  5183. });
  5184. }
  5185. return buffered;
  5186. }
  5187. static bufferInfo(media, pos, maxHoleDuration) {
  5188. if (media) {
  5189. const buffered = BufferHelper.bufferedRanges(media);
  5190. if (buffered.length) {
  5191. return BufferHelper.bufferedInfo(buffered, pos, maxHoleDuration);
  5192. }
  5193. }
  5194. return {
  5195. len: 0,
  5196. start: pos,
  5197. end: pos,
  5198. bufferedIndex: -1
  5199. };
  5200. }
  5201. static bufferedInfo(buffered, pos, maxHoleDuration) {
  5202. pos = Math.max(0, pos);
  5203. if (buffered.length > 1) {
  5204. buffered.sort((a, b) => a.start - b.start || b.end - a.end);
  5205. }
  5206. let bufferedIndex = -1;
  5207. let buffered2 = [];
  5208. if (maxHoleDuration) {
  5209. for (let i = 0; i < buffered.length; i++) {
  5210. if (pos >= buffered[i].start && pos <= buffered[i].end) {
  5211. bufferedIndex = i;
  5212. }
  5213. const buf2len = buffered2.length;
  5214. if (buf2len) {
  5215. const buf2end = buffered2[buf2len - 1].end;
  5216. if (buffered[i].start - buf2end < maxHoleDuration) {
  5217. if (buffered[i].end > buf2end) {
  5218. buffered2[buf2len - 1].end = buffered[i].end;
  5219. }
  5220. } else {
  5221. buffered2.push(buffered[i]);
  5222. }
  5223. } else {
  5224. buffered2.push(buffered[i]);
  5225. }
  5226. }
  5227. } else {
  5228. buffered2 = buffered;
  5229. }
  5230. let bufferLen = 0;
  5231. let nextStart;
  5232. let bufferStart = pos;
  5233. let bufferEnd = pos;
  5234. for (let i = 0; i < buffered2.length; i++) {
  5235. const start = buffered2[i].start;
  5236. const end = buffered2[i].end;
  5237. if (bufferedIndex === -1 && pos >= start && pos <= end) {
  5238. bufferedIndex = i;
  5239. }
  5240. if (pos + maxHoleDuration >= start && pos < end) {
  5241. bufferStart = start;
  5242. bufferEnd = end;
  5243. bufferLen = bufferEnd - pos;
  5244. } else if (pos + maxHoleDuration < start) {
  5245. nextStart = start;
  5246. break;
  5247. }
  5248. }
  5249. return {
  5250. len: bufferLen,
  5251. start: bufferStart || 0,
  5252. end: bufferEnd || 0,
  5253. nextStart,
  5254. buffered,
  5255. bufferedIndex
  5256. };
  5257. }
  5258. static getBuffered(media) {
  5259. try {
  5260. return media.buffered || noopBuffered;
  5261. } catch (e) {
  5262. logger.log("failed to get media.buffered", e);
  5263. return noopBuffered;
  5264. }
  5265. }
  5266. };
  5267. var VARIABLE_REPLACEMENT_REGEX = /\{\$([a-zA-Z0-9-_]+)\}/g;
  5268. function hasVariableReferences(str) {
  5269. return VARIABLE_REPLACEMENT_REGEX.test(str);
  5270. }
  5271. function substituteVariables(parsed, value) {
  5272. if (parsed.variableList !== null || parsed.hasVariableRefs) {
  5273. const variableList = parsed.variableList;
  5274. return value.replace(VARIABLE_REPLACEMENT_REGEX, (variableReference) => {
  5275. const variableName = variableReference.substring(2, variableReference.length - 1);
  5276. const variableValue = variableList == null ? void 0 : variableList[variableName];
  5277. if (variableValue === void 0) {
  5278. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${variableName}"`));
  5279. return variableReference;
  5280. }
  5281. return variableValue;
  5282. });
  5283. }
  5284. return value;
  5285. }
  5286. function addVariableDefinition(parsed, attr, parentUrl) {
  5287. let variableList = parsed.variableList;
  5288. if (!variableList) {
  5289. parsed.variableList = variableList = {};
  5290. }
  5291. let NAME;
  5292. let VALUE;
  5293. if ("QUERYPARAM" in attr) {
  5294. NAME = attr.QUERYPARAM;
  5295. try {
  5296. const searchParams = new self.URL(parentUrl).searchParams;
  5297. if (searchParams.has(NAME)) {
  5298. VALUE = searchParams.get(NAME);
  5299. } else {
  5300. throw new Error(`"${NAME}" does not match any query parameter in URI: "${parentUrl}"`);
  5301. }
  5302. } catch (error) {
  5303. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE QUERYPARAM: ${error.message}`));
  5304. }
  5305. } else {
  5306. NAME = attr.NAME;
  5307. VALUE = attr.VALUE;
  5308. }
  5309. if (NAME in variableList) {
  5310. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${NAME}"`));
  5311. } else {
  5312. variableList[NAME] = VALUE || "";
  5313. }
  5314. }
  5315. function importVariableDefinition(parsed, attr, sourceVariableList) {
  5316. const IMPORT = attr.IMPORT;
  5317. if (sourceVariableList && IMPORT in sourceVariableList) {
  5318. let variableList = parsed.variableList;
  5319. if (!variableList) {
  5320. parsed.variableList = variableList = {};
  5321. }
  5322. variableList[IMPORT] = sourceVariableList[IMPORT];
  5323. } else {
  5324. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${IMPORT}"`));
  5325. }
  5326. }
  5327. var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/;
  5328. var ATTR_LIST_REGEX = /(.+?)=(".*?"|.*?)(?:,|$)/g;
  5329. var AttrList = class {
  5330. constructor(attrs, parsed) {
  5331. if (typeof attrs === "string") {
  5332. attrs = AttrList.parseAttrList(attrs, parsed);
  5333. }
  5334. _extends(this, attrs);
  5335. }
  5336. get clientAttrs() {
  5337. return Object.keys(this).filter((attr) => attr.substring(0, 2) === "X-");
  5338. }
  5339. decimalInteger(attrName) {
  5340. const intValue = parseInt(this[attrName], 10);
  5341. if (intValue > Number.MAX_SAFE_INTEGER) {
  5342. return Infinity;
  5343. }
  5344. return intValue;
  5345. }
  5346. hexadecimalInteger(attrName) {
  5347. if (this[attrName]) {
  5348. let stringValue = (this[attrName] || "0x").slice(2);
  5349. stringValue = (stringValue.length & 1 ? "0" : "") + stringValue;
  5350. const value = new Uint8Array(stringValue.length / 2);
  5351. for (let i = 0; i < stringValue.length / 2; i++) {
  5352. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  5353. }
  5354. return value;
  5355. }
  5356. return null;
  5357. }
  5358. hexadecimalIntegerAsNumber(attrName) {
  5359. const intValue = parseInt(this[attrName], 16);
  5360. if (intValue > Number.MAX_SAFE_INTEGER) {
  5361. return Infinity;
  5362. }
  5363. return intValue;
  5364. }
  5365. decimalFloatingPoint(attrName) {
  5366. return parseFloat(this[attrName]);
  5367. }
  5368. optionalFloat(attrName, defaultValue) {
  5369. const value = this[attrName];
  5370. return value ? parseFloat(value) : defaultValue;
  5371. }
  5372. enumeratedString(attrName) {
  5373. return this[attrName];
  5374. }
  5375. enumeratedStringList(attrName, dict) {
  5376. const attrValue = this[attrName];
  5377. return (attrValue ? attrValue.split(/[ ,]+/) : []).reduce((result, identifier) => {
  5378. result[identifier.toLowerCase()] = true;
  5379. return result;
  5380. }, dict);
  5381. }
  5382. bool(attrName) {
  5383. return this[attrName] === "YES";
  5384. }
  5385. decimalResolution(attrName) {
  5386. const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  5387. if (res === null) {
  5388. return void 0;
  5389. }
  5390. return {
  5391. width: parseInt(res[1], 10),
  5392. height: parseInt(res[2], 10)
  5393. };
  5394. }
  5395. static parseAttrList(input, parsed) {
  5396. let match;
  5397. const attrs = {};
  5398. const quote = '"';
  5399. ATTR_LIST_REGEX.lastIndex = 0;
  5400. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  5401. const name = match[1].trim();
  5402. let value = match[2];
  5403. const quotedString = value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1;
  5404. let hexadecimalSequence = false;
  5405. if (quotedString) {
  5406. value = value.slice(1, -1);
  5407. } else {
  5408. switch (name) {
  5409. case "IV":
  5410. case "SCTE35-CMD":
  5411. case "SCTE35-IN":
  5412. case "SCTE35-OUT":
  5413. hexadecimalSequence = true;
  5414. }
  5415. }
  5416. if (parsed && (quotedString || hexadecimalSequence)) {
  5417. {
  5418. value = substituteVariables(parsed, value);
  5419. }
  5420. } else if (!hexadecimalSequence && !quotedString) {
  5421. switch (name) {
  5422. case "CLOSED-CAPTIONS":
  5423. if (value === "NONE") {
  5424. break;
  5425. }
  5426. case "ALLOWED-CPC":
  5427. case "CLASS":
  5428. case "ASSOC-LANGUAGE":
  5429. case "AUDIO":
  5430. case "BYTERANGE":
  5431. case "CHANNELS":
  5432. case "CHARACTERISTICS":
  5433. case "CODECS":
  5434. case "DATA-ID":
  5435. case "END-DATE":
  5436. case "GROUP-ID":
  5437. case "ID":
  5438. case "IMPORT":
  5439. case "INSTREAM-ID":
  5440. case "KEYFORMAT":
  5441. case "KEYFORMATVERSIONS":
  5442. case "LANGUAGE":
  5443. case "NAME":
  5444. case "PATHWAY-ID":
  5445. case "QUERYPARAM":
  5446. case "RECENTLY-REMOVED-DATERANGES":
  5447. case "SERVER-URI":
  5448. case "STABLE-RENDITION-ID":
  5449. case "STABLE-VARIANT-ID":
  5450. case "START-DATE":
  5451. case "SUBTITLES":
  5452. case "SUPPLEMENTAL-CODECS":
  5453. case "URI":
  5454. case "VALUE":
  5455. case "VIDEO":
  5456. case "X-ASSET-LIST":
  5457. case "X-ASSET-URI":
  5458. logger.warn(`${input}: attribute ${name} is missing quotes`);
  5459. }
  5460. }
  5461. attrs[name] = value;
  5462. }
  5463. return attrs;
  5464. }
  5465. };
  5466. var CLASS_INTERSTITIAL = "com.apple.hls.interstitial";
  5467. function isDateRangeCueAttribute(attrName) {
  5468. return attrName !== "ID" && attrName !== "CLASS" && attrName !== "CUE" && attrName !== "START-DATE" && attrName !== "DURATION" && attrName !== "END-DATE" && attrName !== "END-ON-NEXT";
  5469. }
  5470. function isSCTE35Attribute(attrName) {
  5471. return attrName === "SCTE35-OUT" || attrName === "SCTE35-IN" || attrName === "SCTE35-CMD";
  5472. }
  5473. var DateRange = class {
  5474. constructor(dateRangeAttr, dateRangeWithSameId, tagCount = 0) {
  5475. var _dateRangeWithSameId$;
  5476. this.attr = void 0;
  5477. this.tagAnchor = void 0;
  5478. this.tagOrder = void 0;
  5479. this._startDate = void 0;
  5480. this._endDate = void 0;
  5481. this._dateAtEnd = void 0;
  5482. this._cue = void 0;
  5483. this._badValueForSameId = void 0;
  5484. this.tagAnchor = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagAnchor) || null;
  5485. this.tagOrder = (_dateRangeWithSameId$ = dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagOrder) != null ? _dateRangeWithSameId$ : tagCount;
  5486. if (dateRangeWithSameId) {
  5487. const previousAttr = dateRangeWithSameId.attr;
  5488. for (const key in previousAttr) {
  5489. if (Object.prototype.hasOwnProperty.call(dateRangeAttr, key) && dateRangeAttr[key] !== previousAttr[key]) {
  5490. logger.warn(`DATERANGE tag attribute: "${key}" does not match for tags with ID: "${dateRangeAttr.ID}"`);
  5491. this._badValueForSameId = key;
  5492. break;
  5493. }
  5494. }
  5495. dateRangeAttr = _extends(new AttrList({}), previousAttr, dateRangeAttr);
  5496. }
  5497. this.attr = dateRangeAttr;
  5498. if (dateRangeWithSameId) {
  5499. this._startDate = dateRangeWithSameId._startDate;
  5500. this._cue = dateRangeWithSameId._cue;
  5501. this._endDate = dateRangeWithSameId._endDate;
  5502. this._dateAtEnd = dateRangeWithSameId._dateAtEnd;
  5503. } else {
  5504. this._startDate = new Date(dateRangeAttr["START-DATE"]);
  5505. }
  5506. if ("END-DATE" in this.attr) {
  5507. const endDate = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.endDate) || new Date(this.attr["END-DATE"]);
  5508. if (isFiniteNumber(endDate.getTime())) {
  5509. this._endDate = endDate;
  5510. }
  5511. }
  5512. }
  5513. get id() {
  5514. return this.attr.ID;
  5515. }
  5516. get class() {
  5517. return this.attr.CLASS;
  5518. }
  5519. get cue() {
  5520. const _cue = this._cue;
  5521. if (_cue === void 0) {
  5522. return this._cue = this.attr.enumeratedStringList(this.attr.CUE ? "CUE" : "X-CUE", {
  5523. pre: false,
  5524. post: false,
  5525. once: false
  5526. });
  5527. }
  5528. return _cue;
  5529. }
  5530. get startTime() {
  5531. const {
  5532. tagAnchor
  5533. } = this;
  5534. if (tagAnchor === null || tagAnchor.programDateTime === null) {
  5535. logger.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${tagAnchor}`);
  5536. return NaN;
  5537. }
  5538. return tagAnchor.start + (this.startDate.getTime() - tagAnchor.programDateTime) / 1e3;
  5539. }
  5540. get startDate() {
  5541. return this._startDate;
  5542. }
  5543. get endDate() {
  5544. const dateAtEnd = this._endDate || this._dateAtEnd;
  5545. if (dateAtEnd) {
  5546. return dateAtEnd;
  5547. }
  5548. const duration = this.duration;
  5549. if (duration !== null) {
  5550. return this._dateAtEnd = new Date(this._startDate.getTime() + duration * 1e3);
  5551. }
  5552. return null;
  5553. }
  5554. get duration() {
  5555. if ("DURATION" in this.attr) {
  5556. const duration = this.attr.decimalFloatingPoint("DURATION");
  5557. if (isFiniteNumber(duration)) {
  5558. return duration;
  5559. }
  5560. } else if (this._endDate) {
  5561. return (this._endDate.getTime() - this._startDate.getTime()) / 1e3;
  5562. }
  5563. return null;
  5564. }
  5565. get plannedDuration() {
  5566. if ("PLANNED-DURATION" in this.attr) {
  5567. return this.attr.decimalFloatingPoint("PLANNED-DURATION");
  5568. }
  5569. return null;
  5570. }
  5571. get endOnNext() {
  5572. return this.attr.bool("END-ON-NEXT");
  5573. }
  5574. get isInterstitial() {
  5575. return this.class === CLASS_INTERSTITIAL;
  5576. }
  5577. get isValid() {
  5578. 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);
  5579. }
  5580. };
  5581. var DEFAULT_TARGET_DURATION = 10;
  5582. var LevelDetails = class {
  5583. constructor(baseUrl) {
  5584. this.PTSKnown = false;
  5585. this.alignedSliding = false;
  5586. this.averagetargetduration = void 0;
  5587. this.endCC = 0;
  5588. this.endSN = 0;
  5589. this.fragments = void 0;
  5590. this.fragmentHint = void 0;
  5591. this.partList = null;
  5592. this.dateRanges = void 0;
  5593. this.dateRangeTagCount = 0;
  5594. this.live = true;
  5595. this.requestScheduled = -1;
  5596. this.ageHeader = 0;
  5597. this.advancedDateTime = void 0;
  5598. this.updated = true;
  5599. this.advanced = true;
  5600. this.misses = 0;
  5601. this.startCC = 0;
  5602. this.startSN = 0;
  5603. this.startTimeOffset = null;
  5604. this.targetduration = 0;
  5605. this.totalduration = 0;
  5606. this.type = null;
  5607. this.url = void 0;
  5608. this.m3u8 = "";
  5609. this.version = null;
  5610. this.canBlockReload = false;
  5611. this.canSkipUntil = 0;
  5612. this.canSkipDateRanges = false;
  5613. this.skippedSegments = 0;
  5614. this.recentlyRemovedDateranges = void 0;
  5615. this.partHoldBack = 0;
  5616. this.holdBack = 0;
  5617. this.partTarget = 0;
  5618. this.preloadHint = void 0;
  5619. this.renditionReports = void 0;
  5620. this.tuneInGoal = 0;
  5621. this.deltaUpdateFailed = void 0;
  5622. this.driftStartTime = 0;
  5623. this.driftEndTime = 0;
  5624. this.driftStart = 0;
  5625. this.driftEnd = 0;
  5626. this.encryptedFragments = void 0;
  5627. this.playlistParsingError = null;
  5628. this.variableList = null;
  5629. this.hasVariableRefs = false;
  5630. this.appliedTimelineOffset = void 0;
  5631. this.fragments = [];
  5632. this.encryptedFragments = [];
  5633. this.dateRanges = {};
  5634. this.url = baseUrl;
  5635. }
  5636. reloaded(previous) {
  5637. if (!previous) {
  5638. this.advanced = true;
  5639. this.updated = true;
  5640. return;
  5641. }
  5642. const partSnDiff = this.lastPartSn - previous.lastPartSn;
  5643. const partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
  5644. this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff || !this.live;
  5645. this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
  5646. if (this.updated || this.advanced) {
  5647. this.misses = Math.floor(previous.misses * 0.6);
  5648. } else {
  5649. this.misses = previous.misses + 1;
  5650. }
  5651. }
  5652. get hasProgramDateTime() {
  5653. if (this.fragments.length) {
  5654. return isFiniteNumber(this.fragments[this.fragments.length - 1].programDateTime);
  5655. }
  5656. return false;
  5657. }
  5658. get levelTargetDuration() {
  5659. return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
  5660. }
  5661. get drift() {
  5662. const runTime = this.driftEndTime - this.driftStartTime;
  5663. if (runTime > 0) {
  5664. const runDuration = this.driftEnd - this.driftStart;
  5665. return runDuration * 1e3 / runTime;
  5666. }
  5667. return 1;
  5668. }
  5669. get edge() {
  5670. return this.partEnd || this.fragmentEnd;
  5671. }
  5672. get partEnd() {
  5673. var _this$partList;
  5674. if ((_this$partList = this.partList) != null && _this$partList.length) {
  5675. return this.partList[this.partList.length - 1].end;
  5676. }
  5677. return this.fragmentEnd;
  5678. }
  5679. get fragmentEnd() {
  5680. var _this$fragments;
  5681. if ((_this$fragments = this.fragments) != null && _this$fragments.length) {
  5682. return this.fragments[this.fragments.length - 1].end;
  5683. }
  5684. return 0;
  5685. }
  5686. get fragmentStart() {
  5687. var _this$fragments2;
  5688. if ((_this$fragments2 = this.fragments) != null && _this$fragments2.length) {
  5689. return this.fragments[0].start;
  5690. }
  5691. return 0;
  5692. }
  5693. get age() {
  5694. if (this.advancedDateTime) {
  5695. return Math.max(Date.now() - this.advancedDateTime, 0) / 1e3;
  5696. }
  5697. return 0;
  5698. }
  5699. get lastPartIndex() {
  5700. var _this$partList2;
  5701. if ((_this$partList2 = this.partList) != null && _this$partList2.length) {
  5702. return this.partList[this.partList.length - 1].index;
  5703. }
  5704. return -1;
  5705. }
  5706. get maxPartIndex() {
  5707. const partList = this.partList;
  5708. if (partList) {
  5709. const lastIndex = this.lastPartIndex;
  5710. if (lastIndex !== -1) {
  5711. for (let i = partList.length; i--; ) {
  5712. if (partList[i].index > lastIndex) {
  5713. return partList[i].index;
  5714. }
  5715. }
  5716. return lastIndex;
  5717. }
  5718. }
  5719. return 0;
  5720. }
  5721. get lastPartSn() {
  5722. var _this$partList3;
  5723. if ((_this$partList3 = this.partList) != null && _this$partList3.length) {
  5724. return this.partList[this.partList.length - 1].fragment.sn;
  5725. }
  5726. return this.endSN;
  5727. }
  5728. get expired() {
  5729. if (this.live && this.age && this.misses < 3) {
  5730. const playlistWindowDuration = this.partEnd - this.fragmentStart;
  5731. return this.age > Math.max(playlistWindowDuration, this.totalduration) + this.levelTargetDuration;
  5732. }
  5733. return false;
  5734. }
  5735. };
  5736. function isFullSegmentEncryption(method) {
  5737. return method === "AES-128" || method === "AES-256" || method === "AES-256-CTR";
  5738. }
  5739. function getAesModeFromFullSegmentMethod(method) {
  5740. switch (method) {
  5741. case "AES-128":
  5742. case "AES-256":
  5743. return DecrypterAesMode.cbc;
  5744. case "AES-256-CTR":
  5745. return DecrypterAesMode.ctr;
  5746. default:
  5747. throw new Error(`invalid full segment method ${method}`);
  5748. }
  5749. }
  5750. function base64Decode(base64encodedStr) {
  5751. return Uint8Array.from(atob(base64encodedStr), (c) => c.charCodeAt(0));
  5752. }
  5753. function strToUtf8array(str) {
  5754. return Uint8Array.from(unescape(encodeURIComponent(str)), (c) => c.charCodeAt(0));
  5755. }
  5756. function getKeyIdBytes(str) {
  5757. const keyIdbytes = strToUtf8array(str).subarray(0, 16);
  5758. const paddedkeyIdbytes = new Uint8Array(16);
  5759. paddedkeyIdbytes.set(keyIdbytes, 16 - keyIdbytes.length);
  5760. return paddedkeyIdbytes;
  5761. }
  5762. function changeEndianness(keyId) {
  5763. const swap = function swap2(array, from, to) {
  5764. const cur = array[from];
  5765. array[from] = array[to];
  5766. array[to] = cur;
  5767. };
  5768. swap(keyId, 0, 3);
  5769. swap(keyId, 1, 2);
  5770. swap(keyId, 4, 5);
  5771. swap(keyId, 6, 7);
  5772. }
  5773. function convertDataUriToArrayBytes(uri) {
  5774. const colonsplit = uri.split(":");
  5775. let keydata = null;
  5776. if (colonsplit[0] === "data" && colonsplit.length === 2) {
  5777. const semicolonsplit = colonsplit[1].split(";");
  5778. const commasplit = semicolonsplit[semicolonsplit.length - 1].split(",");
  5779. if (commasplit.length === 2) {
  5780. const isbase64 = commasplit[0] === "base64";
  5781. const data = commasplit[1];
  5782. if (isbase64) {
  5783. semicolonsplit.splice(-1, 1);
  5784. keydata = base64Decode(data);
  5785. } else {
  5786. keydata = getKeyIdBytes(data);
  5787. }
  5788. }
  5789. }
  5790. return keydata;
  5791. }
  5792. var optionalSelf = typeof self !== "undefined" ? self : void 0;
  5793. var KeySystems = {
  5794. CLEARKEY: "org.w3.clearkey",
  5795. FAIRPLAY: "com.apple.fps",
  5796. PLAYREADY: "com.microsoft.playready",
  5797. WIDEVINE: "com.widevine.alpha"
  5798. };
  5799. var KeySystemFormats = {
  5800. CLEARKEY: "org.w3.clearkey",
  5801. FAIRPLAY: "com.apple.streamingkeydelivery",
  5802. PLAYREADY: "com.microsoft.playready",
  5803. WIDEVINE: "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"
  5804. };
  5805. function keySystemFormatToKeySystemDomain(format2) {
  5806. switch (format2) {
  5807. case KeySystemFormats.FAIRPLAY:
  5808. return KeySystems.FAIRPLAY;
  5809. case KeySystemFormats.PLAYREADY:
  5810. return KeySystems.PLAYREADY;
  5811. case KeySystemFormats.WIDEVINE:
  5812. return KeySystems.WIDEVINE;
  5813. case KeySystemFormats.CLEARKEY:
  5814. return KeySystems.CLEARKEY;
  5815. }
  5816. }
  5817. function keySystemDomainToKeySystemFormat(keySystem) {
  5818. switch (keySystem) {
  5819. case KeySystems.FAIRPLAY:
  5820. return KeySystemFormats.FAIRPLAY;
  5821. case KeySystems.PLAYREADY:
  5822. return KeySystemFormats.PLAYREADY;
  5823. case KeySystems.WIDEVINE:
  5824. return KeySystemFormats.WIDEVINE;
  5825. case KeySystems.CLEARKEY:
  5826. return KeySystemFormats.CLEARKEY;
  5827. }
  5828. }
  5829. function getKeySystemsForConfig(config) {
  5830. const {
  5831. drmSystems,
  5832. widevineLicenseUrl
  5833. } = config;
  5834. const keySystemsToAttempt = drmSystems ? [KeySystems.FAIRPLAY, KeySystems.WIDEVINE, KeySystems.PLAYREADY, KeySystems.CLEARKEY].filter((keySystem) => !!drmSystems[keySystem]) : [];
  5835. if (!keySystemsToAttempt[KeySystems.WIDEVINE] && widevineLicenseUrl) {
  5836. keySystemsToAttempt.push(KeySystems.WIDEVINE);
  5837. }
  5838. return keySystemsToAttempt;
  5839. }
  5840. var requestMediaKeySystemAccess = function(_optionalSelf$navigat) {
  5841. if (optionalSelf != null && (_optionalSelf$navigat = optionalSelf.navigator) != null && _optionalSelf$navigat.requestMediaKeySystemAccess) {
  5842. return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);
  5843. } else {
  5844. return null;
  5845. }
  5846. }();
  5847. function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {
  5848. let initDataTypes;
  5849. switch (keySystem) {
  5850. case KeySystems.FAIRPLAY:
  5851. initDataTypes = ["cenc", "sinf"];
  5852. break;
  5853. case KeySystems.WIDEVINE:
  5854. case KeySystems.PLAYREADY:
  5855. initDataTypes = ["cenc"];
  5856. break;
  5857. case KeySystems.CLEARKEY:
  5858. initDataTypes = ["cenc", "keyids"];
  5859. break;
  5860. default:
  5861. throw new Error(`Unknown key-system: ${keySystem}`);
  5862. }
  5863. return createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions);
  5864. }
  5865. function createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions) {
  5866. const baseConfig = {
  5867. initDataTypes,
  5868. persistentState: drmSystemOptions.persistentState || "optional",
  5869. distinctiveIdentifier: drmSystemOptions.distinctiveIdentifier || "optional",
  5870. sessionTypes: drmSystemOptions.sessionTypes || [drmSystemOptions.sessionType || "temporary"],
  5871. audioCapabilities: audioCodecs.map((codec) => ({
  5872. contentType: `audio/mp4; codecs=${codec}`,
  5873. robustness: drmSystemOptions.audioRobustness || "",
  5874. encryptionScheme: drmSystemOptions.audioEncryptionScheme || null
  5875. })),
  5876. videoCapabilities: videoCodecs.map((codec) => ({
  5877. contentType: `video/mp4; codecs=${codec}`,
  5878. robustness: drmSystemOptions.videoRobustness || "",
  5879. encryptionScheme: drmSystemOptions.videoEncryptionScheme || null
  5880. }))
  5881. };
  5882. return [baseConfig];
  5883. }
  5884. function isPersistentSessionType(drmSystemOptions) {
  5885. var _drmSystemOptions$ses;
  5886. return drmSystemOptions.sessionType === "persistent-license" || !!((_drmSystemOptions$ses = drmSystemOptions.sessionTypes) != null && _drmSystemOptions$ses.some((type) => type === "persistent-license"));
  5887. }
  5888. function parsePlayReadyWRM(keyBytes) {
  5889. const keyBytesUtf16 = new Uint16Array(keyBytes.buffer, keyBytes.byteOffset, keyBytes.byteLength / 2);
  5890. const keyByteStr = String.fromCharCode.apply(null, Array.from(keyBytesUtf16));
  5891. const xmlKeyBytes = keyByteStr.substring(keyByteStr.indexOf("<"), keyByteStr.length);
  5892. const parser = new DOMParser();
  5893. const xmlDoc = parser.parseFromString(xmlKeyBytes, "text/xml");
  5894. const keyData = xmlDoc.getElementsByTagName("KID")[0];
  5895. if (keyData) {
  5896. const keyId = keyData.childNodes[0] ? keyData.childNodes[0].nodeValue : keyData.getAttribute("VALUE");
  5897. if (keyId) {
  5898. const keyIdArray = base64Decode(keyId).subarray(0, 16);
  5899. changeEndianness(keyIdArray);
  5900. return keyIdArray;
  5901. }
  5902. }
  5903. return null;
  5904. }
  5905. var keyUriToKeyIdMap = {};
  5906. var LevelKey = class {
  5907. static clearKeyUriToKeyIdMap() {
  5908. keyUriToKeyIdMap = {};
  5909. }
  5910. constructor(method, uri, format2, formatversions = [1], iv = null, keyId) {
  5911. this.uri = void 0;
  5912. this.method = void 0;
  5913. this.keyFormat = void 0;
  5914. this.keyFormatVersions = void 0;
  5915. this.encrypted = void 0;
  5916. this.isCommonEncryption = void 0;
  5917. this.iv = null;
  5918. this.key = null;
  5919. this.keyId = null;
  5920. this.pssh = null;
  5921. this.method = method;
  5922. this.uri = uri;
  5923. this.keyFormat = format2;
  5924. this.keyFormatVersions = formatversions;
  5925. this.iv = iv;
  5926. this.encrypted = method ? method !== "NONE" : false;
  5927. this.isCommonEncryption = this.encrypted && !isFullSegmentEncryption(method);
  5928. if (keyId != null && keyId.startsWith("0x")) {
  5929. this.keyId = new Uint8Array(hexToArrayBuffer(keyId));
  5930. }
  5931. }
  5932. matches(key) {
  5933. var _key$iv, _this$iv;
  5934. 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(","));
  5935. }
  5936. isSupported() {
  5937. if (this.method) {
  5938. if (isFullSegmentEncryption(this.method) || this.method === "NONE") {
  5939. return true;
  5940. }
  5941. if (this.keyFormat === "identity") {
  5942. return this.method === "SAMPLE-AES";
  5943. } else {
  5944. switch (this.keyFormat) {
  5945. case KeySystemFormats.FAIRPLAY:
  5946. case KeySystemFormats.WIDEVINE:
  5947. case KeySystemFormats.PLAYREADY:
  5948. case KeySystemFormats.CLEARKEY:
  5949. return ["ISO-23001-7", "SAMPLE-AES", "SAMPLE-AES-CENC", "SAMPLE-AES-CTR"].indexOf(this.method) !== -1;
  5950. }
  5951. }
  5952. }
  5953. return false;
  5954. }
  5955. getDecryptData(sn) {
  5956. if (!this.encrypted || !this.uri) {
  5957. return null;
  5958. }
  5959. if (isFullSegmentEncryption(this.method) && this.uri && !this.iv) {
  5960. if (typeof sn !== "number") {
  5961. logger.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`);
  5962. sn = 0;
  5963. }
  5964. const iv = createInitializationVector(sn);
  5965. const decryptdata = new LevelKey(this.method, this.uri, "identity", this.keyFormatVersions, iv);
  5966. return decryptdata;
  5967. }
  5968. if (this.pssh && this.keyId) {
  5969. return this;
  5970. }
  5971. const keyBytes = convertDataUriToArrayBytes(this.uri);
  5972. if (keyBytes) {
  5973. switch (this.keyFormat) {
  5974. case KeySystemFormats.WIDEVINE:
  5975. this.pssh = keyBytes;
  5976. if (!this.keyId && keyBytes.length >= 22) {
  5977. const offset = keyBytes.length - 22;
  5978. this.keyId = keyBytes.subarray(offset, offset + 16);
  5979. }
  5980. break;
  5981. case KeySystemFormats.PLAYREADY: {
  5982. const PlayReadyKeySystemUUID = new Uint8Array([154, 4, 240, 121, 152, 64, 66, 134, 171, 146, 230, 91, 224, 136, 95, 149]);
  5983. this.pssh = mp4pssh(PlayReadyKeySystemUUID, null, keyBytes);
  5984. this.keyId = parsePlayReadyWRM(keyBytes);
  5985. break;
  5986. }
  5987. default: {
  5988. let keydata = keyBytes.subarray(0, 16);
  5989. if (keydata.length !== 16) {
  5990. const padded = new Uint8Array(16);
  5991. padded.set(keydata, 16 - keydata.length);
  5992. keydata = padded;
  5993. }
  5994. this.keyId = keydata;
  5995. break;
  5996. }
  5997. }
  5998. }
  5999. if (!this.keyId || this.keyId.byteLength !== 16) {
  6000. let keyId = keyUriToKeyIdMap[this.uri];
  6001. if (!keyId) {
  6002. const val = Object.keys(keyUriToKeyIdMap).length % Number.MAX_SAFE_INTEGER;
  6003. keyId = new Uint8Array(16);
  6004. const dv = new DataView(keyId.buffer, 12, 4);
  6005. dv.setUint32(0, val);
  6006. keyUriToKeyIdMap[this.uri] = keyId;
  6007. }
  6008. this.keyId = keyId;
  6009. }
  6010. return this;
  6011. }
  6012. };
  6013. function createInitializationVector(segmentNumber) {
  6014. const uint8View = new Uint8Array(16);
  6015. for (let i = 12; i < 16; i++) {
  6016. uint8View[i] = segmentNumber >> 8 * (15 - i) & 255;
  6017. }
  6018. return uint8View;
  6019. }
  6020. 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;
  6021. var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  6022. var IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m;
  6023. var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([
  6024. /#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,
  6025. /(?!#) *(\S[^\r\n]*)/.source,
  6026. /#.*/.source
  6027. ].join("|"), "g");
  6028. 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("|"));
  6029. var M3U8Parser = class {
  6030. static findGroup(groups, mediaGroupId) {
  6031. for (let i = 0; i < groups.length; i++) {
  6032. const group = groups[i];
  6033. if (group.id === mediaGroupId) {
  6034. return group;
  6035. }
  6036. }
  6037. }
  6038. static resolve(url, baseUrl) {
  6039. return urlToolkitExports.buildAbsoluteURL(baseUrl, url, {
  6040. alwaysNormalize: true
  6041. });
  6042. }
  6043. static isMediaPlaylist(str) {
  6044. return IS_MEDIA_PLAYLIST.test(str);
  6045. }
  6046. static parseMasterPlaylist(string, baseurl) {
  6047. const hasVariableRefs = hasVariableReferences(string);
  6048. const parsed = {
  6049. contentSteering: null,
  6050. levels: [],
  6051. playlistParsingError: null,
  6052. sessionData: null,
  6053. sessionKeys: null,
  6054. startTimeOffset: null,
  6055. variableList: null,
  6056. hasVariableRefs
  6057. };
  6058. const levelsWithKnownCodecs = [];
  6059. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  6060. let result;
  6061. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  6062. if (result[1]) {
  6063. var _level$unknownCodecs;
  6064. const attrs = new AttrList(result[1], parsed);
  6065. const uri = substituteVariables(parsed, result[2]);
  6066. const level = {
  6067. attrs,
  6068. bitrate: attrs.decimalInteger("BANDWIDTH") || attrs.decimalInteger("AVERAGE-BANDWIDTH"),
  6069. name: attrs.NAME,
  6070. url: M3U8Parser.resolve(uri, baseurl)
  6071. };
  6072. const resolution = attrs.decimalResolution("RESOLUTION");
  6073. if (resolution) {
  6074. level.width = resolution.width;
  6075. level.height = resolution.height;
  6076. }
  6077. setCodecs(attrs.CODECS, level);
  6078. const supplementalCodecs = attrs["SUPPLEMENTAL-CODECS"];
  6079. if (supplementalCodecs) {
  6080. level.supplemental = {};
  6081. setCodecs(supplementalCodecs, level.supplemental);
  6082. }
  6083. if (!((_level$unknownCodecs = level.unknownCodecs) != null && _level$unknownCodecs.length)) {
  6084. levelsWithKnownCodecs.push(level);
  6085. }
  6086. parsed.levels.push(level);
  6087. } else if (result[3]) {
  6088. const tag = result[3];
  6089. const attributes = result[4];
  6090. switch (tag) {
  6091. case "SESSION-DATA": {
  6092. const sessionAttrs = new AttrList(attributes, parsed);
  6093. const dataId = sessionAttrs["DATA-ID"];
  6094. if (dataId) {
  6095. if (parsed.sessionData === null) {
  6096. parsed.sessionData = {};
  6097. }
  6098. parsed.sessionData[dataId] = sessionAttrs;
  6099. }
  6100. break;
  6101. }
  6102. case "SESSION-KEY": {
  6103. const sessionKey = parseKey(attributes, baseurl, parsed);
  6104. if (sessionKey.encrypted && sessionKey.isSupported()) {
  6105. if (parsed.sessionKeys === null) {
  6106. parsed.sessionKeys = [];
  6107. }
  6108. parsed.sessionKeys.push(sessionKey);
  6109. } else {
  6110. logger.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${attributes}"`);
  6111. }
  6112. break;
  6113. }
  6114. case "DEFINE": {
  6115. {
  6116. const variableAttributes = new AttrList(attributes, parsed);
  6117. addVariableDefinition(parsed, variableAttributes, baseurl);
  6118. }
  6119. break;
  6120. }
  6121. case "CONTENT-STEERING": {
  6122. const contentSteeringAttributes = new AttrList(attributes, parsed);
  6123. parsed.contentSteering = {
  6124. uri: M3U8Parser.resolve(contentSteeringAttributes["SERVER-URI"], baseurl),
  6125. pathwayId: contentSteeringAttributes["PATHWAY-ID"] || "."
  6126. };
  6127. break;
  6128. }
  6129. case "START": {
  6130. parsed.startTimeOffset = parseStartTimeOffset(attributes);
  6131. break;
  6132. }
  6133. }
  6134. }
  6135. }
  6136. const stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < parsed.levels.length;
  6137. parsed.levels = stripUnknownCodecLevels ? levelsWithKnownCodecs : parsed.levels;
  6138. if (parsed.levels.length === 0) {
  6139. parsed.playlistParsingError = new Error("no levels found in manifest");
  6140. }
  6141. return parsed;
  6142. }
  6143. static parseMasterPlaylistMedia(string, baseurl, parsed) {
  6144. let result;
  6145. const results = {};
  6146. const levels = parsed.levels;
  6147. const groupsByType = {
  6148. AUDIO: levels.map((level) => ({
  6149. id: level.attrs.AUDIO,
  6150. audioCodec: level.audioCodec
  6151. })),
  6152. SUBTITLES: levels.map((level) => ({
  6153. id: level.attrs.SUBTITLES,
  6154. textCodec: level.textCodec
  6155. })),
  6156. "CLOSED-CAPTIONS": []
  6157. };
  6158. let id = 0;
  6159. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  6160. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  6161. const attrs = new AttrList(result[1], parsed);
  6162. const type = attrs.TYPE;
  6163. if (type) {
  6164. const groups = groupsByType[type];
  6165. const medias = results[type] || [];
  6166. results[type] = medias;
  6167. const lang = attrs.LANGUAGE;
  6168. const assocLang = attrs["ASSOC-LANGUAGE"];
  6169. const channels = attrs.CHANNELS;
  6170. const characteristics = attrs.CHARACTERISTICS;
  6171. const instreamId = attrs["INSTREAM-ID"];
  6172. const media = {
  6173. attrs,
  6174. bitrate: 0,
  6175. id: id++,
  6176. groupId: attrs["GROUP-ID"] || "",
  6177. name: attrs.NAME || lang || "",
  6178. type,
  6179. default: attrs.bool("DEFAULT"),
  6180. autoselect: attrs.bool("AUTOSELECT"),
  6181. forced: attrs.bool("FORCED"),
  6182. lang,
  6183. url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ""
  6184. };
  6185. if (assocLang) {
  6186. media.assocLang = assocLang;
  6187. }
  6188. if (channels) {
  6189. media.channels = channels;
  6190. }
  6191. if (characteristics) {
  6192. media.characteristics = characteristics;
  6193. }
  6194. if (instreamId) {
  6195. media.instreamId = instreamId;
  6196. }
  6197. if (groups != null && groups.length) {
  6198. const groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
  6199. assignCodec(media, groupCodec, "audioCodec");
  6200. assignCodec(media, groupCodec, "textCodec");
  6201. }
  6202. medias.push(media);
  6203. }
  6204. }
  6205. return results;
  6206. }
  6207. static parseLevelPlaylist(string, baseurl, id, type, levelUrlId, multivariantVariableList) {
  6208. var _LEVEL_PLAYLIST_REGEX;
  6209. const base = {
  6210. url: baseurl
  6211. };
  6212. const level = new LevelDetails(baseurl);
  6213. const fragments = level.fragments;
  6214. const programDateTimes = [];
  6215. let currentInitSegment = null;
  6216. let currentSN = 0;
  6217. let currentPart = 0;
  6218. let totalduration = 0;
  6219. let discontinuityCounter = 0;
  6220. let currentBitrate = 0;
  6221. let prevFrag = null;
  6222. let frag = new Fragment(type, base);
  6223. let result;
  6224. let i;
  6225. let levelkeys;
  6226. let firstPdtIndex = -1;
  6227. let createNextFrag = false;
  6228. let nextByteRange = null;
  6229. let serverControlAttrs;
  6230. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  6231. level.m3u8 = string;
  6232. level.hasVariableRefs = hasVariableReferences(string);
  6233. if (((_LEVEL_PLAYLIST_REGEX = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) == null ? void 0 : _LEVEL_PLAYLIST_REGEX[0]) !== "#EXTM3U") {
  6234. level.playlistParsingError = new Error("Missing format identifier #EXTM3U");
  6235. return level;
  6236. }
  6237. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  6238. if (createNextFrag) {
  6239. createNextFrag = false;
  6240. frag = new Fragment(type, base);
  6241. frag.playlistOffset = totalduration;
  6242. frag.start = totalduration;
  6243. frag.sn = currentSN;
  6244. frag.cc = discontinuityCounter;
  6245. if (currentBitrate) {
  6246. frag.bitrate = currentBitrate;
  6247. }
  6248. frag.level = id;
  6249. if (currentInitSegment) {
  6250. frag.initSegment = currentInitSegment;
  6251. if (currentInitSegment.rawProgramDateTime) {
  6252. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  6253. currentInitSegment.rawProgramDateTime = null;
  6254. }
  6255. if (nextByteRange) {
  6256. frag.setByteRange(nextByteRange);
  6257. nextByteRange = null;
  6258. }
  6259. }
  6260. }
  6261. const duration = result[1];
  6262. if (duration) {
  6263. frag.duration = parseFloat(duration);
  6264. const title = (" " + result[2]).slice(1);
  6265. frag.title = title || null;
  6266. frag.tagList.push(title ? ["INF", duration, title] : ["INF", duration]);
  6267. } else if (result[3]) {
  6268. if (isFiniteNumber(frag.duration)) {
  6269. frag.playlistOffset = totalduration;
  6270. frag.start = totalduration;
  6271. if (levelkeys) {
  6272. setFragLevelKeys(frag, levelkeys, level);
  6273. }
  6274. frag.sn = currentSN;
  6275. frag.level = id;
  6276. frag.cc = discontinuityCounter;
  6277. fragments.push(frag);
  6278. const uri = (" " + result[3]).slice(1);
  6279. frag.relurl = substituteVariables(level, uri);
  6280. assignProgramDateTime(frag, prevFrag, programDateTimes);
  6281. prevFrag = frag;
  6282. totalduration += frag.duration;
  6283. currentSN++;
  6284. currentPart = 0;
  6285. createNextFrag = true;
  6286. }
  6287. } else {
  6288. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  6289. if (!result) {
  6290. logger.warn("No matches on slow regex match for level playlist!");
  6291. continue;
  6292. }
  6293. for (i = 1; i < result.length; i++) {
  6294. if (result[i] !== void 0) {
  6295. break;
  6296. }
  6297. }
  6298. const tag = (" " + result[i]).slice(1);
  6299. const value1 = (" " + result[i + 1]).slice(1);
  6300. const value2 = result[i + 2] ? (" " + result[i + 2]).slice(1) : null;
  6301. switch (tag) {
  6302. case "BYTERANGE":
  6303. if (prevFrag) {
  6304. frag.setByteRange(value1, prevFrag);
  6305. } else {
  6306. frag.setByteRange(value1);
  6307. }
  6308. break;
  6309. case "PROGRAM-DATE-TIME":
  6310. frag.rawProgramDateTime = value1;
  6311. frag.tagList.push(["PROGRAM-DATE-TIME", value1]);
  6312. if (firstPdtIndex === -1) {
  6313. firstPdtIndex = fragments.length;
  6314. }
  6315. break;
  6316. case "PLAYLIST-TYPE":
  6317. if (level.type) {
  6318. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6319. }
  6320. level.type = value1.toUpperCase();
  6321. break;
  6322. case "MEDIA-SEQUENCE":
  6323. if (level.startSN !== 0) {
  6324. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6325. } else if (fragments.length > 0) {
  6326. assignMustAppearBeforeSegmentsError(level, tag, result);
  6327. }
  6328. currentSN = level.startSN = parseInt(value1);
  6329. break;
  6330. case "SKIP": {
  6331. if (level.skippedSegments) {
  6332. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6333. }
  6334. const skipAttrs = new AttrList(value1, level);
  6335. const skippedSegments = skipAttrs.decimalInteger("SKIPPED-SEGMENTS");
  6336. if (isFiniteNumber(skippedSegments)) {
  6337. level.skippedSegments += skippedSegments;
  6338. for (let _i = skippedSegments; _i--; ) {
  6339. fragments.push(null);
  6340. }
  6341. currentSN += skippedSegments;
  6342. }
  6343. const recentlyRemovedDateranges = skipAttrs.enumeratedString("RECENTLY-REMOVED-DATERANGES");
  6344. if (recentlyRemovedDateranges) {
  6345. level.recentlyRemovedDateranges = (level.recentlyRemovedDateranges || []).concat(recentlyRemovedDateranges.split(" "));
  6346. }
  6347. break;
  6348. }
  6349. case "TARGETDURATION":
  6350. if (level.targetduration !== 0) {
  6351. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6352. }
  6353. level.targetduration = Math.max(parseInt(value1), 1);
  6354. break;
  6355. case "VERSION":
  6356. if (level.version !== null) {
  6357. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6358. }
  6359. level.version = parseInt(value1);
  6360. break;
  6361. case "INDEPENDENT-SEGMENTS":
  6362. break;
  6363. case "ENDLIST":
  6364. if (!level.live) {
  6365. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6366. }
  6367. level.live = false;
  6368. break;
  6369. case "#":
  6370. if (value1 || value2) {
  6371. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  6372. }
  6373. break;
  6374. case "DISCONTINUITY":
  6375. discontinuityCounter++;
  6376. frag.tagList.push(["DIS"]);
  6377. break;
  6378. case "GAP":
  6379. frag.gap = true;
  6380. frag.tagList.push([tag]);
  6381. break;
  6382. case "BITRATE":
  6383. frag.tagList.push([tag, value1]);
  6384. currentBitrate = parseInt(value1) * 1e3;
  6385. if (isFiniteNumber(currentBitrate)) {
  6386. frag.bitrate = currentBitrate;
  6387. } else {
  6388. currentBitrate = 0;
  6389. }
  6390. break;
  6391. case "DATERANGE": {
  6392. const dateRangeAttr = new AttrList(value1, level);
  6393. const dateRange = new DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID], level.dateRangeTagCount);
  6394. level.dateRangeTagCount++;
  6395. if (dateRange.isValid || level.skippedSegments) {
  6396. level.dateRanges[dateRange.id] = dateRange;
  6397. } else {
  6398. logger.warn(`Ignoring invalid DATERANGE tag: "${value1}"`);
  6399. }
  6400. frag.tagList.push(["EXT-X-DATERANGE", value1]);
  6401. break;
  6402. }
  6403. case "DEFINE": {
  6404. {
  6405. const variableAttributes = new AttrList(value1, level);
  6406. if ("IMPORT" in variableAttributes) {
  6407. importVariableDefinition(level, variableAttributes, multivariantVariableList);
  6408. } else {
  6409. addVariableDefinition(level, variableAttributes, baseurl);
  6410. }
  6411. }
  6412. break;
  6413. }
  6414. case "DISCONTINUITY-SEQUENCE":
  6415. if (level.startCC !== 0) {
  6416. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6417. } else if (fragments.length > 0) {
  6418. assignMustAppearBeforeSegmentsError(level, tag, result);
  6419. }
  6420. level.startCC = discontinuityCounter = parseInt(value1);
  6421. break;
  6422. case "KEY": {
  6423. const levelKey = parseKey(value1, baseurl, level);
  6424. if (levelKey.isSupported()) {
  6425. if (levelKey.method === "NONE") {
  6426. levelkeys = void 0;
  6427. break;
  6428. }
  6429. if (!levelkeys) {
  6430. levelkeys = {};
  6431. }
  6432. const currentKey = levelkeys[levelKey.keyFormat];
  6433. if (!(currentKey != null && currentKey.matches(levelKey))) {
  6434. if (currentKey) {
  6435. levelkeys = _extends({}, levelkeys);
  6436. }
  6437. levelkeys[levelKey.keyFormat] = levelKey;
  6438. }
  6439. } else {
  6440. logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${value1}"`);
  6441. }
  6442. break;
  6443. }
  6444. case "START":
  6445. level.startTimeOffset = parseStartTimeOffset(value1);
  6446. break;
  6447. case "MAP": {
  6448. const mapAttrs = new AttrList(value1, level);
  6449. if (frag.duration) {
  6450. const init = new Fragment(type, base);
  6451. setInitSegment(init, mapAttrs, id, levelkeys);
  6452. currentInitSegment = init;
  6453. frag.initSegment = currentInitSegment;
  6454. if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) {
  6455. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  6456. }
  6457. } else {
  6458. const end = frag.byteRangeEndOffset;
  6459. if (end) {
  6460. const start = frag.byteRangeStartOffset;
  6461. nextByteRange = `${end - start}@${start}`;
  6462. } else {
  6463. nextByteRange = null;
  6464. }
  6465. setInitSegment(frag, mapAttrs, id, levelkeys);
  6466. currentInitSegment = frag;
  6467. createNextFrag = true;
  6468. }
  6469. currentInitSegment.cc = discontinuityCounter;
  6470. break;
  6471. }
  6472. case "SERVER-CONTROL": {
  6473. if (serverControlAttrs) {
  6474. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6475. }
  6476. serverControlAttrs = new AttrList(value1);
  6477. level.canBlockReload = serverControlAttrs.bool("CAN-BLOCK-RELOAD");
  6478. level.canSkipUntil = serverControlAttrs.optionalFloat("CAN-SKIP-UNTIL", 0);
  6479. level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool("CAN-SKIP-DATERANGES");
  6480. level.partHoldBack = serverControlAttrs.optionalFloat("PART-HOLD-BACK", 0);
  6481. level.holdBack = serverControlAttrs.optionalFloat("HOLD-BACK", 0);
  6482. break;
  6483. }
  6484. case "PART-INF": {
  6485. if (level.partTarget) {
  6486. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6487. }
  6488. const partInfAttrs = new AttrList(value1);
  6489. level.partTarget = partInfAttrs.decimalFloatingPoint("PART-TARGET");
  6490. break;
  6491. }
  6492. case "PART": {
  6493. let partList = level.partList;
  6494. if (!partList) {
  6495. partList = level.partList = [];
  6496. }
  6497. const previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : void 0;
  6498. const index = currentPart++;
  6499. const partAttrs = new AttrList(value1, level);
  6500. const part = new Part(partAttrs, frag, base, index, previousFragmentPart);
  6501. partList.push(part);
  6502. frag.duration += part.duration;
  6503. break;
  6504. }
  6505. case "PRELOAD-HINT": {
  6506. const preloadHintAttrs = new AttrList(value1, level);
  6507. level.preloadHint = preloadHintAttrs;
  6508. break;
  6509. }
  6510. case "RENDITION-REPORT": {
  6511. const renditionReportAttrs = new AttrList(value1, level);
  6512. level.renditionReports = level.renditionReports || [];
  6513. level.renditionReports.push(renditionReportAttrs);
  6514. break;
  6515. }
  6516. default:
  6517. logger.warn(`line parsed but not handled: ${result}`);
  6518. break;
  6519. }
  6520. }
  6521. }
  6522. if (prevFrag && !prevFrag.relurl) {
  6523. fragments.pop();
  6524. totalduration -= prevFrag.duration;
  6525. if (level.partList) {
  6526. level.fragmentHint = prevFrag;
  6527. }
  6528. } else if (level.partList) {
  6529. assignProgramDateTime(frag, prevFrag, programDateTimes);
  6530. frag.cc = discontinuityCounter;
  6531. level.fragmentHint = frag;
  6532. if (levelkeys) {
  6533. setFragLevelKeys(frag, levelkeys, level);
  6534. }
  6535. }
  6536. if (!level.targetduration) {
  6537. level.playlistParsingError = new Error(`#EXT-X-TARGETDURATION is required`);
  6538. }
  6539. const fragmentLength = fragments.length;
  6540. const firstFragment = fragments[0];
  6541. const lastFragment = fragments[fragmentLength - 1];
  6542. totalduration += level.skippedSegments * level.targetduration;
  6543. if (totalduration > 0 && fragmentLength && lastFragment) {
  6544. level.averagetargetduration = totalduration / fragmentLength;
  6545. const lastSn = lastFragment.sn;
  6546. level.endSN = lastSn !== "initSegment" ? lastSn : 0;
  6547. if (!level.live) {
  6548. lastFragment.endList = true;
  6549. }
  6550. if (firstFragment && level.startCC === void 0) {
  6551. level.startCC = firstFragment.cc;
  6552. }
  6553. if (firstPdtIndex > 0) {
  6554. backfillProgramDateTimes(fragments, firstPdtIndex);
  6555. if (firstFragment) {
  6556. programDateTimes.unshift(firstFragment);
  6557. }
  6558. }
  6559. } else {
  6560. level.endSN = 0;
  6561. level.startCC = 0;
  6562. }
  6563. if (level.fragmentHint) {
  6564. totalduration += level.fragmentHint.duration;
  6565. }
  6566. level.totalduration = totalduration;
  6567. if (programDateTimes.length && level.dateRangeTagCount && firstFragment) {
  6568. mapDateRanges(programDateTimes, level);
  6569. }
  6570. level.endCC = discontinuityCounter;
  6571. return level;
  6572. }
  6573. };
  6574. function mapDateRanges(programDateTimes, details) {
  6575. const programDateTimeCount = programDateTimes.length;
  6576. if (!programDateTimeCount) {
  6577. return;
  6578. }
  6579. const lastProgramDateTime = programDateTimes[programDateTimeCount - 1];
  6580. const playlistEnd = details.live ? Infinity : details.totalduration;
  6581. const dateRangeIds = Object.keys(details.dateRanges);
  6582. for (let i = dateRangeIds.length; i--; ) {
  6583. const dateRange = details.dateRanges[dateRangeIds[i]];
  6584. const startDateTime = dateRange.startDate.getTime();
  6585. dateRange.tagAnchor = lastProgramDateTime.ref;
  6586. for (let j = programDateTimeCount; j--; ) {
  6587. const fragIndex = findFragmentWithStartDate(details, startDateTime, programDateTimes, j, playlistEnd);
  6588. if (fragIndex !== -1) {
  6589. dateRange.tagAnchor = details.fragments[fragIndex].ref;
  6590. break;
  6591. }
  6592. }
  6593. }
  6594. }
  6595. function findFragmentWithStartDate(details, startDateTime, programDateTimes, index, endTime) {
  6596. const pdtFragment = programDateTimes[index];
  6597. if (pdtFragment) {
  6598. const pdtStart = pdtFragment.programDateTime;
  6599. if (startDateTime >= pdtStart || index === 0) {
  6600. var _programDateTimes;
  6601. const durationBetweenPdt = (((_programDateTimes = programDateTimes[index + 1]) == null ? void 0 : _programDateTimes.start) || endTime) - pdtFragment.start;
  6602. if (startDateTime <= pdtStart + durationBetweenPdt * 1e3) {
  6603. const startIndex = programDateTimes[index].sn - details.startSN;
  6604. const fragments = details.fragments;
  6605. if (fragments.length > programDateTimes.length) {
  6606. const endSegment = programDateTimes[index + 1] || fragments[fragments.length - 1];
  6607. const endIndex = endSegment.sn - details.startSN;
  6608. for (let i = endIndex; i > startIndex; i--) {
  6609. const fragStartDateTime = fragments[i].programDateTime;
  6610. if (startDateTime >= fragStartDateTime && startDateTime < fragStartDateTime + fragments[i].duration * 1e3) {
  6611. return i;
  6612. }
  6613. }
  6614. }
  6615. return startIndex;
  6616. }
  6617. }
  6618. }
  6619. return -1;
  6620. }
  6621. function parseKey(keyTagAttributes, baseurl, parsed) {
  6622. var _keyAttrs$METHOD, _keyAttrs$KEYFORMAT;
  6623. const keyAttrs = new AttrList(keyTagAttributes, parsed);
  6624. const decryptmethod = (_keyAttrs$METHOD = keyAttrs.METHOD) != null ? _keyAttrs$METHOD : "";
  6625. const decrypturi = keyAttrs.URI;
  6626. const decryptiv = keyAttrs.hexadecimalInteger("IV");
  6627. const decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;
  6628. const decryptkeyformat = (_keyAttrs$KEYFORMAT = keyAttrs.KEYFORMAT) != null ? _keyAttrs$KEYFORMAT : "identity";
  6629. if (decrypturi && keyAttrs.IV && !decryptiv) {
  6630. logger.error(`Invalid IV: ${keyAttrs.IV}`);
  6631. }
  6632. const resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : "";
  6633. const keyFormatVersions = (decryptkeyformatversions ? decryptkeyformatversions : "1").split("/").map(Number).filter(Number.isFinite);
  6634. return new LevelKey(decryptmethod, resolvedUri, decryptkeyformat, keyFormatVersions, decryptiv, keyAttrs.KEYID);
  6635. }
  6636. function parseStartTimeOffset(startAttributes) {
  6637. const startAttrs = new AttrList(startAttributes);
  6638. const startTimeOffset = startAttrs.decimalFloatingPoint("TIME-OFFSET");
  6639. if (isFiniteNumber(startTimeOffset)) {
  6640. return startTimeOffset;
  6641. }
  6642. return null;
  6643. }
  6644. function setCodecs(codecsAttributeValue, level) {
  6645. let codecs = (codecsAttributeValue || "").split(/[ ,]+/).filter((c) => c);
  6646. ["video", "audio", "text"].forEach((type) => {
  6647. const filtered = codecs.filter((codec) => isCodecType(codec, type));
  6648. if (filtered.length) {
  6649. level[`${type}Codec`] = filtered.map((c) => c.split("/")[0]).join(",");
  6650. codecs = codecs.filter((codec) => filtered.indexOf(codec) === -1);
  6651. }
  6652. });
  6653. level.unknownCodecs = codecs;
  6654. }
  6655. function assignCodec(media, groupItem, codecProperty) {
  6656. const codecValue = groupItem[codecProperty];
  6657. if (codecValue) {
  6658. media[codecProperty] = codecValue;
  6659. }
  6660. }
  6661. function backfillProgramDateTimes(fragments, firstPdtIndex) {
  6662. let fragPrev = fragments[firstPdtIndex];
  6663. for (let i = firstPdtIndex; i--; ) {
  6664. const frag = fragments[i];
  6665. if (!frag) {
  6666. return;
  6667. }
  6668. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1e3;
  6669. fragPrev = frag;
  6670. }
  6671. }
  6672. function assignProgramDateTime(frag, prevFrag, programDateTimes) {
  6673. if (frag.rawProgramDateTime) {
  6674. programDateTimes.push(frag);
  6675. } else if (prevFrag != null && prevFrag.programDateTime) {
  6676. frag.programDateTime = prevFrag.endProgramDateTime;
  6677. }
  6678. }
  6679. function setInitSegment(frag, mapAttrs, id, levelkeys) {
  6680. frag.relurl = mapAttrs.URI;
  6681. if (mapAttrs.BYTERANGE) {
  6682. frag.setByteRange(mapAttrs.BYTERANGE);
  6683. }
  6684. frag.level = id;
  6685. frag.sn = "initSegment";
  6686. if (levelkeys) {
  6687. frag.levelkeys = levelkeys;
  6688. }
  6689. frag.initSegment = null;
  6690. }
  6691. function setFragLevelKeys(frag, levelkeys, level) {
  6692. frag.levelkeys = levelkeys;
  6693. const {
  6694. encryptedFragments
  6695. } = level;
  6696. if ((!encryptedFragments.length || encryptedFragments[encryptedFragments.length - 1].levelkeys !== levelkeys) && Object.keys(levelkeys).some((format2) => levelkeys[format2].isCommonEncryption)) {
  6697. encryptedFragments.push(frag);
  6698. }
  6699. }
  6700. function assignMultipleMediaPlaylistTagOccuranceError(level, tag, result) {
  6701. level.playlistParsingError = new Error(`#EXT-X-${tag} must not appear more than once (${result[0]})`);
  6702. }
  6703. function assignMustAppearBeforeSegmentsError(level, tag, result) {
  6704. level.playlistParsingError = new Error(`#EXT-X-${tag} must appear before the first Media Segment (${result[0]})`);
  6705. }
  6706. function updateFromToPTS(fragFrom, fragTo) {
  6707. const fragToPTS = fragTo.startPTS;
  6708. if (isFiniteNumber(fragToPTS)) {
  6709. let duration = 0;
  6710. let frag;
  6711. if (fragTo.sn > fragFrom.sn) {
  6712. duration = fragToPTS - fragFrom.start;
  6713. frag = fragFrom;
  6714. } else {
  6715. duration = fragFrom.start - fragToPTS;
  6716. frag = fragTo;
  6717. }
  6718. if (frag.duration !== duration) {
  6719. frag.setDuration(duration);
  6720. }
  6721. } else if (fragTo.sn > fragFrom.sn) {
  6722. const contiguous = fragFrom.cc === fragTo.cc;
  6723. if (contiguous && fragFrom.minEndPTS) {
  6724. fragTo.setStart(fragFrom.start + (fragFrom.minEndPTS - fragFrom.start));
  6725. } else {
  6726. fragTo.setStart(fragFrom.start + fragFrom.duration);
  6727. }
  6728. } else {
  6729. fragTo.setStart(Math.max(fragFrom.start - fragTo.duration, 0));
  6730. }
  6731. }
  6732. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  6733. const parsedMediaDuration = endPTS - startPTS;
  6734. if (parsedMediaDuration <= 0) {
  6735. logger.warn("Fragment should have a positive duration", frag);
  6736. endPTS = startPTS + frag.duration;
  6737. endDTS = startDTS + frag.duration;
  6738. }
  6739. let maxStartPTS = startPTS;
  6740. let minEndPTS = endPTS;
  6741. const fragStartPts = frag.startPTS;
  6742. const fragEndPts = frag.endPTS;
  6743. if (isFiniteNumber(fragStartPts)) {
  6744. const deltaPTS = Math.abs(fragStartPts - startPTS);
  6745. if (!isFiniteNumber(frag.deltaPTS)) {
  6746. frag.deltaPTS = deltaPTS;
  6747. } else {
  6748. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  6749. }
  6750. maxStartPTS = Math.max(startPTS, fragStartPts);
  6751. startPTS = Math.min(startPTS, fragStartPts);
  6752. startDTS = Math.min(startDTS, frag.startDTS);
  6753. minEndPTS = Math.min(endPTS, fragEndPts);
  6754. endPTS = Math.max(endPTS, fragEndPts);
  6755. endDTS = Math.max(endDTS, frag.endDTS);
  6756. }
  6757. const drift = startPTS - frag.start;
  6758. if (frag.start !== 0) {
  6759. frag.setStart(startPTS);
  6760. }
  6761. frag.setDuration(endPTS - frag.start);
  6762. frag.startPTS = startPTS;
  6763. frag.maxStartPTS = maxStartPTS;
  6764. frag.startDTS = startDTS;
  6765. frag.endPTS = endPTS;
  6766. frag.minEndPTS = minEndPTS;
  6767. frag.endDTS = endDTS;
  6768. const sn = frag.sn;
  6769. if (!details || sn < details.startSN || sn > details.endSN) {
  6770. return 0;
  6771. }
  6772. let i;
  6773. const fragIdx = sn - details.startSN;
  6774. const fragments = details.fragments;
  6775. fragments[fragIdx] = frag;
  6776. for (i = fragIdx; i > 0; i--) {
  6777. updateFromToPTS(fragments[i], fragments[i - 1]);
  6778. }
  6779. for (i = fragIdx; i < fragments.length - 1; i++) {
  6780. updateFromToPTS(fragments[i], fragments[i + 1]);
  6781. }
  6782. if (details.fragmentHint) {
  6783. updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
  6784. }
  6785. details.PTSKnown = details.alignedSliding = true;
  6786. return drift;
  6787. }
  6788. function mergeDetails(oldDetails, newDetails) {
  6789. if (oldDetails === newDetails) {
  6790. return;
  6791. }
  6792. let currentInitSegment = null;
  6793. const oldFragments = oldDetails.fragments;
  6794. for (let i = oldFragments.length - 1; i >= 0; i--) {
  6795. const oldInit = oldFragments[i].initSegment;
  6796. if (oldInit) {
  6797. currentInitSegment = oldInit;
  6798. break;
  6799. }
  6800. }
  6801. if (oldDetails.fragmentHint) {
  6802. delete oldDetails.fragmentHint.endPTS;
  6803. }
  6804. let PTSFrag;
  6805. mapFragmentIntersection(oldDetails, newDetails, (oldFrag, newFrag, newFragIndex, newFragments2) => {
  6806. if ((!newDetails.startCC || newDetails.skippedSegments) && newFrag.cc !== oldFrag.cc) {
  6807. const ccOffset = oldFrag.cc - newFrag.cc;
  6808. for (let i = newFragIndex; i < newFragments2.length; i++) {
  6809. newFragments2[i].cc += ccOffset;
  6810. }
  6811. newDetails.endCC = newFragments2[newFragments2.length - 1].cc;
  6812. }
  6813. if (isFiniteNumber(oldFrag.startPTS) && isFiniteNumber(oldFrag.endPTS)) {
  6814. newFrag.setStart(newFrag.startPTS = oldFrag.startPTS);
  6815. newFrag.startDTS = oldFrag.startDTS;
  6816. newFrag.maxStartPTS = oldFrag.maxStartPTS;
  6817. newFrag.endPTS = oldFrag.endPTS;
  6818. newFrag.endDTS = oldFrag.endDTS;
  6819. newFrag.minEndPTS = oldFrag.minEndPTS;
  6820. newFrag.setDuration(oldFrag.endPTS - oldFrag.startPTS);
  6821. if (newFrag.duration) {
  6822. PTSFrag = newFrag;
  6823. }
  6824. newDetails.PTSKnown = newDetails.alignedSliding = true;
  6825. }
  6826. if (oldFrag.hasStreams) {
  6827. newFrag.elementaryStreams = oldFrag.elementaryStreams;
  6828. }
  6829. newFrag.loader = oldFrag.loader;
  6830. if (oldFrag.hasStats) {
  6831. newFrag.stats = oldFrag.stats;
  6832. }
  6833. if (oldFrag.initSegment) {
  6834. newFrag.initSegment = oldFrag.initSegment;
  6835. currentInitSegment = oldFrag.initSegment;
  6836. }
  6837. });
  6838. const newFragments = newDetails.fragments;
  6839. const fragmentsToCheck = newDetails.fragmentHint ? newFragments.concat(newDetails.fragmentHint) : newFragments;
  6840. if (currentInitSegment) {
  6841. fragmentsToCheck.forEach((frag) => {
  6842. var _currentInitSegment;
  6843. if (frag && (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) == null ? void 0 : _currentInitSegment.relurl))) {
  6844. frag.initSegment = currentInitSegment;
  6845. }
  6846. });
  6847. }
  6848. if (newDetails.skippedSegments) {
  6849. newDetails.deltaUpdateFailed = newFragments.some((frag) => !frag);
  6850. if (newDetails.deltaUpdateFailed) {
  6851. logger.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");
  6852. for (let i = newDetails.skippedSegments; i--; ) {
  6853. newFragments.shift();
  6854. }
  6855. newDetails.startSN = newFragments[0].sn;
  6856. } else {
  6857. if (newDetails.canSkipDateRanges) {
  6858. newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails);
  6859. }
  6860. const programDateTimes = oldDetails.fragments.filter((frag) => frag.rawProgramDateTime);
  6861. if (oldDetails.hasProgramDateTime && !newDetails.hasProgramDateTime) {
  6862. for (let i = 1; i < fragmentsToCheck.length; i++) {
  6863. if (fragmentsToCheck[i].programDateTime === null) {
  6864. assignProgramDateTime(fragmentsToCheck[i], fragmentsToCheck[i - 1], programDateTimes);
  6865. }
  6866. }
  6867. }
  6868. mapDateRanges(programDateTimes, newDetails);
  6869. }
  6870. newDetails.endCC = newFragments[newFragments.length - 1].cc;
  6871. }
  6872. if (!newDetails.startCC) {
  6873. var _fragPriorToNewStart$;
  6874. const fragPriorToNewStart = getFragmentWithSN(oldDetails, newDetails.startSN - 1);
  6875. newDetails.startCC = (_fragPriorToNewStart$ = fragPriorToNewStart == null ? void 0 : fragPriorToNewStart.cc) != null ? _fragPriorToNewStart$ : newFragments[0].cc;
  6876. }
  6877. mapPartIntersection(oldDetails.partList, newDetails.partList, (oldPart, newPart) => {
  6878. newPart.elementaryStreams = oldPart.elementaryStreams;
  6879. newPart.stats = oldPart.stats;
  6880. });
  6881. if (PTSFrag) {
  6882. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  6883. } else {
  6884. adjustSliding(oldDetails, newDetails);
  6885. }
  6886. if (newFragments.length) {
  6887. newDetails.totalduration = newDetails.edge - newFragments[0].start;
  6888. }
  6889. newDetails.driftStartTime = oldDetails.driftStartTime;
  6890. newDetails.driftStart = oldDetails.driftStart;
  6891. const advancedDateTime = newDetails.advancedDateTime;
  6892. if (newDetails.advanced && advancedDateTime) {
  6893. const edge = newDetails.edge;
  6894. if (!newDetails.driftStart) {
  6895. newDetails.driftStartTime = advancedDateTime;
  6896. newDetails.driftStart = edge;
  6897. }
  6898. newDetails.driftEndTime = advancedDateTime;
  6899. newDetails.driftEnd = edge;
  6900. } else {
  6901. newDetails.driftEndTime = oldDetails.driftEndTime;
  6902. newDetails.driftEnd = oldDetails.driftEnd;
  6903. newDetails.advancedDateTime = oldDetails.advancedDateTime;
  6904. }
  6905. if (newDetails.requestScheduled === -1) {
  6906. newDetails.requestScheduled = oldDetails.requestScheduled;
  6907. }
  6908. }
  6909. function mergeDateRanges(oldDateRanges, newDetails) {
  6910. const {
  6911. dateRanges: deltaDateRanges,
  6912. recentlyRemovedDateranges
  6913. } = newDetails;
  6914. const dateRanges = _extends({}, oldDateRanges);
  6915. if (recentlyRemovedDateranges) {
  6916. recentlyRemovedDateranges.forEach((id) => {
  6917. delete dateRanges[id];
  6918. });
  6919. }
  6920. const mergeIds = Object.keys(dateRanges);
  6921. const mergeCount = mergeIds.length;
  6922. if (mergeCount) {
  6923. Object.keys(deltaDateRanges).forEach((id) => {
  6924. const mergedDateRange = dateRanges[id];
  6925. const dateRange = new DateRange(deltaDateRanges[id].attr, mergedDateRange);
  6926. if (dateRange.isValid) {
  6927. dateRanges[id] = dateRange;
  6928. if (!mergedDateRange) {
  6929. dateRange.tagOrder += mergeCount;
  6930. }
  6931. } else {
  6932. logger.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${stringify(deltaDateRanges[id].attr)}"`);
  6933. }
  6934. });
  6935. }
  6936. return dateRanges;
  6937. }
  6938. function mapPartIntersection(oldParts, newParts, intersectionFn) {
  6939. if (oldParts && newParts) {
  6940. let delta = 0;
  6941. for (let i = 0, len = oldParts.length; i <= len; i++) {
  6942. const oldPart = oldParts[i];
  6943. const newPart = newParts[i + delta];
  6944. if (oldPart && newPart && oldPart.index === newPart.index && oldPart.fragment.sn === newPart.fragment.sn) {
  6945. intersectionFn(oldPart, newPart);
  6946. } else {
  6947. delta--;
  6948. }
  6949. }
  6950. }
  6951. }
  6952. function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
  6953. const skippedSegments = newDetails.skippedSegments;
  6954. const start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
  6955. const end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
  6956. const delta = newDetails.startSN - oldDetails.startSN;
  6957. const newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  6958. const oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
  6959. for (let i = start; i <= end; i++) {
  6960. const oldFrag = oldFrags[delta + i];
  6961. let newFrag = newFrags[i];
  6962. if (skippedSegments && !newFrag && oldFrag) {
  6963. newFrag = newDetails.fragments[i] = oldFrag;
  6964. }
  6965. if (oldFrag && newFrag) {
  6966. intersectionFn(oldFrag, newFrag, i, newFrags);
  6967. if (oldFrag.url && oldFrag.url !== newFrag.url) {
  6968. newDetails.playlistParsingError = getSequenceError(`media sequence mismatch ${newFrag.sn}:`, oldDetails, newDetails, oldFrag, newFrag);
  6969. return;
  6970. } else if (oldFrag.cc !== newFrag.cc) {
  6971. newDetails.playlistParsingError = getSequenceError(`discontinuity sequence mismatch (${oldFrag.cc}!=${newFrag.cc})`, oldDetails, newDetails, oldFrag, newFrag);
  6972. return;
  6973. }
  6974. }
  6975. }
  6976. }
  6977. function getSequenceError(message, oldDetails, newDetails, oldFrag, newFrag) {
  6978. return new Error(`${message} ${newFrag.url}
  6979. Playlist starting @${oldDetails.startSN}
  6980. ${oldDetails.m3u8}
  6981. Playlist starting @${newDetails.startSN}
  6982. ${newDetails.m3u8}`);
  6983. }
  6984. function adjustSliding(oldDetails, newDetails, matchingStableVariantOrRendition = true) {
  6985. const delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
  6986. const oldFragments = oldDetails.fragments;
  6987. const advancedOrStable = delta >= 0;
  6988. let sliding = 0;
  6989. if (advancedOrStable && delta < oldFragments.length) {
  6990. sliding = oldFragments[delta].start;
  6991. } else if (advancedOrStable && newDetails.startSN === oldDetails.endSN + 1) {
  6992. sliding = oldDetails.fragmentEnd;
  6993. } else if (advancedOrStable && matchingStableVariantOrRendition) {
  6994. sliding = oldDetails.fragmentStart + delta * newDetails.levelTargetDuration;
  6995. } else if (!newDetails.skippedSegments && newDetails.fragmentStart === 0) {
  6996. sliding = oldDetails.fragmentStart;
  6997. } else {
  6998. return;
  6999. }
  7000. addSliding(newDetails, sliding);
  7001. }
  7002. function addSliding(details, sliding) {
  7003. if (sliding) {
  7004. const fragments = details.fragments;
  7005. for (let i = details.skippedSegments; i < fragments.length; i++) {
  7006. fragments[i].addStart(sliding);
  7007. }
  7008. if (details.fragmentHint) {
  7009. details.fragmentHint.addStart(sliding);
  7010. }
  7011. }
  7012. }
  7013. function computeReloadInterval(newDetails, distanceToLiveEdgeMs = Infinity) {
  7014. let reloadInterval = 1e3 * newDetails.targetduration;
  7015. if (newDetails.updated) {
  7016. const fragments = newDetails.fragments;
  7017. const liveEdgeMaxTargetDurations = 4;
  7018. if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) {
  7019. const lastSegmentDuration = fragments[fragments.length - 1].duration * 1e3;
  7020. if (lastSegmentDuration < reloadInterval) {
  7021. reloadInterval = lastSegmentDuration;
  7022. }
  7023. }
  7024. } else {
  7025. reloadInterval /= 2;
  7026. }
  7027. return Math.round(reloadInterval);
  7028. }
  7029. function getFragmentWithSN(details, sn, fragCurrent) {
  7030. if (!details) {
  7031. return null;
  7032. }
  7033. let fragment = details.fragments[sn - details.startSN];
  7034. if (fragment) {
  7035. return fragment;
  7036. }
  7037. fragment = details.fragmentHint;
  7038. if (fragment && fragment.sn === sn) {
  7039. return fragment;
  7040. }
  7041. if (sn < details.startSN && fragCurrent && fragCurrent.sn === sn) {
  7042. return fragCurrent;
  7043. }
  7044. return null;
  7045. }
  7046. function getPartWith(details, sn, partIndex) {
  7047. if (!details) {
  7048. return null;
  7049. }
  7050. return findPart(details.partList, sn, partIndex);
  7051. }
  7052. function findPart(partList, sn, partIndex) {
  7053. if (partList) {
  7054. for (let i = partList.length; i--; ) {
  7055. const part = partList[i];
  7056. if (part.index === partIndex && part.fragment.sn === sn) {
  7057. return part;
  7058. }
  7059. }
  7060. }
  7061. return null;
  7062. }
  7063. function reassignFragmentLevelIndexes(levels) {
  7064. levels.forEach((level, index) => {
  7065. var _level$details;
  7066. (_level$details = level.details) == null ? void 0 : _level$details.fragments.forEach((fragment) => {
  7067. fragment.level = index;
  7068. if (fragment.initSegment) {
  7069. fragment.initSegment.level = index;
  7070. }
  7071. });
  7072. });
  7073. }
  7074. function findFirstFragWithCC(fragments, cc) {
  7075. for (let i = 0, len = fragments.length; i < len; i++) {
  7076. var _fragments$i;
  7077. if (((_fragments$i = fragments[i]) == null ? void 0 : _fragments$i.cc) === cc) {
  7078. return fragments[i];
  7079. }
  7080. }
  7081. return null;
  7082. }
  7083. function shouldAlignOnDiscontinuities(refDetails, details) {
  7084. if (refDetails) {
  7085. if (details.startCC < refDetails.endCC && details.endCC > refDetails.startCC) {
  7086. return true;
  7087. }
  7088. }
  7089. return false;
  7090. }
  7091. function adjustFragmentStart(frag, sliding) {
  7092. if (frag) {
  7093. const start = frag.start + sliding;
  7094. frag.start = frag.startPTS = start;
  7095. frag.endPTS = start + frag.duration;
  7096. }
  7097. }
  7098. function adjustSlidingStart(sliding, details) {
  7099. const fragments = details.fragments;
  7100. for (let i = 0, len = fragments.length; i < len; i++) {
  7101. adjustFragmentStart(fragments[i], sliding);
  7102. }
  7103. if (details.fragmentHint) {
  7104. adjustFragmentStart(details.fragmentHint, sliding);
  7105. }
  7106. details.alignedSliding = true;
  7107. }
  7108. function alignStream(switchDetails, details) {
  7109. if (!switchDetails) {
  7110. return;
  7111. }
  7112. alignDiscontinuities(details, switchDetails);
  7113. if (!details.alignedSliding && switchDetails) {
  7114. alignMediaPlaylistByPDT(details, switchDetails);
  7115. }
  7116. if (!details.alignedSliding && switchDetails && !details.skippedSegments) {
  7117. adjustSliding(switchDetails, details, false);
  7118. }
  7119. }
  7120. function alignDiscontinuities(details, refDetails) {
  7121. if (!shouldAlignOnDiscontinuities(refDetails, details)) {
  7122. return;
  7123. }
  7124. const targetCC = Math.min(refDetails.endCC, details.endCC);
  7125. const refFrag = findFirstFragWithCC(refDetails.fragments, targetCC);
  7126. const frag = findFirstFragWithCC(details.fragments, targetCC);
  7127. if (!refFrag || !frag) {
  7128. return;
  7129. }
  7130. logger.log(`Aligning playlist at start of dicontinuity sequence ${targetCC}`);
  7131. const delta = refFrag.start - frag.start;
  7132. adjustSlidingStart(delta, details);
  7133. }
  7134. function alignMediaPlaylistByPDT(details, refDetails) {
  7135. if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
  7136. return;
  7137. }
  7138. const fragments = details.fragments;
  7139. const refFragments = refDetails.fragments;
  7140. if (!fragments.length || !refFragments.length) {
  7141. return;
  7142. }
  7143. let refFrag;
  7144. let frag;
  7145. const targetCC = Math.min(refDetails.endCC, details.endCC);
  7146. if (refDetails.startCC < targetCC && details.startCC < targetCC) {
  7147. refFrag = findFirstFragWithCC(refFragments, targetCC);
  7148. frag = findFirstFragWithCC(fragments, targetCC);
  7149. }
  7150. if (!refFrag || !frag) {
  7151. refFrag = refFragments[Math.floor(refFragments.length / 2)];
  7152. frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.floor(fragments.length / 2)];
  7153. }
  7154. const refPDT = refFrag.programDateTime;
  7155. const targetPDT = frag.programDateTime;
  7156. if (!refPDT || !targetPDT) {
  7157. return;
  7158. }
  7159. const delta = (targetPDT - refPDT) / 1e3 - (frag.start - refFrag.start);
  7160. adjustSlidingStart(delta, details);
  7161. }
  7162. var TimeRanges = {
  7163. toString: function(r) {
  7164. let log = "";
  7165. const len = r.length;
  7166. for (let i = 0; i < len; i++) {
  7167. log += `[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;
  7168. }
  7169. return log;
  7170. }
  7171. };
  7172. var State = {
  7173. STOPPED: "STOPPED",
  7174. IDLE: "IDLE",
  7175. KEY_LOADING: "KEY_LOADING",
  7176. FRAG_LOADING: "FRAG_LOADING",
  7177. FRAG_LOADING_WAITING_RETRY: "FRAG_LOADING_WAITING_RETRY",
  7178. WAITING_TRACK: "WAITING_TRACK",
  7179. PARSING: "PARSING",
  7180. PARSED: "PARSED",
  7181. ENDED: "ENDED",
  7182. ERROR: "ERROR",
  7183. WAITING_INIT_PTS: "WAITING_INIT_PTS",
  7184. WAITING_LEVEL: "WAITING_LEVEL"
  7185. };
  7186. var BaseStreamController = class extends TaskLoop {
  7187. constructor(hls, fragmentTracker, keyLoader, logPrefix, playlistType) {
  7188. super(logPrefix, hls.logger);
  7189. this.hls = void 0;
  7190. this.fragPrevious = null;
  7191. this.fragCurrent = null;
  7192. this.fragmentTracker = void 0;
  7193. this.transmuxer = null;
  7194. this._state = State.STOPPED;
  7195. this.playlistType = void 0;
  7196. this.media = null;
  7197. this.mediaBuffer = null;
  7198. this.config = void 0;
  7199. this.bitrateTest = false;
  7200. this.lastCurrentTime = 0;
  7201. this.nextLoadPosition = 0;
  7202. this.startPosition = 0;
  7203. this.startTimeOffset = null;
  7204. this.retryDate = 0;
  7205. this.levels = null;
  7206. this.fragmentLoader = void 0;
  7207. this.keyLoader = void 0;
  7208. this.levelLastLoaded = null;
  7209. this.startFragRequested = false;
  7210. this.decrypter = void 0;
  7211. this.initPTS = [];
  7212. this.buffering = true;
  7213. this.loadingParts = false;
  7214. this.loopSn = void 0;
  7215. this.onMediaSeeking = () => {
  7216. const {
  7217. config,
  7218. fragCurrent,
  7219. media,
  7220. mediaBuffer,
  7221. state
  7222. } = this;
  7223. const currentTime = media ? media.currentTime : 0;
  7224. const bufferInfo = BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config.maxBufferHole);
  7225. const noFowardBuffer = !bufferInfo.len;
  7226. this.log(`Media seeking to ${isFiniteNumber(currentTime) ? currentTime.toFixed(3) : currentTime}, state: ${state}, ${noFowardBuffer ? "out of" : "in"} buffer`);
  7227. if (this.state === State.ENDED) {
  7228. this.resetLoadingState();
  7229. } else if (fragCurrent) {
  7230. const tolerance = config.maxFragLookUpTolerance;
  7231. const fragStartOffset = fragCurrent.start - tolerance;
  7232. const fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  7233. if (noFowardBuffer || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) {
  7234. const pastFragment = currentTime > fragEndOffset;
  7235. if (currentTime < fragStartOffset || pastFragment) {
  7236. if (pastFragment && fragCurrent.loader) {
  7237. this.log(`Cancelling fragment load for seek (sn: ${fragCurrent.sn})`);
  7238. fragCurrent.abortRequests();
  7239. this.resetLoadingState();
  7240. }
  7241. this.fragPrevious = null;
  7242. }
  7243. }
  7244. }
  7245. if (media) {
  7246. this.fragmentTracker.removeFragmentsInRange(currentTime, Infinity, this.playlistType, true);
  7247. const lastCurrentTime = this.lastCurrentTime;
  7248. if (currentTime > lastCurrentTime) {
  7249. this.lastCurrentTime = currentTime;
  7250. }
  7251. if (!this.loadingParts) {
  7252. const bufferEnd = Math.max(bufferInfo.end, currentTime);
  7253. const shouldLoadParts = this.shouldLoadParts(this.getLevelDetails(), bufferEnd);
  7254. if (shouldLoadParts) {
  7255. this.log(`LL-Part loading ON after seeking to ${currentTime.toFixed(2)} with buffer @${bufferEnd.toFixed(2)}`);
  7256. this.loadingParts = shouldLoadParts;
  7257. }
  7258. }
  7259. }
  7260. if (!this.hls.hasEnoughToStart) {
  7261. this.log(`Setting ${noFowardBuffer ? "startPosition" : "nextLoadPosition"} to ${currentTime} for seek without enough to start`);
  7262. this.nextLoadPosition = currentTime;
  7263. if (noFowardBuffer) {
  7264. this.startPosition = currentTime;
  7265. }
  7266. }
  7267. this.tickImmediate();
  7268. };
  7269. this.onMediaEnded = () => {
  7270. this.log(`setting startPosition to 0 because media ended`);
  7271. this.startPosition = this.lastCurrentTime = 0;
  7272. };
  7273. this.playlistType = playlistType;
  7274. this.hls = hls;
  7275. this.fragmentLoader = new FragmentLoader(hls.config);
  7276. this.keyLoader = keyLoader;
  7277. this.fragmentTracker = fragmentTracker;
  7278. this.config = hls.config;
  7279. this.decrypter = new Decrypter(hls.config);
  7280. }
  7281. registerListeners() {
  7282. const {
  7283. hls
  7284. } = this;
  7285. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  7286. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  7287. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  7288. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  7289. hls.on(Events.ERROR, this.onError, this);
  7290. }
  7291. unregisterListeners() {
  7292. const {
  7293. hls
  7294. } = this;
  7295. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  7296. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  7297. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  7298. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  7299. hls.off(Events.ERROR, this.onError, this);
  7300. }
  7301. doTick() {
  7302. this.onTickEnd();
  7303. }
  7304. onTickEnd() {
  7305. }
  7306. startLoad(startPosition) {
  7307. }
  7308. stopLoad() {
  7309. if (this.state === State.STOPPED) {
  7310. return;
  7311. }
  7312. this.fragmentLoader.abort();
  7313. this.keyLoader.abort(this.playlistType);
  7314. const frag = this.fragCurrent;
  7315. if (frag != null && frag.loader) {
  7316. frag.abortRequests();
  7317. this.fragmentTracker.removeFragment(frag);
  7318. }
  7319. this.resetTransmuxer();
  7320. this.fragCurrent = null;
  7321. this.fragPrevious = null;
  7322. this.clearInterval();
  7323. this.clearNextTick();
  7324. this.state = State.STOPPED;
  7325. }
  7326. get startPositionValue() {
  7327. const {
  7328. nextLoadPosition,
  7329. startPosition
  7330. } = this;
  7331. if (startPosition === -1 && nextLoadPosition) {
  7332. return nextLoadPosition;
  7333. }
  7334. return startPosition;
  7335. }
  7336. get bufferingEnabled() {
  7337. return this.buffering;
  7338. }
  7339. pauseBuffering() {
  7340. this.buffering = false;
  7341. }
  7342. resumeBuffering() {
  7343. this.buffering = true;
  7344. }
  7345. get inFlightFrag() {
  7346. return {
  7347. frag: this.fragCurrent,
  7348. state: this.state
  7349. };
  7350. }
  7351. _streamEnded(bufferInfo, levelDetails) {
  7352. if (levelDetails.live || !this.media) {
  7353. return false;
  7354. }
  7355. const bufferEnd = bufferInfo.end || 0;
  7356. const timelineStart = this.config.timelineOffset || 0;
  7357. if (bufferEnd <= timelineStart) {
  7358. return false;
  7359. }
  7360. const bufferedRanges = bufferInfo.buffered;
  7361. if (this.config.maxBufferHole && bufferedRanges && bufferedRanges.length > 1) {
  7362. bufferInfo = BufferHelper.bufferedInfo(bufferedRanges, bufferInfo.start, 0);
  7363. }
  7364. const nextStart = bufferInfo.nextStart;
  7365. const hasSecondBufferedRange = nextStart && nextStart > timelineStart && nextStart < levelDetails.edge;
  7366. if (hasSecondBufferedRange) {
  7367. return false;
  7368. }
  7369. if (this.media.currentTime < bufferInfo.start) {
  7370. return false;
  7371. }
  7372. const partList = levelDetails.partList;
  7373. if (partList != null && partList.length) {
  7374. const lastPart = partList[partList.length - 1];
  7375. const lastPartBuffered = BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2);
  7376. return lastPartBuffered;
  7377. }
  7378. const playlistType = levelDetails.fragments[levelDetails.fragments.length - 1].type;
  7379. return this.fragmentTracker.isEndListAppended(playlistType);
  7380. }
  7381. getLevelDetails() {
  7382. if (this.levels && this.levelLastLoaded !== null) {
  7383. var _this$levelLastLoaded;
  7384. return (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details;
  7385. }
  7386. }
  7387. get timelineOffset() {
  7388. const configuredTimelineOffset = this.config.timelineOffset;
  7389. if (configuredTimelineOffset) {
  7390. var _this$getLevelDetails;
  7391. return ((_this$getLevelDetails = this.getLevelDetails()) == null ? void 0 : _this$getLevelDetails.appliedTimelineOffset) || configuredTimelineOffset;
  7392. }
  7393. return 0;
  7394. }
  7395. onMediaAttached(event, data) {
  7396. const media = this.media = this.mediaBuffer = data.media;
  7397. media.removeEventListener("seeking", this.onMediaSeeking);
  7398. media.removeEventListener("ended", this.onMediaEnded);
  7399. media.addEventListener("seeking", this.onMediaSeeking);
  7400. media.addEventListener("ended", this.onMediaEnded);
  7401. const config = this.config;
  7402. if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
  7403. this.startLoad(config.startPosition);
  7404. }
  7405. }
  7406. onMediaDetaching(event, data) {
  7407. const transferringMedia = !!data.transferMedia;
  7408. const media = this.media;
  7409. if (media === null) {
  7410. return;
  7411. }
  7412. if (media.ended) {
  7413. this.log("MSE detaching and video ended, reset startPosition");
  7414. this.startPosition = this.lastCurrentTime = 0;
  7415. }
  7416. media.removeEventListener("seeking", this.onMediaSeeking);
  7417. media.removeEventListener("ended", this.onMediaEnded);
  7418. if (this.keyLoader && !transferringMedia) {
  7419. this.keyLoader.detach();
  7420. }
  7421. this.media = this.mediaBuffer = null;
  7422. this.loopSn = void 0;
  7423. if (transferringMedia) {
  7424. this.resetLoadingState();
  7425. this.resetTransmuxer();
  7426. return;
  7427. }
  7428. this.loadingParts = false;
  7429. this.fragmentTracker.removeAllFragments();
  7430. this.stopLoad();
  7431. }
  7432. onManifestLoading() {
  7433. this.initPTS = [];
  7434. this.levels = this.levelLastLoaded = this.fragCurrent = null;
  7435. this.lastCurrentTime = this.startPosition = 0;
  7436. this.startFragRequested = false;
  7437. }
  7438. onError(event, data) {
  7439. }
  7440. onManifestLoaded(event, data) {
  7441. this.startTimeOffset = data.startTimeOffset;
  7442. }
  7443. onHandlerDestroying() {
  7444. this.stopLoad();
  7445. if (this.transmuxer) {
  7446. this.transmuxer.destroy();
  7447. this.transmuxer = null;
  7448. }
  7449. super.onHandlerDestroying();
  7450. this.hls = this.onMediaSeeking = this.onMediaEnded = null;
  7451. }
  7452. onHandlerDestroyed() {
  7453. this.state = State.STOPPED;
  7454. if (this.fragmentLoader) {
  7455. this.fragmentLoader.destroy();
  7456. }
  7457. if (this.keyLoader) {
  7458. this.keyLoader.destroy();
  7459. }
  7460. if (this.decrypter) {
  7461. this.decrypter.destroy();
  7462. }
  7463. this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null;
  7464. super.onHandlerDestroyed();
  7465. }
  7466. loadFragment(frag, level, targetBufferTime) {
  7467. this.startFragRequested = true;
  7468. this._loadFragForPlayback(frag, level, targetBufferTime);
  7469. }
  7470. _loadFragForPlayback(fragment, level, targetBufferTime) {
  7471. const progressCallback = (data) => {
  7472. const frag = data.frag;
  7473. if (this.fragContextChanged(frag)) {
  7474. this.warn(`${frag.type} sn: ${frag.sn}${data.part ? " part: " + data.part.index : ""} of ${this.fragInfo(frag, false, data.part)}) was dropped during download.`);
  7475. this.fragmentTracker.removeFragment(frag);
  7476. return;
  7477. }
  7478. frag.stats.chunkCount++;
  7479. this._handleFragmentLoadProgress(data);
  7480. };
  7481. this._doFragLoad(fragment, level, targetBufferTime, progressCallback).then((data) => {
  7482. if (!data) {
  7483. return;
  7484. }
  7485. const state = this.state;
  7486. const frag = data.frag;
  7487. if (this.fragContextChanged(frag)) {
  7488. if (state === State.FRAG_LOADING || !this.fragCurrent && state === State.PARSING) {
  7489. this.fragmentTracker.removeFragment(frag);
  7490. this.state = State.IDLE;
  7491. }
  7492. return;
  7493. }
  7494. if ("payload" in data) {
  7495. this.log(`Loaded ${frag.type} sn: ${frag.sn} of ${this.playlistLabel()} ${frag.level}`);
  7496. this.hls.trigger(Events.FRAG_LOADED, data);
  7497. }
  7498. this._handleFragmentLoadComplete(data);
  7499. }).catch((reason) => {
  7500. if (this.state === State.STOPPED || this.state === State.ERROR) {
  7501. return;
  7502. }
  7503. this.warn(`Frag error: ${(reason == null ? void 0 : reason.message) || reason}`);
  7504. this.resetFragmentLoading(fragment);
  7505. });
  7506. }
  7507. clearTrackerIfNeeded(frag) {
  7508. var _this$mediaBuffer;
  7509. const {
  7510. fragmentTracker
  7511. } = this;
  7512. const fragState = fragmentTracker.getState(frag);
  7513. if (fragState === FragmentState.APPENDING) {
  7514. const playlistType = frag.type;
  7515. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  7516. const minForwardBufferLength = Math.max(frag.duration, bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength);
  7517. const backtrackFragment = this.backtrackFragment;
  7518. const backtracked = backtrackFragment ? frag.sn - backtrackFragment.sn : 0;
  7519. if (backtracked === 1 || this.reduceMaxBufferLength(minForwardBufferLength, frag.duration)) {
  7520. fragmentTracker.removeFragment(frag);
  7521. }
  7522. } else if (((_this$mediaBuffer = this.mediaBuffer) == null ? void 0 : _this$mediaBuffer.buffered.length) === 0) {
  7523. fragmentTracker.removeAllFragments();
  7524. } else if (fragmentTracker.hasParts(frag.type)) {
  7525. fragmentTracker.detectPartialFragments({
  7526. frag,
  7527. part: null,
  7528. stats: frag.stats,
  7529. id: frag.type
  7530. });
  7531. if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {
  7532. fragmentTracker.removeFragment(frag);
  7533. }
  7534. }
  7535. }
  7536. checkLiveUpdate(details) {
  7537. if (details.updated && !details.live) {
  7538. const lastFragment = details.fragments[details.fragments.length - 1];
  7539. this.fragmentTracker.detectPartialFragments({
  7540. frag: lastFragment,
  7541. part: null,
  7542. stats: lastFragment.stats,
  7543. id: lastFragment.type
  7544. });
  7545. }
  7546. if (!details.fragments[0]) {
  7547. details.deltaUpdateFailed = true;
  7548. }
  7549. }
  7550. waitForLive(levelInfo) {
  7551. const details = levelInfo.details;
  7552. return (details == null ? void 0 : details.live) && details.type !== "EVENT" && (this.levelLastLoaded !== levelInfo || details.expired);
  7553. }
  7554. flushMainBuffer(startOffset, endOffset, type = null) {
  7555. if (!(startOffset - endOffset)) {
  7556. return;
  7557. }
  7558. const flushScope = {
  7559. startOffset,
  7560. endOffset,
  7561. type
  7562. };
  7563. this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);
  7564. }
  7565. _loadInitSegment(fragment, level) {
  7566. this._doFragLoad(fragment, level).then((data) => {
  7567. const frag = data == null ? void 0 : data.frag;
  7568. if (!frag || this.fragContextChanged(frag) || !this.levels) {
  7569. throw new Error("init load aborted");
  7570. }
  7571. return data;
  7572. }).then((data) => {
  7573. const {
  7574. hls
  7575. } = this;
  7576. const {
  7577. frag,
  7578. payload
  7579. } = data;
  7580. const decryptData = frag.decryptdata;
  7581. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
  7582. const startTime = self.performance.now();
  7583. return this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch((err) => {
  7584. hls.trigger(Events.ERROR, {
  7585. type: ErrorTypes.MEDIA_ERROR,
  7586. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  7587. fatal: false,
  7588. error: err,
  7589. reason: err.message,
  7590. frag
  7591. });
  7592. throw err;
  7593. }).then((decryptedData) => {
  7594. const endTime = self.performance.now();
  7595. hls.trigger(Events.FRAG_DECRYPTED, {
  7596. frag,
  7597. payload: decryptedData,
  7598. stats: {
  7599. tstart: startTime,
  7600. tdecrypt: endTime
  7601. }
  7602. });
  7603. data.payload = decryptedData;
  7604. return this.completeInitSegmentLoad(data);
  7605. });
  7606. }
  7607. return this.completeInitSegmentLoad(data);
  7608. }).catch((reason) => {
  7609. if (this.state === State.STOPPED || this.state === State.ERROR) {
  7610. return;
  7611. }
  7612. this.warn(reason);
  7613. this.resetFragmentLoading(fragment);
  7614. });
  7615. }
  7616. completeInitSegmentLoad(data) {
  7617. const {
  7618. levels
  7619. } = this;
  7620. if (!levels) {
  7621. throw new Error("init load aborted, missing levels");
  7622. }
  7623. const stats = data.frag.stats;
  7624. if (this.state !== State.STOPPED) {
  7625. this.state = State.IDLE;
  7626. }
  7627. data.frag.data = new Uint8Array(data.payload);
  7628. stats.parsing.start = stats.buffering.start = self.performance.now();
  7629. stats.parsing.end = stats.buffering.end = self.performance.now();
  7630. this.tick();
  7631. }
  7632. fragContextChanged(frag) {
  7633. const {
  7634. fragCurrent
  7635. } = this;
  7636. return !frag || !fragCurrent || frag.sn !== fragCurrent.sn || frag.level !== fragCurrent.level;
  7637. }
  7638. fragBufferedComplete(frag, part) {
  7639. const media = this.mediaBuffer ? this.mediaBuffer : this.media;
  7640. 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)"})`);
  7641. if (isMediaFragment(frag)) {
  7642. var _this$levels;
  7643. if (frag.type !== PlaylistLevelType.SUBTITLE) {
  7644. const el = frag.elementaryStreams;
  7645. if (!Object.keys(el).some((type) => !!el[type])) {
  7646. this.state = State.IDLE;
  7647. return;
  7648. }
  7649. }
  7650. const level = (_this$levels = this.levels) == null ? void 0 : _this$levels[frag.level];
  7651. if (level != null && level.fragmentError) {
  7652. this.log(`Resetting level fragment error count of ${level.fragmentError} on frag buffered`);
  7653. level.fragmentError = 0;
  7654. }
  7655. }
  7656. this.state = State.IDLE;
  7657. }
  7658. _handleFragmentLoadComplete(fragLoadedEndData) {
  7659. const {
  7660. transmuxer
  7661. } = this;
  7662. if (!transmuxer) {
  7663. return;
  7664. }
  7665. const {
  7666. frag,
  7667. part,
  7668. partsLoaded
  7669. } = fragLoadedEndData;
  7670. const complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some((fragLoaded) => !fragLoaded);
  7671. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
  7672. transmuxer.flush(chunkMeta);
  7673. }
  7674. _handleFragmentLoadProgress(frag) {
  7675. }
  7676. _doFragLoad(frag, level, targetBufferTime = null, progressCallback) {
  7677. var _frag$decryptdata;
  7678. this.fragCurrent = frag;
  7679. const details = level == null ? void 0 : level.details;
  7680. if (!this.levels || !details) {
  7681. throw new Error(`frag load aborted, missing level${details ? "" : " detail"}s`);
  7682. }
  7683. let keyLoadingPromise = null;
  7684. if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) != null && _frag$decryptdata.key)) {
  7685. this.log(`Loading key for ${frag.sn} of [${details.startSN}-${details.endSN}], ${this.playlistLabel()} ${frag.level}`);
  7686. this.state = State.KEY_LOADING;
  7687. this.fragCurrent = frag;
  7688. keyLoadingPromise = this.keyLoader.load(frag).then((keyLoadedData) => {
  7689. if (!this.fragContextChanged(keyLoadedData.frag)) {
  7690. this.hls.trigger(Events.KEY_LOADED, keyLoadedData);
  7691. if (this.state === State.KEY_LOADING) {
  7692. this.state = State.IDLE;
  7693. }
  7694. return keyLoadedData;
  7695. }
  7696. });
  7697. this.hls.trigger(Events.KEY_LOADING, {
  7698. frag
  7699. });
  7700. if (this.fragCurrent === null) {
  7701. keyLoadingPromise = Promise.reject(new Error(`frag load aborted, context changed in KEY_LOADING`));
  7702. }
  7703. } else if (!frag.encrypted) {
  7704. keyLoadingPromise = this.keyLoader.loadClear(frag, details.encryptedFragments, this.startFragRequested);
  7705. if (keyLoadingPromise) {
  7706. this.log(`[eme] blocking frag load until media-keys acquired`);
  7707. }
  7708. }
  7709. const fragPrevious = this.fragPrevious;
  7710. if (isMediaFragment(frag) && (!fragPrevious || frag.sn !== fragPrevious.sn)) {
  7711. const shouldLoadParts = this.shouldLoadParts(level.details, frag.end);
  7712. if (shouldLoadParts !== this.loadingParts) {
  7713. this.log(`LL-Part loading ${shouldLoadParts ? "ON" : "OFF"} loading sn ${fragPrevious == null ? void 0 : fragPrevious.sn}->${frag.sn}`);
  7714. this.loadingParts = shouldLoadParts;
  7715. }
  7716. }
  7717. targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
  7718. if (this.loadingParts && isMediaFragment(frag)) {
  7719. const partList = details.partList;
  7720. if (partList && progressCallback) {
  7721. if (targetBufferTime > frag.end && details.fragmentHint) {
  7722. frag = details.fragmentHint;
  7723. }
  7724. const partIndex = this.getNextPart(partList, frag, targetBufferTime);
  7725. if (partIndex > -1) {
  7726. const part = partList[partIndex];
  7727. frag = this.fragCurrent = part.fragment;
  7728. 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))}`);
  7729. this.nextLoadPosition = part.start + part.duration;
  7730. this.state = State.FRAG_LOADING;
  7731. let _result;
  7732. if (keyLoadingPromise) {
  7733. _result = keyLoadingPromise.then((keyLoadedData) => {
  7734. if (!keyLoadedData || this.fragContextChanged(keyLoadedData.frag)) {
  7735. return null;
  7736. }
  7737. return this.doFragPartsLoad(frag, part, level, progressCallback);
  7738. }).catch((error) => this.handleFragLoadError(error));
  7739. } else {
  7740. _result = this.doFragPartsLoad(frag, part, level, progressCallback).catch((error) => this.handleFragLoadError(error));
  7741. }
  7742. this.hls.trigger(Events.FRAG_LOADING, {
  7743. frag,
  7744. part,
  7745. targetBufferTime
  7746. });
  7747. if (this.fragCurrent === null) {
  7748. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING parts`));
  7749. }
  7750. return _result;
  7751. } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
  7752. return Promise.resolve(null);
  7753. }
  7754. }
  7755. }
  7756. if (isMediaFragment(frag) && this.loadingParts) {
  7757. this.log(`LL-Part loading OFF after next part miss @${targetBufferTime.toFixed(2)}`);
  7758. this.loadingParts = false;
  7759. } else if (!frag.url) {
  7760. return Promise.resolve(null);
  7761. }
  7762. 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))}`);
  7763. if (isFiniteNumber(frag.sn) && !this.bitrateTest) {
  7764. this.nextLoadPosition = frag.start + frag.duration;
  7765. }
  7766. this.state = State.FRAG_LOADING;
  7767. const dataOnProgress = this.config.progressive;
  7768. let result;
  7769. if (dataOnProgress && keyLoadingPromise) {
  7770. result = keyLoadingPromise.then((keyLoadedData) => {
  7771. if (!keyLoadedData || this.fragContextChanged(keyLoadedData == null ? void 0 : keyLoadedData.frag)) {
  7772. return null;
  7773. }
  7774. return this.fragmentLoader.load(frag, progressCallback);
  7775. }).catch((error) => this.handleFragLoadError(error));
  7776. } else {
  7777. result = Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : void 0), keyLoadingPromise]).then(([fragLoadedData]) => {
  7778. if (!dataOnProgress && fragLoadedData && progressCallback) {
  7779. progressCallback(fragLoadedData);
  7780. }
  7781. return fragLoadedData;
  7782. }).catch((error) => this.handleFragLoadError(error));
  7783. }
  7784. this.hls.trigger(Events.FRAG_LOADING, {
  7785. frag,
  7786. targetBufferTime
  7787. });
  7788. if (this.fragCurrent === null) {
  7789. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING`));
  7790. }
  7791. return result;
  7792. }
  7793. doFragPartsLoad(frag, fromPart, level, progressCallback) {
  7794. return new Promise((resolve, reject) => {
  7795. var _level$details;
  7796. const partsLoaded = [];
  7797. const initialPartList = (_level$details = level.details) == null ? void 0 : _level$details.partList;
  7798. const loadPart = (part) => {
  7799. this.fragmentLoader.loadPart(frag, part, progressCallback).then((partLoadedData) => {
  7800. partsLoaded[part.index] = partLoadedData;
  7801. const loadedPart = partLoadedData.part;
  7802. this.hls.trigger(Events.FRAG_LOADED, partLoadedData);
  7803. const nextPart = getPartWith(level.details, frag.sn, part.index + 1) || findPart(initialPartList, frag.sn, part.index + 1);
  7804. if (nextPart) {
  7805. loadPart(nextPart);
  7806. } else {
  7807. return resolve({
  7808. frag,
  7809. part: loadedPart,
  7810. partsLoaded
  7811. });
  7812. }
  7813. }).catch(reject);
  7814. };
  7815. loadPart(fromPart);
  7816. });
  7817. }
  7818. handleFragLoadError(error) {
  7819. if ("data" in error) {
  7820. const data = error.data;
  7821. if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) {
  7822. this.handleFragLoadAborted(data.frag, data.part);
  7823. } else {
  7824. this.hls.trigger(Events.ERROR, data);
  7825. }
  7826. } else {
  7827. this.hls.trigger(Events.ERROR, {
  7828. type: ErrorTypes.OTHER_ERROR,
  7829. details: ErrorDetails.INTERNAL_EXCEPTION,
  7830. err: error,
  7831. error,
  7832. fatal: true
  7833. });
  7834. }
  7835. return null;
  7836. }
  7837. _handleTransmuxerFlush(chunkMeta) {
  7838. const context = this.getCurrentContext(chunkMeta);
  7839. if (!context || this.state !== State.PARSING) {
  7840. if (!this.fragCurrent && this.state !== State.STOPPED && this.state !== State.ERROR) {
  7841. this.state = State.IDLE;
  7842. }
  7843. return;
  7844. }
  7845. const {
  7846. frag,
  7847. part,
  7848. level
  7849. } = context;
  7850. const now2 = self.performance.now();
  7851. frag.stats.parsing.end = now2;
  7852. if (part) {
  7853. part.stats.parsing.end = now2;
  7854. }
  7855. const levelDetails = this.getLevelDetails();
  7856. const loadingPartsAtEdge = levelDetails && frag.sn > levelDetails.endSN;
  7857. const shouldLoadParts = loadingPartsAtEdge || this.shouldLoadParts(levelDetails, frag.end);
  7858. if (shouldLoadParts !== this.loadingParts) {
  7859. this.log(`LL-Part loading ${shouldLoadParts ? "ON" : "OFF"} after parsing segment ending @${frag.end.toFixed(2)}`);
  7860. this.loadingParts = shouldLoadParts;
  7861. }
  7862. this.updateLevelTiming(frag, part, level, chunkMeta.partial);
  7863. }
  7864. shouldLoadParts(details, bufferEnd) {
  7865. if (this.config.lowLatencyMode) {
  7866. if (!details) {
  7867. return this.loadingParts;
  7868. }
  7869. if (details != null && details.partList) {
  7870. var _details$fragmentHint;
  7871. const firstPart = details.partList[0];
  7872. const safePartStart = firstPart.end + (((_details$fragmentHint = details.fragmentHint) == null ? void 0 : _details$fragmentHint.duration) || 0);
  7873. if (bufferEnd >= safePartStart) {
  7874. var _this$media;
  7875. const playhead = this.hls.hasEnoughToStart ? ((_this$media = this.media) == null ? void 0 : _this$media.currentTime) || this.lastCurrentTime : this.getLoadPosition();
  7876. if (playhead > firstPart.start - firstPart.fragment.duration) {
  7877. return true;
  7878. }
  7879. }
  7880. }
  7881. }
  7882. return false;
  7883. }
  7884. getCurrentContext(chunkMeta) {
  7885. const {
  7886. levels,
  7887. fragCurrent
  7888. } = this;
  7889. const {
  7890. level: levelIndex,
  7891. sn,
  7892. part: partIndex
  7893. } = chunkMeta;
  7894. if (!(levels != null && levels[levelIndex])) {
  7895. this.warn(`Levels object was unset while buffering fragment ${sn} of ${this.playlistLabel()} ${levelIndex}. The current chunk will not be buffered.`);
  7896. return null;
  7897. }
  7898. const level = levels[levelIndex];
  7899. const levelDetails = level.details;
  7900. const part = partIndex > -1 ? getPartWith(levelDetails, sn, partIndex) : null;
  7901. const frag = part ? part.fragment : getFragmentWithSN(levelDetails, sn, fragCurrent);
  7902. if (!frag) {
  7903. return null;
  7904. }
  7905. if (fragCurrent && fragCurrent !== frag) {
  7906. frag.stats = fragCurrent.stats;
  7907. }
  7908. return {
  7909. frag,
  7910. part,
  7911. level
  7912. };
  7913. }
  7914. bufferFragmentData(data, frag, part, chunkMeta, noBacktracking) {
  7915. var _buffer;
  7916. if (!data || this.state !== State.PARSING) {
  7917. return;
  7918. }
  7919. const {
  7920. data1,
  7921. data2
  7922. } = data;
  7923. let buffer = data1;
  7924. if (data1 && data2) {
  7925. buffer = appendUint8Array(data1, data2);
  7926. }
  7927. if (!((_buffer = buffer) != null && _buffer.length)) {
  7928. return;
  7929. }
  7930. const offsetTimestamp = this.initPTS[frag.cc];
  7931. const offset = offsetTimestamp ? -offsetTimestamp.baseTime / offsetTimestamp.timescale : void 0;
  7932. const segment = {
  7933. type: data.type,
  7934. frag,
  7935. part,
  7936. chunkMeta,
  7937. offset,
  7938. parent: frag.type,
  7939. data: buffer
  7940. };
  7941. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  7942. if (data.dropped && data.independent && !part) {
  7943. if (noBacktracking) {
  7944. return;
  7945. }
  7946. this.flushBufferGap(frag);
  7947. }
  7948. }
  7949. flushBufferGap(frag) {
  7950. const media = this.media;
  7951. if (!media) {
  7952. return;
  7953. }
  7954. if (!BufferHelper.isBuffered(media, media.currentTime)) {
  7955. this.flushMainBuffer(0, frag.start);
  7956. return;
  7957. }
  7958. const currentTime = media.currentTime;
  7959. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  7960. const fragDuration = frag.duration;
  7961. const segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
  7962. const start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
  7963. if (frag.start - start > segmentFraction) {
  7964. this.flushMainBuffer(start, frag.start);
  7965. }
  7966. }
  7967. getFwdBufferInfo(bufferable, type) {
  7968. var _this$media2;
  7969. const pos = this.getLoadPosition();
  7970. if (!isFiniteNumber(pos)) {
  7971. return null;
  7972. }
  7973. const backwardSeek = this.lastCurrentTime > pos;
  7974. const maxBufferHole = backwardSeek || (_this$media2 = this.media) != null && _this$media2.paused ? 0 : this.config.maxBufferHole;
  7975. return this.getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole);
  7976. }
  7977. getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole) {
  7978. const bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);
  7979. if (bufferInfo.len === 0 && bufferInfo.nextStart !== void 0) {
  7980. const bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
  7981. if (bufferedFragAtPos && (bufferInfo.nextStart <= bufferedFragAtPos.end || bufferedFragAtPos.gap)) {
  7982. const gapDuration = Math.max(Math.min(bufferInfo.nextStart, bufferedFragAtPos.end) - pos, maxBufferHole);
  7983. return BufferHelper.bufferInfo(bufferable, pos, gapDuration);
  7984. }
  7985. }
  7986. return bufferInfo;
  7987. }
  7988. getMaxBufferLength(levelBitrate) {
  7989. const {
  7990. config
  7991. } = this;
  7992. let maxBufLen;
  7993. if (levelBitrate) {
  7994. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  7995. } else {
  7996. maxBufLen = config.maxBufferLength;
  7997. }
  7998. return Math.min(maxBufLen, config.maxMaxBufferLength);
  7999. }
  8000. reduceMaxBufferLength(threshold, fragDuration) {
  8001. const config = this.config;
  8002. const minLength = Math.max(Math.min(threshold - fragDuration, config.maxBufferLength), fragDuration);
  8003. const reducedLength = Math.max(threshold - fragDuration * 3, config.maxMaxBufferLength / 2, minLength);
  8004. if (reducedLength >= minLength) {
  8005. config.maxMaxBufferLength = reducedLength;
  8006. this.warn(`Reduce max buffer length to ${reducedLength}s`);
  8007. return true;
  8008. }
  8009. return false;
  8010. }
  8011. getAppendedFrag(position, playlistType = PlaylistLevelType.MAIN) {
  8012. var _this$fragmentTracker;
  8013. const fragOrPart = (_this$fragmentTracker = this.fragmentTracker) == null ? void 0 : _this$fragmentTracker.getAppendedFrag(position, playlistType);
  8014. if (fragOrPart && "fragment" in fragOrPart) {
  8015. return fragOrPart.fragment;
  8016. }
  8017. return fragOrPart;
  8018. }
  8019. getNextFragment(pos, levelDetails) {
  8020. const fragments = levelDetails.fragments;
  8021. const fragLen = fragments.length;
  8022. if (!fragLen) {
  8023. return null;
  8024. }
  8025. const {
  8026. config
  8027. } = this;
  8028. const start = fragments[0].start;
  8029. const canLoadParts = config.lowLatencyMode && !!levelDetails.partList;
  8030. let frag = null;
  8031. if (levelDetails.live) {
  8032. const initialLiveManifestSize = config.initialLiveManifestSize;
  8033. if (fragLen < initialLiveManifestSize) {
  8034. this.warn(`Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`);
  8035. return null;
  8036. }
  8037. if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1 || pos < start) {
  8038. var _frag;
  8039. if (canLoadParts && !this.loadingParts) {
  8040. this.log(`LL-Part loading ON for initial live fragment`);
  8041. this.loadingParts = true;
  8042. }
  8043. frag = this.getInitialLiveFragment(levelDetails);
  8044. const mainStart = this.hls.startPosition;
  8045. const liveSyncPosition = this.hls.liveSyncPosition;
  8046. const startPosition = frag ? (mainStart !== -1 && mainStart >= start ? mainStart : liveSyncPosition) || frag.start : pos;
  8047. 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}`);
  8048. this.startPosition = this.nextLoadPosition = startPosition;
  8049. }
  8050. } else if (pos <= start) {
  8051. frag = fragments[0];
  8052. }
  8053. if (!frag) {
  8054. const end = this.loadingParts ? levelDetails.partEnd : levelDetails.fragmentEnd;
  8055. frag = this.getFragmentAtPosition(pos, end, levelDetails);
  8056. }
  8057. let programFrag = this.filterReplacedPrimary(frag, levelDetails);
  8058. if (!programFrag && frag) {
  8059. const curSNIdx = frag.sn - levelDetails.startSN;
  8060. programFrag = this.filterReplacedPrimary(fragments[curSNIdx + 1] || null, levelDetails);
  8061. }
  8062. return this.mapToInitFragWhenRequired(programFrag);
  8063. }
  8064. isLoopLoading(frag, targetBufferTime) {
  8065. const trackerState = this.fragmentTracker.getState(frag);
  8066. return (trackerState === FragmentState.OK || trackerState === FragmentState.PARTIAL && !!frag.gap) && this.nextLoadPosition > targetBufferTime;
  8067. }
  8068. getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, playlistType, maxBufLen) {
  8069. let nextFragment = null;
  8070. if (frag.gap) {
  8071. nextFragment = this.getNextFragment(this.nextLoadPosition, levelDetails);
  8072. if (nextFragment && !nextFragment.gap && bufferInfo.nextStart) {
  8073. const nextbufferInfo = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, bufferInfo.nextStart, playlistType, 0);
  8074. if (nextbufferInfo !== null && bufferInfo.len + nextbufferInfo.len >= maxBufLen) {
  8075. const sn = nextFragment.sn;
  8076. if (this.loopSn !== sn) {
  8077. this.log(`buffer full after gaps in "${playlistType}" playlist starting at sn: ${sn}`);
  8078. this.loopSn = sn;
  8079. }
  8080. return null;
  8081. }
  8082. }
  8083. }
  8084. this.loopSn = void 0;
  8085. return nextFragment;
  8086. }
  8087. get primaryPrefetch() {
  8088. if (interstitialsEnabled(this.hls.config)) {
  8089. var _this$hls$interstitia, _this$hls$interstitia2;
  8090. 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;
  8091. if (playingInterstitial) {
  8092. return true;
  8093. }
  8094. }
  8095. return false;
  8096. }
  8097. filterReplacedPrimary(frag, details) {
  8098. if (!frag) {
  8099. return frag;
  8100. }
  8101. if (interstitialsEnabled(this.hls.config) && frag.type !== PlaylistLevelType.SUBTITLE) {
  8102. const interstitials = this.hls.interstitialsManager;
  8103. const bufferingItem = interstitials == null ? void 0 : interstitials.bufferingItem;
  8104. if (bufferingItem) {
  8105. const bufferingInterstitial = bufferingItem.event;
  8106. if (bufferingInterstitial) {
  8107. if (bufferingInterstitial.appendInPlace || Math.abs(frag.start - bufferingItem.start) > 1 || bufferingItem.start === 0) {
  8108. return null;
  8109. }
  8110. } else {
  8111. if (frag.end <= bufferingItem.start && (details == null ? void 0 : details.live) === false) {
  8112. return null;
  8113. }
  8114. if (frag.start > bufferingItem.end && bufferingItem.nextEvent) {
  8115. if (bufferingItem.nextEvent.appendInPlace || frag.start - bufferingItem.end > 1) {
  8116. return null;
  8117. }
  8118. }
  8119. }
  8120. }
  8121. const playerQueue = interstitials == null ? void 0 : interstitials.playerQueue;
  8122. if (playerQueue) {
  8123. for (let i = playerQueue.length; i--; ) {
  8124. const interstitial = playerQueue[i].interstitial;
  8125. if (interstitial.appendInPlace && frag.start >= interstitial.startTime && frag.end <= interstitial.resumeTime) {
  8126. return null;
  8127. }
  8128. }
  8129. }
  8130. }
  8131. return frag;
  8132. }
  8133. mapToInitFragWhenRequired(frag) {
  8134. if (frag != null && frag.initSegment && !(frag != null && frag.initSegment.data) && !this.bitrateTest) {
  8135. return frag.initSegment;
  8136. }
  8137. return frag;
  8138. }
  8139. getNextPart(partList, frag, targetBufferTime) {
  8140. let nextPart = -1;
  8141. let contiguous = false;
  8142. let independentAttrOmitted = true;
  8143. for (let i = 0, len = partList.length; i < len; i++) {
  8144. const part = partList[i];
  8145. independentAttrOmitted = independentAttrOmitted && !part.independent;
  8146. if (nextPart > -1 && targetBufferTime < part.start) {
  8147. break;
  8148. }
  8149. const loaded = part.loaded;
  8150. if (loaded) {
  8151. nextPart = -1;
  8152. } else if ((contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
  8153. nextPart = i;
  8154. }
  8155. contiguous = loaded;
  8156. }
  8157. return nextPart;
  8158. }
  8159. loadedEndOfParts(partList, targetBufferTime) {
  8160. const lastPart = partList[partList.length - 1];
  8161. return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
  8162. }
  8163. getInitialLiveFragment(levelDetails) {
  8164. const fragments = levelDetails.fragments;
  8165. const fragPrevious = this.fragPrevious;
  8166. let frag = null;
  8167. if (fragPrevious) {
  8168. if (levelDetails.hasProgramDateTime) {
  8169. this.log(`Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`);
  8170. frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
  8171. }
  8172. if (!frag) {
  8173. const targetSN = fragPrevious.sn + 1;
  8174. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  8175. const fragNext = fragments[targetSN - levelDetails.startSN];
  8176. if (fragPrevious.cc === fragNext.cc) {
  8177. frag = fragNext;
  8178. this.log(`Live playlist, switching playlist, load frag with next SN: ${frag.sn}`);
  8179. }
  8180. }
  8181. if (!frag) {
  8182. frag = findNearestWithCC(levelDetails, fragPrevious.cc, fragPrevious.end);
  8183. if (frag) {
  8184. this.log(`Live playlist, switching playlist, load frag with same CC: ${frag.sn}`);
  8185. }
  8186. }
  8187. }
  8188. } else {
  8189. const liveStart = this.hls.liveSyncPosition;
  8190. if (liveStart !== null) {
  8191. frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
  8192. }
  8193. }
  8194. return frag;
  8195. }
  8196. getFragmentAtPosition(bufferEnd, end, levelDetails) {
  8197. const {
  8198. config
  8199. } = this;
  8200. let {
  8201. fragPrevious
  8202. } = this;
  8203. let {
  8204. fragments,
  8205. endSN
  8206. } = levelDetails;
  8207. const {
  8208. fragmentHint
  8209. } = levelDetails;
  8210. const {
  8211. maxFragLookUpTolerance
  8212. } = config;
  8213. const partList = levelDetails.partList;
  8214. const loadingParts = !!(this.loadingParts && partList != null && partList.length && fragmentHint);
  8215. if (loadingParts && fragmentHint && !this.bitrateTest && partList[partList.length - 1].fragment.sn === fragmentHint.sn) {
  8216. fragments = fragments.concat(fragmentHint);
  8217. endSN = fragmentHint.sn;
  8218. }
  8219. let frag;
  8220. if (bufferEnd < end) {
  8221. var _this$media3;
  8222. const backwardSeek = bufferEnd < this.lastCurrentTime;
  8223. const lookupTolerance = backwardSeek || bufferEnd > end - maxFragLookUpTolerance || (_this$media3 = this.media) != null && _this$media3.paused || !this.startFragRequested ? 0 : maxFragLookUpTolerance;
  8224. frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);
  8225. } else {
  8226. frag = fragments[fragments.length - 1];
  8227. }
  8228. if (frag) {
  8229. const curSNIdx = frag.sn - levelDetails.startSN;
  8230. const fragState = this.fragmentTracker.getState(frag);
  8231. if (fragState === FragmentState.OK || fragState === FragmentState.PARTIAL && frag.gap) {
  8232. fragPrevious = frag;
  8233. }
  8234. if (fragPrevious && frag.sn === fragPrevious.sn && (!loadingParts || partList[0].fragment.sn > frag.sn || !levelDetails.live && !loadingParts)) {
  8235. const sameLevel = fragPrevious && frag.level === fragPrevious.level;
  8236. if (sameLevel) {
  8237. const nextFrag = fragments[curSNIdx + 1];
  8238. if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== FragmentState.OK) {
  8239. frag = nextFrag;
  8240. } else {
  8241. frag = null;
  8242. }
  8243. }
  8244. }
  8245. }
  8246. return frag;
  8247. }
  8248. alignPlaylists(details, previousDetails, switchDetails) {
  8249. const length = details.fragments.length;
  8250. if (!length) {
  8251. this.warn(`No fragments in live playlist`);
  8252. return 0;
  8253. }
  8254. const slidingStart = details.fragmentStart;
  8255. const firstLevelLoad = !previousDetails;
  8256. const aligned = details.alignedSliding && isFiniteNumber(slidingStart);
  8257. if (firstLevelLoad || !aligned && !slidingStart) {
  8258. alignStream(switchDetails, details);
  8259. const alignedSlidingStart = details.fragmentStart;
  8260. this.log(`Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${previousDetails ? previousDetails.startSN : "na"}->${details.startSN} fragments: ${length}`);
  8261. return alignedSlidingStart;
  8262. }
  8263. return slidingStart;
  8264. }
  8265. waitForCdnTuneIn(details) {
  8266. const advancePartLimit = 3;
  8267. return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
  8268. }
  8269. setStartPosition(details, sliding) {
  8270. let startPosition = this.startPosition;
  8271. if (startPosition < sliding) {
  8272. startPosition = -1;
  8273. }
  8274. const timelineOffset = this.timelineOffset;
  8275. if (startPosition === -1) {
  8276. const offsetInMultivariantPlaylist = this.startTimeOffset !== null;
  8277. const startTimeOffset = offsetInMultivariantPlaylist ? this.startTimeOffset : details.startTimeOffset;
  8278. if (startTimeOffset !== null && isFiniteNumber(startTimeOffset)) {
  8279. startPosition = sliding + startTimeOffset;
  8280. if (startTimeOffset < 0) {
  8281. startPosition += details.edge;
  8282. }
  8283. startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
  8284. this.log(`Setting startPosition to ${startPosition} for start time offset ${startTimeOffset} found in ${offsetInMultivariantPlaylist ? "multivariant" : "media"} playlist`);
  8285. this.startPosition = startPosition;
  8286. } else if (details.live) {
  8287. startPosition = this.hls.liveSyncPosition || sliding;
  8288. this.log(`Setting startPosition to -1 to start at live edge ${startPosition}`);
  8289. this.startPosition = -1;
  8290. } else {
  8291. this.log(`setting startPosition to 0 by default`);
  8292. this.startPosition = startPosition = 0;
  8293. }
  8294. this.lastCurrentTime = startPosition + timelineOffset;
  8295. }
  8296. this.nextLoadPosition = startPosition + timelineOffset;
  8297. }
  8298. getLoadPosition() {
  8299. var _this$hls;
  8300. const {
  8301. media
  8302. } = this;
  8303. let pos = 0;
  8304. if ((_this$hls = this.hls) != null && _this$hls.hasEnoughToStart && media) {
  8305. pos = media.currentTime;
  8306. } else if (this.nextLoadPosition >= 0) {
  8307. pos = this.nextLoadPosition;
  8308. }
  8309. return pos;
  8310. }
  8311. handleFragLoadAborted(frag, part) {
  8312. if (this.transmuxer && frag.type === this.playlistType && isMediaFragment(frag) && frag.stats.aborted) {
  8313. this.log(`Fragment ${frag.sn}${part ? " part " + part.index : ""} of ${this.playlistLabel()} ${frag.level} was aborted`);
  8314. this.resetFragmentLoading(frag);
  8315. }
  8316. }
  8317. resetFragmentLoading(frag) {
  8318. if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) {
  8319. this.state = State.IDLE;
  8320. }
  8321. }
  8322. onFragmentOrKeyLoadError(filterType, data) {
  8323. if (data.chunkMeta && !data.frag) {
  8324. const context = this.getCurrentContext(data.chunkMeta);
  8325. if (context) {
  8326. data.frag = context.frag;
  8327. }
  8328. }
  8329. const frag = data.frag;
  8330. if (!frag || frag.type !== filterType || !this.levels) {
  8331. return;
  8332. }
  8333. if (this.fragContextChanged(frag)) {
  8334. var _this$fragCurrent;
  8335. this.warn(`Frag load error must match current frag to retry ${frag.url} > ${(_this$fragCurrent = this.fragCurrent) == null ? void 0 : _this$fragCurrent.url}`);
  8336. return;
  8337. }
  8338. const gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;
  8339. if (gapTagEncountered) {
  8340. this.fragmentTracker.fragBuffered(frag, true);
  8341. }
  8342. const errorAction = data.errorAction;
  8343. const {
  8344. action,
  8345. flags,
  8346. retryCount = 0,
  8347. retryConfig
  8348. } = errorAction || {};
  8349. const couldRetry = !!errorAction && !!retryConfig;
  8350. const retry = couldRetry && action === NetworkErrorAction.RetryRequest;
  8351. const noAlternate = couldRetry && !errorAction.resolved && flags === ErrorActionFlags.MoveAllAlternatesMatchingHost;
  8352. if (!retry && noAlternate && isMediaFragment(frag) && !frag.endList) {
  8353. this.resetFragmentErrors(filterType);
  8354. this.treatAsGap(frag);
  8355. errorAction.resolved = true;
  8356. } else if ((retry || noAlternate) && retryCount < retryConfig.maxNumRetry) {
  8357. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  8358. const delay = getRetryDelay(retryConfig, retryCount);
  8359. this.warn(`Fragment ${frag.sn} of ${filterType} ${frag.level} errored with ${data.details}, retrying loading ${retryCount + 1}/${retryConfig.maxNumRetry} in ${delay}ms`);
  8360. errorAction.resolved = true;
  8361. this.retryDate = self.performance.now() + delay;
  8362. this.state = State.FRAG_LOADING_WAITING_RETRY;
  8363. } else if (retryConfig && errorAction) {
  8364. this.resetFragmentErrors(filterType);
  8365. if (retryCount < retryConfig.maxNumRetry) {
  8366. if (!gapTagEncountered && action !== NetworkErrorAction.RemoveAlternatePermanently) {
  8367. errorAction.resolved = true;
  8368. }
  8369. } else {
  8370. this.warn(`${data.details} reached or exceeded max retry (${retryCount})`);
  8371. return;
  8372. }
  8373. } else if (action === NetworkErrorAction.SendAlternateToPenaltyBox) {
  8374. this.state = State.WAITING_LEVEL;
  8375. } else {
  8376. this.state = State.ERROR;
  8377. }
  8378. this.tickImmediate();
  8379. }
  8380. reduceLengthAndFlushBuffer(data) {
  8381. if (this.state === State.PARSING || this.state === State.PARSED) {
  8382. const frag = data.frag;
  8383. const playlistType = data.parent;
  8384. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  8385. const buffered = bufferedInfo && bufferedInfo.len > 0.5;
  8386. if (buffered) {
  8387. this.reduceMaxBufferLength(bufferedInfo.len, (frag == null ? void 0 : frag.duration) || 10);
  8388. }
  8389. const flushBuffer = !buffered;
  8390. if (flushBuffer) {
  8391. this.warn(`Buffer full error while media.currentTime is not buffered, flush ${playlistType} buffer`);
  8392. }
  8393. if (frag) {
  8394. this.fragmentTracker.removeFragment(frag);
  8395. this.nextLoadPosition = frag.start;
  8396. }
  8397. this.resetLoadingState();
  8398. return flushBuffer;
  8399. }
  8400. return false;
  8401. }
  8402. resetFragmentErrors(filterType) {
  8403. if (filterType === PlaylistLevelType.AUDIO) {
  8404. this.fragCurrent = null;
  8405. }
  8406. if (!this.hls.hasEnoughToStart) {
  8407. this.startFragRequested = false;
  8408. }
  8409. if (this.state !== State.STOPPED) {
  8410. this.state = State.IDLE;
  8411. }
  8412. }
  8413. afterBufferFlushed(media, bufferType, playlistType) {
  8414. if (!media) {
  8415. return;
  8416. }
  8417. const bufferedTimeRanges = BufferHelper.getBuffered(media);
  8418. this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
  8419. if (this.state === State.ENDED) {
  8420. this.resetLoadingState();
  8421. }
  8422. }
  8423. resetLoadingState() {
  8424. this.log("Reset loading state");
  8425. this.fragCurrent = null;
  8426. this.fragPrevious = null;
  8427. if (this.state !== State.STOPPED) {
  8428. this.state = State.IDLE;
  8429. }
  8430. }
  8431. resetStartWhenNotLoaded(level) {
  8432. if (!this.hls.hasEnoughToStart) {
  8433. this.startFragRequested = false;
  8434. const details = level ? level.details : null;
  8435. if (details != null && details.live) {
  8436. this.log(`resetting startPosition for live start`);
  8437. this.startPosition = -1;
  8438. this.setStartPosition(details, details.fragmentStart);
  8439. this.resetLoadingState();
  8440. } else {
  8441. this.nextLoadPosition = this.startPosition;
  8442. }
  8443. }
  8444. }
  8445. resetWhenMissingContext(chunkMeta) {
  8446. this.warn(`The loading context changed while buffering fragment ${chunkMeta.sn} of ${this.playlistLabel()} ${chunkMeta.level}. This chunk will not be buffered.`);
  8447. this.removeUnbufferedFrags();
  8448. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  8449. this.resetLoadingState();
  8450. }
  8451. removeUnbufferedFrags(start = 0) {
  8452. this.fragmentTracker.removeFragmentsInRange(start, Infinity, this.playlistType, false, true);
  8453. }
  8454. updateLevelTiming(frag, part, level, partial) {
  8455. const details = level.details;
  8456. if (!details) {
  8457. this.warn("level.details undefined");
  8458. return;
  8459. }
  8460. const parsed = Object.keys(frag.elementaryStreams).reduce((result, type) => {
  8461. const info = frag.elementaryStreams[type];
  8462. if (info) {
  8463. const parsedDuration = info.endPTS - info.startPTS;
  8464. if (parsedDuration <= 0) {
  8465. this.warn(`Could not parse fragment ${frag.sn} ${type} duration reliably (${parsedDuration})`);
  8466. return result || false;
  8467. }
  8468. const drift = partial ? 0 : updateFragPTSDTS(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
  8469. this.hls.trigger(Events.LEVEL_PTS_UPDATED, {
  8470. details,
  8471. level,
  8472. drift,
  8473. type,
  8474. frag,
  8475. start: info.startPTS,
  8476. end: info.endPTS
  8477. });
  8478. return true;
  8479. }
  8480. return result;
  8481. }, false);
  8482. if (!parsed) {
  8483. var _this$transmuxer;
  8484. if (level.fragmentError === 0) {
  8485. this.treatAsGap(frag, level);
  8486. }
  8487. if (((_this$transmuxer = this.transmuxer) == null ? void 0 : _this$transmuxer.error) === null) {
  8488. const error = new Error(`Found no media in fragment ${frag.sn} of ${this.playlistLabel()} ${frag.level} resetting transmuxer to fallback to playlist timing`);
  8489. this.warn(error.message);
  8490. this.hls.trigger(Events.ERROR, {
  8491. type: ErrorTypes.MEDIA_ERROR,
  8492. details: ErrorDetails.FRAG_PARSING_ERROR,
  8493. fatal: false,
  8494. error,
  8495. frag,
  8496. reason: `Found no media in msn ${frag.sn} of ${this.playlistLabel()} "${level.url}"`
  8497. });
  8498. if (!this.hls) {
  8499. return;
  8500. }
  8501. this.resetTransmuxer();
  8502. }
  8503. }
  8504. this.state = State.PARSED;
  8505. this.log(`Parsed ${frag.type} sn: ${frag.sn}${part ? " part: " + part.index : ""} of ${this.fragInfo(frag, false, part)})`);
  8506. this.hls.trigger(Events.FRAG_PARSED, {
  8507. frag,
  8508. part
  8509. });
  8510. }
  8511. playlistLabel() {
  8512. return this.playlistType === PlaylistLevelType.MAIN ? "level" : "track";
  8513. }
  8514. fragInfo(frag, pts = true, part) {
  8515. var _ref, _ref2;
  8516. 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") : ""}`;
  8517. }
  8518. treatAsGap(frag, level) {
  8519. if (level) {
  8520. level.fragmentError++;
  8521. }
  8522. frag.gap = true;
  8523. this.fragmentTracker.removeFragment(frag);
  8524. this.fragmentTracker.fragBuffered(frag, true);
  8525. }
  8526. resetTransmuxer() {
  8527. var _this$transmuxer2;
  8528. (_this$transmuxer2 = this.transmuxer) == null ? void 0 : _this$transmuxer2.reset();
  8529. }
  8530. recoverWorkerError(data) {
  8531. if (data.event === "demuxerWorker") {
  8532. this.fragmentTracker.removeAllFragments();
  8533. if (this.transmuxer) {
  8534. this.transmuxer.destroy();
  8535. this.transmuxer = null;
  8536. }
  8537. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  8538. this.resetLoadingState();
  8539. }
  8540. }
  8541. set state(nextState) {
  8542. const previousState = this._state;
  8543. if (previousState !== nextState) {
  8544. this._state = nextState;
  8545. this.log(`${previousState}->${nextState}`);
  8546. }
  8547. }
  8548. get state() {
  8549. return this._state;
  8550. }
  8551. };
  8552. function interstitialsEnabled(config) {
  8553. return !!config.interstitialsController && config.enableInterstitialPlayback !== false;
  8554. }
  8555. var ChunkCache = class {
  8556. constructor() {
  8557. this.chunks = [];
  8558. this.dataLength = 0;
  8559. }
  8560. push(chunk) {
  8561. this.chunks.push(chunk);
  8562. this.dataLength += chunk.length;
  8563. }
  8564. flush() {
  8565. const {
  8566. chunks,
  8567. dataLength
  8568. } = this;
  8569. let result;
  8570. if (!chunks.length) {
  8571. return new Uint8Array(0);
  8572. } else if (chunks.length === 1) {
  8573. result = chunks[0];
  8574. } else {
  8575. result = concatUint8Arrays(chunks, dataLength);
  8576. }
  8577. this.reset();
  8578. return result;
  8579. }
  8580. reset() {
  8581. this.chunks.length = 0;
  8582. this.dataLength = 0;
  8583. }
  8584. };
  8585. function concatUint8Arrays(chunks, dataLength) {
  8586. const result = new Uint8Array(dataLength);
  8587. let offset = 0;
  8588. for (let i = 0; i < chunks.length; i++) {
  8589. const chunk = chunks[i];
  8590. result.set(chunk, offset);
  8591. offset += chunk.length;
  8592. }
  8593. return result;
  8594. }
  8595. var eventemitter3 = { exports: {} };
  8596. var hasRequiredEventemitter3;
  8597. function requireEventemitter3() {
  8598. if (hasRequiredEventemitter3)
  8599. return eventemitter3.exports;
  8600. hasRequiredEventemitter3 = 1;
  8601. (function(module) {
  8602. var has = Object.prototype.hasOwnProperty, prefix = "~";
  8603. function Events2() {
  8604. }
  8605. if (Object.create) {
  8606. Events2.prototype = /* @__PURE__ */ Object.create(null);
  8607. if (!new Events2().__proto__)
  8608. prefix = false;
  8609. }
  8610. function EE(fn, context, once) {
  8611. this.fn = fn;
  8612. this.context = context;
  8613. this.once = once || false;
  8614. }
  8615. function addListener(emitter, event, fn, context, once) {
  8616. if (typeof fn !== "function") {
  8617. throw new TypeError("The listener must be a function");
  8618. }
  8619. var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
  8620. if (!emitter._events[evt])
  8621. emitter._events[evt] = listener, emitter._eventsCount++;
  8622. else if (!emitter._events[evt].fn)
  8623. emitter._events[evt].push(listener);
  8624. else
  8625. emitter._events[evt] = [emitter._events[evt], listener];
  8626. return emitter;
  8627. }
  8628. function clearEvent(emitter, evt) {
  8629. if (--emitter._eventsCount === 0)
  8630. emitter._events = new Events2();
  8631. else
  8632. delete emitter._events[evt];
  8633. }
  8634. function EventEmitter2() {
  8635. this._events = new Events2();
  8636. this._eventsCount = 0;
  8637. }
  8638. EventEmitter2.prototype.eventNames = function eventNames() {
  8639. var names = [], events, name;
  8640. if (this._eventsCount === 0)
  8641. return names;
  8642. for (name in events = this._events) {
  8643. if (has.call(events, name))
  8644. names.push(prefix ? name.slice(1) : name);
  8645. }
  8646. if (Object.getOwnPropertySymbols) {
  8647. return names.concat(Object.getOwnPropertySymbols(events));
  8648. }
  8649. return names;
  8650. };
  8651. EventEmitter2.prototype.listeners = function listeners(event) {
  8652. var evt = prefix ? prefix + event : event, handlers = this._events[evt];
  8653. if (!handlers)
  8654. return [];
  8655. if (handlers.fn)
  8656. return [handlers.fn];
  8657. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  8658. ee[i] = handlers[i].fn;
  8659. }
  8660. return ee;
  8661. };
  8662. EventEmitter2.prototype.listenerCount = function listenerCount(event) {
  8663. var evt = prefix ? prefix + event : event, listeners = this._events[evt];
  8664. if (!listeners)
  8665. return 0;
  8666. if (listeners.fn)
  8667. return 1;
  8668. return listeners.length;
  8669. };
  8670. EventEmitter2.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  8671. var evt = prefix ? prefix + event : event;
  8672. if (!this._events[evt])
  8673. return false;
  8674. var listeners = this._events[evt], len = arguments.length, args, i;
  8675. if (listeners.fn) {
  8676. if (listeners.once)
  8677. this.removeListener(event, listeners.fn, void 0, true);
  8678. switch (len) {
  8679. case 1:
  8680. return listeners.fn.call(listeners.context), true;
  8681. case 2:
  8682. return listeners.fn.call(listeners.context, a1), true;
  8683. case 3:
  8684. return listeners.fn.call(listeners.context, a1, a2), true;
  8685. case 4:
  8686. return listeners.fn.call(listeners.context, a1, a2, a3), true;
  8687. case 5:
  8688. return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  8689. case 6:
  8690. return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  8691. }
  8692. for (i = 1, args = new Array(len - 1); i < len; i++) {
  8693. args[i - 1] = arguments[i];
  8694. }
  8695. listeners.fn.apply(listeners.context, args);
  8696. } else {
  8697. var length = listeners.length, j;
  8698. for (i = 0; i < length; i++) {
  8699. if (listeners[i].once)
  8700. this.removeListener(event, listeners[i].fn, void 0, true);
  8701. switch (len) {
  8702. case 1:
  8703. listeners[i].fn.call(listeners[i].context);
  8704. break;
  8705. case 2:
  8706. listeners[i].fn.call(listeners[i].context, a1);
  8707. break;
  8708. case 3:
  8709. listeners[i].fn.call(listeners[i].context, a1, a2);
  8710. break;
  8711. case 4:
  8712. listeners[i].fn.call(listeners[i].context, a1, a2, a3);
  8713. break;
  8714. default:
  8715. if (!args)
  8716. for (j = 1, args = new Array(len - 1); j < len; j++) {
  8717. args[j - 1] = arguments[j];
  8718. }
  8719. listeners[i].fn.apply(listeners[i].context, args);
  8720. }
  8721. }
  8722. }
  8723. return true;
  8724. };
  8725. EventEmitter2.prototype.on = function on(event, fn, context) {
  8726. return addListener(this, event, fn, context, false);
  8727. };
  8728. EventEmitter2.prototype.once = function once(event, fn, context) {
  8729. return addListener(this, event, fn, context, true);
  8730. };
  8731. EventEmitter2.prototype.removeListener = function removeListener(event, fn, context, once) {
  8732. var evt = prefix ? prefix + event : event;
  8733. if (!this._events[evt])
  8734. return this;
  8735. if (!fn) {
  8736. clearEvent(this, evt);
  8737. return this;
  8738. }
  8739. var listeners = this._events[evt];
  8740. if (listeners.fn) {
  8741. if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
  8742. clearEvent(this, evt);
  8743. }
  8744. } else {
  8745. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  8746. if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
  8747. events.push(listeners[i]);
  8748. }
  8749. }
  8750. if (events.length)
  8751. this._events[evt] = events.length === 1 ? events[0] : events;
  8752. else
  8753. clearEvent(this, evt);
  8754. }
  8755. return this;
  8756. };
  8757. EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) {
  8758. var evt;
  8759. if (event) {
  8760. evt = prefix ? prefix + event : event;
  8761. if (this._events[evt])
  8762. clearEvent(this, evt);
  8763. } else {
  8764. this._events = new Events2();
  8765. this._eventsCount = 0;
  8766. }
  8767. return this;
  8768. };
  8769. EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
  8770. EventEmitter2.prototype.addListener = EventEmitter2.prototype.on;
  8771. EventEmitter2.prefixed = prefix;
  8772. EventEmitter2.EventEmitter = EventEmitter2;
  8773. {
  8774. module.exports = EventEmitter2;
  8775. }
  8776. })(eventemitter3);
  8777. return eventemitter3.exports;
  8778. }
  8779. var eventemitter3Exports = requireEventemitter3();
  8780. var EventEmitter = getDefaultExportFromCjs(eventemitter3Exports);
  8781. var version = "1.6.7";
  8782. var workerStore = {};
  8783. function hasUMDWorker() {
  8784. return typeof __HLS_WORKER_BUNDLE__ === "function";
  8785. }
  8786. function injectWorker() {
  8787. const workerContext = workerStore[version];
  8788. if (workerContext) {
  8789. workerContext.clientCount++;
  8790. return workerContext;
  8791. }
  8792. const blob = new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`], {
  8793. type: "text/javascript"
  8794. });
  8795. const objectURL = self.URL.createObjectURL(blob);
  8796. const worker = new self.Worker(objectURL);
  8797. const result = {
  8798. worker,
  8799. objectURL,
  8800. clientCount: 1
  8801. };
  8802. workerStore[version] = result;
  8803. return result;
  8804. }
  8805. function loadWorker(path) {
  8806. const workerContext = workerStore[path];
  8807. if (workerContext) {
  8808. workerContext.clientCount++;
  8809. return workerContext;
  8810. }
  8811. const scriptURL = new self.URL(path, self.location.href).href;
  8812. const worker = new self.Worker(scriptURL);
  8813. const result = {
  8814. worker,
  8815. scriptURL,
  8816. clientCount: 1
  8817. };
  8818. workerStore[path] = result;
  8819. return result;
  8820. }
  8821. function removeWorkerFromStore(path) {
  8822. const workerContext = workerStore[path || version];
  8823. if (workerContext) {
  8824. const clientCount = workerContext.clientCount--;
  8825. if (clientCount === 1) {
  8826. const {
  8827. worker,
  8828. objectURL
  8829. } = workerContext;
  8830. delete workerStore[path || version];
  8831. if (objectURL) {
  8832. self.URL.revokeObjectURL(objectURL);
  8833. }
  8834. worker.terminate();
  8835. }
  8836. }
  8837. }
  8838. function isId3Footer(data, offset) {
  8839. if (offset + 10 <= data.length) {
  8840. if (data[offset] === 51 && data[offset + 1] === 68 && data[offset + 2] === 73) {
  8841. if (data[offset + 3] < 255 && data[offset + 4] < 255) {
  8842. if (data[offset + 6] < 128 && data[offset + 7] < 128 && data[offset + 8] < 128 && data[offset + 9] < 128) {
  8843. return true;
  8844. }
  8845. }
  8846. }
  8847. }
  8848. return false;
  8849. }
  8850. function isId3Header(data, offset) {
  8851. if (offset + 10 <= data.length) {
  8852. if (data[offset] === 73 && data[offset + 1] === 68 && data[offset + 2] === 51) {
  8853. if (data[offset + 3] < 255 && data[offset + 4] < 255) {
  8854. if (data[offset + 6] < 128 && data[offset + 7] < 128 && data[offset + 8] < 128 && data[offset + 9] < 128) {
  8855. return true;
  8856. }
  8857. }
  8858. }
  8859. }
  8860. return false;
  8861. }
  8862. function readId3Size(data, offset) {
  8863. let size = 0;
  8864. size = (data[offset] & 127) << 21;
  8865. size |= (data[offset + 1] & 127) << 14;
  8866. size |= (data[offset + 2] & 127) << 7;
  8867. size |= data[offset + 3] & 127;
  8868. return size;
  8869. }
  8870. function getId3Data(data, offset) {
  8871. const front = offset;
  8872. let length = 0;
  8873. while (isId3Header(data, offset)) {
  8874. length += 10;
  8875. const size = readId3Size(data, offset + 6);
  8876. length += size;
  8877. if (isId3Footer(data, offset + 10)) {
  8878. length += 10;
  8879. }
  8880. offset += length;
  8881. }
  8882. if (length > 0) {
  8883. return data.subarray(front, front + length);
  8884. }
  8885. return void 0;
  8886. }
  8887. function getAudioConfig(observer, data, offset, manifestCodec) {
  8888. const adtsSamplingRates = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350];
  8889. const byte2 = data[offset + 2];
  8890. const adtsSamplingIndex = byte2 >> 2 & 15;
  8891. if (adtsSamplingIndex > 12) {
  8892. const error = new Error(`invalid ADTS sampling index:${adtsSamplingIndex}`);
  8893. observer.emit(Events.ERROR, Events.ERROR, {
  8894. type: ErrorTypes.MEDIA_ERROR,
  8895. details: ErrorDetails.FRAG_PARSING_ERROR,
  8896. fatal: true,
  8897. error,
  8898. reason: error.message
  8899. });
  8900. return;
  8901. }
  8902. const adtsObjectType = (byte2 >> 6 & 3) + 1;
  8903. const channelCount = data[offset + 3] >> 6 & 3 | (byte2 & 1) << 2;
  8904. const codec = "mp4a.40." + adtsObjectType;
  8905. const samplerate = adtsSamplingRates[adtsSamplingIndex];
  8906. let aacSampleIndex = adtsSamplingIndex;
  8907. if (adtsObjectType === 5 || adtsObjectType === 29) {
  8908. aacSampleIndex -= 3;
  8909. }
  8910. const config = [adtsObjectType << 3 | (aacSampleIndex & 14) >> 1, (aacSampleIndex & 1) << 7 | channelCount << 3];
  8911. logger.log(`manifest codec:${manifestCodec}, parsed codec:${codec}, channels:${channelCount}, rate:${samplerate} (ADTS object type:${adtsObjectType} sampling index:${adtsSamplingIndex})`);
  8912. return {
  8913. config,
  8914. samplerate,
  8915. channelCount,
  8916. codec,
  8917. parsedCodec: codec,
  8918. manifestCodec
  8919. };
  8920. }
  8921. function isHeaderPattern$1(data, offset) {
  8922. return data[offset] === 255 && (data[offset + 1] & 246) === 240;
  8923. }
  8924. function getHeaderLength(data, offset) {
  8925. return data[offset + 1] & 1 ? 7 : 9;
  8926. }
  8927. function getFullFrameLength(data, offset) {
  8928. return (data[offset + 3] & 3) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 224) >>> 5;
  8929. }
  8930. function canGetFrameLength(data, offset) {
  8931. return offset + 5 < data.length;
  8932. }
  8933. function isHeader$1(data, offset) {
  8934. return offset + 1 < data.length && isHeaderPattern$1(data, offset);
  8935. }
  8936. function canParse$1(data, offset) {
  8937. return canGetFrameLength(data, offset) && isHeaderPattern$1(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
  8938. }
  8939. function probe$1(data, offset) {
  8940. if (isHeader$1(data, offset)) {
  8941. const headerLength = getHeaderLength(data, offset);
  8942. if (offset + headerLength >= data.length) {
  8943. return false;
  8944. }
  8945. const frameLength = getFullFrameLength(data, offset);
  8946. if (frameLength <= headerLength) {
  8947. return false;
  8948. }
  8949. const newOffset = offset + frameLength;
  8950. return newOffset === data.length || isHeader$1(data, newOffset);
  8951. }
  8952. return false;
  8953. }
  8954. function initTrackConfig(track, observer, data, offset, audioCodec) {
  8955. if (!track.samplerate) {
  8956. const config = getAudioConfig(observer, data, offset, audioCodec);
  8957. if (!config) {
  8958. return;
  8959. }
  8960. _extends(track, config);
  8961. }
  8962. }
  8963. function getFrameDuration(samplerate) {
  8964. return 1024 * 9e4 / samplerate;
  8965. }
  8966. function parseFrameHeader(data, offset) {
  8967. const headerLength = getHeaderLength(data, offset);
  8968. if (offset + headerLength <= data.length) {
  8969. const frameLength = getFullFrameLength(data, offset) - headerLength;
  8970. if (frameLength > 0) {
  8971. return {
  8972. headerLength,
  8973. frameLength
  8974. };
  8975. }
  8976. }
  8977. }
  8978. function appendFrame$2(track, data, offset, pts, frameIndex) {
  8979. const frameDuration = getFrameDuration(track.samplerate);
  8980. const stamp = pts + frameIndex * frameDuration;
  8981. const header = parseFrameHeader(data, offset);
  8982. let unit;
  8983. if (header) {
  8984. const {
  8985. frameLength,
  8986. headerLength
  8987. } = header;
  8988. const _length = headerLength + frameLength;
  8989. const missing = Math.max(0, offset + _length - data.length);
  8990. if (missing) {
  8991. unit = new Uint8Array(_length - headerLength);
  8992. unit.set(data.subarray(offset + headerLength, data.length), 0);
  8993. } else {
  8994. unit = data.subarray(offset + headerLength, offset + _length);
  8995. }
  8996. const _sample = {
  8997. unit,
  8998. pts: stamp
  8999. };
  9000. if (!missing) {
  9001. track.samples.push(_sample);
  9002. }
  9003. return {
  9004. sample: _sample,
  9005. length: _length,
  9006. missing
  9007. };
  9008. }
  9009. const length = data.length - offset;
  9010. unit = new Uint8Array(length);
  9011. unit.set(data.subarray(offset, data.length), 0);
  9012. const sample = {
  9013. unit,
  9014. pts: stamp
  9015. };
  9016. return {
  9017. sample,
  9018. length,
  9019. missing: -1
  9020. };
  9021. }
  9022. function canParseId3(data, offset) {
  9023. return isId3Header(data, offset) && readId3Size(data, offset + 6) + 10 <= data.length - offset;
  9024. }
  9025. function toArrayBuffer(view2) {
  9026. if (view2 instanceof ArrayBuffer) {
  9027. return view2;
  9028. } else {
  9029. if (view2.byteOffset == 0 && view2.byteLength == view2.buffer.byteLength) {
  9030. return view2.buffer;
  9031. }
  9032. return new Uint8Array(view2).buffer;
  9033. }
  9034. }
  9035. function toUint8(data, offset = 0, length = Infinity) {
  9036. return view(data, offset, length, Uint8Array);
  9037. }
  9038. function view(data, offset, length, Type) {
  9039. const buffer = unsafeGetArrayBuffer(data);
  9040. let bytesPerElement = 1;
  9041. if ("BYTES_PER_ELEMENT" in Type) {
  9042. bytesPerElement = Type.BYTES_PER_ELEMENT;
  9043. }
  9044. const dataOffset = isArrayBufferView(data) ? data.byteOffset : 0;
  9045. const dataEnd = (dataOffset + data.byteLength) / bytesPerElement;
  9046. const rawStart = (dataOffset + offset) / bytesPerElement;
  9047. const start = Math.floor(Math.max(0, Math.min(rawStart, dataEnd)));
  9048. const end = Math.floor(Math.min(start + Math.max(length, 0), dataEnd));
  9049. return new Type(buffer, start, end - start);
  9050. }
  9051. function unsafeGetArrayBuffer(view2) {
  9052. if (view2 instanceof ArrayBuffer) {
  9053. return view2;
  9054. } else {
  9055. return view2.buffer;
  9056. }
  9057. }
  9058. function isArrayBufferView(obj) {
  9059. return obj && obj.buffer instanceof ArrayBuffer && obj.byteLength !== void 0 && obj.byteOffset !== void 0;
  9060. }
  9061. function decodeId3ImageFrame(frame) {
  9062. const metadataFrame = {
  9063. key: frame.type,
  9064. description: "",
  9065. data: "",
  9066. mimeType: null,
  9067. pictureType: null
  9068. };
  9069. const utf8Encoding = 3;
  9070. if (frame.size < 2) {
  9071. return void 0;
  9072. }
  9073. if (frame.data[0] !== utf8Encoding) {
  9074. console.log("Ignore frame with unrecognized character encoding");
  9075. return void 0;
  9076. }
  9077. const mimeTypeEndIndex = frame.data.subarray(1).indexOf(0);
  9078. if (mimeTypeEndIndex === -1) {
  9079. return void 0;
  9080. }
  9081. const mimeType = utf8ArrayToStr(toUint8(frame.data, 1, mimeTypeEndIndex));
  9082. const pictureType = frame.data[2 + mimeTypeEndIndex];
  9083. const descriptionEndIndex = frame.data.subarray(3 + mimeTypeEndIndex).indexOf(0);
  9084. if (descriptionEndIndex === -1) {
  9085. return void 0;
  9086. }
  9087. const description = utf8ArrayToStr(toUint8(frame.data, 3 + mimeTypeEndIndex, descriptionEndIndex));
  9088. let data;
  9089. if (mimeType === "-->") {
  9090. data = utf8ArrayToStr(toUint8(frame.data, 4 + mimeTypeEndIndex + descriptionEndIndex));
  9091. } else {
  9092. data = toArrayBuffer(frame.data.subarray(4 + mimeTypeEndIndex + descriptionEndIndex));
  9093. }
  9094. metadataFrame.mimeType = mimeType;
  9095. metadataFrame.pictureType = pictureType;
  9096. metadataFrame.description = description;
  9097. metadataFrame.data = data;
  9098. return metadataFrame;
  9099. }
  9100. function decodeId3PrivFrame(frame) {
  9101. if (frame.size < 2) {
  9102. return void 0;
  9103. }
  9104. const owner = utf8ArrayToStr(frame.data, true);
  9105. const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  9106. return {
  9107. key: frame.type,
  9108. info: owner,
  9109. data: privateData.buffer
  9110. };
  9111. }
  9112. function decodeId3TextFrame(frame) {
  9113. if (frame.size < 2) {
  9114. return void 0;
  9115. }
  9116. if (frame.type === "TXXX") {
  9117. let index = 1;
  9118. const description = utf8ArrayToStr(frame.data.subarray(index), true);
  9119. index += description.length + 1;
  9120. const value = utf8ArrayToStr(frame.data.subarray(index));
  9121. return {
  9122. key: frame.type,
  9123. info: description,
  9124. data: value
  9125. };
  9126. }
  9127. const text = utf8ArrayToStr(frame.data.subarray(1));
  9128. return {
  9129. key: frame.type,
  9130. info: "",
  9131. data: text
  9132. };
  9133. }
  9134. function decodeId3UrlFrame(frame) {
  9135. if (frame.type === "WXXX") {
  9136. if (frame.size < 2) {
  9137. return void 0;
  9138. }
  9139. let index = 1;
  9140. const description = utf8ArrayToStr(frame.data.subarray(index), true);
  9141. index += description.length + 1;
  9142. const value = utf8ArrayToStr(frame.data.subarray(index));
  9143. return {
  9144. key: frame.type,
  9145. info: description,
  9146. data: value
  9147. };
  9148. }
  9149. const url = utf8ArrayToStr(frame.data);
  9150. return {
  9151. key: frame.type,
  9152. info: "",
  9153. data: url
  9154. };
  9155. }
  9156. function decodeId3Frame(frame) {
  9157. if (frame.type === "PRIV") {
  9158. return decodeId3PrivFrame(frame);
  9159. } else if (frame.type[0] === "W") {
  9160. return decodeId3UrlFrame(frame);
  9161. } else if (frame.type === "APIC") {
  9162. return decodeId3ImageFrame(frame);
  9163. }
  9164. return decodeId3TextFrame(frame);
  9165. }
  9166. function getId3FrameData(data) {
  9167. const type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  9168. const size = readId3Size(data, 4);
  9169. const offset = 10;
  9170. return {
  9171. type,
  9172. size,
  9173. data: data.subarray(offset, offset + size)
  9174. };
  9175. }
  9176. var HEADER_FOOTER_SIZE = 10;
  9177. var FRAME_SIZE = 10;
  9178. function getId3Frames(id3Data) {
  9179. let offset = 0;
  9180. const frames = [];
  9181. while (isId3Header(id3Data, offset)) {
  9182. const size = readId3Size(id3Data, offset + 6);
  9183. if (id3Data[offset + 5] >> 6 & 1) {
  9184. offset += HEADER_FOOTER_SIZE;
  9185. }
  9186. offset += HEADER_FOOTER_SIZE;
  9187. const end = offset + size;
  9188. while (offset + FRAME_SIZE < end) {
  9189. const frameData = getId3FrameData(id3Data.subarray(offset));
  9190. const frame = decodeId3Frame(frameData);
  9191. if (frame) {
  9192. frames.push(frame);
  9193. }
  9194. offset += frameData.size + HEADER_FOOTER_SIZE;
  9195. }
  9196. if (isId3Footer(id3Data, offset)) {
  9197. offset += HEADER_FOOTER_SIZE;
  9198. }
  9199. }
  9200. return frames;
  9201. }
  9202. function isId3TimestampFrame(frame) {
  9203. return frame && frame.key === "PRIV" && frame.info === "com.apple.streaming.transportStreamTimestamp";
  9204. }
  9205. function readId3Timestamp(timeStampFrame) {
  9206. if (timeStampFrame.data.byteLength === 8) {
  9207. const data = new Uint8Array(timeStampFrame.data);
  9208. const pts33Bit = data[3] & 1;
  9209. let timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  9210. timestamp /= 45;
  9211. if (pts33Bit) {
  9212. timestamp += 4772185884e-2;
  9213. }
  9214. return Math.round(timestamp);
  9215. }
  9216. return void 0;
  9217. }
  9218. function getId3Timestamp(data) {
  9219. const frames = getId3Frames(data);
  9220. for (let i = 0; i < frames.length; i++) {
  9221. const frame = frames[i];
  9222. if (isId3TimestampFrame(frame)) {
  9223. return readId3Timestamp(frame);
  9224. }
  9225. }
  9226. return void 0;
  9227. }
  9228. var MetadataSchema = function(MetadataSchema2) {
  9229. MetadataSchema2["audioId3"] = "org.id3";
  9230. MetadataSchema2["dateRange"] = "com.apple.quicktime.HLS";
  9231. MetadataSchema2["emsg"] = "https://aomedia.org/emsg/ID3";
  9232. MetadataSchema2["misbklv"] = "urn:misb:KLV:bin:1910.1";
  9233. return MetadataSchema2;
  9234. }({});
  9235. function dummyTrack(type = "", inputTimeScale = 9e4) {
  9236. return {
  9237. type,
  9238. id: -1,
  9239. pid: -1,
  9240. inputTimeScale,
  9241. sequenceNumber: -1,
  9242. samples: [],
  9243. dropped: 0
  9244. };
  9245. }
  9246. var BaseAudioDemuxer = class {
  9247. constructor() {
  9248. this._audioTrack = void 0;
  9249. this._id3Track = void 0;
  9250. this.frameIndex = 0;
  9251. this.cachedData = null;
  9252. this.basePTS = null;
  9253. this.initPTS = null;
  9254. this.lastPTS = null;
  9255. }
  9256. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  9257. this._id3Track = {
  9258. type: "id3",
  9259. id: 3,
  9260. pid: -1,
  9261. inputTimeScale: 9e4,
  9262. sequenceNumber: 0,
  9263. samples: [],
  9264. dropped: 0
  9265. };
  9266. }
  9267. resetTimeStamp(deaultTimestamp) {
  9268. this.initPTS = deaultTimestamp;
  9269. this.resetContiguity();
  9270. }
  9271. resetContiguity() {
  9272. this.basePTS = null;
  9273. this.lastPTS = null;
  9274. this.frameIndex = 0;
  9275. }
  9276. canParse(data, offset) {
  9277. return false;
  9278. }
  9279. appendFrame(track, data, offset) {
  9280. }
  9281. demux(data, timeOffset) {
  9282. if (this.cachedData) {
  9283. data = appendUint8Array(this.cachedData, data);
  9284. this.cachedData = null;
  9285. }
  9286. let id3Data = getId3Data(data, 0);
  9287. let offset = id3Data ? id3Data.length : 0;
  9288. let lastDataIndex;
  9289. const track = this._audioTrack;
  9290. const id3Track = this._id3Track;
  9291. const timestamp = id3Data ? getId3Timestamp(id3Data) : void 0;
  9292. const length = data.length;
  9293. if (this.basePTS === null || this.frameIndex === 0 && isFiniteNumber(timestamp)) {
  9294. this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);
  9295. this.lastPTS = this.basePTS;
  9296. }
  9297. if (this.lastPTS === null) {
  9298. this.lastPTS = this.basePTS;
  9299. }
  9300. if (id3Data && id3Data.length > 0) {
  9301. id3Track.samples.push({
  9302. pts: this.lastPTS,
  9303. dts: this.lastPTS,
  9304. data: id3Data,
  9305. type: MetadataSchema.audioId3,
  9306. duration: Number.POSITIVE_INFINITY
  9307. });
  9308. }
  9309. while (offset < length) {
  9310. if (this.canParse(data, offset)) {
  9311. const frame = this.appendFrame(track, data, offset);
  9312. if (frame) {
  9313. this.frameIndex++;
  9314. this.lastPTS = frame.sample.pts;
  9315. offset += frame.length;
  9316. lastDataIndex = offset;
  9317. } else {
  9318. offset = length;
  9319. }
  9320. } else if (canParseId3(data, offset)) {
  9321. id3Data = getId3Data(data, offset);
  9322. id3Track.samples.push({
  9323. pts: this.lastPTS,
  9324. dts: this.lastPTS,
  9325. data: id3Data,
  9326. type: MetadataSchema.audioId3,
  9327. duration: Number.POSITIVE_INFINITY
  9328. });
  9329. offset += id3Data.length;
  9330. lastDataIndex = offset;
  9331. } else {
  9332. offset++;
  9333. }
  9334. if (offset === length && lastDataIndex !== length) {
  9335. const partialData = data.slice(lastDataIndex);
  9336. if (this.cachedData) {
  9337. this.cachedData = appendUint8Array(this.cachedData, partialData);
  9338. } else {
  9339. this.cachedData = partialData;
  9340. }
  9341. }
  9342. }
  9343. return {
  9344. audioTrack: track,
  9345. videoTrack: dummyTrack(),
  9346. id3Track,
  9347. textTrack: dummyTrack()
  9348. };
  9349. }
  9350. demuxSampleAes(data, keyData, timeOffset) {
  9351. return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`));
  9352. }
  9353. flush(timeOffset) {
  9354. const cachedData = this.cachedData;
  9355. if (cachedData) {
  9356. this.cachedData = null;
  9357. this.demux(cachedData, 0);
  9358. }
  9359. return {
  9360. audioTrack: this._audioTrack,
  9361. videoTrack: dummyTrack(),
  9362. id3Track: this._id3Track,
  9363. textTrack: dummyTrack()
  9364. };
  9365. }
  9366. destroy() {
  9367. this.cachedData = null;
  9368. this._audioTrack = this._id3Track = void 0;
  9369. }
  9370. };
  9371. var initPTSFn = (timestamp, timeOffset, initPTS) => {
  9372. if (isFiniteNumber(timestamp)) {
  9373. return timestamp * 90;
  9374. }
  9375. const init90kHz = initPTS ? initPTS.baseTime * 9e4 / initPTS.timescale : 0;
  9376. return timeOffset * 9e4 + init90kHz;
  9377. };
  9378. var chromeVersion$1 = null;
  9379. 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];
  9380. var SamplingRateMap = [44100, 48e3, 32e3, 22050, 24e3, 16e3, 11025, 12e3, 8e3];
  9381. var SamplesCoefficients = [
  9382. [
  9383. 0,
  9384. 72,
  9385. 144,
  9386. 12
  9387. ],
  9388. [
  9389. 0,
  9390. 0,
  9391. 0,
  9392. 0
  9393. ],
  9394. [
  9395. 0,
  9396. 72,
  9397. 144,
  9398. 12
  9399. ],
  9400. [
  9401. 0,
  9402. 144,
  9403. 144,
  9404. 12
  9405. ]
  9406. ];
  9407. var BytesInSlot = [
  9408. 0,
  9409. 1,
  9410. 1,
  9411. 4
  9412. ];
  9413. function appendFrame$1(track, data, offset, pts, frameIndex) {
  9414. if (offset + 24 > data.length) {
  9415. return;
  9416. }
  9417. const header = parseHeader(data, offset);
  9418. if (header && offset + header.frameLength <= data.length) {
  9419. const frameDuration = header.samplesPerFrame * 9e4 / header.sampleRate;
  9420. const stamp = pts + frameIndex * frameDuration;
  9421. const sample = {
  9422. unit: data.subarray(offset, offset + header.frameLength),
  9423. pts: stamp,
  9424. dts: stamp
  9425. };
  9426. track.config = [];
  9427. track.channelCount = header.channelCount;
  9428. track.samplerate = header.sampleRate;
  9429. track.samples.push(sample);
  9430. return {
  9431. sample,
  9432. length: header.frameLength,
  9433. missing: 0
  9434. };
  9435. }
  9436. }
  9437. function parseHeader(data, offset) {
  9438. const mpegVersion = data[offset + 1] >> 3 & 3;
  9439. const mpegLayer = data[offset + 1] >> 1 & 3;
  9440. const bitRateIndex = data[offset + 2] >> 4 & 15;
  9441. const sampleRateIndex = data[offset + 2] >> 2 & 3;
  9442. if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
  9443. const paddingBit = data[offset + 2] >> 1 & 1;
  9444. const channelMode = data[offset + 3] >> 6;
  9445. const columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
  9446. const bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1e3;
  9447. const columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
  9448. const sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
  9449. const channelCount = channelMode === 3 ? 1 : 2;
  9450. const sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
  9451. const bytesInSlot = BytesInSlot[mpegLayer];
  9452. const samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  9453. const frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
  9454. if (chromeVersion$1 === null) {
  9455. const userAgent = navigator.userAgent || "";
  9456. const result = userAgent.match(/Chrome\/(\d+)/i);
  9457. chromeVersion$1 = result ? parseInt(result[1]) : 0;
  9458. }
  9459. const needChromeFix = !!chromeVersion$1 && chromeVersion$1 <= 87;
  9460. if (needChromeFix && mpegLayer === 2 && bitRate >= 224e3 && channelMode === 0) {
  9461. data[offset + 3] = data[offset + 3] | 128;
  9462. }
  9463. return {
  9464. sampleRate,
  9465. channelCount,
  9466. frameLength,
  9467. samplesPerFrame
  9468. };
  9469. }
  9470. }
  9471. function isHeaderPattern(data, offset) {
  9472. return data[offset] === 255 && (data[offset + 1] & 224) === 224 && (data[offset + 1] & 6) !== 0;
  9473. }
  9474. function isHeader(data, offset) {
  9475. return offset + 1 < data.length && isHeaderPattern(data, offset);
  9476. }
  9477. function canParse(data, offset) {
  9478. const headerSize = 4;
  9479. return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
  9480. }
  9481. function probe(data, offset) {
  9482. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  9483. const headerLength = 4;
  9484. const header = parseHeader(data, offset);
  9485. let frameLength = headerLength;
  9486. if (header != null && header.frameLength) {
  9487. frameLength = header.frameLength;
  9488. }
  9489. const newOffset = offset + frameLength;
  9490. return newOffset === data.length || isHeader(data, newOffset);
  9491. }
  9492. return false;
  9493. }
  9494. var AACDemuxer = class extends BaseAudioDemuxer {
  9495. constructor(observer, config) {
  9496. super();
  9497. this.observer = void 0;
  9498. this.config = void 0;
  9499. this.observer = observer;
  9500. this.config = config;
  9501. }
  9502. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  9503. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  9504. this._audioTrack = {
  9505. container: "audio/adts",
  9506. type: "audio",
  9507. id: 2,
  9508. pid: -1,
  9509. sequenceNumber: 0,
  9510. segmentCodec: "aac",
  9511. samples: [],
  9512. manifestCodec: audioCodec,
  9513. duration: trackDuration,
  9514. inputTimeScale: 9e4,
  9515. dropped: 0
  9516. };
  9517. }
  9518. static probe(data, logger2) {
  9519. if (!data) {
  9520. return false;
  9521. }
  9522. const id3Data = getId3Data(data, 0);
  9523. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  9524. if (probe(data, offset)) {
  9525. return false;
  9526. }
  9527. for (let length = data.length; offset < length; offset++) {
  9528. if (probe$1(data, offset)) {
  9529. logger2.log("ADTS sync word found !");
  9530. return true;
  9531. }
  9532. }
  9533. return false;
  9534. }
  9535. canParse(data, offset) {
  9536. return canParse$1(data, offset);
  9537. }
  9538. appendFrame(track, data, offset) {
  9539. initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  9540. const frame = appendFrame$2(track, data, offset, this.basePTS, this.frameIndex);
  9541. if (frame && frame.missing === 0) {
  9542. return frame;
  9543. }
  9544. }
  9545. };
  9546. var getAudioBSID = (data, offset) => {
  9547. let bsid = 0;
  9548. let numBits = 5;
  9549. offset += numBits;
  9550. const temp = new Uint32Array(1);
  9551. const mask = new Uint32Array(1);
  9552. const byte = new Uint8Array(1);
  9553. while (numBits > 0) {
  9554. byte[0] = data[offset];
  9555. const bits = Math.min(numBits, 8);
  9556. const shift = 8 - bits;
  9557. mask[0] = 4278190080 >>> 24 + shift << shift;
  9558. temp[0] = (byte[0] & mask[0]) >> shift;
  9559. bsid = !bsid ? temp[0] : bsid << bits | temp[0];
  9560. offset += 1;
  9561. numBits -= bits;
  9562. }
  9563. return bsid;
  9564. };
  9565. var AC3Demuxer = class extends BaseAudioDemuxer {
  9566. constructor(observer) {
  9567. super();
  9568. this.observer = void 0;
  9569. this.observer = observer;
  9570. }
  9571. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  9572. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  9573. this._audioTrack = {
  9574. container: "audio/ac-3",
  9575. type: "audio",
  9576. id: 2,
  9577. pid: -1,
  9578. sequenceNumber: 0,
  9579. segmentCodec: "ac3",
  9580. samples: [],
  9581. manifestCodec: audioCodec,
  9582. duration: trackDuration,
  9583. inputTimeScale: 9e4,
  9584. dropped: 0
  9585. };
  9586. }
  9587. canParse(data, offset) {
  9588. return offset + 64 < data.length;
  9589. }
  9590. appendFrame(track, data, offset) {
  9591. const frameLength = appendFrame(track, data, offset, this.basePTS, this.frameIndex);
  9592. if (frameLength !== -1) {
  9593. const sample = track.samples[track.samples.length - 1];
  9594. return {
  9595. sample,
  9596. length: frameLength,
  9597. missing: 0
  9598. };
  9599. }
  9600. }
  9601. static probe(data) {
  9602. if (!data) {
  9603. return false;
  9604. }
  9605. const id3Data = getId3Data(data, 0);
  9606. if (!id3Data) {
  9607. return false;
  9608. }
  9609. const offset = id3Data.length;
  9610. if (data[offset] === 11 && data[offset + 1] === 119 && getId3Timestamp(id3Data) !== void 0 && getAudioBSID(data, offset) < 16) {
  9611. return true;
  9612. }
  9613. return false;
  9614. }
  9615. };
  9616. function appendFrame(track, data, start, pts, frameIndex) {
  9617. if (start + 8 > data.length) {
  9618. return -1;
  9619. }
  9620. if (data[start] !== 11 || data[start + 1] !== 119) {
  9621. return -1;
  9622. }
  9623. const samplingRateCode = data[start + 4] >> 6;
  9624. if (samplingRateCode >= 3) {
  9625. return -1;
  9626. }
  9627. const samplingRateMap = [48e3, 44100, 32e3];
  9628. const sampleRate = samplingRateMap[samplingRateCode];
  9629. const frameSizeCode = data[start + 4] & 63;
  9630. 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];
  9631. const frameLength = frameSizeMap[frameSizeCode * 3 + samplingRateCode] * 2;
  9632. if (start + frameLength > data.length) {
  9633. return -1;
  9634. }
  9635. const channelMode = data[start + 6] >> 5;
  9636. let skipCount = 0;
  9637. if (channelMode === 2) {
  9638. skipCount += 2;
  9639. } else {
  9640. if (channelMode & 1 && channelMode !== 1) {
  9641. skipCount += 2;
  9642. }
  9643. if (channelMode & 4) {
  9644. skipCount += 2;
  9645. }
  9646. }
  9647. const lfeon = (data[start + 6] << 8 | data[start + 7]) >> 12 - skipCount & 1;
  9648. const channelsMap = [2, 1, 2, 3, 3, 4, 4, 5];
  9649. const channelCount = channelsMap[channelMode] + lfeon;
  9650. const bsid = data[start + 5] >> 3;
  9651. const bsmod = data[start + 5] & 7;
  9652. const config = new Uint8Array([samplingRateCode << 6 | bsid << 1 | bsmod >> 2, (bsmod & 3) << 6 | channelMode << 3 | lfeon << 2 | frameSizeCode >> 4, frameSizeCode << 4 & 224]);
  9653. const frameDuration = 1536 / sampleRate * 9e4;
  9654. const stamp = pts + frameIndex * frameDuration;
  9655. const unit = data.subarray(start, start + frameLength);
  9656. track.config = config;
  9657. track.channelCount = channelCount;
  9658. track.samplerate = sampleRate;
  9659. track.samples.push({
  9660. unit,
  9661. pts: stamp
  9662. });
  9663. return frameLength;
  9664. }
  9665. var MP3Demuxer = class extends BaseAudioDemuxer {
  9666. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  9667. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  9668. this._audioTrack = {
  9669. container: "audio/mpeg",
  9670. type: "audio",
  9671. id: 2,
  9672. pid: -1,
  9673. sequenceNumber: 0,
  9674. segmentCodec: "mp3",
  9675. samples: [],
  9676. manifestCodec: audioCodec,
  9677. duration: trackDuration,
  9678. inputTimeScale: 9e4,
  9679. dropped: 0
  9680. };
  9681. }
  9682. static probe(data) {
  9683. if (!data) {
  9684. return false;
  9685. }
  9686. const id3Data = getId3Data(data, 0);
  9687. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  9688. if (id3Data && data[offset] === 11 && data[offset + 1] === 119 && getId3Timestamp(id3Data) !== void 0 && getAudioBSID(data, offset) <= 16) {
  9689. return false;
  9690. }
  9691. for (let length = data.length; offset < length; offset++) {
  9692. if (probe(data, offset)) {
  9693. logger.log("MPEG Audio sync word found !");
  9694. return true;
  9695. }
  9696. }
  9697. return false;
  9698. }
  9699. canParse(data, offset) {
  9700. return canParse(data, offset);
  9701. }
  9702. appendFrame(track, data, offset) {
  9703. if (this.basePTS === null) {
  9704. return;
  9705. }
  9706. return appendFrame$1(track, data, offset, this.basePTS, this.frameIndex);
  9707. }
  9708. };
  9709. var emsgSchemePattern = /\/emsg[-/]ID3/i;
  9710. var MP4Demuxer = class {
  9711. constructor(observer, config) {
  9712. this.remainderData = null;
  9713. this.timeOffset = 0;
  9714. this.config = void 0;
  9715. this.videoTrack = void 0;
  9716. this.audioTrack = void 0;
  9717. this.id3Track = void 0;
  9718. this.txtTrack = void 0;
  9719. this.config = config;
  9720. }
  9721. resetTimeStamp() {
  9722. }
  9723. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  9724. const videoTrack = this.videoTrack = dummyTrack("video", 1);
  9725. const audioTrack = this.audioTrack = dummyTrack("audio", 1);
  9726. const captionTrack = this.txtTrack = dummyTrack("text", 1);
  9727. this.id3Track = dummyTrack("id3", 1);
  9728. this.timeOffset = 0;
  9729. if (!(initSegment != null && initSegment.byteLength)) {
  9730. return;
  9731. }
  9732. const initData = parseInitSegment(initSegment);
  9733. if (initData.video) {
  9734. const {
  9735. id,
  9736. timescale,
  9737. codec,
  9738. supplemental
  9739. } = initData.video;
  9740. videoTrack.id = id;
  9741. videoTrack.timescale = captionTrack.timescale = timescale;
  9742. videoTrack.codec = codec;
  9743. videoTrack.supplemental = supplemental;
  9744. }
  9745. if (initData.audio) {
  9746. const {
  9747. id,
  9748. timescale,
  9749. codec
  9750. } = initData.audio;
  9751. audioTrack.id = id;
  9752. audioTrack.timescale = timescale;
  9753. audioTrack.codec = codec;
  9754. }
  9755. captionTrack.id = RemuxerTrackIdConfig.text;
  9756. videoTrack.sampleDuration = 0;
  9757. videoTrack.duration = audioTrack.duration = trackDuration;
  9758. }
  9759. resetContiguity() {
  9760. this.remainderData = null;
  9761. }
  9762. static probe(data) {
  9763. return hasMoofData(data);
  9764. }
  9765. demux(data, timeOffset) {
  9766. this.timeOffset = timeOffset;
  9767. let videoSamples = data;
  9768. const videoTrack = this.videoTrack;
  9769. const textTrack = this.txtTrack;
  9770. if (this.config.progressive) {
  9771. if (this.remainderData) {
  9772. videoSamples = appendUint8Array(this.remainderData, data);
  9773. }
  9774. const segmentedData = segmentValidRange(videoSamples);
  9775. this.remainderData = segmentedData.remainder;
  9776. videoTrack.samples = segmentedData.valid || new Uint8Array();
  9777. } else {
  9778. videoTrack.samples = videoSamples;
  9779. }
  9780. const id3Track = this.extractID3Track(videoTrack, timeOffset);
  9781. textTrack.samples = parseSamples(timeOffset, videoTrack);
  9782. return {
  9783. videoTrack,
  9784. audioTrack: this.audioTrack,
  9785. id3Track,
  9786. textTrack: this.txtTrack
  9787. };
  9788. }
  9789. flush() {
  9790. const timeOffset = this.timeOffset;
  9791. const videoTrack = this.videoTrack;
  9792. const textTrack = this.txtTrack;
  9793. videoTrack.samples = this.remainderData || new Uint8Array();
  9794. this.remainderData = null;
  9795. const id3Track = this.extractID3Track(videoTrack, this.timeOffset);
  9796. textTrack.samples = parseSamples(timeOffset, videoTrack);
  9797. return {
  9798. videoTrack,
  9799. audioTrack: dummyTrack(),
  9800. id3Track,
  9801. textTrack: dummyTrack()
  9802. };
  9803. }
  9804. extractID3Track(videoTrack, timeOffset) {
  9805. const id3Track = this.id3Track;
  9806. if (videoTrack.samples.length) {
  9807. const emsgs = findBox(videoTrack.samples, ["emsg"]);
  9808. if (emsgs) {
  9809. emsgs.forEach((data) => {
  9810. const emsgInfo = parseEmsg(data);
  9811. if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {
  9812. const pts = getEmsgStartTime(emsgInfo, timeOffset);
  9813. let duration = emsgInfo.eventDuration === 4294967295 ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale;
  9814. if (duration <= 1e-3) {
  9815. duration = Number.POSITIVE_INFINITY;
  9816. }
  9817. const payload = emsgInfo.payload;
  9818. id3Track.samples.push({
  9819. data: payload,
  9820. len: payload.byteLength,
  9821. dts: pts,
  9822. pts,
  9823. type: MetadataSchema.emsg,
  9824. duration
  9825. });
  9826. } else if (this.config.enableEmsgKLVMetadata && emsgInfo.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")) {
  9827. const pts = getEmsgStartTime(emsgInfo, timeOffset);
  9828. id3Track.samples.push({
  9829. data: emsgInfo.payload,
  9830. len: emsgInfo.payload.byteLength,
  9831. dts: pts,
  9832. pts,
  9833. type: MetadataSchema.misbklv,
  9834. duration: Number.POSITIVE_INFINITY
  9835. });
  9836. }
  9837. });
  9838. }
  9839. }
  9840. return id3Track;
  9841. }
  9842. demuxSampleAes(data, keyData, timeOffset) {
  9843. return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"));
  9844. }
  9845. destroy() {
  9846. this.config = null;
  9847. this.remainderData = null;
  9848. this.videoTrack = this.audioTrack = this.id3Track = this.txtTrack = void 0;
  9849. }
  9850. };
  9851. function getEmsgStartTime(emsgInfo, timeOffset) {
  9852. return isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;
  9853. }
  9854. var SampleAesDecrypter = class {
  9855. constructor(observer, config, keyData) {
  9856. this.keyData = void 0;
  9857. this.decrypter = void 0;
  9858. this.keyData = keyData;
  9859. this.decrypter = new Decrypter(config, {
  9860. removePKCS7Padding: false
  9861. });
  9862. }
  9863. decryptBuffer(encryptedData) {
  9864. return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, DecrypterAesMode.cbc);
  9865. }
  9866. decryptAacSample(samples, sampleIndex, callback) {
  9867. const curUnit = samples[sampleIndex].unit;
  9868. if (curUnit.length <= 16) {
  9869. return;
  9870. }
  9871. const encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  9872. const encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  9873. this.decryptBuffer(encryptedBuffer).then((decryptedBuffer) => {
  9874. const decryptedData = new Uint8Array(decryptedBuffer);
  9875. curUnit.set(decryptedData, 16);
  9876. if (!this.decrypter.isSync()) {
  9877. this.decryptAacSamples(samples, sampleIndex + 1, callback);
  9878. }
  9879. });
  9880. }
  9881. decryptAacSamples(samples, sampleIndex, callback) {
  9882. for (; ; sampleIndex++) {
  9883. if (sampleIndex >= samples.length) {
  9884. callback();
  9885. return;
  9886. }
  9887. if (samples[sampleIndex].unit.length < 32) {
  9888. continue;
  9889. }
  9890. this.decryptAacSample(samples, sampleIndex, callback);
  9891. if (!this.decrypter.isSync()) {
  9892. return;
  9893. }
  9894. }
  9895. }
  9896. getAvcEncryptedData(decodedData) {
  9897. const encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  9898. const encryptedData = new Int8Array(encryptedDataLen);
  9899. let outputPos = 0;
  9900. for (let inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) {
  9901. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  9902. }
  9903. return encryptedData;
  9904. }
  9905. getAvcDecryptedUnit(decodedData, decryptedData) {
  9906. const uint8DecryptedData = new Uint8Array(decryptedData);
  9907. let inputPos = 0;
  9908. for (let outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) {
  9909. decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
  9910. }
  9911. return decodedData;
  9912. }
  9913. decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit) {
  9914. const decodedData = discardEPB(curUnit.data);
  9915. const encryptedData = this.getAvcEncryptedData(decodedData);
  9916. this.decryptBuffer(encryptedData.buffer).then((decryptedBuffer) => {
  9917. curUnit.data = this.getAvcDecryptedUnit(decodedData, decryptedBuffer);
  9918. if (!this.decrypter.isSync()) {
  9919. this.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  9920. }
  9921. });
  9922. }
  9923. decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  9924. if (samples instanceof Uint8Array) {
  9925. throw new Error("Cannot decrypt samples of type Uint8Array");
  9926. }
  9927. for (; ; sampleIndex++, unitIndex = 0) {
  9928. if (sampleIndex >= samples.length) {
  9929. callback();
  9930. return;
  9931. }
  9932. const curUnits = samples[sampleIndex].units;
  9933. for (; ; unitIndex++) {
  9934. if (unitIndex >= curUnits.length) {
  9935. break;
  9936. }
  9937. const curUnit = curUnits[unitIndex];
  9938. if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  9939. continue;
  9940. }
  9941. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit);
  9942. if (!this.decrypter.isSync()) {
  9943. return;
  9944. }
  9945. }
  9946. }
  9947. }
  9948. };
  9949. var BaseVideoParser = class {
  9950. constructor() {
  9951. this.VideoSample = null;
  9952. }
  9953. createVideoSample(key, pts, dts) {
  9954. return {
  9955. key,
  9956. frame: false,
  9957. pts,
  9958. dts,
  9959. units: [],
  9960. length: 0
  9961. };
  9962. }
  9963. getLastNalUnit(samples) {
  9964. var _VideoSample;
  9965. let VideoSample = this.VideoSample;
  9966. let lastUnit;
  9967. if (!VideoSample || VideoSample.units.length === 0) {
  9968. VideoSample = samples[samples.length - 1];
  9969. }
  9970. if ((_VideoSample = VideoSample) != null && _VideoSample.units) {
  9971. const units = VideoSample.units;
  9972. lastUnit = units[units.length - 1];
  9973. }
  9974. return lastUnit;
  9975. }
  9976. pushAccessUnit(VideoSample, videoTrack) {
  9977. if (VideoSample.units.length && VideoSample.frame) {
  9978. if (VideoSample.pts === void 0) {
  9979. const samples = videoTrack.samples;
  9980. const nbSamples = samples.length;
  9981. if (nbSamples) {
  9982. const lastSample = samples[nbSamples - 1];
  9983. VideoSample.pts = lastSample.pts;
  9984. VideoSample.dts = lastSample.dts;
  9985. } else {
  9986. videoTrack.dropped++;
  9987. return;
  9988. }
  9989. }
  9990. videoTrack.samples.push(VideoSample);
  9991. }
  9992. }
  9993. parseNALu(track, array, endOfSegment) {
  9994. const len = array.byteLength;
  9995. let state = track.naluState || 0;
  9996. const lastState = state;
  9997. const units = [];
  9998. let i = 0;
  9999. let value;
  10000. let overflow;
  10001. let unitType;
  10002. let lastUnitStart = -1;
  10003. let lastUnitType = 0;
  10004. if (state === -1) {
  10005. lastUnitStart = 0;
  10006. lastUnitType = this.getNALuType(array, 0);
  10007. state = 0;
  10008. i = 1;
  10009. }
  10010. while (i < len) {
  10011. value = array[i++];
  10012. if (!state) {
  10013. state = value ? 0 : 1;
  10014. continue;
  10015. }
  10016. if (state === 1) {
  10017. state = value ? 0 : 2;
  10018. continue;
  10019. }
  10020. if (!value) {
  10021. state = 3;
  10022. } else if (value === 1) {
  10023. overflow = i - state - 1;
  10024. if (lastUnitStart >= 0) {
  10025. const unit = {
  10026. data: array.subarray(lastUnitStart, overflow),
  10027. type: lastUnitType
  10028. };
  10029. units.push(unit);
  10030. } else {
  10031. const lastUnit = this.getLastNalUnit(track.samples);
  10032. if (lastUnit) {
  10033. if (lastState && i <= 4 - lastState) {
  10034. if (lastUnit.state) {
  10035. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  10036. }
  10037. }
  10038. if (overflow > 0) {
  10039. lastUnit.data = appendUint8Array(lastUnit.data, array.subarray(0, overflow));
  10040. lastUnit.state = 0;
  10041. }
  10042. }
  10043. }
  10044. if (i < len) {
  10045. unitType = this.getNALuType(array, i);
  10046. lastUnitStart = i;
  10047. lastUnitType = unitType;
  10048. state = 0;
  10049. } else {
  10050. state = -1;
  10051. }
  10052. } else {
  10053. state = 0;
  10054. }
  10055. }
  10056. if (lastUnitStart >= 0 && state >= 0) {
  10057. const unit = {
  10058. data: array.subarray(lastUnitStart, len),
  10059. type: lastUnitType,
  10060. state
  10061. };
  10062. units.push(unit);
  10063. }
  10064. if (units.length === 0) {
  10065. const lastUnit = this.getLastNalUnit(track.samples);
  10066. if (lastUnit) {
  10067. lastUnit.data = appendUint8Array(lastUnit.data, array);
  10068. }
  10069. }
  10070. track.naluState = state;
  10071. return units;
  10072. }
  10073. };
  10074. var ExpGolomb = class {
  10075. constructor(data) {
  10076. this.data = void 0;
  10077. this.bytesAvailable = void 0;
  10078. this.word = void 0;
  10079. this.bitsAvailable = void 0;
  10080. this.data = data;
  10081. this.bytesAvailable = data.byteLength;
  10082. this.word = 0;
  10083. this.bitsAvailable = 0;
  10084. }
  10085. loadWord() {
  10086. const data = this.data;
  10087. const bytesAvailable = this.bytesAvailable;
  10088. const position = data.byteLength - bytesAvailable;
  10089. const workingBytes = new Uint8Array(4);
  10090. const availableBytes = Math.min(4, bytesAvailable);
  10091. if (availableBytes === 0) {
  10092. throw new Error("no bytes available");
  10093. }
  10094. workingBytes.set(data.subarray(position, position + availableBytes));
  10095. this.word = new DataView(workingBytes.buffer).getUint32(0);
  10096. this.bitsAvailable = availableBytes * 8;
  10097. this.bytesAvailable -= availableBytes;
  10098. }
  10099. skipBits(count) {
  10100. let skipBytes;
  10101. count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);
  10102. if (this.bitsAvailable > count) {
  10103. this.word <<= count;
  10104. this.bitsAvailable -= count;
  10105. } else {
  10106. count -= this.bitsAvailable;
  10107. skipBytes = count >> 3;
  10108. count -= skipBytes << 3;
  10109. this.bytesAvailable -= skipBytes;
  10110. this.loadWord();
  10111. this.word <<= count;
  10112. this.bitsAvailable -= count;
  10113. }
  10114. }
  10115. readBits(size) {
  10116. let bits = Math.min(this.bitsAvailable, size);
  10117. const valu = this.word >>> 32 - bits;
  10118. if (size > 32) {
  10119. logger.error("Cannot read more than 32 bits at a time");
  10120. }
  10121. this.bitsAvailable -= bits;
  10122. if (this.bitsAvailable > 0) {
  10123. this.word <<= bits;
  10124. } else if (this.bytesAvailable > 0) {
  10125. this.loadWord();
  10126. } else {
  10127. throw new Error("no bits available");
  10128. }
  10129. bits = size - bits;
  10130. if (bits > 0 && this.bitsAvailable) {
  10131. return valu << bits | this.readBits(bits);
  10132. } else {
  10133. return valu;
  10134. }
  10135. }
  10136. skipLZ() {
  10137. let leadingZeroCount;
  10138. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  10139. if ((this.word & 2147483648 >>> leadingZeroCount) !== 0) {
  10140. this.word <<= leadingZeroCount;
  10141. this.bitsAvailable -= leadingZeroCount;
  10142. return leadingZeroCount;
  10143. }
  10144. }
  10145. this.loadWord();
  10146. return leadingZeroCount + this.skipLZ();
  10147. }
  10148. skipUEG() {
  10149. this.skipBits(1 + this.skipLZ());
  10150. }
  10151. skipEG() {
  10152. this.skipBits(1 + this.skipLZ());
  10153. }
  10154. readUEG() {
  10155. const clz = this.skipLZ();
  10156. return this.readBits(clz + 1) - 1;
  10157. }
  10158. readEG() {
  10159. const valu = this.readUEG();
  10160. if (1 & valu) {
  10161. return 1 + valu >>> 1;
  10162. } else {
  10163. return -1 * (valu >>> 1);
  10164. }
  10165. }
  10166. readBoolean() {
  10167. return this.readBits(1) === 1;
  10168. }
  10169. readUByte() {
  10170. return this.readBits(8);
  10171. }
  10172. readUShort() {
  10173. return this.readBits(16);
  10174. }
  10175. readUInt() {
  10176. return this.readBits(32);
  10177. }
  10178. };
  10179. var AvcVideoParser = class extends BaseVideoParser {
  10180. parsePES(track, textTrack, pes, endOfSegment) {
  10181. const units = this.parseNALu(track, pes.data, endOfSegment);
  10182. let VideoSample = this.VideoSample;
  10183. let push2;
  10184. let spsfound = false;
  10185. pes.data = null;
  10186. if (VideoSample && units.length && !track.audFound) {
  10187. this.pushAccessUnit(VideoSample, track);
  10188. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  10189. }
  10190. units.forEach((unit) => {
  10191. var _VideoSample2, _VideoSample3;
  10192. switch (unit.type) {
  10193. case 1: {
  10194. let iskey = false;
  10195. push2 = true;
  10196. const data = unit.data;
  10197. if (spsfound && data.length > 4) {
  10198. const sliceType = this.readSliceType(data);
  10199. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  10200. iskey = true;
  10201. }
  10202. }
  10203. if (iskey) {
  10204. var _VideoSample;
  10205. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  10206. this.pushAccessUnit(VideoSample, track);
  10207. VideoSample = this.VideoSample = null;
  10208. }
  10209. }
  10210. if (!VideoSample) {
  10211. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  10212. }
  10213. VideoSample.frame = true;
  10214. VideoSample.key = iskey;
  10215. break;
  10216. }
  10217. case 5:
  10218. push2 = true;
  10219. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  10220. this.pushAccessUnit(VideoSample, track);
  10221. VideoSample = this.VideoSample = null;
  10222. }
  10223. if (!VideoSample) {
  10224. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  10225. }
  10226. VideoSample.key = true;
  10227. VideoSample.frame = true;
  10228. break;
  10229. case 6: {
  10230. push2 = true;
  10231. parseSEIMessageFromNALu(unit.data, 1, pes.pts, textTrack.samples);
  10232. break;
  10233. }
  10234. case 7: {
  10235. var _track$pixelRatio, _track$pixelRatio2;
  10236. push2 = true;
  10237. spsfound = true;
  10238. const sps = unit.data;
  10239. const config = this.readSPS(sps);
  10240. 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]) {
  10241. track.width = config.width;
  10242. track.height = config.height;
  10243. track.pixelRatio = config.pixelRatio;
  10244. track.sps = [sps];
  10245. const codecarray = sps.subarray(1, 4);
  10246. let codecstring = "avc1.";
  10247. for (let i = 0; i < 3; i++) {
  10248. let h = codecarray[i].toString(16);
  10249. if (h.length < 2) {
  10250. h = "0" + h;
  10251. }
  10252. codecstring += h;
  10253. }
  10254. track.codec = codecstring;
  10255. }
  10256. break;
  10257. }
  10258. case 8:
  10259. push2 = true;
  10260. track.pps = [unit.data];
  10261. break;
  10262. case 9:
  10263. push2 = true;
  10264. track.audFound = true;
  10265. if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
  10266. this.pushAccessUnit(VideoSample, track);
  10267. VideoSample = null;
  10268. }
  10269. if (!VideoSample) {
  10270. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  10271. }
  10272. break;
  10273. case 12:
  10274. push2 = true;
  10275. break;
  10276. default:
  10277. push2 = false;
  10278. break;
  10279. }
  10280. if (VideoSample && push2) {
  10281. const units2 = VideoSample.units;
  10282. units2.push(unit);
  10283. }
  10284. });
  10285. if (endOfSegment && VideoSample) {
  10286. this.pushAccessUnit(VideoSample, track);
  10287. this.VideoSample = null;
  10288. }
  10289. }
  10290. getNALuType(data, offset) {
  10291. return data[offset] & 31;
  10292. }
  10293. readSliceType(data) {
  10294. const eg = new ExpGolomb(data);
  10295. eg.readUByte();
  10296. eg.readUEG();
  10297. return eg.readUEG();
  10298. }
  10299. skipScalingList(count, reader) {
  10300. let lastScale = 8;
  10301. let nextScale = 8;
  10302. let deltaScale;
  10303. for (let j = 0; j < count; j++) {
  10304. if (nextScale !== 0) {
  10305. deltaScale = reader.readEG();
  10306. nextScale = (lastScale + deltaScale + 256) % 256;
  10307. }
  10308. lastScale = nextScale === 0 ? lastScale : nextScale;
  10309. }
  10310. }
  10311. readSPS(sps) {
  10312. const eg = new ExpGolomb(sps);
  10313. let frameCropLeftOffset = 0;
  10314. let frameCropRightOffset = 0;
  10315. let frameCropTopOffset = 0;
  10316. let frameCropBottomOffset = 0;
  10317. let numRefFramesInPicOrderCntCycle;
  10318. let scalingListCount;
  10319. let i;
  10320. const readUByte = eg.readUByte.bind(eg);
  10321. const readBits = eg.readBits.bind(eg);
  10322. const readUEG = eg.readUEG.bind(eg);
  10323. const readBoolean = eg.readBoolean.bind(eg);
  10324. const skipBits = eg.skipBits.bind(eg);
  10325. const skipEG = eg.skipEG.bind(eg);
  10326. const skipUEG = eg.skipUEG.bind(eg);
  10327. const skipScalingList = this.skipScalingList.bind(this);
  10328. readUByte();
  10329. const profileIdc = readUByte();
  10330. readBits(5);
  10331. skipBits(3);
  10332. readUByte();
  10333. skipUEG();
  10334. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  10335. const chromaFormatIdc = readUEG();
  10336. if (chromaFormatIdc === 3) {
  10337. skipBits(1);
  10338. }
  10339. skipUEG();
  10340. skipUEG();
  10341. skipBits(1);
  10342. if (readBoolean()) {
  10343. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  10344. for (i = 0; i < scalingListCount; i++) {
  10345. if (readBoolean()) {
  10346. if (i < 6) {
  10347. skipScalingList(16, eg);
  10348. } else {
  10349. skipScalingList(64, eg);
  10350. }
  10351. }
  10352. }
  10353. }
  10354. }
  10355. skipUEG();
  10356. const picOrderCntType = readUEG();
  10357. if (picOrderCntType === 0) {
  10358. readUEG();
  10359. } else if (picOrderCntType === 1) {
  10360. skipBits(1);
  10361. skipEG();
  10362. skipEG();
  10363. numRefFramesInPicOrderCntCycle = readUEG();
  10364. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  10365. skipEG();
  10366. }
  10367. }
  10368. skipUEG();
  10369. skipBits(1);
  10370. const picWidthInMbsMinus1 = readUEG();
  10371. const picHeightInMapUnitsMinus1 = readUEG();
  10372. const frameMbsOnlyFlag = readBits(1);
  10373. if (frameMbsOnlyFlag === 0) {
  10374. skipBits(1);
  10375. }
  10376. skipBits(1);
  10377. if (readBoolean()) {
  10378. frameCropLeftOffset = readUEG();
  10379. frameCropRightOffset = readUEG();
  10380. frameCropTopOffset = readUEG();
  10381. frameCropBottomOffset = readUEG();
  10382. }
  10383. let pixelRatio = [1, 1];
  10384. if (readBoolean()) {
  10385. if (readBoolean()) {
  10386. const aspectRatioIdc = readUByte();
  10387. switch (aspectRatioIdc) {
  10388. case 1:
  10389. pixelRatio = [1, 1];
  10390. break;
  10391. case 2:
  10392. pixelRatio = [12, 11];
  10393. break;
  10394. case 3:
  10395. pixelRatio = [10, 11];
  10396. break;
  10397. case 4:
  10398. pixelRatio = [16, 11];
  10399. break;
  10400. case 5:
  10401. pixelRatio = [40, 33];
  10402. break;
  10403. case 6:
  10404. pixelRatio = [24, 11];
  10405. break;
  10406. case 7:
  10407. pixelRatio = [20, 11];
  10408. break;
  10409. case 8:
  10410. pixelRatio = [32, 11];
  10411. break;
  10412. case 9:
  10413. pixelRatio = [80, 33];
  10414. break;
  10415. case 10:
  10416. pixelRatio = [18, 11];
  10417. break;
  10418. case 11:
  10419. pixelRatio = [15, 11];
  10420. break;
  10421. case 12:
  10422. pixelRatio = [64, 33];
  10423. break;
  10424. case 13:
  10425. pixelRatio = [160, 99];
  10426. break;
  10427. case 14:
  10428. pixelRatio = [4, 3];
  10429. break;
  10430. case 15:
  10431. pixelRatio = [3, 2];
  10432. break;
  10433. case 16:
  10434. pixelRatio = [2, 1];
  10435. break;
  10436. case 255: {
  10437. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  10438. break;
  10439. }
  10440. }
  10441. }
  10442. }
  10443. return {
  10444. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  10445. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  10446. pixelRatio
  10447. };
  10448. }
  10449. };
  10450. var HevcVideoParser = class extends BaseVideoParser {
  10451. constructor(...args) {
  10452. super(...args);
  10453. this.initVPS = null;
  10454. }
  10455. parsePES(track, textTrack, pes, endOfSegment) {
  10456. const units = this.parseNALu(track, pes.data, endOfSegment);
  10457. let VideoSample = this.VideoSample;
  10458. let push2;
  10459. let spsfound = false;
  10460. pes.data = null;
  10461. if (VideoSample && units.length && !track.audFound) {
  10462. this.pushAccessUnit(VideoSample, track);
  10463. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  10464. }
  10465. units.forEach((unit) => {
  10466. var _VideoSample2, _VideoSample3;
  10467. switch (unit.type) {
  10468. case 0:
  10469. case 1:
  10470. case 2:
  10471. case 3:
  10472. case 4:
  10473. case 5:
  10474. case 6:
  10475. case 7:
  10476. case 8:
  10477. case 9:
  10478. if (!VideoSample) {
  10479. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  10480. }
  10481. VideoSample.frame = true;
  10482. push2 = true;
  10483. break;
  10484. case 16:
  10485. case 17:
  10486. case 18:
  10487. case 21:
  10488. push2 = true;
  10489. if (spsfound) {
  10490. var _VideoSample;
  10491. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  10492. this.pushAccessUnit(VideoSample, track);
  10493. VideoSample = this.VideoSample = null;
  10494. }
  10495. }
  10496. if (!VideoSample) {
  10497. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  10498. }
  10499. VideoSample.key = true;
  10500. VideoSample.frame = true;
  10501. break;
  10502. case 19:
  10503. case 20:
  10504. push2 = true;
  10505. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  10506. this.pushAccessUnit(VideoSample, track);
  10507. VideoSample = this.VideoSample = null;
  10508. }
  10509. if (!VideoSample) {
  10510. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  10511. }
  10512. VideoSample.key = true;
  10513. VideoSample.frame = true;
  10514. break;
  10515. case 39:
  10516. push2 = true;
  10517. parseSEIMessageFromNALu(unit.data, 2, pes.pts, textTrack.samples);
  10518. break;
  10519. case 32:
  10520. push2 = true;
  10521. if (!track.vps) {
  10522. if (typeof track.params !== "object") {
  10523. track.params = {};
  10524. }
  10525. track.params = _extends(track.params, this.readVPS(unit.data));
  10526. this.initVPS = unit.data;
  10527. }
  10528. track.vps = [unit.data];
  10529. break;
  10530. case 33:
  10531. push2 = true;
  10532. spsfound = true;
  10533. if (track.vps !== void 0 && track.vps[0] !== this.initVPS && track.sps !== void 0 && !this.matchSPS(track.sps[0], unit.data)) {
  10534. this.initVPS = track.vps[0];
  10535. track.sps = track.pps = void 0;
  10536. }
  10537. if (!track.sps) {
  10538. const config = this.readSPS(unit.data);
  10539. track.width = config.width;
  10540. track.height = config.height;
  10541. track.pixelRatio = config.pixelRatio;
  10542. track.codec = config.codecString;
  10543. track.sps = [];
  10544. if (typeof track.params !== "object") {
  10545. track.params = {};
  10546. }
  10547. for (const prop in config.params) {
  10548. track.params[prop] = config.params[prop];
  10549. }
  10550. }
  10551. this.pushParameterSet(track.sps, unit.data, track.vps);
  10552. if (!VideoSample) {
  10553. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  10554. }
  10555. VideoSample.key = true;
  10556. break;
  10557. case 34:
  10558. push2 = true;
  10559. if (typeof track.params === "object") {
  10560. if (!track.pps) {
  10561. track.pps = [];
  10562. const config = this.readPPS(unit.data);
  10563. for (const prop in config) {
  10564. track.params[prop] = config[prop];
  10565. }
  10566. }
  10567. this.pushParameterSet(track.pps, unit.data, track.vps);
  10568. }
  10569. break;
  10570. case 35:
  10571. push2 = true;
  10572. track.audFound = true;
  10573. if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
  10574. this.pushAccessUnit(VideoSample, track);
  10575. VideoSample = null;
  10576. }
  10577. if (!VideoSample) {
  10578. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  10579. }
  10580. break;
  10581. default:
  10582. push2 = false;
  10583. break;
  10584. }
  10585. if (VideoSample && push2) {
  10586. const units2 = VideoSample.units;
  10587. units2.push(unit);
  10588. }
  10589. });
  10590. if (endOfSegment && VideoSample) {
  10591. this.pushAccessUnit(VideoSample, track);
  10592. this.VideoSample = null;
  10593. }
  10594. }
  10595. pushParameterSet(parameterSets, data, vps) {
  10596. if (vps && vps[0] === this.initVPS || !vps && !parameterSets.length) {
  10597. parameterSets.push(data);
  10598. }
  10599. }
  10600. getNALuType(data, offset) {
  10601. return (data[offset] & 126) >>> 1;
  10602. }
  10603. ebsp2rbsp(arr) {
  10604. const dst = new Uint8Array(arr.byteLength);
  10605. let dstIdx = 0;
  10606. for (let i = 0; i < arr.byteLength; i++) {
  10607. if (i >= 2) {
  10608. if (arr[i] === 3 && arr[i - 1] === 0 && arr[i - 2] === 0) {
  10609. continue;
  10610. }
  10611. }
  10612. dst[dstIdx] = arr[i];
  10613. dstIdx++;
  10614. }
  10615. return new Uint8Array(dst.buffer, 0, dstIdx);
  10616. }
  10617. pushAccessUnit(VideoSample, videoTrack) {
  10618. super.pushAccessUnit(VideoSample, videoTrack);
  10619. if (this.initVPS) {
  10620. this.initVPS = null;
  10621. }
  10622. }
  10623. readVPS(vps) {
  10624. const eg = new ExpGolomb(vps);
  10625. eg.readUByte();
  10626. eg.readUByte();
  10627. eg.readBits(4);
  10628. eg.skipBits(2);
  10629. eg.readBits(6);
  10630. const max_sub_layers_minus1 = eg.readBits(3);
  10631. const temporal_id_nesting_flag = eg.readBoolean();
  10632. return {
  10633. numTemporalLayers: max_sub_layers_minus1 + 1,
  10634. temporalIdNested: temporal_id_nesting_flag
  10635. };
  10636. }
  10637. readSPS(sps) {
  10638. const eg = new ExpGolomb(this.ebsp2rbsp(sps));
  10639. eg.readUByte();
  10640. eg.readUByte();
  10641. eg.readBits(4);
  10642. const max_sub_layers_minus1 = eg.readBits(3);
  10643. eg.readBoolean();
  10644. const general_profile_space = eg.readBits(2);
  10645. const general_tier_flag = eg.readBoolean();
  10646. const general_profile_idc = eg.readBits(5);
  10647. const general_profile_compatibility_flags_1 = eg.readUByte();
  10648. const general_profile_compatibility_flags_2 = eg.readUByte();
  10649. const general_profile_compatibility_flags_3 = eg.readUByte();
  10650. const general_profile_compatibility_flags_4 = eg.readUByte();
  10651. const general_constraint_indicator_flags_1 = eg.readUByte();
  10652. const general_constraint_indicator_flags_2 = eg.readUByte();
  10653. const general_constraint_indicator_flags_3 = eg.readUByte();
  10654. const general_constraint_indicator_flags_4 = eg.readUByte();
  10655. const general_constraint_indicator_flags_5 = eg.readUByte();
  10656. const general_constraint_indicator_flags_6 = eg.readUByte();
  10657. const general_level_idc = eg.readUByte();
  10658. const sub_layer_profile_present_flags = [];
  10659. const sub_layer_level_present_flags = [];
  10660. for (let i = 0; i < max_sub_layers_minus1; i++) {
  10661. sub_layer_profile_present_flags.push(eg.readBoolean());
  10662. sub_layer_level_present_flags.push(eg.readBoolean());
  10663. }
  10664. if (max_sub_layers_minus1 > 0) {
  10665. for (let i = max_sub_layers_minus1; i < 8; i++) {
  10666. eg.readBits(2);
  10667. }
  10668. }
  10669. for (let i = 0; i < max_sub_layers_minus1; i++) {
  10670. if (sub_layer_profile_present_flags[i]) {
  10671. eg.readUByte();
  10672. eg.readUByte();
  10673. eg.readUByte();
  10674. eg.readUByte();
  10675. eg.readUByte();
  10676. eg.readUByte();
  10677. eg.readUByte();
  10678. eg.readUByte();
  10679. eg.readUByte();
  10680. eg.readUByte();
  10681. eg.readUByte();
  10682. }
  10683. if (sub_layer_level_present_flags[i]) {
  10684. eg.readUByte();
  10685. }
  10686. }
  10687. eg.readUEG();
  10688. const chroma_format_idc = eg.readUEG();
  10689. if (chroma_format_idc == 3) {
  10690. eg.skipBits(1);
  10691. }
  10692. const pic_width_in_luma_samples = eg.readUEG();
  10693. const pic_height_in_luma_samples = eg.readUEG();
  10694. const conformance_window_flag = eg.readBoolean();
  10695. let pic_left_offset = 0, pic_right_offset = 0, pic_top_offset = 0, pic_bottom_offset = 0;
  10696. if (conformance_window_flag) {
  10697. pic_left_offset += eg.readUEG();
  10698. pic_right_offset += eg.readUEG();
  10699. pic_top_offset += eg.readUEG();
  10700. pic_bottom_offset += eg.readUEG();
  10701. }
  10702. const bit_depth_luma_minus8 = eg.readUEG();
  10703. const bit_depth_chroma_minus8 = eg.readUEG();
  10704. const log2_max_pic_order_cnt_lsb_minus4 = eg.readUEG();
  10705. const sub_layer_ordering_info_present_flag = eg.readBoolean();
  10706. for (let i = sub_layer_ordering_info_present_flag ? 0 : max_sub_layers_minus1; i <= max_sub_layers_minus1; i++) {
  10707. eg.skipUEG();
  10708. eg.skipUEG();
  10709. eg.skipUEG();
  10710. }
  10711. eg.skipUEG();
  10712. eg.skipUEG();
  10713. eg.skipUEG();
  10714. eg.skipUEG();
  10715. eg.skipUEG();
  10716. eg.skipUEG();
  10717. const scaling_list_enabled_flag = eg.readBoolean();
  10718. if (scaling_list_enabled_flag) {
  10719. const sps_scaling_list_data_present_flag = eg.readBoolean();
  10720. if (sps_scaling_list_data_present_flag) {
  10721. for (let sizeId = 0; sizeId < 4; sizeId++) {
  10722. for (let matrixId = 0; matrixId < (sizeId === 3 ? 2 : 6); matrixId++) {
  10723. const scaling_list_pred_mode_flag = eg.readBoolean();
  10724. if (!scaling_list_pred_mode_flag) {
  10725. eg.readUEG();
  10726. } else {
  10727. const coefNum = Math.min(64, 1 << 4 + (sizeId << 1));
  10728. if (sizeId > 1) {
  10729. eg.readEG();
  10730. }
  10731. for (let i = 0; i < coefNum; i++) {
  10732. eg.readEG();
  10733. }
  10734. }
  10735. }
  10736. }
  10737. }
  10738. }
  10739. eg.readBoolean();
  10740. eg.readBoolean();
  10741. const pcm_enabled_flag = eg.readBoolean();
  10742. if (pcm_enabled_flag) {
  10743. eg.readUByte();
  10744. eg.skipUEG();
  10745. eg.skipUEG();
  10746. eg.readBoolean();
  10747. }
  10748. const num_short_term_ref_pic_sets = eg.readUEG();
  10749. let num_delta_pocs = 0;
  10750. for (let i = 0; i < num_short_term_ref_pic_sets; i++) {
  10751. let inter_ref_pic_set_prediction_flag = false;
  10752. if (i !== 0) {
  10753. inter_ref_pic_set_prediction_flag = eg.readBoolean();
  10754. }
  10755. if (inter_ref_pic_set_prediction_flag) {
  10756. if (i === num_short_term_ref_pic_sets) {
  10757. eg.readUEG();
  10758. }
  10759. eg.readBoolean();
  10760. eg.readUEG();
  10761. let next_num_delta_pocs = 0;
  10762. for (let j = 0; j <= num_delta_pocs; j++) {
  10763. const used_by_curr_pic_flag = eg.readBoolean();
  10764. let use_delta_flag = false;
  10765. if (!used_by_curr_pic_flag) {
  10766. use_delta_flag = eg.readBoolean();
  10767. }
  10768. if (used_by_curr_pic_flag || use_delta_flag) {
  10769. next_num_delta_pocs++;
  10770. }
  10771. }
  10772. num_delta_pocs = next_num_delta_pocs;
  10773. } else {
  10774. const num_negative_pics = eg.readUEG();
  10775. const num_positive_pics = eg.readUEG();
  10776. num_delta_pocs = num_negative_pics + num_positive_pics;
  10777. for (let j = 0; j < num_negative_pics; j++) {
  10778. eg.readUEG();
  10779. eg.readBoolean();
  10780. }
  10781. for (let j = 0; j < num_positive_pics; j++) {
  10782. eg.readUEG();
  10783. eg.readBoolean();
  10784. }
  10785. }
  10786. }
  10787. const long_term_ref_pics_present_flag = eg.readBoolean();
  10788. if (long_term_ref_pics_present_flag) {
  10789. const num_long_term_ref_pics_sps = eg.readUEG();
  10790. for (let i = 0; i < num_long_term_ref_pics_sps; i++) {
  10791. for (let j = 0; j < log2_max_pic_order_cnt_lsb_minus4 + 4; j++) {
  10792. eg.readBits(1);
  10793. }
  10794. eg.readBits(1);
  10795. }
  10796. }
  10797. let min_spatial_segmentation_idc = 0;
  10798. let sar_width = 1, sar_height = 1;
  10799. let fps_fixed = true, fps_den = 1, fps_num = 0;
  10800. eg.readBoolean();
  10801. eg.readBoolean();
  10802. let default_display_window_flag = false;
  10803. const vui_parameters_present_flag = eg.readBoolean();
  10804. if (vui_parameters_present_flag) {
  10805. const aspect_ratio_info_present_flag = eg.readBoolean();
  10806. if (aspect_ratio_info_present_flag) {
  10807. const aspect_ratio_idc = eg.readUByte();
  10808. const sar_width_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2];
  10809. const sar_height_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
  10810. if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) {
  10811. sar_width = sar_width_table[aspect_ratio_idc - 1];
  10812. sar_height = sar_height_table[aspect_ratio_idc - 1];
  10813. } else if (aspect_ratio_idc === 255) {
  10814. sar_width = eg.readBits(16);
  10815. sar_height = eg.readBits(16);
  10816. }
  10817. }
  10818. const overscan_info_present_flag = eg.readBoolean();
  10819. if (overscan_info_present_flag) {
  10820. eg.readBoolean();
  10821. }
  10822. const video_signal_type_present_flag = eg.readBoolean();
  10823. if (video_signal_type_present_flag) {
  10824. eg.readBits(3);
  10825. eg.readBoolean();
  10826. const colour_description_present_flag = eg.readBoolean();
  10827. if (colour_description_present_flag) {
  10828. eg.readUByte();
  10829. eg.readUByte();
  10830. eg.readUByte();
  10831. }
  10832. }
  10833. const chroma_loc_info_present_flag = eg.readBoolean();
  10834. if (chroma_loc_info_present_flag) {
  10835. eg.readUEG();
  10836. eg.readUEG();
  10837. }
  10838. eg.readBoolean();
  10839. eg.readBoolean();
  10840. eg.readBoolean();
  10841. default_display_window_flag = eg.readBoolean();
  10842. if (default_display_window_flag) {
  10843. pic_left_offset += eg.readUEG();
  10844. pic_right_offset += eg.readUEG();
  10845. pic_top_offset += eg.readUEG();
  10846. pic_bottom_offset += eg.readUEG();
  10847. }
  10848. const vui_timing_info_present_flag = eg.readBoolean();
  10849. if (vui_timing_info_present_flag) {
  10850. fps_den = eg.readBits(32);
  10851. fps_num = eg.readBits(32);
  10852. const vui_poc_proportional_to_timing_flag = eg.readBoolean();
  10853. if (vui_poc_proportional_to_timing_flag) {
  10854. eg.readUEG();
  10855. }
  10856. const vui_hrd_parameters_present_flag = eg.readBoolean();
  10857. if (vui_hrd_parameters_present_flag) {
  10858. const nal_hrd_parameters_present_flag = eg.readBoolean();
  10859. const vcl_hrd_parameters_present_flag = eg.readBoolean();
  10860. let sub_pic_hrd_params_present_flag = false;
  10861. if (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag) {
  10862. sub_pic_hrd_params_present_flag = eg.readBoolean();
  10863. if (sub_pic_hrd_params_present_flag) {
  10864. eg.readUByte();
  10865. eg.readBits(5);
  10866. eg.readBoolean();
  10867. eg.readBits(5);
  10868. }
  10869. eg.readBits(4);
  10870. eg.readBits(4);
  10871. if (sub_pic_hrd_params_present_flag) {
  10872. eg.readBits(4);
  10873. }
  10874. eg.readBits(5);
  10875. eg.readBits(5);
  10876. eg.readBits(5);
  10877. }
  10878. for (let i = 0; i <= max_sub_layers_minus1; i++) {
  10879. fps_fixed = eg.readBoolean();
  10880. const fixed_pic_rate_within_cvs_flag = fps_fixed || eg.readBoolean();
  10881. let low_delay_hrd_flag = false;
  10882. if (fixed_pic_rate_within_cvs_flag) {
  10883. eg.readEG();
  10884. } else {
  10885. low_delay_hrd_flag = eg.readBoolean();
  10886. }
  10887. const cpb_cnt = low_delay_hrd_flag ? 1 : eg.readUEG() + 1;
  10888. if (nal_hrd_parameters_present_flag) {
  10889. for (let j = 0; j < cpb_cnt; j++) {
  10890. eg.readUEG();
  10891. eg.readUEG();
  10892. if (sub_pic_hrd_params_present_flag) {
  10893. eg.readUEG();
  10894. eg.readUEG();
  10895. }
  10896. eg.skipBits(1);
  10897. }
  10898. }
  10899. if (vcl_hrd_parameters_present_flag) {
  10900. for (let j = 0; j < cpb_cnt; j++) {
  10901. eg.readUEG();
  10902. eg.readUEG();
  10903. if (sub_pic_hrd_params_present_flag) {
  10904. eg.readUEG();
  10905. eg.readUEG();
  10906. }
  10907. eg.skipBits(1);
  10908. }
  10909. }
  10910. }
  10911. }
  10912. }
  10913. const bitstream_restriction_flag = eg.readBoolean();
  10914. if (bitstream_restriction_flag) {
  10915. eg.readBoolean();
  10916. eg.readBoolean();
  10917. eg.readBoolean();
  10918. min_spatial_segmentation_idc = eg.readUEG();
  10919. }
  10920. }
  10921. let width = pic_width_in_luma_samples, height = pic_height_in_luma_samples;
  10922. if (conformance_window_flag || default_display_window_flag) {
  10923. let chroma_scale_w = 1, chroma_scale_h = 1;
  10924. if (chroma_format_idc === 1) {
  10925. chroma_scale_w = chroma_scale_h = 2;
  10926. } else if (chroma_format_idc == 2) {
  10927. chroma_scale_w = 2;
  10928. }
  10929. width = pic_width_in_luma_samples - chroma_scale_w * pic_right_offset - chroma_scale_w * pic_left_offset;
  10930. height = pic_height_in_luma_samples - chroma_scale_h * pic_bottom_offset - chroma_scale_h * pic_top_offset;
  10931. }
  10932. const profile_space_string = general_profile_space ? ["A", "B", "C"][general_profile_space] : "";
  10933. 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;
  10934. let profile_compatibility_rev = 0;
  10935. for (let i = 0; i < 32; i++) {
  10936. profile_compatibility_rev = (profile_compatibility_rev | (profile_compatibility_buf >> i & 1) << 31 - i) >>> 0;
  10937. }
  10938. let profile_compatibility_flags_string = profile_compatibility_rev.toString(16);
  10939. if (general_profile_idc === 1 && profile_compatibility_flags_string === "2") {
  10940. profile_compatibility_flags_string = "6";
  10941. }
  10942. const tier_flag_string = general_tier_flag ? "H" : "L";
  10943. return {
  10944. codecString: `hvc1.${profile_space_string}${general_profile_idc}.${profile_compatibility_flags_string}.${tier_flag_string}${general_level_idc}.B0`,
  10945. params: {
  10946. general_tier_flag,
  10947. general_profile_idc,
  10948. general_profile_space,
  10949. general_profile_compatibility_flags: [general_profile_compatibility_flags_1, general_profile_compatibility_flags_2, general_profile_compatibility_flags_3, general_profile_compatibility_flags_4],
  10950. 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],
  10951. general_level_idc,
  10952. bit_depth: bit_depth_luma_minus8 + 8,
  10953. bit_depth_luma_minus8,
  10954. bit_depth_chroma_minus8,
  10955. min_spatial_segmentation_idc,
  10956. chroma_format_idc,
  10957. frame_rate: {
  10958. fixed: fps_fixed,
  10959. fps: fps_num / fps_den
  10960. }
  10961. },
  10962. width,
  10963. height,
  10964. pixelRatio: [sar_width, sar_height]
  10965. };
  10966. }
  10967. readPPS(pps) {
  10968. const eg = new ExpGolomb(this.ebsp2rbsp(pps));
  10969. eg.readUByte();
  10970. eg.readUByte();
  10971. eg.skipUEG();
  10972. eg.skipUEG();
  10973. eg.skipBits(2);
  10974. eg.skipBits(3);
  10975. eg.skipBits(2);
  10976. eg.skipUEG();
  10977. eg.skipUEG();
  10978. eg.skipEG();
  10979. eg.skipBits(2);
  10980. const cu_qp_delta_enabled_flag = eg.readBoolean();
  10981. if (cu_qp_delta_enabled_flag) {
  10982. eg.skipUEG();
  10983. }
  10984. eg.skipEG();
  10985. eg.skipEG();
  10986. eg.skipBits(4);
  10987. const tiles_enabled_flag = eg.readBoolean();
  10988. const entropy_coding_sync_enabled_flag = eg.readBoolean();
  10989. let parallelismType = 1;
  10990. if (entropy_coding_sync_enabled_flag && tiles_enabled_flag) {
  10991. parallelismType = 0;
  10992. } else if (entropy_coding_sync_enabled_flag) {
  10993. parallelismType = 3;
  10994. } else if (tiles_enabled_flag) {
  10995. parallelismType = 2;
  10996. }
  10997. return {
  10998. parallelismType
  10999. };
  11000. }
  11001. matchSPS(sps1, sps2) {
  11002. return String.fromCharCode.apply(null, sps1).substr(3) === String.fromCharCode.apply(null, sps2).substr(3);
  11003. }
  11004. };
  11005. var PACKET_LENGTH = 188;
  11006. var TSDemuxer = class {
  11007. constructor(observer, config, typeSupported, logger2) {
  11008. this.logger = void 0;
  11009. this.observer = void 0;
  11010. this.config = void 0;
  11011. this.typeSupported = void 0;
  11012. this.sampleAes = null;
  11013. this.pmtParsed = false;
  11014. this.audioCodec = void 0;
  11015. this.videoCodec = void 0;
  11016. this._pmtId = -1;
  11017. this._videoTrack = void 0;
  11018. this._audioTrack = void 0;
  11019. this._id3Track = void 0;
  11020. this._txtTrack = void 0;
  11021. this.aacOverFlow = null;
  11022. this.remainderData = null;
  11023. this.videoParser = void 0;
  11024. this.observer = observer;
  11025. this.config = config;
  11026. this.typeSupported = typeSupported;
  11027. this.logger = logger2;
  11028. this.videoParser = null;
  11029. }
  11030. static probe(data, logger2) {
  11031. const syncOffset = TSDemuxer.syncOffset(data);
  11032. if (syncOffset > 0) {
  11033. logger2.warn(`MPEG2-TS detected but first sync word found @ offset ${syncOffset}`);
  11034. }
  11035. return syncOffset !== -1;
  11036. }
  11037. static syncOffset(data) {
  11038. const length = data.length;
  11039. let scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;
  11040. let i = 0;
  11041. while (i < scanwindow) {
  11042. let foundPat = false;
  11043. let packetStart = -1;
  11044. let tsPackets = 0;
  11045. for (let j = i; j < length; j += PACKET_LENGTH) {
  11046. if (data[j] === 71 && (length - j === PACKET_LENGTH || data[j + PACKET_LENGTH] === 71)) {
  11047. tsPackets++;
  11048. if (packetStart === -1) {
  11049. packetStart = j;
  11050. if (packetStart !== 0) {
  11051. scanwindow = Math.min(packetStart + PACKET_LENGTH * 99, data.length - PACKET_LENGTH) + 1;
  11052. }
  11053. }
  11054. if (!foundPat) {
  11055. foundPat = parsePID(data, j) === 0;
  11056. }
  11057. if (foundPat && tsPackets > 1 && (packetStart === 0 && tsPackets > 2 || j + PACKET_LENGTH > scanwindow)) {
  11058. return packetStart;
  11059. }
  11060. } else if (tsPackets) {
  11061. return -1;
  11062. } else {
  11063. break;
  11064. }
  11065. }
  11066. i++;
  11067. }
  11068. return -1;
  11069. }
  11070. static createTrack(type, duration) {
  11071. return {
  11072. container: type === "video" || type === "audio" ? "video/mp2t" : void 0,
  11073. type,
  11074. id: RemuxerTrackIdConfig[type],
  11075. pid: -1,
  11076. inputTimeScale: 9e4,
  11077. sequenceNumber: 0,
  11078. samples: [],
  11079. dropped: 0,
  11080. duration: type === "audio" ? duration : void 0
  11081. };
  11082. }
  11083. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  11084. this.pmtParsed = false;
  11085. this._pmtId = -1;
  11086. this._videoTrack = TSDemuxer.createTrack("video");
  11087. this._videoTrack.duration = trackDuration;
  11088. this._audioTrack = TSDemuxer.createTrack("audio", trackDuration);
  11089. this._id3Track = TSDemuxer.createTrack("id3");
  11090. this._txtTrack = TSDemuxer.createTrack("text");
  11091. this._audioTrack.segmentCodec = "aac";
  11092. this.aacOverFlow = null;
  11093. this.remainderData = null;
  11094. this.audioCodec = audioCodec;
  11095. this.videoCodec = videoCodec;
  11096. }
  11097. resetTimeStamp() {
  11098. }
  11099. resetContiguity() {
  11100. const {
  11101. _audioTrack,
  11102. _videoTrack,
  11103. _id3Track
  11104. } = this;
  11105. if (_audioTrack) {
  11106. _audioTrack.pesData = null;
  11107. }
  11108. if (_videoTrack) {
  11109. _videoTrack.pesData = null;
  11110. }
  11111. if (_id3Track) {
  11112. _id3Track.pesData = null;
  11113. }
  11114. this.aacOverFlow = null;
  11115. this.remainderData = null;
  11116. }
  11117. demux(data, timeOffset, isSampleAes = false, flush = false) {
  11118. if (!isSampleAes) {
  11119. this.sampleAes = null;
  11120. }
  11121. let pes;
  11122. const videoTrack = this._videoTrack;
  11123. const audioTrack = this._audioTrack;
  11124. const id3Track = this._id3Track;
  11125. const textTrack = this._txtTrack;
  11126. let videoPid = videoTrack.pid;
  11127. let videoData = videoTrack.pesData;
  11128. let audioPid = audioTrack.pid;
  11129. let id3Pid = id3Track.pid;
  11130. let audioData = audioTrack.pesData;
  11131. let id3Data = id3Track.pesData;
  11132. let unknownPID = null;
  11133. let pmtParsed = this.pmtParsed;
  11134. let pmtId = this._pmtId;
  11135. let len = data.length;
  11136. if (this.remainderData) {
  11137. data = appendUint8Array(this.remainderData, data);
  11138. len = data.length;
  11139. this.remainderData = null;
  11140. }
  11141. if (len < PACKET_LENGTH && !flush) {
  11142. this.remainderData = data;
  11143. return {
  11144. audioTrack,
  11145. videoTrack,
  11146. id3Track,
  11147. textTrack
  11148. };
  11149. }
  11150. const syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
  11151. len -= (len - syncOffset) % PACKET_LENGTH;
  11152. if (len < data.byteLength && !flush) {
  11153. this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
  11154. }
  11155. let tsPacketErrors = 0;
  11156. for (let start = syncOffset; start < len; start += PACKET_LENGTH) {
  11157. if (data[start] === 71) {
  11158. const stt = !!(data[start + 1] & 64);
  11159. const pid = parsePID(data, start);
  11160. const atf = (data[start + 3] & 48) >> 4;
  11161. let offset;
  11162. if (atf > 1) {
  11163. offset = start + 5 + data[start + 4];
  11164. if (offset === start + PACKET_LENGTH) {
  11165. continue;
  11166. }
  11167. } else {
  11168. offset = start + 4;
  11169. }
  11170. switch (pid) {
  11171. case videoPid:
  11172. if (stt) {
  11173. if (videoData && (pes = parsePES(videoData, this.logger))) {
  11174. if (this.videoParser === null) {
  11175. switch (videoTrack.segmentCodec) {
  11176. case "avc":
  11177. this.videoParser = new AvcVideoParser();
  11178. break;
  11179. case "hevc":
  11180. {
  11181. this.videoParser = new HevcVideoParser();
  11182. }
  11183. break;
  11184. }
  11185. }
  11186. if (this.videoParser !== null) {
  11187. this.videoParser.parsePES(videoTrack, textTrack, pes, false);
  11188. }
  11189. }
  11190. videoData = {
  11191. data: [],
  11192. size: 0
  11193. };
  11194. }
  11195. if (videoData) {
  11196. videoData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  11197. videoData.size += start + PACKET_LENGTH - offset;
  11198. }
  11199. break;
  11200. case audioPid:
  11201. if (stt) {
  11202. if (audioData && (pes = parsePES(audioData, this.logger))) {
  11203. switch (audioTrack.segmentCodec) {
  11204. case "aac":
  11205. this.parseAACPES(audioTrack, pes);
  11206. break;
  11207. case "mp3":
  11208. this.parseMPEGPES(audioTrack, pes);
  11209. break;
  11210. case "ac3":
  11211. {
  11212. this.parseAC3PES(audioTrack, pes);
  11213. }
  11214. break;
  11215. }
  11216. }
  11217. audioData = {
  11218. data: [],
  11219. size: 0
  11220. };
  11221. }
  11222. if (audioData) {
  11223. audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  11224. audioData.size += start + PACKET_LENGTH - offset;
  11225. }
  11226. break;
  11227. case id3Pid:
  11228. if (stt) {
  11229. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  11230. this.parseID3PES(id3Track, pes);
  11231. }
  11232. id3Data = {
  11233. data: [],
  11234. size: 0
  11235. };
  11236. }
  11237. if (id3Data) {
  11238. id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));
  11239. id3Data.size += start + PACKET_LENGTH - offset;
  11240. }
  11241. break;
  11242. case 0:
  11243. if (stt) {
  11244. offset += data[offset] + 1;
  11245. }
  11246. pmtId = this._pmtId = parsePAT(data, offset);
  11247. break;
  11248. case pmtId: {
  11249. if (stt) {
  11250. offset += data[offset] + 1;
  11251. }
  11252. const parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes, this.observer, this.logger);
  11253. videoPid = parsedPIDs.videoPid;
  11254. if (videoPid > 0) {
  11255. videoTrack.pid = videoPid;
  11256. videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;
  11257. }
  11258. audioPid = parsedPIDs.audioPid;
  11259. if (audioPid > 0) {
  11260. audioTrack.pid = audioPid;
  11261. audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;
  11262. }
  11263. id3Pid = parsedPIDs.id3Pid;
  11264. if (id3Pid > 0) {
  11265. id3Track.pid = id3Pid;
  11266. }
  11267. if (unknownPID !== null && !pmtParsed) {
  11268. this.logger.warn(`MPEG-TS PMT found at ${start} after unknown PID '${unknownPID}'. Backtracking to sync byte @${syncOffset} to parse all TS packets.`);
  11269. unknownPID = null;
  11270. start = syncOffset - 188;
  11271. }
  11272. pmtParsed = this.pmtParsed = true;
  11273. break;
  11274. }
  11275. case 17:
  11276. case 8191:
  11277. break;
  11278. default:
  11279. unknownPID = pid;
  11280. break;
  11281. }
  11282. } else {
  11283. tsPacketErrors++;
  11284. }
  11285. }
  11286. if (tsPacketErrors > 0) {
  11287. emitParsingError(this.observer, new Error(`Found ${tsPacketErrors} TS packet/s that do not start with 0x47`), void 0, this.logger);
  11288. }
  11289. videoTrack.pesData = videoData;
  11290. audioTrack.pesData = audioData;
  11291. id3Track.pesData = id3Data;
  11292. const demuxResult = {
  11293. audioTrack,
  11294. videoTrack,
  11295. id3Track,
  11296. textTrack
  11297. };
  11298. if (flush) {
  11299. this.extractRemainingSamples(demuxResult);
  11300. }
  11301. return demuxResult;
  11302. }
  11303. flush() {
  11304. const {
  11305. remainderData
  11306. } = this;
  11307. this.remainderData = null;
  11308. let result;
  11309. if (remainderData) {
  11310. result = this.demux(remainderData, -1, false, true);
  11311. } else {
  11312. result = {
  11313. videoTrack: this._videoTrack,
  11314. audioTrack: this._audioTrack,
  11315. id3Track: this._id3Track,
  11316. textTrack: this._txtTrack
  11317. };
  11318. }
  11319. this.extractRemainingSamples(result);
  11320. if (this.sampleAes) {
  11321. return this.decrypt(result, this.sampleAes);
  11322. }
  11323. return result;
  11324. }
  11325. extractRemainingSamples(demuxResult) {
  11326. const {
  11327. audioTrack,
  11328. videoTrack,
  11329. id3Track,
  11330. textTrack
  11331. } = demuxResult;
  11332. const videoData = videoTrack.pesData;
  11333. const audioData = audioTrack.pesData;
  11334. const id3Data = id3Track.pesData;
  11335. let pes;
  11336. if (videoData && (pes = parsePES(videoData, this.logger))) {
  11337. if (this.videoParser === null) {
  11338. switch (videoTrack.segmentCodec) {
  11339. case "avc":
  11340. this.videoParser = new AvcVideoParser();
  11341. break;
  11342. case "hevc":
  11343. {
  11344. this.videoParser = new HevcVideoParser();
  11345. }
  11346. break;
  11347. }
  11348. }
  11349. if (this.videoParser !== null) {
  11350. this.videoParser.parsePES(videoTrack, textTrack, pes, true);
  11351. videoTrack.pesData = null;
  11352. }
  11353. } else {
  11354. videoTrack.pesData = videoData;
  11355. }
  11356. if (audioData && (pes = parsePES(audioData, this.logger))) {
  11357. switch (audioTrack.segmentCodec) {
  11358. case "aac":
  11359. this.parseAACPES(audioTrack, pes);
  11360. break;
  11361. case "mp3":
  11362. this.parseMPEGPES(audioTrack, pes);
  11363. break;
  11364. case "ac3":
  11365. {
  11366. this.parseAC3PES(audioTrack, pes);
  11367. }
  11368. break;
  11369. }
  11370. audioTrack.pesData = null;
  11371. } else {
  11372. if (audioData != null && audioData.size) {
  11373. this.logger.log("last AAC PES packet truncated,might overlap between fragments");
  11374. }
  11375. audioTrack.pesData = audioData;
  11376. }
  11377. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  11378. this.parseID3PES(id3Track, pes);
  11379. id3Track.pesData = null;
  11380. } else {
  11381. id3Track.pesData = id3Data;
  11382. }
  11383. }
  11384. demuxSampleAes(data, keyData, timeOffset) {
  11385. const demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
  11386. const sampleAes = this.sampleAes = new SampleAesDecrypter(this.observer, this.config, keyData);
  11387. return this.decrypt(demuxResult, sampleAes);
  11388. }
  11389. decrypt(demuxResult, sampleAes) {
  11390. return new Promise((resolve) => {
  11391. const {
  11392. audioTrack,
  11393. videoTrack
  11394. } = demuxResult;
  11395. if (audioTrack.samples && audioTrack.segmentCodec === "aac") {
  11396. sampleAes.decryptAacSamples(audioTrack.samples, 0, () => {
  11397. if (videoTrack.samples) {
  11398. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  11399. resolve(demuxResult);
  11400. });
  11401. } else {
  11402. resolve(demuxResult);
  11403. }
  11404. });
  11405. } else if (videoTrack.samples) {
  11406. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  11407. resolve(demuxResult);
  11408. });
  11409. }
  11410. });
  11411. }
  11412. destroy() {
  11413. if (this.observer) {
  11414. this.observer.removeAllListeners();
  11415. }
  11416. this.config = this.logger = this.observer = null;
  11417. this.aacOverFlow = this.videoParser = this.remainderData = this.sampleAes = null;
  11418. this._videoTrack = this._audioTrack = this._id3Track = this._txtTrack = void 0;
  11419. }
  11420. parseAACPES(track, pes) {
  11421. let startOffset = 0;
  11422. const aacOverFlow = this.aacOverFlow;
  11423. let data = pes.data;
  11424. if (aacOverFlow) {
  11425. this.aacOverFlow = null;
  11426. const frameMissingBytes = aacOverFlow.missing;
  11427. const sampleLength = aacOverFlow.sample.unit.byteLength;
  11428. if (frameMissingBytes === -1) {
  11429. data = appendUint8Array(aacOverFlow.sample.unit, data);
  11430. } else {
  11431. const frameOverflowBytes = sampleLength - frameMissingBytes;
  11432. aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
  11433. track.samples.push(aacOverFlow.sample);
  11434. startOffset = aacOverFlow.missing;
  11435. }
  11436. }
  11437. let offset;
  11438. let len;
  11439. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  11440. if (isHeader$1(data, offset)) {
  11441. break;
  11442. }
  11443. }
  11444. if (offset !== startOffset) {
  11445. let reason;
  11446. const recoverable = offset < len - 1;
  11447. if (recoverable) {
  11448. reason = `AAC PES did not start with ADTS header,offset:${offset}`;
  11449. } else {
  11450. reason = "No ADTS header found in AAC PES";
  11451. }
  11452. emitParsingError(this.observer, new Error(reason), recoverable, this.logger);
  11453. if (!recoverable) {
  11454. return;
  11455. }
  11456. }
  11457. initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  11458. let pts;
  11459. if (pes.pts !== void 0) {
  11460. pts = pes.pts;
  11461. } else if (aacOverFlow) {
  11462. const frameDuration = getFrameDuration(track.samplerate);
  11463. pts = aacOverFlow.sample.pts + frameDuration;
  11464. } else {
  11465. this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");
  11466. return;
  11467. }
  11468. let frameIndex = 0;
  11469. let frame;
  11470. while (offset < len) {
  11471. frame = appendFrame$2(track, data, offset, pts, frameIndex);
  11472. offset += frame.length;
  11473. if (!frame.missing) {
  11474. frameIndex++;
  11475. for (; offset < len - 1; offset++) {
  11476. if (isHeader$1(data, offset)) {
  11477. break;
  11478. }
  11479. }
  11480. } else {
  11481. this.aacOverFlow = frame;
  11482. break;
  11483. }
  11484. }
  11485. }
  11486. parseMPEGPES(track, pes) {
  11487. const data = pes.data;
  11488. const length = data.length;
  11489. let frameIndex = 0;
  11490. let offset = 0;
  11491. const pts = pes.pts;
  11492. if (pts === void 0) {
  11493. this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");
  11494. return;
  11495. }
  11496. while (offset < length) {
  11497. if (isHeader(data, offset)) {
  11498. const frame = appendFrame$1(track, data, offset, pts, frameIndex);
  11499. if (frame) {
  11500. offset += frame.length;
  11501. frameIndex++;
  11502. } else {
  11503. break;
  11504. }
  11505. } else {
  11506. offset++;
  11507. }
  11508. }
  11509. }
  11510. parseAC3PES(track, pes) {
  11511. {
  11512. const data = pes.data;
  11513. const pts = pes.pts;
  11514. if (pts === void 0) {
  11515. this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");
  11516. return;
  11517. }
  11518. const length = data.length;
  11519. let frameIndex = 0;
  11520. let offset = 0;
  11521. let parsed;
  11522. while (offset < length && (parsed = appendFrame(track, data, offset, pts, frameIndex++)) > 0) {
  11523. offset += parsed;
  11524. }
  11525. }
  11526. }
  11527. parseID3PES(id3Track, pes) {
  11528. if (pes.pts === void 0) {
  11529. this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");
  11530. return;
  11531. }
  11532. const id3Sample = _extends({}, pes, {
  11533. type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,
  11534. duration: Number.POSITIVE_INFINITY
  11535. });
  11536. id3Track.samples.push(id3Sample);
  11537. }
  11538. };
  11539. function parsePID(data, offset) {
  11540. return ((data[offset + 1] & 31) << 8) + data[offset + 2];
  11541. }
  11542. function parsePAT(data, offset) {
  11543. return (data[offset + 10] & 31) << 8 | data[offset + 11];
  11544. }
  11545. function parsePMT(data, offset, typeSupported, isSampleAes, observer, logger2) {
  11546. const result = {
  11547. audioPid: -1,
  11548. videoPid: -1,
  11549. id3Pid: -1,
  11550. segmentVideoCodec: "avc",
  11551. segmentAudioCodec: "aac"
  11552. };
  11553. const sectionLength = (data[offset + 1] & 15) << 8 | data[offset + 2];
  11554. const tableEnd = offset + 3 + sectionLength - 4;
  11555. const programInfoLength = (data[offset + 10] & 15) << 8 | data[offset + 11];
  11556. offset += 12 + programInfoLength;
  11557. while (offset < tableEnd) {
  11558. const pid = parsePID(data, offset);
  11559. const esInfoLength = (data[offset + 3] & 15) << 8 | data[offset + 4];
  11560. switch (data[offset]) {
  11561. case 207:
  11562. if (!isSampleAes) {
  11563. logEncryptedSamplesFoundInUnencryptedStream("ADTS AAC", logger2);
  11564. break;
  11565. }
  11566. case 15:
  11567. if (result.audioPid === -1) {
  11568. result.audioPid = pid;
  11569. }
  11570. break;
  11571. case 21:
  11572. if (result.id3Pid === -1) {
  11573. result.id3Pid = pid;
  11574. }
  11575. break;
  11576. case 219:
  11577. if (!isSampleAes) {
  11578. logEncryptedSamplesFoundInUnencryptedStream("H.264", logger2);
  11579. break;
  11580. }
  11581. case 27:
  11582. if (result.videoPid === -1) {
  11583. result.videoPid = pid;
  11584. }
  11585. break;
  11586. case 3:
  11587. case 4:
  11588. if (!typeSupported.mpeg && !typeSupported.mp3) {
  11589. logger2.log("MPEG audio found, not supported in this browser");
  11590. } else if (result.audioPid === -1) {
  11591. result.audioPid = pid;
  11592. result.segmentAudioCodec = "mp3";
  11593. }
  11594. break;
  11595. case 193:
  11596. if (!isSampleAes) {
  11597. logEncryptedSamplesFoundInUnencryptedStream("AC-3", logger2);
  11598. break;
  11599. }
  11600. case 129:
  11601. {
  11602. if (!typeSupported.ac3) {
  11603. logger2.log("AC-3 audio found, not supported in this browser");
  11604. } else if (result.audioPid === -1) {
  11605. result.audioPid = pid;
  11606. result.segmentAudioCodec = "ac3";
  11607. }
  11608. }
  11609. break;
  11610. case 6:
  11611. if (result.audioPid === -1 && esInfoLength > 0) {
  11612. let parsePos = offset + 5;
  11613. let remaining = esInfoLength;
  11614. while (remaining > 2) {
  11615. const descriptorId = data[parsePos];
  11616. switch (descriptorId) {
  11617. case 106:
  11618. {
  11619. if (typeSupported.ac3 !== true) {
  11620. logger2.log("AC-3 audio found, not supported in this browser for now");
  11621. } else {
  11622. result.audioPid = pid;
  11623. result.segmentAudioCodec = "ac3";
  11624. }
  11625. }
  11626. break;
  11627. }
  11628. const descriptorLen = data[parsePos + 1] + 2;
  11629. parsePos += descriptorLen;
  11630. remaining -= descriptorLen;
  11631. }
  11632. }
  11633. break;
  11634. case 194:
  11635. case 135:
  11636. emitParsingError(observer, new Error("Unsupported EC-3 in M2TS found"), void 0, logger2);
  11637. return result;
  11638. case 36:
  11639. {
  11640. if (result.videoPid === -1) {
  11641. result.videoPid = pid;
  11642. result.segmentVideoCodec = "hevc";
  11643. logger2.log("HEVC in M2TS found");
  11644. }
  11645. }
  11646. break;
  11647. }
  11648. offset += esInfoLength + 5;
  11649. }
  11650. return result;
  11651. }
  11652. function emitParsingError(observer, error, levelRetry, logger2) {
  11653. logger2.warn(`parsing error: ${error.message}`);
  11654. observer.emit(Events.ERROR, Events.ERROR, {
  11655. type: ErrorTypes.MEDIA_ERROR,
  11656. details: ErrorDetails.FRAG_PARSING_ERROR,
  11657. fatal: false,
  11658. levelRetry,
  11659. error,
  11660. reason: error.message
  11661. });
  11662. }
  11663. function logEncryptedSamplesFoundInUnencryptedStream(type, logger2) {
  11664. logger2.log(`${type} with AES-128-CBC encryption found in unencrypted stream`);
  11665. }
  11666. function parsePES(stream, logger2) {
  11667. let i = 0;
  11668. let frag;
  11669. let pesLen;
  11670. let pesHdrLen;
  11671. let pesPts;
  11672. let pesDts;
  11673. const data = stream.data;
  11674. if (!stream || stream.size === 0) {
  11675. return null;
  11676. }
  11677. while (data[0].length < 19 && data.length > 1) {
  11678. data[0] = appendUint8Array(data[0], data[1]);
  11679. data.splice(1, 1);
  11680. }
  11681. frag = data[0];
  11682. const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  11683. if (pesPrefix === 1) {
  11684. pesLen = (frag[4] << 8) + frag[5];
  11685. if (pesLen && pesLen > stream.size - 6) {
  11686. return null;
  11687. }
  11688. const pesFlags = frag[7];
  11689. if (pesFlags & 192) {
  11690. pesPts = (frag[9] & 14) * 536870912 + (frag[10] & 255) * 4194304 + (frag[11] & 254) * 16384 + (frag[12] & 255) * 128 + (frag[13] & 254) / 2;
  11691. if (pesFlags & 64) {
  11692. pesDts = (frag[14] & 14) * 536870912 + (frag[15] & 255) * 4194304 + (frag[16] & 254) * 16384 + (frag[17] & 255) * 128 + (frag[18] & 254) / 2;
  11693. if (pesPts - pesDts > 60 * 9e4) {
  11694. logger2.warn(`${Math.round((pesPts - pesDts) / 9e4)}s delta between PTS and DTS, align them`);
  11695. pesPts = pesDts;
  11696. }
  11697. } else {
  11698. pesDts = pesPts;
  11699. }
  11700. }
  11701. pesHdrLen = frag[8];
  11702. let payloadStartOffset = pesHdrLen + 9;
  11703. if (stream.size <= payloadStartOffset) {
  11704. return null;
  11705. }
  11706. stream.size -= payloadStartOffset;
  11707. const pesData = new Uint8Array(stream.size);
  11708. for (let j = 0, dataLen = data.length; j < dataLen; j++) {
  11709. frag = data[j];
  11710. let len = frag.byteLength;
  11711. if (payloadStartOffset) {
  11712. if (payloadStartOffset > len) {
  11713. payloadStartOffset -= len;
  11714. continue;
  11715. } else {
  11716. frag = frag.subarray(payloadStartOffset);
  11717. len -= payloadStartOffset;
  11718. payloadStartOffset = 0;
  11719. }
  11720. }
  11721. pesData.set(frag, i);
  11722. i += len;
  11723. }
  11724. if (pesLen) {
  11725. pesLen -= pesHdrLen + 3;
  11726. }
  11727. return {
  11728. data: pesData,
  11729. pts: pesPts,
  11730. dts: pesDts,
  11731. len: pesLen
  11732. };
  11733. }
  11734. return null;
  11735. }
  11736. var AAC = class {
  11737. static getSilentFrame(codec, channelCount) {
  11738. switch (codec) {
  11739. case "mp4a.40.2":
  11740. if (channelCount === 1) {
  11741. return new Uint8Array([0, 200, 0, 128, 35, 128]);
  11742. } else if (channelCount === 2) {
  11743. return new Uint8Array([33, 0, 73, 144, 2, 25, 0, 35, 128]);
  11744. } else if (channelCount === 3) {
  11745. return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 142]);
  11746. } else if (channelCount === 4) {
  11747. return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 128, 44, 128, 8, 2, 56]);
  11748. } else if (channelCount === 5) {
  11749. return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 56]);
  11750. } else if (channelCount === 6) {
  11751. 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]);
  11752. }
  11753. break;
  11754. default:
  11755. if (channelCount === 1) {
  11756. 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]);
  11757. } else if (channelCount === 2) {
  11758. 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]);
  11759. } else if (channelCount === 3) {
  11760. 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]);
  11761. }
  11762. break;
  11763. }
  11764. return void 0;
  11765. }
  11766. };
  11767. var UINT32_MAX = Math.pow(2, 32) - 1;
  11768. var MP4 = class {
  11769. static init() {
  11770. MP4.types = {
  11771. avc1: [],
  11772. avcC: [],
  11773. hvc1: [],
  11774. hvcC: [],
  11775. btrt: [],
  11776. dinf: [],
  11777. dref: [],
  11778. esds: [],
  11779. ftyp: [],
  11780. hdlr: [],
  11781. mdat: [],
  11782. mdhd: [],
  11783. mdia: [],
  11784. mfhd: [],
  11785. minf: [],
  11786. moof: [],
  11787. moov: [],
  11788. mp4a: [],
  11789. ".mp3": [],
  11790. dac3: [],
  11791. "ac-3": [],
  11792. mvex: [],
  11793. mvhd: [],
  11794. pasp: [],
  11795. sdtp: [],
  11796. stbl: [],
  11797. stco: [],
  11798. stsc: [],
  11799. stsd: [],
  11800. stsz: [],
  11801. stts: [],
  11802. tfdt: [],
  11803. tfhd: [],
  11804. traf: [],
  11805. trak: [],
  11806. trun: [],
  11807. trex: [],
  11808. tkhd: [],
  11809. vmhd: [],
  11810. smhd: []
  11811. };
  11812. let i;
  11813. for (i in MP4.types) {
  11814. if (MP4.types.hasOwnProperty(i)) {
  11815. MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  11816. }
  11817. }
  11818. const videoHdlr = new Uint8Array([
  11819. 0,
  11820. 0,
  11821. 0,
  11822. 0,
  11823. 0,
  11824. 0,
  11825. 0,
  11826. 0,
  11827. 118,
  11828. 105,
  11829. 100,
  11830. 101,
  11831. 0,
  11832. 0,
  11833. 0,
  11834. 0,
  11835. 0,
  11836. 0,
  11837. 0,
  11838. 0,
  11839. 0,
  11840. 0,
  11841. 0,
  11842. 0,
  11843. 86,
  11844. 105,
  11845. 100,
  11846. 101,
  11847. 111,
  11848. 72,
  11849. 97,
  11850. 110,
  11851. 100,
  11852. 108,
  11853. 101,
  11854. 114,
  11855. 0
  11856. ]);
  11857. const audioHdlr = new Uint8Array([
  11858. 0,
  11859. 0,
  11860. 0,
  11861. 0,
  11862. 0,
  11863. 0,
  11864. 0,
  11865. 0,
  11866. 115,
  11867. 111,
  11868. 117,
  11869. 110,
  11870. 0,
  11871. 0,
  11872. 0,
  11873. 0,
  11874. 0,
  11875. 0,
  11876. 0,
  11877. 0,
  11878. 0,
  11879. 0,
  11880. 0,
  11881. 0,
  11882. 83,
  11883. 111,
  11884. 117,
  11885. 110,
  11886. 100,
  11887. 72,
  11888. 97,
  11889. 110,
  11890. 100,
  11891. 108,
  11892. 101,
  11893. 114,
  11894. 0
  11895. ]);
  11896. MP4.HDLR_TYPES = {
  11897. video: videoHdlr,
  11898. audio: audioHdlr
  11899. };
  11900. const dref = new Uint8Array([
  11901. 0,
  11902. 0,
  11903. 0,
  11904. 0,
  11905. 0,
  11906. 0,
  11907. 0,
  11908. 1,
  11909. 0,
  11910. 0,
  11911. 0,
  11912. 12,
  11913. 117,
  11914. 114,
  11915. 108,
  11916. 32,
  11917. 0,
  11918. 0,
  11919. 0,
  11920. 1
  11921. ]);
  11922. const stco = new Uint8Array([
  11923. 0,
  11924. 0,
  11925. 0,
  11926. 0,
  11927. 0,
  11928. 0,
  11929. 0,
  11930. 0
  11931. ]);
  11932. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  11933. MP4.STSZ = new Uint8Array([
  11934. 0,
  11935. 0,
  11936. 0,
  11937. 0,
  11938. 0,
  11939. 0,
  11940. 0,
  11941. 0,
  11942. 0,
  11943. 0,
  11944. 0,
  11945. 0
  11946. ]);
  11947. MP4.VMHD = new Uint8Array([
  11948. 0,
  11949. 0,
  11950. 0,
  11951. 1,
  11952. 0,
  11953. 0,
  11954. 0,
  11955. 0,
  11956. 0,
  11957. 0,
  11958. 0,
  11959. 0
  11960. ]);
  11961. MP4.SMHD = new Uint8Array([
  11962. 0,
  11963. 0,
  11964. 0,
  11965. 0,
  11966. 0,
  11967. 0,
  11968. 0,
  11969. 0
  11970. ]);
  11971. MP4.STSD = new Uint8Array([
  11972. 0,
  11973. 0,
  11974. 0,
  11975. 0,
  11976. 0,
  11977. 0,
  11978. 0,
  11979. 1
  11980. ]);
  11981. const majorBrand = new Uint8Array([105, 115, 111, 109]);
  11982. const avc1Brand = new Uint8Array([97, 118, 99, 49]);
  11983. const minorVersion = new Uint8Array([0, 0, 0, 1]);
  11984. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  11985. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  11986. }
  11987. static box(type, ...payload) {
  11988. let size = 8;
  11989. let i = payload.length;
  11990. const len = i;
  11991. while (i--) {
  11992. size += payload[i].byteLength;
  11993. }
  11994. const result = new Uint8Array(size);
  11995. result[0] = size >> 24 & 255;
  11996. result[1] = size >> 16 & 255;
  11997. result[2] = size >> 8 & 255;
  11998. result[3] = size & 255;
  11999. result.set(type, 4);
  12000. for (i = 0, size = 8; i < len; i++) {
  12001. result.set(payload[i], size);
  12002. size += payload[i].byteLength;
  12003. }
  12004. return result;
  12005. }
  12006. static hdlr(type) {
  12007. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  12008. }
  12009. static mdat(data) {
  12010. return MP4.box(MP4.types.mdat, data);
  12011. }
  12012. static mdhd(timescale, duration) {
  12013. duration *= timescale;
  12014. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  12015. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  12016. return MP4.box(MP4.types.mdhd, new Uint8Array([
  12017. 1,
  12018. 0,
  12019. 0,
  12020. 0,
  12021. 0,
  12022. 0,
  12023. 0,
  12024. 0,
  12025. 0,
  12026. 0,
  12027. 0,
  12028. 2,
  12029. 0,
  12030. 0,
  12031. 0,
  12032. 0,
  12033. 0,
  12034. 0,
  12035. 0,
  12036. 3,
  12037. timescale >> 24 & 255,
  12038. timescale >> 16 & 255,
  12039. timescale >> 8 & 255,
  12040. timescale & 255,
  12041. upperWordDuration >> 24,
  12042. upperWordDuration >> 16 & 255,
  12043. upperWordDuration >> 8 & 255,
  12044. upperWordDuration & 255,
  12045. lowerWordDuration >> 24,
  12046. lowerWordDuration >> 16 & 255,
  12047. lowerWordDuration >> 8 & 255,
  12048. lowerWordDuration & 255,
  12049. 85,
  12050. 196,
  12051. 0,
  12052. 0
  12053. ]));
  12054. }
  12055. static mdia(track) {
  12056. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale || 0, track.duration || 0), MP4.hdlr(track.type), MP4.minf(track));
  12057. }
  12058. static mfhd(sequenceNumber) {
  12059. return MP4.box(MP4.types.mfhd, new Uint8Array([
  12060. 0,
  12061. 0,
  12062. 0,
  12063. 0,
  12064. sequenceNumber >> 24,
  12065. sequenceNumber >> 16 & 255,
  12066. sequenceNumber >> 8 & 255,
  12067. sequenceNumber & 255
  12068. ]));
  12069. }
  12070. static minf(track) {
  12071. if (track.type === "audio") {
  12072. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  12073. } else {
  12074. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  12075. }
  12076. }
  12077. static moof(sn, baseMediaDecodeTime, track) {
  12078. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  12079. }
  12080. static moov(tracks) {
  12081. let i = tracks.length;
  12082. const boxes = [];
  12083. while (i--) {
  12084. boxes[i] = MP4.trak(tracks[i]);
  12085. }
  12086. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale || 0, tracks[0].duration || 0)].concat(boxes).concat(MP4.mvex(tracks)));
  12087. }
  12088. static mvex(tracks) {
  12089. let i = tracks.length;
  12090. const boxes = [];
  12091. while (i--) {
  12092. boxes[i] = MP4.trex(tracks[i]);
  12093. }
  12094. return MP4.box.apply(null, [MP4.types.mvex, ...boxes]);
  12095. }
  12096. static mvhd(timescale, duration) {
  12097. duration *= timescale;
  12098. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  12099. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  12100. const bytes = new Uint8Array([
  12101. 1,
  12102. 0,
  12103. 0,
  12104. 0,
  12105. 0,
  12106. 0,
  12107. 0,
  12108. 0,
  12109. 0,
  12110. 0,
  12111. 0,
  12112. 2,
  12113. 0,
  12114. 0,
  12115. 0,
  12116. 0,
  12117. 0,
  12118. 0,
  12119. 0,
  12120. 3,
  12121. timescale >> 24 & 255,
  12122. timescale >> 16 & 255,
  12123. timescale >> 8 & 255,
  12124. timescale & 255,
  12125. upperWordDuration >> 24,
  12126. upperWordDuration >> 16 & 255,
  12127. upperWordDuration >> 8 & 255,
  12128. upperWordDuration & 255,
  12129. lowerWordDuration >> 24,
  12130. lowerWordDuration >> 16 & 255,
  12131. lowerWordDuration >> 8 & 255,
  12132. lowerWordDuration & 255,
  12133. 0,
  12134. 1,
  12135. 0,
  12136. 0,
  12137. 1,
  12138. 0,
  12139. 0,
  12140. 0,
  12141. 0,
  12142. 0,
  12143. 0,
  12144. 0,
  12145. 0,
  12146. 0,
  12147. 0,
  12148. 0,
  12149. 0,
  12150. 1,
  12151. 0,
  12152. 0,
  12153. 0,
  12154. 0,
  12155. 0,
  12156. 0,
  12157. 0,
  12158. 0,
  12159. 0,
  12160. 0,
  12161. 0,
  12162. 0,
  12163. 0,
  12164. 0,
  12165. 0,
  12166. 1,
  12167. 0,
  12168. 0,
  12169. 0,
  12170. 0,
  12171. 0,
  12172. 0,
  12173. 0,
  12174. 0,
  12175. 0,
  12176. 0,
  12177. 0,
  12178. 0,
  12179. 0,
  12180. 0,
  12181. 64,
  12182. 0,
  12183. 0,
  12184. 0,
  12185. 0,
  12186. 0,
  12187. 0,
  12188. 0,
  12189. 0,
  12190. 0,
  12191. 0,
  12192. 0,
  12193. 0,
  12194. 0,
  12195. 0,
  12196. 0,
  12197. 0,
  12198. 0,
  12199. 0,
  12200. 0,
  12201. 0,
  12202. 0,
  12203. 0,
  12204. 0,
  12205. 0,
  12206. 0,
  12207. 0,
  12208. 0,
  12209. 255,
  12210. 255,
  12211. 255,
  12212. 255
  12213. ]);
  12214. return MP4.box(MP4.types.mvhd, bytes);
  12215. }
  12216. static sdtp(track) {
  12217. const samples = track.samples || [];
  12218. const bytes = new Uint8Array(4 + samples.length);
  12219. let i;
  12220. let flags;
  12221. for (i = 0; i < samples.length; i++) {
  12222. flags = samples[i].flags;
  12223. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  12224. }
  12225. return MP4.box(MP4.types.sdtp, bytes);
  12226. }
  12227. static stbl(track) {
  12228. 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));
  12229. }
  12230. static avc1(track) {
  12231. let sps = [];
  12232. let pps = [];
  12233. let i;
  12234. let data;
  12235. let len;
  12236. for (i = 0; i < track.sps.length; i++) {
  12237. data = track.sps[i];
  12238. len = data.byteLength;
  12239. sps.push(len >>> 8 & 255);
  12240. sps.push(len & 255);
  12241. sps = sps.concat(Array.prototype.slice.call(data));
  12242. }
  12243. for (i = 0; i < track.pps.length; i++) {
  12244. data = track.pps[i];
  12245. len = data.byteLength;
  12246. pps.push(len >>> 8 & 255);
  12247. pps.push(len & 255);
  12248. pps = pps.concat(Array.prototype.slice.call(data));
  12249. }
  12250. const avcc = MP4.box(MP4.types.avcC, new Uint8Array([
  12251. 1,
  12252. sps[3],
  12253. sps[4],
  12254. sps[5],
  12255. 252 | 3,
  12256. 224 | track.sps.length
  12257. ].concat(sps).concat([
  12258. track.pps.length
  12259. ]).concat(pps)));
  12260. const width = track.width;
  12261. const height = track.height;
  12262. const hSpacing = track.pixelRatio[0];
  12263. const vSpacing = track.pixelRatio[1];
  12264. return MP4.box(MP4.types.avc1, new Uint8Array([
  12265. 0,
  12266. 0,
  12267. 0,
  12268. 0,
  12269. 0,
  12270. 0,
  12271. 0,
  12272. 1,
  12273. 0,
  12274. 0,
  12275. 0,
  12276. 0,
  12277. 0,
  12278. 0,
  12279. 0,
  12280. 0,
  12281. 0,
  12282. 0,
  12283. 0,
  12284. 0,
  12285. 0,
  12286. 0,
  12287. 0,
  12288. 0,
  12289. width >> 8 & 255,
  12290. width & 255,
  12291. height >> 8 & 255,
  12292. height & 255,
  12293. 0,
  12294. 72,
  12295. 0,
  12296. 0,
  12297. 0,
  12298. 72,
  12299. 0,
  12300. 0,
  12301. 0,
  12302. 0,
  12303. 0,
  12304. 0,
  12305. 0,
  12306. 1,
  12307. 18,
  12308. 100,
  12309. 97,
  12310. 105,
  12311. 108,
  12312. 121,
  12313. 109,
  12314. 111,
  12315. 116,
  12316. 105,
  12317. 111,
  12318. 110,
  12319. 47,
  12320. 104,
  12321. 108,
  12322. 115,
  12323. 46,
  12324. 106,
  12325. 115,
  12326. 0,
  12327. 0,
  12328. 0,
  12329. 0,
  12330. 0,
  12331. 0,
  12332. 0,
  12333. 0,
  12334. 0,
  12335. 0,
  12336. 0,
  12337. 0,
  12338. 0,
  12339. 0,
  12340. 24,
  12341. 17,
  12342. 17
  12343. ]), avcc, MP4.box(MP4.types.btrt, new Uint8Array([
  12344. 0,
  12345. 28,
  12346. 156,
  12347. 128,
  12348. 0,
  12349. 45,
  12350. 198,
  12351. 192,
  12352. 0,
  12353. 45,
  12354. 198,
  12355. 192
  12356. ])), MP4.box(MP4.types.pasp, new Uint8Array([
  12357. hSpacing >> 24,
  12358. hSpacing >> 16 & 255,
  12359. hSpacing >> 8 & 255,
  12360. hSpacing & 255,
  12361. vSpacing >> 24,
  12362. vSpacing >> 16 & 255,
  12363. vSpacing >> 8 & 255,
  12364. vSpacing & 255
  12365. ])));
  12366. }
  12367. static esds(track) {
  12368. const config = track.config;
  12369. return new Uint8Array([
  12370. 0,
  12371. 0,
  12372. 0,
  12373. 0,
  12374. 3,
  12375. 25,
  12376. 0,
  12377. 1,
  12378. 0,
  12379. 4,
  12380. 17,
  12381. 64,
  12382. 21,
  12383. 0,
  12384. 0,
  12385. 0,
  12386. 0,
  12387. 0,
  12388. 0,
  12389. 0,
  12390. 0,
  12391. 0,
  12392. 0,
  12393. 0,
  12394. 5,
  12395. 2,
  12396. ...config,
  12397. 6,
  12398. 1,
  12399. 2
  12400. ]);
  12401. }
  12402. static audioStsd(track) {
  12403. const samplerate = track.samplerate || 0;
  12404. return new Uint8Array([
  12405. 0,
  12406. 0,
  12407. 0,
  12408. 0,
  12409. 0,
  12410. 0,
  12411. 0,
  12412. 1,
  12413. 0,
  12414. 0,
  12415. 0,
  12416. 0,
  12417. 0,
  12418. 0,
  12419. 0,
  12420. 0,
  12421. 0,
  12422. track.channelCount || 0,
  12423. 0,
  12424. 16,
  12425. 0,
  12426. 0,
  12427. 0,
  12428. 0,
  12429. samplerate >> 8 & 255,
  12430. samplerate & 255,
  12431. 0,
  12432. 0
  12433. ]);
  12434. }
  12435. static mp4a(track) {
  12436. return MP4.box(MP4.types.mp4a, MP4.audioStsd(track), MP4.box(MP4.types.esds, MP4.esds(track)));
  12437. }
  12438. static mp3(track) {
  12439. return MP4.box(MP4.types[".mp3"], MP4.audioStsd(track));
  12440. }
  12441. static ac3(track) {
  12442. return MP4.box(MP4.types["ac-3"], MP4.audioStsd(track), MP4.box(MP4.types.dac3, track.config));
  12443. }
  12444. static stsd(track) {
  12445. const {
  12446. segmentCodec
  12447. } = track;
  12448. if (track.type === "audio") {
  12449. if (segmentCodec === "aac") {
  12450. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  12451. }
  12452. if (segmentCodec === "ac3" && track.config) {
  12453. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.ac3(track));
  12454. }
  12455. if (segmentCodec === "mp3" && track.codec === "mp3") {
  12456. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  12457. }
  12458. } else {
  12459. if (track.pps && track.sps) {
  12460. if (segmentCodec === "avc") {
  12461. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  12462. }
  12463. if (segmentCodec === "hevc" && track.vps) {
  12464. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.hvc1(track));
  12465. }
  12466. } else {
  12467. throw new Error(`video track missing pps or sps`);
  12468. }
  12469. }
  12470. throw new Error(`unsupported ${track.type} segment codec (${segmentCodec}/${track.codec})`);
  12471. }
  12472. static tkhd(track) {
  12473. const id = track.id;
  12474. const duration = (track.duration || 0) * (track.timescale || 0);
  12475. const width = track.width || 0;
  12476. const height = track.height || 0;
  12477. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  12478. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  12479. return MP4.box(MP4.types.tkhd, new Uint8Array([
  12480. 1,
  12481. 0,
  12482. 0,
  12483. 7,
  12484. 0,
  12485. 0,
  12486. 0,
  12487. 0,
  12488. 0,
  12489. 0,
  12490. 0,
  12491. 2,
  12492. 0,
  12493. 0,
  12494. 0,
  12495. 0,
  12496. 0,
  12497. 0,
  12498. 0,
  12499. 3,
  12500. id >> 24 & 255,
  12501. id >> 16 & 255,
  12502. id >> 8 & 255,
  12503. id & 255,
  12504. 0,
  12505. 0,
  12506. 0,
  12507. 0,
  12508. upperWordDuration >> 24,
  12509. upperWordDuration >> 16 & 255,
  12510. upperWordDuration >> 8 & 255,
  12511. upperWordDuration & 255,
  12512. lowerWordDuration >> 24,
  12513. lowerWordDuration >> 16 & 255,
  12514. lowerWordDuration >> 8 & 255,
  12515. lowerWordDuration & 255,
  12516. 0,
  12517. 0,
  12518. 0,
  12519. 0,
  12520. 0,
  12521. 0,
  12522. 0,
  12523. 0,
  12524. 0,
  12525. 0,
  12526. 0,
  12527. 0,
  12528. 0,
  12529. 0,
  12530. 0,
  12531. 0,
  12532. 0,
  12533. 1,
  12534. 0,
  12535. 0,
  12536. 0,
  12537. 0,
  12538. 0,
  12539. 0,
  12540. 0,
  12541. 0,
  12542. 0,
  12543. 0,
  12544. 0,
  12545. 0,
  12546. 0,
  12547. 0,
  12548. 0,
  12549. 1,
  12550. 0,
  12551. 0,
  12552. 0,
  12553. 0,
  12554. 0,
  12555. 0,
  12556. 0,
  12557. 0,
  12558. 0,
  12559. 0,
  12560. 0,
  12561. 0,
  12562. 0,
  12563. 0,
  12564. 64,
  12565. 0,
  12566. 0,
  12567. 0,
  12568. width >> 8 & 255,
  12569. width & 255,
  12570. 0,
  12571. 0,
  12572. height >> 8 & 255,
  12573. height & 255,
  12574. 0,
  12575. 0
  12576. ]));
  12577. }
  12578. static traf(track, baseMediaDecodeTime) {
  12579. const sampleDependencyTable = MP4.sdtp(track);
  12580. const id = track.id;
  12581. const upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  12582. const lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  12583. return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([
  12584. 0,
  12585. 0,
  12586. 0,
  12587. 0,
  12588. id >> 24,
  12589. id >> 16 & 255,
  12590. id >> 8 & 255,
  12591. id & 255
  12592. ])), MP4.box(MP4.types.tfdt, new Uint8Array([
  12593. 1,
  12594. 0,
  12595. 0,
  12596. 0,
  12597. upperWordBaseMediaDecodeTime >> 24,
  12598. upperWordBaseMediaDecodeTime >> 16 & 255,
  12599. upperWordBaseMediaDecodeTime >> 8 & 255,
  12600. upperWordBaseMediaDecodeTime & 255,
  12601. lowerWordBaseMediaDecodeTime >> 24,
  12602. lowerWordBaseMediaDecodeTime >> 16 & 255,
  12603. lowerWordBaseMediaDecodeTime >> 8 & 255,
  12604. lowerWordBaseMediaDecodeTime & 255
  12605. ])), MP4.trun(track, sampleDependencyTable.length + 16 + 20 + 8 + 16 + 8 + 8), sampleDependencyTable);
  12606. }
  12607. static trak(track) {
  12608. track.duration = track.duration || 4294967295;
  12609. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  12610. }
  12611. static trex(track) {
  12612. const id = track.id;
  12613. return MP4.box(MP4.types.trex, new Uint8Array([
  12614. 0,
  12615. 0,
  12616. 0,
  12617. 0,
  12618. id >> 24,
  12619. id >> 16 & 255,
  12620. id >> 8 & 255,
  12621. id & 255,
  12622. 0,
  12623. 0,
  12624. 0,
  12625. 1,
  12626. 0,
  12627. 0,
  12628. 0,
  12629. 0,
  12630. 0,
  12631. 0,
  12632. 0,
  12633. 0,
  12634. 0,
  12635. 1,
  12636. 0,
  12637. 1
  12638. ]));
  12639. }
  12640. static trun(track, offset) {
  12641. const samples = track.samples || [];
  12642. const len = samples.length;
  12643. const arraylen = 12 + 16 * len;
  12644. const array = new Uint8Array(arraylen);
  12645. let i;
  12646. let sample;
  12647. let duration;
  12648. let size;
  12649. let flags;
  12650. let cts;
  12651. offset += 8 + arraylen;
  12652. array.set([
  12653. track.type === "video" ? 1 : 0,
  12654. 0,
  12655. 15,
  12656. 1,
  12657. len >>> 24 & 255,
  12658. len >>> 16 & 255,
  12659. len >>> 8 & 255,
  12660. len & 255,
  12661. offset >>> 24 & 255,
  12662. offset >>> 16 & 255,
  12663. offset >>> 8 & 255,
  12664. offset & 255
  12665. ], 0);
  12666. for (i = 0; i < len; i++) {
  12667. sample = samples[i];
  12668. duration = sample.duration;
  12669. size = sample.size;
  12670. flags = sample.flags;
  12671. cts = sample.cts;
  12672. array.set([
  12673. duration >>> 24 & 255,
  12674. duration >>> 16 & 255,
  12675. duration >>> 8 & 255,
  12676. duration & 255,
  12677. size >>> 24 & 255,
  12678. size >>> 16 & 255,
  12679. size >>> 8 & 255,
  12680. size & 255,
  12681. flags.isLeading << 2 | flags.dependsOn,
  12682. flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync,
  12683. flags.degradPrio & 240 << 8,
  12684. flags.degradPrio & 15,
  12685. cts >>> 24 & 255,
  12686. cts >>> 16 & 255,
  12687. cts >>> 8 & 255,
  12688. cts & 255
  12689. ], 12 + 16 * i);
  12690. }
  12691. return MP4.box(MP4.types.trun, array);
  12692. }
  12693. static initSegment(tracks) {
  12694. if (!MP4.types) {
  12695. MP4.init();
  12696. }
  12697. const movie = MP4.moov(tracks);
  12698. const result = appendUint8Array(MP4.FTYP, movie);
  12699. return result;
  12700. }
  12701. static hvc1(track) {
  12702. const ps = track.params;
  12703. const units = [track.vps, track.sps, track.pps];
  12704. const NALuLengthSize = 4;
  12705. 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]);
  12706. let length = config.length;
  12707. for (let i = 0; i < units.length; i += 1) {
  12708. length += 3;
  12709. for (let j = 0; j < units[i].length; j += 1) {
  12710. length += 2 + units[i][j].length;
  12711. }
  12712. }
  12713. const hvcC = new Uint8Array(length);
  12714. hvcC.set(config, 0);
  12715. length = config.length;
  12716. const iMax = units.length - 1;
  12717. for (let i = 0; i < units.length; i += 1) {
  12718. hvcC.set(new Uint8Array([32 + i | (i === iMax ? 128 : 0), 0, units[i].length]), length);
  12719. length += 3;
  12720. for (let j = 0; j < units[i].length; j += 1) {
  12721. hvcC.set(new Uint8Array([units[i][j].length >> 8, units[i][j].length & 255]), length);
  12722. length += 2;
  12723. hvcC.set(units[i][j], length);
  12724. length += units[i][j].length;
  12725. }
  12726. }
  12727. const hvcc = MP4.box(MP4.types.hvcC, hvcC);
  12728. const width = track.width;
  12729. const height = track.height;
  12730. const hSpacing = track.pixelRatio[0];
  12731. const vSpacing = track.pixelRatio[1];
  12732. return MP4.box(MP4.types.hvc1, new Uint8Array([
  12733. 0,
  12734. 0,
  12735. 0,
  12736. 0,
  12737. 0,
  12738. 0,
  12739. 0,
  12740. 1,
  12741. 0,
  12742. 0,
  12743. 0,
  12744. 0,
  12745. 0,
  12746. 0,
  12747. 0,
  12748. 0,
  12749. 0,
  12750. 0,
  12751. 0,
  12752. 0,
  12753. 0,
  12754. 0,
  12755. 0,
  12756. 0,
  12757. width >> 8 & 255,
  12758. width & 255,
  12759. height >> 8 & 255,
  12760. height & 255,
  12761. 0,
  12762. 72,
  12763. 0,
  12764. 0,
  12765. 0,
  12766. 72,
  12767. 0,
  12768. 0,
  12769. 0,
  12770. 0,
  12771. 0,
  12772. 0,
  12773. 0,
  12774. 1,
  12775. 18,
  12776. 100,
  12777. 97,
  12778. 105,
  12779. 108,
  12780. 121,
  12781. 109,
  12782. 111,
  12783. 116,
  12784. 105,
  12785. 111,
  12786. 110,
  12787. 47,
  12788. 104,
  12789. 108,
  12790. 115,
  12791. 46,
  12792. 106,
  12793. 115,
  12794. 0,
  12795. 0,
  12796. 0,
  12797. 0,
  12798. 0,
  12799. 0,
  12800. 0,
  12801. 0,
  12802. 0,
  12803. 0,
  12804. 0,
  12805. 0,
  12806. 0,
  12807. 0,
  12808. 24,
  12809. 17,
  12810. 17
  12811. ]), hvcc, MP4.box(MP4.types.btrt, new Uint8Array([
  12812. 0,
  12813. 28,
  12814. 156,
  12815. 128,
  12816. 0,
  12817. 45,
  12818. 198,
  12819. 192,
  12820. 0,
  12821. 45,
  12822. 198,
  12823. 192
  12824. ])), MP4.box(MP4.types.pasp, new Uint8Array([
  12825. hSpacing >> 24,
  12826. hSpacing >> 16 & 255,
  12827. hSpacing >> 8 & 255,
  12828. hSpacing & 255,
  12829. vSpacing >> 24,
  12830. vSpacing >> 16 & 255,
  12831. vSpacing >> 8 & 255,
  12832. vSpacing & 255
  12833. ])));
  12834. }
  12835. };
  12836. MP4.types = void 0;
  12837. MP4.HDLR_TYPES = void 0;
  12838. MP4.STTS = void 0;
  12839. MP4.STSC = void 0;
  12840. MP4.STCO = void 0;
  12841. MP4.STSZ = void 0;
  12842. MP4.VMHD = void 0;
  12843. MP4.SMHD = void 0;
  12844. MP4.STSD = void 0;
  12845. MP4.FTYP = void 0;
  12846. MP4.DINF = void 0;
  12847. var MPEG_TS_CLOCK_FREQ_HZ = 9e4;
  12848. function toTimescaleFromBase(baseTime, destScale, srcBase = 1, round = false) {
  12849. const result = baseTime * destScale * srcBase;
  12850. return round ? Math.round(result) : result;
  12851. }
  12852. function toTimescaleFromScale(baseTime, destScale, srcScale = 1, round = false) {
  12853. return toTimescaleFromBase(baseTime, destScale, 1 / srcScale, round);
  12854. }
  12855. function toMsFromMpegTsClock(baseTime, round = false) {
  12856. return toTimescaleFromBase(baseTime, 1e3, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
  12857. }
  12858. function toMpegTsClockFromTimescale(baseTime, srcScale = 1) {
  12859. return toTimescaleFromBase(baseTime, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
  12860. }
  12861. var MAX_SILENT_FRAME_DURATION = 10 * 1e3;
  12862. var AAC_SAMPLES_PER_FRAME = 1024;
  12863. var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
  12864. var AC3_SAMPLES_PER_FRAME = 1536;
  12865. var chromeVersion = null;
  12866. var safariWebkitVersion = null;
  12867. function createMp4Sample(isKeyframe, duration, size, cts) {
  12868. return {
  12869. duration,
  12870. size,
  12871. cts,
  12872. flags: {
  12873. isLeading: 0,
  12874. isDependedOn: 0,
  12875. hasRedundancy: 0,
  12876. degradPrio: 0,
  12877. dependsOn: isKeyframe ? 2 : 1,
  12878. isNonSync: isKeyframe ? 0 : 1
  12879. }
  12880. };
  12881. }
  12882. var MP4Remuxer = class extends Logger {
  12883. constructor(observer, config, typeSupported, logger2) {
  12884. super("mp4-remuxer", logger2);
  12885. this.observer = void 0;
  12886. this.config = void 0;
  12887. this.typeSupported = void 0;
  12888. this.ISGenerated = false;
  12889. this._initPTS = null;
  12890. this._initDTS = null;
  12891. this.nextVideoTs = null;
  12892. this.nextAudioTs = null;
  12893. this.videoSampleDuration = null;
  12894. this.isAudioContiguous = false;
  12895. this.isVideoContiguous = false;
  12896. this.videoTrackConfig = void 0;
  12897. this.observer = observer;
  12898. this.config = config;
  12899. this.typeSupported = typeSupported;
  12900. this.ISGenerated = false;
  12901. if (chromeVersion === null) {
  12902. const userAgent = navigator.userAgent || "";
  12903. const result = userAgent.match(/Chrome\/(\d+)/i);
  12904. chromeVersion = result ? parseInt(result[1]) : 0;
  12905. }
  12906. if (safariWebkitVersion === null) {
  12907. const result = navigator.userAgent.match(/Safari\/(\d+)/i);
  12908. safariWebkitVersion = result ? parseInt(result[1]) : 0;
  12909. }
  12910. }
  12911. destroy() {
  12912. this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;
  12913. }
  12914. resetTimeStamp(defaultTimeStamp) {
  12915. this.log("initPTS & initDTS reset");
  12916. this._initPTS = this._initDTS = defaultTimeStamp;
  12917. }
  12918. resetNextTimestamp() {
  12919. this.log("reset next timestamp");
  12920. this.isVideoContiguous = false;
  12921. this.isAudioContiguous = false;
  12922. }
  12923. resetInitSegment() {
  12924. this.log("ISGenerated flag reset");
  12925. this.ISGenerated = false;
  12926. this.videoTrackConfig = void 0;
  12927. }
  12928. getVideoStartPts(videoSamples) {
  12929. let rolloverDetected = false;
  12930. const firstPts = videoSamples[0].pts;
  12931. const startPTS = videoSamples.reduce((minPTS, sample) => {
  12932. let pts = sample.pts;
  12933. let delta = pts - minPTS;
  12934. if (delta < -4294967296) {
  12935. rolloverDetected = true;
  12936. pts = normalizePts(pts, firstPts);
  12937. delta = pts - minPTS;
  12938. }
  12939. if (delta > 0) {
  12940. return minPTS;
  12941. }
  12942. return pts;
  12943. }, firstPts);
  12944. if (rolloverDetected) {
  12945. this.debug("PTS rollover detected");
  12946. }
  12947. return startPTS;
  12948. }
  12949. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
  12950. let video;
  12951. let audio;
  12952. let initSegment;
  12953. let text;
  12954. let id3;
  12955. let independent;
  12956. let audioTimeOffset = timeOffset;
  12957. let videoTimeOffset = timeOffset;
  12958. const hasAudio = audioTrack.pid > -1;
  12959. const hasVideo = videoTrack.pid > -1;
  12960. const length = videoTrack.samples.length;
  12961. const enoughAudioSamples = audioTrack.samples.length > 0;
  12962. const enoughVideoSamples = flush && length > 0 || length > 1;
  12963. const canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
  12964. if (canRemuxAvc) {
  12965. if (this.ISGenerated) {
  12966. var _videoTrack$pixelRati, _config$pixelRatio, _videoTrack$pixelRati2, _config$pixelRatio2;
  12967. const config = this.videoTrackConfig;
  12968. 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) {
  12969. this.resetInitSegment();
  12970. }
  12971. }
  12972. if (!this.ISGenerated) {
  12973. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  12974. }
  12975. const isVideoContiguous = this.isVideoContiguous;
  12976. let firstKeyFrameIndex = -1;
  12977. let firstKeyFramePTS;
  12978. if (enoughVideoSamples) {
  12979. firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
  12980. if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
  12981. independent = true;
  12982. if (firstKeyFrameIndex > 0) {
  12983. this.warn(`Dropped ${firstKeyFrameIndex} out of ${length} video samples due to a missing keyframe`);
  12984. const startPTS = this.getVideoStartPts(videoTrack.samples);
  12985. videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
  12986. videoTrack.dropped += firstKeyFrameIndex;
  12987. videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale;
  12988. firstKeyFramePTS = videoTimeOffset;
  12989. } else if (firstKeyFrameIndex === -1) {
  12990. this.warn(`No keyframe found out of ${length} video samples`);
  12991. independent = false;
  12992. }
  12993. }
  12994. }
  12995. if (this.ISGenerated) {
  12996. if (enoughAudioSamples && enoughVideoSamples) {
  12997. const startPTS = this.getVideoStartPts(videoTrack.samples);
  12998. const tsDelta = normalizePts(audioTrack.samples[0].pts, startPTS) - startPTS;
  12999. const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
  13000. audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
  13001. videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
  13002. }
  13003. if (enoughAudioSamples) {
  13004. if (!audioTrack.samplerate) {
  13005. this.warn("regenerate InitSegment as audio detected");
  13006. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  13007. }
  13008. audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : void 0);
  13009. if (enoughVideoSamples) {
  13010. const audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;
  13011. if (!videoTrack.inputTimeScale) {
  13012. this.warn("regenerate InitSegment as video detected");
  13013. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  13014. }
  13015. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
  13016. }
  13017. } else if (enoughVideoSamples) {
  13018. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
  13019. }
  13020. if (video) {
  13021. video.firstKeyFrame = firstKeyFrameIndex;
  13022. video.independent = firstKeyFrameIndex !== -1;
  13023. video.firstKeyFramePTS = firstKeyFramePTS;
  13024. }
  13025. }
  13026. }
  13027. if (this.ISGenerated && this._initPTS && this._initDTS) {
  13028. if (id3Track.samples.length) {
  13029. id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS);
  13030. }
  13031. if (textTrack.samples.length) {
  13032. text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS);
  13033. }
  13034. }
  13035. return {
  13036. audio,
  13037. video,
  13038. initSegment,
  13039. independent,
  13040. text,
  13041. id3
  13042. };
  13043. }
  13044. generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset) {
  13045. const audioSamples = audioTrack.samples;
  13046. const videoSamples = videoTrack.samples;
  13047. const typeSupported = this.typeSupported;
  13048. const tracks = {};
  13049. const _initPTS = this._initPTS;
  13050. let computePTSDTS = !_initPTS || accurateTimeOffset;
  13051. let container = "audio/mp4";
  13052. let initPTS;
  13053. let initDTS;
  13054. let timescale;
  13055. let trackId;
  13056. if (computePTSDTS) {
  13057. initPTS = initDTS = Infinity;
  13058. }
  13059. if (audioTrack.config && audioSamples.length) {
  13060. audioTrack.timescale = audioTrack.samplerate;
  13061. switch (audioTrack.segmentCodec) {
  13062. case "mp3":
  13063. if (typeSupported.mpeg) {
  13064. container = "audio/mpeg";
  13065. audioTrack.codec = "";
  13066. } else if (typeSupported.mp3) {
  13067. audioTrack.codec = "mp3";
  13068. }
  13069. break;
  13070. case "ac3":
  13071. audioTrack.codec = "ac-3";
  13072. break;
  13073. }
  13074. tracks.audio = {
  13075. id: "audio",
  13076. container,
  13077. codec: audioTrack.codec,
  13078. initSegment: audioTrack.segmentCodec === "mp3" && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]),
  13079. metadata: {
  13080. channelCount: audioTrack.channelCount
  13081. }
  13082. };
  13083. if (computePTSDTS) {
  13084. trackId = audioTrack.id;
  13085. timescale = audioTrack.inputTimeScale;
  13086. if (!_initPTS || timescale !== _initPTS.timescale) {
  13087. initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
  13088. } else {
  13089. computePTSDTS = false;
  13090. }
  13091. }
  13092. }
  13093. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  13094. videoTrack.timescale = videoTrack.inputTimeScale;
  13095. tracks.video = {
  13096. id: "main",
  13097. container: "video/mp4",
  13098. codec: videoTrack.codec,
  13099. initSegment: MP4.initSegment([videoTrack]),
  13100. metadata: {
  13101. width: videoTrack.width,
  13102. height: videoTrack.height
  13103. }
  13104. };
  13105. if (computePTSDTS) {
  13106. trackId = videoTrack.id;
  13107. timescale = videoTrack.inputTimeScale;
  13108. if (!_initPTS || timescale !== _initPTS.timescale) {
  13109. const startPTS = this.getVideoStartPts(videoSamples);
  13110. const startOffset = Math.round(timescale * timeOffset);
  13111. initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
  13112. initPTS = Math.min(initPTS, startPTS - startOffset);
  13113. } else {
  13114. computePTSDTS = false;
  13115. }
  13116. }
  13117. this.videoTrackConfig = {
  13118. width: videoTrack.width,
  13119. height: videoTrack.height,
  13120. pixelRatio: videoTrack.pixelRatio
  13121. };
  13122. }
  13123. if (Object.keys(tracks).length) {
  13124. this.ISGenerated = true;
  13125. if (computePTSDTS) {
  13126. this._initPTS = {
  13127. baseTime: initPTS,
  13128. timescale
  13129. };
  13130. this._initDTS = {
  13131. baseTime: initDTS,
  13132. timescale
  13133. };
  13134. } else {
  13135. initPTS = timescale = void 0;
  13136. }
  13137. return {
  13138. tracks,
  13139. initPTS,
  13140. timescale,
  13141. trackId
  13142. };
  13143. }
  13144. }
  13145. remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
  13146. const timeScale = track.inputTimeScale;
  13147. const inputSamples = track.samples;
  13148. const outputSamples = [];
  13149. const nbSamples = inputSamples.length;
  13150. const initPTS = this._initPTS;
  13151. const initTime = initPTS.baseTime * timeScale / initPTS.timescale;
  13152. let nextVideoTs = this.nextVideoTs;
  13153. let offset = 8;
  13154. let mp4SampleDuration = this.videoSampleDuration;
  13155. let firstDTS;
  13156. let lastDTS;
  13157. let minPTS = Number.POSITIVE_INFINITY;
  13158. let maxPTS = Number.NEGATIVE_INFINITY;
  13159. let sortSamples = false;
  13160. if (!contiguous || nextVideoTs === null) {
  13161. const pts = initTime + timeOffset * timeScale;
  13162. const cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts);
  13163. if (chromeVersion && nextVideoTs !== null && Math.abs(pts - cts - (nextVideoTs + initTime)) < 15e3) {
  13164. contiguous = true;
  13165. } else {
  13166. nextVideoTs = pts - cts - initTime;
  13167. }
  13168. }
  13169. const nextVideoPts = nextVideoTs + initTime;
  13170. for (let i = 0; i < nbSamples; i++) {
  13171. const sample = inputSamples[i];
  13172. sample.pts = normalizePts(sample.pts, nextVideoPts);
  13173. sample.dts = normalizePts(sample.dts, nextVideoPts);
  13174. if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
  13175. sortSamples = true;
  13176. }
  13177. }
  13178. if (sortSamples) {
  13179. inputSamples.sort(function(a, b) {
  13180. const deltadts = a.dts - b.dts;
  13181. const deltapts = a.pts - b.pts;
  13182. return deltadts || deltapts;
  13183. });
  13184. }
  13185. firstDTS = inputSamples[0].dts;
  13186. lastDTS = inputSamples[inputSamples.length - 1].dts;
  13187. const inputDuration = lastDTS - firstDTS;
  13188. const averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track.inputTimeScale / 30;
  13189. if (contiguous) {
  13190. const delta = firstDTS - nextVideoPts;
  13191. const foundHole = delta > averageSampleDuration;
  13192. const foundOverlap = delta < -1;
  13193. if (foundHole || foundOverlap) {
  13194. if (foundHole) {
  13195. this.warn(`${(track.segmentCodec || "").toUpperCase()}: ${toMsFromMpegTsClock(delta, true)} ms (${delta}dts) hole between fragments detected at ${timeOffset.toFixed(3)}`);
  13196. } else {
  13197. this.warn(`${(track.segmentCodec || "").toUpperCase()}: ${toMsFromMpegTsClock(-delta, true)} ms (${delta}dts) overlapping between fragments detected at ${timeOffset.toFixed(3)}`);
  13198. }
  13199. if (!foundOverlap || nextVideoPts >= inputSamples[0].pts || chromeVersion) {
  13200. firstDTS = nextVideoPts;
  13201. const firstPTS = inputSamples[0].pts - delta;
  13202. if (foundHole) {
  13203. inputSamples[0].dts = firstDTS;
  13204. inputSamples[0].pts = firstPTS;
  13205. } else {
  13206. let isPTSOrderRetained = true;
  13207. for (let i = 0; i < inputSamples.length; i++) {
  13208. if (inputSamples[i].dts > firstPTS && isPTSOrderRetained) {
  13209. break;
  13210. }
  13211. const prevPTS = inputSamples[i].pts;
  13212. inputSamples[i].dts -= delta;
  13213. inputSamples[i].pts -= delta;
  13214. if (i < inputSamples.length - 1) {
  13215. const nextSamplePTS = inputSamples[i + 1].pts;
  13216. const currentSamplePTS = inputSamples[i].pts;
  13217. const currentOrder = nextSamplePTS <= currentSamplePTS;
  13218. const prevOrder = nextSamplePTS <= prevPTS;
  13219. isPTSOrderRetained = currentOrder == prevOrder;
  13220. }
  13221. }
  13222. }
  13223. this.log(`Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(firstPTS, true)}/${toMsFromMpegTsClock(firstDTS, true)}, delta: ${toMsFromMpegTsClock(delta, true)} ms`);
  13224. }
  13225. }
  13226. }
  13227. firstDTS = Math.max(0, firstDTS);
  13228. let nbNalu = 0;
  13229. let naluLen = 0;
  13230. let dtsStep = firstDTS;
  13231. for (let i = 0; i < nbSamples; i++) {
  13232. const sample = inputSamples[i];
  13233. const units = sample.units;
  13234. const nbUnits = units.length;
  13235. let sampleLen = 0;
  13236. for (let j = 0; j < nbUnits; j++) {
  13237. sampleLen += units[j].data.length;
  13238. }
  13239. naluLen += sampleLen;
  13240. nbNalu += nbUnits;
  13241. sample.length = sampleLen;
  13242. if (sample.dts < dtsStep) {
  13243. sample.dts = dtsStep;
  13244. dtsStep += averageSampleDuration / 4 | 0 || 1;
  13245. } else {
  13246. dtsStep = sample.dts;
  13247. }
  13248. minPTS = Math.min(sample.pts, minPTS);
  13249. maxPTS = Math.max(sample.pts, maxPTS);
  13250. }
  13251. lastDTS = inputSamples[nbSamples - 1].dts;
  13252. const mdatSize = naluLen + 4 * nbNalu + 8;
  13253. let mdat;
  13254. try {
  13255. mdat = new Uint8Array(mdatSize);
  13256. } catch (err) {
  13257. this.observer.emit(Events.ERROR, Events.ERROR, {
  13258. type: ErrorTypes.MUX_ERROR,
  13259. details: ErrorDetails.REMUX_ALLOC_ERROR,
  13260. fatal: false,
  13261. error: err,
  13262. bytes: mdatSize,
  13263. reason: `fail allocating video mdat ${mdatSize}`
  13264. });
  13265. return;
  13266. }
  13267. const view2 = new DataView(mdat.buffer);
  13268. view2.setUint32(0, mdatSize);
  13269. mdat.set(MP4.types.mdat, 4);
  13270. let stretchedLastFrame = false;
  13271. let minDtsDelta = Number.POSITIVE_INFINITY;
  13272. let minPtsDelta = Number.POSITIVE_INFINITY;
  13273. let maxDtsDelta = Number.NEGATIVE_INFINITY;
  13274. let maxPtsDelta = Number.NEGATIVE_INFINITY;
  13275. for (let i = 0; i < nbSamples; i++) {
  13276. const VideoSample = inputSamples[i];
  13277. const VideoSampleUnits = VideoSample.units;
  13278. let mp4SampleLength = 0;
  13279. for (let j = 0, nbUnits = VideoSampleUnits.length; j < nbUnits; j++) {
  13280. const unit = VideoSampleUnits[j];
  13281. const unitData = unit.data;
  13282. const unitDataLen = unit.data.byteLength;
  13283. view2.setUint32(offset, unitDataLen);
  13284. offset += 4;
  13285. mdat.set(unitData, offset);
  13286. offset += unitDataLen;
  13287. mp4SampleLength += 4 + unitDataLen;
  13288. }
  13289. let ptsDelta;
  13290. if (i < nbSamples - 1) {
  13291. mp4SampleDuration = inputSamples[i + 1].dts - VideoSample.dts;
  13292. ptsDelta = inputSamples[i + 1].pts - VideoSample.pts;
  13293. } else {
  13294. const config = this.config;
  13295. const lastFrameDuration = i > 0 ? VideoSample.dts - inputSamples[i - 1].dts : averageSampleDuration;
  13296. ptsDelta = i > 0 ? VideoSample.pts - inputSamples[i - 1].pts : averageSampleDuration;
  13297. if (config.stretchShortVideoTrack && this.nextAudioTs !== null) {
  13298. const gapTolerance = Math.floor(config.maxBufferHole * timeScale);
  13299. const deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioTs + initTime) - VideoSample.pts;
  13300. if (deltaToFrameEnd > gapTolerance) {
  13301. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  13302. if (mp4SampleDuration < 0) {
  13303. mp4SampleDuration = lastFrameDuration;
  13304. } else {
  13305. stretchedLastFrame = true;
  13306. }
  13307. this.log(`It is approximately ${deltaToFrameEnd / 90} ms to the next segment; using duration ${mp4SampleDuration / 90} ms for the last video frame.`);
  13308. } else {
  13309. mp4SampleDuration = lastFrameDuration;
  13310. }
  13311. } else {
  13312. mp4SampleDuration = lastFrameDuration;
  13313. }
  13314. }
  13315. const compositionTimeOffset = Math.round(VideoSample.pts - VideoSample.dts);
  13316. minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);
  13317. maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);
  13318. minPtsDelta = Math.min(minPtsDelta, ptsDelta);
  13319. maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);
  13320. outputSamples.push(createMp4Sample(VideoSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
  13321. }
  13322. if (outputSamples.length) {
  13323. if (chromeVersion) {
  13324. if (chromeVersion < 70) {
  13325. const flags = outputSamples[0].flags;
  13326. flags.dependsOn = 2;
  13327. flags.isNonSync = 0;
  13328. }
  13329. } else if (safariWebkitVersion) {
  13330. if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) {
  13331. this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");
  13332. let dts = firstDTS;
  13333. for (let i = 0, len = outputSamples.length; i < len; i++) {
  13334. const nextDts = dts + outputSamples[i].duration;
  13335. const pts = dts + outputSamples[i].cts;
  13336. if (i < len - 1) {
  13337. const nextPts = nextDts + outputSamples[i + 1].cts;
  13338. outputSamples[i].duration = nextPts - pts;
  13339. } else {
  13340. outputSamples[i].duration = i ? outputSamples[i - 1].duration : averageSampleDuration;
  13341. }
  13342. outputSamples[i].cts = 0;
  13343. dts = nextDts;
  13344. }
  13345. }
  13346. }
  13347. }
  13348. mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration;
  13349. const endDTS = lastDTS + mp4SampleDuration;
  13350. this.nextVideoTs = nextVideoTs = endDTS - initTime;
  13351. this.videoSampleDuration = mp4SampleDuration;
  13352. this.isVideoContiguous = true;
  13353. const moof = MP4.moof(track.sequenceNumber++, firstDTS, _extends(track, {
  13354. samples: outputSamples
  13355. }));
  13356. const type = "video";
  13357. const data = {
  13358. data1: moof,
  13359. data2: mdat,
  13360. startPTS: (minPTS - initTime) / timeScale,
  13361. endPTS: (maxPTS + mp4SampleDuration - initTime) / timeScale,
  13362. startDTS: (firstDTS - initTime) / timeScale,
  13363. endDTS: nextVideoTs / timeScale,
  13364. type,
  13365. hasAudio: false,
  13366. hasVideo: true,
  13367. nb: outputSamples.length,
  13368. dropped: track.dropped
  13369. };
  13370. track.samples = [];
  13371. track.dropped = 0;
  13372. return data;
  13373. }
  13374. getSamplesPerFrame(track) {
  13375. switch (track.segmentCodec) {
  13376. case "mp3":
  13377. return MPEG_AUDIO_SAMPLE_PER_FRAME;
  13378. case "ac3":
  13379. return AC3_SAMPLES_PER_FRAME;
  13380. default:
  13381. return AAC_SAMPLES_PER_FRAME;
  13382. }
  13383. }
  13384. remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
  13385. const inputTimeScale = track.inputTimeScale;
  13386. const mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  13387. const scaleFactor = inputTimeScale / mp4timeScale;
  13388. const mp4SampleDuration = this.getSamplesPerFrame(track);
  13389. const inputSampleDuration = mp4SampleDuration * scaleFactor;
  13390. const initPTS = this._initPTS;
  13391. const rawMPEG = track.segmentCodec === "mp3" && this.typeSupported.mpeg;
  13392. const outputSamples = [];
  13393. const alignedWithVideo = videoTimeOffset !== void 0;
  13394. let inputSamples = track.samples;
  13395. let offset = rawMPEG ? 0 : 8;
  13396. let nextAudioTs = this.nextAudioTs || -1;
  13397. const initTime = initPTS.baseTime * inputTimeScale / initPTS.timescale;
  13398. const timeOffsetMpegTS = initTime + timeOffset * inputTimeScale;
  13399. 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);
  13400. inputSamples.forEach(function(sample) {
  13401. sample.pts = normalizePts(sample.pts, timeOffsetMpegTS);
  13402. });
  13403. if (!contiguous || nextAudioTs < 0) {
  13404. inputSamples = inputSamples.filter((sample) => sample.pts >= 0);
  13405. if (!inputSamples.length) {
  13406. return;
  13407. }
  13408. if (videoTimeOffset === 0) {
  13409. nextAudioTs = 0;
  13410. } else if (accurateTimeOffset && !alignedWithVideo) {
  13411. nextAudioTs = Math.max(0, timeOffsetMpegTS - initTime);
  13412. } else {
  13413. nextAudioTs = inputSamples[0].pts - initTime;
  13414. }
  13415. }
  13416. if (track.segmentCodec === "aac") {
  13417. const maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  13418. for (let i = 0, nextPts = nextAudioTs + initTime; i < inputSamples.length; i++) {
  13419. const sample = inputSamples[i];
  13420. const pts = sample.pts;
  13421. const delta = pts - nextPts;
  13422. const duration = Math.abs(1e3 * delta / inputTimeScale);
  13423. if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
  13424. if (i === 0) {
  13425. this.warn(`Audio frame @ ${(pts / inputTimeScale).toFixed(3)}s overlaps marker by ${Math.round(1e3 * delta / inputTimeScale)} ms.`);
  13426. this.nextAudioTs = nextAudioTs = pts - initTime;
  13427. nextPts = pts;
  13428. }
  13429. } else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
  13430. let missing = Math.round(delta / inputSampleDuration);
  13431. nextPts = pts - missing * inputSampleDuration;
  13432. while (nextPts < 0 && missing && inputSampleDuration) {
  13433. missing--;
  13434. nextPts += inputSampleDuration;
  13435. }
  13436. if (i === 0) {
  13437. this.nextAudioTs = nextAudioTs = nextPts - initTime;
  13438. }
  13439. this.warn(`Injecting ${missing} audio frames @ ${((nextPts - initTime) / inputTimeScale).toFixed(3)}s due to ${Math.round(1e3 * delta / inputTimeScale)} ms gap.`);
  13440. for (let j = 0; j < missing; j++) {
  13441. let fillFrame = AAC.getSilentFrame(track.parsedCodec || track.manifestCodec || track.codec, track.channelCount);
  13442. if (!fillFrame) {
  13443. this.log("Unable to get silent frame for given audio codec; duplicating last frame instead.");
  13444. fillFrame = sample.unit.subarray();
  13445. }
  13446. inputSamples.splice(i, 0, {
  13447. unit: fillFrame,
  13448. pts: nextPts
  13449. });
  13450. nextPts += inputSampleDuration;
  13451. i++;
  13452. }
  13453. }
  13454. sample.pts = nextPts;
  13455. nextPts += inputSampleDuration;
  13456. }
  13457. }
  13458. let firstPTS = null;
  13459. let lastPTS = null;
  13460. let mdat;
  13461. let mdatSize = 0;
  13462. let sampleLength = inputSamples.length;
  13463. while (sampleLength--) {
  13464. mdatSize += inputSamples[sampleLength].unit.byteLength;
  13465. }
  13466. for (let j = 0, _nbSamples = inputSamples.length; j < _nbSamples; j++) {
  13467. const audioSample = inputSamples[j];
  13468. const unit = audioSample.unit;
  13469. let pts = audioSample.pts;
  13470. if (lastPTS !== null) {
  13471. const prevSample = outputSamples[j - 1];
  13472. prevSample.duration = Math.round((pts - lastPTS) / scaleFactor);
  13473. } else {
  13474. if (contiguous && track.segmentCodec === "aac") {
  13475. pts = nextAudioTs + initTime;
  13476. }
  13477. firstPTS = pts;
  13478. if (mdatSize > 0) {
  13479. mdatSize += offset;
  13480. try {
  13481. mdat = new Uint8Array(mdatSize);
  13482. } catch (err) {
  13483. this.observer.emit(Events.ERROR, Events.ERROR, {
  13484. type: ErrorTypes.MUX_ERROR,
  13485. details: ErrorDetails.REMUX_ALLOC_ERROR,
  13486. fatal: false,
  13487. error: err,
  13488. bytes: mdatSize,
  13489. reason: `fail allocating audio mdat ${mdatSize}`
  13490. });
  13491. return;
  13492. }
  13493. if (!rawMPEG) {
  13494. const view2 = new DataView(mdat.buffer);
  13495. view2.setUint32(0, mdatSize);
  13496. mdat.set(MP4.types.mdat, 4);
  13497. }
  13498. } else {
  13499. return;
  13500. }
  13501. }
  13502. mdat.set(unit, offset);
  13503. const unitLen = unit.byteLength;
  13504. offset += unitLen;
  13505. outputSamples.push(createMp4Sample(true, mp4SampleDuration, unitLen, 0));
  13506. lastPTS = pts;
  13507. }
  13508. const nbSamples = outputSamples.length;
  13509. if (!nbSamples) {
  13510. return;
  13511. }
  13512. const lastSample = outputSamples[outputSamples.length - 1];
  13513. nextAudioTs = lastPTS - initTime;
  13514. this.nextAudioTs = nextAudioTs + scaleFactor * lastSample.duration;
  13515. const moof = rawMPEG ? new Uint8Array(0) : MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
  13516. samples: outputSamples
  13517. }));
  13518. track.samples = [];
  13519. const start = (firstPTS - initTime) / inputTimeScale;
  13520. const end = nextAudioTs / inputTimeScale;
  13521. const type = "audio";
  13522. const audioData = {
  13523. data1: moof,
  13524. data2: mdat,
  13525. startPTS: start,
  13526. endPTS: end,
  13527. startDTS: start,
  13528. endDTS: end,
  13529. type,
  13530. hasAudio: true,
  13531. hasVideo: false,
  13532. nb: nbSamples
  13533. };
  13534. this.isAudioContiguous = true;
  13535. return audioData;
  13536. }
  13537. };
  13538. function normalizePts(value, reference) {
  13539. let offset;
  13540. if (reference === null) {
  13541. return value;
  13542. }
  13543. if (reference < value) {
  13544. offset = -8589934592;
  13545. } else {
  13546. offset = 8589934592;
  13547. }
  13548. while (Math.abs(value - reference) > 4294967296) {
  13549. value += offset;
  13550. }
  13551. return value;
  13552. }
  13553. function findKeyframeIndex(samples) {
  13554. for (let i = 0; i < samples.length; i++) {
  13555. if (samples[i].key) {
  13556. return i;
  13557. }
  13558. }
  13559. return -1;
  13560. }
  13561. function flushTextTrackMetadataCueSamples(track, timeOffset, initPTS, initDTS) {
  13562. const length = track.samples.length;
  13563. if (!length) {
  13564. return;
  13565. }
  13566. const inputTimeScale = track.inputTimeScale;
  13567. for (let index = 0; index < length; index++) {
  13568. const sample = track.samples[index];
  13569. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  13570. sample.dts = normalizePts(sample.dts - initDTS.baseTime * inputTimeScale / initDTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  13571. }
  13572. const samples = track.samples;
  13573. track.samples = [];
  13574. return {
  13575. samples
  13576. };
  13577. }
  13578. function flushTextTrackUserdataCueSamples(track, timeOffset, initPTS) {
  13579. const length = track.samples.length;
  13580. if (!length) {
  13581. return;
  13582. }
  13583. const inputTimeScale = track.inputTimeScale;
  13584. for (let index = 0; index < length; index++) {
  13585. const sample = track.samples[index];
  13586. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  13587. }
  13588. track.samples.sort((a, b) => a.pts - b.pts);
  13589. const samples = track.samples;
  13590. track.samples = [];
  13591. return {
  13592. samples
  13593. };
  13594. }
  13595. var PassThroughRemuxer = class extends Logger {
  13596. constructor(observer, config, typeSupported, logger2) {
  13597. super("passthrough-remuxer", logger2);
  13598. this.emitInitSegment = false;
  13599. this.audioCodec = void 0;
  13600. this.videoCodec = void 0;
  13601. this.initData = void 0;
  13602. this.initPTS = null;
  13603. this.initTracks = void 0;
  13604. this.lastEndTime = null;
  13605. this.isVideoContiguous = false;
  13606. }
  13607. destroy() {
  13608. }
  13609. resetTimeStamp(defaultInitPTS) {
  13610. this.lastEndTime = null;
  13611. const initPTS = this.initPTS;
  13612. if (initPTS && defaultInitPTS) {
  13613. if (initPTS.baseTime === defaultInitPTS.baseTime && initPTS.timescale === defaultInitPTS.timescale) {
  13614. return;
  13615. }
  13616. }
  13617. this.initPTS = defaultInitPTS;
  13618. }
  13619. resetNextTimestamp() {
  13620. this.isVideoContiguous = false;
  13621. this.lastEndTime = null;
  13622. }
  13623. resetInitSegment(initSegment, audioCodec, videoCodec, decryptdata) {
  13624. this.audioCodec = audioCodec;
  13625. this.videoCodec = videoCodec;
  13626. this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));
  13627. this.emitInitSegment = true;
  13628. }
  13629. generateInitSegment(initSegment) {
  13630. let {
  13631. audioCodec,
  13632. videoCodec
  13633. } = this;
  13634. if (!(initSegment != null && initSegment.byteLength)) {
  13635. this.initTracks = void 0;
  13636. this.initData = void 0;
  13637. return;
  13638. }
  13639. const initData = this.initData = parseInitSegment(initSegment);
  13640. if (initData.audio) {
  13641. audioCodec = getParsedTrackCodec(initData.audio, ElementaryStreamTypes.AUDIO, this);
  13642. }
  13643. if (initData.video) {
  13644. videoCodec = getParsedTrackCodec(initData.video, ElementaryStreamTypes.VIDEO, this);
  13645. }
  13646. const tracks = {};
  13647. if (initData.audio && initData.video) {
  13648. tracks.audiovideo = {
  13649. container: "video/mp4",
  13650. codec: audioCodec + "," + videoCodec,
  13651. supplemental: initData.video.supplemental,
  13652. initSegment,
  13653. id: "main"
  13654. };
  13655. } else if (initData.audio) {
  13656. tracks.audio = {
  13657. container: "audio/mp4",
  13658. codec: audioCodec,
  13659. initSegment,
  13660. id: "audio"
  13661. };
  13662. } else if (initData.video) {
  13663. tracks.video = {
  13664. container: "video/mp4",
  13665. codec: videoCodec,
  13666. supplemental: initData.video.supplemental,
  13667. initSegment,
  13668. id: "main"
  13669. };
  13670. } else {
  13671. this.warn("initSegment does not contain moov or trak boxes.");
  13672. }
  13673. this.initTracks = tracks;
  13674. }
  13675. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset) {
  13676. var _initData, _initData2;
  13677. let {
  13678. initPTS,
  13679. lastEndTime
  13680. } = this;
  13681. const result = {
  13682. audio: void 0,
  13683. video: void 0,
  13684. text: textTrack,
  13685. id3: id3Track,
  13686. initSegment: void 0
  13687. };
  13688. if (!isFiniteNumber(lastEndTime)) {
  13689. lastEndTime = this.lastEndTime = timeOffset || 0;
  13690. }
  13691. const data = videoTrack.samples;
  13692. if (!(data != null && data.length)) {
  13693. return result;
  13694. }
  13695. const initSegment = {
  13696. initPTS: void 0,
  13697. timescale: void 0,
  13698. trackId: void 0
  13699. };
  13700. let initData = this.initData;
  13701. if (!((_initData = initData) != null && _initData.length)) {
  13702. this.generateInitSegment(data);
  13703. initData = this.initData;
  13704. }
  13705. if (!((_initData2 = initData) != null && _initData2.length)) {
  13706. this.warn("Failed to generate initSegment.");
  13707. return result;
  13708. }
  13709. if (this.emitInitSegment) {
  13710. initSegment.tracks = this.initTracks;
  13711. this.emitInitSegment = false;
  13712. }
  13713. const trackSampleData = getSampleData(data, initData, this);
  13714. const audioSampleTimestamps = initData.audio ? trackSampleData[initData.audio.id] : null;
  13715. const videoSampleTimestamps = initData.video ? trackSampleData[initData.video.id] : null;
  13716. const videoStartTime = toStartEndOrDefault(videoSampleTimestamps, Infinity);
  13717. const audioStartTime = toStartEndOrDefault(audioSampleTimestamps, Infinity);
  13718. const videoEndTime = toStartEndOrDefault(videoSampleTimestamps, 0, true);
  13719. const audioEndTime = toStartEndOrDefault(audioSampleTimestamps, 0, true);
  13720. let baseOffsetSamples;
  13721. let decodeTime = timeOffset;
  13722. let duration = 0;
  13723. if (audioSampleTimestamps && (!videoSampleTimestamps || !initPTS && audioStartTime < videoStartTime || initPTS && initPTS.trackId === initData.audio.id)) {
  13724. initSegment.trackId = initData.audio.id;
  13725. baseOffsetSamples = audioSampleTimestamps;
  13726. duration = audioEndTime - audioStartTime;
  13727. } else if (videoSampleTimestamps) {
  13728. initSegment.trackId = initData.video.id;
  13729. baseOffsetSamples = videoSampleTimestamps;
  13730. duration = videoEndTime - videoStartTime;
  13731. }
  13732. if (baseOffsetSamples) {
  13733. const timescale = baseOffsetSamples.timescale;
  13734. decodeTime = baseOffsetSamples.start / timescale;
  13735. initSegment.initPTS = baseOffsetSamples.start - timeOffset * timescale;
  13736. initSegment.timescale = timescale;
  13737. if (!initPTS) {
  13738. this.initPTS = initPTS = {
  13739. baseTime: initSegment.initPTS,
  13740. timescale,
  13741. trackId: initSegment.trackId
  13742. };
  13743. }
  13744. }
  13745. if ((accurateTimeOffset || !initPTS) && (isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) || initSegment.timescale !== initPTS.timescale)) {
  13746. initSegment.initPTS = decodeTime - timeOffset;
  13747. initSegment.timescale = 1;
  13748. if (initPTS && initPTS.timescale === 1) {
  13749. this.warn(`Adjusting initPTS @${timeOffset} from ${initPTS.baseTime / initPTS.timescale} to ${initSegment.initPTS}`);
  13750. }
  13751. this.initPTS = initPTS = {
  13752. baseTime: initSegment.initPTS,
  13753. timescale: 1
  13754. };
  13755. }
  13756. const startTime = audioTrack ? decodeTime - initPTS.baseTime / initPTS.timescale : lastEndTime;
  13757. const endTime = startTime + duration;
  13758. if (duration > 0) {
  13759. this.lastEndTime = endTime;
  13760. } else {
  13761. this.warn("Duration parsed from mp4 should be greater than zero");
  13762. this.resetNextTimestamp();
  13763. }
  13764. const hasAudio = !!initData.audio;
  13765. const hasVideo = !!initData.video;
  13766. let type = "";
  13767. if (hasAudio) {
  13768. type += "audio";
  13769. }
  13770. if (hasVideo) {
  13771. type += "video";
  13772. }
  13773. const track = {
  13774. data1: data,
  13775. startPTS: startTime,
  13776. startDTS: startTime,
  13777. endPTS: endTime,
  13778. endDTS: endTime,
  13779. type,
  13780. hasAudio,
  13781. hasVideo,
  13782. nb: 1,
  13783. dropped: 0
  13784. };
  13785. result.audio = hasAudio && !hasVideo ? track : void 0;
  13786. result.video = hasVideo ? track : void 0;
  13787. const videoSampleCount = videoSampleTimestamps == null ? void 0 : videoSampleTimestamps.sampleCount;
  13788. if (videoSampleCount) {
  13789. const firstKeyFrame = videoSampleTimestamps.keyFrameIndex;
  13790. const independent = firstKeyFrame !== -1;
  13791. track.nb = videoSampleCount;
  13792. track.dropped = firstKeyFrame === 0 || this.isVideoContiguous ? 0 : independent ? firstKeyFrame : videoSampleCount;
  13793. track.independent = independent;
  13794. track.firstKeyFrame = firstKeyFrame;
  13795. if (independent && videoSampleTimestamps.keyFrameStart) {
  13796. track.firstKeyFramePTS = (videoSampleTimestamps.keyFrameStart - initPTS.baseTime) / initPTS.timescale;
  13797. }
  13798. if (!this.isVideoContiguous) {
  13799. result.independent = independent;
  13800. }
  13801. this.isVideoContiguous || (this.isVideoContiguous = independent);
  13802. if (track.dropped) {
  13803. this.warn(`fmp4 does not start with IDR: firstIDR ${firstKeyFrame}/${videoSampleCount} dropped: ${track.dropped} start: ${track.firstKeyFramePTS || "NA"}`);
  13804. }
  13805. }
  13806. result.initSegment = initSegment;
  13807. result.id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, initPTS, initPTS);
  13808. if (textTrack.samples.length) {
  13809. result.text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, initPTS);
  13810. }
  13811. return result;
  13812. }
  13813. };
  13814. function toStartEndOrDefault(trackTimes, defaultValue, end = false) {
  13815. return (trackTimes == null ? void 0 : trackTimes.start) !== void 0 ? (trackTimes.start + (end ? trackTimes.duration : 0)) / trackTimes.timescale : defaultValue;
  13816. }
  13817. function isInvalidInitPts(initPTS, startDTS, timeOffset, duration) {
  13818. if (initPTS === null) {
  13819. return true;
  13820. }
  13821. const minDuration = Math.max(duration, 1);
  13822. const startTime = startDTS - initPTS.baseTime / initPTS.timescale;
  13823. return Math.abs(startTime - timeOffset) > minDuration;
  13824. }
  13825. function getParsedTrackCodec(track, type, logger2) {
  13826. const parsedCodec = track == null ? void 0 : track.codec;
  13827. if (parsedCodec && parsedCodec.length > 4) {
  13828. return parsedCodec;
  13829. }
  13830. if (type === ElementaryStreamTypes.AUDIO) {
  13831. if (parsedCodec === "ec-3" || parsedCodec === "ac-3" || parsedCodec === "alac") {
  13832. return parsedCodec;
  13833. }
  13834. if (parsedCodec === "fLaC" || parsedCodec === "Opus") {
  13835. const preferManagedMediaSource = false;
  13836. return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);
  13837. }
  13838. logger2.warn(`Unhandled audio codec "${parsedCodec}" in mp4 MAP`);
  13839. return parsedCodec || "mp4a";
  13840. }
  13841. logger2.warn(`Unhandled video codec "${parsedCodec}" in mp4 MAP`);
  13842. return parsedCodec || "avc1";
  13843. }
  13844. var now;
  13845. try {
  13846. now = self.performance.now.bind(self.performance);
  13847. } catch (err) {
  13848. now = Date.now;
  13849. }
  13850. var muxConfig = [{
  13851. demux: MP4Demuxer,
  13852. remux: PassThroughRemuxer
  13853. }, {
  13854. demux: TSDemuxer,
  13855. remux: MP4Remuxer
  13856. }, {
  13857. demux: AACDemuxer,
  13858. remux: MP4Remuxer
  13859. }, {
  13860. demux: MP3Demuxer,
  13861. remux: MP4Remuxer
  13862. }];
  13863. {
  13864. muxConfig.splice(2, 0, {
  13865. demux: AC3Demuxer,
  13866. remux: MP4Remuxer
  13867. });
  13868. }
  13869. var Transmuxer = class {
  13870. constructor(observer, typeSupported, config, vendor, id, logger2) {
  13871. this.asyncResult = false;
  13872. this.logger = void 0;
  13873. this.observer = void 0;
  13874. this.typeSupported = void 0;
  13875. this.config = void 0;
  13876. this.id = void 0;
  13877. this.demuxer = void 0;
  13878. this.remuxer = void 0;
  13879. this.decrypter = void 0;
  13880. this.probe = void 0;
  13881. this.decryptionPromise = null;
  13882. this.transmuxConfig = void 0;
  13883. this.currentTransmuxState = void 0;
  13884. this.observer = observer;
  13885. this.typeSupported = typeSupported;
  13886. this.config = config;
  13887. this.id = id;
  13888. this.logger = logger2;
  13889. }
  13890. configure(transmuxConfig) {
  13891. this.transmuxConfig = transmuxConfig;
  13892. if (this.decrypter) {
  13893. this.decrypter.reset();
  13894. }
  13895. }
  13896. push(data, decryptdata, chunkMeta, state) {
  13897. const stats = chunkMeta.transmuxing;
  13898. stats.executeStart = now();
  13899. let uintData = new Uint8Array(data);
  13900. const {
  13901. currentTransmuxState,
  13902. transmuxConfig
  13903. } = this;
  13904. if (state) {
  13905. this.currentTransmuxState = state;
  13906. }
  13907. const {
  13908. contiguous,
  13909. discontinuity,
  13910. trackSwitch,
  13911. accurateTimeOffset,
  13912. timeOffset,
  13913. initSegmentChange
  13914. } = state || currentTransmuxState;
  13915. const {
  13916. audioCodec,
  13917. videoCodec,
  13918. defaultInitPts,
  13919. duration,
  13920. initSegmentData
  13921. } = transmuxConfig;
  13922. const keyData = getEncryptionType(uintData, decryptdata);
  13923. if (keyData && isFullSegmentEncryption(keyData.method)) {
  13924. const decrypter = this.getDecrypter();
  13925. const aesMode = getAesModeFromFullSegmentMethod(keyData.method);
  13926. if (decrypter.isSync()) {
  13927. let decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode);
  13928. const loadingParts = chunkMeta.part > -1;
  13929. if (loadingParts) {
  13930. const _data = decrypter.flush();
  13931. decryptedData = _data ? _data.buffer : _data;
  13932. }
  13933. if (!decryptedData) {
  13934. stats.executeEnd = now();
  13935. return emptyResult(chunkMeta);
  13936. }
  13937. uintData = new Uint8Array(decryptedData);
  13938. } else {
  13939. this.asyncResult = true;
  13940. this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode).then((decryptedData) => {
  13941. const result2 = this.push(decryptedData, null, chunkMeta);
  13942. this.decryptionPromise = null;
  13943. return result2;
  13944. });
  13945. return this.decryptionPromise;
  13946. }
  13947. }
  13948. const resetMuxers = this.needsProbing(discontinuity, trackSwitch);
  13949. if (resetMuxers) {
  13950. const error = this.configureTransmuxer(uintData);
  13951. if (error) {
  13952. this.logger.warn(`[transmuxer] ${error.message}`);
  13953. this.observer.emit(Events.ERROR, Events.ERROR, {
  13954. type: ErrorTypes.MEDIA_ERROR,
  13955. details: ErrorDetails.FRAG_PARSING_ERROR,
  13956. fatal: false,
  13957. error,
  13958. reason: error.message
  13959. });
  13960. stats.executeEnd = now();
  13961. return emptyResult(chunkMeta);
  13962. }
  13963. }
  13964. if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {
  13965. this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration, decryptdata);
  13966. }
  13967. if (discontinuity || initSegmentChange || resetMuxers) {
  13968. this.resetInitialTimestamp(defaultInitPts);
  13969. }
  13970. if (!contiguous) {
  13971. this.resetContiguity();
  13972. }
  13973. const result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  13974. this.asyncResult = isPromise(result);
  13975. const currentState = this.currentTransmuxState;
  13976. currentState.contiguous = true;
  13977. currentState.discontinuity = false;
  13978. currentState.trackSwitch = false;
  13979. stats.executeEnd = now();
  13980. return result;
  13981. }
  13982. flush(chunkMeta) {
  13983. const stats = chunkMeta.transmuxing;
  13984. stats.executeStart = now();
  13985. const {
  13986. decrypter,
  13987. currentTransmuxState,
  13988. decryptionPromise
  13989. } = this;
  13990. if (decryptionPromise) {
  13991. this.asyncResult = true;
  13992. return decryptionPromise.then(() => {
  13993. return this.flush(chunkMeta);
  13994. });
  13995. }
  13996. const transmuxResults = [];
  13997. const {
  13998. timeOffset
  13999. } = currentTransmuxState;
  14000. if (decrypter) {
  14001. const decryptedData = decrypter.flush();
  14002. if (decryptedData) {
  14003. transmuxResults.push(this.push(decryptedData.buffer, null, chunkMeta));
  14004. }
  14005. }
  14006. const {
  14007. demuxer,
  14008. remuxer
  14009. } = this;
  14010. if (!demuxer || !remuxer) {
  14011. stats.executeEnd = now();
  14012. const emptyResults = [emptyResult(chunkMeta)];
  14013. if (this.asyncResult) {
  14014. return Promise.resolve(emptyResults);
  14015. }
  14016. return emptyResults;
  14017. }
  14018. const demuxResultOrPromise = demuxer.flush(timeOffset);
  14019. if (isPromise(demuxResultOrPromise)) {
  14020. this.asyncResult = true;
  14021. return demuxResultOrPromise.then((demuxResult) => {
  14022. this.flushRemux(transmuxResults, demuxResult, chunkMeta);
  14023. return transmuxResults;
  14024. });
  14025. }
  14026. this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
  14027. if (this.asyncResult) {
  14028. return Promise.resolve(transmuxResults);
  14029. }
  14030. return transmuxResults;
  14031. }
  14032. flushRemux(transmuxResults, demuxResult, chunkMeta) {
  14033. const {
  14034. audioTrack,
  14035. videoTrack,
  14036. id3Track,
  14037. textTrack
  14038. } = demuxResult;
  14039. const {
  14040. accurateTimeOffset,
  14041. timeOffset
  14042. } = this.currentTransmuxState;
  14043. 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}`);
  14044. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
  14045. transmuxResults.push({
  14046. remuxResult,
  14047. chunkMeta
  14048. });
  14049. chunkMeta.transmuxing.executeEnd = now();
  14050. }
  14051. resetInitialTimestamp(defaultInitPts) {
  14052. const {
  14053. demuxer,
  14054. remuxer
  14055. } = this;
  14056. if (!demuxer || !remuxer) {
  14057. return;
  14058. }
  14059. demuxer.resetTimeStamp(defaultInitPts);
  14060. remuxer.resetTimeStamp(defaultInitPts);
  14061. }
  14062. resetContiguity() {
  14063. const {
  14064. demuxer,
  14065. remuxer
  14066. } = this;
  14067. if (!demuxer || !remuxer) {
  14068. return;
  14069. }
  14070. demuxer.resetContiguity();
  14071. remuxer.resetNextTimestamp();
  14072. }
  14073. resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration, decryptdata) {
  14074. const {
  14075. demuxer,
  14076. remuxer
  14077. } = this;
  14078. if (!demuxer || !remuxer) {
  14079. return;
  14080. }
  14081. demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration);
  14082. remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, decryptdata);
  14083. }
  14084. destroy() {
  14085. if (this.demuxer) {
  14086. this.demuxer.destroy();
  14087. this.demuxer = void 0;
  14088. }
  14089. if (this.remuxer) {
  14090. this.remuxer.destroy();
  14091. this.remuxer = void 0;
  14092. }
  14093. }
  14094. transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
  14095. let result;
  14096. if (keyData && keyData.method === "SAMPLE-AES") {
  14097. result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  14098. } else {
  14099. result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
  14100. }
  14101. return result;
  14102. }
  14103. transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
  14104. const {
  14105. audioTrack,
  14106. videoTrack,
  14107. id3Track,
  14108. textTrack
  14109. } = this.demuxer.demux(data, timeOffset, false, !this.config.progressive);
  14110. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
  14111. return {
  14112. remuxResult,
  14113. chunkMeta
  14114. };
  14115. }
  14116. transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
  14117. return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then((demuxResult) => {
  14118. const remuxResult = this.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, this.id);
  14119. return {
  14120. remuxResult,
  14121. chunkMeta
  14122. };
  14123. });
  14124. }
  14125. configureTransmuxer(data) {
  14126. const {
  14127. config,
  14128. observer,
  14129. typeSupported
  14130. } = this;
  14131. let mux;
  14132. for (let i = 0, len = muxConfig.length; i < len; i++) {
  14133. var _muxConfig$i$demux;
  14134. if ((_muxConfig$i$demux = muxConfig[i].demux) != null && _muxConfig$i$demux.probe(data, this.logger)) {
  14135. mux = muxConfig[i];
  14136. break;
  14137. }
  14138. }
  14139. if (!mux) {
  14140. return new Error("Failed to find demuxer by probing fragment data");
  14141. }
  14142. const demuxer = this.demuxer;
  14143. const remuxer = this.remuxer;
  14144. const Remuxer = mux.remux;
  14145. const Demuxer = mux.demux;
  14146. if (!remuxer || !(remuxer instanceof Remuxer)) {
  14147. this.remuxer = new Remuxer(observer, config, typeSupported, this.logger);
  14148. }
  14149. if (!demuxer || !(demuxer instanceof Demuxer)) {
  14150. this.demuxer = new Demuxer(observer, config, typeSupported, this.logger);
  14151. this.probe = Demuxer.probe;
  14152. }
  14153. }
  14154. needsProbing(discontinuity, trackSwitch) {
  14155. return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
  14156. }
  14157. getDecrypter() {
  14158. let decrypter = this.decrypter;
  14159. if (!decrypter) {
  14160. decrypter = this.decrypter = new Decrypter(this.config);
  14161. }
  14162. return decrypter;
  14163. }
  14164. };
  14165. function getEncryptionType(data, decryptData) {
  14166. let encryptionType = null;
  14167. if (data.byteLength > 0 && (decryptData == null ? void 0 : decryptData.key) != null && decryptData.iv !== null && decryptData.method != null) {
  14168. encryptionType = decryptData;
  14169. }
  14170. return encryptionType;
  14171. }
  14172. var emptyResult = (chunkMeta) => ({
  14173. remuxResult: {},
  14174. chunkMeta
  14175. });
  14176. function isPromise(p) {
  14177. return "then" in p && p.then instanceof Function;
  14178. }
  14179. var TransmuxConfig = class {
  14180. constructor(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
  14181. this.audioCodec = void 0;
  14182. this.videoCodec = void 0;
  14183. this.initSegmentData = void 0;
  14184. this.duration = void 0;
  14185. this.defaultInitPts = void 0;
  14186. this.audioCodec = audioCodec;
  14187. this.videoCodec = videoCodec;
  14188. this.initSegmentData = initSegmentData;
  14189. this.duration = duration;
  14190. this.defaultInitPts = defaultInitPts || null;
  14191. }
  14192. };
  14193. var TransmuxState = class {
  14194. constructor(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) {
  14195. this.discontinuity = void 0;
  14196. this.contiguous = void 0;
  14197. this.accurateTimeOffset = void 0;
  14198. this.trackSwitch = void 0;
  14199. this.timeOffset = void 0;
  14200. this.initSegmentChange = void 0;
  14201. this.discontinuity = discontinuity;
  14202. this.contiguous = contiguous;
  14203. this.accurateTimeOffset = accurateTimeOffset;
  14204. this.trackSwitch = trackSwitch;
  14205. this.timeOffset = timeOffset;
  14206. this.initSegmentChange = initSegmentChange;
  14207. }
  14208. };
  14209. var transmuxerInstanceCount = 0;
  14210. var TransmuxerInterface = class {
  14211. constructor(_hls, id, onTransmuxComplete, onFlush) {
  14212. this.error = null;
  14213. this.hls = void 0;
  14214. this.id = void 0;
  14215. this.instanceNo = transmuxerInstanceCount++;
  14216. this.observer = void 0;
  14217. this.frag = null;
  14218. this.part = null;
  14219. this.useWorker = void 0;
  14220. this.workerContext = null;
  14221. this.transmuxer = null;
  14222. this.onTransmuxComplete = void 0;
  14223. this.onFlush = void 0;
  14224. this.onWorkerMessage = (event) => {
  14225. const data = event.data;
  14226. const hls = this.hls;
  14227. if (!hls || !(data != null && data.event) || data.instanceNo !== this.instanceNo) {
  14228. return;
  14229. }
  14230. switch (data.event) {
  14231. case "init": {
  14232. var _this$workerContext;
  14233. const objectURL = (_this$workerContext = this.workerContext) == null ? void 0 : _this$workerContext.objectURL;
  14234. if (objectURL) {
  14235. self.URL.revokeObjectURL(objectURL);
  14236. }
  14237. break;
  14238. }
  14239. case "transmuxComplete": {
  14240. this.handleTransmuxComplete(data.data);
  14241. break;
  14242. }
  14243. case "flush": {
  14244. this.onFlush(data.data);
  14245. break;
  14246. }
  14247. case "workerLog": {
  14248. if (hls.logger[data.data.logType]) {
  14249. hls.logger[data.data.logType](data.data.message);
  14250. }
  14251. break;
  14252. }
  14253. default: {
  14254. data.data = data.data || {};
  14255. data.data.frag = this.frag;
  14256. data.data.part = this.part;
  14257. data.data.id = this.id;
  14258. hls.trigger(data.event, data.data);
  14259. break;
  14260. }
  14261. }
  14262. };
  14263. this.onWorkerError = (event) => {
  14264. if (!this.hls) {
  14265. return;
  14266. }
  14267. const error = new Error(`${event.message} (${event.filename}:${event.lineno})`);
  14268. this.hls.config.enableWorker = false;
  14269. this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`);
  14270. this.hls.trigger(Events.ERROR, {
  14271. type: ErrorTypes.OTHER_ERROR,
  14272. details: ErrorDetails.INTERNAL_EXCEPTION,
  14273. fatal: false,
  14274. event: "demuxerWorker",
  14275. error
  14276. });
  14277. };
  14278. const config = _hls.config;
  14279. this.hls = _hls;
  14280. this.id = id;
  14281. this.useWorker = !!config.enableWorker;
  14282. this.onTransmuxComplete = onTransmuxComplete;
  14283. this.onFlush = onFlush;
  14284. const forwardMessage = (ev, data) => {
  14285. data = data || {};
  14286. data.frag = this.frag || void 0;
  14287. if (ev === Events.ERROR) {
  14288. data = data;
  14289. data.parent = this.id;
  14290. data.part = this.part;
  14291. this.error = data.error;
  14292. }
  14293. this.hls.trigger(ev, data);
  14294. };
  14295. this.observer = new EventEmitter();
  14296. this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  14297. this.observer.on(Events.ERROR, forwardMessage);
  14298. const m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
  14299. if (this.useWorker && typeof Worker !== "undefined") {
  14300. const logger2 = this.hls.logger;
  14301. const canCreateWorker = config.workerPath || hasUMDWorker();
  14302. if (canCreateWorker) {
  14303. try {
  14304. if (config.workerPath) {
  14305. logger2.log(`loading Web Worker ${config.workerPath} for "${id}"`);
  14306. this.workerContext = loadWorker(config.workerPath);
  14307. } else {
  14308. logger2.log(`injecting Web Worker for "${id}"`);
  14309. this.workerContext = injectWorker();
  14310. }
  14311. const {
  14312. worker
  14313. } = this.workerContext;
  14314. worker.addEventListener("message", this.onWorkerMessage);
  14315. worker.addEventListener("error", this.onWorkerError);
  14316. worker.postMessage({
  14317. instanceNo: this.instanceNo,
  14318. cmd: "init",
  14319. typeSupported: m2tsTypeSupported,
  14320. id,
  14321. config: stringify(config)
  14322. });
  14323. } catch (err) {
  14324. logger2.warn(`Error setting up "${id}" Web Worker, fallback to inline`, err);
  14325. this.terminateWorker();
  14326. this.error = null;
  14327. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, "", id, _hls.logger);
  14328. }
  14329. return;
  14330. }
  14331. }
  14332. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, "", id, _hls.logger);
  14333. }
  14334. reset() {
  14335. this.frag = null;
  14336. this.part = null;
  14337. if (this.workerContext) {
  14338. const instanceNo = this.instanceNo;
  14339. this.instanceNo = transmuxerInstanceCount++;
  14340. const config = this.hls.config;
  14341. const m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
  14342. this.workerContext.worker.postMessage({
  14343. instanceNo: this.instanceNo,
  14344. cmd: "reset",
  14345. resetNo: instanceNo,
  14346. typeSupported: m2tsTypeSupported,
  14347. id: this.id,
  14348. config: stringify(config)
  14349. });
  14350. }
  14351. }
  14352. terminateWorker() {
  14353. if (this.workerContext) {
  14354. const {
  14355. worker
  14356. } = this.workerContext;
  14357. this.workerContext = null;
  14358. worker.removeEventListener("message", this.onWorkerMessage);
  14359. worker.removeEventListener("error", this.onWorkerError);
  14360. removeWorkerFromStore(this.hls.config.workerPath);
  14361. }
  14362. }
  14363. destroy() {
  14364. if (this.workerContext) {
  14365. this.terminateWorker();
  14366. this.onWorkerMessage = this.onWorkerError = null;
  14367. } else {
  14368. const transmuxer = this.transmuxer;
  14369. if (transmuxer) {
  14370. transmuxer.destroy();
  14371. this.transmuxer = null;
  14372. }
  14373. }
  14374. const observer = this.observer;
  14375. if (observer) {
  14376. observer.removeAllListeners();
  14377. }
  14378. this.frag = null;
  14379. this.part = null;
  14380. this.observer = null;
  14381. this.hls = null;
  14382. }
  14383. push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
  14384. var _frag$initSegment, _lastFrag$initSegment;
  14385. chunkMeta.transmuxing.start = self.performance.now();
  14386. const {
  14387. instanceNo,
  14388. transmuxer
  14389. } = this;
  14390. const timeOffset = part ? part.start : frag.start;
  14391. const decryptdata = frag.decryptdata;
  14392. const lastFrag = this.frag;
  14393. const discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  14394. const trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
  14395. const snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
  14396. const partDiff = this.part ? chunkMeta.part - this.part.index : -1;
  14397. const progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag == null ? void 0 : lastFrag.stats.chunkCount);
  14398. const contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0));
  14399. const now2 = self.performance.now();
  14400. if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
  14401. frag.stats.parsing.start = now2;
  14402. }
  14403. if (part && (partDiff || !contiguous)) {
  14404. part.stats.parsing.start = now2;
  14405. }
  14406. const initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) == null ? void 0 : _lastFrag$initSegment.url));
  14407. const state = new TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange);
  14408. if (!contiguous || discontinuity || initSegmentChange) {
  14409. 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}
  14410. discontinuity: ${discontinuity}
  14411. trackSwitch: ${trackSwitch}
  14412. contiguous: ${contiguous}
  14413. accurateTimeOffset: ${accurateTimeOffset}
  14414. timeOffset: ${timeOffset}
  14415. initSegmentChange: ${initSegmentChange}`);
  14416. const config = new TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
  14417. this.configureTransmuxer(config);
  14418. }
  14419. this.frag = frag;
  14420. this.part = part;
  14421. if (this.workerContext) {
  14422. this.workerContext.worker.postMessage({
  14423. instanceNo,
  14424. cmd: "demux",
  14425. data,
  14426. decryptdata,
  14427. chunkMeta,
  14428. state
  14429. }, data instanceof ArrayBuffer ? [data] : []);
  14430. } else if (transmuxer) {
  14431. const transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
  14432. if (isPromise(transmuxResult)) {
  14433. transmuxResult.then((data2) => {
  14434. this.handleTransmuxComplete(data2);
  14435. }).catch((error) => {
  14436. this.transmuxerError(error, chunkMeta, "transmuxer-interface push error");
  14437. });
  14438. } else {
  14439. this.handleTransmuxComplete(transmuxResult);
  14440. }
  14441. }
  14442. }
  14443. flush(chunkMeta) {
  14444. chunkMeta.transmuxing.start = self.performance.now();
  14445. const {
  14446. instanceNo,
  14447. transmuxer
  14448. } = this;
  14449. if (this.workerContext) {
  14450. this.workerContext.worker.postMessage({
  14451. instanceNo,
  14452. cmd: "flush",
  14453. chunkMeta
  14454. });
  14455. } else if (transmuxer) {
  14456. const transmuxResult = transmuxer.flush(chunkMeta);
  14457. if (isPromise(transmuxResult)) {
  14458. transmuxResult.then((data) => {
  14459. this.handleFlushResult(data, chunkMeta);
  14460. }).catch((error) => {
  14461. this.transmuxerError(error, chunkMeta, "transmuxer-interface flush error");
  14462. });
  14463. } else {
  14464. this.handleFlushResult(transmuxResult, chunkMeta);
  14465. }
  14466. }
  14467. }
  14468. transmuxerError(error, chunkMeta, reason) {
  14469. if (!this.hls) {
  14470. return;
  14471. }
  14472. this.error = error;
  14473. this.hls.trigger(Events.ERROR, {
  14474. type: ErrorTypes.MEDIA_ERROR,
  14475. details: ErrorDetails.FRAG_PARSING_ERROR,
  14476. chunkMeta,
  14477. frag: this.frag || void 0,
  14478. part: this.part || void 0,
  14479. fatal: false,
  14480. error,
  14481. err: error,
  14482. reason
  14483. });
  14484. }
  14485. handleFlushResult(results, chunkMeta) {
  14486. results.forEach((result) => {
  14487. this.handleTransmuxComplete(result);
  14488. });
  14489. this.onFlush(chunkMeta);
  14490. }
  14491. configureTransmuxer(config) {
  14492. const {
  14493. instanceNo,
  14494. transmuxer
  14495. } = this;
  14496. if (this.workerContext) {
  14497. this.workerContext.worker.postMessage({
  14498. instanceNo,
  14499. cmd: "configure",
  14500. config
  14501. });
  14502. } else if (transmuxer) {
  14503. transmuxer.configure(config);
  14504. }
  14505. }
  14506. handleTransmuxComplete(result) {
  14507. result.chunkMeta.transmuxing.end = self.performance.now();
  14508. this.onTransmuxComplete(result);
  14509. }
  14510. };
  14511. var TICK_INTERVAL$3 = 100;
  14512. var AudioStreamController = class extends BaseStreamController {
  14513. constructor(hls, fragmentTracker, keyLoader) {
  14514. super(hls, fragmentTracker, keyLoader, "audio-stream-controller", PlaylistLevelType.AUDIO);
  14515. this.mainAnchor = null;
  14516. this.mainFragLoading = null;
  14517. this.audioOnly = false;
  14518. this.bufferedTrack = null;
  14519. this.switchingTrack = null;
  14520. this.trackId = -1;
  14521. this.waitingData = null;
  14522. this.mainDetails = null;
  14523. this.flushing = false;
  14524. this.bufferFlushed = false;
  14525. this.cachedTrackLoadedData = null;
  14526. this.registerListeners();
  14527. }
  14528. onHandlerDestroying() {
  14529. this.unregisterListeners();
  14530. super.onHandlerDestroying();
  14531. this.resetItem();
  14532. }
  14533. resetItem() {
  14534. this.mainDetails = this.mainAnchor = this.mainFragLoading = this.bufferedTrack = this.switchingTrack = this.waitingData = this.cachedTrackLoadedData = null;
  14535. }
  14536. registerListeners() {
  14537. super.registerListeners();
  14538. const {
  14539. hls
  14540. } = this;
  14541. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  14542. hls.on(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  14543. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  14544. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  14545. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  14546. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  14547. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  14548. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  14549. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  14550. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  14551. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  14552. }
  14553. unregisterListeners() {
  14554. const {
  14555. hls
  14556. } = this;
  14557. if (!hls) {
  14558. return;
  14559. }
  14560. super.unregisterListeners();
  14561. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  14562. hls.off(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  14563. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  14564. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  14565. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  14566. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  14567. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  14568. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  14569. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  14570. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  14571. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  14572. }
  14573. onInitPtsFound(event, {
  14574. frag,
  14575. id,
  14576. initPTS,
  14577. timescale
  14578. }) {
  14579. if (id === PlaylistLevelType.MAIN) {
  14580. const cc = frag.cc;
  14581. const inFlightFrag = this.fragCurrent;
  14582. this.initPTS[cc] = {
  14583. baseTime: initPTS,
  14584. timescale
  14585. };
  14586. this.log(`InitPTS for cc: ${cc} found from main: ${initPTS}/${timescale}`);
  14587. this.mainAnchor = frag;
  14588. if (this.state === State.WAITING_INIT_PTS) {
  14589. const waitingData = this.waitingData;
  14590. if (!waitingData && !this.loadingParts || waitingData && waitingData.frag.cc !== cc) {
  14591. this.syncWithAnchor(frag, waitingData == null ? void 0 : waitingData.frag);
  14592. }
  14593. } else if (!this.hls.hasEnoughToStart && inFlightFrag && inFlightFrag.cc !== cc) {
  14594. inFlightFrag.abortRequests();
  14595. this.syncWithAnchor(frag, inFlightFrag);
  14596. } else if (this.state === State.IDLE) {
  14597. this.tick();
  14598. }
  14599. }
  14600. }
  14601. getLoadPosition() {
  14602. if (!this.startFragRequested && this.nextLoadPosition >= 0) {
  14603. return this.nextLoadPosition;
  14604. }
  14605. return super.getLoadPosition();
  14606. }
  14607. syncWithAnchor(mainAnchor, waitingToAppend) {
  14608. var _this$mainFragLoading;
  14609. const mainFragLoading = ((_this$mainFragLoading = this.mainFragLoading) == null ? void 0 : _this$mainFragLoading.frag) || null;
  14610. if (waitingToAppend) {
  14611. if ((mainFragLoading == null ? void 0 : mainFragLoading.cc) === waitingToAppend.cc) {
  14612. return;
  14613. }
  14614. }
  14615. const targetDiscontinuity = (mainFragLoading || mainAnchor).cc;
  14616. const trackDetails = this.getLevelDetails();
  14617. const pos = this.getLoadPosition();
  14618. const syncFrag = findNearestWithCC(trackDetails, targetDiscontinuity, pos);
  14619. if (syncFrag) {
  14620. this.log(`Syncing with main frag at ${syncFrag.start} cc ${syncFrag.cc}`);
  14621. this.startFragRequested = false;
  14622. this.nextLoadPosition = syncFrag.start;
  14623. this.resetLoadingState();
  14624. if (this.state === State.IDLE) {
  14625. this.doTickIdle();
  14626. }
  14627. }
  14628. }
  14629. startLoad(startPosition, skipSeekToStartPosition) {
  14630. if (!this.levels) {
  14631. this.startPosition = startPosition;
  14632. this.state = State.STOPPED;
  14633. return;
  14634. }
  14635. const lastCurrentTime = this.lastCurrentTime;
  14636. this.stopLoad();
  14637. this.setInterval(TICK_INTERVAL$3);
  14638. if (lastCurrentTime > 0 && startPosition === -1) {
  14639. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  14640. startPosition = lastCurrentTime;
  14641. this.state = State.IDLE;
  14642. } else {
  14643. this.state = State.WAITING_TRACK;
  14644. }
  14645. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  14646. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  14647. this.tick();
  14648. }
  14649. doTick() {
  14650. switch (this.state) {
  14651. case State.IDLE:
  14652. this.doTickIdle();
  14653. break;
  14654. case State.WAITING_TRACK: {
  14655. const {
  14656. levels,
  14657. trackId
  14658. } = this;
  14659. const currenTrack = levels == null ? void 0 : levels[trackId];
  14660. const details = currenTrack == null ? void 0 : currenTrack.details;
  14661. if (details && !this.waitForLive(currenTrack)) {
  14662. if (this.waitForCdnTuneIn(details)) {
  14663. break;
  14664. }
  14665. this.state = State.WAITING_INIT_PTS;
  14666. }
  14667. break;
  14668. }
  14669. case State.FRAG_LOADING_WAITING_RETRY: {
  14670. var _this$media;
  14671. const now2 = performance.now();
  14672. const retryDate = this.retryDate;
  14673. if (!retryDate || now2 >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  14674. const {
  14675. levels,
  14676. trackId
  14677. } = this;
  14678. this.log("RetryDate reached, switch back to IDLE state");
  14679. this.resetStartWhenNotLoaded((levels == null ? void 0 : levels[trackId]) || null);
  14680. this.state = State.IDLE;
  14681. }
  14682. break;
  14683. }
  14684. case State.WAITING_INIT_PTS: {
  14685. const waitingData = this.waitingData;
  14686. if (waitingData) {
  14687. const {
  14688. frag,
  14689. part,
  14690. cache,
  14691. complete
  14692. } = waitingData;
  14693. const mainAnchor = this.mainAnchor;
  14694. if (this.initPTS[frag.cc] !== void 0) {
  14695. this.waitingData = null;
  14696. this.state = State.FRAG_LOADING;
  14697. const payload = cache.flush().buffer;
  14698. const data = {
  14699. frag,
  14700. part,
  14701. payload,
  14702. networkDetails: null
  14703. };
  14704. this._handleFragmentLoadProgress(data);
  14705. if (complete) {
  14706. super._handleFragmentLoadComplete(data);
  14707. }
  14708. } else if (mainAnchor && mainAnchor.cc !== waitingData.frag.cc) {
  14709. this.syncWithAnchor(mainAnchor, waitingData.frag);
  14710. }
  14711. } else {
  14712. this.state = State.IDLE;
  14713. }
  14714. }
  14715. }
  14716. this.onTickEnd();
  14717. }
  14718. resetLoadingState() {
  14719. const waitingData = this.waitingData;
  14720. if (waitingData) {
  14721. this.fragmentTracker.removeFragment(waitingData.frag);
  14722. this.waitingData = null;
  14723. }
  14724. super.resetLoadingState();
  14725. }
  14726. onTickEnd() {
  14727. const {
  14728. media
  14729. } = this;
  14730. if (!(media != null && media.readyState)) {
  14731. return;
  14732. }
  14733. this.lastCurrentTime = media.currentTime;
  14734. }
  14735. doTickIdle() {
  14736. var _this$mainFragLoading2;
  14737. const {
  14738. hls,
  14739. levels,
  14740. media,
  14741. trackId
  14742. } = this;
  14743. const config = hls.config;
  14744. if (!this.buffering || !media && !this.primaryPrefetch && (this.startFragRequested || !config.startFragPrefetch) || !(levels != null && levels[trackId])) {
  14745. return;
  14746. }
  14747. const levelInfo = levels[trackId];
  14748. const trackDetails = levelInfo.details;
  14749. if (!trackDetails || this.waitForLive(levelInfo) || this.waitForCdnTuneIn(trackDetails)) {
  14750. this.state = State.WAITING_TRACK;
  14751. this.startFragRequested = false;
  14752. return;
  14753. }
  14754. const bufferable = this.mediaBuffer ? this.mediaBuffer : this.media;
  14755. if (this.bufferFlushed && bufferable) {
  14756. this.bufferFlushed = false;
  14757. this.afterBufferFlushed(bufferable, ElementaryStreamTypes.AUDIO, PlaylistLevelType.AUDIO);
  14758. }
  14759. const bufferInfo = this.getFwdBufferInfo(bufferable, PlaylistLevelType.AUDIO);
  14760. if (bufferInfo === null) {
  14761. return;
  14762. }
  14763. if (!this.switchingTrack && this._streamEnded(bufferInfo, trackDetails)) {
  14764. hls.trigger(Events.BUFFER_EOS, {
  14765. type: "audio"
  14766. });
  14767. this.state = State.ENDED;
  14768. return;
  14769. }
  14770. const bufferLen = bufferInfo.len;
  14771. const maxBufLen = hls.maxBufferLength;
  14772. const fragments = trackDetails.fragments;
  14773. const start = fragments[0].start;
  14774. const loadPosition = this.getLoadPosition();
  14775. const targetBufferTime = this.flushing ? loadPosition : bufferInfo.end;
  14776. if (this.switchingTrack && media) {
  14777. const pos = loadPosition;
  14778. if (trackDetails.PTSKnown && pos < start) {
  14779. if (bufferInfo.end > start || bufferInfo.nextStart) {
  14780. this.log("Alt audio track ahead of main track, seek to start of alt audio track");
  14781. media.currentTime = start + 0.05;
  14782. }
  14783. }
  14784. }
  14785. if (bufferLen >= maxBufLen && !this.switchingTrack && targetBufferTime < fragments[fragments.length - 1].start) {
  14786. return;
  14787. }
  14788. let frag = this.getNextFragment(targetBufferTime, trackDetails);
  14789. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  14790. frag = this.getNextFragmentLoopLoading(frag, trackDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  14791. }
  14792. if (!frag) {
  14793. this.bufferFlushed = true;
  14794. return;
  14795. }
  14796. let mainFragLoading = ((_this$mainFragLoading2 = this.mainFragLoading) == null ? void 0 : _this$mainFragLoading2.frag) || null;
  14797. if (!this.audioOnly && this.startFragRequested && mainFragLoading && isMediaFragment(frag) && !frag.endList && (!trackDetails.live || !this.loadingParts && targetBufferTime < this.hls.liveSyncPosition)) {
  14798. if (this.fragmentTracker.getState(mainFragLoading) === FragmentState.OK) {
  14799. this.mainFragLoading = mainFragLoading = null;
  14800. }
  14801. if (mainFragLoading && isMediaFragment(mainFragLoading)) {
  14802. if (frag.start > mainFragLoading.end) {
  14803. const mainFragAtPos = this.fragmentTracker.getFragAtPos(targetBufferTime, PlaylistLevelType.MAIN);
  14804. if (mainFragAtPos && mainFragAtPos.end > mainFragLoading.end) {
  14805. mainFragLoading = mainFragAtPos;
  14806. this.mainFragLoading = {
  14807. frag: mainFragAtPos,
  14808. targetBufferTime: null
  14809. };
  14810. }
  14811. }
  14812. const atBufferSyncLimit = frag.start > mainFragLoading.end;
  14813. if (atBufferSyncLimit) {
  14814. return;
  14815. }
  14816. }
  14817. }
  14818. this.loadFragment(frag, levelInfo, targetBufferTime);
  14819. }
  14820. onMediaDetaching(event, data) {
  14821. this.bufferFlushed = this.flushing = false;
  14822. super.onMediaDetaching(event, data);
  14823. }
  14824. onAudioTracksUpdated(event, {
  14825. audioTracks
  14826. }) {
  14827. this.resetTransmuxer();
  14828. this.levels = audioTracks.map((mediaPlaylist) => new Level(mediaPlaylist));
  14829. }
  14830. onAudioTrackSwitching(event, data) {
  14831. const altAudio = !!data.url;
  14832. this.trackId = data.id;
  14833. const {
  14834. fragCurrent
  14835. } = this;
  14836. if (fragCurrent) {
  14837. fragCurrent.abortRequests();
  14838. this.removeUnbufferedFrags(fragCurrent.start);
  14839. }
  14840. this.resetLoadingState();
  14841. if (altAudio) {
  14842. this.switchingTrack = data;
  14843. this.flushAudioIfNeeded(data);
  14844. if (this.state !== State.STOPPED) {
  14845. this.setInterval(TICK_INTERVAL$3);
  14846. this.state = State.IDLE;
  14847. this.tick();
  14848. }
  14849. } else {
  14850. this.resetTransmuxer();
  14851. this.switchingTrack = null;
  14852. this.bufferedTrack = data;
  14853. this.clearInterval();
  14854. }
  14855. }
  14856. onManifestLoading() {
  14857. super.onManifestLoading();
  14858. this.bufferFlushed = this.flushing = this.audioOnly = false;
  14859. this.resetItem();
  14860. this.trackId = -1;
  14861. }
  14862. onLevelLoaded(event, data) {
  14863. this.mainDetails = data.details;
  14864. const cachedTrackLoadedData = this.cachedTrackLoadedData;
  14865. if (cachedTrackLoadedData) {
  14866. this.cachedTrackLoadedData = null;
  14867. this.onAudioTrackLoaded(Events.AUDIO_TRACK_LOADED, cachedTrackLoadedData);
  14868. }
  14869. }
  14870. onAudioTrackLoaded(event, data) {
  14871. var _trackLevel$details;
  14872. const {
  14873. levels
  14874. } = this;
  14875. const {
  14876. details: newDetails,
  14877. id: trackId,
  14878. groupId,
  14879. track
  14880. } = data;
  14881. if (!levels) {
  14882. this.warn(`Audio tracks reset while loading track ${trackId} "${track.name}" of "${groupId}"`);
  14883. return;
  14884. }
  14885. const mainDetails = this.mainDetails;
  14886. if (!mainDetails || newDetails.endCC > mainDetails.endCC || mainDetails.expired) {
  14887. this.cachedTrackLoadedData = data;
  14888. if (this.state !== State.STOPPED) {
  14889. this.state = State.WAITING_TRACK;
  14890. }
  14891. return;
  14892. }
  14893. this.cachedTrackLoadedData = null;
  14894. this.log(`Audio track ${trackId} "${track.name}" of "${groupId}" loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""},duration:${newDetails.totalduration}`);
  14895. const trackLevel = levels[trackId];
  14896. let sliding = 0;
  14897. if (newDetails.live || (_trackLevel$details = trackLevel.details) != null && _trackLevel$details.live) {
  14898. this.checkLiveUpdate(newDetails);
  14899. if (newDetails.deltaUpdateFailed) {
  14900. return;
  14901. }
  14902. if (trackLevel.details) {
  14903. var _this$levelLastLoaded;
  14904. sliding = this.alignPlaylists(newDetails, trackLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  14905. }
  14906. if (!newDetails.alignedSliding) {
  14907. alignDiscontinuities(newDetails, mainDetails);
  14908. if (!newDetails.alignedSliding) {
  14909. alignMediaPlaylistByPDT(newDetails, mainDetails);
  14910. }
  14911. sliding = newDetails.fragmentStart;
  14912. }
  14913. }
  14914. trackLevel.details = newDetails;
  14915. this.levelLastLoaded = trackLevel;
  14916. if (!this.startFragRequested) {
  14917. this.setStartPosition(mainDetails, sliding);
  14918. }
  14919. this.hls.trigger(Events.AUDIO_TRACK_UPDATED, {
  14920. details: newDetails,
  14921. id: trackId,
  14922. groupId: data.groupId
  14923. });
  14924. if (this.state === State.WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) {
  14925. this.state = State.IDLE;
  14926. }
  14927. this.tick();
  14928. }
  14929. _handleFragmentLoadProgress(data) {
  14930. var _frag$initSegment;
  14931. const frag = data.frag;
  14932. const {
  14933. part,
  14934. payload
  14935. } = data;
  14936. const {
  14937. config,
  14938. trackId,
  14939. levels
  14940. } = this;
  14941. if (!levels) {
  14942. this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  14943. return;
  14944. }
  14945. const track = levels[trackId];
  14946. if (!track) {
  14947. this.warn("Audio track is undefined on fragment load progress");
  14948. return;
  14949. }
  14950. const details = track.details;
  14951. if (!details) {
  14952. this.warn("Audio track details undefined on fragment load progress");
  14953. this.removeUnbufferedFrags(frag.start);
  14954. return;
  14955. }
  14956. const audioCodec = config.defaultAudioCodec || track.audioCodec || "mp4a.40.2";
  14957. let transmuxer = this.transmuxer;
  14958. if (!transmuxer) {
  14959. transmuxer = this.transmuxer = new TransmuxerInterface(this.hls, PlaylistLevelType.AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  14960. }
  14961. const initPTS = this.initPTS[frag.cc];
  14962. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  14963. if (initPTS !== void 0) {
  14964. const accurateTimeOffset = false;
  14965. const partIndex = part ? part.index : -1;
  14966. const partial = partIndex !== -1;
  14967. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  14968. transmuxer.push(payload, initSegmentData, audioCodec, "", frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  14969. } else {
  14970. 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}`);
  14971. const {
  14972. cache
  14973. } = this.waitingData = this.waitingData || {
  14974. frag,
  14975. part,
  14976. cache: new ChunkCache(),
  14977. complete: false
  14978. };
  14979. cache.push(new Uint8Array(payload));
  14980. if (this.state !== State.STOPPED) {
  14981. this.state = State.WAITING_INIT_PTS;
  14982. }
  14983. }
  14984. }
  14985. _handleFragmentLoadComplete(fragLoadedData) {
  14986. if (this.waitingData) {
  14987. this.waitingData.complete = true;
  14988. return;
  14989. }
  14990. super._handleFragmentLoadComplete(fragLoadedData);
  14991. }
  14992. onBufferReset() {
  14993. this.mediaBuffer = null;
  14994. }
  14995. onBufferCreated(event, data) {
  14996. this.bufferFlushed = this.flushing = false;
  14997. const audioTrack = data.tracks.audio;
  14998. if (audioTrack) {
  14999. this.mediaBuffer = audioTrack.buffer || null;
  15000. }
  15001. }
  15002. onFragLoading(event, data) {
  15003. if (!this.audioOnly && data.frag.type === PlaylistLevelType.MAIN && isMediaFragment(data.frag)) {
  15004. this.mainFragLoading = data;
  15005. if (this.state === State.IDLE) {
  15006. this.tick();
  15007. }
  15008. }
  15009. }
  15010. onFragBuffered(event, data) {
  15011. const {
  15012. frag,
  15013. part
  15014. } = data;
  15015. if (frag.type !== PlaylistLevelType.AUDIO) {
  15016. if (!this.audioOnly && frag.type === PlaylistLevelType.MAIN && !frag.elementaryStreams.video && !frag.elementaryStreams.audiovideo) {
  15017. this.audioOnly = true;
  15018. this.mainFragLoading = null;
  15019. }
  15020. return;
  15021. }
  15022. if (this.fragContextChanged(frag)) {
  15023. 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"}`);
  15024. return;
  15025. }
  15026. if (isMediaFragment(frag)) {
  15027. this.fragPrevious = frag;
  15028. const track = this.switchingTrack;
  15029. if (track) {
  15030. this.bufferedTrack = track;
  15031. this.switchingTrack = null;
  15032. this.hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, track));
  15033. }
  15034. }
  15035. this.fragBufferedComplete(frag, part);
  15036. if (this.media) {
  15037. this.tick();
  15038. }
  15039. }
  15040. onError(event, data) {
  15041. var _data$context;
  15042. if (data.fatal) {
  15043. this.state = State.ERROR;
  15044. return;
  15045. }
  15046. switch (data.details) {
  15047. case ErrorDetails.FRAG_GAP:
  15048. case ErrorDetails.FRAG_PARSING_ERROR:
  15049. case ErrorDetails.FRAG_DECRYPT_ERROR:
  15050. case ErrorDetails.FRAG_LOAD_ERROR:
  15051. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  15052. case ErrorDetails.KEY_LOAD_ERROR:
  15053. case ErrorDetails.KEY_LOAD_TIMEOUT:
  15054. this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO, data);
  15055. break;
  15056. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  15057. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  15058. case ErrorDetails.LEVEL_PARSING_ERROR:
  15059. if (!data.levelRetry && this.state === State.WAITING_TRACK && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.AUDIO_TRACK) {
  15060. this.state = State.IDLE;
  15061. }
  15062. break;
  15063. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  15064. case ErrorDetails.BUFFER_APPEND_ERROR:
  15065. if (data.parent !== "audio") {
  15066. return;
  15067. }
  15068. if (!this.reduceLengthAndFlushBuffer(data)) {
  15069. this.resetLoadingState();
  15070. }
  15071. break;
  15072. case ErrorDetails.BUFFER_FULL_ERROR:
  15073. if (data.parent !== "audio") {
  15074. return;
  15075. }
  15076. if (this.reduceLengthAndFlushBuffer(data)) {
  15077. this.bufferedTrack = null;
  15078. super.flushMainBuffer(0, Number.POSITIVE_INFINITY, "audio");
  15079. }
  15080. break;
  15081. case ErrorDetails.INTERNAL_EXCEPTION:
  15082. this.recoverWorkerError(data);
  15083. break;
  15084. }
  15085. }
  15086. onBufferFlushing(event, {
  15087. type
  15088. }) {
  15089. if (type !== ElementaryStreamTypes.VIDEO) {
  15090. this.flushing = true;
  15091. }
  15092. }
  15093. onBufferFlushed(event, {
  15094. type
  15095. }) {
  15096. if (type !== ElementaryStreamTypes.VIDEO) {
  15097. this.flushing = false;
  15098. this.bufferFlushed = true;
  15099. if (this.state === State.ENDED) {
  15100. this.state = State.IDLE;
  15101. }
  15102. const mediaBuffer = this.mediaBuffer || this.media;
  15103. if (mediaBuffer) {
  15104. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.AUDIO);
  15105. this.tick();
  15106. }
  15107. }
  15108. }
  15109. _handleTransmuxComplete(transmuxResult) {
  15110. var _id3$samples;
  15111. const id = "audio";
  15112. const {
  15113. hls
  15114. } = this;
  15115. const {
  15116. remuxResult,
  15117. chunkMeta
  15118. } = transmuxResult;
  15119. const context = this.getCurrentContext(chunkMeta);
  15120. if (!context) {
  15121. this.resetWhenMissingContext(chunkMeta);
  15122. return;
  15123. }
  15124. const {
  15125. frag,
  15126. part,
  15127. level
  15128. } = context;
  15129. const {
  15130. details
  15131. } = level;
  15132. const {
  15133. audio,
  15134. text,
  15135. id3,
  15136. initSegment
  15137. } = remuxResult;
  15138. if (this.fragContextChanged(frag) || !details) {
  15139. this.fragmentTracker.removeFragment(frag);
  15140. return;
  15141. }
  15142. this.state = State.PARSING;
  15143. if (this.switchingTrack && audio) {
  15144. this.completeAudioSwitch(this.switchingTrack);
  15145. }
  15146. if (initSegment != null && initSegment.tracks) {
  15147. const mapFragment = frag.initSegment || frag;
  15148. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  15149. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  15150. frag: mapFragment,
  15151. id,
  15152. tracks: initSegment.tracks
  15153. });
  15154. }
  15155. if (audio) {
  15156. const {
  15157. startPTS,
  15158. endPTS,
  15159. startDTS,
  15160. endDTS
  15161. } = audio;
  15162. if (part) {
  15163. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  15164. startPTS,
  15165. endPTS,
  15166. startDTS,
  15167. endDTS
  15168. };
  15169. }
  15170. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  15171. this.bufferFragmentData(audio, frag, part, chunkMeta);
  15172. }
  15173. if (id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  15174. const emittedID3 = _extends({
  15175. id,
  15176. frag,
  15177. details
  15178. }, id3);
  15179. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  15180. }
  15181. if (text) {
  15182. const emittedText = _extends({
  15183. id,
  15184. frag,
  15185. details
  15186. }, text);
  15187. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  15188. }
  15189. }
  15190. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  15191. if (this.state !== State.PARSING) {
  15192. return;
  15193. }
  15194. if (tracks.video) {
  15195. delete tracks.video;
  15196. }
  15197. if (tracks.audiovideo) {
  15198. delete tracks.audiovideo;
  15199. }
  15200. if (!tracks.audio) {
  15201. return;
  15202. }
  15203. const track = tracks.audio;
  15204. track.id = PlaylistLevelType.AUDIO;
  15205. const variantAudioCodecs = currentLevel.audioCodec;
  15206. this.log(`Init audio buffer, container:${track.container}, codecs[level/parsed]=[${variantAudioCodecs}/${track.codec}]`);
  15207. if (variantAudioCodecs && variantAudioCodecs.split(",").length === 1) {
  15208. track.levelCodec = variantAudioCodecs;
  15209. }
  15210. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  15211. const initSegment = track.initSegment;
  15212. if (initSegment != null && initSegment.byteLength) {
  15213. const segment = {
  15214. type: "audio",
  15215. frag,
  15216. part: null,
  15217. chunkMeta,
  15218. parent: frag.type,
  15219. data: initSegment
  15220. };
  15221. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  15222. }
  15223. this.tickImmediate();
  15224. }
  15225. loadFragment(frag, track, targetBufferTime) {
  15226. const fragState = this.fragmentTracker.getState(frag);
  15227. if (this.switchingTrack || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  15228. var _track$details;
  15229. if (!isMediaFragment(frag)) {
  15230. this._loadInitSegment(frag, track);
  15231. } else if ((_track$details = track.details) != null && _track$details.live && !this.initPTS[frag.cc]) {
  15232. this.log(`Waiting for video PTS in continuity counter ${frag.cc} of live stream before loading audio fragment ${frag.sn} of level ${this.trackId}`);
  15233. this.state = State.WAITING_INIT_PTS;
  15234. const mainDetails = this.mainDetails;
  15235. if (mainDetails && mainDetails.fragmentStart !== track.details.fragmentStart) {
  15236. alignMediaPlaylistByPDT(track.details, mainDetails);
  15237. }
  15238. } else {
  15239. super.loadFragment(frag, track, targetBufferTime);
  15240. }
  15241. } else {
  15242. this.clearTrackerIfNeeded(frag);
  15243. }
  15244. }
  15245. flushAudioIfNeeded(switchingTrack) {
  15246. if (this.media && this.bufferedTrack) {
  15247. const {
  15248. name,
  15249. lang,
  15250. assocLang,
  15251. characteristics,
  15252. audioCodec,
  15253. channels
  15254. } = this.bufferedTrack;
  15255. if (!matchesOption({
  15256. name,
  15257. lang,
  15258. assocLang,
  15259. characteristics,
  15260. audioCodec,
  15261. channels
  15262. }, switchingTrack, audioMatchPredicate)) {
  15263. if (useAlternateAudio(switchingTrack.url, this.hls)) {
  15264. this.log("Switching audio track : flushing all audio");
  15265. super.flushMainBuffer(0, Number.POSITIVE_INFINITY, "audio");
  15266. this.bufferedTrack = null;
  15267. } else {
  15268. this.bufferedTrack = switchingTrack;
  15269. }
  15270. }
  15271. }
  15272. }
  15273. completeAudioSwitch(switchingTrack) {
  15274. const {
  15275. hls
  15276. } = this;
  15277. this.flushAudioIfNeeded(switchingTrack);
  15278. this.bufferedTrack = switchingTrack;
  15279. this.switchingTrack = null;
  15280. hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, switchingTrack));
  15281. }
  15282. };
  15283. var BasePlaylistController = class extends Logger {
  15284. constructor(hls, logPrefix) {
  15285. super(logPrefix, hls.logger);
  15286. this.hls = void 0;
  15287. this.canLoad = false;
  15288. this.timer = -1;
  15289. this.hls = hls;
  15290. }
  15291. destroy() {
  15292. this.clearTimer();
  15293. this.hls = this.log = this.warn = null;
  15294. }
  15295. clearTimer() {
  15296. if (this.timer !== -1) {
  15297. self.clearTimeout(this.timer);
  15298. this.timer = -1;
  15299. }
  15300. }
  15301. startLoad() {
  15302. this.canLoad = true;
  15303. this.loadPlaylist();
  15304. }
  15305. stopLoad() {
  15306. this.canLoad = false;
  15307. this.clearTimer();
  15308. }
  15309. switchParams(playlistUri, previous, current) {
  15310. const renditionReports = previous == null ? void 0 : previous.renditionReports;
  15311. if (renditionReports) {
  15312. let foundIndex = -1;
  15313. for (let i = 0; i < renditionReports.length; i++) {
  15314. const attr = renditionReports[i];
  15315. let uri;
  15316. try {
  15317. uri = new self.URL(attr.URI, previous.url).href;
  15318. } catch (error) {
  15319. this.warn(`Could not construct new URL for Rendition Report: ${error}`);
  15320. uri = attr.URI || "";
  15321. }
  15322. if (uri === playlistUri) {
  15323. foundIndex = i;
  15324. break;
  15325. } else if (uri === playlistUri.substring(0, uri.length)) {
  15326. foundIndex = i;
  15327. }
  15328. }
  15329. if (foundIndex !== -1) {
  15330. const attr = renditionReports[foundIndex];
  15331. const msn = parseInt(attr["LAST-MSN"]) || (previous == null ? void 0 : previous.lastPartSn);
  15332. let part = parseInt(attr["LAST-PART"]) || (previous == null ? void 0 : previous.lastPartIndex);
  15333. if (this.hls.config.lowLatencyMode) {
  15334. const currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
  15335. if (part >= 0 && currentGoal > previous.partTarget) {
  15336. part += 1;
  15337. }
  15338. }
  15339. const skip = current && getSkipValue(current);
  15340. return new HlsUrlParameters(msn, part >= 0 ? part : void 0, skip);
  15341. }
  15342. }
  15343. }
  15344. loadPlaylist(hlsUrlParameters) {
  15345. this.clearTimer();
  15346. }
  15347. loadingPlaylist(playlist, hlsUrlParameters) {
  15348. this.clearTimer();
  15349. }
  15350. shouldLoadPlaylist(playlist) {
  15351. return this.canLoad && !!playlist && !!playlist.url && (!playlist.details || playlist.details.live);
  15352. }
  15353. getUrlWithDirectives(uri, hlsUrlParameters) {
  15354. if (hlsUrlParameters) {
  15355. try {
  15356. return hlsUrlParameters.addDirectives(uri);
  15357. } catch (error) {
  15358. this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`);
  15359. }
  15360. }
  15361. return uri;
  15362. }
  15363. playlistLoaded(index, data, previousDetails) {
  15364. const {
  15365. details,
  15366. stats
  15367. } = data;
  15368. const now2 = self.performance.now();
  15369. const elapsed = stats.loading.first ? Math.max(0, now2 - stats.loading.first) : 0;
  15370. details.advancedDateTime = Date.now() - elapsed;
  15371. const timelineOffset = this.hls.config.timelineOffset;
  15372. if (timelineOffset !== details.appliedTimelineOffset) {
  15373. const offset = Math.max(timelineOffset || 0, 0);
  15374. details.appliedTimelineOffset = offset;
  15375. details.fragments.forEach((frag) => {
  15376. frag.start = frag.playlistOffset + offset;
  15377. });
  15378. }
  15379. if (details.live || previousDetails != null && previousDetails.live) {
  15380. const levelOrTrack = "levelInfo" in data ? data.levelInfo : data.track;
  15381. details.reloaded(previousDetails);
  15382. if (previousDetails && details.fragments.length > 0) {
  15383. mergeDetails(previousDetails, details);
  15384. const error = details.playlistParsingError;
  15385. if (error) {
  15386. this.warn(error);
  15387. const hls = this.hls;
  15388. if (!hls.config.ignorePlaylistParsingErrors) {
  15389. var _details$fragments$;
  15390. const {
  15391. networkDetails
  15392. } = data;
  15393. hls.trigger(Events.ERROR, {
  15394. type: ErrorTypes.NETWORK_ERROR,
  15395. details: ErrorDetails.LEVEL_PARSING_ERROR,
  15396. fatal: false,
  15397. url: details.url,
  15398. error,
  15399. reason: error.message,
  15400. level: data.level || void 0,
  15401. parent: (_details$fragments$ = details.fragments[0]) == null ? void 0 : _details$fragments$.type,
  15402. networkDetails,
  15403. stats
  15404. });
  15405. return;
  15406. }
  15407. details.playlistParsingError = null;
  15408. }
  15409. }
  15410. if (details.requestScheduled === -1) {
  15411. details.requestScheduled = stats.loading.start;
  15412. }
  15413. const bufferInfo = this.hls.mainForwardBufferInfo;
  15414. const position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;
  15415. const distanceToLiveEdgeMs = (details.edge - position) * 1e3;
  15416. const reloadInterval = computeReloadInterval(details, distanceToLiveEdgeMs);
  15417. if (details.requestScheduled + reloadInterval < now2) {
  15418. details.requestScheduled = now2;
  15419. } else {
  15420. details.requestScheduled += reloadInterval;
  15421. }
  15422. this.log(`live playlist ${index} ${details.advanced ? "REFRESHED " + details.lastPartSn + "-" + details.lastPartIndex : details.updated ? "UPDATED" : "MISSED"}`);
  15423. if (!this.canLoad || !details.live) {
  15424. return;
  15425. }
  15426. let deliveryDirectives;
  15427. let msn = void 0;
  15428. let part = void 0;
  15429. if (details.canBlockReload && details.endSN && details.advanced) {
  15430. const lowLatencyMode = this.hls.config.lowLatencyMode;
  15431. const lastPartSn = details.lastPartSn;
  15432. const endSn = details.endSN;
  15433. const lastPartIndex = details.lastPartIndex;
  15434. const hasParts = lastPartIndex !== -1;
  15435. const atLastPartOfSegment = lastPartSn === endSn;
  15436. if (hasParts) {
  15437. if (atLastPartOfSegment) {
  15438. msn = endSn + 1;
  15439. part = lowLatencyMode ? 0 : lastPartIndex;
  15440. } else {
  15441. msn = lastPartSn;
  15442. part = lowLatencyMode ? lastPartIndex + 1 : details.maxPartIndex;
  15443. }
  15444. } else {
  15445. msn = endSn + 1;
  15446. }
  15447. const lastAdvanced = details.age;
  15448. const cdnAge = lastAdvanced + details.ageHeader;
  15449. let currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
  15450. if (currentGoal > 0) {
  15451. if (cdnAge > details.targetduration * 3) {
  15452. this.log(`Playlist last advanced ${lastAdvanced.toFixed(2)}s ago. Omitting segment and part directives.`);
  15453. msn = void 0;
  15454. part = void 0;
  15455. } else if (previousDetails != null && previousDetails.tuneInGoal && cdnAge - details.partTarget > previousDetails.tuneInGoal) {
  15456. this.warn(`CDN Tune-in goal increased from: ${previousDetails.tuneInGoal} to: ${currentGoal} with playlist age: ${details.age}`);
  15457. currentGoal = 0;
  15458. } else {
  15459. const segments = Math.floor(currentGoal / details.targetduration);
  15460. msn += segments;
  15461. if (part !== void 0) {
  15462. const parts = Math.round(currentGoal % details.targetduration / details.partTarget);
  15463. part += parts;
  15464. }
  15465. this.log(`CDN Tune-in age: ${details.ageHeader}s last advanced ${lastAdvanced.toFixed(2)}s goal: ${currentGoal} skip sn ${segments} to part ${part}`);
  15466. }
  15467. details.tuneInGoal = currentGoal;
  15468. }
  15469. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  15470. if (lowLatencyMode || !atLastPartOfSegment) {
  15471. details.requestScheduled = now2;
  15472. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  15473. return;
  15474. }
  15475. } else if (details.canBlockReload || details.canSkipUntil) {
  15476. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  15477. }
  15478. if (deliveryDirectives && msn !== void 0 && details.canBlockReload) {
  15479. details.requestScheduled = stats.loading.first + Math.max(reloadInterval - elapsed * 2, reloadInterval / 2);
  15480. }
  15481. this.scheduleLoading(levelOrTrack, deliveryDirectives, details);
  15482. } else {
  15483. this.clearTimer();
  15484. }
  15485. }
  15486. scheduleLoading(levelOrTrack, deliveryDirectives, updatedDetails) {
  15487. const details = updatedDetails || levelOrTrack.details;
  15488. if (!details) {
  15489. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  15490. return;
  15491. }
  15492. const now2 = self.performance.now();
  15493. const requestScheduled = details.requestScheduled;
  15494. if (now2 >= requestScheduled) {
  15495. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  15496. return;
  15497. }
  15498. const estimatedTimeUntilUpdate = requestScheduled - now2;
  15499. this.log(`reload live playlist ${levelOrTrack.name || levelOrTrack.bitrate + "bps"} in ${Math.round(estimatedTimeUntilUpdate)} ms`);
  15500. this.clearTimer();
  15501. this.timer = self.setTimeout(() => this.loadingPlaylist(levelOrTrack, deliveryDirectives), estimatedTimeUntilUpdate);
  15502. }
  15503. getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
  15504. let skip = getSkipValue(details);
  15505. if (previousDeliveryDirectives != null && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
  15506. msn = previousDeliveryDirectives.msn;
  15507. part = previousDeliveryDirectives.part;
  15508. skip = HlsSkip.No;
  15509. }
  15510. return new HlsUrlParameters(msn, part, skip);
  15511. }
  15512. checkRetry(errorEvent) {
  15513. const errorDetails = errorEvent.details;
  15514. const isTimeout = isTimeoutError(errorEvent);
  15515. const errorAction = errorEvent.errorAction;
  15516. const {
  15517. action,
  15518. retryCount = 0,
  15519. retryConfig
  15520. } = errorAction || {};
  15521. const retry = !!errorAction && !!retryConfig && (action === NetworkErrorAction.RetryRequest || !errorAction.resolved && action === NetworkErrorAction.SendAlternateToPenaltyBox);
  15522. if (retry) {
  15523. var _errorEvent$context;
  15524. if (retryCount >= retryConfig.maxNumRetry) {
  15525. return false;
  15526. }
  15527. if (isTimeout && (_errorEvent$context = errorEvent.context) != null && _errorEvent$context.deliveryDirectives) {
  15528. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" without delivery-directives`);
  15529. this.loadPlaylist();
  15530. } else {
  15531. const delay = getRetryDelay(retryConfig, retryCount);
  15532. this.clearTimer();
  15533. this.timer = self.setTimeout(() => this.loadPlaylist(), delay);
  15534. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" in ${delay}ms`);
  15535. }
  15536. errorEvent.levelRetry = true;
  15537. errorAction.resolved = true;
  15538. }
  15539. return retry;
  15540. }
  15541. };
  15542. function subtitleOptionsIdentical(trackList1, trackList2) {
  15543. if (trackList1.length !== trackList2.length) {
  15544. return false;
  15545. }
  15546. for (let i = 0; i < trackList1.length; i++) {
  15547. if (!mediaAttributesIdentical(trackList1[i].attrs, trackList2[i].attrs)) {
  15548. return false;
  15549. }
  15550. }
  15551. return true;
  15552. }
  15553. function mediaAttributesIdentical(attrs1, attrs2, customAttributes) {
  15554. const stableRenditionId = attrs1["STABLE-RENDITION-ID"];
  15555. if (stableRenditionId && !customAttributes) {
  15556. return stableRenditionId === attrs2["STABLE-RENDITION-ID"];
  15557. }
  15558. return !(customAttributes || ["LANGUAGE", "NAME", "CHARACTERISTICS", "AUTOSELECT", "DEFAULT", "FORCED", "ASSOC-LANGUAGE"]).some((subtitleAttribute) => attrs1[subtitleAttribute] !== attrs2[subtitleAttribute]);
  15559. }
  15560. function subtitleTrackMatchesTextTrack(subtitleTrack, textTrack) {
  15561. return textTrack.label.toLowerCase() === subtitleTrack.name.toLowerCase() && (!textTrack.language || textTrack.language.toLowerCase() === (subtitleTrack.lang || "").toLowerCase());
  15562. }
  15563. var AudioTrackController = class extends BasePlaylistController {
  15564. constructor(hls) {
  15565. super(hls, "audio-track-controller");
  15566. this.tracks = [];
  15567. this.groupIds = null;
  15568. this.tracksInGroup = [];
  15569. this.trackId = -1;
  15570. this.currentTrack = null;
  15571. this.selectDefaultTrack = true;
  15572. this.registerListeners();
  15573. }
  15574. registerListeners() {
  15575. const {
  15576. hls
  15577. } = this;
  15578. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  15579. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  15580. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  15581. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  15582. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  15583. hls.on(Events.ERROR, this.onError, this);
  15584. }
  15585. unregisterListeners() {
  15586. const {
  15587. hls
  15588. } = this;
  15589. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  15590. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  15591. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  15592. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  15593. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  15594. hls.off(Events.ERROR, this.onError, this);
  15595. }
  15596. destroy() {
  15597. this.unregisterListeners();
  15598. this.tracks.length = 0;
  15599. this.tracksInGroup.length = 0;
  15600. this.currentTrack = null;
  15601. super.destroy();
  15602. }
  15603. onManifestLoading() {
  15604. this.tracks = [];
  15605. this.tracksInGroup = [];
  15606. this.groupIds = null;
  15607. this.currentTrack = null;
  15608. this.trackId = -1;
  15609. this.selectDefaultTrack = true;
  15610. }
  15611. onManifestParsed(event, data) {
  15612. this.tracks = data.audioTracks || [];
  15613. }
  15614. onAudioTrackLoaded(event, data) {
  15615. const {
  15616. id,
  15617. groupId,
  15618. details
  15619. } = data;
  15620. const trackInActiveGroup = this.tracksInGroup[id];
  15621. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  15622. this.warn(`Audio track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
  15623. return;
  15624. }
  15625. const curDetails = trackInActiveGroup.details;
  15626. trackInActiveGroup.details = data.details;
  15627. this.log(`Audio track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
  15628. if (id === this.trackId) {
  15629. this.playlistLoaded(id, data, curDetails);
  15630. }
  15631. }
  15632. onLevelLoading(event, data) {
  15633. this.switchLevel(data.level);
  15634. }
  15635. onLevelSwitching(event, data) {
  15636. this.switchLevel(data.level);
  15637. }
  15638. switchLevel(levelIndex) {
  15639. const levelInfo = this.hls.levels[levelIndex];
  15640. if (!levelInfo) {
  15641. return;
  15642. }
  15643. const audioGroups = levelInfo.audioGroups || null;
  15644. const currentGroups = this.groupIds;
  15645. let currentTrack = this.currentTrack;
  15646. 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)) {
  15647. this.groupIds = audioGroups;
  15648. this.trackId = -1;
  15649. this.currentTrack = null;
  15650. const audioTracks = this.tracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  15651. if (audioTracks.length) {
  15652. if (this.selectDefaultTrack && !audioTracks.some((track) => track.default)) {
  15653. this.selectDefaultTrack = false;
  15654. }
  15655. audioTracks.forEach((track, i) => {
  15656. track.id = i;
  15657. });
  15658. } else if (!currentTrack && !this.tracksInGroup.length) {
  15659. return;
  15660. }
  15661. this.tracksInGroup = audioTracks;
  15662. const audioPreference = this.hls.config.audioPreference;
  15663. if (!currentTrack && audioPreference) {
  15664. const groupIndex = findMatchingOption(audioPreference, audioTracks, audioMatchPredicate);
  15665. if (groupIndex > -1) {
  15666. currentTrack = audioTracks[groupIndex];
  15667. } else {
  15668. const allIndex = findMatchingOption(audioPreference, this.tracks);
  15669. currentTrack = this.tracks[allIndex];
  15670. }
  15671. }
  15672. let trackId = this.findTrackId(currentTrack);
  15673. if (trackId === -1 && currentTrack) {
  15674. trackId = this.findTrackId(null);
  15675. }
  15676. const audioTracksUpdated = {
  15677. audioTracks
  15678. };
  15679. this.log(`Updating audio tracks, ${audioTracks.length} track(s) found in group(s): ${audioGroups == null ? void 0 : audioGroups.join(",")}`);
  15680. this.hls.trigger(Events.AUDIO_TRACKS_UPDATED, audioTracksUpdated);
  15681. const selectedTrackId = this.trackId;
  15682. if (trackId !== -1 && selectedTrackId === -1) {
  15683. this.setAudioTrack(trackId);
  15684. } else if (audioTracks.length && selectedTrackId === -1) {
  15685. var _this$groupIds;
  15686. 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}`);
  15687. this.warn(error.message);
  15688. this.hls.trigger(Events.ERROR, {
  15689. type: ErrorTypes.MEDIA_ERROR,
  15690. details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,
  15691. fatal: true,
  15692. error
  15693. });
  15694. }
  15695. }
  15696. }
  15697. onError(event, data) {
  15698. if (data.fatal || !data.context) {
  15699. return;
  15700. }
  15701. if (data.context.type === PlaylistContextType.AUDIO_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  15702. this.checkRetry(data);
  15703. }
  15704. }
  15705. get allAudioTracks() {
  15706. return this.tracks;
  15707. }
  15708. get audioTracks() {
  15709. return this.tracksInGroup;
  15710. }
  15711. get audioTrack() {
  15712. return this.trackId;
  15713. }
  15714. set audioTrack(newId) {
  15715. this.selectDefaultTrack = false;
  15716. this.setAudioTrack(newId);
  15717. }
  15718. setAudioOption(audioOption) {
  15719. const hls = this.hls;
  15720. hls.config.audioPreference = audioOption;
  15721. if (audioOption) {
  15722. const allAudioTracks = this.allAudioTracks;
  15723. this.selectDefaultTrack = false;
  15724. if (allAudioTracks.length) {
  15725. const currentTrack = this.currentTrack;
  15726. if (currentTrack && matchesOption(audioOption, currentTrack, audioMatchPredicate)) {
  15727. return currentTrack;
  15728. }
  15729. const groupIndex = findMatchingOption(audioOption, this.tracksInGroup, audioMatchPredicate);
  15730. if (groupIndex > -1) {
  15731. const track = this.tracksInGroup[groupIndex];
  15732. this.setAudioTrack(groupIndex);
  15733. return track;
  15734. } else if (currentTrack) {
  15735. let searchIndex = hls.loadLevel;
  15736. if (searchIndex === -1) {
  15737. searchIndex = hls.firstAutoLevel;
  15738. }
  15739. const switchIndex = findClosestLevelWithAudioGroup(audioOption, hls.levels, allAudioTracks, searchIndex, audioMatchPredicate);
  15740. if (switchIndex === -1) {
  15741. return null;
  15742. }
  15743. hls.nextLoadLevel = switchIndex;
  15744. }
  15745. if (audioOption.channels || audioOption.audioCodec) {
  15746. const withoutCodecAndChannelsMatch = findMatchingOption(audioOption, allAudioTracks);
  15747. if (withoutCodecAndChannelsMatch > -1) {
  15748. return allAudioTracks[withoutCodecAndChannelsMatch];
  15749. }
  15750. }
  15751. }
  15752. }
  15753. return null;
  15754. }
  15755. setAudioTrack(newId) {
  15756. const tracks = this.tracksInGroup;
  15757. if (newId < 0 || newId >= tracks.length) {
  15758. this.warn(`Invalid audio track id: ${newId}`);
  15759. return;
  15760. }
  15761. this.selectDefaultTrack = false;
  15762. const lastTrack = this.currentTrack;
  15763. const track = tracks[newId];
  15764. const trackLoaded = track.details && !track.details.live;
  15765. if (newId === this.trackId && track === lastTrack && trackLoaded) {
  15766. return;
  15767. }
  15768. this.log(`Switching to audio-track ${newId} "${track.name}" lang:${track.lang} group:${track.groupId} channels:${track.channels}`);
  15769. this.trackId = newId;
  15770. this.currentTrack = track;
  15771. this.hls.trigger(Events.AUDIO_TRACK_SWITCHING, _objectSpread2({}, track));
  15772. if (trackLoaded) {
  15773. return;
  15774. }
  15775. const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
  15776. this.loadPlaylist(hlsUrlParameters);
  15777. }
  15778. findTrackId(currentTrack) {
  15779. const audioTracks = this.tracksInGroup;
  15780. for (let i = 0; i < audioTracks.length; i++) {
  15781. const track = audioTracks[i];
  15782. if (this.selectDefaultTrack && !track.default) {
  15783. continue;
  15784. }
  15785. if (!currentTrack || matchesOption(currentTrack, track, audioMatchPredicate)) {
  15786. return i;
  15787. }
  15788. }
  15789. if (currentTrack) {
  15790. const {
  15791. name,
  15792. lang,
  15793. assocLang,
  15794. characteristics,
  15795. audioCodec,
  15796. channels
  15797. } = currentTrack;
  15798. for (let i = 0; i < audioTracks.length; i++) {
  15799. const track = audioTracks[i];
  15800. if (matchesOption({
  15801. name,
  15802. lang,
  15803. assocLang,
  15804. characteristics,
  15805. audioCodec,
  15806. channels
  15807. }, track, audioMatchPredicate)) {
  15808. return i;
  15809. }
  15810. }
  15811. for (let i = 0; i < audioTracks.length; i++) {
  15812. const track = audioTracks[i];
  15813. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE", "ASSOC-LANGUAGE", "CHARACTERISTICS"])) {
  15814. return i;
  15815. }
  15816. }
  15817. for (let i = 0; i < audioTracks.length; i++) {
  15818. const track = audioTracks[i];
  15819. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE"])) {
  15820. return i;
  15821. }
  15822. }
  15823. }
  15824. return -1;
  15825. }
  15826. loadPlaylist(hlsUrlParameters) {
  15827. super.loadPlaylist();
  15828. const audioTrack = this.currentTrack;
  15829. if (!this.shouldLoadPlaylist(audioTrack)) {
  15830. return;
  15831. }
  15832. if (useAlternateAudio(audioTrack.url, this.hls)) {
  15833. this.scheduleLoading(audioTrack, hlsUrlParameters);
  15834. }
  15835. }
  15836. loadingPlaylist(audioTrack, hlsUrlParameters) {
  15837. super.loadingPlaylist(audioTrack, hlsUrlParameters);
  15838. const id = audioTrack.id;
  15839. const groupId = audioTrack.groupId;
  15840. const url = this.getUrlWithDirectives(audioTrack.url, hlsUrlParameters);
  15841. const details = audioTrack.details;
  15842. const age = details == null ? void 0 : details.age;
  15843. 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}`);
  15844. this.hls.trigger(Events.AUDIO_TRACK_LOADING, {
  15845. url,
  15846. id,
  15847. groupId,
  15848. deliveryDirectives: hlsUrlParameters || null,
  15849. track: audioTrack
  15850. });
  15851. }
  15852. };
  15853. var BufferOperationQueue = class {
  15854. constructor(sourceBufferReference) {
  15855. this.tracks = void 0;
  15856. this.queues = {
  15857. video: [],
  15858. audio: [],
  15859. audiovideo: []
  15860. };
  15861. this.tracks = sourceBufferReference;
  15862. }
  15863. destroy() {
  15864. this.tracks = this.queues = null;
  15865. }
  15866. append(operation, type, pending) {
  15867. if (this.queues === null || this.tracks === null) {
  15868. return;
  15869. }
  15870. const queue = this.queues[type];
  15871. queue.push(operation);
  15872. if (queue.length === 1 && !pending) {
  15873. this.executeNext(type);
  15874. }
  15875. }
  15876. appendBlocker(type) {
  15877. return new Promise((resolve) => {
  15878. const operation = {
  15879. label: "async-blocker",
  15880. execute: resolve,
  15881. onStart: () => {
  15882. },
  15883. onComplete: () => {
  15884. },
  15885. onError: () => {
  15886. }
  15887. };
  15888. this.append(operation, type);
  15889. });
  15890. }
  15891. prependBlocker(type) {
  15892. return new Promise((resolve) => {
  15893. if (this.queues) {
  15894. const operation = {
  15895. label: "async-blocker-prepend",
  15896. execute: resolve,
  15897. onStart: () => {
  15898. },
  15899. onComplete: () => {
  15900. },
  15901. onError: () => {
  15902. }
  15903. };
  15904. this.queues[type].unshift(operation);
  15905. }
  15906. });
  15907. }
  15908. removeBlockers() {
  15909. if (this.queues === null) {
  15910. return;
  15911. }
  15912. [this.queues.video, this.queues.audio, this.queues.audiovideo].forEach((queue) => {
  15913. var _queue$;
  15914. const label = (_queue$ = queue[0]) == null ? void 0 : _queue$.label;
  15915. if (label === "async-blocker" || label === "async-blocker-prepend") {
  15916. queue[0].execute();
  15917. queue.splice(0, 1);
  15918. }
  15919. });
  15920. }
  15921. unblockAudio(op) {
  15922. if (this.queues === null) {
  15923. return;
  15924. }
  15925. const queue = this.queues.audio;
  15926. if (queue[0] === op) {
  15927. this.shiftAndExecuteNext("audio");
  15928. }
  15929. }
  15930. executeNext(type) {
  15931. if (this.queues === null || this.tracks === null) {
  15932. return;
  15933. }
  15934. const queue = this.queues[type];
  15935. if (queue.length) {
  15936. const operation = queue[0];
  15937. try {
  15938. operation.execute();
  15939. } catch (error) {
  15940. var _this$tracks$type;
  15941. operation.onError(error);
  15942. if (this.queues === null || this.tracks === null) {
  15943. return;
  15944. }
  15945. const sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  15946. if (!(sb != null && sb.updating)) {
  15947. this.shiftAndExecuteNext(type);
  15948. }
  15949. }
  15950. }
  15951. }
  15952. shiftAndExecuteNext(type) {
  15953. if (this.queues === null) {
  15954. return;
  15955. }
  15956. this.queues[type].shift();
  15957. this.executeNext(type);
  15958. }
  15959. current(type) {
  15960. var _this$queues;
  15961. return ((_this$queues = this.queues) == null ? void 0 : _this$queues[type][0]) || null;
  15962. }
  15963. toString() {
  15964. const {
  15965. queues,
  15966. tracks
  15967. } = this;
  15968. if (queues === null || tracks === null) {
  15969. return `<destroyed>`;
  15970. }
  15971. return `
  15972. ${this.list("video")}
  15973. ${this.list("audio")}
  15974. ${this.list("audiovideo")}}`;
  15975. }
  15976. list(type) {
  15977. var _this$queues2, _this$tracks;
  15978. return (_this$queues2 = this.queues) != null && _this$queues2[type] || (_this$tracks = this.tracks) != null && _this$tracks[type] ? `${type}: (${this.listSbInfo(type)}) ${this.listOps(type)}` : "";
  15979. }
  15980. listSbInfo(type) {
  15981. var _this$tracks2;
  15982. const track = (_this$tracks2 = this.tracks) == null ? void 0 : _this$tracks2[type];
  15983. const sb = track == null ? void 0 : track.buffer;
  15984. if (!sb) {
  15985. return "none";
  15986. }
  15987. return `SourceBuffer${sb.updating ? " updating" : ""}${track.ended ? " ended" : ""}${track.ending ? " ending" : ""}`;
  15988. }
  15989. listOps(type) {
  15990. var _this$queues3;
  15991. return ((_this$queues3 = this.queues) == null ? void 0 : _this$queues3[type].map((op) => op.label).join(", ")) || "";
  15992. }
  15993. };
  15994. var VIDEO_CODEC_PROFILE_REPLACE = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;
  15995. var TRACK_REMOVED_ERROR_NAME = "HlsJsTrackRemovedError";
  15996. var HlsJsTrackRemovedError = class extends Error {
  15997. constructor(message) {
  15998. super(message);
  15999. this.name = TRACK_REMOVED_ERROR_NAME;
  16000. }
  16001. };
  16002. var BufferController = class extends Logger {
  16003. constructor(hls, fragmentTracker) {
  16004. super("buffer-controller", hls.logger);
  16005. this.hls = void 0;
  16006. this.fragmentTracker = void 0;
  16007. this.details = null;
  16008. this._objectUrl = null;
  16009. this.operationQueue = null;
  16010. this.bufferCodecEventsTotal = 0;
  16011. this.media = null;
  16012. this.mediaSource = null;
  16013. this.lastMpegAudioChunk = null;
  16014. this.blockedAudioAppend = null;
  16015. this.lastVideoAppendEnd = 0;
  16016. this.appendSource = void 0;
  16017. this.transferData = void 0;
  16018. this.overrides = void 0;
  16019. this.appendErrors = {
  16020. audio: 0,
  16021. video: 0,
  16022. audiovideo: 0
  16023. };
  16024. this.tracks = {};
  16025. this.sourceBuffers = [[null, null], [null, null]];
  16026. this._onEndStreaming = (event) => {
  16027. var _this$mediaSource;
  16028. if (!this.hls) {
  16029. return;
  16030. }
  16031. if (((_this$mediaSource = this.mediaSource) == null ? void 0 : _this$mediaSource.readyState) !== "open") {
  16032. return;
  16033. }
  16034. this.hls.pauseBuffering();
  16035. };
  16036. this._onStartStreaming = (event) => {
  16037. if (!this.hls) {
  16038. return;
  16039. }
  16040. this.hls.resumeBuffering();
  16041. };
  16042. this._onMediaSourceOpen = (e) => {
  16043. const {
  16044. media,
  16045. mediaSource
  16046. } = this;
  16047. if (e) {
  16048. this.log("Media source opened");
  16049. }
  16050. if (!media || !mediaSource) {
  16051. return;
  16052. }
  16053. mediaSource.removeEventListener("sourceopen", this._onMediaSourceOpen);
  16054. media.removeEventListener("emptied", this._onMediaEmptied);
  16055. this.updateDuration();
  16056. this.hls.trigger(Events.MEDIA_ATTACHED, {
  16057. media,
  16058. mediaSource
  16059. });
  16060. if (this.mediaSource !== null) {
  16061. this.checkPendingTracks();
  16062. }
  16063. };
  16064. this._onMediaSourceClose = () => {
  16065. this.log("Media source closed");
  16066. };
  16067. this._onMediaSourceEnded = () => {
  16068. this.log("Media source ended");
  16069. };
  16070. this._onMediaEmptied = () => {
  16071. const {
  16072. mediaSrc,
  16073. _objectUrl
  16074. } = this;
  16075. if (mediaSrc !== _objectUrl) {
  16076. this.error(`Media element src was set while attaching MediaSource (${_objectUrl} > ${mediaSrc})`);
  16077. }
  16078. };
  16079. this.hls = hls;
  16080. this.fragmentTracker = fragmentTracker;
  16081. this.appendSource = isManagedMediaSource(getMediaSource(hls.config.preferManagedMediaSource));
  16082. this.initTracks();
  16083. this.registerListeners();
  16084. }
  16085. hasSourceTypes() {
  16086. return Object.keys(this.tracks).length > 0;
  16087. }
  16088. destroy() {
  16089. this.unregisterListeners();
  16090. this.details = null;
  16091. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  16092. this.transferData = this.overrides = void 0;
  16093. if (this.operationQueue) {
  16094. this.operationQueue.destroy();
  16095. this.operationQueue = null;
  16096. }
  16097. this.hls = this.fragmentTracker = null;
  16098. this._onMediaSourceOpen = this._onMediaSourceClose = null;
  16099. this._onMediaSourceEnded = null;
  16100. this._onStartStreaming = this._onEndStreaming = null;
  16101. }
  16102. registerListeners() {
  16103. const {
  16104. hls
  16105. } = this;
  16106. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  16107. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  16108. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16109. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  16110. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  16111. hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  16112. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  16113. hls.on(Events.BUFFER_EOS, this.onBufferEos, this);
  16114. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  16115. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  16116. hls.on(Events.FRAG_PARSED, this.onFragParsed, this);
  16117. hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);
  16118. hls.on(Events.ERROR, this.onError, this);
  16119. }
  16120. unregisterListeners() {
  16121. const {
  16122. hls
  16123. } = this;
  16124. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  16125. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  16126. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16127. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  16128. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  16129. hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  16130. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  16131. hls.off(Events.BUFFER_EOS, this.onBufferEos, this);
  16132. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  16133. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  16134. hls.off(Events.FRAG_PARSED, this.onFragParsed, this);
  16135. hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);
  16136. hls.off(Events.ERROR, this.onError, this);
  16137. }
  16138. transferMedia() {
  16139. const {
  16140. media,
  16141. mediaSource
  16142. } = this;
  16143. if (!media) {
  16144. return null;
  16145. }
  16146. const tracks = {};
  16147. if (this.operationQueue) {
  16148. const updating = this.isUpdating();
  16149. if (!updating) {
  16150. this.operationQueue.removeBlockers();
  16151. }
  16152. const queued = this.isQueued();
  16153. if (updating || queued) {
  16154. this.warn(`Transfering MediaSource with${queued ? " operations in queue" : ""}${updating ? " updating SourceBuffer(s)" : ""} ${this.operationQueue}`);
  16155. }
  16156. this.operationQueue.destroy();
  16157. }
  16158. const transferData = this.transferData;
  16159. if (!this.sourceBufferCount && transferData && transferData.mediaSource === mediaSource) {
  16160. _extends(tracks, transferData.tracks);
  16161. } else {
  16162. this.sourceBuffers.forEach((tuple) => {
  16163. const [type] = tuple;
  16164. if (type) {
  16165. tracks[type] = _extends({}, this.tracks[type]);
  16166. this.removeBuffer(type);
  16167. }
  16168. tuple[0] = tuple[1] = null;
  16169. });
  16170. }
  16171. return {
  16172. media,
  16173. mediaSource,
  16174. tracks
  16175. };
  16176. }
  16177. initTracks() {
  16178. const tracks = {};
  16179. this.sourceBuffers = [[null, null], [null, null]];
  16180. this.tracks = tracks;
  16181. this.resetQueue();
  16182. this.resetAppendErrors();
  16183. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  16184. this.lastVideoAppendEnd = 0;
  16185. }
  16186. onManifestLoading() {
  16187. this.bufferCodecEventsTotal = 0;
  16188. this.details = null;
  16189. }
  16190. onManifestParsed(event, data) {
  16191. var _this$transferData;
  16192. let codecEvents = 2;
  16193. if (data.audio && !data.video || !data.altAudio) {
  16194. codecEvents = 1;
  16195. }
  16196. this.bufferCodecEventsTotal = codecEvents;
  16197. this.log(`${codecEvents} bufferCodec event(s) expected.`);
  16198. if ((_this$transferData = this.transferData) != null && _this$transferData.mediaSource && this.sourceBufferCount && codecEvents) {
  16199. this.bufferCreated();
  16200. }
  16201. }
  16202. onMediaAttaching(event, data) {
  16203. const media = this.media = data.media;
  16204. const MediaSource = getMediaSource(this.appendSource);
  16205. this.transferData = this.overrides = void 0;
  16206. if (media && MediaSource) {
  16207. const transferringMedia = !!data.mediaSource;
  16208. if (transferringMedia || data.overrides) {
  16209. this.transferData = data;
  16210. this.overrides = data.overrides;
  16211. }
  16212. const ms = this.mediaSource = data.mediaSource || new MediaSource();
  16213. this.assignMediaSource(ms);
  16214. if (transferringMedia) {
  16215. this._objectUrl = media.src;
  16216. this.attachTransferred();
  16217. } else {
  16218. const objectUrl = this._objectUrl = self.URL.createObjectURL(ms);
  16219. if (this.appendSource) {
  16220. try {
  16221. media.removeAttribute("src");
  16222. const MMS = self.ManagedMediaSource;
  16223. media.disableRemotePlayback = media.disableRemotePlayback || MMS && ms instanceof MMS;
  16224. removeSourceChildren(media);
  16225. addSource(media, objectUrl);
  16226. media.load();
  16227. } catch (error) {
  16228. media.src = objectUrl;
  16229. }
  16230. } else {
  16231. media.src = objectUrl;
  16232. }
  16233. }
  16234. media.addEventListener("emptied", this._onMediaEmptied);
  16235. }
  16236. }
  16237. assignMediaSource(ms) {
  16238. var _this$transferData2, _ms$constructor;
  16239. 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}`);
  16240. ms.addEventListener("sourceopen", this._onMediaSourceOpen);
  16241. ms.addEventListener("sourceended", this._onMediaSourceEnded);
  16242. ms.addEventListener("sourceclose", this._onMediaSourceClose);
  16243. if (this.appendSource) {
  16244. ms.addEventListener("startstreaming", this._onStartStreaming);
  16245. ms.addEventListener("endstreaming", this._onEndStreaming);
  16246. }
  16247. }
  16248. attachTransferred() {
  16249. const media = this.media;
  16250. const data = this.transferData;
  16251. if (!data || !media) {
  16252. return;
  16253. }
  16254. const requiredTracks = this.tracks;
  16255. const transferredTracks = data.tracks;
  16256. const trackNames = transferredTracks ? Object.keys(transferredTracks) : null;
  16257. const trackCount = trackNames ? trackNames.length : 0;
  16258. const mediaSourceOpenCallback = () => {
  16259. if (this.media && this.mediaSourceOpenOrEnded) {
  16260. this._onMediaSourceOpen();
  16261. }
  16262. };
  16263. if (transferredTracks && trackNames && trackCount) {
  16264. if (!this.tracksReady) {
  16265. this.hls.config.startFragPrefetch = true;
  16266. this.log(`attachTransferred: waiting for SourceBuffer track info`);
  16267. return;
  16268. }
  16269. this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
  16270. required tracks: ${stringify(requiredTracks, (key, value) => key === "initSegment" ? void 0 : value)};
  16271. transfer tracks: ${stringify(transferredTracks, (key, value) => key === "initSegment" ? void 0 : value)}}`);
  16272. if (!isCompatibleTrackChange(transferredTracks, requiredTracks)) {
  16273. data.mediaSource = null;
  16274. data.tracks = void 0;
  16275. const currentTime = media.currentTime;
  16276. const details = this.details;
  16277. const startTime = Math.max(currentTime, (details == null ? void 0 : details.fragments[0].start) || 0);
  16278. if (startTime - currentTime > 1) {
  16279. this.log(`attachTransferred: waiting for playback to reach new tracks start time ${currentTime} -> ${startTime}`);
  16280. return;
  16281. }
  16282. this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(transferredTracks)}"->"${Object.keys(requiredTracks)}") start time: ${startTime} currentTime: ${currentTime}`);
  16283. this.onMediaDetaching(Events.MEDIA_DETACHING, {});
  16284. this.onMediaAttaching(Events.MEDIA_ATTACHING, data);
  16285. media.currentTime = startTime;
  16286. return;
  16287. }
  16288. this.transferData = void 0;
  16289. trackNames.forEach((trackName) => {
  16290. const type = trackName;
  16291. const track = transferredTracks[type];
  16292. if (track) {
  16293. const sb = track.buffer;
  16294. if (sb) {
  16295. const fragmentTracker = this.fragmentTracker;
  16296. const playlistType = track.id;
  16297. if (fragmentTracker.hasFragments(playlistType) || fragmentTracker.hasParts(playlistType)) {
  16298. const bufferedTimeRanges = BufferHelper.getBuffered(sb);
  16299. fragmentTracker.detectEvictedFragments(type, bufferedTimeRanges, playlistType, null, true);
  16300. }
  16301. const sbIndex = sourceBufferNameToIndex(type);
  16302. const sbTuple = [type, sb];
  16303. this.sourceBuffers[sbIndex] = sbTuple;
  16304. if (sb.updating && this.operationQueue) {
  16305. this.operationQueue.prependBlocker(type);
  16306. }
  16307. this.trackSourceBuffer(type, track);
  16308. }
  16309. }
  16310. });
  16311. mediaSourceOpenCallback();
  16312. this.bufferCreated();
  16313. } else {
  16314. this.log(`attachTransferred: MediaSource w/o SourceBuffers`);
  16315. mediaSourceOpenCallback();
  16316. }
  16317. }
  16318. get mediaSourceOpenOrEnded() {
  16319. var _this$mediaSource2;
  16320. const readyState = (_this$mediaSource2 = this.mediaSource) == null ? void 0 : _this$mediaSource2.readyState;
  16321. return readyState === "open" || readyState === "ended";
  16322. }
  16323. onMediaDetaching(event, data) {
  16324. const transferringMedia = !!data.transferMedia;
  16325. this.transferData = this.overrides = void 0;
  16326. const {
  16327. media,
  16328. mediaSource,
  16329. _objectUrl
  16330. } = this;
  16331. if (mediaSource) {
  16332. this.log(`media source ${transferringMedia ? "transferring" : "detaching"}`);
  16333. if (transferringMedia) {
  16334. this.sourceBuffers.forEach(([type]) => {
  16335. if (type) {
  16336. this.removeBuffer(type);
  16337. }
  16338. });
  16339. this.resetQueue();
  16340. } else {
  16341. if (this.mediaSourceOpenOrEnded) {
  16342. const open = mediaSource.readyState === "open";
  16343. try {
  16344. const sourceBuffers = mediaSource.sourceBuffers;
  16345. for (let i = sourceBuffers.length; i--; ) {
  16346. if (open) {
  16347. sourceBuffers[i].abort();
  16348. }
  16349. mediaSource.removeSourceBuffer(sourceBuffers[i]);
  16350. }
  16351. if (open) {
  16352. mediaSource.endOfStream();
  16353. }
  16354. } catch (err) {
  16355. this.warn(`onMediaDetaching: ${err.message} while calling endOfStream`);
  16356. }
  16357. }
  16358. if (this.sourceBufferCount) {
  16359. this.onBufferReset();
  16360. }
  16361. }
  16362. mediaSource.removeEventListener("sourceopen", this._onMediaSourceOpen);
  16363. mediaSource.removeEventListener("sourceended", this._onMediaSourceEnded);
  16364. mediaSource.removeEventListener("sourceclose", this._onMediaSourceClose);
  16365. if (this.appendSource) {
  16366. mediaSource.removeEventListener("startstreaming", this._onStartStreaming);
  16367. mediaSource.removeEventListener("endstreaming", this._onEndStreaming);
  16368. }
  16369. this.mediaSource = null;
  16370. this._objectUrl = null;
  16371. }
  16372. if (media) {
  16373. media.removeEventListener("emptied", this._onMediaEmptied);
  16374. if (!transferringMedia) {
  16375. if (_objectUrl) {
  16376. self.URL.revokeObjectURL(_objectUrl);
  16377. }
  16378. if (this.mediaSrc === _objectUrl) {
  16379. media.removeAttribute("src");
  16380. if (this.appendSource) {
  16381. removeSourceChildren(media);
  16382. }
  16383. media.load();
  16384. } else {
  16385. this.warn("media|source.src was changed by a third party - skip cleanup");
  16386. }
  16387. }
  16388. this.media = null;
  16389. }
  16390. this.hls.trigger(Events.MEDIA_DETACHED, data);
  16391. }
  16392. onBufferReset() {
  16393. this.sourceBuffers.forEach(([type]) => {
  16394. if (type) {
  16395. this.resetBuffer(type);
  16396. }
  16397. });
  16398. this.initTracks();
  16399. }
  16400. resetBuffer(type) {
  16401. var _this$tracks$type;
  16402. const sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  16403. this.removeBuffer(type);
  16404. if (sb) {
  16405. try {
  16406. var _this$mediaSource3;
  16407. if ((_this$mediaSource3 = this.mediaSource) != null && _this$mediaSource3.sourceBuffers.length) {
  16408. this.mediaSource.removeSourceBuffer(sb);
  16409. }
  16410. } catch (err) {
  16411. this.warn(`onBufferReset ${type}`, err);
  16412. }
  16413. }
  16414. delete this.tracks[type];
  16415. }
  16416. removeBuffer(type) {
  16417. this.removeBufferListeners(type);
  16418. this.sourceBuffers[sourceBufferNameToIndex(type)] = [null, null];
  16419. const track = this.tracks[type];
  16420. if (track) {
  16421. track.buffer = void 0;
  16422. }
  16423. }
  16424. resetQueue() {
  16425. if (this.operationQueue) {
  16426. this.operationQueue.destroy();
  16427. }
  16428. this.operationQueue = new BufferOperationQueue(this.tracks);
  16429. }
  16430. onBufferCodecs(event, data) {
  16431. const tracks = this.tracks;
  16432. const trackNames = Object.keys(data);
  16433. this.log(`BUFFER_CODECS: "${trackNames}" (current SB count ${this.sourceBufferCount})`);
  16434. const unmuxedToMuxed = "audiovideo" in data && (tracks.audio || tracks.video) || tracks.audiovideo && ("audio" in data || "video" in data);
  16435. const muxedToUnmuxed = !unmuxedToMuxed && this.sourceBufferCount && this.media && trackNames.some((sbName) => !tracks[sbName]);
  16436. if (unmuxedToMuxed || muxedToUnmuxed) {
  16437. this.warn(`Unsupported transition between "${Object.keys(tracks)}" and "${trackNames}" SourceBuffers`);
  16438. return;
  16439. }
  16440. trackNames.forEach((trackName) => {
  16441. var _this$transferData3, _this$transferData3$t, _trackCodec;
  16442. const parsedTrack = data[trackName];
  16443. const {
  16444. id,
  16445. codec,
  16446. levelCodec,
  16447. container,
  16448. metadata,
  16449. supplemental
  16450. } = parsedTrack;
  16451. let track = tracks[trackName];
  16452. const transferredTrack = (_this$transferData3 = this.transferData) == null ? void 0 : (_this$transferData3$t = _this$transferData3.tracks) == null ? void 0 : _this$transferData3$t[trackName];
  16453. const sbTrack = transferredTrack != null && transferredTrack.buffer ? transferredTrack : track;
  16454. const sbCodec = (sbTrack == null ? void 0 : sbTrack.pendingCodec) || (sbTrack == null ? void 0 : sbTrack.codec);
  16455. const trackLevelCodec = sbTrack == null ? void 0 : sbTrack.levelCodec;
  16456. if (!track) {
  16457. track = tracks[trackName] = {
  16458. buffer: void 0,
  16459. listeners: [],
  16460. codec,
  16461. supplemental,
  16462. container,
  16463. levelCodec,
  16464. metadata,
  16465. id
  16466. };
  16467. }
  16468. const currentCodecFull = pickMostCompleteCodecName(sbCodec, trackLevelCodec);
  16469. const currentCodec = currentCodecFull == null ? void 0 : currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE, "$1");
  16470. let trackCodec = pickMostCompleteCodecName(codec, levelCodec);
  16471. const nextCodec = (_trackCodec = trackCodec) == null ? void 0 : _trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE, "$1");
  16472. if (trackCodec && currentCodecFull && currentCodec !== nextCodec) {
  16473. if (trackName.slice(0, 5) === "audio") {
  16474. trackCodec = getCodecCompatibleName(trackCodec, this.appendSource);
  16475. }
  16476. this.log(`switching codec ${sbCodec} to ${trackCodec}`);
  16477. if (trackCodec !== (track.pendingCodec || track.codec)) {
  16478. track.pendingCodec = trackCodec;
  16479. }
  16480. track.container = container;
  16481. this.appendChangeType(trackName, container, trackCodec);
  16482. }
  16483. });
  16484. if (this.tracksReady || this.sourceBufferCount) {
  16485. data.tracks = this.sourceBufferTracks;
  16486. }
  16487. if (this.sourceBufferCount) {
  16488. return;
  16489. }
  16490. if (this.mediaSourceOpenOrEnded) {
  16491. this.checkPendingTracks();
  16492. }
  16493. }
  16494. get sourceBufferTracks() {
  16495. return Object.keys(this.tracks).reduce((baseTracks, type) => {
  16496. const track = this.tracks[type];
  16497. baseTracks[type] = {
  16498. id: track.id,
  16499. container: track.container,
  16500. codec: track.codec,
  16501. levelCodec: track.levelCodec
  16502. };
  16503. return baseTracks;
  16504. }, {});
  16505. }
  16506. appendChangeType(type, container, codec) {
  16507. const mimeType = `${container};codecs=${codec}`;
  16508. const operation = {
  16509. label: `change-type=${mimeType}`,
  16510. execute: () => {
  16511. const track = this.tracks[type];
  16512. if (track) {
  16513. const sb = track.buffer;
  16514. if (sb != null && sb.changeType) {
  16515. this.log(`changing ${type} sourceBuffer type to ${mimeType}`);
  16516. sb.changeType(mimeType);
  16517. track.codec = codec;
  16518. track.container = container;
  16519. }
  16520. }
  16521. this.shiftAndExecuteNext(type);
  16522. },
  16523. onStart: () => {
  16524. },
  16525. onComplete: () => {
  16526. },
  16527. onError: (error) => {
  16528. this.warn(`Failed to change ${type} SourceBuffer type`, error);
  16529. }
  16530. };
  16531. this.append(operation, type, this.isPending(this.tracks[type]));
  16532. }
  16533. blockAudio(partOrFrag) {
  16534. var _this$fragmentTracker;
  16535. const pStart = partOrFrag.start;
  16536. const pTime = pStart + partOrFrag.duration * 0.05;
  16537. const atGap = ((_this$fragmentTracker = this.fragmentTracker.getAppendedFrag(pStart, PlaylistLevelType.MAIN)) == null ? void 0 : _this$fragmentTracker.gap) === true;
  16538. if (atGap) {
  16539. return;
  16540. }
  16541. const op = {
  16542. label: "block-audio",
  16543. execute: () => {
  16544. var _this$fragmentTracker2;
  16545. const videoTrack = this.tracks.video;
  16546. 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) {
  16547. this.blockedAudioAppend = null;
  16548. this.shiftAndExecuteNext("audio");
  16549. }
  16550. },
  16551. onStart: () => {
  16552. },
  16553. onComplete: () => {
  16554. },
  16555. onError: (error) => {
  16556. this.warn("Error executing block-audio operation", error);
  16557. }
  16558. };
  16559. this.blockedAudioAppend = {
  16560. op,
  16561. frag: partOrFrag
  16562. };
  16563. this.append(op, "audio", true);
  16564. }
  16565. unblockAudio() {
  16566. const {
  16567. blockedAudioAppend,
  16568. operationQueue
  16569. } = this;
  16570. if (blockedAudioAppend && operationQueue) {
  16571. this.blockedAudioAppend = null;
  16572. operationQueue.unblockAudio(blockedAudioAppend.op);
  16573. }
  16574. }
  16575. onBufferAppending(event, eventData) {
  16576. const {
  16577. tracks
  16578. } = this;
  16579. const {
  16580. data,
  16581. type,
  16582. parent,
  16583. frag,
  16584. part,
  16585. chunkMeta,
  16586. offset
  16587. } = eventData;
  16588. const chunkStats = chunkMeta.buffering[type];
  16589. const {
  16590. sn,
  16591. cc
  16592. } = frag;
  16593. const bufferAppendingStart = self.performance.now();
  16594. chunkStats.start = bufferAppendingStart;
  16595. const fragBuffering = frag.stats.buffering;
  16596. const partBuffering = part ? part.stats.buffering : null;
  16597. if (fragBuffering.start === 0) {
  16598. fragBuffering.start = bufferAppendingStart;
  16599. }
  16600. if (partBuffering && partBuffering.start === 0) {
  16601. partBuffering.start = bufferAppendingStart;
  16602. }
  16603. const audioTrack = tracks.audio;
  16604. let checkTimestampOffset = false;
  16605. if (type === "audio" && (audioTrack == null ? void 0 : audioTrack.container) === "audio/mpeg") {
  16606. checkTimestampOffset = !this.lastMpegAudioChunk || chunkMeta.id === 1 || this.lastMpegAudioChunk.sn !== chunkMeta.sn;
  16607. this.lastMpegAudioChunk = chunkMeta;
  16608. }
  16609. const videoTrack = tracks.video;
  16610. const videoSb = videoTrack == null ? void 0 : videoTrack.buffer;
  16611. if (videoSb && sn !== "initSegment") {
  16612. const partOrFrag = part || frag;
  16613. const blockedAudioAppend = this.blockedAudioAppend;
  16614. if (type === "audio" && parent !== "main" && !this.blockedAudioAppend) {
  16615. const pStart = partOrFrag.start;
  16616. const pTime = pStart + partOrFrag.duration * 0.05;
  16617. const vbuffered = videoSb.buffered;
  16618. const vappending = this.currentOp("video");
  16619. if (!vbuffered.length && !vappending) {
  16620. this.blockAudio(partOrFrag);
  16621. } else if (!vappending && !BufferHelper.isBuffered(videoSb, pTime) && this.lastVideoAppendEnd < pTime) {
  16622. this.blockAudio(partOrFrag);
  16623. }
  16624. } else if (type === "video") {
  16625. const videoAppendEnd = partOrFrag.end;
  16626. if (blockedAudioAppend) {
  16627. const audioStart = blockedAudioAppend.frag.start;
  16628. if (videoAppendEnd > audioStart || videoAppendEnd < this.lastVideoAppendEnd || BufferHelper.isBuffered(videoSb, audioStart)) {
  16629. this.unblockAudio();
  16630. }
  16631. }
  16632. this.lastVideoAppendEnd = videoAppendEnd;
  16633. }
  16634. }
  16635. const fragStart = (part || frag).start;
  16636. const operation = {
  16637. label: `append-${type}`,
  16638. execute: () => {
  16639. var _this$tracks$type2;
  16640. chunkStats.executeStart = self.performance.now();
  16641. const sb = (_this$tracks$type2 = this.tracks[type]) == null ? void 0 : _this$tracks$type2.buffer;
  16642. if (sb) {
  16643. if (checkTimestampOffset) {
  16644. this.updateTimestampOffset(sb, fragStart, 0.1, type, sn, cc);
  16645. } else if (offset !== void 0 && isFiniteNumber(offset)) {
  16646. this.updateTimestampOffset(sb, offset, 1e-6, type, sn, cc);
  16647. }
  16648. }
  16649. this.appendExecutor(data, type);
  16650. },
  16651. onStart: () => {
  16652. },
  16653. onComplete: () => {
  16654. const end = self.performance.now();
  16655. chunkStats.executeEnd = chunkStats.end = end;
  16656. if (fragBuffering.first === 0) {
  16657. fragBuffering.first = end;
  16658. }
  16659. if (partBuffering && partBuffering.first === 0) {
  16660. partBuffering.first = end;
  16661. }
  16662. const timeRanges = {};
  16663. this.sourceBuffers.forEach(([type2, sb]) => {
  16664. if (type2) {
  16665. timeRanges[type2] = BufferHelper.getBuffered(sb);
  16666. }
  16667. });
  16668. this.appendErrors[type] = 0;
  16669. if (type === "audio" || type === "video") {
  16670. this.appendErrors.audiovideo = 0;
  16671. } else {
  16672. this.appendErrors.audio = 0;
  16673. this.appendErrors.video = 0;
  16674. }
  16675. this.hls.trigger(Events.BUFFER_APPENDED, {
  16676. type,
  16677. frag,
  16678. part,
  16679. chunkMeta,
  16680. parent: frag.type,
  16681. timeRanges
  16682. });
  16683. },
  16684. onError: (error) => {
  16685. var _this$media;
  16686. const event2 = {
  16687. type: ErrorTypes.MEDIA_ERROR,
  16688. parent: frag.type,
  16689. details: ErrorDetails.BUFFER_APPEND_ERROR,
  16690. sourceBufferName: type,
  16691. frag,
  16692. part,
  16693. chunkMeta,
  16694. error,
  16695. err: error,
  16696. fatal: false
  16697. };
  16698. const mediaError = (_this$media = this.media) == null ? void 0 : _this$media.error;
  16699. if (error.code === DOMException.QUOTA_EXCEEDED_ERR || error.name == "QuotaExceededError" || `quota` in error) {
  16700. event2.details = ErrorDetails.BUFFER_FULL_ERROR;
  16701. } else if (error.code === DOMException.INVALID_STATE_ERR && this.mediaSourceOpenOrEnded && !mediaError) {
  16702. event2.errorAction = createDoNothingErrorAction(true);
  16703. } else if (error.name === TRACK_REMOVED_ERROR_NAME && this.sourceBufferCount === 0) {
  16704. event2.errorAction = createDoNothingErrorAction(true);
  16705. } else {
  16706. const appendErrorCount = ++this.appendErrors[type];
  16707. this.warn(`Failed ${appendErrorCount}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${type}" sourceBuffer (${mediaError ? mediaError : "no media error"})`);
  16708. if (appendErrorCount >= this.hls.config.appendErrorMaxRetry || !!mediaError) {
  16709. event2.fatal = true;
  16710. }
  16711. }
  16712. this.hls.trigger(Events.ERROR, event2);
  16713. }
  16714. };
  16715. this.append(operation, type, this.isPending(this.tracks[type]));
  16716. }
  16717. getFlushOp(type, start, end) {
  16718. this.log(`queuing "${type}" remove ${start}-${end}`);
  16719. return {
  16720. label: "remove",
  16721. execute: () => {
  16722. this.removeExecutor(type, start, end);
  16723. },
  16724. onStart: () => {
  16725. },
  16726. onComplete: () => {
  16727. this.hls.trigger(Events.BUFFER_FLUSHED, {
  16728. type
  16729. });
  16730. },
  16731. onError: (error) => {
  16732. this.warn(`Failed to remove ${start}-${end} from "${type}" SourceBuffer`, error);
  16733. }
  16734. };
  16735. }
  16736. onBufferFlushing(event, data) {
  16737. const {
  16738. type,
  16739. startOffset,
  16740. endOffset
  16741. } = data;
  16742. if (type) {
  16743. this.append(this.getFlushOp(type, startOffset, endOffset), type);
  16744. } else {
  16745. this.sourceBuffers.forEach(([type2]) => {
  16746. if (type2) {
  16747. this.append(this.getFlushOp(type2, startOffset, endOffset), type2);
  16748. }
  16749. });
  16750. }
  16751. }
  16752. onFragParsed(event, data) {
  16753. const {
  16754. frag,
  16755. part
  16756. } = data;
  16757. const buffersAppendedTo = [];
  16758. const elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
  16759. if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {
  16760. buffersAppendedTo.push("audiovideo");
  16761. } else {
  16762. if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {
  16763. buffersAppendedTo.push("audio");
  16764. }
  16765. if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {
  16766. buffersAppendedTo.push("video");
  16767. }
  16768. }
  16769. const onUnblocked = () => {
  16770. const now2 = self.performance.now();
  16771. frag.stats.buffering.end = now2;
  16772. if (part) {
  16773. part.stats.buffering.end = now2;
  16774. }
  16775. const stats = part ? part.stats : frag.stats;
  16776. this.hls.trigger(Events.FRAG_BUFFERED, {
  16777. frag,
  16778. part,
  16779. stats,
  16780. id: frag.type
  16781. });
  16782. };
  16783. if (buffersAppendedTo.length === 0) {
  16784. this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${frag.type} level: ${frag.level} sn: ${frag.sn}`);
  16785. }
  16786. this.blockBuffers(onUnblocked, buffersAppendedTo).catch((error) => {
  16787. this.warn(`Fragment buffered callback ${error}`);
  16788. this.stepOperationQueue(this.sourceBufferTypes);
  16789. });
  16790. }
  16791. onFragChanged(event, data) {
  16792. this.trimBuffers();
  16793. }
  16794. get bufferedToEnd() {
  16795. return this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type]) => {
  16796. var _this$tracks$type3, _this$tracks$type4;
  16797. 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));
  16798. });
  16799. }
  16800. onBufferEos(event, data) {
  16801. var _this$overrides;
  16802. this.sourceBuffers.forEach(([type]) => {
  16803. if (type) {
  16804. const track = this.tracks[type];
  16805. if (!data.type || data.type === type) {
  16806. track.ending = true;
  16807. if (!track.ended) {
  16808. track.ended = true;
  16809. this.log(`${type} buffer reached EOS`);
  16810. }
  16811. }
  16812. }
  16813. });
  16814. const allowEndOfStream = ((_this$overrides = this.overrides) == null ? void 0 : _this$overrides.endOfStream) !== false;
  16815. const allTracksEnding = this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type]) => {
  16816. var _this$tracks$type5;
  16817. return type && !((_this$tracks$type5 = this.tracks[type]) != null && _this$tracks$type5.ended);
  16818. });
  16819. if (allTracksEnding) {
  16820. if (allowEndOfStream) {
  16821. this.log(`Queueing EOS`);
  16822. this.blockUntilOpen(() => {
  16823. this.tracksEnded();
  16824. const {
  16825. mediaSource
  16826. } = this;
  16827. if (!mediaSource || mediaSource.readyState !== "open") {
  16828. if (mediaSource) {
  16829. this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${mediaSource.readyState}`);
  16830. }
  16831. return;
  16832. }
  16833. this.log(`Calling mediaSource.endOfStream()`);
  16834. mediaSource.endOfStream();
  16835. this.hls.trigger(Events.BUFFERED_TO_END, void 0);
  16836. });
  16837. } else {
  16838. this.tracksEnded();
  16839. this.hls.trigger(Events.BUFFERED_TO_END, void 0);
  16840. }
  16841. }
  16842. }
  16843. tracksEnded() {
  16844. this.sourceBuffers.forEach(([type]) => {
  16845. if (type !== null) {
  16846. const track = this.tracks[type];
  16847. if (track) {
  16848. track.ending = false;
  16849. }
  16850. }
  16851. });
  16852. }
  16853. onLevelUpdated(event, {
  16854. details
  16855. }) {
  16856. if (!details.fragments.length) {
  16857. return;
  16858. }
  16859. this.details = details;
  16860. this.updateDuration();
  16861. }
  16862. updateDuration() {
  16863. this.blockUntilOpen(() => {
  16864. const durationAndRange = this.getDurationAndRange();
  16865. if (!durationAndRange) {
  16866. return;
  16867. }
  16868. this.updateMediaSource(durationAndRange);
  16869. });
  16870. }
  16871. onError(event, data) {
  16872. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && data.frag) {
  16873. var _data$errorAction;
  16874. const nextAutoLevel = (_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.nextAutoLevel;
  16875. if (isFiniteNumber(nextAutoLevel) && nextAutoLevel !== data.frag.level) {
  16876. this.resetAppendErrors();
  16877. }
  16878. }
  16879. }
  16880. resetAppendErrors() {
  16881. this.appendErrors = {
  16882. audio: 0,
  16883. video: 0,
  16884. audiovideo: 0
  16885. };
  16886. }
  16887. trimBuffers() {
  16888. const {
  16889. hls,
  16890. details,
  16891. media
  16892. } = this;
  16893. if (!media || details === null) {
  16894. return;
  16895. }
  16896. if (!this.sourceBufferCount) {
  16897. return;
  16898. }
  16899. const config = hls.config;
  16900. const currentTime = media.currentTime;
  16901. const targetDuration = details.levelTargetDuration;
  16902. const backBufferLength = details.live && config.liveBackBufferLength !== null ? config.liveBackBufferLength : config.backBufferLength;
  16903. if (isFiniteNumber(backBufferLength) && backBufferLength >= 0) {
  16904. const maxBackBufferLength = Math.max(backBufferLength, targetDuration);
  16905. const targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
  16906. this.flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition);
  16907. }
  16908. if (isFiniteNumber(config.frontBufferFlushThreshold) && config.frontBufferFlushThreshold > 0) {
  16909. const frontBufferLength = Math.max(config.maxBufferLength, config.frontBufferFlushThreshold);
  16910. const maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);
  16911. const targetFrontBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration + maxFrontBufferLength;
  16912. this.flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition);
  16913. }
  16914. }
  16915. flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition) {
  16916. this.sourceBuffers.forEach(([type, sb]) => {
  16917. if (sb) {
  16918. const buffered = BufferHelper.getBuffered(sb);
  16919. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  16920. var _this$details;
  16921. this.hls.trigger(Events.BACK_BUFFER_REACHED, {
  16922. bufferEnd: targetBackBufferPosition
  16923. });
  16924. const track = this.tracks[type];
  16925. if ((_this$details = this.details) != null && _this$details.live) {
  16926. this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {
  16927. bufferEnd: targetBackBufferPosition
  16928. });
  16929. } else if (track != null && track.ended) {
  16930. this.log(`Cannot flush ${type} back buffer while SourceBuffer is in ended state`);
  16931. return;
  16932. }
  16933. this.hls.trigger(Events.BUFFER_FLUSHING, {
  16934. startOffset: 0,
  16935. endOffset: targetBackBufferPosition,
  16936. type
  16937. });
  16938. }
  16939. }
  16940. });
  16941. }
  16942. flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition) {
  16943. this.sourceBuffers.forEach(([type, sb]) => {
  16944. if (sb) {
  16945. const buffered = BufferHelper.getBuffered(sb);
  16946. const numBufferedRanges = buffered.length;
  16947. if (numBufferedRanges < 2) {
  16948. return;
  16949. }
  16950. const bufferStart = buffered.start(numBufferedRanges - 1);
  16951. const bufferEnd = buffered.end(numBufferedRanges - 1);
  16952. if (targetFrontBufferPosition > bufferStart || currentTime >= bufferStart && currentTime <= bufferEnd) {
  16953. return;
  16954. }
  16955. this.hls.trigger(Events.BUFFER_FLUSHING, {
  16956. startOffset: bufferStart,
  16957. endOffset: Infinity,
  16958. type
  16959. });
  16960. }
  16961. });
  16962. }
  16963. getDurationAndRange() {
  16964. var _this$overrides2;
  16965. const {
  16966. details,
  16967. mediaSource
  16968. } = this;
  16969. if (!details || !this.media || (mediaSource == null ? void 0 : mediaSource.readyState) !== "open") {
  16970. return null;
  16971. }
  16972. const playlistEnd = details.edge;
  16973. if (details.live && this.hls.config.liveDurationInfinity) {
  16974. const len = details.fragments.length;
  16975. if (len && details.live && !!mediaSource.setLiveSeekableRange) {
  16976. const start = Math.max(0, details.fragmentStart);
  16977. const end = Math.max(start, playlistEnd);
  16978. return {
  16979. duration: Infinity,
  16980. start,
  16981. end
  16982. };
  16983. }
  16984. return {
  16985. duration: Infinity
  16986. };
  16987. }
  16988. const overrideDuration = (_this$overrides2 = this.overrides) == null ? void 0 : _this$overrides2.duration;
  16989. if (overrideDuration) {
  16990. if (!isFiniteNumber(overrideDuration)) {
  16991. return null;
  16992. }
  16993. return {
  16994. duration: overrideDuration
  16995. };
  16996. }
  16997. const mediaDuration = this.media.duration;
  16998. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : 0;
  16999. if (playlistEnd > msDuration && playlistEnd > mediaDuration || !isFiniteNumber(mediaDuration)) {
  17000. return {
  17001. duration: playlistEnd
  17002. };
  17003. }
  17004. return null;
  17005. }
  17006. updateMediaSource({
  17007. duration,
  17008. start,
  17009. end
  17010. }) {
  17011. const mediaSource = this.mediaSource;
  17012. if (!this.media || !mediaSource || mediaSource.readyState !== "open") {
  17013. return;
  17014. }
  17015. if (mediaSource.duration !== duration) {
  17016. if (isFiniteNumber(duration)) {
  17017. this.log(`Updating MediaSource duration to ${duration.toFixed(3)}`);
  17018. }
  17019. mediaSource.duration = duration;
  17020. }
  17021. if (start !== void 0 && end !== void 0) {
  17022. this.log(`MediaSource duration is set to ${mediaSource.duration}. Setting seekable range to ${start}-${end}.`);
  17023. mediaSource.setLiveSeekableRange(start, end);
  17024. }
  17025. }
  17026. get tracksReady() {
  17027. const pendingTrackCount = this.pendingTrackCount;
  17028. return pendingTrackCount > 0 && (pendingTrackCount >= this.bufferCodecEventsTotal || this.isPending(this.tracks.audiovideo));
  17029. }
  17030. checkPendingTracks() {
  17031. const {
  17032. bufferCodecEventsTotal,
  17033. pendingTrackCount,
  17034. tracks
  17035. } = this;
  17036. this.log(`checkPendingTracks (pending: ${pendingTrackCount} codec events expected: ${bufferCodecEventsTotal}) ${stringify(tracks)}`);
  17037. if (this.tracksReady) {
  17038. var _this$transferData4;
  17039. const transferredTracks = (_this$transferData4 = this.transferData) == null ? void 0 : _this$transferData4.tracks;
  17040. if (transferredTracks && Object.keys(transferredTracks).length) {
  17041. this.attachTransferred();
  17042. } else {
  17043. this.createSourceBuffers();
  17044. }
  17045. }
  17046. }
  17047. bufferCreated() {
  17048. if (this.sourceBufferCount) {
  17049. const tracks = {};
  17050. this.sourceBuffers.forEach(([type, buffer]) => {
  17051. if (type) {
  17052. const track = this.tracks[type];
  17053. tracks[type] = {
  17054. buffer,
  17055. container: track.container,
  17056. codec: track.codec,
  17057. supplemental: track.supplemental,
  17058. levelCodec: track.levelCodec,
  17059. id: track.id,
  17060. metadata: track.metadata
  17061. };
  17062. }
  17063. });
  17064. this.hls.trigger(Events.BUFFER_CREATED, {
  17065. tracks
  17066. });
  17067. this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`);
  17068. this.sourceBuffers.forEach(([type]) => {
  17069. this.executeNext(type);
  17070. });
  17071. } else {
  17072. const error = new Error("could not create source buffer for media codec(s)");
  17073. this.hls.trigger(Events.ERROR, {
  17074. type: ErrorTypes.MEDIA_ERROR,
  17075. details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,
  17076. fatal: true,
  17077. error,
  17078. reason: error.message
  17079. });
  17080. }
  17081. }
  17082. createSourceBuffers() {
  17083. const {
  17084. tracks,
  17085. sourceBuffers,
  17086. mediaSource
  17087. } = this;
  17088. if (!mediaSource) {
  17089. throw new Error("createSourceBuffers called when mediaSource was null");
  17090. }
  17091. for (const trackName in tracks) {
  17092. const type = trackName;
  17093. const track = tracks[type];
  17094. if (this.isPending(track)) {
  17095. const codec = this.getTrackCodec(track, type);
  17096. const mimeType = `${track.container};codecs=${codec}`;
  17097. track.codec = codec;
  17098. this.log(`creating sourceBuffer(${mimeType})${this.currentOp(type) ? " Queued" : ""} ${stringify(track)}`);
  17099. try {
  17100. const sb = mediaSource.addSourceBuffer(mimeType);
  17101. const sbIndex = sourceBufferNameToIndex(type);
  17102. const sbTuple = [type, sb];
  17103. sourceBuffers[sbIndex] = sbTuple;
  17104. track.buffer = sb;
  17105. } catch (error) {
  17106. var _this$operationQueue;
  17107. this.error(`error while trying to add sourceBuffer: ${error.message}`);
  17108. this.shiftAndExecuteNext(type);
  17109. (_this$operationQueue = this.operationQueue) == null ? void 0 : _this$operationQueue.removeBlockers();
  17110. delete this.tracks[type];
  17111. this.hls.trigger(Events.ERROR, {
  17112. type: ErrorTypes.MEDIA_ERROR,
  17113. details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,
  17114. fatal: false,
  17115. error,
  17116. sourceBufferName: type,
  17117. mimeType,
  17118. parent: track.id
  17119. });
  17120. return;
  17121. }
  17122. this.trackSourceBuffer(type, track);
  17123. }
  17124. }
  17125. this.bufferCreated();
  17126. }
  17127. getTrackCodec(track, trackName) {
  17128. const supplementalCodec = track.supplemental;
  17129. let trackCodec = track.codec;
  17130. if (supplementalCodec && (trackName === "video" || trackName === "audiovideo") && areCodecsMediaSourceSupported(supplementalCodec, "video")) {
  17131. trackCodec = replaceVideoCodec(trackCodec, supplementalCodec);
  17132. }
  17133. const codec = pickMostCompleteCodecName(trackCodec, track.levelCodec);
  17134. if (codec) {
  17135. if (trackName.slice(0, 5) === "audio") {
  17136. return getCodecCompatibleName(codec, this.appendSource);
  17137. }
  17138. return codec;
  17139. }
  17140. return "";
  17141. }
  17142. trackSourceBuffer(type, track) {
  17143. const buffer = track.buffer;
  17144. if (!buffer) {
  17145. return;
  17146. }
  17147. const codec = this.getTrackCodec(track, type);
  17148. this.tracks[type] = {
  17149. buffer,
  17150. codec,
  17151. container: track.container,
  17152. levelCodec: track.levelCodec,
  17153. supplemental: track.supplemental,
  17154. metadata: track.metadata,
  17155. id: track.id,
  17156. listeners: []
  17157. };
  17158. this.removeBufferListeners(type);
  17159. this.addBufferListener(type, "updatestart", this.onSBUpdateStart);
  17160. this.addBufferListener(type, "updateend", this.onSBUpdateEnd);
  17161. this.addBufferListener(type, "error", this.onSBUpdateError);
  17162. if (this.appendSource) {
  17163. this.addBufferListener(type, "bufferedchange", (type2, event) => {
  17164. const removedRanges = event.removedRanges;
  17165. if (removedRanges != null && removedRanges.length) {
  17166. this.hls.trigger(Events.BUFFER_FLUSHED, {
  17167. type: type2
  17168. });
  17169. }
  17170. });
  17171. }
  17172. }
  17173. get mediaSrc() {
  17174. var _this$media2, _this$media2$querySel;
  17175. 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;
  17176. return media == null ? void 0 : media.src;
  17177. }
  17178. onSBUpdateStart(type) {
  17179. const operation = this.currentOp(type);
  17180. if (!operation) {
  17181. return;
  17182. }
  17183. operation.onStart();
  17184. }
  17185. onSBUpdateEnd(type) {
  17186. var _this$mediaSource4;
  17187. if (((_this$mediaSource4 = this.mediaSource) == null ? void 0 : _this$mediaSource4.readyState) === "closed") {
  17188. this.resetBuffer(type);
  17189. return;
  17190. }
  17191. const operation = this.currentOp(type);
  17192. if (!operation) {
  17193. return;
  17194. }
  17195. operation.onComplete();
  17196. this.shiftAndExecuteNext(type);
  17197. }
  17198. onSBUpdateError(type, event) {
  17199. var _this$mediaSource5;
  17200. const error = new Error(`${type} SourceBuffer error. MediaSource readyState: ${(_this$mediaSource5 = this.mediaSource) == null ? void 0 : _this$mediaSource5.readyState}`);
  17201. this.error(`${error}`, event);
  17202. this.hls.trigger(Events.ERROR, {
  17203. type: ErrorTypes.MEDIA_ERROR,
  17204. details: ErrorDetails.BUFFER_APPENDING_ERROR,
  17205. sourceBufferName: type,
  17206. error,
  17207. fatal: false
  17208. });
  17209. const operation = this.currentOp(type);
  17210. if (operation) {
  17211. operation.onError(error);
  17212. }
  17213. }
  17214. updateTimestampOffset(sb, timestampOffset, tolerance, type, sn, cc) {
  17215. const delta = timestampOffset - sb.timestampOffset;
  17216. if (Math.abs(delta) >= tolerance) {
  17217. this.log(`Updating ${type} SourceBuffer timestampOffset to ${timestampOffset} (sn: ${sn} cc: ${cc})`);
  17218. sb.timestampOffset = timestampOffset;
  17219. }
  17220. }
  17221. removeExecutor(type, startOffset, endOffset) {
  17222. const {
  17223. media,
  17224. mediaSource
  17225. } = this;
  17226. const track = this.tracks[type];
  17227. const sb = track == null ? void 0 : track.buffer;
  17228. if (!media || !mediaSource || !sb) {
  17229. this.warn(`Attempting to remove from the ${type} SourceBuffer, but it does not exist`);
  17230. this.shiftAndExecuteNext(type);
  17231. return;
  17232. }
  17233. const mediaDuration = isFiniteNumber(media.duration) ? media.duration : Infinity;
  17234. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : Infinity;
  17235. const removeStart = Math.max(0, startOffset);
  17236. const removeEnd = Math.min(endOffset, mediaDuration, msDuration);
  17237. if (removeEnd > removeStart && (!track.ending || track.ended)) {
  17238. track.ended = false;
  17239. this.log(`Removing [${removeStart},${removeEnd}] from the ${type} SourceBuffer`);
  17240. sb.remove(removeStart, removeEnd);
  17241. } else {
  17242. this.shiftAndExecuteNext(type);
  17243. }
  17244. }
  17245. appendExecutor(data, type) {
  17246. const track = this.tracks[type];
  17247. const sb = track == null ? void 0 : track.buffer;
  17248. if (!sb) {
  17249. throw new HlsJsTrackRemovedError(`Attempting to append to the ${type} SourceBuffer, but it does not exist`);
  17250. }
  17251. track.ending = false;
  17252. track.ended = false;
  17253. sb.appendBuffer(data);
  17254. }
  17255. blockUntilOpen(callback) {
  17256. if (this.isUpdating() || this.isQueued()) {
  17257. this.blockBuffers(callback).catch((error) => {
  17258. this.warn(`SourceBuffer blocked callback ${error}`);
  17259. this.stepOperationQueue(this.sourceBufferTypes);
  17260. });
  17261. } else {
  17262. try {
  17263. callback();
  17264. } catch (error) {
  17265. this.warn(`Callback run without blocking ${this.operationQueue} ${error}`);
  17266. }
  17267. }
  17268. }
  17269. isUpdating() {
  17270. return this.sourceBuffers.some(([type, sb]) => type && sb.updating);
  17271. }
  17272. isQueued() {
  17273. return this.sourceBuffers.some(([type]) => type && !!this.currentOp(type));
  17274. }
  17275. isPending(track) {
  17276. return !!track && !track.buffer;
  17277. }
  17278. blockBuffers(onUnblocked, bufferNames = this.sourceBufferTypes) {
  17279. if (!bufferNames.length) {
  17280. this.log("Blocking operation requested, but no SourceBuffers exist");
  17281. return Promise.resolve().then(onUnblocked);
  17282. }
  17283. const {
  17284. operationQueue
  17285. } = this;
  17286. const blockingOperations = bufferNames.map((type) => this.appendBlocker(type));
  17287. const audioBlocked = bufferNames.length > 1 && !!this.blockedAudioAppend;
  17288. if (audioBlocked) {
  17289. this.unblockAudio();
  17290. }
  17291. return Promise.all(blockingOperations).then((result) => {
  17292. if (operationQueue !== this.operationQueue) {
  17293. return;
  17294. }
  17295. onUnblocked();
  17296. this.stepOperationQueue(this.sourceBufferTypes);
  17297. });
  17298. }
  17299. stepOperationQueue(bufferNames) {
  17300. bufferNames.forEach((type) => {
  17301. var _this$tracks$type6;
  17302. const sb = (_this$tracks$type6 = this.tracks[type]) == null ? void 0 : _this$tracks$type6.buffer;
  17303. if (!sb || sb.updating) {
  17304. return;
  17305. }
  17306. this.shiftAndExecuteNext(type);
  17307. });
  17308. }
  17309. append(operation, type, pending) {
  17310. if (this.operationQueue) {
  17311. this.operationQueue.append(operation, type, pending);
  17312. }
  17313. }
  17314. appendBlocker(type) {
  17315. if (this.operationQueue) {
  17316. return this.operationQueue.appendBlocker(type);
  17317. }
  17318. }
  17319. currentOp(type) {
  17320. if (this.operationQueue) {
  17321. return this.operationQueue.current(type);
  17322. }
  17323. return null;
  17324. }
  17325. executeNext(type) {
  17326. if (type && this.operationQueue) {
  17327. this.operationQueue.executeNext(type);
  17328. }
  17329. }
  17330. shiftAndExecuteNext(type) {
  17331. if (this.operationQueue) {
  17332. this.operationQueue.shiftAndExecuteNext(type);
  17333. }
  17334. }
  17335. get pendingTrackCount() {
  17336. return Object.keys(this.tracks).reduce((acc, type) => acc + (this.isPending(this.tracks[type]) ? 1 : 0), 0);
  17337. }
  17338. get sourceBufferCount() {
  17339. return this.sourceBuffers.reduce((acc, [type]) => acc + (type ? 1 : 0), 0);
  17340. }
  17341. get sourceBufferTypes() {
  17342. return this.sourceBuffers.map(([type]) => type).filter((type) => !!type);
  17343. }
  17344. addBufferListener(type, event, fn) {
  17345. const track = this.tracks[type];
  17346. if (!track) {
  17347. return;
  17348. }
  17349. const buffer = track.buffer;
  17350. if (!buffer) {
  17351. return;
  17352. }
  17353. const listener = fn.bind(this, type);
  17354. track.listeners.push({
  17355. event,
  17356. listener
  17357. });
  17358. buffer.addEventListener(event, listener);
  17359. }
  17360. removeBufferListeners(type) {
  17361. const track = this.tracks[type];
  17362. if (!track) {
  17363. return;
  17364. }
  17365. const buffer = track.buffer;
  17366. if (!buffer) {
  17367. return;
  17368. }
  17369. track.listeners.forEach((l) => {
  17370. buffer.removeEventListener(l.event, l.listener);
  17371. });
  17372. track.listeners.length = 0;
  17373. }
  17374. };
  17375. function removeSourceChildren(node) {
  17376. const sourceChildren = node.querySelectorAll("source");
  17377. [].slice.call(sourceChildren).forEach((source) => {
  17378. node.removeChild(source);
  17379. });
  17380. }
  17381. function addSource(media, url) {
  17382. const source = self.document.createElement("source");
  17383. source.type = "video/mp4";
  17384. source.src = url;
  17385. media.appendChild(source);
  17386. }
  17387. function sourceBufferNameToIndex(type) {
  17388. return type === "audio" ? 1 : 0;
  17389. }
  17390. var CapLevelController = class {
  17391. constructor(hls) {
  17392. this.hls = void 0;
  17393. this.autoLevelCapping = void 0;
  17394. this.firstLevel = void 0;
  17395. this.media = void 0;
  17396. this.restrictedLevels = void 0;
  17397. this.timer = void 0;
  17398. this.clientRect = void 0;
  17399. this.streamController = void 0;
  17400. this.hls = hls;
  17401. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  17402. this.firstLevel = -1;
  17403. this.media = null;
  17404. this.restrictedLevels = [];
  17405. this.timer = void 0;
  17406. this.clientRect = null;
  17407. this.registerListeners();
  17408. }
  17409. setStreamController(streamController) {
  17410. this.streamController = streamController;
  17411. }
  17412. destroy() {
  17413. if (this.hls) {
  17414. this.unregisterListener();
  17415. }
  17416. if (this.timer) {
  17417. this.stopCapping();
  17418. }
  17419. this.media = null;
  17420. this.clientRect = null;
  17421. this.hls = this.streamController = null;
  17422. }
  17423. registerListeners() {
  17424. const {
  17425. hls
  17426. } = this;
  17427. hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  17428. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  17429. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  17430. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  17431. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  17432. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  17433. }
  17434. unregisterListener() {
  17435. const {
  17436. hls
  17437. } = this;
  17438. hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  17439. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  17440. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  17441. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  17442. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  17443. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  17444. }
  17445. onFpsDropLevelCapping(event, data) {
  17446. const level = this.hls.levels[data.droppedLevel];
  17447. if (this.isLevelAllowed(level)) {
  17448. this.restrictedLevels.push({
  17449. bitrate: level.bitrate,
  17450. height: level.height,
  17451. width: level.width
  17452. });
  17453. }
  17454. }
  17455. onMediaAttaching(event, data) {
  17456. this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  17457. this.clientRect = null;
  17458. if (this.timer && this.hls.levels.length) {
  17459. this.detectPlayerSize();
  17460. }
  17461. }
  17462. onManifestParsed(event, data) {
  17463. const hls = this.hls;
  17464. this.restrictedLevels = [];
  17465. this.firstLevel = data.firstLevel;
  17466. if (hls.config.capLevelToPlayerSize && data.video) {
  17467. this.startCapping();
  17468. }
  17469. }
  17470. onLevelsUpdated(event, data) {
  17471. if (this.timer && isFiniteNumber(this.autoLevelCapping)) {
  17472. this.detectPlayerSize();
  17473. }
  17474. }
  17475. onBufferCodecs(event, data) {
  17476. const hls = this.hls;
  17477. if (hls.config.capLevelToPlayerSize && data.video) {
  17478. this.startCapping();
  17479. }
  17480. }
  17481. onMediaDetaching() {
  17482. this.stopCapping();
  17483. this.media = null;
  17484. }
  17485. detectPlayerSize() {
  17486. if (this.media) {
  17487. if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {
  17488. this.clientRect = null;
  17489. return;
  17490. }
  17491. const levels = this.hls.levels;
  17492. if (levels.length) {
  17493. const hls = this.hls;
  17494. const maxLevel = this.getMaxLevel(levels.length - 1);
  17495. if (maxLevel !== this.autoLevelCapping) {
  17496. hls.logger.log(`Setting autoLevelCapping to ${maxLevel}: ${levels[maxLevel].height}p@${levels[maxLevel].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`);
  17497. }
  17498. hls.autoLevelCapping = maxLevel;
  17499. if (hls.autoLevelEnabled && hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
  17500. this.streamController.nextLevelSwitch();
  17501. }
  17502. this.autoLevelCapping = hls.autoLevelCapping;
  17503. }
  17504. }
  17505. }
  17506. getMaxLevel(capLevelIndex) {
  17507. const levels = this.hls.levels;
  17508. if (!levels.length) {
  17509. return -1;
  17510. }
  17511. const validLevels = levels.filter((level, index) => this.isLevelAllowed(level) && index <= capLevelIndex);
  17512. this.clientRect = null;
  17513. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  17514. }
  17515. startCapping() {
  17516. if (this.timer) {
  17517. return;
  17518. }
  17519. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  17520. self.clearInterval(this.timer);
  17521. this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1e3);
  17522. this.detectPlayerSize();
  17523. }
  17524. stopCapping() {
  17525. this.restrictedLevels = [];
  17526. this.firstLevel = -1;
  17527. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  17528. if (this.timer) {
  17529. self.clearInterval(this.timer);
  17530. this.timer = void 0;
  17531. }
  17532. }
  17533. getDimensions() {
  17534. if (this.clientRect) {
  17535. return this.clientRect;
  17536. }
  17537. const media = this.media;
  17538. const boundsRect = {
  17539. width: 0,
  17540. height: 0
  17541. };
  17542. if (media) {
  17543. const clientRect = media.getBoundingClientRect();
  17544. boundsRect.width = clientRect.width;
  17545. boundsRect.height = clientRect.height;
  17546. if (!boundsRect.width && !boundsRect.height) {
  17547. boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
  17548. boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
  17549. }
  17550. }
  17551. this.clientRect = boundsRect;
  17552. return boundsRect;
  17553. }
  17554. get mediaWidth() {
  17555. return this.getDimensions().width * this.contentScaleFactor;
  17556. }
  17557. get mediaHeight() {
  17558. return this.getDimensions().height * this.contentScaleFactor;
  17559. }
  17560. get contentScaleFactor() {
  17561. let pixelRatio = 1;
  17562. if (!this.hls.config.ignoreDevicePixelRatio) {
  17563. try {
  17564. pixelRatio = self.devicePixelRatio;
  17565. } catch (e) {
  17566. }
  17567. }
  17568. return Math.min(pixelRatio, this.hls.config.maxDevicePixelRatio);
  17569. }
  17570. isLevelAllowed(level) {
  17571. const restrictedLevels = this.restrictedLevels;
  17572. return !restrictedLevels.some((restrictedLevel) => {
  17573. return level.bitrate === restrictedLevel.bitrate && level.width === restrictedLevel.width && level.height === restrictedLevel.height;
  17574. });
  17575. }
  17576. static getMaxLevelByMediaSize(levels, width, height) {
  17577. if (!(levels != null && levels.length)) {
  17578. return -1;
  17579. }
  17580. const atGreatestBandwidth = (curLevel, nextLevel) => {
  17581. if (!nextLevel) {
  17582. return true;
  17583. }
  17584. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  17585. };
  17586. let maxLevelIndex = levels.length - 1;
  17587. const squareSize = Math.max(width, height);
  17588. for (let i = 0; i < levels.length; i += 1) {
  17589. const level = levels[i];
  17590. if ((level.width >= squareSize || level.height >= squareSize) && atGreatestBandwidth(level, levels[i + 1])) {
  17591. maxLevelIndex = i;
  17592. break;
  17593. }
  17594. }
  17595. return maxLevelIndex;
  17596. }
  17597. };
  17598. var CmObjectType = {
  17599. MANIFEST: "m",
  17600. AUDIO: "a",
  17601. VIDEO: "v",
  17602. MUXED: "av",
  17603. INIT: "i",
  17604. CAPTION: "c",
  17605. TIMED_TEXT: "tt",
  17606. KEY: "k",
  17607. OTHER: "o"
  17608. };
  17609. var CmcdObjectType = CmObjectType;
  17610. var CmStreamingFormat = {
  17611. HLS: "h"
  17612. };
  17613. var CmcdStreamingFormat = CmStreamingFormat;
  17614. var CMCD_OBJECT = "CMCD-Object";
  17615. var CMCD_REQUEST = "CMCD-Request";
  17616. var CMCD_SESSION = "CMCD-Session";
  17617. var CMCD_STATUS = "CMCD-Status";
  17618. var CmcdHeaderField = {
  17619. OBJECT: CMCD_OBJECT,
  17620. REQUEST: CMCD_REQUEST,
  17621. SESSION: CMCD_SESSION,
  17622. STATUS: CMCD_STATUS
  17623. };
  17624. var CmcdHeaderMap = {
  17625. [CmcdHeaderField.OBJECT]: ["br", "ab", "d", "ot", "tb", "tpb", "lb", "tab", "lab", "url"],
  17626. [CmcdHeaderField.REQUEST]: ["pb", "bl", "tbl", "dl", "ltc", "mtp", "nor", "nrr", "rc", "sn", "sta", "su", "ttfb", "ttfbb", "ttlb", "cmsdd", "cmsds", "smrt", "df", "cs"],
  17627. [CmcdHeaderField.SESSION]: ["cid", "pr", "sf", "sid", "st", "v", "msd"],
  17628. [CmcdHeaderField.STATUS]: ["bs", "bsd", "cdn", "rtp", "bg", "pt", "ec", "e"]
  17629. };
  17630. var SfItem = class {
  17631. constructor(value, params) {
  17632. if (Array.isArray(value)) {
  17633. value = value.map((v) => v instanceof SfItem ? v : new SfItem(v));
  17634. }
  17635. this.value = value;
  17636. this.params = params;
  17637. }
  17638. };
  17639. var DICT = "Dict";
  17640. function format(value) {
  17641. if (Array.isArray(value)) {
  17642. return JSON.stringify(value);
  17643. }
  17644. if (value instanceof Map) {
  17645. return "Map{}";
  17646. }
  17647. if (value instanceof Set) {
  17648. return "Set{}";
  17649. }
  17650. if (typeof value === "object") {
  17651. return JSON.stringify(value);
  17652. }
  17653. return String(value);
  17654. }
  17655. function throwError(action, src, type, cause) {
  17656. return new Error(`failed to ${action} "${format(src)}" as ${type}`, {
  17657. cause
  17658. });
  17659. }
  17660. function serializeError(src, type, cause) {
  17661. return throwError("serialize", src, type, cause);
  17662. }
  17663. var SfToken = class {
  17664. constructor(description) {
  17665. this.description = description;
  17666. }
  17667. };
  17668. var BARE_ITEM = "Bare Item";
  17669. var BOOLEAN = "Boolean";
  17670. function serializeBoolean(value) {
  17671. if (typeof value !== "boolean") {
  17672. throw serializeError(value, BOOLEAN);
  17673. }
  17674. return value ? "?1" : "?0";
  17675. }
  17676. function encodeBase64(binary) {
  17677. return btoa(String.fromCharCode(...binary));
  17678. }
  17679. var BYTES = "Byte Sequence";
  17680. function serializeByteSequence(value) {
  17681. if (ArrayBuffer.isView(value) === false) {
  17682. throw serializeError(value, BYTES);
  17683. }
  17684. return `:${encodeBase64(value)}:`;
  17685. }
  17686. var INTEGER = "Integer";
  17687. function isInvalidInt(value) {
  17688. return value < -999999999999999 || 999999999999999 < value;
  17689. }
  17690. function serializeInteger(value) {
  17691. if (isInvalidInt(value)) {
  17692. throw serializeError(value, INTEGER);
  17693. }
  17694. return value.toString();
  17695. }
  17696. function serializeDate(value) {
  17697. return `@${serializeInteger(value.getTime() / 1e3)}`;
  17698. }
  17699. function roundToEven(value, precision) {
  17700. if (value < 0) {
  17701. return -roundToEven(-value, precision);
  17702. }
  17703. const decimalShift = Math.pow(10, precision);
  17704. const isEquidistant = Math.abs(value * decimalShift % 1 - 0.5) < Number.EPSILON;
  17705. if (isEquidistant) {
  17706. const flooredValue = Math.floor(value * decimalShift);
  17707. return (flooredValue % 2 === 0 ? flooredValue : flooredValue + 1) / decimalShift;
  17708. } else {
  17709. return Math.round(value * decimalShift) / decimalShift;
  17710. }
  17711. }
  17712. var DECIMAL = "Decimal";
  17713. function serializeDecimal(value) {
  17714. const roundedValue = roundToEven(value, 3);
  17715. if (Math.floor(Math.abs(roundedValue)).toString().length > 12) {
  17716. throw serializeError(value, DECIMAL);
  17717. }
  17718. const stringValue = roundedValue.toString();
  17719. return stringValue.includes(".") ? stringValue : `${stringValue}.0`;
  17720. }
  17721. var STRING = "String";
  17722. var STRING_REGEX = /[\x00-\x1f\x7f]+/;
  17723. function serializeString(value) {
  17724. if (STRING_REGEX.test(value)) {
  17725. throw serializeError(value, STRING);
  17726. }
  17727. return `"${value.replace(/\\/g, `\\\\`).replace(/"/g, `\\"`)}"`;
  17728. }
  17729. function symbolToStr(symbol) {
  17730. return symbol.description || symbol.toString().slice(7, -1);
  17731. }
  17732. var TOKEN = "Token";
  17733. function serializeToken(token) {
  17734. const value = symbolToStr(token);
  17735. if (/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(value) === false) {
  17736. throw serializeError(value, TOKEN);
  17737. }
  17738. return value;
  17739. }
  17740. function serializeBareItem(value) {
  17741. switch (typeof value) {
  17742. case "number":
  17743. if (!isFiniteNumber(value)) {
  17744. throw serializeError(value, BARE_ITEM);
  17745. }
  17746. if (Number.isInteger(value)) {
  17747. return serializeInteger(value);
  17748. }
  17749. return serializeDecimal(value);
  17750. case "string":
  17751. return serializeString(value);
  17752. case "symbol":
  17753. return serializeToken(value);
  17754. case "boolean":
  17755. return serializeBoolean(value);
  17756. case "object":
  17757. if (value instanceof Date) {
  17758. return serializeDate(value);
  17759. }
  17760. if (value instanceof Uint8Array) {
  17761. return serializeByteSequence(value);
  17762. }
  17763. if (value instanceof SfToken) {
  17764. return serializeToken(value);
  17765. }
  17766. default:
  17767. throw serializeError(value, BARE_ITEM);
  17768. }
  17769. }
  17770. var KEY = "Key";
  17771. function serializeKey(value) {
  17772. if (/^[a-z*][a-z0-9\-_.*]*$/.test(value) === false) {
  17773. throw serializeError(value, KEY);
  17774. }
  17775. return value;
  17776. }
  17777. function serializeParams(params) {
  17778. if (params == null) {
  17779. return "";
  17780. }
  17781. return Object.entries(params).map(([key, value]) => {
  17782. if (value === true) {
  17783. return `;${serializeKey(key)}`;
  17784. }
  17785. return `;${serializeKey(key)}=${serializeBareItem(value)}`;
  17786. }).join("");
  17787. }
  17788. function serializeItem(value) {
  17789. if (value instanceof SfItem) {
  17790. return `${serializeBareItem(value.value)}${serializeParams(value.params)}`;
  17791. } else {
  17792. return serializeBareItem(value);
  17793. }
  17794. }
  17795. function serializeInnerList(value) {
  17796. return `(${value.value.map(serializeItem).join(" ")})${serializeParams(value.params)}`;
  17797. }
  17798. function serializeDict(dict, options = {
  17799. whitespace: true
  17800. }) {
  17801. if (typeof dict !== "object") {
  17802. throw serializeError(dict, DICT);
  17803. }
  17804. const entries = dict instanceof Map ? dict.entries() : Object.entries(dict);
  17805. const optionalWhiteSpace = (options === null || options === void 0 ? void 0 : options.whitespace) ? " " : "";
  17806. return Array.from(entries).map(([key, item]) => {
  17807. if (item instanceof SfItem === false) {
  17808. item = new SfItem(item);
  17809. }
  17810. let output = serializeKey(key);
  17811. if (item.value === true) {
  17812. output += serializeParams(item.params);
  17813. } else {
  17814. output += "=";
  17815. if (Array.isArray(item.value)) {
  17816. output += serializeInnerList(item);
  17817. } else {
  17818. output += serializeItem(item);
  17819. }
  17820. }
  17821. return output;
  17822. }).join(`,${optionalWhiteSpace}`);
  17823. }
  17824. function encodeSfDict(value, options) {
  17825. return serializeDict(value, options);
  17826. }
  17827. function isTokenField(key) {
  17828. return ["ot", "sf", "st", "e", "sta"].includes(key);
  17829. }
  17830. function isValid(value) {
  17831. if (typeof value === "number") {
  17832. return isFiniteNumber(value);
  17833. }
  17834. return value != null && value !== "" && value !== false;
  17835. }
  17836. function urlToRelativePath(url, base) {
  17837. const to = new URL(url);
  17838. const from = new URL(base);
  17839. if (to.origin !== from.origin) {
  17840. return url;
  17841. }
  17842. const toPath = to.pathname.split("/").slice(1);
  17843. const fromPath = from.pathname.split("/").slice(1, -1);
  17844. while (toPath[0] === fromPath[0]) {
  17845. toPath.shift();
  17846. fromPath.shift();
  17847. }
  17848. while (fromPath.length) {
  17849. fromPath.shift();
  17850. toPath.unshift("..");
  17851. }
  17852. return toPath.join("/");
  17853. }
  17854. var toRounded = (value) => Math.round(value);
  17855. var toUrlSafe = (value, options) => {
  17856. if (options === null || options === void 0 ? void 0 : options.baseUrl) {
  17857. value = urlToRelativePath(value, options.baseUrl);
  17858. }
  17859. return encodeURIComponent(value);
  17860. };
  17861. var toHundred = (value) => toRounded(value / 100) * 100;
  17862. var CmcdFormatters = {
  17863. br: toRounded,
  17864. d: toRounded,
  17865. bl: toHundred,
  17866. dl: toHundred,
  17867. mtp: toHundred,
  17868. nor: toUrlSafe,
  17869. rtp: toHundred,
  17870. tb: toRounded
  17871. };
  17872. function processCmcd(obj, options) {
  17873. const results = {};
  17874. if (obj == null || typeof obj !== "object") {
  17875. return results;
  17876. }
  17877. const keys = Object.keys(obj).sort();
  17878. const formatters = _extends({}, CmcdFormatters, options === null || options === void 0 ? void 0 : options.formatters);
  17879. const filter = options === null || options === void 0 ? void 0 : options.filter;
  17880. keys.forEach((key) => {
  17881. if ((filter === null || filter === void 0 ? void 0 : filter(key)) === false) {
  17882. return;
  17883. }
  17884. let value = obj[key];
  17885. const formatter = formatters[key];
  17886. if (formatter) {
  17887. value = formatter(value, options);
  17888. }
  17889. if (key === "v" && value === 1) {
  17890. return;
  17891. }
  17892. if (key == "pr" && value === 1) {
  17893. return;
  17894. }
  17895. if (!isValid(value)) {
  17896. return;
  17897. }
  17898. if (isTokenField(key) && typeof value === "string") {
  17899. value = new SfToken(value);
  17900. }
  17901. results[key] = value;
  17902. });
  17903. return results;
  17904. }
  17905. function encodeCmcd(cmcd, options = {}) {
  17906. if (!cmcd) {
  17907. return "";
  17908. }
  17909. return encodeSfDict(processCmcd(cmcd, options), _extends({
  17910. whitespace: false
  17911. }, options));
  17912. }
  17913. function toCmcdHeaders(cmcd, options = {}) {
  17914. const result = {};
  17915. if (!cmcd) {
  17916. return result;
  17917. }
  17918. const entries = Object.entries(cmcd);
  17919. const headerMap = Object.entries(CmcdHeaderMap).concat(Object.entries((options === null || options === void 0 ? void 0 : options.customHeaderMap) || {}));
  17920. const shards = entries.reduce((acc, entry) => {
  17921. var _a, _b;
  17922. const [key, value] = entry;
  17923. const field = ((_a = headerMap.find((entry2) => entry2[1].includes(key))) === null || _a === void 0 ? void 0 : _a[0]) || CmcdHeaderField.REQUEST;
  17924. (_b = acc[field]) !== null && _b !== void 0 ? _b : acc[field] = {};
  17925. acc[field][key] = value;
  17926. return acc;
  17927. }, {});
  17928. return Object.entries(shards).reduce((acc, [field, value]) => {
  17929. acc[field] = encodeCmcd(value, options);
  17930. return acc;
  17931. }, result);
  17932. }
  17933. function appendCmcdHeaders(headers, cmcd, options) {
  17934. return _extends(headers, toCmcdHeaders(cmcd, options));
  17935. }
  17936. var CMCD_PARAM = "CMCD";
  17937. function toCmcdQuery(cmcd, options = {}) {
  17938. if (!cmcd) {
  17939. return "";
  17940. }
  17941. const params = encodeCmcd(cmcd, options);
  17942. return `${CMCD_PARAM}=${encodeURIComponent(params)}`;
  17943. }
  17944. var REGEX = /CMCD=[^&#]+/;
  17945. function appendCmcdQuery(url, cmcd, options) {
  17946. const query = toCmcdQuery(cmcd, options);
  17947. if (!query) {
  17948. return url;
  17949. }
  17950. if (REGEX.test(url)) {
  17951. return url.replace(REGEX, query);
  17952. }
  17953. const separator = url.includes("?") ? "&" : "?";
  17954. return `${url}${separator}${query}`;
  17955. }
  17956. var CMCDController = class {
  17957. constructor(hls) {
  17958. this.hls = void 0;
  17959. this.config = void 0;
  17960. this.media = void 0;
  17961. this.sid = void 0;
  17962. this.cid = void 0;
  17963. this.useHeaders = false;
  17964. this.includeKeys = void 0;
  17965. this.initialized = false;
  17966. this.starved = false;
  17967. this.buffering = true;
  17968. this.audioBuffer = void 0;
  17969. this.videoBuffer = void 0;
  17970. this.onWaiting = () => {
  17971. if (this.initialized) {
  17972. this.starved = true;
  17973. }
  17974. this.buffering = true;
  17975. };
  17976. this.onPlaying = () => {
  17977. if (!this.initialized) {
  17978. this.initialized = true;
  17979. }
  17980. this.buffering = false;
  17981. };
  17982. this.applyPlaylistData = (context) => {
  17983. try {
  17984. this.apply(context, {
  17985. ot: CmcdObjectType.MANIFEST,
  17986. su: !this.initialized
  17987. });
  17988. } catch (error) {
  17989. this.hls.logger.warn("Could not generate manifest CMCD data.", error);
  17990. }
  17991. };
  17992. this.applyFragmentData = (context) => {
  17993. try {
  17994. const {
  17995. frag,
  17996. part
  17997. } = context;
  17998. const level = this.hls.levels[frag.level];
  17999. const ot = this.getObjectType(frag);
  18000. const data = {
  18001. d: (part || frag).duration * 1e3,
  18002. ot
  18003. };
  18004. if (ot === CmcdObjectType.VIDEO || ot === CmcdObjectType.AUDIO || ot == CmcdObjectType.MUXED) {
  18005. data.br = level.bitrate / 1e3;
  18006. data.tb = this.getTopBandwidth(ot) / 1e3;
  18007. data.bl = this.getBufferLength(ot);
  18008. }
  18009. const next = part ? this.getNextPart(part) : this.getNextFrag(frag);
  18010. if (next != null && next.url && next.url !== frag.url) {
  18011. data.nor = next.url;
  18012. }
  18013. this.apply(context, data);
  18014. } catch (error) {
  18015. this.hls.logger.warn("Could not generate segment CMCD data.", error);
  18016. }
  18017. };
  18018. this.hls = hls;
  18019. const config = this.config = hls.config;
  18020. const {
  18021. cmcd
  18022. } = config;
  18023. if (cmcd != null) {
  18024. config.pLoader = this.createPlaylistLoader();
  18025. config.fLoader = this.createFragmentLoader();
  18026. this.sid = cmcd.sessionId || hls.sessionId;
  18027. this.cid = cmcd.contentId;
  18028. this.useHeaders = cmcd.useHeaders === true;
  18029. this.includeKeys = cmcd.includeKeys;
  18030. this.registerListeners();
  18031. }
  18032. }
  18033. registerListeners() {
  18034. const hls = this.hls;
  18035. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18036. hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  18037. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  18038. }
  18039. unregisterListeners() {
  18040. const hls = this.hls;
  18041. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18042. hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  18043. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  18044. }
  18045. destroy() {
  18046. this.unregisterListeners();
  18047. this.onMediaDetached();
  18048. this.hls = this.config = this.audioBuffer = this.videoBuffer = null;
  18049. this.onWaiting = this.onPlaying = this.media = null;
  18050. }
  18051. onMediaAttached(event, data) {
  18052. this.media = data.media;
  18053. this.media.addEventListener("waiting", this.onWaiting);
  18054. this.media.addEventListener("playing", this.onPlaying);
  18055. }
  18056. onMediaDetached() {
  18057. if (!this.media) {
  18058. return;
  18059. }
  18060. this.media.removeEventListener("waiting", this.onWaiting);
  18061. this.media.removeEventListener("playing", this.onPlaying);
  18062. this.media = null;
  18063. }
  18064. onBufferCreated(event, data) {
  18065. var _data$tracks$audio, _data$tracks$video;
  18066. this.audioBuffer = (_data$tracks$audio = data.tracks.audio) == null ? void 0 : _data$tracks$audio.buffer;
  18067. this.videoBuffer = (_data$tracks$video = data.tracks.video) == null ? void 0 : _data$tracks$video.buffer;
  18068. }
  18069. createData() {
  18070. var _this$media;
  18071. return {
  18072. v: 1,
  18073. sf: CmcdStreamingFormat.HLS,
  18074. sid: this.sid,
  18075. cid: this.cid,
  18076. pr: (_this$media = this.media) == null ? void 0 : _this$media.playbackRate,
  18077. mtp: this.hls.bandwidthEstimate / 1e3
  18078. };
  18079. }
  18080. apply(context, data = {}) {
  18081. _extends(data, this.createData());
  18082. const isVideo = data.ot === CmcdObjectType.INIT || data.ot === CmcdObjectType.VIDEO || data.ot === CmcdObjectType.MUXED;
  18083. if (this.starved && isVideo) {
  18084. data.bs = true;
  18085. data.su = true;
  18086. this.starved = false;
  18087. }
  18088. if (data.su == null) {
  18089. data.su = this.buffering;
  18090. }
  18091. const {
  18092. includeKeys
  18093. } = this;
  18094. if (includeKeys) {
  18095. data = Object.keys(data).reduce((acc, key) => {
  18096. includeKeys.includes(key) && (acc[key] = data[key]);
  18097. return acc;
  18098. }, {});
  18099. }
  18100. const options = {
  18101. baseUrl: context.url
  18102. };
  18103. if (this.useHeaders) {
  18104. if (!context.headers) {
  18105. context.headers = {};
  18106. }
  18107. appendCmcdHeaders(context.headers, data, options);
  18108. } else {
  18109. context.url = appendCmcdQuery(context.url, data, options);
  18110. }
  18111. }
  18112. getNextFrag(fragment) {
  18113. var _this$hls$levels$frag;
  18114. const levelDetails = (_this$hls$levels$frag = this.hls.levels[fragment.level]) == null ? void 0 : _this$hls$levels$frag.details;
  18115. if (levelDetails) {
  18116. const index = fragment.sn - levelDetails.startSN;
  18117. return levelDetails.fragments[index + 1];
  18118. }
  18119. return void 0;
  18120. }
  18121. getNextPart(part) {
  18122. var _this$hls$levels$frag2, _this$hls$levels$frag3;
  18123. const {
  18124. index,
  18125. fragment
  18126. } = part;
  18127. 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;
  18128. if (partList) {
  18129. const {
  18130. sn
  18131. } = fragment;
  18132. for (let i = partList.length - 1; i >= 0; i--) {
  18133. const p = partList[i];
  18134. if (p.index === index && p.fragment.sn === sn) {
  18135. return partList[i + 1];
  18136. }
  18137. }
  18138. }
  18139. return void 0;
  18140. }
  18141. getObjectType(fragment) {
  18142. const {
  18143. type
  18144. } = fragment;
  18145. if (type === "subtitle") {
  18146. return CmcdObjectType.TIMED_TEXT;
  18147. }
  18148. if (fragment.sn === "initSegment") {
  18149. return CmcdObjectType.INIT;
  18150. }
  18151. if (type === "audio") {
  18152. return CmcdObjectType.AUDIO;
  18153. }
  18154. if (type === "main") {
  18155. if (!this.hls.audioTracks.length) {
  18156. return CmcdObjectType.MUXED;
  18157. }
  18158. return CmcdObjectType.VIDEO;
  18159. }
  18160. return void 0;
  18161. }
  18162. getTopBandwidth(type) {
  18163. let bitrate = 0;
  18164. let levels;
  18165. const hls = this.hls;
  18166. if (type === CmcdObjectType.AUDIO) {
  18167. levels = hls.audioTracks;
  18168. } else {
  18169. const max = hls.maxAutoLevel;
  18170. const len = max > -1 ? max + 1 : hls.levels.length;
  18171. levels = hls.levels.slice(0, len);
  18172. }
  18173. levels.forEach((level) => {
  18174. if (level.bitrate > bitrate) {
  18175. bitrate = level.bitrate;
  18176. }
  18177. });
  18178. return bitrate > 0 ? bitrate : NaN;
  18179. }
  18180. getBufferLength(type) {
  18181. const media = this.media;
  18182. const buffer = type === CmcdObjectType.AUDIO ? this.audioBuffer : this.videoBuffer;
  18183. if (!buffer || !media) {
  18184. return NaN;
  18185. }
  18186. const info = BufferHelper.bufferInfo(buffer, media.currentTime, this.config.maxBufferHole);
  18187. return info.len * 1e3;
  18188. }
  18189. createPlaylistLoader() {
  18190. const {
  18191. pLoader
  18192. } = this.config;
  18193. const apply = this.applyPlaylistData;
  18194. const Ctor = pLoader || this.config.loader;
  18195. return class CmcdPlaylistLoader {
  18196. constructor(config) {
  18197. this.loader = void 0;
  18198. this.loader = new Ctor(config);
  18199. }
  18200. get stats() {
  18201. return this.loader.stats;
  18202. }
  18203. get context() {
  18204. return this.loader.context;
  18205. }
  18206. destroy() {
  18207. this.loader.destroy();
  18208. }
  18209. abort() {
  18210. this.loader.abort();
  18211. }
  18212. load(context, config, callbacks) {
  18213. apply(context);
  18214. this.loader.load(context, config, callbacks);
  18215. }
  18216. };
  18217. }
  18218. createFragmentLoader() {
  18219. const {
  18220. fLoader
  18221. } = this.config;
  18222. const apply = this.applyFragmentData;
  18223. const Ctor = fLoader || this.config.loader;
  18224. return class CmcdFragmentLoader {
  18225. constructor(config) {
  18226. this.loader = void 0;
  18227. this.loader = new Ctor(config);
  18228. }
  18229. get stats() {
  18230. return this.loader.stats;
  18231. }
  18232. get context() {
  18233. return this.loader.context;
  18234. }
  18235. destroy() {
  18236. this.loader.destroy();
  18237. }
  18238. abort() {
  18239. this.loader.abort();
  18240. }
  18241. load(context, config, callbacks) {
  18242. apply(context);
  18243. this.loader.load(context, config, callbacks);
  18244. }
  18245. };
  18246. }
  18247. };
  18248. var PATHWAY_PENALTY_DURATION_MS = 3e5;
  18249. var ContentSteeringController = class extends Logger {
  18250. constructor(hls) {
  18251. super("content-steering", hls.logger);
  18252. this.hls = void 0;
  18253. this.loader = null;
  18254. this.uri = null;
  18255. this.pathwayId = ".";
  18256. this._pathwayPriority = null;
  18257. this.timeToLoad = 300;
  18258. this.reloadTimer = -1;
  18259. this.updated = 0;
  18260. this.started = false;
  18261. this.enabled = true;
  18262. this.levels = null;
  18263. this.audioTracks = null;
  18264. this.subtitleTracks = null;
  18265. this.penalizedPathways = {};
  18266. this.hls = hls;
  18267. this.registerListeners();
  18268. }
  18269. registerListeners() {
  18270. const hls = this.hls;
  18271. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18272. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  18273. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  18274. hls.on(Events.ERROR, this.onError, this);
  18275. }
  18276. unregisterListeners() {
  18277. const hls = this.hls;
  18278. if (!hls) {
  18279. return;
  18280. }
  18281. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18282. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  18283. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  18284. hls.off(Events.ERROR, this.onError, this);
  18285. }
  18286. pathways() {
  18287. return (this.levels || []).reduce((pathways, level) => {
  18288. if (pathways.indexOf(level.pathwayId) === -1) {
  18289. pathways.push(level.pathwayId);
  18290. }
  18291. return pathways;
  18292. }, []);
  18293. }
  18294. get pathwayPriority() {
  18295. return this._pathwayPriority;
  18296. }
  18297. set pathwayPriority(pathwayPriority) {
  18298. this.updatePathwayPriority(pathwayPriority);
  18299. }
  18300. startLoad() {
  18301. this.started = true;
  18302. this.clearTimeout();
  18303. if (this.enabled && this.uri) {
  18304. if (this.updated) {
  18305. const ttl = this.timeToLoad * 1e3 - (performance.now() - this.updated);
  18306. if (ttl > 0) {
  18307. this.scheduleRefresh(this.uri, ttl);
  18308. return;
  18309. }
  18310. }
  18311. this.loadSteeringManifest(this.uri);
  18312. }
  18313. }
  18314. stopLoad() {
  18315. this.started = false;
  18316. if (this.loader) {
  18317. this.loader.destroy();
  18318. this.loader = null;
  18319. }
  18320. this.clearTimeout();
  18321. }
  18322. clearTimeout() {
  18323. if (this.reloadTimer !== -1) {
  18324. self.clearTimeout(this.reloadTimer);
  18325. this.reloadTimer = -1;
  18326. }
  18327. }
  18328. destroy() {
  18329. this.unregisterListeners();
  18330. this.stopLoad();
  18331. this.hls = null;
  18332. this.levels = this.audioTracks = this.subtitleTracks = null;
  18333. }
  18334. removeLevel(levelToRemove) {
  18335. const levels = this.levels;
  18336. if (levels) {
  18337. this.levels = levels.filter((level) => level !== levelToRemove);
  18338. }
  18339. }
  18340. onManifestLoading() {
  18341. this.stopLoad();
  18342. this.enabled = true;
  18343. this.timeToLoad = 300;
  18344. this.updated = 0;
  18345. this.uri = null;
  18346. this.pathwayId = ".";
  18347. this.levels = this.audioTracks = this.subtitleTracks = null;
  18348. }
  18349. onManifestLoaded(event, data) {
  18350. const {
  18351. contentSteering
  18352. } = data;
  18353. if (contentSteering === null) {
  18354. return;
  18355. }
  18356. this.pathwayId = contentSteering.pathwayId;
  18357. this.uri = contentSteering.uri;
  18358. if (this.started) {
  18359. this.startLoad();
  18360. }
  18361. }
  18362. onManifestParsed(event, data) {
  18363. this.audioTracks = data.audioTracks;
  18364. this.subtitleTracks = data.subtitleTracks;
  18365. }
  18366. onError(event, data) {
  18367. const {
  18368. errorAction
  18369. } = data;
  18370. if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox && errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost) {
  18371. const levels = this.levels;
  18372. let pathwayPriority = this._pathwayPriority;
  18373. let errorPathway = this.pathwayId;
  18374. if (data.context) {
  18375. const {
  18376. groupId,
  18377. pathwayId,
  18378. type
  18379. } = data.context;
  18380. if (groupId && levels) {
  18381. errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway);
  18382. } else if (pathwayId) {
  18383. errorPathway = pathwayId;
  18384. }
  18385. }
  18386. if (!(errorPathway in this.penalizedPathways)) {
  18387. this.penalizedPathways[errorPathway] = performance.now();
  18388. }
  18389. if (!pathwayPriority && levels) {
  18390. pathwayPriority = this.pathways();
  18391. }
  18392. if (pathwayPriority && pathwayPriority.length > 1) {
  18393. this.updatePathwayPriority(pathwayPriority);
  18394. errorAction.resolved = this.pathwayId !== errorPathway;
  18395. }
  18396. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && !data.fatal) {
  18397. errorAction.resolved = true;
  18398. } else if (!errorAction.resolved) {
  18399. 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)}`);
  18400. }
  18401. }
  18402. }
  18403. filterParsedLevels(levels) {
  18404. this.levels = levels;
  18405. let pathwayLevels = this.getLevelsForPathway(this.pathwayId);
  18406. if (pathwayLevels.length === 0) {
  18407. const pathwayId = levels[0].pathwayId;
  18408. this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${pathwayId}"`);
  18409. pathwayLevels = this.getLevelsForPathway(pathwayId);
  18410. this.pathwayId = pathwayId;
  18411. }
  18412. if (pathwayLevels.length !== levels.length) {
  18413. this.log(`Found ${pathwayLevels.length}/${levels.length} levels in Pathway "${this.pathwayId}"`);
  18414. }
  18415. return pathwayLevels;
  18416. }
  18417. getLevelsForPathway(pathwayId) {
  18418. if (this.levels === null) {
  18419. return [];
  18420. }
  18421. return this.levels.filter((level) => pathwayId === level.pathwayId);
  18422. }
  18423. updatePathwayPriority(pathwayPriority) {
  18424. this._pathwayPriority = pathwayPriority;
  18425. let levels;
  18426. const penalizedPathways = this.penalizedPathways;
  18427. const now2 = performance.now();
  18428. Object.keys(penalizedPathways).forEach((pathwayId) => {
  18429. if (now2 - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {
  18430. delete penalizedPathways[pathwayId];
  18431. }
  18432. });
  18433. for (let i = 0; i < pathwayPriority.length; i++) {
  18434. const pathwayId = pathwayPriority[i];
  18435. if (pathwayId in penalizedPathways) {
  18436. continue;
  18437. }
  18438. if (pathwayId === this.pathwayId) {
  18439. return;
  18440. }
  18441. const selectedIndex = this.hls.nextLoadLevel;
  18442. const selectedLevel = this.hls.levels[selectedIndex];
  18443. levels = this.getLevelsForPathway(pathwayId);
  18444. if (levels.length > 0) {
  18445. this.log(`Setting Pathway to "${pathwayId}"`);
  18446. this.pathwayId = pathwayId;
  18447. reassignFragmentLevelIndexes(levels);
  18448. this.hls.trigger(Events.LEVELS_UPDATED, {
  18449. levels
  18450. });
  18451. const levelAfterChange = this.hls.levels[selectedIndex];
  18452. if (selectedLevel && levelAfterChange && this.levels) {
  18453. if (levelAfterChange.attrs["STABLE-VARIANT-ID"] !== selectedLevel.attrs["STABLE-VARIANT-ID"] && levelAfterChange.bitrate !== selectedLevel.bitrate) {
  18454. this.log(`Unstable Pathways change from bitrate ${selectedLevel.bitrate} to ${levelAfterChange.bitrate}`);
  18455. }
  18456. this.hls.nextLoadLevel = selectedIndex;
  18457. }
  18458. break;
  18459. }
  18460. }
  18461. }
  18462. getPathwayForGroupId(groupId, type, defaultPathway) {
  18463. const levels = this.getLevelsForPathway(defaultPathway).concat(this.levels || []);
  18464. for (let i = 0; i < levels.length; i++) {
  18465. if (type === PlaylistContextType.AUDIO_TRACK && levels[i].hasAudioGroup(groupId) || type === PlaylistContextType.SUBTITLE_TRACK && levels[i].hasSubtitleGroup(groupId)) {
  18466. return levels[i].pathwayId;
  18467. }
  18468. }
  18469. return defaultPathway;
  18470. }
  18471. clonePathways(pathwayClones) {
  18472. const levels = this.levels;
  18473. if (!levels) {
  18474. return;
  18475. }
  18476. const audioGroupCloneMap = {};
  18477. const subtitleGroupCloneMap = {};
  18478. pathwayClones.forEach((pathwayClone) => {
  18479. const {
  18480. ID: cloneId,
  18481. "BASE-ID": baseId,
  18482. "URI-REPLACEMENT": uriReplacement
  18483. } = pathwayClone;
  18484. if (levels.some((level) => level.pathwayId === cloneId)) {
  18485. return;
  18486. }
  18487. const clonedVariants = this.getLevelsForPathway(baseId).map((baseLevel) => {
  18488. const attributes = new AttrList(baseLevel.attrs);
  18489. attributes["PATHWAY-ID"] = cloneId;
  18490. const clonedAudioGroupId = attributes.AUDIO && `${attributes.AUDIO}_clone_${cloneId}`;
  18491. const clonedSubtitleGroupId = attributes.SUBTITLES && `${attributes.SUBTITLES}_clone_${cloneId}`;
  18492. if (clonedAudioGroupId) {
  18493. audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;
  18494. attributes.AUDIO = clonedAudioGroupId;
  18495. }
  18496. if (clonedSubtitleGroupId) {
  18497. subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;
  18498. attributes.SUBTITLES = clonedSubtitleGroupId;
  18499. }
  18500. const url = performUriReplacement(baseLevel.uri, attributes["STABLE-VARIANT-ID"], "PER-VARIANT-URIS", uriReplacement);
  18501. const clonedLevel = new Level({
  18502. attrs: attributes,
  18503. audioCodec: baseLevel.audioCodec,
  18504. bitrate: baseLevel.bitrate,
  18505. height: baseLevel.height,
  18506. name: baseLevel.name,
  18507. url,
  18508. videoCodec: baseLevel.videoCodec,
  18509. width: baseLevel.width
  18510. });
  18511. if (baseLevel.audioGroups) {
  18512. for (let i = 1; i < baseLevel.audioGroups.length; i++) {
  18513. clonedLevel.addGroupId("audio", `${baseLevel.audioGroups[i]}_clone_${cloneId}`);
  18514. }
  18515. }
  18516. if (baseLevel.subtitleGroups) {
  18517. for (let i = 1; i < baseLevel.subtitleGroups.length; i++) {
  18518. clonedLevel.addGroupId("text", `${baseLevel.subtitleGroups[i]}_clone_${cloneId}`);
  18519. }
  18520. }
  18521. return clonedLevel;
  18522. });
  18523. levels.push(...clonedVariants);
  18524. cloneRenditionGroups(this.audioTracks, audioGroupCloneMap, uriReplacement, cloneId);
  18525. cloneRenditionGroups(this.subtitleTracks, subtitleGroupCloneMap, uriReplacement, cloneId);
  18526. });
  18527. }
  18528. loadSteeringManifest(uri) {
  18529. const config = this.hls.config;
  18530. const Loader = config.loader;
  18531. if (this.loader) {
  18532. this.loader.destroy();
  18533. }
  18534. this.loader = new Loader(config);
  18535. let url;
  18536. try {
  18537. url = new self.URL(uri);
  18538. } catch (error) {
  18539. this.enabled = false;
  18540. this.log(`Failed to parse Steering Manifest URI: ${uri}`);
  18541. return;
  18542. }
  18543. if (url.protocol !== "data:") {
  18544. const throughput = (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;
  18545. url.searchParams.set("_HLS_pathway", this.pathwayId);
  18546. url.searchParams.set("_HLS_throughput", "" + throughput);
  18547. }
  18548. const context = {
  18549. responseType: "json",
  18550. url: url.href
  18551. };
  18552. const loadPolicy = config.steeringManifestLoadPolicy.default;
  18553. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  18554. const loaderConfig = {
  18555. loadPolicy,
  18556. timeout: loadPolicy.maxLoadTimeMs,
  18557. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  18558. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  18559. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  18560. };
  18561. const callbacks = {
  18562. onSuccess: (response, stats, context2, networkDetails) => {
  18563. this.log(`Loaded steering manifest: "${url}"`);
  18564. const steeringData = response.data;
  18565. if ((steeringData == null ? void 0 : steeringData.VERSION) !== 1) {
  18566. this.log(`Steering VERSION ${steeringData.VERSION} not supported!`);
  18567. return;
  18568. }
  18569. this.updated = performance.now();
  18570. this.timeToLoad = steeringData.TTL;
  18571. const {
  18572. "RELOAD-URI": reloadUri,
  18573. "PATHWAY-CLONES": pathwayClones,
  18574. "PATHWAY-PRIORITY": pathwayPriority
  18575. } = steeringData;
  18576. if (reloadUri) {
  18577. try {
  18578. this.uri = new self.URL(reloadUri, url).href;
  18579. } catch (error) {
  18580. this.enabled = false;
  18581. this.log(`Failed to parse Steering Manifest RELOAD-URI: ${reloadUri}`);
  18582. return;
  18583. }
  18584. }
  18585. this.scheduleRefresh(this.uri || context2.url);
  18586. if (pathwayClones) {
  18587. this.clonePathways(pathwayClones);
  18588. }
  18589. const loadedSteeringData = {
  18590. steeringManifest: steeringData,
  18591. url: url.toString()
  18592. };
  18593. this.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);
  18594. if (pathwayPriority) {
  18595. this.updatePathwayPriority(pathwayPriority);
  18596. }
  18597. },
  18598. onError: (error, context2, networkDetails, stats) => {
  18599. this.log(`Error loading steering manifest: ${error.code} ${error.text} (${context2.url})`);
  18600. this.stopLoad();
  18601. if (error.code === 410) {
  18602. this.enabled = false;
  18603. this.log(`Steering manifest ${context2.url} no longer available`);
  18604. return;
  18605. }
  18606. let ttl = this.timeToLoad * 1e3;
  18607. if (error.code === 429) {
  18608. const loader = this.loader;
  18609. if (typeof (loader == null ? void 0 : loader.getResponseHeader) === "function") {
  18610. const retryAfter = loader.getResponseHeader("Retry-After");
  18611. if (retryAfter) {
  18612. ttl = parseFloat(retryAfter) * 1e3;
  18613. }
  18614. }
  18615. this.log(`Steering manifest ${context2.url} rate limited`);
  18616. return;
  18617. }
  18618. this.scheduleRefresh(this.uri || context2.url, ttl);
  18619. },
  18620. onTimeout: (stats, context2, networkDetails) => {
  18621. this.log(`Timeout loading steering manifest (${context2.url})`);
  18622. this.scheduleRefresh(this.uri || context2.url);
  18623. }
  18624. };
  18625. this.log(`Requesting steering manifest: ${url}`);
  18626. this.loader.load(context, loaderConfig, callbacks);
  18627. }
  18628. scheduleRefresh(uri, ttlMs = this.timeToLoad * 1e3) {
  18629. this.clearTimeout();
  18630. this.reloadTimer = self.setTimeout(() => {
  18631. var _this$hls;
  18632. const media = (_this$hls = this.hls) == null ? void 0 : _this$hls.media;
  18633. if (media && !media.ended) {
  18634. this.loadSteeringManifest(uri);
  18635. return;
  18636. }
  18637. this.scheduleRefresh(uri, this.timeToLoad * 1e3);
  18638. }, ttlMs);
  18639. }
  18640. };
  18641. function cloneRenditionGroups(tracks, groupCloneMap, uriReplacement, cloneId) {
  18642. if (!tracks) {
  18643. return;
  18644. }
  18645. Object.keys(groupCloneMap).forEach((audioGroupId) => {
  18646. const clonedTracks = tracks.filter((track) => track.groupId === audioGroupId).map((track) => {
  18647. const clonedTrack = _extends({}, track);
  18648. clonedTrack.details = void 0;
  18649. clonedTrack.attrs = new AttrList(clonedTrack.attrs);
  18650. clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(track.url, track.attrs["STABLE-RENDITION-ID"], "PER-RENDITION-URIS", uriReplacement);
  18651. clonedTrack.groupId = clonedTrack.attrs["GROUP-ID"] = groupCloneMap[audioGroupId];
  18652. clonedTrack.attrs["PATHWAY-ID"] = cloneId;
  18653. return clonedTrack;
  18654. });
  18655. tracks.push(...clonedTracks);
  18656. });
  18657. }
  18658. function performUriReplacement(uri, stableId, perOptionKey, uriReplacement) {
  18659. const {
  18660. HOST: host,
  18661. PARAMS: params,
  18662. [perOptionKey]: perOptionUris
  18663. } = uriReplacement;
  18664. let perVariantUri;
  18665. if (stableId) {
  18666. perVariantUri = perOptionUris == null ? void 0 : perOptionUris[stableId];
  18667. if (perVariantUri) {
  18668. uri = perVariantUri;
  18669. }
  18670. }
  18671. const url = new self.URL(uri);
  18672. if (host && !perVariantUri) {
  18673. url.host = host;
  18674. }
  18675. if (params) {
  18676. Object.keys(params).sort().forEach((key) => {
  18677. if (key) {
  18678. url.searchParams.set(key, params[key]);
  18679. }
  18680. });
  18681. }
  18682. return url.href;
  18683. }
  18684. function addEventListener(el, type, listener) {
  18685. removeEventListener(el, type, listener);
  18686. el.addEventListener(type, listener);
  18687. }
  18688. function removeEventListener(el, type, listener) {
  18689. el.removeEventListener(type, listener);
  18690. }
  18691. var EMEController = class extends Logger {
  18692. constructor(hls) {
  18693. super("eme", hls.logger);
  18694. this.hls = void 0;
  18695. this.config = void 0;
  18696. this.media = null;
  18697. this.keyFormatPromise = null;
  18698. this.keySystemAccessPromises = {};
  18699. this._requestLicenseFailureCount = 0;
  18700. this.mediaKeySessions = [];
  18701. this.keyIdToKeySessionPromise = {};
  18702. this.mediaKeys = null;
  18703. this.setMediaKeysQueue = EMEController.CDMCleanupPromise ? [EMEController.CDMCleanupPromise] : [];
  18704. this.onWaitingForKey = (event) => {
  18705. this.log(`"${event.type}" event`);
  18706. };
  18707. this.hls = hls;
  18708. this.config = hls.config;
  18709. this.registerListeners();
  18710. }
  18711. destroy() {
  18712. this.onDestroying();
  18713. this.onMediaDetached();
  18714. const config = this.config;
  18715. config.requestMediaKeySystemAccessFunc = null;
  18716. config.licenseXhrSetup = config.licenseResponseCallback = void 0;
  18717. config.drmSystems = config.drmSystemOptions = {};
  18718. this.hls = this.config = this.keyIdToKeySessionPromise = null;
  18719. this.onWaitingForKey = null;
  18720. }
  18721. registerListeners() {
  18722. this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18723. this.hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  18724. this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18725. this.hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  18726. this.hls.on(Events.DESTROYING, this.onDestroying, this);
  18727. }
  18728. unregisterListeners() {
  18729. this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18730. this.hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  18731. this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18732. this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  18733. this.hls.off(Events.DESTROYING, this.onDestroying, this);
  18734. }
  18735. getLicenseServerUrl(keySystem) {
  18736. const {
  18737. drmSystems,
  18738. widevineLicenseUrl
  18739. } = this.config;
  18740. const keySystemConfiguration = drmSystems[keySystem];
  18741. if (keySystemConfiguration) {
  18742. return keySystemConfiguration.licenseUrl;
  18743. }
  18744. if (keySystem === KeySystems.WIDEVINE && widevineLicenseUrl) {
  18745. return widevineLicenseUrl;
  18746. }
  18747. }
  18748. getLicenseServerUrlOrThrow(keySystem) {
  18749. const url = this.getLicenseServerUrl(keySystem);
  18750. if (url === void 0) {
  18751. throw new Error(`no license server URL configured for key-system "${keySystem}"`);
  18752. }
  18753. return url;
  18754. }
  18755. getServerCertificateUrl(keySystem) {
  18756. const {
  18757. drmSystems
  18758. } = this.config;
  18759. const keySystemConfiguration = drmSystems[keySystem];
  18760. if (keySystemConfiguration) {
  18761. return keySystemConfiguration.serverCertificateUrl;
  18762. } else {
  18763. this.log(`No Server Certificate in config.drmSystems["${keySystem}"]`);
  18764. }
  18765. }
  18766. attemptKeySystemAccess(keySystemsToAttempt) {
  18767. const levels = this.hls.levels;
  18768. const uniqueCodec = (value, i, a) => !!value && a.indexOf(value) === i;
  18769. const audioCodecs = levels.map((level) => level.audioCodec).filter(uniqueCodec);
  18770. const videoCodecs = levels.map((level) => level.videoCodec).filter(uniqueCodec);
  18771. if (audioCodecs.length + videoCodecs.length === 0) {
  18772. videoCodecs.push("avc1.42e01e");
  18773. }
  18774. return new Promise((resolve, reject) => {
  18775. const attempt = (keySystems) => {
  18776. const keySystem = keySystems.shift();
  18777. this.getMediaKeysPromise(keySystem, audioCodecs, videoCodecs).then((mediaKeys) => resolve({
  18778. keySystem,
  18779. mediaKeys
  18780. })).catch((error) => {
  18781. if (keySystems.length) {
  18782. attempt(keySystems);
  18783. } else if (error instanceof EMEKeyError) {
  18784. reject(error);
  18785. } else {
  18786. reject(new EMEKeyError({
  18787. type: ErrorTypes.KEY_SYSTEM_ERROR,
  18788. details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,
  18789. error,
  18790. fatal: true
  18791. }, error.message));
  18792. }
  18793. });
  18794. };
  18795. attempt(keySystemsToAttempt);
  18796. });
  18797. }
  18798. requestMediaKeySystemAccess(keySystem, supportedConfigurations) {
  18799. const {
  18800. requestMediaKeySystemAccessFunc
  18801. } = this.config;
  18802. if (!(typeof requestMediaKeySystemAccessFunc === "function")) {
  18803. let errMessage = `Configured requestMediaKeySystemAccess is not a function ${requestMediaKeySystemAccessFunc}`;
  18804. if (requestMediaKeySystemAccess === null && self.location.protocol === "http:") {
  18805. errMessage = `navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`;
  18806. }
  18807. return Promise.reject(new Error(errMessage));
  18808. }
  18809. return requestMediaKeySystemAccessFunc(keySystem, supportedConfigurations);
  18810. }
  18811. getMediaKeysPromise(keySystem, audioCodecs, videoCodecs) {
  18812. const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this.config.drmSystemOptions);
  18813. const keySystemAccessPromises = this.keySystemAccessPromises[keySystem];
  18814. let keySystemAccess = keySystemAccessPromises == null ? void 0 : keySystemAccessPromises.keySystemAccess;
  18815. if (!keySystemAccess) {
  18816. this.log(`Requesting encrypted media "${keySystem}" key-system access with config: ${stringify(mediaKeySystemConfigs)}`);
  18817. keySystemAccess = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);
  18818. const _keySystemAccessPromises = this.keySystemAccessPromises[keySystem] = {
  18819. keySystemAccess
  18820. };
  18821. keySystemAccess.catch((error) => {
  18822. this.log(`Failed to obtain access to key-system "${keySystem}": ${error}`);
  18823. });
  18824. return keySystemAccess.then((mediaKeySystemAccess) => {
  18825. this.log(`Access for key-system "${mediaKeySystemAccess.keySystem}" obtained`);
  18826. const certificateRequest = this.fetchServerCertificate(keySystem);
  18827. this.log(`Create media-keys for "${keySystem}"`);
  18828. _keySystemAccessPromises.mediaKeys = mediaKeySystemAccess.createMediaKeys().then((mediaKeys) => {
  18829. this.log(`Media-keys created for "${keySystem}"`);
  18830. _keySystemAccessPromises.hasMediaKeys = true;
  18831. return certificateRequest.then((certificate) => {
  18832. if (certificate) {
  18833. return this.setMediaKeysServerCertificate(mediaKeys, keySystem, certificate);
  18834. }
  18835. return mediaKeys;
  18836. });
  18837. });
  18838. _keySystemAccessPromises.mediaKeys.catch((error) => {
  18839. this.error(`Failed to create media-keys for "${keySystem}"}: ${error}`);
  18840. });
  18841. return _keySystemAccessPromises.mediaKeys;
  18842. });
  18843. }
  18844. return keySystemAccess.then(() => keySystemAccessPromises.mediaKeys);
  18845. }
  18846. createMediaKeySessionContext({
  18847. decryptdata,
  18848. keySystem,
  18849. mediaKeys
  18850. }) {
  18851. this.log(`Creating key-system session "${keySystem}" keyId: ${Hex.hexDump(decryptdata.keyId || [])}`);
  18852. const mediaKeysSession = mediaKeys.createSession();
  18853. const mediaKeySessionContext = {
  18854. decryptdata,
  18855. keySystem,
  18856. mediaKeys,
  18857. mediaKeysSession,
  18858. keyStatus: "status-pending"
  18859. };
  18860. this.mediaKeySessions.push(mediaKeySessionContext);
  18861. return mediaKeySessionContext;
  18862. }
  18863. renewKeySession(mediaKeySessionContext) {
  18864. const decryptdata = mediaKeySessionContext.decryptdata;
  18865. if (decryptdata.pssh) {
  18866. const keySessionContext = this.createMediaKeySessionContext(mediaKeySessionContext);
  18867. const keyId = this.getKeyIdString(decryptdata);
  18868. const scheme = "cenc";
  18869. this.keyIdToKeySessionPromise[keyId] = this.generateRequestWithPreferredKeySession(keySessionContext, scheme, decryptdata.pssh.buffer, "expired");
  18870. } else {
  18871. this.warn(`Could not renew expired session. Missing pssh initData.`);
  18872. }
  18873. this.removeSession(mediaKeySessionContext);
  18874. }
  18875. getKeyIdString(decryptdata) {
  18876. if (!decryptdata) {
  18877. throw new Error("Could not read keyId of undefined decryptdata");
  18878. }
  18879. if (decryptdata.keyId === null) {
  18880. throw new Error("keyId is null");
  18881. }
  18882. return Hex.hexDump(decryptdata.keyId);
  18883. }
  18884. updateKeySession(mediaKeySessionContext, data) {
  18885. var _mediaKeySessionConte;
  18886. const keySession = mediaKeySessionContext.mediaKeysSession;
  18887. this.log(`Updating key-session "${keySession.sessionId}" for keyID ${Hex.hexDump(((_mediaKeySessionConte = mediaKeySessionContext.decryptdata) == null ? void 0 : _mediaKeySessionConte.keyId) || [])}
  18888. } (data length: ${data ? data.byteLength : data})`);
  18889. return keySession.update(data);
  18890. }
  18891. getSelectedKeySystemFormats() {
  18892. return Object.keys(this.keySystemAccessPromises).map((keySystem) => ({
  18893. keySystem,
  18894. hasMediaKeys: this.keySystemAccessPromises[keySystem].hasMediaKeys
  18895. })).filter(({
  18896. hasMediaKeys
  18897. }) => !!hasMediaKeys).map(({
  18898. keySystem
  18899. }) => keySystemDomainToKeySystemFormat(keySystem)).filter((keySystem) => !!keySystem);
  18900. }
  18901. getKeySystemAccess(keySystemsToAttempt) {
  18902. return this.getKeySystemSelectionPromise(keySystemsToAttempt).then(({
  18903. keySystem,
  18904. mediaKeys
  18905. }) => {
  18906. return this.attemptSetMediaKeys(keySystem, mediaKeys);
  18907. });
  18908. }
  18909. selectKeySystem(keySystemsToAttempt) {
  18910. return new Promise((resolve, reject) => {
  18911. return this.getKeySystemSelectionPromise(keySystemsToAttempt).then(({
  18912. keySystem
  18913. }) => {
  18914. const keySystemFormat = keySystemDomainToKeySystemFormat(keySystem);
  18915. if (keySystemFormat) {
  18916. resolve(keySystemFormat);
  18917. } else {
  18918. reject(new Error(`Unable to find format for key-system "${keySystem}"`));
  18919. }
  18920. }).catch(reject);
  18921. });
  18922. }
  18923. selectKeySystemFormat(frag) {
  18924. const keyFormats = Object.keys(frag.levelkeys || {});
  18925. if (!this.keyFormatPromise) {
  18926. this.log(`Selecting key-system from fragment (sn: ${frag.sn} ${frag.type}: ${frag.level}) key formats ${keyFormats.join(", ")}`);
  18927. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  18928. }
  18929. return this.keyFormatPromise;
  18930. }
  18931. getKeyFormatPromise(keyFormats) {
  18932. const keySystemsInConfig = getKeySystemsForConfig(this.config);
  18933. const keySystemsToAttempt = keyFormats.map(keySystemFormatToKeySystemDomain).filter((value) => !!value && keySystemsInConfig.indexOf(value) !== -1);
  18934. return this.selectKeySystem(keySystemsToAttempt);
  18935. }
  18936. loadKey(data) {
  18937. const decryptdata = data.keyInfo.decryptdata;
  18938. const keyId = this.getKeyIdString(decryptdata);
  18939. const keyDetails = `(keyId: ${keyId} format: "${decryptdata.keyFormat}" method: ${decryptdata.method} uri: ${decryptdata.uri})`;
  18940. this.log(`Starting session for key ${keyDetails}`);
  18941. let keyContextPromise = this.keyIdToKeySessionPromise[keyId];
  18942. if (!keyContextPromise) {
  18943. keyContextPromise = this.getKeySystemForKeyPromise(decryptdata).then(({
  18944. keySystem,
  18945. mediaKeys
  18946. }) => {
  18947. this.throwIfDestroyed();
  18948. this.log(`Handle encrypted media sn: ${data.frag.sn} ${data.frag.type}: ${data.frag.level} using key ${keyDetails}`);
  18949. return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => {
  18950. this.throwIfDestroyed();
  18951. return this.createMediaKeySessionContext({
  18952. keySystem,
  18953. mediaKeys,
  18954. decryptdata
  18955. });
  18956. });
  18957. });
  18958. const keySessionContextPromise = this.keyIdToKeySessionPromise[keyId] = keyContextPromise.then((keySessionContext) => {
  18959. const scheme = "cenc";
  18960. const initData = decryptdata.pssh ? decryptdata.pssh.buffer : null;
  18961. return this.generateRequestWithPreferredKeySession(keySessionContext, scheme, initData, "playlist-key");
  18962. });
  18963. keySessionContextPromise.catch((error) => this.handleError(error));
  18964. }
  18965. return keyContextPromise;
  18966. }
  18967. throwIfDestroyed(message = "Invalid state") {
  18968. if (!this.hls) {
  18969. throw new Error("invalid state");
  18970. }
  18971. }
  18972. handleError(error) {
  18973. if (!this.hls) {
  18974. return;
  18975. }
  18976. this.error(error.message);
  18977. if (error instanceof EMEKeyError) {
  18978. this.hls.trigger(Events.ERROR, error.data);
  18979. } else {
  18980. this.hls.trigger(Events.ERROR, {
  18981. type: ErrorTypes.KEY_SYSTEM_ERROR,
  18982. details: ErrorDetails.KEY_SYSTEM_NO_KEYS,
  18983. error,
  18984. fatal: true
  18985. });
  18986. }
  18987. }
  18988. getKeySystemForKeyPromise(decryptdata) {
  18989. const keyId = this.getKeyIdString(decryptdata);
  18990. const mediaKeySessionContext = this.keyIdToKeySessionPromise[keyId];
  18991. if (!mediaKeySessionContext) {
  18992. const keySystem = keySystemFormatToKeySystemDomain(decryptdata.keyFormat);
  18993. const keySystemsToAttempt = keySystem ? [keySystem] : getKeySystemsForConfig(this.config);
  18994. return this.attemptKeySystemAccess(keySystemsToAttempt);
  18995. }
  18996. return mediaKeySessionContext;
  18997. }
  18998. getKeySystemSelectionPromise(keySystemsToAttempt) {
  18999. if (!keySystemsToAttempt.length) {
  19000. keySystemsToAttempt = getKeySystemsForConfig(this.config);
  19001. }
  19002. if (keySystemsToAttempt.length === 0) {
  19003. throw new EMEKeyError({
  19004. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19005. details: ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,
  19006. fatal: true
  19007. }, `Missing key-system license configuration options ${stringify({
  19008. drmSystems: this.config.drmSystems
  19009. })}`);
  19010. }
  19011. return this.attemptKeySystemAccess(keySystemsToAttempt);
  19012. }
  19013. attemptSetMediaKeys(keySystem, mediaKeys) {
  19014. if (this.mediaKeys === mediaKeys) {
  19015. return Promise.resolve();
  19016. }
  19017. const queue = this.setMediaKeysQueue.slice();
  19018. this.log(`Setting media-keys for "${keySystem}"`);
  19019. const setMediaKeysPromise = Promise.all(queue).then(() => {
  19020. if (!this.media) {
  19021. this.mediaKeys = null;
  19022. throw new Error("Attempted to set mediaKeys without media element attached");
  19023. }
  19024. return this.media.setMediaKeys(mediaKeys);
  19025. });
  19026. this.mediaKeys = mediaKeys;
  19027. this.setMediaKeysQueue.push(setMediaKeysPromise);
  19028. return setMediaKeysPromise.then(() => {
  19029. this.log(`Media-keys set for "${keySystem}"`);
  19030. queue.push(setMediaKeysPromise);
  19031. this.setMediaKeysQueue = this.setMediaKeysQueue.filter((p) => queue.indexOf(p) === -1);
  19032. });
  19033. }
  19034. generateRequestWithPreferredKeySession(context, initDataType, initData, reason) {
  19035. var _this$config$drmSyste, _this$config$drmSyste2;
  19036. 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;
  19037. if (generateRequestFilter) {
  19038. try {
  19039. const mappedInitData = generateRequestFilter.call(this.hls, initDataType, initData, context);
  19040. if (!mappedInitData) {
  19041. throw new Error("Invalid response from configured generateRequest filter");
  19042. }
  19043. initDataType = mappedInitData.initDataType;
  19044. initData = mappedInitData.initData ? mappedInitData.initData : null;
  19045. context.decryptdata.pssh = initData ? new Uint8Array(initData) : null;
  19046. } catch (error) {
  19047. var _this$hls;
  19048. this.warn(error.message);
  19049. if ((_this$hls = this.hls) != null && _this$hls.config.debug) {
  19050. throw error;
  19051. }
  19052. }
  19053. }
  19054. if (initData === null) {
  19055. this.log(`Skipping key-session request for "${reason}" (no initData)`);
  19056. return Promise.resolve(context);
  19057. }
  19058. const keyId = this.getKeyIdString(context.decryptdata);
  19059. this.log(`Generating key-session request for "${reason}": ${keyId} (init data type: ${initDataType} length: ${initData ? initData.byteLength : null})`);
  19060. const licenseStatus = new EventEmitter();
  19061. const onmessage = context._onmessage = (event) => {
  19062. const keySession = context.mediaKeysSession;
  19063. if (!keySession) {
  19064. licenseStatus.emit("error", new Error("invalid state"));
  19065. return;
  19066. }
  19067. const {
  19068. messageType,
  19069. message
  19070. } = event;
  19071. this.log(`"${messageType}" message event for session "${keySession.sessionId}" message size: ${message.byteLength}`);
  19072. if (messageType === "license-request" || messageType === "license-renewal") {
  19073. this.renewLicense(context, message).catch((error) => {
  19074. if (licenseStatus.eventNames().length) {
  19075. licenseStatus.emit("error", error);
  19076. } else {
  19077. this.handleError(error);
  19078. }
  19079. });
  19080. } else if (messageType === "license-release") {
  19081. if (context.keySystem === KeySystems.FAIRPLAY) {
  19082. this.updateKeySession(context, strToUtf8array("acknowledged"));
  19083. this.removeSession(context);
  19084. }
  19085. } else {
  19086. this.warn(`unhandled media key message type "${messageType}"`);
  19087. }
  19088. };
  19089. const onkeystatuseschange = context._onkeystatuseschange = (event) => {
  19090. const keySession = context.mediaKeysSession;
  19091. if (!keySession) {
  19092. licenseStatus.emit("error", new Error("invalid state"));
  19093. return;
  19094. }
  19095. this.onKeyStatusChange(context);
  19096. const keyStatus = context.keyStatus;
  19097. licenseStatus.emit("keyStatus", keyStatus);
  19098. if (keyStatus === "expired") {
  19099. this.warn(`${context.keySystem} expired for key ${keyId}`);
  19100. this.renewKeySession(context);
  19101. }
  19102. };
  19103. addEventListener(context.mediaKeysSession, "message", onmessage);
  19104. addEventListener(context.mediaKeysSession, "keystatuseschange", onkeystatuseschange);
  19105. const keyUsablePromise = new Promise((resolve, reject) => {
  19106. licenseStatus.on("error", reject);
  19107. licenseStatus.on("keyStatus", (keyStatus) => {
  19108. if (keyStatus.startsWith("usable")) {
  19109. resolve();
  19110. } else if (keyStatus === "output-restricted") {
  19111. reject(new EMEKeyError({
  19112. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19113. details: ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,
  19114. fatal: false
  19115. }, "HDCP level output restricted"));
  19116. } else if (keyStatus === "internal-error") {
  19117. reject(new EMEKeyError({
  19118. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19119. details: ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR,
  19120. fatal: true
  19121. }, `key status changed to "${keyStatus}"`));
  19122. } else if (keyStatus === "expired") {
  19123. reject(new Error("key expired while generating request"));
  19124. } else {
  19125. this.warn(`unhandled key status change "${keyStatus}"`);
  19126. }
  19127. });
  19128. });
  19129. return context.mediaKeysSession.generateRequest(initDataType, initData).then(() => {
  19130. var _context$mediaKeysSes;
  19131. this.log(`Request generated for key-session "${(_context$mediaKeysSes = context.mediaKeysSession) == null ? void 0 : _context$mediaKeysSes.sessionId}" keyId: ${keyId}`);
  19132. }).catch((error) => {
  19133. throw new EMEKeyError({
  19134. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19135. details: ErrorDetails.KEY_SYSTEM_NO_SESSION,
  19136. error,
  19137. fatal: false
  19138. }, `Error generating key-session request: ${error}`);
  19139. }).then(() => keyUsablePromise).catch((error) => {
  19140. licenseStatus.removeAllListeners();
  19141. this.removeSession(context);
  19142. throw error;
  19143. }).then(() => {
  19144. licenseStatus.removeAllListeners();
  19145. return context;
  19146. });
  19147. }
  19148. onKeyStatusChange(mediaKeySessionContext) {
  19149. mediaKeySessionContext.mediaKeysSession.keyStatuses.forEach((status2, keyId) => {
  19150. if (typeof keyId === "string" && typeof status2 === "object") {
  19151. const temp = keyId;
  19152. keyId = status2;
  19153. status2 = temp;
  19154. }
  19155. 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}`);
  19156. mediaKeySessionContext.keyStatus = status2;
  19157. });
  19158. }
  19159. fetchServerCertificate(keySystem) {
  19160. const config = this.config;
  19161. const Loader = config.loader;
  19162. const certLoader = new Loader(config);
  19163. const url = this.getServerCertificateUrl(keySystem);
  19164. if (!url) {
  19165. return Promise.resolve();
  19166. }
  19167. this.log(`Fetching server certificate for "${keySystem}"`);
  19168. return new Promise((resolve, reject) => {
  19169. const loaderContext = {
  19170. responseType: "arraybuffer",
  19171. url
  19172. };
  19173. const loadPolicy = config.certLoadPolicy.default;
  19174. const loaderConfig = {
  19175. loadPolicy,
  19176. timeout: loadPolicy.maxLoadTimeMs,
  19177. maxRetry: 0,
  19178. retryDelay: 0,
  19179. maxRetryDelay: 0
  19180. };
  19181. const loaderCallbacks = {
  19182. onSuccess: (response, stats, context, networkDetails) => {
  19183. resolve(response.data);
  19184. },
  19185. onError: (response, contex, networkDetails, stats) => {
  19186. reject(new EMEKeyError({
  19187. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19188. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  19189. fatal: true,
  19190. networkDetails,
  19191. response: _objectSpread2({
  19192. url: loaderContext.url,
  19193. data: void 0
  19194. }, response)
  19195. }, `"${keySystem}" certificate request failed (${url}). Status: ${response.code} (${response.text})`));
  19196. },
  19197. onTimeout: (stats, context, networkDetails) => {
  19198. reject(new EMEKeyError({
  19199. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19200. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  19201. fatal: true,
  19202. networkDetails,
  19203. response: {
  19204. url: loaderContext.url,
  19205. data: void 0
  19206. }
  19207. }, `"${keySystem}" certificate request timed out (${url})`));
  19208. },
  19209. onAbort: (stats, context, networkDetails) => {
  19210. reject(new Error("aborted"));
  19211. }
  19212. };
  19213. certLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  19214. });
  19215. }
  19216. setMediaKeysServerCertificate(mediaKeys, keySystem, cert) {
  19217. return new Promise((resolve, reject) => {
  19218. mediaKeys.setServerCertificate(cert).then((success) => {
  19219. this.log(`setServerCertificate ${success ? "success" : "not supported by CDM"} (${cert == null ? void 0 : cert.byteLength}) on "${keySystem}"`);
  19220. resolve(mediaKeys);
  19221. }).catch((error) => {
  19222. reject(new EMEKeyError({
  19223. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19224. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,
  19225. error,
  19226. fatal: true
  19227. }, error.message));
  19228. });
  19229. });
  19230. }
  19231. renewLicense(context, keyMessage) {
  19232. return this.requestLicense(context, new Uint8Array(keyMessage)).then((data) => {
  19233. return this.updateKeySession(context, new Uint8Array(data)).catch((error) => {
  19234. throw new EMEKeyError({
  19235. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19236. details: ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,
  19237. error,
  19238. fatal: true
  19239. }, error.message);
  19240. });
  19241. });
  19242. }
  19243. unpackPlayReadyKeyMessage(xhr, licenseChallenge) {
  19244. const xmlString = String.fromCharCode.apply(null, new Uint16Array(licenseChallenge.buffer));
  19245. if (!xmlString.includes("PlayReadyKeyMessage")) {
  19246. xhr.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  19247. return licenseChallenge;
  19248. }
  19249. const keyMessageXml = new DOMParser().parseFromString(xmlString, "application/xml");
  19250. const headers = keyMessageXml.querySelectorAll("HttpHeader");
  19251. if (headers.length > 0) {
  19252. let header;
  19253. for (let i = 0, len = headers.length; i < len; i++) {
  19254. var _header$querySelector, _header$querySelector2;
  19255. header = headers[i];
  19256. const name = (_header$querySelector = header.querySelector("name")) == null ? void 0 : _header$querySelector.textContent;
  19257. const value = (_header$querySelector2 = header.querySelector("value")) == null ? void 0 : _header$querySelector2.textContent;
  19258. if (name && value) {
  19259. xhr.setRequestHeader(name, value);
  19260. }
  19261. }
  19262. }
  19263. const challengeElement = keyMessageXml.querySelector("Challenge");
  19264. const challengeText = challengeElement == null ? void 0 : challengeElement.textContent;
  19265. if (!challengeText) {
  19266. throw new Error(`Cannot find <Challenge> in key message`);
  19267. }
  19268. return strToUtf8array(atob(challengeText));
  19269. }
  19270. setupLicenseXHR(xhr, url, keysListItem, licenseChallenge) {
  19271. const licenseXhrSetup = this.config.licenseXhrSetup;
  19272. if (!licenseXhrSetup) {
  19273. xhr.open("POST", url, true);
  19274. return Promise.resolve({
  19275. xhr,
  19276. licenseChallenge
  19277. });
  19278. }
  19279. return Promise.resolve().then(() => {
  19280. if (!keysListItem.decryptdata) {
  19281. throw new Error("Key removed");
  19282. }
  19283. return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);
  19284. }).catch((error) => {
  19285. if (!keysListItem.decryptdata) {
  19286. throw error;
  19287. }
  19288. xhr.open("POST", url, true);
  19289. return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);
  19290. }).then((licenseXhrSetupResult) => {
  19291. if (!xhr.readyState) {
  19292. xhr.open("POST", url, true);
  19293. }
  19294. const finalLicenseChallenge = licenseXhrSetupResult ? licenseXhrSetupResult : licenseChallenge;
  19295. return {
  19296. xhr,
  19297. licenseChallenge: finalLicenseChallenge
  19298. };
  19299. });
  19300. }
  19301. requestLicense(keySessionContext, licenseChallenge) {
  19302. const keyLoadPolicy = this.config.keyLoadPolicy.default;
  19303. return new Promise((resolve, reject) => {
  19304. const url = this.getLicenseServerUrlOrThrow(keySessionContext.keySystem);
  19305. this.log(`Sending license request to URL: ${url}`);
  19306. const xhr = new XMLHttpRequest();
  19307. xhr.responseType = "arraybuffer";
  19308. xhr.onreadystatechange = () => {
  19309. if (!this.hls || !keySessionContext.mediaKeysSession) {
  19310. return reject(new Error("invalid state"));
  19311. }
  19312. if (xhr.readyState === 4) {
  19313. if (xhr.status === 200) {
  19314. this._requestLicenseFailureCount = 0;
  19315. let data = xhr.response;
  19316. this.log(`License received ${data instanceof ArrayBuffer ? data.byteLength : data}`);
  19317. const licenseResponseCallback = this.config.licenseResponseCallback;
  19318. if (licenseResponseCallback) {
  19319. try {
  19320. data = licenseResponseCallback.call(this.hls, xhr, url, keySessionContext);
  19321. } catch (error) {
  19322. this.error(error);
  19323. }
  19324. }
  19325. resolve(data);
  19326. } else {
  19327. const retryConfig = keyLoadPolicy.errorRetry;
  19328. const maxNumRetry = retryConfig ? retryConfig.maxNumRetry : 0;
  19329. this._requestLicenseFailureCount++;
  19330. if (this._requestLicenseFailureCount > maxNumRetry || xhr.status >= 400 && xhr.status < 500) {
  19331. reject(new EMEKeyError({
  19332. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19333. details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  19334. fatal: true,
  19335. networkDetails: xhr,
  19336. response: {
  19337. url,
  19338. data: void 0,
  19339. code: xhr.status,
  19340. text: xhr.statusText
  19341. }
  19342. }, `License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`));
  19343. } else {
  19344. const attemptsLeft = maxNumRetry - this._requestLicenseFailureCount + 1;
  19345. this.warn(`Retrying license request, ${attemptsLeft} attempts left`);
  19346. this.requestLicense(keySessionContext, licenseChallenge).then(resolve, reject);
  19347. }
  19348. }
  19349. }
  19350. };
  19351. if (keySessionContext.licenseXhr && keySessionContext.licenseXhr.readyState !== XMLHttpRequest.DONE) {
  19352. keySessionContext.licenseXhr.abort();
  19353. }
  19354. keySessionContext.licenseXhr = xhr;
  19355. this.setupLicenseXHR(xhr, url, keySessionContext, licenseChallenge).then(({
  19356. xhr: xhr2,
  19357. licenseChallenge: licenseChallenge2
  19358. }) => {
  19359. if (keySessionContext.keySystem == KeySystems.PLAYREADY) {
  19360. licenseChallenge2 = this.unpackPlayReadyKeyMessage(xhr2, licenseChallenge2);
  19361. }
  19362. xhr2.send(licenseChallenge2);
  19363. });
  19364. });
  19365. }
  19366. onDestroying() {
  19367. this.unregisterListeners();
  19368. this._clear();
  19369. }
  19370. onMediaAttached(event, data) {
  19371. if (!this.config.emeEnabled) {
  19372. return;
  19373. }
  19374. const media = data.media;
  19375. this.media = media;
  19376. addEventListener(media, "waitingforkey", this.onWaitingForKey);
  19377. }
  19378. onMediaDetached() {
  19379. const media = this.media;
  19380. if (media) {
  19381. removeEventListener(media, "waitingforkey", this.onWaitingForKey);
  19382. this.media = null;
  19383. this.mediaKeys = null;
  19384. }
  19385. }
  19386. _clear() {
  19387. var _media$setMediaKeys;
  19388. this._requestLicenseFailureCount = 0;
  19389. this.keyIdToKeySessionPromise = {};
  19390. if (!this.mediaKeys && !this.mediaKeySessions.length) {
  19391. return;
  19392. }
  19393. const media = this.media;
  19394. const mediaKeysList = this.mediaKeySessions.slice();
  19395. this.mediaKeySessions = [];
  19396. this.mediaKeys = null;
  19397. LevelKey.clearKeyUriToKeyIdMap();
  19398. const keySessionCount = mediaKeysList.length;
  19399. 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) => {
  19400. var _this$hls2;
  19401. this.log(`Could not clear media keys: ${error}`);
  19402. (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.trigger(Events.ERROR, {
  19403. type: ErrorTypes.OTHER_ERROR,
  19404. details: ErrorDetails.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,
  19405. fatal: false,
  19406. error: new Error(`Could not clear media keys: ${error}`)
  19407. });
  19408. }))).catch((error) => {
  19409. var _this$hls3;
  19410. this.log(`Could not close sessions and clear media keys: ${error}`);
  19411. (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.trigger(Events.ERROR, {
  19412. type: ErrorTypes.OTHER_ERROR,
  19413. details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
  19414. fatal: false,
  19415. error: new Error(`Could not close sessions and clear media keys: ${error}`)
  19416. });
  19417. }).then(() => {
  19418. if (keySessionCount) {
  19419. this.log("finished closing key sessions and clearing media keys");
  19420. }
  19421. });
  19422. }
  19423. onManifestLoading() {
  19424. this.keyFormatPromise = null;
  19425. }
  19426. onManifestLoaded(event, {
  19427. sessionKeys
  19428. }) {
  19429. if (!sessionKeys || !this.config.emeEnabled) {
  19430. return;
  19431. }
  19432. if (!this.keyFormatPromise) {
  19433. const keyFormats = sessionKeys.reduce((formats, sessionKey) => {
  19434. if (formats.indexOf(sessionKey.keyFormat) === -1) {
  19435. formats.push(sessionKey.keyFormat);
  19436. }
  19437. return formats;
  19438. }, []);
  19439. this.log(`Selecting key-system from session-keys ${keyFormats.join(", ")}`);
  19440. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  19441. }
  19442. }
  19443. removeSession(mediaKeySessionContext) {
  19444. const {
  19445. mediaKeysSession,
  19446. licenseXhr
  19447. } = mediaKeySessionContext;
  19448. if (mediaKeysSession) {
  19449. this.log(`Remove licenses and keys and close session ${mediaKeysSession.sessionId}`);
  19450. if (mediaKeySessionContext._onmessage) {
  19451. mediaKeysSession.removeEventListener("message", mediaKeySessionContext._onmessage);
  19452. mediaKeySessionContext._onmessage = void 0;
  19453. }
  19454. if (mediaKeySessionContext._onkeystatuseschange) {
  19455. mediaKeysSession.removeEventListener("keystatuseschange", mediaKeySessionContext._onkeystatuseschange);
  19456. mediaKeySessionContext._onkeystatuseschange = void 0;
  19457. }
  19458. if (licenseXhr && licenseXhr.readyState !== XMLHttpRequest.DONE) {
  19459. licenseXhr.abort();
  19460. }
  19461. mediaKeySessionContext.mediaKeysSession = mediaKeySessionContext.decryptdata = mediaKeySessionContext.licenseXhr = void 0;
  19462. const index = this.mediaKeySessions.indexOf(mediaKeySessionContext);
  19463. if (index > -1) {
  19464. this.mediaKeySessions.splice(index, 1);
  19465. }
  19466. const {
  19467. drmSystemOptions
  19468. } = this.config;
  19469. const removePromise = isPersistentSessionType(drmSystemOptions) ? new Promise((resolve, reject) => {
  19470. self.setTimeout(() => reject(new Error(`MediaKeySession.remove() timeout`)), 8e3);
  19471. mediaKeysSession.remove().then(resolve);
  19472. }) : Promise.resolve();
  19473. return removePromise.catch((error) => {
  19474. var _this$hls4;
  19475. this.log(`Could not remove session: ${error}`);
  19476. (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.trigger(Events.ERROR, {
  19477. type: ErrorTypes.OTHER_ERROR,
  19478. details: ErrorDetails.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,
  19479. fatal: false,
  19480. error: new Error(`Could not remove session: ${error}`)
  19481. });
  19482. }).then(() => {
  19483. return mediaKeysSession.close();
  19484. }).catch((error) => {
  19485. var _this$hls5;
  19486. this.log(`Could not close session: ${error}`);
  19487. (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.trigger(Events.ERROR, {
  19488. type: ErrorTypes.OTHER_ERROR,
  19489. details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
  19490. fatal: false,
  19491. error: new Error(`Could not close session: ${error}`)
  19492. });
  19493. });
  19494. }
  19495. }
  19496. };
  19497. EMEController.CDMCleanupPromise = void 0;
  19498. var EMEKeyError = class extends Error {
  19499. constructor(data, message) {
  19500. super(message);
  19501. this.data = void 0;
  19502. data.error || (data.error = new Error(message));
  19503. this.data = data;
  19504. data.err = data.error;
  19505. }
  19506. };
  19507. var FPSController = class {
  19508. constructor(hls) {
  19509. this.hls = void 0;
  19510. this.isVideoPlaybackQualityAvailable = false;
  19511. this.timer = void 0;
  19512. this.media = null;
  19513. this.lastTime = void 0;
  19514. this.lastDroppedFrames = 0;
  19515. this.lastDecodedFrames = 0;
  19516. this.streamController = void 0;
  19517. this.hls = hls;
  19518. this.registerListeners();
  19519. }
  19520. setStreamController(streamController) {
  19521. this.streamController = streamController;
  19522. }
  19523. registerListeners() {
  19524. this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  19525. this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  19526. }
  19527. unregisterListeners() {
  19528. this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  19529. this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  19530. }
  19531. destroy() {
  19532. if (this.timer) {
  19533. clearInterval(this.timer);
  19534. }
  19535. this.unregisterListeners();
  19536. this.isVideoPlaybackQualityAvailable = false;
  19537. this.media = null;
  19538. }
  19539. onMediaAttaching(event, data) {
  19540. const config = this.hls.config;
  19541. if (config.capLevelOnFPSDrop) {
  19542. const media = data.media instanceof self.HTMLVideoElement ? data.media : null;
  19543. this.media = media;
  19544. if (media && typeof media.getVideoPlaybackQuality === "function") {
  19545. this.isVideoPlaybackQualityAvailable = true;
  19546. }
  19547. self.clearInterval(this.timer);
  19548. this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  19549. }
  19550. }
  19551. onMediaDetaching() {
  19552. this.media = null;
  19553. }
  19554. checkFPS(video, decodedFrames, droppedFrames) {
  19555. const currentTime = performance.now();
  19556. if (decodedFrames) {
  19557. if (this.lastTime) {
  19558. const currentPeriod = currentTime - this.lastTime;
  19559. const currentDropped = droppedFrames - this.lastDroppedFrames;
  19560. const currentDecoded = decodedFrames - this.lastDecodedFrames;
  19561. const droppedFPS = 1e3 * currentDropped / currentPeriod;
  19562. const hls = this.hls;
  19563. hls.trigger(Events.FPS_DROP, {
  19564. currentDropped,
  19565. currentDecoded,
  19566. totalDroppedFrames: droppedFrames
  19567. });
  19568. if (droppedFPS > 0) {
  19569. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  19570. let currentLevel = hls.currentLevel;
  19571. hls.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: " + currentLevel);
  19572. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  19573. currentLevel = currentLevel - 1;
  19574. hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {
  19575. level: currentLevel,
  19576. droppedLevel: hls.currentLevel
  19577. });
  19578. hls.autoLevelCapping = currentLevel;
  19579. this.streamController.nextLevelSwitch();
  19580. }
  19581. }
  19582. }
  19583. }
  19584. this.lastTime = currentTime;
  19585. this.lastDroppedFrames = droppedFrames;
  19586. this.lastDecodedFrames = decodedFrames;
  19587. }
  19588. }
  19589. checkFPSInterval() {
  19590. const video = this.media;
  19591. if (video) {
  19592. if (this.isVideoPlaybackQualityAvailable) {
  19593. const videoPlaybackQuality = video.getVideoPlaybackQuality();
  19594. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  19595. } else {
  19596. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  19597. }
  19598. }
  19599. }
  19600. };
  19601. function sendAddTrackEvent(track, videoEl) {
  19602. let event;
  19603. try {
  19604. event = new Event("addtrack");
  19605. } catch (err) {
  19606. event = document.createEvent("Event");
  19607. event.initEvent("addtrack", false, false);
  19608. }
  19609. event.track = track;
  19610. videoEl.dispatchEvent(event);
  19611. }
  19612. function addCueToTrack(track, cue) {
  19613. const mode = track.mode;
  19614. if (mode === "disabled") {
  19615. track.mode = "hidden";
  19616. }
  19617. if (track.cues && !track.cues.getCueById(cue.id)) {
  19618. try {
  19619. track.addCue(cue);
  19620. if (!track.cues.getCueById(cue.id)) {
  19621. throw new Error(`addCue is failed for: ${cue}`);
  19622. }
  19623. } catch (err) {
  19624. logger.debug(`[texttrack-utils]: ${err}`);
  19625. try {
  19626. const textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);
  19627. textTrackCue.id = cue.id;
  19628. track.addCue(textTrackCue);
  19629. } catch (err2) {
  19630. logger.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${err2}`);
  19631. }
  19632. }
  19633. }
  19634. if (mode === "disabled") {
  19635. track.mode = mode;
  19636. }
  19637. }
  19638. function clearCurrentCues(track, enterHandler) {
  19639. const mode = track.mode;
  19640. if (mode === "disabled") {
  19641. track.mode = "hidden";
  19642. }
  19643. if (track.cues) {
  19644. for (let i = track.cues.length; i--; ) {
  19645. if (enterHandler) {
  19646. track.cues[i].removeEventListener("enter", enterHandler);
  19647. }
  19648. track.removeCue(track.cues[i]);
  19649. }
  19650. }
  19651. if (mode === "disabled") {
  19652. track.mode = mode;
  19653. }
  19654. }
  19655. function removeCuesInRange(track, start, end, predicate) {
  19656. const mode = track.mode;
  19657. if (mode === "disabled") {
  19658. track.mode = "hidden";
  19659. }
  19660. if (track.cues && track.cues.length > 0) {
  19661. const cues = getCuesInRange(track.cues, start, end);
  19662. for (let i = 0; i < cues.length; i++) {
  19663. if (!predicate || predicate(cues[i])) {
  19664. track.removeCue(cues[i]);
  19665. }
  19666. }
  19667. }
  19668. if (mode === "disabled") {
  19669. track.mode = mode;
  19670. }
  19671. }
  19672. function getFirstCueIndexFromTime(cues, time) {
  19673. if (time <= cues[0].startTime) {
  19674. return 0;
  19675. }
  19676. const len = cues.length - 1;
  19677. if (time > cues[len].endTime) {
  19678. return -1;
  19679. }
  19680. let left = 0;
  19681. let right = len;
  19682. let mid;
  19683. while (left <= right) {
  19684. mid = Math.floor((right + left) / 2);
  19685. if (time < cues[mid].startTime) {
  19686. right = mid - 1;
  19687. } else if (time > cues[mid].startTime && left < len) {
  19688. left = mid + 1;
  19689. } else {
  19690. return mid;
  19691. }
  19692. }
  19693. return cues[left].startTime - time < time - cues[right].startTime ? left : right;
  19694. }
  19695. function getCuesInRange(cues, start, end) {
  19696. const cuesFound = [];
  19697. const firstCueInRange = getFirstCueIndexFromTime(cues, start);
  19698. if (firstCueInRange > -1) {
  19699. for (let i = firstCueInRange, len = cues.length; i < len; i++) {
  19700. const cue = cues[i];
  19701. if (cue.startTime >= start && cue.endTime <= end) {
  19702. cuesFound.push(cue);
  19703. } else if (cue.startTime > end) {
  19704. return cuesFound;
  19705. }
  19706. }
  19707. }
  19708. return cuesFound;
  19709. }
  19710. function filterSubtitleTracks(textTrackList) {
  19711. const tracks = [];
  19712. for (let i = 0; i < textTrackList.length; i++) {
  19713. const track = textTrackList[i];
  19714. if ((track.kind === "subtitles" || track.kind === "captions") && track.label) {
  19715. tracks.push(textTrackList[i]);
  19716. }
  19717. }
  19718. return tracks;
  19719. }
  19720. var SubtitleTrackController = class extends BasePlaylistController {
  19721. constructor(hls) {
  19722. super(hls, "subtitle-track-controller");
  19723. this.media = null;
  19724. this.tracks = [];
  19725. this.groupIds = null;
  19726. this.tracksInGroup = [];
  19727. this.trackId = -1;
  19728. this.currentTrack = null;
  19729. this.selectDefaultTrack = true;
  19730. this.queuedDefaultTrack = -1;
  19731. this.useTextTrackPolling = false;
  19732. this.subtitlePollingInterval = -1;
  19733. this._subtitleDisplay = true;
  19734. this.asyncPollTrackChange = () => this.pollTrackChange(0);
  19735. this.onTextTracksChanged = () => {
  19736. if (!this.useTextTrackPolling) {
  19737. self.clearInterval(this.subtitlePollingInterval);
  19738. }
  19739. if (!this.media || !this.hls.config.renderTextTracksNatively) {
  19740. return;
  19741. }
  19742. let textTrack = null;
  19743. const tracks = filterSubtitleTracks(this.media.textTracks);
  19744. for (let i = 0; i < tracks.length; i++) {
  19745. if (tracks[i].mode === "hidden") {
  19746. textTrack = tracks[i];
  19747. } else if (tracks[i].mode === "showing") {
  19748. textTrack = tracks[i];
  19749. break;
  19750. }
  19751. }
  19752. const trackId = this.findTrackForTextTrack(textTrack);
  19753. if (this.subtitleTrack !== trackId) {
  19754. this.setSubtitleTrack(trackId);
  19755. }
  19756. };
  19757. this.registerListeners();
  19758. }
  19759. destroy() {
  19760. this.unregisterListeners();
  19761. this.tracks.length = 0;
  19762. this.tracksInGroup.length = 0;
  19763. this.currentTrack = null;
  19764. this.onTextTracksChanged = this.asyncPollTrackChange = null;
  19765. super.destroy();
  19766. }
  19767. get subtitleDisplay() {
  19768. return this._subtitleDisplay;
  19769. }
  19770. set subtitleDisplay(value) {
  19771. this._subtitleDisplay = value;
  19772. if (this.trackId > -1) {
  19773. this.toggleTrackModes();
  19774. }
  19775. }
  19776. registerListeners() {
  19777. const {
  19778. hls
  19779. } = this;
  19780. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  19781. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  19782. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  19783. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  19784. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  19785. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  19786. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  19787. hls.on(Events.ERROR, this.onError, this);
  19788. }
  19789. unregisterListeners() {
  19790. const {
  19791. hls
  19792. } = this;
  19793. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  19794. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  19795. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  19796. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  19797. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  19798. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  19799. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  19800. hls.off(Events.ERROR, this.onError, this);
  19801. }
  19802. onMediaAttached(event, data) {
  19803. this.media = data.media;
  19804. if (!this.media) {
  19805. return;
  19806. }
  19807. if (this.queuedDefaultTrack > -1) {
  19808. this.subtitleTrack = this.queuedDefaultTrack;
  19809. this.queuedDefaultTrack = -1;
  19810. }
  19811. this.useTextTrackPolling = !(this.media.textTracks && "onchange" in this.media.textTracks);
  19812. if (this.useTextTrackPolling) {
  19813. this.pollTrackChange(500);
  19814. } else {
  19815. this.media.textTracks.addEventListener("change", this.asyncPollTrackChange);
  19816. }
  19817. }
  19818. pollTrackChange(timeout) {
  19819. self.clearInterval(this.subtitlePollingInterval);
  19820. this.subtitlePollingInterval = self.setInterval(this.onTextTracksChanged, timeout);
  19821. }
  19822. onMediaDetaching(event, data) {
  19823. const media = this.media;
  19824. if (!media) {
  19825. return;
  19826. }
  19827. const transferringMedia = !!data.transferMedia;
  19828. self.clearInterval(this.subtitlePollingInterval);
  19829. if (!this.useTextTrackPolling) {
  19830. media.textTracks.removeEventListener("change", this.asyncPollTrackChange);
  19831. }
  19832. if (this.trackId > -1) {
  19833. this.queuedDefaultTrack = this.trackId;
  19834. }
  19835. this.subtitleTrack = -1;
  19836. this.media = null;
  19837. if (transferringMedia) {
  19838. return;
  19839. }
  19840. const textTracks = filterSubtitleTracks(media.textTracks);
  19841. textTracks.forEach((track) => {
  19842. clearCurrentCues(track);
  19843. });
  19844. }
  19845. onManifestLoading() {
  19846. this.tracks = [];
  19847. this.groupIds = null;
  19848. this.tracksInGroup = [];
  19849. this.trackId = -1;
  19850. this.currentTrack = null;
  19851. this.selectDefaultTrack = true;
  19852. }
  19853. onManifestParsed(event, data) {
  19854. this.tracks = data.subtitleTracks;
  19855. }
  19856. onSubtitleTrackLoaded(event, data) {
  19857. const {
  19858. id,
  19859. groupId,
  19860. details
  19861. } = data;
  19862. const trackInActiveGroup = this.tracksInGroup[id];
  19863. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  19864. this.warn(`Subtitle track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
  19865. return;
  19866. }
  19867. const curDetails = trackInActiveGroup.details;
  19868. trackInActiveGroup.details = data.details;
  19869. this.log(`Subtitle track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
  19870. if (id === this.trackId) {
  19871. this.playlistLoaded(id, data, curDetails);
  19872. }
  19873. }
  19874. onLevelLoading(event, data) {
  19875. this.switchLevel(data.level);
  19876. }
  19877. onLevelSwitching(event, data) {
  19878. this.switchLevel(data.level);
  19879. }
  19880. switchLevel(levelIndex) {
  19881. const levelInfo = this.hls.levels[levelIndex];
  19882. if (!levelInfo) {
  19883. return;
  19884. }
  19885. const subtitleGroups = levelInfo.subtitleGroups || null;
  19886. const currentGroups = this.groupIds;
  19887. let currentTrack = this.currentTrack;
  19888. 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)) {
  19889. this.groupIds = subtitleGroups;
  19890. this.trackId = -1;
  19891. this.currentTrack = null;
  19892. const subtitleTracks = this.tracks.filter((track) => !subtitleGroups || subtitleGroups.indexOf(track.groupId) !== -1);
  19893. if (subtitleTracks.length) {
  19894. if (this.selectDefaultTrack && !subtitleTracks.some((track) => track.default)) {
  19895. this.selectDefaultTrack = false;
  19896. }
  19897. subtitleTracks.forEach((track, i) => {
  19898. track.id = i;
  19899. });
  19900. } else if (!currentTrack && !this.tracksInGroup.length) {
  19901. return;
  19902. }
  19903. this.tracksInGroup = subtitleTracks;
  19904. const subtitlePreference = this.hls.config.subtitlePreference;
  19905. if (!currentTrack && subtitlePreference) {
  19906. this.selectDefaultTrack = false;
  19907. const groupIndex = findMatchingOption(subtitlePreference, subtitleTracks);
  19908. if (groupIndex > -1) {
  19909. currentTrack = subtitleTracks[groupIndex];
  19910. } else {
  19911. const allIndex = findMatchingOption(subtitlePreference, this.tracks);
  19912. currentTrack = this.tracks[allIndex];
  19913. }
  19914. }
  19915. let trackId = this.findTrackId(currentTrack);
  19916. if (trackId === -1 && currentTrack) {
  19917. trackId = this.findTrackId(null);
  19918. }
  19919. const subtitleTracksUpdated = {
  19920. subtitleTracks
  19921. };
  19922. this.log(`Updating subtitle tracks, ${subtitleTracks.length} track(s) found in "${subtitleGroups == null ? void 0 : subtitleGroups.join(",")}" group-id`);
  19923. this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);
  19924. if (trackId !== -1 && this.trackId === -1) {
  19925. this.setSubtitleTrack(trackId);
  19926. }
  19927. }
  19928. }
  19929. findTrackId(currentTrack) {
  19930. const tracks = this.tracksInGroup;
  19931. const selectDefault = this.selectDefaultTrack;
  19932. for (let i = 0; i < tracks.length; i++) {
  19933. const track = tracks[i];
  19934. if (selectDefault && !track.default || !selectDefault && !currentTrack) {
  19935. continue;
  19936. }
  19937. if (!currentTrack || matchesOption(track, currentTrack)) {
  19938. return i;
  19939. }
  19940. }
  19941. if (currentTrack) {
  19942. for (let i = 0; i < tracks.length; i++) {
  19943. const track = tracks[i];
  19944. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE", "ASSOC-LANGUAGE", "CHARACTERISTICS"])) {
  19945. return i;
  19946. }
  19947. }
  19948. for (let i = 0; i < tracks.length; i++) {
  19949. const track = tracks[i];
  19950. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE"])) {
  19951. return i;
  19952. }
  19953. }
  19954. }
  19955. return -1;
  19956. }
  19957. findTrackForTextTrack(textTrack) {
  19958. if (textTrack) {
  19959. const tracks = this.tracksInGroup;
  19960. for (let i = 0; i < tracks.length; i++) {
  19961. const track = tracks[i];
  19962. if (subtitleTrackMatchesTextTrack(track, textTrack)) {
  19963. return i;
  19964. }
  19965. }
  19966. }
  19967. return -1;
  19968. }
  19969. onError(event, data) {
  19970. if (data.fatal || !data.context) {
  19971. return;
  19972. }
  19973. if (data.context.type === PlaylistContextType.SUBTITLE_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  19974. this.checkRetry(data);
  19975. }
  19976. }
  19977. get allSubtitleTracks() {
  19978. return this.tracks;
  19979. }
  19980. get subtitleTracks() {
  19981. return this.tracksInGroup;
  19982. }
  19983. get subtitleTrack() {
  19984. return this.trackId;
  19985. }
  19986. set subtitleTrack(newId) {
  19987. this.selectDefaultTrack = false;
  19988. this.setSubtitleTrack(newId);
  19989. }
  19990. setSubtitleOption(subtitleOption) {
  19991. this.hls.config.subtitlePreference = subtitleOption;
  19992. if (subtitleOption) {
  19993. if (subtitleOption.id === -1) {
  19994. this.setSubtitleTrack(-1);
  19995. return null;
  19996. }
  19997. const allSubtitleTracks = this.allSubtitleTracks;
  19998. this.selectDefaultTrack = false;
  19999. if (allSubtitleTracks.length) {
  20000. const currentTrack = this.currentTrack;
  20001. if (currentTrack && matchesOption(subtitleOption, currentTrack)) {
  20002. return currentTrack;
  20003. }
  20004. const groupIndex = findMatchingOption(subtitleOption, this.tracksInGroup);
  20005. if (groupIndex > -1) {
  20006. const track = this.tracksInGroup[groupIndex];
  20007. this.setSubtitleTrack(groupIndex);
  20008. return track;
  20009. } else if (currentTrack) {
  20010. return null;
  20011. } else {
  20012. const allIndex = findMatchingOption(subtitleOption, allSubtitleTracks);
  20013. if (allIndex > -1) {
  20014. return allSubtitleTracks[allIndex];
  20015. }
  20016. }
  20017. }
  20018. }
  20019. return null;
  20020. }
  20021. loadPlaylist(hlsUrlParameters) {
  20022. super.loadPlaylist();
  20023. if (this.shouldLoadPlaylist(this.currentTrack)) {
  20024. this.scheduleLoading(this.currentTrack, hlsUrlParameters);
  20025. }
  20026. }
  20027. loadingPlaylist(currentTrack, hlsUrlParameters) {
  20028. super.loadingPlaylist(currentTrack, hlsUrlParameters);
  20029. const id = currentTrack.id;
  20030. const groupId = currentTrack.groupId;
  20031. const url = this.getUrlWithDirectives(currentTrack.url, hlsUrlParameters);
  20032. const details = currentTrack.details;
  20033. const age = details == null ? void 0 : details.age;
  20034. 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}`);
  20035. this.hls.trigger(Events.SUBTITLE_TRACK_LOADING, {
  20036. url,
  20037. id,
  20038. groupId,
  20039. deliveryDirectives: hlsUrlParameters || null,
  20040. track: currentTrack
  20041. });
  20042. }
  20043. toggleTrackModes() {
  20044. const {
  20045. media
  20046. } = this;
  20047. if (!media) {
  20048. return;
  20049. }
  20050. const textTracks = filterSubtitleTracks(media.textTracks);
  20051. const currentTrack = this.currentTrack;
  20052. let nextTrack;
  20053. if (currentTrack) {
  20054. nextTrack = textTracks.filter((textTrack) => subtitleTrackMatchesTextTrack(currentTrack, textTrack))[0];
  20055. if (!nextTrack) {
  20056. this.warn(`Unable to find subtitle TextTrack with name "${currentTrack.name}" and language "${currentTrack.lang}"`);
  20057. }
  20058. }
  20059. [].slice.call(textTracks).forEach((track) => {
  20060. if (track.mode !== "disabled" && track !== nextTrack) {
  20061. track.mode = "disabled";
  20062. }
  20063. });
  20064. if (nextTrack) {
  20065. const mode = this.subtitleDisplay ? "showing" : "hidden";
  20066. if (nextTrack.mode !== mode) {
  20067. nextTrack.mode = mode;
  20068. }
  20069. }
  20070. }
  20071. setSubtitleTrack(newId) {
  20072. const tracks = this.tracksInGroup;
  20073. if (!this.media) {
  20074. this.queuedDefaultTrack = newId;
  20075. return;
  20076. }
  20077. if (newId < -1 || newId >= tracks.length || !isFiniteNumber(newId)) {
  20078. this.warn(`Invalid subtitle track id: ${newId}`);
  20079. return;
  20080. }
  20081. this.selectDefaultTrack = false;
  20082. const lastTrack = this.currentTrack;
  20083. const track = tracks[newId] || null;
  20084. this.trackId = newId;
  20085. this.currentTrack = track;
  20086. this.toggleTrackModes();
  20087. if (!track) {
  20088. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  20089. id: newId
  20090. });
  20091. return;
  20092. }
  20093. const trackLoaded = !!track.details && !track.details.live;
  20094. if (newId === this.trackId && track === lastTrack && trackLoaded) {
  20095. return;
  20096. }
  20097. this.log(`Switching to subtitle-track ${newId}` + (track ? ` "${track.name}" lang:${track.lang} group:${track.groupId}` : ""));
  20098. const {
  20099. id,
  20100. groupId = "",
  20101. name,
  20102. type,
  20103. url
  20104. } = track;
  20105. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  20106. id,
  20107. groupId,
  20108. name,
  20109. type,
  20110. url
  20111. });
  20112. const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
  20113. this.loadPlaylist(hlsUrlParameters);
  20114. }
  20115. };
  20116. function uuid() {
  20117. try {
  20118. return crypto.randomUUID();
  20119. } catch (error) {
  20120. try {
  20121. const url = URL.createObjectURL(new Blob());
  20122. const uuid2 = url.toString();
  20123. URL.revokeObjectURL(url);
  20124. return uuid2.slice(uuid2.lastIndexOf("/") + 1);
  20125. } catch (error2) {
  20126. let dt = new Date().getTime();
  20127. const uuid2 = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
  20128. const r = (dt + Math.random() * 16) % 16 | 0;
  20129. dt = Math.floor(dt / 16);
  20130. return (c == "x" ? r : r & 3 | 8).toString(16);
  20131. });
  20132. return uuid2;
  20133. }
  20134. }
  20135. }
  20136. function hash(text) {
  20137. let hash2 = 5381;
  20138. let i = text.length;
  20139. while (i) {
  20140. hash2 = hash2 * 33 ^ text.charCodeAt(--i);
  20141. }
  20142. return (hash2 >>> 0).toString();
  20143. }
  20144. var ALIGNED_END_THRESHOLD_SECONDS = 0.025;
  20145. var TimelineOccupancy = function(TimelineOccupancy2) {
  20146. TimelineOccupancy2[TimelineOccupancy2["Point"] = 0] = "Point";
  20147. TimelineOccupancy2[TimelineOccupancy2["Range"] = 1] = "Range";
  20148. return TimelineOccupancy2;
  20149. }({});
  20150. function generateAssetIdentifier(interstitial, uri, assetListIndex) {
  20151. return `${interstitial.identifier}-${assetListIndex + 1}-${hash(uri)}`;
  20152. }
  20153. var InterstitialEvent = class {
  20154. constructor(dateRange, base) {
  20155. this.base = void 0;
  20156. this._duration = null;
  20157. this._timelineStart = null;
  20158. this.appendInPlaceDisabled = void 0;
  20159. this.appendInPlaceStarted = void 0;
  20160. this.dateRange = void 0;
  20161. this.hasPlayed = false;
  20162. this.cumulativeDuration = 0;
  20163. this.resumeOffset = NaN;
  20164. this.playoutLimit = NaN;
  20165. this.restrictions = {
  20166. skip: false,
  20167. jump: false
  20168. };
  20169. this.snapOptions = {
  20170. out: false,
  20171. in: false
  20172. };
  20173. this.assetList = [];
  20174. this.assetListLoader = void 0;
  20175. this.assetListResponse = null;
  20176. this.resumeAnchor = void 0;
  20177. this.error = void 0;
  20178. this.resetOnResume = void 0;
  20179. this.base = base;
  20180. this.dateRange = dateRange;
  20181. this.setDateRange(dateRange);
  20182. }
  20183. setDateRange(dateRange) {
  20184. this.dateRange = dateRange;
  20185. this.resumeOffset = dateRange.attr.optionalFloat("X-RESUME-OFFSET", this.resumeOffset);
  20186. this.playoutLimit = dateRange.attr.optionalFloat("X-PLAYOUT-LIMIT", this.playoutLimit);
  20187. this.restrictions = dateRange.attr.enumeratedStringList("X-RESTRICT", this.restrictions);
  20188. this.snapOptions = dateRange.attr.enumeratedStringList("X-SNAP", this.snapOptions);
  20189. }
  20190. reset() {
  20191. var _this$assetListLoader;
  20192. this.appendInPlaceStarted = false;
  20193. (_this$assetListLoader = this.assetListLoader) == null ? void 0 : _this$assetListLoader.destroy();
  20194. this.assetListLoader = void 0;
  20195. if (!this.supplementsPrimary) {
  20196. this.assetListResponse = null;
  20197. this.assetList = [];
  20198. this._duration = null;
  20199. }
  20200. }
  20201. isAssetPastPlayoutLimit(assetIndex) {
  20202. var _this$assetList$asset;
  20203. if (assetIndex > 0 && assetIndex >= this.assetList.length) {
  20204. return true;
  20205. }
  20206. const playoutLimit = this.playoutLimit;
  20207. if (assetIndex <= 0 || isNaN(playoutLimit)) {
  20208. return false;
  20209. }
  20210. if (playoutLimit === 0) {
  20211. return true;
  20212. }
  20213. const assetOffset = ((_this$assetList$asset = this.assetList[assetIndex]) == null ? void 0 : _this$assetList$asset.startOffset) || 0;
  20214. return assetOffset > playoutLimit;
  20215. }
  20216. findAssetIndex(asset) {
  20217. const index = this.assetList.indexOf(asset);
  20218. return index;
  20219. }
  20220. get identifier() {
  20221. return this.dateRange.id;
  20222. }
  20223. get startDate() {
  20224. return this.dateRange.startDate;
  20225. }
  20226. get startTime() {
  20227. const startTime = this.dateRange.startTime;
  20228. if (this.snapOptions.out) {
  20229. const frag = this.dateRange.tagAnchor;
  20230. if (frag) {
  20231. return getSnapToFragmentTime(startTime, frag);
  20232. }
  20233. }
  20234. return startTime;
  20235. }
  20236. get startOffset() {
  20237. return this.cue.pre ? 0 : this.startTime;
  20238. }
  20239. get startIsAligned() {
  20240. if (this.startTime === 0 || this.snapOptions.out) {
  20241. return true;
  20242. }
  20243. const frag = this.dateRange.tagAnchor;
  20244. if (frag) {
  20245. const startTime = this.dateRange.startTime;
  20246. const snappedStart = getSnapToFragmentTime(startTime, frag);
  20247. return startTime - snappedStart < 0.1;
  20248. }
  20249. return false;
  20250. }
  20251. get resumptionOffset() {
  20252. const resumeOffset = this.resumeOffset;
  20253. const offset = isFiniteNumber(resumeOffset) ? resumeOffset : this.duration;
  20254. return this.cumulativeDuration + offset;
  20255. }
  20256. get resumeTime() {
  20257. const resumeTime = this.startOffset + this.resumptionOffset;
  20258. if (this.snapOptions.in) {
  20259. const frag = this.resumeAnchor;
  20260. if (frag) {
  20261. return getSnapToFragmentTime(resumeTime, frag);
  20262. }
  20263. }
  20264. return resumeTime;
  20265. }
  20266. get appendInPlace() {
  20267. if (this.appendInPlaceStarted) {
  20268. return true;
  20269. }
  20270. if (this.appendInPlaceDisabled) {
  20271. return false;
  20272. }
  20273. if (!this.cue.once && !this.cue.pre && this.startIsAligned && (isNaN(this.playoutLimit) && isNaN(this.resumeOffset) || this.resumeOffset && this.duration && Math.abs(this.resumeOffset - this.duration) < ALIGNED_END_THRESHOLD_SECONDS)) {
  20274. return true;
  20275. }
  20276. return false;
  20277. }
  20278. set appendInPlace(value) {
  20279. if (this.appendInPlaceStarted) {
  20280. this.resetOnResume = !value;
  20281. return;
  20282. }
  20283. this.appendInPlaceDisabled = !value;
  20284. }
  20285. get timelineStart() {
  20286. if (this._timelineStart !== null) {
  20287. return this._timelineStart;
  20288. }
  20289. return this.startTime;
  20290. }
  20291. set timelineStart(value) {
  20292. this._timelineStart = value;
  20293. }
  20294. get duration() {
  20295. const playoutLimit = this.playoutLimit;
  20296. let duration;
  20297. if (this._duration !== null) {
  20298. duration = this._duration;
  20299. } else if (this.dateRange.duration) {
  20300. duration = this.dateRange.duration;
  20301. } else {
  20302. duration = this.dateRange.plannedDuration || 0;
  20303. }
  20304. if (!isNaN(playoutLimit) && playoutLimit < duration) {
  20305. duration = playoutLimit;
  20306. }
  20307. return duration;
  20308. }
  20309. set duration(value) {
  20310. this._duration = value;
  20311. }
  20312. get cue() {
  20313. return this.dateRange.cue;
  20314. }
  20315. get timelineOccupancy() {
  20316. if (this.dateRange.attr["X-TIMELINE-OCCUPIES"] === "RANGE") {
  20317. return TimelineOccupancy.Range;
  20318. }
  20319. return TimelineOccupancy.Point;
  20320. }
  20321. get supplementsPrimary() {
  20322. return this.dateRange.attr["X-TIMELINE-STYLE"] === "PRIMARY";
  20323. }
  20324. get contentMayVary() {
  20325. return this.dateRange.attr["X-CONTENT-MAY-VARY"] !== "NO";
  20326. }
  20327. get assetUrl() {
  20328. return this.dateRange.attr["X-ASSET-URI"];
  20329. }
  20330. get assetListUrl() {
  20331. return this.dateRange.attr["X-ASSET-LIST"];
  20332. }
  20333. get baseUrl() {
  20334. return this.base.url;
  20335. }
  20336. get assetListLoaded() {
  20337. return this.assetList.length > 0 || this.assetListResponse !== null;
  20338. }
  20339. toString() {
  20340. return eventToString(this);
  20341. }
  20342. };
  20343. function getSnapToFragmentTime(time, frag) {
  20344. return time - frag.start < frag.duration / 2 && !(Math.abs(time - (frag.start + frag.duration)) < ALIGNED_END_THRESHOLD_SECONDS) ? frag.start : frag.start + frag.duration;
  20345. }
  20346. function getInterstitialUrl(uri, sessionId, baseUrl) {
  20347. const url = new self.URL(uri, baseUrl);
  20348. if (url.protocol !== "data:") {
  20349. url.searchParams.set("_HLS_primary_id", sessionId);
  20350. }
  20351. return url;
  20352. }
  20353. function getNextAssetIndex(interstitial, assetListIndex) {
  20354. while ((_interstitial$assetLi = interstitial.assetList[++assetListIndex]) != null && _interstitial$assetLi.error) {
  20355. var _interstitial$assetLi;
  20356. }
  20357. return assetListIndex;
  20358. }
  20359. function eventToString(interstitial) {
  20360. return `["${interstitial.identifier}" ${interstitial.cue.pre ? "<pre>" : interstitial.cue.post ? "<post>" : ""}${interstitial.timelineStart.toFixed(2)}-${interstitial.resumeTime.toFixed(2)}]`;
  20361. }
  20362. function eventAssetToString(asset) {
  20363. const start = asset.timelineStart;
  20364. const duration = asset.duration || 0;
  20365. return `["${asset.identifier}" ${start.toFixed(2)}-${(start + duration).toFixed(2)}]`;
  20366. }
  20367. var HlsAssetPlayer = class {
  20368. constructor(HlsPlayerClass, userConfig, interstitial, assetItem) {
  20369. this.hls = void 0;
  20370. this.interstitial = void 0;
  20371. this.assetItem = void 0;
  20372. this.tracks = null;
  20373. this.hasDetails = false;
  20374. this.mediaAttached = null;
  20375. this._currentTime = void 0;
  20376. this._bufferedEosTime = void 0;
  20377. this.checkPlayout = () => {
  20378. if (this.reachedPlayout(this.currentTime)) {
  20379. this.hls.trigger(Events.PLAYOUT_LIMIT_REACHED, {});
  20380. }
  20381. };
  20382. const hls = this.hls = new HlsPlayerClass(userConfig);
  20383. this.interstitial = interstitial;
  20384. this.assetItem = assetItem;
  20385. let uri = assetItem.uri;
  20386. try {
  20387. uri = getInterstitialUrl(uri, userConfig.primarySessionId).href;
  20388. } catch (error) {
  20389. }
  20390. hls.loadSource(uri);
  20391. const detailsLoaded = () => {
  20392. this.hasDetails = true;
  20393. };
  20394. hls.once(Events.LEVEL_LOADED, detailsLoaded);
  20395. hls.once(Events.AUDIO_TRACK_LOADED, detailsLoaded);
  20396. hls.once(Events.SUBTITLE_TRACK_LOADED, detailsLoaded);
  20397. hls.on(Events.MEDIA_ATTACHING, (name, {
  20398. media
  20399. }) => {
  20400. this.removeMediaListeners();
  20401. this.mediaAttached = media;
  20402. const event = this.interstitial;
  20403. if (event.playoutLimit) {
  20404. media.addEventListener("timeupdate", this.checkPlayout);
  20405. if (this.appendInPlace) {
  20406. hls.on(Events.BUFFER_APPENDED, () => {
  20407. const bufferedEnd = this.bufferedEnd;
  20408. if (this.reachedPlayout(bufferedEnd)) {
  20409. this._bufferedEosTime = bufferedEnd;
  20410. hls.trigger(Events.BUFFERED_TO_END, void 0);
  20411. }
  20412. });
  20413. }
  20414. }
  20415. });
  20416. }
  20417. get appendInPlace() {
  20418. var _this$interstitial;
  20419. return ((_this$interstitial = this.interstitial) == null ? void 0 : _this$interstitial.appendInPlace) || false;
  20420. }
  20421. bufferedInPlaceToEnd(media) {
  20422. var _this$hls;
  20423. if (!this.appendInPlace) {
  20424. return false;
  20425. }
  20426. if ((_this$hls = this.hls) != null && _this$hls.bufferedToEnd) {
  20427. return true;
  20428. }
  20429. if (!media || !this._bufferedEosTime) {
  20430. return false;
  20431. }
  20432. const start = this.timelineOffset;
  20433. const bufferInfo = BufferHelper.bufferInfo(media, start, 0);
  20434. const bufferedEnd = this.getAssetTime(bufferInfo.end);
  20435. return bufferedEnd >= this._bufferedEosTime - 0.02;
  20436. }
  20437. reachedPlayout(time) {
  20438. const interstitial = this.interstitial;
  20439. const playoutLimit = interstitial.playoutLimit;
  20440. return this.startOffset + time >= playoutLimit;
  20441. }
  20442. get destroyed() {
  20443. var _this$hls2;
  20444. return !((_this$hls2 = this.hls) != null && _this$hls2.userConfig);
  20445. }
  20446. get assetId() {
  20447. return this.assetItem.identifier;
  20448. }
  20449. get interstitialId() {
  20450. return this.assetItem.parentIdentifier;
  20451. }
  20452. get media() {
  20453. var _this$hls3;
  20454. return ((_this$hls3 = this.hls) == null ? void 0 : _this$hls3.media) || null;
  20455. }
  20456. get bufferedEnd() {
  20457. const media = this.media || this.mediaAttached;
  20458. if (!media) {
  20459. if (this._bufferedEosTime) {
  20460. return this._bufferedEosTime;
  20461. }
  20462. return this.currentTime;
  20463. }
  20464. const bufferInfo = BufferHelper.bufferInfo(media, media.currentTime, 1e-3);
  20465. return this.getAssetTime(bufferInfo.end);
  20466. }
  20467. get currentTime() {
  20468. const media = this.media || this.mediaAttached;
  20469. if (!media) {
  20470. return this._currentTime || 0;
  20471. }
  20472. return this.getAssetTime(media.currentTime);
  20473. }
  20474. get duration() {
  20475. const duration = this.assetItem.duration;
  20476. if (!duration) {
  20477. return 0;
  20478. }
  20479. return duration;
  20480. }
  20481. get remaining() {
  20482. const duration = this.duration;
  20483. if (!duration) {
  20484. return 0;
  20485. }
  20486. return Math.max(0, duration - this.currentTime);
  20487. }
  20488. get startOffset() {
  20489. return this.assetItem.startOffset;
  20490. }
  20491. get timelineOffset() {
  20492. var _this$hls4;
  20493. return ((_this$hls4 = this.hls) == null ? void 0 : _this$hls4.config.timelineOffset) || 0;
  20494. }
  20495. set timelineOffset(value) {
  20496. const timelineOffset = this.timelineOffset;
  20497. if (value !== timelineOffset) {
  20498. const diff = value - timelineOffset;
  20499. if (Math.abs(diff) > 1 / 9e4) {
  20500. if (this.hasDetails) {
  20501. throw new Error(`Cannot set timelineOffset after playlists are loaded`);
  20502. }
  20503. this.hls.config.timelineOffset = value;
  20504. }
  20505. }
  20506. }
  20507. getAssetTime(time) {
  20508. const timelineOffset = this.timelineOffset;
  20509. const duration = this.duration;
  20510. return Math.min(Math.max(0, time - timelineOffset), duration);
  20511. }
  20512. removeMediaListeners() {
  20513. const media = this.mediaAttached;
  20514. if (media) {
  20515. this._currentTime = media.currentTime;
  20516. this.bufferSnapShot();
  20517. media.removeEventListener("timeupdate", this.checkPlayout);
  20518. }
  20519. }
  20520. bufferSnapShot() {
  20521. if (this.mediaAttached) {
  20522. var _this$hls5;
  20523. if ((_this$hls5 = this.hls) != null && _this$hls5.bufferedToEnd) {
  20524. this._bufferedEosTime = this.bufferedEnd;
  20525. }
  20526. }
  20527. }
  20528. destroy() {
  20529. this.removeMediaListeners();
  20530. this.hls.destroy();
  20531. this.hls = this.interstitial = null;
  20532. this.tracks = this.mediaAttached = this.checkPlayout = null;
  20533. }
  20534. attachMedia(data) {
  20535. this.hls.attachMedia(data);
  20536. }
  20537. detachMedia() {
  20538. this.removeMediaListeners();
  20539. this.mediaAttached = null;
  20540. this.hls.detachMedia();
  20541. }
  20542. resumeBuffering() {
  20543. this.hls.resumeBuffering();
  20544. }
  20545. pauseBuffering() {
  20546. this.hls.pauseBuffering();
  20547. }
  20548. transferMedia() {
  20549. this.bufferSnapShot();
  20550. return this.hls.transferMedia();
  20551. }
  20552. resetDetails() {
  20553. const hls = this.hls;
  20554. if (this.hasDetails) {
  20555. hls.stopLoad();
  20556. const deleteDetails = (obj) => delete obj.details;
  20557. hls.levels.forEach(deleteDetails);
  20558. hls.allAudioTracks.forEach(deleteDetails);
  20559. hls.allSubtitleTracks.forEach(deleteDetails);
  20560. this.hasDetails = false;
  20561. }
  20562. }
  20563. on(event, listener, context) {
  20564. this.hls.on(event, listener);
  20565. }
  20566. once(event, listener, context) {
  20567. this.hls.once(event, listener);
  20568. }
  20569. off(event, listener, context) {
  20570. this.hls.off(event, listener);
  20571. }
  20572. toString() {
  20573. var _this$hls6;
  20574. return `HlsAssetPlayer: ${eventAssetToString(this.assetItem)} ${(_this$hls6 = this.hls) == null ? void 0 : _this$hls6.sessionId} ${this.appendInPlace ? "append-in-place" : ""}`;
  20575. }
  20576. };
  20577. var ABUTTING_THRESHOLD_SECONDS = 0.033;
  20578. var InterstitialsSchedule = class extends Logger {
  20579. constructor(onScheduleUpdate, logger2) {
  20580. super("interstitials-sched", logger2);
  20581. this.onScheduleUpdate = void 0;
  20582. this.eventMap = {};
  20583. this.events = null;
  20584. this.items = null;
  20585. this.durations = {
  20586. primary: 0,
  20587. playout: 0,
  20588. integrated: 0
  20589. };
  20590. this.onScheduleUpdate = onScheduleUpdate;
  20591. }
  20592. destroy() {
  20593. this.reset();
  20594. this.onScheduleUpdate = null;
  20595. }
  20596. reset() {
  20597. this.eventMap = {};
  20598. this.setDurations(0, 0, 0);
  20599. if (this.events) {
  20600. this.events.forEach((interstitial) => interstitial.reset());
  20601. }
  20602. this.events = this.items = null;
  20603. }
  20604. resetErrorsInRange(start, end) {
  20605. if (this.events) {
  20606. return this.events.reduce((count, interstitial) => {
  20607. if (start <= interstitial.startOffset && end > interstitial.startOffset) {
  20608. delete interstitial.error;
  20609. return count + 1;
  20610. }
  20611. return count;
  20612. }, 0);
  20613. }
  20614. return 0;
  20615. }
  20616. get duration() {
  20617. const items = this.items;
  20618. return items ? items[items.length - 1].end : 0;
  20619. }
  20620. get length() {
  20621. return this.items ? this.items.length : 0;
  20622. }
  20623. getEvent(identifier) {
  20624. return identifier ? this.eventMap[identifier] || null : null;
  20625. }
  20626. hasEvent(identifier) {
  20627. return identifier in this.eventMap;
  20628. }
  20629. findItemIndex(item, time) {
  20630. if (item.event) {
  20631. return this.findEventIndex(item.event.identifier);
  20632. }
  20633. let index = -1;
  20634. if (item.nextEvent) {
  20635. index = this.findEventIndex(item.nextEvent.identifier) - 1;
  20636. } else if (item.previousEvent) {
  20637. index = this.findEventIndex(item.previousEvent.identifier) + 1;
  20638. }
  20639. const items = this.items;
  20640. if (items) {
  20641. if (!items[index]) {
  20642. if (time === void 0) {
  20643. time = item.start;
  20644. }
  20645. index = this.findItemIndexAtTime(time);
  20646. }
  20647. while (index >= 0 && (_items$index = items[index]) != null && _items$index.event) {
  20648. var _items$index;
  20649. index--;
  20650. }
  20651. }
  20652. return index;
  20653. }
  20654. findItemIndexAtTime(timelinePos, timelineType) {
  20655. const items = this.items;
  20656. if (items) {
  20657. for (let i = 0; i < items.length; i++) {
  20658. let timeRange = items[i];
  20659. if (timelineType && timelineType !== "primary") {
  20660. timeRange = timeRange[timelineType];
  20661. }
  20662. if (timelinePos === timeRange.start || timelinePos > timeRange.start && timelinePos < timeRange.end) {
  20663. return i;
  20664. }
  20665. }
  20666. }
  20667. return -1;
  20668. }
  20669. findJumpRestrictedIndex(startIndex, endIndex) {
  20670. const items = this.items;
  20671. if (items) {
  20672. for (let i = startIndex; i <= endIndex; i++) {
  20673. if (!items[i]) {
  20674. break;
  20675. }
  20676. const event = items[i].event;
  20677. if (event != null && event.restrictions.jump && !event.appendInPlace) {
  20678. return i;
  20679. }
  20680. }
  20681. }
  20682. return -1;
  20683. }
  20684. findEventIndex(identifier) {
  20685. const items = this.items;
  20686. if (items) {
  20687. for (let i = items.length; i--; ) {
  20688. var _items$i$event;
  20689. if (((_items$i$event = items[i].event) == null ? void 0 : _items$i$event.identifier) === identifier) {
  20690. return i;
  20691. }
  20692. }
  20693. }
  20694. return -1;
  20695. }
  20696. findAssetIndex(event, timelinePos) {
  20697. const assetList = event.assetList;
  20698. const length = assetList.length;
  20699. if (length > 1) {
  20700. for (let i = 0; i < length; i++) {
  20701. const asset = assetList[i];
  20702. if (!asset.error) {
  20703. const timelineStart = asset.timelineStart;
  20704. if (timelinePos === timelineStart || timelinePos > timelineStart && timelinePos < timelineStart + (asset.duration || 0)) {
  20705. return i;
  20706. }
  20707. }
  20708. }
  20709. }
  20710. return 0;
  20711. }
  20712. get assetIdAtEnd() {
  20713. var _this$items, _this$items2;
  20714. const interstitialAtEnd = (_this$items = this.items) == null ? void 0 : (_this$items2 = _this$items[this.length - 1]) == null ? void 0 : _this$items2.event;
  20715. if (interstitialAtEnd) {
  20716. const assetList = interstitialAtEnd.assetList;
  20717. const assetAtEnd = assetList[assetList.length - 1];
  20718. if (assetAtEnd) {
  20719. return assetAtEnd.identifier;
  20720. }
  20721. }
  20722. return null;
  20723. }
  20724. parseInterstitialDateRanges(mediaSelection, enableAppendInPlace) {
  20725. const details = mediaSelection.main.details;
  20726. const {
  20727. dateRanges
  20728. } = details;
  20729. const previousInterstitialEvents = this.events;
  20730. const interstitialEvents = this.parseDateRanges(dateRanges, {
  20731. url: details.url
  20732. }, enableAppendInPlace);
  20733. const ids = Object.keys(dateRanges);
  20734. const removedInterstitials = previousInterstitialEvents ? previousInterstitialEvents.filter((event) => !ids.includes(event.identifier)) : [];
  20735. if (interstitialEvents.length) {
  20736. interstitialEvents.sort((a, b) => {
  20737. const aPre = a.cue.pre;
  20738. const aPost = a.cue.post;
  20739. const bPre = b.cue.pre;
  20740. const bPost = b.cue.post;
  20741. if (aPre && !bPre) {
  20742. return -1;
  20743. }
  20744. if (bPre && !aPre) {
  20745. return 1;
  20746. }
  20747. if (aPost && !bPost) {
  20748. return 1;
  20749. }
  20750. if (bPost && !aPost) {
  20751. return -1;
  20752. }
  20753. if (!aPre && !bPre && !aPost && !bPost) {
  20754. const startA = a.startTime;
  20755. const startB = b.startTime;
  20756. if (startA !== startB) {
  20757. return startA - startB;
  20758. }
  20759. }
  20760. return a.dateRange.tagOrder - b.dateRange.tagOrder;
  20761. });
  20762. }
  20763. this.events = interstitialEvents;
  20764. removedInterstitials.forEach((interstitial) => {
  20765. this.removeEvent(interstitial);
  20766. });
  20767. this.updateSchedule(mediaSelection, removedInterstitials);
  20768. }
  20769. updateSchedule(mediaSelection, removedInterstitials = []) {
  20770. const events = this.events || [];
  20771. if (events.length || removedInterstitials.length || this.length < 2) {
  20772. const currentItems = this.items;
  20773. const updatedItems = this.parseSchedule(events, mediaSelection);
  20774. const updated = removedInterstitials.length || (currentItems == null ? void 0 : currentItems.length) !== updatedItems.length || updatedItems.some((item, i) => {
  20775. return Math.abs(item.playout.start - currentItems[i].playout.start) > 5e-3 || Math.abs(item.playout.end - currentItems[i].playout.end) > 5e-3;
  20776. });
  20777. if (updated) {
  20778. this.items = updatedItems;
  20779. this.onScheduleUpdate(removedInterstitials, currentItems);
  20780. }
  20781. }
  20782. }
  20783. parseDateRanges(dateRanges, baseData, enableAppendInPlace) {
  20784. const interstitialEvents = [];
  20785. const ids = Object.keys(dateRanges);
  20786. for (let i = 0; i < ids.length; i++) {
  20787. const id = ids[i];
  20788. const dateRange = dateRanges[id];
  20789. if (dateRange.isInterstitial) {
  20790. let interstitial = this.eventMap[id];
  20791. if (interstitial) {
  20792. interstitial.setDateRange(dateRange);
  20793. } else {
  20794. interstitial = new InterstitialEvent(dateRange, baseData);
  20795. this.eventMap[id] = interstitial;
  20796. if (enableAppendInPlace === false) {
  20797. interstitial.appendInPlace = enableAppendInPlace;
  20798. }
  20799. }
  20800. interstitialEvents.push(interstitial);
  20801. }
  20802. }
  20803. return interstitialEvents;
  20804. }
  20805. parseSchedule(interstitialEvents, mediaSelection) {
  20806. const schedule = [];
  20807. const details = mediaSelection.main.details;
  20808. const primaryDuration = details.live ? Infinity : details.edge;
  20809. let playoutDuration = 0;
  20810. interstitialEvents = interstitialEvents.filter((event) => !event.error && !(event.cue.once && event.hasPlayed));
  20811. if (interstitialEvents.length) {
  20812. this.resolveOffsets(interstitialEvents, mediaSelection);
  20813. let primaryPosition = 0;
  20814. let integratedTime = 0;
  20815. interstitialEvents.forEach((interstitial, i) => {
  20816. const preroll = interstitial.cue.pre;
  20817. const postroll = interstitial.cue.post;
  20818. const previousEvent = interstitialEvents[i - 1] || null;
  20819. const appendInPlace = interstitial.appendInPlace;
  20820. const eventStart = postroll ? primaryDuration : interstitial.startOffset;
  20821. const interstitialDuration = interstitial.duration;
  20822. const timelineDuration = interstitial.timelineOccupancy === TimelineOccupancy.Range ? interstitialDuration : 0;
  20823. const resumptionOffset = interstitial.resumptionOffset;
  20824. const inSameStartTimeSequence = (previousEvent == null ? void 0 : previousEvent.startTime) === eventStart;
  20825. const start = eventStart + interstitial.cumulativeDuration;
  20826. let end = appendInPlace ? start + interstitialDuration : eventStart + resumptionOffset;
  20827. if (preroll || !postroll && eventStart <= 0) {
  20828. const integratedStart = integratedTime;
  20829. integratedTime += timelineDuration;
  20830. interstitial.timelineStart = start;
  20831. const playoutStart = playoutDuration;
  20832. playoutDuration += interstitialDuration;
  20833. schedule.push({
  20834. event: interstitial,
  20835. start,
  20836. end,
  20837. playout: {
  20838. start: playoutStart,
  20839. end: playoutDuration
  20840. },
  20841. integrated: {
  20842. start: integratedStart,
  20843. end: integratedTime
  20844. }
  20845. });
  20846. } else if (eventStart <= primaryDuration) {
  20847. if (!inSameStartTimeSequence) {
  20848. const segmentDuration = eventStart - primaryPosition;
  20849. if (segmentDuration > ABUTTING_THRESHOLD_SECONDS) {
  20850. const timelineStart = primaryPosition;
  20851. const _integratedStart = integratedTime;
  20852. integratedTime += segmentDuration;
  20853. const _playoutStart = playoutDuration;
  20854. playoutDuration += segmentDuration;
  20855. const primarySegment = {
  20856. previousEvent: interstitialEvents[i - 1] || null,
  20857. nextEvent: interstitial,
  20858. start: timelineStart,
  20859. end: timelineStart + segmentDuration,
  20860. playout: {
  20861. start: _playoutStart,
  20862. end: playoutDuration
  20863. },
  20864. integrated: {
  20865. start: _integratedStart,
  20866. end: integratedTime
  20867. }
  20868. };
  20869. schedule.push(primarySegment);
  20870. } else if (segmentDuration > 0 && previousEvent) {
  20871. previousEvent.cumulativeDuration += segmentDuration;
  20872. schedule[schedule.length - 1].end = eventStart;
  20873. }
  20874. }
  20875. if (postroll) {
  20876. end = start;
  20877. }
  20878. interstitial.timelineStart = start;
  20879. const integratedStart = integratedTime;
  20880. integratedTime += timelineDuration;
  20881. const playoutStart = playoutDuration;
  20882. playoutDuration += interstitialDuration;
  20883. schedule.push({
  20884. event: interstitial,
  20885. start,
  20886. end,
  20887. playout: {
  20888. start: playoutStart,
  20889. end: playoutDuration
  20890. },
  20891. integrated: {
  20892. start: integratedStart,
  20893. end: integratedTime
  20894. }
  20895. });
  20896. } else {
  20897. return;
  20898. }
  20899. const resumeTime = interstitial.resumeTime;
  20900. if (postroll || resumeTime > primaryDuration) {
  20901. primaryPosition = primaryDuration;
  20902. } else {
  20903. primaryPosition = resumeTime;
  20904. }
  20905. });
  20906. if (primaryPosition < primaryDuration) {
  20907. var _schedule;
  20908. const timelineStart = primaryPosition;
  20909. const integratedStart = integratedTime;
  20910. const segmentDuration = primaryDuration - primaryPosition;
  20911. integratedTime += segmentDuration;
  20912. const playoutStart = playoutDuration;
  20913. playoutDuration += segmentDuration;
  20914. schedule.push({
  20915. previousEvent: ((_schedule = schedule[schedule.length - 1]) == null ? void 0 : _schedule.event) || null,
  20916. nextEvent: null,
  20917. start: primaryPosition,
  20918. end: timelineStart + segmentDuration,
  20919. playout: {
  20920. start: playoutStart,
  20921. end: playoutDuration
  20922. },
  20923. integrated: {
  20924. start: integratedStart,
  20925. end: integratedTime
  20926. }
  20927. });
  20928. }
  20929. this.setDurations(primaryDuration, playoutDuration, integratedTime);
  20930. } else {
  20931. const start = 0;
  20932. schedule.push({
  20933. previousEvent: null,
  20934. nextEvent: null,
  20935. start,
  20936. end: primaryDuration,
  20937. playout: {
  20938. start,
  20939. end: primaryDuration
  20940. },
  20941. integrated: {
  20942. start,
  20943. end: primaryDuration
  20944. }
  20945. });
  20946. this.setDurations(primaryDuration, primaryDuration, primaryDuration);
  20947. }
  20948. return schedule;
  20949. }
  20950. setDurations(primary, playout, integrated) {
  20951. this.durations = {
  20952. primary,
  20953. playout,
  20954. integrated
  20955. };
  20956. }
  20957. resolveOffsets(interstitialEvents, mediaSelection) {
  20958. const details = mediaSelection.main.details;
  20959. const primaryDuration = details.live ? Infinity : details.edge;
  20960. let cumulativeDuration = 0;
  20961. let lastScheduledStart = -1;
  20962. interstitialEvents.forEach((interstitial, i) => {
  20963. const preroll = interstitial.cue.pre;
  20964. const postroll = interstitial.cue.post;
  20965. const eventStart = preroll ? 0 : postroll ? primaryDuration : interstitial.startTime;
  20966. this.updateAssetDurations(interstitial);
  20967. const inSameStartTimeSequence = lastScheduledStart === eventStart;
  20968. if (inSameStartTimeSequence) {
  20969. interstitial.cumulativeDuration = cumulativeDuration;
  20970. } else {
  20971. cumulativeDuration = 0;
  20972. lastScheduledStart = eventStart;
  20973. }
  20974. if (!postroll && interstitial.snapOptions.in) {
  20975. interstitial.resumeAnchor = findFragmentByPTS(null, details.fragments, interstitial.startOffset + interstitial.resumptionOffset, 0, 0) || void 0;
  20976. }
  20977. if (interstitial.appendInPlace && !interstitial.appendInPlaceStarted) {
  20978. const alignedSegmentStart = this.primaryCanResumeInPlaceAt(interstitial, mediaSelection);
  20979. if (!alignedSegmentStart) {
  20980. interstitial.appendInPlace = false;
  20981. }
  20982. }
  20983. if (!interstitial.appendInPlace && i + 1 < interstitialEvents.length) {
  20984. const timeBetween = interstitialEvents[i + 1].startTime - interstitialEvents[i].resumeTime;
  20985. if (timeBetween < ABUTTING_THRESHOLD_SECONDS) {
  20986. interstitialEvents[i + 1].appendInPlace = false;
  20987. if (interstitialEvents[i + 1].appendInPlace) {
  20988. this.warn(`Could not change append strategy for abutting event ${interstitial}`);
  20989. }
  20990. }
  20991. }
  20992. const resumeOffset = isFiniteNumber(interstitial.resumeOffset) ? interstitial.resumeOffset : interstitial.duration;
  20993. cumulativeDuration += resumeOffset;
  20994. });
  20995. }
  20996. primaryCanResumeInPlaceAt(interstitial, mediaSelection) {
  20997. const resumeTime = interstitial.resumeTime;
  20998. const resumesInPlaceAt = interstitial.startTime + interstitial.resumptionOffset;
  20999. if (Math.abs(resumeTime - resumesInPlaceAt) > ALIGNED_END_THRESHOLD_SECONDS) {
  21000. this.log(`"${interstitial.identifier}" resumption ${resumeTime} not aligned with estimated timeline end ${resumesInPlaceAt}`);
  21001. return false;
  21002. }
  21003. if (!mediaSelection) {
  21004. this.log(`"${interstitial.identifier}" resumption ${resumeTime} can not be aligned with media (none selected)`);
  21005. return false;
  21006. }
  21007. const playlists = Object.keys(mediaSelection);
  21008. return !playlists.some((playlistType) => {
  21009. const details = mediaSelection[playlistType].details;
  21010. const playlistEnd = details.edge;
  21011. if (resumeTime >= playlistEnd) {
  21012. this.log(`"${interstitial.identifier}" resumption ${resumeTime} past ${playlistType} playlist end ${playlistEnd}`);
  21013. return false;
  21014. }
  21015. const startFragment = findFragmentByPTS(null, details.fragments, resumeTime);
  21016. if (!startFragment) {
  21017. this.log(`"${interstitial.identifier}" resumption ${resumeTime} does not align with any fragments in ${playlistType} playlist (${details.fragStart}-${details.fragmentEnd})`);
  21018. return true;
  21019. }
  21020. const allowance = playlistType === "audio" ? 0.175 : 0;
  21021. const alignedWithSegment = Math.abs(startFragment.start - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance || Math.abs(startFragment.end - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance;
  21022. if (!alignedWithSegment) {
  21023. this.log(`"${interstitial.identifier}" resumption ${resumeTime} not aligned with ${playlistType} fragment bounds (${startFragment.start}-${startFragment.end} sn: ${startFragment.sn} cc: ${startFragment.cc})`);
  21024. return true;
  21025. }
  21026. return false;
  21027. });
  21028. }
  21029. updateAssetDurations(interstitial) {
  21030. if (!interstitial.assetListLoaded) {
  21031. return;
  21032. }
  21033. const eventStart = interstitial.timelineStart;
  21034. let sumDuration = 0;
  21035. let hasUnknownDuration = false;
  21036. let hasErrors = false;
  21037. interstitial.assetList.forEach((asset, i) => {
  21038. const timelineStart = eventStart + sumDuration;
  21039. asset.startOffset = sumDuration;
  21040. asset.timelineStart = timelineStart;
  21041. hasUnknownDuration || (hasUnknownDuration = asset.duration === null);
  21042. hasErrors || (hasErrors = !!asset.error);
  21043. const duration = asset.error ? 0 : asset.duration || 0;
  21044. sumDuration += duration;
  21045. });
  21046. if (hasUnknownDuration && !hasErrors) {
  21047. interstitial.duration = Math.max(sumDuration, interstitial.duration);
  21048. } else {
  21049. interstitial.duration = sumDuration;
  21050. }
  21051. }
  21052. removeEvent(interstitial) {
  21053. interstitial.reset();
  21054. delete this.eventMap[interstitial.identifier];
  21055. }
  21056. };
  21057. function segmentToString(segment) {
  21058. return `[${segment.event ? '"' + segment.event.identifier + '"' : "primary"}: ${segment.start.toFixed(2)}-${segment.end.toFixed(2)}]`;
  21059. }
  21060. var AssetListLoader = class {
  21061. constructor(hls) {
  21062. this.hls = void 0;
  21063. this.hls = hls;
  21064. }
  21065. destroy() {
  21066. this.hls = null;
  21067. }
  21068. loadAssetList(interstitial, hlsStartOffset) {
  21069. const assetListUrl = interstitial.assetListUrl;
  21070. let url;
  21071. try {
  21072. url = getInterstitialUrl(assetListUrl, this.hls.sessionId, interstitial.baseUrl);
  21073. } catch (error) {
  21074. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_ERROR, error, assetListUrl);
  21075. this.hls.trigger(Events.ERROR, errorData);
  21076. return;
  21077. }
  21078. if (hlsStartOffset && url.protocol !== "data:") {
  21079. url.searchParams.set("_HLS_start_offset", "" + hlsStartOffset);
  21080. }
  21081. const config = this.hls.config;
  21082. const Loader = config.loader;
  21083. const loader = new Loader(config);
  21084. const context = {
  21085. responseType: "json",
  21086. url: url.href
  21087. };
  21088. const loadPolicy = config.interstitialAssetListLoadPolicy.default;
  21089. const loaderConfig = {
  21090. loadPolicy,
  21091. timeout: loadPolicy.maxLoadTimeMs,
  21092. maxRetry: 0,
  21093. retryDelay: 0,
  21094. maxRetryDelay: 0
  21095. };
  21096. const callbacks = {
  21097. onSuccess: (response, stats, context2, networkDetails) => {
  21098. const assetListResponse = response.data;
  21099. const assets = assetListResponse == null ? void 0 : assetListResponse.ASSETS;
  21100. if (!Array.isArray(assets)) {
  21101. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_PARSING_ERROR, new Error(`Invalid interstitial asset list`), context2.url, stats, networkDetails);
  21102. this.hls.trigger(Events.ERROR, errorData);
  21103. return;
  21104. }
  21105. interstitial.assetListResponse = assetListResponse;
  21106. this.hls.trigger(Events.ASSET_LIST_LOADED, {
  21107. event: interstitial,
  21108. assetListResponse,
  21109. networkDetails
  21110. });
  21111. },
  21112. onError: (error, context2, networkDetails, stats) => {
  21113. 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);
  21114. this.hls.trigger(Events.ERROR, errorData);
  21115. },
  21116. onTimeout: (stats, context2, networkDetails) => {
  21117. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_TIMEOUT, new Error(`Timeout loading X-ASSET-LIST (${context2.url})`), context2.url, stats, networkDetails);
  21118. this.hls.trigger(Events.ERROR, errorData);
  21119. }
  21120. };
  21121. loader.load(context, loaderConfig, callbacks);
  21122. this.hls.trigger(Events.ASSET_LIST_LOADING, {
  21123. event: interstitial
  21124. });
  21125. return loader;
  21126. }
  21127. assignAssetListError(interstitial, details, error, url, stats, networkDetails) {
  21128. interstitial.error = error;
  21129. return {
  21130. type: ErrorTypes.NETWORK_ERROR,
  21131. details,
  21132. fatal: false,
  21133. interstitial,
  21134. url,
  21135. error,
  21136. networkDetails,
  21137. stats
  21138. };
  21139. }
  21140. };
  21141. function playWithCatch(media) {
  21142. media == null ? void 0 : media.play().catch(() => {
  21143. });
  21144. }
  21145. var InterstitialsController = class extends Logger {
  21146. constructor(hls, HlsPlayerClass) {
  21147. super("interstitials", hls.logger);
  21148. this.HlsPlayerClass = void 0;
  21149. this.hls = void 0;
  21150. this.assetListLoader = void 0;
  21151. this.mediaSelection = null;
  21152. this.altSelection = null;
  21153. this.media = null;
  21154. this.detachedData = null;
  21155. this.requiredTracks = null;
  21156. this.manager = null;
  21157. this.playerQueue = [];
  21158. this.bufferedPos = -1;
  21159. this.timelinePos = -1;
  21160. this.schedule = void 0;
  21161. this.playingItem = null;
  21162. this.bufferingItem = null;
  21163. this.waitingItem = null;
  21164. this.endedItem = null;
  21165. this.playingAsset = null;
  21166. this.endedAsset = null;
  21167. this.bufferingAsset = null;
  21168. this.shouldPlay = false;
  21169. this.onPlay = () => {
  21170. this.shouldPlay = true;
  21171. };
  21172. this.onPause = () => {
  21173. this.shouldPlay = false;
  21174. };
  21175. this.onSeeking = () => {
  21176. const currentTime = this.currentTime;
  21177. if (currentTime === void 0 || this.playbackDisabled) {
  21178. return;
  21179. }
  21180. const diff = currentTime - this.timelinePos;
  21181. const roundingError = Math.abs(diff) < 1 / 7056e5;
  21182. if (roundingError) {
  21183. return;
  21184. }
  21185. const backwardSeek = diff <= -0.01;
  21186. this.timelinePos = currentTime;
  21187. this.bufferedPos = currentTime;
  21188. const playingItem = this.playingItem;
  21189. if (!playingItem) {
  21190. this.checkBuffer();
  21191. return;
  21192. }
  21193. if (backwardSeek) {
  21194. const resetCount = this.schedule.resetErrorsInRange(currentTime, currentTime - diff);
  21195. if (resetCount) {
  21196. this.updateSchedule();
  21197. }
  21198. }
  21199. this.checkBuffer();
  21200. if (backwardSeek && currentTime < playingItem.start || currentTime >= playingItem.end) {
  21201. var _this$media;
  21202. const scheduleIndex = this.schedule.findItemIndexAtTime(this.timelinePos);
  21203. if (!this.isInterstitial(playingItem) && (_this$media = this.media) != null && _this$media.paused) {
  21204. this.shouldPlay = false;
  21205. }
  21206. if (!backwardSeek) {
  21207. const playingIndex = this.findItemIndex(playingItem);
  21208. if (scheduleIndex > playingIndex) {
  21209. const jumpIndex = this.schedule.findJumpRestrictedIndex(playingIndex + 1, scheduleIndex);
  21210. if (jumpIndex > playingIndex) {
  21211. this.setSchedulePosition(jumpIndex);
  21212. return;
  21213. }
  21214. }
  21215. }
  21216. this.setSchedulePosition(scheduleIndex);
  21217. return;
  21218. }
  21219. const playingAsset = this.playingAsset;
  21220. if (!playingAsset) {
  21221. if (this.playingLastItem && this.isInterstitial(playingItem)) {
  21222. const restartAsset = playingItem.event.assetList[0];
  21223. if (restartAsset) {
  21224. this.endedItem = this.playingItem;
  21225. this.playingItem = null;
  21226. this.setScheduleToAssetAtTime(currentTime, restartAsset);
  21227. }
  21228. }
  21229. return;
  21230. }
  21231. const start = playingAsset.timelineStart;
  21232. const duration = playingAsset.duration || 0;
  21233. if (backwardSeek && currentTime < start || currentTime >= start + duration) {
  21234. this.setScheduleToAssetAtTime(currentTime, playingAsset);
  21235. }
  21236. };
  21237. this.onTimeupdate = () => {
  21238. const currentTime = this.currentTime;
  21239. if (currentTime === void 0 || this.playbackDisabled) {
  21240. return;
  21241. }
  21242. if (currentTime > this.timelinePos) {
  21243. this.timelinePos = currentTime;
  21244. if (currentTime > this.bufferedPos) {
  21245. this.checkBuffer();
  21246. }
  21247. } else {
  21248. return;
  21249. }
  21250. const playingItem = this.playingItem;
  21251. if (!playingItem || this.playingLastItem) {
  21252. return;
  21253. }
  21254. if (currentTime >= playingItem.end) {
  21255. this.timelinePos = playingItem.end;
  21256. const playingIndex = this.findItemIndex(playingItem);
  21257. this.setSchedulePosition(playingIndex + 1);
  21258. }
  21259. const playingAsset = this.playingAsset;
  21260. if (!playingAsset) {
  21261. return;
  21262. }
  21263. const end = playingAsset.timelineStart + (playingAsset.duration || 0);
  21264. if (currentTime >= end) {
  21265. this.setScheduleToAssetAtTime(currentTime, playingAsset);
  21266. }
  21267. };
  21268. this.onScheduleUpdate = (removedInterstitials, previousItems) => {
  21269. const schedule = this.schedule;
  21270. const playingItem = this.playingItem;
  21271. const interstitialEvents = schedule.events || [];
  21272. const scheduleItems = schedule.items || [];
  21273. const durations = schedule.durations;
  21274. const removedIds = removedInterstitials.map((interstitial) => interstitial.identifier);
  21275. const interstitialsUpdated = !!(interstitialEvents.length || removedIds.length);
  21276. if (interstitialsUpdated || previousItems) {
  21277. this.log(`INTERSTITIALS_UPDATED (${interstitialEvents.length}): ${interstitialEvents}
  21278. Schedule: ${scheduleItems.map((seg) => segmentToString(seg))} pos: ${this.timelinePos}`);
  21279. }
  21280. if (removedIds.length) {
  21281. this.log(`Removed events ${removedIds}`);
  21282. }
  21283. this.playerQueue.forEach((player) => {
  21284. if (player.interstitial.appendInPlace) {
  21285. const timelineStart = player.assetItem.timelineStart;
  21286. const diff = player.timelineOffset - timelineStart;
  21287. if (diff) {
  21288. try {
  21289. player.timelineOffset = timelineStart;
  21290. } catch (e) {
  21291. if (Math.abs(diff) > ALIGNED_END_THRESHOLD_SECONDS) {
  21292. this.warn(`${e} ("${player.assetId}" ${player.timelineOffset}->${timelineStart})`);
  21293. }
  21294. }
  21295. }
  21296. }
  21297. });
  21298. let trimInPlaceForPlayout = null;
  21299. if (playingItem) {
  21300. const updatedPlayingItem = this.updateItem(playingItem, this.timelinePos);
  21301. if (this.itemsMatch(playingItem, updatedPlayingItem)) {
  21302. this.playingItem = updatedPlayingItem;
  21303. this.waitingItem = this.endedItem = null;
  21304. trimInPlaceForPlayout = () => this.trimInPlace(updatedPlayingItem, playingItem);
  21305. }
  21306. } else {
  21307. this.waitingItem = this.updateItem(this.waitingItem);
  21308. this.endedItem = this.updateItem(this.endedItem);
  21309. }
  21310. const bufferingItem = this.bufferingItem;
  21311. if (bufferingItem) {
  21312. const updatedBufferingItem = this.updateItem(bufferingItem, this.bufferedPos);
  21313. if (this.itemsMatch(bufferingItem, updatedBufferingItem)) {
  21314. this.bufferingItem = updatedBufferingItem;
  21315. trimInPlaceForPlayout || (trimInPlaceForPlayout = () => this.trimInPlace(updatedBufferingItem, bufferingItem));
  21316. } else if (bufferingItem.event) {
  21317. this.bufferingItem = this.playingItem;
  21318. this.clearInterstitial(bufferingItem.event, null);
  21319. }
  21320. }
  21321. removedInterstitials.forEach((interstitial) => {
  21322. interstitial.assetList.forEach((asset) => {
  21323. this.clearAssetPlayer(asset.identifier, null);
  21324. });
  21325. });
  21326. if (interstitialsUpdated || previousItems) {
  21327. this.hls.trigger(Events.INTERSTITIALS_UPDATED, {
  21328. events: interstitialEvents.slice(0),
  21329. schedule: scheduleItems.slice(0),
  21330. durations,
  21331. removedIds
  21332. });
  21333. if (this.isInterstitial(playingItem) && removedIds.includes(playingItem.event.identifier)) {
  21334. this.warn(`Interstitial "${playingItem.event.identifier}" removed while playing`);
  21335. this.primaryFallback(playingItem.event);
  21336. return;
  21337. }
  21338. if (trimInPlaceForPlayout) {
  21339. trimInPlaceForPlayout();
  21340. }
  21341. this.checkBuffer();
  21342. }
  21343. };
  21344. this.hls = hls;
  21345. this.HlsPlayerClass = HlsPlayerClass;
  21346. this.assetListLoader = new AssetListLoader(hls);
  21347. this.schedule = new InterstitialsSchedule(this.onScheduleUpdate, hls.logger);
  21348. this.registerListeners();
  21349. }
  21350. registerListeners() {
  21351. const hls = this.hls;
  21352. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  21353. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  21354. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  21355. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21356. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  21357. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  21358. hls.on(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);
  21359. hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  21360. hls.on(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);
  21361. hls.on(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);
  21362. hls.on(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);
  21363. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  21364. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  21365. hls.on(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);
  21366. hls.on(Events.MEDIA_ENDED, this.onMediaEnded, this);
  21367. hls.on(Events.ERROR, this.onError, this);
  21368. hls.on(Events.DESTROYING, this.onDestroying, this);
  21369. }
  21370. unregisterListeners() {
  21371. const hls = this.hls;
  21372. if (!hls) {
  21373. return;
  21374. }
  21375. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  21376. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  21377. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  21378. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21379. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  21380. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  21381. hls.off(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);
  21382. hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  21383. hls.off(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);
  21384. hls.off(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);
  21385. hls.off(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);
  21386. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  21387. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  21388. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  21389. hls.off(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);
  21390. hls.off(Events.MEDIA_ENDED, this.onMediaEnded, this);
  21391. hls.off(Events.ERROR, this.onError, this);
  21392. hls.off(Events.DESTROYING, this.onDestroying, this);
  21393. }
  21394. startLoad() {
  21395. this.resumeBuffering();
  21396. }
  21397. stopLoad() {
  21398. this.pauseBuffering();
  21399. }
  21400. resumeBuffering() {
  21401. var _this$getBufferingPla;
  21402. (_this$getBufferingPla = this.getBufferingPlayer()) == null ? void 0 : _this$getBufferingPla.resumeBuffering();
  21403. }
  21404. pauseBuffering() {
  21405. var _this$getBufferingPla2;
  21406. (_this$getBufferingPla2 = this.getBufferingPlayer()) == null ? void 0 : _this$getBufferingPla2.pauseBuffering();
  21407. }
  21408. destroy() {
  21409. this.unregisterListeners();
  21410. this.stopLoad();
  21411. if (this.assetListLoader) {
  21412. this.assetListLoader.destroy();
  21413. }
  21414. this.emptyPlayerQueue();
  21415. this.clearScheduleState();
  21416. if (this.schedule) {
  21417. this.schedule.destroy();
  21418. }
  21419. this.media = this.detachedData = this.mediaSelection = this.requiredTracks = this.altSelection = this.manager = null;
  21420. this.hls = this.HlsPlayerClass = this.schedule = this.log = null;
  21421. this.assetListLoader = null;
  21422. this.onPlay = this.onPause = this.onSeeking = this.onTimeupdate = null;
  21423. this.onScheduleUpdate = null;
  21424. }
  21425. onDestroying() {
  21426. const media = this.primaryMedia || this.media;
  21427. if (media) {
  21428. this.removeMediaListeners(media);
  21429. }
  21430. }
  21431. removeMediaListeners(media) {
  21432. removeEventListener(media, "play", this.onPlay);
  21433. removeEventListener(media, "pause", this.onPause);
  21434. removeEventListener(media, "seeking", this.onSeeking);
  21435. removeEventListener(media, "timeupdate", this.onTimeupdate);
  21436. }
  21437. onMediaAttaching(event, data) {
  21438. const media = this.media = data.media;
  21439. addEventListener(media, "seeking", this.onSeeking);
  21440. addEventListener(media, "timeupdate", this.onTimeupdate);
  21441. addEventListener(media, "play", this.onPlay);
  21442. addEventListener(media, "pause", this.onPause);
  21443. }
  21444. onMediaAttached(event, data) {
  21445. const playingItem = this.effectivePlayingItem;
  21446. const detachedMedia = this.detachedData;
  21447. this.detachedData = null;
  21448. if (playingItem === null) {
  21449. this.checkStart();
  21450. } else if (!detachedMedia) {
  21451. this.clearScheduleState();
  21452. const playingIndex = this.findItemIndex(playingItem);
  21453. this.setSchedulePosition(playingIndex);
  21454. }
  21455. }
  21456. clearScheduleState() {
  21457. this.playingItem = this.bufferingItem = this.waitingItem = this.endedItem = this.playingAsset = this.endedAsset = this.bufferingAsset = null;
  21458. }
  21459. onMediaDetaching(event, data) {
  21460. const transferringMedia = !!data.transferMedia;
  21461. const media = this.media;
  21462. this.media = null;
  21463. if (transferringMedia) {
  21464. return;
  21465. }
  21466. if (media) {
  21467. this.removeMediaListeners(media);
  21468. }
  21469. if (this.detachedData) {
  21470. const player = this.getBufferingPlayer();
  21471. if (player) {
  21472. this.playingAsset = this.endedAsset = this.bufferingAsset = this.bufferingItem = this.waitingItem = this.detachedData = null;
  21473. player.detachMedia();
  21474. }
  21475. this.shouldPlay = false;
  21476. }
  21477. }
  21478. get interstitialsManager() {
  21479. if (!this.manager) {
  21480. if (!this.hls) {
  21481. return null;
  21482. }
  21483. const c = this;
  21484. const effectiveBufferingItem = () => c.bufferingItem || c.waitingItem;
  21485. const getAssetPlayer = (asset) => asset ? c.getAssetPlayer(asset.identifier) : asset;
  21486. const getMappedTime = (item, timelineType, asset, controllerField, assetPlayerField) => {
  21487. if (item) {
  21488. let time = item[timelineType].start;
  21489. const interstitial = item.event;
  21490. if (interstitial) {
  21491. if (timelineType === "playout" || interstitial.timelineOccupancy !== TimelineOccupancy.Point) {
  21492. const assetPlayer = getAssetPlayer(asset);
  21493. if ((assetPlayer == null ? void 0 : assetPlayer.interstitial) === interstitial) {
  21494. time += assetPlayer.assetItem.startOffset + assetPlayer[assetPlayerField];
  21495. }
  21496. }
  21497. } else {
  21498. const value = controllerField === "bufferedPos" ? getBufferedEnd() : c[controllerField];
  21499. time += value - item.start;
  21500. }
  21501. return time;
  21502. }
  21503. return 0;
  21504. };
  21505. const findMappedTime = (primaryTime, timelineType) => {
  21506. if (primaryTime !== 0 && timelineType !== "primary" && c.schedule.length) {
  21507. var _c$schedule$items;
  21508. const index = c.schedule.findItemIndexAtTime(primaryTime);
  21509. const item = (_c$schedule$items = c.schedule.items) == null ? void 0 : _c$schedule$items[index];
  21510. if (item) {
  21511. const diff = item[timelineType].start - item.start;
  21512. return primaryTime + diff;
  21513. }
  21514. }
  21515. return primaryTime;
  21516. };
  21517. const getBufferedEnd = () => {
  21518. const value = c.bufferedPos;
  21519. if (value === Number.MAX_VALUE) {
  21520. return getMappedDuration("primary");
  21521. }
  21522. return Math.max(value, 0);
  21523. };
  21524. const getMappedDuration = (timelineType) => {
  21525. var _c$primaryDetails;
  21526. if ((_c$primaryDetails = c.primaryDetails) != null && _c$primaryDetails.live) {
  21527. return c.primaryDetails.edge;
  21528. }
  21529. return c.schedule.durations[timelineType];
  21530. };
  21531. const seekTo = (time, timelineType) => {
  21532. var _item$event, _c$schedule$items2;
  21533. const item = c.effectivePlayingItem;
  21534. if (item != null && (_item$event = item.event) != null && _item$event.restrictions.skip) {
  21535. return;
  21536. }
  21537. c.log(`seek to ${time} "${timelineType}"`);
  21538. const playingItem = c.effectivePlayingItem;
  21539. const targetIndex = c.schedule.findItemIndexAtTime(time, timelineType);
  21540. const targetItem = (_c$schedule$items2 = c.schedule.items) == null ? void 0 : _c$schedule$items2[targetIndex];
  21541. const bufferingPlayer = c.getBufferingPlayer();
  21542. const bufferingInterstitial = bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial;
  21543. const appendInPlace = bufferingInterstitial == null ? void 0 : bufferingInterstitial.appendInPlace;
  21544. const seekInItem = playingItem && c.itemsMatch(playingItem, targetItem);
  21545. if (playingItem && (appendInPlace || seekInItem)) {
  21546. const assetPlayer = getAssetPlayer(c.playingAsset);
  21547. const media = (assetPlayer == null ? void 0 : assetPlayer.media) || c.primaryMedia;
  21548. if (media) {
  21549. const currentTime = timelineType === "primary" ? media.currentTime : getMappedTime(playingItem, timelineType, c.playingAsset, "timelinePos", "currentTime");
  21550. const diff = time - currentTime;
  21551. const seekToTime = (appendInPlace ? currentTime : media.currentTime) + diff;
  21552. if (seekToTime >= 0 && (!assetPlayer || appendInPlace || seekToTime <= assetPlayer.duration)) {
  21553. media.currentTime = seekToTime;
  21554. return;
  21555. }
  21556. }
  21557. }
  21558. if (targetItem) {
  21559. let seekToTime = time;
  21560. if (timelineType !== "primary") {
  21561. const primarySegmentStart = targetItem[timelineType].start;
  21562. const diff = time - primarySegmentStart;
  21563. seekToTime = targetItem.start + diff;
  21564. }
  21565. const targetIsPrimary = !c.isInterstitial(targetItem);
  21566. if ((!c.isInterstitial(playingItem) || playingItem.event.appendInPlace) && (targetIsPrimary || targetItem.event.appendInPlace)) {
  21567. const media = c.media || (appendInPlace ? bufferingPlayer == null ? void 0 : bufferingPlayer.media : null);
  21568. if (media) {
  21569. media.currentTime = seekToTime;
  21570. }
  21571. } else if (playingItem) {
  21572. const playingIndex = c.findItemIndex(playingItem);
  21573. if (targetIndex > playingIndex) {
  21574. const jumpIndex = c.schedule.findJumpRestrictedIndex(playingIndex + 1, targetIndex);
  21575. if (jumpIndex > playingIndex) {
  21576. c.setSchedulePosition(jumpIndex);
  21577. return;
  21578. }
  21579. }
  21580. let assetIndex = 0;
  21581. if (targetIsPrimary) {
  21582. c.timelinePos = seekToTime;
  21583. c.checkBuffer();
  21584. } else {
  21585. var _targetItem$event;
  21586. const assetList = targetItem == null ? void 0 : (_targetItem$event = targetItem.event) == null ? void 0 : _targetItem$event.assetList;
  21587. if (assetList) {
  21588. const eventTime = time - (targetItem[timelineType] || targetItem).start;
  21589. for (let i = assetList.length; i--; ) {
  21590. const asset = assetList[i];
  21591. if (asset.duration && eventTime >= asset.startOffset && eventTime < asset.startOffset + asset.duration) {
  21592. assetIndex = i;
  21593. break;
  21594. }
  21595. }
  21596. }
  21597. }
  21598. c.setSchedulePosition(targetIndex, assetIndex);
  21599. }
  21600. }
  21601. };
  21602. const getActiveInterstitial = () => {
  21603. const playingItem = c.effectivePlayingItem;
  21604. if (c.isInterstitial(playingItem)) {
  21605. return playingItem;
  21606. }
  21607. const bufferingItem = effectiveBufferingItem();
  21608. if (c.isInterstitial(bufferingItem)) {
  21609. return bufferingItem;
  21610. }
  21611. return null;
  21612. };
  21613. const interstitialPlayer = {
  21614. get currentTime() {
  21615. const interstitialItem = getActiveInterstitial();
  21616. const playingItem = c.effectivePlayingItem;
  21617. if (playingItem && playingItem === interstitialItem) {
  21618. return getMappedTime(playingItem, "playout", c.effectivePlayingAsset, "timelinePos", "currentTime") - playingItem.playout.start;
  21619. }
  21620. return 0;
  21621. },
  21622. set currentTime(time) {
  21623. const interstitialItem = getActiveInterstitial();
  21624. const playingItem = c.effectivePlayingItem;
  21625. if (playingItem && playingItem === interstitialItem) {
  21626. seekTo(time + playingItem.playout.start, "playout");
  21627. }
  21628. },
  21629. get duration() {
  21630. const interstitialItem = getActiveInterstitial();
  21631. if (interstitialItem) {
  21632. return interstitialItem.playout.end - interstitialItem.playout.start;
  21633. }
  21634. return 0;
  21635. },
  21636. get assetPlayers() {
  21637. var _getActiveInterstitia;
  21638. const assetList = (_getActiveInterstitia = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia.event.assetList;
  21639. if (assetList) {
  21640. return assetList.map((asset) => c.getAssetPlayer(asset.identifier));
  21641. }
  21642. return [];
  21643. },
  21644. get playingIndex() {
  21645. var _getActiveInterstitia2;
  21646. const interstitial = (_getActiveInterstitia2 = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia2.event;
  21647. if (interstitial && c.effectivePlayingAsset) {
  21648. return interstitial.findAssetIndex(c.effectivePlayingAsset);
  21649. }
  21650. return -1;
  21651. },
  21652. get scheduleItem() {
  21653. return getActiveInterstitial();
  21654. }
  21655. };
  21656. this.manager = {
  21657. get events() {
  21658. var _c$schedule, _c$schedule$events;
  21659. return ((_c$schedule = c.schedule) == null ? void 0 : (_c$schedule$events = _c$schedule.events) == null ? void 0 : _c$schedule$events.slice(0)) || [];
  21660. },
  21661. get schedule() {
  21662. var _c$schedule2, _c$schedule2$items;
  21663. return ((_c$schedule2 = c.schedule) == null ? void 0 : (_c$schedule2$items = _c$schedule2.items) == null ? void 0 : _c$schedule2$items.slice(0)) || [];
  21664. },
  21665. get interstitialPlayer() {
  21666. if (getActiveInterstitial()) {
  21667. return interstitialPlayer;
  21668. }
  21669. return null;
  21670. },
  21671. get playerQueue() {
  21672. return c.playerQueue.slice(0);
  21673. },
  21674. get bufferingAsset() {
  21675. return c.bufferingAsset;
  21676. },
  21677. get bufferingItem() {
  21678. return effectiveBufferingItem();
  21679. },
  21680. get bufferingIndex() {
  21681. const item = effectiveBufferingItem();
  21682. return c.findItemIndex(item);
  21683. },
  21684. get playingAsset() {
  21685. return c.effectivePlayingAsset;
  21686. },
  21687. get playingItem() {
  21688. return c.effectivePlayingItem;
  21689. },
  21690. get playingIndex() {
  21691. const item = c.effectivePlayingItem;
  21692. return c.findItemIndex(item);
  21693. },
  21694. primary: {
  21695. get bufferedEnd() {
  21696. return getBufferedEnd();
  21697. },
  21698. get currentTime() {
  21699. const timelinePos = c.timelinePos;
  21700. return timelinePos > 0 ? timelinePos : 0;
  21701. },
  21702. set currentTime(time) {
  21703. seekTo(time, "primary");
  21704. },
  21705. get duration() {
  21706. return getMappedDuration("primary");
  21707. },
  21708. get seekableStart() {
  21709. var _c$primaryDetails2;
  21710. return ((_c$primaryDetails2 = c.primaryDetails) == null ? void 0 : _c$primaryDetails2.fragmentStart) || 0;
  21711. }
  21712. },
  21713. integrated: {
  21714. get bufferedEnd() {
  21715. return getMappedTime(effectiveBufferingItem(), "integrated", c.bufferingAsset, "bufferedPos", "bufferedEnd");
  21716. },
  21717. get currentTime() {
  21718. return getMappedTime(c.effectivePlayingItem, "integrated", c.effectivePlayingAsset, "timelinePos", "currentTime");
  21719. },
  21720. set currentTime(time) {
  21721. seekTo(time, "integrated");
  21722. },
  21723. get duration() {
  21724. return getMappedDuration("integrated");
  21725. },
  21726. get seekableStart() {
  21727. var _c$primaryDetails3;
  21728. return findMappedTime(((_c$primaryDetails3 = c.primaryDetails) == null ? void 0 : _c$primaryDetails3.fragmentStart) || 0, "integrated");
  21729. }
  21730. },
  21731. skip: () => {
  21732. const item = c.effectivePlayingItem;
  21733. const event = item == null ? void 0 : item.event;
  21734. if (event && !event.restrictions.skip) {
  21735. const index = c.findItemIndex(item);
  21736. if (event.appendInPlace) {
  21737. const time = item.playout.start + item.event.duration;
  21738. seekTo(time + 1e-3, "playout");
  21739. } else {
  21740. c.advanceAfterAssetEnded(event, index, Infinity);
  21741. }
  21742. }
  21743. }
  21744. };
  21745. }
  21746. return this.manager;
  21747. }
  21748. get effectivePlayingItem() {
  21749. return this.waitingItem || this.playingItem || this.endedItem;
  21750. }
  21751. get effectivePlayingAsset() {
  21752. return this.playingAsset || this.endedAsset;
  21753. }
  21754. get playingLastItem() {
  21755. var _this$schedule;
  21756. const playingItem = this.playingItem;
  21757. const items = (_this$schedule = this.schedule) == null ? void 0 : _this$schedule.items;
  21758. if (!this.playbackStarted || !playingItem || !items) {
  21759. return false;
  21760. }
  21761. return this.findItemIndex(playingItem) === items.length - 1;
  21762. }
  21763. get playbackStarted() {
  21764. return this.effectivePlayingItem !== null;
  21765. }
  21766. get currentTime() {
  21767. var _this$bufferingItem, _this$bufferingItem$e, _media;
  21768. if (this.mediaSelection === null) {
  21769. return void 0;
  21770. }
  21771. const queuedForPlayback = this.waitingItem || this.playingItem;
  21772. if (this.isInterstitial(queuedForPlayback) && !queuedForPlayback.event.appendInPlace) {
  21773. return void 0;
  21774. }
  21775. let media = this.media;
  21776. if (!media && (_this$bufferingItem = this.bufferingItem) != null && (_this$bufferingItem$e = _this$bufferingItem.event) != null && _this$bufferingItem$e.appendInPlace) {
  21777. media = this.primaryMedia;
  21778. }
  21779. const currentTime = (_media = media) == null ? void 0 : _media.currentTime;
  21780. if (currentTime === void 0 || !isFiniteNumber(currentTime)) {
  21781. return void 0;
  21782. }
  21783. return currentTime;
  21784. }
  21785. get primaryMedia() {
  21786. var _this$detachedData;
  21787. return this.media || ((_this$detachedData = this.detachedData) == null ? void 0 : _this$detachedData.media) || null;
  21788. }
  21789. isInterstitial(item) {
  21790. return !!(item != null && item.event);
  21791. }
  21792. retreiveMediaSource(assetId, toSegment) {
  21793. const player = this.getAssetPlayer(assetId);
  21794. if (player) {
  21795. this.transferMediaFromPlayer(player, toSegment);
  21796. }
  21797. }
  21798. transferMediaFromPlayer(player, toSegment) {
  21799. const appendInPlace = player.interstitial.appendInPlace;
  21800. const playerMedia = player.media;
  21801. if (appendInPlace && playerMedia === this.primaryMedia) {
  21802. this.bufferingAsset = null;
  21803. if (!toSegment || this.isInterstitial(toSegment) && !toSegment.event.appendInPlace) {
  21804. if (toSegment && playerMedia) {
  21805. this.detachedData = {
  21806. media: playerMedia
  21807. };
  21808. return;
  21809. }
  21810. }
  21811. const attachMediaSourceData = player.transferMedia();
  21812. this.log(`transfer MediaSource from ${player} ${stringify(attachMediaSourceData)}`);
  21813. this.detachedData = attachMediaSourceData;
  21814. } else if (toSegment && playerMedia) {
  21815. this.shouldPlay || (this.shouldPlay = !playerMedia.paused);
  21816. }
  21817. }
  21818. transferMediaTo(player, media) {
  21819. var _this$detachedData2, _attachMediaSourceDat;
  21820. if (player.media === media) {
  21821. return;
  21822. }
  21823. let attachMediaSourceData = null;
  21824. const primaryPlayer = this.hls;
  21825. const isAssetPlayer = player !== primaryPlayer;
  21826. const appendInPlace = isAssetPlayer && player.interstitial.appendInPlace;
  21827. const detachedMediaSource = (_this$detachedData2 = this.detachedData) == null ? void 0 : _this$detachedData2.mediaSource;
  21828. let logFromSource;
  21829. if (primaryPlayer.media) {
  21830. if (appendInPlace) {
  21831. attachMediaSourceData = primaryPlayer.transferMedia();
  21832. this.detachedData = attachMediaSourceData;
  21833. }
  21834. logFromSource = `Primary`;
  21835. } else if (detachedMediaSource) {
  21836. const bufferingPlayer = this.getBufferingPlayer();
  21837. if (bufferingPlayer) {
  21838. attachMediaSourceData = bufferingPlayer.transferMedia();
  21839. logFromSource = `${bufferingPlayer}`;
  21840. } else {
  21841. logFromSource = `detached MediaSource`;
  21842. }
  21843. } else {
  21844. logFromSource = `detached media`;
  21845. }
  21846. if (!attachMediaSourceData) {
  21847. if (detachedMediaSource) {
  21848. attachMediaSourceData = this.detachedData;
  21849. this.log(`using detachedData: MediaSource ${stringify(attachMediaSourceData)}`);
  21850. } else if (!this.detachedData || primaryPlayer.media === media) {
  21851. const playerQueue = this.playerQueue;
  21852. if (playerQueue.length > 1) {
  21853. playerQueue.forEach((queuedPlayer) => {
  21854. if (isAssetPlayer && queuedPlayer.interstitial.appendInPlace !== appendInPlace) {
  21855. const interstitial = queuedPlayer.interstitial;
  21856. this.clearInterstitial(queuedPlayer.interstitial, null);
  21857. interstitial.appendInPlace = false;
  21858. if (interstitial.appendInPlace) {
  21859. this.warn(`Could not change append strategy for queued assets ${interstitial}`);
  21860. }
  21861. }
  21862. });
  21863. }
  21864. this.hls.detachMedia();
  21865. this.detachedData = {
  21866. media
  21867. };
  21868. }
  21869. }
  21870. const transferring = attachMediaSourceData && "mediaSource" in attachMediaSourceData && ((_attachMediaSourceDat = attachMediaSourceData.mediaSource) == null ? void 0 : _attachMediaSourceDat.readyState) !== "closed";
  21871. const dataToAttach = transferring && attachMediaSourceData ? attachMediaSourceData : media;
  21872. this.log(`${transferring ? "transfering MediaSource" : "attaching media"} to ${isAssetPlayer ? player : "Primary"} from ${logFromSource}`);
  21873. if (dataToAttach === attachMediaSourceData) {
  21874. const isAssetAtEndOfSchedule = isAssetPlayer && player.assetId === this.schedule.assetIdAtEnd;
  21875. dataToAttach.overrides = {
  21876. duration: this.schedule.duration,
  21877. endOfStream: !isAssetPlayer || isAssetAtEndOfSchedule,
  21878. cueRemoval: !isAssetPlayer
  21879. };
  21880. }
  21881. player.attachMedia(dataToAttach);
  21882. }
  21883. onInterstitialCueEnter() {
  21884. this.onTimeupdate();
  21885. }
  21886. checkStart() {
  21887. const schedule = this.schedule;
  21888. const interstitialEvents = schedule.events;
  21889. if (!interstitialEvents || this.playbackDisabled || !this.media) {
  21890. return;
  21891. }
  21892. if (this.bufferedPos === -1) {
  21893. this.bufferedPos = 0;
  21894. }
  21895. const timelinePos = this.timelinePos;
  21896. const effectivePlayingItem = this.effectivePlayingItem;
  21897. if (timelinePos === -1) {
  21898. const startPosition = this.hls.startPosition;
  21899. this.timelinePos = startPosition;
  21900. if (interstitialEvents.length && interstitialEvents[0].cue.pre) {
  21901. const index = schedule.findEventIndex(interstitialEvents[0].identifier);
  21902. this.setSchedulePosition(index);
  21903. } else if (startPosition >= 0 || !this.primaryLive) {
  21904. const start = this.timelinePos = startPosition > 0 ? startPosition : 0;
  21905. const index = schedule.findItemIndexAtTime(start);
  21906. this.setSchedulePosition(index);
  21907. }
  21908. } else if (effectivePlayingItem && !this.playingItem) {
  21909. const index = schedule.findItemIndex(effectivePlayingItem);
  21910. this.setSchedulePosition(index);
  21911. }
  21912. }
  21913. advanceAfterAssetEnded(interstitial, index, assetListIndex) {
  21914. const nextAssetIndex = getNextAssetIndex(interstitial, assetListIndex);
  21915. if (!interstitial.isAssetPastPlayoutLimit(nextAssetIndex)) {
  21916. this.setSchedulePosition(index, nextAssetIndex);
  21917. } else {
  21918. const scheduleItems = this.schedule.items;
  21919. if (scheduleItems) {
  21920. const nextIndex = index + 1;
  21921. const scheduleLength = scheduleItems.length;
  21922. if (nextIndex >= scheduleLength) {
  21923. this.setSchedulePosition(-1);
  21924. return;
  21925. }
  21926. const resumptionTime = interstitial.resumeTime;
  21927. if (this.timelinePos < resumptionTime) {
  21928. this.timelinePos = resumptionTime;
  21929. this.checkBuffer();
  21930. }
  21931. this.setSchedulePosition(nextIndex);
  21932. }
  21933. }
  21934. }
  21935. setScheduleToAssetAtTime(time, playingAsset) {
  21936. const schedule = this.schedule;
  21937. const parentIdentifier = playingAsset.parentIdentifier;
  21938. const interstitial = schedule.getEvent(parentIdentifier);
  21939. if (interstitial) {
  21940. const itemIndex = schedule.findEventIndex(parentIdentifier);
  21941. const assetListIndex = schedule.findAssetIndex(interstitial, time);
  21942. this.advanceAfterAssetEnded(interstitial, itemIndex, assetListIndex - 1);
  21943. }
  21944. }
  21945. setSchedulePosition(index, assetListIndex) {
  21946. const scheduleItems = this.schedule.items;
  21947. if (!scheduleItems || this.playbackDisabled) {
  21948. return;
  21949. }
  21950. this.log(`setSchedulePosition ${index}, ${assetListIndex}`);
  21951. const scheduledItem = index >= 0 ? scheduleItems[index] : null;
  21952. const currentItem = this.playingItem;
  21953. const playingLastItem = this.playingLastItem;
  21954. if (this.isInterstitial(currentItem)) {
  21955. var _interstitial$assetLi;
  21956. const interstitial = currentItem.event;
  21957. const playingAsset = this.playingAsset;
  21958. const assetId = playingAsset == null ? void 0 : playingAsset.identifier;
  21959. const player = assetId ? this.getAssetPlayer(assetId) : null;
  21960. if (player && assetId && (!this.eventItemsMatch(currentItem, scheduledItem) || assetListIndex !== void 0 && assetId !== ((_interstitial$assetLi = interstitial.assetList) == null ? void 0 : _interstitial$assetLi[assetListIndex].identifier))) {
  21961. var _this$detachedData3;
  21962. const playingAssetListIndex = interstitial.findAssetIndex(playingAsset);
  21963. this.log(`INTERSTITIAL_ASSET_ENDED ${playingAssetListIndex + 1}/${interstitial.assetList.length} ${eventAssetToString(playingAsset)}`);
  21964. this.endedAsset = playingAsset;
  21965. this.playingAsset = null;
  21966. this.hls.trigger(Events.INTERSTITIAL_ASSET_ENDED, {
  21967. asset: playingAsset,
  21968. assetListIndex: playingAssetListIndex,
  21969. event: interstitial,
  21970. schedule: scheduleItems.slice(0),
  21971. scheduleIndex: index,
  21972. player
  21973. });
  21974. if (currentItem !== this.playingItem) {
  21975. if (this.itemsMatch(currentItem, this.playingItem) && !this.playingAsset) {
  21976. this.advanceAfterAssetEnded(interstitial, this.findItemIndex(this.playingItem), playingAssetListIndex);
  21977. }
  21978. return;
  21979. }
  21980. this.retreiveMediaSource(assetId, scheduledItem);
  21981. if (player.media && !((_this$detachedData3 = this.detachedData) != null && _this$detachedData3.mediaSource)) {
  21982. player.detachMedia();
  21983. }
  21984. }
  21985. if (!this.eventItemsMatch(currentItem, scheduledItem)) {
  21986. this.endedItem = currentItem;
  21987. this.playingItem = null;
  21988. this.log(`INTERSTITIAL_ENDED ${interstitial} ${segmentToString(currentItem)}`);
  21989. interstitial.hasPlayed = true;
  21990. this.hls.trigger(Events.INTERSTITIAL_ENDED, {
  21991. event: interstitial,
  21992. schedule: scheduleItems.slice(0),
  21993. scheduleIndex: index
  21994. });
  21995. if (interstitial.cue.once) {
  21996. this.updateSchedule();
  21997. const items = this.schedule.items;
  21998. if (scheduledItem && items) {
  21999. const updatedIndex = this.findItemIndex(scheduledItem);
  22000. this.advanceSchedule(updatedIndex, items, assetListIndex, currentItem, playingLastItem);
  22001. }
  22002. return;
  22003. }
  22004. }
  22005. }
  22006. this.advanceSchedule(index, scheduleItems, assetListIndex, currentItem, playingLastItem);
  22007. }
  22008. advanceSchedule(index, scheduleItems, assetListIndex, currentItem, playedLastItem) {
  22009. const scheduledItem = index >= 0 ? scheduleItems[index] : null;
  22010. const media = this.primaryMedia;
  22011. const playerQueue = this.playerQueue;
  22012. if (playerQueue.length) {
  22013. playerQueue.forEach((player) => {
  22014. const interstitial = player.interstitial;
  22015. const queuedIndex = this.schedule.findEventIndex(interstitial.identifier);
  22016. if (queuedIndex < index || queuedIndex > index + 1) {
  22017. this.clearInterstitial(interstitial, scheduledItem);
  22018. }
  22019. });
  22020. }
  22021. if (this.isInterstitial(scheduledItem)) {
  22022. this.timelinePos = Math.min(Math.max(this.timelinePos, scheduledItem.start), scheduledItem.end);
  22023. const interstitial = scheduledItem.event;
  22024. if (assetListIndex === void 0) {
  22025. assetListIndex = this.schedule.findAssetIndex(interstitial, this.timelinePos);
  22026. const assetIndexCandidate = getNextAssetIndex(interstitial, assetListIndex - 1);
  22027. if (interstitial.isAssetPastPlayoutLimit(assetIndexCandidate)) {
  22028. this.advanceAfterAssetEnded(interstitial, index, assetListIndex);
  22029. return;
  22030. }
  22031. assetListIndex = assetIndexCandidate;
  22032. }
  22033. const waitingItem = this.waitingItem;
  22034. if (!this.assetsBuffered(scheduledItem, media)) {
  22035. this.setBufferingItem(scheduledItem);
  22036. }
  22037. let player = this.preloadAssets(interstitial, assetListIndex);
  22038. if (!this.eventItemsMatch(scheduledItem, waitingItem || currentItem)) {
  22039. this.waitingItem = scheduledItem;
  22040. this.log(`INTERSTITIAL_STARTED ${segmentToString(scheduledItem)} ${interstitial.appendInPlace ? "append in place" : ""}`);
  22041. this.hls.trigger(Events.INTERSTITIAL_STARTED, {
  22042. event: interstitial,
  22043. schedule: scheduleItems.slice(0),
  22044. scheduleIndex: index
  22045. });
  22046. }
  22047. if (!interstitial.assetListLoaded) {
  22048. this.log(`Waiting for ASSET-LIST to complete loading ${interstitial}`);
  22049. return;
  22050. }
  22051. if (interstitial.assetListLoader) {
  22052. interstitial.assetListLoader.destroy();
  22053. interstitial.assetListLoader = void 0;
  22054. }
  22055. if (!media) {
  22056. this.log(`Waiting for attachMedia to start Interstitial ${interstitial}`);
  22057. return;
  22058. }
  22059. this.waitingItem = this.endedItem = null;
  22060. this.playingItem = scheduledItem;
  22061. const assetItem = interstitial.assetList[assetListIndex];
  22062. if (!assetItem) {
  22063. const nextItem = scheduleItems[index + 1];
  22064. const _media2 = this.media;
  22065. if (nextItem && _media2 && !this.isInterstitial(nextItem) && _media2.currentTime < nextItem.start) {
  22066. _media2.currentTime = this.timelinePos = nextItem.start;
  22067. }
  22068. this.advanceAfterAssetEnded(interstitial, index, assetListIndex || 0);
  22069. return;
  22070. }
  22071. if (!player) {
  22072. player = this.getAssetPlayer(assetItem.identifier);
  22073. }
  22074. if (player === null || player.destroyed) {
  22075. const assetListLength = interstitial.assetList.length;
  22076. this.warn(`asset ${assetListIndex + 1}/${assetListLength} player destroyed ${interstitial}`);
  22077. player = this.createAssetPlayer(interstitial, assetItem, assetListIndex);
  22078. }
  22079. if (!this.eventItemsMatch(scheduledItem, this.bufferingItem)) {
  22080. if (interstitial.appendInPlace && this.isAssetBuffered(assetItem)) {
  22081. return;
  22082. }
  22083. }
  22084. this.startAssetPlayer(player, assetListIndex, scheduleItems, index, media);
  22085. if (this.shouldPlay) {
  22086. playWithCatch(player.media);
  22087. }
  22088. } else if (scheduledItem !== null) {
  22089. this.resumePrimary(scheduledItem, index, currentItem);
  22090. if (this.shouldPlay) {
  22091. playWithCatch(this.hls.media);
  22092. }
  22093. } else if (playedLastItem && this.isInterstitial(currentItem)) {
  22094. this.endedItem = null;
  22095. this.playingItem = currentItem;
  22096. if (!currentItem.event.appendInPlace) {
  22097. this.attachPrimary(this.schedule.durations.primary, null);
  22098. }
  22099. }
  22100. }
  22101. get playbackDisabled() {
  22102. return this.hls.config.enableInterstitialPlayback === false;
  22103. }
  22104. get primaryDetails() {
  22105. var _this$mediaSelection, _this$mediaSelection$;
  22106. return (_this$mediaSelection = this.mediaSelection) == null ? void 0 : (_this$mediaSelection$ = _this$mediaSelection.main) == null ? void 0 : _this$mediaSelection$.details;
  22107. }
  22108. get primaryLive() {
  22109. var _this$primaryDetails;
  22110. return !!((_this$primaryDetails = this.primaryDetails) != null && _this$primaryDetails.live);
  22111. }
  22112. resumePrimary(scheduledItem, index, fromItem) {
  22113. var _this$detachedData4;
  22114. this.playingItem = scheduledItem;
  22115. this.playingAsset = this.endedAsset = null;
  22116. this.waitingItem = this.endedItem = null;
  22117. this.bufferedToItem(scheduledItem);
  22118. this.log(`resuming ${segmentToString(scheduledItem)}`);
  22119. if (!((_this$detachedData4 = this.detachedData) != null && _this$detachedData4.mediaSource)) {
  22120. let timelinePos = this.timelinePos;
  22121. if (timelinePos < scheduledItem.start || timelinePos >= scheduledItem.end) {
  22122. timelinePos = this.getPrimaryResumption(scheduledItem, index);
  22123. this.timelinePos = timelinePos;
  22124. }
  22125. this.attachPrimary(timelinePos, scheduledItem);
  22126. }
  22127. if (!fromItem) {
  22128. return;
  22129. }
  22130. const scheduleItems = this.schedule.items;
  22131. if (!scheduleItems) {
  22132. return;
  22133. }
  22134. this.log(`INTERSTITIALS_PRIMARY_RESUMED ${segmentToString(scheduledItem)}`);
  22135. this.hls.trigger(Events.INTERSTITIALS_PRIMARY_RESUMED, {
  22136. schedule: scheduleItems.slice(0),
  22137. scheduleIndex: index
  22138. });
  22139. this.checkBuffer();
  22140. }
  22141. getPrimaryResumption(scheduledItem, index) {
  22142. const itemStart = scheduledItem.start;
  22143. if (this.primaryLive) {
  22144. const details = this.primaryDetails;
  22145. if (index === 0) {
  22146. return this.hls.startPosition;
  22147. } else if (details && (itemStart < details.fragmentStart || itemStart > details.edge)) {
  22148. return this.hls.liveSyncPosition || -1;
  22149. }
  22150. }
  22151. return itemStart;
  22152. }
  22153. isAssetBuffered(asset) {
  22154. const player = this.getAssetPlayer(asset.identifier);
  22155. if (player != null && player.hls) {
  22156. return player.hls.bufferedToEnd;
  22157. }
  22158. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);
  22159. return bufferInfo.end + 1 >= asset.timelineStart + (asset.duration || 0);
  22160. }
  22161. attachPrimary(timelinePos, item, skipSeekToStartPosition) {
  22162. if (item) {
  22163. this.setBufferingItem(item);
  22164. } else {
  22165. this.bufferingItem = this.playingItem;
  22166. }
  22167. this.bufferingAsset = null;
  22168. const media = this.primaryMedia;
  22169. if (!media) {
  22170. return;
  22171. }
  22172. const hls = this.hls;
  22173. if (hls.media) {
  22174. this.checkBuffer();
  22175. } else {
  22176. this.transferMediaTo(hls, media);
  22177. if (skipSeekToStartPosition) {
  22178. this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);
  22179. }
  22180. }
  22181. if (!skipSeekToStartPosition) {
  22182. this.timelinePos = timelinePos;
  22183. this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);
  22184. }
  22185. }
  22186. startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition) {
  22187. var _hls$mainForwardBuffe;
  22188. const hls = this.hls;
  22189. if (!hls.loadingEnabled || !hls.media || Math.abs((((_hls$mainForwardBuffe = hls.mainForwardBufferInfo) == null ? void 0 : _hls$mainForwardBuffe.start) || hls.media.currentTime) - timelinePos) > 0.5) {
  22190. hls.startLoad(timelinePos, skipSeekToStartPosition);
  22191. } else if (!hls.bufferingEnabled) {
  22192. hls.resumeBuffering();
  22193. }
  22194. }
  22195. onManifestLoading() {
  22196. this.stopLoad();
  22197. this.schedule.reset();
  22198. this.emptyPlayerQueue();
  22199. this.clearScheduleState();
  22200. this.shouldPlay = false;
  22201. this.bufferedPos = this.timelinePos = -1;
  22202. this.mediaSelection = this.altSelection = this.manager = this.requiredTracks = null;
  22203. this.hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  22204. this.hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  22205. }
  22206. onLevelUpdated(event, data) {
  22207. if (data.level === -1) {
  22208. return;
  22209. }
  22210. const main = this.hls.levels[data.level];
  22211. const currentSelection = _objectSpread2(_objectSpread2({}, this.mediaSelection || this.altSelection), {}, {
  22212. main
  22213. });
  22214. this.mediaSelection = currentSelection;
  22215. this.schedule.parseInterstitialDateRanges(currentSelection, this.hls.config.interstitialAppendInPlace);
  22216. if (!this.effectivePlayingItem && this.schedule.items) {
  22217. this.checkStart();
  22218. }
  22219. }
  22220. onAudioTrackUpdated(event, data) {
  22221. const audio = this.hls.audioTracks[data.id];
  22222. const previousSelection = this.mediaSelection;
  22223. if (!previousSelection) {
  22224. this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {
  22225. audio
  22226. });
  22227. return;
  22228. }
  22229. const currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {
  22230. audio
  22231. });
  22232. this.mediaSelection = currentSelection;
  22233. }
  22234. onSubtitleTrackUpdated(event, data) {
  22235. const subtitles = this.hls.subtitleTracks[data.id];
  22236. const previousSelection = this.mediaSelection;
  22237. if (!previousSelection) {
  22238. this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {
  22239. subtitles
  22240. });
  22241. return;
  22242. }
  22243. const currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {
  22244. subtitles
  22245. });
  22246. this.mediaSelection = currentSelection;
  22247. }
  22248. onAudioTrackSwitching(event, data) {
  22249. const audioOption = getBasicSelectionOption(data);
  22250. this.playerQueue.forEach((player) => player.hls.setAudioOption(data) || player.hls.setAudioOption(audioOption));
  22251. }
  22252. onSubtitleTrackSwitch(event, data) {
  22253. const subtitleOption = getBasicSelectionOption(data);
  22254. this.playerQueue.forEach((player) => player.hls.setSubtitleOption(data) || data.id !== -1 && player.hls.setSubtitleOption(subtitleOption));
  22255. }
  22256. onBufferCodecs(event, data) {
  22257. const requiredTracks = data.tracks;
  22258. if (requiredTracks) {
  22259. this.requiredTracks = requiredTracks;
  22260. }
  22261. }
  22262. onBufferAppended(event, data) {
  22263. this.checkBuffer();
  22264. }
  22265. onBufferFlushed(event, data) {
  22266. const playingItem = this.playingItem;
  22267. if (playingItem && !this.itemsMatch(playingItem, this.bufferingItem) && !this.isInterstitial(playingItem)) {
  22268. const timelinePos = this.timelinePos;
  22269. this.bufferedPos = timelinePos;
  22270. this.checkBuffer();
  22271. }
  22272. }
  22273. onBufferedToEnd(event) {
  22274. const interstitialEvents = this.schedule.events;
  22275. if (this.bufferedPos < Number.MAX_VALUE && interstitialEvents) {
  22276. for (let i = 0; i < interstitialEvents.length; i++) {
  22277. const interstitial = interstitialEvents[i];
  22278. if (interstitial.cue.post) {
  22279. var _this$schedule$items;
  22280. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  22281. const item = (_this$schedule$items = this.schedule.items) == null ? void 0 : _this$schedule$items[scheduleIndex];
  22282. if (this.isInterstitial(item) && this.eventItemsMatch(item, this.bufferingItem)) {
  22283. this.bufferedToItem(item, 0);
  22284. }
  22285. break;
  22286. }
  22287. }
  22288. this.bufferedPos = Number.MAX_VALUE;
  22289. }
  22290. }
  22291. onMediaEnded(event) {
  22292. const playingItem = this.playingItem;
  22293. if (!this.playingLastItem && playingItem) {
  22294. const playingIndex = this.findItemIndex(playingItem);
  22295. this.setSchedulePosition(playingIndex + 1);
  22296. } else {
  22297. this.shouldPlay = false;
  22298. }
  22299. }
  22300. updateItem(previousItem, time) {
  22301. const items = this.schedule.items;
  22302. if (previousItem && items) {
  22303. const index = this.findItemIndex(previousItem, time);
  22304. return items[index] || null;
  22305. }
  22306. return null;
  22307. }
  22308. trimInPlace(updatedItem, itemBeforeUpdate) {
  22309. if (this.isInterstitial(updatedItem) && updatedItem.event.appendInPlace && itemBeforeUpdate.end - updatedItem.end > 0.25) {
  22310. updatedItem.event.assetList.forEach((asset, index) => {
  22311. if (updatedItem.event.isAssetPastPlayoutLimit(index)) {
  22312. this.clearAssetPlayer(asset.identifier, null);
  22313. }
  22314. });
  22315. const flushStart = updatedItem.end + 0.25;
  22316. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, flushStart, 0);
  22317. if (bufferInfo.end > flushStart || (bufferInfo.nextStart || 0) > flushStart) {
  22318. this.attachPrimary(flushStart, null);
  22319. this.flushFrontBuffer(flushStart);
  22320. }
  22321. }
  22322. }
  22323. itemsMatch(a, b) {
  22324. return !!b && (a === b || a.event && b.event && this.eventItemsMatch(a, b) || !a.event && !b.event && this.findItemIndex(a) === this.findItemIndex(b));
  22325. }
  22326. eventItemsMatch(a, b) {
  22327. var _b$event;
  22328. return !!b && (a === b || a.event.identifier === ((_b$event = b.event) == null ? void 0 : _b$event.identifier));
  22329. }
  22330. findItemIndex(item, time) {
  22331. return item ? this.schedule.findItemIndex(item, time) : -1;
  22332. }
  22333. updateSchedule() {
  22334. const mediaSelection = this.mediaSelection;
  22335. if (!mediaSelection) {
  22336. return;
  22337. }
  22338. this.schedule.updateSchedule(mediaSelection, []);
  22339. }
  22340. checkBuffer(starved) {
  22341. const items = this.schedule.items;
  22342. if (!items) {
  22343. return;
  22344. }
  22345. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);
  22346. if (starved) {
  22347. this.bufferedPos = this.timelinePos;
  22348. }
  22349. starved || (starved = bufferInfo.len < 1);
  22350. this.updateBufferedPos(bufferInfo.end, items, starved);
  22351. }
  22352. updateBufferedPos(bufferEnd, items, bufferIsEmpty) {
  22353. const schedule = this.schedule;
  22354. const bufferingItem = this.bufferingItem;
  22355. if (this.bufferedPos > bufferEnd) {
  22356. return;
  22357. }
  22358. if (items.length === 1 && this.itemsMatch(items[0], bufferingItem)) {
  22359. this.bufferedPos = bufferEnd;
  22360. return;
  22361. }
  22362. const playingItem = this.playingItem;
  22363. const playingIndex = this.findItemIndex(playingItem);
  22364. let bufferEndIndex = schedule.findItemIndexAtTime(bufferEnd);
  22365. if (this.bufferedPos < bufferEnd) {
  22366. var _nextItemToBuffer$eve, _bufferingItem$event;
  22367. const bufferingIndex = this.findItemIndex(bufferingItem);
  22368. const nextToBufferIndex = Math.min(bufferingIndex + 1, items.length - 1);
  22369. const nextItemToBuffer = items[nextToBufferIndex];
  22370. if (bufferEndIndex === -1 && bufferingItem && bufferEnd >= bufferingItem.end || (_nextItemToBuffer$eve = nextItemToBuffer.event) != null && _nextItemToBuffer$eve.appendInPlace && bufferEnd + 0.01 >= nextItemToBuffer.start) {
  22371. bufferEndIndex = nextToBufferIndex;
  22372. }
  22373. if (nextToBufferIndex - playingIndex > 1 && (bufferingItem == null ? void 0 : (_bufferingItem$event = bufferingItem.event) == null ? void 0 : _bufferingItem$event.appendInPlace) === false) {
  22374. return;
  22375. }
  22376. this.bufferedPos = bufferEnd;
  22377. if (bufferEndIndex > bufferingIndex && bufferEndIndex > playingIndex) {
  22378. this.bufferedToItem(nextItemToBuffer);
  22379. } else {
  22380. const details = this.primaryDetails;
  22381. if (this.primaryLive && details && bufferEnd > details.edge - details.targetduration && nextItemToBuffer.start < details.edge + this.hls.config.interstitialLiveLookAhead && this.isInterstitial(nextItemToBuffer)) {
  22382. this.preloadAssets(nextItemToBuffer.event, 0);
  22383. }
  22384. }
  22385. } else if (bufferIsEmpty && playingItem && !this.itemsMatch(playingItem, bufferingItem)) {
  22386. if (bufferEndIndex === playingIndex) {
  22387. this.bufferedToItem(playingItem);
  22388. } else if (bufferEndIndex === playingIndex + 1) {
  22389. this.bufferedToItem(items[bufferEndIndex]);
  22390. }
  22391. }
  22392. }
  22393. assetsBuffered(item, media) {
  22394. const assetList = item.event.assetList;
  22395. if (assetList.length === 0) {
  22396. return false;
  22397. }
  22398. return !item.event.assetList.some((asset) => {
  22399. const player = this.getAssetPlayer(asset.identifier);
  22400. return !(player != null && player.bufferedInPlaceToEnd(media));
  22401. });
  22402. }
  22403. setBufferingItem(item) {
  22404. const bufferingLast = this.bufferingItem;
  22405. const schedule = this.schedule;
  22406. if (!this.itemsMatch(item, bufferingLast)) {
  22407. const {
  22408. items,
  22409. events
  22410. } = schedule;
  22411. if (!items || !events) {
  22412. return bufferingLast;
  22413. }
  22414. const isInterstitial = this.isInterstitial(item);
  22415. const bufferingPlayer = this.getBufferingPlayer();
  22416. this.bufferingItem = item;
  22417. this.bufferedPos = Math.max(item.start, Math.min(item.end, this.timelinePos));
  22418. const timeRemaining = bufferingPlayer ? bufferingPlayer.remaining : bufferingLast ? bufferingLast.end - this.timelinePos : 0;
  22419. this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${segmentToString(item)}` + (bufferingLast ? ` (${timeRemaining.toFixed(2)} remaining)` : ""));
  22420. if (!this.playbackDisabled) {
  22421. if (isInterstitial) {
  22422. item.event.assetList.forEach((asset) => {
  22423. const player = this.getAssetPlayer(asset.identifier);
  22424. if (player) {
  22425. player.resumeBuffering();
  22426. }
  22427. });
  22428. } else {
  22429. this.hls.resumeBuffering();
  22430. this.playerQueue.forEach((player) => player.pauseBuffering());
  22431. }
  22432. }
  22433. this.hls.trigger(Events.INTERSTITIALS_BUFFERED_TO_BOUNDARY, {
  22434. events: events.slice(0),
  22435. schedule: items.slice(0),
  22436. bufferingIndex: this.findItemIndex(item),
  22437. playingIndex: this.findItemIndex(this.playingItem)
  22438. });
  22439. } else if (this.bufferingItem !== item) {
  22440. this.bufferingItem = item;
  22441. }
  22442. return bufferingLast;
  22443. }
  22444. bufferedToItem(item, assetListIndex = 0) {
  22445. const bufferingLast = this.setBufferingItem(item);
  22446. if (this.playbackDisabled) {
  22447. return;
  22448. }
  22449. if (this.isInterstitial(item)) {
  22450. this.bufferedToEvent(item, assetListIndex);
  22451. } else if (bufferingLast !== null) {
  22452. this.bufferingAsset = null;
  22453. const detachedData = this.detachedData;
  22454. if (detachedData) {
  22455. if (detachedData.mediaSource) {
  22456. const skipSeekToStartPosition = true;
  22457. this.attachPrimary(item.start, item, skipSeekToStartPosition);
  22458. } else {
  22459. this.preloadPrimary(item);
  22460. }
  22461. } else {
  22462. this.preloadPrimary(item);
  22463. }
  22464. }
  22465. }
  22466. preloadPrimary(item) {
  22467. const index = this.findItemIndex(item);
  22468. const timelinePos = this.getPrimaryResumption(item, index);
  22469. this.startLoadingPrimaryAt(timelinePos);
  22470. }
  22471. bufferedToEvent(item, assetListIndex) {
  22472. const interstitial = item.event;
  22473. const neverLoaded = interstitial.assetList.length === 0 && !interstitial.assetListLoader;
  22474. const playOnce = interstitial.cue.once;
  22475. if (neverLoaded || !playOnce) {
  22476. const player = this.preloadAssets(interstitial, assetListIndex);
  22477. if (player != null && player.interstitial.appendInPlace) {
  22478. const assetItem = interstitial.assetList[assetListIndex];
  22479. const media = this.primaryMedia;
  22480. if (assetItem && media) {
  22481. this.bufferAssetPlayer(player, media);
  22482. }
  22483. }
  22484. }
  22485. }
  22486. preloadAssets(interstitial, assetListIndex) {
  22487. const uri = interstitial.assetUrl;
  22488. const assetListLength = interstitial.assetList.length;
  22489. const neverLoaded = assetListLength === 0 && !interstitial.assetListLoader;
  22490. const playOnce = interstitial.cue.once;
  22491. if (neverLoaded) {
  22492. const timelineStart = interstitial.timelineStart;
  22493. if (interstitial.appendInPlace) {
  22494. var _playingItem$nextEven;
  22495. const playingItem = this.playingItem;
  22496. if (!this.isInterstitial(playingItem) && (playingItem == null ? void 0 : (_playingItem$nextEven = playingItem.nextEvent) == null ? void 0 : _playingItem$nextEven.identifier) === interstitial.identifier) {
  22497. this.flushFrontBuffer(timelineStart + 0.25);
  22498. }
  22499. }
  22500. let hlsStartOffset;
  22501. let liveStartPosition = 0;
  22502. if (!this.playingItem && this.primaryLive) {
  22503. liveStartPosition = this.hls.startPosition;
  22504. if (liveStartPosition === -1) {
  22505. liveStartPosition = this.hls.liveSyncPosition || 0;
  22506. }
  22507. }
  22508. if (liveStartPosition && !(interstitial.cue.pre || interstitial.cue.post)) {
  22509. const startOffset = liveStartPosition - timelineStart;
  22510. if (startOffset > 0) {
  22511. hlsStartOffset = Math.round(startOffset * 1e3) / 1e3;
  22512. }
  22513. }
  22514. this.log(`Load interstitial asset ${assetListIndex + 1}/${uri ? 1 : assetListLength} ${interstitial}${hlsStartOffset ? ` live-start: ${liveStartPosition} start-offset: ${hlsStartOffset}` : ""}`);
  22515. if (uri) {
  22516. return this.createAsset(interstitial, 0, 0, timelineStart, interstitial.duration, uri);
  22517. }
  22518. const assetListLoader = this.assetListLoader.loadAssetList(interstitial, hlsStartOffset);
  22519. if (assetListLoader) {
  22520. interstitial.assetListLoader = assetListLoader;
  22521. }
  22522. } else if (!playOnce && assetListLength) {
  22523. for (let i = assetListIndex; i < assetListLength; i++) {
  22524. const asset = interstitial.assetList[i];
  22525. const playerIndex = this.getAssetPlayerQueueIndex(asset.identifier);
  22526. if ((playerIndex === -1 || this.playerQueue[playerIndex].destroyed) && !asset.error) {
  22527. this.createAssetPlayer(interstitial, asset, i);
  22528. }
  22529. }
  22530. return this.getAssetPlayer(interstitial.assetList[assetListIndex].identifier);
  22531. }
  22532. return null;
  22533. }
  22534. flushFrontBuffer(startOffset) {
  22535. const requiredTracks = this.requiredTracks;
  22536. if (!requiredTracks) {
  22537. return;
  22538. }
  22539. this.log(`Removing front buffer starting at ${startOffset}`);
  22540. const sourceBufferNames = Object.keys(requiredTracks);
  22541. sourceBufferNames.forEach((type) => {
  22542. this.hls.trigger(Events.BUFFER_FLUSHING, {
  22543. startOffset,
  22544. endOffset: Infinity,
  22545. type
  22546. });
  22547. });
  22548. }
  22549. getAssetPlayerQueueIndex(assetId) {
  22550. const playerQueue = this.playerQueue;
  22551. for (let i = 0; i < playerQueue.length; i++) {
  22552. if (assetId === playerQueue[i].assetId) {
  22553. return i;
  22554. }
  22555. }
  22556. return -1;
  22557. }
  22558. getAssetPlayer(assetId) {
  22559. const index = this.getAssetPlayerQueueIndex(assetId);
  22560. return this.playerQueue[index] || null;
  22561. }
  22562. getBufferingPlayer() {
  22563. const {
  22564. playerQueue,
  22565. primaryMedia
  22566. } = this;
  22567. if (primaryMedia) {
  22568. for (let i = 0; i < playerQueue.length; i++) {
  22569. if (playerQueue[i].media === primaryMedia) {
  22570. return playerQueue[i];
  22571. }
  22572. }
  22573. }
  22574. return null;
  22575. }
  22576. createAsset(interstitial, assetListIndex, startOffset, timelineStart, duration, uri) {
  22577. const assetItem = {
  22578. parentIdentifier: interstitial.identifier,
  22579. identifier: generateAssetIdentifier(interstitial, uri, assetListIndex),
  22580. duration,
  22581. startOffset,
  22582. timelineStart,
  22583. uri
  22584. };
  22585. return this.createAssetPlayer(interstitial, assetItem, assetListIndex);
  22586. }
  22587. createAssetPlayer(interstitial, assetItem, assetListIndex) {
  22588. const primary = this.hls;
  22589. const userConfig = primary.userConfig;
  22590. let videoPreference = userConfig.videoPreference;
  22591. const currentLevel = primary.loadLevelObj || primary.levels[primary.currentLevel];
  22592. if (videoPreference || currentLevel) {
  22593. videoPreference = _extends({}, videoPreference);
  22594. if (currentLevel.videoCodec) {
  22595. videoPreference.videoCodec = currentLevel.videoCodec;
  22596. }
  22597. if (currentLevel.videoRange) {
  22598. videoPreference.allowedVideoRanges = [currentLevel.videoRange];
  22599. }
  22600. }
  22601. const selectedAudio = primary.audioTracks[primary.audioTrack];
  22602. const selectedSubtitle = primary.subtitleTracks[primary.subtitleTrack];
  22603. let startPosition = 0;
  22604. if (this.primaryLive || interstitial.appendInPlace) {
  22605. const timePastStart = this.timelinePos - assetItem.timelineStart;
  22606. if (timePastStart > 1) {
  22607. const duration = assetItem.duration;
  22608. if (duration && timePastStart < duration) {
  22609. startPosition = timePastStart;
  22610. }
  22611. }
  22612. }
  22613. const assetId = assetItem.identifier;
  22614. const playerConfig = _objectSpread2(_objectSpread2({}, userConfig), {}, {
  22615. autoStartLoad: true,
  22616. startFragPrefetch: true,
  22617. primarySessionId: primary.sessionId,
  22618. assetPlayerId: assetId,
  22619. abrEwmaDefaultEstimate: primary.bandwidthEstimate,
  22620. interstitialsController: void 0,
  22621. startPosition,
  22622. liveDurationInfinity: false,
  22623. testBandwidth: false,
  22624. videoPreference,
  22625. audioPreference: selectedAudio || userConfig.audioPreference,
  22626. subtitlePreference: selectedSubtitle || userConfig.subtitlePreference
  22627. });
  22628. if (interstitial.appendInPlace) {
  22629. interstitial.appendInPlaceStarted = true;
  22630. if (assetItem.timelineStart) {
  22631. playerConfig.timelineOffset = assetItem.timelineStart;
  22632. }
  22633. }
  22634. const cmcd = playerConfig.cmcd;
  22635. if (cmcd != null && cmcd.sessionId && cmcd.contentId) {
  22636. playerConfig.cmcd = _extends({}, cmcd, {
  22637. contentId: hash(assetItem.uri)
  22638. });
  22639. }
  22640. if (this.getAssetPlayer(assetId)) {
  22641. this.warn(`Duplicate date range identifier ${interstitial} and asset ${assetId}`);
  22642. }
  22643. const player = new HlsAssetPlayer(this.HlsPlayerClass, playerConfig, interstitial, assetItem);
  22644. this.playerQueue.push(player);
  22645. interstitial.assetList[assetListIndex] = assetItem;
  22646. const updateAssetPlayerDetails = (details) => {
  22647. if (details.live) {
  22648. const error = new Error(`Interstitials MUST be VOD assets ${interstitial}`);
  22649. const errorData = {
  22650. fatal: true,
  22651. type: ErrorTypes.OTHER_ERROR,
  22652. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  22653. error
  22654. };
  22655. this.handleAssetItemError(errorData, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, error.message);
  22656. return;
  22657. }
  22658. const duration = details.edge - details.fragmentStart;
  22659. const currentAssetDuration = assetItem.duration;
  22660. if (currentAssetDuration === null || duration > currentAssetDuration) {
  22661. this.log(`Interstitial asset "${assetId}" duration change ${currentAssetDuration} > ${duration}`);
  22662. assetItem.duration = duration;
  22663. this.updateSchedule();
  22664. }
  22665. };
  22666. player.on(Events.LEVEL_UPDATED, (event, {
  22667. details
  22668. }) => updateAssetPlayerDetails(details));
  22669. player.on(Events.LEVEL_PTS_UPDATED, (event, {
  22670. details
  22671. }) => updateAssetPlayerDetails(details));
  22672. const onBufferCodecs = (event, data) => {
  22673. const inQueuPlayer = this.getAssetPlayer(assetId);
  22674. if (inQueuPlayer && data.tracks) {
  22675. inQueuPlayer.off(Events.BUFFER_CODECS, onBufferCodecs);
  22676. inQueuPlayer.tracks = data.tracks;
  22677. const media = this.primaryMedia;
  22678. if (this.bufferingAsset === inQueuPlayer.assetItem && media && !inQueuPlayer.media) {
  22679. this.bufferAssetPlayer(inQueuPlayer, media);
  22680. }
  22681. }
  22682. };
  22683. player.on(Events.BUFFER_CODECS, onBufferCodecs);
  22684. const bufferedToEnd = () => {
  22685. var _this$schedule$items2;
  22686. const inQueuPlayer = this.getAssetPlayer(assetId);
  22687. this.log(`buffered to end of asset ${inQueuPlayer}`);
  22688. if (!inQueuPlayer) {
  22689. return;
  22690. }
  22691. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  22692. const item = (_this$schedule$items2 = this.schedule.items) == null ? void 0 : _this$schedule$items2[scheduleIndex];
  22693. if (this.isInterstitial(item)) {
  22694. const assetListIndex2 = interstitial.findAssetIndex(assetItem);
  22695. const nextAssetIndex = getNextAssetIndex(interstitial, assetListIndex2);
  22696. if (!interstitial.isAssetPastPlayoutLimit(nextAssetIndex)) {
  22697. this.bufferedToItem(item, nextAssetIndex);
  22698. } else {
  22699. var _this$schedule$items3;
  22700. const nextItem = (_this$schedule$items3 = this.schedule.items) == null ? void 0 : _this$schedule$items3[scheduleIndex + 1];
  22701. if (nextItem) {
  22702. this.bufferedToItem(nextItem);
  22703. }
  22704. }
  22705. }
  22706. };
  22707. player.on(Events.BUFFERED_TO_END, bufferedToEnd);
  22708. const endedWithAssetIndex = (assetIndex) => {
  22709. return () => {
  22710. const inQueuPlayer = this.getAssetPlayer(assetId);
  22711. if (!inQueuPlayer) {
  22712. return;
  22713. }
  22714. this.shouldPlay = true;
  22715. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  22716. this.advanceAfterAssetEnded(interstitial, scheduleIndex, assetIndex);
  22717. };
  22718. };
  22719. player.once(Events.MEDIA_ENDED, endedWithAssetIndex(assetListIndex));
  22720. player.once(Events.PLAYOUT_LIMIT_REACHED, endedWithAssetIndex(Infinity));
  22721. player.on(Events.ERROR, (event, data) => {
  22722. const inQueuPlayer = this.getAssetPlayer(assetId);
  22723. if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {
  22724. if (inQueuPlayer != null && inQueuPlayer.media) {
  22725. const assetCurrentTime = inQueuPlayer.currentTime;
  22726. const distanceFromEnd = inQueuPlayer.duration - assetCurrentTime;
  22727. if (assetCurrentTime && interstitial.appendInPlace && distanceFromEnd / inQueuPlayer.media.playbackRate < 0.5) {
  22728. this.log(`Advancing buffer past end of asset ${assetId} ${interstitial} at ${inQueuPlayer.media.currentTime}`);
  22729. bufferedToEnd();
  22730. } else {
  22731. this.warn(`Stalled at ${assetCurrentTime} of ${assetCurrentTime + distanceFromEnd} in asset ${assetId} ${interstitial}`);
  22732. this.onTimeupdate();
  22733. this.checkBuffer(true);
  22734. }
  22735. }
  22736. return;
  22737. }
  22738. this.handleAssetItemError(data, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, `Asset player error ${data.error} ${interstitial}`);
  22739. });
  22740. player.on(Events.DESTROYING, () => {
  22741. const inQueuPlayer = this.getAssetPlayer(assetId);
  22742. if (!inQueuPlayer) {
  22743. return;
  22744. }
  22745. const error = new Error(`Asset player destroyed unexpectedly ${assetId}`);
  22746. const errorData = {
  22747. fatal: true,
  22748. type: ErrorTypes.OTHER_ERROR,
  22749. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  22750. error
  22751. };
  22752. this.handleAssetItemError(errorData, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, error.message);
  22753. });
  22754. this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${eventAssetToString(assetItem)}`);
  22755. this.hls.trigger(Events.INTERSTITIAL_ASSET_PLAYER_CREATED, {
  22756. asset: assetItem,
  22757. assetListIndex,
  22758. event: interstitial,
  22759. player
  22760. });
  22761. return player;
  22762. }
  22763. clearInterstitial(interstitial, toSegment) {
  22764. interstitial.assetList.forEach((asset) => {
  22765. this.clearAssetPlayer(asset.identifier, toSegment);
  22766. });
  22767. interstitial.reset();
  22768. }
  22769. resetAssetPlayer(assetId) {
  22770. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  22771. if (playerIndex !== -1) {
  22772. this.log(`reset asset player "${assetId}" after error`);
  22773. const player = this.playerQueue[playerIndex];
  22774. this.transferMediaFromPlayer(player, null);
  22775. player.resetDetails();
  22776. }
  22777. }
  22778. clearAssetPlayer(assetId, toSegment) {
  22779. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  22780. if (playerIndex !== -1) {
  22781. this.log(`clear asset player "${assetId}" toSegment: ${toSegment ? segmentToString(toSegment) : toSegment}`);
  22782. const player = this.playerQueue[playerIndex];
  22783. this.transferMediaFromPlayer(player, toSegment);
  22784. this.playerQueue.splice(playerIndex, 1);
  22785. player.destroy();
  22786. }
  22787. }
  22788. emptyPlayerQueue() {
  22789. let player;
  22790. while (player = this.playerQueue.pop()) {
  22791. player.destroy();
  22792. }
  22793. this.playerQueue = [];
  22794. }
  22795. startAssetPlayer(player, assetListIndex, scheduleItems, scheduleIndex, media) {
  22796. const {
  22797. interstitial,
  22798. assetItem,
  22799. assetId
  22800. } = player;
  22801. const assetListLength = interstitial.assetList.length;
  22802. const playingAsset = this.playingAsset;
  22803. this.endedAsset = null;
  22804. this.playingAsset = assetItem;
  22805. if (!playingAsset || playingAsset.identifier !== assetId) {
  22806. if (playingAsset) {
  22807. this.clearAssetPlayer(playingAsset.identifier, scheduleItems[scheduleIndex]);
  22808. delete playingAsset.error;
  22809. }
  22810. this.log(`INTERSTITIAL_ASSET_STARTED ${assetListIndex + 1}/${assetListLength} ${eventAssetToString(assetItem)}`);
  22811. this.hls.trigger(Events.INTERSTITIAL_ASSET_STARTED, {
  22812. asset: assetItem,
  22813. assetListIndex,
  22814. event: interstitial,
  22815. schedule: scheduleItems.slice(0),
  22816. scheduleIndex,
  22817. player
  22818. });
  22819. }
  22820. this.bufferAssetPlayer(player, media);
  22821. }
  22822. bufferAssetPlayer(player, media) {
  22823. var _this$schedule$items4, _this$detachedData5;
  22824. const {
  22825. interstitial,
  22826. assetItem
  22827. } = player;
  22828. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  22829. const item = (_this$schedule$items4 = this.schedule.items) == null ? void 0 : _this$schedule$items4[scheduleIndex];
  22830. if (!item) {
  22831. return;
  22832. }
  22833. this.setBufferingItem(item);
  22834. this.bufferingAsset = assetItem;
  22835. const bufferingPlayer = this.getBufferingPlayer();
  22836. if (bufferingPlayer === player) {
  22837. return;
  22838. }
  22839. const appendInPlaceNext = interstitial.appendInPlace;
  22840. if (appendInPlaceNext && (bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial.appendInPlace) === false) {
  22841. return;
  22842. }
  22843. const activeTracks = (bufferingPlayer == null ? void 0 : bufferingPlayer.tracks) || ((_this$detachedData5 = this.detachedData) == null ? void 0 : _this$detachedData5.tracks) || this.requiredTracks;
  22844. if (appendInPlaceNext && assetItem !== this.playingAsset) {
  22845. if (!player.tracks) {
  22846. return;
  22847. }
  22848. if (activeTracks && !isCompatibleTrackChange(activeTracks, player.tracks)) {
  22849. const error = new Error(`Asset ${eventAssetToString(assetItem)} SourceBuffer tracks ('${Object.keys(player.tracks)}') are not compatible with primary content tracks ('${Object.keys(activeTracks)}')`);
  22850. const errorData = {
  22851. fatal: true,
  22852. type: ErrorTypes.OTHER_ERROR,
  22853. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  22854. error
  22855. };
  22856. const assetListIndex = interstitial.findAssetIndex(assetItem);
  22857. this.handleAssetItemError(errorData, interstitial, scheduleIndex, assetListIndex, error.message);
  22858. return;
  22859. }
  22860. }
  22861. this.transferMediaTo(player, media);
  22862. }
  22863. handleAssetItemError(data, interstitial, scheduleIndex, assetListIndex, errorMessage) {
  22864. if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {
  22865. return;
  22866. }
  22867. const assetItem = interstitial.assetList[assetListIndex];
  22868. this.warn(`INTERSTITIAL_ASSET_ERROR ${assetItem ? eventAssetToString(assetItem) : assetItem} ${data.error}`);
  22869. const assetId = assetItem == null ? void 0 : assetItem.identifier;
  22870. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  22871. const player = this.playerQueue[playerIndex] || null;
  22872. const items = this.schedule.items;
  22873. const interstitialAssetError = _extends({}, data, {
  22874. fatal: false,
  22875. errorAction: createDoNothingErrorAction(true),
  22876. asset: assetItem,
  22877. assetListIndex,
  22878. event: interstitial,
  22879. schedule: items,
  22880. scheduleIndex,
  22881. player
  22882. });
  22883. this.hls.trigger(Events.INTERSTITIAL_ASSET_ERROR, interstitialAssetError);
  22884. if (!data.fatal) {
  22885. return;
  22886. }
  22887. const playingAsset = this.playingAsset;
  22888. const error = new Error(errorMessage);
  22889. if (assetItem) {
  22890. this.clearAssetPlayer(assetId, null);
  22891. assetItem.error = error;
  22892. }
  22893. if (!interstitial.assetList.some((asset) => !asset.error)) {
  22894. interstitial.error = error;
  22895. } else {
  22896. for (let i = assetListIndex; i < interstitial.assetList.length; i++) {
  22897. this.resetAssetPlayer(interstitial.assetList[i].identifier);
  22898. }
  22899. this.updateSchedule();
  22900. }
  22901. if (interstitial.error) {
  22902. this.primaryFallback(interstitial);
  22903. } else if (playingAsset && playingAsset.identifier === assetId) {
  22904. this.advanceAfterAssetEnded(interstitial, scheduleIndex, assetListIndex);
  22905. }
  22906. }
  22907. primaryFallback(interstitial) {
  22908. const flushStart = interstitial.timelineStart;
  22909. const playingItem = this.effectivePlayingItem;
  22910. this.updateSchedule();
  22911. if (playingItem) {
  22912. this.log(`Fallback to primary from event "${interstitial.identifier}" start: ${flushStart} pos: ${this.timelinePos} playing: ${playingItem ? segmentToString(playingItem) : "<none>"} error: ${interstitial.error}`);
  22913. let timelinePos = this.timelinePos;
  22914. if (timelinePos === -1) {
  22915. timelinePos = this.hls.startPosition;
  22916. }
  22917. const newPlayingItem = this.updateItem(playingItem, timelinePos);
  22918. if (this.itemsMatch(playingItem, newPlayingItem)) {
  22919. this.clearInterstitial(interstitial, null);
  22920. }
  22921. if (interstitial.appendInPlace) {
  22922. this.attachPrimary(flushStart, null);
  22923. this.flushFrontBuffer(flushStart);
  22924. }
  22925. const scheduleIndex = this.schedule.findItemIndexAtTime(timelinePos);
  22926. this.setSchedulePosition(scheduleIndex);
  22927. } else {
  22928. this.checkStart();
  22929. }
  22930. }
  22931. onAssetListLoaded(event, data) {
  22932. var _this$bufferingItem2;
  22933. const interstitial = data.event;
  22934. const interstitialId = interstitial.identifier;
  22935. const assets = data.assetListResponse.ASSETS;
  22936. if (!this.schedule.hasEvent(interstitialId)) {
  22937. return;
  22938. }
  22939. const eventStart = interstitial.timelineStart;
  22940. const previousDuration = interstitial.duration;
  22941. let sumDuration = 0;
  22942. assets.forEach((asset, assetListIndex) => {
  22943. const duration = parseFloat(asset.DURATION);
  22944. this.createAsset(interstitial, assetListIndex, sumDuration, eventStart + sumDuration, duration, asset.URI);
  22945. sumDuration += duration;
  22946. });
  22947. interstitial.duration = sumDuration;
  22948. this.log(`Loaded asset-list with duration: ${sumDuration} (was: ${previousDuration}) ${interstitial}`);
  22949. const waitingItem = this.waitingItem;
  22950. const waitingForItem = (waitingItem == null ? void 0 : waitingItem.event.identifier) === interstitialId;
  22951. this.updateSchedule();
  22952. const bufferingEvent = (_this$bufferingItem2 = this.bufferingItem) == null ? void 0 : _this$bufferingItem2.event;
  22953. if (waitingForItem) {
  22954. var _this$schedule$items5;
  22955. const scheduleIndex = this.schedule.findEventIndex(interstitialId);
  22956. const item = (_this$schedule$items5 = this.schedule.items) == null ? void 0 : _this$schedule$items5[scheduleIndex];
  22957. if (item) {
  22958. if (!this.playingItem && this.timelinePos > item.end) {
  22959. const index = this.schedule.findItemIndexAtTime(this.timelinePos);
  22960. if (index !== scheduleIndex) {
  22961. interstitial.error = new Error(`Interstitial no longer within playback range ${this.timelinePos} ${interstitial}`);
  22962. this.primaryFallback(interstitial);
  22963. return;
  22964. }
  22965. }
  22966. this.setBufferingItem(item);
  22967. }
  22968. this.setSchedulePosition(scheduleIndex);
  22969. } else if ((bufferingEvent == null ? void 0 : bufferingEvent.identifier) === interstitialId && bufferingEvent.appendInPlace) {
  22970. const assetItem = interstitial.assetList[0];
  22971. const player = this.getAssetPlayer(assetItem.identifier);
  22972. const media = this.primaryMedia;
  22973. if (assetItem && player && media) {
  22974. this.bufferAssetPlayer(player, media);
  22975. }
  22976. }
  22977. }
  22978. onError(event, data) {
  22979. switch (data.details) {
  22980. case ErrorDetails.ASSET_LIST_PARSING_ERROR:
  22981. case ErrorDetails.ASSET_LIST_LOAD_ERROR:
  22982. case ErrorDetails.ASSET_LIST_LOAD_TIMEOUT: {
  22983. const interstitial = data.interstitial;
  22984. if (interstitial) {
  22985. this.primaryFallback(interstitial);
  22986. }
  22987. break;
  22988. }
  22989. case ErrorDetails.BUFFER_STALLED_ERROR: {
  22990. this.onTimeupdate();
  22991. this.checkBuffer(true);
  22992. break;
  22993. }
  22994. }
  22995. }
  22996. };
  22997. var TICK_INTERVAL$2 = 500;
  22998. var SubtitleStreamController = class extends BaseStreamController {
  22999. constructor(hls, fragmentTracker, keyLoader) {
  23000. super(hls, fragmentTracker, keyLoader, "subtitle-stream-controller", PlaylistLevelType.SUBTITLE);
  23001. this.currentTrackId = -1;
  23002. this.tracksBuffered = [];
  23003. this.mainDetails = null;
  23004. this.registerListeners();
  23005. }
  23006. onHandlerDestroying() {
  23007. this.unregisterListeners();
  23008. super.onHandlerDestroying();
  23009. this.mainDetails = null;
  23010. }
  23011. registerListeners() {
  23012. super.registerListeners();
  23013. const {
  23014. hls
  23015. } = this;
  23016. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  23017. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  23018. hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  23019. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  23020. hls.on(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  23021. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  23022. }
  23023. unregisterListeners() {
  23024. super.unregisterListeners();
  23025. const {
  23026. hls
  23027. } = this;
  23028. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  23029. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  23030. hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  23031. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  23032. hls.off(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  23033. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  23034. }
  23035. startLoad(startPosition, skipSeekToStartPosition) {
  23036. this.stopLoad();
  23037. this.state = State.IDLE;
  23038. this.setInterval(TICK_INTERVAL$2);
  23039. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  23040. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  23041. this.tick();
  23042. }
  23043. onManifestLoading() {
  23044. super.onManifestLoading();
  23045. this.mainDetails = null;
  23046. }
  23047. onMediaDetaching(event, data) {
  23048. this.tracksBuffered = [];
  23049. super.onMediaDetaching(event, data);
  23050. }
  23051. onLevelLoaded(event, data) {
  23052. this.mainDetails = data.details;
  23053. }
  23054. onSubtitleFragProcessed(event, data) {
  23055. const {
  23056. frag,
  23057. success
  23058. } = data;
  23059. if (!this.fragContextChanged(frag)) {
  23060. if (isMediaFragment(frag)) {
  23061. this.fragPrevious = frag;
  23062. }
  23063. this.state = State.IDLE;
  23064. }
  23065. if (!success) {
  23066. return;
  23067. }
  23068. const buffered = this.tracksBuffered[this.currentTrackId];
  23069. if (!buffered) {
  23070. return;
  23071. }
  23072. let timeRange;
  23073. const fragStart = frag.start;
  23074. for (let i = 0; i < buffered.length; i++) {
  23075. if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
  23076. timeRange = buffered[i];
  23077. break;
  23078. }
  23079. }
  23080. const fragEnd = frag.start + frag.duration;
  23081. if (timeRange) {
  23082. timeRange.end = fragEnd;
  23083. } else {
  23084. timeRange = {
  23085. start: fragStart,
  23086. end: fragEnd
  23087. };
  23088. buffered.push(timeRange);
  23089. }
  23090. this.fragmentTracker.fragBuffered(frag);
  23091. this.fragBufferedComplete(frag, null);
  23092. if (this.media) {
  23093. this.tick();
  23094. }
  23095. }
  23096. onBufferFlushing(event, data) {
  23097. const {
  23098. startOffset,
  23099. endOffset
  23100. } = data;
  23101. if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) {
  23102. const endOffsetSubtitles = endOffset - 1;
  23103. if (endOffsetSubtitles <= 0) {
  23104. return;
  23105. }
  23106. data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles);
  23107. this.tracksBuffered.forEach((buffered) => {
  23108. for (let i = 0; i < buffered.length; ) {
  23109. if (buffered[i].end <= endOffsetSubtitles) {
  23110. buffered.shift();
  23111. continue;
  23112. } else if (buffered[i].start < endOffsetSubtitles) {
  23113. buffered[i].start = endOffsetSubtitles;
  23114. } else {
  23115. break;
  23116. }
  23117. i++;
  23118. }
  23119. });
  23120. this.fragmentTracker.removeFragmentsInRange(startOffset, endOffsetSubtitles, PlaylistLevelType.SUBTITLE);
  23121. }
  23122. }
  23123. onError(event, data) {
  23124. const frag = data.frag;
  23125. if ((frag == null ? void 0 : frag.type) === PlaylistLevelType.SUBTITLE) {
  23126. if (data.details === ErrorDetails.FRAG_GAP) {
  23127. this.fragmentTracker.fragBuffered(frag, true);
  23128. }
  23129. if (this.fragCurrent) {
  23130. this.fragCurrent.abortRequests();
  23131. }
  23132. if (this.state !== State.STOPPED) {
  23133. this.state = State.IDLE;
  23134. }
  23135. }
  23136. }
  23137. onSubtitleTracksUpdated(event, {
  23138. subtitleTracks
  23139. }) {
  23140. if (this.levels && subtitleOptionsIdentical(this.levels, subtitleTracks)) {
  23141. this.levels = subtitleTracks.map((mediaPlaylist) => new Level(mediaPlaylist));
  23142. return;
  23143. }
  23144. this.tracksBuffered = [];
  23145. this.levels = subtitleTracks.map((mediaPlaylist) => {
  23146. const level = new Level(mediaPlaylist);
  23147. this.tracksBuffered[level.id] = [];
  23148. return level;
  23149. });
  23150. this.fragmentTracker.removeFragmentsInRange(0, Number.POSITIVE_INFINITY, PlaylistLevelType.SUBTITLE);
  23151. this.fragPrevious = null;
  23152. this.mediaBuffer = null;
  23153. }
  23154. onSubtitleTrackSwitch(event, data) {
  23155. var _this$levels;
  23156. this.currentTrackId = data.id;
  23157. if (!((_this$levels = this.levels) != null && _this$levels.length) || this.currentTrackId === -1) {
  23158. this.clearInterval();
  23159. return;
  23160. }
  23161. const currentTrack = this.levels[this.currentTrackId];
  23162. if (currentTrack != null && currentTrack.details) {
  23163. this.mediaBuffer = this.mediaBufferTimeRanges;
  23164. } else {
  23165. this.mediaBuffer = null;
  23166. }
  23167. if (currentTrack && this.state !== State.STOPPED) {
  23168. this.setInterval(TICK_INTERVAL$2);
  23169. }
  23170. }
  23171. onSubtitleTrackLoaded(event, data) {
  23172. var _track$details;
  23173. const {
  23174. currentTrackId,
  23175. levels
  23176. } = this;
  23177. const {
  23178. details: newDetails,
  23179. id: trackId
  23180. } = data;
  23181. if (!levels) {
  23182. this.warn(`Subtitle tracks were reset while loading level ${trackId}`);
  23183. return;
  23184. }
  23185. const track = levels[trackId];
  23186. if (trackId >= levels.length || !track) {
  23187. return;
  23188. }
  23189. this.log(`Subtitle track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""},duration:${newDetails.totalduration}`);
  23190. this.mediaBuffer = this.mediaBufferTimeRanges;
  23191. let sliding = 0;
  23192. if (newDetails.live || (_track$details = track.details) != null && _track$details.live) {
  23193. if (newDetails.deltaUpdateFailed) {
  23194. return;
  23195. }
  23196. const mainDetails = this.mainDetails;
  23197. if (!mainDetails) {
  23198. this.startFragRequested = false;
  23199. return;
  23200. }
  23201. const mainSlidingStartFragment = mainDetails.fragments[0];
  23202. if (!track.details) {
  23203. if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {
  23204. alignMediaPlaylistByPDT(newDetails, mainDetails);
  23205. sliding = newDetails.fragmentStart;
  23206. } else if (mainSlidingStartFragment) {
  23207. sliding = mainSlidingStartFragment.start;
  23208. addSliding(newDetails, sliding);
  23209. }
  23210. } else {
  23211. var _this$levelLastLoaded;
  23212. sliding = this.alignPlaylists(newDetails, track.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  23213. if (sliding === 0 && mainSlidingStartFragment) {
  23214. sliding = mainSlidingStartFragment.start;
  23215. addSliding(newDetails, sliding);
  23216. }
  23217. }
  23218. if (mainDetails && !this.startFragRequested) {
  23219. this.setStartPosition(mainDetails, sliding);
  23220. }
  23221. }
  23222. track.details = newDetails;
  23223. this.levelLastLoaded = track;
  23224. if (trackId !== currentTrackId) {
  23225. return;
  23226. }
  23227. this.hls.trigger(Events.SUBTITLE_TRACK_UPDATED, {
  23228. details: newDetails,
  23229. id: trackId,
  23230. groupId: data.groupId
  23231. });
  23232. this.tick();
  23233. if (newDetails.live && !this.fragCurrent && this.media && this.state === State.IDLE) {
  23234. const foundFrag = findFragmentByPTS(null, newDetails.fragments, this.media.currentTime, 0);
  23235. if (!foundFrag) {
  23236. this.warn("Subtitle playlist not aligned with playback");
  23237. track.details = void 0;
  23238. }
  23239. }
  23240. }
  23241. _handleFragmentLoadComplete(fragLoadedData) {
  23242. const {
  23243. frag,
  23244. payload
  23245. } = fragLoadedData;
  23246. const decryptData = frag.decryptdata;
  23247. const hls = this.hls;
  23248. if (this.fragContextChanged(frag)) {
  23249. return;
  23250. }
  23251. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
  23252. const startTime = performance.now();
  23253. this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch((err) => {
  23254. hls.trigger(Events.ERROR, {
  23255. type: ErrorTypes.MEDIA_ERROR,
  23256. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  23257. fatal: false,
  23258. error: err,
  23259. reason: err.message,
  23260. frag
  23261. });
  23262. throw err;
  23263. }).then((decryptedData) => {
  23264. const endTime = performance.now();
  23265. hls.trigger(Events.FRAG_DECRYPTED, {
  23266. frag,
  23267. payload: decryptedData,
  23268. stats: {
  23269. tstart: startTime,
  23270. tdecrypt: endTime
  23271. }
  23272. });
  23273. }).catch((err) => {
  23274. this.warn(`${err.name}: ${err.message}`);
  23275. this.state = State.IDLE;
  23276. });
  23277. }
  23278. }
  23279. doTick() {
  23280. if (!this.media) {
  23281. this.state = State.IDLE;
  23282. return;
  23283. }
  23284. if (this.state === State.IDLE) {
  23285. const {
  23286. currentTrackId,
  23287. levels
  23288. } = this;
  23289. const track = levels == null ? void 0 : levels[currentTrackId];
  23290. if (!track || !levels.length || !track.details) {
  23291. return;
  23292. }
  23293. if (this.waitForLive(track)) {
  23294. return;
  23295. }
  23296. const {
  23297. config
  23298. } = this;
  23299. const currentTime = this.getLoadPosition();
  23300. const bufferedInfo = BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId] || [], currentTime, config.maxBufferHole);
  23301. const {
  23302. end: targetBufferTime,
  23303. len: bufferLen
  23304. } = bufferedInfo;
  23305. const trackDetails = track.details;
  23306. const maxBufLen = this.hls.maxBufferLength + trackDetails.levelTargetDuration;
  23307. if (bufferLen > maxBufLen) {
  23308. return;
  23309. }
  23310. const fragments = trackDetails.fragments;
  23311. const fragLen = fragments.length;
  23312. const end = trackDetails.edge;
  23313. let foundFrag = null;
  23314. const fragPrevious = this.fragPrevious;
  23315. if (targetBufferTime < end) {
  23316. const tolerance = config.maxFragLookUpTolerance;
  23317. const lookupTolerance = targetBufferTime > end - tolerance ? 0 : tolerance;
  23318. foundFrag = findFragmentByPTS(fragPrevious, fragments, Math.max(fragments[0].start, targetBufferTime), lookupTolerance);
  23319. if (!foundFrag && fragPrevious && fragPrevious.start < fragments[0].start) {
  23320. foundFrag = fragments[0];
  23321. }
  23322. } else {
  23323. foundFrag = fragments[fragLen - 1];
  23324. }
  23325. foundFrag = this.filterReplacedPrimary(foundFrag, track.details);
  23326. if (!foundFrag) {
  23327. return;
  23328. }
  23329. const curSNIdx = foundFrag.sn - trackDetails.startSN;
  23330. const prevFrag = fragments[curSNIdx - 1];
  23331. if (prevFrag && prevFrag.cc === foundFrag.cc && this.fragmentTracker.getState(prevFrag) === FragmentState.NOT_LOADED) {
  23332. foundFrag = prevFrag;
  23333. }
  23334. if (this.fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) {
  23335. const fragToLoad = this.mapToInitFragWhenRequired(foundFrag);
  23336. if (fragToLoad) {
  23337. this.loadFragment(fragToLoad, track, targetBufferTime);
  23338. }
  23339. }
  23340. }
  23341. }
  23342. loadFragment(frag, level, targetBufferTime) {
  23343. if (!isMediaFragment(frag)) {
  23344. this._loadInitSegment(frag, level);
  23345. } else {
  23346. super.loadFragment(frag, level, targetBufferTime);
  23347. }
  23348. }
  23349. get mediaBufferTimeRanges() {
  23350. return new BufferableInstance(this.tracksBuffered[this.currentTrackId] || []);
  23351. }
  23352. };
  23353. var BufferableInstance = class {
  23354. constructor(timeranges) {
  23355. this.buffered = void 0;
  23356. const getRange = (name, index, length) => {
  23357. index = index >>> 0;
  23358. if (index > length - 1) {
  23359. throw new DOMException(`Failed to execute '${name}' on 'TimeRanges': The index provided (${index}) is greater than the maximum bound (${length})`);
  23360. }
  23361. return timeranges[index][name];
  23362. };
  23363. this.buffered = {
  23364. get length() {
  23365. return timeranges.length;
  23366. },
  23367. end(index) {
  23368. return getRange("end", index, timeranges.length);
  23369. },
  23370. start(index) {
  23371. return getRange("start", index, timeranges.length);
  23372. }
  23373. };
  23374. }
  23375. };
  23376. var specialCea608CharsCodes = {
  23377. 42: 225,
  23378. 92: 233,
  23379. 94: 237,
  23380. 95: 243,
  23381. 96: 250,
  23382. 123: 231,
  23383. 124: 247,
  23384. 125: 209,
  23385. 126: 241,
  23386. 127: 9608,
  23387. 128: 174,
  23388. 129: 176,
  23389. 130: 189,
  23390. 131: 191,
  23391. 132: 8482,
  23392. 133: 162,
  23393. 134: 163,
  23394. 135: 9834,
  23395. 136: 224,
  23396. 137: 32,
  23397. 138: 232,
  23398. 139: 226,
  23399. 140: 234,
  23400. 141: 238,
  23401. 142: 244,
  23402. 143: 251,
  23403. 144: 193,
  23404. 145: 201,
  23405. 146: 211,
  23406. 147: 218,
  23407. 148: 220,
  23408. 149: 252,
  23409. 150: 8216,
  23410. 151: 161,
  23411. 152: 42,
  23412. 153: 8217,
  23413. 154: 9473,
  23414. 155: 169,
  23415. 156: 8480,
  23416. 157: 8226,
  23417. 158: 8220,
  23418. 159: 8221,
  23419. 160: 192,
  23420. 161: 194,
  23421. 162: 199,
  23422. 163: 200,
  23423. 164: 202,
  23424. 165: 203,
  23425. 166: 235,
  23426. 167: 206,
  23427. 168: 207,
  23428. 169: 239,
  23429. 170: 212,
  23430. 171: 217,
  23431. 172: 249,
  23432. 173: 219,
  23433. 174: 171,
  23434. 175: 187,
  23435. 176: 195,
  23436. 177: 227,
  23437. 178: 205,
  23438. 179: 204,
  23439. 180: 236,
  23440. 181: 210,
  23441. 182: 242,
  23442. 183: 213,
  23443. 184: 245,
  23444. 185: 123,
  23445. 186: 125,
  23446. 187: 92,
  23447. 188: 94,
  23448. 189: 95,
  23449. 190: 124,
  23450. 191: 8764,
  23451. 192: 196,
  23452. 193: 228,
  23453. 194: 214,
  23454. 195: 246,
  23455. 196: 223,
  23456. 197: 165,
  23457. 198: 164,
  23458. 199: 9475,
  23459. 200: 197,
  23460. 201: 229,
  23461. 202: 216,
  23462. 203: 248,
  23463. 204: 9487,
  23464. 205: 9491,
  23465. 206: 9495,
  23466. 207: 9499
  23467. };
  23468. var getCharForByte = (byte) => String.fromCharCode(specialCea608CharsCodes[byte] || byte);
  23469. var NR_ROWS = 15;
  23470. var NR_COLS = 100;
  23471. var rowsLowCh1 = {
  23472. 17: 1,
  23473. 18: 3,
  23474. 21: 5,
  23475. 22: 7,
  23476. 23: 9,
  23477. 16: 11,
  23478. 19: 12,
  23479. 20: 14
  23480. };
  23481. var rowsHighCh1 = {
  23482. 17: 2,
  23483. 18: 4,
  23484. 21: 6,
  23485. 22: 8,
  23486. 23: 10,
  23487. 19: 13,
  23488. 20: 15
  23489. };
  23490. var rowsLowCh2 = {
  23491. 25: 1,
  23492. 26: 3,
  23493. 29: 5,
  23494. 30: 7,
  23495. 31: 9,
  23496. 24: 11,
  23497. 27: 12,
  23498. 28: 14
  23499. };
  23500. var rowsHighCh2 = {
  23501. 25: 2,
  23502. 26: 4,
  23503. 29: 6,
  23504. 30: 8,
  23505. 31: 10,
  23506. 27: 13,
  23507. 28: 15
  23508. };
  23509. var backgroundColors = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "black", "transparent"];
  23510. var CaptionsLogger = class {
  23511. constructor() {
  23512. this.time = null;
  23513. this.verboseLevel = 0;
  23514. }
  23515. log(severity, msg) {
  23516. if (this.verboseLevel >= severity) {
  23517. const m = typeof msg === "function" ? msg() : msg;
  23518. logger.log(`${this.time} [${severity}] ${m}`);
  23519. }
  23520. }
  23521. };
  23522. var numArrayToHexArray = function numArrayToHexArray2(numArray) {
  23523. const hexArray = [];
  23524. for (let j = 0; j < numArray.length; j++) {
  23525. hexArray.push(numArray[j].toString(16));
  23526. }
  23527. return hexArray;
  23528. };
  23529. var PenState = class {
  23530. constructor() {
  23531. this.foreground = "white";
  23532. this.underline = false;
  23533. this.italics = false;
  23534. this.background = "black";
  23535. this.flash = false;
  23536. }
  23537. reset() {
  23538. this.foreground = "white";
  23539. this.underline = false;
  23540. this.italics = false;
  23541. this.background = "black";
  23542. this.flash = false;
  23543. }
  23544. setStyles(styles) {
  23545. const attribs = ["foreground", "underline", "italics", "background", "flash"];
  23546. for (let i = 0; i < attribs.length; i++) {
  23547. const style = attribs[i];
  23548. if (styles.hasOwnProperty(style)) {
  23549. this[style] = styles[style];
  23550. }
  23551. }
  23552. }
  23553. isDefault() {
  23554. return this.foreground === "white" && !this.underline && !this.italics && this.background === "black" && !this.flash;
  23555. }
  23556. equals(other) {
  23557. return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
  23558. }
  23559. copy(newPenState) {
  23560. this.foreground = newPenState.foreground;
  23561. this.underline = newPenState.underline;
  23562. this.italics = newPenState.italics;
  23563. this.background = newPenState.background;
  23564. this.flash = newPenState.flash;
  23565. }
  23566. toString() {
  23567. return "color=" + this.foreground + ", underline=" + this.underline + ", italics=" + this.italics + ", background=" + this.background + ", flash=" + this.flash;
  23568. }
  23569. };
  23570. var StyledUnicodeChar = class {
  23571. constructor() {
  23572. this.uchar = " ";
  23573. this.penState = new PenState();
  23574. }
  23575. reset() {
  23576. this.uchar = " ";
  23577. this.penState.reset();
  23578. }
  23579. setChar(uchar, newPenState) {
  23580. this.uchar = uchar;
  23581. this.penState.copy(newPenState);
  23582. }
  23583. setPenState(newPenState) {
  23584. this.penState.copy(newPenState);
  23585. }
  23586. equals(other) {
  23587. return this.uchar === other.uchar && this.penState.equals(other.penState);
  23588. }
  23589. copy(newChar) {
  23590. this.uchar = newChar.uchar;
  23591. this.penState.copy(newChar.penState);
  23592. }
  23593. isEmpty() {
  23594. return this.uchar === " " && this.penState.isDefault();
  23595. }
  23596. };
  23597. var Row = class {
  23598. constructor(logger2) {
  23599. this.chars = [];
  23600. this.pos = 0;
  23601. this.currPenState = new PenState();
  23602. this.cueStartTime = null;
  23603. this.logger = void 0;
  23604. for (let i = 0; i < NR_COLS; i++) {
  23605. this.chars.push(new StyledUnicodeChar());
  23606. }
  23607. this.logger = logger2;
  23608. }
  23609. equals(other) {
  23610. for (let i = 0; i < NR_COLS; i++) {
  23611. if (!this.chars[i].equals(other.chars[i])) {
  23612. return false;
  23613. }
  23614. }
  23615. return true;
  23616. }
  23617. copy(other) {
  23618. for (let i = 0; i < NR_COLS; i++) {
  23619. this.chars[i].copy(other.chars[i]);
  23620. }
  23621. }
  23622. isEmpty() {
  23623. let empty = true;
  23624. for (let i = 0; i < NR_COLS; i++) {
  23625. if (!this.chars[i].isEmpty()) {
  23626. empty = false;
  23627. break;
  23628. }
  23629. }
  23630. return empty;
  23631. }
  23632. setCursor(absPos) {
  23633. if (this.pos !== absPos) {
  23634. this.pos = absPos;
  23635. }
  23636. if (this.pos < 0) {
  23637. this.logger.log(3, "Negative cursor position " + this.pos);
  23638. this.pos = 0;
  23639. } else if (this.pos > NR_COLS) {
  23640. this.logger.log(3, "Too large cursor position " + this.pos);
  23641. this.pos = NR_COLS;
  23642. }
  23643. }
  23644. moveCursor(relPos) {
  23645. const newPos = this.pos + relPos;
  23646. if (relPos > 1) {
  23647. for (let i = this.pos + 1; i < newPos + 1; i++) {
  23648. this.chars[i].setPenState(this.currPenState);
  23649. }
  23650. }
  23651. this.setCursor(newPos);
  23652. }
  23653. backSpace() {
  23654. this.moveCursor(-1);
  23655. this.chars[this.pos].setChar(" ", this.currPenState);
  23656. }
  23657. insertChar(byte) {
  23658. if (byte >= 144) {
  23659. this.backSpace();
  23660. }
  23661. const char = getCharForByte(byte);
  23662. if (this.pos >= NR_COLS) {
  23663. this.logger.log(0, () => "Cannot insert " + byte.toString(16) + " (" + char + ") at position " + this.pos + ". Skipping it!");
  23664. return;
  23665. }
  23666. this.chars[this.pos].setChar(char, this.currPenState);
  23667. this.moveCursor(1);
  23668. }
  23669. clearFromPos(startPos) {
  23670. let i;
  23671. for (i = startPos; i < NR_COLS; i++) {
  23672. this.chars[i].reset();
  23673. }
  23674. }
  23675. clear() {
  23676. this.clearFromPos(0);
  23677. this.pos = 0;
  23678. this.currPenState.reset();
  23679. }
  23680. clearToEndOfRow() {
  23681. this.clearFromPos(this.pos);
  23682. }
  23683. getTextString() {
  23684. const chars = [];
  23685. let empty = true;
  23686. for (let i = 0; i < NR_COLS; i++) {
  23687. const char = this.chars[i].uchar;
  23688. if (char !== " ") {
  23689. empty = false;
  23690. }
  23691. chars.push(char);
  23692. }
  23693. if (empty) {
  23694. return "";
  23695. } else {
  23696. return chars.join("");
  23697. }
  23698. }
  23699. setPenStyles(styles) {
  23700. this.currPenState.setStyles(styles);
  23701. const currChar = this.chars[this.pos];
  23702. currChar.setPenState(this.currPenState);
  23703. }
  23704. };
  23705. var CaptionScreen = class {
  23706. constructor(logger2) {
  23707. this.rows = [];
  23708. this.currRow = NR_ROWS - 1;
  23709. this.nrRollUpRows = null;
  23710. this.lastOutputScreen = null;
  23711. this.logger = void 0;
  23712. for (let i = 0; i < NR_ROWS; i++) {
  23713. this.rows.push(new Row(logger2));
  23714. }
  23715. this.logger = logger2;
  23716. }
  23717. reset() {
  23718. for (let i = 0; i < NR_ROWS; i++) {
  23719. this.rows[i].clear();
  23720. }
  23721. this.currRow = NR_ROWS - 1;
  23722. }
  23723. equals(other) {
  23724. let equal = true;
  23725. for (let i = 0; i < NR_ROWS; i++) {
  23726. if (!this.rows[i].equals(other.rows[i])) {
  23727. equal = false;
  23728. break;
  23729. }
  23730. }
  23731. return equal;
  23732. }
  23733. copy(other) {
  23734. for (let i = 0; i < NR_ROWS; i++) {
  23735. this.rows[i].copy(other.rows[i]);
  23736. }
  23737. }
  23738. isEmpty() {
  23739. let empty = true;
  23740. for (let i = 0; i < NR_ROWS; i++) {
  23741. if (!this.rows[i].isEmpty()) {
  23742. empty = false;
  23743. break;
  23744. }
  23745. }
  23746. return empty;
  23747. }
  23748. backSpace() {
  23749. const row = this.rows[this.currRow];
  23750. row.backSpace();
  23751. }
  23752. clearToEndOfRow() {
  23753. const row = this.rows[this.currRow];
  23754. row.clearToEndOfRow();
  23755. }
  23756. insertChar(char) {
  23757. const row = this.rows[this.currRow];
  23758. row.insertChar(char);
  23759. }
  23760. setPen(styles) {
  23761. const row = this.rows[this.currRow];
  23762. row.setPenStyles(styles);
  23763. }
  23764. moveCursor(relPos) {
  23765. const row = this.rows[this.currRow];
  23766. row.moveCursor(relPos);
  23767. }
  23768. setCursor(absPos) {
  23769. this.logger.log(2, "setCursor: " + absPos);
  23770. const row = this.rows[this.currRow];
  23771. row.setCursor(absPos);
  23772. }
  23773. setPAC(pacData) {
  23774. this.logger.log(2, () => "pacData = " + stringify(pacData));
  23775. let newRow = pacData.row - 1;
  23776. if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
  23777. newRow = this.nrRollUpRows - 1;
  23778. }
  23779. if (this.nrRollUpRows && this.currRow !== newRow) {
  23780. for (let i = 0; i < NR_ROWS; i++) {
  23781. this.rows[i].clear();
  23782. }
  23783. const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  23784. const lastOutputScreen = this.lastOutputScreen;
  23785. if (lastOutputScreen) {
  23786. const prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
  23787. const time = this.logger.time;
  23788. if (prevLineTime !== null && time !== null && prevLineTime < time) {
  23789. for (let i = 0; i < this.nrRollUpRows; i++) {
  23790. this.rows[newRow - this.nrRollUpRows + i + 1].copy(lastOutputScreen.rows[topRowIndex + i]);
  23791. }
  23792. }
  23793. }
  23794. }
  23795. this.currRow = newRow;
  23796. const row = this.rows[this.currRow];
  23797. if (pacData.indent !== null) {
  23798. const indent = pacData.indent;
  23799. const prevPos = Math.max(indent - 1, 0);
  23800. row.setCursor(pacData.indent);
  23801. pacData.color = row.chars[prevPos].penState.foreground;
  23802. }
  23803. const styles = {
  23804. foreground: pacData.color,
  23805. underline: pacData.underline,
  23806. italics: pacData.italics,
  23807. background: "black",
  23808. flash: false
  23809. };
  23810. this.setPen(styles);
  23811. }
  23812. setBkgData(bkgData) {
  23813. this.logger.log(2, () => "bkgData = " + stringify(bkgData));
  23814. this.backSpace();
  23815. this.setPen(bkgData);
  23816. this.insertChar(32);
  23817. }
  23818. setRollUpRows(nrRows) {
  23819. this.nrRollUpRows = nrRows;
  23820. }
  23821. rollUp() {
  23822. if (this.nrRollUpRows === null) {
  23823. this.logger.log(3, "roll_up but nrRollUpRows not set yet");
  23824. return;
  23825. }
  23826. this.logger.log(1, () => this.getDisplayText());
  23827. const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  23828. const topRow = this.rows.splice(topRowIndex, 1)[0];
  23829. topRow.clear();
  23830. this.rows.splice(this.currRow, 0, topRow);
  23831. this.logger.log(2, "Rolling up");
  23832. }
  23833. getDisplayText(asOneRow) {
  23834. asOneRow = asOneRow || false;
  23835. const displayText = [];
  23836. let text = "";
  23837. let rowNr = -1;
  23838. for (let i = 0; i < NR_ROWS; i++) {
  23839. const rowText = this.rows[i].getTextString();
  23840. if (rowText) {
  23841. rowNr = i + 1;
  23842. if (asOneRow) {
  23843. displayText.push("Row " + rowNr + ": '" + rowText + "'");
  23844. } else {
  23845. displayText.push(rowText.trim());
  23846. }
  23847. }
  23848. }
  23849. if (displayText.length > 0) {
  23850. if (asOneRow) {
  23851. text = "[" + displayText.join(" | ") + "]";
  23852. } else {
  23853. text = displayText.join("\n");
  23854. }
  23855. }
  23856. return text;
  23857. }
  23858. getTextAndFormat() {
  23859. return this.rows;
  23860. }
  23861. };
  23862. var Cea608Channel = class {
  23863. constructor(channelNumber, outputFilter, logger2) {
  23864. this.chNr = void 0;
  23865. this.outputFilter = void 0;
  23866. this.mode = void 0;
  23867. this.verbose = void 0;
  23868. this.displayedMemory = void 0;
  23869. this.nonDisplayedMemory = void 0;
  23870. this.lastOutputScreen = void 0;
  23871. this.currRollUpRow = void 0;
  23872. this.writeScreen = void 0;
  23873. this.cueStartTime = void 0;
  23874. this.logger = void 0;
  23875. this.chNr = channelNumber;
  23876. this.outputFilter = outputFilter;
  23877. this.mode = null;
  23878. this.verbose = 0;
  23879. this.displayedMemory = new CaptionScreen(logger2);
  23880. this.nonDisplayedMemory = new CaptionScreen(logger2);
  23881. this.lastOutputScreen = new CaptionScreen(logger2);
  23882. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  23883. this.writeScreen = this.displayedMemory;
  23884. this.mode = null;
  23885. this.cueStartTime = null;
  23886. this.logger = logger2;
  23887. }
  23888. reset() {
  23889. this.mode = null;
  23890. this.displayedMemory.reset();
  23891. this.nonDisplayedMemory.reset();
  23892. this.lastOutputScreen.reset();
  23893. this.outputFilter.reset();
  23894. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  23895. this.writeScreen = this.displayedMemory;
  23896. this.mode = null;
  23897. this.cueStartTime = null;
  23898. }
  23899. getHandler() {
  23900. return this.outputFilter;
  23901. }
  23902. setHandler(newHandler) {
  23903. this.outputFilter = newHandler;
  23904. }
  23905. setPAC(pacData) {
  23906. this.writeScreen.setPAC(pacData);
  23907. }
  23908. setBkgData(bkgData) {
  23909. this.writeScreen.setBkgData(bkgData);
  23910. }
  23911. setMode(newMode) {
  23912. if (newMode === this.mode) {
  23913. return;
  23914. }
  23915. this.mode = newMode;
  23916. this.logger.log(2, () => "MODE=" + newMode);
  23917. if (this.mode === "MODE_POP-ON") {
  23918. this.writeScreen = this.nonDisplayedMemory;
  23919. } else {
  23920. this.writeScreen = this.displayedMemory;
  23921. this.writeScreen.reset();
  23922. }
  23923. if (this.mode !== "MODE_ROLL-UP") {
  23924. this.displayedMemory.nrRollUpRows = null;
  23925. this.nonDisplayedMemory.nrRollUpRows = null;
  23926. }
  23927. this.mode = newMode;
  23928. }
  23929. insertChars(chars) {
  23930. for (let i = 0; i < chars.length; i++) {
  23931. this.writeScreen.insertChar(chars[i]);
  23932. }
  23933. const screen = this.writeScreen === this.displayedMemory ? "DISP" : "NON_DISP";
  23934. this.logger.log(2, () => screen + ": " + this.writeScreen.getDisplayText(true));
  23935. if (this.mode === "MODE_PAINT-ON" || this.mode === "MODE_ROLL-UP") {
  23936. this.logger.log(1, () => "DISPLAYED: " + this.displayedMemory.getDisplayText(true));
  23937. this.outputDataUpdate();
  23938. }
  23939. }
  23940. ccRCL() {
  23941. this.logger.log(2, "RCL - Resume Caption Loading");
  23942. this.setMode("MODE_POP-ON");
  23943. }
  23944. ccBS() {
  23945. this.logger.log(2, "BS - BackSpace");
  23946. if (this.mode === "MODE_TEXT") {
  23947. return;
  23948. }
  23949. this.writeScreen.backSpace();
  23950. if (this.writeScreen === this.displayedMemory) {
  23951. this.outputDataUpdate();
  23952. }
  23953. }
  23954. ccAOF() {
  23955. }
  23956. ccAON() {
  23957. }
  23958. ccDER() {
  23959. this.logger.log(2, "DER- Delete to End of Row");
  23960. this.writeScreen.clearToEndOfRow();
  23961. this.outputDataUpdate();
  23962. }
  23963. ccRU(nrRows) {
  23964. this.logger.log(2, "RU(" + nrRows + ") - Roll Up");
  23965. this.writeScreen = this.displayedMemory;
  23966. this.setMode("MODE_ROLL-UP");
  23967. this.writeScreen.setRollUpRows(nrRows);
  23968. }
  23969. ccFON() {
  23970. this.logger.log(2, "FON - Flash On");
  23971. this.writeScreen.setPen({
  23972. flash: true
  23973. });
  23974. }
  23975. ccRDC() {
  23976. this.logger.log(2, "RDC - Resume Direct Captioning");
  23977. this.setMode("MODE_PAINT-ON");
  23978. }
  23979. ccTR() {
  23980. this.logger.log(2, "TR");
  23981. this.setMode("MODE_TEXT");
  23982. }
  23983. ccRTD() {
  23984. this.logger.log(2, "RTD");
  23985. this.setMode("MODE_TEXT");
  23986. }
  23987. ccEDM() {
  23988. this.logger.log(2, "EDM - Erase Displayed Memory");
  23989. this.displayedMemory.reset();
  23990. this.outputDataUpdate(true);
  23991. }
  23992. ccCR() {
  23993. this.logger.log(2, "CR - Carriage Return");
  23994. this.writeScreen.rollUp();
  23995. this.outputDataUpdate(true);
  23996. }
  23997. ccENM() {
  23998. this.logger.log(2, "ENM - Erase Non-displayed Memory");
  23999. this.nonDisplayedMemory.reset();
  24000. }
  24001. ccEOC() {
  24002. this.logger.log(2, "EOC - End Of Caption");
  24003. if (this.mode === "MODE_POP-ON") {
  24004. const tmp = this.displayedMemory;
  24005. this.displayedMemory = this.nonDisplayedMemory;
  24006. this.nonDisplayedMemory = tmp;
  24007. this.writeScreen = this.nonDisplayedMemory;
  24008. this.logger.log(1, () => "DISP: " + this.displayedMemory.getDisplayText());
  24009. }
  24010. this.outputDataUpdate(true);
  24011. }
  24012. ccTO(nrCols) {
  24013. this.logger.log(2, "TO(" + nrCols + ") - Tab Offset");
  24014. this.writeScreen.moveCursor(nrCols);
  24015. }
  24016. ccMIDROW(secondByte) {
  24017. const styles = {
  24018. flash: false
  24019. };
  24020. styles.underline = secondByte % 2 === 1;
  24021. styles.italics = secondByte >= 46;
  24022. if (!styles.italics) {
  24023. const colorIndex = Math.floor(secondByte / 2) - 16;
  24024. const colors = ["white", "green", "blue", "cyan", "red", "yellow", "magenta"];
  24025. styles.foreground = colors[colorIndex];
  24026. } else {
  24027. styles.foreground = "white";
  24028. }
  24029. this.logger.log(2, "MIDROW: " + stringify(styles));
  24030. this.writeScreen.setPen(styles);
  24031. }
  24032. outputDataUpdate(dispatch = false) {
  24033. const time = this.logger.time;
  24034. if (time === null) {
  24035. return;
  24036. }
  24037. if (this.outputFilter) {
  24038. if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
  24039. this.cueStartTime = time;
  24040. } else {
  24041. if (!this.displayedMemory.equals(this.lastOutputScreen)) {
  24042. this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);
  24043. if (dispatch && this.outputFilter.dispatchCue) {
  24044. this.outputFilter.dispatchCue();
  24045. }
  24046. this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;
  24047. }
  24048. }
  24049. this.lastOutputScreen.copy(this.displayedMemory);
  24050. }
  24051. }
  24052. cueSplitAtTime(t) {
  24053. if (this.outputFilter) {
  24054. if (!this.displayedMemory.isEmpty()) {
  24055. if (this.outputFilter.newCue) {
  24056. this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
  24057. }
  24058. this.cueStartTime = t;
  24059. }
  24060. }
  24061. }
  24062. };
  24063. var Cea608Parser = class {
  24064. constructor(field, out1, out2) {
  24065. this.channels = void 0;
  24066. this.currentChannel = 0;
  24067. this.cmdHistory = createCmdHistory();
  24068. this.logger = void 0;
  24069. const logger2 = this.logger = new CaptionsLogger();
  24070. this.channels = [null, new Cea608Channel(field, out1, logger2), new Cea608Channel(field + 1, out2, logger2)];
  24071. }
  24072. getHandler(channel) {
  24073. return this.channels[channel].getHandler();
  24074. }
  24075. setHandler(channel, newHandler) {
  24076. this.channels[channel].setHandler(newHandler);
  24077. }
  24078. addData(time, byteList) {
  24079. this.logger.time = time;
  24080. for (let i = 0; i < byteList.length; i += 2) {
  24081. const a = byteList[i] & 127;
  24082. const b = byteList[i + 1] & 127;
  24083. let cmdFound = false;
  24084. let charsFound = null;
  24085. if (a === 0 && b === 0) {
  24086. continue;
  24087. } else {
  24088. this.logger.log(3, () => "[" + numArrayToHexArray([byteList[i], byteList[i + 1]]) + "] -> (" + numArrayToHexArray([a, b]) + ")");
  24089. }
  24090. const cmdHistory = this.cmdHistory;
  24091. const isControlCode = a >= 16 && a <= 31;
  24092. if (isControlCode) {
  24093. if (hasCmdRepeated(a, b, cmdHistory)) {
  24094. setLastCmd(null, null, cmdHistory);
  24095. this.logger.log(3, () => "Repeated command (" + numArrayToHexArray([a, b]) + ") is dropped");
  24096. continue;
  24097. }
  24098. setLastCmd(a, b, this.cmdHistory);
  24099. cmdFound = this.parseCmd(a, b);
  24100. if (!cmdFound) {
  24101. cmdFound = this.parseMidrow(a, b);
  24102. }
  24103. if (!cmdFound) {
  24104. cmdFound = this.parsePAC(a, b);
  24105. }
  24106. if (!cmdFound) {
  24107. cmdFound = this.parseBackgroundAttributes(a, b);
  24108. }
  24109. } else {
  24110. setLastCmd(null, null, cmdHistory);
  24111. }
  24112. if (!cmdFound) {
  24113. charsFound = this.parseChars(a, b);
  24114. if (charsFound) {
  24115. const currChNr = this.currentChannel;
  24116. if (currChNr && currChNr > 0) {
  24117. const channel = this.channels[currChNr];
  24118. channel.insertChars(charsFound);
  24119. } else {
  24120. this.logger.log(2, "No channel found yet. TEXT-MODE?");
  24121. }
  24122. }
  24123. }
  24124. if (!cmdFound && !charsFound) {
  24125. this.logger.log(2, () => "Couldn't parse cleaned data " + numArrayToHexArray([a, b]) + " orig: " + numArrayToHexArray([byteList[i], byteList[i + 1]]));
  24126. }
  24127. }
  24128. }
  24129. parseCmd(a, b) {
  24130. const cond1 = (a === 20 || a === 28 || a === 21 || a === 29) && b >= 32 && b <= 47;
  24131. const cond2 = (a === 23 || a === 31) && b >= 33 && b <= 35;
  24132. if (!(cond1 || cond2)) {
  24133. return false;
  24134. }
  24135. const chNr = a === 20 || a === 21 || a === 23 ? 1 : 2;
  24136. const channel = this.channels[chNr];
  24137. if (a === 20 || a === 21 || a === 28 || a === 29) {
  24138. if (b === 32) {
  24139. channel.ccRCL();
  24140. } else if (b === 33) {
  24141. channel.ccBS();
  24142. } else if (b === 34) {
  24143. channel.ccAOF();
  24144. } else if (b === 35) {
  24145. channel.ccAON();
  24146. } else if (b === 36) {
  24147. channel.ccDER();
  24148. } else if (b === 37) {
  24149. channel.ccRU(2);
  24150. } else if (b === 38) {
  24151. channel.ccRU(3);
  24152. } else if (b === 39) {
  24153. channel.ccRU(4);
  24154. } else if (b === 40) {
  24155. channel.ccFON();
  24156. } else if (b === 41) {
  24157. channel.ccRDC();
  24158. } else if (b === 42) {
  24159. channel.ccTR();
  24160. } else if (b === 43) {
  24161. channel.ccRTD();
  24162. } else if (b === 44) {
  24163. channel.ccEDM();
  24164. } else if (b === 45) {
  24165. channel.ccCR();
  24166. } else if (b === 46) {
  24167. channel.ccENM();
  24168. } else if (b === 47) {
  24169. channel.ccEOC();
  24170. }
  24171. } else {
  24172. channel.ccTO(b - 32);
  24173. }
  24174. this.currentChannel = chNr;
  24175. return true;
  24176. }
  24177. parseMidrow(a, b) {
  24178. let chNr = 0;
  24179. if ((a === 17 || a === 25) && b >= 32 && b <= 47) {
  24180. if (a === 17) {
  24181. chNr = 1;
  24182. } else {
  24183. chNr = 2;
  24184. }
  24185. if (chNr !== this.currentChannel) {
  24186. this.logger.log(0, "Mismatch channel in midrow parsing");
  24187. return false;
  24188. }
  24189. const channel = this.channels[chNr];
  24190. if (!channel) {
  24191. return false;
  24192. }
  24193. channel.ccMIDROW(b);
  24194. this.logger.log(3, () => "MIDROW (" + numArrayToHexArray([a, b]) + ")");
  24195. return true;
  24196. }
  24197. return false;
  24198. }
  24199. parsePAC(a, b) {
  24200. let row;
  24201. const case1 = (a >= 17 && a <= 23 || a >= 25 && a <= 31) && b >= 64 && b <= 127;
  24202. const case2 = (a === 16 || a === 24) && b >= 64 && b <= 95;
  24203. if (!(case1 || case2)) {
  24204. return false;
  24205. }
  24206. const chNr = a <= 23 ? 1 : 2;
  24207. if (b >= 64 && b <= 95) {
  24208. row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
  24209. } else {
  24210. row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
  24211. }
  24212. const channel = this.channels[chNr];
  24213. if (!channel) {
  24214. return false;
  24215. }
  24216. channel.setPAC(this.interpretPAC(row, b));
  24217. this.currentChannel = chNr;
  24218. return true;
  24219. }
  24220. interpretPAC(row, byte) {
  24221. let pacIndex;
  24222. const pacData = {
  24223. color: null,
  24224. italics: false,
  24225. indent: null,
  24226. underline: false,
  24227. row
  24228. };
  24229. if (byte > 95) {
  24230. pacIndex = byte - 96;
  24231. } else {
  24232. pacIndex = byte - 64;
  24233. }
  24234. pacData.underline = (pacIndex & 1) === 1;
  24235. if (pacIndex <= 13) {
  24236. pacData.color = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "white"][Math.floor(pacIndex / 2)];
  24237. } else if (pacIndex <= 15) {
  24238. pacData.italics = true;
  24239. pacData.color = "white";
  24240. } else {
  24241. pacData.indent = Math.floor((pacIndex - 16) / 2) * 4;
  24242. }
  24243. return pacData;
  24244. }
  24245. parseChars(a, b) {
  24246. let channelNr;
  24247. let charCodes = null;
  24248. let charCode1 = null;
  24249. if (a >= 25) {
  24250. channelNr = 2;
  24251. charCode1 = a - 8;
  24252. } else {
  24253. channelNr = 1;
  24254. charCode1 = a;
  24255. }
  24256. if (charCode1 >= 17 && charCode1 <= 19) {
  24257. let oneCode;
  24258. if (charCode1 === 17) {
  24259. oneCode = b + 80;
  24260. } else if (charCode1 === 18) {
  24261. oneCode = b + 112;
  24262. } else {
  24263. oneCode = b + 144;
  24264. }
  24265. this.logger.log(2, () => "Special char '" + getCharForByte(oneCode) + "' in channel " + channelNr);
  24266. charCodes = [oneCode];
  24267. } else if (a >= 32 && a <= 127) {
  24268. charCodes = b === 0 ? [a] : [a, b];
  24269. }
  24270. if (charCodes) {
  24271. this.logger.log(3, () => "Char codes = " + numArrayToHexArray(charCodes).join(","));
  24272. }
  24273. return charCodes;
  24274. }
  24275. parseBackgroundAttributes(a, b) {
  24276. const case1 = (a === 16 || a === 24) && b >= 32 && b <= 47;
  24277. const case2 = (a === 23 || a === 31) && b >= 45 && b <= 47;
  24278. if (!(case1 || case2)) {
  24279. return false;
  24280. }
  24281. let index;
  24282. const bkgData = {};
  24283. if (a === 16 || a === 24) {
  24284. index = Math.floor((b - 32) / 2);
  24285. bkgData.background = backgroundColors[index];
  24286. if (b % 2 === 1) {
  24287. bkgData.background = bkgData.background + "_semi";
  24288. }
  24289. } else if (b === 45) {
  24290. bkgData.background = "transparent";
  24291. } else {
  24292. bkgData.foreground = "black";
  24293. if (b === 47) {
  24294. bkgData.underline = true;
  24295. }
  24296. }
  24297. const chNr = a <= 23 ? 1 : 2;
  24298. const channel = this.channels[chNr];
  24299. channel.setBkgData(bkgData);
  24300. return true;
  24301. }
  24302. reset() {
  24303. for (let i = 0; i < Object.keys(this.channels).length; i++) {
  24304. const channel = this.channels[i];
  24305. if (channel) {
  24306. channel.reset();
  24307. }
  24308. }
  24309. setLastCmd(null, null, this.cmdHistory);
  24310. }
  24311. cueSplitAtTime(t) {
  24312. for (let i = 0; i < this.channels.length; i++) {
  24313. const channel = this.channels[i];
  24314. if (channel) {
  24315. channel.cueSplitAtTime(t);
  24316. }
  24317. }
  24318. }
  24319. };
  24320. function setLastCmd(a, b, cmdHistory) {
  24321. cmdHistory.a = a;
  24322. cmdHistory.b = b;
  24323. }
  24324. function hasCmdRepeated(a, b, cmdHistory) {
  24325. return cmdHistory.a === a && cmdHistory.b === b;
  24326. }
  24327. function createCmdHistory() {
  24328. return {
  24329. a: null,
  24330. b: null
  24331. };
  24332. }
  24333. var VTTCue = function() {
  24334. if (optionalSelf != null && optionalSelf.VTTCue) {
  24335. return self.VTTCue;
  24336. }
  24337. const AllowedDirections = ["", "lr", "rl"];
  24338. const AllowedAlignments = ["start", "middle", "end", "left", "right"];
  24339. function isAllowedValue(allowed, value) {
  24340. if (typeof value !== "string") {
  24341. return false;
  24342. }
  24343. if (!Array.isArray(allowed)) {
  24344. return false;
  24345. }
  24346. const lcValue = value.toLowerCase();
  24347. if (~allowed.indexOf(lcValue)) {
  24348. return lcValue;
  24349. }
  24350. return false;
  24351. }
  24352. function findDirectionSetting(value) {
  24353. return isAllowedValue(AllowedDirections, value);
  24354. }
  24355. function findAlignSetting(value) {
  24356. return isAllowedValue(AllowedAlignments, value);
  24357. }
  24358. function extend(obj, ...rest) {
  24359. let i = 1;
  24360. for (; i < arguments.length; i++) {
  24361. const cobj = arguments[i];
  24362. for (const p in cobj) {
  24363. obj[p] = cobj[p];
  24364. }
  24365. }
  24366. return obj;
  24367. }
  24368. function VTTCue2(startTime, endTime, text) {
  24369. const cue = this;
  24370. const baseObj = {
  24371. enumerable: true
  24372. };
  24373. cue.hasBeenReset = false;
  24374. let _id = "";
  24375. let _pauseOnExit = false;
  24376. let _startTime = startTime;
  24377. let _endTime = endTime;
  24378. let _text = text;
  24379. let _region = null;
  24380. let _vertical = "";
  24381. let _snapToLines = true;
  24382. let _line = "auto";
  24383. let _lineAlign = "start";
  24384. let _position = 50;
  24385. let _positionAlign = "middle";
  24386. let _size = 50;
  24387. let _align = "middle";
  24388. Object.defineProperty(cue, "id", extend({}, baseObj, {
  24389. get: function() {
  24390. return _id;
  24391. },
  24392. set: function(value) {
  24393. _id = "" + value;
  24394. }
  24395. }));
  24396. Object.defineProperty(cue, "pauseOnExit", extend({}, baseObj, {
  24397. get: function() {
  24398. return _pauseOnExit;
  24399. },
  24400. set: function(value) {
  24401. _pauseOnExit = !!value;
  24402. }
  24403. }));
  24404. Object.defineProperty(cue, "startTime", extend({}, baseObj, {
  24405. get: function() {
  24406. return _startTime;
  24407. },
  24408. set: function(value) {
  24409. if (typeof value !== "number") {
  24410. throw new TypeError("Start time must be set to a number.");
  24411. }
  24412. _startTime = value;
  24413. this.hasBeenReset = true;
  24414. }
  24415. }));
  24416. Object.defineProperty(cue, "endTime", extend({}, baseObj, {
  24417. get: function() {
  24418. return _endTime;
  24419. },
  24420. set: function(value) {
  24421. if (typeof value !== "number") {
  24422. throw new TypeError("End time must be set to a number.");
  24423. }
  24424. _endTime = value;
  24425. this.hasBeenReset = true;
  24426. }
  24427. }));
  24428. Object.defineProperty(cue, "text", extend({}, baseObj, {
  24429. get: function() {
  24430. return _text;
  24431. },
  24432. set: function(value) {
  24433. _text = "" + value;
  24434. this.hasBeenReset = true;
  24435. }
  24436. }));
  24437. Object.defineProperty(cue, "region", extend({}, baseObj, {
  24438. get: function() {
  24439. return _region;
  24440. },
  24441. set: function(value) {
  24442. _region = value;
  24443. this.hasBeenReset = true;
  24444. }
  24445. }));
  24446. Object.defineProperty(cue, "vertical", extend({}, baseObj, {
  24447. get: function() {
  24448. return _vertical;
  24449. },
  24450. set: function(value) {
  24451. const setting = findDirectionSetting(value);
  24452. if (setting === false) {
  24453. throw new SyntaxError("An invalid or illegal string was specified.");
  24454. }
  24455. _vertical = setting;
  24456. this.hasBeenReset = true;
  24457. }
  24458. }));
  24459. Object.defineProperty(cue, "snapToLines", extend({}, baseObj, {
  24460. get: function() {
  24461. return _snapToLines;
  24462. },
  24463. set: function(value) {
  24464. _snapToLines = !!value;
  24465. this.hasBeenReset = true;
  24466. }
  24467. }));
  24468. Object.defineProperty(cue, "line", extend({}, baseObj, {
  24469. get: function() {
  24470. return _line;
  24471. },
  24472. set: function(value) {
  24473. if (typeof value !== "number" && value !== "auto") {
  24474. throw new SyntaxError("An invalid number or illegal string was specified.");
  24475. }
  24476. _line = value;
  24477. this.hasBeenReset = true;
  24478. }
  24479. }));
  24480. Object.defineProperty(cue, "lineAlign", extend({}, baseObj, {
  24481. get: function() {
  24482. return _lineAlign;
  24483. },
  24484. set: function(value) {
  24485. const setting = findAlignSetting(value);
  24486. if (!setting) {
  24487. throw new SyntaxError("An invalid or illegal string was specified.");
  24488. }
  24489. _lineAlign = setting;
  24490. this.hasBeenReset = true;
  24491. }
  24492. }));
  24493. Object.defineProperty(cue, "position", extend({}, baseObj, {
  24494. get: function() {
  24495. return _position;
  24496. },
  24497. set: function(value) {
  24498. if (value < 0 || value > 100) {
  24499. throw new Error("Position must be between 0 and 100.");
  24500. }
  24501. _position = value;
  24502. this.hasBeenReset = true;
  24503. }
  24504. }));
  24505. Object.defineProperty(cue, "positionAlign", extend({}, baseObj, {
  24506. get: function() {
  24507. return _positionAlign;
  24508. },
  24509. set: function(value) {
  24510. const setting = findAlignSetting(value);
  24511. if (!setting) {
  24512. throw new SyntaxError("An invalid or illegal string was specified.");
  24513. }
  24514. _positionAlign = setting;
  24515. this.hasBeenReset = true;
  24516. }
  24517. }));
  24518. Object.defineProperty(cue, "size", extend({}, baseObj, {
  24519. get: function() {
  24520. return _size;
  24521. },
  24522. set: function(value) {
  24523. if (value < 0 || value > 100) {
  24524. throw new Error("Size must be between 0 and 100.");
  24525. }
  24526. _size = value;
  24527. this.hasBeenReset = true;
  24528. }
  24529. }));
  24530. Object.defineProperty(cue, "align", extend({}, baseObj, {
  24531. get: function() {
  24532. return _align;
  24533. },
  24534. set: function(value) {
  24535. const setting = findAlignSetting(value);
  24536. if (!setting) {
  24537. throw new SyntaxError("An invalid or illegal string was specified.");
  24538. }
  24539. _align = setting;
  24540. this.hasBeenReset = true;
  24541. }
  24542. }));
  24543. cue.displayState = void 0;
  24544. }
  24545. VTTCue2.prototype.getCueAsHTML = function() {
  24546. const WebVTT = self.WebVTT;
  24547. return WebVTT.convertCueToDOMTree(self, this.text);
  24548. };
  24549. return VTTCue2;
  24550. }();
  24551. var StringDecoder = class {
  24552. decode(data, options) {
  24553. if (!data) {
  24554. return "";
  24555. }
  24556. if (typeof data !== "string") {
  24557. throw new Error("Error - expected string data.");
  24558. }
  24559. return decodeURIComponent(encodeURIComponent(data));
  24560. }
  24561. };
  24562. function parseTimeStamp(input) {
  24563. function computeSeconds(h, m2, s, f) {
  24564. return (h | 0) * 3600 + (m2 | 0) * 60 + (s | 0) + parseFloat(f || 0);
  24565. }
  24566. const m = input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);
  24567. if (!m) {
  24568. return null;
  24569. }
  24570. if (parseFloat(m[2]) > 59) {
  24571. return computeSeconds(m[2], m[3], 0, m[4]);
  24572. }
  24573. return computeSeconds(m[1], m[2], m[3], m[4]);
  24574. }
  24575. var Settings = class {
  24576. constructor() {
  24577. this.values = /* @__PURE__ */ Object.create(null);
  24578. }
  24579. set(k, v) {
  24580. if (!this.get(k) && v !== "") {
  24581. this.values[k] = v;
  24582. }
  24583. }
  24584. get(k, dflt, defaultKey) {
  24585. if (defaultKey) {
  24586. return this.has(k) ? this.values[k] : dflt[defaultKey];
  24587. }
  24588. return this.has(k) ? this.values[k] : dflt;
  24589. }
  24590. has(k) {
  24591. return k in this.values;
  24592. }
  24593. alt(k, v, a) {
  24594. for (let n = 0; n < a.length; ++n) {
  24595. if (v === a[n]) {
  24596. this.set(k, v);
  24597. break;
  24598. }
  24599. }
  24600. }
  24601. integer(k, v) {
  24602. if (/^-?\d+$/.test(v)) {
  24603. this.set(k, parseInt(v, 10));
  24604. }
  24605. }
  24606. percent(k, v) {
  24607. if (/^([\d]{1,3})(\.[\d]*)?%$/.test(v)) {
  24608. const percent = parseFloat(v);
  24609. if (percent >= 0 && percent <= 100) {
  24610. this.set(k, percent);
  24611. return true;
  24612. }
  24613. }
  24614. return false;
  24615. }
  24616. };
  24617. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  24618. const groups = groupDelim ? input.split(groupDelim) : [input];
  24619. for (const i in groups) {
  24620. if (typeof groups[i] !== "string") {
  24621. continue;
  24622. }
  24623. const kv = groups[i].split(keyValueDelim);
  24624. if (kv.length !== 2) {
  24625. continue;
  24626. }
  24627. const k = kv[0];
  24628. const v = kv[1];
  24629. callback(k, v);
  24630. }
  24631. }
  24632. var defaults = new VTTCue(0, 0, "");
  24633. var center = defaults.align === "middle" ? "middle" : "center";
  24634. function parseCue(input, cue, regionList) {
  24635. const oInput = input;
  24636. function consumeTimeStamp() {
  24637. const ts = parseTimeStamp(input);
  24638. if (ts === null) {
  24639. throw new Error("Malformed timestamp: " + oInput);
  24640. }
  24641. input = input.replace(/^[^\sa-zA-Z-]+/, "");
  24642. return ts;
  24643. }
  24644. function consumeCueSettings(input2, cue2) {
  24645. const settings = new Settings();
  24646. parseOptions(input2, function(k, v) {
  24647. let vals;
  24648. switch (k) {
  24649. case "region":
  24650. for (let i = regionList.length - 1; i >= 0; i--) {
  24651. if (regionList[i].id === v) {
  24652. settings.set(k, regionList[i].region);
  24653. break;
  24654. }
  24655. }
  24656. break;
  24657. case "vertical":
  24658. settings.alt(k, v, ["rl", "lr"]);
  24659. break;
  24660. case "line":
  24661. vals = v.split(",");
  24662. settings.integer(k, vals[0]);
  24663. if (settings.percent(k, vals[0])) {
  24664. settings.set("snapToLines", false);
  24665. }
  24666. settings.alt(k, vals[0], ["auto"]);
  24667. if (vals.length === 2) {
  24668. settings.alt("lineAlign", vals[1], ["start", center, "end"]);
  24669. }
  24670. break;
  24671. case "position":
  24672. vals = v.split(",");
  24673. settings.percent(k, vals[0]);
  24674. if (vals.length === 2) {
  24675. settings.alt("positionAlign", vals[1], ["start", center, "end", "line-left", "line-right", "auto"]);
  24676. }
  24677. break;
  24678. case "size":
  24679. settings.percent(k, v);
  24680. break;
  24681. case "align":
  24682. settings.alt(k, v, ["start", center, "end", "left", "right"]);
  24683. break;
  24684. }
  24685. }, /:/, /\s/);
  24686. cue2.region = settings.get("region", null);
  24687. cue2.vertical = settings.get("vertical", "");
  24688. let line = settings.get("line", "auto");
  24689. if (line === "auto" && defaults.line === -1) {
  24690. line = -1;
  24691. }
  24692. cue2.line = line;
  24693. cue2.lineAlign = settings.get("lineAlign", "start");
  24694. cue2.snapToLines = settings.get("snapToLines", true);
  24695. cue2.size = settings.get("size", 100);
  24696. cue2.align = settings.get("align", center);
  24697. let position = settings.get("position", "auto");
  24698. if (position === "auto" && defaults.position === 50) {
  24699. position = cue2.align === "start" || cue2.align === "left" ? 0 : cue2.align === "end" || cue2.align === "right" ? 100 : 50;
  24700. }
  24701. cue2.position = position;
  24702. }
  24703. function skipWhitespace() {
  24704. input = input.replace(/^\s+/, "");
  24705. }
  24706. skipWhitespace();
  24707. cue.startTime = consumeTimeStamp();
  24708. skipWhitespace();
  24709. if (input.slice(0, 3) !== "-->") {
  24710. throw new Error("Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
  24711. }
  24712. input = input.slice(3);
  24713. skipWhitespace();
  24714. cue.endTime = consumeTimeStamp();
  24715. skipWhitespace();
  24716. consumeCueSettings(input, cue);
  24717. }
  24718. function fixLineBreaks(input) {
  24719. return input.replace(/<br(?: \/)?>/gi, "\n");
  24720. }
  24721. var VTTParser = class {
  24722. constructor() {
  24723. this.state = "INITIAL";
  24724. this.buffer = "";
  24725. this.decoder = new StringDecoder();
  24726. this.regionList = [];
  24727. this.cue = null;
  24728. this.oncue = void 0;
  24729. this.onparsingerror = void 0;
  24730. this.onflush = void 0;
  24731. }
  24732. parse(data) {
  24733. const _this = this;
  24734. if (data) {
  24735. _this.buffer += _this.decoder.decode(data, {
  24736. stream: true
  24737. });
  24738. }
  24739. function collectNextLine() {
  24740. let buffer = _this.buffer;
  24741. let pos = 0;
  24742. buffer = fixLineBreaks(buffer);
  24743. while (pos < buffer.length && buffer[pos] !== "\r" && buffer[pos] !== "\n") {
  24744. ++pos;
  24745. }
  24746. const line = buffer.slice(0, pos);
  24747. if (buffer[pos] === "\r") {
  24748. ++pos;
  24749. }
  24750. if (buffer[pos] === "\n") {
  24751. ++pos;
  24752. }
  24753. _this.buffer = buffer.slice(pos);
  24754. return line;
  24755. }
  24756. function parseHeader2(input) {
  24757. parseOptions(input, function(k, v) {
  24758. }, /:/);
  24759. }
  24760. try {
  24761. let line = "";
  24762. if (_this.state === "INITIAL") {
  24763. if (!/\r\n|\n/.test(_this.buffer)) {
  24764. return this;
  24765. }
  24766. line = collectNextLine();
  24767. const m = line.match(/^()?WEBVTT([ \t].*)?$/);
  24768. if (!(m != null && m[0])) {
  24769. throw new Error("Malformed WebVTT signature.");
  24770. }
  24771. _this.state = "HEADER";
  24772. }
  24773. let alreadyCollectedLine = false;
  24774. while (_this.buffer) {
  24775. if (!/\r\n|\n/.test(_this.buffer)) {
  24776. return this;
  24777. }
  24778. if (!alreadyCollectedLine) {
  24779. line = collectNextLine();
  24780. } else {
  24781. alreadyCollectedLine = false;
  24782. }
  24783. switch (_this.state) {
  24784. case "HEADER":
  24785. if (/:/.test(line)) {
  24786. parseHeader2(line);
  24787. } else if (!line) {
  24788. _this.state = "ID";
  24789. }
  24790. continue;
  24791. case "NOTE":
  24792. if (!line) {
  24793. _this.state = "ID";
  24794. }
  24795. continue;
  24796. case "ID":
  24797. if (/^NOTE($|[ \t])/.test(line)) {
  24798. _this.state = "NOTE";
  24799. break;
  24800. }
  24801. if (!line) {
  24802. continue;
  24803. }
  24804. _this.cue = new VTTCue(0, 0, "");
  24805. _this.state = "CUE";
  24806. if (line.indexOf("-->") === -1) {
  24807. _this.cue.id = line;
  24808. continue;
  24809. }
  24810. case "CUE":
  24811. if (!_this.cue) {
  24812. _this.state = "BADCUE";
  24813. continue;
  24814. }
  24815. try {
  24816. parseCue(line, _this.cue, _this.regionList);
  24817. } catch (e) {
  24818. _this.cue = null;
  24819. _this.state = "BADCUE";
  24820. continue;
  24821. }
  24822. _this.state = "CUETEXT";
  24823. continue;
  24824. case "CUETEXT":
  24825. {
  24826. const hasSubstring = line.indexOf("-->") !== -1;
  24827. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  24828. if (_this.oncue && _this.cue) {
  24829. _this.oncue(_this.cue);
  24830. }
  24831. _this.cue = null;
  24832. _this.state = "ID";
  24833. continue;
  24834. }
  24835. if (_this.cue === null) {
  24836. continue;
  24837. }
  24838. if (_this.cue.text) {
  24839. _this.cue.text += "\n";
  24840. }
  24841. _this.cue.text += line;
  24842. }
  24843. continue;
  24844. case "BADCUE":
  24845. if (!line) {
  24846. _this.state = "ID";
  24847. }
  24848. }
  24849. }
  24850. } catch (e) {
  24851. if (_this.state === "CUETEXT" && _this.cue && _this.oncue) {
  24852. _this.oncue(_this.cue);
  24853. }
  24854. _this.cue = null;
  24855. _this.state = _this.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
  24856. }
  24857. return this;
  24858. }
  24859. flush() {
  24860. const _this = this;
  24861. try {
  24862. if (_this.cue || _this.state === "HEADER") {
  24863. _this.buffer += "\n\n";
  24864. _this.parse();
  24865. }
  24866. if (_this.state === "INITIAL" || _this.state === "BADWEBVTT") {
  24867. throw new Error("Malformed WebVTT signature.");
  24868. }
  24869. } catch (e) {
  24870. if (_this.onparsingerror) {
  24871. _this.onparsingerror(e);
  24872. }
  24873. }
  24874. if (_this.onflush) {
  24875. _this.onflush();
  24876. }
  24877. return this;
  24878. }
  24879. };
  24880. var LINEBREAKS = /\r\n|\n\r|\n|\r/g;
  24881. var startsWith = function startsWith2(inputString, searchString, position = 0) {
  24882. return inputString.slice(position, position + searchString.length) === searchString;
  24883. };
  24884. var cueString2millis = function cueString2millis2(timeString) {
  24885. let ts = parseInt(timeString.slice(-3));
  24886. const secs = parseInt(timeString.slice(-6, -4));
  24887. const mins = parseInt(timeString.slice(-9, -7));
  24888. const hours = timeString.length > 9 ? parseInt(timeString.substring(0, timeString.indexOf(":"))) : 0;
  24889. if (!isFiniteNumber(ts) || !isFiniteNumber(secs) || !isFiniteNumber(mins) || !isFiniteNumber(hours)) {
  24890. throw Error(`Malformed X-TIMESTAMP-MAP: Local:${timeString}`);
  24891. }
  24892. ts += 1e3 * secs;
  24893. ts += 60 * 1e3 * mins;
  24894. ts += 60 * 60 * 1e3 * hours;
  24895. return ts;
  24896. };
  24897. function generateCueId(startTime, endTime, text) {
  24898. return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);
  24899. }
  24900. var calculateOffset = function calculateOffset2(vttCCs, cc, presentationTime) {
  24901. let currCC = vttCCs[cc];
  24902. let prevCC = vttCCs[currCC.prevCC];
  24903. if (!prevCC || !prevCC.new && currCC.new) {
  24904. vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
  24905. currCC.new = false;
  24906. return;
  24907. }
  24908. while ((_prevCC = prevCC) != null && _prevCC.new) {
  24909. var _prevCC;
  24910. vttCCs.ccOffset += currCC.start - prevCC.start;
  24911. currCC.new = false;
  24912. currCC = prevCC;
  24913. prevCC = vttCCs[currCC.prevCC];
  24914. }
  24915. vttCCs.presentationOffset = presentationTime;
  24916. };
  24917. function parseWebVTT(vttByteArray, initPTS, vttCCs, cc, timeOffset, callBack, errorCallBack) {
  24918. const parser = new VTTParser();
  24919. const vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, "\n").split("\n");
  24920. const cues = [];
  24921. const init90kHz = initPTS ? toMpegTsClockFromTimescale(initPTS.baseTime, initPTS.timescale) : 0;
  24922. let cueTime = "00:00.000";
  24923. let timestampMapMPEGTS = 0;
  24924. let timestampMapLOCAL = 0;
  24925. let parsingError;
  24926. let inHeader = true;
  24927. parser.oncue = function(cue) {
  24928. const currCC = vttCCs[cc];
  24929. let cueOffset = vttCCs.ccOffset;
  24930. const webVttMpegTsMapOffset = (timestampMapMPEGTS - init90kHz) / 9e4;
  24931. if (currCC != null && currCC.new) {
  24932. if (timestampMapLOCAL !== void 0) {
  24933. cueOffset = vttCCs.ccOffset = currCC.start;
  24934. } else {
  24935. calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);
  24936. }
  24937. }
  24938. if (webVttMpegTsMapOffset) {
  24939. if (!initPTS) {
  24940. parsingError = new Error("Missing initPTS for VTT MPEGTS");
  24941. return;
  24942. }
  24943. cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;
  24944. }
  24945. const duration = cue.endTime - cue.startTime;
  24946. const startTime = normalizePts((cue.startTime + cueOffset - timestampMapLOCAL) * 9e4, timeOffset * 9e4) / 9e4;
  24947. cue.startTime = Math.max(startTime, 0);
  24948. cue.endTime = Math.max(startTime + duration, 0);
  24949. const text = cue.text.trim();
  24950. cue.text = decodeURIComponent(encodeURIComponent(text));
  24951. if (!cue.id) {
  24952. cue.id = generateCueId(cue.startTime, cue.endTime, text);
  24953. }
  24954. if (cue.endTime > 0) {
  24955. cues.push(cue);
  24956. }
  24957. };
  24958. parser.onparsingerror = function(error) {
  24959. parsingError = error;
  24960. };
  24961. parser.onflush = function() {
  24962. if (parsingError) {
  24963. errorCallBack(parsingError);
  24964. return;
  24965. }
  24966. callBack(cues);
  24967. };
  24968. vttLines.forEach((line) => {
  24969. if (inHeader) {
  24970. if (startsWith(line, "X-TIMESTAMP-MAP=")) {
  24971. inHeader = false;
  24972. line.slice(16).split(",").forEach((timestamp) => {
  24973. if (startsWith(timestamp, "LOCAL:")) {
  24974. cueTime = timestamp.slice(6);
  24975. } else if (startsWith(timestamp, "MPEGTS:")) {
  24976. timestampMapMPEGTS = parseInt(timestamp.slice(7));
  24977. }
  24978. });
  24979. try {
  24980. timestampMapLOCAL = cueString2millis(cueTime) / 1e3;
  24981. } catch (error) {
  24982. parsingError = error;
  24983. }
  24984. return;
  24985. } else if (line === "") {
  24986. inHeader = false;
  24987. }
  24988. }
  24989. parser.parse(line + "\n");
  24990. });
  24991. parser.flush();
  24992. }
  24993. var IMSC1_CODEC = "stpp.ttml.im1t";
  24994. var HMSF_REGEX = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/;
  24995. var TIME_UNIT_REGEX = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/;
  24996. var textAlignToLineAlign = {
  24997. left: "start",
  24998. center: "center",
  24999. right: "end",
  25000. start: "start",
  25001. end: "end"
  25002. };
  25003. function parseIMSC1(payload, initPTS, callBack, errorCallBack) {
  25004. const results = findBox(new Uint8Array(payload), ["mdat"]);
  25005. if (results.length === 0) {
  25006. errorCallBack(new Error("Could not parse IMSC1 mdat"));
  25007. return;
  25008. }
  25009. const ttmlList = results.map((mdat) => utf8ArrayToStr(mdat));
  25010. const syncTime = toTimescaleFromScale(initPTS.baseTime, 1, initPTS.timescale);
  25011. try {
  25012. ttmlList.forEach((ttml) => callBack(parseTTML(ttml, syncTime)));
  25013. } catch (error) {
  25014. errorCallBack(error);
  25015. }
  25016. }
  25017. function parseTTML(ttml, syncTime) {
  25018. const parser = new DOMParser();
  25019. const xmlDoc = parser.parseFromString(ttml, "text/xml");
  25020. const tt = xmlDoc.getElementsByTagName("tt")[0];
  25021. if (!tt) {
  25022. throw new Error("Invalid ttml");
  25023. }
  25024. const defaultRateInfo = {
  25025. frameRate: 30,
  25026. subFrameRate: 1,
  25027. frameRateMultiplier: 0,
  25028. tickRate: 0
  25029. };
  25030. const rateInfo = Object.keys(defaultRateInfo).reduce((result, key) => {
  25031. result[key] = tt.getAttribute(`ttp:${key}`) || defaultRateInfo[key];
  25032. return result;
  25033. }, {});
  25034. const trim = tt.getAttribute("xml:space") !== "preserve";
  25035. const styleElements = collectionToDictionary(getElementCollection(tt, "styling", "style"));
  25036. const regionElements = collectionToDictionary(getElementCollection(tt, "layout", "region"));
  25037. const cueElements = getElementCollection(tt, "body", "[begin]");
  25038. return [].map.call(cueElements, (cueElement) => {
  25039. const cueText = getTextContent(cueElement, trim);
  25040. if (!cueText || !cueElement.hasAttribute("begin")) {
  25041. return null;
  25042. }
  25043. const startTime = parseTtmlTime(cueElement.getAttribute("begin"), rateInfo);
  25044. const duration = parseTtmlTime(cueElement.getAttribute("dur"), rateInfo);
  25045. let endTime = parseTtmlTime(cueElement.getAttribute("end"), rateInfo);
  25046. if (startTime === null) {
  25047. throw timestampParsingError(cueElement);
  25048. }
  25049. if (endTime === null) {
  25050. if (duration === null) {
  25051. throw timestampParsingError(cueElement);
  25052. }
  25053. endTime = startTime + duration;
  25054. }
  25055. const cue = new VTTCue(startTime - syncTime, endTime - syncTime, cueText);
  25056. cue.id = generateCueId(cue.startTime, cue.endTime, cue.text);
  25057. const region = regionElements[cueElement.getAttribute("region")];
  25058. const style = styleElements[cueElement.getAttribute("style")];
  25059. const styles = getTtmlStyles(region, style, styleElements);
  25060. const {
  25061. textAlign
  25062. } = styles;
  25063. if (textAlign) {
  25064. const lineAlign = textAlignToLineAlign[textAlign];
  25065. if (lineAlign) {
  25066. cue.lineAlign = lineAlign;
  25067. }
  25068. cue.align = textAlign;
  25069. }
  25070. _extends(cue, styles);
  25071. return cue;
  25072. }).filter((cue) => cue !== null);
  25073. }
  25074. function getElementCollection(fromElement, parentName, childName) {
  25075. const parent = fromElement.getElementsByTagName(parentName)[0];
  25076. if (parent) {
  25077. return [].slice.call(parent.querySelectorAll(childName));
  25078. }
  25079. return [];
  25080. }
  25081. function collectionToDictionary(elementsWithId) {
  25082. return elementsWithId.reduce((dict, element) => {
  25083. const id = element.getAttribute("xml:id");
  25084. if (id) {
  25085. dict[id] = element;
  25086. }
  25087. return dict;
  25088. }, {});
  25089. }
  25090. function getTextContent(element, trim) {
  25091. return [].slice.call(element.childNodes).reduce((str, node, i) => {
  25092. var _node$childNodes;
  25093. if (node.nodeName === "br" && i) {
  25094. return str + "\n";
  25095. }
  25096. if ((_node$childNodes = node.childNodes) != null && _node$childNodes.length) {
  25097. return getTextContent(node, trim);
  25098. } else if (trim) {
  25099. return str + node.textContent.trim().replace(/\s+/g, " ");
  25100. }
  25101. return str + node.textContent;
  25102. }, "");
  25103. }
  25104. function getTtmlStyles(region, style, styleElements) {
  25105. const ttsNs = "http://www.w3.org/ns/ttml#styling";
  25106. let regionStyle = null;
  25107. const styleAttributes = [
  25108. "displayAlign",
  25109. "textAlign",
  25110. "color",
  25111. "backgroundColor",
  25112. "fontSize",
  25113. "fontFamily"
  25114. ];
  25115. const regionStyleName = region != null && region.hasAttribute("style") ? region.getAttribute("style") : null;
  25116. if (regionStyleName && styleElements.hasOwnProperty(regionStyleName)) {
  25117. regionStyle = styleElements[regionStyleName];
  25118. }
  25119. return styleAttributes.reduce((styles, name) => {
  25120. const value = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name) || getAttributeNS(regionStyle, ttsNs, name);
  25121. if (value) {
  25122. styles[name] = value;
  25123. }
  25124. return styles;
  25125. }, {});
  25126. }
  25127. function getAttributeNS(element, ns, name) {
  25128. if (!element) {
  25129. return null;
  25130. }
  25131. return element.hasAttributeNS(ns, name) ? element.getAttributeNS(ns, name) : null;
  25132. }
  25133. function timestampParsingError(node) {
  25134. return new Error(`Could not parse ttml timestamp ${node}`);
  25135. }
  25136. function parseTtmlTime(timeAttributeValue, rateInfo) {
  25137. if (!timeAttributeValue) {
  25138. return null;
  25139. }
  25140. let seconds = parseTimeStamp(timeAttributeValue);
  25141. if (seconds === null) {
  25142. if (HMSF_REGEX.test(timeAttributeValue)) {
  25143. seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);
  25144. } else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {
  25145. seconds = parseTimeUnits(timeAttributeValue, rateInfo);
  25146. }
  25147. }
  25148. return seconds;
  25149. }
  25150. function parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) {
  25151. const m = HMSF_REGEX.exec(timeAttributeValue);
  25152. const frames = (m[4] | 0) + (m[5] | 0) / rateInfo.subFrameRate;
  25153. return (m[1] | 0) * 3600 + (m[2] | 0) * 60 + (m[3] | 0) + frames / rateInfo.frameRate;
  25154. }
  25155. function parseTimeUnits(timeAttributeValue, rateInfo) {
  25156. const m = TIME_UNIT_REGEX.exec(timeAttributeValue);
  25157. const value = Number(m[1]);
  25158. const unit = m[2];
  25159. switch (unit) {
  25160. case "h":
  25161. return value * 3600;
  25162. case "m":
  25163. return value * 60;
  25164. case "ms":
  25165. return value * 1e3;
  25166. case "f":
  25167. return value / rateInfo.frameRate;
  25168. case "t":
  25169. return value / rateInfo.tickRate;
  25170. }
  25171. return value;
  25172. }
  25173. var OutputFilter = class {
  25174. constructor(timelineController, trackName) {
  25175. this.timelineController = void 0;
  25176. this.cueRanges = [];
  25177. this.trackName = void 0;
  25178. this.startTime = null;
  25179. this.endTime = null;
  25180. this.screen = null;
  25181. this.timelineController = timelineController;
  25182. this.trackName = trackName;
  25183. }
  25184. dispatchCue() {
  25185. if (this.startTime === null) {
  25186. return;
  25187. }
  25188. this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);
  25189. this.startTime = null;
  25190. }
  25191. newCue(startTime, endTime, screen) {
  25192. if (this.startTime === null || this.startTime > startTime) {
  25193. this.startTime = startTime;
  25194. }
  25195. this.endTime = endTime;
  25196. this.screen = screen;
  25197. this.timelineController.createCaptionsTrack(this.trackName);
  25198. }
  25199. reset() {
  25200. this.cueRanges = [];
  25201. this.startTime = null;
  25202. }
  25203. };
  25204. var TimelineController = class {
  25205. constructor(hls) {
  25206. this.hls = void 0;
  25207. this.media = null;
  25208. this.config = void 0;
  25209. this.enabled = true;
  25210. this.Cues = void 0;
  25211. this.textTracks = [];
  25212. this.tracks = [];
  25213. this.initPTS = [];
  25214. this.unparsedVttFrags = [];
  25215. this.captionsTracks = {};
  25216. this.nonNativeCaptionsTracks = {};
  25217. this.cea608Parser1 = void 0;
  25218. this.cea608Parser2 = void 0;
  25219. this.lastCc = -1;
  25220. this.lastSn = -1;
  25221. this.lastPartIndex = -1;
  25222. this.prevCC = -1;
  25223. this.vttCCs = newVTTCCs();
  25224. this.captionsProperties = void 0;
  25225. this.hls = hls;
  25226. this.config = hls.config;
  25227. this.Cues = hls.config.cueHandler;
  25228. this.captionsProperties = {
  25229. textTrack1: {
  25230. label: this.config.captionsTextTrack1Label,
  25231. languageCode: this.config.captionsTextTrack1LanguageCode
  25232. },
  25233. textTrack2: {
  25234. label: this.config.captionsTextTrack2Label,
  25235. languageCode: this.config.captionsTextTrack2LanguageCode
  25236. },
  25237. textTrack3: {
  25238. label: this.config.captionsTextTrack3Label,
  25239. languageCode: this.config.captionsTextTrack3LanguageCode
  25240. },
  25241. textTrack4: {
  25242. label: this.config.captionsTextTrack4Label,
  25243. languageCode: this.config.captionsTextTrack4LanguageCode
  25244. }
  25245. };
  25246. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  25247. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  25248. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  25249. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  25250. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  25251. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  25252. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  25253. hls.on(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  25254. hls.on(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  25255. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  25256. hls.on(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  25257. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  25258. }
  25259. destroy() {
  25260. const {
  25261. hls
  25262. } = this;
  25263. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  25264. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  25265. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  25266. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  25267. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  25268. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  25269. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  25270. hls.off(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  25271. hls.off(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  25272. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  25273. hls.off(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  25274. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  25275. this.hls = this.config = this.media = null;
  25276. this.cea608Parser1 = this.cea608Parser2 = void 0;
  25277. }
  25278. initCea608Parsers() {
  25279. const channel1 = new OutputFilter(this, "textTrack1");
  25280. const channel2 = new OutputFilter(this, "textTrack2");
  25281. const channel3 = new OutputFilter(this, "textTrack3");
  25282. const channel4 = new OutputFilter(this, "textTrack4");
  25283. this.cea608Parser1 = new Cea608Parser(1, channel1, channel2);
  25284. this.cea608Parser2 = new Cea608Parser(3, channel3, channel4);
  25285. }
  25286. addCues(trackName, startTime, endTime, screen, cueRanges) {
  25287. let merged = false;
  25288. for (let i = cueRanges.length; i--; ) {
  25289. const cueRange = cueRanges[i];
  25290. const overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
  25291. if (overlap >= 0) {
  25292. cueRange[0] = Math.min(cueRange[0], startTime);
  25293. cueRange[1] = Math.max(cueRange[1], endTime);
  25294. merged = true;
  25295. if (overlap / (endTime - startTime) > 0.5) {
  25296. return;
  25297. }
  25298. }
  25299. }
  25300. if (!merged) {
  25301. cueRanges.push([startTime, endTime]);
  25302. }
  25303. if (this.config.renderTextTracksNatively) {
  25304. const track = this.captionsTracks[trackName];
  25305. this.Cues.newCue(track, startTime, endTime, screen);
  25306. } else {
  25307. const cues = this.Cues.newCue(null, startTime, endTime, screen);
  25308. this.hls.trigger(Events.CUES_PARSED, {
  25309. type: "captions",
  25310. cues,
  25311. track: trackName
  25312. });
  25313. }
  25314. }
  25315. onInitPtsFound(event, {
  25316. frag,
  25317. id,
  25318. initPTS,
  25319. timescale
  25320. }) {
  25321. const {
  25322. unparsedVttFrags
  25323. } = this;
  25324. if (id === PlaylistLevelType.MAIN) {
  25325. this.initPTS[frag.cc] = {
  25326. baseTime: initPTS,
  25327. timescale
  25328. };
  25329. }
  25330. if (unparsedVttFrags.length) {
  25331. this.unparsedVttFrags = [];
  25332. unparsedVttFrags.forEach((data) => {
  25333. if (this.initPTS[data.frag.cc]) {
  25334. this.onFragLoaded(Events.FRAG_LOADED, data);
  25335. } else {
  25336. this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  25337. success: false,
  25338. frag: data.frag,
  25339. error: new Error("Subtitle discontinuity domain does not match main")
  25340. });
  25341. }
  25342. });
  25343. }
  25344. }
  25345. getExistingTrack(label, language) {
  25346. const {
  25347. media
  25348. } = this;
  25349. if (media) {
  25350. for (let i = 0; i < media.textTracks.length; i++) {
  25351. const textTrack = media.textTracks[i];
  25352. if (canReuseVttTextTrack(textTrack, {
  25353. name: label,
  25354. lang: language,
  25355. characteristics: "transcribes-spoken-dialog,describes-music-and-sound"
  25356. })) {
  25357. return textTrack;
  25358. }
  25359. }
  25360. }
  25361. return null;
  25362. }
  25363. createCaptionsTrack(trackName) {
  25364. if (this.config.renderTextTracksNatively) {
  25365. this.createNativeTrack(trackName);
  25366. } else {
  25367. this.createNonNativeTrack(trackName);
  25368. }
  25369. }
  25370. createNativeTrack(trackName) {
  25371. if (this.captionsTracks[trackName]) {
  25372. return;
  25373. }
  25374. const {
  25375. captionsProperties,
  25376. captionsTracks,
  25377. media
  25378. } = this;
  25379. const {
  25380. label,
  25381. languageCode
  25382. } = captionsProperties[trackName];
  25383. const existingTrack = this.getExistingTrack(label, languageCode);
  25384. if (!existingTrack) {
  25385. const textTrack = this.createTextTrack("captions", label, languageCode);
  25386. if (textTrack) {
  25387. textTrack[trackName] = true;
  25388. captionsTracks[trackName] = textTrack;
  25389. }
  25390. } else {
  25391. captionsTracks[trackName] = existingTrack;
  25392. clearCurrentCues(captionsTracks[trackName]);
  25393. sendAddTrackEvent(captionsTracks[trackName], media);
  25394. }
  25395. }
  25396. createNonNativeTrack(trackName) {
  25397. if (this.nonNativeCaptionsTracks[trackName]) {
  25398. return;
  25399. }
  25400. const trackProperties = this.captionsProperties[trackName];
  25401. if (!trackProperties) {
  25402. return;
  25403. }
  25404. const label = trackProperties.label;
  25405. const track = {
  25406. _id: trackName,
  25407. label,
  25408. kind: "captions",
  25409. default: trackProperties.media ? !!trackProperties.media.default : false,
  25410. closedCaptions: trackProperties.media
  25411. };
  25412. this.nonNativeCaptionsTracks[trackName] = track;
  25413. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  25414. tracks: [track]
  25415. });
  25416. }
  25417. createTextTrack(kind, label, lang) {
  25418. const media = this.media;
  25419. if (!media) {
  25420. return;
  25421. }
  25422. return media.addTextTrack(kind, label, lang);
  25423. }
  25424. onMediaAttaching(event, data) {
  25425. this.media = data.media;
  25426. if (!data.mediaSource) {
  25427. this._cleanTracks();
  25428. }
  25429. }
  25430. onMediaDetaching(event, data) {
  25431. const transferringMedia = !!data.transferMedia;
  25432. this.media = null;
  25433. if (transferringMedia) {
  25434. return;
  25435. }
  25436. const {
  25437. captionsTracks
  25438. } = this;
  25439. Object.keys(captionsTracks).forEach((trackName) => {
  25440. clearCurrentCues(captionsTracks[trackName]);
  25441. delete captionsTracks[trackName];
  25442. });
  25443. this.nonNativeCaptionsTracks = {};
  25444. }
  25445. onManifestLoading() {
  25446. this.lastCc = -1;
  25447. this.lastSn = -1;
  25448. this.lastPartIndex = -1;
  25449. this.prevCC = -1;
  25450. this.vttCCs = newVTTCCs();
  25451. this._cleanTracks();
  25452. this.tracks = [];
  25453. this.captionsTracks = {};
  25454. this.nonNativeCaptionsTracks = {};
  25455. this.textTracks = [];
  25456. this.unparsedVttFrags = [];
  25457. this.initPTS = [];
  25458. if (this.cea608Parser1 && this.cea608Parser2) {
  25459. this.cea608Parser1.reset();
  25460. this.cea608Parser2.reset();
  25461. }
  25462. }
  25463. _cleanTracks() {
  25464. const {
  25465. media
  25466. } = this;
  25467. if (!media) {
  25468. return;
  25469. }
  25470. const textTracks = media.textTracks;
  25471. if (textTracks) {
  25472. for (let i = 0; i < textTracks.length; i++) {
  25473. clearCurrentCues(textTracks[i]);
  25474. }
  25475. }
  25476. }
  25477. onSubtitleTracksUpdated(event, data) {
  25478. const tracks = data.subtitleTracks || [];
  25479. const hasIMSC1 = tracks.some((track) => track.textCodec === IMSC1_CODEC);
  25480. if (this.config.enableWebVTT || hasIMSC1 && this.config.enableIMSC1) {
  25481. const listIsIdentical = subtitleOptionsIdentical(this.tracks, tracks);
  25482. if (listIsIdentical) {
  25483. this.tracks = tracks;
  25484. return;
  25485. }
  25486. this.textTracks = [];
  25487. this.tracks = tracks;
  25488. if (this.config.renderTextTracksNatively) {
  25489. const media = this.media;
  25490. const inUseTracks = media ? filterSubtitleTracks(media.textTracks) : null;
  25491. this.tracks.forEach((track, index) => {
  25492. let textTrack;
  25493. if (inUseTracks) {
  25494. let inUseTrack = null;
  25495. for (let i = 0; i < inUseTracks.length; i++) {
  25496. if (inUseTracks[i] && canReuseVttTextTrack(inUseTracks[i], track)) {
  25497. inUseTrack = inUseTracks[i];
  25498. inUseTracks[i] = null;
  25499. break;
  25500. }
  25501. }
  25502. if (inUseTrack) {
  25503. textTrack = inUseTrack;
  25504. }
  25505. }
  25506. if (textTrack) {
  25507. clearCurrentCues(textTrack);
  25508. } else {
  25509. const textTrackKind = captionsOrSubtitlesFromCharacteristics(track);
  25510. textTrack = this.createTextTrack(textTrackKind, track.name, track.lang);
  25511. if (textTrack) {
  25512. textTrack.mode = "disabled";
  25513. }
  25514. }
  25515. if (textTrack) {
  25516. this.textTracks.push(textTrack);
  25517. }
  25518. });
  25519. if (inUseTracks != null && inUseTracks.length) {
  25520. const unusedTextTracks = inUseTracks.filter((t) => t !== null).map((t) => t.label);
  25521. if (unusedTextTracks.length) {
  25522. this.hls.logger.warn(`Media element contains unused subtitle tracks: ${unusedTextTracks.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`);
  25523. }
  25524. }
  25525. } else if (this.tracks.length) {
  25526. const tracksList = this.tracks.map((track) => {
  25527. return {
  25528. label: track.name,
  25529. kind: track.type.toLowerCase(),
  25530. default: track.default,
  25531. subtitleTrack: track
  25532. };
  25533. });
  25534. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  25535. tracks: tracksList
  25536. });
  25537. }
  25538. }
  25539. }
  25540. onManifestLoaded(event, data) {
  25541. if (this.config.enableCEA708Captions && data.captions) {
  25542. data.captions.forEach((captionsTrack) => {
  25543. const instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);
  25544. if (!instreamIdMatch) {
  25545. return;
  25546. }
  25547. const trackName = `textTrack${instreamIdMatch[1]}`;
  25548. const trackProperties = this.captionsProperties[trackName];
  25549. if (!trackProperties) {
  25550. return;
  25551. }
  25552. trackProperties.label = captionsTrack.name;
  25553. if (captionsTrack.lang) {
  25554. trackProperties.languageCode = captionsTrack.lang;
  25555. }
  25556. trackProperties.media = captionsTrack;
  25557. });
  25558. }
  25559. }
  25560. closedCaptionsForLevel(frag) {
  25561. const level = this.hls.levels[frag.level];
  25562. return level == null ? void 0 : level.attrs["CLOSED-CAPTIONS"];
  25563. }
  25564. onFragLoading(event, data) {
  25565. if (this.enabled && data.frag.type === PlaylistLevelType.MAIN) {
  25566. var _data$part$index, _data$part;
  25567. const {
  25568. cea608Parser1,
  25569. cea608Parser2,
  25570. lastSn
  25571. } = this;
  25572. const {
  25573. cc,
  25574. sn
  25575. } = data.frag;
  25576. const partIndex = (_data$part$index = (_data$part = data.part) == null ? void 0 : _data$part.index) != null ? _data$part$index : -1;
  25577. if (cea608Parser1 && cea608Parser2) {
  25578. if (sn !== lastSn + 1 || sn === lastSn && partIndex !== this.lastPartIndex + 1 || cc !== this.lastCc) {
  25579. cea608Parser1.reset();
  25580. cea608Parser2.reset();
  25581. }
  25582. }
  25583. this.lastCc = cc;
  25584. this.lastSn = sn;
  25585. this.lastPartIndex = partIndex;
  25586. }
  25587. }
  25588. onFragLoaded(event, data) {
  25589. const {
  25590. frag,
  25591. payload
  25592. } = data;
  25593. if (frag.type === PlaylistLevelType.SUBTITLE) {
  25594. if (payload.byteLength) {
  25595. const decryptData = frag.decryptdata;
  25596. const decrypted = "stats" in data;
  25597. if (decryptData == null || !decryptData.encrypted || decrypted) {
  25598. const trackPlaylistMedia = this.tracks[frag.level];
  25599. const vttCCs = this.vttCCs;
  25600. if (!vttCCs[frag.cc]) {
  25601. vttCCs[frag.cc] = {
  25602. start: frag.start,
  25603. prevCC: this.prevCC,
  25604. new: true
  25605. };
  25606. this.prevCC = frag.cc;
  25607. }
  25608. if (trackPlaylistMedia && trackPlaylistMedia.textCodec === IMSC1_CODEC) {
  25609. this._parseIMSC1(frag, payload);
  25610. } else {
  25611. this._parseVTTs(data);
  25612. }
  25613. }
  25614. } else {
  25615. this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  25616. success: false,
  25617. frag,
  25618. error: new Error("Empty subtitle payload")
  25619. });
  25620. }
  25621. }
  25622. }
  25623. _parseIMSC1(frag, payload) {
  25624. const hls = this.hls;
  25625. parseIMSC1(payload, this.initPTS[frag.cc], (cues) => {
  25626. this._appendCues(cues, frag.level);
  25627. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  25628. success: true,
  25629. frag
  25630. });
  25631. }, (error) => {
  25632. hls.logger.log(`Failed to parse IMSC1: ${error}`);
  25633. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  25634. success: false,
  25635. frag,
  25636. error
  25637. });
  25638. });
  25639. }
  25640. _parseVTTs(data) {
  25641. var _frag$initSegment;
  25642. const {
  25643. frag,
  25644. payload
  25645. } = data;
  25646. const {
  25647. initPTS,
  25648. unparsedVttFrags
  25649. } = this;
  25650. const maxAvCC = initPTS.length - 1;
  25651. if (!initPTS[frag.cc] && maxAvCC === -1) {
  25652. unparsedVttFrags.push(data);
  25653. return;
  25654. }
  25655. const hls = this.hls;
  25656. const payloadWebVTT = (_frag$initSegment = frag.initSegment) != null && _frag$initSegment.data ? appendUint8Array(frag.initSegment.data, new Uint8Array(payload)).buffer : payload;
  25657. parseWebVTT(payloadWebVTT, this.initPTS[frag.cc], this.vttCCs, frag.cc, frag.start, (cues) => {
  25658. this._appendCues(cues, frag.level);
  25659. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  25660. success: true,
  25661. frag
  25662. });
  25663. }, (error) => {
  25664. const missingInitPTS = error.message === "Missing initPTS for VTT MPEGTS";
  25665. if (missingInitPTS) {
  25666. unparsedVttFrags.push(data);
  25667. } else {
  25668. this._fallbackToIMSC1(frag, payload);
  25669. }
  25670. hls.logger.log(`Failed to parse VTT cue: ${error}`);
  25671. if (missingInitPTS && maxAvCC > frag.cc) {
  25672. return;
  25673. }
  25674. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  25675. success: false,
  25676. frag,
  25677. error
  25678. });
  25679. });
  25680. }
  25681. _fallbackToIMSC1(frag, payload) {
  25682. const trackPlaylistMedia = this.tracks[frag.level];
  25683. if (!trackPlaylistMedia.textCodec) {
  25684. parseIMSC1(payload, this.initPTS[frag.cc], () => {
  25685. trackPlaylistMedia.textCodec = IMSC1_CODEC;
  25686. this._parseIMSC1(frag, payload);
  25687. }, () => {
  25688. trackPlaylistMedia.textCodec = "wvtt";
  25689. });
  25690. }
  25691. }
  25692. _appendCues(cues, fragLevel) {
  25693. const hls = this.hls;
  25694. if (this.config.renderTextTracksNatively) {
  25695. const textTrack = this.textTracks[fragLevel];
  25696. if (!textTrack || textTrack.mode === "disabled") {
  25697. return;
  25698. }
  25699. cues.forEach((cue) => addCueToTrack(textTrack, cue));
  25700. } else {
  25701. const currentTrack = this.tracks[fragLevel];
  25702. if (!currentTrack) {
  25703. return;
  25704. }
  25705. const track = currentTrack.default ? "default" : "subtitles" + fragLevel;
  25706. hls.trigger(Events.CUES_PARSED, {
  25707. type: "subtitles",
  25708. cues,
  25709. track
  25710. });
  25711. }
  25712. }
  25713. onFragDecrypted(event, data) {
  25714. const {
  25715. frag
  25716. } = data;
  25717. if (frag.type === PlaylistLevelType.SUBTITLE) {
  25718. this.onFragLoaded(Events.FRAG_LOADED, data);
  25719. }
  25720. }
  25721. onSubtitleTracksCleared() {
  25722. this.tracks = [];
  25723. this.captionsTracks = {};
  25724. }
  25725. onFragParsingUserdata(event, data) {
  25726. if (!this.enabled || !this.config.enableCEA708Captions) {
  25727. return;
  25728. }
  25729. const {
  25730. frag,
  25731. samples
  25732. } = data;
  25733. if (frag.type === PlaylistLevelType.MAIN && this.closedCaptionsForLevel(frag) === "NONE") {
  25734. return;
  25735. }
  25736. for (let i = 0; i < samples.length; i++) {
  25737. const ccBytes = samples[i].bytes;
  25738. if (ccBytes) {
  25739. if (!this.cea608Parser1) {
  25740. this.initCea608Parsers();
  25741. }
  25742. const ccdatas = this.extractCea608Data(ccBytes);
  25743. this.cea608Parser1.addData(samples[i].pts, ccdatas[0]);
  25744. this.cea608Parser2.addData(samples[i].pts, ccdatas[1]);
  25745. }
  25746. }
  25747. }
  25748. onBufferFlushing(event, {
  25749. startOffset,
  25750. endOffset,
  25751. endOffsetSubtitles,
  25752. type
  25753. }) {
  25754. const {
  25755. media
  25756. } = this;
  25757. if (!media || media.currentTime < endOffset) {
  25758. return;
  25759. }
  25760. if (!type || type === "video") {
  25761. const {
  25762. captionsTracks
  25763. } = this;
  25764. Object.keys(captionsTracks).forEach((trackName) => removeCuesInRange(captionsTracks[trackName], startOffset, endOffset));
  25765. }
  25766. if (this.config.renderTextTracksNatively) {
  25767. if (startOffset === 0 && endOffsetSubtitles !== void 0) {
  25768. const {
  25769. textTracks
  25770. } = this;
  25771. Object.keys(textTracks).forEach((trackName) => removeCuesInRange(textTracks[trackName], startOffset, endOffsetSubtitles));
  25772. }
  25773. }
  25774. }
  25775. extractCea608Data(byteArray) {
  25776. const actualCCBytes = [[], []];
  25777. const count = byteArray[0] & 31;
  25778. let position = 2;
  25779. for (let j = 0; j < count; j++) {
  25780. const tmpByte = byteArray[position++];
  25781. const ccbyte1 = 127 & byteArray[position++];
  25782. const ccbyte2 = 127 & byteArray[position++];
  25783. if (ccbyte1 === 0 && ccbyte2 === 0) {
  25784. continue;
  25785. }
  25786. const ccValid = (4 & tmpByte) !== 0;
  25787. if (ccValid) {
  25788. const ccType = 3 & tmpByte;
  25789. if (ccType === 0 || ccType === 1) {
  25790. actualCCBytes[ccType].push(ccbyte1);
  25791. actualCCBytes[ccType].push(ccbyte2);
  25792. }
  25793. }
  25794. }
  25795. return actualCCBytes;
  25796. }
  25797. };
  25798. function captionsOrSubtitlesFromCharacteristics(track) {
  25799. if (track.characteristics) {
  25800. if (/transcribes-spoken-dialog/gi.test(track.characteristics) && /describes-music-and-sound/gi.test(track.characteristics)) {
  25801. return "captions";
  25802. }
  25803. }
  25804. return "subtitles";
  25805. }
  25806. function canReuseVttTextTrack(inUseTrack, manifestTrack) {
  25807. return !!inUseTrack && inUseTrack.kind === captionsOrSubtitlesFromCharacteristics(manifestTrack) && subtitleTrackMatchesTextTrack(manifestTrack, inUseTrack);
  25808. }
  25809. function intersection(x1, x2, y1, y2) {
  25810. return Math.min(x2, y2) - Math.max(x1, y1);
  25811. }
  25812. function newVTTCCs() {
  25813. return {
  25814. ccOffset: 0,
  25815. presentationOffset: 0,
  25816. 0: {
  25817. start: 0,
  25818. prevCC: -1,
  25819. new: true
  25820. }
  25821. };
  25822. }
  25823. var WHITESPACE_CHAR = /\s/;
  25824. var Cues = {
  25825. newCue(track, startTime, endTime, captionScreen) {
  25826. const result = [];
  25827. let row;
  25828. let cue;
  25829. let indenting;
  25830. let indent;
  25831. let text;
  25832. const Cue = self.VTTCue || self.TextTrackCue;
  25833. for (let r = 0; r < captionScreen.rows.length; r++) {
  25834. row = captionScreen.rows[r];
  25835. indenting = true;
  25836. indent = 0;
  25837. text = "";
  25838. if (!row.isEmpty()) {
  25839. var _track$cues;
  25840. for (let c = 0; c < row.chars.length; c++) {
  25841. if (WHITESPACE_CHAR.test(row.chars[c].uchar) && indenting) {
  25842. indent++;
  25843. } else {
  25844. text += row.chars[c].uchar;
  25845. indenting = false;
  25846. }
  25847. }
  25848. row.cueStartTime = startTime;
  25849. if (startTime === endTime) {
  25850. endTime += 1e-4;
  25851. }
  25852. if (indent >= 16) {
  25853. indent--;
  25854. } else {
  25855. indent++;
  25856. }
  25857. const cueText = fixLineBreaks(text.trim());
  25858. const id = generateCueId(startTime, endTime, cueText);
  25859. if (!(track != null && (_track$cues = track.cues) != null && _track$cues.getCueById(id))) {
  25860. cue = new Cue(startTime, endTime, cueText);
  25861. cue.id = id;
  25862. cue.line = r + 1;
  25863. cue.align = "left";
  25864. cue.position = 10 + Math.min(80, Math.floor(indent * 8 / 32) * 10);
  25865. result.push(cue);
  25866. }
  25867. }
  25868. }
  25869. if (track && result.length) {
  25870. result.sort((cueA, cueB) => {
  25871. if (cueA.line === "auto" || cueB.line === "auto") {
  25872. return 0;
  25873. }
  25874. if (cueA.line > 8 && cueB.line > 8) {
  25875. return cueB.line - cueA.line;
  25876. }
  25877. return cueA.line - cueB.line;
  25878. });
  25879. result.forEach((cue2) => addCueToTrack(track, cue2));
  25880. }
  25881. return result;
  25882. }
  25883. };
  25884. function fetchSupported() {
  25885. if (self.fetch && self.AbortController && self.ReadableStream && self.Request) {
  25886. try {
  25887. new self.ReadableStream({});
  25888. return true;
  25889. } catch (e) {
  25890. }
  25891. }
  25892. return false;
  25893. }
  25894. var BYTERANGE = /(\d+)-(\d+)\/(\d+)/;
  25895. var FetchLoader = class {
  25896. constructor(config) {
  25897. this.fetchSetup = void 0;
  25898. this.requestTimeout = void 0;
  25899. this.request = null;
  25900. this.response = null;
  25901. this.controller = void 0;
  25902. this.context = null;
  25903. this.config = null;
  25904. this.callbacks = null;
  25905. this.stats = void 0;
  25906. this.loader = null;
  25907. this.fetchSetup = config.fetchSetup || getRequest;
  25908. this.controller = new self.AbortController();
  25909. this.stats = new LoadStats();
  25910. }
  25911. destroy() {
  25912. this.loader = this.callbacks = this.context = this.config = this.request = null;
  25913. this.abortInternal();
  25914. this.response = null;
  25915. this.fetchSetup = this.controller = this.stats = null;
  25916. }
  25917. abortInternal() {
  25918. if (this.controller && !this.stats.loading.end) {
  25919. this.stats.aborted = true;
  25920. this.controller.abort();
  25921. }
  25922. }
  25923. abort() {
  25924. var _this$callbacks;
  25925. this.abortInternal();
  25926. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  25927. this.callbacks.onAbort(this.stats, this.context, this.response);
  25928. }
  25929. }
  25930. load(context, config, callbacks) {
  25931. const stats = this.stats;
  25932. if (stats.loading.start) {
  25933. throw new Error("Loader can only be used once.");
  25934. }
  25935. stats.loading.start = self.performance.now();
  25936. const initParams = getRequestParameters(context, this.controller.signal);
  25937. const isArrayBuffer = context.responseType === "arraybuffer";
  25938. const LENGTH = isArrayBuffer ? "byteLength" : "length";
  25939. const {
  25940. maxTimeToFirstByteMs,
  25941. maxLoadTimeMs
  25942. } = config.loadPolicy;
  25943. this.context = context;
  25944. this.config = config;
  25945. this.callbacks = callbacks;
  25946. this.request = this.fetchSetup(context, initParams);
  25947. self.clearTimeout(this.requestTimeout);
  25948. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  25949. this.requestTimeout = self.setTimeout(() => {
  25950. if (this.callbacks) {
  25951. this.abortInternal();
  25952. this.callbacks.onTimeout(stats, context, this.response);
  25953. }
  25954. }, config.timeout);
  25955. const fetchPromise = isPromise(this.request) ? this.request.then(self.fetch) : self.fetch(this.request);
  25956. fetchPromise.then((response) => {
  25957. var _this$callbacks2;
  25958. this.response = this.loader = response;
  25959. const first = Math.max(self.performance.now(), stats.loading.start);
  25960. self.clearTimeout(this.requestTimeout);
  25961. config.timeout = maxLoadTimeMs;
  25962. this.requestTimeout = self.setTimeout(() => {
  25963. if (this.callbacks) {
  25964. this.abortInternal();
  25965. this.callbacks.onTimeout(stats, context, this.response);
  25966. }
  25967. }, maxLoadTimeMs - (first - stats.loading.start));
  25968. if (!response.ok) {
  25969. const {
  25970. status: status2,
  25971. statusText
  25972. } = response;
  25973. throw new FetchError(statusText || "fetch, bad network response", status2, response);
  25974. }
  25975. stats.loading.first = first;
  25976. stats.total = getContentLength(response.headers) || stats.total;
  25977. const onProgress = (_this$callbacks2 = this.callbacks) == null ? void 0 : _this$callbacks2.onProgress;
  25978. if (onProgress && isFiniteNumber(config.highWaterMark)) {
  25979. return this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
  25980. }
  25981. if (isArrayBuffer) {
  25982. return response.arrayBuffer();
  25983. }
  25984. if (context.responseType === "json") {
  25985. return response.json();
  25986. }
  25987. return response.text();
  25988. }).then((responseData) => {
  25989. var _this$callbacks3, _this$callbacks4;
  25990. const response = this.response;
  25991. if (!response) {
  25992. throw new Error("loader destroyed");
  25993. }
  25994. self.clearTimeout(this.requestTimeout);
  25995. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  25996. const total = responseData[LENGTH];
  25997. if (total) {
  25998. stats.loaded = stats.total = total;
  25999. }
  26000. const loaderResponse = {
  26001. url: response.url,
  26002. data: responseData,
  26003. code: response.status
  26004. };
  26005. const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  26006. if (onProgress && !isFiniteNumber(config.highWaterMark)) {
  26007. onProgress(stats, context, responseData, response);
  26008. }
  26009. (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(loaderResponse, stats, context, response);
  26010. }).catch((error) => {
  26011. var _this$callbacks5;
  26012. self.clearTimeout(this.requestTimeout);
  26013. if (stats.aborted) {
  26014. return;
  26015. }
  26016. const code = !error ? 0 : error.code || 0;
  26017. const text = !error ? null : error.message;
  26018. (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({
  26019. code,
  26020. text
  26021. }, context, error ? error.details : null, stats);
  26022. });
  26023. }
  26024. getCacheAge() {
  26025. let result = null;
  26026. if (this.response) {
  26027. const ageHeader = this.response.headers.get("age");
  26028. result = ageHeader ? parseFloat(ageHeader) : null;
  26029. }
  26030. return result;
  26031. }
  26032. getResponseHeader(name) {
  26033. return this.response ? this.response.headers.get(name) : null;
  26034. }
  26035. loadProgressively(response, stats, context, highWaterMark = 0, onProgress) {
  26036. const chunkCache = new ChunkCache();
  26037. const reader = response.body.getReader();
  26038. const pump = () => {
  26039. return reader.read().then((data) => {
  26040. if (data.done) {
  26041. if (chunkCache.dataLength) {
  26042. onProgress(stats, context, chunkCache.flush().buffer, response);
  26043. }
  26044. return Promise.resolve(new ArrayBuffer(0));
  26045. }
  26046. const chunk = data.value;
  26047. const len = chunk.length;
  26048. stats.loaded += len;
  26049. if (len < highWaterMark || chunkCache.dataLength) {
  26050. chunkCache.push(chunk);
  26051. if (chunkCache.dataLength >= highWaterMark) {
  26052. onProgress(stats, context, chunkCache.flush().buffer, response);
  26053. }
  26054. } else {
  26055. onProgress(stats, context, chunk.buffer, response);
  26056. }
  26057. return pump();
  26058. }).catch(() => {
  26059. return Promise.reject();
  26060. });
  26061. };
  26062. return pump();
  26063. }
  26064. };
  26065. function getRequestParameters(context, signal) {
  26066. const initParams = {
  26067. method: "GET",
  26068. mode: "cors",
  26069. credentials: "same-origin",
  26070. signal,
  26071. headers: new self.Headers(_extends({}, context.headers))
  26072. };
  26073. if (context.rangeEnd) {
  26074. initParams.headers.set("Range", "bytes=" + context.rangeStart + "-" + String(context.rangeEnd - 1));
  26075. }
  26076. return initParams;
  26077. }
  26078. function getByteRangeLength(byteRangeHeader) {
  26079. const result = BYTERANGE.exec(byteRangeHeader);
  26080. if (result) {
  26081. return parseInt(result[2]) - parseInt(result[1]) + 1;
  26082. }
  26083. }
  26084. function getContentLength(headers) {
  26085. const contentRange = headers.get("Content-Range");
  26086. if (contentRange) {
  26087. const byteRangeLength = getByteRangeLength(contentRange);
  26088. if (isFiniteNumber(byteRangeLength)) {
  26089. return byteRangeLength;
  26090. }
  26091. }
  26092. const contentLength = headers.get("Content-Length");
  26093. if (contentLength) {
  26094. return parseInt(contentLength);
  26095. }
  26096. }
  26097. function getRequest(context, initParams) {
  26098. return new self.Request(context.url, initParams);
  26099. }
  26100. var FetchError = class extends Error {
  26101. constructor(message, code, details) {
  26102. super(message);
  26103. this.code = void 0;
  26104. this.details = void 0;
  26105. this.code = code;
  26106. this.details = details;
  26107. }
  26108. };
  26109. var AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/im;
  26110. var XhrLoader = class {
  26111. constructor(config) {
  26112. this.xhrSetup = void 0;
  26113. this.requestTimeout = void 0;
  26114. this.retryTimeout = void 0;
  26115. this.retryDelay = void 0;
  26116. this.config = null;
  26117. this.callbacks = null;
  26118. this.context = null;
  26119. this.loader = null;
  26120. this.stats = void 0;
  26121. this.xhrSetup = config ? config.xhrSetup || null : null;
  26122. this.stats = new LoadStats();
  26123. this.retryDelay = 0;
  26124. }
  26125. destroy() {
  26126. this.callbacks = null;
  26127. this.abortInternal();
  26128. this.loader = null;
  26129. this.config = null;
  26130. this.context = null;
  26131. this.xhrSetup = null;
  26132. }
  26133. abortInternal() {
  26134. const loader = this.loader;
  26135. self.clearTimeout(this.requestTimeout);
  26136. self.clearTimeout(this.retryTimeout);
  26137. if (loader) {
  26138. loader.onreadystatechange = null;
  26139. loader.onprogress = null;
  26140. if (loader.readyState !== 4) {
  26141. this.stats.aborted = true;
  26142. loader.abort();
  26143. }
  26144. }
  26145. }
  26146. abort() {
  26147. var _this$callbacks;
  26148. this.abortInternal();
  26149. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  26150. this.callbacks.onAbort(this.stats, this.context, this.loader);
  26151. }
  26152. }
  26153. load(context, config, callbacks) {
  26154. if (this.stats.loading.start) {
  26155. throw new Error("Loader can only be used once.");
  26156. }
  26157. this.stats.loading.start = self.performance.now();
  26158. this.context = context;
  26159. this.config = config;
  26160. this.callbacks = callbacks;
  26161. this.loadInternal();
  26162. }
  26163. loadInternal() {
  26164. const {
  26165. config,
  26166. context
  26167. } = this;
  26168. if (!config || !context) {
  26169. return;
  26170. }
  26171. const xhr = this.loader = new self.XMLHttpRequest();
  26172. const stats = this.stats;
  26173. stats.loading.first = 0;
  26174. stats.loaded = 0;
  26175. stats.aborted = false;
  26176. const xhrSetup = this.xhrSetup;
  26177. if (xhrSetup) {
  26178. Promise.resolve().then(() => {
  26179. if (this.loader !== xhr || this.stats.aborted)
  26180. return;
  26181. return xhrSetup(xhr, context.url);
  26182. }).catch((error) => {
  26183. if (this.loader !== xhr || this.stats.aborted)
  26184. return;
  26185. xhr.open("GET", context.url, true);
  26186. return xhrSetup(xhr, context.url);
  26187. }).then(() => {
  26188. if (this.loader !== xhr || this.stats.aborted)
  26189. return;
  26190. this.openAndSendXhr(xhr, context, config);
  26191. }).catch((error) => {
  26192. var _this$callbacks2;
  26193. (_this$callbacks2 = this.callbacks) == null ? void 0 : _this$callbacks2.onError({
  26194. code: xhr.status,
  26195. text: error.message
  26196. }, context, xhr, stats);
  26197. return;
  26198. });
  26199. } else {
  26200. this.openAndSendXhr(xhr, context, config);
  26201. }
  26202. }
  26203. openAndSendXhr(xhr, context, config) {
  26204. if (!xhr.readyState) {
  26205. xhr.open("GET", context.url, true);
  26206. }
  26207. const headers = context.headers;
  26208. const {
  26209. maxTimeToFirstByteMs,
  26210. maxLoadTimeMs
  26211. } = config.loadPolicy;
  26212. if (headers) {
  26213. for (const header in headers) {
  26214. xhr.setRequestHeader(header, headers[header]);
  26215. }
  26216. }
  26217. if (context.rangeEnd) {
  26218. xhr.setRequestHeader("Range", "bytes=" + context.rangeStart + "-" + (context.rangeEnd - 1));
  26219. }
  26220. xhr.onreadystatechange = this.readystatechange.bind(this);
  26221. xhr.onprogress = this.loadprogress.bind(this);
  26222. xhr.responseType = context.responseType;
  26223. self.clearTimeout(this.requestTimeout);
  26224. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  26225. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
  26226. xhr.send();
  26227. }
  26228. readystatechange() {
  26229. const {
  26230. context,
  26231. loader: xhr,
  26232. stats
  26233. } = this;
  26234. if (!context || !xhr) {
  26235. return;
  26236. }
  26237. const readyState = xhr.readyState;
  26238. const config = this.config;
  26239. if (stats.aborted) {
  26240. return;
  26241. }
  26242. if (readyState >= 2) {
  26243. if (stats.loading.first === 0) {
  26244. stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
  26245. if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {
  26246. self.clearTimeout(this.requestTimeout);
  26247. config.timeout = config.loadPolicy.maxLoadTimeMs;
  26248. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.loadPolicy.maxLoadTimeMs - (stats.loading.first - stats.loading.start));
  26249. }
  26250. }
  26251. if (readyState === 4) {
  26252. self.clearTimeout(this.requestTimeout);
  26253. xhr.onreadystatechange = null;
  26254. xhr.onprogress = null;
  26255. const status2 = xhr.status;
  26256. const useResponseText = xhr.responseType === "text" ? xhr.responseText : null;
  26257. if (status2 >= 200 && status2 < 300) {
  26258. const data = useResponseText != null ? useResponseText : xhr.response;
  26259. if (data != null) {
  26260. var _this$callbacks3, _this$callbacks4;
  26261. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  26262. const len = xhr.responseType === "arraybuffer" ? data.byteLength : data.length;
  26263. stats.loaded = stats.total = len;
  26264. stats.bwEstimate = stats.total * 8e3 / (stats.loading.end - stats.loading.first);
  26265. const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  26266. if (onProgress) {
  26267. onProgress(stats, context, data, xhr);
  26268. }
  26269. const _response = {
  26270. url: xhr.responseURL,
  26271. data,
  26272. code: status2
  26273. };
  26274. (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(_response, stats, context, xhr);
  26275. return;
  26276. }
  26277. }
  26278. const retryConfig = config.loadPolicy.errorRetry;
  26279. const retryCount = stats.retry;
  26280. const response = {
  26281. url: context.url,
  26282. data: void 0,
  26283. code: status2
  26284. };
  26285. if (shouldRetry(retryConfig, retryCount, false, response)) {
  26286. this.retry(retryConfig);
  26287. } else {
  26288. var _this$callbacks5;
  26289. logger.error(`${status2} while loading ${context.url}`);
  26290. (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({
  26291. code: status2,
  26292. text: xhr.statusText
  26293. }, context, xhr, stats);
  26294. }
  26295. }
  26296. }
  26297. }
  26298. loadtimeout() {
  26299. if (!this.config)
  26300. return;
  26301. const retryConfig = this.config.loadPolicy.timeoutRetry;
  26302. const retryCount = this.stats.retry;
  26303. if (shouldRetry(retryConfig, retryCount, true)) {
  26304. this.retry(retryConfig);
  26305. } else {
  26306. var _this$context;
  26307. logger.warn(`timeout while loading ${(_this$context = this.context) == null ? void 0 : _this$context.url}`);
  26308. const callbacks = this.callbacks;
  26309. if (callbacks) {
  26310. this.abortInternal();
  26311. callbacks.onTimeout(this.stats, this.context, this.loader);
  26312. }
  26313. }
  26314. }
  26315. retry(retryConfig) {
  26316. const {
  26317. context,
  26318. stats
  26319. } = this;
  26320. this.retryDelay = getRetryDelay(retryConfig, stats.retry);
  26321. stats.retry++;
  26322. logger.warn(`${status ? "HTTP Status " + status : "Timeout"} while loading ${context == null ? void 0 : context.url}, retrying ${stats.retry}/${retryConfig.maxNumRetry} in ${this.retryDelay}ms`);
  26323. this.abortInternal();
  26324. this.loader = null;
  26325. self.clearTimeout(this.retryTimeout);
  26326. this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  26327. }
  26328. loadprogress(event) {
  26329. const stats = this.stats;
  26330. stats.loaded = event.loaded;
  26331. if (event.lengthComputable) {
  26332. stats.total = event.total;
  26333. }
  26334. }
  26335. getCacheAge() {
  26336. let result = null;
  26337. if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
  26338. const ageHeader = this.loader.getResponseHeader("age");
  26339. result = ageHeader ? parseFloat(ageHeader) : null;
  26340. }
  26341. return result;
  26342. }
  26343. getResponseHeader(name) {
  26344. if (this.loader && new RegExp(`^${name}:\\s*[\\d.]+\\s*$`, "im").test(this.loader.getAllResponseHeaders())) {
  26345. return this.loader.getResponseHeader(name);
  26346. }
  26347. return null;
  26348. }
  26349. };
  26350. var defaultLoadPolicy = {
  26351. maxTimeToFirstByteMs: 8e3,
  26352. maxLoadTimeMs: 2e4,
  26353. timeoutRetry: null,
  26354. errorRetry: null
  26355. };
  26356. var hlsDefaultConfig = _objectSpread2(_objectSpread2({
  26357. autoStartLoad: true,
  26358. startPosition: -1,
  26359. defaultAudioCodec: void 0,
  26360. debug: false,
  26361. capLevelOnFPSDrop: false,
  26362. capLevelToPlayerSize: false,
  26363. ignoreDevicePixelRatio: false,
  26364. maxDevicePixelRatio: Number.POSITIVE_INFINITY,
  26365. preferManagedMediaSource: true,
  26366. initialLiveManifestSize: 1,
  26367. maxBufferLength: 30,
  26368. backBufferLength: Infinity,
  26369. frontBufferFlushThreshold: Infinity,
  26370. startOnSegmentBoundary: false,
  26371. maxBufferSize: 60 * 1e3 * 1e3,
  26372. maxFragLookUpTolerance: 0.25,
  26373. maxBufferHole: 0.1,
  26374. detectStallWithCurrentTimeMs: 1250,
  26375. highBufferWatchdogPeriod: 2,
  26376. nudgeOffset: 0.1,
  26377. nudgeMaxRetry: 3,
  26378. nudgeOnVideoHole: true,
  26379. liveSyncMode: "edge",
  26380. liveSyncDurationCount: 3,
  26381. liveSyncOnStallIncrease: 1,
  26382. liveMaxLatencyDurationCount: Infinity,
  26383. liveSyncDuration: void 0,
  26384. liveMaxLatencyDuration: void 0,
  26385. maxLiveSyncPlaybackRate: 1,
  26386. liveDurationInfinity: false,
  26387. liveBackBufferLength: null,
  26388. maxMaxBufferLength: 600,
  26389. enableWorker: true,
  26390. workerPath: null,
  26391. enableSoftwareAES: true,
  26392. startLevel: void 0,
  26393. startFragPrefetch: false,
  26394. fpsDroppedMonitoringPeriod: 5e3,
  26395. fpsDroppedMonitoringThreshold: 0.2,
  26396. appendErrorMaxRetry: 3,
  26397. ignorePlaylistParsingErrors: false,
  26398. loader: XhrLoader,
  26399. fLoader: void 0,
  26400. pLoader: void 0,
  26401. xhrSetup: void 0,
  26402. licenseXhrSetup: void 0,
  26403. licenseResponseCallback: void 0,
  26404. abrController: AbrController,
  26405. bufferController: BufferController,
  26406. capLevelController: CapLevelController,
  26407. errorController: ErrorController,
  26408. fpsController: FPSController,
  26409. stretchShortVideoTrack: false,
  26410. maxAudioFramesDrift: 1,
  26411. forceKeyFrameOnDiscontinuity: true,
  26412. abrEwmaFastLive: 3,
  26413. abrEwmaSlowLive: 9,
  26414. abrEwmaFastVoD: 3,
  26415. abrEwmaSlowVoD: 9,
  26416. abrEwmaDefaultEstimate: 5e5,
  26417. abrEwmaDefaultEstimateMax: 5e6,
  26418. abrBandWidthFactor: 0.95,
  26419. abrBandWidthUpFactor: 0.7,
  26420. abrMaxWithRealBitrate: false,
  26421. maxStarvationDelay: 4,
  26422. maxLoadingDelay: 4,
  26423. minAutoBitrate: 0,
  26424. emeEnabled: false,
  26425. widevineLicenseUrl: void 0,
  26426. drmSystems: {},
  26427. drmSystemOptions: {},
  26428. requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess,
  26429. requireKeySystemAccessOnStart: false,
  26430. testBandwidth: true,
  26431. progressive: false,
  26432. lowLatencyMode: true,
  26433. cmcd: void 0,
  26434. enableDateRangeMetadataCues: true,
  26435. enableEmsgMetadataCues: true,
  26436. enableEmsgKLVMetadata: false,
  26437. enableID3MetadataCues: true,
  26438. enableInterstitialPlayback: true,
  26439. interstitialAppendInPlace: true,
  26440. interstitialLiveLookAhead: 10,
  26441. useMediaCapabilities: true,
  26442. preserveManualLevelOnError: false,
  26443. certLoadPolicy: {
  26444. default: defaultLoadPolicy
  26445. },
  26446. keyLoadPolicy: {
  26447. default: {
  26448. maxTimeToFirstByteMs: 8e3,
  26449. maxLoadTimeMs: 2e4,
  26450. timeoutRetry: {
  26451. maxNumRetry: 1,
  26452. retryDelayMs: 1e3,
  26453. maxRetryDelayMs: 2e4,
  26454. backoff: "linear"
  26455. },
  26456. errorRetry: {
  26457. maxNumRetry: 8,
  26458. retryDelayMs: 1e3,
  26459. maxRetryDelayMs: 2e4,
  26460. backoff: "linear"
  26461. }
  26462. }
  26463. },
  26464. manifestLoadPolicy: {
  26465. default: {
  26466. maxTimeToFirstByteMs: Infinity,
  26467. maxLoadTimeMs: 2e4,
  26468. timeoutRetry: {
  26469. maxNumRetry: 2,
  26470. retryDelayMs: 0,
  26471. maxRetryDelayMs: 0
  26472. },
  26473. errorRetry: {
  26474. maxNumRetry: 1,
  26475. retryDelayMs: 1e3,
  26476. maxRetryDelayMs: 8e3
  26477. }
  26478. }
  26479. },
  26480. playlistLoadPolicy: {
  26481. default: {
  26482. maxTimeToFirstByteMs: 1e4,
  26483. maxLoadTimeMs: 2e4,
  26484. timeoutRetry: {
  26485. maxNumRetry: 2,
  26486. retryDelayMs: 0,
  26487. maxRetryDelayMs: 0
  26488. },
  26489. errorRetry: {
  26490. maxNumRetry: 2,
  26491. retryDelayMs: 1e3,
  26492. maxRetryDelayMs: 8e3
  26493. }
  26494. }
  26495. },
  26496. fragLoadPolicy: {
  26497. default: {
  26498. maxTimeToFirstByteMs: 1e4,
  26499. maxLoadTimeMs: 12e4,
  26500. timeoutRetry: {
  26501. maxNumRetry: 4,
  26502. retryDelayMs: 0,
  26503. maxRetryDelayMs: 0
  26504. },
  26505. errorRetry: {
  26506. maxNumRetry: 6,
  26507. retryDelayMs: 1e3,
  26508. maxRetryDelayMs: 8e3
  26509. }
  26510. }
  26511. },
  26512. steeringManifestLoadPolicy: {
  26513. default: {
  26514. maxTimeToFirstByteMs: 1e4,
  26515. maxLoadTimeMs: 2e4,
  26516. timeoutRetry: {
  26517. maxNumRetry: 2,
  26518. retryDelayMs: 0,
  26519. maxRetryDelayMs: 0
  26520. },
  26521. errorRetry: {
  26522. maxNumRetry: 1,
  26523. retryDelayMs: 1e3,
  26524. maxRetryDelayMs: 8e3
  26525. }
  26526. }
  26527. },
  26528. interstitialAssetListLoadPolicy: {
  26529. default: {
  26530. maxTimeToFirstByteMs: 1e4,
  26531. maxLoadTimeMs: 3e4,
  26532. timeoutRetry: {
  26533. maxNumRetry: 0,
  26534. retryDelayMs: 0,
  26535. maxRetryDelayMs: 0
  26536. },
  26537. errorRetry: {
  26538. maxNumRetry: 0,
  26539. retryDelayMs: 1e3,
  26540. maxRetryDelayMs: 8e3
  26541. }
  26542. }
  26543. },
  26544. manifestLoadingTimeOut: 1e4,
  26545. manifestLoadingMaxRetry: 1,
  26546. manifestLoadingRetryDelay: 1e3,
  26547. manifestLoadingMaxRetryTimeout: 64e3,
  26548. levelLoadingTimeOut: 1e4,
  26549. levelLoadingMaxRetry: 4,
  26550. levelLoadingRetryDelay: 1e3,
  26551. levelLoadingMaxRetryTimeout: 64e3,
  26552. fragLoadingTimeOut: 2e4,
  26553. fragLoadingMaxRetry: 6,
  26554. fragLoadingRetryDelay: 1e3,
  26555. fragLoadingMaxRetryTimeout: 64e3
  26556. }, timelineConfig()), {}, {
  26557. subtitleStreamController: SubtitleStreamController,
  26558. subtitleTrackController: SubtitleTrackController,
  26559. timelineController: TimelineController,
  26560. audioStreamController: AudioStreamController,
  26561. audioTrackController: AudioTrackController,
  26562. emeController: EMEController,
  26563. cmcdController: CMCDController,
  26564. contentSteeringController: ContentSteeringController,
  26565. interstitialsController: InterstitialsController
  26566. });
  26567. function timelineConfig() {
  26568. return {
  26569. cueHandler: Cues,
  26570. enableWebVTT: true,
  26571. enableIMSC1: true,
  26572. enableCEA708Captions: true,
  26573. captionsTextTrack1Label: "English",
  26574. captionsTextTrack1LanguageCode: "en",
  26575. captionsTextTrack2Label: "Spanish",
  26576. captionsTextTrack2LanguageCode: "es",
  26577. captionsTextTrack3Label: "Unknown CC",
  26578. captionsTextTrack3LanguageCode: "",
  26579. captionsTextTrack4Label: "Unknown CC",
  26580. captionsTextTrack4LanguageCode: "",
  26581. renderTextTracksNatively: true
  26582. };
  26583. }
  26584. function mergeConfig(defaultConfig, userConfig, logger2) {
  26585. if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
  26586. throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  26587. }
  26588. if (userConfig.liveMaxLatencyDurationCount !== void 0 && (userConfig.liveSyncDurationCount === void 0 || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
  26589. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  26590. }
  26591. if (userConfig.liveMaxLatencyDuration !== void 0 && (userConfig.liveSyncDuration === void 0 || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
  26592. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  26593. }
  26594. const defaultsCopy = deepCpy(defaultConfig);
  26595. const deprecatedSettingTypes = ["manifest", "level", "frag"];
  26596. const deprecatedSettings = ["TimeOut", "MaxRetry", "RetryDelay", "MaxRetryTimeout"];
  26597. deprecatedSettingTypes.forEach((type) => {
  26598. const policyName = `${type === "level" ? "playlist" : type}LoadPolicy`;
  26599. const policyNotSet = userConfig[policyName] === void 0;
  26600. const report = [];
  26601. deprecatedSettings.forEach((setting) => {
  26602. const deprecatedSetting = `${type}Loading${setting}`;
  26603. const value = userConfig[deprecatedSetting];
  26604. if (value !== void 0 && policyNotSet) {
  26605. report.push(deprecatedSetting);
  26606. const settings = defaultsCopy[policyName].default;
  26607. userConfig[policyName] = {
  26608. default: settings
  26609. };
  26610. switch (setting) {
  26611. case "TimeOut":
  26612. settings.maxLoadTimeMs = value;
  26613. settings.maxTimeToFirstByteMs = value;
  26614. break;
  26615. case "MaxRetry":
  26616. settings.errorRetry.maxNumRetry = value;
  26617. settings.timeoutRetry.maxNumRetry = value;
  26618. break;
  26619. case "RetryDelay":
  26620. settings.errorRetry.retryDelayMs = value;
  26621. settings.timeoutRetry.retryDelayMs = value;
  26622. break;
  26623. case "MaxRetryTimeout":
  26624. settings.errorRetry.maxRetryDelayMs = value;
  26625. settings.timeoutRetry.maxRetryDelayMs = value;
  26626. break;
  26627. }
  26628. }
  26629. });
  26630. if (report.length) {
  26631. logger2.warn(`hls.js config: "${report.join('", "')}" setting(s) are deprecated, use "${policyName}": ${stringify(userConfig[policyName])}`);
  26632. }
  26633. });
  26634. return _objectSpread2(_objectSpread2({}, defaultsCopy), userConfig);
  26635. }
  26636. function deepCpy(obj) {
  26637. if (obj && typeof obj === "object") {
  26638. if (Array.isArray(obj)) {
  26639. return obj.map(deepCpy);
  26640. }
  26641. return Object.keys(obj).reduce((result, key) => {
  26642. result[key] = deepCpy(obj[key]);
  26643. return result;
  26644. }, {});
  26645. }
  26646. return obj;
  26647. }
  26648. function enableStreamingMode(config, logger2) {
  26649. const currentLoader = config.loader;
  26650. if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {
  26651. logger2.log("[config]: Custom loader detected, cannot enable progressive streaming");
  26652. config.progressive = false;
  26653. } else {
  26654. const canStreamProgressively = fetchSupported();
  26655. if (canStreamProgressively) {
  26656. config.loader = FetchLoader;
  26657. config.progressive = true;
  26658. config.enableSoftwareAES = true;
  26659. logger2.log("[config]: Progressive streaming enabled, using FetchLoader");
  26660. }
  26661. }
  26662. }
  26663. var MAX_START_GAP_JUMP = 2;
  26664. var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
  26665. var SKIP_BUFFER_RANGE_START = 0.05;
  26666. var TICK_INTERVAL$1 = 100;
  26667. var GapController = class extends TaskLoop {
  26668. constructor(hls, fragmentTracker) {
  26669. super("gap-controller", hls.logger);
  26670. this.hls = null;
  26671. this.fragmentTracker = null;
  26672. this.media = null;
  26673. this.mediaSource = void 0;
  26674. this.nudgeRetry = 0;
  26675. this.stallReported = false;
  26676. this.stalled = null;
  26677. this.moved = false;
  26678. this.seeking = false;
  26679. this.buffered = {};
  26680. this.lastCurrentTime = 0;
  26681. this.ended = 0;
  26682. this.waiting = 0;
  26683. this.onMediaPlaying = () => {
  26684. this.ended = 0;
  26685. this.waiting = 0;
  26686. };
  26687. this.onMediaWaiting = () => {
  26688. var _this$media;
  26689. if ((_this$media = this.media) != null && _this$media.seeking) {
  26690. return;
  26691. }
  26692. this.waiting = self.performance.now();
  26693. this.tick();
  26694. };
  26695. this.onMediaEnded = () => {
  26696. if (this.hls) {
  26697. var _this$media2;
  26698. this.ended = ((_this$media2 = this.media) == null ? void 0 : _this$media2.currentTime) || 1;
  26699. this.hls.trigger(Events.MEDIA_ENDED, {
  26700. stalled: false
  26701. });
  26702. }
  26703. };
  26704. this.hls = hls;
  26705. this.fragmentTracker = fragmentTracker;
  26706. this.registerListeners();
  26707. }
  26708. registerListeners() {
  26709. const {
  26710. hls
  26711. } = this;
  26712. if (hls) {
  26713. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  26714. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  26715. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  26716. }
  26717. }
  26718. unregisterListeners() {
  26719. const {
  26720. hls
  26721. } = this;
  26722. if (hls) {
  26723. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  26724. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  26725. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  26726. }
  26727. }
  26728. destroy() {
  26729. super.destroy();
  26730. this.unregisterListeners();
  26731. this.media = this.hls = this.fragmentTracker = null;
  26732. this.mediaSource = void 0;
  26733. }
  26734. onMediaAttached(event, data) {
  26735. this.setInterval(TICK_INTERVAL$1);
  26736. this.mediaSource = data.mediaSource;
  26737. const media = this.media = data.media;
  26738. addEventListener(media, "playing", this.onMediaPlaying);
  26739. addEventListener(media, "waiting", this.onMediaWaiting);
  26740. addEventListener(media, "ended", this.onMediaEnded);
  26741. }
  26742. onMediaDetaching(event, data) {
  26743. this.clearInterval();
  26744. const {
  26745. media
  26746. } = this;
  26747. if (media) {
  26748. removeEventListener(media, "playing", this.onMediaPlaying);
  26749. removeEventListener(media, "waiting", this.onMediaWaiting);
  26750. removeEventListener(media, "ended", this.onMediaEnded);
  26751. this.media = null;
  26752. }
  26753. this.mediaSource = void 0;
  26754. }
  26755. onBufferAppended(event, data) {
  26756. this.buffered = data.timeRanges;
  26757. }
  26758. get hasBuffered() {
  26759. return Object.keys(this.buffered).length > 0;
  26760. }
  26761. tick() {
  26762. var _this$media3;
  26763. if (!((_this$media3 = this.media) != null && _this$media3.readyState) || !this.hasBuffered) {
  26764. return;
  26765. }
  26766. const currentTime = this.media.currentTime;
  26767. this.poll(currentTime, this.lastCurrentTime);
  26768. this.lastCurrentTime = currentTime;
  26769. }
  26770. poll(currentTime, lastCurrentTime) {
  26771. var _this$hls, _this$hls2;
  26772. const config = (_this$hls = this.hls) == null ? void 0 : _this$hls.config;
  26773. if (!config) {
  26774. return;
  26775. }
  26776. const media = this.media;
  26777. if (!media) {
  26778. return;
  26779. }
  26780. const {
  26781. seeking
  26782. } = media;
  26783. const seeked = this.seeking && !seeking;
  26784. const beginSeek = !this.seeking && seeking;
  26785. const pausedEndedOrHalted = media.paused && !seeking || media.ended || media.playbackRate === 0;
  26786. this.seeking = seeking;
  26787. if (currentTime !== lastCurrentTime) {
  26788. if (lastCurrentTime) {
  26789. this.ended = 0;
  26790. }
  26791. this.moved = true;
  26792. if (!seeking) {
  26793. this.nudgeRetry = 0;
  26794. if (config.nudgeOnVideoHole && !pausedEndedOrHalted && currentTime > lastCurrentTime) {
  26795. this.nudgeOnVideoHole(currentTime, lastCurrentTime);
  26796. }
  26797. }
  26798. if (this.waiting === 0) {
  26799. this.stallResolved(currentTime);
  26800. }
  26801. return;
  26802. }
  26803. if (beginSeek || seeked) {
  26804. if (seeked) {
  26805. this.stallResolved(currentTime);
  26806. }
  26807. return;
  26808. }
  26809. if (pausedEndedOrHalted) {
  26810. this.nudgeRetry = 0;
  26811. this.stallResolved(currentTime);
  26812. if (!this.ended && media.ended && this.hls) {
  26813. this.ended = currentTime || 1;
  26814. this.hls.trigger(Events.MEDIA_ENDED, {
  26815. stalled: false
  26816. });
  26817. }
  26818. return;
  26819. }
  26820. if (!BufferHelper.getBuffered(media).length) {
  26821. this.nudgeRetry = 0;
  26822. return;
  26823. }
  26824. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  26825. const nextStart = bufferInfo.nextStart || 0;
  26826. const fragmentTracker = this.fragmentTracker;
  26827. if (seeking && fragmentTracker && this.hls) {
  26828. const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, currentTime);
  26829. const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;
  26830. const noBufferHole = !nextStart || inFlightDependency || nextStart - currentTime > MAX_START_GAP_JUMP && !fragmentTracker.getPartialFragment(currentTime);
  26831. if (hasEnoughBuffer || noBufferHole) {
  26832. return;
  26833. }
  26834. this.moved = false;
  26835. }
  26836. const levelDetails = (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.latestLevelDetails;
  26837. if (!this.moved && this.stalled !== null && fragmentTracker) {
  26838. const isBuffered = bufferInfo.len > 0;
  26839. if (!isBuffered && !nextStart) {
  26840. return;
  26841. }
  26842. const startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
  26843. const isLive = !!(levelDetails != null && levelDetails.live);
  26844. const maxStartGapJump = isLive ? levelDetails.targetduration * 2 : MAX_START_GAP_JUMP;
  26845. const partialOrGap = fragmentTracker.getPartialFragment(currentTime);
  26846. if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {
  26847. if (!media.paused) {
  26848. this._trySkipBufferHole(partialOrGap);
  26849. }
  26850. return;
  26851. }
  26852. }
  26853. const detectStallWithCurrentTimeMs = config.detectStallWithCurrentTimeMs;
  26854. const tnow = self.performance.now();
  26855. const tWaiting = this.waiting;
  26856. let stalled = this.stalled;
  26857. if (stalled === null) {
  26858. if (tWaiting > 0 && tnow - tWaiting < detectStallWithCurrentTimeMs) {
  26859. stalled = this.stalled = tWaiting;
  26860. } else {
  26861. this.stalled = tnow;
  26862. return;
  26863. }
  26864. }
  26865. const stalledDuration = tnow - stalled;
  26866. if (!seeking && (stalledDuration >= detectStallWithCurrentTimeMs || tWaiting) && this.hls) {
  26867. var _this$mediaSource;
  26868. 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) {
  26869. if (this.ended) {
  26870. return;
  26871. }
  26872. this.ended = currentTime || 1;
  26873. this.hls.trigger(Events.MEDIA_ENDED, {
  26874. stalled: true
  26875. });
  26876. return;
  26877. }
  26878. this._reportStall(bufferInfo);
  26879. if (!this.media || !this.hls) {
  26880. return;
  26881. }
  26882. }
  26883. const bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  26884. this._tryFixBufferStall(bufferedWithHoles, stalledDuration, currentTime);
  26885. }
  26886. stallResolved(currentTime) {
  26887. const stalled = this.stalled;
  26888. if (stalled && this.hls) {
  26889. this.stalled = null;
  26890. if (this.stallReported) {
  26891. const stalledDuration = self.performance.now() - stalled;
  26892. this.log(`playback not stuck anymore @${currentTime}, after ${Math.round(stalledDuration)}ms`);
  26893. this.stallReported = false;
  26894. this.waiting = 0;
  26895. this.hls.trigger(Events.STALL_RESOLVED, {});
  26896. }
  26897. }
  26898. }
  26899. nudgeOnVideoHole(currentTime, lastCurrentTime) {
  26900. var _this$buffered$audio;
  26901. const videoSourceBuffered = this.buffered.video;
  26902. 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)) {
  26903. const audioBufferInfo = BufferHelper.bufferedInfo(BufferHelper.timeRangesToArray(this.buffered.audio), currentTime, 0);
  26904. if (audioBufferInfo.len > 1 && lastCurrentTime >= audioBufferInfo.start) {
  26905. const videoTimes = BufferHelper.timeRangesToArray(videoSourceBuffered);
  26906. const lastBufferedIndex = BufferHelper.bufferedInfo(videoTimes, lastCurrentTime, 0).bufferedIndex;
  26907. if (lastBufferedIndex > -1 && lastBufferedIndex < videoTimes.length - 1) {
  26908. const bufferedIndex = BufferHelper.bufferedInfo(videoTimes, currentTime, 0).bufferedIndex;
  26909. const holeStart = videoTimes[lastBufferedIndex].end;
  26910. const holeEnd = videoTimes[lastBufferedIndex + 1].start;
  26911. if ((bufferedIndex === -1 || bufferedIndex > lastBufferedIndex) && holeEnd - holeStart < 1 && currentTime - holeStart < 2) {
  26912. const error = new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${currentTime} hole: ${holeStart} -> ${holeEnd} buffered index: ${bufferedIndex}`);
  26913. this.warn(error.message);
  26914. this.media.currentTime += 1e-6;
  26915. const frag = this.fragmentTracker.getPartialFragment(currentTime) || void 0;
  26916. const bufferInfo = BufferHelper.bufferInfo(this.media, currentTime, 0);
  26917. this.hls.trigger(Events.ERROR, {
  26918. type: ErrorTypes.MEDIA_ERROR,
  26919. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  26920. fatal: false,
  26921. error,
  26922. reason: error.message,
  26923. frag,
  26924. buffer: bufferInfo.len,
  26925. bufferInfo
  26926. });
  26927. }
  26928. }
  26929. }
  26930. }
  26931. }
  26932. _tryFixBufferStall(bufferInfo, stalledDurationMs, currentTime) {
  26933. var _this$hls3, _this$hls4;
  26934. const {
  26935. fragmentTracker,
  26936. media
  26937. } = this;
  26938. const config = (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.config;
  26939. if (!media || !fragmentTracker || !config) {
  26940. return;
  26941. }
  26942. const levelDetails = (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.latestLevelDetails;
  26943. const partial = fragmentTracker.getPartialFragment(currentTime);
  26944. if (partial || levelDetails != null && levelDetails.live && currentTime < levelDetails.fragmentStart) {
  26945. const targetTime = this._trySkipBufferHole(partial);
  26946. if (targetTime || !this.media) {
  26947. return;
  26948. }
  26949. }
  26950. const bufferedRanges = bufferInfo.buffered;
  26951. const adjacentTraversal = this.adjacentTraversal(bufferInfo, currentTime);
  26952. if ((bufferedRanges && bufferedRanges.length > 1 && bufferInfo.len > config.maxBufferHole || bufferInfo.nextStart && (bufferInfo.nextStart - currentTime < config.maxBufferHole || adjacentTraversal)) && (stalledDurationMs > config.highBufferWatchdogPeriod * 1e3 || this.waiting)) {
  26953. this.warn("Trying to nudge playhead over buffer-hole");
  26954. this._tryNudgeBuffer(bufferInfo);
  26955. }
  26956. }
  26957. adjacentTraversal(bufferInfo, currentTime) {
  26958. const fragmentTracker = this.fragmentTracker;
  26959. const nextStart = bufferInfo.nextStart;
  26960. if (fragmentTracker && nextStart) {
  26961. const current = fragmentTracker.getFragAtPos(currentTime, PlaylistLevelType.MAIN);
  26962. const next = fragmentTracker.getFragAtPos(nextStart, PlaylistLevelType.MAIN);
  26963. if (current && next) {
  26964. return next.sn - current.sn < 2;
  26965. }
  26966. }
  26967. return false;
  26968. }
  26969. _reportStall(bufferInfo) {
  26970. const {
  26971. hls,
  26972. media,
  26973. stallReported,
  26974. stalled
  26975. } = this;
  26976. if (!stallReported && stalled !== null && media && hls) {
  26977. this.stallReported = true;
  26978. const error = new Error(`Playback stalling at @${media.currentTime} due to low buffer (${stringify(bufferInfo)})`);
  26979. this.warn(error.message);
  26980. hls.trigger(Events.ERROR, {
  26981. type: ErrorTypes.MEDIA_ERROR,
  26982. details: ErrorDetails.BUFFER_STALLED_ERROR,
  26983. fatal: false,
  26984. error,
  26985. buffer: bufferInfo.len,
  26986. bufferInfo,
  26987. stalled: {
  26988. start: stalled
  26989. }
  26990. });
  26991. }
  26992. }
  26993. _trySkipBufferHole(partial) {
  26994. var _this$hls5;
  26995. const {
  26996. fragmentTracker,
  26997. media
  26998. } = this;
  26999. const config = (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.config;
  27000. if (!media || !fragmentTracker || !config) {
  27001. return 0;
  27002. }
  27003. const currentTime = media.currentTime;
  27004. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  27005. const startTime = currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;
  27006. if (startTime && this.hls) {
  27007. const bufferStarved = bufferInfo.len <= config.maxBufferHole;
  27008. const waiting = bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;
  27009. const gapLength = startTime - currentTime;
  27010. if (gapLength > 0 && (bufferStarved || waiting)) {
  27011. if (gapLength > config.maxBufferHole) {
  27012. let startGap = false;
  27013. if (currentTime === 0) {
  27014. const startFrag = fragmentTracker.getAppendedFrag(0, PlaylistLevelType.MAIN);
  27015. if (startFrag && startTime < startFrag.end) {
  27016. startGap = true;
  27017. }
  27018. }
  27019. if (!startGap) {
  27020. const startProvisioned = partial || fragmentTracker.getAppendedFrag(currentTime, PlaylistLevelType.MAIN);
  27021. if (startProvisioned) {
  27022. var _this$hls$loadLevelOb;
  27023. if (!((_this$hls$loadLevelOb = this.hls.loadLevelObj) != null && _this$hls$loadLevelOb.details)) {
  27024. return 0;
  27025. }
  27026. const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, startTime);
  27027. if (inFlightDependency) {
  27028. return 0;
  27029. }
  27030. let moreToLoad = false;
  27031. let pos = startProvisioned.end;
  27032. while (pos < startTime) {
  27033. const provisioned = fragmentTracker.getAppendedFrag(pos, PlaylistLevelType.MAIN) || fragmentTracker.getPartialFragment(pos);
  27034. if (provisioned) {
  27035. pos += provisioned.duration;
  27036. } else {
  27037. moreToLoad = true;
  27038. break;
  27039. }
  27040. }
  27041. if (moreToLoad) {
  27042. return 0;
  27043. }
  27044. }
  27045. }
  27046. }
  27047. const targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
  27048. this.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`);
  27049. this.moved = true;
  27050. media.currentTime = targetTime;
  27051. if (!(partial != null && partial.gap)) {
  27052. const error = new Error(`fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`);
  27053. this.hls.trigger(Events.ERROR, {
  27054. type: ErrorTypes.MEDIA_ERROR,
  27055. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  27056. fatal: false,
  27057. error,
  27058. reason: error.message,
  27059. frag: partial || void 0,
  27060. buffer: bufferInfo.len,
  27061. bufferInfo
  27062. });
  27063. }
  27064. return targetTime;
  27065. }
  27066. }
  27067. return 0;
  27068. }
  27069. _tryNudgeBuffer(bufferInfo) {
  27070. const {
  27071. hls,
  27072. media,
  27073. nudgeRetry
  27074. } = this;
  27075. const config = hls == null ? void 0 : hls.config;
  27076. if (!media || !config) {
  27077. return 0;
  27078. }
  27079. const currentTime = media.currentTime;
  27080. this.nudgeRetry++;
  27081. if (nudgeRetry < config.nudgeMaxRetry) {
  27082. const targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;
  27083. const error = new Error(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`);
  27084. this.warn(error.message);
  27085. media.currentTime = targetTime;
  27086. hls.trigger(Events.ERROR, {
  27087. type: ErrorTypes.MEDIA_ERROR,
  27088. details: ErrorDetails.BUFFER_NUDGE_ON_STALL,
  27089. error,
  27090. fatal: false,
  27091. buffer: bufferInfo.len,
  27092. bufferInfo
  27093. });
  27094. } else {
  27095. const error = new Error(`Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`);
  27096. this.error(error.message);
  27097. hls.trigger(Events.ERROR, {
  27098. type: ErrorTypes.MEDIA_ERROR,
  27099. details: ErrorDetails.BUFFER_STALLED_ERROR,
  27100. error,
  27101. fatal: true,
  27102. buffer: bufferInfo.len,
  27103. bufferInfo
  27104. });
  27105. }
  27106. }
  27107. };
  27108. function getInFlightDependency(inFlightFragments, currentTime) {
  27109. const main = inFlight(inFlightFragments.main);
  27110. if (main && main.start <= currentTime) {
  27111. return main;
  27112. }
  27113. const audio = inFlight(inFlightFragments.audio);
  27114. if (audio && audio.start <= currentTime) {
  27115. return audio;
  27116. }
  27117. return null;
  27118. }
  27119. function inFlight(inFlightData) {
  27120. if (!inFlightData) {
  27121. return null;
  27122. }
  27123. switch (inFlightData.state) {
  27124. case State.IDLE:
  27125. case State.STOPPED:
  27126. case State.ENDED:
  27127. case State.ERROR:
  27128. return null;
  27129. }
  27130. return inFlightData.frag;
  27131. }
  27132. var MIN_CUE_DURATION = 0.25;
  27133. function getCueClass() {
  27134. if (typeof self === "undefined")
  27135. return void 0;
  27136. return self.VTTCue || self.TextTrackCue;
  27137. }
  27138. function createCueWithDataFields(Cue, startTime, endTime, data, type) {
  27139. let cue = new Cue(startTime, endTime, "");
  27140. try {
  27141. cue.value = data;
  27142. if (type) {
  27143. cue.type = type;
  27144. }
  27145. } catch (e) {
  27146. cue = new Cue(startTime, endTime, stringify(type ? _objectSpread2({
  27147. type
  27148. }, data) : data));
  27149. }
  27150. return cue;
  27151. }
  27152. var MAX_CUE_ENDTIME = (() => {
  27153. const Cue = getCueClass();
  27154. try {
  27155. Cue && new Cue(0, Number.POSITIVE_INFINITY, "");
  27156. } catch (e) {
  27157. return Number.MAX_VALUE;
  27158. }
  27159. return Number.POSITIVE_INFINITY;
  27160. })();
  27161. var ID3TrackController = class {
  27162. constructor(hls) {
  27163. this.hls = void 0;
  27164. this.id3Track = null;
  27165. this.media = null;
  27166. this.dateRangeCuesAppended = {};
  27167. this.removeCues = true;
  27168. this.onEventCueEnter = () => {
  27169. if (!this.hls) {
  27170. return;
  27171. }
  27172. this.hls.trigger(Events.EVENT_CUE_ENTER, {});
  27173. };
  27174. this.hls = hls;
  27175. this._registerListeners();
  27176. }
  27177. destroy() {
  27178. this._unregisterListeners();
  27179. this.id3Track = null;
  27180. this.media = null;
  27181. this.dateRangeCuesAppended = {};
  27182. this.hls = this.onEventCueEnter = null;
  27183. }
  27184. _registerListeners() {
  27185. const {
  27186. hls
  27187. } = this;
  27188. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  27189. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  27190. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  27191. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  27192. hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  27193. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  27194. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  27195. hls.on(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  27196. }
  27197. _unregisterListeners() {
  27198. const {
  27199. hls
  27200. } = this;
  27201. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  27202. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  27203. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  27204. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  27205. hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  27206. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  27207. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  27208. hls.off(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  27209. }
  27210. onMediaAttaching(event, data) {
  27211. var _data$overrides;
  27212. this.media = data.media;
  27213. if (((_data$overrides = data.overrides) == null ? void 0 : _data$overrides.cueRemoval) === false) {
  27214. this.removeCues = false;
  27215. }
  27216. }
  27217. onMediaAttached() {
  27218. const details = this.hls.latestLevelDetails;
  27219. if (details) {
  27220. this.updateDateRangeCues(details);
  27221. }
  27222. }
  27223. onMediaDetaching(event, data) {
  27224. this.media = null;
  27225. const transferringMedia = !!data.transferMedia;
  27226. if (transferringMedia) {
  27227. return;
  27228. }
  27229. if (this.id3Track) {
  27230. if (this.removeCues) {
  27231. clearCurrentCues(this.id3Track, this.onEventCueEnter);
  27232. }
  27233. this.id3Track = null;
  27234. }
  27235. this.dateRangeCuesAppended = {};
  27236. }
  27237. onManifestLoading() {
  27238. this.dateRangeCuesAppended = {};
  27239. }
  27240. createTrack(media) {
  27241. const track = this.getID3Track(media.textTracks);
  27242. track.mode = "hidden";
  27243. return track;
  27244. }
  27245. getID3Track(textTracks) {
  27246. if (!this.media) {
  27247. return;
  27248. }
  27249. for (let i = 0; i < textTracks.length; i++) {
  27250. const textTrack = textTracks[i];
  27251. if (textTrack.kind === "metadata" && textTrack.label === "id3") {
  27252. sendAddTrackEvent(textTrack, this.media);
  27253. return textTrack;
  27254. }
  27255. }
  27256. return this.media.addTextTrack("metadata", "id3");
  27257. }
  27258. onFragParsingMetadata(event, data) {
  27259. if (!this.media) {
  27260. return;
  27261. }
  27262. const {
  27263. hls: {
  27264. config: {
  27265. enableEmsgMetadataCues,
  27266. enableID3MetadataCues
  27267. }
  27268. }
  27269. } = this;
  27270. if (!enableEmsgMetadataCues && !enableID3MetadataCues) {
  27271. return;
  27272. }
  27273. const {
  27274. samples
  27275. } = data;
  27276. if (!this.id3Track) {
  27277. this.id3Track = this.createTrack(this.media);
  27278. }
  27279. const Cue = getCueClass();
  27280. if (!Cue) {
  27281. return;
  27282. }
  27283. for (let i = 0; i < samples.length; i++) {
  27284. const type = samples[i].type;
  27285. if (type === MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) {
  27286. continue;
  27287. }
  27288. const frames = getId3Frames(samples[i].data);
  27289. if (frames) {
  27290. const startTime = samples[i].pts;
  27291. let endTime = startTime + samples[i].duration;
  27292. if (endTime > MAX_CUE_ENDTIME) {
  27293. endTime = MAX_CUE_ENDTIME;
  27294. }
  27295. const timeDiff = endTime - startTime;
  27296. if (timeDiff <= 0) {
  27297. endTime = startTime + MIN_CUE_DURATION;
  27298. }
  27299. for (let j = 0; j < frames.length; j++) {
  27300. const frame = frames[j];
  27301. if (!isId3TimestampFrame(frame)) {
  27302. this.updateId3CueEnds(startTime, type);
  27303. const cue = createCueWithDataFields(Cue, startTime, endTime, frame, type);
  27304. if (cue) {
  27305. this.id3Track.addCue(cue);
  27306. }
  27307. }
  27308. }
  27309. }
  27310. }
  27311. }
  27312. updateId3CueEnds(startTime, type) {
  27313. var _this$id3Track;
  27314. const cues = (_this$id3Track = this.id3Track) == null ? void 0 : _this$id3Track.cues;
  27315. if (cues) {
  27316. for (let i = cues.length; i--; ) {
  27317. const cue = cues[i];
  27318. if (cue.type === type && cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {
  27319. cue.endTime = startTime;
  27320. }
  27321. }
  27322. }
  27323. }
  27324. onBufferFlushing(event, {
  27325. startOffset,
  27326. endOffset,
  27327. type
  27328. }) {
  27329. const {
  27330. id3Track,
  27331. hls
  27332. } = this;
  27333. if (!hls) {
  27334. return;
  27335. }
  27336. const {
  27337. config: {
  27338. enableEmsgMetadataCues,
  27339. enableID3MetadataCues
  27340. }
  27341. } = hls;
  27342. if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {
  27343. let predicate;
  27344. if (type === "audio") {
  27345. predicate = (cue) => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues;
  27346. } else if (type === "video") {
  27347. predicate = (cue) => cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  27348. } else {
  27349. predicate = (cue) => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  27350. }
  27351. removeCuesInRange(id3Track, startOffset, endOffset, predicate);
  27352. }
  27353. }
  27354. onLevelUpdated(event, {
  27355. details
  27356. }) {
  27357. this.updateDateRangeCues(details, true);
  27358. }
  27359. onLevelPtsUpdated(event, data) {
  27360. if (Math.abs(data.drift) > 0.01) {
  27361. this.updateDateRangeCues(data.details);
  27362. }
  27363. }
  27364. updateDateRangeCues(details, removeOldCues) {
  27365. if (!this.media || !details.hasProgramDateTime || !this.hls.config.enableDateRangeMetadataCues) {
  27366. return;
  27367. }
  27368. const {
  27369. id3Track
  27370. } = this;
  27371. const {
  27372. dateRanges
  27373. } = details;
  27374. const ids = Object.keys(dateRanges);
  27375. let dateRangeCuesAppended = this.dateRangeCuesAppended;
  27376. if (id3Track && removeOldCues) {
  27377. var _id3Track$cues;
  27378. if ((_id3Track$cues = id3Track.cues) != null && _id3Track$cues.length) {
  27379. const idsToRemove = Object.keys(dateRangeCuesAppended).filter((id) => !ids.includes(id));
  27380. for (let i = idsToRemove.length; i--; ) {
  27381. const id = idsToRemove[i];
  27382. const cues = dateRangeCuesAppended[id].cues;
  27383. delete dateRangeCuesAppended[id];
  27384. Object.keys(cues).forEach((key) => {
  27385. try {
  27386. const cue = cues[key];
  27387. cue.removeEventListener("enter", this.onEventCueEnter);
  27388. id3Track.removeCue(cue);
  27389. } catch (e) {
  27390. }
  27391. });
  27392. }
  27393. } else {
  27394. dateRangeCuesAppended = this.dateRangeCuesAppended = {};
  27395. }
  27396. }
  27397. const lastFragment = details.fragments[details.fragments.length - 1];
  27398. if (ids.length === 0 || !isFiniteNumber(lastFragment == null ? void 0 : lastFragment.programDateTime)) {
  27399. return;
  27400. }
  27401. if (!this.id3Track) {
  27402. this.id3Track = this.createTrack(this.media);
  27403. }
  27404. const Cue = getCueClass();
  27405. for (let i = 0; i < ids.length; i++) {
  27406. const id = ids[i];
  27407. const dateRange = dateRanges[id];
  27408. const startTime = dateRange.startTime;
  27409. const appendedDateRangeCues = dateRangeCuesAppended[id];
  27410. const cues = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.cues) || {};
  27411. let durationKnown = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.durationKnown) || false;
  27412. let endTime = MAX_CUE_ENDTIME;
  27413. const {
  27414. duration,
  27415. endDate
  27416. } = dateRange;
  27417. if (endDate && duration !== null) {
  27418. endTime = startTime + duration;
  27419. durationKnown = true;
  27420. } else if (dateRange.endOnNext && !durationKnown) {
  27421. const nextDateRangeWithSameClass = ids.reduce((candidateDateRange, id2) => {
  27422. if (id2 !== dateRange.id) {
  27423. const otherDateRange = dateRanges[id2];
  27424. if (otherDateRange.class === dateRange.class && otherDateRange.startDate > dateRange.startDate && (!candidateDateRange || dateRange.startDate < candidateDateRange.startDate)) {
  27425. return otherDateRange;
  27426. }
  27427. }
  27428. return candidateDateRange;
  27429. }, null);
  27430. if (nextDateRangeWithSameClass) {
  27431. endTime = nextDateRangeWithSameClass.startTime;
  27432. durationKnown = true;
  27433. }
  27434. }
  27435. const attributes = Object.keys(dateRange.attr);
  27436. for (let j = 0; j < attributes.length; j++) {
  27437. const key = attributes[j];
  27438. if (!isDateRangeCueAttribute(key)) {
  27439. continue;
  27440. }
  27441. const cue = cues[key];
  27442. if (cue) {
  27443. if (durationKnown && !appendedDateRangeCues.durationKnown) {
  27444. cue.endTime = endTime;
  27445. } else if (Math.abs(cue.startTime - startTime) > 0.01) {
  27446. cue.startTime = startTime;
  27447. cue.endTime = endTime;
  27448. }
  27449. } else if (Cue) {
  27450. let data = dateRange.attr[key];
  27451. if (isSCTE35Attribute(key)) {
  27452. data = hexToArrayBuffer(data);
  27453. }
  27454. const payload = {
  27455. key,
  27456. data
  27457. };
  27458. const _cue = createCueWithDataFields(Cue, startTime, endTime, payload, MetadataSchema.dateRange);
  27459. if (_cue) {
  27460. _cue.id = id;
  27461. this.id3Track.addCue(_cue);
  27462. cues[key] = _cue;
  27463. if (this.hls.config.interstitialsController) {
  27464. if (key === "X-ASSET-LIST" || key === "X-ASSET-URL") {
  27465. _cue.addEventListener("enter", this.onEventCueEnter);
  27466. }
  27467. }
  27468. }
  27469. }
  27470. }
  27471. dateRangeCuesAppended[id] = {
  27472. cues,
  27473. dateRange,
  27474. durationKnown
  27475. };
  27476. }
  27477. }
  27478. };
  27479. var LatencyController = class {
  27480. constructor(hls) {
  27481. this.hls = void 0;
  27482. this.config = void 0;
  27483. this.media = null;
  27484. this.currentTime = 0;
  27485. this.stallCount = 0;
  27486. this._latency = null;
  27487. this._targetLatencyUpdated = false;
  27488. this.onTimeupdate = () => {
  27489. const {
  27490. media
  27491. } = this;
  27492. const levelDetails = this.levelDetails;
  27493. if (!media || !levelDetails) {
  27494. return;
  27495. }
  27496. this.currentTime = media.currentTime;
  27497. const latency = this.computeLatency();
  27498. if (latency === null) {
  27499. return;
  27500. }
  27501. this._latency = latency;
  27502. const {
  27503. lowLatencyMode,
  27504. maxLiveSyncPlaybackRate
  27505. } = this.config;
  27506. if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1 || !levelDetails.live) {
  27507. return;
  27508. }
  27509. const targetLatency = this.targetLatency;
  27510. if (targetLatency === null) {
  27511. return;
  27512. }
  27513. const distanceFromTarget = latency - targetLatency;
  27514. const liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
  27515. const inLiveRange = distanceFromTarget < liveMinLatencyDuration;
  27516. if (inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
  27517. const max = Math.min(2, Math.max(1, maxLiveSyncPlaybackRate));
  27518. const rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
  27519. const playbackRate = Math.min(max, Math.max(1, rate));
  27520. this.changeMediaPlaybackRate(media, playbackRate);
  27521. } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
  27522. this.changeMediaPlaybackRate(media, 1);
  27523. }
  27524. };
  27525. this.hls = hls;
  27526. this.config = hls.config;
  27527. this.registerListeners();
  27528. }
  27529. get levelDetails() {
  27530. var _this$hls;
  27531. return ((_this$hls = this.hls) == null ? void 0 : _this$hls.latestLevelDetails) || null;
  27532. }
  27533. get latency() {
  27534. return this._latency || 0;
  27535. }
  27536. get maxLatency() {
  27537. const {
  27538. config
  27539. } = this;
  27540. if (config.liveMaxLatencyDuration !== void 0) {
  27541. return config.liveMaxLatencyDuration;
  27542. }
  27543. const levelDetails = this.levelDetails;
  27544. return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
  27545. }
  27546. get targetLatency() {
  27547. const levelDetails = this.levelDetails;
  27548. if (levelDetails === null || this.hls === null) {
  27549. return null;
  27550. }
  27551. const {
  27552. holdBack,
  27553. partHoldBack,
  27554. targetduration
  27555. } = levelDetails;
  27556. const {
  27557. liveSyncDuration,
  27558. liveSyncDurationCount,
  27559. lowLatencyMode
  27560. } = this.config;
  27561. const userConfig = this.hls.userConfig;
  27562. let targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
  27563. if (this._targetLatencyUpdated || userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
  27564. targetLatency = liveSyncDuration !== void 0 ? liveSyncDuration : liveSyncDurationCount * targetduration;
  27565. }
  27566. const maxLiveSyncOnStallIncrease = targetduration;
  27567. return targetLatency + Math.min(this.stallCount * this.config.liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
  27568. }
  27569. set targetLatency(latency) {
  27570. this.stallCount = 0;
  27571. this.config.liveSyncDuration = latency;
  27572. this._targetLatencyUpdated = true;
  27573. }
  27574. get liveSyncPosition() {
  27575. const liveEdge = this.estimateLiveEdge();
  27576. const targetLatency = this.targetLatency;
  27577. if (liveEdge === null || targetLatency === null) {
  27578. return null;
  27579. }
  27580. const levelDetails = this.levelDetails;
  27581. if (levelDetails === null) {
  27582. return null;
  27583. }
  27584. const edge = levelDetails.edge;
  27585. const syncPosition = liveEdge - targetLatency - this.edgeStalled;
  27586. const min = edge - levelDetails.totalduration;
  27587. const max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
  27588. return Math.min(Math.max(min, syncPosition), max);
  27589. }
  27590. get drift() {
  27591. const levelDetails = this.levelDetails;
  27592. if (levelDetails === null) {
  27593. return 1;
  27594. }
  27595. return levelDetails.drift;
  27596. }
  27597. get edgeStalled() {
  27598. const levelDetails = this.levelDetails;
  27599. if (levelDetails === null) {
  27600. return 0;
  27601. }
  27602. const maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
  27603. return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
  27604. }
  27605. get forwardBufferLength() {
  27606. const {
  27607. media
  27608. } = this;
  27609. const levelDetails = this.levelDetails;
  27610. if (!media || !levelDetails) {
  27611. return 0;
  27612. }
  27613. const bufferedRanges = media.buffered.length;
  27614. return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime;
  27615. }
  27616. destroy() {
  27617. this.unregisterListeners();
  27618. this.onMediaDetaching();
  27619. this.hls = null;
  27620. }
  27621. registerListeners() {
  27622. const {
  27623. hls
  27624. } = this;
  27625. if (!hls) {
  27626. return;
  27627. }
  27628. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  27629. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  27630. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  27631. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  27632. hls.on(Events.ERROR, this.onError, this);
  27633. }
  27634. unregisterListeners() {
  27635. const {
  27636. hls
  27637. } = this;
  27638. if (!hls) {
  27639. return;
  27640. }
  27641. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  27642. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  27643. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  27644. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  27645. hls.off(Events.ERROR, this.onError, this);
  27646. }
  27647. onMediaAttached(event, data) {
  27648. this.media = data.media;
  27649. this.media.addEventListener("timeupdate", this.onTimeupdate);
  27650. }
  27651. onMediaDetaching() {
  27652. if (this.media) {
  27653. this.media.removeEventListener("timeupdate", this.onTimeupdate);
  27654. this.media = null;
  27655. }
  27656. }
  27657. onManifestLoading() {
  27658. this._latency = null;
  27659. this.stallCount = 0;
  27660. }
  27661. onLevelUpdated(event, {
  27662. details
  27663. }) {
  27664. if (details.advanced) {
  27665. this.onTimeupdate();
  27666. }
  27667. if (!details.live && this.media) {
  27668. this.media.removeEventListener("timeupdate", this.onTimeupdate);
  27669. }
  27670. }
  27671. onError(event, data) {
  27672. var _this$levelDetails;
  27673. if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {
  27674. return;
  27675. }
  27676. this.stallCount++;
  27677. if (this.hls && (_this$levelDetails = this.levelDetails) != null && _this$levelDetails.live) {
  27678. this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency");
  27679. }
  27680. }
  27681. changeMediaPlaybackRate(media, playbackRate) {
  27682. var _this$hls2, _this$targetLatency;
  27683. if (media.playbackRate === playbackRate) {
  27684. return;
  27685. }
  27686. (_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}`);
  27687. media.playbackRate = playbackRate;
  27688. }
  27689. estimateLiveEdge() {
  27690. const levelDetails = this.levelDetails;
  27691. if (levelDetails === null) {
  27692. return null;
  27693. }
  27694. return levelDetails.edge + levelDetails.age;
  27695. }
  27696. computeLatency() {
  27697. const liveEdge = this.estimateLiveEdge();
  27698. if (liveEdge === null) {
  27699. return null;
  27700. }
  27701. return liveEdge - this.currentTime;
  27702. }
  27703. };
  27704. var LevelController = class extends BasePlaylistController {
  27705. constructor(hls, contentSteeringController) {
  27706. super(hls, "level-controller");
  27707. this._levels = [];
  27708. this._firstLevel = -1;
  27709. this._maxAutoLevel = -1;
  27710. this._startLevel = void 0;
  27711. this.currentLevel = null;
  27712. this.currentLevelIndex = -1;
  27713. this.manualLevelIndex = -1;
  27714. this.steering = void 0;
  27715. this.onParsedComplete = void 0;
  27716. this.steering = contentSteeringController;
  27717. this._registerListeners();
  27718. }
  27719. _registerListeners() {
  27720. const {
  27721. hls
  27722. } = this;
  27723. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  27724. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  27725. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  27726. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  27727. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  27728. hls.on(Events.ERROR, this.onError, this);
  27729. }
  27730. _unregisterListeners() {
  27731. const {
  27732. hls
  27733. } = this;
  27734. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  27735. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  27736. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  27737. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  27738. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  27739. hls.off(Events.ERROR, this.onError, this);
  27740. }
  27741. destroy() {
  27742. this._unregisterListeners();
  27743. this.steering = null;
  27744. this.resetLevels();
  27745. super.destroy();
  27746. }
  27747. stopLoad() {
  27748. const levels = this._levels;
  27749. levels.forEach((level) => {
  27750. level.loadError = 0;
  27751. level.fragmentError = 0;
  27752. });
  27753. super.stopLoad();
  27754. }
  27755. resetLevels() {
  27756. this._startLevel = void 0;
  27757. this.manualLevelIndex = -1;
  27758. this.currentLevelIndex = -1;
  27759. this.currentLevel = null;
  27760. this._levels = [];
  27761. this._maxAutoLevel = -1;
  27762. }
  27763. onManifestLoading(event, data) {
  27764. this.resetLevels();
  27765. }
  27766. onManifestLoaded(event, data) {
  27767. const preferManagedMediaSource = this.hls.config.preferManagedMediaSource;
  27768. const levels = [];
  27769. const redundantSet = {};
  27770. const generatePathwaySet = {};
  27771. let resolutionFound = false;
  27772. let videoCodecFound = false;
  27773. let audioCodecFound = false;
  27774. data.levels.forEach((levelParsed) => {
  27775. const attributes = levelParsed.attrs;
  27776. let {
  27777. audioCodec,
  27778. videoCodec
  27779. } = levelParsed;
  27780. if (audioCodec) {
  27781. levelParsed.audioCodec = audioCodec = getCodecCompatibleName(audioCodec, preferManagedMediaSource) || void 0;
  27782. }
  27783. if (videoCodec) {
  27784. videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);
  27785. }
  27786. const {
  27787. width,
  27788. height,
  27789. unknownCodecs
  27790. } = levelParsed;
  27791. let unknownUnsupportedCodecCount = unknownCodecs ? unknownCodecs.length : 0;
  27792. if (unknownCodecs) {
  27793. for (let i = unknownUnsupportedCodecCount; i--; ) {
  27794. const unknownCodec = unknownCodecs[i];
  27795. if (this.isAudioSupported(unknownCodec)) {
  27796. levelParsed.audioCodec = audioCodec = audioCodec ? `${audioCodec},${unknownCodec}` : unknownCodec;
  27797. unknownUnsupportedCodecCount--;
  27798. sampleEntryCodesISO.audio[audioCodec.substring(0, 4)] = 2;
  27799. } else if (this.isVideoSupported(unknownCodec)) {
  27800. levelParsed.videoCodec = videoCodec = videoCodec ? `${videoCodec},${unknownCodec}` : unknownCodec;
  27801. unknownUnsupportedCodecCount--;
  27802. sampleEntryCodesISO.video[videoCodec.substring(0, 4)] = 2;
  27803. }
  27804. }
  27805. }
  27806. resolutionFound || (resolutionFound = !!(width && height));
  27807. videoCodecFound || (videoCodecFound = !!videoCodec);
  27808. audioCodecFound || (audioCodecFound = !!audioCodec);
  27809. if (unknownUnsupportedCodecCount || audioCodec && !this.isAudioSupported(audioCodec) || videoCodec && !this.isVideoSupported(videoCodec)) {
  27810. this.log(`Some or all CODECS not supported "${attributes.CODECS}"`);
  27811. return;
  27812. }
  27813. const {
  27814. CODECS,
  27815. "FRAME-RATE": FRAMERATE,
  27816. "HDCP-LEVEL": HDCP,
  27817. "PATHWAY-ID": PATHWAY,
  27818. RESOLUTION,
  27819. "VIDEO-RANGE": VIDEO_RANGE
  27820. } = attributes;
  27821. const contentSteeringPrefix = `${PATHWAY || "."}-`;
  27822. const levelKey = `${contentSteeringPrefix}${levelParsed.bitrate}-${RESOLUTION}-${FRAMERATE}-${CODECS}-${VIDEO_RANGE}-${HDCP}`;
  27823. if (!redundantSet[levelKey]) {
  27824. const level = this.createLevel(levelParsed);
  27825. redundantSet[levelKey] = level;
  27826. generatePathwaySet[levelKey] = 1;
  27827. levels.push(level);
  27828. } else if (redundantSet[levelKey].uri !== levelParsed.url && !levelParsed.attrs["PATHWAY-ID"]) {
  27829. const pathwayCount = generatePathwaySet[levelKey] += 1;
  27830. levelParsed.attrs["PATHWAY-ID"] = new Array(pathwayCount + 1).join(".");
  27831. const level = this.createLevel(levelParsed);
  27832. redundantSet[levelKey] = level;
  27833. levels.push(level);
  27834. } else {
  27835. redundantSet[levelKey].addGroupId("audio", attributes.AUDIO);
  27836. redundantSet[levelKey].addGroupId("text", attributes.SUBTITLES);
  27837. }
  27838. });
  27839. this.filterAndSortMediaOptions(levels, data, resolutionFound, videoCodecFound, audioCodecFound);
  27840. }
  27841. createLevel(levelParsed) {
  27842. const level = new Level(levelParsed);
  27843. const supplemental = levelParsed.supplemental;
  27844. if (supplemental != null && supplemental.videoCodec && !this.isVideoSupported(supplemental.videoCodec)) {
  27845. const error = new Error(`SUPPLEMENTAL-CODECS not supported "${supplemental.videoCodec}"`);
  27846. this.log(error.message);
  27847. level.supportedResult = getUnsupportedResult(error, []);
  27848. }
  27849. return level;
  27850. }
  27851. isAudioSupported(codec) {
  27852. return areCodecsMediaSourceSupported(codec, "audio", this.hls.config.preferManagedMediaSource);
  27853. }
  27854. isVideoSupported(codec) {
  27855. return areCodecsMediaSourceSupported(codec, "video", this.hls.config.preferManagedMediaSource);
  27856. }
  27857. filterAndSortMediaOptions(filteredLevels, data, resolutionFound, videoCodecFound, audioCodecFound) {
  27858. let audioTracks = [];
  27859. let subtitleTracks = [];
  27860. let levels = filteredLevels;
  27861. if ((resolutionFound || videoCodecFound) && audioCodecFound) {
  27862. levels = levels.filter(({
  27863. videoCodec,
  27864. videoRange,
  27865. width,
  27866. height
  27867. }) => (!!videoCodec || !!(width && height)) && isVideoRange(videoRange));
  27868. }
  27869. if (levels.length === 0) {
  27870. Promise.resolve().then(() => {
  27871. if (this.hls) {
  27872. let message = "no level with compatible codecs found in manifest";
  27873. let reason = message;
  27874. if (data.levels.length) {
  27875. 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))}`;
  27876. this.warn(reason);
  27877. message += ` (${reason})`;
  27878. }
  27879. const error = new Error(message);
  27880. this.hls.trigger(Events.ERROR, {
  27881. type: ErrorTypes.MEDIA_ERROR,
  27882. details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  27883. fatal: true,
  27884. url: data.url,
  27885. error,
  27886. reason
  27887. });
  27888. }
  27889. });
  27890. return;
  27891. }
  27892. if (data.audioTracks) {
  27893. audioTracks = data.audioTracks.filter((track) => !track.audioCodec || this.isAudioSupported(track.audioCodec));
  27894. assignTrackIdsByGroup(audioTracks);
  27895. }
  27896. if (data.subtitles) {
  27897. subtitleTracks = data.subtitles;
  27898. assignTrackIdsByGroup(subtitleTracks);
  27899. }
  27900. const unsortedLevels = levels.slice(0);
  27901. levels.sort((a, b) => {
  27902. if (a.attrs["HDCP-LEVEL"] !== b.attrs["HDCP-LEVEL"]) {
  27903. return (a.attrs["HDCP-LEVEL"] || "") > (b.attrs["HDCP-LEVEL"] || "") ? 1 : -1;
  27904. }
  27905. if (resolutionFound && a.height !== b.height) {
  27906. return a.height - b.height;
  27907. }
  27908. if (a.frameRate !== b.frameRate) {
  27909. return a.frameRate - b.frameRate;
  27910. }
  27911. if (a.videoRange !== b.videoRange) {
  27912. return VideoRangeValues.indexOf(a.videoRange) - VideoRangeValues.indexOf(b.videoRange);
  27913. }
  27914. if (a.videoCodec !== b.videoCodec) {
  27915. const valueA = videoCodecPreferenceValue(a.videoCodec);
  27916. const valueB = videoCodecPreferenceValue(b.videoCodec);
  27917. if (valueA !== valueB) {
  27918. return valueB - valueA;
  27919. }
  27920. }
  27921. if (a.uri === b.uri && a.codecSet !== b.codecSet) {
  27922. const valueA = codecsSetSelectionPreferenceValue(a.codecSet);
  27923. const valueB = codecsSetSelectionPreferenceValue(b.codecSet);
  27924. if (valueA !== valueB) {
  27925. return valueB - valueA;
  27926. }
  27927. }
  27928. if (a.averageBitrate !== b.averageBitrate) {
  27929. return a.averageBitrate - b.averageBitrate;
  27930. }
  27931. return 0;
  27932. });
  27933. let firstLevelInPlaylist = unsortedLevels[0];
  27934. if (this.steering) {
  27935. levels = this.steering.filterParsedLevels(levels);
  27936. if (levels.length !== unsortedLevels.length) {
  27937. for (let i = 0; i < unsortedLevels.length; i++) {
  27938. if (unsortedLevels[i].pathwayId === levels[0].pathwayId) {
  27939. firstLevelInPlaylist = unsortedLevels[i];
  27940. break;
  27941. }
  27942. }
  27943. }
  27944. }
  27945. this._levels = levels;
  27946. for (let i = 0; i < levels.length; i++) {
  27947. if (levels[i] === firstLevelInPlaylist) {
  27948. var _this$hls$userConfig;
  27949. this._firstLevel = i;
  27950. const firstLevelBitrate = firstLevelInPlaylist.bitrate;
  27951. const bandwidthEstimate = this.hls.bandwidthEstimate;
  27952. this.log(`manifest loaded, ${levels.length} level(s) found, first bitrate: ${firstLevelBitrate}`);
  27953. if (((_this$hls$userConfig = this.hls.userConfig) == null ? void 0 : _this$hls$userConfig.abrEwmaDefaultEstimate) === void 0) {
  27954. const startingBwEstimate = Math.min(firstLevelBitrate, this.hls.config.abrEwmaDefaultEstimateMax);
  27955. if (startingBwEstimate > bandwidthEstimate && bandwidthEstimate === this.hls.abrEwmaDefaultEstimate) {
  27956. this.hls.bandwidthEstimate = startingBwEstimate;
  27957. }
  27958. }
  27959. break;
  27960. }
  27961. }
  27962. const audioOnly = audioCodecFound && !videoCodecFound;
  27963. const config = this.hls.config;
  27964. const altAudioEnabled = !!(config.audioStreamController && config.audioTrackController);
  27965. const edata = {
  27966. levels,
  27967. audioTracks,
  27968. subtitleTracks,
  27969. sessionData: data.sessionData,
  27970. sessionKeys: data.sessionKeys,
  27971. firstLevel: this._firstLevel,
  27972. stats: data.stats,
  27973. audio: audioCodecFound,
  27974. video: videoCodecFound,
  27975. altAudio: altAudioEnabled && !audioOnly && audioTracks.some((t) => !!t.url)
  27976. };
  27977. this.hls.trigger(Events.MANIFEST_PARSED, edata);
  27978. }
  27979. get levels() {
  27980. if (this._levels.length === 0) {
  27981. return null;
  27982. }
  27983. return this._levels;
  27984. }
  27985. get loadLevelObj() {
  27986. return this.currentLevel;
  27987. }
  27988. get level() {
  27989. return this.currentLevelIndex;
  27990. }
  27991. set level(newLevel) {
  27992. const levels = this._levels;
  27993. if (levels.length === 0) {
  27994. return;
  27995. }
  27996. if (newLevel < 0 || newLevel >= levels.length) {
  27997. const error = new Error("invalid level idx");
  27998. const fatal = newLevel < 0;
  27999. this.hls.trigger(Events.ERROR, {
  28000. type: ErrorTypes.OTHER_ERROR,
  28001. details: ErrorDetails.LEVEL_SWITCH_ERROR,
  28002. level: newLevel,
  28003. fatal,
  28004. error,
  28005. reason: error.message
  28006. });
  28007. if (fatal) {
  28008. return;
  28009. }
  28010. newLevel = Math.min(newLevel, levels.length - 1);
  28011. }
  28012. const lastLevelIndex = this.currentLevelIndex;
  28013. const lastLevel = this.currentLevel;
  28014. const lastPathwayId = lastLevel ? lastLevel.attrs["PATHWAY-ID"] : void 0;
  28015. const level = levels[newLevel];
  28016. const pathwayId = level.attrs["PATHWAY-ID"];
  28017. this.currentLevelIndex = newLevel;
  28018. this.currentLevel = level;
  28019. if (lastLevelIndex === newLevel && lastLevel && lastPathwayId === pathwayId) {
  28020. return;
  28021. }
  28022. 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 : ""}`);
  28023. const levelSwitchingData = {
  28024. level: newLevel,
  28025. attrs: level.attrs,
  28026. details: level.details,
  28027. bitrate: level.bitrate,
  28028. averageBitrate: level.averageBitrate,
  28029. maxBitrate: level.maxBitrate,
  28030. realBitrate: level.realBitrate,
  28031. width: level.width,
  28032. height: level.height,
  28033. codecSet: level.codecSet,
  28034. audioCodec: level.audioCodec,
  28035. videoCodec: level.videoCodec,
  28036. audioGroups: level.audioGroups,
  28037. subtitleGroups: level.subtitleGroups,
  28038. loaded: level.loaded,
  28039. loadError: level.loadError,
  28040. fragmentError: level.fragmentError,
  28041. name: level.name,
  28042. id: level.id,
  28043. uri: level.uri,
  28044. url: level.url,
  28045. urlId: 0,
  28046. audioGroupIds: level.audioGroupIds,
  28047. textGroupIds: level.textGroupIds
  28048. };
  28049. this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);
  28050. const levelDetails = level.details;
  28051. if (!levelDetails || levelDetails.live) {
  28052. const hlsUrlParameters = this.switchParams(level.uri, lastLevel == null ? void 0 : lastLevel.details, levelDetails);
  28053. this.loadPlaylist(hlsUrlParameters);
  28054. }
  28055. }
  28056. get manualLevel() {
  28057. return this.manualLevelIndex;
  28058. }
  28059. set manualLevel(newLevel) {
  28060. this.manualLevelIndex = newLevel;
  28061. if (this._startLevel === void 0) {
  28062. this._startLevel = newLevel;
  28063. }
  28064. if (newLevel !== -1) {
  28065. this.level = newLevel;
  28066. }
  28067. }
  28068. get firstLevel() {
  28069. return this._firstLevel;
  28070. }
  28071. set firstLevel(newLevel) {
  28072. this._firstLevel = newLevel;
  28073. }
  28074. get startLevel() {
  28075. if (this._startLevel === void 0) {
  28076. const configStartLevel = this.hls.config.startLevel;
  28077. if (configStartLevel !== void 0) {
  28078. return configStartLevel;
  28079. }
  28080. return this.hls.firstAutoLevel;
  28081. }
  28082. return this._startLevel;
  28083. }
  28084. set startLevel(newLevel) {
  28085. this._startLevel = newLevel;
  28086. }
  28087. get pathways() {
  28088. if (this.steering) {
  28089. return this.steering.pathways();
  28090. }
  28091. return [];
  28092. }
  28093. get pathwayPriority() {
  28094. if (this.steering) {
  28095. return this.steering.pathwayPriority;
  28096. }
  28097. return null;
  28098. }
  28099. set pathwayPriority(pathwayPriority) {
  28100. if (this.steering) {
  28101. const pathwaysList = this.steering.pathways();
  28102. const filteredPathwayPriority = pathwayPriority.filter((pathwayId) => {
  28103. return pathwaysList.indexOf(pathwayId) !== -1;
  28104. });
  28105. if (pathwayPriority.length < 1) {
  28106. this.warn(`pathwayPriority ${pathwayPriority} should contain at least one pathway from list: ${pathwaysList}`);
  28107. return;
  28108. }
  28109. this.steering.pathwayPriority = filteredPathwayPriority;
  28110. }
  28111. }
  28112. onError(event, data) {
  28113. if (data.fatal || !data.context) {
  28114. return;
  28115. }
  28116. if (data.context.type === PlaylistContextType.LEVEL && data.context.level === this.level) {
  28117. this.checkRetry(data);
  28118. }
  28119. }
  28120. onFragBuffered(event, {
  28121. frag
  28122. }) {
  28123. if (frag !== void 0 && frag.type === PlaylistLevelType.MAIN) {
  28124. const el = frag.elementaryStreams;
  28125. if (!Object.keys(el).some((type) => !!el[type])) {
  28126. return;
  28127. }
  28128. const level = this._levels[frag.level];
  28129. if (level != null && level.loadError) {
  28130. this.log(`Resetting level error count of ${level.loadError} on frag buffered`);
  28131. level.loadError = 0;
  28132. }
  28133. }
  28134. }
  28135. onLevelLoaded(event, data) {
  28136. var _data$deliveryDirecti2;
  28137. const {
  28138. level,
  28139. details
  28140. } = data;
  28141. const curLevel = data.levelInfo;
  28142. if (!curLevel) {
  28143. var _data$deliveryDirecti;
  28144. this.warn(`Invalid level index ${level}`);
  28145. if ((_data$deliveryDirecti = data.deliveryDirectives) != null && _data$deliveryDirecti.skip) {
  28146. details.deltaUpdateFailed = true;
  28147. }
  28148. return;
  28149. }
  28150. if (curLevel === this.currentLevel || data.withoutMultiVariant) {
  28151. if (curLevel.fragmentError === 0) {
  28152. curLevel.loadError = 0;
  28153. }
  28154. let previousDetails = curLevel.details;
  28155. if (previousDetails === data.details && previousDetails.advanced) {
  28156. previousDetails = void 0;
  28157. }
  28158. this.playlistLoaded(level, data, previousDetails);
  28159. } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) != null && _data$deliveryDirecti2.skip) {
  28160. details.deltaUpdateFailed = true;
  28161. }
  28162. }
  28163. loadPlaylist(hlsUrlParameters) {
  28164. super.loadPlaylist();
  28165. if (this.shouldLoadPlaylist(this.currentLevel)) {
  28166. this.scheduleLoading(this.currentLevel, hlsUrlParameters);
  28167. }
  28168. }
  28169. loadingPlaylist(currentLevel, hlsUrlParameters) {
  28170. super.loadingPlaylist(currentLevel, hlsUrlParameters);
  28171. const url = this.getUrlWithDirectives(currentLevel.uri, hlsUrlParameters);
  28172. const currentLevelIndex = this.currentLevelIndex;
  28173. const pathwayId = currentLevel.attrs["PATHWAY-ID"];
  28174. const details = currentLevel.details;
  28175. const age = details == null ? void 0 : details.age;
  28176. 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}`);
  28177. this.hls.trigger(Events.LEVEL_LOADING, {
  28178. url,
  28179. level: currentLevelIndex,
  28180. levelInfo: currentLevel,
  28181. pathwayId: currentLevel.attrs["PATHWAY-ID"],
  28182. id: 0,
  28183. deliveryDirectives: hlsUrlParameters || null
  28184. });
  28185. }
  28186. get nextLoadLevel() {
  28187. if (this.manualLevelIndex !== -1) {
  28188. return this.manualLevelIndex;
  28189. } else {
  28190. return this.hls.nextAutoLevel;
  28191. }
  28192. }
  28193. set nextLoadLevel(nextLevel) {
  28194. this.level = nextLevel;
  28195. if (this.manualLevelIndex === -1) {
  28196. this.hls.nextAutoLevel = nextLevel;
  28197. }
  28198. }
  28199. removeLevel(levelIndex) {
  28200. var _this$currentLevel;
  28201. if (this._levels.length === 1) {
  28202. return;
  28203. }
  28204. const levels = this._levels.filter((level, index) => {
  28205. if (index !== levelIndex) {
  28206. return true;
  28207. }
  28208. if (this.steering) {
  28209. this.steering.removeLevel(level);
  28210. }
  28211. if (level === this.currentLevel) {
  28212. this.currentLevel = null;
  28213. this.currentLevelIndex = -1;
  28214. if (level.details) {
  28215. level.details.fragments.forEach((f) => f.level = -1);
  28216. }
  28217. }
  28218. return false;
  28219. });
  28220. reassignFragmentLevelIndexes(levels);
  28221. this._levels = levels;
  28222. if (this.currentLevelIndex > -1 && (_this$currentLevel = this.currentLevel) != null && _this$currentLevel.details) {
  28223. this.currentLevelIndex = this.currentLevel.details.fragments[0].level;
  28224. }
  28225. if (this.manualLevelIndex > -1) {
  28226. this.manualLevelIndex = this.currentLevelIndex;
  28227. }
  28228. const maxLevel = levels.length - 1;
  28229. this._firstLevel = Math.min(this._firstLevel, maxLevel);
  28230. if (this._startLevel) {
  28231. this._startLevel = Math.min(this._startLevel, maxLevel);
  28232. }
  28233. this.hls.trigger(Events.LEVELS_UPDATED, {
  28234. levels
  28235. });
  28236. }
  28237. onLevelsUpdated(event, {
  28238. levels
  28239. }) {
  28240. this._levels = levels;
  28241. }
  28242. checkMaxAutoUpdated() {
  28243. const {
  28244. autoLevelCapping,
  28245. maxAutoLevel,
  28246. maxHdcpLevel
  28247. } = this.hls;
  28248. if (this._maxAutoLevel !== maxAutoLevel) {
  28249. this._maxAutoLevel = maxAutoLevel;
  28250. this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {
  28251. autoLevelCapping,
  28252. levels: this.levels,
  28253. maxAutoLevel,
  28254. minAutoLevel: this.hls.minAutoLevel,
  28255. maxHdcpLevel
  28256. });
  28257. }
  28258. }
  28259. };
  28260. function assignTrackIdsByGroup(tracks) {
  28261. const groups = {};
  28262. tracks.forEach((track) => {
  28263. const groupId = track.groupId || "";
  28264. track.id = groups[groupId] = groups[groupId] || 0;
  28265. groups[groupId]++;
  28266. });
  28267. }
  28268. function getSourceBuffer() {
  28269. return self.SourceBuffer || self.WebKitSourceBuffer;
  28270. }
  28271. function isMSESupported() {
  28272. const mediaSource = getMediaSource();
  28273. if (!mediaSource) {
  28274. return false;
  28275. }
  28276. const sourceBuffer = getSourceBuffer();
  28277. return !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === "function" && typeof sourceBuffer.prototype.remove === "function";
  28278. }
  28279. function isSupported() {
  28280. if (!isMSESupported()) {
  28281. return false;
  28282. }
  28283. const mediaSource = getMediaSource();
  28284. 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"))));
  28285. }
  28286. function changeTypeSupported() {
  28287. var _sourceBuffer$prototy;
  28288. const sourceBuffer = getSourceBuffer();
  28289. return typeof (sourceBuffer == null ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) == null ? void 0 : _sourceBuffer$prototy.changeType) === "function";
  28290. }
  28291. var TICK_INTERVAL = 100;
  28292. var StreamController = class extends BaseStreamController {
  28293. constructor(hls, fragmentTracker, keyLoader) {
  28294. super(hls, fragmentTracker, keyLoader, "stream-controller", PlaylistLevelType.MAIN);
  28295. this.audioCodecSwap = false;
  28296. this.level = -1;
  28297. this._forceStartLoad = false;
  28298. this._hasEnoughToStart = false;
  28299. this.altAudio = 0;
  28300. this.audioOnly = false;
  28301. this.fragPlaying = null;
  28302. this.fragLastKbps = 0;
  28303. this.couldBacktrack = false;
  28304. this.backtrackFragment = null;
  28305. this.audioCodecSwitch = false;
  28306. this.videoBuffer = null;
  28307. this.onMediaPlaying = () => {
  28308. this.tick();
  28309. };
  28310. this.onMediaSeeked = () => {
  28311. const media = this.media;
  28312. const currentTime = media ? media.currentTime : null;
  28313. if (currentTime === null || !isFiniteNumber(currentTime)) {
  28314. return;
  28315. }
  28316. this.log(`Media seeked to ${currentTime.toFixed(3)}`);
  28317. if (!this.getBufferedFrag(currentTime)) {
  28318. return;
  28319. }
  28320. const bufferInfo = this.getFwdBufferInfoAtPos(media, currentTime, PlaylistLevelType.MAIN, 0);
  28321. if (bufferInfo === null || bufferInfo.len === 0) {
  28322. this.warn(`Main forward buffer length at ${currentTime} on "seeked" event ${bufferInfo ? bufferInfo.len : "empty"})`);
  28323. return;
  28324. }
  28325. this.tick();
  28326. };
  28327. this.registerListeners();
  28328. }
  28329. registerListeners() {
  28330. super.registerListeners();
  28331. const {
  28332. hls
  28333. } = this;
  28334. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  28335. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  28336. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  28337. hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  28338. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  28339. hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  28340. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  28341. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  28342. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  28343. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  28344. }
  28345. unregisterListeners() {
  28346. super.unregisterListeners();
  28347. const {
  28348. hls
  28349. } = this;
  28350. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  28351. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  28352. hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  28353. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  28354. hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  28355. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  28356. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  28357. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  28358. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  28359. }
  28360. onHandlerDestroying() {
  28361. this.onMediaPlaying = this.onMediaSeeked = null;
  28362. this.unregisterListeners();
  28363. super.onHandlerDestroying();
  28364. }
  28365. startLoad(startPosition, skipSeekToStartPosition) {
  28366. if (this.levels) {
  28367. const {
  28368. lastCurrentTime,
  28369. hls
  28370. } = this;
  28371. this.stopLoad();
  28372. this.setInterval(TICK_INTERVAL);
  28373. this.level = -1;
  28374. if (!this.startFragRequested) {
  28375. let startLevel = hls.startLevel;
  28376. if (startLevel === -1) {
  28377. if (hls.config.testBandwidth && this.levels.length > 1) {
  28378. startLevel = 0;
  28379. this.bitrateTest = true;
  28380. } else {
  28381. startLevel = hls.firstAutoLevel;
  28382. }
  28383. }
  28384. hls.nextLoadLevel = startLevel;
  28385. this.level = hls.loadLevel;
  28386. this._hasEnoughToStart = !!skipSeekToStartPosition;
  28387. }
  28388. if (lastCurrentTime > 0 && startPosition === -1 && !skipSeekToStartPosition) {
  28389. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  28390. startPosition = lastCurrentTime;
  28391. }
  28392. this.state = State.IDLE;
  28393. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  28394. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  28395. this.tick();
  28396. } else {
  28397. this._forceStartLoad = true;
  28398. this.state = State.STOPPED;
  28399. }
  28400. }
  28401. stopLoad() {
  28402. this._forceStartLoad = false;
  28403. super.stopLoad();
  28404. }
  28405. doTick() {
  28406. switch (this.state) {
  28407. case State.WAITING_LEVEL: {
  28408. const {
  28409. levels,
  28410. level
  28411. } = this;
  28412. const currentLevel = levels == null ? void 0 : levels[level];
  28413. const details = currentLevel == null ? void 0 : currentLevel.details;
  28414. if (details && (!details.live || this.levelLastLoaded === currentLevel && !this.waitForLive(currentLevel))) {
  28415. if (this.waitForCdnTuneIn(details)) {
  28416. break;
  28417. }
  28418. this.state = State.IDLE;
  28419. break;
  28420. } else if (this.hls.nextLoadLevel !== this.level) {
  28421. this.state = State.IDLE;
  28422. break;
  28423. }
  28424. break;
  28425. }
  28426. case State.FRAG_LOADING_WAITING_RETRY:
  28427. {
  28428. var _this$media;
  28429. const now2 = self.performance.now();
  28430. const retryDate = this.retryDate;
  28431. if (!retryDate || now2 >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  28432. const {
  28433. levels,
  28434. level
  28435. } = this;
  28436. const currentLevel = levels == null ? void 0 : levels[level];
  28437. this.resetStartWhenNotLoaded(currentLevel || null);
  28438. this.state = State.IDLE;
  28439. }
  28440. }
  28441. break;
  28442. }
  28443. if (this.state === State.IDLE) {
  28444. this.doTickIdle();
  28445. }
  28446. this.onTickEnd();
  28447. }
  28448. onTickEnd() {
  28449. var _this$media2;
  28450. super.onTickEnd();
  28451. if ((_this$media2 = this.media) != null && _this$media2.readyState && this.media.seeking === false) {
  28452. this.lastCurrentTime = this.media.currentTime;
  28453. }
  28454. this.checkFragmentChanged();
  28455. }
  28456. doTickIdle() {
  28457. const {
  28458. hls,
  28459. levelLastLoaded,
  28460. levels,
  28461. media
  28462. } = this;
  28463. if (levelLastLoaded === null || !media && !this.primaryPrefetch && (this.startFragRequested || !hls.config.startFragPrefetch)) {
  28464. return;
  28465. }
  28466. if (this.altAudio && this.audioOnly) {
  28467. return;
  28468. }
  28469. const level = this.buffering ? hls.nextLoadLevel : hls.loadLevel;
  28470. if (!(levels != null && levels[level])) {
  28471. return;
  28472. }
  28473. const levelInfo = levels[level];
  28474. const bufferInfo = this.getMainFwdBufferInfo();
  28475. if (bufferInfo === null) {
  28476. return;
  28477. }
  28478. const lastDetails = this.getLevelDetails();
  28479. if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {
  28480. const data = {};
  28481. if (this.altAudio === 2) {
  28482. data.type = "video";
  28483. }
  28484. this.hls.trigger(Events.BUFFER_EOS, data);
  28485. this.state = State.ENDED;
  28486. return;
  28487. }
  28488. if (!this.buffering) {
  28489. return;
  28490. }
  28491. if (hls.loadLevel !== level && hls.manualLevel === -1) {
  28492. this.log(`Adapting to level ${level} from level ${this.level}`);
  28493. }
  28494. this.level = hls.nextLoadLevel = level;
  28495. const levelDetails = levelInfo.details;
  28496. if (!levelDetails || this.state === State.WAITING_LEVEL || this.waitForLive(levelInfo)) {
  28497. this.level = level;
  28498. this.state = State.WAITING_LEVEL;
  28499. this.startFragRequested = false;
  28500. return;
  28501. }
  28502. const bufferLen = bufferInfo.len;
  28503. const maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);
  28504. if (bufferLen >= maxBufLen) {
  28505. return;
  28506. }
  28507. if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) {
  28508. this.backtrackFragment = null;
  28509. }
  28510. const targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end;
  28511. let frag = this.getNextFragment(targetBufferTime, levelDetails);
  28512. if (this.couldBacktrack && !this.fragPrevious && frag && isMediaFragment(frag) && this.fragmentTracker.getState(frag) !== FragmentState.OK) {
  28513. var _this$backtrackFragme;
  28514. const backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn;
  28515. const fragIdx = backtrackSn - levelDetails.startSN;
  28516. const backtrackFrag = levelDetails.fragments[fragIdx - 1];
  28517. if (backtrackFrag && frag.cc === backtrackFrag.cc) {
  28518. frag = backtrackFrag;
  28519. this.fragmentTracker.removeFragment(backtrackFrag);
  28520. }
  28521. } else if (this.backtrackFragment && bufferInfo.len) {
  28522. this.backtrackFragment = null;
  28523. }
  28524. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  28525. const gapStart = frag.gap;
  28526. if (!gapStart) {
  28527. const type = this.audioOnly && !this.altAudio ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
  28528. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  28529. if (mediaBuffer) {
  28530. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  28531. }
  28532. }
  28533. frag = this.getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  28534. }
  28535. if (!frag) {
  28536. return;
  28537. }
  28538. if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
  28539. frag = frag.initSegment;
  28540. }
  28541. this.loadFragment(frag, levelInfo, targetBufferTime);
  28542. }
  28543. loadFragment(frag, level, targetBufferTime) {
  28544. const fragState = this.fragmentTracker.getState(frag);
  28545. if (fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  28546. if (!isMediaFragment(frag)) {
  28547. this._loadInitSegment(frag, level);
  28548. } else if (this.bitrateTest) {
  28549. this.log(`Fragment ${frag.sn} of level ${frag.level} is being downloaded to test bitrate and will not be buffered`);
  28550. this._loadBitrateTestFrag(frag, level);
  28551. } else {
  28552. super.loadFragment(frag, level, targetBufferTime);
  28553. }
  28554. } else {
  28555. this.clearTrackerIfNeeded(frag);
  28556. }
  28557. }
  28558. getBufferedFrag(position) {
  28559. return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
  28560. }
  28561. followingBufferedFrag(frag) {
  28562. if (frag) {
  28563. return this.getBufferedFrag(frag.end + 0.5);
  28564. }
  28565. return null;
  28566. }
  28567. immediateLevelSwitch() {
  28568. this.abortCurrentFrag();
  28569. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  28570. }
  28571. nextLevelSwitch() {
  28572. const {
  28573. levels,
  28574. media
  28575. } = this;
  28576. if (media != null && media.readyState) {
  28577. let fetchdelay;
  28578. const fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
  28579. if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
  28580. this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
  28581. }
  28582. const levelDetails = this.getLevelDetails();
  28583. if (levelDetails != null && levelDetails.live) {
  28584. const bufferInfo = this.getMainFwdBufferInfo();
  28585. if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {
  28586. return;
  28587. }
  28588. }
  28589. if (!media.paused && levels) {
  28590. const nextLevelId = this.hls.nextLoadLevel;
  28591. const nextLevel = levels[nextLevelId];
  28592. const fragLastKbps = this.fragLastKbps;
  28593. if (fragLastKbps && this.fragCurrent) {
  28594. fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1e3 * fragLastKbps) + 1;
  28595. } else {
  28596. fetchdelay = 0;
  28597. }
  28598. } else {
  28599. fetchdelay = 0;
  28600. }
  28601. const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  28602. if (bufferedFrag) {
  28603. const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
  28604. if (nextBufferedFrag) {
  28605. this.abortCurrentFrag();
  28606. const maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
  28607. const fragDuration = nextBufferedFrag.duration;
  28608. 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)));
  28609. this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
  28610. }
  28611. }
  28612. }
  28613. }
  28614. abortCurrentFrag() {
  28615. const fragCurrent = this.fragCurrent;
  28616. this.fragCurrent = null;
  28617. this.backtrackFragment = null;
  28618. if (fragCurrent) {
  28619. fragCurrent.abortRequests();
  28620. this.fragmentTracker.removeFragment(fragCurrent);
  28621. }
  28622. switch (this.state) {
  28623. case State.KEY_LOADING:
  28624. case State.FRAG_LOADING:
  28625. case State.FRAG_LOADING_WAITING_RETRY:
  28626. case State.PARSING:
  28627. case State.PARSED:
  28628. this.state = State.IDLE;
  28629. break;
  28630. }
  28631. this.nextLoadPosition = this.getLoadPosition();
  28632. }
  28633. flushMainBuffer(startOffset, endOffset) {
  28634. super.flushMainBuffer(startOffset, endOffset, this.altAudio === 2 ? "video" : null);
  28635. }
  28636. onMediaAttached(event, data) {
  28637. super.onMediaAttached(event, data);
  28638. const media = data.media;
  28639. addEventListener(media, "playing", this.onMediaPlaying);
  28640. addEventListener(media, "seeked", this.onMediaSeeked);
  28641. }
  28642. onMediaDetaching(event, data) {
  28643. const {
  28644. media
  28645. } = this;
  28646. if (media) {
  28647. removeEventListener(media, "playing", this.onMediaPlaying);
  28648. removeEventListener(media, "seeked", this.onMediaSeeked);
  28649. }
  28650. this.videoBuffer = null;
  28651. this.fragPlaying = null;
  28652. super.onMediaDetaching(event, data);
  28653. const transferringMedia = !!data.transferMedia;
  28654. if (transferringMedia) {
  28655. return;
  28656. }
  28657. this._hasEnoughToStart = false;
  28658. }
  28659. onManifestLoading() {
  28660. super.onManifestLoading();
  28661. this.log("Trigger BUFFER_RESET");
  28662. this.hls.trigger(Events.BUFFER_RESET, void 0);
  28663. this.couldBacktrack = false;
  28664. this.fragLastKbps = 0;
  28665. this.fragPlaying = this.backtrackFragment = null;
  28666. this.altAudio = 0;
  28667. this.audioOnly = false;
  28668. }
  28669. onManifestParsed(event, data) {
  28670. let aac = false;
  28671. let heaac = false;
  28672. data.levels.forEach((level) => {
  28673. const codec = level.audioCodec;
  28674. if (codec) {
  28675. aac = aac || codec.indexOf("mp4a.40.2") !== -1;
  28676. heaac = heaac || codec.indexOf("mp4a.40.5") !== -1;
  28677. }
  28678. });
  28679. this.audioCodecSwitch = aac && heaac && !changeTypeSupported();
  28680. if (this.audioCodecSwitch) {
  28681. this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC");
  28682. }
  28683. this.levels = data.levels;
  28684. this.startFragRequested = false;
  28685. }
  28686. onLevelLoading(event, data) {
  28687. const {
  28688. levels
  28689. } = this;
  28690. if (!levels || this.state !== State.IDLE) {
  28691. return;
  28692. }
  28693. const level = data.levelInfo;
  28694. if (!level.details || level.details.live && (this.levelLastLoaded !== level || level.details.expired) || this.waitForCdnTuneIn(level.details)) {
  28695. this.state = State.WAITING_LEVEL;
  28696. }
  28697. }
  28698. onLevelLoaded(event, data) {
  28699. var _curLevel$details;
  28700. const {
  28701. levels,
  28702. startFragRequested
  28703. } = this;
  28704. const newLevelId = data.level;
  28705. const newDetails = data.details;
  28706. const duration = newDetails.totalduration;
  28707. if (!levels) {
  28708. this.warn(`Levels were reset while loading level ${newLevelId}`);
  28709. return;
  28710. }
  28711. this.log(`Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""}, cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration}`);
  28712. const curLevel = data.levelInfo;
  28713. const fragCurrent = this.fragCurrent;
  28714. if (fragCurrent && (this.state === State.FRAG_LOADING || this.state === State.FRAG_LOADING_WAITING_RETRY)) {
  28715. if (fragCurrent.level !== data.level && fragCurrent.loader) {
  28716. this.abortCurrentFrag();
  28717. }
  28718. }
  28719. let sliding = 0;
  28720. if (newDetails.live || (_curLevel$details = curLevel.details) != null && _curLevel$details.live) {
  28721. var _this$levelLastLoaded;
  28722. this.checkLiveUpdate(newDetails);
  28723. if (newDetails.deltaUpdateFailed) {
  28724. return;
  28725. }
  28726. sliding = this.alignPlaylists(newDetails, curLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  28727. }
  28728. curLevel.details = newDetails;
  28729. this.levelLastLoaded = curLevel;
  28730. if (!startFragRequested) {
  28731. this.setStartPosition(newDetails, sliding);
  28732. }
  28733. this.hls.trigger(Events.LEVEL_UPDATED, {
  28734. details: newDetails,
  28735. level: newLevelId
  28736. });
  28737. if (this.state === State.WAITING_LEVEL) {
  28738. if (this.waitForCdnTuneIn(newDetails)) {
  28739. return;
  28740. }
  28741. this.state = State.IDLE;
  28742. }
  28743. if (startFragRequested && newDetails.live) {
  28744. this.synchronizeToLiveEdge(newDetails);
  28745. }
  28746. this.tick();
  28747. }
  28748. synchronizeToLiveEdge(levelDetails) {
  28749. const {
  28750. config,
  28751. media
  28752. } = this;
  28753. if (!media) {
  28754. return;
  28755. }
  28756. const liveSyncPosition = this.hls.liveSyncPosition;
  28757. const currentTime = this.getLoadPosition();
  28758. const start = levelDetails.fragmentStart;
  28759. const end = levelDetails.edge;
  28760. const withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end;
  28761. if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
  28762. const maxLatency = config.liveMaxLatencyDuration !== void 0 ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  28763. if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
  28764. if (!this._hasEnoughToStart) {
  28765. this.nextLoadPosition = liveSyncPosition;
  28766. }
  28767. if (media.readyState) {
  28768. this.warn(`Playback: ${currentTime.toFixed(3)} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);
  28769. if (this.config.liveSyncMode === "buffered") {
  28770. var _bufferInfo$buffered;
  28771. const bufferInfo = BufferHelper.bufferInfo(media, liveSyncPosition, 0);
  28772. if (!(bufferInfo != null && (_bufferInfo$buffered = bufferInfo.buffered) != null && _bufferInfo$buffered.length)) {
  28773. media.currentTime = liveSyncPosition;
  28774. return;
  28775. }
  28776. const isLiveSyncInBuffer = bufferInfo.start <= currentTime;
  28777. if (isLiveSyncInBuffer) {
  28778. media.currentTime = liveSyncPosition;
  28779. return;
  28780. }
  28781. const {
  28782. nextStart
  28783. } = BufferHelper.bufferedInfo(bufferInfo.buffered, currentTime, 0);
  28784. if (nextStart) {
  28785. media.currentTime = nextStart;
  28786. }
  28787. } else {
  28788. media.currentTime = liveSyncPosition;
  28789. }
  28790. }
  28791. }
  28792. }
  28793. }
  28794. _handleFragmentLoadProgress(data) {
  28795. var _frag$initSegment;
  28796. const frag = data.frag;
  28797. const {
  28798. part,
  28799. payload
  28800. } = data;
  28801. const {
  28802. levels
  28803. } = this;
  28804. if (!levels) {
  28805. this.warn(`Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  28806. return;
  28807. }
  28808. const currentLevel = levels[frag.level];
  28809. if (!currentLevel) {
  28810. this.warn(`Level ${frag.level} not found on progress`);
  28811. return;
  28812. }
  28813. const details = currentLevel.details;
  28814. if (!details) {
  28815. this.warn(`Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`);
  28816. this.fragmentTracker.removeFragment(frag);
  28817. return;
  28818. }
  28819. const videoCodec = currentLevel.videoCodec;
  28820. const accurateTimeOffset = details.PTSKnown || !details.live;
  28821. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  28822. const audioCodec = this._getAudioCodec(currentLevel);
  28823. const transmuxer = this.transmuxer = this.transmuxer || new TransmuxerInterface(this.hls, PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  28824. const partIndex = part ? part.index : -1;
  28825. const partial = partIndex !== -1;
  28826. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  28827. const initPTS = this.initPTS[frag.cc];
  28828. transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  28829. }
  28830. onAudioTrackSwitching(event, data) {
  28831. const hls = this.hls;
  28832. const fromAltAudio = this.altAudio === 2;
  28833. const altAudio = useAlternateAudio(data.url, hls);
  28834. if (!altAudio) {
  28835. if (this.mediaBuffer !== this.media) {
  28836. this.log("Switching on main audio, use media.buffered to schedule main fragment loading");
  28837. this.mediaBuffer = this.media;
  28838. const fragCurrent = this.fragCurrent;
  28839. if (fragCurrent) {
  28840. this.log("Switching to main audio track, cancel main fragment load");
  28841. fragCurrent.abortRequests();
  28842. this.fragmentTracker.removeFragment(fragCurrent);
  28843. }
  28844. this.resetTransmuxer();
  28845. this.resetLoadingState();
  28846. } else if (this.audioOnly) {
  28847. this.resetTransmuxer();
  28848. }
  28849. if (fromAltAudio) {
  28850. this.fragmentTracker.removeAllFragments();
  28851. hls.once(Events.BUFFER_FLUSHED, () => {
  28852. var _this$hls;
  28853. (_this$hls = this.hls) == null ? void 0 : _this$hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  28854. });
  28855. hls.trigger(Events.BUFFER_FLUSHING, {
  28856. startOffset: 0,
  28857. endOffset: Number.POSITIVE_INFINITY,
  28858. type: null
  28859. });
  28860. return;
  28861. }
  28862. hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  28863. } else {
  28864. this.altAudio = 1;
  28865. }
  28866. }
  28867. onAudioTrackSwitched(event, data) {
  28868. const altAudio = useAlternateAudio(data.url, this.hls);
  28869. if (altAudio) {
  28870. const videoBuffer = this.videoBuffer;
  28871. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  28872. this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading");
  28873. this.mediaBuffer = videoBuffer;
  28874. }
  28875. }
  28876. this.altAudio = altAudio ? 2 : 0;
  28877. this.tick();
  28878. }
  28879. onBufferCreated(event, data) {
  28880. const tracks = data.tracks;
  28881. let mediaTrack;
  28882. let name;
  28883. let alternate = false;
  28884. for (const type in tracks) {
  28885. const track = tracks[type];
  28886. if (track.id === "main") {
  28887. name = type;
  28888. mediaTrack = track;
  28889. if (type === "video") {
  28890. const videoTrack = tracks[type];
  28891. if (videoTrack) {
  28892. this.videoBuffer = videoTrack.buffer;
  28893. }
  28894. }
  28895. } else {
  28896. alternate = true;
  28897. }
  28898. }
  28899. if (alternate && mediaTrack) {
  28900. this.log(`Alternate track found, use ${name}.buffered to schedule main fragment loading`);
  28901. this.mediaBuffer = mediaTrack.buffer;
  28902. } else {
  28903. this.mediaBuffer = this.media;
  28904. }
  28905. }
  28906. onFragBuffered(event, data) {
  28907. const {
  28908. frag,
  28909. part
  28910. } = data;
  28911. const bufferedMainFragment = frag.type === PlaylistLevelType.MAIN;
  28912. if (bufferedMainFragment) {
  28913. if (this.fragContextChanged(frag)) {
  28914. this.warn(`Fragment ${frag.sn}${part ? " p: " + part.index : ""} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}`);
  28915. if (this.state === State.PARSED) {
  28916. this.state = State.IDLE;
  28917. }
  28918. return;
  28919. }
  28920. const stats = part ? part.stats : frag.stats;
  28921. this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
  28922. if (isMediaFragment(frag)) {
  28923. this.fragPrevious = frag;
  28924. }
  28925. this.fragBufferedComplete(frag, part);
  28926. }
  28927. const media = this.media;
  28928. if (!media) {
  28929. return;
  28930. }
  28931. if (!this._hasEnoughToStart && BufferHelper.getBuffered(media).length) {
  28932. this._hasEnoughToStart = true;
  28933. this.seekToStartPos();
  28934. }
  28935. if (bufferedMainFragment) {
  28936. this.tick();
  28937. }
  28938. }
  28939. get hasEnoughToStart() {
  28940. return this._hasEnoughToStart;
  28941. }
  28942. onError(event, data) {
  28943. var _data$context;
  28944. if (data.fatal) {
  28945. this.state = State.ERROR;
  28946. return;
  28947. }
  28948. switch (data.details) {
  28949. case ErrorDetails.FRAG_GAP:
  28950. case ErrorDetails.FRAG_PARSING_ERROR:
  28951. case ErrorDetails.FRAG_DECRYPT_ERROR:
  28952. case ErrorDetails.FRAG_LOAD_ERROR:
  28953. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  28954. case ErrorDetails.KEY_LOAD_ERROR:
  28955. case ErrorDetails.KEY_LOAD_TIMEOUT:
  28956. this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);
  28957. break;
  28958. case ErrorDetails.LEVEL_LOAD_ERROR:
  28959. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  28960. case ErrorDetails.LEVEL_PARSING_ERROR:
  28961. if (!data.levelRetry && this.state === State.WAITING_LEVEL && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.LEVEL) {
  28962. this.state = State.IDLE;
  28963. }
  28964. break;
  28965. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  28966. case ErrorDetails.BUFFER_APPEND_ERROR:
  28967. if (data.parent !== "main") {
  28968. return;
  28969. }
  28970. if (this.reduceLengthAndFlushBuffer(data)) {
  28971. this.resetLoadingState();
  28972. }
  28973. break;
  28974. case ErrorDetails.BUFFER_FULL_ERROR:
  28975. if (data.parent !== "main") {
  28976. return;
  28977. }
  28978. if (this.reduceLengthAndFlushBuffer(data)) {
  28979. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  28980. }
  28981. break;
  28982. case ErrorDetails.INTERNAL_EXCEPTION:
  28983. this.recoverWorkerError(data);
  28984. break;
  28985. }
  28986. }
  28987. onFragLoadEmergencyAborted() {
  28988. this.state = State.IDLE;
  28989. if (!this._hasEnoughToStart) {
  28990. this.startFragRequested = false;
  28991. this.nextLoadPosition = this.lastCurrentTime;
  28992. }
  28993. this.tickImmediate();
  28994. }
  28995. onBufferFlushed(event, {
  28996. type
  28997. }) {
  28998. if (type !== ElementaryStreamTypes.AUDIO || !this.altAudio) {
  28999. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  29000. if (mediaBuffer) {
  29001. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  29002. this.tick();
  29003. }
  29004. }
  29005. }
  29006. onLevelsUpdated(event, data) {
  29007. if (this.level > -1 && this.fragCurrent) {
  29008. this.level = this.fragCurrent.level;
  29009. if (this.level === -1) {
  29010. this.resetWhenMissingContext(this.fragCurrent);
  29011. }
  29012. }
  29013. this.levels = data.levels;
  29014. }
  29015. swapAudioCodec() {
  29016. this.audioCodecSwap = !this.audioCodecSwap;
  29017. }
  29018. seekToStartPos() {
  29019. const {
  29020. media
  29021. } = this;
  29022. if (!media) {
  29023. return;
  29024. }
  29025. const currentTime = media.currentTime;
  29026. let startPosition = this.startPosition;
  29027. if (startPosition >= 0 && currentTime < startPosition) {
  29028. if (media.seeking) {
  29029. this.log(`could not seek to ${startPosition}, already seeking at ${currentTime}`);
  29030. return;
  29031. }
  29032. const timelineOffset = this.timelineOffset;
  29033. if (timelineOffset && startPosition) {
  29034. startPosition += timelineOffset;
  29035. }
  29036. const details = this.getLevelDetails();
  29037. const buffered = BufferHelper.getBuffered(media);
  29038. const bufferStart = buffered.length ? buffered.start(0) : 0;
  29039. const delta = bufferStart - startPosition;
  29040. const skipTolerance = Math.max(this.config.maxBufferHole, this.config.maxFragLookUpTolerance);
  29041. if (this.config.startOnSegmentBoundary || delta > 0 && (delta < skipTolerance || this.loadingParts && delta < 2 * ((details == null ? void 0 : details.partTarget) || 0))) {
  29042. this.log(`adjusting start position by ${delta} to match buffer start`);
  29043. startPosition += delta;
  29044. this.startPosition = startPosition;
  29045. }
  29046. if (currentTime < startPosition) {
  29047. this.log(`seek to target start position ${startPosition} from current time ${currentTime} buffer start ${bufferStart}`);
  29048. media.currentTime = startPosition;
  29049. }
  29050. }
  29051. }
  29052. _getAudioCodec(currentLevel) {
  29053. let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  29054. if (this.audioCodecSwap && audioCodec) {
  29055. this.log("Swapping audio codec");
  29056. if (audioCodec.indexOf("mp4a.40.5") !== -1) {
  29057. audioCodec = "mp4a.40.2";
  29058. } else {
  29059. audioCodec = "mp4a.40.5";
  29060. }
  29061. }
  29062. return audioCodec;
  29063. }
  29064. _loadBitrateTestFrag(fragment, level) {
  29065. fragment.bitrateTest = true;
  29066. this._doFragLoad(fragment, level).then((data) => {
  29067. const {
  29068. hls
  29069. } = this;
  29070. const frag = data == null ? void 0 : data.frag;
  29071. if (!frag || this.fragContextChanged(frag)) {
  29072. return;
  29073. }
  29074. level.fragmentError = 0;
  29075. this.state = State.IDLE;
  29076. this.startFragRequested = false;
  29077. this.bitrateTest = false;
  29078. const stats = frag.stats;
  29079. stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
  29080. hls.trigger(Events.FRAG_LOADED, data);
  29081. frag.bitrateTest = false;
  29082. });
  29083. }
  29084. _handleTransmuxComplete(transmuxResult) {
  29085. var _id3$samples;
  29086. const id = this.playlistType;
  29087. const {
  29088. hls
  29089. } = this;
  29090. const {
  29091. remuxResult,
  29092. chunkMeta
  29093. } = transmuxResult;
  29094. const context = this.getCurrentContext(chunkMeta);
  29095. if (!context) {
  29096. this.resetWhenMissingContext(chunkMeta);
  29097. return;
  29098. }
  29099. const {
  29100. frag,
  29101. part,
  29102. level
  29103. } = context;
  29104. const {
  29105. video,
  29106. text,
  29107. id3,
  29108. initSegment
  29109. } = remuxResult;
  29110. const {
  29111. details
  29112. } = level;
  29113. const audio = this.altAudio ? void 0 : remuxResult.audio;
  29114. if (this.fragContextChanged(frag)) {
  29115. this.fragmentTracker.removeFragment(frag);
  29116. return;
  29117. }
  29118. this.state = State.PARSING;
  29119. if (initSegment) {
  29120. if (initSegment != null && initSegment.tracks) {
  29121. const mapFragment = frag.initSegment || frag;
  29122. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  29123. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  29124. frag: mapFragment,
  29125. id,
  29126. tracks: initSegment.tracks
  29127. });
  29128. }
  29129. const baseTime = initSegment.initPTS;
  29130. const timescale = initSegment.timescale;
  29131. const initPTS = this.initPTS[frag.cc];
  29132. if (isFiniteNumber(baseTime) && (!initPTS || initPTS.baseTime !== baseTime || initPTS.timescale !== timescale)) {
  29133. this.initPTS[frag.cc] = {
  29134. baseTime,
  29135. timescale
  29136. };
  29137. hls.trigger(Events.INIT_PTS_FOUND, {
  29138. frag,
  29139. id,
  29140. initPTS: baseTime,
  29141. timescale
  29142. });
  29143. }
  29144. }
  29145. if (video && details) {
  29146. if (audio && video.type === "audiovideo") {
  29147. this.logMuxedErr(frag);
  29148. }
  29149. const prevFrag = details.fragments[frag.sn - 1 - details.startSN];
  29150. const isFirstFragment = frag.sn === details.startSN;
  29151. const isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;
  29152. if (remuxResult.independent !== false) {
  29153. const {
  29154. startPTS,
  29155. endPTS,
  29156. startDTS,
  29157. endDTS
  29158. } = video;
  29159. if (part) {
  29160. part.elementaryStreams[video.type] = {
  29161. startPTS,
  29162. endPTS,
  29163. startDTS,
  29164. endDTS
  29165. };
  29166. } else {
  29167. if (video.firstKeyFrame && video.independent && chunkMeta.id === 1 && !isFirstInDiscontinuity) {
  29168. this.couldBacktrack = true;
  29169. }
  29170. if (video.dropped && video.independent) {
  29171. const bufferInfo = this.getMainFwdBufferInfo();
  29172. const targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole;
  29173. const startTime = video.firstKeyFramePTS ? video.firstKeyFramePTS : startPTS;
  29174. if (!isFirstFragment && targetBufferTime < startTime - this.config.maxBufferHole && !isFirstInDiscontinuity) {
  29175. this.backtrack(frag);
  29176. return;
  29177. } else if (isFirstInDiscontinuity) {
  29178. frag.gap = true;
  29179. }
  29180. frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
  29181. } else if (isFirstFragment && startPTS - (details.appliedTimelineOffset || 0) > MAX_START_GAP_JUMP) {
  29182. frag.gap = true;
  29183. }
  29184. }
  29185. frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
  29186. if (this.backtrackFragment) {
  29187. this.backtrackFragment = frag;
  29188. }
  29189. this.bufferFragmentData(video, frag, part, chunkMeta, isFirstFragment || isFirstInDiscontinuity);
  29190. } else if (isFirstFragment || isFirstInDiscontinuity) {
  29191. frag.gap = true;
  29192. } else {
  29193. this.backtrack(frag);
  29194. return;
  29195. }
  29196. }
  29197. if (audio) {
  29198. const {
  29199. startPTS,
  29200. endPTS,
  29201. startDTS,
  29202. endDTS
  29203. } = audio;
  29204. if (part) {
  29205. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  29206. startPTS,
  29207. endPTS,
  29208. startDTS,
  29209. endDTS
  29210. };
  29211. }
  29212. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  29213. this.bufferFragmentData(audio, frag, part, chunkMeta);
  29214. }
  29215. if (details && id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  29216. const emittedID3 = {
  29217. id,
  29218. frag,
  29219. details,
  29220. samples: id3.samples
  29221. };
  29222. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  29223. }
  29224. if (details && text) {
  29225. const emittedText = {
  29226. id,
  29227. frag,
  29228. details,
  29229. samples: text.samples
  29230. };
  29231. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  29232. }
  29233. }
  29234. logMuxedErr(frag) {
  29235. this.warn(`${isMediaFragment(frag) ? "Media" : "Init"} segment with muxed audiovideo where only video expected: ${frag.url}`);
  29236. }
  29237. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  29238. if (this.state !== State.PARSING) {
  29239. return;
  29240. }
  29241. this.audioOnly = !!tracks.audio && !tracks.video;
  29242. if (this.altAudio && !this.audioOnly) {
  29243. delete tracks.audio;
  29244. if (tracks.audiovideo) {
  29245. this.logMuxedErr(frag);
  29246. }
  29247. }
  29248. const {
  29249. audio,
  29250. video,
  29251. audiovideo
  29252. } = tracks;
  29253. if (audio) {
  29254. const levelCodec = currentLevel.audioCodec;
  29255. let audioCodec = pickMostCompleteCodecName(audio.codec, levelCodec);
  29256. if (audioCodec === "mp4a") {
  29257. audioCodec = "mp4a.40.5";
  29258. }
  29259. const ua = navigator.userAgent.toLowerCase();
  29260. if (this.audioCodecSwitch) {
  29261. if (audioCodec) {
  29262. if (audioCodec.indexOf("mp4a.40.5") !== -1) {
  29263. audioCodec = "mp4a.40.2";
  29264. } else {
  29265. audioCodec = "mp4a.40.5";
  29266. }
  29267. }
  29268. const audioMetadata = audio.metadata;
  29269. if (audioMetadata && "channelCount" in audioMetadata && (audioMetadata.channelCount || 1) !== 1 && ua.indexOf("firefox") === -1) {
  29270. audioCodec = "mp4a.40.5";
  29271. }
  29272. }
  29273. if (audioCodec && audioCodec.indexOf("mp4a.40.5") !== -1 && ua.indexOf("android") !== -1 && audio.container !== "audio/mpeg") {
  29274. audioCodec = "mp4a.40.2";
  29275. this.log(`Android: force audio codec to ${audioCodec}`);
  29276. }
  29277. if (levelCodec && levelCodec !== audioCodec) {
  29278. this.log(`Swapping manifest audio codec "${levelCodec}" for "${audioCodec}"`);
  29279. }
  29280. audio.levelCodec = audioCodec;
  29281. audio.id = PlaylistLevelType.MAIN;
  29282. this.log(`Init audio buffer, container:${audio.container}, codecs[selected/level/parsed]=[${audioCodec || ""}/${levelCodec || ""}/${audio.codec}]`);
  29283. delete tracks.audiovideo;
  29284. }
  29285. if (video) {
  29286. video.levelCodec = currentLevel.videoCodec;
  29287. video.id = PlaylistLevelType.MAIN;
  29288. const parsedVideoCodec = video.codec;
  29289. if ((parsedVideoCodec == null ? void 0 : parsedVideoCodec.length) === 4) {
  29290. switch (parsedVideoCodec) {
  29291. case "hvc1":
  29292. case "hev1":
  29293. video.codec = "hvc1.1.6.L120.90";
  29294. break;
  29295. case "av01":
  29296. video.codec = "av01.0.04M.08";
  29297. break;
  29298. case "avc1":
  29299. video.codec = "avc1.42e01e";
  29300. break;
  29301. }
  29302. }
  29303. 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 : ""}`);
  29304. delete tracks.audiovideo;
  29305. }
  29306. if (audiovideo) {
  29307. this.log(`Init audiovideo buffer, container:${audiovideo.container}, codecs[level/parsed]=[${currentLevel.codecs}/${audiovideo.codec}]`);
  29308. delete tracks.video;
  29309. delete tracks.audio;
  29310. }
  29311. const trackTypes = Object.keys(tracks);
  29312. if (trackTypes.length) {
  29313. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  29314. if (!this.hls) {
  29315. return;
  29316. }
  29317. trackTypes.forEach((trackName) => {
  29318. const track = tracks[trackName];
  29319. const initSegment = track.initSegment;
  29320. if (initSegment != null && initSegment.byteLength) {
  29321. this.hls.trigger(Events.BUFFER_APPENDING, {
  29322. type: trackName,
  29323. data: initSegment,
  29324. frag,
  29325. part: null,
  29326. chunkMeta,
  29327. parent: frag.type
  29328. });
  29329. }
  29330. });
  29331. }
  29332. this.tickImmediate();
  29333. }
  29334. getMainFwdBufferInfo() {
  29335. const bufferOutput = this.mediaBuffer && this.altAudio === 2 ? this.mediaBuffer : this.media;
  29336. return this.getFwdBufferInfo(bufferOutput, PlaylistLevelType.MAIN);
  29337. }
  29338. get maxBufferLength() {
  29339. const {
  29340. levels,
  29341. level
  29342. } = this;
  29343. const levelInfo = levels == null ? void 0 : levels[level];
  29344. if (!levelInfo) {
  29345. return this.config.maxBufferLength;
  29346. }
  29347. return this.getMaxBufferLength(levelInfo.maxBitrate);
  29348. }
  29349. backtrack(frag) {
  29350. this.couldBacktrack = true;
  29351. this.backtrackFragment = frag;
  29352. this.resetTransmuxer();
  29353. this.flushBufferGap(frag);
  29354. this.fragmentTracker.removeFragment(frag);
  29355. this.fragPrevious = null;
  29356. this.nextLoadPosition = frag.start;
  29357. this.state = State.IDLE;
  29358. }
  29359. checkFragmentChanged() {
  29360. const video = this.media;
  29361. let fragPlayingCurrent = null;
  29362. if (video && video.readyState > 1 && video.seeking === false) {
  29363. const currentTime = video.currentTime;
  29364. if (BufferHelper.isBuffered(video, currentTime)) {
  29365. fragPlayingCurrent = this.getAppendedFrag(currentTime);
  29366. } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
  29367. fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
  29368. }
  29369. if (fragPlayingCurrent) {
  29370. this.backtrackFragment = null;
  29371. const fragPlaying = this.fragPlaying;
  29372. const fragCurrentLevel = fragPlayingCurrent.level;
  29373. if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel) {
  29374. this.fragPlaying = fragPlayingCurrent;
  29375. this.hls.trigger(Events.FRAG_CHANGED, {
  29376. frag: fragPlayingCurrent
  29377. });
  29378. if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
  29379. this.hls.trigger(Events.LEVEL_SWITCHED, {
  29380. level: fragCurrentLevel
  29381. });
  29382. }
  29383. }
  29384. }
  29385. }
  29386. }
  29387. get nextLevel() {
  29388. const frag = this.nextBufferedFrag;
  29389. if (frag) {
  29390. return frag.level;
  29391. }
  29392. return -1;
  29393. }
  29394. get currentFrag() {
  29395. var _this$media3;
  29396. if (this.fragPlaying) {
  29397. return this.fragPlaying;
  29398. }
  29399. const currentTime = ((_this$media3 = this.media) == null ? void 0 : _this$media3.currentTime) || this.lastCurrentTime;
  29400. if (isFiniteNumber(currentTime)) {
  29401. return this.getAppendedFrag(currentTime);
  29402. }
  29403. return null;
  29404. }
  29405. get currentProgramDateTime() {
  29406. var _this$media4;
  29407. const currentTime = ((_this$media4 = this.media) == null ? void 0 : _this$media4.currentTime) || this.lastCurrentTime;
  29408. if (isFiniteNumber(currentTime)) {
  29409. const details = this.getLevelDetails();
  29410. const frag = this.currentFrag || (details ? findFragmentByPTS(null, details.fragments, currentTime) : null);
  29411. if (frag) {
  29412. const programDateTime = frag.programDateTime;
  29413. if (programDateTime !== null) {
  29414. const epocMs = programDateTime + (currentTime - frag.start) * 1e3;
  29415. return new Date(epocMs);
  29416. }
  29417. }
  29418. }
  29419. return null;
  29420. }
  29421. get currentLevel() {
  29422. const frag = this.currentFrag;
  29423. if (frag) {
  29424. return frag.level;
  29425. }
  29426. return -1;
  29427. }
  29428. get nextBufferedFrag() {
  29429. const frag = this.currentFrag;
  29430. if (frag) {
  29431. return this.followingBufferedFrag(frag);
  29432. }
  29433. return null;
  29434. }
  29435. get forceStartLoad() {
  29436. return this._forceStartLoad;
  29437. }
  29438. };
  29439. var KeyLoader = class {
  29440. constructor(config) {
  29441. this.config = void 0;
  29442. this.keyUriToKeyInfo = {};
  29443. this.emeController = null;
  29444. this.config = config;
  29445. }
  29446. abort(type) {
  29447. for (const uri in this.keyUriToKeyInfo) {
  29448. const loader = this.keyUriToKeyInfo[uri].loader;
  29449. if (loader) {
  29450. var _loader$context;
  29451. if (type && type !== ((_loader$context = loader.context) == null ? void 0 : _loader$context.frag.type)) {
  29452. return;
  29453. }
  29454. loader.abort();
  29455. }
  29456. }
  29457. }
  29458. detach() {
  29459. for (const uri in this.keyUriToKeyInfo) {
  29460. const keyInfo = this.keyUriToKeyInfo[uri];
  29461. if (keyInfo.mediaKeySessionContext || keyInfo.decryptdata.isCommonEncryption) {
  29462. delete this.keyUriToKeyInfo[uri];
  29463. }
  29464. }
  29465. }
  29466. destroy() {
  29467. this.detach();
  29468. for (const uri in this.keyUriToKeyInfo) {
  29469. const loader = this.keyUriToKeyInfo[uri].loader;
  29470. if (loader) {
  29471. loader.destroy();
  29472. }
  29473. }
  29474. this.keyUriToKeyInfo = {};
  29475. }
  29476. createKeyLoadError(frag, details = ErrorDetails.KEY_LOAD_ERROR, error, networkDetails, response) {
  29477. return new LoadError({
  29478. type: ErrorTypes.NETWORK_ERROR,
  29479. details,
  29480. fatal: false,
  29481. frag,
  29482. response,
  29483. error,
  29484. networkDetails
  29485. });
  29486. }
  29487. loadClear(loadingFrag, encryptedFragments, startFragRequested) {
  29488. if (this.emeController && this.config.emeEnabled && !this.emeController.getSelectedKeySystemFormats().length) {
  29489. if (encryptedFragments.length) {
  29490. for (let i = 0, l = encryptedFragments.length; i < l; i++) {
  29491. const frag = encryptedFragments[i];
  29492. if (loadingFrag.cc <= frag.cc && (!isMediaFragment(loadingFrag) || !isMediaFragment(frag) || loadingFrag.sn < frag.sn) || !startFragRequested && i == l - 1) {
  29493. return this.emeController.selectKeySystemFormat(frag).then((keySystemFormat) => {
  29494. if (!this.emeController) {
  29495. return;
  29496. }
  29497. frag.setKeyFormat(keySystemFormat);
  29498. const keySystem = keySystemFormatToKeySystemDomain(keySystemFormat);
  29499. if (keySystem) {
  29500. return this.emeController.getKeySystemAccess([keySystem]);
  29501. }
  29502. });
  29503. }
  29504. }
  29505. }
  29506. if (this.config.requireKeySystemAccessOnStart) {
  29507. const keySystemsInConfig = getKeySystemsForConfig(this.config);
  29508. if (keySystemsInConfig.length) {
  29509. return this.emeController.getKeySystemAccess(keySystemsInConfig);
  29510. }
  29511. }
  29512. }
  29513. return null;
  29514. }
  29515. load(frag) {
  29516. if (!frag.decryptdata && frag.encrypted && this.emeController && this.config.emeEnabled) {
  29517. return this.emeController.selectKeySystemFormat(frag).then((keySystemFormat) => {
  29518. return this.loadInternal(frag, keySystemFormat);
  29519. });
  29520. }
  29521. return this.loadInternal(frag);
  29522. }
  29523. loadInternal(frag, keySystemFormat) {
  29524. var _keyInfo, _keyInfo2;
  29525. if (keySystemFormat) {
  29526. frag.setKeyFormat(keySystemFormat);
  29527. }
  29528. const decryptdata = frag.decryptdata;
  29529. if (!decryptdata) {
  29530. const error = new Error(keySystemFormat ? `Expected frag.decryptdata to be defined after setting format ${keySystemFormat}` : "Missing decryption data on fragment in onKeyLoading");
  29531. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error));
  29532. }
  29533. const uri = decryptdata.uri;
  29534. if (!uri) {
  29535. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Invalid key URI: "${uri}"`)));
  29536. }
  29537. let keyInfo = this.keyUriToKeyInfo[uri];
  29538. if ((_keyInfo = keyInfo) != null && _keyInfo.decryptdata.key) {
  29539. decryptdata.key = keyInfo.decryptdata.key;
  29540. return Promise.resolve({
  29541. frag,
  29542. keyInfo
  29543. });
  29544. }
  29545. if ((_keyInfo2 = keyInfo) != null && _keyInfo2.keyLoadPromise) {
  29546. var _keyInfo$mediaKeySess;
  29547. switch ((_keyInfo$mediaKeySess = keyInfo.mediaKeySessionContext) == null ? void 0 : _keyInfo$mediaKeySess.keyStatus) {
  29548. case void 0:
  29549. case "status-pending":
  29550. case "usable":
  29551. case "usable-in-future":
  29552. return keyInfo.keyLoadPromise.then((keyLoadedData) => {
  29553. decryptdata.key = keyLoadedData.keyInfo.decryptdata.key;
  29554. return {
  29555. frag,
  29556. keyInfo
  29557. };
  29558. });
  29559. }
  29560. }
  29561. keyInfo = this.keyUriToKeyInfo[uri] = {
  29562. decryptdata,
  29563. keyLoadPromise: null,
  29564. loader: null,
  29565. mediaKeySessionContext: null
  29566. };
  29567. switch (decryptdata.method) {
  29568. case "ISO-23001-7":
  29569. case "SAMPLE-AES":
  29570. case "SAMPLE-AES-CENC":
  29571. case "SAMPLE-AES-CTR":
  29572. if (decryptdata.keyFormat === "identity") {
  29573. return this.loadKeyHTTP(keyInfo, frag);
  29574. }
  29575. return this.loadKeyEME(keyInfo, frag);
  29576. case "AES-128":
  29577. case "AES-256":
  29578. case "AES-256-CTR":
  29579. return this.loadKeyHTTP(keyInfo, frag);
  29580. default:
  29581. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Key supplied with unsupported METHOD: "${decryptdata.method}"`)));
  29582. }
  29583. }
  29584. loadKeyEME(keyInfo, frag) {
  29585. const keyLoadedData = {
  29586. frag,
  29587. keyInfo
  29588. };
  29589. if (this.emeController && this.config.emeEnabled) {
  29590. const keySessionContextPromise = this.emeController.loadKey(keyLoadedData);
  29591. if (keySessionContextPromise) {
  29592. return (keyInfo.keyLoadPromise = keySessionContextPromise.then((keySessionContext) => {
  29593. keyInfo.mediaKeySessionContext = keySessionContext;
  29594. return keyLoadedData;
  29595. })).catch((error) => {
  29596. keyInfo.keyLoadPromise = null;
  29597. throw error;
  29598. });
  29599. }
  29600. }
  29601. return Promise.resolve(keyLoadedData);
  29602. }
  29603. loadKeyHTTP(keyInfo, frag) {
  29604. const config = this.config;
  29605. const Loader = config.loader;
  29606. const keyLoader = new Loader(config);
  29607. frag.keyLoader = keyInfo.loader = keyLoader;
  29608. return keyInfo.keyLoadPromise = new Promise((resolve, reject) => {
  29609. const loaderContext = {
  29610. keyInfo,
  29611. frag,
  29612. responseType: "arraybuffer",
  29613. url: keyInfo.decryptdata.uri
  29614. };
  29615. const loadPolicy = config.keyLoadPolicy.default;
  29616. const loaderConfig = {
  29617. loadPolicy,
  29618. timeout: loadPolicy.maxLoadTimeMs,
  29619. maxRetry: 0,
  29620. retryDelay: 0,
  29621. maxRetryDelay: 0
  29622. };
  29623. const loaderCallbacks = {
  29624. onSuccess: (response, stats, context, networkDetails) => {
  29625. const {
  29626. frag: frag2,
  29627. keyInfo: keyInfo2,
  29628. url: uri
  29629. } = context;
  29630. if (!frag2.decryptdata || keyInfo2 !== this.keyUriToKeyInfo[uri]) {
  29631. return reject(this.createKeyLoadError(frag2, ErrorDetails.KEY_LOAD_ERROR, new Error("after key load, decryptdata unset or changed"), networkDetails));
  29632. }
  29633. keyInfo2.decryptdata.key = frag2.decryptdata.key = new Uint8Array(response.data);
  29634. frag2.keyLoader = null;
  29635. keyInfo2.loader = null;
  29636. resolve({
  29637. frag: frag2,
  29638. keyInfo: keyInfo2
  29639. });
  29640. },
  29641. onError: (response, context, networkDetails, stats) => {
  29642. this.resetLoader(context);
  29643. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`HTTP Error ${response.code} loading key ${response.text}`), networkDetails, _objectSpread2({
  29644. url: loaderContext.url,
  29645. data: void 0
  29646. }, response)));
  29647. },
  29648. onTimeout: (stats, context, networkDetails) => {
  29649. this.resetLoader(context);
  29650. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_TIMEOUT, new Error("key loading timed out"), networkDetails));
  29651. },
  29652. onAbort: (stats, context, networkDetails) => {
  29653. this.resetLoader(context);
  29654. reject(this.createKeyLoadError(frag, ErrorDetails.INTERNAL_ABORTED, new Error("key loading aborted"), networkDetails));
  29655. }
  29656. };
  29657. keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  29658. });
  29659. }
  29660. resetLoader(context) {
  29661. const {
  29662. frag,
  29663. keyInfo,
  29664. url: uri
  29665. } = context;
  29666. const loader = keyInfo.loader;
  29667. if (frag.keyLoader === loader) {
  29668. frag.keyLoader = null;
  29669. keyInfo.loader = null;
  29670. }
  29671. delete this.keyUriToKeyInfo[uri];
  29672. if (loader) {
  29673. loader.destroy();
  29674. }
  29675. }
  29676. };
  29677. function mapContextToLevelType(context) {
  29678. const {
  29679. type
  29680. } = context;
  29681. switch (type) {
  29682. case PlaylistContextType.AUDIO_TRACK:
  29683. return PlaylistLevelType.AUDIO;
  29684. case PlaylistContextType.SUBTITLE_TRACK:
  29685. return PlaylistLevelType.SUBTITLE;
  29686. default:
  29687. return PlaylistLevelType.MAIN;
  29688. }
  29689. }
  29690. function getResponseUrl(response, context) {
  29691. let url = response.url;
  29692. if (url === void 0 || url.indexOf("data:") === 0) {
  29693. url = context.url;
  29694. }
  29695. return url;
  29696. }
  29697. var PlaylistLoader = class {
  29698. constructor(hls) {
  29699. this.hls = void 0;
  29700. this.loaders = /* @__PURE__ */ Object.create(null);
  29701. this.variableList = null;
  29702. this.onManifestLoaded = this.checkAutostartLoad;
  29703. this.hls = hls;
  29704. this.registerListeners();
  29705. }
  29706. startLoad(startPosition) {
  29707. }
  29708. stopLoad() {
  29709. this.destroyInternalLoaders();
  29710. }
  29711. registerListeners() {
  29712. const {
  29713. hls
  29714. } = this;
  29715. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  29716. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  29717. hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  29718. hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  29719. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  29720. }
  29721. unregisterListeners() {
  29722. const {
  29723. hls
  29724. } = this;
  29725. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  29726. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  29727. hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  29728. hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  29729. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  29730. }
  29731. createInternalLoader(context) {
  29732. const config = this.hls.config;
  29733. const PLoader = config.pLoader;
  29734. const Loader = config.loader;
  29735. const InternalLoader = PLoader || Loader;
  29736. const loader = new InternalLoader(config);
  29737. this.loaders[context.type] = loader;
  29738. return loader;
  29739. }
  29740. getInternalLoader(context) {
  29741. return this.loaders[context.type];
  29742. }
  29743. resetInternalLoader(contextType) {
  29744. if (this.loaders[contextType]) {
  29745. delete this.loaders[contextType];
  29746. }
  29747. }
  29748. destroyInternalLoaders() {
  29749. for (const contextType in this.loaders) {
  29750. const loader = this.loaders[contextType];
  29751. if (loader) {
  29752. loader.destroy();
  29753. }
  29754. this.resetInternalLoader(contextType);
  29755. }
  29756. }
  29757. destroy() {
  29758. this.variableList = null;
  29759. this.unregisterListeners();
  29760. this.destroyInternalLoaders();
  29761. }
  29762. onManifestLoading(event, data) {
  29763. const {
  29764. url
  29765. } = data;
  29766. this.variableList = null;
  29767. this.load({
  29768. id: null,
  29769. level: 0,
  29770. responseType: "text",
  29771. type: PlaylistContextType.MANIFEST,
  29772. url,
  29773. deliveryDirectives: null,
  29774. levelOrTrack: null
  29775. });
  29776. }
  29777. onLevelLoading(event, data) {
  29778. const {
  29779. id,
  29780. level,
  29781. pathwayId,
  29782. url,
  29783. deliveryDirectives,
  29784. levelInfo
  29785. } = data;
  29786. this.load({
  29787. id,
  29788. level,
  29789. pathwayId,
  29790. responseType: "text",
  29791. type: PlaylistContextType.LEVEL,
  29792. url,
  29793. deliveryDirectives,
  29794. levelOrTrack: levelInfo
  29795. });
  29796. }
  29797. onAudioTrackLoading(event, data) {
  29798. const {
  29799. id,
  29800. groupId,
  29801. url,
  29802. deliveryDirectives,
  29803. track
  29804. } = data;
  29805. this.load({
  29806. id,
  29807. groupId,
  29808. level: null,
  29809. responseType: "text",
  29810. type: PlaylistContextType.AUDIO_TRACK,
  29811. url,
  29812. deliveryDirectives,
  29813. levelOrTrack: track
  29814. });
  29815. }
  29816. onSubtitleTrackLoading(event, data) {
  29817. const {
  29818. id,
  29819. groupId,
  29820. url,
  29821. deliveryDirectives,
  29822. track
  29823. } = data;
  29824. this.load({
  29825. id,
  29826. groupId,
  29827. level: null,
  29828. responseType: "text",
  29829. type: PlaylistContextType.SUBTITLE_TRACK,
  29830. url,
  29831. deliveryDirectives,
  29832. levelOrTrack: track
  29833. });
  29834. }
  29835. onLevelsUpdated(event, data) {
  29836. const loader = this.loaders[PlaylistContextType.LEVEL];
  29837. if (loader) {
  29838. const context = loader.context;
  29839. if (context && !data.levels.some((lvl) => lvl === context.levelOrTrack)) {
  29840. loader.abort();
  29841. delete this.loaders[PlaylistContextType.LEVEL];
  29842. }
  29843. }
  29844. }
  29845. load(context) {
  29846. var _context$deliveryDire;
  29847. const config = this.hls.config;
  29848. let loader = this.getInternalLoader(context);
  29849. if (loader) {
  29850. const logger2 = this.hls.logger;
  29851. const loaderContext = loader.context;
  29852. if (loaderContext && loaderContext.levelOrTrack === context.levelOrTrack && (loaderContext.url === context.url || loaderContext.deliveryDirectives && !context.deliveryDirectives)) {
  29853. if (loaderContext.url === context.url) {
  29854. logger2.log(`[playlist-loader]: ignore ${context.url} ongoing request`);
  29855. } else {
  29856. logger2.log(`[playlist-loader]: ignore ${context.url} in favor of ${loaderContext.url}`);
  29857. }
  29858. return;
  29859. }
  29860. logger2.log(`[playlist-loader]: aborting previous loader for type: ${context.type}`);
  29861. loader.abort();
  29862. }
  29863. let loadPolicy;
  29864. if (context.type === PlaylistContextType.MANIFEST) {
  29865. loadPolicy = config.manifestLoadPolicy.default;
  29866. } else {
  29867. loadPolicy = _extends({}, config.playlistLoadPolicy.default, {
  29868. timeoutRetry: null,
  29869. errorRetry: null
  29870. });
  29871. }
  29872. loader = this.createInternalLoader(context);
  29873. if (isFiniteNumber((_context$deliveryDire = context.deliveryDirectives) == null ? void 0 : _context$deliveryDire.part)) {
  29874. let levelDetails;
  29875. if (context.type === PlaylistContextType.LEVEL && context.level !== null) {
  29876. levelDetails = this.hls.levels[context.level].details;
  29877. } else if (context.type === PlaylistContextType.AUDIO_TRACK && context.id !== null) {
  29878. levelDetails = this.hls.audioTracks[context.id].details;
  29879. } else if (context.type === PlaylistContextType.SUBTITLE_TRACK && context.id !== null) {
  29880. levelDetails = this.hls.subtitleTracks[context.id].details;
  29881. }
  29882. if (levelDetails) {
  29883. const partTarget = levelDetails.partTarget;
  29884. const targetDuration = levelDetails.targetduration;
  29885. if (partTarget && targetDuration) {
  29886. const maxLowLatencyPlaylistRefresh = Math.max(partTarget * 3, targetDuration * 0.8) * 1e3;
  29887. loadPolicy = _extends({}, loadPolicy, {
  29888. maxTimeToFirstByteMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs),
  29889. maxLoadTimeMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs)
  29890. });
  29891. }
  29892. }
  29893. }
  29894. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  29895. const loaderConfig = {
  29896. loadPolicy,
  29897. timeout: loadPolicy.maxLoadTimeMs,
  29898. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  29899. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  29900. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  29901. };
  29902. const loaderCallbacks = {
  29903. onSuccess: (response, stats, context2, networkDetails) => {
  29904. const loader2 = this.getInternalLoader(context2);
  29905. this.resetInternalLoader(context2.type);
  29906. const string = response.data;
  29907. if (string.indexOf("#EXTM3U") !== 0) {
  29908. this.handleManifestParsingError(response, context2, new Error("no EXTM3U delimiter"), networkDetails || null, stats);
  29909. return;
  29910. }
  29911. stats.parsing.start = performance.now();
  29912. if (M3U8Parser.isMediaPlaylist(string) || context2.type !== PlaylistContextType.MANIFEST) {
  29913. this.handleTrackOrLevelPlaylist(response, stats, context2, networkDetails || null, loader2);
  29914. } else {
  29915. this.handleMasterPlaylist(response, stats, context2, networkDetails);
  29916. }
  29917. },
  29918. onError: (response, context2, networkDetails, stats) => {
  29919. this.handleNetworkError(context2, networkDetails, false, response, stats);
  29920. },
  29921. onTimeout: (stats, context2, networkDetails) => {
  29922. this.handleNetworkError(context2, networkDetails, true, void 0, stats);
  29923. }
  29924. };
  29925. loader.load(context, loaderConfig, loaderCallbacks);
  29926. }
  29927. checkAutostartLoad() {
  29928. if (!this.hls) {
  29929. return;
  29930. }
  29931. const {
  29932. config: {
  29933. autoStartLoad,
  29934. startPosition
  29935. },
  29936. forceStartLoad
  29937. } = this.hls;
  29938. if (autoStartLoad || forceStartLoad) {
  29939. this.hls.logger.log(`${autoStartLoad ? "auto" : "force"} startLoad with configured startPosition ${startPosition}`);
  29940. this.hls.startLoad(startPosition);
  29941. }
  29942. }
  29943. handleMasterPlaylist(response, stats, context, networkDetails) {
  29944. const hls = this.hls;
  29945. const string = response.data;
  29946. const url = getResponseUrl(response, context);
  29947. const parsedResult = M3U8Parser.parseMasterPlaylist(string, url);
  29948. if (parsedResult.playlistParsingError) {
  29949. this.handleManifestParsingError(response, context, parsedResult.playlistParsingError, networkDetails, stats);
  29950. return;
  29951. }
  29952. const {
  29953. contentSteering,
  29954. levels,
  29955. sessionData,
  29956. sessionKeys,
  29957. startTimeOffset,
  29958. variableList
  29959. } = parsedResult;
  29960. this.variableList = variableList;
  29961. const {
  29962. AUDIO: audioTracks = [],
  29963. SUBTITLES: subtitles,
  29964. "CLOSED-CAPTIONS": captions
  29965. } = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult);
  29966. if (audioTracks.length) {
  29967. const embeddedAudioFound = audioTracks.some((audioTrack) => !audioTrack.url);
  29968. if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  29969. this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one");
  29970. audioTracks.unshift({
  29971. type: "main",
  29972. name: "main",
  29973. groupId: "main",
  29974. default: false,
  29975. autoselect: false,
  29976. forced: false,
  29977. id: -1,
  29978. attrs: new AttrList({}),
  29979. bitrate: 0,
  29980. url: ""
  29981. });
  29982. }
  29983. }
  29984. hls.trigger(Events.MANIFEST_LOADED, {
  29985. levels,
  29986. audioTracks,
  29987. subtitles,
  29988. captions,
  29989. contentSteering,
  29990. url,
  29991. stats,
  29992. networkDetails,
  29993. sessionData,
  29994. sessionKeys,
  29995. startTimeOffset,
  29996. variableList
  29997. });
  29998. }
  29999. handleTrackOrLevelPlaylist(response, stats, context, networkDetails, loader) {
  30000. const hls = this.hls;
  30001. const {
  30002. id,
  30003. level,
  30004. type
  30005. } = context;
  30006. const url = getResponseUrl(response, context);
  30007. const levelId = isFiniteNumber(level) ? level : isFiniteNumber(id) ? id : 0;
  30008. const levelType = mapContextToLevelType(context);
  30009. const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, 0, this.variableList);
  30010. if (type === PlaylistContextType.MANIFEST) {
  30011. const singleLevel = {
  30012. attrs: new AttrList({}),
  30013. bitrate: 0,
  30014. details: levelDetails,
  30015. name: "",
  30016. url
  30017. };
  30018. levelDetails.requestScheduled = stats.loading.start + computeReloadInterval(levelDetails, 0);
  30019. hls.trigger(Events.MANIFEST_LOADED, {
  30020. levels: [singleLevel],
  30021. audioTracks: [],
  30022. url,
  30023. stats,
  30024. networkDetails,
  30025. sessionData: null,
  30026. sessionKeys: null,
  30027. contentSteering: null,
  30028. startTimeOffset: null,
  30029. variableList: null
  30030. });
  30031. }
  30032. stats.parsing.end = performance.now();
  30033. context.levelDetails = levelDetails;
  30034. this.handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader);
  30035. }
  30036. handleManifestParsingError(response, context, error, networkDetails, stats) {
  30037. this.hls.trigger(Events.ERROR, {
  30038. type: ErrorTypes.NETWORK_ERROR,
  30039. details: ErrorDetails.MANIFEST_PARSING_ERROR,
  30040. fatal: context.type === PlaylistContextType.MANIFEST,
  30041. url: response.url,
  30042. err: error,
  30043. error,
  30044. reason: error.message,
  30045. response,
  30046. context,
  30047. networkDetails,
  30048. stats
  30049. });
  30050. }
  30051. handleNetworkError(context, networkDetails, timeout = false, response, stats) {
  30052. let message = `A network ${timeout ? "timeout" : "error" + (response ? " (status " + response.code + ")" : "")} occurred while loading ${context.type}`;
  30053. if (context.type === PlaylistContextType.LEVEL) {
  30054. message += `: ${context.level} id: ${context.id}`;
  30055. } else if (context.type === PlaylistContextType.AUDIO_TRACK || context.type === PlaylistContextType.SUBTITLE_TRACK) {
  30056. message += ` id: ${context.id} group-id: "${context.groupId}"`;
  30057. }
  30058. const error = new Error(message);
  30059. this.hls.logger.warn(`[playlist-loader]: ${message}`);
  30060. let details = ErrorDetails.UNKNOWN;
  30061. let fatal = false;
  30062. const loader = this.getInternalLoader(context);
  30063. switch (context.type) {
  30064. case PlaylistContextType.MANIFEST:
  30065. details = timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR;
  30066. fatal = true;
  30067. break;
  30068. case PlaylistContextType.LEVEL:
  30069. details = timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR;
  30070. fatal = false;
  30071. break;
  30072. case PlaylistContextType.AUDIO_TRACK:
  30073. details = timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  30074. fatal = false;
  30075. break;
  30076. case PlaylistContextType.SUBTITLE_TRACK:
  30077. details = timeout ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_LOAD_ERROR;
  30078. fatal = false;
  30079. break;
  30080. }
  30081. if (loader) {
  30082. this.resetInternalLoader(context.type);
  30083. }
  30084. const errorData = {
  30085. type: ErrorTypes.NETWORK_ERROR,
  30086. details,
  30087. fatal,
  30088. url: context.url,
  30089. loader,
  30090. context,
  30091. error,
  30092. networkDetails,
  30093. stats
  30094. };
  30095. if (response) {
  30096. const url = (networkDetails == null ? void 0 : networkDetails.url) || context.url;
  30097. errorData.response = _objectSpread2({
  30098. url,
  30099. data: void 0
  30100. }, response);
  30101. }
  30102. this.hls.trigger(Events.ERROR, errorData);
  30103. }
  30104. handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader) {
  30105. const hls = this.hls;
  30106. const {
  30107. type,
  30108. level,
  30109. id,
  30110. groupId,
  30111. deliveryDirectives
  30112. } = context;
  30113. const url = getResponseUrl(response, context);
  30114. const parent = mapContextToLevelType(context);
  30115. const levelIndex = typeof context.level === "number" && parent === PlaylistLevelType.MAIN ? level : void 0;
  30116. if (!levelDetails.fragments.length) {
  30117. const _error = levelDetails.playlistParsingError = new Error("No Segments found in Playlist");
  30118. hls.trigger(Events.ERROR, {
  30119. type: ErrorTypes.NETWORK_ERROR,
  30120. details: ErrorDetails.LEVEL_EMPTY_ERROR,
  30121. fatal: false,
  30122. url,
  30123. error: _error,
  30124. reason: _error.message,
  30125. response,
  30126. context,
  30127. level: levelIndex,
  30128. parent,
  30129. networkDetails,
  30130. stats
  30131. });
  30132. return;
  30133. }
  30134. if (!levelDetails.targetduration) {
  30135. levelDetails.playlistParsingError = new Error("Missing Target Duration");
  30136. }
  30137. const error = levelDetails.playlistParsingError;
  30138. if (error) {
  30139. this.hls.logger.warn(error);
  30140. if (!hls.config.ignorePlaylistParsingErrors) {
  30141. hls.trigger(Events.ERROR, {
  30142. type: ErrorTypes.NETWORK_ERROR,
  30143. details: ErrorDetails.LEVEL_PARSING_ERROR,
  30144. fatal: false,
  30145. url,
  30146. error,
  30147. reason: error.message,
  30148. response,
  30149. context,
  30150. level: levelIndex,
  30151. parent,
  30152. networkDetails,
  30153. stats
  30154. });
  30155. return;
  30156. }
  30157. levelDetails.playlistParsingError = null;
  30158. }
  30159. if (levelDetails.live && loader) {
  30160. if (loader.getCacheAge) {
  30161. levelDetails.ageHeader = loader.getCacheAge() || 0;
  30162. }
  30163. if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
  30164. levelDetails.ageHeader = 0;
  30165. }
  30166. }
  30167. switch (type) {
  30168. case PlaylistContextType.MANIFEST:
  30169. case PlaylistContextType.LEVEL:
  30170. hls.trigger(Events.LEVEL_LOADED, {
  30171. details: levelDetails,
  30172. levelInfo: context.levelOrTrack || hls.levels[0],
  30173. level: levelIndex || 0,
  30174. id: id || 0,
  30175. stats,
  30176. networkDetails,
  30177. deliveryDirectives,
  30178. withoutMultiVariant: type === PlaylistContextType.MANIFEST
  30179. });
  30180. break;
  30181. case PlaylistContextType.AUDIO_TRACK:
  30182. hls.trigger(Events.AUDIO_TRACK_LOADED, {
  30183. details: levelDetails,
  30184. track: context.levelOrTrack,
  30185. id: id || 0,
  30186. groupId: groupId || "",
  30187. stats,
  30188. networkDetails,
  30189. deliveryDirectives
  30190. });
  30191. break;
  30192. case PlaylistContextType.SUBTITLE_TRACK:
  30193. hls.trigger(Events.SUBTITLE_TRACK_LOADED, {
  30194. details: levelDetails,
  30195. track: context.levelOrTrack,
  30196. id: id || 0,
  30197. groupId: groupId || "",
  30198. stats,
  30199. networkDetails,
  30200. deliveryDirectives
  30201. });
  30202. break;
  30203. }
  30204. }
  30205. };
  30206. var Hls = class {
  30207. static get version() {
  30208. return version;
  30209. }
  30210. static isMSESupported() {
  30211. return isMSESupported();
  30212. }
  30213. static isSupported() {
  30214. return isSupported();
  30215. }
  30216. static getMediaSource() {
  30217. return getMediaSource();
  30218. }
  30219. static get Events() {
  30220. return Events;
  30221. }
  30222. static get MetadataSchema() {
  30223. return MetadataSchema;
  30224. }
  30225. static get ErrorTypes() {
  30226. return ErrorTypes;
  30227. }
  30228. static get ErrorDetails() {
  30229. return ErrorDetails;
  30230. }
  30231. static get DefaultConfig() {
  30232. if (!Hls.defaultConfig) {
  30233. return hlsDefaultConfig;
  30234. }
  30235. return Hls.defaultConfig;
  30236. }
  30237. static set DefaultConfig(defaultConfig) {
  30238. Hls.defaultConfig = defaultConfig;
  30239. }
  30240. constructor(userConfig = {}) {
  30241. this.config = void 0;
  30242. this.userConfig = void 0;
  30243. this.logger = void 0;
  30244. this.coreComponents = void 0;
  30245. this.networkControllers = void 0;
  30246. this._emitter = new EventEmitter();
  30247. this._autoLevelCapping = -1;
  30248. this._maxHdcpLevel = null;
  30249. this.abrController = void 0;
  30250. this.bufferController = void 0;
  30251. this.capLevelController = void 0;
  30252. this.latencyController = void 0;
  30253. this.levelController = void 0;
  30254. this.streamController = void 0;
  30255. this.audioStreamController = void 0;
  30256. this.subtititleStreamController = void 0;
  30257. this.audioTrackController = void 0;
  30258. this.subtitleTrackController = void 0;
  30259. this.interstitialsController = void 0;
  30260. this.gapController = void 0;
  30261. this.emeController = void 0;
  30262. this.cmcdController = void 0;
  30263. this._media = null;
  30264. this._url = null;
  30265. this._sessionId = void 0;
  30266. this.triggeringException = void 0;
  30267. this.started = false;
  30268. const logger2 = this.logger = enableLogs(userConfig.debug || false, "Hls instance", userConfig.assetPlayerId);
  30269. const config = this.config = mergeConfig(Hls.DefaultConfig, userConfig, logger2);
  30270. this.userConfig = userConfig;
  30271. if (config.progressive) {
  30272. enableStreamingMode(config, logger2);
  30273. }
  30274. const {
  30275. abrController: _AbrController,
  30276. bufferController: _BufferController,
  30277. capLevelController: _CapLevelController,
  30278. errorController: _ErrorController,
  30279. fpsController: _FpsController
  30280. } = config;
  30281. const errorController = new _ErrorController(this);
  30282. const abrController = this.abrController = new _AbrController(this);
  30283. const fragmentTracker = new FragmentTracker(this);
  30284. const _InterstitialsController = config.interstitialsController;
  30285. const interstitialsController = _InterstitialsController ? this.interstitialsController = new _InterstitialsController(this, Hls) : null;
  30286. const bufferController = this.bufferController = new _BufferController(this, fragmentTracker);
  30287. const capLevelController = this.capLevelController = new _CapLevelController(this);
  30288. const fpsController = new _FpsController(this);
  30289. const playListLoader = new PlaylistLoader(this);
  30290. const _ContentSteeringController = config.contentSteeringController;
  30291. const contentSteering = _ContentSteeringController ? new _ContentSteeringController(this) : null;
  30292. const levelController = this.levelController = new LevelController(this, contentSteering);
  30293. const id3TrackController = new ID3TrackController(this);
  30294. const keyLoader = new KeyLoader(this.config);
  30295. const streamController = this.streamController = new StreamController(this, fragmentTracker, keyLoader);
  30296. const gapController = this.gapController = new GapController(this, fragmentTracker);
  30297. capLevelController.setStreamController(streamController);
  30298. fpsController.setStreamController(streamController);
  30299. const networkControllers = [playListLoader, levelController, streamController];
  30300. if (interstitialsController) {
  30301. networkControllers.splice(1, 0, interstitialsController);
  30302. }
  30303. if (contentSteering) {
  30304. networkControllers.splice(1, 0, contentSteering);
  30305. }
  30306. this.networkControllers = networkControllers;
  30307. const coreComponents = [abrController, bufferController, gapController, capLevelController, fpsController, id3TrackController, fragmentTracker];
  30308. this.audioTrackController = this.createController(config.audioTrackController, networkControllers);
  30309. const AudioStreamControllerClass = config.audioStreamController;
  30310. if (AudioStreamControllerClass) {
  30311. networkControllers.push(this.audioStreamController = new AudioStreamControllerClass(this, fragmentTracker, keyLoader));
  30312. }
  30313. this.subtitleTrackController = this.createController(config.subtitleTrackController, networkControllers);
  30314. const SubtitleStreamControllerClass = config.subtitleStreamController;
  30315. if (SubtitleStreamControllerClass) {
  30316. networkControllers.push(this.subtititleStreamController = new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader));
  30317. }
  30318. this.createController(config.timelineController, coreComponents);
  30319. keyLoader.emeController = this.emeController = this.createController(config.emeController, coreComponents);
  30320. this.cmcdController = this.createController(config.cmcdController, coreComponents);
  30321. this.latencyController = this.createController(LatencyController, coreComponents);
  30322. this.coreComponents = coreComponents;
  30323. networkControllers.push(errorController);
  30324. const onErrorOut = errorController.onErrorOut;
  30325. if (typeof onErrorOut === "function") {
  30326. this.on(Events.ERROR, onErrorOut, errorController);
  30327. }
  30328. this.on(Events.MANIFEST_LOADED, playListLoader.onManifestLoaded, playListLoader);
  30329. }
  30330. createController(ControllerClass, components) {
  30331. if (ControllerClass) {
  30332. const controllerInstance = new ControllerClass(this);
  30333. if (components) {
  30334. components.push(controllerInstance);
  30335. }
  30336. return controllerInstance;
  30337. }
  30338. return null;
  30339. }
  30340. on(event, listener, context = this) {
  30341. this._emitter.on(event, listener, context);
  30342. }
  30343. once(event, listener, context = this) {
  30344. this._emitter.once(event, listener, context);
  30345. }
  30346. removeAllListeners(event) {
  30347. this._emitter.removeAllListeners(event);
  30348. }
  30349. off(event, listener, context = this, once) {
  30350. this._emitter.off(event, listener, context, once);
  30351. }
  30352. listeners(event) {
  30353. return this._emitter.listeners(event);
  30354. }
  30355. emit(event, name, eventObject) {
  30356. return this._emitter.emit(event, name, eventObject);
  30357. }
  30358. trigger(event, eventObject) {
  30359. if (this.config.debug) {
  30360. return this.emit(event, event, eventObject);
  30361. } else {
  30362. try {
  30363. return this.emit(event, event, eventObject);
  30364. } catch (error) {
  30365. this.logger.error("An internal error happened while handling event " + event + '. Error message: "' + error.message + '". Here is a stacktrace:', error);
  30366. if (!this.triggeringException) {
  30367. this.triggeringException = true;
  30368. const fatal = event === Events.ERROR;
  30369. this.trigger(Events.ERROR, {
  30370. type: ErrorTypes.OTHER_ERROR,
  30371. details: ErrorDetails.INTERNAL_EXCEPTION,
  30372. fatal,
  30373. event,
  30374. error
  30375. });
  30376. this.triggeringException = false;
  30377. }
  30378. }
  30379. }
  30380. return false;
  30381. }
  30382. listenerCount(event) {
  30383. return this._emitter.listenerCount(event);
  30384. }
  30385. destroy() {
  30386. this.logger.log("destroy");
  30387. this.trigger(Events.DESTROYING, void 0);
  30388. this.detachMedia();
  30389. this.removeAllListeners();
  30390. this._autoLevelCapping = -1;
  30391. this._url = null;
  30392. this.networkControllers.forEach((component) => component.destroy());
  30393. this.networkControllers.length = 0;
  30394. this.coreComponents.forEach((component) => component.destroy());
  30395. this.coreComponents.length = 0;
  30396. const config = this.config;
  30397. config.xhrSetup = config.fetchSetup = void 0;
  30398. this.userConfig = null;
  30399. }
  30400. attachMedia(data) {
  30401. if (!data || "media" in data && !data.media) {
  30402. const error = new Error(`attachMedia failed: invalid argument (${data})`);
  30403. this.trigger(Events.ERROR, {
  30404. type: ErrorTypes.OTHER_ERROR,
  30405. details: ErrorDetails.ATTACH_MEDIA_ERROR,
  30406. fatal: true,
  30407. error
  30408. });
  30409. return;
  30410. }
  30411. this.logger.log(`attachMedia`);
  30412. if (this._media) {
  30413. this.logger.warn(`media must be detached before attaching`);
  30414. this.detachMedia();
  30415. }
  30416. const attachMediaSource = "media" in data;
  30417. const media = attachMediaSource ? data.media : data;
  30418. const attachingData = attachMediaSource ? data : {
  30419. media
  30420. };
  30421. this._media = media;
  30422. this.trigger(Events.MEDIA_ATTACHING, attachingData);
  30423. }
  30424. detachMedia() {
  30425. this.logger.log("detachMedia");
  30426. this.trigger(Events.MEDIA_DETACHING, {});
  30427. this._media = null;
  30428. }
  30429. transferMedia() {
  30430. this._media = null;
  30431. const transferMedia = this.bufferController.transferMedia();
  30432. this.trigger(Events.MEDIA_DETACHING, {
  30433. transferMedia
  30434. });
  30435. return transferMedia;
  30436. }
  30437. loadSource(url) {
  30438. this.stopLoad();
  30439. const media = this.media;
  30440. const loadedSource = this._url;
  30441. const loadingSource = this._url = urlToolkitExports.buildAbsoluteURL(self.location.href, url, {
  30442. alwaysNormalize: true
  30443. });
  30444. this._autoLevelCapping = -1;
  30445. this._maxHdcpLevel = null;
  30446. this.logger.log(`loadSource:${loadingSource}`);
  30447. if (media && loadedSource && (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())) {
  30448. this.detachMedia();
  30449. this.attachMedia(media);
  30450. }
  30451. this.trigger(Events.MANIFEST_LOADING, {
  30452. url
  30453. });
  30454. }
  30455. get url() {
  30456. return this._url;
  30457. }
  30458. get hasEnoughToStart() {
  30459. return this.streamController.hasEnoughToStart;
  30460. }
  30461. get startPosition() {
  30462. return this.streamController.startPositionValue;
  30463. }
  30464. startLoad(startPosition = -1, skipSeekToStartPosition) {
  30465. this.logger.log(`startLoad(${startPosition + (skipSeekToStartPosition ? ", <skip seek to start>" : "")})`);
  30466. this.started = true;
  30467. this.resumeBuffering();
  30468. for (let i = 0; i < this.networkControllers.length; i++) {
  30469. this.networkControllers[i].startLoad(startPosition, skipSeekToStartPosition);
  30470. if (!this.started || !this.networkControllers) {
  30471. break;
  30472. }
  30473. }
  30474. }
  30475. stopLoad() {
  30476. this.logger.log("stopLoad");
  30477. this.started = false;
  30478. for (let i = 0; i < this.networkControllers.length; i++) {
  30479. this.networkControllers[i].stopLoad();
  30480. if (this.started || !this.networkControllers) {
  30481. break;
  30482. }
  30483. }
  30484. }
  30485. get loadingEnabled() {
  30486. return this.started;
  30487. }
  30488. get bufferingEnabled() {
  30489. return this.streamController.bufferingEnabled;
  30490. }
  30491. resumeBuffering() {
  30492. if (!this.bufferingEnabled) {
  30493. this.logger.log(`resume buffering`);
  30494. this.networkControllers.forEach((controller) => {
  30495. if (controller.resumeBuffering) {
  30496. controller.resumeBuffering();
  30497. }
  30498. });
  30499. }
  30500. }
  30501. pauseBuffering() {
  30502. if (this.bufferingEnabled) {
  30503. this.logger.log(`pause buffering`);
  30504. this.networkControllers.forEach((controller) => {
  30505. if (controller.pauseBuffering) {
  30506. controller.pauseBuffering();
  30507. }
  30508. });
  30509. }
  30510. }
  30511. get inFlightFragments() {
  30512. const inFlightData = {
  30513. [PlaylistLevelType.MAIN]: this.streamController.inFlightFrag
  30514. };
  30515. if (this.audioStreamController) {
  30516. inFlightData[PlaylistLevelType.AUDIO] = this.audioStreamController.inFlightFrag;
  30517. }
  30518. if (this.subtititleStreamController) {
  30519. inFlightData[PlaylistLevelType.SUBTITLE] = this.subtititleStreamController.inFlightFrag;
  30520. }
  30521. return inFlightData;
  30522. }
  30523. swapAudioCodec() {
  30524. this.logger.log("swapAudioCodec");
  30525. this.streamController.swapAudioCodec();
  30526. }
  30527. recoverMediaError() {
  30528. this.logger.log("recoverMediaError");
  30529. const media = this._media;
  30530. const time = media == null ? void 0 : media.currentTime;
  30531. this.detachMedia();
  30532. if (media) {
  30533. this.attachMedia(media);
  30534. if (time) {
  30535. this.startLoad(time);
  30536. }
  30537. }
  30538. }
  30539. removeLevel(levelIndex) {
  30540. this.levelController.removeLevel(levelIndex);
  30541. }
  30542. get sessionId() {
  30543. let _sessionId = this._sessionId;
  30544. if (!_sessionId) {
  30545. _sessionId = this._sessionId = uuid();
  30546. }
  30547. return _sessionId;
  30548. }
  30549. get levels() {
  30550. const levels = this.levelController.levels;
  30551. return levels ? levels : [];
  30552. }
  30553. get latestLevelDetails() {
  30554. return this.streamController.getLevelDetails() || null;
  30555. }
  30556. get loadLevelObj() {
  30557. return this.levelController.loadLevelObj;
  30558. }
  30559. get currentLevel() {
  30560. return this.streamController.currentLevel;
  30561. }
  30562. set currentLevel(newLevel) {
  30563. this.logger.log(`set currentLevel:${newLevel}`);
  30564. this.levelController.manualLevel = newLevel;
  30565. this.streamController.immediateLevelSwitch();
  30566. }
  30567. get nextLevel() {
  30568. return this.streamController.nextLevel;
  30569. }
  30570. set nextLevel(newLevel) {
  30571. this.logger.log(`set nextLevel:${newLevel}`);
  30572. this.levelController.manualLevel = newLevel;
  30573. this.streamController.nextLevelSwitch();
  30574. }
  30575. get loadLevel() {
  30576. return this.levelController.level;
  30577. }
  30578. set loadLevel(newLevel) {
  30579. this.logger.log(`set loadLevel:${newLevel}`);
  30580. this.levelController.manualLevel = newLevel;
  30581. }
  30582. get nextLoadLevel() {
  30583. return this.levelController.nextLoadLevel;
  30584. }
  30585. set nextLoadLevel(level) {
  30586. this.levelController.nextLoadLevel = level;
  30587. }
  30588. get firstLevel() {
  30589. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  30590. }
  30591. set firstLevel(newLevel) {
  30592. this.logger.log(`set firstLevel:${newLevel}`);
  30593. this.levelController.firstLevel = newLevel;
  30594. }
  30595. get startLevel() {
  30596. const startLevel = this.levelController.startLevel;
  30597. if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {
  30598. return this.abrController.forcedAutoLevel;
  30599. }
  30600. return startLevel;
  30601. }
  30602. set startLevel(newLevel) {
  30603. this.logger.log(`set startLevel:${newLevel}`);
  30604. if (newLevel !== -1) {
  30605. newLevel = Math.max(newLevel, this.minAutoLevel);
  30606. }
  30607. this.levelController.startLevel = newLevel;
  30608. }
  30609. get capLevelToPlayerSize() {
  30610. return this.config.capLevelToPlayerSize;
  30611. }
  30612. set capLevelToPlayerSize(shouldStartCapping) {
  30613. const newCapLevelToPlayerSize = !!shouldStartCapping;
  30614. if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
  30615. if (newCapLevelToPlayerSize) {
  30616. this.capLevelController.startCapping();
  30617. } else {
  30618. this.capLevelController.stopCapping();
  30619. this.autoLevelCapping = -1;
  30620. this.streamController.nextLevelSwitch();
  30621. }
  30622. this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
  30623. }
  30624. }
  30625. get autoLevelCapping() {
  30626. return this._autoLevelCapping;
  30627. }
  30628. get bandwidthEstimate() {
  30629. const {
  30630. bwEstimator
  30631. } = this.abrController;
  30632. if (!bwEstimator) {
  30633. return NaN;
  30634. }
  30635. return bwEstimator.getEstimate();
  30636. }
  30637. set bandwidthEstimate(abrEwmaDefaultEstimate) {
  30638. this.abrController.resetEstimator(abrEwmaDefaultEstimate);
  30639. }
  30640. get abrEwmaDefaultEstimate() {
  30641. const {
  30642. bwEstimator
  30643. } = this.abrController;
  30644. if (!bwEstimator) {
  30645. return NaN;
  30646. }
  30647. return bwEstimator.defaultEstimate;
  30648. }
  30649. get ttfbEstimate() {
  30650. const {
  30651. bwEstimator
  30652. } = this.abrController;
  30653. if (!bwEstimator) {
  30654. return NaN;
  30655. }
  30656. return bwEstimator.getEstimateTTFB();
  30657. }
  30658. set autoLevelCapping(newLevel) {
  30659. if (this._autoLevelCapping !== newLevel) {
  30660. this.logger.log(`set autoLevelCapping:${newLevel}`);
  30661. this._autoLevelCapping = newLevel;
  30662. this.levelController.checkMaxAutoUpdated();
  30663. }
  30664. }
  30665. get maxHdcpLevel() {
  30666. return this._maxHdcpLevel;
  30667. }
  30668. set maxHdcpLevel(value) {
  30669. if (isHdcpLevel(value) && this._maxHdcpLevel !== value) {
  30670. this._maxHdcpLevel = value;
  30671. this.levelController.checkMaxAutoUpdated();
  30672. }
  30673. }
  30674. get autoLevelEnabled() {
  30675. return this.levelController.manualLevel === -1;
  30676. }
  30677. get manualLevel() {
  30678. return this.levelController.manualLevel;
  30679. }
  30680. get minAutoLevel() {
  30681. const {
  30682. levels,
  30683. config: {
  30684. minAutoBitrate
  30685. }
  30686. } = this;
  30687. if (!levels)
  30688. return 0;
  30689. const len = levels.length;
  30690. for (let i = 0; i < len; i++) {
  30691. if (levels[i].maxBitrate >= minAutoBitrate) {
  30692. return i;
  30693. }
  30694. }
  30695. return 0;
  30696. }
  30697. get maxAutoLevel() {
  30698. const {
  30699. levels,
  30700. autoLevelCapping,
  30701. maxHdcpLevel
  30702. } = this;
  30703. let maxAutoLevel;
  30704. if (autoLevelCapping === -1 && levels != null && levels.length) {
  30705. maxAutoLevel = levels.length - 1;
  30706. } else {
  30707. maxAutoLevel = autoLevelCapping;
  30708. }
  30709. if (maxHdcpLevel) {
  30710. for (let i = maxAutoLevel; i--; ) {
  30711. const hdcpLevel = levels[i].attrs["HDCP-LEVEL"];
  30712. if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {
  30713. return i;
  30714. }
  30715. }
  30716. }
  30717. return maxAutoLevel;
  30718. }
  30719. get firstAutoLevel() {
  30720. return this.abrController.firstAutoLevel;
  30721. }
  30722. get nextAutoLevel() {
  30723. return this.abrController.nextAutoLevel;
  30724. }
  30725. set nextAutoLevel(nextLevel) {
  30726. this.abrController.nextAutoLevel = nextLevel;
  30727. }
  30728. get playingDate() {
  30729. return this.streamController.currentProgramDateTime;
  30730. }
  30731. get mainForwardBufferInfo() {
  30732. return this.streamController.getMainFwdBufferInfo();
  30733. }
  30734. get maxBufferLength() {
  30735. return this.streamController.maxBufferLength;
  30736. }
  30737. setAudioOption(audioOption) {
  30738. var _this$audioTrackContr;
  30739. return ((_this$audioTrackContr = this.audioTrackController) == null ? void 0 : _this$audioTrackContr.setAudioOption(audioOption)) || null;
  30740. }
  30741. setSubtitleOption(subtitleOption) {
  30742. var _this$subtitleTrackCo;
  30743. return ((_this$subtitleTrackCo = this.subtitleTrackController) == null ? void 0 : _this$subtitleTrackCo.setSubtitleOption(subtitleOption)) || null;
  30744. }
  30745. get allAudioTracks() {
  30746. const audioTrackController = this.audioTrackController;
  30747. return audioTrackController ? audioTrackController.allAudioTracks : [];
  30748. }
  30749. get audioTracks() {
  30750. const audioTrackController = this.audioTrackController;
  30751. return audioTrackController ? audioTrackController.audioTracks : [];
  30752. }
  30753. get audioTrack() {
  30754. const audioTrackController = this.audioTrackController;
  30755. return audioTrackController ? audioTrackController.audioTrack : -1;
  30756. }
  30757. set audioTrack(audioTrackId) {
  30758. const audioTrackController = this.audioTrackController;
  30759. if (audioTrackController) {
  30760. audioTrackController.audioTrack = audioTrackId;
  30761. }
  30762. }
  30763. get allSubtitleTracks() {
  30764. const subtitleTrackController = this.subtitleTrackController;
  30765. return subtitleTrackController ? subtitleTrackController.allSubtitleTracks : [];
  30766. }
  30767. get subtitleTracks() {
  30768. const subtitleTrackController = this.subtitleTrackController;
  30769. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  30770. }
  30771. get subtitleTrack() {
  30772. const subtitleTrackController = this.subtitleTrackController;
  30773. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  30774. }
  30775. get media() {
  30776. return this._media;
  30777. }
  30778. set subtitleTrack(subtitleTrackId) {
  30779. const subtitleTrackController = this.subtitleTrackController;
  30780. if (subtitleTrackController) {
  30781. subtitleTrackController.subtitleTrack = subtitleTrackId;
  30782. }
  30783. }
  30784. get subtitleDisplay() {
  30785. const subtitleTrackController = this.subtitleTrackController;
  30786. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  30787. }
  30788. set subtitleDisplay(value) {
  30789. const subtitleTrackController = this.subtitleTrackController;
  30790. if (subtitleTrackController) {
  30791. subtitleTrackController.subtitleDisplay = value;
  30792. }
  30793. }
  30794. get lowLatencyMode() {
  30795. return this.config.lowLatencyMode;
  30796. }
  30797. set lowLatencyMode(mode) {
  30798. this.config.lowLatencyMode = mode;
  30799. }
  30800. get liveSyncPosition() {
  30801. return this.latencyController.liveSyncPosition;
  30802. }
  30803. get latency() {
  30804. return this.latencyController.latency;
  30805. }
  30806. get maxLatency() {
  30807. return this.latencyController.maxLatency;
  30808. }
  30809. get targetLatency() {
  30810. return this.latencyController.targetLatency;
  30811. }
  30812. set targetLatency(latency) {
  30813. this.latencyController.targetLatency = latency;
  30814. }
  30815. get drift() {
  30816. return this.latencyController.drift;
  30817. }
  30818. get forceStartLoad() {
  30819. return this.streamController.forceStartLoad;
  30820. }
  30821. get pathways() {
  30822. return this.levelController.pathways;
  30823. }
  30824. get pathwayPriority() {
  30825. return this.levelController.pathwayPriority;
  30826. }
  30827. set pathwayPriority(pathwayPriority) {
  30828. this.levelController.pathwayPriority = pathwayPriority;
  30829. }
  30830. get bufferedToEnd() {
  30831. var _this$bufferControlle;
  30832. return !!((_this$bufferControlle = this.bufferController) != null && _this$bufferControlle.bufferedToEnd);
  30833. }
  30834. get interstitialsManager() {
  30835. var _this$interstitialsCo;
  30836. return ((_this$interstitialsCo = this.interstitialsController) == null ? void 0 : _this$interstitialsCo.interstitialsManager) || null;
  30837. }
  30838. getMediaDecodingInfo(level, audioTracks = this.allAudioTracks) {
  30839. const audioTracksByGroup = getAudioTracksByGroup(audioTracks);
  30840. return getMediaDecodingInfoPromise(level, audioTracksByGroup, navigator.mediaCapabilities);
  30841. }
  30842. };
  30843. Hls.defaultConfig = void 0;
  30844. // dep:hls_js
  30845. var hls_js_default = Hls;
  30846. export {
  30847. AbrController,
  30848. AttrList,
  30849. AudioStreamController,
  30850. AudioTrackController,
  30851. BasePlaylistController,
  30852. BaseSegment,
  30853. BaseStreamController,
  30854. BufferController,
  30855. CMCDController,
  30856. CapLevelController,
  30857. ChunkMetadata,
  30858. ContentSteeringController,
  30859. Cues,
  30860. DateRange,
  30861. EMEController,
  30862. ErrorActionFlags,
  30863. ErrorController,
  30864. ErrorDetails,
  30865. ErrorTypes,
  30866. Events,
  30867. FPSController,
  30868. FetchLoader,
  30869. Fragment,
  30870. Hls,
  30871. HlsSkip,
  30872. HlsUrlParameters,
  30873. KeySystemFormats,
  30874. KeySystems,
  30875. Level,
  30876. LevelDetails,
  30877. LevelKey,
  30878. LoadStats,
  30879. M3U8Parser,
  30880. MetadataSchema,
  30881. NetworkErrorAction,
  30882. Part,
  30883. PlaylistLevelType,
  30884. SubtitleStreamController,
  30885. SubtitleTrackController,
  30886. TimelineController,
  30887. XhrLoader,
  30888. hls_js_default as default,
  30889. fetchSupported,
  30890. getMediaSource,
  30891. isMSESupported,
  30892. isSupported,
  30893. requestMediaKeySystemAccess
  30894. };
  30895. //# sourceMappingURL=hls_js.js.map