hls__js.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965
  1. import "./chunk-Y2F7D3TJ.js";
  2. // ../../../../ZhiYi/uni-app/uni-app-demo/node_modules/hls.js/dist/hls.mjs
  3. var isFiniteNumber = Number.isFinite || function(value) {
  4. return typeof value === "number" && isFinite(value);
  5. };
  6. var isSafeInteger = Number.isSafeInteger || function(value) {
  7. return typeof value === "number" && Math.abs(value) <= MAX_SAFE_INTEGER;
  8. };
  9. var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  10. var ErrorTypes = function(ErrorTypes2) {
  11. ErrorTypes2["NETWORK_ERROR"] = "networkError";
  12. ErrorTypes2["MEDIA_ERROR"] = "mediaError";
  13. ErrorTypes2["KEY_SYSTEM_ERROR"] = "keySystemError";
  14. ErrorTypes2["MUX_ERROR"] = "muxError";
  15. ErrorTypes2["OTHER_ERROR"] = "otherError";
  16. return ErrorTypes2;
  17. }({});
  18. var ErrorDetails = function(ErrorDetails2) {
  19. ErrorDetails2["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
  20. ErrorDetails2["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
  21. ErrorDetails2["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
  22. ErrorDetails2["KEY_SYSTEM_NO_CONFIGURED_LICENSE"] = "keySystemNoConfiguredLicense";
  23. ErrorDetails2["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
  24. ErrorDetails2["KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED"] = "keySystemServerCertificateRequestFailed";
  25. ErrorDetails2["KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED"] = "keySystemServerCertificateUpdateFailed";
  26. ErrorDetails2["KEY_SYSTEM_SESSION_UPDATE_FAILED"] = "keySystemSessionUpdateFailed";
  27. ErrorDetails2["KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED"] = "keySystemStatusOutputRestricted";
  28. ErrorDetails2["KEY_SYSTEM_STATUS_INTERNAL_ERROR"] = "keySystemStatusInternalError";
  29. ErrorDetails2["KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR"] = "keySystemDestroyMediaKeysError";
  30. ErrorDetails2["KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR"] = "keySystemDestroyCloseSessionError";
  31. ErrorDetails2["KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR"] = "keySystemDestroyRemoveSessionError";
  32. ErrorDetails2["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
  33. ErrorDetails2["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
  34. ErrorDetails2["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
  35. ErrorDetails2["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
  36. ErrorDetails2["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
  37. ErrorDetails2["LEVEL_LOAD_ERROR"] = "levelLoadError";
  38. ErrorDetails2["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
  39. ErrorDetails2["LEVEL_PARSING_ERROR"] = "levelParsingError";
  40. ErrorDetails2["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
  41. ErrorDetails2["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
  42. ErrorDetails2["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
  43. ErrorDetails2["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
  44. ErrorDetails2["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
  45. ErrorDetails2["FRAG_LOAD_ERROR"] = "fragLoadError";
  46. ErrorDetails2["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
  47. ErrorDetails2["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
  48. ErrorDetails2["FRAG_PARSING_ERROR"] = "fragParsingError";
  49. ErrorDetails2["FRAG_GAP"] = "fragGap";
  50. ErrorDetails2["REMUX_ALLOC_ERROR"] = "remuxAllocError";
  51. ErrorDetails2["KEY_LOAD_ERROR"] = "keyLoadError";
  52. ErrorDetails2["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
  53. ErrorDetails2["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
  54. ErrorDetails2["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
  55. ErrorDetails2["BUFFER_APPEND_ERROR"] = "bufferAppendError";
  56. ErrorDetails2["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
  57. ErrorDetails2["BUFFER_STALLED_ERROR"] = "bufferStalledError";
  58. ErrorDetails2["BUFFER_FULL_ERROR"] = "bufferFullError";
  59. ErrorDetails2["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
  60. ErrorDetails2["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
  61. ErrorDetails2["ASSET_LIST_LOAD_ERROR"] = "assetListLoadError";
  62. ErrorDetails2["ASSET_LIST_LOAD_TIMEOUT"] = "assetListLoadTimeout";
  63. ErrorDetails2["ASSET_LIST_PARSING_ERROR"] = "assetListParsingError";
  64. ErrorDetails2["INTERSTITIAL_ASSET_ITEM_ERROR"] = "interstitialAssetItemError";
  65. ErrorDetails2["INTERNAL_EXCEPTION"] = "internalException";
  66. ErrorDetails2["INTERNAL_ABORTED"] = "aborted";
  67. ErrorDetails2["ATTACH_MEDIA_ERROR"] = "attachMediaError";
  68. ErrorDetails2["UNKNOWN"] = "unknown";
  69. return ErrorDetails2;
  70. }({});
  71. var Events = function(Events2) {
  72. Events2["MEDIA_ATTACHING"] = "hlsMediaAttaching";
  73. Events2["MEDIA_ATTACHED"] = "hlsMediaAttached";
  74. Events2["MEDIA_DETACHING"] = "hlsMediaDetaching";
  75. Events2["MEDIA_DETACHED"] = "hlsMediaDetached";
  76. Events2["MEDIA_ENDED"] = "hlsMediaEnded";
  77. Events2["STALL_RESOLVED"] = "hlsStallResolved";
  78. Events2["BUFFER_RESET"] = "hlsBufferReset";
  79. Events2["BUFFER_CODECS"] = "hlsBufferCodecs";
  80. Events2["BUFFER_CREATED"] = "hlsBufferCreated";
  81. Events2["BUFFER_APPENDING"] = "hlsBufferAppending";
  82. Events2["BUFFER_APPENDED"] = "hlsBufferAppended";
  83. Events2["BUFFER_EOS"] = "hlsBufferEos";
  84. Events2["BUFFERED_TO_END"] = "hlsBufferedToEnd";
  85. Events2["BUFFER_FLUSHING"] = "hlsBufferFlushing";
  86. Events2["BUFFER_FLUSHED"] = "hlsBufferFlushed";
  87. Events2["MANIFEST_LOADING"] = "hlsManifestLoading";
  88. Events2["MANIFEST_LOADED"] = "hlsManifestLoaded";
  89. Events2["MANIFEST_PARSED"] = "hlsManifestParsed";
  90. Events2["LEVEL_SWITCHING"] = "hlsLevelSwitching";
  91. Events2["LEVEL_SWITCHED"] = "hlsLevelSwitched";
  92. Events2["LEVEL_LOADING"] = "hlsLevelLoading";
  93. Events2["LEVEL_LOADED"] = "hlsLevelLoaded";
  94. Events2["LEVEL_UPDATED"] = "hlsLevelUpdated";
  95. Events2["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
  96. Events2["LEVELS_UPDATED"] = "hlsLevelsUpdated";
  97. Events2["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
  98. Events2["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
  99. Events2["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
  100. Events2["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
  101. Events2["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
  102. Events2["AUDIO_TRACK_UPDATED"] = "hlsAudioTrackUpdated";
  103. Events2["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
  104. Events2["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
  105. Events2["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
  106. Events2["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
  107. Events2["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
  108. Events2["SUBTITLE_TRACK_UPDATED"] = "hlsSubtitleTrackUpdated";
  109. Events2["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
  110. Events2["CUES_PARSED"] = "hlsCuesParsed";
  111. Events2["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
  112. Events2["INIT_PTS_FOUND"] = "hlsInitPtsFound";
  113. Events2["FRAG_LOADING"] = "hlsFragLoading";
  114. Events2["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
  115. Events2["FRAG_LOADED"] = "hlsFragLoaded";
  116. Events2["FRAG_DECRYPTED"] = "hlsFragDecrypted";
  117. Events2["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
  118. Events2["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
  119. Events2["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
  120. Events2["FRAG_PARSED"] = "hlsFragParsed";
  121. Events2["FRAG_BUFFERED"] = "hlsFragBuffered";
  122. Events2["FRAG_CHANGED"] = "hlsFragChanged";
  123. Events2["FPS_DROP"] = "hlsFpsDrop";
  124. Events2["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
  125. Events2["MAX_AUTO_LEVEL_UPDATED"] = "hlsMaxAutoLevelUpdated";
  126. Events2["ERROR"] = "hlsError";
  127. Events2["DESTROYING"] = "hlsDestroying";
  128. Events2["KEY_LOADING"] = "hlsKeyLoading";
  129. Events2["KEY_LOADED"] = "hlsKeyLoaded";
  130. Events2["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
  131. Events2["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
  132. Events2["STEERING_MANIFEST_LOADED"] = "hlsSteeringManifestLoaded";
  133. Events2["ASSET_LIST_LOADING"] = "hlsAssetListLoading";
  134. Events2["ASSET_LIST_LOADED"] = "hlsAssetListLoaded";
  135. Events2["INTERSTITIALS_UPDATED"] = "hlsInterstitialsUpdated";
  136. Events2["INTERSTITIALS_BUFFERED_TO_BOUNDARY"] = "hlsInterstitialsBufferedToBoundary";
  137. Events2["INTERSTITIAL_ASSET_PLAYER_CREATED"] = "hlsInterstitialAssetPlayerCreated";
  138. Events2["INTERSTITIAL_STARTED"] = "hlsInterstitialStarted";
  139. Events2["INTERSTITIAL_ASSET_STARTED"] = "hlsInterstitialAssetStarted";
  140. Events2["INTERSTITIAL_ASSET_ENDED"] = "hlsInterstitialAssetEnded";
  141. Events2["INTERSTITIAL_ASSET_ERROR"] = "hlsInterstitialAssetError";
  142. Events2["INTERSTITIAL_ENDED"] = "hlsInterstitialEnded";
  143. Events2["INTERSTITIALS_PRIMARY_RESUMED"] = "hlsInterstitialsPrimaryResumed";
  144. Events2["PLAYOUT_LIMIT_REACHED"] = "hlsPlayoutLimitReached";
  145. Events2["EVENT_CUE_ENTER"] = "hlsEventCueEnter";
  146. return Events2;
  147. }({});
  148. var PlaylistContextType = {
  149. MANIFEST: "manifest",
  150. LEVEL: "level",
  151. AUDIO_TRACK: "audioTrack",
  152. SUBTITLE_TRACK: "subtitleTrack"
  153. };
  154. var PlaylistLevelType = {
  155. MAIN: "main",
  156. AUDIO: "audio",
  157. SUBTITLE: "subtitle"
  158. };
  159. var EWMA = class {
  160. // About half of the estimated value will be from the last |halfLife| samples by weight.
  161. constructor(halfLife, estimate = 0, weight = 0) {
  162. this.halfLife = void 0;
  163. this.alpha_ = void 0;
  164. this.estimate_ = void 0;
  165. this.totalWeight_ = void 0;
  166. this.halfLife = halfLife;
  167. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  168. this.estimate_ = estimate;
  169. this.totalWeight_ = weight;
  170. }
  171. sample(weight, value) {
  172. const adjAlpha = Math.pow(this.alpha_, weight);
  173. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  174. this.totalWeight_ += weight;
  175. }
  176. getTotalWeight() {
  177. return this.totalWeight_;
  178. }
  179. getEstimate() {
  180. if (this.alpha_) {
  181. const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  182. if (zeroFactor) {
  183. return this.estimate_ / zeroFactor;
  184. }
  185. }
  186. return this.estimate_;
  187. }
  188. };
  189. var EwmaBandWidthEstimator = class {
  190. constructor(slow, fast, defaultEstimate, defaultTTFB = 100) {
  191. this.defaultEstimate_ = void 0;
  192. this.minWeight_ = void 0;
  193. this.minDelayMs_ = void 0;
  194. this.slow_ = void 0;
  195. this.fast_ = void 0;
  196. this.defaultTTFB_ = void 0;
  197. this.ttfb_ = void 0;
  198. this.defaultEstimate_ = defaultEstimate;
  199. this.minWeight_ = 1e-3;
  200. this.minDelayMs_ = 50;
  201. this.slow_ = new EWMA(slow);
  202. this.fast_ = new EWMA(fast);
  203. this.defaultTTFB_ = defaultTTFB;
  204. this.ttfb_ = new EWMA(slow);
  205. }
  206. update(slow, fast) {
  207. const {
  208. slow_,
  209. fast_,
  210. ttfb_
  211. } = this;
  212. if (slow_.halfLife !== slow) {
  213. this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());
  214. }
  215. if (fast_.halfLife !== fast) {
  216. this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());
  217. }
  218. if (ttfb_.halfLife !== slow) {
  219. this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());
  220. }
  221. }
  222. sample(durationMs, numBytes) {
  223. durationMs = Math.max(durationMs, this.minDelayMs_);
  224. const numBits = 8 * numBytes;
  225. const durationS = durationMs / 1e3;
  226. const bandwidthInBps = numBits / durationS;
  227. this.fast_.sample(durationS, bandwidthInBps);
  228. this.slow_.sample(durationS, bandwidthInBps);
  229. }
  230. sampleTTFB(ttfb) {
  231. const seconds = ttfb / 1e3;
  232. const weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);
  233. this.ttfb_.sample(weight, Math.max(ttfb, 5));
  234. }
  235. canEstimate() {
  236. return this.fast_.getTotalWeight() >= this.minWeight_;
  237. }
  238. getEstimate() {
  239. if (this.canEstimate()) {
  240. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  241. } else {
  242. return this.defaultEstimate_;
  243. }
  244. }
  245. getEstimateTTFB() {
  246. if (this.ttfb_.getTotalWeight() >= this.minWeight_) {
  247. return this.ttfb_.getEstimate();
  248. } else {
  249. return this.defaultTTFB_;
  250. }
  251. }
  252. get defaultEstimate() {
  253. return this.defaultEstimate_;
  254. }
  255. destroy() {
  256. }
  257. };
  258. function _defineProperty(e, r, t) {
  259. return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
  260. value: t,
  261. enumerable: true,
  262. configurable: true,
  263. writable: true
  264. }) : e[r] = t, e;
  265. }
  266. function _extends() {
  267. return _extends = Object.assign ? Object.assign.bind() : function(n) {
  268. for (var e = 1; e < arguments.length; e++) {
  269. var t = arguments[e];
  270. for (var r in t)
  271. ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
  272. }
  273. return n;
  274. }, _extends.apply(null, arguments);
  275. }
  276. function ownKeys(e, r) {
  277. var t = Object.keys(e);
  278. if (Object.getOwnPropertySymbols) {
  279. var o = Object.getOwnPropertySymbols(e);
  280. r && (o = o.filter(function(r2) {
  281. return Object.getOwnPropertyDescriptor(e, r2).enumerable;
  282. })), t.push.apply(t, o);
  283. }
  284. return t;
  285. }
  286. function _objectSpread2(e) {
  287. for (var r = 1; r < arguments.length; r++) {
  288. var t = null != arguments[r] ? arguments[r] : {};
  289. r % 2 ? ownKeys(Object(t), true).forEach(function(r2) {
  290. _defineProperty(e, r2, t[r2]);
  291. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) {
  292. Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
  293. });
  294. }
  295. return e;
  296. }
  297. function _toPrimitive(t, r) {
  298. if ("object" != typeof t || !t)
  299. return t;
  300. var e = t[Symbol.toPrimitive];
  301. if (void 0 !== e) {
  302. var i = e.call(t, r);
  303. if ("object" != typeof i)
  304. return i;
  305. throw new TypeError("@@toPrimitive must return a primitive value.");
  306. }
  307. return ("string" === r ? String : Number)(t);
  308. }
  309. function _toPropertyKey(t) {
  310. var i = _toPrimitive(t, "string");
  311. return "symbol" == typeof i ? i : i + "";
  312. }
  313. var Logger = class {
  314. constructor(label, logger2) {
  315. this.trace = void 0;
  316. this.debug = void 0;
  317. this.log = void 0;
  318. this.warn = void 0;
  319. this.info = void 0;
  320. this.error = void 0;
  321. const lb = `[${label}]:`;
  322. this.trace = noop;
  323. this.debug = logger2.debug.bind(null, lb);
  324. this.log = logger2.log.bind(null, lb);
  325. this.warn = logger2.warn.bind(null, lb);
  326. this.info = logger2.info.bind(null, lb);
  327. this.error = logger2.error.bind(null, lb);
  328. }
  329. };
  330. var noop = function noop2() {
  331. };
  332. var fakeLogger = {
  333. trace: noop,
  334. debug: noop,
  335. log: noop,
  336. warn: noop,
  337. info: noop,
  338. error: noop
  339. };
  340. function createLogger() {
  341. return _extends({}, fakeLogger);
  342. }
  343. function consolePrintFn(type, id) {
  344. const func = self.console[type];
  345. return func ? func.bind(self.console, `${id ? "[" + id + "] " : ""}[${type}] >`) : noop;
  346. }
  347. function getLoggerFn(key, debugConfig, id) {
  348. return debugConfig[key] ? debugConfig[key].bind(debugConfig) : consolePrintFn(key, id);
  349. }
  350. var exportedLogger = createLogger();
  351. function enableLogs(debugConfig, context, id) {
  352. const newLogger = createLogger();
  353. if (typeof console === "object" && debugConfig === true || typeof debugConfig === "object") {
  354. const keys = [
  355. // Remove out from list here to hard-disable a log-level
  356. // 'trace',
  357. "debug",
  358. "log",
  359. "info",
  360. "warn",
  361. "error"
  362. ];
  363. keys.forEach((key) => {
  364. newLogger[key] = getLoggerFn(key, debugConfig, id);
  365. });
  366. try {
  367. newLogger.log(`Debug logs enabled for "${context}" in hls.js version ${"1.6.13"}`);
  368. } catch (e) {
  369. return createLogger();
  370. }
  371. keys.forEach((key) => {
  372. exportedLogger[key] = getLoggerFn(key, debugConfig);
  373. });
  374. } else {
  375. _extends(exportedLogger, newLogger);
  376. }
  377. return newLogger;
  378. }
  379. var logger = exportedLogger;
  380. function getMediaSource(preferManagedMediaSource = true) {
  381. if (typeof self === "undefined")
  382. return void 0;
  383. const mms = (preferManagedMediaSource || !self.MediaSource) && self.ManagedMediaSource;
  384. return mms || self.MediaSource || self.WebKitMediaSource;
  385. }
  386. function isManagedMediaSource(source) {
  387. return typeof self !== "undefined" && source === self.ManagedMediaSource;
  388. }
  389. function isCompatibleTrackChange(currentTracks, requiredTracks) {
  390. const trackNames = Object.keys(currentTracks);
  391. const requiredTrackNames = Object.keys(requiredTracks);
  392. const trackCount = trackNames.length;
  393. const requiredTrackCount = requiredTrackNames.length;
  394. return !trackCount || !requiredTrackCount || trackCount === requiredTrackCount && !trackNames.some((name) => requiredTrackNames.indexOf(name) === -1);
  395. }
  396. function utf8ArrayToStr(array, exitOnNull = false) {
  397. if (typeof TextDecoder !== "undefined") {
  398. const decoder = new TextDecoder("utf-8");
  399. const decoded = decoder.decode(array);
  400. if (exitOnNull) {
  401. const idx = decoded.indexOf("\0");
  402. return idx !== -1 ? decoded.substring(0, idx) : decoded;
  403. }
  404. return decoded.replace(/\0/g, "");
  405. }
  406. const len = array.length;
  407. let c;
  408. let char2;
  409. let char3;
  410. let out = "";
  411. let i = 0;
  412. while (i < len) {
  413. c = array[i++];
  414. if (c === 0 && exitOnNull) {
  415. return out;
  416. } else if (c === 0 || c === 3) {
  417. continue;
  418. }
  419. switch (c >> 4) {
  420. case 0:
  421. case 1:
  422. case 2:
  423. case 3:
  424. case 4:
  425. case 5:
  426. case 6:
  427. case 7:
  428. out += String.fromCharCode(c);
  429. break;
  430. case 12:
  431. case 13:
  432. char2 = array[i++];
  433. out += String.fromCharCode((c & 31) << 6 | char2 & 63);
  434. break;
  435. case 14:
  436. char2 = array[i++];
  437. char3 = array[i++];
  438. out += String.fromCharCode((c & 15) << 12 | (char2 & 63) << 6 | (char3 & 63) << 0);
  439. break;
  440. }
  441. }
  442. return out;
  443. }
  444. function arrayToHex(array) {
  445. let str = "";
  446. for (let i = 0; i < array.length; i++) {
  447. let h = array[i].toString(16);
  448. if (h.length < 2) {
  449. h = "0" + h;
  450. }
  451. str += h;
  452. }
  453. return str;
  454. }
  455. function hexToArrayBuffer(str) {
  456. return Uint8Array.from(str.replace(/^0x/, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")).buffer;
  457. }
  458. function getDefaultExportFromCjs(x) {
  459. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
  460. }
  461. var urlToolkit = { exports: {} };
  462. var hasRequiredUrlToolkit;
  463. function requireUrlToolkit() {
  464. if (hasRequiredUrlToolkit)
  465. return urlToolkit.exports;
  466. hasRequiredUrlToolkit = 1;
  467. (function(module, exports) {
  468. (function(root) {
  469. var URL_REGEX = /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/;
  470. var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/;
  471. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  472. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  473. var URLToolkit = {
  474. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  475. // E.g
  476. // With opts.alwaysNormalize = false (default, spec compliant)
  477. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  478. // With opts.alwaysNormalize = true (not spec compliant)
  479. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  480. buildAbsoluteURL: function(baseURL, relativeURL, opts) {
  481. opts = opts || {};
  482. baseURL = baseURL.trim();
  483. relativeURL = relativeURL.trim();
  484. if (!relativeURL) {
  485. if (!opts.alwaysNormalize) {
  486. return baseURL;
  487. }
  488. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  489. if (!basePartsForNormalise) {
  490. throw new Error("Error trying to parse base URL.");
  491. }
  492. basePartsForNormalise.path = URLToolkit.normalizePath(
  493. basePartsForNormalise.path
  494. );
  495. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  496. }
  497. var relativeParts = URLToolkit.parseURL(relativeURL);
  498. if (!relativeParts) {
  499. throw new Error("Error trying to parse relative URL.");
  500. }
  501. if (relativeParts.scheme) {
  502. if (!opts.alwaysNormalize) {
  503. return relativeURL;
  504. }
  505. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  506. return URLToolkit.buildURLFromParts(relativeParts);
  507. }
  508. var baseParts = URLToolkit.parseURL(baseURL);
  509. if (!baseParts) {
  510. throw new Error("Error trying to parse base URL.");
  511. }
  512. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== "/") {
  513. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  514. baseParts.netLoc = pathParts[1];
  515. baseParts.path = pathParts[2];
  516. }
  517. if (baseParts.netLoc && !baseParts.path) {
  518. baseParts.path = "/";
  519. }
  520. var builtParts = {
  521. // 2c) Otherwise, the embedded URL inherits the scheme of
  522. // the base URL.
  523. scheme: baseParts.scheme,
  524. netLoc: relativeParts.netLoc,
  525. path: null,
  526. params: relativeParts.params,
  527. query: relativeParts.query,
  528. fragment: relativeParts.fragment
  529. };
  530. if (!relativeParts.netLoc) {
  531. builtParts.netLoc = baseParts.netLoc;
  532. if (relativeParts.path[0] !== "/") {
  533. if (!relativeParts.path) {
  534. builtParts.path = baseParts.path;
  535. if (!relativeParts.params) {
  536. builtParts.params = baseParts.params;
  537. if (!relativeParts.query) {
  538. builtParts.query = baseParts.query;
  539. }
  540. }
  541. } else {
  542. var baseURLPath = baseParts.path;
  543. var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf("/") + 1) + relativeParts.path;
  544. builtParts.path = URLToolkit.normalizePath(newPath);
  545. }
  546. }
  547. }
  548. if (builtParts.path === null) {
  549. builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
  550. }
  551. return URLToolkit.buildURLFromParts(builtParts);
  552. },
  553. parseURL: function(url) {
  554. var parts = URL_REGEX.exec(url);
  555. if (!parts) {
  556. return null;
  557. }
  558. return {
  559. scheme: parts[1] || "",
  560. netLoc: parts[2] || "",
  561. path: parts[3] || "",
  562. params: parts[4] || "",
  563. query: parts[5] || "",
  564. fragment: parts[6] || ""
  565. };
  566. },
  567. normalizePath: function(path) {
  568. path = path.split("").reverse().join("").replace(SLASH_DOT_REGEX, "");
  569. while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, "")).length) {
  570. }
  571. return path.split("").reverse().join("");
  572. },
  573. buildURLFromParts: function(parts) {
  574. return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
  575. }
  576. };
  577. module.exports = URLToolkit;
  578. })();
  579. })(urlToolkit);
  580. return urlToolkit.exports;
  581. }
  582. var urlToolkitExports = requireUrlToolkit();
  583. var LoadStats = class {
  584. constructor() {
  585. this.aborted = false;
  586. this.loaded = 0;
  587. this.retry = 0;
  588. this.total = 0;
  589. this.chunkCount = 0;
  590. this.bwEstimate = 0;
  591. this.loading = {
  592. start: 0,
  593. first: 0,
  594. end: 0
  595. };
  596. this.parsing = {
  597. start: 0,
  598. end: 0
  599. };
  600. this.buffering = {
  601. start: 0,
  602. first: 0,
  603. end: 0
  604. };
  605. }
  606. };
  607. var ElementaryStreamTypes = {
  608. AUDIO: "audio",
  609. VIDEO: "video",
  610. AUDIOVIDEO: "audiovideo"
  611. };
  612. var BaseSegment = class {
  613. constructor(base) {
  614. this._byteRange = null;
  615. this._url = null;
  616. this._stats = null;
  617. this._streams = null;
  618. this.base = void 0;
  619. this.relurl = void 0;
  620. if (typeof base === "string") {
  621. base = {
  622. url: base
  623. };
  624. }
  625. this.base = base;
  626. makeEnumerable(this, "stats");
  627. }
  628. // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
  629. setByteRange(value, previous) {
  630. const params = value.split("@", 2);
  631. let start;
  632. if (params.length === 1) {
  633. start = (previous == null ? void 0 : previous.byteRangeEndOffset) || 0;
  634. } else {
  635. start = parseInt(params[1]);
  636. }
  637. this._byteRange = [start, parseInt(params[0]) + start];
  638. }
  639. get baseurl() {
  640. return this.base.url;
  641. }
  642. get byteRange() {
  643. if (this._byteRange === null) {
  644. return [];
  645. }
  646. return this._byteRange;
  647. }
  648. get byteRangeStartOffset() {
  649. return this.byteRange[0];
  650. }
  651. get byteRangeEndOffset() {
  652. return this.byteRange[1];
  653. }
  654. get elementaryStreams() {
  655. if (this._streams === null) {
  656. this._streams = {
  657. [ElementaryStreamTypes.AUDIO]: null,
  658. [ElementaryStreamTypes.VIDEO]: null,
  659. [ElementaryStreamTypes.AUDIOVIDEO]: null
  660. };
  661. }
  662. return this._streams;
  663. }
  664. set elementaryStreams(value) {
  665. this._streams = value;
  666. }
  667. get hasStats() {
  668. return this._stats !== null;
  669. }
  670. get hasStreams() {
  671. return this._streams !== null;
  672. }
  673. get stats() {
  674. if (this._stats === null) {
  675. this._stats = new LoadStats();
  676. }
  677. return this._stats;
  678. }
  679. set stats(value) {
  680. this._stats = value;
  681. }
  682. get url() {
  683. if (!this._url && this.baseurl && this.relurl) {
  684. this._url = urlToolkitExports.buildAbsoluteURL(this.baseurl, this.relurl, {
  685. alwaysNormalize: true
  686. });
  687. }
  688. return this._url || "";
  689. }
  690. set url(value) {
  691. this._url = value;
  692. }
  693. clearElementaryStreamInfo() {
  694. const {
  695. elementaryStreams
  696. } = this;
  697. elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
  698. elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
  699. elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
  700. }
  701. };
  702. function isMediaFragment(frag) {
  703. return frag.sn !== "initSegment";
  704. }
  705. var Fragment = class extends BaseSegment {
  706. constructor(type, base) {
  707. super(base);
  708. this._decryptdata = null;
  709. this._programDateTime = null;
  710. this._ref = null;
  711. this._bitrate = void 0;
  712. this.rawProgramDateTime = null;
  713. this.tagList = [];
  714. this.duration = 0;
  715. this.sn = 0;
  716. this.levelkeys = void 0;
  717. this.type = void 0;
  718. this.loader = null;
  719. this.keyLoader = null;
  720. this.level = -1;
  721. this.cc = 0;
  722. this.startPTS = void 0;
  723. this.endPTS = void 0;
  724. this.startDTS = void 0;
  725. this.endDTS = void 0;
  726. this.start = 0;
  727. this.playlistOffset = 0;
  728. this.deltaPTS = void 0;
  729. this.maxStartPTS = void 0;
  730. this.minEndPTS = void 0;
  731. this.data = void 0;
  732. this.bitrateTest = false;
  733. this.title = null;
  734. this.initSegment = null;
  735. this.endList = void 0;
  736. this.gap = void 0;
  737. this.urlId = 0;
  738. this.type = type;
  739. }
  740. get byteLength() {
  741. if (this.hasStats) {
  742. const total = this.stats.total;
  743. if (total) {
  744. return total;
  745. }
  746. }
  747. if (this.byteRange.length) {
  748. const start = this.byteRange[0];
  749. const end = this.byteRange[1];
  750. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  751. return end - start;
  752. }
  753. }
  754. return null;
  755. }
  756. get bitrate() {
  757. if (this.byteLength) {
  758. return this.byteLength * 8 / this.duration;
  759. }
  760. if (this._bitrate) {
  761. return this._bitrate;
  762. }
  763. return null;
  764. }
  765. set bitrate(value) {
  766. this._bitrate = value;
  767. }
  768. get decryptdata() {
  769. var _this$_decryptdata;
  770. const {
  771. levelkeys
  772. } = this;
  773. if (!levelkeys || levelkeys.NONE) {
  774. return null;
  775. }
  776. if (levelkeys.identity) {
  777. if (!this._decryptdata) {
  778. this._decryptdata = levelkeys.identity.getDecryptData(this.sn);
  779. }
  780. } else if (!((_this$_decryptdata = this._decryptdata) != null && _this$_decryptdata.keyId)) {
  781. const keyFormats = Object.keys(levelkeys);
  782. if (keyFormats.length === 1) {
  783. const levelKey = this._decryptdata = levelkeys[keyFormats[0]] || null;
  784. if (levelKey) {
  785. this._decryptdata = levelKey.getDecryptData(this.sn, levelkeys);
  786. }
  787. }
  788. }
  789. return this._decryptdata;
  790. }
  791. get end() {
  792. return this.start + this.duration;
  793. }
  794. get endProgramDateTime() {
  795. if (this.programDateTime === null) {
  796. return null;
  797. }
  798. const duration = !isFiniteNumber(this.duration) ? 0 : this.duration;
  799. return this.programDateTime + duration * 1e3;
  800. }
  801. get encrypted() {
  802. var _this$_decryptdata2;
  803. if ((_this$_decryptdata2 = this._decryptdata) != null && _this$_decryptdata2.encrypted) {
  804. return true;
  805. } else if (this.levelkeys) {
  806. var _this$levelkeys$keyFo;
  807. const keyFormats = Object.keys(this.levelkeys);
  808. const len = keyFormats.length;
  809. if (len > 1 || len === 1 && (_this$levelkeys$keyFo = this.levelkeys[keyFormats[0]]) != null && _this$levelkeys$keyFo.encrypted) {
  810. return true;
  811. }
  812. }
  813. return false;
  814. }
  815. get programDateTime() {
  816. if (this._programDateTime === null && this.rawProgramDateTime) {
  817. this.programDateTime = Date.parse(this.rawProgramDateTime);
  818. }
  819. return this._programDateTime;
  820. }
  821. set programDateTime(value) {
  822. if (!isFiniteNumber(value)) {
  823. this._programDateTime = this.rawProgramDateTime = null;
  824. return;
  825. }
  826. this._programDateTime = value;
  827. }
  828. get ref() {
  829. if (!isMediaFragment(this)) {
  830. return null;
  831. }
  832. if (!this._ref) {
  833. this._ref = {
  834. base: this.base,
  835. start: this.start,
  836. duration: this.duration,
  837. sn: this.sn,
  838. programDateTime: this.programDateTime
  839. };
  840. }
  841. return this._ref;
  842. }
  843. addStart(value) {
  844. this.setStart(this.start + value);
  845. }
  846. setStart(value) {
  847. this.start = value;
  848. if (this._ref) {
  849. this._ref.start = value;
  850. }
  851. }
  852. setDuration(value) {
  853. this.duration = value;
  854. if (this._ref) {
  855. this._ref.duration = value;
  856. }
  857. }
  858. setKeyFormat(keyFormat) {
  859. const levelkeys = this.levelkeys;
  860. if (levelkeys) {
  861. var _this$_decryptdata3;
  862. const key = levelkeys[keyFormat];
  863. if (key && !((_this$_decryptdata3 = this._decryptdata) != null && _this$_decryptdata3.keyId)) {
  864. this._decryptdata = key.getDecryptData(this.sn, levelkeys);
  865. }
  866. }
  867. }
  868. abortRequests() {
  869. var _this$loader, _this$keyLoader;
  870. (_this$loader = this.loader) == null || _this$loader.abort();
  871. (_this$keyLoader = this.keyLoader) == null || _this$keyLoader.abort();
  872. }
  873. setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial = false) {
  874. const {
  875. elementaryStreams
  876. } = this;
  877. const info = elementaryStreams[type];
  878. if (!info) {
  879. elementaryStreams[type] = {
  880. startPTS,
  881. endPTS,
  882. startDTS,
  883. endDTS,
  884. partial
  885. };
  886. return;
  887. }
  888. info.startPTS = Math.min(info.startPTS, startPTS);
  889. info.endPTS = Math.max(info.endPTS, endPTS);
  890. info.startDTS = Math.min(info.startDTS, startDTS);
  891. info.endDTS = Math.max(info.endDTS, endDTS);
  892. }
  893. };
  894. var Part = class extends BaseSegment {
  895. constructor(partAttrs, frag, base, index, previous) {
  896. super(base);
  897. this.fragOffset = 0;
  898. this.duration = 0;
  899. this.gap = false;
  900. this.independent = false;
  901. this.relurl = void 0;
  902. this.fragment = void 0;
  903. this.index = void 0;
  904. this.duration = partAttrs.decimalFloatingPoint("DURATION");
  905. this.gap = partAttrs.bool("GAP");
  906. this.independent = partAttrs.bool("INDEPENDENT");
  907. this.relurl = partAttrs.enumeratedString("URI");
  908. this.fragment = frag;
  909. this.index = index;
  910. const byteRange = partAttrs.enumeratedString("BYTERANGE");
  911. if (byteRange) {
  912. this.setByteRange(byteRange, previous);
  913. }
  914. if (previous) {
  915. this.fragOffset = previous.fragOffset + previous.duration;
  916. }
  917. }
  918. get start() {
  919. return this.fragment.start + this.fragOffset;
  920. }
  921. get end() {
  922. return this.start + this.duration;
  923. }
  924. get loaded() {
  925. const {
  926. elementaryStreams
  927. } = this;
  928. return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
  929. }
  930. };
  931. function getOwnPropertyDescriptorFromPrototypeChain(object, property) {
  932. const prototype = Object.getPrototypeOf(object);
  933. if (prototype) {
  934. const propertyDescriptor = Object.getOwnPropertyDescriptor(prototype, property);
  935. if (propertyDescriptor) {
  936. return propertyDescriptor;
  937. }
  938. return getOwnPropertyDescriptorFromPrototypeChain(prototype, property);
  939. }
  940. }
  941. function makeEnumerable(object, property) {
  942. const d = getOwnPropertyDescriptorFromPrototypeChain(object, property);
  943. if (d) {
  944. d.enumerable = true;
  945. Object.defineProperty(object, property, d);
  946. }
  947. }
  948. var UINT32_MAX$1 = Math.pow(2, 32) - 1;
  949. var push = [].push;
  950. var RemuxerTrackIdConfig = {
  951. video: 1,
  952. audio: 2,
  953. id3: 3,
  954. text: 4
  955. };
  956. function bin2str(data) {
  957. return String.fromCharCode.apply(null, data);
  958. }
  959. function readUint16(buffer, offset) {
  960. const val = buffer[offset] << 8 | buffer[offset + 1];
  961. return val < 0 ? 65536 + val : val;
  962. }
  963. function readUint32(buffer, offset) {
  964. const val = readSint32(buffer, offset);
  965. return val < 0 ? 4294967296 + val : val;
  966. }
  967. function readUint64(buffer, offset) {
  968. let result = readUint32(buffer, offset);
  969. result *= Math.pow(2, 32);
  970. result += readUint32(buffer, offset + 4);
  971. return result;
  972. }
  973. function readSint32(buffer, offset) {
  974. return buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
  975. }
  976. function hasMoofData(data) {
  977. const end = data.byteLength;
  978. for (let i = 0; i < end; ) {
  979. const size = readUint32(data, i);
  980. if (size > 8 && data[i + 4] === 109 && data[i + 5] === 111 && data[i + 6] === 111 && data[i + 7] === 102) {
  981. return true;
  982. }
  983. i = size > 1 ? i + size : end;
  984. }
  985. return false;
  986. }
  987. function findBox(data, path) {
  988. const results = [];
  989. if (!path.length) {
  990. return results;
  991. }
  992. const end = data.byteLength;
  993. for (let i = 0; i < end; ) {
  994. const size = readUint32(data, i);
  995. const type = bin2str(data.subarray(i + 4, i + 8));
  996. const endbox = size > 1 ? i + size : end;
  997. if (type === path[0]) {
  998. if (path.length === 1) {
  999. results.push(data.subarray(i + 8, endbox));
  1000. } else {
  1001. const subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));
  1002. if (subresults.length) {
  1003. push.apply(results, subresults);
  1004. }
  1005. }
  1006. }
  1007. i = endbox;
  1008. }
  1009. return results;
  1010. }
  1011. function parseSegmentIndex(sidx) {
  1012. const references = [];
  1013. const version2 = sidx[0];
  1014. let index = 8;
  1015. const timescale = readUint32(sidx, index);
  1016. index += 4;
  1017. let earliestPresentationTime = 0;
  1018. let firstOffset = 0;
  1019. if (version2 === 0) {
  1020. earliestPresentationTime = readUint32(sidx, index);
  1021. firstOffset = readUint32(sidx, index + 4);
  1022. index += 8;
  1023. } else {
  1024. earliestPresentationTime = readUint64(sidx, index);
  1025. firstOffset = readUint64(sidx, index + 8);
  1026. index += 16;
  1027. }
  1028. index += 2;
  1029. let startByte = sidx.length + firstOffset;
  1030. const referencesCount = readUint16(sidx, index);
  1031. index += 2;
  1032. for (let i = 0; i < referencesCount; i++) {
  1033. let referenceIndex = index;
  1034. const referenceInfo = readUint32(sidx, referenceIndex);
  1035. referenceIndex += 4;
  1036. const referenceSize = referenceInfo & 2147483647;
  1037. const referenceType = (referenceInfo & 2147483648) >>> 31;
  1038. if (referenceType === 1) {
  1039. logger.warn("SIDX has hierarchical references (not supported)");
  1040. return null;
  1041. }
  1042. const subsegmentDuration = readUint32(sidx, referenceIndex);
  1043. referenceIndex += 4;
  1044. references.push({
  1045. referenceSize,
  1046. subsegmentDuration,
  1047. // unscaled
  1048. info: {
  1049. duration: subsegmentDuration / timescale,
  1050. start: startByte,
  1051. end: startByte + referenceSize - 1
  1052. }
  1053. });
  1054. startByte += referenceSize;
  1055. referenceIndex += 4;
  1056. index = referenceIndex;
  1057. }
  1058. return {
  1059. earliestPresentationTime,
  1060. timescale,
  1061. version: version2,
  1062. referencesCount,
  1063. references
  1064. };
  1065. }
  1066. function parseInitSegment(initSegment) {
  1067. const result = [];
  1068. const traks = findBox(initSegment, ["moov", "trak"]);
  1069. for (let i = 0; i < traks.length; i++) {
  1070. const trak = traks[i];
  1071. const tkhd = findBox(trak, ["tkhd"])[0];
  1072. if (tkhd) {
  1073. let version2 = tkhd[0];
  1074. const trackId = readUint32(tkhd, version2 === 0 ? 12 : 20);
  1075. const mdhd = findBox(trak, ["mdia", "mdhd"])[0];
  1076. if (mdhd) {
  1077. version2 = mdhd[0];
  1078. const timescale = readUint32(mdhd, version2 === 0 ? 12 : 20);
  1079. const hdlr = findBox(trak, ["mdia", "hdlr"])[0];
  1080. if (hdlr) {
  1081. const hdlrType = bin2str(hdlr.subarray(8, 12));
  1082. const type = {
  1083. soun: ElementaryStreamTypes.AUDIO,
  1084. vide: ElementaryStreamTypes.VIDEO
  1085. }[hdlrType];
  1086. const stsdBox = findBox(trak, ["mdia", "minf", "stbl", "stsd"])[0];
  1087. const stsd = parseStsd(stsdBox);
  1088. if (type) {
  1089. result[trackId] = {
  1090. timescale,
  1091. type,
  1092. stsd
  1093. };
  1094. result[type] = _objectSpread2({
  1095. timescale,
  1096. id: trackId
  1097. }, stsd);
  1098. } else {
  1099. result[trackId] = {
  1100. timescale,
  1101. type: hdlrType,
  1102. stsd
  1103. };
  1104. }
  1105. }
  1106. }
  1107. }
  1108. }
  1109. const trex = findBox(initSegment, ["moov", "mvex", "trex"]);
  1110. trex.forEach((trex2) => {
  1111. const trackId = readUint32(trex2, 4);
  1112. const track = result[trackId];
  1113. if (track) {
  1114. track.default = {
  1115. duration: readUint32(trex2, 12),
  1116. flags: readUint32(trex2, 20)
  1117. };
  1118. }
  1119. });
  1120. return result;
  1121. }
  1122. function parseStsd(stsd) {
  1123. const sampleEntries = stsd.subarray(8);
  1124. const sampleEntriesEnd = sampleEntries.subarray(8 + 78);
  1125. const fourCC = bin2str(sampleEntries.subarray(4, 8));
  1126. let codec = fourCC;
  1127. let supplemental;
  1128. const encrypted = fourCC === "enca" || fourCC === "encv";
  1129. if (encrypted) {
  1130. const encBox = findBox(sampleEntries, [fourCC])[0];
  1131. const encBoxChildren = encBox.subarray(fourCC === "enca" ? 28 : 78);
  1132. const sinfs = findBox(encBoxChildren, ["sinf"]);
  1133. sinfs.forEach((sinf) => {
  1134. const schm = findBox(sinf, ["schm"])[0];
  1135. if (schm) {
  1136. const scheme = bin2str(schm.subarray(4, 8));
  1137. if (scheme === "cbcs" || scheme === "cenc") {
  1138. const frma = findBox(sinf, ["frma"])[0];
  1139. if (frma) {
  1140. codec = bin2str(frma);
  1141. }
  1142. }
  1143. }
  1144. });
  1145. }
  1146. const codecFourCC = codec;
  1147. switch (codec) {
  1148. case "avc1":
  1149. case "avc2":
  1150. case "avc3":
  1151. case "avc4": {
  1152. const avcCBox = findBox(sampleEntriesEnd, ["avcC"])[0];
  1153. if (avcCBox && avcCBox.length > 3) {
  1154. codec += "." + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]);
  1155. supplemental = parseSupplementalDoViCodec(codecFourCC === "avc1" ? "dva1" : "dvav", sampleEntriesEnd);
  1156. }
  1157. break;
  1158. }
  1159. case "mp4a": {
  1160. const codecBox = findBox(sampleEntries, [fourCC])[0];
  1161. const esdsBox = findBox(codecBox.subarray(28), ["esds"])[0];
  1162. if (esdsBox && esdsBox.length > 7) {
  1163. let i = 4;
  1164. if (esdsBox[i++] !== 3) {
  1165. break;
  1166. }
  1167. i = skipBERInteger(esdsBox, i);
  1168. i += 2;
  1169. const flags = esdsBox[i++];
  1170. if (flags & 128) {
  1171. i += 2;
  1172. }
  1173. if (flags & 64) {
  1174. i += esdsBox[i++];
  1175. }
  1176. if (esdsBox[i++] !== 4) {
  1177. break;
  1178. }
  1179. i = skipBERInteger(esdsBox, i);
  1180. const objectType = esdsBox[i++];
  1181. if (objectType === 64) {
  1182. codec += "." + toHex(objectType);
  1183. } else {
  1184. break;
  1185. }
  1186. i += 12;
  1187. if (esdsBox[i++] !== 5) {
  1188. break;
  1189. }
  1190. i = skipBERInteger(esdsBox, i);
  1191. const firstByte = esdsBox[i++];
  1192. let audioObjectType = (firstByte & 248) >> 3;
  1193. if (audioObjectType === 31) {
  1194. audioObjectType += 1 + ((firstByte & 7) << 3) + ((esdsBox[i] & 224) >> 5);
  1195. }
  1196. codec += "." + audioObjectType;
  1197. }
  1198. break;
  1199. }
  1200. case "hvc1":
  1201. case "hev1": {
  1202. const hvcCBox = findBox(sampleEntriesEnd, ["hvcC"])[0];
  1203. if (hvcCBox && hvcCBox.length > 12) {
  1204. const profileByte = hvcCBox[1];
  1205. const profileSpace = ["", "A", "B", "C"][profileByte >> 6];
  1206. const generalProfileIdc = profileByte & 31;
  1207. const profileCompat = readUint32(hvcCBox, 2);
  1208. const tierFlag = (profileByte & 32) >> 5 ? "H" : "L";
  1209. const levelIDC = hvcCBox[12];
  1210. const constraintIndicator = hvcCBox.subarray(6, 12);
  1211. codec += "." + profileSpace + generalProfileIdc;
  1212. codec += "." + reverse32BitInt(profileCompat).toString(16).toUpperCase();
  1213. codec += "." + tierFlag + levelIDC;
  1214. let constraintString = "";
  1215. for (let i = constraintIndicator.length; i--; ) {
  1216. const byte = constraintIndicator[i];
  1217. if (byte || constraintString) {
  1218. const encodedByte = byte.toString(16).toUpperCase();
  1219. constraintString = "." + encodedByte + constraintString;
  1220. }
  1221. }
  1222. codec += constraintString;
  1223. }
  1224. supplemental = parseSupplementalDoViCodec(codecFourCC == "hev1" ? "dvhe" : "dvh1", sampleEntriesEnd);
  1225. break;
  1226. }
  1227. case "dvh1":
  1228. case "dvhe":
  1229. case "dvav":
  1230. case "dva1":
  1231. case "dav1": {
  1232. codec = parseSupplementalDoViCodec(codec, sampleEntriesEnd) || codec;
  1233. break;
  1234. }
  1235. case "vp09": {
  1236. const vpcCBox = findBox(sampleEntriesEnd, ["vpcC"])[0];
  1237. if (vpcCBox && vpcCBox.length > 6) {
  1238. const profile = vpcCBox[4];
  1239. const level = vpcCBox[5];
  1240. const bitDepth = vpcCBox[6] >> 4 & 15;
  1241. codec += "." + addLeadingZero(profile) + "." + addLeadingZero(level) + "." + addLeadingZero(bitDepth);
  1242. }
  1243. break;
  1244. }
  1245. case "av01": {
  1246. const av1CBox = findBox(sampleEntriesEnd, ["av1C"])[0];
  1247. if (av1CBox && av1CBox.length > 2) {
  1248. const profile = av1CBox[1] >>> 5;
  1249. const level = av1CBox[1] & 31;
  1250. const tierFlag = av1CBox[2] >>> 7 ? "H" : "M";
  1251. const highBitDepth = (av1CBox[2] & 64) >> 6;
  1252. const twelveBit = (av1CBox[2] & 32) >> 5;
  1253. const bitDepth = profile === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8;
  1254. const monochrome = (av1CBox[2] & 16) >> 4;
  1255. const chromaSubsamplingX = (av1CBox[2] & 8) >> 3;
  1256. const chromaSubsamplingY = (av1CBox[2] & 4) >> 2;
  1257. const chromaSamplePosition = av1CBox[2] & 3;
  1258. const colorPrimaries = 1;
  1259. const transferCharacteristics = 1;
  1260. const matrixCoefficients = 1;
  1261. const videoFullRangeFlag = 0;
  1262. codec += "." + profile + "." + addLeadingZero(level) + tierFlag + "." + addLeadingZero(bitDepth) + "." + monochrome + "." + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition + "." + addLeadingZero(colorPrimaries) + "." + addLeadingZero(transferCharacteristics) + "." + addLeadingZero(matrixCoefficients) + "." + videoFullRangeFlag;
  1263. supplemental = parseSupplementalDoViCodec("dav1", sampleEntriesEnd);
  1264. }
  1265. break;
  1266. }
  1267. }
  1268. return {
  1269. codec,
  1270. encrypted,
  1271. supplemental
  1272. };
  1273. }
  1274. function parseSupplementalDoViCodec(fourCC, sampleEntriesEnd) {
  1275. const dvvCResult = findBox(sampleEntriesEnd, ["dvvC"]);
  1276. const dvXCBox = dvvCResult.length ? dvvCResult[0] : findBox(sampleEntriesEnd, ["dvcC"])[0];
  1277. if (dvXCBox) {
  1278. const doViProfile = dvXCBox[2] >> 1 & 127;
  1279. const doViLevel = dvXCBox[2] << 5 & 32 | dvXCBox[3] >> 3 & 31;
  1280. return fourCC + "." + addLeadingZero(doViProfile) + "." + addLeadingZero(doViLevel);
  1281. }
  1282. }
  1283. function reverse32BitInt(val) {
  1284. let result = 0;
  1285. for (let i = 0; i < 32; i++) {
  1286. result |= (val >> i & 1) << 32 - 1 - i;
  1287. }
  1288. return result >>> 0;
  1289. }
  1290. function skipBERInteger(bytes, i) {
  1291. const limit = i + 5;
  1292. while (bytes[i++] & 128 && i < limit) {
  1293. }
  1294. return i;
  1295. }
  1296. function toHex(x) {
  1297. return ("0" + x.toString(16).toUpperCase()).slice(-2);
  1298. }
  1299. function addLeadingZero(num) {
  1300. return (num < 10 ? "0" : "") + num;
  1301. }
  1302. function patchEncyptionData(initSegment, decryptdata) {
  1303. if (!initSegment || !decryptdata) {
  1304. return;
  1305. }
  1306. const keyId = decryptdata.keyId;
  1307. if (keyId && decryptdata.isCommonEncryption) {
  1308. applyToTencBoxes(initSegment, (tenc, isAudio) => {
  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: ${arrayToHex(tencKeyId)} -> ${arrayToHex(keyId)}`);
  1312. tenc.set(keyId, 8);
  1313. }
  1314. });
  1315. }
  1316. }
  1317. function parseKeyIdsFromTenc(initSegment) {
  1318. const keyIds = [];
  1319. applyToTencBoxes(initSegment, (tenc) => keyIds.push(tenc.subarray(8, 24)));
  1320. return keyIds;
  1321. }
  1322. function applyToTencBoxes(initSegment, predicate) {
  1323. const traks = findBox(initSegment, ["moov", "trak"]);
  1324. traks.forEach((trak) => {
  1325. const stsd = findBox(trak, ["mdia", "minf", "stbl", "stsd"])[0];
  1326. if (!stsd)
  1327. return;
  1328. const sampleEntries = stsd.subarray(8);
  1329. let encBoxes = findBox(sampleEntries, ["enca"]);
  1330. const isAudio = encBoxes.length > 0;
  1331. if (!isAudio) {
  1332. encBoxes = findBox(sampleEntries, ["encv"]);
  1333. }
  1334. encBoxes.forEach((enc) => {
  1335. const encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);
  1336. const sinfBoxes = findBox(encBoxChildren, ["sinf"]);
  1337. sinfBoxes.forEach((sinf) => {
  1338. const tenc = parseSinf(sinf);
  1339. if (tenc) {
  1340. predicate(tenc, isAudio);
  1341. }
  1342. });
  1343. });
  1344. });
  1345. }
  1346. function parseSinf(sinf) {
  1347. const schm = findBox(sinf, ["schm"])[0];
  1348. if (schm) {
  1349. const scheme = bin2str(schm.subarray(4, 8));
  1350. if (scheme === "cbcs" || scheme === "cenc") {
  1351. const tenc = findBox(sinf, ["schi", "tenc"])[0];
  1352. if (tenc) {
  1353. return tenc;
  1354. }
  1355. }
  1356. }
  1357. }
  1358. function getSampleData(data, initData, logger2) {
  1359. const tracks = {};
  1360. const trafs = findBox(data, ["moof", "traf"]);
  1361. for (let i = 0; i < trafs.length; i++) {
  1362. const traf = trafs[i];
  1363. const tfhd = findBox(traf, ["tfhd"])[0];
  1364. const id = readUint32(tfhd, 4);
  1365. const track = initData[id];
  1366. if (!track) {
  1367. continue;
  1368. }
  1369. tracks[id] || (tracks[id] = {
  1370. start: NaN,
  1371. duration: 0,
  1372. sampleCount: 0,
  1373. timescale: track.timescale,
  1374. type: track.type
  1375. });
  1376. const trackTimes = tracks[id];
  1377. const tfdt = findBox(traf, ["tfdt"])[0];
  1378. if (tfdt) {
  1379. const version2 = tfdt[0];
  1380. let baseTime = readUint32(tfdt, 4);
  1381. if (version2 === 1) {
  1382. if (baseTime === UINT32_MAX$1) {
  1383. logger2.warn(`[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`);
  1384. } else {
  1385. baseTime *= UINT32_MAX$1 + 1;
  1386. baseTime += readUint32(tfdt, 8);
  1387. }
  1388. }
  1389. if (isFiniteNumber(baseTime) && (!isFiniteNumber(trackTimes.start) || baseTime < trackTimes.start)) {
  1390. trackTimes.start = baseTime;
  1391. }
  1392. }
  1393. const trackDefault = track.default;
  1394. const tfhdFlags = readUint32(tfhd, 0) | (trackDefault == null ? void 0 : trackDefault.flags);
  1395. let defaultSampleDuration = (trackDefault == null ? void 0 : trackDefault.duration) || 0;
  1396. if (tfhdFlags & 8) {
  1397. if (tfhdFlags & 2) {
  1398. defaultSampleDuration = readUint32(tfhd, 12);
  1399. } else {
  1400. defaultSampleDuration = readUint32(tfhd, 8);
  1401. }
  1402. }
  1403. const truns = findBox(traf, ["trun"]);
  1404. let sampleDTS = trackTimes.start || 0;
  1405. let rawDuration = 0;
  1406. let sampleDuration = defaultSampleDuration;
  1407. for (let j = 0; j < truns.length; j++) {
  1408. const trun = truns[j];
  1409. const sampleCount = readUint32(trun, 4);
  1410. const sampleIndex = trackTimes.sampleCount;
  1411. trackTimes.sampleCount += sampleCount;
  1412. const dataOffsetPresent = trun[3] & 1;
  1413. const firstSampleFlagsPresent = trun[3] & 4;
  1414. const sampleDurationPresent = trun[2] & 1;
  1415. const sampleSizePresent = trun[2] & 2;
  1416. const sampleFlagsPresent = trun[2] & 4;
  1417. const sampleCompositionTimeOffsetPresent = trun[2] & 8;
  1418. let offset = 8;
  1419. let remaining = sampleCount;
  1420. if (dataOffsetPresent) {
  1421. offset += 4;
  1422. }
  1423. if (firstSampleFlagsPresent && sampleCount) {
  1424. const isNonSyncSample = trun[offset + 1] & 1;
  1425. if (!isNonSyncSample && trackTimes.keyFrameIndex === void 0) {
  1426. trackTimes.keyFrameIndex = sampleIndex;
  1427. }
  1428. offset += 4;
  1429. if (sampleDurationPresent) {
  1430. sampleDuration = readUint32(trun, offset);
  1431. offset += 4;
  1432. } else {
  1433. sampleDuration = defaultSampleDuration;
  1434. }
  1435. if (sampleSizePresent) {
  1436. offset += 4;
  1437. }
  1438. if (sampleCompositionTimeOffsetPresent) {
  1439. offset += 4;
  1440. }
  1441. sampleDTS += sampleDuration;
  1442. rawDuration += sampleDuration;
  1443. remaining--;
  1444. }
  1445. while (remaining--) {
  1446. if (sampleDurationPresent) {
  1447. sampleDuration = readUint32(trun, offset);
  1448. offset += 4;
  1449. } else {
  1450. sampleDuration = defaultSampleDuration;
  1451. }
  1452. if (sampleSizePresent) {
  1453. offset += 4;
  1454. }
  1455. if (sampleFlagsPresent) {
  1456. const isNonSyncSample = trun[offset + 1] & 1;
  1457. if (!isNonSyncSample) {
  1458. if (trackTimes.keyFrameIndex === void 0) {
  1459. trackTimes.keyFrameIndex = trackTimes.sampleCount - (remaining + 1);
  1460. trackTimes.keyFrameStart = sampleDTS;
  1461. }
  1462. }
  1463. offset += 4;
  1464. }
  1465. if (sampleCompositionTimeOffsetPresent) {
  1466. offset += 4;
  1467. }
  1468. sampleDTS += sampleDuration;
  1469. rawDuration += sampleDuration;
  1470. }
  1471. if (!rawDuration && defaultSampleDuration) {
  1472. rawDuration += defaultSampleDuration * sampleCount;
  1473. }
  1474. }
  1475. trackTimes.duration += rawDuration;
  1476. }
  1477. if (!Object.keys(tracks).some((trackId) => tracks[trackId].duration)) {
  1478. let sidxMinStart = Infinity;
  1479. let sidxMaxEnd = 0;
  1480. const sidxs = findBox(data, ["sidx"]);
  1481. for (let i = 0; i < sidxs.length; i++) {
  1482. const sidx = parseSegmentIndex(sidxs[i]);
  1483. if (sidx != null && sidx.references) {
  1484. sidxMinStart = Math.min(sidxMinStart, sidx.earliestPresentationTime / sidx.timescale);
  1485. const subSegmentDuration = sidx.references.reduce((dur, ref) => dur + ref.info.duration || 0, 0);
  1486. sidxMaxEnd = Math.max(sidxMaxEnd, subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale);
  1487. }
  1488. }
  1489. if (sidxMaxEnd && isFiniteNumber(sidxMaxEnd)) {
  1490. Object.keys(tracks).forEach((trackId) => {
  1491. if (!tracks[trackId].duration) {
  1492. tracks[trackId].duration = sidxMaxEnd * tracks[trackId].timescale - tracks[trackId].start;
  1493. }
  1494. });
  1495. }
  1496. }
  1497. return tracks;
  1498. }
  1499. function segmentValidRange(data) {
  1500. const segmentedRange = {
  1501. valid: null,
  1502. remainder: null
  1503. };
  1504. const moofs = findBox(data, ["moof"]);
  1505. if (moofs.length < 2) {
  1506. segmentedRange.remainder = data;
  1507. return segmentedRange;
  1508. }
  1509. const last = moofs[moofs.length - 1];
  1510. segmentedRange.valid = data.slice(0, last.byteOffset - 8);
  1511. segmentedRange.remainder = data.slice(last.byteOffset - 8);
  1512. return segmentedRange;
  1513. }
  1514. function appendUint8Array(data1, data2) {
  1515. const temp = new Uint8Array(data1.length + data2.length);
  1516. temp.set(data1);
  1517. temp.set(data2, data1.length);
  1518. return temp;
  1519. }
  1520. function parseSamples(timeOffset, track) {
  1521. const seiSamples = [];
  1522. const videoData = track.samples;
  1523. const timescale = track.timescale;
  1524. const trackId = track.id;
  1525. let isHEVCFlavor = false;
  1526. const moofs = findBox(videoData, ["moof"]);
  1527. moofs.map((moof) => {
  1528. const moofOffset = moof.byteOffset - 8;
  1529. const trafs = findBox(moof, ["traf"]);
  1530. trafs.map((traf) => {
  1531. const baseTime = findBox(traf, ["tfdt"]).map((tfdt) => {
  1532. const version2 = tfdt[0];
  1533. let result = readUint32(tfdt, 4);
  1534. if (version2 === 1) {
  1535. result *= Math.pow(2, 32);
  1536. result += readUint32(tfdt, 8);
  1537. }
  1538. return result / timescale;
  1539. })[0];
  1540. if (baseTime !== void 0) {
  1541. timeOffset = baseTime;
  1542. }
  1543. return findBox(traf, ["tfhd"]).map((tfhd) => {
  1544. const id = readUint32(tfhd, 4);
  1545. const tfhdFlags = readUint32(tfhd, 0) & 16777215;
  1546. const baseDataOffsetPresent = (tfhdFlags & 1) !== 0;
  1547. const sampleDescriptionIndexPresent = (tfhdFlags & 2) !== 0;
  1548. const defaultSampleDurationPresent = (tfhdFlags & 8) !== 0;
  1549. let defaultSampleDuration = 0;
  1550. const defaultSampleSizePresent = (tfhdFlags & 16) !== 0;
  1551. let defaultSampleSize = 0;
  1552. const defaultSampleFlagsPresent = (tfhdFlags & 32) !== 0;
  1553. let tfhdOffset = 8;
  1554. if (id === trackId) {
  1555. if (baseDataOffsetPresent) {
  1556. tfhdOffset += 8;
  1557. }
  1558. if (sampleDescriptionIndexPresent) {
  1559. tfhdOffset += 4;
  1560. }
  1561. if (defaultSampleDurationPresent) {
  1562. defaultSampleDuration = readUint32(tfhd, tfhdOffset);
  1563. tfhdOffset += 4;
  1564. }
  1565. if (defaultSampleSizePresent) {
  1566. defaultSampleSize = readUint32(tfhd, tfhdOffset);
  1567. tfhdOffset += 4;
  1568. }
  1569. if (defaultSampleFlagsPresent) {
  1570. tfhdOffset += 4;
  1571. }
  1572. if (track.type === "video") {
  1573. isHEVCFlavor = isHEVC(track.codec);
  1574. }
  1575. findBox(traf, ["trun"]).map((trun) => {
  1576. const version2 = trun[0];
  1577. const flags = readUint32(trun, 0) & 16777215;
  1578. const dataOffsetPresent = (flags & 1) !== 0;
  1579. let dataOffset = 0;
  1580. const firstSampleFlagsPresent = (flags & 4) !== 0;
  1581. const sampleDurationPresent = (flags & 256) !== 0;
  1582. let sampleDuration = 0;
  1583. const sampleSizePresent = (flags & 512) !== 0;
  1584. let sampleSize = 0;
  1585. const sampleFlagsPresent = (flags & 1024) !== 0;
  1586. const sampleCompositionOffsetsPresent = (flags & 2048) !== 0;
  1587. let compositionOffset = 0;
  1588. const sampleCount = readUint32(trun, 4);
  1589. let trunOffset = 8;
  1590. if (dataOffsetPresent) {
  1591. dataOffset = readUint32(trun, trunOffset);
  1592. trunOffset += 4;
  1593. }
  1594. if (firstSampleFlagsPresent) {
  1595. trunOffset += 4;
  1596. }
  1597. let sampleOffset = dataOffset + moofOffset;
  1598. for (let ix = 0; ix < sampleCount; ix++) {
  1599. if (sampleDurationPresent) {
  1600. sampleDuration = readUint32(trun, trunOffset);
  1601. trunOffset += 4;
  1602. } else {
  1603. sampleDuration = defaultSampleDuration;
  1604. }
  1605. if (sampleSizePresent) {
  1606. sampleSize = readUint32(trun, trunOffset);
  1607. trunOffset += 4;
  1608. } else {
  1609. sampleSize = defaultSampleSize;
  1610. }
  1611. if (sampleFlagsPresent) {
  1612. trunOffset += 4;
  1613. }
  1614. if (sampleCompositionOffsetsPresent) {
  1615. if (version2 === 0) {
  1616. compositionOffset = readUint32(trun, trunOffset);
  1617. } else {
  1618. compositionOffset = readSint32(trun, trunOffset);
  1619. }
  1620. trunOffset += 4;
  1621. }
  1622. if (track.type === ElementaryStreamTypes.VIDEO) {
  1623. let naluTotalSize = 0;
  1624. while (naluTotalSize < sampleSize) {
  1625. const naluSize = readUint32(videoData, sampleOffset);
  1626. sampleOffset += 4;
  1627. if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {
  1628. const data = videoData.subarray(sampleOffset, sampleOffset + naluSize);
  1629. parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale, seiSamples);
  1630. }
  1631. sampleOffset += naluSize;
  1632. naluTotalSize += naluSize + 4;
  1633. }
  1634. }
  1635. timeOffset += sampleDuration / timescale;
  1636. }
  1637. });
  1638. }
  1639. });
  1640. });
  1641. });
  1642. return seiSamples;
  1643. }
  1644. function isHEVC(codec) {
  1645. if (!codec) {
  1646. return false;
  1647. }
  1648. const baseCodec = codec.substring(0, 4);
  1649. return baseCodec === "hvc1" || baseCodec === "hev1" || // Dolby Vision
  1650. baseCodec === "dvh1" || baseCodec === "dvhe";
  1651. }
  1652. function isSEIMessage(isHEVCFlavor, naluHeader) {
  1653. if (isHEVCFlavor) {
  1654. const naluType = naluHeader >> 1 & 63;
  1655. return naluType === 39 || naluType === 40;
  1656. } else {
  1657. const naluType = naluHeader & 31;
  1658. return naluType === 6;
  1659. }
  1660. }
  1661. function parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) {
  1662. const data = discardEPB(unescapedData);
  1663. let seiPtr = 0;
  1664. seiPtr += headerSize;
  1665. let payloadType = 0;
  1666. let payloadSize = 0;
  1667. let b = 0;
  1668. while (seiPtr < data.length) {
  1669. payloadType = 0;
  1670. do {
  1671. if (seiPtr >= data.length) {
  1672. break;
  1673. }
  1674. b = data[seiPtr++];
  1675. payloadType += b;
  1676. } while (b === 255);
  1677. payloadSize = 0;
  1678. do {
  1679. if (seiPtr >= data.length) {
  1680. break;
  1681. }
  1682. b = data[seiPtr++];
  1683. payloadSize += b;
  1684. } while (b === 255);
  1685. const leftOver = data.length - seiPtr;
  1686. let payPtr = seiPtr;
  1687. if (payloadSize < leftOver) {
  1688. seiPtr += payloadSize;
  1689. } else if (payloadSize > leftOver) {
  1690. logger.error(`Malformed SEI payload. ${payloadSize} is too small, only ${leftOver} bytes left to parse.`);
  1691. break;
  1692. }
  1693. if (payloadType === 4) {
  1694. const countryCode = data[payPtr++];
  1695. if (countryCode === 181) {
  1696. const providerCode = readUint16(data, payPtr);
  1697. payPtr += 2;
  1698. if (providerCode === 49) {
  1699. const userStructure = readUint32(data, payPtr);
  1700. payPtr += 4;
  1701. if (userStructure === 1195456820) {
  1702. const userDataType = data[payPtr++];
  1703. if (userDataType === 3) {
  1704. const firstByte = data[payPtr++];
  1705. const totalCCs = 31 & firstByte;
  1706. const enabled = 64 & firstByte;
  1707. const totalBytes = enabled ? 2 + totalCCs * 3 : 0;
  1708. const byteArray = new Uint8Array(totalBytes);
  1709. if (enabled) {
  1710. byteArray[0] = firstByte;
  1711. for (let i = 1; i < totalBytes; i++) {
  1712. byteArray[i] = data[payPtr++];
  1713. }
  1714. }
  1715. samples.push({
  1716. type: userDataType,
  1717. payloadType,
  1718. pts,
  1719. bytes: byteArray
  1720. });
  1721. }
  1722. }
  1723. }
  1724. }
  1725. } else if (payloadType === 5) {
  1726. if (payloadSize > 16) {
  1727. const uuidStrArray = [];
  1728. for (let i = 0; i < 16; i++) {
  1729. const _b = data[payPtr++].toString(16);
  1730. uuidStrArray.push(_b.length == 1 ? "0" + _b : _b);
  1731. if (i === 3 || i === 5 || i === 7 || i === 9) {
  1732. uuidStrArray.push("-");
  1733. }
  1734. }
  1735. const length = payloadSize - 16;
  1736. const userDataBytes = new Uint8Array(length);
  1737. for (let i = 0; i < length; i++) {
  1738. userDataBytes[i] = data[payPtr++];
  1739. }
  1740. samples.push({
  1741. payloadType,
  1742. pts,
  1743. uuid: uuidStrArray.join(""),
  1744. userData: utf8ArrayToStr(userDataBytes),
  1745. userDataBytes
  1746. });
  1747. }
  1748. }
  1749. }
  1750. }
  1751. function discardEPB(data) {
  1752. const length = data.byteLength;
  1753. const EPBPositions = [];
  1754. let i = 1;
  1755. while (i < length - 2) {
  1756. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 3) {
  1757. EPBPositions.push(i + 2);
  1758. i += 2;
  1759. } else {
  1760. i++;
  1761. }
  1762. }
  1763. if (EPBPositions.length === 0) {
  1764. return data;
  1765. }
  1766. const newLength = length - EPBPositions.length;
  1767. const newData = new Uint8Array(newLength);
  1768. let sourceIndex = 0;
  1769. for (i = 0; i < newLength; sourceIndex++, i++) {
  1770. if (sourceIndex === EPBPositions[0]) {
  1771. sourceIndex++;
  1772. EPBPositions.shift();
  1773. }
  1774. newData[i] = data[sourceIndex];
  1775. }
  1776. return newData;
  1777. }
  1778. function parseEmsg(data) {
  1779. const version2 = data[0];
  1780. let schemeIdUri = "";
  1781. let value = "";
  1782. let timeScale = 0;
  1783. let presentationTimeDelta = 0;
  1784. let presentationTime = 0;
  1785. let eventDuration = 0;
  1786. let id = 0;
  1787. let offset = 0;
  1788. if (version2 === 0) {
  1789. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  1790. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  1791. offset += 1;
  1792. }
  1793. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  1794. offset += 1;
  1795. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  1796. value += bin2str(data.subarray(offset, offset + 1));
  1797. offset += 1;
  1798. }
  1799. value += bin2str(data.subarray(offset, offset + 1));
  1800. offset += 1;
  1801. timeScale = readUint32(data, 12);
  1802. presentationTimeDelta = readUint32(data, 16);
  1803. eventDuration = readUint32(data, 20);
  1804. id = readUint32(data, 24);
  1805. offset = 28;
  1806. } else if (version2 === 1) {
  1807. offset += 4;
  1808. timeScale = readUint32(data, offset);
  1809. offset += 4;
  1810. const leftPresentationTime = readUint32(data, offset);
  1811. offset += 4;
  1812. const rightPresentationTime = readUint32(data, offset);
  1813. offset += 4;
  1814. presentationTime = 2 ** 32 * leftPresentationTime + rightPresentationTime;
  1815. if (!isSafeInteger(presentationTime)) {
  1816. presentationTime = Number.MAX_SAFE_INTEGER;
  1817. logger.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box");
  1818. }
  1819. eventDuration = readUint32(data, offset);
  1820. offset += 4;
  1821. id = readUint32(data, offset);
  1822. offset += 4;
  1823. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  1824. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  1825. offset += 1;
  1826. }
  1827. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  1828. offset += 1;
  1829. while (bin2str(data.subarray(offset, offset + 1)) !== "\0") {
  1830. value += bin2str(data.subarray(offset, offset + 1));
  1831. offset += 1;
  1832. }
  1833. value += bin2str(data.subarray(offset, offset + 1));
  1834. offset += 1;
  1835. }
  1836. const payload = data.subarray(offset, data.byteLength);
  1837. return {
  1838. schemeIdUri,
  1839. value,
  1840. timeScale,
  1841. presentationTime,
  1842. presentationTimeDelta,
  1843. eventDuration,
  1844. id,
  1845. payload
  1846. };
  1847. }
  1848. function mp4Box(type, ...payload) {
  1849. const len = payload.length;
  1850. let size = 8;
  1851. let i = len;
  1852. while (i--) {
  1853. size += payload[i].byteLength;
  1854. }
  1855. const result = new Uint8Array(size);
  1856. result[0] = size >> 24 & 255;
  1857. result[1] = size >> 16 & 255;
  1858. result[2] = size >> 8 & 255;
  1859. result[3] = size & 255;
  1860. result.set(type, 4);
  1861. for (i = 0, size = 8; i < len; i++) {
  1862. result.set(payload[i], size);
  1863. size += payload[i].byteLength;
  1864. }
  1865. return result;
  1866. }
  1867. function mp4pssh(systemId, keyids, data) {
  1868. if (systemId.byteLength !== 16) {
  1869. throw new RangeError("Invalid system id");
  1870. }
  1871. let version2;
  1872. let kids;
  1873. {
  1874. version2 = 0;
  1875. kids = new Uint8Array();
  1876. }
  1877. let kidCount;
  1878. if (version2 > 0) {
  1879. kidCount = new Uint8Array(4);
  1880. if (keyids.length > 0) {
  1881. new DataView(kidCount.buffer).setUint32(0, keyids.length, false);
  1882. }
  1883. } else {
  1884. kidCount = new Uint8Array();
  1885. }
  1886. const dataSize = new Uint8Array(4);
  1887. if (data.byteLength > 0) {
  1888. new DataView(dataSize.buffer).setUint32(0, data.byteLength, false);
  1889. }
  1890. return mp4Box(
  1891. [112, 115, 115, 104],
  1892. new Uint8Array([
  1893. version2,
  1894. 0,
  1895. 0,
  1896. 0
  1897. // Flags
  1898. ]),
  1899. systemId,
  1900. // 16 bytes
  1901. kidCount,
  1902. kids,
  1903. dataSize,
  1904. data
  1905. );
  1906. }
  1907. function parseMultiPssh(initData) {
  1908. const results = [];
  1909. if (initData instanceof ArrayBuffer) {
  1910. const length = initData.byteLength;
  1911. let offset = 0;
  1912. while (offset + 32 < length) {
  1913. const view2 = new DataView(initData, offset);
  1914. const pssh = parsePssh(view2);
  1915. results.push(pssh);
  1916. offset += pssh.size;
  1917. }
  1918. }
  1919. return results;
  1920. }
  1921. function parsePssh(view2) {
  1922. const size = view2.getUint32(0);
  1923. const offset = view2.byteOffset;
  1924. const length = view2.byteLength;
  1925. if (length < size) {
  1926. return {
  1927. offset,
  1928. size: length
  1929. };
  1930. }
  1931. const type = view2.getUint32(4);
  1932. if (type !== 1886614376) {
  1933. return {
  1934. offset,
  1935. size
  1936. };
  1937. }
  1938. const version2 = view2.getUint32(8) >>> 24;
  1939. if (version2 !== 0 && version2 !== 1) {
  1940. return {
  1941. offset,
  1942. size
  1943. };
  1944. }
  1945. const buffer = view2.buffer;
  1946. const systemId = arrayToHex(new Uint8Array(buffer, offset + 12, 16));
  1947. let kids = null;
  1948. let data = null;
  1949. let dataSizeOffset = 0;
  1950. if (version2 === 0) {
  1951. dataSizeOffset = 28;
  1952. } else {
  1953. const kidCounts = view2.getUint32(28);
  1954. if (!kidCounts || length < 32 + kidCounts * 16) {
  1955. return {
  1956. offset,
  1957. size
  1958. };
  1959. }
  1960. kids = [];
  1961. for (let i = 0; i < kidCounts; i++) {
  1962. kids.push(new Uint8Array(buffer, offset + 32 + i * 16, 16));
  1963. }
  1964. dataSizeOffset = 32 + kidCounts * 16;
  1965. }
  1966. if (!dataSizeOffset) {
  1967. return {
  1968. offset,
  1969. size
  1970. };
  1971. }
  1972. const dataSizeOrKidCount = view2.getUint32(dataSizeOffset);
  1973. if (size - 32 < dataSizeOrKidCount) {
  1974. return {
  1975. offset,
  1976. size
  1977. };
  1978. }
  1979. data = new Uint8Array(buffer, offset + dataSizeOffset + 4, dataSizeOrKidCount);
  1980. return {
  1981. version: version2,
  1982. systemId,
  1983. kids,
  1984. data,
  1985. offset,
  1986. size
  1987. };
  1988. }
  1989. var userAgentHevcSupportIsInaccurate = () => {
  1990. return /\(Windows.+Firefox\//i.test(navigator.userAgent);
  1991. };
  1992. var sampleEntryCodesISO = {
  1993. audio: {
  1994. a3ds: 1,
  1995. "ac-3": 0.95,
  1996. "ac-4": 1,
  1997. alac: 0.9,
  1998. alaw: 1,
  1999. dra1: 1,
  2000. "dts+": 1,
  2001. "dts-": 1,
  2002. dtsc: 1,
  2003. dtse: 1,
  2004. dtsh: 1,
  2005. "ec-3": 0.9,
  2006. enca: 1,
  2007. fLaC: 0.9,
  2008. // MP4-RA listed codec entry for FLAC
  2009. flac: 0.9,
  2010. // legacy browser codec name for FLAC
  2011. FLAC: 0.9,
  2012. // some manifests may list "FLAC" with Apple's tools
  2013. g719: 1,
  2014. g726: 1,
  2015. m4ae: 1,
  2016. mha1: 1,
  2017. mha2: 1,
  2018. mhm1: 1,
  2019. mhm2: 1,
  2020. mlpa: 1,
  2021. mp4a: 1,
  2022. "raw ": 1,
  2023. Opus: 1,
  2024. opus: 1,
  2025. // browsers expect this to be lowercase despite MP4RA says 'Opus'
  2026. samr: 1,
  2027. sawb: 1,
  2028. sawp: 1,
  2029. sevc: 1,
  2030. sqcp: 1,
  2031. ssmv: 1,
  2032. twos: 1,
  2033. ulaw: 1
  2034. },
  2035. video: {
  2036. avc1: 1,
  2037. avc2: 1,
  2038. avc3: 1,
  2039. avc4: 1,
  2040. avcp: 1,
  2041. av01: 0.8,
  2042. dav1: 0.8,
  2043. drac: 1,
  2044. dva1: 1,
  2045. dvav: 1,
  2046. dvh1: 0.7,
  2047. dvhe: 0.7,
  2048. encv: 1,
  2049. hev1: 0.75,
  2050. hvc1: 0.75,
  2051. mjp2: 1,
  2052. mp4v: 1,
  2053. mvc1: 1,
  2054. mvc2: 1,
  2055. mvc3: 1,
  2056. mvc4: 1,
  2057. resv: 1,
  2058. rv60: 1,
  2059. s263: 1,
  2060. svc1: 1,
  2061. svc2: 1,
  2062. "vc-1": 1,
  2063. vp08: 1,
  2064. vp09: 0.9
  2065. },
  2066. text: {
  2067. stpp: 1,
  2068. wvtt: 1
  2069. }
  2070. };
  2071. function isCodecType(codec, type) {
  2072. const typeCodes = sampleEntryCodesISO[type];
  2073. return !!typeCodes && !!typeCodes[codec.slice(0, 4)];
  2074. }
  2075. function areCodecsMediaSourceSupported(codecs, type, preferManagedMediaSource = true) {
  2076. return !codecs.split(",").some((codec) => !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource));
  2077. }
  2078. function isCodecMediaSourceSupported(codec, type, preferManagedMediaSource = true) {
  2079. var _MediaSource$isTypeSu;
  2080. const MediaSource = getMediaSource(preferManagedMediaSource);
  2081. return (_MediaSource$isTypeSu = MediaSource == null ? void 0 : MediaSource.isTypeSupported(mimeTypeForCodec(codec, type))) != null ? _MediaSource$isTypeSu : false;
  2082. }
  2083. function mimeTypeForCodec(codec, type) {
  2084. return `${type}/mp4;codecs=${codec}`;
  2085. }
  2086. function videoCodecPreferenceValue(videoCodec) {
  2087. if (videoCodec) {
  2088. const fourCC = videoCodec.substring(0, 4);
  2089. return sampleEntryCodesISO.video[fourCC];
  2090. }
  2091. return 2;
  2092. }
  2093. function codecsSetSelectionPreferenceValue(codecSet) {
  2094. const limitedHevcSupport = userAgentHevcSupportIsInaccurate();
  2095. return codecSet.split(",").reduce((num, fourCC) => {
  2096. const lowerPriority = limitedHevcSupport && isHEVC(fourCC);
  2097. const preferenceValue = lowerPriority ? 9 : sampleEntryCodesISO.video[fourCC];
  2098. if (preferenceValue) {
  2099. return (preferenceValue * 2 + num) / (num ? 3 : 2);
  2100. }
  2101. return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);
  2102. }, 0);
  2103. }
  2104. var CODEC_COMPATIBLE_NAMES = {};
  2105. function getCodecCompatibleNameLower(lowerCaseCodec, preferManagedMediaSource = true) {
  2106. if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {
  2107. return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];
  2108. }
  2109. const codecsToCheck = {
  2110. // Idealy fLaC and Opus would be first (spec-compliant) but
  2111. // some browsers will report that fLaC is supported then fail.
  2112. // see: https://bugs.chromium.org/p/chromium/issues/detail?id=1422728
  2113. flac: ["flac", "fLaC", "FLAC"],
  2114. opus: ["opus", "Opus"],
  2115. // Replace audio codec info if browser does not support mp4a.40.34,
  2116. // and demuxer can fallback to 'audio/mpeg' or 'audio/mp4;codecs="mp3"'
  2117. "mp4a.40.34": ["mp3"]
  2118. }[lowerCaseCodec];
  2119. for (let i = 0; i < codecsToCheck.length; i++) {
  2120. var _getMediaSource;
  2121. if (isCodecMediaSourceSupported(codecsToCheck[i], "audio", preferManagedMediaSource)) {
  2122. CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i];
  2123. return codecsToCheck[i];
  2124. } else if (codecsToCheck[i] === "mp3" && (_getMediaSource = getMediaSource(preferManagedMediaSource)) != null && _getMediaSource.isTypeSupported("audio/mpeg")) {
  2125. return "";
  2126. }
  2127. }
  2128. return lowerCaseCodec;
  2129. }
  2130. var AUDIO_CODEC_REGEXP = /flac|opus|mp4a\.40\.34/i;
  2131. function getCodecCompatibleName(codec, preferManagedMediaSource = true) {
  2132. return codec.replace(AUDIO_CODEC_REGEXP, (m) => getCodecCompatibleNameLower(m.toLowerCase(), preferManagedMediaSource));
  2133. }
  2134. function replaceVideoCodec(originalCodecs, newVideoCodec) {
  2135. const codecs = [];
  2136. if (originalCodecs) {
  2137. const allCodecs = originalCodecs.split(",");
  2138. for (let i = 0; i < allCodecs.length; i++) {
  2139. if (!isCodecType(allCodecs[i], "video")) {
  2140. codecs.push(allCodecs[i]);
  2141. }
  2142. }
  2143. }
  2144. if (newVideoCodec) {
  2145. codecs.push(newVideoCodec);
  2146. }
  2147. return codecs.join(",");
  2148. }
  2149. function pickMostCompleteCodecName(parsedCodec, levelCodec) {
  2150. if (parsedCodec && (parsedCodec.length > 4 || ["ac-3", "ec-3", "alac", "fLaC", "Opus"].indexOf(parsedCodec) !== -1)) {
  2151. if (isCodecSupportedAsType(parsedCodec, "audio") || isCodecSupportedAsType(parsedCodec, "video")) {
  2152. return parsedCodec;
  2153. }
  2154. }
  2155. if (levelCodec) {
  2156. const levelCodecs = levelCodec.split(",");
  2157. if (levelCodecs.length > 1) {
  2158. if (parsedCodec) {
  2159. for (let i = levelCodecs.length; i--; ) {
  2160. if (levelCodecs[i].substring(0, 4) === parsedCodec.substring(0, 4)) {
  2161. return levelCodecs[i];
  2162. }
  2163. }
  2164. }
  2165. return levelCodecs[0];
  2166. }
  2167. }
  2168. return levelCodec || parsedCodec;
  2169. }
  2170. function isCodecSupportedAsType(codec, type) {
  2171. return isCodecType(codec, type) && isCodecMediaSourceSupported(codec, type);
  2172. }
  2173. function convertAVC1ToAVCOTI(videoCodecs) {
  2174. const codecs = videoCodecs.split(",");
  2175. for (let i = 0; i < codecs.length; i++) {
  2176. const avcdata = codecs[i].split(".");
  2177. if (avcdata.length > 2 && avcdata[0] === "avc1") {
  2178. codecs[i] = `avc1.${parseInt(avcdata[1]).toString(16)}${("000" + parseInt(avcdata[2]).toString(16)).slice(-4)}`;
  2179. }
  2180. }
  2181. return codecs.join(",");
  2182. }
  2183. function fillInMissingAV01Params(videoCodec) {
  2184. if (videoCodec.startsWith("av01.")) {
  2185. const av1params = videoCodec.split(".");
  2186. const placeholders = ["0", "111", "01", "01", "01", "0"];
  2187. for (let i = av1params.length; i > 4 && i < 10; i++) {
  2188. av1params[i] = placeholders[i - 4];
  2189. }
  2190. return av1params.join(".");
  2191. }
  2192. return videoCodec;
  2193. }
  2194. function getM2TSSupportedAudioTypes(preferManagedMediaSource) {
  2195. const MediaSource = getMediaSource(preferManagedMediaSource) || {
  2196. isTypeSupported: () => false
  2197. };
  2198. return {
  2199. mpeg: MediaSource.isTypeSupported("audio/mpeg"),
  2200. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"'),
  2201. ac3: MediaSource.isTypeSupported('audio/mp4; codecs="ac-3"')
  2202. };
  2203. }
  2204. function getCodecsForMimeType(mimeType) {
  2205. return mimeType.replace(/^.+codecs=["']?([^"']+).*$/, "$1");
  2206. }
  2207. var supportedResult = {
  2208. supported: true,
  2209. powerEfficient: true,
  2210. smooth: true
  2211. // keySystemAccess: null,
  2212. };
  2213. var unsupportedResult = {
  2214. supported: false,
  2215. smooth: false,
  2216. powerEfficient: false
  2217. // keySystemAccess: null,
  2218. };
  2219. var SUPPORTED_INFO_DEFAULT = {
  2220. supported: true,
  2221. configurations: [],
  2222. decodingInfoResults: [supportedResult]
  2223. };
  2224. function getUnsupportedResult(error, configurations) {
  2225. return {
  2226. supported: false,
  2227. configurations,
  2228. decodingInfoResults: [unsupportedResult],
  2229. error
  2230. };
  2231. }
  2232. function requiresMediaCapabilitiesDecodingInfo(level, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference) {
  2233. const videoCodecs = level.videoCodec;
  2234. const audioGroups = level.audioCodec ? level.audioGroups : null;
  2235. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  2236. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  2237. const maxChannels = channelsPreference ? parseInt(channelsPreference) : audioCodecPreference ? Infinity : 2;
  2238. let audioChannels = null;
  2239. if (audioGroups != null && audioGroups.length) {
  2240. try {
  2241. if (audioGroups.length === 1 && audioGroups[0]) {
  2242. audioChannels = audioTracksByGroup.groups[audioGroups[0]].channels;
  2243. } else {
  2244. audioChannels = audioGroups.reduce((acc, groupId) => {
  2245. if (groupId) {
  2246. const audioTrackGroup = audioTracksByGroup.groups[groupId];
  2247. if (!audioTrackGroup) {
  2248. throw new Error(`Audio track group ${groupId} not found`);
  2249. }
  2250. Object.keys(audioTrackGroup.channels).forEach((key) => {
  2251. acc[key] = (acc[key] || 0) + audioTrackGroup.channels[key];
  2252. });
  2253. }
  2254. return acc;
  2255. }, {
  2256. 2: 0
  2257. });
  2258. }
  2259. } catch (error) {
  2260. return true;
  2261. }
  2262. }
  2263. return videoCodecs !== void 0 && // Force media capabilities check for HEVC to avoid failure on Windows
  2264. (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);
  2265. }
  2266. function getMediaDecodingInfoPromise(level, audioTracksByGroup, mediaCapabilities, cache = {}) {
  2267. const videoCodecs = level.videoCodec;
  2268. if (!videoCodecs && !level.audioCodec || !mediaCapabilities) {
  2269. return Promise.resolve(SUPPORTED_INFO_DEFAULT);
  2270. }
  2271. const configurations = [];
  2272. const videoDecodeList = makeVideoConfigurations(level);
  2273. const videoCount = videoDecodeList.length;
  2274. const audioDecodeList = makeAudioConfigurations(level, audioTracksByGroup, videoCount > 0);
  2275. const audioCount = audioDecodeList.length;
  2276. for (let i = videoCount || 1 * audioCount || 1; i--; ) {
  2277. const configuration = {
  2278. type: "media-source"
  2279. };
  2280. if (videoCount) {
  2281. configuration.video = videoDecodeList[i % videoCount];
  2282. }
  2283. if (audioCount) {
  2284. configuration.audio = audioDecodeList[i % audioCount];
  2285. const audioBitrate = configuration.audio.bitrate;
  2286. if (configuration.video && audioBitrate) {
  2287. configuration.video.bitrate -= audioBitrate;
  2288. }
  2289. }
  2290. configurations.push(configuration);
  2291. }
  2292. if (videoCodecs) {
  2293. const ua = navigator.userAgent;
  2294. if (videoCodecs.split(",").some((videoCodec) => isHEVC(videoCodec)) && userAgentHevcSupportIsInaccurate()) {
  2295. return Promise.resolve(getUnsupportedResult(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${ua})`), configurations));
  2296. }
  2297. }
  2298. return Promise.all(configurations.map((configuration) => {
  2299. const decodingInfoKey = getMediaDecodingInfoKey(configuration);
  2300. return cache[decodingInfoKey] || (cache[decodingInfoKey] = mediaCapabilities.decodingInfo(configuration));
  2301. })).then((decodingInfoResults) => ({
  2302. supported: !decodingInfoResults.some((info) => !info.supported),
  2303. configurations,
  2304. decodingInfoResults
  2305. })).catch((error) => ({
  2306. supported: false,
  2307. configurations,
  2308. decodingInfoResults: [],
  2309. error
  2310. }));
  2311. }
  2312. function makeVideoConfigurations(level) {
  2313. var _level$videoCodec;
  2314. const videoCodecs = (_level$videoCodec = level.videoCodec) == null ? void 0 : _level$videoCodec.split(",");
  2315. const bitrate = getVariantDecodingBitrate(level);
  2316. const width = level.width || 640;
  2317. const height = level.height || 480;
  2318. const framerate = level.frameRate || 30;
  2319. const videoRange = level.videoRange.toLowerCase();
  2320. return videoCodecs ? videoCodecs.map((videoCodec) => {
  2321. const videoConfiguration = {
  2322. contentType: mimeTypeForCodec(fillInMissingAV01Params(videoCodec), "video"),
  2323. width,
  2324. height,
  2325. bitrate,
  2326. framerate
  2327. };
  2328. if (videoRange !== "sdr") {
  2329. videoConfiguration.transferFunction = videoRange;
  2330. }
  2331. return videoConfiguration;
  2332. }) : [];
  2333. }
  2334. function makeAudioConfigurations(level, audioTracksByGroup, hasVideo) {
  2335. var _level$audioCodec;
  2336. const audioCodecs = (_level$audioCodec = level.audioCodec) == null ? void 0 : _level$audioCodec.split(",");
  2337. const combinedBitrate = getVariantDecodingBitrate(level);
  2338. if (audioCodecs && level.audioGroups) {
  2339. return level.audioGroups.reduce((configurations, audioGroupId) => {
  2340. var _audioTracksByGroup$g;
  2341. const tracks = audioGroupId ? (_audioTracksByGroup$g = audioTracksByGroup.groups[audioGroupId]) == null ? void 0 : _audioTracksByGroup$g.tracks : null;
  2342. if (tracks) {
  2343. return tracks.reduce((configs, audioTrack) => {
  2344. if (audioTrack.groupId === audioGroupId) {
  2345. const channelsNumber = parseFloat(audioTrack.channels || "");
  2346. audioCodecs.forEach((audioCodec) => {
  2347. const audioConfiguration = {
  2348. contentType: mimeTypeForCodec(audioCodec, "audio"),
  2349. bitrate: hasVideo ? estimatedAudioBitrate(audioCodec, combinedBitrate) : combinedBitrate
  2350. };
  2351. if (channelsNumber) {
  2352. audioConfiguration.channels = "" + channelsNumber;
  2353. }
  2354. configs.push(audioConfiguration);
  2355. });
  2356. }
  2357. return configs;
  2358. }, configurations);
  2359. }
  2360. return configurations;
  2361. }, []);
  2362. }
  2363. return [];
  2364. }
  2365. function estimatedAudioBitrate(audioCodec, levelBitrate) {
  2366. if (levelBitrate <= 1) {
  2367. return 1;
  2368. }
  2369. let audioBitrate = 128e3;
  2370. if (audioCodec === "ec-3") {
  2371. audioBitrate = 768e3;
  2372. } else if (audioCodec === "ac-3") {
  2373. audioBitrate = 64e4;
  2374. }
  2375. return Math.min(levelBitrate / 2, audioBitrate);
  2376. }
  2377. function getVariantDecodingBitrate(level) {
  2378. return Math.ceil(Math.max(level.bitrate * 0.9, level.averageBitrate) / 1e3) * 1e3 || 1;
  2379. }
  2380. function getMediaDecodingInfoKey(config) {
  2381. let key = "";
  2382. const {
  2383. audio,
  2384. video
  2385. } = config;
  2386. if (video) {
  2387. const codec = getCodecsForMimeType(video.contentType);
  2388. key += `${codec}_r${video.height}x${video.width}f${Math.ceil(video.framerate)}${video.transferFunction || "sd"}_${Math.ceil(video.bitrate / 1e5)}`;
  2389. }
  2390. if (audio) {
  2391. const codec = getCodecsForMimeType(audio.contentType);
  2392. key += `${video ? "_" : ""}${codec}_c${audio.channels}`;
  2393. }
  2394. return key;
  2395. }
  2396. var HdcpLevels = ["NONE", "TYPE-0", "TYPE-1", null];
  2397. function isHdcpLevel(value) {
  2398. return HdcpLevels.indexOf(value) > -1;
  2399. }
  2400. var VideoRangeValues = ["SDR", "PQ", "HLG"];
  2401. function isVideoRange(value) {
  2402. return !!value && VideoRangeValues.indexOf(value) > -1;
  2403. }
  2404. var HlsSkip = {
  2405. No: "",
  2406. Yes: "YES",
  2407. v2: "v2"
  2408. };
  2409. function getSkipValue(details) {
  2410. const {
  2411. canSkipUntil,
  2412. canSkipDateRanges,
  2413. age
  2414. } = details;
  2415. const playlistRecentEnough = age < canSkipUntil / 2;
  2416. if (canSkipUntil && playlistRecentEnough) {
  2417. if (canSkipDateRanges) {
  2418. return HlsSkip.v2;
  2419. }
  2420. return HlsSkip.Yes;
  2421. }
  2422. return HlsSkip.No;
  2423. }
  2424. var HlsUrlParameters = class {
  2425. constructor(msn, part, skip) {
  2426. this.msn = void 0;
  2427. this.part = void 0;
  2428. this.skip = void 0;
  2429. this.msn = msn;
  2430. this.part = part;
  2431. this.skip = skip;
  2432. }
  2433. addDirectives(uri) {
  2434. const url = new self.URL(uri);
  2435. if (this.msn !== void 0) {
  2436. url.searchParams.set("_HLS_msn", this.msn.toString());
  2437. }
  2438. if (this.part !== void 0) {
  2439. url.searchParams.set("_HLS_part", this.part.toString());
  2440. }
  2441. if (this.skip) {
  2442. url.searchParams.set("_HLS_skip", this.skip);
  2443. }
  2444. return url.href;
  2445. }
  2446. };
  2447. var Level = class {
  2448. constructor(data) {
  2449. this._attrs = void 0;
  2450. this.audioCodec = void 0;
  2451. this.bitrate = void 0;
  2452. this.codecSet = void 0;
  2453. this.url = void 0;
  2454. this.frameRate = void 0;
  2455. this.height = void 0;
  2456. this.id = void 0;
  2457. this.name = void 0;
  2458. this.supplemental = void 0;
  2459. this.videoCodec = void 0;
  2460. this.width = void 0;
  2461. this.details = void 0;
  2462. this.fragmentError = 0;
  2463. this.loadError = 0;
  2464. this.loaded = void 0;
  2465. this.realBitrate = 0;
  2466. this.supportedPromise = void 0;
  2467. this.supportedResult = void 0;
  2468. this._avgBitrate = 0;
  2469. this._audioGroups = void 0;
  2470. this._subtitleGroups = void 0;
  2471. this._urlId = 0;
  2472. this.url = [data.url];
  2473. this._attrs = [data.attrs];
  2474. this.bitrate = data.bitrate;
  2475. if (data.details) {
  2476. this.details = data.details;
  2477. }
  2478. this.id = data.id || 0;
  2479. this.name = data.name;
  2480. this.width = data.width || 0;
  2481. this.height = data.height || 0;
  2482. this.frameRate = data.attrs.optionalFloat("FRAME-RATE", 0);
  2483. this._avgBitrate = data.attrs.decimalInteger("AVERAGE-BANDWIDTH");
  2484. this.audioCodec = data.audioCodec;
  2485. this.videoCodec = data.videoCodec;
  2486. this.codecSet = [data.videoCodec, data.audioCodec].filter((c) => !!c).map((s) => s.substring(0, 4)).join(",");
  2487. if ("supplemental" in data) {
  2488. var _data$supplemental;
  2489. this.supplemental = data.supplemental;
  2490. const supplementalVideo = (_data$supplemental = data.supplemental) == null ? void 0 : _data$supplemental.videoCodec;
  2491. if (supplementalVideo && supplementalVideo !== data.videoCodec) {
  2492. this.codecSet += `,${supplementalVideo.substring(0, 4)}`;
  2493. }
  2494. }
  2495. this.addGroupId("audio", data.attrs.AUDIO);
  2496. this.addGroupId("text", data.attrs.SUBTITLES);
  2497. }
  2498. get maxBitrate() {
  2499. return Math.max(this.realBitrate, this.bitrate);
  2500. }
  2501. get averageBitrate() {
  2502. return this._avgBitrate || this.realBitrate || this.bitrate;
  2503. }
  2504. get attrs() {
  2505. return this._attrs[0];
  2506. }
  2507. get codecs() {
  2508. return this.attrs.CODECS || "";
  2509. }
  2510. get pathwayId() {
  2511. return this.attrs["PATHWAY-ID"] || ".";
  2512. }
  2513. get videoRange() {
  2514. return this.attrs["VIDEO-RANGE"] || "SDR";
  2515. }
  2516. get score() {
  2517. return this.attrs.optionalFloat("SCORE", 0);
  2518. }
  2519. get uri() {
  2520. return this.url[0] || "";
  2521. }
  2522. hasAudioGroup(groupId) {
  2523. return hasGroup(this._audioGroups, groupId);
  2524. }
  2525. hasSubtitleGroup(groupId) {
  2526. return hasGroup(this._subtitleGroups, groupId);
  2527. }
  2528. get audioGroups() {
  2529. return this._audioGroups;
  2530. }
  2531. get subtitleGroups() {
  2532. return this._subtitleGroups;
  2533. }
  2534. addGroupId(type, groupId) {
  2535. if (!groupId) {
  2536. return;
  2537. }
  2538. if (type === "audio") {
  2539. let audioGroups = this._audioGroups;
  2540. if (!audioGroups) {
  2541. audioGroups = this._audioGroups = [];
  2542. }
  2543. if (audioGroups.indexOf(groupId) === -1) {
  2544. audioGroups.push(groupId);
  2545. }
  2546. } else if (type === "text") {
  2547. let subtitleGroups = this._subtitleGroups;
  2548. if (!subtitleGroups) {
  2549. subtitleGroups = this._subtitleGroups = [];
  2550. }
  2551. if (subtitleGroups.indexOf(groupId) === -1) {
  2552. subtitleGroups.push(groupId);
  2553. }
  2554. }
  2555. }
  2556. // Deprecated methods (retained for backwards compatibility)
  2557. get urlId() {
  2558. return 0;
  2559. }
  2560. set urlId(value) {
  2561. }
  2562. get audioGroupIds() {
  2563. return this.audioGroups ? [this.audioGroupId] : void 0;
  2564. }
  2565. get textGroupIds() {
  2566. return this.subtitleGroups ? [this.textGroupId] : void 0;
  2567. }
  2568. get audioGroupId() {
  2569. var _this$audioGroups;
  2570. return (_this$audioGroups = this.audioGroups) == null ? void 0 : _this$audioGroups[0];
  2571. }
  2572. get textGroupId() {
  2573. var _this$subtitleGroups;
  2574. return (_this$subtitleGroups = this.subtitleGroups) == null ? void 0 : _this$subtitleGroups[0];
  2575. }
  2576. addFallback() {
  2577. }
  2578. };
  2579. function hasGroup(groups, groupId) {
  2580. if (!groupId || !groups) {
  2581. return false;
  2582. }
  2583. return groups.indexOf(groupId) !== -1;
  2584. }
  2585. function isHdrSupported() {
  2586. if (typeof matchMedia === "function") {
  2587. const mediaQueryList = matchMedia("(dynamic-range: high)");
  2588. const badQuery = matchMedia("bad query");
  2589. if (mediaQueryList.media !== badQuery.media) {
  2590. return mediaQueryList.matches === true;
  2591. }
  2592. }
  2593. return false;
  2594. }
  2595. function getVideoSelectionOptions(currentVideoRange, videoPreference) {
  2596. let preferHDR = false;
  2597. let allowedVideoRanges = [];
  2598. if (currentVideoRange) {
  2599. preferHDR = currentVideoRange !== "SDR";
  2600. allowedVideoRanges = [currentVideoRange];
  2601. }
  2602. if (videoPreference) {
  2603. allowedVideoRanges = videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);
  2604. const allowAutoPreferHDR = allowedVideoRanges.join("") !== "SDR" && !videoPreference.videoCodec;
  2605. preferHDR = videoPreference.preferHDR !== void 0 ? videoPreference.preferHDR : allowAutoPreferHDR && isHdrSupported();
  2606. if (!preferHDR) {
  2607. allowedVideoRanges = ["SDR"];
  2608. }
  2609. }
  2610. return {
  2611. preferHDR,
  2612. allowedVideoRanges
  2613. };
  2614. }
  2615. var omitCircularRefsReplacer = (replacer) => {
  2616. const known = /* @__PURE__ */ new WeakSet();
  2617. return (_, value) => {
  2618. if (replacer) {
  2619. value = replacer(_, value);
  2620. }
  2621. if (typeof value === "object" && value !== null) {
  2622. if (known.has(value)) {
  2623. return;
  2624. }
  2625. known.add(value);
  2626. }
  2627. return value;
  2628. };
  2629. };
  2630. var stringify = (object, replacer) => JSON.stringify(object, omitCircularRefsReplacer(replacer));
  2631. function getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference) {
  2632. const codecSets = Object.keys(codecTiers);
  2633. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  2634. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  2635. const videoCodecPreference = videoPreference == null ? void 0 : videoPreference.videoCodec;
  2636. const preferStereo = channelsPreference && parseInt(channelsPreference) === 2;
  2637. let hasStereo = false;
  2638. let hasCurrentVideoRange = false;
  2639. let minHeight = Infinity;
  2640. let minFramerate = Infinity;
  2641. let minBitrate = Infinity;
  2642. let minIndex = Infinity;
  2643. let selectedScore = 0;
  2644. let videoRanges = [];
  2645. const {
  2646. preferHDR,
  2647. allowedVideoRanges
  2648. } = getVideoSelectionOptions(currentVideoRange, videoPreference);
  2649. for (let i = codecSets.length; i--; ) {
  2650. const tier = codecTiers[codecSets[i]];
  2651. hasStereo || (hasStereo = tier.channels[2] > 0);
  2652. minHeight = Math.min(minHeight, tier.minHeight);
  2653. minFramerate = Math.min(minFramerate, tier.minFramerate);
  2654. minBitrate = Math.min(minBitrate, tier.minBitrate);
  2655. const matchingVideoRanges = allowedVideoRanges.filter((range) => tier.videoRanges[range] > 0);
  2656. if (matchingVideoRanges.length > 0) {
  2657. hasCurrentVideoRange = true;
  2658. }
  2659. }
  2660. minHeight = isFiniteNumber(minHeight) ? minHeight : 0;
  2661. minFramerate = isFiniteNumber(minFramerate) ? minFramerate : 0;
  2662. const maxHeight = Math.max(1080, minHeight);
  2663. const maxFramerate = Math.max(30, minFramerate);
  2664. minBitrate = isFiniteNumber(minBitrate) ? minBitrate : currentBw;
  2665. currentBw = Math.max(minBitrate, currentBw);
  2666. if (!hasCurrentVideoRange) {
  2667. currentVideoRange = void 0;
  2668. }
  2669. const hasMultipleSets = codecSets.length > 1;
  2670. const codecSet = codecSets.reduce((selected, candidate) => {
  2671. const candidateTier = codecTiers[candidate];
  2672. if (candidate === selected) {
  2673. return selected;
  2674. }
  2675. videoRanges = hasCurrentVideoRange ? allowedVideoRanges.filter((range) => candidateTier.videoRanges[range] > 0) : [];
  2676. if (hasMultipleSets) {
  2677. if (candidateTier.minBitrate > currentBw) {
  2678. logStartCodecCandidateIgnored(candidate, `min bitrate of ${candidateTier.minBitrate} > current estimate of ${currentBw}`);
  2679. return selected;
  2680. }
  2681. if (!candidateTier.hasDefaultAudio) {
  2682. logStartCodecCandidateIgnored(candidate, `no renditions with default or auto-select sound found`);
  2683. return selected;
  2684. }
  2685. if (audioCodecPreference && candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0) {
  2686. logStartCodecCandidateIgnored(candidate, `audio codec preference "${audioCodecPreference}" not found`);
  2687. return selected;
  2688. }
  2689. if (channelsPreference && !preferStereo) {
  2690. if (!candidateTier.channels[channelsPreference]) {
  2691. logStartCodecCandidateIgnored(candidate, `no renditions with ${channelsPreference} channel sound found (channels options: ${Object.keys(candidateTier.channels)})`);
  2692. return selected;
  2693. }
  2694. } else if ((!audioCodecPreference || preferStereo) && hasStereo && candidateTier.channels["2"] === 0) {
  2695. logStartCodecCandidateIgnored(candidate, `no renditions with stereo sound found`);
  2696. return selected;
  2697. }
  2698. if (candidateTier.minHeight > maxHeight) {
  2699. logStartCodecCandidateIgnored(candidate, `min resolution of ${candidateTier.minHeight} > maximum of ${maxHeight}`);
  2700. return selected;
  2701. }
  2702. if (candidateTier.minFramerate > maxFramerate) {
  2703. logStartCodecCandidateIgnored(candidate, `min framerate of ${candidateTier.minFramerate} > maximum of ${maxFramerate}`);
  2704. return selected;
  2705. }
  2706. if (!videoRanges.some((range) => candidateTier.videoRanges[range] > 0)) {
  2707. logStartCodecCandidateIgnored(candidate, `no variants with VIDEO-RANGE of ${stringify(videoRanges)} found`);
  2708. return selected;
  2709. }
  2710. if (videoCodecPreference && candidate.indexOf(videoCodecPreference.substring(0, 4)) % 5 !== 0) {
  2711. logStartCodecCandidateIgnored(candidate, `video codec preference "${videoCodecPreference}" not found`);
  2712. return selected;
  2713. }
  2714. if (candidateTier.maxScore < selectedScore) {
  2715. logStartCodecCandidateIgnored(candidate, `max score of ${candidateTier.maxScore} < selected max of ${selectedScore}`);
  2716. return selected;
  2717. }
  2718. }
  2719. if (selected && (codecsSetSelectionPreferenceValue(candidate) >= codecsSetSelectionPreferenceValue(selected) || candidateTier.fragmentError > codecTiers[selected].fragmentError)) {
  2720. return selected;
  2721. }
  2722. minIndex = candidateTier.minIndex;
  2723. selectedScore = candidateTier.maxScore;
  2724. return candidate;
  2725. }, void 0);
  2726. return {
  2727. codecSet,
  2728. videoRanges,
  2729. preferHDR,
  2730. minFramerate,
  2731. minBitrate,
  2732. minIndex
  2733. };
  2734. }
  2735. function logStartCodecCandidateIgnored(codeSet, reason) {
  2736. logger.log(`[abr] start candidates with "${codeSet}" ignored because ${reason}`);
  2737. }
  2738. function getAudioTracksByGroup(allAudioTracks) {
  2739. return allAudioTracks.reduce((audioTracksByGroup, track) => {
  2740. let trackGroup = audioTracksByGroup.groups[track.groupId];
  2741. if (!trackGroup) {
  2742. trackGroup = audioTracksByGroup.groups[track.groupId] = {
  2743. tracks: [],
  2744. channels: {
  2745. 2: 0
  2746. },
  2747. hasDefault: false,
  2748. hasAutoSelect: false
  2749. };
  2750. }
  2751. trackGroup.tracks.push(track);
  2752. const channelsKey = track.channels || "2";
  2753. trackGroup.channels[channelsKey] = (trackGroup.channels[channelsKey] || 0) + 1;
  2754. trackGroup.hasDefault = trackGroup.hasDefault || track.default;
  2755. trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;
  2756. if (trackGroup.hasDefault) {
  2757. audioTracksByGroup.hasDefaultAudio = true;
  2758. }
  2759. if (trackGroup.hasAutoSelect) {
  2760. audioTracksByGroup.hasAutoSelectAudio = true;
  2761. }
  2762. return audioTracksByGroup;
  2763. }, {
  2764. hasDefaultAudio: false,
  2765. hasAutoSelectAudio: false,
  2766. groups: {}
  2767. });
  2768. }
  2769. function getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel) {
  2770. return levels.slice(minAutoLevel, maxAutoLevel + 1).reduce((tiers, level, index) => {
  2771. if (!level.codecSet) {
  2772. return tiers;
  2773. }
  2774. const audioGroups = level.audioGroups;
  2775. let tier = tiers[level.codecSet];
  2776. if (!tier) {
  2777. tiers[level.codecSet] = tier = {
  2778. minBitrate: Infinity,
  2779. minHeight: Infinity,
  2780. minFramerate: Infinity,
  2781. minIndex: index,
  2782. maxScore: 0,
  2783. videoRanges: {
  2784. SDR: 0
  2785. },
  2786. channels: {
  2787. "2": 0
  2788. },
  2789. hasDefaultAudio: !audioGroups,
  2790. fragmentError: 0
  2791. };
  2792. }
  2793. tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);
  2794. const lesserWidthOrHeight = Math.min(level.height, level.width);
  2795. tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);
  2796. tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);
  2797. tier.minIndex = Math.min(tier.minIndex, index);
  2798. tier.maxScore = Math.max(tier.maxScore, level.score);
  2799. tier.fragmentError += level.fragmentError;
  2800. tier.videoRanges[level.videoRange] = (tier.videoRanges[level.videoRange] || 0) + 1;
  2801. if (audioGroups) {
  2802. audioGroups.forEach((audioGroupId) => {
  2803. if (!audioGroupId) {
  2804. return;
  2805. }
  2806. const audioGroup = audioTracksByGroup.groups[audioGroupId];
  2807. if (!audioGroup) {
  2808. return;
  2809. }
  2810. tier.hasDefaultAudio = tier.hasDefaultAudio || audioTracksByGroup.hasDefaultAudio ? audioGroup.hasDefault : audioGroup.hasAutoSelect || !audioTracksByGroup.hasDefaultAudio && !audioTracksByGroup.hasAutoSelectAudio;
  2811. Object.keys(audioGroup.channels).forEach((channels) => {
  2812. tier.channels[channels] = (tier.channels[channels] || 0) + audioGroup.channels[channels];
  2813. });
  2814. });
  2815. }
  2816. return tiers;
  2817. }, {});
  2818. }
  2819. function getBasicSelectionOption(option) {
  2820. if (!option) {
  2821. return option;
  2822. }
  2823. const {
  2824. lang,
  2825. assocLang,
  2826. characteristics,
  2827. channels,
  2828. audioCodec
  2829. } = option;
  2830. return {
  2831. lang,
  2832. assocLang,
  2833. characteristics,
  2834. channels,
  2835. audioCodec
  2836. };
  2837. }
  2838. function findMatchingOption(option, tracks, matchPredicate) {
  2839. if ("attrs" in option) {
  2840. const index = tracks.indexOf(option);
  2841. if (index !== -1) {
  2842. return index;
  2843. }
  2844. }
  2845. for (let i = 0; i < tracks.length; i++) {
  2846. const track = tracks[i];
  2847. if (matchesOption(option, track, matchPredicate)) {
  2848. return i;
  2849. }
  2850. }
  2851. return -1;
  2852. }
  2853. function matchesOption(option, track, matchPredicate) {
  2854. const {
  2855. groupId,
  2856. name,
  2857. lang,
  2858. assocLang,
  2859. default: isDefault
  2860. } = option;
  2861. const forced = option.forced;
  2862. 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));
  2863. }
  2864. function languagesMatch(languageA, languageB = "--") {
  2865. if (languageA.length === languageB.length) {
  2866. return languageA === languageB;
  2867. }
  2868. return languageA.startsWith(languageB) || languageB.startsWith(languageA);
  2869. }
  2870. function characteristicsMatch(characteristicsA, characteristicsB = "") {
  2871. const arrA = characteristicsA.split(",");
  2872. const arrB = characteristicsB.split(",");
  2873. return arrA.length === arrB.length && !arrA.some((el) => arrB.indexOf(el) === -1);
  2874. }
  2875. function audioMatchPredicate(option, track) {
  2876. const {
  2877. audioCodec,
  2878. channels
  2879. } = option;
  2880. return (audioCodec === void 0 || (track.audioCodec || "").substring(0, 4) === audioCodec.substring(0, 4)) && (channels === void 0 || channels === (track.channels || "2"));
  2881. }
  2882. function findClosestLevelWithAudioGroup(option, levels, allAudioTracks, searchIndex, matchPredicate) {
  2883. const currentLevel = levels[searchIndex];
  2884. const variants = levels.reduce((variantMap, level, index) => {
  2885. const uri = level.uri;
  2886. const renditions2 = variantMap[uri] || (variantMap[uri] = []);
  2887. renditions2.push(index);
  2888. return variantMap;
  2889. }, {});
  2890. const renditions = variants[currentLevel.uri];
  2891. if (renditions.length > 1) {
  2892. searchIndex = Math.max.apply(Math, renditions);
  2893. }
  2894. const currentVideoRange = currentLevel.videoRange;
  2895. const currentFrameRate = currentLevel.frameRate;
  2896. const currentVideoCodec = currentLevel.codecSet.substring(0, 4);
  2897. const matchingVideo = searchDownAndUpList(levels, searchIndex, (level) => {
  2898. if (level.videoRange !== currentVideoRange || level.frameRate !== currentFrameRate || level.codecSet.substring(0, 4) !== currentVideoCodec) {
  2899. return false;
  2900. }
  2901. const audioGroups = level.audioGroups;
  2902. const tracks = allAudioTracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  2903. return findMatchingOption(option, tracks, matchPredicate) > -1;
  2904. });
  2905. if (matchingVideo > -1) {
  2906. return matchingVideo;
  2907. }
  2908. return searchDownAndUpList(levels, searchIndex, (level) => {
  2909. const audioGroups = level.audioGroups;
  2910. const tracks = allAudioTracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  2911. return findMatchingOption(option, tracks, matchPredicate) > -1;
  2912. });
  2913. }
  2914. function searchDownAndUpList(arr, searchIndex, predicate) {
  2915. for (let i = searchIndex; i > -1; i--) {
  2916. if (predicate(arr[i])) {
  2917. return i;
  2918. }
  2919. }
  2920. for (let i = searchIndex + 1; i < arr.length; i++) {
  2921. if (predicate(arr[i])) {
  2922. return i;
  2923. }
  2924. }
  2925. return -1;
  2926. }
  2927. function useAlternateAudio(audioTrackUrl, hls) {
  2928. var _hls$loadLevelObj;
  2929. return !!audioTrackUrl && audioTrackUrl !== ((_hls$loadLevelObj = hls.loadLevelObj) == null ? void 0 : _hls$loadLevelObj.uri);
  2930. }
  2931. var AbrController = class extends Logger {
  2932. constructor(_hls) {
  2933. super("abr", _hls.logger);
  2934. this.hls = void 0;
  2935. this.lastLevelLoadSec = 0;
  2936. this.lastLoadedFragLevel = -1;
  2937. this.firstSelection = -1;
  2938. this._nextAutoLevel = -1;
  2939. this.nextAutoLevelKey = "";
  2940. this.audioTracksByGroup = null;
  2941. this.codecTiers = null;
  2942. this.timer = -1;
  2943. this.fragCurrent = null;
  2944. this.partCurrent = null;
  2945. this.bitrateTestDelay = 0;
  2946. this.rebufferNotice = -1;
  2947. this.supportedCache = {};
  2948. this.bwEstimator = void 0;
  2949. this._abandonRulesCheck = (levelLoaded) => {
  2950. var _ref;
  2951. const {
  2952. fragCurrent: frag,
  2953. partCurrent: part,
  2954. hls
  2955. } = this;
  2956. const {
  2957. autoLevelEnabled,
  2958. media
  2959. } = hls;
  2960. if (!frag || !media) {
  2961. return;
  2962. }
  2963. const now2 = performance.now();
  2964. const stats = part ? part.stats : frag.stats;
  2965. const duration = part ? part.duration : frag.duration;
  2966. const timeLoading = now2 - stats.loading.start;
  2967. const minAutoLevel = hls.minAutoLevel;
  2968. const loadingFragForLevel = frag.level;
  2969. const currentAutoLevel = this._nextAutoLevel;
  2970. if (stats.aborted || stats.loaded && stats.loaded === stats.total || loadingFragForLevel <= minAutoLevel) {
  2971. this.clearTimer();
  2972. this._nextAutoLevel = -1;
  2973. return;
  2974. }
  2975. if (!autoLevelEnabled) {
  2976. return;
  2977. }
  2978. const fragBlockingSwitch = currentAutoLevel > -1 && currentAutoLevel !== loadingFragForLevel;
  2979. const levelChange = !!levelLoaded || fragBlockingSwitch;
  2980. if (!levelChange && (media.paused || !media.playbackRate || !media.readyState)) {
  2981. return;
  2982. }
  2983. const bufferInfo = hls.mainForwardBufferInfo;
  2984. if (!levelChange && bufferInfo === null) {
  2985. return;
  2986. }
  2987. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  2988. const playbackRate = Math.abs(media.playbackRate);
  2989. if (timeLoading <= Math.max(ttfbEstimate, 1e3 * (duration / (playbackRate * 2)))) {
  2990. return;
  2991. }
  2992. const bufferStarvationDelay = bufferInfo ? bufferInfo.len / playbackRate : 0;
  2993. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  2994. const loadedFirstByte = stats.loaded && ttfb > -1;
  2995. const bwEstimate = this.getBwEstimate();
  2996. const levels = hls.levels;
  2997. const level = levels[loadingFragForLevel];
  2998. const expectedLen = Math.max(stats.loaded, Math.round(duration * (frag.bitrate || level.averageBitrate) / 8));
  2999. let timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;
  3000. if (timeStreaming < 1 && loadedFirstByte) {
  3001. timeStreaming = Math.min(timeLoading, stats.loaded * 8 / bwEstimate);
  3002. }
  3003. const loadRate = loadedFirstByte ? stats.loaded * 1e3 / timeStreaming : 0;
  3004. const ttfbSeconds = ttfbEstimate / 1e3;
  3005. const fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate + ttfbSeconds;
  3006. if (fragLoadedDelay <= bufferStarvationDelay) {
  3007. return;
  3008. }
  3009. const bwe = loadRate ? loadRate * 8 : bwEstimate;
  3010. const live = ((_ref = (levelLoaded == null ? void 0 : levelLoaded.details) || this.hls.latestLevelDetails) == null ? void 0 : _ref.live) === true;
  3011. const abrBandWidthUpFactor = this.hls.config.abrBandWidthUpFactor;
  3012. let fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
  3013. let nextLoadLevel;
  3014. for (nextLoadLevel = loadingFragForLevel - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  3015. const levelNextBitrate = levels[nextLoadLevel].maxBitrate;
  3016. const requiresLevelLoad = !levels[nextLoadLevel].details || live;
  3017. fragLevelNextLoadedDelay = this.getTimeToLoadFrag(ttfbSeconds, bwe, duration * levelNextBitrate, requiresLevelLoad);
  3018. if (fragLevelNextLoadedDelay < Math.min(bufferStarvationDelay, duration + ttfbSeconds)) {
  3019. break;
  3020. }
  3021. }
  3022. if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
  3023. return;
  3024. }
  3025. if (fragLevelNextLoadedDelay > duration * 10) {
  3026. return;
  3027. }
  3028. if (loadedFirstByte) {
  3029. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  3030. } else {
  3031. this.bwEstimator.sampleTTFB(timeLoading);
  3032. }
  3033. const nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;
  3034. if (this.getBwEstimate() * abrBandWidthUpFactor > nextLoadLevelBitrate) {
  3035. this.resetEstimator(nextLoadLevelBitrate);
  3036. }
  3037. const bestSwitchLevel = this.findBestLevel(nextLoadLevelBitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay, 1, 1);
  3038. if (bestSwitchLevel > -1) {
  3039. nextLoadLevel = bestSwitchLevel;
  3040. }
  3041. this.warn(`Fragment ${frag.sn}${part ? " part " + part.index : ""} of level ${loadingFragForLevel} is loading too slowly;
  3042. Fragment duration: ${frag.duration.toFixed(3)}
  3043. Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s
  3044. Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s
  3045. Estimated load time for down switch fragment: ${fragLevelNextLoadedDelay.toFixed(3)} s
  3046. TTFB estimate: ${ttfb | 0} ms
  3047. Current BW estimate: ${isFiniteNumber(bwEstimate) ? bwEstimate | 0 : "Unknown"} bps
  3048. New BW estimate: ${this.getBwEstimate() | 0} bps
  3049. Switching to level ${nextLoadLevel} @ ${nextLoadLevelBitrate | 0} bps`);
  3050. hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;
  3051. this.clearTimer();
  3052. const abortAndSwitch = () => {
  3053. this.clearTimer();
  3054. if (this.fragCurrent === frag && this.hls.loadLevel === nextLoadLevel && nextLoadLevel > 0) {
  3055. const bufferStarvationDelay2 = this.getStarvationDelay();
  3056. this.warn(`Aborting inflight request ${nextLoadLevel > 0 ? "and switching down" : ""}
  3057. Fragment duration: ${frag.duration.toFixed(3)} s
  3058. Time to underbuffer: ${bufferStarvationDelay2.toFixed(3)} s`);
  3059. frag.abortRequests();
  3060. this.fragCurrent = this.partCurrent = null;
  3061. if (nextLoadLevel > minAutoLevel) {
  3062. let lowestSwitchLevel = this.findBestLevel(this.hls.levels[minAutoLevel].bitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay2, 1, 1);
  3063. if (lowestSwitchLevel === -1) {
  3064. lowestSwitchLevel = minAutoLevel;
  3065. }
  3066. this.hls.nextLoadLevel = this.hls.nextAutoLevel = lowestSwitchLevel;
  3067. this.resetEstimator(this.hls.levels[lowestSwitchLevel].bitrate);
  3068. }
  3069. }
  3070. };
  3071. if (fragBlockingSwitch || fragLoadedDelay > fragLevelNextLoadedDelay * 2) {
  3072. abortAndSwitch();
  3073. } else {
  3074. this.timer = self.setInterval(abortAndSwitch, fragLevelNextLoadedDelay * 1e3);
  3075. }
  3076. hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, {
  3077. frag,
  3078. part,
  3079. stats
  3080. });
  3081. };
  3082. this.hls = _hls;
  3083. this.bwEstimator = this.initEstimator();
  3084. this.registerListeners();
  3085. }
  3086. resetEstimator(abrEwmaDefaultEstimate) {
  3087. if (abrEwmaDefaultEstimate) {
  3088. this.log(`setting initial bwe to ${abrEwmaDefaultEstimate}`);
  3089. this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;
  3090. }
  3091. this.firstSelection = -1;
  3092. this.bwEstimator = this.initEstimator();
  3093. }
  3094. initEstimator() {
  3095. const config = this.hls.config;
  3096. return new EwmaBandWidthEstimator(config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
  3097. }
  3098. registerListeners() {
  3099. const {
  3100. hls
  3101. } = this;
  3102. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3103. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  3104. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  3105. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  3106. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  3107. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  3108. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  3109. hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  3110. hls.on(Events.ERROR, this.onError, this);
  3111. }
  3112. unregisterListeners() {
  3113. const {
  3114. hls
  3115. } = this;
  3116. if (!hls) {
  3117. return;
  3118. }
  3119. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3120. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  3121. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  3122. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  3123. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  3124. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  3125. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  3126. hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  3127. hls.off(Events.ERROR, this.onError, this);
  3128. }
  3129. destroy() {
  3130. this.unregisterListeners();
  3131. this.clearTimer();
  3132. this.hls = this._abandonRulesCheck = this.supportedCache = null;
  3133. this.fragCurrent = this.partCurrent = null;
  3134. }
  3135. onManifestLoading(event, data) {
  3136. this.lastLoadedFragLevel = -1;
  3137. this.firstSelection = -1;
  3138. this.lastLevelLoadSec = 0;
  3139. this.supportedCache = {};
  3140. this.fragCurrent = this.partCurrent = null;
  3141. this.onLevelsUpdated();
  3142. this.clearTimer();
  3143. }
  3144. onLevelsUpdated() {
  3145. if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {
  3146. this.lastLoadedFragLevel = this.fragCurrent.level;
  3147. }
  3148. this._nextAutoLevel = -1;
  3149. this.onMaxAutoLevelUpdated();
  3150. this.codecTiers = null;
  3151. this.audioTracksByGroup = null;
  3152. }
  3153. onMaxAutoLevelUpdated() {
  3154. this.firstSelection = -1;
  3155. this.nextAutoLevelKey = "";
  3156. }
  3157. onFragLoading(event, data) {
  3158. const frag = data.frag;
  3159. if (this.ignoreFragment(frag)) {
  3160. return;
  3161. }
  3162. if (!frag.bitrateTest) {
  3163. var _data$part;
  3164. this.fragCurrent = frag;
  3165. this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
  3166. }
  3167. this.clearTimer();
  3168. this.timer = self.setInterval(this._abandonRulesCheck, 100);
  3169. }
  3170. onLevelSwitching(event, data) {
  3171. this.clearTimer();
  3172. }
  3173. onError(event, data) {
  3174. if (data.fatal) {
  3175. return;
  3176. }
  3177. switch (data.details) {
  3178. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  3179. case ErrorDetails.BUFFER_APPEND_ERROR:
  3180. this.lastLoadedFragLevel = -1;
  3181. this.firstSelection = -1;
  3182. break;
  3183. case ErrorDetails.FRAG_LOAD_TIMEOUT: {
  3184. const frag = data.frag;
  3185. const {
  3186. fragCurrent,
  3187. partCurrent: part
  3188. } = this;
  3189. if (frag && fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level) {
  3190. const now2 = performance.now();
  3191. const stats = part ? part.stats : frag.stats;
  3192. const timeLoading = now2 - stats.loading.start;
  3193. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  3194. const loadedFirstByte = stats.loaded && ttfb > -1;
  3195. if (loadedFirstByte) {
  3196. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  3197. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  3198. } else {
  3199. this.bwEstimator.sampleTTFB(timeLoading);
  3200. }
  3201. }
  3202. break;
  3203. }
  3204. }
  3205. }
  3206. getTimeToLoadFrag(timeToFirstByteSec, bandwidth, fragSizeBits, isSwitch) {
  3207. const fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;
  3208. const playlistLoadSec = isSwitch ? timeToFirstByteSec + this.lastLevelLoadSec : 0;
  3209. return fragLoadSec + playlistLoadSec;
  3210. }
  3211. onLevelLoaded(event, data) {
  3212. const config = this.hls.config;
  3213. const {
  3214. loading
  3215. } = data.stats;
  3216. const timeLoadingMs = loading.end - loading.first;
  3217. if (isFiniteNumber(timeLoadingMs)) {
  3218. this.lastLevelLoadSec = timeLoadingMs / 1e3;
  3219. }
  3220. if (data.details.live) {
  3221. this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
  3222. } else {
  3223. this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
  3224. }
  3225. if (this.timer > -1) {
  3226. this._abandonRulesCheck(data.levelInfo);
  3227. }
  3228. }
  3229. onFragLoaded(event, {
  3230. frag,
  3231. part
  3232. }) {
  3233. const stats = part ? part.stats : frag.stats;
  3234. if (frag.type === PlaylistLevelType.MAIN) {
  3235. this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);
  3236. }
  3237. if (this.ignoreFragment(frag)) {
  3238. return;
  3239. }
  3240. this.clearTimer();
  3241. if (frag.level === this._nextAutoLevel) {
  3242. this._nextAutoLevel = -1;
  3243. }
  3244. this.firstSelection = -1;
  3245. if (this.hls.config.abrMaxWithRealBitrate) {
  3246. const duration = part ? part.duration : frag.duration;
  3247. const level = this.hls.levels[frag.level];
  3248. const loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
  3249. const loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
  3250. level.loaded = {
  3251. bytes: loadedBytes,
  3252. duration: loadedDuration
  3253. };
  3254. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  3255. }
  3256. if (frag.bitrateTest) {
  3257. const fragBufferedData = {
  3258. stats,
  3259. frag,
  3260. part,
  3261. id: frag.type
  3262. };
  3263. this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);
  3264. frag.bitrateTest = false;
  3265. } else {
  3266. this.lastLoadedFragLevel = frag.level;
  3267. }
  3268. }
  3269. onFragBuffered(event, data) {
  3270. const {
  3271. frag,
  3272. part
  3273. } = data;
  3274. const stats = part != null && part.stats.loaded ? part.stats : frag.stats;
  3275. if (stats.aborted) {
  3276. return;
  3277. }
  3278. if (this.ignoreFragment(frag)) {
  3279. return;
  3280. }
  3281. const processingMs = stats.parsing.end - stats.loading.start - Math.min(stats.loading.first - stats.loading.start, this.bwEstimator.getEstimateTTFB());
  3282. this.bwEstimator.sample(processingMs, stats.loaded);
  3283. stats.bwEstimate = this.getBwEstimate();
  3284. if (frag.bitrateTest) {
  3285. this.bitrateTestDelay = processingMs / 1e3;
  3286. } else {
  3287. this.bitrateTestDelay = 0;
  3288. }
  3289. }
  3290. ignoreFragment(frag) {
  3291. return frag.type !== PlaylistLevelType.MAIN || frag.sn === "initSegment";
  3292. }
  3293. clearTimer() {
  3294. if (this.timer > -1) {
  3295. self.clearInterval(this.timer);
  3296. this.timer = -1;
  3297. }
  3298. }
  3299. get firstAutoLevel() {
  3300. const {
  3301. maxAutoLevel,
  3302. minAutoLevel
  3303. } = this.hls;
  3304. const bwEstimate = this.getBwEstimate();
  3305. const maxStartDelay = this.hls.config.maxStarvationDelay;
  3306. const abrAutoLevel = this.findBestLevel(bwEstimate, minAutoLevel, maxAutoLevel, 0, maxStartDelay, 1, 1);
  3307. if (abrAutoLevel > -1) {
  3308. return abrAutoLevel;
  3309. }
  3310. const firstLevel = this.hls.firstLevel;
  3311. const clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);
  3312. this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${firstLevel} clamped to ${clamped}`);
  3313. return clamped;
  3314. }
  3315. get forcedAutoLevel() {
  3316. if (this.nextAutoLevelKey) {
  3317. return -1;
  3318. }
  3319. return this._nextAutoLevel;
  3320. }
  3321. // return next auto level
  3322. get nextAutoLevel() {
  3323. const forcedAutoLevel = this.forcedAutoLevel;
  3324. const bwEstimator = this.bwEstimator;
  3325. const useEstimate = bwEstimator.canEstimate();
  3326. const loadedFirstFrag = this.lastLoadedFragLevel > -1;
  3327. if (forcedAutoLevel !== -1 && (!useEstimate || !loadedFirstFrag || this.nextAutoLevelKey === this.getAutoLevelKey())) {
  3328. return forcedAutoLevel;
  3329. }
  3330. const nextABRAutoLevel = useEstimate && loadedFirstFrag ? this.getNextABRAutoLevel() : this.firstAutoLevel;
  3331. if (forcedAutoLevel !== -1) {
  3332. const levels = this.hls.levels;
  3333. if (levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) && levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError) {
  3334. return forcedAutoLevel;
  3335. }
  3336. }
  3337. this._nextAutoLevel = nextABRAutoLevel;
  3338. this.nextAutoLevelKey = this.getAutoLevelKey();
  3339. return nextABRAutoLevel;
  3340. }
  3341. getAutoLevelKey() {
  3342. return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`;
  3343. }
  3344. getNextABRAutoLevel() {
  3345. const {
  3346. fragCurrent,
  3347. partCurrent,
  3348. hls
  3349. } = this;
  3350. if (hls.levels.length <= 1) {
  3351. return hls.loadLevel;
  3352. }
  3353. const {
  3354. maxAutoLevel,
  3355. config,
  3356. minAutoLevel
  3357. } = hls;
  3358. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  3359. const avgbw = this.getBwEstimate();
  3360. const bufferStarvationDelay = this.getStarvationDelay();
  3361. let bwFactor = config.abrBandWidthFactor;
  3362. let bwUpFactor = config.abrBandWidthUpFactor;
  3363. if (bufferStarvationDelay) {
  3364. const _bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, 0, bwFactor, bwUpFactor);
  3365. if (_bestLevel >= 0) {
  3366. this.rebufferNotice = -1;
  3367. return _bestLevel;
  3368. }
  3369. }
  3370. let maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
  3371. if (!bufferStarvationDelay) {
  3372. const bitrateTestDelay = this.bitrateTestDelay;
  3373. if (bitrateTestDelay) {
  3374. const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  3375. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  3376. this.info(`bitrate test took ${Math.round(1e3 * bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1e3 * maxStarvationDelay)} ms`);
  3377. bwFactor = bwUpFactor = 1;
  3378. }
  3379. }
  3380. const bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor);
  3381. if (this.rebufferNotice !== bestLevel) {
  3382. this.rebufferNotice = bestLevel;
  3383. this.info(`${bufferStarvationDelay ? "rebuffering expected" : "buffer is empty"}, optimal quality level ${bestLevel}`);
  3384. }
  3385. if (bestLevel > -1) {
  3386. return bestLevel;
  3387. }
  3388. const minLevel = hls.levels[minAutoLevel];
  3389. const autoLevel = hls.loadLevelObj;
  3390. if (autoLevel && (minLevel == null ? void 0 : minLevel.bitrate) < autoLevel.bitrate) {
  3391. return minAutoLevel;
  3392. }
  3393. return hls.loadLevel;
  3394. }
  3395. getStarvationDelay() {
  3396. const hls = this.hls;
  3397. const media = hls.media;
  3398. if (!media) {
  3399. return Infinity;
  3400. }
  3401. const playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1;
  3402. const bufferInfo = hls.mainForwardBufferInfo;
  3403. return (bufferInfo ? bufferInfo.len : 0) / playbackRate;
  3404. }
  3405. getBwEstimate() {
  3406. return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;
  3407. }
  3408. findBestLevel(currentBw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor) {
  3409. var _this$hls$latestLevel;
  3410. const maxFetchDuration = bufferStarvationDelay + maxStarvationDelay;
  3411. const lastLoadedFragLevel = this.lastLoadedFragLevel;
  3412. const selectionBaseLevel = lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;
  3413. const {
  3414. fragCurrent,
  3415. partCurrent
  3416. } = this;
  3417. const {
  3418. levels,
  3419. allAudioTracks,
  3420. loadLevel,
  3421. config
  3422. } = this.hls;
  3423. if (levels.length === 1) {
  3424. return 0;
  3425. }
  3426. const level = levels[selectionBaseLevel];
  3427. const live = !!((_this$hls$latestLevel = this.hls.latestLevelDetails) != null && _this$hls$latestLevel.live);
  3428. const firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;
  3429. let currentCodecSet;
  3430. let currentVideoRange = "SDR";
  3431. let currentFrameRate = (level == null ? void 0 : level.frameRate) || 0;
  3432. const {
  3433. audioPreference,
  3434. videoPreference
  3435. } = config;
  3436. const audioTracksByGroup = this.audioTracksByGroup || (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));
  3437. let minStartIndex = -1;
  3438. if (firstSelection) {
  3439. if (this.firstSelection !== -1) {
  3440. return this.firstSelection;
  3441. }
  3442. const codecTiers = this.codecTiers || (this.codecTiers = getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel));
  3443. const startTier = getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference);
  3444. const {
  3445. codecSet,
  3446. videoRanges,
  3447. minFramerate,
  3448. minBitrate,
  3449. minIndex,
  3450. preferHDR
  3451. } = startTier;
  3452. minStartIndex = minIndex;
  3453. currentCodecSet = codecSet;
  3454. currentVideoRange = preferHDR ? videoRanges[videoRanges.length - 1] : videoRanges[0];
  3455. currentFrameRate = minFramerate;
  3456. currentBw = Math.max(currentBw, minBitrate);
  3457. this.log(`picked start tier ${stringify(startTier)}`);
  3458. } else {
  3459. currentCodecSet = level == null ? void 0 : level.codecSet;
  3460. currentVideoRange = level == null ? void 0 : level.videoRange;
  3461. }
  3462. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  3463. const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1e3;
  3464. const levelsSkipped = [];
  3465. for (let i = maxAutoLevel; i >= minAutoLevel; i--) {
  3466. var _levelInfo$supportedR;
  3467. const levelInfo = levels[i];
  3468. const upSwitch = i > selectionBaseLevel;
  3469. if (!levelInfo) {
  3470. continue;
  3471. }
  3472. if (config.useMediaCapabilities && !levelInfo.supportedResult && !levelInfo.supportedPromise) {
  3473. const mediaCapabilities = navigator.mediaCapabilities;
  3474. if (typeof (mediaCapabilities == null ? void 0 : mediaCapabilities.decodingInfo) === "function" && requiresMediaCapabilitiesDecodingInfo(levelInfo, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference)) {
  3475. levelInfo.supportedPromise = getMediaDecodingInfoPromise(levelInfo, audioTracksByGroup, mediaCapabilities, this.supportedCache);
  3476. levelInfo.supportedPromise.then((decodingInfo) => {
  3477. if (!this.hls) {
  3478. return;
  3479. }
  3480. levelInfo.supportedResult = decodingInfo;
  3481. const levels2 = this.hls.levels;
  3482. const index = levels2.indexOf(levelInfo);
  3483. if (decodingInfo.error) {
  3484. this.warn(`MediaCapabilities decodingInfo error: "${decodingInfo.error}" for level ${index} ${stringify(decodingInfo)}`);
  3485. } else if (!decodingInfo.supported) {
  3486. this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${index} ${stringify(decodingInfo)}`);
  3487. if (index > -1 && levels2.length > 1) {
  3488. this.log(`Removing unsupported level ${index}`);
  3489. this.hls.removeLevel(index);
  3490. if (this.hls.loadLevel === -1) {
  3491. this.hls.nextLoadLevel = 0;
  3492. }
  3493. }
  3494. } else if (decodingInfo.decodingInfoResults.some((info) => info.smooth === false || info.powerEfficient === false)) {
  3495. this.log(`MediaCapabilities decodingInfo for level ${index} not smooth or powerEfficient: ${stringify(decodingInfo)}`);
  3496. }
  3497. }).catch((error) => {
  3498. this.warn(`Error handling MediaCapabilities decodingInfo: ${error}`);
  3499. });
  3500. } else {
  3501. levelInfo.supportedResult = SUPPORTED_INFO_DEFAULT;
  3502. }
  3503. }
  3504. 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$supportedR = _levelInfo$supportedR.decodingInfoResults) != null && _levelInfo$supportedR.some((info) => info.smooth === false)) {
  3505. if (!firstSelection || i !== minStartIndex) {
  3506. levelsSkipped.push(i);
  3507. continue;
  3508. }
  3509. }
  3510. const levelDetails = levelInfo.details;
  3511. const avgDuration = (partCurrent ? levelDetails == null ? void 0 : levelDetails.partTarget : levelDetails == null ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
  3512. let adjustedbw;
  3513. if (!upSwitch) {
  3514. adjustedbw = bwFactor * currentBw;
  3515. } else {
  3516. adjustedbw = bwUpFactor * currentBw;
  3517. }
  3518. const bitrate = currentFragDuration && bufferStarvationDelay >= currentFragDuration * 2 && maxStarvationDelay === 0 ? levelInfo.averageBitrate : levelInfo.maxBitrate;
  3519. const fetchDuration = this.getTimeToLoadFrag(ttfbEstimateSec, adjustedbw, bitrate * avgDuration, levelDetails === void 0);
  3520. const canSwitchWithinTolerance = (
  3521. // if adjusted bw is greater than level bitrate AND
  3522. adjustedbw >= bitrate && // no level change, or new level has no error history
  3523. (i === lastLoadedFragLevel || levelInfo.loadError === 0 && levelInfo.fragmentError === 0) && // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  3524. // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...
  3525. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
  3526. (fetchDuration <= ttfbEstimateSec || !isFiniteNumber(fetchDuration) || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)
  3527. );
  3528. if (canSwitchWithinTolerance) {
  3529. const forcedAutoLevel = this.forcedAutoLevel;
  3530. if (i !== loadLevel && (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)) {
  3531. if (levelsSkipped.length) {
  3532. 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}`);
  3533. }
  3534. 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}`);
  3535. }
  3536. if (firstSelection) {
  3537. this.firstSelection = i;
  3538. }
  3539. return i;
  3540. }
  3541. }
  3542. return -1;
  3543. }
  3544. set nextAutoLevel(nextLevel) {
  3545. const value = this.deriveNextAutoLevel(nextLevel);
  3546. if (this._nextAutoLevel !== value) {
  3547. this.nextAutoLevelKey = "";
  3548. this._nextAutoLevel = value;
  3549. }
  3550. }
  3551. deriveNextAutoLevel(nextLevel) {
  3552. const {
  3553. maxAutoLevel,
  3554. minAutoLevel
  3555. } = this.hls;
  3556. return Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);
  3557. }
  3558. };
  3559. var BinarySearch = {
  3560. /**
  3561. * Searches for an item in an array which matches a certain condition.
  3562. * This requires the condition to only match one item in the array,
  3563. * and for the array to be ordered.
  3564. *
  3565. * @param list The array to search.
  3566. * @param comparisonFn
  3567. * Called and provided a candidate item as the first argument.
  3568. * Should return:
  3569. * > -1 if the item should be located at a lower index than the provided item.
  3570. * > 1 if the item should be located at a higher index than the provided item.
  3571. * > 0 if the item is the item you're looking for.
  3572. *
  3573. * @returns the object if found, otherwise returns null
  3574. */
  3575. search: function(list, comparisonFn) {
  3576. let minIndex = 0;
  3577. let maxIndex = list.length - 1;
  3578. let currentIndex = null;
  3579. let currentElement = null;
  3580. while (minIndex <= maxIndex) {
  3581. currentIndex = (minIndex + maxIndex) / 2 | 0;
  3582. currentElement = list[currentIndex];
  3583. const comparisonResult = comparisonFn(currentElement);
  3584. if (comparisonResult > 0) {
  3585. minIndex = currentIndex + 1;
  3586. } else if (comparisonResult < 0) {
  3587. maxIndex = currentIndex - 1;
  3588. } else {
  3589. return currentElement;
  3590. }
  3591. }
  3592. return null;
  3593. }
  3594. };
  3595. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  3596. if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !isFiniteNumber(PDTValue)) {
  3597. return null;
  3598. }
  3599. const startPDT = fragments[0].programDateTime;
  3600. if (PDTValue < (startPDT || 0)) {
  3601. return null;
  3602. }
  3603. const endPDT = fragments[fragments.length - 1].endProgramDateTime;
  3604. if (PDTValue >= (endPDT || 0)) {
  3605. return null;
  3606. }
  3607. for (let seg = 0; seg < fragments.length; ++seg) {
  3608. const frag = fragments[seg];
  3609. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  3610. return frag;
  3611. }
  3612. }
  3613. return null;
  3614. }
  3615. function findFragmentByPTS(fragPrevious, fragments, bufferEnd = 0, maxFragLookUpTolerance = 0, nextFragLookupTolerance = 5e-3) {
  3616. let fragNext = null;
  3617. if (fragPrevious) {
  3618. fragNext = fragments[1 + fragPrevious.sn - fragments[0].sn] || null;
  3619. const bufferEdgeError = fragPrevious.endDTS - bufferEnd;
  3620. if (bufferEdgeError > 0 && bufferEdgeError < 15e-7) {
  3621. bufferEnd += 15e-7;
  3622. }
  3623. if (fragNext && fragPrevious.level !== fragNext.level && fragNext.end <= fragPrevious.end) {
  3624. fragNext = fragments[2 + fragPrevious.sn - fragments[0].sn] || null;
  3625. }
  3626. } else if (bufferEnd === 0 && fragments[0].start === 0) {
  3627. fragNext = fragments[0];
  3628. }
  3629. if (fragNext && ((!fragPrevious || fragPrevious.level === fragNext.level) && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0 || fragmentWithinFastStartSwitch(fragNext, fragPrevious, Math.min(nextFragLookupTolerance, maxFragLookUpTolerance)))) {
  3630. return fragNext;
  3631. }
  3632. const foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  3633. if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {
  3634. return foundFragment;
  3635. }
  3636. return fragNext;
  3637. }
  3638. function fragmentWithinFastStartSwitch(fragNext, fragPrevious, nextFragLookupTolerance) {
  3639. if (fragPrevious && fragPrevious.start === 0 && fragPrevious.level < fragNext.level && (fragPrevious.endPTS || 0) > 0) {
  3640. const firstDuration = fragPrevious.tagList.reduce((duration, tag) => {
  3641. if (tag[0] === "INF") {
  3642. duration += parseFloat(tag[1]);
  3643. }
  3644. return duration;
  3645. }, nextFragLookupTolerance);
  3646. return fragNext.start <= firstDuration;
  3647. }
  3648. return false;
  3649. }
  3650. function fragmentWithinToleranceTest(bufferEnd = 0, maxFragLookUpTolerance = 0, candidate) {
  3651. if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) {
  3652. return 0;
  3653. }
  3654. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  3655. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  3656. return 1;
  3657. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  3658. return -1;
  3659. }
  3660. return 0;
  3661. }
  3662. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  3663. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1e3;
  3664. const endProgramDateTime = candidate.endProgramDateTime || 0;
  3665. return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  3666. }
  3667. function findNearestWithCC(details, cc, pos) {
  3668. if (details) {
  3669. if (details.startCC <= cc && details.endCC >= cc) {
  3670. let fragments = details.fragments;
  3671. const {
  3672. fragmentHint
  3673. } = details;
  3674. if (fragmentHint) {
  3675. fragments = fragments.concat(fragmentHint);
  3676. }
  3677. let closest;
  3678. BinarySearch.search(fragments, (candidate) => {
  3679. if (candidate.cc < cc) {
  3680. return 1;
  3681. }
  3682. if (candidate.cc > cc) {
  3683. return -1;
  3684. }
  3685. closest = candidate;
  3686. if (candidate.end <= pos) {
  3687. return 1;
  3688. }
  3689. if (candidate.start > pos) {
  3690. return -1;
  3691. }
  3692. return 0;
  3693. });
  3694. return closest || null;
  3695. }
  3696. }
  3697. return null;
  3698. }
  3699. function isTimeoutError(error) {
  3700. switch (error.details) {
  3701. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  3702. case ErrorDetails.KEY_LOAD_TIMEOUT:
  3703. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  3704. case ErrorDetails.MANIFEST_LOAD_TIMEOUT:
  3705. return true;
  3706. }
  3707. return false;
  3708. }
  3709. function isKeyError(error) {
  3710. return error.details.startsWith("key");
  3711. }
  3712. function isUnusableKeyError(error) {
  3713. return isKeyError(error) && !!error.frag && !error.frag.decryptdata;
  3714. }
  3715. function getRetryConfig(loadPolicy, error) {
  3716. const isTimeout = isTimeoutError(error);
  3717. return loadPolicy.default[`${isTimeout ? "timeout" : "error"}Retry`];
  3718. }
  3719. function getRetryDelay(retryConfig, retryCount) {
  3720. const backoffFactor = retryConfig.backoff === "linear" ? 1 : Math.pow(2, retryCount);
  3721. return Math.min(backoffFactor * retryConfig.retryDelayMs, retryConfig.maxRetryDelayMs);
  3722. }
  3723. function getLoaderConfigWithoutReties(loderConfig) {
  3724. return _objectSpread2(_objectSpread2({}, loderConfig), {
  3725. errorRetry: null,
  3726. timeoutRetry: null
  3727. });
  3728. }
  3729. function shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse) {
  3730. if (!retryConfig) {
  3731. return false;
  3732. }
  3733. const httpStatus = loaderResponse == null ? void 0 : loaderResponse.code;
  3734. const retry = retryCount < retryConfig.maxNumRetry && (retryForHttpStatus(httpStatus) || !!isTimeout);
  3735. return retryConfig.shouldRetry ? retryConfig.shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse, retry) : retry;
  3736. }
  3737. function retryForHttpStatus(httpStatus) {
  3738. return offlineHttpStatus(httpStatus) || !!httpStatus && (httpStatus < 400 || httpStatus > 499);
  3739. }
  3740. function offlineHttpStatus(httpStatus) {
  3741. return httpStatus === 0 && navigator.onLine === false;
  3742. }
  3743. var NetworkErrorAction = {
  3744. DoNothing: 0,
  3745. SendEndCallback: 1,
  3746. SendAlternateToPenaltyBox: 2,
  3747. RemoveAlternatePermanently: 3,
  3748. InsertDiscontinuity: 4,
  3749. RetryRequest: 5
  3750. };
  3751. var ErrorActionFlags = {
  3752. None: 0,
  3753. MoveAllAlternatesMatchingHost: 1,
  3754. MoveAllAlternatesMatchingHDCP: 2,
  3755. MoveAllAlternatesMatchingKey: 4,
  3756. SwitchToSDR: 8
  3757. };
  3758. var ErrorController = class extends Logger {
  3759. constructor(hls) {
  3760. super("error-controller", hls.logger);
  3761. this.hls = void 0;
  3762. this.playlistError = 0;
  3763. this.hls = hls;
  3764. this.registerListeners();
  3765. }
  3766. registerListeners() {
  3767. const hls = this.hls;
  3768. hls.on(Events.ERROR, this.onError, this);
  3769. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3770. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  3771. }
  3772. unregisterListeners() {
  3773. const hls = this.hls;
  3774. if (!hls) {
  3775. return;
  3776. }
  3777. hls.off(Events.ERROR, this.onError, this);
  3778. hls.off(Events.ERROR, this.onErrorOut, this);
  3779. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3780. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  3781. }
  3782. destroy() {
  3783. this.unregisterListeners();
  3784. this.hls = null;
  3785. }
  3786. startLoad(startPosition) {
  3787. }
  3788. stopLoad() {
  3789. this.playlistError = 0;
  3790. }
  3791. getVariantLevelIndex(frag) {
  3792. if ((frag == null ? void 0 : frag.type) === PlaylistLevelType.MAIN) {
  3793. return frag.level;
  3794. }
  3795. return this.getVariantIndex();
  3796. }
  3797. getVariantIndex() {
  3798. var _hls$loadLevelObj;
  3799. const hls = this.hls;
  3800. const currentLevel = hls.currentLevel;
  3801. if ((_hls$loadLevelObj = hls.loadLevelObj) != null && _hls$loadLevelObj.details || currentLevel === -1) {
  3802. return hls.loadLevel;
  3803. }
  3804. return currentLevel;
  3805. }
  3806. variantHasKey(level, keyInError) {
  3807. if (level) {
  3808. var _level$details;
  3809. if ((_level$details = level.details) != null && _level$details.hasKey(keyInError)) {
  3810. return true;
  3811. }
  3812. const audioGroupsIds = level.audioGroups;
  3813. if (audioGroupsIds) {
  3814. const audioTracks = this.hls.allAudioTracks.filter((track) => audioGroupsIds.indexOf(track.groupId) >= 0);
  3815. return audioTracks.some((track) => {
  3816. var _track$details;
  3817. return (_track$details = track.details) == null ? void 0 : _track$details.hasKey(keyInError);
  3818. });
  3819. }
  3820. }
  3821. return false;
  3822. }
  3823. onManifestLoading() {
  3824. this.playlistError = 0;
  3825. }
  3826. onLevelUpdated() {
  3827. this.playlistError = 0;
  3828. }
  3829. onError(event, data) {
  3830. var _data$frag;
  3831. if (data.fatal) {
  3832. return;
  3833. }
  3834. const hls = this.hls;
  3835. const context = data.context;
  3836. switch (data.details) {
  3837. case ErrorDetails.FRAG_LOAD_ERROR:
  3838. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  3839. case ErrorDetails.KEY_LOAD_ERROR:
  3840. case ErrorDetails.KEY_LOAD_TIMEOUT:
  3841. data.errorAction = this.getFragRetryOrSwitchAction(data);
  3842. return;
  3843. case ErrorDetails.FRAG_PARSING_ERROR:
  3844. if ((_data$frag = data.frag) != null && _data$frag.gap) {
  3845. data.errorAction = createDoNothingErrorAction();
  3846. return;
  3847. }
  3848. case ErrorDetails.FRAG_GAP:
  3849. case ErrorDetails.FRAG_DECRYPT_ERROR: {
  3850. data.errorAction = this.getFragRetryOrSwitchAction(data);
  3851. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  3852. return;
  3853. }
  3854. case ErrorDetails.LEVEL_EMPTY_ERROR:
  3855. case ErrorDetails.LEVEL_PARSING_ERROR:
  3856. {
  3857. var _data$context;
  3858. const levelIndex = data.parent === PlaylistLevelType.MAIN ? data.level : hls.loadLevel;
  3859. if (data.details === ErrorDetails.LEVEL_EMPTY_ERROR && !!((_data$context = data.context) != null && (_data$context = _data$context.levelDetails) != null && _data$context.live)) {
  3860. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, levelIndex);
  3861. } else {
  3862. data.levelRetry = false;
  3863. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  3864. }
  3865. }
  3866. return;
  3867. case ErrorDetails.LEVEL_LOAD_ERROR:
  3868. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  3869. if (typeof (context == null ? void 0 : context.level) === "number") {
  3870. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, context.level);
  3871. }
  3872. return;
  3873. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  3874. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  3875. case ErrorDetails.SUBTITLE_LOAD_ERROR:
  3876. case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:
  3877. if (context) {
  3878. const level = hls.loadLevelObj;
  3879. if (level && (context.type === PlaylistContextType.AUDIO_TRACK && level.hasAudioGroup(context.groupId) || context.type === PlaylistContextType.SUBTITLE_TRACK && level.hasSubtitleGroup(context.groupId))) {
  3880. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, hls.loadLevel);
  3881. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  3882. data.errorAction.flags = ErrorActionFlags.MoveAllAlternatesMatchingHost;
  3883. return;
  3884. }
  3885. }
  3886. return;
  3887. case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:
  3888. {
  3889. data.errorAction = {
  3890. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  3891. flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP
  3892. };
  3893. }
  3894. return;
  3895. case ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED:
  3896. case ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR:
  3897. case ErrorDetails.KEY_SYSTEM_NO_SESSION:
  3898. {
  3899. data.errorAction = {
  3900. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  3901. flags: ErrorActionFlags.MoveAllAlternatesMatchingKey
  3902. };
  3903. }
  3904. return;
  3905. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  3906. case ErrorDetails.REMUX_ALLOC_ERROR:
  3907. case ErrorDetails.BUFFER_APPEND_ERROR:
  3908. if (!data.errorAction) {
  3909. var _data$level;
  3910. data.errorAction = this.getLevelSwitchAction(data, (_data$level = data.level) != null ? _data$level : hls.loadLevel);
  3911. }
  3912. return;
  3913. case ErrorDetails.INTERNAL_EXCEPTION:
  3914. case ErrorDetails.BUFFER_APPENDING_ERROR:
  3915. case ErrorDetails.BUFFER_FULL_ERROR:
  3916. case ErrorDetails.LEVEL_SWITCH_ERROR:
  3917. case ErrorDetails.BUFFER_STALLED_ERROR:
  3918. case ErrorDetails.BUFFER_SEEK_OVER_HOLE:
  3919. case ErrorDetails.BUFFER_NUDGE_ON_STALL:
  3920. data.errorAction = createDoNothingErrorAction();
  3921. return;
  3922. }
  3923. if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {
  3924. data.levelRetry = false;
  3925. data.errorAction = createDoNothingErrorAction();
  3926. }
  3927. }
  3928. getPlaylistRetryOrSwitchAction(data, levelIndex) {
  3929. const hls = this.hls;
  3930. const retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);
  3931. const retryCount = this.playlistError++;
  3932. const retry = shouldRetry(retryConfig, retryCount, isTimeoutError(data), data.response);
  3933. if (retry) {
  3934. return {
  3935. action: NetworkErrorAction.RetryRequest,
  3936. flags: ErrorActionFlags.None,
  3937. retryConfig,
  3938. retryCount
  3939. };
  3940. }
  3941. const errorAction = this.getLevelSwitchAction(data, levelIndex);
  3942. if (retryConfig) {
  3943. errorAction.retryConfig = retryConfig;
  3944. errorAction.retryCount = retryCount;
  3945. }
  3946. return errorAction;
  3947. }
  3948. getFragRetryOrSwitchAction(data) {
  3949. const hls = this.hls;
  3950. const variantLevelIndex = this.getVariantLevelIndex(data.frag);
  3951. const level = hls.levels[variantLevelIndex];
  3952. const {
  3953. fragLoadPolicy,
  3954. keyLoadPolicy
  3955. } = hls.config;
  3956. const retryConfig = getRetryConfig(isKeyError(data) ? keyLoadPolicy : fragLoadPolicy, data);
  3957. const fragmentErrors = hls.levels.reduce((acc, level2) => acc + level2.fragmentError, 0);
  3958. if (level) {
  3959. if (data.details !== ErrorDetails.FRAG_GAP) {
  3960. level.fragmentError++;
  3961. }
  3962. if (!isUnusableKeyError(data)) {
  3963. const retry = shouldRetry(retryConfig, fragmentErrors, isTimeoutError(data), data.response);
  3964. if (retry) {
  3965. return {
  3966. action: NetworkErrorAction.RetryRequest,
  3967. flags: ErrorActionFlags.None,
  3968. retryConfig,
  3969. retryCount: fragmentErrors
  3970. };
  3971. }
  3972. }
  3973. }
  3974. const errorAction = this.getLevelSwitchAction(data, variantLevelIndex);
  3975. if (retryConfig) {
  3976. errorAction.retryConfig = retryConfig;
  3977. errorAction.retryCount = fragmentErrors;
  3978. }
  3979. return errorAction;
  3980. }
  3981. getLevelSwitchAction(data, levelIndex) {
  3982. const hls = this.hls;
  3983. if (levelIndex === null || levelIndex === void 0) {
  3984. levelIndex = hls.loadLevel;
  3985. }
  3986. const level = this.hls.levels[levelIndex];
  3987. if (level) {
  3988. var _data$frag2, _data$context2;
  3989. const errorDetails = data.details;
  3990. level.loadError++;
  3991. if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {
  3992. level.fragmentError++;
  3993. }
  3994. let nextLevel = -1;
  3995. const {
  3996. levels,
  3997. loadLevel,
  3998. minAutoLevel,
  3999. maxAutoLevel
  4000. } = hls;
  4001. if (!hls.autoLevelEnabled && !hls.config.preserveManualLevelOnError) {
  4002. hls.loadLevel = -1;
  4003. }
  4004. const fragErrorType = (_data$frag2 = data.frag) == null ? void 0 : _data$frag2.type;
  4005. const isAudioCodecError = fragErrorType === PlaylistLevelType.AUDIO && errorDetails === ErrorDetails.FRAG_PARSING_ERROR || data.sourceBufferName === "audio" && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  4006. const findAudioCodecAlternate = isAudioCodecError && levels.some(({
  4007. audioCodec
  4008. }) => level.audioCodec !== audioCodec);
  4009. const isVideoCodecError = data.sourceBufferName === "video" && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  4010. const findVideoCodecAlternate = isVideoCodecError && levels.some(({
  4011. codecSet,
  4012. audioCodec
  4013. }) => level.codecSet !== codecSet && level.audioCodec === audioCodec);
  4014. const {
  4015. type: playlistErrorType,
  4016. groupId: playlistErrorGroupId
  4017. } = (_data$context2 = data.context) != null ? _data$context2 : {};
  4018. for (let i = levels.length; i--; ) {
  4019. const candidate = (i + loadLevel) % levels.length;
  4020. if (candidate !== loadLevel && candidate >= minAutoLevel && candidate <= maxAutoLevel && levels[candidate].loadError === 0) {
  4021. var _level$audioGroups, _level$subtitleGroups;
  4022. const levelCandidate = levels[candidate];
  4023. if (errorDetails === ErrorDetails.FRAG_GAP && fragErrorType === PlaylistLevelType.MAIN && data.frag) {
  4024. const levelDetails = levels[candidate].details;
  4025. if (levelDetails) {
  4026. const fragCandidate = findFragmentByPTS(data.frag, levelDetails.fragments, data.frag.start);
  4027. if (fragCandidate != null && fragCandidate.gap) {
  4028. continue;
  4029. }
  4030. }
  4031. } else if (playlistErrorType === PlaylistContextType.AUDIO_TRACK && levelCandidate.hasAudioGroup(playlistErrorGroupId) || playlistErrorType === PlaylistContextType.SUBTITLE_TRACK && levelCandidate.hasSubtitleGroup(playlistErrorGroupId)) {
  4032. continue;
  4033. } 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 || findVideoCodecAlternate && level.codecSet === levelCandidate.codecSet || !findAudioCodecAlternate && level.codecSet !== levelCandidate.codecSet) {
  4034. continue;
  4035. }
  4036. nextLevel = candidate;
  4037. break;
  4038. }
  4039. }
  4040. if (nextLevel > -1 && hls.loadLevel !== nextLevel) {
  4041. data.levelRetry = true;
  4042. this.playlistError = 0;
  4043. return {
  4044. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  4045. flags: ErrorActionFlags.None,
  4046. nextAutoLevel: nextLevel
  4047. };
  4048. }
  4049. }
  4050. return {
  4051. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  4052. flags: ErrorActionFlags.MoveAllAlternatesMatchingHost
  4053. };
  4054. }
  4055. onErrorOut(event, data) {
  4056. var _data$errorAction;
  4057. switch ((_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.action) {
  4058. case NetworkErrorAction.DoNothing:
  4059. break;
  4060. case NetworkErrorAction.SendAlternateToPenaltyBox:
  4061. this.sendAlternateToPenaltyBox(data);
  4062. if (!data.errorAction.resolved && data.details !== ErrorDetails.FRAG_GAP) {
  4063. data.fatal = true;
  4064. } else if (/MediaSource readyState: ended/.test(data.error.message)) {
  4065. this.warn(`MediaSource ended after "${data.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`);
  4066. this.hls.recoverMediaError();
  4067. }
  4068. break;
  4069. case NetworkErrorAction.RetryRequest:
  4070. break;
  4071. }
  4072. if (data.fatal) {
  4073. this.hls.stopLoad();
  4074. return;
  4075. }
  4076. }
  4077. sendAlternateToPenaltyBox(data) {
  4078. const hls = this.hls;
  4079. const errorAction = data.errorAction;
  4080. if (!errorAction) {
  4081. return;
  4082. }
  4083. const {
  4084. flags
  4085. } = errorAction;
  4086. const nextAutoLevel = errorAction.nextAutoLevel;
  4087. switch (flags) {
  4088. case ErrorActionFlags.None:
  4089. this.switchLevel(data, nextAutoLevel);
  4090. break;
  4091. case ErrorActionFlags.MoveAllAlternatesMatchingHDCP: {
  4092. const levelIndex = this.getVariantLevelIndex(data.frag);
  4093. const level = hls.levels[levelIndex];
  4094. const restrictedHdcpLevel = level == null ? void 0 : level.attrs["HDCP-LEVEL"];
  4095. errorAction.hdcpLevel = restrictedHdcpLevel;
  4096. if (restrictedHdcpLevel === "NONE") {
  4097. this.warn(`HDCP policy resticted output with HDCP-LEVEL=NONE`);
  4098. } else if (restrictedHdcpLevel) {
  4099. hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(restrictedHdcpLevel) - 1];
  4100. errorAction.resolved = true;
  4101. this.warn(`Restricting playback to HDCP-LEVEL of "${hls.maxHdcpLevel}" or lower`);
  4102. break;
  4103. }
  4104. }
  4105. case ErrorActionFlags.MoveAllAlternatesMatchingKey: {
  4106. const levelKey = data.decryptdata;
  4107. if (levelKey) {
  4108. const levels = this.hls.levels;
  4109. const levelCountWithError = levels.length;
  4110. for (let i = levelCountWithError; i--; ) {
  4111. if (this.variantHasKey(levels[i], levelKey)) {
  4112. var _levels$i$audioGroups, _data$frag3;
  4113. this.log(`Banned key found in level ${i} (${levels[i].bitrate}bps) or audio group "${(_levels$i$audioGroups = levels[i].audioGroups) == null ? void 0 : _levels$i$audioGroups.join(",")}" (${(_data$frag3 = data.frag) == null ? void 0 : _data$frag3.type} fragment) ${arrayToHex(levelKey.keyId || [])}`);
  4114. levels[i].fragmentError++;
  4115. levels[i].loadError++;
  4116. this.log(`Removing level ${i} with key error (${data.error})`);
  4117. this.hls.removeLevel(i);
  4118. }
  4119. }
  4120. const frag = data.frag;
  4121. if (this.hls.levels.length < levelCountWithError) {
  4122. errorAction.resolved = true;
  4123. } else if (frag && frag.type !== PlaylistLevelType.MAIN) {
  4124. const fragLevelKey = frag.decryptdata;
  4125. if (fragLevelKey && !levelKey.matches(fragLevelKey)) {
  4126. errorAction.resolved = true;
  4127. }
  4128. }
  4129. }
  4130. break;
  4131. }
  4132. }
  4133. if (!errorAction.resolved) {
  4134. this.switchLevel(data, nextAutoLevel);
  4135. }
  4136. }
  4137. switchLevel(data, levelIndex) {
  4138. if (levelIndex !== void 0 && data.errorAction) {
  4139. this.warn(`switching to level ${levelIndex} after ${data.details}`);
  4140. this.hls.nextAutoLevel = levelIndex;
  4141. data.errorAction.resolved = true;
  4142. this.hls.nextLoadLevel = this.hls.nextAutoLevel;
  4143. if (data.details === ErrorDetails.BUFFER_ADD_CODEC_ERROR && data.mimeType && data.sourceBufferName !== "audiovideo") {
  4144. const codec = getCodecsForMimeType(data.mimeType);
  4145. const levels = this.hls.levels;
  4146. for (let i = levels.length; i--; ) {
  4147. if (levels[i][`${data.sourceBufferName}Codec`] === codec) {
  4148. this.log(`Removing level ${i} for ${data.details} ("${codec}" not supported)`);
  4149. this.hls.removeLevel(i);
  4150. }
  4151. }
  4152. }
  4153. }
  4154. }
  4155. };
  4156. function createDoNothingErrorAction(resolved) {
  4157. const errorAction = {
  4158. action: NetworkErrorAction.DoNothing,
  4159. flags: ErrorActionFlags.None
  4160. };
  4161. if (resolved) {
  4162. errorAction.resolved = true;
  4163. }
  4164. return errorAction;
  4165. }
  4166. var FragmentState = {
  4167. NOT_LOADED: "NOT_LOADED",
  4168. APPENDING: "APPENDING",
  4169. PARTIAL: "PARTIAL",
  4170. OK: "OK"
  4171. };
  4172. var FragmentTracker = class {
  4173. constructor(hls) {
  4174. this.activePartLists = /* @__PURE__ */ Object.create(null);
  4175. this.endListFragments = /* @__PURE__ */ Object.create(null);
  4176. this.fragments = /* @__PURE__ */ Object.create(null);
  4177. this.timeRanges = /* @__PURE__ */ Object.create(null);
  4178. this.bufferPadding = 0.2;
  4179. this.hls = void 0;
  4180. this.hasGaps = false;
  4181. this.hls = hls;
  4182. this._registerListeners();
  4183. }
  4184. _registerListeners() {
  4185. const {
  4186. hls
  4187. } = this;
  4188. if (hls) {
  4189. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4190. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  4191. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  4192. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  4193. }
  4194. }
  4195. _unregisterListeners() {
  4196. const {
  4197. hls
  4198. } = this;
  4199. if (hls) {
  4200. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4201. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  4202. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  4203. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  4204. }
  4205. }
  4206. destroy() {
  4207. this._unregisterListeners();
  4208. this.hls = // @ts-ignore
  4209. this.fragments = // @ts-ignore
  4210. this.activePartLists = // @ts-ignore
  4211. this.endListFragments = this.timeRanges = null;
  4212. }
  4213. /**
  4214. * Return a Fragment or Part with an appended range that matches the position and levelType
  4215. * Otherwise, return null
  4216. */
  4217. getAppendedFrag(position, levelType) {
  4218. const activeParts = this.activePartLists[levelType];
  4219. if (activeParts) {
  4220. for (let i = activeParts.length; i--; ) {
  4221. const activePart = activeParts[i];
  4222. if (!activePart) {
  4223. break;
  4224. }
  4225. if (activePart.start <= position && position <= activePart.end && activePart.loaded) {
  4226. return activePart;
  4227. }
  4228. }
  4229. }
  4230. return this.getBufferedFrag(position, levelType);
  4231. }
  4232. /**
  4233. * Return a buffered Fragment that matches the position and levelType.
  4234. * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
  4235. * If not found any Fragment, return null
  4236. */
  4237. getBufferedFrag(position, levelType) {
  4238. return this.getFragAtPos(position, levelType, true);
  4239. }
  4240. getFragAtPos(position, levelType, buffered) {
  4241. const {
  4242. fragments
  4243. } = this;
  4244. const keys = Object.keys(fragments);
  4245. for (let i = keys.length; i--; ) {
  4246. const fragmentEntity = fragments[keys[i]];
  4247. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === levelType && (!buffered || fragmentEntity.buffered)) {
  4248. const frag = fragmentEntity.body;
  4249. if (frag.start <= position && position <= frag.end) {
  4250. return frag;
  4251. }
  4252. }
  4253. }
  4254. return null;
  4255. }
  4256. /**
  4257. * Partial fragments effected by coded frame eviction will be removed
  4258. * The browser will unload parts of the buffer to free up memory for new buffer data
  4259. * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)
  4260. */
  4261. detectEvictedFragments(elementaryStream, timeRange, playlistType, appendedPart, removeAppending) {
  4262. if (this.timeRanges) {
  4263. this.timeRanges[elementaryStream] = timeRange;
  4264. }
  4265. const appendedPartSn = (appendedPart == null ? void 0 : appendedPart.fragment.sn) || -1;
  4266. Object.keys(this.fragments).forEach((key) => {
  4267. const fragmentEntity = this.fragments[key];
  4268. if (!fragmentEntity) {
  4269. return;
  4270. }
  4271. if (appendedPartSn >= fragmentEntity.body.sn) {
  4272. return;
  4273. }
  4274. if (!fragmentEntity.buffered && (!fragmentEntity.loaded || removeAppending)) {
  4275. if (fragmentEntity.body.type === playlistType) {
  4276. this.removeFragment(fragmentEntity.body);
  4277. }
  4278. return;
  4279. }
  4280. const esData = fragmentEntity.range[elementaryStream];
  4281. if (!esData) {
  4282. return;
  4283. }
  4284. if (esData.time.length === 0) {
  4285. this.removeFragment(fragmentEntity.body);
  4286. return;
  4287. }
  4288. esData.time.some((time) => {
  4289. const isNotBuffered = !this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
  4290. if (isNotBuffered) {
  4291. this.removeFragment(fragmentEntity.body);
  4292. }
  4293. return isNotBuffered;
  4294. });
  4295. });
  4296. }
  4297. /**
  4298. * Checks if the fragment passed in is loaded in the buffer properly
  4299. * Partially loaded fragments will be registered as a partial fragment
  4300. */
  4301. detectPartialFragments(data) {
  4302. const timeRanges = this.timeRanges;
  4303. if (!timeRanges || data.frag.sn === "initSegment") {
  4304. return;
  4305. }
  4306. const frag = data.frag;
  4307. const fragKey = getFragmentKey(frag);
  4308. const fragmentEntity = this.fragments[fragKey];
  4309. if (!fragmentEntity || fragmentEntity.buffered && frag.gap) {
  4310. return;
  4311. }
  4312. const isFragHint = !frag.relurl;
  4313. Object.keys(timeRanges).forEach((elementaryStream) => {
  4314. const streamInfo = frag.elementaryStreams[elementaryStream];
  4315. if (!streamInfo) {
  4316. return;
  4317. }
  4318. const timeRange = timeRanges[elementaryStream];
  4319. const partial = isFragHint || streamInfo.partial === true;
  4320. fragmentEntity.range[elementaryStream] = this.getBufferedTimes(frag, data.part, partial, timeRange);
  4321. });
  4322. fragmentEntity.loaded = null;
  4323. if (Object.keys(fragmentEntity.range).length) {
  4324. fragmentEntity.buffered = true;
  4325. const endList = fragmentEntity.body.endList = frag.endList || fragmentEntity.body.endList;
  4326. if (endList) {
  4327. this.endListFragments[fragmentEntity.body.type] = fragmentEntity;
  4328. }
  4329. if (!isPartial(fragmentEntity)) {
  4330. this.removeParts(frag.sn - 1, frag.type);
  4331. }
  4332. } else {
  4333. this.removeFragment(fragmentEntity.body);
  4334. }
  4335. }
  4336. removeParts(snToKeep, levelType) {
  4337. const activeParts = this.activePartLists[levelType];
  4338. if (!activeParts) {
  4339. return;
  4340. }
  4341. this.activePartLists[levelType] = filterParts(activeParts, (part) => part.fragment.sn >= snToKeep);
  4342. }
  4343. fragBuffered(frag, force) {
  4344. const fragKey = getFragmentKey(frag);
  4345. let fragmentEntity = this.fragments[fragKey];
  4346. if (!fragmentEntity && force) {
  4347. fragmentEntity = this.fragments[fragKey] = {
  4348. body: frag,
  4349. appendedPTS: null,
  4350. loaded: null,
  4351. buffered: false,
  4352. range: /* @__PURE__ */ Object.create(null)
  4353. };
  4354. if (frag.gap) {
  4355. this.hasGaps = true;
  4356. }
  4357. }
  4358. if (fragmentEntity) {
  4359. fragmentEntity.loaded = null;
  4360. fragmentEntity.buffered = true;
  4361. }
  4362. }
  4363. getBufferedTimes(fragment, part, partial, timeRange) {
  4364. const buffered = {
  4365. time: [],
  4366. partial
  4367. };
  4368. const startPTS = fragment.start;
  4369. const endPTS = fragment.end;
  4370. const minEndPTS = fragment.minEndPTS || endPTS;
  4371. const maxStartPTS = fragment.maxStartPTS || startPTS;
  4372. for (let i = 0; i < timeRange.length; i++) {
  4373. const startTime = timeRange.start(i) - this.bufferPadding;
  4374. const endTime = timeRange.end(i) + this.bufferPadding;
  4375. if (maxStartPTS >= startTime && minEndPTS <= endTime) {
  4376. buffered.time.push({
  4377. startPTS: Math.max(startPTS, timeRange.start(i)),
  4378. endPTS: Math.min(endPTS, timeRange.end(i))
  4379. });
  4380. break;
  4381. } else if (startPTS < endTime && endPTS > startTime) {
  4382. const start = Math.max(startPTS, timeRange.start(i));
  4383. const end = Math.min(endPTS, timeRange.end(i));
  4384. if (end > start) {
  4385. buffered.partial = true;
  4386. buffered.time.push({
  4387. startPTS: start,
  4388. endPTS: end
  4389. });
  4390. }
  4391. } else if (endPTS <= startTime) {
  4392. break;
  4393. }
  4394. }
  4395. return buffered;
  4396. }
  4397. /**
  4398. * Gets the partial fragment for a certain time
  4399. */
  4400. getPartialFragment(time) {
  4401. let bestFragment = null;
  4402. let timePadding;
  4403. let startTime;
  4404. let endTime;
  4405. let bestOverlap = 0;
  4406. const {
  4407. bufferPadding,
  4408. fragments
  4409. } = this;
  4410. Object.keys(fragments).forEach((key) => {
  4411. const fragmentEntity = fragments[key];
  4412. if (!fragmentEntity) {
  4413. return;
  4414. }
  4415. if (isPartial(fragmentEntity)) {
  4416. startTime = fragmentEntity.body.start - bufferPadding;
  4417. endTime = fragmentEntity.body.end + bufferPadding;
  4418. if (time >= startTime && time <= endTime) {
  4419. timePadding = Math.min(time - startTime, endTime - time);
  4420. if (bestOverlap <= timePadding) {
  4421. bestFragment = fragmentEntity.body;
  4422. bestOverlap = timePadding;
  4423. }
  4424. }
  4425. }
  4426. });
  4427. return bestFragment;
  4428. }
  4429. isEndListAppended(type) {
  4430. const lastFragmentEntity = this.endListFragments[type];
  4431. return lastFragmentEntity !== void 0 && (lastFragmentEntity.buffered || isPartial(lastFragmentEntity));
  4432. }
  4433. getState(fragment) {
  4434. const fragKey = getFragmentKey(fragment);
  4435. const fragmentEntity = this.fragments[fragKey];
  4436. if (fragmentEntity) {
  4437. if (!fragmentEntity.buffered) {
  4438. return FragmentState.APPENDING;
  4439. } else if (isPartial(fragmentEntity)) {
  4440. return FragmentState.PARTIAL;
  4441. } else {
  4442. return FragmentState.OK;
  4443. }
  4444. }
  4445. return FragmentState.NOT_LOADED;
  4446. }
  4447. isTimeBuffered(startPTS, endPTS, timeRange) {
  4448. let startTime;
  4449. let endTime;
  4450. for (let i = 0; i < timeRange.length; i++) {
  4451. startTime = timeRange.start(i) - this.bufferPadding;
  4452. endTime = timeRange.end(i) + this.bufferPadding;
  4453. if (startPTS >= startTime && endPTS <= endTime) {
  4454. return true;
  4455. }
  4456. if (endPTS <= startTime) {
  4457. return false;
  4458. }
  4459. }
  4460. return false;
  4461. }
  4462. onManifestLoading() {
  4463. this.removeAllFragments();
  4464. }
  4465. onFragLoaded(event, data) {
  4466. if (data.frag.sn === "initSegment" || data.frag.bitrateTest) {
  4467. return;
  4468. }
  4469. const frag = data.frag;
  4470. const loaded = data.part ? null : data;
  4471. const fragKey = getFragmentKey(frag);
  4472. this.fragments[fragKey] = {
  4473. body: frag,
  4474. appendedPTS: null,
  4475. loaded,
  4476. buffered: false,
  4477. range: /* @__PURE__ */ Object.create(null)
  4478. };
  4479. }
  4480. onBufferAppended(event, data) {
  4481. const {
  4482. frag,
  4483. part,
  4484. timeRanges,
  4485. type
  4486. } = data;
  4487. if (frag.sn === "initSegment") {
  4488. return;
  4489. }
  4490. const playlistType = frag.type;
  4491. if (part) {
  4492. let activeParts = this.activePartLists[playlistType];
  4493. if (!activeParts) {
  4494. this.activePartLists[playlistType] = activeParts = [];
  4495. }
  4496. activeParts.push(part);
  4497. }
  4498. this.timeRanges = timeRanges;
  4499. const timeRange = timeRanges[type];
  4500. this.detectEvictedFragments(type, timeRange, playlistType, part);
  4501. }
  4502. onFragBuffered(event, data) {
  4503. this.detectPartialFragments(data);
  4504. }
  4505. hasFragment(fragment) {
  4506. const fragKey = getFragmentKey(fragment);
  4507. return !!this.fragments[fragKey];
  4508. }
  4509. hasFragments(type) {
  4510. const {
  4511. fragments
  4512. } = this;
  4513. const keys = Object.keys(fragments);
  4514. if (!type) {
  4515. return keys.length > 0;
  4516. }
  4517. for (let i = keys.length; i--; ) {
  4518. const fragmentEntity = fragments[keys[i]];
  4519. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === type) {
  4520. return true;
  4521. }
  4522. }
  4523. return false;
  4524. }
  4525. hasParts(type) {
  4526. var _this$activePartLists;
  4527. return !!((_this$activePartLists = this.activePartLists[type]) != null && _this$activePartLists.length);
  4528. }
  4529. removeFragmentsInRange(start, end, playlistType, withGapOnly, unbufferedOnly) {
  4530. if (withGapOnly && !this.hasGaps) {
  4531. return;
  4532. }
  4533. Object.keys(this.fragments).forEach((key) => {
  4534. const fragmentEntity = this.fragments[key];
  4535. if (!fragmentEntity) {
  4536. return;
  4537. }
  4538. const frag = fragmentEntity.body;
  4539. if (frag.type !== playlistType || withGapOnly && !frag.gap) {
  4540. return;
  4541. }
  4542. if (frag.start < end && frag.end > start && (fragmentEntity.buffered || unbufferedOnly)) {
  4543. this.removeFragment(frag);
  4544. }
  4545. });
  4546. }
  4547. removeFragment(fragment) {
  4548. const fragKey = getFragmentKey(fragment);
  4549. fragment.clearElementaryStreamInfo();
  4550. const activeParts = this.activePartLists[fragment.type];
  4551. if (activeParts) {
  4552. const snToRemove = fragment.sn;
  4553. this.activePartLists[fragment.type] = filterParts(activeParts, (part) => part.fragment.sn !== snToRemove);
  4554. }
  4555. delete this.fragments[fragKey];
  4556. if (fragment.endList) {
  4557. delete this.endListFragments[fragment.type];
  4558. }
  4559. }
  4560. removeAllFragments() {
  4561. var _this$hls;
  4562. this.fragments = /* @__PURE__ */ Object.create(null);
  4563. this.endListFragments = /* @__PURE__ */ Object.create(null);
  4564. this.activePartLists = /* @__PURE__ */ Object.create(null);
  4565. this.hasGaps = false;
  4566. const partlist = (_this$hls = this.hls) == null || (_this$hls = _this$hls.latestLevelDetails) == null ? void 0 : _this$hls.partList;
  4567. if (partlist) {
  4568. partlist.forEach((part) => part.clearElementaryStreamInfo());
  4569. }
  4570. }
  4571. };
  4572. function isPartial(fragmentEntity) {
  4573. var _fragmentEntity$range, _fragmentEntity$range2, _fragmentEntity$range3;
  4574. return fragmentEntity.buffered && !!(fragmentEntity.body.gap || (_fragmentEntity$range = fragmentEntity.range.video) != null && _fragmentEntity$range.partial || (_fragmentEntity$range2 = fragmentEntity.range.audio) != null && _fragmentEntity$range2.partial || (_fragmentEntity$range3 = fragmentEntity.range.audiovideo) != null && _fragmentEntity$range3.partial);
  4575. }
  4576. function getFragmentKey(fragment) {
  4577. return `${fragment.type}_${fragment.level}_${fragment.sn}`;
  4578. }
  4579. function filterParts(partList, predicate) {
  4580. return partList.filter((part) => {
  4581. const keep = predicate(part);
  4582. if (!keep) {
  4583. part.clearElementaryStreamInfo();
  4584. }
  4585. return keep;
  4586. });
  4587. }
  4588. var DecrypterAesMode = {
  4589. cbc: 0,
  4590. ctr: 1
  4591. };
  4592. var AESCrypto = class {
  4593. constructor(subtle, iv, aesMode) {
  4594. this.subtle = void 0;
  4595. this.aesIV = void 0;
  4596. this.aesMode = void 0;
  4597. this.subtle = subtle;
  4598. this.aesIV = iv;
  4599. this.aesMode = aesMode;
  4600. }
  4601. decrypt(data, key) {
  4602. switch (this.aesMode) {
  4603. case DecrypterAesMode.cbc:
  4604. return this.subtle.decrypt({
  4605. name: "AES-CBC",
  4606. iv: this.aesIV
  4607. }, key, data);
  4608. case DecrypterAesMode.ctr:
  4609. return this.subtle.decrypt(
  4610. {
  4611. name: "AES-CTR",
  4612. counter: this.aesIV,
  4613. length: 64
  4614. },
  4615. //64 : NIST SP800-38A standard suggests that the counter should occupy half of the counter block
  4616. key,
  4617. data
  4618. );
  4619. default:
  4620. throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`);
  4621. }
  4622. }
  4623. };
  4624. function removePadding(array) {
  4625. const outputBytes = array.byteLength;
  4626. const paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
  4627. if (paddingBytes) {
  4628. return array.slice(0, outputBytes - paddingBytes);
  4629. }
  4630. return array;
  4631. }
  4632. var AESDecryptor = class {
  4633. constructor() {
  4634. this.rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54];
  4635. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  4636. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  4637. this.sBox = new Uint32Array(256);
  4638. this.invSBox = new Uint32Array(256);
  4639. this.key = new Uint32Array(0);
  4640. this.ksRows = 0;
  4641. this.keySize = 0;
  4642. this.keySchedule = void 0;
  4643. this.invKeySchedule = void 0;
  4644. this.initTable();
  4645. }
  4646. // Using view.getUint32() also swaps the byte order.
  4647. uint8ArrayToUint32Array_(arrayBuffer) {
  4648. const view2 = new DataView(arrayBuffer);
  4649. const newArray = new Uint32Array(4);
  4650. for (let i = 0; i < 4; i++) {
  4651. newArray[i] = view2.getUint32(i * 4);
  4652. }
  4653. return newArray;
  4654. }
  4655. initTable() {
  4656. const sBox = this.sBox;
  4657. const invSBox = this.invSBox;
  4658. const subMix = this.subMix;
  4659. const subMix0 = subMix[0];
  4660. const subMix1 = subMix[1];
  4661. const subMix2 = subMix[2];
  4662. const subMix3 = subMix[3];
  4663. const invSubMix = this.invSubMix;
  4664. const invSubMix0 = invSubMix[0];
  4665. const invSubMix1 = invSubMix[1];
  4666. const invSubMix2 = invSubMix[2];
  4667. const invSubMix3 = invSubMix[3];
  4668. const d = new Uint32Array(256);
  4669. let x = 0;
  4670. let xi = 0;
  4671. let i = 0;
  4672. for (i = 0; i < 256; i++) {
  4673. if (i < 128) {
  4674. d[i] = i << 1;
  4675. } else {
  4676. d[i] = i << 1 ^ 283;
  4677. }
  4678. }
  4679. for (i = 0; i < 256; i++) {
  4680. let sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  4681. sx = sx >>> 8 ^ sx & 255 ^ 99;
  4682. sBox[x] = sx;
  4683. invSBox[sx] = x;
  4684. const x2 = d[x];
  4685. const x4 = d[x2];
  4686. const x8 = d[x4];
  4687. let t = d[sx] * 257 ^ sx * 16843008;
  4688. subMix0[x] = t << 24 | t >>> 8;
  4689. subMix1[x] = t << 16 | t >>> 16;
  4690. subMix2[x] = t << 8 | t >>> 24;
  4691. subMix3[x] = t;
  4692. t = x8 * 16843009 ^ x4 * 65537 ^ x2 * 257 ^ x * 16843008;
  4693. invSubMix0[sx] = t << 24 | t >>> 8;
  4694. invSubMix1[sx] = t << 16 | t >>> 16;
  4695. invSubMix2[sx] = t << 8 | t >>> 24;
  4696. invSubMix3[sx] = t;
  4697. if (!x) {
  4698. x = xi = 1;
  4699. } else {
  4700. x = x2 ^ d[d[d[x8 ^ x2]]];
  4701. xi ^= d[d[xi]];
  4702. }
  4703. }
  4704. }
  4705. expandKey(keyBuffer) {
  4706. const key = this.uint8ArrayToUint32Array_(keyBuffer);
  4707. let sameKey = true;
  4708. let offset = 0;
  4709. while (offset < key.length && sameKey) {
  4710. sameKey = key[offset] === this.key[offset];
  4711. offset++;
  4712. }
  4713. if (sameKey) {
  4714. return;
  4715. }
  4716. this.key = key;
  4717. const keySize = this.keySize = key.length;
  4718. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  4719. throw new Error("Invalid aes key size=" + keySize);
  4720. }
  4721. const ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  4722. let ksRow;
  4723. let invKsRow;
  4724. const keySchedule = this.keySchedule = new Uint32Array(ksRows);
  4725. const invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  4726. const sbox = this.sBox;
  4727. const rcon = this.rcon;
  4728. const invSubMix = this.invSubMix;
  4729. const invSubMix0 = invSubMix[0];
  4730. const invSubMix1 = invSubMix[1];
  4731. const invSubMix2 = invSubMix[2];
  4732. const invSubMix3 = invSubMix[3];
  4733. let prev;
  4734. let t;
  4735. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  4736. if (ksRow < keySize) {
  4737. prev = keySchedule[ksRow] = key[ksRow];
  4738. continue;
  4739. }
  4740. t = prev;
  4741. if (ksRow % keySize === 0) {
  4742. t = t << 8 | t >>> 24;
  4743. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 255] << 16 | sbox[t >>> 8 & 255] << 8 | sbox[t & 255];
  4744. t ^= rcon[ksRow / keySize | 0] << 24;
  4745. } else if (keySize > 6 && ksRow % keySize === 4) {
  4746. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 255] << 16 | sbox[t >>> 8 & 255] << 8 | sbox[t & 255];
  4747. }
  4748. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  4749. }
  4750. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  4751. ksRow = ksRows - invKsRow;
  4752. if (invKsRow & 3) {
  4753. t = keySchedule[ksRow];
  4754. } else {
  4755. t = keySchedule[ksRow - 4];
  4756. }
  4757. if (invKsRow < 4 || ksRow <= 4) {
  4758. invKeySchedule[invKsRow] = t;
  4759. } else {
  4760. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 255]] ^ invSubMix2[sbox[t >>> 8 & 255]] ^ invSubMix3[sbox[t & 255]];
  4761. }
  4762. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  4763. }
  4764. }
  4765. // Adding this as a method greatly improves performance.
  4766. networkToHostOrderSwap(word) {
  4767. return word << 24 | (word & 65280) << 8 | (word & 16711680) >> 8 | word >>> 24;
  4768. }
  4769. decrypt(inputArrayBuffer, offset, aesIV) {
  4770. const nRounds = this.keySize + 6;
  4771. const invKeySchedule = this.invKeySchedule;
  4772. const invSBOX = this.invSBox;
  4773. const invSubMix = this.invSubMix;
  4774. const invSubMix0 = invSubMix[0];
  4775. const invSubMix1 = invSubMix[1];
  4776. const invSubMix2 = invSubMix[2];
  4777. const invSubMix3 = invSubMix[3];
  4778. const initVector = this.uint8ArrayToUint32Array_(aesIV);
  4779. let initVector0 = initVector[0];
  4780. let initVector1 = initVector[1];
  4781. let initVector2 = initVector[2];
  4782. let initVector3 = initVector[3];
  4783. const inputInt32 = new Int32Array(inputArrayBuffer);
  4784. const outputInt32 = new Int32Array(inputInt32.length);
  4785. let t0, t1, t2, t3;
  4786. let s0, s1, s2, s3;
  4787. let inputWords0, inputWords1, inputWords2, inputWords3;
  4788. let ksRow, i;
  4789. const swapWord = this.networkToHostOrderSwap;
  4790. while (offset < inputInt32.length) {
  4791. inputWords0 = swapWord(inputInt32[offset]);
  4792. inputWords1 = swapWord(inputInt32[offset + 1]);
  4793. inputWords2 = swapWord(inputInt32[offset + 2]);
  4794. inputWords3 = swapWord(inputInt32[offset + 3]);
  4795. s0 = inputWords0 ^ invKeySchedule[0];
  4796. s1 = inputWords3 ^ invKeySchedule[1];
  4797. s2 = inputWords2 ^ invKeySchedule[2];
  4798. s3 = inputWords1 ^ invKeySchedule[3];
  4799. ksRow = 4;
  4800. for (i = 1; i < nRounds; i++) {
  4801. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 255] ^ invSubMix2[s2 >> 8 & 255] ^ invSubMix3[s3 & 255] ^ invKeySchedule[ksRow];
  4802. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 255] ^ invSubMix2[s3 >> 8 & 255] ^ invSubMix3[s0 & 255] ^ invKeySchedule[ksRow + 1];
  4803. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 255] ^ invSubMix2[s0 >> 8 & 255] ^ invSubMix3[s1 & 255] ^ invKeySchedule[ksRow + 2];
  4804. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 255] ^ invSubMix2[s1 >> 8 & 255] ^ invSubMix3[s2 & 255] ^ invKeySchedule[ksRow + 3];
  4805. s0 = t0;
  4806. s1 = t1;
  4807. s2 = t2;
  4808. s3 = t3;
  4809. ksRow = ksRow + 4;
  4810. }
  4811. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 255] << 16 ^ invSBOX[s2 >> 8 & 255] << 8 ^ invSBOX[s3 & 255] ^ invKeySchedule[ksRow];
  4812. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 255] << 16 ^ invSBOX[s3 >> 8 & 255] << 8 ^ invSBOX[s0 & 255] ^ invKeySchedule[ksRow + 1];
  4813. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 255] << 16 ^ invSBOX[s0 >> 8 & 255] << 8 ^ invSBOX[s1 & 255] ^ invKeySchedule[ksRow + 2];
  4814. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 255] << 16 ^ invSBOX[s1 >> 8 & 255] << 8 ^ invSBOX[s2 & 255] ^ invKeySchedule[ksRow + 3];
  4815. outputInt32[offset] = swapWord(t0 ^ initVector0);
  4816. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  4817. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  4818. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  4819. initVector0 = inputWords0;
  4820. initVector1 = inputWords1;
  4821. initVector2 = inputWords2;
  4822. initVector3 = inputWords3;
  4823. offset = offset + 4;
  4824. }
  4825. return outputInt32.buffer;
  4826. }
  4827. };
  4828. var FastAESKey = class {
  4829. constructor(subtle, key, aesMode) {
  4830. this.subtle = void 0;
  4831. this.key = void 0;
  4832. this.aesMode = void 0;
  4833. this.subtle = subtle;
  4834. this.key = key;
  4835. this.aesMode = aesMode;
  4836. }
  4837. expandKey() {
  4838. const subtleAlgoName = getSubtleAlgoName(this.aesMode);
  4839. return this.subtle.importKey("raw", this.key, {
  4840. name: subtleAlgoName
  4841. }, false, ["encrypt", "decrypt"]);
  4842. }
  4843. };
  4844. function getSubtleAlgoName(aesMode) {
  4845. switch (aesMode) {
  4846. case DecrypterAesMode.cbc:
  4847. return "AES-CBC";
  4848. case DecrypterAesMode.ctr:
  4849. return "AES-CTR";
  4850. default:
  4851. throw new Error(`[FastAESKey] invalid aes mode ${aesMode}`);
  4852. }
  4853. }
  4854. var CHUNK_SIZE = 16;
  4855. var Decrypter = class {
  4856. constructor(config, {
  4857. removePKCS7Padding = true
  4858. } = {}) {
  4859. this.logEnabled = true;
  4860. this.removePKCS7Padding = void 0;
  4861. this.subtle = null;
  4862. this.softwareDecrypter = null;
  4863. this.key = null;
  4864. this.fastAesKey = null;
  4865. this.remainderData = null;
  4866. this.currentIV = null;
  4867. this.currentResult = null;
  4868. this.useSoftware = void 0;
  4869. this.enableSoftwareAES = void 0;
  4870. this.enableSoftwareAES = config.enableSoftwareAES;
  4871. this.removePKCS7Padding = removePKCS7Padding;
  4872. if (removePKCS7Padding) {
  4873. try {
  4874. const browserCrypto = self.crypto;
  4875. if (browserCrypto) {
  4876. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  4877. }
  4878. } catch (e) {
  4879. }
  4880. }
  4881. this.useSoftware = !this.subtle;
  4882. }
  4883. destroy() {
  4884. this.subtle = null;
  4885. this.softwareDecrypter = null;
  4886. this.key = null;
  4887. this.fastAesKey = null;
  4888. this.remainderData = null;
  4889. this.currentIV = null;
  4890. this.currentResult = null;
  4891. }
  4892. isSync() {
  4893. return this.useSoftware;
  4894. }
  4895. flush() {
  4896. const {
  4897. currentResult,
  4898. remainderData
  4899. } = this;
  4900. if (!currentResult || remainderData) {
  4901. this.reset();
  4902. return null;
  4903. }
  4904. const data = new Uint8Array(currentResult);
  4905. this.reset();
  4906. if (this.removePKCS7Padding) {
  4907. return removePadding(data);
  4908. }
  4909. return data;
  4910. }
  4911. reset() {
  4912. this.currentResult = null;
  4913. this.currentIV = null;
  4914. this.remainderData = null;
  4915. if (this.softwareDecrypter) {
  4916. this.softwareDecrypter = null;
  4917. }
  4918. }
  4919. decrypt(data, key, iv, aesMode) {
  4920. if (this.useSoftware) {
  4921. return new Promise((resolve, reject) => {
  4922. const dataView = ArrayBuffer.isView(data) ? data : new Uint8Array(data);
  4923. this.softwareDecrypt(dataView, key, iv, aesMode);
  4924. const decryptResult = this.flush();
  4925. if (decryptResult) {
  4926. resolve(decryptResult.buffer);
  4927. } else {
  4928. reject(new Error("[softwareDecrypt] Failed to decrypt data"));
  4929. }
  4930. });
  4931. }
  4932. return this.webCryptoDecrypt(new Uint8Array(data), key, iv, aesMode);
  4933. }
  4934. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  4935. // data is handled in the flush() call
  4936. softwareDecrypt(data, key, iv, aesMode) {
  4937. const {
  4938. currentIV,
  4939. currentResult,
  4940. remainderData
  4941. } = this;
  4942. if (aesMode !== DecrypterAesMode.cbc || key.byteLength !== 16) {
  4943. logger.warn("SoftwareDecrypt: can only handle AES-128-CBC");
  4944. return null;
  4945. }
  4946. this.logOnce("JS AES decrypt");
  4947. if (remainderData) {
  4948. data = appendUint8Array(remainderData, data);
  4949. this.remainderData = null;
  4950. }
  4951. const currentChunk = this.getValidChunk(data);
  4952. if (!currentChunk.length) {
  4953. return null;
  4954. }
  4955. if (currentIV) {
  4956. iv = currentIV;
  4957. }
  4958. let softwareDecrypter = this.softwareDecrypter;
  4959. if (!softwareDecrypter) {
  4960. softwareDecrypter = this.softwareDecrypter = new AESDecryptor();
  4961. }
  4962. softwareDecrypter.expandKey(key);
  4963. const result = currentResult;
  4964. this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
  4965. this.currentIV = currentChunk.slice(-16).buffer;
  4966. if (!result) {
  4967. return null;
  4968. }
  4969. return result;
  4970. }
  4971. webCryptoDecrypt(data, key, iv, aesMode) {
  4972. if (this.key !== key || !this.fastAesKey) {
  4973. if (!this.subtle) {
  4974. return Promise.resolve(this.onWebCryptoError(data, key, iv, aesMode));
  4975. }
  4976. this.key = key;
  4977. this.fastAesKey = new FastAESKey(this.subtle, key, aesMode);
  4978. }
  4979. return this.fastAesKey.expandKey().then((aesKey) => {
  4980. if (!this.subtle) {
  4981. return Promise.reject(new Error("web crypto not initialized"));
  4982. }
  4983. this.logOnce("WebCrypto AES decrypt");
  4984. const crypto2 = new AESCrypto(this.subtle, new Uint8Array(iv), aesMode);
  4985. return crypto2.decrypt(data.buffer, aesKey);
  4986. }).catch((err) => {
  4987. logger.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${err.name}: ${err.message}`);
  4988. return this.onWebCryptoError(data, key, iv, aesMode);
  4989. });
  4990. }
  4991. onWebCryptoError(data, key, iv, aesMode) {
  4992. const enableSoftwareAES = this.enableSoftwareAES;
  4993. if (enableSoftwareAES) {
  4994. this.useSoftware = true;
  4995. this.logEnabled = true;
  4996. this.softwareDecrypt(data, key, iv, aesMode);
  4997. const decryptResult = this.flush();
  4998. if (decryptResult) {
  4999. return decryptResult.buffer;
  5000. }
  5001. }
  5002. throw new Error("WebCrypto" + (enableSoftwareAES ? " and softwareDecrypt" : "") + ": failed to decrypt data");
  5003. }
  5004. getValidChunk(data) {
  5005. let currentChunk = data;
  5006. const splitPoint = data.length - data.length % CHUNK_SIZE;
  5007. if (splitPoint !== data.length) {
  5008. currentChunk = data.slice(0, splitPoint);
  5009. this.remainderData = data.slice(splitPoint);
  5010. }
  5011. return currentChunk;
  5012. }
  5013. logOnce(msg) {
  5014. if (!this.logEnabled) {
  5015. return;
  5016. }
  5017. logger.log(`[decrypter]: ${msg}`);
  5018. this.logEnabled = false;
  5019. }
  5020. };
  5021. var MIN_CHUNK_SIZE = Math.pow(2, 17);
  5022. var FragmentLoader = class {
  5023. constructor(config) {
  5024. this.config = void 0;
  5025. this.loader = null;
  5026. this.partLoadTimeout = -1;
  5027. this.config = config;
  5028. }
  5029. destroy() {
  5030. if (this.loader) {
  5031. this.loader.destroy();
  5032. this.loader = null;
  5033. }
  5034. }
  5035. abort() {
  5036. if (this.loader) {
  5037. this.loader.abort();
  5038. }
  5039. }
  5040. load(frag, onProgress) {
  5041. const url = frag.url;
  5042. if (!url) {
  5043. return Promise.reject(new LoadError({
  5044. type: ErrorTypes.NETWORK_ERROR,
  5045. details: ErrorDetails.FRAG_LOAD_ERROR,
  5046. fatal: false,
  5047. frag,
  5048. error: new Error(`Fragment does not have a ${url ? "part list" : "url"}`),
  5049. networkDetails: null
  5050. }));
  5051. }
  5052. this.abort();
  5053. const config = this.config;
  5054. const FragmentILoader = config.fLoader;
  5055. const DefaultILoader = config.loader;
  5056. return new Promise((resolve, reject) => {
  5057. if (this.loader) {
  5058. this.loader.destroy();
  5059. }
  5060. if (frag.gap) {
  5061. if (frag.tagList.some((tags) => tags[0] === "GAP")) {
  5062. reject(createGapLoadError(frag));
  5063. return;
  5064. } else {
  5065. frag.gap = false;
  5066. }
  5067. }
  5068. const loader = this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  5069. const loaderContext = createLoaderContext(frag);
  5070. frag.loader = loader;
  5071. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  5072. const loaderConfig = {
  5073. loadPolicy,
  5074. timeout: loadPolicy.maxLoadTimeMs,
  5075. maxRetry: 0,
  5076. retryDelay: 0,
  5077. maxRetryDelay: 0,
  5078. highWaterMark: frag.sn === "initSegment" ? Infinity : MIN_CHUNK_SIZE
  5079. };
  5080. frag.stats = loader.stats;
  5081. const callbacks = {
  5082. onSuccess: (response, stats, context, networkDetails) => {
  5083. this.resetLoader(frag, loader);
  5084. let payload = response.data;
  5085. if (context.resetIV && frag.decryptdata) {
  5086. frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));
  5087. payload = payload.slice(16);
  5088. }
  5089. resolve({
  5090. frag,
  5091. part: null,
  5092. payload,
  5093. networkDetails
  5094. });
  5095. },
  5096. onError: (response, context, networkDetails, stats) => {
  5097. this.resetLoader(frag, loader);
  5098. reject(new LoadError({
  5099. type: ErrorTypes.NETWORK_ERROR,
  5100. details: ErrorDetails.FRAG_LOAD_ERROR,
  5101. fatal: false,
  5102. frag,
  5103. response: _objectSpread2({
  5104. url,
  5105. data: void 0
  5106. }, response),
  5107. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  5108. networkDetails,
  5109. stats
  5110. }));
  5111. },
  5112. onAbort: (stats, context, networkDetails) => {
  5113. this.resetLoader(frag, loader);
  5114. reject(new LoadError({
  5115. type: ErrorTypes.NETWORK_ERROR,
  5116. details: ErrorDetails.INTERNAL_ABORTED,
  5117. fatal: false,
  5118. frag,
  5119. error: new Error("Aborted"),
  5120. networkDetails,
  5121. stats
  5122. }));
  5123. },
  5124. onTimeout: (stats, context, networkDetails) => {
  5125. this.resetLoader(frag, loader);
  5126. reject(new LoadError({
  5127. type: ErrorTypes.NETWORK_ERROR,
  5128. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  5129. fatal: false,
  5130. frag,
  5131. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  5132. networkDetails,
  5133. stats
  5134. }));
  5135. }
  5136. };
  5137. if (onProgress) {
  5138. callbacks.onProgress = (stats, context, data, networkDetails) => onProgress({
  5139. frag,
  5140. part: null,
  5141. payload: data,
  5142. networkDetails
  5143. });
  5144. }
  5145. loader.load(loaderContext, loaderConfig, callbacks);
  5146. });
  5147. }
  5148. loadPart(frag, part, onProgress) {
  5149. this.abort();
  5150. const config = this.config;
  5151. const FragmentILoader = config.fLoader;
  5152. const DefaultILoader = config.loader;
  5153. return new Promise((resolve, reject) => {
  5154. if (this.loader) {
  5155. this.loader.destroy();
  5156. }
  5157. if (frag.gap || part.gap) {
  5158. reject(createGapLoadError(frag, part));
  5159. return;
  5160. }
  5161. const loader = this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  5162. const loaderContext = createLoaderContext(frag, part);
  5163. frag.loader = loader;
  5164. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  5165. const loaderConfig = {
  5166. loadPolicy,
  5167. timeout: loadPolicy.maxLoadTimeMs,
  5168. maxRetry: 0,
  5169. retryDelay: 0,
  5170. maxRetryDelay: 0,
  5171. highWaterMark: MIN_CHUNK_SIZE
  5172. };
  5173. part.stats = loader.stats;
  5174. loader.load(loaderContext, loaderConfig, {
  5175. onSuccess: (response, stats, context, networkDetails) => {
  5176. this.resetLoader(frag, loader);
  5177. this.updateStatsFromPart(frag, part);
  5178. const partLoadedData = {
  5179. frag,
  5180. part,
  5181. payload: response.data,
  5182. networkDetails
  5183. };
  5184. onProgress(partLoadedData);
  5185. resolve(partLoadedData);
  5186. },
  5187. onError: (response, context, networkDetails, stats) => {
  5188. this.resetLoader(frag, loader);
  5189. reject(new LoadError({
  5190. type: ErrorTypes.NETWORK_ERROR,
  5191. details: ErrorDetails.FRAG_LOAD_ERROR,
  5192. fatal: false,
  5193. frag,
  5194. part,
  5195. response: _objectSpread2({
  5196. url: loaderContext.url,
  5197. data: void 0
  5198. }, response),
  5199. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  5200. networkDetails,
  5201. stats
  5202. }));
  5203. },
  5204. onAbort: (stats, context, networkDetails) => {
  5205. frag.stats.aborted = part.stats.aborted;
  5206. this.resetLoader(frag, loader);
  5207. reject(new LoadError({
  5208. type: ErrorTypes.NETWORK_ERROR,
  5209. details: ErrorDetails.INTERNAL_ABORTED,
  5210. fatal: false,
  5211. frag,
  5212. part,
  5213. error: new Error("Aborted"),
  5214. networkDetails,
  5215. stats
  5216. }));
  5217. },
  5218. onTimeout: (stats, context, networkDetails) => {
  5219. this.resetLoader(frag, loader);
  5220. reject(new LoadError({
  5221. type: ErrorTypes.NETWORK_ERROR,
  5222. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  5223. fatal: false,
  5224. frag,
  5225. part,
  5226. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  5227. networkDetails,
  5228. stats
  5229. }));
  5230. }
  5231. });
  5232. });
  5233. }
  5234. updateStatsFromPart(frag, part) {
  5235. const fragStats = frag.stats;
  5236. const partStats = part.stats;
  5237. const partTotal = partStats.total;
  5238. fragStats.loaded += partStats.loaded;
  5239. if (partTotal) {
  5240. const estTotalParts = Math.round(frag.duration / part.duration);
  5241. const estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
  5242. const estRemainingParts = estTotalParts - estLoadedParts;
  5243. const estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
  5244. fragStats.total = fragStats.loaded + estRemainingBytes;
  5245. } else {
  5246. fragStats.total = Math.max(fragStats.loaded, fragStats.total);
  5247. }
  5248. const fragLoading = fragStats.loading;
  5249. const partLoading = partStats.loading;
  5250. if (fragLoading.start) {
  5251. fragLoading.first += partLoading.first - partLoading.start;
  5252. } else {
  5253. fragLoading.start = partLoading.start;
  5254. fragLoading.first = partLoading.first;
  5255. }
  5256. fragLoading.end = partLoading.end;
  5257. }
  5258. resetLoader(frag, loader) {
  5259. frag.loader = null;
  5260. if (this.loader === loader) {
  5261. self.clearTimeout(this.partLoadTimeout);
  5262. this.loader = null;
  5263. }
  5264. loader.destroy();
  5265. }
  5266. };
  5267. function createLoaderContext(frag, part = null) {
  5268. const segment = part || frag;
  5269. const loaderContext = {
  5270. frag,
  5271. part,
  5272. responseType: "arraybuffer",
  5273. url: segment.url,
  5274. headers: {},
  5275. rangeStart: 0,
  5276. rangeEnd: 0
  5277. };
  5278. const start = segment.byteRangeStartOffset;
  5279. const end = segment.byteRangeEndOffset;
  5280. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  5281. var _frag$decryptdata;
  5282. let byteRangeStart = start;
  5283. let byteRangeEnd = end;
  5284. if (frag.sn === "initSegment" && isMethodFullSegmentAesCbc((_frag$decryptdata = frag.decryptdata) == null ? void 0 : _frag$decryptdata.method)) {
  5285. const fragmentLen = end - start;
  5286. if (fragmentLen % 16) {
  5287. byteRangeEnd = end + (16 - fragmentLen % 16);
  5288. }
  5289. if (start !== 0) {
  5290. loaderContext.resetIV = true;
  5291. byteRangeStart = start - 16;
  5292. }
  5293. }
  5294. loaderContext.rangeStart = byteRangeStart;
  5295. loaderContext.rangeEnd = byteRangeEnd;
  5296. }
  5297. return loaderContext;
  5298. }
  5299. function createGapLoadError(frag, part) {
  5300. const error = new Error(`GAP ${frag.gap ? "tag" : "attribute"} found`);
  5301. const errorData = {
  5302. type: ErrorTypes.MEDIA_ERROR,
  5303. details: ErrorDetails.FRAG_GAP,
  5304. fatal: false,
  5305. frag,
  5306. error,
  5307. networkDetails: null
  5308. };
  5309. if (part) {
  5310. errorData.part = part;
  5311. }
  5312. (part ? part : frag).stats.aborted = true;
  5313. return new LoadError(errorData);
  5314. }
  5315. function isMethodFullSegmentAesCbc(method) {
  5316. return method === "AES-128" || method === "AES-256";
  5317. }
  5318. var LoadError = class extends Error {
  5319. constructor(data) {
  5320. super(data.error.message);
  5321. this.data = void 0;
  5322. this.data = data;
  5323. }
  5324. };
  5325. var TaskLoop = class extends Logger {
  5326. constructor(label, logger2) {
  5327. super(label, logger2);
  5328. this._boundTick = void 0;
  5329. this._tickTimer = null;
  5330. this._tickInterval = null;
  5331. this._tickCallCount = 0;
  5332. this._boundTick = this.tick.bind(this);
  5333. }
  5334. destroy() {
  5335. this.onHandlerDestroying();
  5336. this.onHandlerDestroyed();
  5337. }
  5338. onHandlerDestroying() {
  5339. this.clearNextTick();
  5340. this.clearInterval();
  5341. }
  5342. onHandlerDestroyed() {
  5343. }
  5344. hasInterval() {
  5345. return !!this._tickInterval;
  5346. }
  5347. hasNextTick() {
  5348. return !!this._tickTimer;
  5349. }
  5350. /**
  5351. * @param millis - Interval time (ms)
  5352. * @eturns True when interval has been scheduled, false when already scheduled (no effect)
  5353. */
  5354. setInterval(millis) {
  5355. if (!this._tickInterval) {
  5356. this._tickCallCount = 0;
  5357. this._tickInterval = self.setInterval(this._boundTick, millis);
  5358. return true;
  5359. }
  5360. return false;
  5361. }
  5362. /**
  5363. * @returns True when interval was cleared, false when none was set (no effect)
  5364. */
  5365. clearInterval() {
  5366. if (this._tickInterval) {
  5367. self.clearInterval(this._tickInterval);
  5368. this._tickInterval = null;
  5369. return true;
  5370. }
  5371. return false;
  5372. }
  5373. /**
  5374. * @returns True when timeout was cleared, false when none was set (no effect)
  5375. */
  5376. clearNextTick() {
  5377. if (this._tickTimer) {
  5378. self.clearTimeout(this._tickTimer);
  5379. this._tickTimer = null;
  5380. return true;
  5381. }
  5382. return false;
  5383. }
  5384. /**
  5385. * Will call the subclass doTick implementation in this main loop tick
  5386. * or in the next one (via setTimeout(,0)) in case it has already been called
  5387. * in this tick (in case this is a re-entrant call).
  5388. */
  5389. tick() {
  5390. this._tickCallCount++;
  5391. if (this._tickCallCount === 1) {
  5392. this.doTick();
  5393. if (this._tickCallCount > 1) {
  5394. this.tickImmediate();
  5395. }
  5396. this._tickCallCount = 0;
  5397. }
  5398. }
  5399. tickImmediate() {
  5400. this.clearNextTick();
  5401. this._tickTimer = self.setTimeout(this._boundTick, 0);
  5402. }
  5403. /**
  5404. * For subclass to implement task logic
  5405. * @abstract
  5406. */
  5407. doTick() {
  5408. }
  5409. };
  5410. var ChunkMetadata = class {
  5411. constructor(level, sn, id, size = 0, part = -1, partial = false) {
  5412. this.level = void 0;
  5413. this.sn = void 0;
  5414. this.part = void 0;
  5415. this.id = void 0;
  5416. this.size = void 0;
  5417. this.partial = void 0;
  5418. this.transmuxing = getNewPerformanceTiming();
  5419. this.buffering = {
  5420. audio: getNewPerformanceTiming(),
  5421. video: getNewPerformanceTiming(),
  5422. audiovideo: getNewPerformanceTiming()
  5423. };
  5424. this.level = level;
  5425. this.sn = sn;
  5426. this.id = id;
  5427. this.size = size;
  5428. this.part = part;
  5429. this.partial = partial;
  5430. }
  5431. };
  5432. function getNewPerformanceTiming() {
  5433. return {
  5434. start: 0,
  5435. executeStart: 0,
  5436. executeEnd: 0,
  5437. end: 0
  5438. };
  5439. }
  5440. var noopBuffered = {
  5441. length: 0,
  5442. start: () => 0,
  5443. end: () => 0
  5444. };
  5445. var BufferHelper = class _BufferHelper {
  5446. /**
  5447. * Return true if `media`'s buffered include `position`
  5448. */
  5449. static isBuffered(media, position) {
  5450. if (media) {
  5451. const buffered = _BufferHelper.getBuffered(media);
  5452. for (let i = buffered.length; i--; ) {
  5453. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  5454. return true;
  5455. }
  5456. }
  5457. }
  5458. return false;
  5459. }
  5460. static bufferedRanges(media) {
  5461. if (media) {
  5462. const timeRanges = _BufferHelper.getBuffered(media);
  5463. return _BufferHelper.timeRangesToArray(timeRanges);
  5464. }
  5465. return [];
  5466. }
  5467. static timeRangesToArray(timeRanges) {
  5468. const buffered = [];
  5469. for (let i = 0; i < timeRanges.length; i++) {
  5470. buffered.push({
  5471. start: timeRanges.start(i),
  5472. end: timeRanges.end(i)
  5473. });
  5474. }
  5475. return buffered;
  5476. }
  5477. static bufferInfo(media, pos, maxHoleDuration) {
  5478. if (media) {
  5479. const buffered = _BufferHelper.bufferedRanges(media);
  5480. if (buffered.length) {
  5481. return _BufferHelper.bufferedInfo(buffered, pos, maxHoleDuration);
  5482. }
  5483. }
  5484. return {
  5485. len: 0,
  5486. start: pos,
  5487. end: pos,
  5488. bufferedIndex: -1
  5489. };
  5490. }
  5491. static bufferedInfo(buffered, pos, maxHoleDuration) {
  5492. pos = Math.max(0, pos);
  5493. if (buffered.length > 1) {
  5494. buffered.sort((a, b) => a.start - b.start || b.end - a.end);
  5495. }
  5496. let bufferedIndex = -1;
  5497. let buffered2 = [];
  5498. if (maxHoleDuration) {
  5499. for (let i = 0; i < buffered.length; i++) {
  5500. if (pos >= buffered[i].start && pos <= buffered[i].end) {
  5501. bufferedIndex = i;
  5502. }
  5503. const buf2len = buffered2.length;
  5504. if (buf2len) {
  5505. const buf2end = buffered2[buf2len - 1].end;
  5506. if (buffered[i].start - buf2end < maxHoleDuration) {
  5507. if (buffered[i].end > buf2end) {
  5508. buffered2[buf2len - 1].end = buffered[i].end;
  5509. }
  5510. } else {
  5511. buffered2.push(buffered[i]);
  5512. }
  5513. } else {
  5514. buffered2.push(buffered[i]);
  5515. }
  5516. }
  5517. } else {
  5518. buffered2 = buffered;
  5519. }
  5520. let bufferLen = 0;
  5521. let nextStart;
  5522. let bufferStart = pos;
  5523. let bufferEnd = pos;
  5524. for (let i = 0; i < buffered2.length; i++) {
  5525. const start = buffered2[i].start;
  5526. const end = buffered2[i].end;
  5527. if (bufferedIndex === -1 && pos >= start && pos <= end) {
  5528. bufferedIndex = i;
  5529. }
  5530. if (pos + maxHoleDuration >= start && pos < end) {
  5531. bufferStart = start;
  5532. bufferEnd = end;
  5533. bufferLen = bufferEnd - pos;
  5534. } else if (pos + maxHoleDuration < start) {
  5535. nextStart = start;
  5536. break;
  5537. }
  5538. }
  5539. return {
  5540. len: bufferLen,
  5541. start: bufferStart || 0,
  5542. end: bufferEnd || 0,
  5543. nextStart,
  5544. buffered,
  5545. bufferedIndex
  5546. };
  5547. }
  5548. /**
  5549. * Safe method to get buffered property.
  5550. * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
  5551. */
  5552. static getBuffered(media) {
  5553. try {
  5554. return media.buffered || noopBuffered;
  5555. } catch (e) {
  5556. logger.log("failed to get media.buffered", e);
  5557. return noopBuffered;
  5558. }
  5559. }
  5560. };
  5561. var VARIABLE_REPLACEMENT_REGEX = /\{\$([a-zA-Z0-9-_]+)\}/g;
  5562. function hasVariableReferences(str) {
  5563. return VARIABLE_REPLACEMENT_REGEX.test(str);
  5564. }
  5565. function substituteVariables(parsed, value) {
  5566. if (parsed.variableList !== null || parsed.hasVariableRefs) {
  5567. const variableList = parsed.variableList;
  5568. return value.replace(VARIABLE_REPLACEMENT_REGEX, (variableReference) => {
  5569. const variableName = variableReference.substring(2, variableReference.length - 1);
  5570. const variableValue = variableList == null ? void 0 : variableList[variableName];
  5571. if (variableValue === void 0) {
  5572. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${variableName}"`));
  5573. return variableReference;
  5574. }
  5575. return variableValue;
  5576. });
  5577. }
  5578. return value;
  5579. }
  5580. function addVariableDefinition(parsed, attr, parentUrl) {
  5581. let variableList = parsed.variableList;
  5582. if (!variableList) {
  5583. parsed.variableList = variableList = {};
  5584. }
  5585. let NAME;
  5586. let VALUE;
  5587. if ("QUERYPARAM" in attr) {
  5588. NAME = attr.QUERYPARAM;
  5589. try {
  5590. const searchParams = new self.URL(parentUrl).searchParams;
  5591. if (searchParams.has(NAME)) {
  5592. VALUE = searchParams.get(NAME);
  5593. } else {
  5594. throw new Error(`"${NAME}" does not match any query parameter in URI: "${parentUrl}"`);
  5595. }
  5596. } catch (error) {
  5597. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE QUERYPARAM: ${error.message}`));
  5598. }
  5599. } else {
  5600. NAME = attr.NAME;
  5601. VALUE = attr.VALUE;
  5602. }
  5603. if (NAME in variableList) {
  5604. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${NAME}"`));
  5605. } else {
  5606. variableList[NAME] = VALUE || "";
  5607. }
  5608. }
  5609. function importVariableDefinition(parsed, attr, sourceVariableList) {
  5610. const IMPORT = attr.IMPORT;
  5611. if (sourceVariableList && IMPORT in sourceVariableList) {
  5612. let variableList = parsed.variableList;
  5613. if (!variableList) {
  5614. parsed.variableList = variableList = {};
  5615. }
  5616. variableList[IMPORT] = sourceVariableList[IMPORT];
  5617. } else {
  5618. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${IMPORT}"`));
  5619. }
  5620. }
  5621. var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/;
  5622. var ATTR_LIST_REGEX = /(.+?)=(".*?"|.*?)(?:,|$)/g;
  5623. var AttrList = class _AttrList {
  5624. constructor(attrs, parsed) {
  5625. if (typeof attrs === "string") {
  5626. attrs = _AttrList.parseAttrList(attrs, parsed);
  5627. }
  5628. _extends(this, attrs);
  5629. }
  5630. get clientAttrs() {
  5631. return Object.keys(this).filter((attr) => attr.substring(0, 2) === "X-");
  5632. }
  5633. decimalInteger(attrName) {
  5634. const intValue = parseInt(this[attrName], 10);
  5635. if (intValue > Number.MAX_SAFE_INTEGER) {
  5636. return Infinity;
  5637. }
  5638. return intValue;
  5639. }
  5640. hexadecimalInteger(attrName) {
  5641. if (this[attrName]) {
  5642. let stringValue = (this[attrName] || "0x").slice(2);
  5643. stringValue = (stringValue.length & 1 ? "0" : "") + stringValue;
  5644. const value = new Uint8Array(stringValue.length / 2);
  5645. for (let i = 0; i < stringValue.length / 2; i++) {
  5646. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  5647. }
  5648. return value;
  5649. }
  5650. return null;
  5651. }
  5652. hexadecimalIntegerAsNumber(attrName) {
  5653. const intValue = parseInt(this[attrName], 16);
  5654. if (intValue > Number.MAX_SAFE_INTEGER) {
  5655. return Infinity;
  5656. }
  5657. return intValue;
  5658. }
  5659. decimalFloatingPoint(attrName) {
  5660. return parseFloat(this[attrName]);
  5661. }
  5662. optionalFloat(attrName, defaultValue) {
  5663. const value = this[attrName];
  5664. return value ? parseFloat(value) : defaultValue;
  5665. }
  5666. enumeratedString(attrName) {
  5667. return this[attrName];
  5668. }
  5669. enumeratedStringList(attrName, dict) {
  5670. const attrValue = this[attrName];
  5671. return (attrValue ? attrValue.split(/[ ,]+/) : []).reduce((result, identifier) => {
  5672. result[identifier.toLowerCase()] = true;
  5673. return result;
  5674. }, dict);
  5675. }
  5676. bool(attrName) {
  5677. return this[attrName] === "YES";
  5678. }
  5679. decimalResolution(attrName) {
  5680. const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  5681. if (res === null) {
  5682. return void 0;
  5683. }
  5684. return {
  5685. width: parseInt(res[1], 10),
  5686. height: parseInt(res[2], 10)
  5687. };
  5688. }
  5689. static parseAttrList(input, parsed) {
  5690. let match;
  5691. const attrs = {};
  5692. const quote = '"';
  5693. ATTR_LIST_REGEX.lastIndex = 0;
  5694. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  5695. const name = match[1].trim();
  5696. let value = match[2];
  5697. const quotedString = value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1;
  5698. let hexadecimalSequence = false;
  5699. if (quotedString) {
  5700. value = value.slice(1, -1);
  5701. } else {
  5702. switch (name) {
  5703. case "IV":
  5704. case "SCTE35-CMD":
  5705. case "SCTE35-IN":
  5706. case "SCTE35-OUT":
  5707. hexadecimalSequence = true;
  5708. }
  5709. }
  5710. if (parsed && (quotedString || hexadecimalSequence)) {
  5711. {
  5712. value = substituteVariables(parsed, value);
  5713. }
  5714. } else if (!hexadecimalSequence && !quotedString) {
  5715. switch (name) {
  5716. case "CLOSED-CAPTIONS":
  5717. if (value === "NONE") {
  5718. break;
  5719. }
  5720. case "ALLOWED-CPC":
  5721. case "CLASS":
  5722. case "ASSOC-LANGUAGE":
  5723. case "AUDIO":
  5724. case "BYTERANGE":
  5725. case "CHANNELS":
  5726. case "CHARACTERISTICS":
  5727. case "CODECS":
  5728. case "DATA-ID":
  5729. case "END-DATE":
  5730. case "GROUP-ID":
  5731. case "ID":
  5732. case "IMPORT":
  5733. case "INSTREAM-ID":
  5734. case "KEYFORMAT":
  5735. case "KEYFORMATVERSIONS":
  5736. case "LANGUAGE":
  5737. case "NAME":
  5738. case "PATHWAY-ID":
  5739. case "QUERYPARAM":
  5740. case "RECENTLY-REMOVED-DATERANGES":
  5741. case "SERVER-URI":
  5742. case "STABLE-RENDITION-ID":
  5743. case "STABLE-VARIANT-ID":
  5744. case "START-DATE":
  5745. case "SUBTITLES":
  5746. case "SUPPLEMENTAL-CODECS":
  5747. case "URI":
  5748. case "VALUE":
  5749. case "VIDEO":
  5750. case "X-ASSET-LIST":
  5751. case "X-ASSET-URI":
  5752. logger.warn(`${input}: attribute ${name} is missing quotes`);
  5753. }
  5754. }
  5755. attrs[name] = value;
  5756. }
  5757. return attrs;
  5758. }
  5759. };
  5760. var CLASS_INTERSTITIAL = "com.apple.hls.interstitial";
  5761. function isDateRangeCueAttribute(attrName) {
  5762. return attrName !== "ID" && attrName !== "CLASS" && attrName !== "CUE" && attrName !== "START-DATE" && attrName !== "DURATION" && attrName !== "END-DATE" && attrName !== "END-ON-NEXT";
  5763. }
  5764. function isSCTE35Attribute(attrName) {
  5765. return attrName === "SCTE35-OUT" || attrName === "SCTE35-IN" || attrName === "SCTE35-CMD";
  5766. }
  5767. var DateRange = class {
  5768. constructor(dateRangeAttr, dateRangeWithSameId, tagCount = 0) {
  5769. var _dateRangeWithSameId$;
  5770. this.attr = void 0;
  5771. this.tagAnchor = void 0;
  5772. this.tagOrder = void 0;
  5773. this._startDate = void 0;
  5774. this._endDate = void 0;
  5775. this._dateAtEnd = void 0;
  5776. this._cue = void 0;
  5777. this._badValueForSameId = void 0;
  5778. this.tagAnchor = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagAnchor) || null;
  5779. this.tagOrder = (_dateRangeWithSameId$ = dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagOrder) != null ? _dateRangeWithSameId$ : tagCount;
  5780. if (dateRangeWithSameId) {
  5781. const previousAttr = dateRangeWithSameId.attr;
  5782. for (const key in previousAttr) {
  5783. if (Object.prototype.hasOwnProperty.call(dateRangeAttr, key) && dateRangeAttr[key] !== previousAttr[key]) {
  5784. logger.warn(`DATERANGE tag attribute: "${key}" does not match for tags with ID: "${dateRangeAttr.ID}"`);
  5785. this._badValueForSameId = key;
  5786. break;
  5787. }
  5788. }
  5789. dateRangeAttr = _extends(new AttrList({}), previousAttr, dateRangeAttr);
  5790. }
  5791. this.attr = dateRangeAttr;
  5792. if (dateRangeWithSameId) {
  5793. this._startDate = dateRangeWithSameId._startDate;
  5794. this._cue = dateRangeWithSameId._cue;
  5795. this._endDate = dateRangeWithSameId._endDate;
  5796. this._dateAtEnd = dateRangeWithSameId._dateAtEnd;
  5797. } else {
  5798. this._startDate = new Date(dateRangeAttr["START-DATE"]);
  5799. }
  5800. if ("END-DATE" in this.attr) {
  5801. const endDate = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.endDate) || new Date(this.attr["END-DATE"]);
  5802. if (isFiniteNumber(endDate.getTime())) {
  5803. this._endDate = endDate;
  5804. }
  5805. }
  5806. }
  5807. get id() {
  5808. return this.attr.ID;
  5809. }
  5810. get class() {
  5811. return this.attr.CLASS;
  5812. }
  5813. get cue() {
  5814. const _cue = this._cue;
  5815. if (_cue === void 0) {
  5816. return this._cue = this.attr.enumeratedStringList(this.attr.CUE ? "CUE" : "X-CUE", {
  5817. pre: false,
  5818. post: false,
  5819. once: false
  5820. });
  5821. }
  5822. return _cue;
  5823. }
  5824. get startTime() {
  5825. const {
  5826. tagAnchor
  5827. } = this;
  5828. if (tagAnchor === null || tagAnchor.programDateTime === null) {
  5829. logger.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${tagAnchor}`);
  5830. return NaN;
  5831. }
  5832. return tagAnchor.start + (this.startDate.getTime() - tagAnchor.programDateTime) / 1e3;
  5833. }
  5834. get startDate() {
  5835. return this._startDate;
  5836. }
  5837. get endDate() {
  5838. const dateAtEnd = this._endDate || this._dateAtEnd;
  5839. if (dateAtEnd) {
  5840. return dateAtEnd;
  5841. }
  5842. const duration = this.duration;
  5843. if (duration !== null) {
  5844. return this._dateAtEnd = new Date(this._startDate.getTime() + duration * 1e3);
  5845. }
  5846. return null;
  5847. }
  5848. get duration() {
  5849. if ("DURATION" in this.attr) {
  5850. const duration = this.attr.decimalFloatingPoint("DURATION");
  5851. if (isFiniteNumber(duration)) {
  5852. return duration;
  5853. }
  5854. } else if (this._endDate) {
  5855. return (this._endDate.getTime() - this._startDate.getTime()) / 1e3;
  5856. }
  5857. return null;
  5858. }
  5859. get plannedDuration() {
  5860. if ("PLANNED-DURATION" in this.attr) {
  5861. return this.attr.decimalFloatingPoint("PLANNED-DURATION");
  5862. }
  5863. return null;
  5864. }
  5865. get endOnNext() {
  5866. return this.attr.bool("END-ON-NEXT");
  5867. }
  5868. get isInterstitial() {
  5869. return this.class === CLASS_INTERSTITIAL;
  5870. }
  5871. get isValid() {
  5872. 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);
  5873. }
  5874. };
  5875. var DEFAULT_TARGET_DURATION = 10;
  5876. var LevelDetails = class {
  5877. constructor(baseUrl) {
  5878. this.PTSKnown = false;
  5879. this.alignedSliding = false;
  5880. this.averagetargetduration = void 0;
  5881. this.endCC = 0;
  5882. this.endSN = 0;
  5883. this.fragments = void 0;
  5884. this.fragmentHint = void 0;
  5885. this.partList = null;
  5886. this.dateRanges = void 0;
  5887. this.dateRangeTagCount = 0;
  5888. this.live = true;
  5889. this.requestScheduled = -1;
  5890. this.ageHeader = 0;
  5891. this.advancedDateTime = void 0;
  5892. this.updated = true;
  5893. this.advanced = true;
  5894. this.misses = 0;
  5895. this.startCC = 0;
  5896. this.startSN = 0;
  5897. this.startTimeOffset = null;
  5898. this.targetduration = 0;
  5899. this.totalduration = 0;
  5900. this.type = null;
  5901. this.url = void 0;
  5902. this.m3u8 = "";
  5903. this.version = null;
  5904. this.canBlockReload = false;
  5905. this.canSkipUntil = 0;
  5906. this.canSkipDateRanges = false;
  5907. this.skippedSegments = 0;
  5908. this.recentlyRemovedDateranges = void 0;
  5909. this.partHoldBack = 0;
  5910. this.holdBack = 0;
  5911. this.partTarget = 0;
  5912. this.preloadHint = void 0;
  5913. this.renditionReports = void 0;
  5914. this.tuneInGoal = 0;
  5915. this.deltaUpdateFailed = void 0;
  5916. this.driftStartTime = 0;
  5917. this.driftEndTime = 0;
  5918. this.driftStart = 0;
  5919. this.driftEnd = 0;
  5920. this.encryptedFragments = void 0;
  5921. this.playlistParsingError = null;
  5922. this.variableList = null;
  5923. this.hasVariableRefs = false;
  5924. this.appliedTimelineOffset = void 0;
  5925. this.fragments = [];
  5926. this.encryptedFragments = [];
  5927. this.dateRanges = {};
  5928. this.url = baseUrl;
  5929. }
  5930. reloaded(previous) {
  5931. if (!previous) {
  5932. this.advanced = true;
  5933. this.updated = true;
  5934. return;
  5935. }
  5936. const partSnDiff = this.lastPartSn - previous.lastPartSn;
  5937. const partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
  5938. this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff || !this.live;
  5939. this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
  5940. if (this.updated || this.advanced) {
  5941. this.misses = Math.floor(previous.misses * 0.6);
  5942. } else {
  5943. this.misses = previous.misses + 1;
  5944. }
  5945. }
  5946. hasKey(levelKey) {
  5947. return this.encryptedFragments.some((frag) => {
  5948. let decryptdata = frag.decryptdata;
  5949. if (!decryptdata) {
  5950. frag.setKeyFormat(levelKey.keyFormat);
  5951. decryptdata = frag.decryptdata;
  5952. }
  5953. return !!decryptdata && levelKey.matches(decryptdata);
  5954. });
  5955. }
  5956. get hasProgramDateTime() {
  5957. if (this.fragments.length) {
  5958. return isFiniteNumber(this.fragments[this.fragments.length - 1].programDateTime);
  5959. }
  5960. return false;
  5961. }
  5962. get levelTargetDuration() {
  5963. return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
  5964. }
  5965. get drift() {
  5966. const runTime = this.driftEndTime - this.driftStartTime;
  5967. if (runTime > 0) {
  5968. const runDuration = this.driftEnd - this.driftStart;
  5969. return runDuration * 1e3 / runTime;
  5970. }
  5971. return 1;
  5972. }
  5973. get edge() {
  5974. return this.partEnd || this.fragmentEnd;
  5975. }
  5976. get partEnd() {
  5977. var _this$partList;
  5978. if ((_this$partList = this.partList) != null && _this$partList.length) {
  5979. return this.partList[this.partList.length - 1].end;
  5980. }
  5981. return this.fragmentEnd;
  5982. }
  5983. get fragmentEnd() {
  5984. if (this.fragments.length) {
  5985. return this.fragments[this.fragments.length - 1].end;
  5986. }
  5987. return 0;
  5988. }
  5989. get fragmentStart() {
  5990. if (this.fragments.length) {
  5991. return this.fragments[0].start;
  5992. }
  5993. return 0;
  5994. }
  5995. get age() {
  5996. if (this.advancedDateTime) {
  5997. return Math.max(Date.now() - this.advancedDateTime, 0) / 1e3;
  5998. }
  5999. return 0;
  6000. }
  6001. get lastPartIndex() {
  6002. var _this$partList2;
  6003. if ((_this$partList2 = this.partList) != null && _this$partList2.length) {
  6004. return this.partList[this.partList.length - 1].index;
  6005. }
  6006. return -1;
  6007. }
  6008. get maxPartIndex() {
  6009. const partList = this.partList;
  6010. if (partList) {
  6011. const lastIndex = this.lastPartIndex;
  6012. if (lastIndex !== -1) {
  6013. for (let i = partList.length; i--; ) {
  6014. if (partList[i].index > lastIndex) {
  6015. return partList[i].index;
  6016. }
  6017. }
  6018. return lastIndex;
  6019. }
  6020. }
  6021. return 0;
  6022. }
  6023. get lastPartSn() {
  6024. var _this$partList3;
  6025. if ((_this$partList3 = this.partList) != null && _this$partList3.length) {
  6026. return this.partList[this.partList.length - 1].fragment.sn;
  6027. }
  6028. return this.endSN;
  6029. }
  6030. get expired() {
  6031. if (this.live && this.age && this.misses < 3) {
  6032. const playlistWindowDuration = this.partEnd - this.fragmentStart;
  6033. return this.age > Math.max(playlistWindowDuration, this.totalduration) + this.levelTargetDuration;
  6034. }
  6035. return false;
  6036. }
  6037. };
  6038. function arrayValuesMatch(a, b) {
  6039. if (a.length === b.length) {
  6040. return !a.some((value, i) => value !== b[i]);
  6041. }
  6042. return false;
  6043. }
  6044. function optionalArrayValuesMatch(a, b) {
  6045. if (!a && !b) {
  6046. return true;
  6047. }
  6048. if (!a || !b) {
  6049. return false;
  6050. }
  6051. return arrayValuesMatch(a, b);
  6052. }
  6053. function isFullSegmentEncryption(method) {
  6054. return method === "AES-128" || method === "AES-256" || method === "AES-256-CTR";
  6055. }
  6056. function getAesModeFromFullSegmentMethod(method) {
  6057. switch (method) {
  6058. case "AES-128":
  6059. case "AES-256":
  6060. return DecrypterAesMode.cbc;
  6061. case "AES-256-CTR":
  6062. return DecrypterAesMode.ctr;
  6063. default:
  6064. throw new Error(`invalid full segment method ${method}`);
  6065. }
  6066. }
  6067. function base64Decode(base64encodedStr) {
  6068. return Uint8Array.from(atob(base64encodedStr), (c) => c.charCodeAt(0));
  6069. }
  6070. function strToUtf8array(str) {
  6071. return Uint8Array.from(unescape(encodeURIComponent(str)), (c) => c.charCodeAt(0));
  6072. }
  6073. function getKeyIdBytes(str) {
  6074. const keyIdbytes = strToUtf8array(str).subarray(0, 16);
  6075. const paddedkeyIdbytes = new Uint8Array(16);
  6076. paddedkeyIdbytes.set(keyIdbytes, 16 - keyIdbytes.length);
  6077. return paddedkeyIdbytes;
  6078. }
  6079. function changeEndianness(keyId) {
  6080. const swap = function swap2(array, from, to) {
  6081. const cur = array[from];
  6082. array[from] = array[to];
  6083. array[to] = cur;
  6084. };
  6085. swap(keyId, 0, 3);
  6086. swap(keyId, 1, 2);
  6087. swap(keyId, 4, 5);
  6088. swap(keyId, 6, 7);
  6089. }
  6090. function convertDataUriToArrayBytes(uri) {
  6091. const colonsplit = uri.split(":");
  6092. let keydata = null;
  6093. if (colonsplit[0] === "data" && colonsplit.length === 2) {
  6094. const semicolonsplit = colonsplit[1].split(";");
  6095. const commasplit = semicolonsplit[semicolonsplit.length - 1].split(",");
  6096. if (commasplit.length === 2) {
  6097. const isbase64 = commasplit[0] === "base64";
  6098. const data = commasplit[1];
  6099. if (isbase64) {
  6100. semicolonsplit.splice(-1, 1);
  6101. keydata = base64Decode(data);
  6102. } else {
  6103. keydata = getKeyIdBytes(data);
  6104. }
  6105. }
  6106. }
  6107. return keydata;
  6108. }
  6109. var optionalSelf = typeof self !== "undefined" ? self : void 0;
  6110. var KeySystems = {
  6111. CLEARKEY: "org.w3.clearkey",
  6112. FAIRPLAY: "com.apple.fps",
  6113. PLAYREADY: "com.microsoft.playready",
  6114. WIDEVINE: "com.widevine.alpha"
  6115. };
  6116. var KeySystemFormats = {
  6117. CLEARKEY: "org.w3.clearkey",
  6118. FAIRPLAY: "com.apple.streamingkeydelivery",
  6119. PLAYREADY: "com.microsoft.playready",
  6120. WIDEVINE: "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"
  6121. };
  6122. function keySystemFormatToKeySystemDomain(format2) {
  6123. switch (format2) {
  6124. case KeySystemFormats.FAIRPLAY:
  6125. return KeySystems.FAIRPLAY;
  6126. case KeySystemFormats.PLAYREADY:
  6127. return KeySystems.PLAYREADY;
  6128. case KeySystemFormats.WIDEVINE:
  6129. return KeySystems.WIDEVINE;
  6130. case KeySystemFormats.CLEARKEY:
  6131. return KeySystems.CLEARKEY;
  6132. }
  6133. }
  6134. function keySystemDomainToKeySystemFormat(keySystem) {
  6135. switch (keySystem) {
  6136. case KeySystems.FAIRPLAY:
  6137. return KeySystemFormats.FAIRPLAY;
  6138. case KeySystems.PLAYREADY:
  6139. return KeySystemFormats.PLAYREADY;
  6140. case KeySystems.WIDEVINE:
  6141. return KeySystemFormats.WIDEVINE;
  6142. case KeySystems.CLEARKEY:
  6143. return KeySystemFormats.CLEARKEY;
  6144. }
  6145. }
  6146. function getKeySystemsForConfig(config) {
  6147. const {
  6148. drmSystems,
  6149. widevineLicenseUrl
  6150. } = config;
  6151. const keySystemsToAttempt = drmSystems ? [KeySystems.FAIRPLAY, KeySystems.WIDEVINE, KeySystems.PLAYREADY, KeySystems.CLEARKEY].filter((keySystem) => !!drmSystems[keySystem]) : [];
  6152. if (!keySystemsToAttempt[KeySystems.WIDEVINE] && widevineLicenseUrl) {
  6153. keySystemsToAttempt.push(KeySystems.WIDEVINE);
  6154. }
  6155. return keySystemsToAttempt;
  6156. }
  6157. var requestMediaKeySystemAccess = function(_optionalSelf$navigat) {
  6158. if (optionalSelf != null && (_optionalSelf$navigat = optionalSelf.navigator) != null && _optionalSelf$navigat.requestMediaKeySystemAccess) {
  6159. return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);
  6160. } else {
  6161. return null;
  6162. }
  6163. }();
  6164. function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {
  6165. let initDataTypes;
  6166. switch (keySystem) {
  6167. case KeySystems.FAIRPLAY:
  6168. initDataTypes = ["cenc", "sinf"];
  6169. break;
  6170. case KeySystems.WIDEVINE:
  6171. case KeySystems.PLAYREADY:
  6172. initDataTypes = ["cenc"];
  6173. break;
  6174. case KeySystems.CLEARKEY:
  6175. initDataTypes = ["cenc", "keyids"];
  6176. break;
  6177. default:
  6178. throw new Error(`Unknown key-system: ${keySystem}`);
  6179. }
  6180. return createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions);
  6181. }
  6182. function createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions) {
  6183. const baseConfig = {
  6184. initDataTypes,
  6185. persistentState: drmSystemOptions.persistentState || "optional",
  6186. distinctiveIdentifier: drmSystemOptions.distinctiveIdentifier || "optional",
  6187. sessionTypes: drmSystemOptions.sessionTypes || [drmSystemOptions.sessionType || "temporary"],
  6188. audioCapabilities: audioCodecs.map((codec) => ({
  6189. contentType: `audio/mp4; codecs=${codec}`,
  6190. robustness: drmSystemOptions.audioRobustness || "",
  6191. encryptionScheme: drmSystemOptions.audioEncryptionScheme || null
  6192. })),
  6193. videoCapabilities: videoCodecs.map((codec) => ({
  6194. contentType: `video/mp4; codecs=${codec}`,
  6195. robustness: drmSystemOptions.videoRobustness || "",
  6196. encryptionScheme: drmSystemOptions.videoEncryptionScheme || null
  6197. }))
  6198. };
  6199. return [baseConfig];
  6200. }
  6201. function isPersistentSessionType(drmSystemOptions) {
  6202. var _drmSystemOptions$ses;
  6203. return !!drmSystemOptions && (drmSystemOptions.sessionType === "persistent-license" || !!((_drmSystemOptions$ses = drmSystemOptions.sessionTypes) != null && _drmSystemOptions$ses.some((type) => type === "persistent-license")));
  6204. }
  6205. function parsePlayReadyWRM(keyBytes) {
  6206. const keyBytesUtf16 = new Uint16Array(keyBytes.buffer, keyBytes.byteOffset, keyBytes.byteLength / 2);
  6207. const keyByteStr = String.fromCharCode.apply(null, Array.from(keyBytesUtf16));
  6208. const xmlKeyBytes = keyByteStr.substring(keyByteStr.indexOf("<"), keyByteStr.length);
  6209. const parser = new DOMParser();
  6210. const xmlDoc = parser.parseFromString(xmlKeyBytes, "text/xml");
  6211. const keyData = xmlDoc.getElementsByTagName("KID")[0];
  6212. if (keyData) {
  6213. const keyId = keyData.childNodes[0] ? keyData.childNodes[0].nodeValue : keyData.getAttribute("VALUE");
  6214. if (keyId) {
  6215. const keyIdArray = base64Decode(keyId).subarray(0, 16);
  6216. changeEndianness(keyIdArray);
  6217. return keyIdArray;
  6218. }
  6219. }
  6220. return null;
  6221. }
  6222. var keyUriToKeyIdMap = {};
  6223. var LevelKey = class _LevelKey {
  6224. static clearKeyUriToKeyIdMap() {
  6225. keyUriToKeyIdMap = {};
  6226. }
  6227. static setKeyIdForUri(uri, keyId) {
  6228. keyUriToKeyIdMap[uri] = keyId;
  6229. }
  6230. constructor(method, uri, format2, formatversions = [1], iv = null, keyId) {
  6231. this.uri = void 0;
  6232. this.method = void 0;
  6233. this.keyFormat = void 0;
  6234. this.keyFormatVersions = void 0;
  6235. this.encrypted = void 0;
  6236. this.isCommonEncryption = void 0;
  6237. this.iv = null;
  6238. this.key = null;
  6239. this.keyId = null;
  6240. this.pssh = null;
  6241. this.method = method;
  6242. this.uri = uri;
  6243. this.keyFormat = format2;
  6244. this.keyFormatVersions = formatversions;
  6245. this.iv = iv;
  6246. this.encrypted = method ? method !== "NONE" : false;
  6247. this.isCommonEncryption = this.encrypted && !isFullSegmentEncryption(method);
  6248. if (keyId != null && keyId.startsWith("0x")) {
  6249. this.keyId = new Uint8Array(hexToArrayBuffer(keyId));
  6250. }
  6251. }
  6252. matches(key) {
  6253. return key.uri === this.uri && key.method === this.method && key.encrypted === this.encrypted && key.keyFormat === this.keyFormat && arrayValuesMatch(key.keyFormatVersions, this.keyFormatVersions) && optionalArrayValuesMatch(key.iv, this.iv) && optionalArrayValuesMatch(key.keyId, this.keyId);
  6254. }
  6255. isSupported() {
  6256. if (this.method) {
  6257. if (isFullSegmentEncryption(this.method) || this.method === "NONE") {
  6258. return true;
  6259. }
  6260. if (this.keyFormat === "identity") {
  6261. return this.method === "SAMPLE-AES";
  6262. } else {
  6263. switch (this.keyFormat) {
  6264. case KeySystemFormats.FAIRPLAY:
  6265. case KeySystemFormats.WIDEVINE:
  6266. case KeySystemFormats.PLAYREADY:
  6267. case KeySystemFormats.CLEARKEY:
  6268. return ["SAMPLE-AES", "SAMPLE-AES-CENC", "SAMPLE-AES-CTR"].indexOf(this.method) !== -1;
  6269. }
  6270. }
  6271. }
  6272. return false;
  6273. }
  6274. getDecryptData(sn, levelKeys) {
  6275. if (!this.encrypted || !this.uri) {
  6276. return null;
  6277. }
  6278. if (isFullSegmentEncryption(this.method)) {
  6279. let iv = this.iv;
  6280. if (!iv) {
  6281. if (typeof sn !== "number") {
  6282. logger.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`);
  6283. sn = 0;
  6284. }
  6285. iv = createInitializationVector(sn);
  6286. }
  6287. const decryptdata = new _LevelKey(this.method, this.uri, "identity", this.keyFormatVersions, iv);
  6288. return decryptdata;
  6289. }
  6290. if (this.keyId) {
  6291. const assignedKeyId = keyUriToKeyIdMap[this.uri];
  6292. if (assignedKeyId && !arrayValuesMatch(this.keyId, assignedKeyId)) {
  6293. _LevelKey.setKeyIdForUri(this.uri, this.keyId);
  6294. }
  6295. if (this.pssh) {
  6296. return this;
  6297. }
  6298. }
  6299. const keyBytes = convertDataUriToArrayBytes(this.uri);
  6300. if (keyBytes) {
  6301. switch (this.keyFormat) {
  6302. case KeySystemFormats.WIDEVINE:
  6303. this.pssh = keyBytes;
  6304. if (!this.keyId) {
  6305. const results = parseMultiPssh(keyBytes.buffer);
  6306. if (results.length) {
  6307. var _psshData$kids;
  6308. const psshData = results[0];
  6309. this.keyId = (_psshData$kids = psshData.kids) != null && _psshData$kids.length ? psshData.kids[0] : null;
  6310. }
  6311. }
  6312. if (!this.keyId) {
  6313. this.keyId = getKeyIdFromPlayReadyKey(levelKeys);
  6314. }
  6315. break;
  6316. case KeySystemFormats.PLAYREADY: {
  6317. const PlayReadyKeySystemUUID = new Uint8Array([154, 4, 240, 121, 152, 64, 66, 134, 171, 146, 230, 91, 224, 136, 95, 149]);
  6318. this.pssh = mp4pssh(PlayReadyKeySystemUUID, null, keyBytes);
  6319. this.keyId = parsePlayReadyWRM(keyBytes);
  6320. break;
  6321. }
  6322. default: {
  6323. let keydata = keyBytes.subarray(0, 16);
  6324. if (keydata.length !== 16) {
  6325. const padded = new Uint8Array(16);
  6326. padded.set(keydata, 16 - keydata.length);
  6327. keydata = padded;
  6328. }
  6329. this.keyId = keydata;
  6330. break;
  6331. }
  6332. }
  6333. }
  6334. if (!this.keyId || this.keyId.byteLength !== 16) {
  6335. let keyId;
  6336. keyId = getKeyIdFromWidevineKey(levelKeys);
  6337. if (!keyId) {
  6338. keyId = getKeyIdFromPlayReadyKey(levelKeys);
  6339. if (!keyId) {
  6340. keyId = keyUriToKeyIdMap[this.uri];
  6341. }
  6342. }
  6343. if (keyId) {
  6344. this.keyId = keyId;
  6345. _LevelKey.setKeyIdForUri(this.uri, keyId);
  6346. }
  6347. }
  6348. return this;
  6349. }
  6350. };
  6351. function getKeyIdFromWidevineKey(levelKeys) {
  6352. const widevineKey = levelKeys == null ? void 0 : levelKeys[KeySystemFormats.WIDEVINE];
  6353. if (widevineKey) {
  6354. return widevineKey.keyId;
  6355. }
  6356. return null;
  6357. }
  6358. function getKeyIdFromPlayReadyKey(levelKeys) {
  6359. const playReadyKey = levelKeys == null ? void 0 : levelKeys[KeySystemFormats.PLAYREADY];
  6360. if (playReadyKey) {
  6361. const playReadyKeyBytes = convertDataUriToArrayBytes(playReadyKey.uri);
  6362. if (playReadyKeyBytes) {
  6363. return parsePlayReadyWRM(playReadyKeyBytes);
  6364. }
  6365. }
  6366. return null;
  6367. }
  6368. function createInitializationVector(segmentNumber) {
  6369. const uint8View = new Uint8Array(16);
  6370. for (let i = 12; i < 16; i++) {
  6371. uint8View[i] = segmentNumber >> 8 * (15 - i) & 255;
  6372. }
  6373. return uint8View;
  6374. }
  6375. 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;
  6376. var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  6377. var IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m;
  6378. var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([
  6379. /#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,
  6380. // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  6381. /(?!#) *(\S[^\r\n]*)/.source,
  6382. // segment URI, group 3 => the URI (note newline is not eaten)
  6383. /#.*/.source
  6384. // All other non-segment oriented tags will match with all groups empty
  6385. ].join("|"), "g");
  6386. 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("|"));
  6387. var M3U8Parser = class _M3U8Parser {
  6388. static findGroup(groups, mediaGroupId) {
  6389. for (let i = 0; i < groups.length; i++) {
  6390. const group = groups[i];
  6391. if (group.id === mediaGroupId) {
  6392. return group;
  6393. }
  6394. }
  6395. }
  6396. static resolve(url, baseUrl) {
  6397. return urlToolkitExports.buildAbsoluteURL(baseUrl, url, {
  6398. alwaysNormalize: true
  6399. });
  6400. }
  6401. static isMediaPlaylist(str) {
  6402. return IS_MEDIA_PLAYLIST.test(str);
  6403. }
  6404. static parseMasterPlaylist(string, baseurl) {
  6405. const hasVariableRefs = hasVariableReferences(string);
  6406. const parsed = {
  6407. contentSteering: null,
  6408. levels: [],
  6409. playlistParsingError: null,
  6410. sessionData: null,
  6411. sessionKeys: null,
  6412. startTimeOffset: null,
  6413. variableList: null,
  6414. hasVariableRefs
  6415. };
  6416. const levelsWithKnownCodecs = [];
  6417. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  6418. if (!string.startsWith("#EXTM3U")) {
  6419. parsed.playlistParsingError = new Error("no EXTM3U delimiter");
  6420. return parsed;
  6421. }
  6422. let result;
  6423. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  6424. if (result[1]) {
  6425. var _level$unknownCodecs;
  6426. const attrs = new AttrList(result[1], parsed);
  6427. const uri = substituteVariables(parsed, result[2]);
  6428. const level = {
  6429. attrs,
  6430. bitrate: attrs.decimalInteger("BANDWIDTH") || attrs.decimalInteger("AVERAGE-BANDWIDTH"),
  6431. name: attrs.NAME,
  6432. url: _M3U8Parser.resolve(uri, baseurl)
  6433. };
  6434. const resolution = attrs.decimalResolution("RESOLUTION");
  6435. if (resolution) {
  6436. level.width = resolution.width;
  6437. level.height = resolution.height;
  6438. }
  6439. setCodecs(attrs.CODECS, level);
  6440. const supplementalCodecs = attrs["SUPPLEMENTAL-CODECS"];
  6441. if (supplementalCodecs) {
  6442. level.supplemental = {};
  6443. setCodecs(supplementalCodecs, level.supplemental);
  6444. }
  6445. if (!((_level$unknownCodecs = level.unknownCodecs) != null && _level$unknownCodecs.length)) {
  6446. levelsWithKnownCodecs.push(level);
  6447. }
  6448. parsed.levels.push(level);
  6449. } else if (result[3]) {
  6450. const tag = result[3];
  6451. const attributes = result[4];
  6452. switch (tag) {
  6453. case "SESSION-DATA": {
  6454. const sessionAttrs = new AttrList(attributes, parsed);
  6455. const dataId = sessionAttrs["DATA-ID"];
  6456. if (dataId) {
  6457. if (parsed.sessionData === null) {
  6458. parsed.sessionData = {};
  6459. }
  6460. parsed.sessionData[dataId] = sessionAttrs;
  6461. }
  6462. break;
  6463. }
  6464. case "SESSION-KEY": {
  6465. const sessionKey = parseKey(attributes, baseurl, parsed);
  6466. if (sessionKey.encrypted && sessionKey.isSupported()) {
  6467. if (parsed.sessionKeys === null) {
  6468. parsed.sessionKeys = [];
  6469. }
  6470. parsed.sessionKeys.push(sessionKey);
  6471. } else {
  6472. logger.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${attributes}"`);
  6473. }
  6474. break;
  6475. }
  6476. case "DEFINE": {
  6477. {
  6478. const variableAttributes = new AttrList(attributes, parsed);
  6479. addVariableDefinition(parsed, variableAttributes, baseurl);
  6480. }
  6481. break;
  6482. }
  6483. case "CONTENT-STEERING": {
  6484. const contentSteeringAttributes = new AttrList(attributes, parsed);
  6485. parsed.contentSteering = {
  6486. uri: _M3U8Parser.resolve(contentSteeringAttributes["SERVER-URI"], baseurl),
  6487. pathwayId: contentSteeringAttributes["PATHWAY-ID"] || "."
  6488. };
  6489. break;
  6490. }
  6491. case "START": {
  6492. parsed.startTimeOffset = parseStartTimeOffset(attributes);
  6493. break;
  6494. }
  6495. }
  6496. }
  6497. }
  6498. const stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < parsed.levels.length;
  6499. parsed.levels = stripUnknownCodecLevels ? levelsWithKnownCodecs : parsed.levels;
  6500. if (parsed.levels.length === 0) {
  6501. parsed.playlistParsingError = new Error("no levels found in manifest");
  6502. }
  6503. return parsed;
  6504. }
  6505. static parseMasterPlaylistMedia(string, baseurl, parsed) {
  6506. let result;
  6507. const results = {};
  6508. const levels = parsed.levels;
  6509. const groupsByType = {
  6510. AUDIO: levels.map((level) => ({
  6511. id: level.attrs.AUDIO,
  6512. audioCodec: level.audioCodec
  6513. })),
  6514. SUBTITLES: levels.map((level) => ({
  6515. id: level.attrs.SUBTITLES,
  6516. textCodec: level.textCodec
  6517. })),
  6518. "CLOSED-CAPTIONS": []
  6519. };
  6520. let id = 0;
  6521. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  6522. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  6523. const attrs = new AttrList(result[1], parsed);
  6524. const type = attrs.TYPE;
  6525. if (type) {
  6526. const groups = groupsByType[type];
  6527. const medias = results[type] || [];
  6528. results[type] = medias;
  6529. const lang = attrs.LANGUAGE;
  6530. const assocLang = attrs["ASSOC-LANGUAGE"];
  6531. const channels = attrs.CHANNELS;
  6532. const characteristics = attrs.CHARACTERISTICS;
  6533. const instreamId = attrs["INSTREAM-ID"];
  6534. const media = {
  6535. attrs,
  6536. bitrate: 0,
  6537. id: id++,
  6538. groupId: attrs["GROUP-ID"] || "",
  6539. name: attrs.NAME || lang || "",
  6540. type,
  6541. default: attrs.bool("DEFAULT"),
  6542. autoselect: attrs.bool("AUTOSELECT"),
  6543. forced: attrs.bool("FORCED"),
  6544. lang,
  6545. url: attrs.URI ? _M3U8Parser.resolve(attrs.URI, baseurl) : ""
  6546. };
  6547. if (assocLang) {
  6548. media.assocLang = assocLang;
  6549. }
  6550. if (channels) {
  6551. media.channels = channels;
  6552. }
  6553. if (characteristics) {
  6554. media.characteristics = characteristics;
  6555. }
  6556. if (instreamId) {
  6557. media.instreamId = instreamId;
  6558. }
  6559. if (groups != null && groups.length) {
  6560. const groupCodec = _M3U8Parser.findGroup(groups, media.groupId) || groups[0];
  6561. assignCodec(media, groupCodec, "audioCodec");
  6562. assignCodec(media, groupCodec, "textCodec");
  6563. }
  6564. medias.push(media);
  6565. }
  6566. }
  6567. return results;
  6568. }
  6569. static parseLevelPlaylist(string, baseurl, id, type, levelUrlId, multivariantVariableList) {
  6570. var _LEVEL_PLAYLIST_REGEX;
  6571. const base = {
  6572. url: baseurl
  6573. };
  6574. const level = new LevelDetails(baseurl);
  6575. const fragments = level.fragments;
  6576. const programDateTimes = [];
  6577. let currentInitSegment = null;
  6578. let currentSN = 0;
  6579. let currentPart = 0;
  6580. let totalduration = 0;
  6581. let discontinuityCounter = 0;
  6582. let currentBitrate = 0;
  6583. let prevFrag = null;
  6584. let frag = new Fragment(type, base);
  6585. let result;
  6586. let i;
  6587. let levelkeys;
  6588. let firstPdtIndex = -1;
  6589. let createNextFrag = false;
  6590. let nextByteRange = null;
  6591. let serverControlAttrs;
  6592. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  6593. level.m3u8 = string;
  6594. level.hasVariableRefs = hasVariableReferences(string);
  6595. if (((_LEVEL_PLAYLIST_REGEX = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) == null ? void 0 : _LEVEL_PLAYLIST_REGEX[0]) !== "#EXTM3U") {
  6596. level.playlistParsingError = new Error("Missing format identifier #EXTM3U");
  6597. return level;
  6598. }
  6599. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  6600. if (createNextFrag) {
  6601. createNextFrag = false;
  6602. frag = new Fragment(type, base);
  6603. frag.playlistOffset = totalduration;
  6604. frag.setStart(totalduration);
  6605. frag.sn = currentSN;
  6606. frag.cc = discontinuityCounter;
  6607. if (currentBitrate) {
  6608. frag.bitrate = currentBitrate;
  6609. }
  6610. frag.level = id;
  6611. if (currentInitSegment) {
  6612. frag.initSegment = currentInitSegment;
  6613. if (currentInitSegment.rawProgramDateTime) {
  6614. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  6615. currentInitSegment.rawProgramDateTime = null;
  6616. }
  6617. if (nextByteRange) {
  6618. frag.setByteRange(nextByteRange);
  6619. nextByteRange = null;
  6620. }
  6621. }
  6622. }
  6623. const duration = result[1];
  6624. if (duration) {
  6625. frag.duration = parseFloat(duration);
  6626. const title = (" " + result[2]).slice(1);
  6627. frag.title = title || null;
  6628. frag.tagList.push(title ? ["INF", duration, title] : ["INF", duration]);
  6629. } else if (result[3]) {
  6630. if (isFiniteNumber(frag.duration)) {
  6631. frag.playlistOffset = totalduration;
  6632. frag.setStart(totalduration);
  6633. if (levelkeys) {
  6634. setFragLevelKeys(frag, levelkeys, level);
  6635. }
  6636. frag.sn = currentSN;
  6637. frag.level = id;
  6638. frag.cc = discontinuityCounter;
  6639. fragments.push(frag);
  6640. const uri = (" " + result[3]).slice(1);
  6641. frag.relurl = substituteVariables(level, uri);
  6642. assignProgramDateTime(frag, prevFrag, programDateTimes);
  6643. prevFrag = frag;
  6644. totalduration += frag.duration;
  6645. currentSN++;
  6646. currentPart = 0;
  6647. createNextFrag = true;
  6648. }
  6649. } else {
  6650. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  6651. if (!result) {
  6652. logger.warn("No matches on slow regex match for level playlist!");
  6653. continue;
  6654. }
  6655. for (i = 1; i < result.length; i++) {
  6656. if (result[i] !== void 0) {
  6657. break;
  6658. }
  6659. }
  6660. const tag = (" " + result[i]).slice(1);
  6661. const value1 = (" " + result[i + 1]).slice(1);
  6662. const value2 = result[i + 2] ? (" " + result[i + 2]).slice(1) : null;
  6663. switch (tag) {
  6664. case "BYTERANGE":
  6665. if (prevFrag) {
  6666. frag.setByteRange(value1, prevFrag);
  6667. } else {
  6668. frag.setByteRange(value1);
  6669. }
  6670. break;
  6671. case "PROGRAM-DATE-TIME":
  6672. frag.rawProgramDateTime = value1;
  6673. frag.tagList.push(["PROGRAM-DATE-TIME", value1]);
  6674. if (firstPdtIndex === -1) {
  6675. firstPdtIndex = fragments.length;
  6676. }
  6677. break;
  6678. case "PLAYLIST-TYPE":
  6679. if (level.type) {
  6680. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6681. }
  6682. level.type = value1.toUpperCase();
  6683. break;
  6684. case "MEDIA-SEQUENCE":
  6685. if (level.startSN !== 0) {
  6686. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6687. } else if (fragments.length > 0) {
  6688. assignMustAppearBeforeSegmentsError(level, tag, result);
  6689. }
  6690. currentSN = level.startSN = parseInt(value1);
  6691. break;
  6692. case "SKIP": {
  6693. if (level.skippedSegments) {
  6694. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6695. }
  6696. const skipAttrs = new AttrList(value1, level);
  6697. const skippedSegments = skipAttrs.decimalInteger("SKIPPED-SEGMENTS");
  6698. if (isFiniteNumber(skippedSegments)) {
  6699. level.skippedSegments += skippedSegments;
  6700. for (let _i = skippedSegments; _i--; ) {
  6701. fragments.push(null);
  6702. }
  6703. currentSN += skippedSegments;
  6704. }
  6705. const recentlyRemovedDateranges = skipAttrs.enumeratedString("RECENTLY-REMOVED-DATERANGES");
  6706. if (recentlyRemovedDateranges) {
  6707. level.recentlyRemovedDateranges = (level.recentlyRemovedDateranges || []).concat(recentlyRemovedDateranges.split(" "));
  6708. }
  6709. break;
  6710. }
  6711. case "TARGETDURATION":
  6712. if (level.targetduration !== 0) {
  6713. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6714. }
  6715. level.targetduration = Math.max(parseInt(value1), 1);
  6716. break;
  6717. case "VERSION":
  6718. if (level.version !== null) {
  6719. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6720. }
  6721. level.version = parseInt(value1);
  6722. break;
  6723. case "INDEPENDENT-SEGMENTS":
  6724. break;
  6725. case "ENDLIST":
  6726. if (!level.live) {
  6727. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6728. }
  6729. level.live = false;
  6730. break;
  6731. case "#":
  6732. if (value1 || value2) {
  6733. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  6734. }
  6735. break;
  6736. case "DISCONTINUITY":
  6737. discontinuityCounter++;
  6738. frag.tagList.push(["DIS"]);
  6739. break;
  6740. case "GAP":
  6741. frag.gap = true;
  6742. frag.tagList.push([tag]);
  6743. break;
  6744. case "BITRATE":
  6745. frag.tagList.push([tag, value1]);
  6746. currentBitrate = parseInt(value1) * 1e3;
  6747. if (isFiniteNumber(currentBitrate)) {
  6748. frag.bitrate = currentBitrate;
  6749. } else {
  6750. currentBitrate = 0;
  6751. }
  6752. break;
  6753. case "DATERANGE": {
  6754. const dateRangeAttr = new AttrList(value1, level);
  6755. const dateRange = new DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID], level.dateRangeTagCount);
  6756. level.dateRangeTagCount++;
  6757. if (dateRange.isValid || level.skippedSegments) {
  6758. level.dateRanges[dateRange.id] = dateRange;
  6759. } else {
  6760. logger.warn(`Ignoring invalid DATERANGE tag: "${value1}"`);
  6761. }
  6762. frag.tagList.push(["EXT-X-DATERANGE", value1]);
  6763. break;
  6764. }
  6765. case "DEFINE": {
  6766. {
  6767. const variableAttributes = new AttrList(value1, level);
  6768. if ("IMPORT" in variableAttributes) {
  6769. importVariableDefinition(level, variableAttributes, multivariantVariableList);
  6770. } else {
  6771. addVariableDefinition(level, variableAttributes, baseurl);
  6772. }
  6773. }
  6774. break;
  6775. }
  6776. case "DISCONTINUITY-SEQUENCE":
  6777. if (level.startCC !== 0) {
  6778. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6779. } else if (fragments.length > 0) {
  6780. assignMustAppearBeforeSegmentsError(level, tag, result);
  6781. }
  6782. level.startCC = discontinuityCounter = parseInt(value1);
  6783. break;
  6784. case "KEY": {
  6785. const levelKey = parseKey(value1, baseurl, level);
  6786. if (levelKey.isSupported()) {
  6787. if (levelKey.method === "NONE") {
  6788. levelkeys = void 0;
  6789. break;
  6790. }
  6791. if (!levelkeys) {
  6792. levelkeys = {};
  6793. }
  6794. const currentKey = levelkeys[levelKey.keyFormat];
  6795. if (!(currentKey != null && currentKey.matches(levelKey))) {
  6796. if (currentKey) {
  6797. levelkeys = _extends({}, levelkeys);
  6798. }
  6799. levelkeys[levelKey.keyFormat] = levelKey;
  6800. }
  6801. } else {
  6802. logger.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${value1}"${""}`);
  6803. }
  6804. break;
  6805. }
  6806. case "START":
  6807. level.startTimeOffset = parseStartTimeOffset(value1);
  6808. break;
  6809. case "MAP": {
  6810. const mapAttrs = new AttrList(value1, level);
  6811. if (frag.duration) {
  6812. const init = new Fragment(type, base);
  6813. setInitSegment(init, mapAttrs, id, levelkeys);
  6814. currentInitSegment = init;
  6815. frag.initSegment = currentInitSegment;
  6816. if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) {
  6817. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  6818. }
  6819. } else {
  6820. const end = frag.byteRangeEndOffset;
  6821. if (end) {
  6822. const start = frag.byteRangeStartOffset;
  6823. nextByteRange = `${end - start}@${start}`;
  6824. } else {
  6825. nextByteRange = null;
  6826. }
  6827. setInitSegment(frag, mapAttrs, id, levelkeys);
  6828. currentInitSegment = frag;
  6829. createNextFrag = true;
  6830. }
  6831. currentInitSegment.cc = discontinuityCounter;
  6832. break;
  6833. }
  6834. case "SERVER-CONTROL": {
  6835. if (serverControlAttrs) {
  6836. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6837. }
  6838. serverControlAttrs = new AttrList(value1);
  6839. level.canBlockReload = serverControlAttrs.bool("CAN-BLOCK-RELOAD");
  6840. level.canSkipUntil = serverControlAttrs.optionalFloat("CAN-SKIP-UNTIL", 0);
  6841. level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool("CAN-SKIP-DATERANGES");
  6842. level.partHoldBack = serverControlAttrs.optionalFloat("PART-HOLD-BACK", 0);
  6843. level.holdBack = serverControlAttrs.optionalFloat("HOLD-BACK", 0);
  6844. break;
  6845. }
  6846. case "PART-INF": {
  6847. if (level.partTarget) {
  6848. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  6849. }
  6850. const partInfAttrs = new AttrList(value1);
  6851. level.partTarget = partInfAttrs.decimalFloatingPoint("PART-TARGET");
  6852. break;
  6853. }
  6854. case "PART": {
  6855. let partList = level.partList;
  6856. if (!partList) {
  6857. partList = level.partList = [];
  6858. }
  6859. const previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : void 0;
  6860. const index = currentPart++;
  6861. const partAttrs = new AttrList(value1, level);
  6862. const part = new Part(partAttrs, frag, base, index, previousFragmentPart);
  6863. partList.push(part);
  6864. frag.duration += part.duration;
  6865. break;
  6866. }
  6867. case "PRELOAD-HINT": {
  6868. const preloadHintAttrs = new AttrList(value1, level);
  6869. level.preloadHint = preloadHintAttrs;
  6870. break;
  6871. }
  6872. case "RENDITION-REPORT": {
  6873. const renditionReportAttrs = new AttrList(value1, level);
  6874. level.renditionReports = level.renditionReports || [];
  6875. level.renditionReports.push(renditionReportAttrs);
  6876. break;
  6877. }
  6878. default:
  6879. logger.warn(`line parsed but not handled: ${result}`);
  6880. break;
  6881. }
  6882. }
  6883. }
  6884. if (prevFrag && !prevFrag.relurl) {
  6885. fragments.pop();
  6886. totalduration -= prevFrag.duration;
  6887. if (level.partList) {
  6888. level.fragmentHint = prevFrag;
  6889. }
  6890. } else if (level.partList) {
  6891. assignProgramDateTime(frag, prevFrag, programDateTimes);
  6892. frag.cc = discontinuityCounter;
  6893. level.fragmentHint = frag;
  6894. if (levelkeys) {
  6895. setFragLevelKeys(frag, levelkeys, level);
  6896. }
  6897. }
  6898. if (!level.targetduration) {
  6899. level.playlistParsingError = new Error(`Missing Target Duration`);
  6900. }
  6901. const fragmentLength = fragments.length;
  6902. const firstFragment = fragments[0];
  6903. const lastFragment = fragments[fragmentLength - 1];
  6904. totalduration += level.skippedSegments * level.targetduration;
  6905. if (totalduration > 0 && fragmentLength && lastFragment) {
  6906. level.averagetargetduration = totalduration / fragmentLength;
  6907. const lastSn = lastFragment.sn;
  6908. level.endSN = lastSn !== "initSegment" ? lastSn : 0;
  6909. if (!level.live) {
  6910. lastFragment.endList = true;
  6911. }
  6912. if (firstPdtIndex > 0) {
  6913. backfillProgramDateTimes(fragments, firstPdtIndex);
  6914. if (firstFragment) {
  6915. programDateTimes.unshift(firstFragment);
  6916. }
  6917. }
  6918. }
  6919. if (level.fragmentHint) {
  6920. totalduration += level.fragmentHint.duration;
  6921. }
  6922. level.totalduration = totalduration;
  6923. if (programDateTimes.length && level.dateRangeTagCount && firstFragment) {
  6924. mapDateRanges(programDateTimes, level);
  6925. }
  6926. level.endCC = discontinuityCounter;
  6927. return level;
  6928. }
  6929. };
  6930. function mapDateRanges(programDateTimes, details) {
  6931. let programDateTimeCount = programDateTimes.length;
  6932. if (!programDateTimeCount) {
  6933. if (details.hasProgramDateTime) {
  6934. const lastFragment = details.fragments[details.fragments.length - 1];
  6935. programDateTimes.push(lastFragment);
  6936. programDateTimeCount++;
  6937. } else {
  6938. return;
  6939. }
  6940. }
  6941. const lastProgramDateTime = programDateTimes[programDateTimeCount - 1];
  6942. const playlistEnd = details.live ? Infinity : details.totalduration;
  6943. const dateRangeIds = Object.keys(details.dateRanges);
  6944. for (let i = dateRangeIds.length; i--; ) {
  6945. const dateRange = details.dateRanges[dateRangeIds[i]];
  6946. const startDateTime = dateRange.startDate.getTime();
  6947. dateRange.tagAnchor = lastProgramDateTime.ref;
  6948. for (let j = programDateTimeCount; j--; ) {
  6949. var _programDateTimes$j;
  6950. if (((_programDateTimes$j = programDateTimes[j]) == null ? void 0 : _programDateTimes$j.sn) < details.startSN) {
  6951. break;
  6952. }
  6953. const fragIndex = findFragmentWithStartDate(details, startDateTime, programDateTimes, j, playlistEnd);
  6954. if (fragIndex !== -1) {
  6955. dateRange.tagAnchor = details.fragments[fragIndex].ref;
  6956. break;
  6957. }
  6958. }
  6959. }
  6960. }
  6961. function findFragmentWithStartDate(details, startDateTime, programDateTimes, index, endTime) {
  6962. const pdtFragment = programDateTimes[index];
  6963. if (pdtFragment) {
  6964. const pdtStart = pdtFragment.programDateTime;
  6965. if (startDateTime >= pdtStart || index === 0) {
  6966. var _programDateTimes;
  6967. const durationBetweenPdt = (((_programDateTimes = programDateTimes[index + 1]) == null ? void 0 : _programDateTimes.start) || endTime) - pdtFragment.start;
  6968. if (startDateTime <= pdtStart + durationBetweenPdt * 1e3) {
  6969. const startIndex = programDateTimes[index].sn - details.startSN;
  6970. if (startIndex < 0) {
  6971. return -1;
  6972. }
  6973. const fragments = details.fragments;
  6974. if (fragments.length > programDateTimes.length) {
  6975. const endSegment = programDateTimes[index + 1] || fragments[fragments.length - 1];
  6976. const endIndex = endSegment.sn - details.startSN;
  6977. for (let i = endIndex; i > startIndex; i--) {
  6978. const fragStartDateTime = fragments[i].programDateTime;
  6979. if (startDateTime >= fragStartDateTime && startDateTime < fragStartDateTime + fragments[i].duration * 1e3) {
  6980. return i;
  6981. }
  6982. }
  6983. }
  6984. return startIndex;
  6985. }
  6986. }
  6987. }
  6988. return -1;
  6989. }
  6990. function parseKey(keyTagAttributes, baseurl, parsed) {
  6991. var _keyAttrs$METHOD, _keyAttrs$KEYFORMAT;
  6992. const keyAttrs = new AttrList(keyTagAttributes, parsed);
  6993. const decryptmethod = (_keyAttrs$METHOD = keyAttrs.METHOD) != null ? _keyAttrs$METHOD : "";
  6994. const decrypturi = keyAttrs.URI;
  6995. const decryptiv = keyAttrs.hexadecimalInteger("IV");
  6996. const decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;
  6997. const decryptkeyformat = (_keyAttrs$KEYFORMAT = keyAttrs.KEYFORMAT) != null ? _keyAttrs$KEYFORMAT : "identity";
  6998. if (decrypturi && keyAttrs.IV && !decryptiv) {
  6999. logger.error(`Invalid IV: ${keyAttrs.IV}`);
  7000. }
  7001. const resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : "";
  7002. const keyFormatVersions = (decryptkeyformatversions ? decryptkeyformatversions : "1").split("/").map(Number).filter(Number.isFinite);
  7003. return new LevelKey(decryptmethod, resolvedUri, decryptkeyformat, keyFormatVersions, decryptiv, keyAttrs.KEYID);
  7004. }
  7005. function parseStartTimeOffset(startAttributes) {
  7006. const startAttrs = new AttrList(startAttributes);
  7007. const startTimeOffset = startAttrs.decimalFloatingPoint("TIME-OFFSET");
  7008. if (isFiniteNumber(startTimeOffset)) {
  7009. return startTimeOffset;
  7010. }
  7011. return null;
  7012. }
  7013. function setCodecs(codecsAttributeValue, level) {
  7014. let codecs = (codecsAttributeValue || "").split(/[ ,]+/).filter((c) => c);
  7015. ["video", "audio", "text"].forEach((type) => {
  7016. const filtered = codecs.filter((codec) => isCodecType(codec, type));
  7017. if (filtered.length) {
  7018. level[`${type}Codec`] = filtered.map((c) => c.split("/")[0]).join(",");
  7019. codecs = codecs.filter((codec) => filtered.indexOf(codec) === -1);
  7020. }
  7021. });
  7022. level.unknownCodecs = codecs;
  7023. }
  7024. function assignCodec(media, groupItem, codecProperty) {
  7025. const codecValue = groupItem[codecProperty];
  7026. if (codecValue) {
  7027. media[codecProperty] = codecValue;
  7028. }
  7029. }
  7030. function backfillProgramDateTimes(fragments, firstPdtIndex) {
  7031. let fragPrev = fragments[firstPdtIndex];
  7032. for (let i = firstPdtIndex; i--; ) {
  7033. const frag = fragments[i];
  7034. if (!frag) {
  7035. return;
  7036. }
  7037. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1e3;
  7038. fragPrev = frag;
  7039. }
  7040. }
  7041. function assignProgramDateTime(frag, prevFrag, programDateTimes) {
  7042. if (frag.rawProgramDateTime) {
  7043. programDateTimes.push(frag);
  7044. } else if (prevFrag != null && prevFrag.programDateTime) {
  7045. frag.programDateTime = prevFrag.endProgramDateTime;
  7046. }
  7047. }
  7048. function setInitSegment(frag, mapAttrs, id, levelkeys) {
  7049. frag.relurl = mapAttrs.URI;
  7050. if (mapAttrs.BYTERANGE) {
  7051. frag.setByteRange(mapAttrs.BYTERANGE);
  7052. }
  7053. frag.level = id;
  7054. frag.sn = "initSegment";
  7055. if (levelkeys) {
  7056. frag.levelkeys = levelkeys;
  7057. }
  7058. frag.initSegment = null;
  7059. }
  7060. function setFragLevelKeys(frag, levelkeys, level) {
  7061. frag.levelkeys = levelkeys;
  7062. const {
  7063. encryptedFragments
  7064. } = level;
  7065. if ((!encryptedFragments.length || encryptedFragments[encryptedFragments.length - 1].levelkeys !== levelkeys) && Object.keys(levelkeys).some((format2) => levelkeys[format2].isCommonEncryption)) {
  7066. encryptedFragments.push(frag);
  7067. }
  7068. }
  7069. function assignMultipleMediaPlaylistTagOccuranceError(level, tag, result) {
  7070. level.playlistParsingError = new Error(`#EXT-X-${tag} must not appear more than once (${result[0]})`);
  7071. }
  7072. function assignMustAppearBeforeSegmentsError(level, tag, result) {
  7073. level.playlistParsingError = new Error(`#EXT-X-${tag} must appear before the first Media Segment (${result[0]})`);
  7074. }
  7075. function updateFromToPTS(fragFrom, fragTo) {
  7076. const fragToPTS = fragTo.startPTS;
  7077. if (isFiniteNumber(fragToPTS)) {
  7078. let duration = 0;
  7079. let frag;
  7080. if (fragTo.sn > fragFrom.sn) {
  7081. duration = fragToPTS - fragFrom.start;
  7082. frag = fragFrom;
  7083. } else {
  7084. duration = fragFrom.start - fragToPTS;
  7085. frag = fragTo;
  7086. }
  7087. if (frag.duration !== duration) {
  7088. frag.setDuration(duration);
  7089. }
  7090. } else if (fragTo.sn > fragFrom.sn) {
  7091. const contiguous = fragFrom.cc === fragTo.cc;
  7092. if (contiguous && fragFrom.minEndPTS) {
  7093. fragTo.setStart(fragFrom.start + (fragFrom.minEndPTS - fragFrom.start));
  7094. } else {
  7095. fragTo.setStart(fragFrom.start + fragFrom.duration);
  7096. }
  7097. } else {
  7098. fragTo.setStart(Math.max(fragFrom.start - fragTo.duration, 0));
  7099. }
  7100. }
  7101. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS, logger2) {
  7102. const parsedMediaDuration = endPTS - startPTS;
  7103. if (parsedMediaDuration <= 0) {
  7104. logger2.warn("Fragment should have a positive duration", frag);
  7105. endPTS = startPTS + frag.duration;
  7106. endDTS = startDTS + frag.duration;
  7107. }
  7108. let maxStartPTS = startPTS;
  7109. let minEndPTS = endPTS;
  7110. const fragStartPts = frag.startPTS;
  7111. const fragEndPts = frag.endPTS;
  7112. if (isFiniteNumber(fragStartPts)) {
  7113. const deltaPTS = Math.abs(fragStartPts - startPTS);
  7114. if (details && deltaPTS > details.totalduration) {
  7115. logger2.warn(`media timestamps and playlist times differ by ${deltaPTS}s for level ${frag.level} ${details.url}`);
  7116. } else if (!isFiniteNumber(frag.deltaPTS)) {
  7117. frag.deltaPTS = deltaPTS;
  7118. } else {
  7119. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  7120. }
  7121. maxStartPTS = Math.max(startPTS, fragStartPts);
  7122. startPTS = Math.min(startPTS, fragStartPts);
  7123. startDTS = frag.startDTS !== void 0 ? Math.min(startDTS, frag.startDTS) : startDTS;
  7124. minEndPTS = Math.min(endPTS, fragEndPts);
  7125. endPTS = Math.max(endPTS, fragEndPts);
  7126. endDTS = frag.endDTS !== void 0 ? Math.max(endDTS, frag.endDTS) : endDTS;
  7127. }
  7128. const drift = startPTS - frag.start;
  7129. if (frag.start !== 0) {
  7130. frag.setStart(startPTS);
  7131. }
  7132. frag.setDuration(endPTS - frag.start);
  7133. frag.startPTS = startPTS;
  7134. frag.maxStartPTS = maxStartPTS;
  7135. frag.startDTS = startDTS;
  7136. frag.endPTS = endPTS;
  7137. frag.minEndPTS = minEndPTS;
  7138. frag.endDTS = endDTS;
  7139. const sn = frag.sn;
  7140. if (!details || sn < details.startSN || sn > details.endSN) {
  7141. return 0;
  7142. }
  7143. let i;
  7144. const fragIdx = sn - details.startSN;
  7145. const fragments = details.fragments;
  7146. fragments[fragIdx] = frag;
  7147. for (i = fragIdx; i > 0; i--) {
  7148. updateFromToPTS(fragments[i], fragments[i - 1]);
  7149. }
  7150. for (i = fragIdx; i < fragments.length - 1; i++) {
  7151. updateFromToPTS(fragments[i], fragments[i + 1]);
  7152. }
  7153. if (details.fragmentHint) {
  7154. updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
  7155. }
  7156. details.PTSKnown = details.alignedSliding = true;
  7157. return drift;
  7158. }
  7159. function mergeDetails(oldDetails, newDetails, logger2) {
  7160. if (oldDetails === newDetails) {
  7161. return;
  7162. }
  7163. let currentInitSegment = null;
  7164. const oldFragments = oldDetails.fragments;
  7165. for (let i = oldFragments.length - 1; i >= 0; i--) {
  7166. const oldInit = oldFragments[i].initSegment;
  7167. if (oldInit) {
  7168. currentInitSegment = oldInit;
  7169. break;
  7170. }
  7171. }
  7172. if (oldDetails.fragmentHint) {
  7173. delete oldDetails.fragmentHint.endPTS;
  7174. }
  7175. let PTSFrag;
  7176. mapFragmentIntersection(oldDetails, newDetails, (oldFrag, newFrag, newFragIndex, newFragments2) => {
  7177. if ((!newDetails.startCC || newDetails.skippedSegments) && newFrag.cc !== oldFrag.cc) {
  7178. const ccOffset = oldFrag.cc - newFrag.cc;
  7179. for (let i = newFragIndex; i < newFragments2.length; i++) {
  7180. newFragments2[i].cc += ccOffset;
  7181. }
  7182. newDetails.endCC = newFragments2[newFragments2.length - 1].cc;
  7183. }
  7184. if (isFiniteNumber(oldFrag.startPTS) && isFiniteNumber(oldFrag.endPTS)) {
  7185. newFrag.setStart(newFrag.startPTS = oldFrag.startPTS);
  7186. newFrag.startDTS = oldFrag.startDTS;
  7187. newFrag.maxStartPTS = oldFrag.maxStartPTS;
  7188. newFrag.endPTS = oldFrag.endPTS;
  7189. newFrag.endDTS = oldFrag.endDTS;
  7190. newFrag.minEndPTS = oldFrag.minEndPTS;
  7191. newFrag.setDuration(oldFrag.endPTS - oldFrag.startPTS);
  7192. if (newFrag.duration) {
  7193. PTSFrag = newFrag;
  7194. }
  7195. newDetails.PTSKnown = newDetails.alignedSliding = true;
  7196. }
  7197. if (oldFrag.hasStreams) {
  7198. newFrag.elementaryStreams = oldFrag.elementaryStreams;
  7199. }
  7200. newFrag.loader = oldFrag.loader;
  7201. if (oldFrag.hasStats) {
  7202. newFrag.stats = oldFrag.stats;
  7203. }
  7204. if (oldFrag.initSegment) {
  7205. newFrag.initSegment = oldFrag.initSegment;
  7206. currentInitSegment = oldFrag.initSegment;
  7207. }
  7208. });
  7209. const newFragments = newDetails.fragments;
  7210. const fragmentsToCheck = newDetails.fragmentHint ? newFragments.concat(newDetails.fragmentHint) : newFragments;
  7211. if (currentInitSegment) {
  7212. fragmentsToCheck.forEach((frag) => {
  7213. var _currentInitSegment;
  7214. if (frag && (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) == null ? void 0 : _currentInitSegment.relurl))) {
  7215. frag.initSegment = currentInitSegment;
  7216. }
  7217. });
  7218. }
  7219. if (newDetails.skippedSegments) {
  7220. newDetails.deltaUpdateFailed = newFragments.some((frag) => !frag);
  7221. if (newDetails.deltaUpdateFailed) {
  7222. logger2.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");
  7223. for (let i = newDetails.skippedSegments; i--; ) {
  7224. newFragments.shift();
  7225. }
  7226. newDetails.startSN = newFragments[0].sn;
  7227. } else {
  7228. if (newDetails.canSkipDateRanges) {
  7229. newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails, logger2);
  7230. }
  7231. const programDateTimes = oldDetails.fragments.filter((frag) => frag.rawProgramDateTime);
  7232. if (oldDetails.hasProgramDateTime && !newDetails.hasProgramDateTime) {
  7233. for (let i = 1; i < fragmentsToCheck.length; i++) {
  7234. if (fragmentsToCheck[i].programDateTime === null) {
  7235. assignProgramDateTime(fragmentsToCheck[i], fragmentsToCheck[i - 1], programDateTimes);
  7236. }
  7237. }
  7238. }
  7239. mapDateRanges(programDateTimes, newDetails);
  7240. }
  7241. newDetails.endCC = newFragments[newFragments.length - 1].cc;
  7242. }
  7243. if (!newDetails.startCC) {
  7244. var _fragPriorToNewStart$;
  7245. const fragPriorToNewStart = getFragmentWithSN(oldDetails, newDetails.startSN - 1);
  7246. newDetails.startCC = (_fragPriorToNewStart$ = fragPriorToNewStart == null ? void 0 : fragPriorToNewStart.cc) != null ? _fragPriorToNewStart$ : newFragments[0].cc;
  7247. }
  7248. mapPartIntersection(oldDetails.partList, newDetails.partList, (oldPart, newPart) => {
  7249. newPart.elementaryStreams = oldPart.elementaryStreams;
  7250. newPart.stats = oldPart.stats;
  7251. });
  7252. if (PTSFrag) {
  7253. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS, logger2);
  7254. } else {
  7255. adjustSliding(oldDetails, newDetails);
  7256. }
  7257. if (newFragments.length) {
  7258. newDetails.totalduration = newDetails.edge - newFragments[0].start;
  7259. }
  7260. newDetails.driftStartTime = oldDetails.driftStartTime;
  7261. newDetails.driftStart = oldDetails.driftStart;
  7262. const advancedDateTime = newDetails.advancedDateTime;
  7263. if (newDetails.advanced && advancedDateTime) {
  7264. const edge = newDetails.edge;
  7265. if (!newDetails.driftStart) {
  7266. newDetails.driftStartTime = advancedDateTime;
  7267. newDetails.driftStart = edge;
  7268. }
  7269. newDetails.driftEndTime = advancedDateTime;
  7270. newDetails.driftEnd = edge;
  7271. } else {
  7272. newDetails.driftEndTime = oldDetails.driftEndTime;
  7273. newDetails.driftEnd = oldDetails.driftEnd;
  7274. newDetails.advancedDateTime = oldDetails.advancedDateTime;
  7275. }
  7276. if (newDetails.requestScheduled === -1) {
  7277. newDetails.requestScheduled = oldDetails.requestScheduled;
  7278. }
  7279. }
  7280. function mergeDateRanges(oldDateRanges, newDetails, logger2) {
  7281. const {
  7282. dateRanges: deltaDateRanges,
  7283. recentlyRemovedDateranges
  7284. } = newDetails;
  7285. const dateRanges = _extends({}, oldDateRanges);
  7286. if (recentlyRemovedDateranges) {
  7287. recentlyRemovedDateranges.forEach((id) => {
  7288. delete dateRanges[id];
  7289. });
  7290. }
  7291. const mergeIds = Object.keys(dateRanges);
  7292. const mergeCount = mergeIds.length;
  7293. if (!mergeCount) {
  7294. return deltaDateRanges;
  7295. }
  7296. Object.keys(deltaDateRanges).forEach((id) => {
  7297. const mergedDateRange = dateRanges[id];
  7298. const dateRange = new DateRange(deltaDateRanges[id].attr, mergedDateRange);
  7299. if (dateRange.isValid) {
  7300. dateRanges[id] = dateRange;
  7301. if (!mergedDateRange) {
  7302. dateRange.tagOrder += mergeCount;
  7303. }
  7304. } else {
  7305. logger2.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${stringify(deltaDateRanges[id].attr)}"`);
  7306. }
  7307. });
  7308. return dateRanges;
  7309. }
  7310. function mapPartIntersection(oldParts, newParts, intersectionFn) {
  7311. if (oldParts && newParts) {
  7312. let delta = 0;
  7313. for (let i = 0, len = oldParts.length; i <= len; i++) {
  7314. const oldPart = oldParts[i];
  7315. const newPart = newParts[i + delta];
  7316. if (oldPart && newPart && oldPart.index === newPart.index && oldPart.fragment.sn === newPart.fragment.sn) {
  7317. intersectionFn(oldPart, newPart);
  7318. } else {
  7319. delta--;
  7320. }
  7321. }
  7322. }
  7323. }
  7324. function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
  7325. const skippedSegments = newDetails.skippedSegments;
  7326. const start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
  7327. const end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
  7328. const delta = newDetails.startSN - oldDetails.startSN;
  7329. const newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  7330. const oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
  7331. for (let i = start; i <= end; i++) {
  7332. const oldFrag = oldFrags[delta + i];
  7333. let newFrag = newFrags[i];
  7334. if (skippedSegments && !newFrag && oldFrag) {
  7335. newFrag = newDetails.fragments[i] = oldFrag;
  7336. }
  7337. if (oldFrag && newFrag) {
  7338. intersectionFn(oldFrag, newFrag, i, newFrags);
  7339. const uriBefore = oldFrag.relurl;
  7340. const uriAfter = newFrag.relurl;
  7341. if (uriBefore && notEqualAfterStrippingQueries(uriBefore, uriAfter)) {
  7342. newDetails.playlistParsingError = getSequenceError(`media sequence mismatch ${newFrag.sn}:`, oldDetails, newDetails, oldFrag, newFrag);
  7343. return;
  7344. } else if (oldFrag.cc !== newFrag.cc) {
  7345. newDetails.playlistParsingError = getSequenceError(`discontinuity sequence mismatch (${oldFrag.cc}!=${newFrag.cc})`, oldDetails, newDetails, oldFrag, newFrag);
  7346. return;
  7347. }
  7348. }
  7349. }
  7350. }
  7351. function getSequenceError(message, oldDetails, newDetails, oldFrag, newFrag) {
  7352. return new Error(`${message} ${newFrag.url}
  7353. Playlist starting @${oldDetails.startSN}
  7354. ${oldDetails.m3u8}
  7355. Playlist starting @${newDetails.startSN}
  7356. ${newDetails.m3u8}`);
  7357. }
  7358. function adjustSliding(oldDetails, newDetails, matchingStableVariantOrRendition = true) {
  7359. const delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
  7360. const oldFragments = oldDetails.fragments;
  7361. const advancedOrStable = delta >= 0;
  7362. let sliding = 0;
  7363. if (advancedOrStable && delta < oldFragments.length) {
  7364. sliding = oldFragments[delta].start;
  7365. } else if (advancedOrStable && newDetails.startSN === oldDetails.endSN + 1) {
  7366. sliding = oldDetails.fragmentEnd;
  7367. } else if (advancedOrStable && matchingStableVariantOrRendition) {
  7368. sliding = oldDetails.fragmentStart + delta * newDetails.levelTargetDuration;
  7369. } else if (!newDetails.skippedSegments && newDetails.fragmentStart === 0) {
  7370. sliding = oldDetails.fragmentStart;
  7371. } else {
  7372. return;
  7373. }
  7374. addSliding(newDetails, sliding);
  7375. }
  7376. function addSliding(details, sliding) {
  7377. if (sliding) {
  7378. const fragments = details.fragments;
  7379. for (let i = details.skippedSegments; i < fragments.length; i++) {
  7380. fragments[i].addStart(sliding);
  7381. }
  7382. if (details.fragmentHint) {
  7383. details.fragmentHint.addStart(sliding);
  7384. }
  7385. }
  7386. }
  7387. function computeReloadInterval(newDetails, distanceToLiveEdgeMs = Infinity) {
  7388. let reloadInterval = 1e3 * newDetails.targetduration;
  7389. if (newDetails.updated) {
  7390. const fragments = newDetails.fragments;
  7391. const liveEdgeMaxTargetDurations = 4;
  7392. if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) {
  7393. const lastSegmentDuration = fragments[fragments.length - 1].duration * 1e3;
  7394. if (lastSegmentDuration < reloadInterval) {
  7395. reloadInterval = lastSegmentDuration;
  7396. }
  7397. }
  7398. } else {
  7399. reloadInterval /= 2;
  7400. }
  7401. return Math.round(reloadInterval);
  7402. }
  7403. function getFragmentWithSN(details, sn, fragCurrent) {
  7404. if (!details) {
  7405. return null;
  7406. }
  7407. let fragment = details.fragments[sn - details.startSN];
  7408. if (fragment) {
  7409. return fragment;
  7410. }
  7411. fragment = details.fragmentHint;
  7412. if (fragment && fragment.sn === sn) {
  7413. return fragment;
  7414. }
  7415. if (sn < details.startSN && fragCurrent && fragCurrent.sn === sn) {
  7416. return fragCurrent;
  7417. }
  7418. return null;
  7419. }
  7420. function getPartWith(details, sn, partIndex) {
  7421. if (!details) {
  7422. return null;
  7423. }
  7424. return findPart(details.partList, sn, partIndex);
  7425. }
  7426. function findPart(partList, sn, partIndex) {
  7427. if (partList) {
  7428. for (let i = partList.length; i--; ) {
  7429. const part = partList[i];
  7430. if (part.index === partIndex && part.fragment.sn === sn) {
  7431. return part;
  7432. }
  7433. }
  7434. }
  7435. return null;
  7436. }
  7437. function reassignFragmentLevelIndexes(levels) {
  7438. levels.forEach((level, index) => {
  7439. var _level$details;
  7440. (_level$details = level.details) == null || _level$details.fragments.forEach((fragment) => {
  7441. fragment.level = index;
  7442. if (fragment.initSegment) {
  7443. fragment.initSegment.level = index;
  7444. }
  7445. });
  7446. });
  7447. }
  7448. function notEqualAfterStrippingQueries(uriBefore, uriAfter) {
  7449. if (uriBefore !== uriAfter && uriAfter) {
  7450. return stripQuery(uriBefore) !== stripQuery(uriAfter);
  7451. }
  7452. return false;
  7453. }
  7454. function stripQuery(uri) {
  7455. return uri.replace(/\?[^?]*$/, "");
  7456. }
  7457. function findFirstFragWithCC(fragments, cc) {
  7458. for (let i = 0, len = fragments.length; i < len; i++) {
  7459. var _fragments$i;
  7460. if (((_fragments$i = fragments[i]) == null ? void 0 : _fragments$i.cc) === cc) {
  7461. return fragments[i];
  7462. }
  7463. }
  7464. return null;
  7465. }
  7466. function shouldAlignOnDiscontinuities(refDetails, details) {
  7467. if (refDetails) {
  7468. if (details.startCC < refDetails.endCC && details.endCC > refDetails.startCC) {
  7469. return true;
  7470. }
  7471. }
  7472. return false;
  7473. }
  7474. function adjustFragmentStart(frag, sliding) {
  7475. const start = frag.start + sliding;
  7476. frag.startPTS = start;
  7477. frag.setStart(start);
  7478. frag.endPTS = start + frag.duration;
  7479. }
  7480. function adjustSlidingStart(sliding, details) {
  7481. const fragments = details.fragments;
  7482. for (let i = 0, len = fragments.length; i < len; i++) {
  7483. adjustFragmentStart(fragments[i], sliding);
  7484. }
  7485. if (details.fragmentHint) {
  7486. adjustFragmentStart(details.fragmentHint, sliding);
  7487. }
  7488. details.alignedSliding = true;
  7489. }
  7490. function alignStream(switchDetails, details) {
  7491. if (!switchDetails) {
  7492. return;
  7493. }
  7494. alignDiscontinuities(details, switchDetails);
  7495. if (!details.alignedSliding) {
  7496. alignMediaPlaylistByPDT(details, switchDetails);
  7497. }
  7498. if (!details.alignedSliding && !details.skippedSegments) {
  7499. adjustSliding(switchDetails, details, false);
  7500. }
  7501. }
  7502. function alignDiscontinuities(details, refDetails) {
  7503. if (!shouldAlignOnDiscontinuities(refDetails, details)) {
  7504. return;
  7505. }
  7506. const targetCC = Math.min(refDetails.endCC, details.endCC);
  7507. const refFrag = findFirstFragWithCC(refDetails.fragments, targetCC);
  7508. const frag = findFirstFragWithCC(details.fragments, targetCC);
  7509. if (!refFrag || !frag) {
  7510. return;
  7511. }
  7512. logger.log(`Aligning playlist at start of dicontinuity sequence ${targetCC}`);
  7513. const delta = refFrag.start - frag.start;
  7514. adjustSlidingStart(delta, details);
  7515. }
  7516. function alignMediaPlaylistByPDT(details, refDetails) {
  7517. if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
  7518. return;
  7519. }
  7520. const fragments = details.fragments;
  7521. const refFragments = refDetails.fragments;
  7522. if (!fragments.length || !refFragments.length) {
  7523. return;
  7524. }
  7525. let refFrag;
  7526. let frag;
  7527. const targetCC = Math.min(refDetails.endCC, details.endCC);
  7528. if (refDetails.startCC < targetCC && details.startCC < targetCC) {
  7529. refFrag = findFirstFragWithCC(refFragments, targetCC);
  7530. frag = findFirstFragWithCC(fragments, targetCC);
  7531. }
  7532. if (!refFrag || !frag) {
  7533. refFrag = refFragments[Math.floor(refFragments.length / 2)];
  7534. frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.floor(fragments.length / 2)];
  7535. }
  7536. const refPDT = refFrag.programDateTime;
  7537. const targetPDT = frag.programDateTime;
  7538. if (!refPDT || !targetPDT) {
  7539. return;
  7540. }
  7541. const delta = (targetPDT - refPDT) / 1e3 - (frag.start - refFrag.start);
  7542. adjustSlidingStart(delta, details);
  7543. }
  7544. function addEventListener(el, type, listener) {
  7545. removeEventListener(el, type, listener);
  7546. el.addEventListener(type, listener);
  7547. }
  7548. function removeEventListener(el, type, listener) {
  7549. el.removeEventListener(type, listener);
  7550. }
  7551. var TimeRanges = {
  7552. toString: function(r) {
  7553. let log = "";
  7554. const len = r.length;
  7555. for (let i = 0; i < len; i++) {
  7556. log += `[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;
  7557. }
  7558. return log;
  7559. }
  7560. };
  7561. var State = {
  7562. STOPPED: "STOPPED",
  7563. IDLE: "IDLE",
  7564. KEY_LOADING: "KEY_LOADING",
  7565. FRAG_LOADING: "FRAG_LOADING",
  7566. FRAG_LOADING_WAITING_RETRY: "FRAG_LOADING_WAITING_RETRY",
  7567. WAITING_TRACK: "WAITING_TRACK",
  7568. PARSING: "PARSING",
  7569. PARSED: "PARSED",
  7570. ENDED: "ENDED",
  7571. ERROR: "ERROR",
  7572. WAITING_INIT_PTS: "WAITING_INIT_PTS",
  7573. WAITING_LEVEL: "WAITING_LEVEL"
  7574. };
  7575. var BaseStreamController = class extends TaskLoop {
  7576. constructor(hls, fragmentTracker, keyLoader, logPrefix, playlistType) {
  7577. super(logPrefix, hls.logger);
  7578. this.hls = void 0;
  7579. this.fragPrevious = null;
  7580. this.fragCurrent = null;
  7581. this.fragmentTracker = void 0;
  7582. this.transmuxer = null;
  7583. this._state = State.STOPPED;
  7584. this.playlistType = void 0;
  7585. this.media = null;
  7586. this.mediaBuffer = null;
  7587. this.config = void 0;
  7588. this.bitrateTest = false;
  7589. this.lastCurrentTime = 0;
  7590. this.nextLoadPosition = 0;
  7591. this.startPosition = 0;
  7592. this.startTimeOffset = null;
  7593. this.retryDate = 0;
  7594. this.levels = null;
  7595. this.fragmentLoader = void 0;
  7596. this.keyLoader = void 0;
  7597. this.levelLastLoaded = null;
  7598. this.startFragRequested = false;
  7599. this.decrypter = void 0;
  7600. this.initPTS = [];
  7601. this.buffering = true;
  7602. this.loadingParts = false;
  7603. this.loopSn = void 0;
  7604. this.onMediaSeeking = () => {
  7605. const {
  7606. config,
  7607. fragCurrent,
  7608. media,
  7609. mediaBuffer,
  7610. state
  7611. } = this;
  7612. const currentTime = media ? media.currentTime : 0;
  7613. const bufferInfo = BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config.maxBufferHole);
  7614. const noFowardBuffer = !bufferInfo.len;
  7615. this.log(`Media seeking to ${isFiniteNumber(currentTime) ? currentTime.toFixed(3) : currentTime}, state: ${state}, ${noFowardBuffer ? "out of" : "in"} buffer`);
  7616. if (this.state === State.ENDED) {
  7617. this.resetLoadingState();
  7618. } else if (fragCurrent) {
  7619. const tolerance = config.maxFragLookUpTolerance;
  7620. const fragStartOffset = fragCurrent.start - tolerance;
  7621. const fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  7622. if (noFowardBuffer || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) {
  7623. const pastFragment = currentTime > fragEndOffset;
  7624. if (currentTime < fragStartOffset || pastFragment) {
  7625. if (pastFragment && fragCurrent.loader) {
  7626. this.log(`Cancelling fragment load for seek (sn: ${fragCurrent.sn})`);
  7627. fragCurrent.abortRequests();
  7628. this.resetLoadingState();
  7629. }
  7630. this.fragPrevious = null;
  7631. }
  7632. }
  7633. }
  7634. if (media) {
  7635. this.fragmentTracker.removeFragmentsInRange(currentTime, Infinity, this.playlistType, true);
  7636. const lastCurrentTime = this.lastCurrentTime;
  7637. if (currentTime > lastCurrentTime) {
  7638. this.lastCurrentTime = currentTime;
  7639. }
  7640. if (!this.loadingParts) {
  7641. const bufferEnd = Math.max(bufferInfo.end, currentTime);
  7642. const shouldLoadParts = this.shouldLoadParts(this.getLevelDetails(), bufferEnd);
  7643. if (shouldLoadParts) {
  7644. this.log(`LL-Part loading ON after seeking to ${currentTime.toFixed(2)} with buffer @${bufferEnd.toFixed(2)}`);
  7645. this.loadingParts = shouldLoadParts;
  7646. }
  7647. }
  7648. }
  7649. if (!this.hls.hasEnoughToStart) {
  7650. this.log(`Setting ${noFowardBuffer ? "startPosition" : "nextLoadPosition"} to ${currentTime} for seek without enough to start`);
  7651. this.nextLoadPosition = currentTime;
  7652. if (noFowardBuffer) {
  7653. this.startPosition = currentTime;
  7654. }
  7655. }
  7656. if (noFowardBuffer && this.state === State.IDLE) {
  7657. this.tickImmediate();
  7658. }
  7659. };
  7660. this.onMediaEnded = () => {
  7661. this.log(`setting startPosition to 0 because media ended`);
  7662. this.startPosition = this.lastCurrentTime = 0;
  7663. };
  7664. this.playlistType = playlistType;
  7665. this.hls = hls;
  7666. this.fragmentLoader = new FragmentLoader(hls.config);
  7667. this.keyLoader = keyLoader;
  7668. this.fragmentTracker = fragmentTracker;
  7669. this.config = hls.config;
  7670. this.decrypter = new Decrypter(hls.config);
  7671. }
  7672. registerListeners() {
  7673. const {
  7674. hls
  7675. } = this;
  7676. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  7677. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  7678. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  7679. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  7680. hls.on(Events.ERROR, this.onError, this);
  7681. }
  7682. unregisterListeners() {
  7683. const {
  7684. hls
  7685. } = this;
  7686. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  7687. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  7688. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  7689. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  7690. hls.off(Events.ERROR, this.onError, this);
  7691. }
  7692. doTick() {
  7693. this.onTickEnd();
  7694. }
  7695. onTickEnd() {
  7696. }
  7697. startLoad(startPosition) {
  7698. }
  7699. stopLoad() {
  7700. if (this.state === State.STOPPED) {
  7701. return;
  7702. }
  7703. this.fragmentLoader.abort();
  7704. this.keyLoader.abort(this.playlistType);
  7705. const frag = this.fragCurrent;
  7706. if (frag != null && frag.loader) {
  7707. frag.abortRequests();
  7708. this.fragmentTracker.removeFragment(frag);
  7709. }
  7710. this.resetTransmuxer();
  7711. this.fragCurrent = null;
  7712. this.fragPrevious = null;
  7713. this.clearInterval();
  7714. this.clearNextTick();
  7715. this.state = State.STOPPED;
  7716. }
  7717. get startPositionValue() {
  7718. const {
  7719. nextLoadPosition,
  7720. startPosition
  7721. } = this;
  7722. if (startPosition === -1 && nextLoadPosition) {
  7723. return nextLoadPosition;
  7724. }
  7725. return startPosition;
  7726. }
  7727. get bufferingEnabled() {
  7728. return this.buffering;
  7729. }
  7730. pauseBuffering() {
  7731. this.buffering = false;
  7732. }
  7733. resumeBuffering() {
  7734. this.buffering = true;
  7735. }
  7736. get inFlightFrag() {
  7737. return {
  7738. frag: this.fragCurrent,
  7739. state: this.state
  7740. };
  7741. }
  7742. _streamEnded(bufferInfo, levelDetails) {
  7743. if (levelDetails.live || !this.media) {
  7744. return false;
  7745. }
  7746. const bufferEnd = bufferInfo.end || 0;
  7747. const timelineStart = this.config.timelineOffset || 0;
  7748. if (bufferEnd <= timelineStart) {
  7749. return false;
  7750. }
  7751. const bufferedRanges = bufferInfo.buffered;
  7752. if (this.config.maxBufferHole && bufferedRanges && bufferedRanges.length > 1) {
  7753. bufferInfo = BufferHelper.bufferedInfo(bufferedRanges, bufferInfo.start, 0);
  7754. }
  7755. const nextStart = bufferInfo.nextStart;
  7756. const hasSecondBufferedRange = nextStart && nextStart > timelineStart && nextStart < levelDetails.edge;
  7757. if (hasSecondBufferedRange) {
  7758. return false;
  7759. }
  7760. if (this.media.currentTime < bufferInfo.start) {
  7761. return false;
  7762. }
  7763. const partList = levelDetails.partList;
  7764. if (partList != null && partList.length) {
  7765. const lastPart = partList[partList.length - 1];
  7766. const lastPartBuffered = BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2);
  7767. return lastPartBuffered;
  7768. }
  7769. const playlistType = levelDetails.fragments[levelDetails.fragments.length - 1].type;
  7770. return this.fragmentTracker.isEndListAppended(playlistType);
  7771. }
  7772. getLevelDetails() {
  7773. if (this.levels && this.levelLastLoaded !== null) {
  7774. return this.levelLastLoaded.details;
  7775. }
  7776. }
  7777. get timelineOffset() {
  7778. const configuredTimelineOffset = this.config.timelineOffset;
  7779. if (configuredTimelineOffset) {
  7780. var _this$getLevelDetails;
  7781. return ((_this$getLevelDetails = this.getLevelDetails()) == null ? void 0 : _this$getLevelDetails.appliedTimelineOffset) || configuredTimelineOffset;
  7782. }
  7783. return 0;
  7784. }
  7785. onMediaAttached(event, data) {
  7786. const media = this.media = this.mediaBuffer = data.media;
  7787. addEventListener(media, "seeking", this.onMediaSeeking);
  7788. addEventListener(media, "ended", this.onMediaEnded);
  7789. const config = this.config;
  7790. if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
  7791. this.startLoad(config.startPosition);
  7792. }
  7793. }
  7794. onMediaDetaching(event, data) {
  7795. const transferringMedia = !!data.transferMedia;
  7796. const media = this.media;
  7797. if (media === null) {
  7798. return;
  7799. }
  7800. if (media.ended) {
  7801. this.log("MSE detaching and video ended, reset startPosition");
  7802. this.startPosition = this.lastCurrentTime = 0;
  7803. }
  7804. removeEventListener(media, "seeking", this.onMediaSeeking);
  7805. removeEventListener(media, "ended", this.onMediaEnded);
  7806. if (this.keyLoader && !transferringMedia) {
  7807. this.keyLoader.detach();
  7808. }
  7809. this.media = this.mediaBuffer = null;
  7810. this.loopSn = void 0;
  7811. if (transferringMedia) {
  7812. this.resetLoadingState();
  7813. this.resetTransmuxer();
  7814. return;
  7815. }
  7816. this.loadingParts = false;
  7817. this.fragmentTracker.removeAllFragments();
  7818. this.stopLoad();
  7819. }
  7820. onManifestLoading() {
  7821. this.initPTS = [];
  7822. this.levels = this.levelLastLoaded = this.fragCurrent = null;
  7823. this.lastCurrentTime = this.startPosition = 0;
  7824. this.startFragRequested = false;
  7825. }
  7826. onError(event, data) {
  7827. }
  7828. onManifestLoaded(event, data) {
  7829. this.startTimeOffset = data.startTimeOffset;
  7830. }
  7831. onHandlerDestroying() {
  7832. this.stopLoad();
  7833. if (this.transmuxer) {
  7834. this.transmuxer.destroy();
  7835. this.transmuxer = null;
  7836. }
  7837. super.onHandlerDestroying();
  7838. this.hls = this.onMediaSeeking = this.onMediaEnded = null;
  7839. }
  7840. onHandlerDestroyed() {
  7841. this.state = State.STOPPED;
  7842. if (this.fragmentLoader) {
  7843. this.fragmentLoader.destroy();
  7844. }
  7845. if (this.keyLoader) {
  7846. this.keyLoader.destroy();
  7847. }
  7848. if (this.decrypter) {
  7849. this.decrypter.destroy();
  7850. }
  7851. this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null;
  7852. super.onHandlerDestroyed();
  7853. }
  7854. loadFragment(frag, level, targetBufferTime) {
  7855. this.startFragRequested = true;
  7856. this._loadFragForPlayback(frag, level, targetBufferTime);
  7857. }
  7858. _loadFragForPlayback(fragment, level, targetBufferTime) {
  7859. const progressCallback = (data) => {
  7860. const frag = data.frag;
  7861. if (this.fragContextChanged(frag)) {
  7862. this.warn(`${frag.type} sn: ${frag.sn}${data.part ? " part: " + data.part.index : ""} of ${this.fragInfo(frag, false, data.part)}) was dropped during download.`);
  7863. this.fragmentTracker.removeFragment(frag);
  7864. return;
  7865. }
  7866. frag.stats.chunkCount++;
  7867. this._handleFragmentLoadProgress(data);
  7868. };
  7869. this._doFragLoad(fragment, level, targetBufferTime, progressCallback).then((data) => {
  7870. if (!data) {
  7871. return;
  7872. }
  7873. const state = this.state;
  7874. const frag = data.frag;
  7875. if (this.fragContextChanged(frag)) {
  7876. if (state === State.FRAG_LOADING || !this.fragCurrent && state === State.PARSING) {
  7877. this.fragmentTracker.removeFragment(frag);
  7878. this.state = State.IDLE;
  7879. }
  7880. return;
  7881. }
  7882. if ("payload" in data) {
  7883. this.log(`Loaded ${frag.type} sn: ${frag.sn} of ${this.playlistLabel()} ${frag.level}`);
  7884. this.hls.trigger(Events.FRAG_LOADED, data);
  7885. }
  7886. this._handleFragmentLoadComplete(data);
  7887. }).catch((reason) => {
  7888. if (this.state === State.STOPPED || this.state === State.ERROR) {
  7889. return;
  7890. }
  7891. this.warn(`Frag error: ${(reason == null ? void 0 : reason.message) || reason}`);
  7892. this.resetFragmentLoading(fragment);
  7893. });
  7894. }
  7895. clearTrackerIfNeeded(frag) {
  7896. var _this$mediaBuffer;
  7897. const {
  7898. fragmentTracker
  7899. } = this;
  7900. const fragState = fragmentTracker.getState(frag);
  7901. if (fragState === FragmentState.APPENDING) {
  7902. const playlistType = frag.type;
  7903. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  7904. const minForwardBufferLength = Math.max(frag.duration, bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength);
  7905. const backtrackFragment = this.backtrackFragment;
  7906. const backtracked = backtrackFragment ? frag.sn - backtrackFragment.sn : 0;
  7907. if (backtracked === 1 || this.reduceMaxBufferLength(minForwardBufferLength, frag.duration)) {
  7908. fragmentTracker.removeFragment(frag);
  7909. }
  7910. } else if (((_this$mediaBuffer = this.mediaBuffer) == null ? void 0 : _this$mediaBuffer.buffered.length) === 0) {
  7911. fragmentTracker.removeAllFragments();
  7912. } else if (fragmentTracker.hasParts(frag.type)) {
  7913. fragmentTracker.detectPartialFragments({
  7914. frag,
  7915. part: null,
  7916. stats: frag.stats,
  7917. id: frag.type
  7918. });
  7919. if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {
  7920. fragmentTracker.removeFragment(frag);
  7921. }
  7922. }
  7923. }
  7924. checkLiveUpdate(details) {
  7925. if (details.updated && !details.live) {
  7926. const lastFragment = details.fragments[details.fragments.length - 1];
  7927. this.fragmentTracker.detectPartialFragments({
  7928. frag: lastFragment,
  7929. part: null,
  7930. stats: lastFragment.stats,
  7931. id: lastFragment.type
  7932. });
  7933. }
  7934. if (!details.fragments[0]) {
  7935. details.deltaUpdateFailed = true;
  7936. }
  7937. }
  7938. waitForLive(levelInfo) {
  7939. const details = levelInfo.details;
  7940. return (details == null ? void 0 : details.live) && details.type !== "EVENT" && (this.levelLastLoaded !== levelInfo || details.expired);
  7941. }
  7942. flushMainBuffer(startOffset, endOffset, type = null) {
  7943. if (!(startOffset - endOffset)) {
  7944. return;
  7945. }
  7946. const flushScope = {
  7947. startOffset,
  7948. endOffset,
  7949. type
  7950. };
  7951. this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);
  7952. }
  7953. _loadInitSegment(fragment, level) {
  7954. this._doFragLoad(fragment, level).then((data) => {
  7955. const frag = data == null ? void 0 : data.frag;
  7956. if (!frag || this.fragContextChanged(frag) || !this.levels) {
  7957. throw new Error("init load aborted");
  7958. }
  7959. return data;
  7960. }).then((data) => {
  7961. const {
  7962. hls
  7963. } = this;
  7964. const {
  7965. frag,
  7966. payload
  7967. } = data;
  7968. const decryptData = frag.decryptdata;
  7969. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
  7970. const startTime = self.performance.now();
  7971. return this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch((err) => {
  7972. hls.trigger(Events.ERROR, {
  7973. type: ErrorTypes.MEDIA_ERROR,
  7974. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  7975. fatal: false,
  7976. error: err,
  7977. reason: err.message,
  7978. frag
  7979. });
  7980. throw err;
  7981. }).then((decryptedData) => {
  7982. const endTime = self.performance.now();
  7983. hls.trigger(Events.FRAG_DECRYPTED, {
  7984. frag,
  7985. payload: decryptedData,
  7986. stats: {
  7987. tstart: startTime,
  7988. tdecrypt: endTime
  7989. }
  7990. });
  7991. data.payload = decryptedData;
  7992. return this.completeInitSegmentLoad(data);
  7993. });
  7994. }
  7995. return this.completeInitSegmentLoad(data);
  7996. }).catch((reason) => {
  7997. if (this.state === State.STOPPED || this.state === State.ERROR) {
  7998. return;
  7999. }
  8000. this.warn(reason);
  8001. this.resetFragmentLoading(fragment);
  8002. });
  8003. }
  8004. completeInitSegmentLoad(data) {
  8005. const {
  8006. levels
  8007. } = this;
  8008. if (!levels) {
  8009. throw new Error("init load aborted, missing levels");
  8010. }
  8011. const stats = data.frag.stats;
  8012. if (this.state !== State.STOPPED) {
  8013. this.state = State.IDLE;
  8014. }
  8015. data.frag.data = new Uint8Array(data.payload);
  8016. stats.parsing.start = stats.buffering.start = self.performance.now();
  8017. stats.parsing.end = stats.buffering.end = self.performance.now();
  8018. this.tick();
  8019. }
  8020. unhandledEncryptionError(initSegment, frag) {
  8021. var _tracks$audio, _tracks$video;
  8022. const tracks = initSegment.tracks;
  8023. if (tracks && !frag.encrypted && ((_tracks$audio = tracks.audio) != null && _tracks$audio.encrypted || (_tracks$video = tracks.video) != null && _tracks$video.encrypted) && (!this.config.emeEnabled || !this.keyLoader.emeController)) {
  8024. const media = this.media;
  8025. const error = new Error(`Encrypted track with no key in ${this.fragInfo(frag)} (media ${media ? "attached mediaKeys: " + media.mediaKeys : "detached"})`);
  8026. this.warn(error.message);
  8027. if (!media || media.mediaKeys) {
  8028. return false;
  8029. }
  8030. this.hls.trigger(Events.ERROR, {
  8031. type: ErrorTypes.KEY_SYSTEM_ERROR,
  8032. details: ErrorDetails.KEY_SYSTEM_NO_KEYS,
  8033. fatal: false,
  8034. error,
  8035. frag
  8036. });
  8037. this.resetTransmuxer();
  8038. return true;
  8039. }
  8040. return false;
  8041. }
  8042. fragContextChanged(frag) {
  8043. const {
  8044. fragCurrent
  8045. } = this;
  8046. return !frag || !fragCurrent || frag.sn !== fragCurrent.sn || frag.level !== fragCurrent.level;
  8047. }
  8048. fragBufferedComplete(frag, part) {
  8049. const media = this.mediaBuffer ? this.mediaBuffer : this.media;
  8050. 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)"})`);
  8051. if (isMediaFragment(frag)) {
  8052. var _this$levels;
  8053. if (frag.type !== PlaylistLevelType.SUBTITLE) {
  8054. const el = frag.elementaryStreams;
  8055. if (!Object.keys(el).some((type) => !!el[type])) {
  8056. this.state = State.IDLE;
  8057. return;
  8058. }
  8059. }
  8060. const level = (_this$levels = this.levels) == null ? void 0 : _this$levels[frag.level];
  8061. if (level != null && level.fragmentError) {
  8062. this.log(`Resetting level fragment error count of ${level.fragmentError} on frag buffered`);
  8063. level.fragmentError = 0;
  8064. }
  8065. }
  8066. this.state = State.IDLE;
  8067. }
  8068. _handleFragmentLoadComplete(fragLoadedEndData) {
  8069. const {
  8070. transmuxer
  8071. } = this;
  8072. if (!transmuxer) {
  8073. return;
  8074. }
  8075. const {
  8076. frag,
  8077. part,
  8078. partsLoaded
  8079. } = fragLoadedEndData;
  8080. const complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some((fragLoaded) => !fragLoaded);
  8081. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
  8082. transmuxer.flush(chunkMeta);
  8083. }
  8084. _handleFragmentLoadProgress(frag) {
  8085. }
  8086. _doFragLoad(frag, level, targetBufferTime = null, progressCallback) {
  8087. var _frag$decryptdata;
  8088. this.fragCurrent = frag;
  8089. const details = level.details;
  8090. if (!this.levels || !details) {
  8091. throw new Error(`frag load aborted, missing level${details ? "" : " detail"}s`);
  8092. }
  8093. let keyLoadingPromise = null;
  8094. if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) != null && _frag$decryptdata.key)) {
  8095. this.log(`Loading key for ${frag.sn} of [${details.startSN}-${details.endSN}], ${this.playlistLabel()} ${frag.level}`);
  8096. this.state = State.KEY_LOADING;
  8097. this.fragCurrent = frag;
  8098. keyLoadingPromise = this.keyLoader.load(frag).then((keyLoadedData) => {
  8099. if (!this.fragContextChanged(keyLoadedData.frag)) {
  8100. this.hls.trigger(Events.KEY_LOADED, keyLoadedData);
  8101. if (this.state === State.KEY_LOADING) {
  8102. this.state = State.IDLE;
  8103. }
  8104. return keyLoadedData;
  8105. }
  8106. });
  8107. this.hls.trigger(Events.KEY_LOADING, {
  8108. frag
  8109. });
  8110. if (this.fragCurrent === null) {
  8111. this.log(`context changed in KEY_LOADING`);
  8112. return Promise.resolve(null);
  8113. }
  8114. } else if (!frag.encrypted) {
  8115. keyLoadingPromise = this.keyLoader.loadClear(frag, details.encryptedFragments, this.startFragRequested);
  8116. if (keyLoadingPromise) {
  8117. this.log(`[eme] blocking frag load until media-keys acquired`);
  8118. }
  8119. }
  8120. const fragPrevious = this.fragPrevious;
  8121. if (isMediaFragment(frag) && (!fragPrevious || frag.sn !== fragPrevious.sn)) {
  8122. const shouldLoadParts = this.shouldLoadParts(level.details, frag.end);
  8123. if (shouldLoadParts !== this.loadingParts) {
  8124. this.log(`LL-Part loading ${shouldLoadParts ? "ON" : "OFF"} loading sn ${fragPrevious == null ? void 0 : fragPrevious.sn}->${frag.sn}`);
  8125. this.loadingParts = shouldLoadParts;
  8126. }
  8127. }
  8128. targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
  8129. if (this.loadingParts && isMediaFragment(frag)) {
  8130. const partList = details.partList;
  8131. if (partList && progressCallback) {
  8132. if (targetBufferTime > details.fragmentEnd && details.fragmentHint) {
  8133. frag = details.fragmentHint;
  8134. }
  8135. const partIndex = this.getNextPart(partList, frag, targetBufferTime);
  8136. if (partIndex > -1) {
  8137. const part = partList[partIndex];
  8138. frag = this.fragCurrent = part.fragment;
  8139. 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))}`);
  8140. this.nextLoadPosition = part.start + part.duration;
  8141. this.state = State.FRAG_LOADING;
  8142. let _result;
  8143. if (keyLoadingPromise) {
  8144. _result = keyLoadingPromise.then((keyLoadedData) => {
  8145. if (!keyLoadedData || this.fragContextChanged(keyLoadedData.frag)) {
  8146. return null;
  8147. }
  8148. return this.doFragPartsLoad(frag, part, level, progressCallback);
  8149. }).catch((error) => this.handleFragLoadError(error));
  8150. } else {
  8151. _result = this.doFragPartsLoad(frag, part, level, progressCallback).catch((error) => this.handleFragLoadError(error));
  8152. }
  8153. this.hls.trigger(Events.FRAG_LOADING, {
  8154. frag,
  8155. part,
  8156. targetBufferTime
  8157. });
  8158. if (this.fragCurrent === null) {
  8159. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING parts`));
  8160. }
  8161. return _result;
  8162. } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
  8163. return Promise.resolve(null);
  8164. }
  8165. }
  8166. }
  8167. if (isMediaFragment(frag) && this.loadingParts) {
  8168. var _details$partList;
  8169. this.log(`LL-Part loading OFF after next part miss @${targetBufferTime.toFixed(2)} Check buffer at sn: ${frag.sn} loaded parts: ${(_details$partList = details.partList) == null ? void 0 : _details$partList.filter((p) => p.loaded).map((p) => `[${p.start}-${p.end}]`)}`);
  8170. this.loadingParts = false;
  8171. } else if (!frag.url) {
  8172. return Promise.resolve(null);
  8173. }
  8174. this.log(`Loading ${frag.type} sn: ${frag.sn} of ${this.fragInfo(frag, false)}) cc: ${frag.cc} ${"[" + details.startSN + "-" + details.endSN + "]"}, target: ${parseFloat(targetBufferTime.toFixed(3))}`);
  8175. if (isFiniteNumber(frag.sn) && !this.bitrateTest) {
  8176. this.nextLoadPosition = frag.start + frag.duration;
  8177. }
  8178. this.state = State.FRAG_LOADING;
  8179. const dataOnProgress = this.config.progressive;
  8180. let result;
  8181. if (dataOnProgress && keyLoadingPromise) {
  8182. result = keyLoadingPromise.then((keyLoadedData) => {
  8183. if (!keyLoadedData || this.fragContextChanged(keyLoadedData.frag)) {
  8184. return null;
  8185. }
  8186. return this.fragmentLoader.load(frag, progressCallback);
  8187. }).catch((error) => this.handleFragLoadError(error));
  8188. } else {
  8189. result = Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : void 0), keyLoadingPromise]).then(([fragLoadedData]) => {
  8190. if (!dataOnProgress && progressCallback) {
  8191. progressCallback(fragLoadedData);
  8192. }
  8193. return fragLoadedData;
  8194. }).catch((error) => this.handleFragLoadError(error));
  8195. }
  8196. this.hls.trigger(Events.FRAG_LOADING, {
  8197. frag,
  8198. targetBufferTime
  8199. });
  8200. if (this.fragCurrent === null) {
  8201. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING`));
  8202. }
  8203. return result;
  8204. }
  8205. doFragPartsLoad(frag, fromPart, level, progressCallback) {
  8206. return new Promise((resolve, reject) => {
  8207. var _level$details;
  8208. const partsLoaded = [];
  8209. const initialPartList = (_level$details = level.details) == null ? void 0 : _level$details.partList;
  8210. const loadPart = (part) => {
  8211. this.fragmentLoader.loadPart(frag, part, progressCallback).then((partLoadedData) => {
  8212. partsLoaded[part.index] = partLoadedData;
  8213. const loadedPart = partLoadedData.part;
  8214. this.hls.trigger(Events.FRAG_LOADED, partLoadedData);
  8215. const nextPart = getPartWith(level.details, frag.sn, part.index + 1) || findPart(initialPartList, frag.sn, part.index + 1);
  8216. if (nextPart) {
  8217. loadPart(nextPart);
  8218. } else {
  8219. return resolve({
  8220. frag,
  8221. part: loadedPart,
  8222. partsLoaded
  8223. });
  8224. }
  8225. }).catch(reject);
  8226. };
  8227. loadPart(fromPart);
  8228. });
  8229. }
  8230. handleFragLoadError(error) {
  8231. if ("data" in error) {
  8232. const data = error.data;
  8233. if (data.frag && data.details === ErrorDetails.INTERNAL_ABORTED) {
  8234. this.handleFragLoadAborted(data.frag, data.part);
  8235. } else if (data.frag && data.type === ErrorTypes.KEY_SYSTEM_ERROR) {
  8236. data.frag.abortRequests();
  8237. this.resetStartWhenNotLoaded();
  8238. this.resetFragmentLoading(data.frag);
  8239. } else {
  8240. this.hls.trigger(Events.ERROR, data);
  8241. }
  8242. } else {
  8243. this.hls.trigger(Events.ERROR, {
  8244. type: ErrorTypes.OTHER_ERROR,
  8245. details: ErrorDetails.INTERNAL_EXCEPTION,
  8246. err: error,
  8247. error,
  8248. fatal: true
  8249. });
  8250. }
  8251. return null;
  8252. }
  8253. _handleTransmuxerFlush(chunkMeta) {
  8254. const context = this.getCurrentContext(chunkMeta);
  8255. if (!context || this.state !== State.PARSING) {
  8256. if (!this.fragCurrent && this.state !== State.STOPPED && this.state !== State.ERROR) {
  8257. this.state = State.IDLE;
  8258. }
  8259. return;
  8260. }
  8261. const {
  8262. frag,
  8263. part,
  8264. level
  8265. } = context;
  8266. const now2 = self.performance.now();
  8267. frag.stats.parsing.end = now2;
  8268. if (part) {
  8269. part.stats.parsing.end = now2;
  8270. }
  8271. const levelDetails = this.getLevelDetails();
  8272. const loadingPartsAtEdge = levelDetails && frag.sn > levelDetails.endSN;
  8273. const shouldLoadParts = loadingPartsAtEdge || this.shouldLoadParts(levelDetails, frag.end);
  8274. if (shouldLoadParts !== this.loadingParts) {
  8275. this.log(`LL-Part loading ${shouldLoadParts ? "ON" : "OFF"} after parsing segment ending @${frag.end.toFixed(2)}`);
  8276. this.loadingParts = shouldLoadParts;
  8277. }
  8278. this.updateLevelTiming(frag, part, level, chunkMeta.partial);
  8279. }
  8280. shouldLoadParts(details, bufferEnd) {
  8281. if (this.config.lowLatencyMode) {
  8282. if (!details) {
  8283. return this.loadingParts;
  8284. }
  8285. if (details.partList) {
  8286. var _details$fragmentHint;
  8287. const firstPart = details.partList[0];
  8288. if (firstPart.fragment.type === PlaylistLevelType.SUBTITLE) {
  8289. return false;
  8290. }
  8291. const safePartStart = firstPart.end + (((_details$fragmentHint = details.fragmentHint) == null ? void 0 : _details$fragmentHint.duration) || 0);
  8292. if (bufferEnd >= safePartStart) {
  8293. var _this$media;
  8294. const playhead = this.hls.hasEnoughToStart ? ((_this$media = this.media) == null ? void 0 : _this$media.currentTime) || this.lastCurrentTime : this.getLoadPosition();
  8295. if (playhead > firstPart.start - firstPart.fragment.duration) {
  8296. return true;
  8297. }
  8298. }
  8299. }
  8300. }
  8301. return false;
  8302. }
  8303. getCurrentContext(chunkMeta) {
  8304. const {
  8305. levels,
  8306. fragCurrent
  8307. } = this;
  8308. const {
  8309. level: levelIndex,
  8310. sn,
  8311. part: partIndex
  8312. } = chunkMeta;
  8313. if (!(levels != null && levels[levelIndex])) {
  8314. this.warn(`Levels object was unset while buffering fragment ${sn} of ${this.playlistLabel()} ${levelIndex}. The current chunk will not be buffered.`);
  8315. return null;
  8316. }
  8317. const level = levels[levelIndex];
  8318. const levelDetails = level.details;
  8319. const part = partIndex > -1 ? getPartWith(levelDetails, sn, partIndex) : null;
  8320. const frag = part ? part.fragment : getFragmentWithSN(levelDetails, sn, fragCurrent);
  8321. if (!frag) {
  8322. return null;
  8323. }
  8324. if (fragCurrent && fragCurrent !== frag) {
  8325. frag.stats = fragCurrent.stats;
  8326. }
  8327. return {
  8328. frag,
  8329. part,
  8330. level
  8331. };
  8332. }
  8333. bufferFragmentData(data, frag, part, chunkMeta, noBacktracking) {
  8334. if (this.state !== State.PARSING) {
  8335. return;
  8336. }
  8337. const {
  8338. data1,
  8339. data2
  8340. } = data;
  8341. let buffer = data1;
  8342. if (data2) {
  8343. buffer = appendUint8Array(data1, data2);
  8344. }
  8345. if (!buffer.length) {
  8346. return;
  8347. }
  8348. const offsetTimestamp = this.initPTS[frag.cc];
  8349. const offset = offsetTimestamp ? -offsetTimestamp.baseTime / offsetTimestamp.timescale : void 0;
  8350. const segment = {
  8351. type: data.type,
  8352. frag,
  8353. part,
  8354. chunkMeta,
  8355. offset,
  8356. parent: frag.type,
  8357. data: buffer
  8358. };
  8359. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  8360. if (data.dropped && data.independent && !part) {
  8361. if (noBacktracking) {
  8362. return;
  8363. }
  8364. this.flushBufferGap(frag);
  8365. }
  8366. }
  8367. flushBufferGap(frag) {
  8368. const media = this.media;
  8369. if (!media) {
  8370. return;
  8371. }
  8372. if (!BufferHelper.isBuffered(media, media.currentTime)) {
  8373. this.flushMainBuffer(0, frag.start);
  8374. return;
  8375. }
  8376. const currentTime = media.currentTime;
  8377. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  8378. const fragDuration = frag.duration;
  8379. const segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
  8380. const start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
  8381. if (frag.start - start > segmentFraction) {
  8382. this.flushMainBuffer(start, frag.start);
  8383. }
  8384. }
  8385. getFwdBufferInfo(bufferable, type) {
  8386. var _this$media2;
  8387. const pos = this.getLoadPosition();
  8388. if (!isFiniteNumber(pos)) {
  8389. return null;
  8390. }
  8391. const backwardSeek = this.lastCurrentTime > pos;
  8392. const maxBufferHole = backwardSeek || (_this$media2 = this.media) != null && _this$media2.paused ? 0 : this.config.maxBufferHole;
  8393. return this.getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole);
  8394. }
  8395. getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole) {
  8396. const bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);
  8397. if (bufferInfo.len === 0 && bufferInfo.nextStart !== void 0) {
  8398. const bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
  8399. if (bufferedFragAtPos && (bufferInfo.nextStart <= bufferedFragAtPos.end || bufferedFragAtPos.gap)) {
  8400. const gapDuration = Math.max(Math.min(bufferInfo.nextStart, bufferedFragAtPos.end) - pos, maxBufferHole);
  8401. return BufferHelper.bufferInfo(bufferable, pos, gapDuration);
  8402. }
  8403. }
  8404. return bufferInfo;
  8405. }
  8406. getMaxBufferLength(levelBitrate) {
  8407. const {
  8408. config
  8409. } = this;
  8410. let maxBufLen;
  8411. if (levelBitrate) {
  8412. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  8413. } else {
  8414. maxBufLen = config.maxBufferLength;
  8415. }
  8416. return Math.min(maxBufLen, config.maxMaxBufferLength);
  8417. }
  8418. reduceMaxBufferLength(threshold, fragDuration) {
  8419. const config = this.config;
  8420. const minLength = Math.max(Math.min(threshold - fragDuration, config.maxBufferLength), fragDuration);
  8421. const reducedLength = Math.max(threshold - fragDuration * 3, config.maxMaxBufferLength / 2, minLength);
  8422. if (reducedLength >= minLength) {
  8423. config.maxMaxBufferLength = reducedLength;
  8424. this.warn(`Reduce max buffer length to ${reducedLength}s`);
  8425. return true;
  8426. }
  8427. return false;
  8428. }
  8429. getAppendedFrag(position, playlistType = PlaylistLevelType.MAIN) {
  8430. const fragOrPart = this.fragmentTracker ? this.fragmentTracker.getAppendedFrag(position, playlistType) : null;
  8431. if (fragOrPart && "fragment" in fragOrPart) {
  8432. return fragOrPart.fragment;
  8433. }
  8434. return fragOrPart;
  8435. }
  8436. getNextFragment(pos, levelDetails) {
  8437. const fragments = levelDetails.fragments;
  8438. const fragLen = fragments.length;
  8439. if (!fragLen) {
  8440. return null;
  8441. }
  8442. const {
  8443. config
  8444. } = this;
  8445. const start = fragments[0].start;
  8446. const canLoadParts = config.lowLatencyMode && !!levelDetails.partList;
  8447. let frag = null;
  8448. if (levelDetails.live) {
  8449. const initialLiveManifestSize = config.initialLiveManifestSize;
  8450. if (fragLen < initialLiveManifestSize) {
  8451. this.warn(`Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`);
  8452. return null;
  8453. }
  8454. if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1 || pos < start) {
  8455. var _frag;
  8456. if (canLoadParts && !this.loadingParts) {
  8457. this.log(`LL-Part loading ON for initial live fragment`);
  8458. this.loadingParts = true;
  8459. }
  8460. frag = this.getInitialLiveFragment(levelDetails);
  8461. const mainStart = this.hls.startPosition;
  8462. const liveSyncPosition = this.hls.liveSyncPosition;
  8463. const startPosition = frag ? (mainStart !== -1 && mainStart >= start ? mainStart : liveSyncPosition) || frag.start : pos;
  8464. 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}`);
  8465. this.startPosition = this.nextLoadPosition = startPosition;
  8466. }
  8467. } else if (pos <= start) {
  8468. frag = fragments[0];
  8469. }
  8470. if (!frag) {
  8471. const end = this.loadingParts ? levelDetails.partEnd : levelDetails.fragmentEnd;
  8472. frag = this.getFragmentAtPosition(pos, end, levelDetails);
  8473. }
  8474. let programFrag = this.filterReplacedPrimary(frag, levelDetails);
  8475. if (!programFrag && frag) {
  8476. const curSNIdx = frag.sn - levelDetails.startSN;
  8477. programFrag = this.filterReplacedPrimary(fragments[curSNIdx + 1] || null, levelDetails);
  8478. }
  8479. return this.mapToInitFragWhenRequired(programFrag);
  8480. }
  8481. isLoopLoading(frag, targetBufferTime) {
  8482. const trackerState = this.fragmentTracker.getState(frag);
  8483. return (trackerState === FragmentState.OK || trackerState === FragmentState.PARTIAL && !!frag.gap) && this.nextLoadPosition > targetBufferTime;
  8484. }
  8485. getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, playlistType, maxBufLen) {
  8486. let nextFragment = null;
  8487. if (frag.gap) {
  8488. nextFragment = this.getNextFragment(this.nextLoadPosition, levelDetails);
  8489. if (nextFragment && !nextFragment.gap && bufferInfo.nextStart) {
  8490. const nextbufferInfo = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, bufferInfo.nextStart, playlistType, 0);
  8491. if (nextbufferInfo !== null && bufferInfo.len + nextbufferInfo.len >= maxBufLen) {
  8492. const sn = nextFragment.sn;
  8493. if (this.loopSn !== sn) {
  8494. this.log(`buffer full after gaps in "${playlistType}" playlist starting at sn: ${sn}`);
  8495. this.loopSn = sn;
  8496. }
  8497. return null;
  8498. }
  8499. }
  8500. }
  8501. this.loopSn = void 0;
  8502. return nextFragment;
  8503. }
  8504. get primaryPrefetch() {
  8505. if (interstitialsEnabled(this.config)) {
  8506. var _this$hls$interstitia;
  8507. const playingInterstitial = (_this$hls$interstitia = this.hls.interstitialsManager) == null || (_this$hls$interstitia = _this$hls$interstitia.playingItem) == null ? void 0 : _this$hls$interstitia.event;
  8508. if (playingInterstitial) {
  8509. return true;
  8510. }
  8511. }
  8512. return false;
  8513. }
  8514. filterReplacedPrimary(frag, details) {
  8515. if (!frag) {
  8516. return frag;
  8517. }
  8518. if (interstitialsEnabled(this.config) && frag.type !== PlaylistLevelType.SUBTITLE) {
  8519. const interstitials = this.hls.interstitialsManager;
  8520. const bufferingItem = interstitials == null ? void 0 : interstitials.bufferingItem;
  8521. if (bufferingItem) {
  8522. const bufferingInterstitial = bufferingItem.event;
  8523. if (bufferingInterstitial) {
  8524. if (bufferingInterstitial.appendInPlace || Math.abs(frag.start - bufferingItem.start) > 1 || bufferingItem.start === 0) {
  8525. return null;
  8526. }
  8527. } else {
  8528. if (frag.end <= bufferingItem.start && (details == null ? void 0 : details.live) === false) {
  8529. return null;
  8530. }
  8531. if (frag.start > bufferingItem.end && bufferingItem.nextEvent) {
  8532. if (bufferingItem.nextEvent.appendInPlace || frag.start - bufferingItem.end > 1) {
  8533. return null;
  8534. }
  8535. }
  8536. }
  8537. }
  8538. const playerQueue = interstitials == null ? void 0 : interstitials.playerQueue;
  8539. if (playerQueue) {
  8540. for (let i = playerQueue.length; i--; ) {
  8541. const interstitial = playerQueue[i].interstitial;
  8542. if (interstitial.appendInPlace && frag.start >= interstitial.startTime && frag.end <= interstitial.resumeTime) {
  8543. return null;
  8544. }
  8545. }
  8546. }
  8547. }
  8548. return frag;
  8549. }
  8550. mapToInitFragWhenRequired(frag) {
  8551. if (frag != null && frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
  8552. return frag.initSegment;
  8553. }
  8554. return frag;
  8555. }
  8556. getNextPart(partList, frag, targetBufferTime) {
  8557. let nextPart = -1;
  8558. let contiguous = false;
  8559. let independentAttrOmitted = true;
  8560. for (let i = 0, len = partList.length; i < len; i++) {
  8561. const part = partList[i];
  8562. independentAttrOmitted = independentAttrOmitted && !part.independent;
  8563. if (nextPart > -1 && targetBufferTime < part.start) {
  8564. break;
  8565. }
  8566. const loaded = part.loaded;
  8567. if (loaded) {
  8568. nextPart = -1;
  8569. } else if (contiguous || (part.independent || independentAttrOmitted) && part.fragment === frag) {
  8570. if (part.fragment !== frag) {
  8571. this.warn(`Need buffer at ${targetBufferTime} but next unloaded part starts at ${part.start}`);
  8572. }
  8573. nextPart = i;
  8574. }
  8575. contiguous = loaded;
  8576. }
  8577. return nextPart;
  8578. }
  8579. loadedEndOfParts(partList, targetBufferTime) {
  8580. let part;
  8581. for (let i = partList.length; i--; ) {
  8582. part = partList[i];
  8583. if (!part.loaded) {
  8584. return false;
  8585. }
  8586. if (targetBufferTime > part.start) {
  8587. return true;
  8588. }
  8589. }
  8590. return false;
  8591. }
  8592. /*
  8593. This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
  8594. "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
  8595. start and end times for each fragment in the playlist (after which this method will not need to be called).
  8596. */
  8597. getInitialLiveFragment(levelDetails) {
  8598. const fragments = levelDetails.fragments;
  8599. const fragPrevious = this.fragPrevious;
  8600. let frag = null;
  8601. if (fragPrevious) {
  8602. if (levelDetails.hasProgramDateTime) {
  8603. this.log(`Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`);
  8604. frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
  8605. }
  8606. if (!frag) {
  8607. const targetSN = fragPrevious.sn + 1;
  8608. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  8609. const fragNext = fragments[targetSN - levelDetails.startSN];
  8610. if (fragPrevious.cc === fragNext.cc) {
  8611. frag = fragNext;
  8612. this.log(`Live playlist, switching playlist, load frag with next SN: ${frag.sn}`);
  8613. }
  8614. }
  8615. if (!frag) {
  8616. frag = findNearestWithCC(levelDetails, fragPrevious.cc, fragPrevious.end);
  8617. if (frag) {
  8618. this.log(`Live playlist, switching playlist, load frag with same CC: ${frag.sn}`);
  8619. }
  8620. }
  8621. }
  8622. } else {
  8623. const liveStart = this.hls.liveSyncPosition;
  8624. if (liveStart !== null) {
  8625. frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
  8626. }
  8627. }
  8628. return frag;
  8629. }
  8630. /*
  8631. This method finds the best matching fragment given the provided position.
  8632. */
  8633. getFragmentAtPosition(bufferEnd, end, levelDetails) {
  8634. const {
  8635. config
  8636. } = this;
  8637. let {
  8638. fragPrevious
  8639. } = this;
  8640. let {
  8641. fragments,
  8642. endSN
  8643. } = levelDetails;
  8644. const {
  8645. fragmentHint
  8646. } = levelDetails;
  8647. const {
  8648. maxFragLookUpTolerance
  8649. } = config;
  8650. const partList = levelDetails.partList;
  8651. const loadingParts = !!(this.loadingParts && partList != null && partList.length && fragmentHint);
  8652. if (loadingParts && !this.bitrateTest && partList[partList.length - 1].fragment.sn === fragmentHint.sn) {
  8653. fragments = fragments.concat(fragmentHint);
  8654. endSN = fragmentHint.sn;
  8655. }
  8656. let frag;
  8657. if (bufferEnd < end) {
  8658. var _this$media3;
  8659. const backwardSeek = bufferEnd < this.lastCurrentTime;
  8660. const lookupTolerance = backwardSeek || bufferEnd > end - maxFragLookUpTolerance || (_this$media3 = this.media) != null && _this$media3.paused || !this.startFragRequested ? 0 : maxFragLookUpTolerance;
  8661. frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);
  8662. } else {
  8663. frag = fragments[fragments.length - 1];
  8664. }
  8665. if (frag) {
  8666. const curSNIdx = frag.sn - levelDetails.startSN;
  8667. const fragState = this.fragmentTracker.getState(frag);
  8668. if (fragState === FragmentState.OK || fragState === FragmentState.PARTIAL && frag.gap) {
  8669. fragPrevious = frag;
  8670. }
  8671. if (fragPrevious && frag.sn === fragPrevious.sn && (!loadingParts || partList[0].fragment.sn > frag.sn || !levelDetails.live)) {
  8672. const sameLevel = frag.level === fragPrevious.level;
  8673. if (sameLevel) {
  8674. const nextFrag = fragments[curSNIdx + 1];
  8675. if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== FragmentState.OK) {
  8676. frag = nextFrag;
  8677. } else {
  8678. frag = null;
  8679. }
  8680. }
  8681. }
  8682. }
  8683. return frag;
  8684. }
  8685. alignPlaylists(details, previousDetails, switchDetails) {
  8686. const length = details.fragments.length;
  8687. if (!length) {
  8688. this.warn(`No fragments in live playlist`);
  8689. return 0;
  8690. }
  8691. const slidingStart = details.fragmentStart;
  8692. const firstLevelLoad = !previousDetails;
  8693. const aligned = details.alignedSliding && isFiniteNumber(slidingStart);
  8694. if (firstLevelLoad || !aligned && !slidingStart) {
  8695. alignStream(switchDetails, details);
  8696. const alignedSlidingStart = details.fragmentStart;
  8697. this.log(`Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${previousDetails ? previousDetails.startSN : "na"}->${details.startSN} fragments: ${length}`);
  8698. return alignedSlidingStart;
  8699. }
  8700. return slidingStart;
  8701. }
  8702. waitForCdnTuneIn(details) {
  8703. const advancePartLimit = 3;
  8704. return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
  8705. }
  8706. setStartPosition(details, sliding) {
  8707. let startPosition = this.startPosition;
  8708. if (startPosition < sliding) {
  8709. startPosition = -1;
  8710. }
  8711. const timelineOffset = this.timelineOffset;
  8712. if (startPosition === -1) {
  8713. const offsetInMultivariantPlaylist = this.startTimeOffset !== null;
  8714. const startTimeOffset = offsetInMultivariantPlaylist ? this.startTimeOffset : details.startTimeOffset;
  8715. if (startTimeOffset !== null && isFiniteNumber(startTimeOffset)) {
  8716. startPosition = sliding + startTimeOffset;
  8717. if (startTimeOffset < 0) {
  8718. startPosition += details.edge;
  8719. }
  8720. startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
  8721. this.log(`Setting startPosition to ${startPosition} for start time offset ${startTimeOffset} found in ${offsetInMultivariantPlaylist ? "multivariant" : "media"} playlist`);
  8722. this.startPosition = startPosition;
  8723. } else if (details.live) {
  8724. startPosition = this.hls.liveSyncPosition || sliding;
  8725. this.log(`Setting startPosition to -1 to start at live edge ${startPosition}`);
  8726. this.startPosition = -1;
  8727. } else {
  8728. this.log(`setting startPosition to 0 by default`);
  8729. this.startPosition = startPosition = 0;
  8730. }
  8731. this.lastCurrentTime = startPosition + timelineOffset;
  8732. }
  8733. this.nextLoadPosition = startPosition + timelineOffset;
  8734. }
  8735. getLoadPosition() {
  8736. var _this$hls;
  8737. const {
  8738. media
  8739. } = this;
  8740. let pos = 0;
  8741. if ((_this$hls = this.hls) != null && _this$hls.hasEnoughToStart && media) {
  8742. pos = media.currentTime;
  8743. } else if (this.nextLoadPosition >= 0) {
  8744. pos = this.nextLoadPosition;
  8745. }
  8746. return pos;
  8747. }
  8748. handleFragLoadAborted(frag, part) {
  8749. if (this.transmuxer && frag.type === this.playlistType && isMediaFragment(frag) && frag.stats.aborted) {
  8750. this.log(`Fragment ${frag.sn}${part ? " part " + part.index : ""} of ${this.playlistLabel()} ${frag.level} was aborted`);
  8751. this.resetFragmentLoading(frag);
  8752. }
  8753. }
  8754. resetFragmentLoading(frag) {
  8755. if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) {
  8756. this.state = State.IDLE;
  8757. }
  8758. }
  8759. onFragmentOrKeyLoadError(filterType, data) {
  8760. var _this$hls$latestLevel;
  8761. if (data.chunkMeta && !data.frag) {
  8762. const context = this.getCurrentContext(data.chunkMeta);
  8763. if (context) {
  8764. data.frag = context.frag;
  8765. }
  8766. }
  8767. const frag = data.frag;
  8768. if (!frag || frag.type !== filterType || !this.levels) {
  8769. return;
  8770. }
  8771. if (this.fragContextChanged(frag)) {
  8772. var _this$fragCurrent;
  8773. this.warn(`Frag load error must match current frag to retry ${frag.url} > ${(_this$fragCurrent = this.fragCurrent) == null ? void 0 : _this$fragCurrent.url}`);
  8774. return;
  8775. }
  8776. const gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;
  8777. if (gapTagEncountered) {
  8778. this.fragmentTracker.fragBuffered(frag, true);
  8779. }
  8780. const errorAction = data.errorAction;
  8781. if (!errorAction) {
  8782. this.state = State.ERROR;
  8783. return;
  8784. }
  8785. const {
  8786. action,
  8787. flags,
  8788. retryCount = 0,
  8789. retryConfig
  8790. } = errorAction;
  8791. const couldRetry = !!retryConfig;
  8792. const retry = couldRetry && action === NetworkErrorAction.RetryRequest;
  8793. const noAlternate = couldRetry && !errorAction.resolved && flags === ErrorActionFlags.MoveAllAlternatesMatchingHost;
  8794. const live = (_this$hls$latestLevel = this.hls.latestLevelDetails) == null ? void 0 : _this$hls$latestLevel.live;
  8795. if (!retry && noAlternate && isMediaFragment(frag) && !frag.endList && live && !isUnusableKeyError(data)) {
  8796. this.resetFragmentErrors(filterType);
  8797. this.treatAsGap(frag);
  8798. errorAction.resolved = true;
  8799. } else if ((retry || noAlternate) && retryCount < retryConfig.maxNumRetry) {
  8800. var _data$response;
  8801. const offlineStatus = offlineHttpStatus((_data$response = data.response) == null ? void 0 : _data$response.code);
  8802. const delay = getRetryDelay(retryConfig, retryCount);
  8803. this.resetStartWhenNotLoaded();
  8804. this.retryDate = self.performance.now() + delay;
  8805. this.state = State.FRAG_LOADING_WAITING_RETRY;
  8806. errorAction.resolved = true;
  8807. if (offlineStatus) {
  8808. this.log(`Waiting for connection (offline)`);
  8809. this.retryDate = Infinity;
  8810. data.reason = "offline";
  8811. return;
  8812. }
  8813. this.warn(`Fragment ${frag.sn} of ${filterType} ${frag.level} errored with ${data.details}, retrying loading ${retryCount + 1}/${retryConfig.maxNumRetry} in ${delay}ms`);
  8814. } else if (retryConfig) {
  8815. this.resetFragmentErrors(filterType);
  8816. if (retryCount < retryConfig.maxNumRetry) {
  8817. if (!gapTagEncountered && action !== NetworkErrorAction.RemoveAlternatePermanently) {
  8818. errorAction.resolved = true;
  8819. }
  8820. } else {
  8821. this.warn(`${data.details} reached or exceeded max retry (${retryCount})`);
  8822. return;
  8823. }
  8824. } else if (action === NetworkErrorAction.SendAlternateToPenaltyBox) {
  8825. this.state = State.WAITING_LEVEL;
  8826. } else {
  8827. this.state = State.ERROR;
  8828. }
  8829. this.tickImmediate();
  8830. }
  8831. checkRetryDate() {
  8832. const now2 = self.performance.now();
  8833. const retryDate = this.retryDate;
  8834. const waitingForConnection = retryDate === Infinity;
  8835. if (!retryDate || now2 >= retryDate || waitingForConnection && !offlineHttpStatus(0)) {
  8836. if (waitingForConnection) {
  8837. this.log(`Connection restored (online)`);
  8838. }
  8839. this.resetStartWhenNotLoaded();
  8840. this.state = State.IDLE;
  8841. }
  8842. }
  8843. reduceLengthAndFlushBuffer(data) {
  8844. if (this.state === State.PARSING || this.state === State.PARSED) {
  8845. const frag = data.frag;
  8846. const playlistType = data.parent;
  8847. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  8848. const buffered = bufferedInfo && bufferedInfo.len > 0.5;
  8849. if (buffered) {
  8850. this.reduceMaxBufferLength(bufferedInfo.len, (frag == null ? void 0 : frag.duration) || 10);
  8851. }
  8852. const flushBuffer = !buffered;
  8853. if (flushBuffer) {
  8854. this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${playlistType} buffer`);
  8855. }
  8856. if (frag) {
  8857. this.fragmentTracker.removeFragment(frag);
  8858. this.nextLoadPosition = frag.start;
  8859. }
  8860. this.resetLoadingState();
  8861. return flushBuffer;
  8862. }
  8863. return false;
  8864. }
  8865. resetFragmentErrors(filterType) {
  8866. if (filterType === PlaylistLevelType.AUDIO) {
  8867. this.fragCurrent = null;
  8868. }
  8869. if (!this.hls.hasEnoughToStart) {
  8870. this.startFragRequested = false;
  8871. }
  8872. if (this.state !== State.STOPPED) {
  8873. this.state = State.IDLE;
  8874. }
  8875. }
  8876. afterBufferFlushed(media, bufferType, playlistType) {
  8877. if (!media) {
  8878. return;
  8879. }
  8880. const bufferedTimeRanges = BufferHelper.getBuffered(media);
  8881. this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
  8882. if (this.state === State.ENDED) {
  8883. this.resetLoadingState();
  8884. }
  8885. }
  8886. resetLoadingState() {
  8887. this.log("Reset loading state");
  8888. this.fragCurrent = null;
  8889. this.fragPrevious = null;
  8890. if (this.state !== State.STOPPED) {
  8891. this.state = State.IDLE;
  8892. }
  8893. }
  8894. resetStartWhenNotLoaded() {
  8895. if (!this.hls.hasEnoughToStart) {
  8896. this.startFragRequested = false;
  8897. const level = this.levelLastLoaded;
  8898. const details = level ? level.details : null;
  8899. if (details != null && details.live) {
  8900. this.log(`resetting startPosition for live start`);
  8901. this.startPosition = -1;
  8902. this.setStartPosition(details, details.fragmentStart);
  8903. this.resetLoadingState();
  8904. } else {
  8905. this.nextLoadPosition = this.startPosition;
  8906. }
  8907. }
  8908. }
  8909. resetWhenMissingContext(chunkMeta) {
  8910. this.log(`Loading context changed while buffering sn ${chunkMeta.sn} of ${this.playlistLabel()} ${chunkMeta.level === -1 ? "<removed>" : chunkMeta.level}. This chunk will not be buffered.`);
  8911. this.removeUnbufferedFrags();
  8912. this.resetStartWhenNotLoaded();
  8913. this.resetLoadingState();
  8914. }
  8915. removeUnbufferedFrags(start = 0) {
  8916. this.fragmentTracker.removeFragmentsInRange(start, Infinity, this.playlistType, false, true);
  8917. }
  8918. updateLevelTiming(frag, part, level, partial) {
  8919. const details = level.details;
  8920. if (!details) {
  8921. this.warn("level.details undefined");
  8922. return;
  8923. }
  8924. const parsed = Object.keys(frag.elementaryStreams).reduce((result, type) => {
  8925. const info = frag.elementaryStreams[type];
  8926. if (info) {
  8927. const parsedDuration = info.endPTS - info.startPTS;
  8928. if (parsedDuration <= 0) {
  8929. this.warn(`Could not parse fragment ${frag.sn} ${type} duration reliably (${parsedDuration})`);
  8930. return result || false;
  8931. }
  8932. const drift = partial ? 0 : updateFragPTSDTS(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS, this);
  8933. this.hls.trigger(Events.LEVEL_PTS_UPDATED, {
  8934. details,
  8935. level,
  8936. drift,
  8937. type,
  8938. frag,
  8939. start: info.startPTS,
  8940. end: info.endPTS
  8941. });
  8942. return true;
  8943. }
  8944. return result;
  8945. }, false);
  8946. if (!parsed) {
  8947. var _this$transmuxer;
  8948. if (level.fragmentError === 0) {
  8949. this.treatAsGap(frag, level);
  8950. }
  8951. if (((_this$transmuxer = this.transmuxer) == null ? void 0 : _this$transmuxer.error) === null) {
  8952. const error = new Error(`Found no media in fragment ${frag.sn} of ${this.playlistLabel()} ${frag.level} resetting transmuxer to fallback to playlist timing`);
  8953. this.warn(error.message);
  8954. this.hls.trigger(Events.ERROR, {
  8955. type: ErrorTypes.MEDIA_ERROR,
  8956. details: ErrorDetails.FRAG_PARSING_ERROR,
  8957. fatal: false,
  8958. error,
  8959. frag,
  8960. reason: `Found no media in msn ${frag.sn} of ${this.playlistLabel()} "${level.url}"`
  8961. });
  8962. if (!this.hls) {
  8963. return;
  8964. }
  8965. this.resetTransmuxer();
  8966. }
  8967. }
  8968. this.state = State.PARSED;
  8969. this.log(`Parsed ${frag.type} sn: ${frag.sn}${part ? " part: " + part.index : ""} of ${this.fragInfo(frag, false, part)})`);
  8970. this.hls.trigger(Events.FRAG_PARSED, {
  8971. frag,
  8972. part
  8973. });
  8974. }
  8975. playlistLabel() {
  8976. return this.playlistType === PlaylistLevelType.MAIN ? "level" : "track";
  8977. }
  8978. fragInfo(frag, pts = true, part) {
  8979. var _ref, _ref2;
  8980. 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") : ""}`;
  8981. }
  8982. treatAsGap(frag, level) {
  8983. if (level) {
  8984. level.fragmentError++;
  8985. }
  8986. frag.gap = true;
  8987. this.fragmentTracker.removeFragment(frag);
  8988. this.fragmentTracker.fragBuffered(frag, true);
  8989. }
  8990. resetTransmuxer() {
  8991. var _this$transmuxer2;
  8992. (_this$transmuxer2 = this.transmuxer) == null || _this$transmuxer2.reset();
  8993. }
  8994. recoverWorkerError(data) {
  8995. if (data.event === "demuxerWorker") {
  8996. this.fragmentTracker.removeAllFragments();
  8997. if (this.transmuxer) {
  8998. this.transmuxer.destroy();
  8999. this.transmuxer = null;
  9000. }
  9001. this.resetStartWhenNotLoaded();
  9002. this.resetLoadingState();
  9003. }
  9004. }
  9005. set state(nextState) {
  9006. const previousState = this._state;
  9007. if (previousState !== nextState) {
  9008. this._state = nextState;
  9009. this.log(`${previousState}->${nextState}`);
  9010. }
  9011. }
  9012. get state() {
  9013. return this._state;
  9014. }
  9015. };
  9016. function interstitialsEnabled(config) {
  9017. return !!config.interstitialsController && config.enableInterstitialPlayback !== false;
  9018. }
  9019. var ChunkCache = class {
  9020. constructor() {
  9021. this.chunks = [];
  9022. this.dataLength = 0;
  9023. }
  9024. push(chunk) {
  9025. this.chunks.push(chunk);
  9026. this.dataLength += chunk.length;
  9027. }
  9028. flush() {
  9029. const {
  9030. chunks,
  9031. dataLength
  9032. } = this;
  9033. let result;
  9034. if (!chunks.length) {
  9035. return new Uint8Array(0);
  9036. } else if (chunks.length === 1) {
  9037. result = chunks[0];
  9038. } else {
  9039. result = concatUint8Arrays(chunks, dataLength);
  9040. }
  9041. this.reset();
  9042. return result;
  9043. }
  9044. reset() {
  9045. this.chunks.length = 0;
  9046. this.dataLength = 0;
  9047. }
  9048. };
  9049. function concatUint8Arrays(chunks, dataLength) {
  9050. const result = new Uint8Array(dataLength);
  9051. let offset = 0;
  9052. for (let i = 0; i < chunks.length; i++) {
  9053. const chunk = chunks[i];
  9054. result.set(chunk, offset);
  9055. offset += chunk.length;
  9056. }
  9057. return result;
  9058. }
  9059. var eventemitter3 = { exports: {} };
  9060. var hasRequiredEventemitter3;
  9061. function requireEventemitter3() {
  9062. if (hasRequiredEventemitter3)
  9063. return eventemitter3.exports;
  9064. hasRequiredEventemitter3 = 1;
  9065. (function(module) {
  9066. var has = Object.prototype.hasOwnProperty, prefix = "~";
  9067. function Events2() {
  9068. }
  9069. if (Object.create) {
  9070. Events2.prototype = /* @__PURE__ */ Object.create(null);
  9071. if (!new Events2().__proto__)
  9072. prefix = false;
  9073. }
  9074. function EE(fn, context, once) {
  9075. this.fn = fn;
  9076. this.context = context;
  9077. this.once = once || false;
  9078. }
  9079. function addListener(emitter, event, fn, context, once) {
  9080. if (typeof fn !== "function") {
  9081. throw new TypeError("The listener must be a function");
  9082. }
  9083. var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
  9084. if (!emitter._events[evt])
  9085. emitter._events[evt] = listener, emitter._eventsCount++;
  9086. else if (!emitter._events[evt].fn)
  9087. emitter._events[evt].push(listener);
  9088. else
  9089. emitter._events[evt] = [emitter._events[evt], listener];
  9090. return emitter;
  9091. }
  9092. function clearEvent(emitter, evt) {
  9093. if (--emitter._eventsCount === 0)
  9094. emitter._events = new Events2();
  9095. else
  9096. delete emitter._events[evt];
  9097. }
  9098. function EventEmitter2() {
  9099. this._events = new Events2();
  9100. this._eventsCount = 0;
  9101. }
  9102. EventEmitter2.prototype.eventNames = function eventNames() {
  9103. var names = [], events, name;
  9104. if (this._eventsCount === 0)
  9105. return names;
  9106. for (name in events = this._events) {
  9107. if (has.call(events, name))
  9108. names.push(prefix ? name.slice(1) : name);
  9109. }
  9110. if (Object.getOwnPropertySymbols) {
  9111. return names.concat(Object.getOwnPropertySymbols(events));
  9112. }
  9113. return names;
  9114. };
  9115. EventEmitter2.prototype.listeners = function listeners(event) {
  9116. var evt = prefix ? prefix + event : event, handlers = this._events[evt];
  9117. if (!handlers)
  9118. return [];
  9119. if (handlers.fn)
  9120. return [handlers.fn];
  9121. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  9122. ee[i] = handlers[i].fn;
  9123. }
  9124. return ee;
  9125. };
  9126. EventEmitter2.prototype.listenerCount = function listenerCount(event) {
  9127. var evt = prefix ? prefix + event : event, listeners = this._events[evt];
  9128. if (!listeners)
  9129. return 0;
  9130. if (listeners.fn)
  9131. return 1;
  9132. return listeners.length;
  9133. };
  9134. EventEmitter2.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  9135. var evt = prefix ? prefix + event : event;
  9136. if (!this._events[evt])
  9137. return false;
  9138. var listeners = this._events[evt], len = arguments.length, args, i;
  9139. if (listeners.fn) {
  9140. if (listeners.once)
  9141. this.removeListener(event, listeners.fn, void 0, true);
  9142. switch (len) {
  9143. case 1:
  9144. return listeners.fn.call(listeners.context), true;
  9145. case 2:
  9146. return listeners.fn.call(listeners.context, a1), true;
  9147. case 3:
  9148. return listeners.fn.call(listeners.context, a1, a2), true;
  9149. case 4:
  9150. return listeners.fn.call(listeners.context, a1, a2, a3), true;
  9151. case 5:
  9152. return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  9153. case 6:
  9154. return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  9155. }
  9156. for (i = 1, args = new Array(len - 1); i < len; i++) {
  9157. args[i - 1] = arguments[i];
  9158. }
  9159. listeners.fn.apply(listeners.context, args);
  9160. } else {
  9161. var length = listeners.length, j;
  9162. for (i = 0; i < length; i++) {
  9163. if (listeners[i].once)
  9164. this.removeListener(event, listeners[i].fn, void 0, true);
  9165. switch (len) {
  9166. case 1:
  9167. listeners[i].fn.call(listeners[i].context);
  9168. break;
  9169. case 2:
  9170. listeners[i].fn.call(listeners[i].context, a1);
  9171. break;
  9172. case 3:
  9173. listeners[i].fn.call(listeners[i].context, a1, a2);
  9174. break;
  9175. case 4:
  9176. listeners[i].fn.call(listeners[i].context, a1, a2, a3);
  9177. break;
  9178. default:
  9179. if (!args)
  9180. for (j = 1, args = new Array(len - 1); j < len; j++) {
  9181. args[j - 1] = arguments[j];
  9182. }
  9183. listeners[i].fn.apply(listeners[i].context, args);
  9184. }
  9185. }
  9186. }
  9187. return true;
  9188. };
  9189. EventEmitter2.prototype.on = function on(event, fn, context) {
  9190. return addListener(this, event, fn, context, false);
  9191. };
  9192. EventEmitter2.prototype.once = function once(event, fn, context) {
  9193. return addListener(this, event, fn, context, true);
  9194. };
  9195. EventEmitter2.prototype.removeListener = function removeListener(event, fn, context, once) {
  9196. var evt = prefix ? prefix + event : event;
  9197. if (!this._events[evt])
  9198. return this;
  9199. if (!fn) {
  9200. clearEvent(this, evt);
  9201. return this;
  9202. }
  9203. var listeners = this._events[evt];
  9204. if (listeners.fn) {
  9205. if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
  9206. clearEvent(this, evt);
  9207. }
  9208. } else {
  9209. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  9210. if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
  9211. events.push(listeners[i]);
  9212. }
  9213. }
  9214. if (events.length)
  9215. this._events[evt] = events.length === 1 ? events[0] : events;
  9216. else
  9217. clearEvent(this, evt);
  9218. }
  9219. return this;
  9220. };
  9221. EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) {
  9222. var evt;
  9223. if (event) {
  9224. evt = prefix ? prefix + event : event;
  9225. if (this._events[evt])
  9226. clearEvent(this, evt);
  9227. } else {
  9228. this._events = new Events2();
  9229. this._eventsCount = 0;
  9230. }
  9231. return this;
  9232. };
  9233. EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
  9234. EventEmitter2.prototype.addListener = EventEmitter2.prototype.on;
  9235. EventEmitter2.prefixed = prefix;
  9236. EventEmitter2.EventEmitter = EventEmitter2;
  9237. {
  9238. module.exports = EventEmitter2;
  9239. }
  9240. })(eventemitter3);
  9241. return eventemitter3.exports;
  9242. }
  9243. var eventemitter3Exports = requireEventemitter3();
  9244. var EventEmitter = getDefaultExportFromCjs(eventemitter3Exports);
  9245. var version = "1.6.13";
  9246. var workerStore = {};
  9247. function hasUMDWorker() {
  9248. return typeof __HLS_WORKER_BUNDLE__ === "function";
  9249. }
  9250. function injectWorker() {
  9251. const workerContext = workerStore[version];
  9252. if (workerContext) {
  9253. workerContext.clientCount++;
  9254. return workerContext;
  9255. }
  9256. const blob = new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`], {
  9257. type: "text/javascript"
  9258. });
  9259. const objectURL = self.URL.createObjectURL(blob);
  9260. const worker = new self.Worker(objectURL);
  9261. const result = {
  9262. worker,
  9263. objectURL,
  9264. clientCount: 1
  9265. };
  9266. workerStore[version] = result;
  9267. return result;
  9268. }
  9269. function loadWorker(path) {
  9270. const workerContext = workerStore[path];
  9271. if (workerContext) {
  9272. workerContext.clientCount++;
  9273. return workerContext;
  9274. }
  9275. const scriptURL = new self.URL(path, self.location.href).href;
  9276. const worker = new self.Worker(scriptURL);
  9277. const result = {
  9278. worker,
  9279. scriptURL,
  9280. clientCount: 1
  9281. };
  9282. workerStore[path] = result;
  9283. return result;
  9284. }
  9285. function removeWorkerFromStore(path) {
  9286. const workerContext = workerStore[path || version];
  9287. if (workerContext) {
  9288. const clientCount = workerContext.clientCount--;
  9289. if (clientCount === 1) {
  9290. const {
  9291. worker,
  9292. objectURL
  9293. } = workerContext;
  9294. delete workerStore[path || version];
  9295. if (objectURL) {
  9296. self.URL.revokeObjectURL(objectURL);
  9297. }
  9298. worker.terminate();
  9299. }
  9300. }
  9301. }
  9302. function isId3Footer(data, offset) {
  9303. if (offset + 10 <= data.length) {
  9304. if (data[offset] === 51 && data[offset + 1] === 68 && data[offset + 2] === 73) {
  9305. if (data[offset + 3] < 255 && data[offset + 4] < 255) {
  9306. if (data[offset + 6] < 128 && data[offset + 7] < 128 && data[offset + 8] < 128 && data[offset + 9] < 128) {
  9307. return true;
  9308. }
  9309. }
  9310. }
  9311. }
  9312. return false;
  9313. }
  9314. function isId3Header(data, offset) {
  9315. if (offset + 10 <= data.length) {
  9316. if (data[offset] === 73 && data[offset + 1] === 68 && data[offset + 2] === 51) {
  9317. if (data[offset + 3] < 255 && data[offset + 4] < 255) {
  9318. if (data[offset + 6] < 128 && data[offset + 7] < 128 && data[offset + 8] < 128 && data[offset + 9] < 128) {
  9319. return true;
  9320. }
  9321. }
  9322. }
  9323. }
  9324. return false;
  9325. }
  9326. function readId3Size(data, offset) {
  9327. let size = 0;
  9328. size = (data[offset] & 127) << 21;
  9329. size |= (data[offset + 1] & 127) << 14;
  9330. size |= (data[offset + 2] & 127) << 7;
  9331. size |= data[offset + 3] & 127;
  9332. return size;
  9333. }
  9334. function getId3Data(data, offset) {
  9335. const front = offset;
  9336. let length = 0;
  9337. while (isId3Header(data, offset)) {
  9338. length += 10;
  9339. const size = readId3Size(data, offset + 6);
  9340. length += size;
  9341. if (isId3Footer(data, offset + 10)) {
  9342. length += 10;
  9343. }
  9344. offset += length;
  9345. }
  9346. if (length > 0) {
  9347. return data.subarray(front, front + length);
  9348. }
  9349. return void 0;
  9350. }
  9351. function getAudioConfig(observer, data, offset, manifestCodec) {
  9352. const adtsSamplingRates = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350];
  9353. const byte2 = data[offset + 2];
  9354. const adtsSamplingIndex = byte2 >> 2 & 15;
  9355. if (adtsSamplingIndex > 12) {
  9356. const error = new Error(`invalid ADTS sampling index:${adtsSamplingIndex}`);
  9357. observer.emit(Events.ERROR, Events.ERROR, {
  9358. type: ErrorTypes.MEDIA_ERROR,
  9359. details: ErrorDetails.FRAG_PARSING_ERROR,
  9360. fatal: true,
  9361. error,
  9362. reason: error.message
  9363. });
  9364. return;
  9365. }
  9366. const adtsObjectType = (byte2 >> 6 & 3) + 1;
  9367. const channelCount = data[offset + 3] >> 6 & 3 | (byte2 & 1) << 2;
  9368. const codec = "mp4a.40." + adtsObjectType;
  9369. const samplerate = adtsSamplingRates[adtsSamplingIndex];
  9370. let aacSampleIndex = adtsSamplingIndex;
  9371. if (adtsObjectType === 5 || adtsObjectType === 29) {
  9372. aacSampleIndex -= 3;
  9373. }
  9374. const config = [adtsObjectType << 3 | (aacSampleIndex & 14) >> 1, (aacSampleIndex & 1) << 7 | channelCount << 3];
  9375. logger.log(`manifest codec:${manifestCodec}, parsed codec:${codec}, channels:${channelCount}, rate:${samplerate} (ADTS object type:${adtsObjectType} sampling index:${adtsSamplingIndex})`);
  9376. return {
  9377. config,
  9378. samplerate,
  9379. channelCount,
  9380. codec,
  9381. parsedCodec: codec,
  9382. manifestCodec
  9383. };
  9384. }
  9385. function isHeaderPattern$1(data, offset) {
  9386. return data[offset] === 255 && (data[offset + 1] & 246) === 240;
  9387. }
  9388. function getHeaderLength(data, offset) {
  9389. return data[offset + 1] & 1 ? 7 : 9;
  9390. }
  9391. function getFullFrameLength(data, offset) {
  9392. return (data[offset + 3] & 3) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 224) >>> 5;
  9393. }
  9394. function canGetFrameLength(data, offset) {
  9395. return offset + 5 < data.length;
  9396. }
  9397. function isHeader$1(data, offset) {
  9398. return offset + 1 < data.length && isHeaderPattern$1(data, offset);
  9399. }
  9400. function canParse$1(data, offset) {
  9401. return canGetFrameLength(data, offset) && isHeaderPattern$1(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
  9402. }
  9403. function probe$1(data, offset) {
  9404. if (isHeader$1(data, offset)) {
  9405. const headerLength = getHeaderLength(data, offset);
  9406. if (offset + headerLength >= data.length) {
  9407. return false;
  9408. }
  9409. const frameLength = getFullFrameLength(data, offset);
  9410. if (frameLength <= headerLength) {
  9411. return false;
  9412. }
  9413. const newOffset = offset + frameLength;
  9414. return newOffset === data.length || isHeader$1(data, newOffset);
  9415. }
  9416. return false;
  9417. }
  9418. function initTrackConfig(track, observer, data, offset, audioCodec) {
  9419. if (!track.samplerate) {
  9420. const config = getAudioConfig(observer, data, offset, audioCodec);
  9421. if (!config) {
  9422. return;
  9423. }
  9424. _extends(track, config);
  9425. }
  9426. }
  9427. function getFrameDuration(samplerate) {
  9428. return 1024 * 9e4 / samplerate;
  9429. }
  9430. function parseFrameHeader(data, offset) {
  9431. const headerLength = getHeaderLength(data, offset);
  9432. if (offset + headerLength <= data.length) {
  9433. const frameLength = getFullFrameLength(data, offset) - headerLength;
  9434. if (frameLength > 0) {
  9435. return {
  9436. headerLength,
  9437. frameLength
  9438. };
  9439. }
  9440. }
  9441. }
  9442. function appendFrame$2(track, data, offset, pts, frameIndex) {
  9443. const frameDuration = getFrameDuration(track.samplerate);
  9444. const stamp = pts + frameIndex * frameDuration;
  9445. const header = parseFrameHeader(data, offset);
  9446. let unit;
  9447. if (header) {
  9448. const {
  9449. frameLength,
  9450. headerLength
  9451. } = header;
  9452. const _length = headerLength + frameLength;
  9453. const missing = Math.max(0, offset + _length - data.length);
  9454. if (missing) {
  9455. unit = new Uint8Array(_length - headerLength);
  9456. unit.set(data.subarray(offset + headerLength, data.length), 0);
  9457. } else {
  9458. unit = data.subarray(offset + headerLength, offset + _length);
  9459. }
  9460. const _sample = {
  9461. unit,
  9462. pts: stamp
  9463. };
  9464. if (!missing) {
  9465. track.samples.push(_sample);
  9466. }
  9467. return {
  9468. sample: _sample,
  9469. length: _length,
  9470. missing
  9471. };
  9472. }
  9473. const length = data.length - offset;
  9474. unit = new Uint8Array(length);
  9475. unit.set(data.subarray(offset, data.length), 0);
  9476. const sample = {
  9477. unit,
  9478. pts: stamp
  9479. };
  9480. return {
  9481. sample,
  9482. length,
  9483. missing: -1
  9484. };
  9485. }
  9486. function canParseId3(data, offset) {
  9487. return isId3Header(data, offset) && readId3Size(data, offset + 6) + 10 <= data.length - offset;
  9488. }
  9489. function toArrayBuffer(view2) {
  9490. if (view2 instanceof ArrayBuffer) {
  9491. return view2;
  9492. } else {
  9493. if (view2.byteOffset == 0 && view2.byteLength == view2.buffer.byteLength) {
  9494. return view2.buffer;
  9495. }
  9496. return new Uint8Array(view2).buffer;
  9497. }
  9498. }
  9499. function toUint8(data, offset = 0, length = Infinity) {
  9500. return view(data, offset, length, Uint8Array);
  9501. }
  9502. function view(data, offset, length, Type) {
  9503. const buffer = unsafeGetArrayBuffer(data);
  9504. let bytesPerElement = 1;
  9505. if ("BYTES_PER_ELEMENT" in Type) {
  9506. bytesPerElement = Type.BYTES_PER_ELEMENT;
  9507. }
  9508. const dataOffset = isArrayBufferView(data) ? data.byteOffset : 0;
  9509. const dataEnd = (dataOffset + data.byteLength) / bytesPerElement;
  9510. const rawStart = (dataOffset + offset) / bytesPerElement;
  9511. const start = Math.floor(Math.max(0, Math.min(rawStart, dataEnd)));
  9512. const end = Math.floor(Math.min(start + Math.max(length, 0), dataEnd));
  9513. return new Type(buffer, start, end - start);
  9514. }
  9515. function unsafeGetArrayBuffer(view2) {
  9516. if (view2 instanceof ArrayBuffer) {
  9517. return view2;
  9518. } else {
  9519. return view2.buffer;
  9520. }
  9521. }
  9522. function isArrayBufferView(obj) {
  9523. return obj && obj.buffer instanceof ArrayBuffer && obj.byteLength !== void 0 && obj.byteOffset !== void 0;
  9524. }
  9525. function decodeId3ImageFrame(frame) {
  9526. const metadataFrame = {
  9527. key: frame.type,
  9528. description: "",
  9529. data: "",
  9530. mimeType: null,
  9531. pictureType: null
  9532. };
  9533. const utf8Encoding = 3;
  9534. if (frame.size < 2) {
  9535. return void 0;
  9536. }
  9537. if (frame.data[0] !== utf8Encoding) {
  9538. console.log("Ignore frame with unrecognized character encoding");
  9539. return void 0;
  9540. }
  9541. const mimeTypeEndIndex = frame.data.subarray(1).indexOf(0);
  9542. if (mimeTypeEndIndex === -1) {
  9543. return void 0;
  9544. }
  9545. const mimeType = utf8ArrayToStr(toUint8(frame.data, 1, mimeTypeEndIndex));
  9546. const pictureType = frame.data[2 + mimeTypeEndIndex];
  9547. const descriptionEndIndex = frame.data.subarray(3 + mimeTypeEndIndex).indexOf(0);
  9548. if (descriptionEndIndex === -1) {
  9549. return void 0;
  9550. }
  9551. const description = utf8ArrayToStr(toUint8(frame.data, 3 + mimeTypeEndIndex, descriptionEndIndex));
  9552. let data;
  9553. if (mimeType === "-->") {
  9554. data = utf8ArrayToStr(toUint8(frame.data, 4 + mimeTypeEndIndex + descriptionEndIndex));
  9555. } else {
  9556. data = toArrayBuffer(frame.data.subarray(4 + mimeTypeEndIndex + descriptionEndIndex));
  9557. }
  9558. metadataFrame.mimeType = mimeType;
  9559. metadataFrame.pictureType = pictureType;
  9560. metadataFrame.description = description;
  9561. metadataFrame.data = data;
  9562. return metadataFrame;
  9563. }
  9564. function decodeId3PrivFrame(frame) {
  9565. if (frame.size < 2) {
  9566. return void 0;
  9567. }
  9568. const owner = utf8ArrayToStr(frame.data, true);
  9569. const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  9570. return {
  9571. key: frame.type,
  9572. info: owner,
  9573. data: privateData.buffer
  9574. };
  9575. }
  9576. function decodeId3TextFrame(frame) {
  9577. if (frame.size < 2) {
  9578. return void 0;
  9579. }
  9580. if (frame.type === "TXXX") {
  9581. let index = 1;
  9582. const description = utf8ArrayToStr(frame.data.subarray(index), true);
  9583. index += description.length + 1;
  9584. const value = utf8ArrayToStr(frame.data.subarray(index));
  9585. return {
  9586. key: frame.type,
  9587. info: description,
  9588. data: value
  9589. };
  9590. }
  9591. const text = utf8ArrayToStr(frame.data.subarray(1));
  9592. return {
  9593. key: frame.type,
  9594. info: "",
  9595. data: text
  9596. };
  9597. }
  9598. function decodeId3UrlFrame(frame) {
  9599. if (frame.type === "WXXX") {
  9600. if (frame.size < 2) {
  9601. return void 0;
  9602. }
  9603. let index = 1;
  9604. const description = utf8ArrayToStr(frame.data.subarray(index), true);
  9605. index += description.length + 1;
  9606. const value = utf8ArrayToStr(frame.data.subarray(index));
  9607. return {
  9608. key: frame.type,
  9609. info: description,
  9610. data: value
  9611. };
  9612. }
  9613. const url = utf8ArrayToStr(frame.data);
  9614. return {
  9615. key: frame.type,
  9616. info: "",
  9617. data: url
  9618. };
  9619. }
  9620. function decodeId3Frame(frame) {
  9621. if (frame.type === "PRIV") {
  9622. return decodeId3PrivFrame(frame);
  9623. } else if (frame.type[0] === "W") {
  9624. return decodeId3UrlFrame(frame);
  9625. } else if (frame.type === "APIC") {
  9626. return decodeId3ImageFrame(frame);
  9627. }
  9628. return decodeId3TextFrame(frame);
  9629. }
  9630. function getId3FrameData(data) {
  9631. const type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  9632. const size = readId3Size(data, 4);
  9633. const offset = 10;
  9634. return {
  9635. type,
  9636. size,
  9637. data: data.subarray(offset, offset + size)
  9638. };
  9639. }
  9640. var HEADER_FOOTER_SIZE = 10;
  9641. var FRAME_SIZE = 10;
  9642. function getId3Frames(id3Data) {
  9643. let offset = 0;
  9644. const frames = [];
  9645. while (isId3Header(id3Data, offset)) {
  9646. const size = readId3Size(id3Data, offset + 6);
  9647. if (id3Data[offset + 5] >> 6 & 1) {
  9648. offset += HEADER_FOOTER_SIZE;
  9649. }
  9650. offset += HEADER_FOOTER_SIZE;
  9651. const end = offset + size;
  9652. while (offset + FRAME_SIZE < end) {
  9653. const frameData = getId3FrameData(id3Data.subarray(offset));
  9654. const frame = decodeId3Frame(frameData);
  9655. if (frame) {
  9656. frames.push(frame);
  9657. }
  9658. offset += frameData.size + HEADER_FOOTER_SIZE;
  9659. }
  9660. if (isId3Footer(id3Data, offset)) {
  9661. offset += HEADER_FOOTER_SIZE;
  9662. }
  9663. }
  9664. return frames;
  9665. }
  9666. function isId3TimestampFrame(frame) {
  9667. return frame && frame.key === "PRIV" && frame.info === "com.apple.streaming.transportStreamTimestamp";
  9668. }
  9669. function readId3Timestamp(timeStampFrame) {
  9670. if (timeStampFrame.data.byteLength === 8) {
  9671. const data = new Uint8Array(timeStampFrame.data);
  9672. const pts33Bit = data[3] & 1;
  9673. let timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  9674. timestamp /= 45;
  9675. if (pts33Bit) {
  9676. timestamp += 4772185884e-2;
  9677. }
  9678. return Math.round(timestamp);
  9679. }
  9680. return void 0;
  9681. }
  9682. function getId3Timestamp(data) {
  9683. const frames = getId3Frames(data);
  9684. for (let i = 0; i < frames.length; i++) {
  9685. const frame = frames[i];
  9686. if (isId3TimestampFrame(frame)) {
  9687. return readId3Timestamp(frame);
  9688. }
  9689. }
  9690. return void 0;
  9691. }
  9692. var MetadataSchema = function(MetadataSchema2) {
  9693. MetadataSchema2["audioId3"] = "org.id3";
  9694. MetadataSchema2["dateRange"] = "com.apple.quicktime.HLS";
  9695. MetadataSchema2["emsg"] = "https://aomedia.org/emsg/ID3";
  9696. MetadataSchema2["misbklv"] = "urn:misb:KLV:bin:1910.1";
  9697. return MetadataSchema2;
  9698. }({});
  9699. function dummyTrack(type = "", inputTimeScale = 9e4) {
  9700. return {
  9701. type,
  9702. id: -1,
  9703. pid: -1,
  9704. inputTimeScale,
  9705. sequenceNumber: -1,
  9706. samples: [],
  9707. dropped: 0
  9708. };
  9709. }
  9710. var BaseAudioDemuxer = class {
  9711. constructor() {
  9712. this._audioTrack = void 0;
  9713. this._id3Track = void 0;
  9714. this.frameIndex = 0;
  9715. this.cachedData = null;
  9716. this.basePTS = null;
  9717. this.initPTS = null;
  9718. this.lastPTS = null;
  9719. }
  9720. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  9721. this._id3Track = {
  9722. type: "id3",
  9723. id: 3,
  9724. pid: -1,
  9725. inputTimeScale: 9e4,
  9726. sequenceNumber: 0,
  9727. samples: [],
  9728. dropped: 0
  9729. };
  9730. }
  9731. resetTimeStamp(deaultTimestamp) {
  9732. this.initPTS = deaultTimestamp;
  9733. this.resetContiguity();
  9734. }
  9735. resetContiguity() {
  9736. this.basePTS = null;
  9737. this.lastPTS = null;
  9738. this.frameIndex = 0;
  9739. }
  9740. canParse(data, offset) {
  9741. return false;
  9742. }
  9743. appendFrame(track, data, offset) {
  9744. }
  9745. // feed incoming data to the front of the parsing pipeline
  9746. demux(data, timeOffset) {
  9747. if (this.cachedData) {
  9748. data = appendUint8Array(this.cachedData, data);
  9749. this.cachedData = null;
  9750. }
  9751. let id3Data = getId3Data(data, 0);
  9752. let offset = id3Data ? id3Data.length : 0;
  9753. let lastDataIndex;
  9754. const track = this._audioTrack;
  9755. const id3Track = this._id3Track;
  9756. const timestamp = id3Data ? getId3Timestamp(id3Data) : void 0;
  9757. const length = data.length;
  9758. if (this.basePTS === null || this.frameIndex === 0 && isFiniteNumber(timestamp)) {
  9759. this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);
  9760. this.lastPTS = this.basePTS;
  9761. }
  9762. if (this.lastPTS === null) {
  9763. this.lastPTS = this.basePTS;
  9764. }
  9765. if (id3Data && id3Data.length > 0) {
  9766. id3Track.samples.push({
  9767. pts: this.lastPTS,
  9768. dts: this.lastPTS,
  9769. data: id3Data,
  9770. type: MetadataSchema.audioId3,
  9771. duration: Number.POSITIVE_INFINITY
  9772. });
  9773. }
  9774. while (offset < length) {
  9775. if (this.canParse(data, offset)) {
  9776. const frame = this.appendFrame(track, data, offset);
  9777. if (frame) {
  9778. this.frameIndex++;
  9779. this.lastPTS = frame.sample.pts;
  9780. offset += frame.length;
  9781. lastDataIndex = offset;
  9782. } else {
  9783. offset = length;
  9784. }
  9785. } else if (canParseId3(data, offset)) {
  9786. id3Data = getId3Data(data, offset);
  9787. id3Track.samples.push({
  9788. pts: this.lastPTS,
  9789. dts: this.lastPTS,
  9790. data: id3Data,
  9791. type: MetadataSchema.audioId3,
  9792. duration: Number.POSITIVE_INFINITY
  9793. });
  9794. offset += id3Data.length;
  9795. lastDataIndex = offset;
  9796. } else {
  9797. offset++;
  9798. }
  9799. if (offset === length && lastDataIndex !== length) {
  9800. const partialData = data.slice(lastDataIndex);
  9801. if (this.cachedData) {
  9802. this.cachedData = appendUint8Array(this.cachedData, partialData);
  9803. } else {
  9804. this.cachedData = partialData;
  9805. }
  9806. }
  9807. }
  9808. return {
  9809. audioTrack: track,
  9810. videoTrack: dummyTrack(),
  9811. id3Track,
  9812. textTrack: dummyTrack()
  9813. };
  9814. }
  9815. demuxSampleAes(data, keyData, timeOffset) {
  9816. return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`));
  9817. }
  9818. flush(timeOffset) {
  9819. const cachedData = this.cachedData;
  9820. if (cachedData) {
  9821. this.cachedData = null;
  9822. this.demux(cachedData, 0);
  9823. }
  9824. return {
  9825. audioTrack: this._audioTrack,
  9826. videoTrack: dummyTrack(),
  9827. id3Track: this._id3Track,
  9828. textTrack: dummyTrack()
  9829. };
  9830. }
  9831. destroy() {
  9832. this.cachedData = null;
  9833. this._audioTrack = this._id3Track = void 0;
  9834. }
  9835. };
  9836. var initPTSFn = (timestamp, timeOffset, initPTS) => {
  9837. if (isFiniteNumber(timestamp)) {
  9838. return timestamp * 90;
  9839. }
  9840. const init90kHz = initPTS ? initPTS.baseTime * 9e4 / initPTS.timescale : 0;
  9841. return timeOffset * 9e4 + init90kHz;
  9842. };
  9843. var chromeVersion$1 = null;
  9844. 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];
  9845. var SamplingRateMap = [44100, 48e3, 32e3, 22050, 24e3, 16e3, 11025, 12e3, 8e3];
  9846. var SamplesCoefficients = [
  9847. // MPEG 2.5
  9848. [
  9849. 0,
  9850. // Reserved
  9851. 72,
  9852. // Layer3
  9853. 144,
  9854. // Layer2
  9855. 12
  9856. // Layer1
  9857. ],
  9858. // Reserved
  9859. [
  9860. 0,
  9861. // Reserved
  9862. 0,
  9863. // Layer3
  9864. 0,
  9865. // Layer2
  9866. 0
  9867. // Layer1
  9868. ],
  9869. // MPEG 2
  9870. [
  9871. 0,
  9872. // Reserved
  9873. 72,
  9874. // Layer3
  9875. 144,
  9876. // Layer2
  9877. 12
  9878. // Layer1
  9879. ],
  9880. // MPEG 1
  9881. [
  9882. 0,
  9883. // Reserved
  9884. 144,
  9885. // Layer3
  9886. 144,
  9887. // Layer2
  9888. 12
  9889. // Layer1
  9890. ]
  9891. ];
  9892. var BytesInSlot = [
  9893. 0,
  9894. // Reserved
  9895. 1,
  9896. // Layer3
  9897. 1,
  9898. // Layer2
  9899. 4
  9900. // Layer1
  9901. ];
  9902. function appendFrame$1(track, data, offset, pts, frameIndex) {
  9903. if (offset + 24 > data.length) {
  9904. return;
  9905. }
  9906. const header = parseHeader(data, offset);
  9907. if (header && offset + header.frameLength <= data.length) {
  9908. const frameDuration = header.samplesPerFrame * 9e4 / header.sampleRate;
  9909. const stamp = pts + frameIndex * frameDuration;
  9910. const sample = {
  9911. unit: data.subarray(offset, offset + header.frameLength),
  9912. pts: stamp,
  9913. dts: stamp
  9914. };
  9915. track.config = [];
  9916. track.channelCount = header.channelCount;
  9917. track.samplerate = header.sampleRate;
  9918. track.samples.push(sample);
  9919. return {
  9920. sample,
  9921. length: header.frameLength,
  9922. missing: 0
  9923. };
  9924. }
  9925. }
  9926. function parseHeader(data, offset) {
  9927. const mpegVersion = data[offset + 1] >> 3 & 3;
  9928. const mpegLayer = data[offset + 1] >> 1 & 3;
  9929. const bitRateIndex = data[offset + 2] >> 4 & 15;
  9930. const sampleRateIndex = data[offset + 2] >> 2 & 3;
  9931. if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
  9932. const paddingBit = data[offset + 2] >> 1 & 1;
  9933. const channelMode = data[offset + 3] >> 6;
  9934. const columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
  9935. const bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1e3;
  9936. const columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
  9937. const sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
  9938. const channelCount = channelMode === 3 ? 1 : 2;
  9939. const sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
  9940. const bytesInSlot = BytesInSlot[mpegLayer];
  9941. const samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  9942. const frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
  9943. if (chromeVersion$1 === null) {
  9944. const userAgent = navigator.userAgent || "";
  9945. const result = userAgent.match(/Chrome\/(\d+)/i);
  9946. chromeVersion$1 = result ? parseInt(result[1]) : 0;
  9947. }
  9948. const needChromeFix = !!chromeVersion$1 && chromeVersion$1 <= 87;
  9949. if (needChromeFix && mpegLayer === 2 && bitRate >= 224e3 && channelMode === 0) {
  9950. data[offset + 3] = data[offset + 3] | 128;
  9951. }
  9952. return {
  9953. sampleRate,
  9954. channelCount,
  9955. frameLength,
  9956. samplesPerFrame
  9957. };
  9958. }
  9959. }
  9960. function isHeaderPattern(data, offset) {
  9961. return data[offset] === 255 && (data[offset + 1] & 224) === 224 && (data[offset + 1] & 6) !== 0;
  9962. }
  9963. function isHeader(data, offset) {
  9964. return offset + 1 < data.length && isHeaderPattern(data, offset);
  9965. }
  9966. function canParse(data, offset) {
  9967. const headerSize = 4;
  9968. return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
  9969. }
  9970. function probe(data, offset) {
  9971. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  9972. const headerLength = 4;
  9973. const header = parseHeader(data, offset);
  9974. let frameLength = headerLength;
  9975. if (header != null && header.frameLength) {
  9976. frameLength = header.frameLength;
  9977. }
  9978. const newOffset = offset + frameLength;
  9979. return newOffset === data.length || isHeader(data, newOffset);
  9980. }
  9981. return false;
  9982. }
  9983. var AACDemuxer = class extends BaseAudioDemuxer {
  9984. constructor(observer, config) {
  9985. super();
  9986. this.observer = void 0;
  9987. this.config = void 0;
  9988. this.observer = observer;
  9989. this.config = config;
  9990. }
  9991. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  9992. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  9993. this._audioTrack = {
  9994. container: "audio/adts",
  9995. type: "audio",
  9996. id: 2,
  9997. pid: -1,
  9998. sequenceNumber: 0,
  9999. segmentCodec: "aac",
  10000. samples: [],
  10001. manifestCodec: audioCodec,
  10002. duration: trackDuration,
  10003. inputTimeScale: 9e4,
  10004. dropped: 0
  10005. };
  10006. }
  10007. // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
  10008. static probe(data, logger2) {
  10009. if (!data) {
  10010. return false;
  10011. }
  10012. const id3Data = getId3Data(data, 0);
  10013. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  10014. if (probe(data, offset)) {
  10015. return false;
  10016. }
  10017. for (let length = data.length; offset < length; offset++) {
  10018. if (probe$1(data, offset)) {
  10019. logger2.log("ADTS sync word found !");
  10020. return true;
  10021. }
  10022. }
  10023. return false;
  10024. }
  10025. canParse(data, offset) {
  10026. return canParse$1(data, offset);
  10027. }
  10028. appendFrame(track, data, offset) {
  10029. initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  10030. const frame = appendFrame$2(track, data, offset, this.basePTS, this.frameIndex);
  10031. if (frame && frame.missing === 0) {
  10032. return frame;
  10033. }
  10034. }
  10035. };
  10036. var getAudioBSID = (data, offset) => {
  10037. let bsid = 0;
  10038. let numBits = 5;
  10039. offset += numBits;
  10040. const temp = new Uint32Array(1);
  10041. const mask = new Uint32Array(1);
  10042. const byte = new Uint8Array(1);
  10043. while (numBits > 0) {
  10044. byte[0] = data[offset];
  10045. const bits = Math.min(numBits, 8);
  10046. const shift = 8 - bits;
  10047. mask[0] = 4278190080 >>> 24 + shift << shift;
  10048. temp[0] = (byte[0] & mask[0]) >> shift;
  10049. bsid = !bsid ? temp[0] : bsid << bits | temp[0];
  10050. offset += 1;
  10051. numBits -= bits;
  10052. }
  10053. return bsid;
  10054. };
  10055. var AC3Demuxer = class extends BaseAudioDemuxer {
  10056. constructor(observer) {
  10057. super();
  10058. this.observer = void 0;
  10059. this.observer = observer;
  10060. }
  10061. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  10062. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  10063. this._audioTrack = {
  10064. container: "audio/ac-3",
  10065. type: "audio",
  10066. id: 2,
  10067. pid: -1,
  10068. sequenceNumber: 0,
  10069. segmentCodec: "ac3",
  10070. samples: [],
  10071. manifestCodec: audioCodec,
  10072. duration: trackDuration,
  10073. inputTimeScale: 9e4,
  10074. dropped: 0
  10075. };
  10076. }
  10077. canParse(data, offset) {
  10078. return offset + 64 < data.length;
  10079. }
  10080. appendFrame(track, data, offset) {
  10081. const frameLength = appendFrame(track, data, offset, this.basePTS, this.frameIndex);
  10082. if (frameLength !== -1) {
  10083. const sample = track.samples[track.samples.length - 1];
  10084. return {
  10085. sample,
  10086. length: frameLength,
  10087. missing: 0
  10088. };
  10089. }
  10090. }
  10091. static probe(data) {
  10092. if (!data) {
  10093. return false;
  10094. }
  10095. const id3Data = getId3Data(data, 0);
  10096. if (!id3Data) {
  10097. return false;
  10098. }
  10099. const offset = id3Data.length;
  10100. if (data[offset] === 11 && data[offset + 1] === 119 && getId3Timestamp(id3Data) !== void 0 && // check the bsid to confirm ac-3
  10101. getAudioBSID(data, offset) < 16) {
  10102. return true;
  10103. }
  10104. return false;
  10105. }
  10106. };
  10107. function appendFrame(track, data, start, pts, frameIndex) {
  10108. if (start + 8 > data.length) {
  10109. return -1;
  10110. }
  10111. if (data[start] !== 11 || data[start + 1] !== 119) {
  10112. return -1;
  10113. }
  10114. const samplingRateCode = data[start + 4] >> 6;
  10115. if (samplingRateCode >= 3) {
  10116. return -1;
  10117. }
  10118. const samplingRateMap = [48e3, 44100, 32e3];
  10119. const sampleRate = samplingRateMap[samplingRateCode];
  10120. const frameSizeCode = data[start + 4] & 63;
  10121. 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];
  10122. const frameLength = frameSizeMap[frameSizeCode * 3 + samplingRateCode] * 2;
  10123. if (start + frameLength > data.length) {
  10124. return -1;
  10125. }
  10126. const channelMode = data[start + 6] >> 5;
  10127. let skipCount = 0;
  10128. if (channelMode === 2) {
  10129. skipCount += 2;
  10130. } else {
  10131. if (channelMode & 1 && channelMode !== 1) {
  10132. skipCount += 2;
  10133. }
  10134. if (channelMode & 4) {
  10135. skipCount += 2;
  10136. }
  10137. }
  10138. const lfeon = (data[start + 6] << 8 | data[start + 7]) >> 12 - skipCount & 1;
  10139. const channelsMap = [2, 1, 2, 3, 3, 4, 4, 5];
  10140. const channelCount = channelsMap[channelMode] + lfeon;
  10141. const bsid = data[start + 5] >> 3;
  10142. const bsmod = data[start + 5] & 7;
  10143. const config = new Uint8Array([samplingRateCode << 6 | bsid << 1 | bsmod >> 2, (bsmod & 3) << 6 | channelMode << 3 | lfeon << 2 | frameSizeCode >> 4, frameSizeCode << 4 & 224]);
  10144. const frameDuration = 1536 / sampleRate * 9e4;
  10145. const stamp = pts + frameIndex * frameDuration;
  10146. const unit = data.subarray(start, start + frameLength);
  10147. track.config = config;
  10148. track.channelCount = channelCount;
  10149. track.samplerate = sampleRate;
  10150. track.samples.push({
  10151. unit,
  10152. pts: stamp
  10153. });
  10154. return frameLength;
  10155. }
  10156. var MP3Demuxer = class extends BaseAudioDemuxer {
  10157. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  10158. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  10159. this._audioTrack = {
  10160. container: "audio/mpeg",
  10161. type: "audio",
  10162. id: 2,
  10163. pid: -1,
  10164. sequenceNumber: 0,
  10165. segmentCodec: "mp3",
  10166. samples: [],
  10167. manifestCodec: audioCodec,
  10168. duration: trackDuration,
  10169. inputTimeScale: 9e4,
  10170. dropped: 0
  10171. };
  10172. }
  10173. static probe(data) {
  10174. if (!data) {
  10175. return false;
  10176. }
  10177. const id3Data = getId3Data(data, 0);
  10178. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  10179. if (id3Data && data[offset] === 11 && data[offset + 1] === 119 && getId3Timestamp(id3Data) !== void 0 && // check the bsid to confirm ac-3 or ec-3 (not mp3)
  10180. getAudioBSID(data, offset) <= 16) {
  10181. return false;
  10182. }
  10183. for (let length = data.length; offset < length; offset++) {
  10184. if (probe(data, offset)) {
  10185. logger.log("MPEG Audio sync word found !");
  10186. return true;
  10187. }
  10188. }
  10189. return false;
  10190. }
  10191. canParse(data, offset) {
  10192. return canParse(data, offset);
  10193. }
  10194. appendFrame(track, data, offset) {
  10195. if (this.basePTS === null) {
  10196. return;
  10197. }
  10198. return appendFrame$1(track, data, offset, this.basePTS, this.frameIndex);
  10199. }
  10200. };
  10201. var emsgSchemePattern = /\/emsg[-/]ID3/i;
  10202. var MP4Demuxer = class {
  10203. constructor(observer, config) {
  10204. this.remainderData = null;
  10205. this.timeOffset = 0;
  10206. this.config = void 0;
  10207. this.videoTrack = void 0;
  10208. this.audioTrack = void 0;
  10209. this.id3Track = void 0;
  10210. this.txtTrack = void 0;
  10211. this.config = config;
  10212. }
  10213. resetTimeStamp() {
  10214. }
  10215. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  10216. const videoTrack = this.videoTrack = dummyTrack("video", 1);
  10217. const audioTrack = this.audioTrack = dummyTrack("audio", 1);
  10218. const captionTrack = this.txtTrack = dummyTrack("text", 1);
  10219. this.id3Track = dummyTrack("id3", 1);
  10220. this.timeOffset = 0;
  10221. if (!(initSegment != null && initSegment.byteLength)) {
  10222. return;
  10223. }
  10224. const initData = parseInitSegment(initSegment);
  10225. if (initData.video) {
  10226. const {
  10227. id,
  10228. timescale,
  10229. codec,
  10230. supplemental
  10231. } = initData.video;
  10232. videoTrack.id = id;
  10233. videoTrack.timescale = captionTrack.timescale = timescale;
  10234. videoTrack.codec = codec;
  10235. videoTrack.supplemental = supplemental;
  10236. }
  10237. if (initData.audio) {
  10238. const {
  10239. id,
  10240. timescale,
  10241. codec
  10242. } = initData.audio;
  10243. audioTrack.id = id;
  10244. audioTrack.timescale = timescale;
  10245. audioTrack.codec = codec;
  10246. }
  10247. captionTrack.id = RemuxerTrackIdConfig.text;
  10248. videoTrack.sampleDuration = 0;
  10249. videoTrack.duration = audioTrack.duration = trackDuration;
  10250. }
  10251. resetContiguity() {
  10252. this.remainderData = null;
  10253. }
  10254. static probe(data) {
  10255. return hasMoofData(data);
  10256. }
  10257. demux(data, timeOffset) {
  10258. this.timeOffset = timeOffset;
  10259. let videoSamples = data;
  10260. const videoTrack = this.videoTrack;
  10261. const textTrack = this.txtTrack;
  10262. if (this.config.progressive) {
  10263. if (this.remainderData) {
  10264. videoSamples = appendUint8Array(this.remainderData, data);
  10265. }
  10266. const segmentedData = segmentValidRange(videoSamples);
  10267. this.remainderData = segmentedData.remainder;
  10268. videoTrack.samples = segmentedData.valid || new Uint8Array();
  10269. } else {
  10270. videoTrack.samples = videoSamples;
  10271. }
  10272. const id3Track = this.extractID3Track(videoTrack, timeOffset);
  10273. textTrack.samples = parseSamples(timeOffset, videoTrack);
  10274. return {
  10275. videoTrack,
  10276. audioTrack: this.audioTrack,
  10277. id3Track,
  10278. textTrack: this.txtTrack
  10279. };
  10280. }
  10281. flush() {
  10282. const timeOffset = this.timeOffset;
  10283. const videoTrack = this.videoTrack;
  10284. const textTrack = this.txtTrack;
  10285. videoTrack.samples = this.remainderData || new Uint8Array();
  10286. this.remainderData = null;
  10287. const id3Track = this.extractID3Track(videoTrack, this.timeOffset);
  10288. textTrack.samples = parseSamples(timeOffset, videoTrack);
  10289. return {
  10290. videoTrack,
  10291. audioTrack: dummyTrack(),
  10292. id3Track,
  10293. textTrack: dummyTrack()
  10294. };
  10295. }
  10296. extractID3Track(videoTrack, timeOffset) {
  10297. const id3Track = this.id3Track;
  10298. if (videoTrack.samples.length) {
  10299. const emsgs = findBox(videoTrack.samples, ["emsg"]);
  10300. if (emsgs) {
  10301. emsgs.forEach((data) => {
  10302. const emsgInfo = parseEmsg(data);
  10303. if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {
  10304. const pts = getEmsgStartTime(emsgInfo, timeOffset);
  10305. let duration = emsgInfo.eventDuration === 4294967295 ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale;
  10306. if (duration <= 1e-3) {
  10307. duration = Number.POSITIVE_INFINITY;
  10308. }
  10309. const payload = emsgInfo.payload;
  10310. id3Track.samples.push({
  10311. data: payload,
  10312. len: payload.byteLength,
  10313. dts: pts,
  10314. pts,
  10315. type: MetadataSchema.emsg,
  10316. duration
  10317. });
  10318. } else if (this.config.enableEmsgKLVMetadata && emsgInfo.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")) {
  10319. const pts = getEmsgStartTime(emsgInfo, timeOffset);
  10320. id3Track.samples.push({
  10321. data: emsgInfo.payload,
  10322. len: emsgInfo.payload.byteLength,
  10323. dts: pts,
  10324. pts,
  10325. type: MetadataSchema.misbklv,
  10326. duration: Number.POSITIVE_INFINITY
  10327. });
  10328. }
  10329. });
  10330. }
  10331. }
  10332. return id3Track;
  10333. }
  10334. demuxSampleAes(data, keyData, timeOffset) {
  10335. return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"));
  10336. }
  10337. destroy() {
  10338. this.config = null;
  10339. this.remainderData = null;
  10340. this.videoTrack = this.audioTrack = this.id3Track = this.txtTrack = void 0;
  10341. }
  10342. };
  10343. function getEmsgStartTime(emsgInfo, timeOffset) {
  10344. return isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;
  10345. }
  10346. var SampleAesDecrypter = class {
  10347. constructor(observer, config, keyData) {
  10348. this.keyData = void 0;
  10349. this.decrypter = void 0;
  10350. this.keyData = keyData;
  10351. this.decrypter = new Decrypter(config, {
  10352. removePKCS7Padding: false
  10353. });
  10354. }
  10355. decryptBuffer(encryptedData) {
  10356. return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, DecrypterAesMode.cbc);
  10357. }
  10358. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  10359. decryptAacSample(samples, sampleIndex, callback) {
  10360. const curUnit = samples[sampleIndex].unit;
  10361. if (curUnit.length <= 16) {
  10362. return;
  10363. }
  10364. const encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  10365. const encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  10366. this.decryptBuffer(encryptedBuffer).then((decryptedBuffer) => {
  10367. const decryptedData = new Uint8Array(decryptedBuffer);
  10368. curUnit.set(decryptedData, 16);
  10369. if (!this.decrypter.isSync()) {
  10370. this.decryptAacSamples(samples, sampleIndex + 1, callback);
  10371. }
  10372. }).catch(callback);
  10373. }
  10374. decryptAacSamples(samples, sampleIndex, callback) {
  10375. for (; ; sampleIndex++) {
  10376. if (sampleIndex >= samples.length) {
  10377. callback();
  10378. return;
  10379. }
  10380. if (samples[sampleIndex].unit.length < 32) {
  10381. continue;
  10382. }
  10383. this.decryptAacSample(samples, sampleIndex, callback);
  10384. if (!this.decrypter.isSync()) {
  10385. return;
  10386. }
  10387. }
  10388. }
  10389. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  10390. getAvcEncryptedData(decodedData) {
  10391. const encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  10392. const encryptedData = new Int8Array(encryptedDataLen);
  10393. let outputPos = 0;
  10394. for (let inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) {
  10395. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  10396. }
  10397. return encryptedData;
  10398. }
  10399. getAvcDecryptedUnit(decodedData, decryptedData) {
  10400. const uint8DecryptedData = new Uint8Array(decryptedData);
  10401. let inputPos = 0;
  10402. for (let outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) {
  10403. decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
  10404. }
  10405. return decodedData;
  10406. }
  10407. decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit) {
  10408. const decodedData = discardEPB(curUnit.data);
  10409. const encryptedData = this.getAvcEncryptedData(decodedData);
  10410. this.decryptBuffer(encryptedData.buffer).then((decryptedBuffer) => {
  10411. curUnit.data = this.getAvcDecryptedUnit(decodedData, decryptedBuffer);
  10412. if (!this.decrypter.isSync()) {
  10413. this.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  10414. }
  10415. }).catch(callback);
  10416. }
  10417. decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  10418. if (samples instanceof Uint8Array) {
  10419. throw new Error("Cannot decrypt samples of type Uint8Array");
  10420. }
  10421. for (; ; sampleIndex++, unitIndex = 0) {
  10422. if (sampleIndex >= samples.length) {
  10423. callback();
  10424. return;
  10425. }
  10426. const curUnits = samples[sampleIndex].units;
  10427. for (; ; unitIndex++) {
  10428. if (unitIndex >= curUnits.length) {
  10429. break;
  10430. }
  10431. const curUnit = curUnits[unitIndex];
  10432. if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  10433. continue;
  10434. }
  10435. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit);
  10436. if (!this.decrypter.isSync()) {
  10437. return;
  10438. }
  10439. }
  10440. }
  10441. }
  10442. };
  10443. var BaseVideoParser = class {
  10444. constructor() {
  10445. this.VideoSample = null;
  10446. }
  10447. createVideoSample(key, pts, dts) {
  10448. return {
  10449. key,
  10450. frame: false,
  10451. pts,
  10452. dts,
  10453. units: [],
  10454. length: 0
  10455. };
  10456. }
  10457. getLastNalUnit(samples) {
  10458. var _VideoSample;
  10459. let VideoSample = this.VideoSample;
  10460. let lastUnit;
  10461. if (!VideoSample || VideoSample.units.length === 0) {
  10462. VideoSample = samples[samples.length - 1];
  10463. }
  10464. if ((_VideoSample = VideoSample) != null && _VideoSample.units) {
  10465. const units = VideoSample.units;
  10466. lastUnit = units[units.length - 1];
  10467. }
  10468. return lastUnit;
  10469. }
  10470. pushAccessUnit(VideoSample, videoTrack) {
  10471. if (VideoSample.units.length && VideoSample.frame) {
  10472. if (VideoSample.pts === void 0) {
  10473. const samples = videoTrack.samples;
  10474. const nbSamples = samples.length;
  10475. if (nbSamples) {
  10476. const lastSample = samples[nbSamples - 1];
  10477. VideoSample.pts = lastSample.pts;
  10478. VideoSample.dts = lastSample.dts;
  10479. } else {
  10480. videoTrack.dropped++;
  10481. return;
  10482. }
  10483. }
  10484. videoTrack.samples.push(VideoSample);
  10485. }
  10486. }
  10487. parseNALu(track, array, endOfSegment) {
  10488. const len = array.byteLength;
  10489. let state = track.naluState || 0;
  10490. const lastState = state;
  10491. const units = [];
  10492. let i = 0;
  10493. let value;
  10494. let overflow;
  10495. let unitType;
  10496. let lastUnitStart = -1;
  10497. let lastUnitType = 0;
  10498. if (state === -1) {
  10499. lastUnitStart = 0;
  10500. lastUnitType = this.getNALuType(array, 0);
  10501. state = 0;
  10502. i = 1;
  10503. }
  10504. while (i < len) {
  10505. value = array[i++];
  10506. if (!state) {
  10507. state = value ? 0 : 1;
  10508. continue;
  10509. }
  10510. if (state === 1) {
  10511. state = value ? 0 : 2;
  10512. continue;
  10513. }
  10514. if (!value) {
  10515. state = 3;
  10516. } else if (value === 1) {
  10517. overflow = i - state - 1;
  10518. if (lastUnitStart >= 0) {
  10519. const unit = {
  10520. data: array.subarray(lastUnitStart, overflow),
  10521. type: lastUnitType
  10522. };
  10523. units.push(unit);
  10524. } else {
  10525. const lastUnit = this.getLastNalUnit(track.samples);
  10526. if (lastUnit) {
  10527. if (lastState && i <= 4 - lastState) {
  10528. if (lastUnit.state) {
  10529. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  10530. }
  10531. }
  10532. if (overflow > 0) {
  10533. lastUnit.data = appendUint8Array(lastUnit.data, array.subarray(0, overflow));
  10534. lastUnit.state = 0;
  10535. }
  10536. }
  10537. }
  10538. if (i < len) {
  10539. unitType = this.getNALuType(array, i);
  10540. lastUnitStart = i;
  10541. lastUnitType = unitType;
  10542. state = 0;
  10543. } else {
  10544. state = -1;
  10545. }
  10546. } else {
  10547. state = 0;
  10548. }
  10549. }
  10550. if (lastUnitStart >= 0 && state >= 0) {
  10551. const unit = {
  10552. data: array.subarray(lastUnitStart, len),
  10553. type: lastUnitType,
  10554. state
  10555. };
  10556. units.push(unit);
  10557. }
  10558. if (units.length === 0) {
  10559. const lastUnit = this.getLastNalUnit(track.samples);
  10560. if (lastUnit) {
  10561. lastUnit.data = appendUint8Array(lastUnit.data, array);
  10562. }
  10563. }
  10564. track.naluState = state;
  10565. return units;
  10566. }
  10567. };
  10568. var ExpGolomb = class {
  10569. constructor(data) {
  10570. this.data = void 0;
  10571. this.bytesAvailable = void 0;
  10572. this.word = void 0;
  10573. this.bitsAvailable = void 0;
  10574. this.data = data;
  10575. this.bytesAvailable = data.byteLength;
  10576. this.word = 0;
  10577. this.bitsAvailable = 0;
  10578. }
  10579. // ():void
  10580. loadWord() {
  10581. const data = this.data;
  10582. const bytesAvailable = this.bytesAvailable;
  10583. const position = data.byteLength - bytesAvailable;
  10584. const workingBytes = new Uint8Array(4);
  10585. const availableBytes = Math.min(4, bytesAvailable);
  10586. if (availableBytes === 0) {
  10587. throw new Error("no bytes available");
  10588. }
  10589. workingBytes.set(data.subarray(position, position + availableBytes));
  10590. this.word = new DataView(workingBytes.buffer).getUint32(0);
  10591. this.bitsAvailable = availableBytes * 8;
  10592. this.bytesAvailable -= availableBytes;
  10593. }
  10594. // (count:int):void
  10595. skipBits(count) {
  10596. let skipBytes;
  10597. count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);
  10598. if (this.bitsAvailable > count) {
  10599. this.word <<= count;
  10600. this.bitsAvailable -= count;
  10601. } else {
  10602. count -= this.bitsAvailable;
  10603. skipBytes = count >> 3;
  10604. count -= skipBytes << 3;
  10605. this.bytesAvailable -= skipBytes;
  10606. this.loadWord();
  10607. this.word <<= count;
  10608. this.bitsAvailable -= count;
  10609. }
  10610. }
  10611. // (size:int):uint
  10612. readBits(size) {
  10613. let bits = Math.min(this.bitsAvailable, size);
  10614. const valu = this.word >>> 32 - bits;
  10615. if (size > 32) {
  10616. logger.error("Cannot read more than 32 bits at a time");
  10617. }
  10618. this.bitsAvailable -= bits;
  10619. if (this.bitsAvailable > 0) {
  10620. this.word <<= bits;
  10621. } else if (this.bytesAvailable > 0) {
  10622. this.loadWord();
  10623. } else {
  10624. throw new Error("no bits available");
  10625. }
  10626. bits = size - bits;
  10627. if (bits > 0 && this.bitsAvailable) {
  10628. return valu << bits | this.readBits(bits);
  10629. } else {
  10630. return valu;
  10631. }
  10632. }
  10633. // ():uint
  10634. skipLZ() {
  10635. let leadingZeroCount;
  10636. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  10637. if ((this.word & 2147483648 >>> leadingZeroCount) !== 0) {
  10638. this.word <<= leadingZeroCount;
  10639. this.bitsAvailable -= leadingZeroCount;
  10640. return leadingZeroCount;
  10641. }
  10642. }
  10643. this.loadWord();
  10644. return leadingZeroCount + this.skipLZ();
  10645. }
  10646. // ():void
  10647. skipUEG() {
  10648. this.skipBits(1 + this.skipLZ());
  10649. }
  10650. // ():void
  10651. skipEG() {
  10652. this.skipBits(1 + this.skipLZ());
  10653. }
  10654. // ():uint
  10655. readUEG() {
  10656. const clz = this.skipLZ();
  10657. return this.readBits(clz + 1) - 1;
  10658. }
  10659. // ():int
  10660. readEG() {
  10661. const valu = this.readUEG();
  10662. if (1 & valu) {
  10663. return 1 + valu >>> 1;
  10664. } else {
  10665. return -1 * (valu >>> 1);
  10666. }
  10667. }
  10668. // Some convenience functions
  10669. // :Boolean
  10670. readBoolean() {
  10671. return this.readBits(1) === 1;
  10672. }
  10673. // ():int
  10674. readUByte() {
  10675. return this.readBits(8);
  10676. }
  10677. // ():int
  10678. readUShort() {
  10679. return this.readBits(16);
  10680. }
  10681. // ():int
  10682. readUInt() {
  10683. return this.readBits(32);
  10684. }
  10685. };
  10686. var AvcVideoParser = class extends BaseVideoParser {
  10687. parsePES(track, textTrack, pes, endOfSegment) {
  10688. const units = this.parseNALu(track, pes.data, endOfSegment);
  10689. let VideoSample = this.VideoSample;
  10690. let push2;
  10691. let spsfound = false;
  10692. pes.data = null;
  10693. if (VideoSample && units.length && !track.audFound) {
  10694. this.pushAccessUnit(VideoSample, track);
  10695. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  10696. }
  10697. units.forEach((unit) => {
  10698. var _VideoSample2, _VideoSample3;
  10699. switch (unit.type) {
  10700. case 1: {
  10701. let iskey = false;
  10702. push2 = true;
  10703. const data = unit.data;
  10704. if (spsfound && data.length > 4) {
  10705. const sliceType = this.readSliceType(data);
  10706. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  10707. iskey = true;
  10708. }
  10709. }
  10710. if (iskey) {
  10711. var _VideoSample;
  10712. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  10713. this.pushAccessUnit(VideoSample, track);
  10714. VideoSample = this.VideoSample = null;
  10715. }
  10716. }
  10717. if (!VideoSample) {
  10718. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  10719. }
  10720. VideoSample.frame = true;
  10721. VideoSample.key = iskey;
  10722. break;
  10723. }
  10724. case 5:
  10725. push2 = true;
  10726. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  10727. this.pushAccessUnit(VideoSample, track);
  10728. VideoSample = this.VideoSample = null;
  10729. }
  10730. if (!VideoSample) {
  10731. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  10732. }
  10733. VideoSample.key = true;
  10734. VideoSample.frame = true;
  10735. break;
  10736. case 6: {
  10737. push2 = true;
  10738. parseSEIMessageFromNALu(unit.data, 1, pes.pts, textTrack.samples);
  10739. break;
  10740. }
  10741. case 7: {
  10742. var _track$pixelRatio, _track$pixelRatio2;
  10743. push2 = true;
  10744. spsfound = true;
  10745. const sps = unit.data;
  10746. const config = this.readSPS(sps);
  10747. 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]) {
  10748. track.width = config.width;
  10749. track.height = config.height;
  10750. track.pixelRatio = config.pixelRatio;
  10751. track.sps = [sps];
  10752. const codecarray = sps.subarray(1, 4);
  10753. let codecstring = "avc1.";
  10754. for (let i = 0; i < 3; i++) {
  10755. let h = codecarray[i].toString(16);
  10756. if (h.length < 2) {
  10757. h = "0" + h;
  10758. }
  10759. codecstring += h;
  10760. }
  10761. track.codec = codecstring;
  10762. }
  10763. break;
  10764. }
  10765. case 8:
  10766. push2 = true;
  10767. track.pps = [unit.data];
  10768. break;
  10769. case 9:
  10770. push2 = true;
  10771. track.audFound = true;
  10772. if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
  10773. this.pushAccessUnit(VideoSample, track);
  10774. VideoSample = null;
  10775. }
  10776. if (!VideoSample) {
  10777. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  10778. }
  10779. break;
  10780. case 12:
  10781. push2 = true;
  10782. break;
  10783. default:
  10784. push2 = false;
  10785. break;
  10786. }
  10787. if (VideoSample && push2) {
  10788. const units2 = VideoSample.units;
  10789. units2.push(unit);
  10790. }
  10791. });
  10792. if (endOfSegment && VideoSample) {
  10793. this.pushAccessUnit(VideoSample, track);
  10794. this.VideoSample = null;
  10795. }
  10796. }
  10797. getNALuType(data, offset) {
  10798. return data[offset] & 31;
  10799. }
  10800. readSliceType(data) {
  10801. const eg = new ExpGolomb(data);
  10802. eg.readUByte();
  10803. eg.readUEG();
  10804. return eg.readUEG();
  10805. }
  10806. /**
  10807. * The scaling list is optionally transmitted as part of a sequence parameter
  10808. * set and is not relevant to transmuxing.
  10809. * @param count the number of entries in this scaling list
  10810. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  10811. */
  10812. skipScalingList(count, reader) {
  10813. let lastScale = 8;
  10814. let nextScale = 8;
  10815. let deltaScale;
  10816. for (let j = 0; j < count; j++) {
  10817. if (nextScale !== 0) {
  10818. deltaScale = reader.readEG();
  10819. nextScale = (lastScale + deltaScale + 256) % 256;
  10820. }
  10821. lastScale = nextScale === 0 ? lastScale : nextScale;
  10822. }
  10823. }
  10824. /**
  10825. * Read a sequence parameter set and return some interesting video
  10826. * properties. A sequence parameter set is the H264 metadata that
  10827. * describes the properties of upcoming video frames.
  10828. * @returns an object with configuration parsed from the
  10829. * sequence parameter set, including the dimensions of the
  10830. * associated video frames.
  10831. */
  10832. readSPS(sps) {
  10833. const eg = new ExpGolomb(sps);
  10834. let frameCropLeftOffset = 0;
  10835. let frameCropRightOffset = 0;
  10836. let frameCropTopOffset = 0;
  10837. let frameCropBottomOffset = 0;
  10838. let numRefFramesInPicOrderCntCycle;
  10839. let scalingListCount;
  10840. let i;
  10841. const readUByte = eg.readUByte.bind(eg);
  10842. const readBits = eg.readBits.bind(eg);
  10843. const readUEG = eg.readUEG.bind(eg);
  10844. const readBoolean = eg.readBoolean.bind(eg);
  10845. const skipBits = eg.skipBits.bind(eg);
  10846. const skipEG = eg.skipEG.bind(eg);
  10847. const skipUEG = eg.skipUEG.bind(eg);
  10848. const skipScalingList = this.skipScalingList.bind(this);
  10849. readUByte();
  10850. const profileIdc = readUByte();
  10851. readBits(5);
  10852. skipBits(3);
  10853. readUByte();
  10854. skipUEG();
  10855. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  10856. const chromaFormatIdc = readUEG();
  10857. if (chromaFormatIdc === 3) {
  10858. skipBits(1);
  10859. }
  10860. skipUEG();
  10861. skipUEG();
  10862. skipBits(1);
  10863. if (readBoolean()) {
  10864. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  10865. for (i = 0; i < scalingListCount; i++) {
  10866. if (readBoolean()) {
  10867. if (i < 6) {
  10868. skipScalingList(16, eg);
  10869. } else {
  10870. skipScalingList(64, eg);
  10871. }
  10872. }
  10873. }
  10874. }
  10875. }
  10876. skipUEG();
  10877. const picOrderCntType = readUEG();
  10878. if (picOrderCntType === 0) {
  10879. readUEG();
  10880. } else if (picOrderCntType === 1) {
  10881. skipBits(1);
  10882. skipEG();
  10883. skipEG();
  10884. numRefFramesInPicOrderCntCycle = readUEG();
  10885. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  10886. skipEG();
  10887. }
  10888. }
  10889. skipUEG();
  10890. skipBits(1);
  10891. const picWidthInMbsMinus1 = readUEG();
  10892. const picHeightInMapUnitsMinus1 = readUEG();
  10893. const frameMbsOnlyFlag = readBits(1);
  10894. if (frameMbsOnlyFlag === 0) {
  10895. skipBits(1);
  10896. }
  10897. skipBits(1);
  10898. if (readBoolean()) {
  10899. frameCropLeftOffset = readUEG();
  10900. frameCropRightOffset = readUEG();
  10901. frameCropTopOffset = readUEG();
  10902. frameCropBottomOffset = readUEG();
  10903. }
  10904. let pixelRatio = [1, 1];
  10905. if (readBoolean()) {
  10906. if (readBoolean()) {
  10907. const aspectRatioIdc = readUByte();
  10908. switch (aspectRatioIdc) {
  10909. case 1:
  10910. pixelRatio = [1, 1];
  10911. break;
  10912. case 2:
  10913. pixelRatio = [12, 11];
  10914. break;
  10915. case 3:
  10916. pixelRatio = [10, 11];
  10917. break;
  10918. case 4:
  10919. pixelRatio = [16, 11];
  10920. break;
  10921. case 5:
  10922. pixelRatio = [40, 33];
  10923. break;
  10924. case 6:
  10925. pixelRatio = [24, 11];
  10926. break;
  10927. case 7:
  10928. pixelRatio = [20, 11];
  10929. break;
  10930. case 8:
  10931. pixelRatio = [32, 11];
  10932. break;
  10933. case 9:
  10934. pixelRatio = [80, 33];
  10935. break;
  10936. case 10:
  10937. pixelRatio = [18, 11];
  10938. break;
  10939. case 11:
  10940. pixelRatio = [15, 11];
  10941. break;
  10942. case 12:
  10943. pixelRatio = [64, 33];
  10944. break;
  10945. case 13:
  10946. pixelRatio = [160, 99];
  10947. break;
  10948. case 14:
  10949. pixelRatio = [4, 3];
  10950. break;
  10951. case 15:
  10952. pixelRatio = [3, 2];
  10953. break;
  10954. case 16:
  10955. pixelRatio = [2, 1];
  10956. break;
  10957. case 255: {
  10958. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  10959. break;
  10960. }
  10961. }
  10962. }
  10963. }
  10964. return {
  10965. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  10966. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  10967. pixelRatio
  10968. };
  10969. }
  10970. };
  10971. var HevcVideoParser = class extends BaseVideoParser {
  10972. constructor(...args) {
  10973. super(...args);
  10974. this.initVPS = null;
  10975. }
  10976. parsePES(track, textTrack, pes, endOfSegment) {
  10977. const units = this.parseNALu(track, pes.data, endOfSegment);
  10978. let VideoSample = this.VideoSample;
  10979. let push2;
  10980. let spsfound = false;
  10981. pes.data = null;
  10982. if (VideoSample && units.length && !track.audFound) {
  10983. this.pushAccessUnit(VideoSample, track);
  10984. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  10985. }
  10986. units.forEach((unit) => {
  10987. var _VideoSample2, _VideoSample3;
  10988. switch (unit.type) {
  10989. case 0:
  10990. case 1:
  10991. case 2:
  10992. case 3:
  10993. case 4:
  10994. case 5:
  10995. case 6:
  10996. case 7:
  10997. case 8:
  10998. case 9:
  10999. if (!VideoSample) {
  11000. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  11001. }
  11002. VideoSample.frame = true;
  11003. push2 = true;
  11004. break;
  11005. case 16:
  11006. case 17:
  11007. case 18:
  11008. case 21:
  11009. push2 = true;
  11010. if (spsfound) {
  11011. var _VideoSample;
  11012. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  11013. this.pushAccessUnit(VideoSample, track);
  11014. VideoSample = this.VideoSample = null;
  11015. }
  11016. }
  11017. if (!VideoSample) {
  11018. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  11019. }
  11020. VideoSample.key = true;
  11021. VideoSample.frame = true;
  11022. break;
  11023. case 19:
  11024. case 20:
  11025. push2 = true;
  11026. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  11027. this.pushAccessUnit(VideoSample, track);
  11028. VideoSample = this.VideoSample = null;
  11029. }
  11030. if (!VideoSample) {
  11031. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  11032. }
  11033. VideoSample.key = true;
  11034. VideoSample.frame = true;
  11035. break;
  11036. case 39:
  11037. push2 = true;
  11038. parseSEIMessageFromNALu(
  11039. unit.data,
  11040. 2,
  11041. // NALu header size
  11042. pes.pts,
  11043. textTrack.samples
  11044. );
  11045. break;
  11046. case 32:
  11047. push2 = true;
  11048. if (!track.vps) {
  11049. if (typeof track.params !== "object") {
  11050. track.params = {};
  11051. }
  11052. track.params = _extends(track.params, this.readVPS(unit.data));
  11053. this.initVPS = unit.data;
  11054. }
  11055. track.vps = [unit.data];
  11056. break;
  11057. case 33:
  11058. push2 = true;
  11059. spsfound = true;
  11060. if (track.vps !== void 0 && track.vps[0] !== this.initVPS && track.sps !== void 0 && !this.matchSPS(track.sps[0], unit.data)) {
  11061. this.initVPS = track.vps[0];
  11062. track.sps = track.pps = void 0;
  11063. }
  11064. if (!track.sps) {
  11065. const config = this.readSPS(unit.data);
  11066. track.width = config.width;
  11067. track.height = config.height;
  11068. track.pixelRatio = config.pixelRatio;
  11069. track.codec = config.codecString;
  11070. track.sps = [];
  11071. if (typeof track.params !== "object") {
  11072. track.params = {};
  11073. }
  11074. for (const prop in config.params) {
  11075. track.params[prop] = config.params[prop];
  11076. }
  11077. }
  11078. this.pushParameterSet(track.sps, unit.data, track.vps);
  11079. if (!VideoSample) {
  11080. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  11081. }
  11082. VideoSample.key = true;
  11083. break;
  11084. case 34:
  11085. push2 = true;
  11086. if (typeof track.params === "object") {
  11087. if (!track.pps) {
  11088. track.pps = [];
  11089. const config = this.readPPS(unit.data);
  11090. for (const prop in config) {
  11091. track.params[prop] = config[prop];
  11092. }
  11093. }
  11094. this.pushParameterSet(track.pps, unit.data, track.vps);
  11095. }
  11096. break;
  11097. case 35:
  11098. push2 = true;
  11099. track.audFound = true;
  11100. if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
  11101. this.pushAccessUnit(VideoSample, track);
  11102. VideoSample = null;
  11103. }
  11104. if (!VideoSample) {
  11105. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  11106. }
  11107. break;
  11108. default:
  11109. push2 = false;
  11110. break;
  11111. }
  11112. if (VideoSample && push2) {
  11113. const units2 = VideoSample.units;
  11114. units2.push(unit);
  11115. }
  11116. });
  11117. if (endOfSegment && VideoSample) {
  11118. this.pushAccessUnit(VideoSample, track);
  11119. this.VideoSample = null;
  11120. }
  11121. }
  11122. pushParameterSet(parameterSets, data, vps) {
  11123. if (vps && vps[0] === this.initVPS || !vps && !parameterSets.length) {
  11124. parameterSets.push(data);
  11125. }
  11126. }
  11127. getNALuType(data, offset) {
  11128. return (data[offset] & 126) >>> 1;
  11129. }
  11130. ebsp2rbsp(arr) {
  11131. const dst = new Uint8Array(arr.byteLength);
  11132. let dstIdx = 0;
  11133. for (let i = 0; i < arr.byteLength; i++) {
  11134. if (i >= 2) {
  11135. if (arr[i] === 3 && arr[i - 1] === 0 && arr[i - 2] === 0) {
  11136. continue;
  11137. }
  11138. }
  11139. dst[dstIdx] = arr[i];
  11140. dstIdx++;
  11141. }
  11142. return new Uint8Array(dst.buffer, 0, dstIdx);
  11143. }
  11144. pushAccessUnit(VideoSample, videoTrack) {
  11145. super.pushAccessUnit(VideoSample, videoTrack);
  11146. if (this.initVPS) {
  11147. this.initVPS = null;
  11148. }
  11149. }
  11150. readVPS(vps) {
  11151. const eg = new ExpGolomb(vps);
  11152. eg.readUByte();
  11153. eg.readUByte();
  11154. eg.readBits(4);
  11155. eg.skipBits(2);
  11156. eg.readBits(6);
  11157. const max_sub_layers_minus1 = eg.readBits(3);
  11158. const temporal_id_nesting_flag = eg.readBoolean();
  11159. return {
  11160. numTemporalLayers: max_sub_layers_minus1 + 1,
  11161. temporalIdNested: temporal_id_nesting_flag
  11162. };
  11163. }
  11164. readSPS(sps) {
  11165. const eg = new ExpGolomb(this.ebsp2rbsp(sps));
  11166. eg.readUByte();
  11167. eg.readUByte();
  11168. eg.readBits(4);
  11169. const max_sub_layers_minus1 = eg.readBits(3);
  11170. eg.readBoolean();
  11171. const general_profile_space = eg.readBits(2);
  11172. const general_tier_flag = eg.readBoolean();
  11173. const general_profile_idc = eg.readBits(5);
  11174. const general_profile_compatibility_flags_1 = eg.readUByte();
  11175. const general_profile_compatibility_flags_2 = eg.readUByte();
  11176. const general_profile_compatibility_flags_3 = eg.readUByte();
  11177. const general_profile_compatibility_flags_4 = eg.readUByte();
  11178. const general_constraint_indicator_flags_1 = eg.readUByte();
  11179. const general_constraint_indicator_flags_2 = eg.readUByte();
  11180. const general_constraint_indicator_flags_3 = eg.readUByte();
  11181. const general_constraint_indicator_flags_4 = eg.readUByte();
  11182. const general_constraint_indicator_flags_5 = eg.readUByte();
  11183. const general_constraint_indicator_flags_6 = eg.readUByte();
  11184. const general_level_idc = eg.readUByte();
  11185. const sub_layer_profile_present_flags = [];
  11186. const sub_layer_level_present_flags = [];
  11187. for (let i = 0; i < max_sub_layers_minus1; i++) {
  11188. sub_layer_profile_present_flags.push(eg.readBoolean());
  11189. sub_layer_level_present_flags.push(eg.readBoolean());
  11190. }
  11191. if (max_sub_layers_minus1 > 0) {
  11192. for (let i = max_sub_layers_minus1; i < 8; i++) {
  11193. eg.readBits(2);
  11194. }
  11195. }
  11196. for (let i = 0; i < max_sub_layers_minus1; i++) {
  11197. if (sub_layer_profile_present_flags[i]) {
  11198. eg.readUByte();
  11199. eg.readUByte();
  11200. eg.readUByte();
  11201. eg.readUByte();
  11202. eg.readUByte();
  11203. eg.readUByte();
  11204. eg.readUByte();
  11205. eg.readUByte();
  11206. eg.readUByte();
  11207. eg.readUByte();
  11208. eg.readUByte();
  11209. }
  11210. if (sub_layer_level_present_flags[i]) {
  11211. eg.readUByte();
  11212. }
  11213. }
  11214. eg.readUEG();
  11215. const chroma_format_idc = eg.readUEG();
  11216. if (chroma_format_idc == 3) {
  11217. eg.skipBits(1);
  11218. }
  11219. const pic_width_in_luma_samples = eg.readUEG();
  11220. const pic_height_in_luma_samples = eg.readUEG();
  11221. const conformance_window_flag = eg.readBoolean();
  11222. let pic_left_offset = 0, pic_right_offset = 0, pic_top_offset = 0, pic_bottom_offset = 0;
  11223. if (conformance_window_flag) {
  11224. pic_left_offset += eg.readUEG();
  11225. pic_right_offset += eg.readUEG();
  11226. pic_top_offset += eg.readUEG();
  11227. pic_bottom_offset += eg.readUEG();
  11228. }
  11229. const bit_depth_luma_minus8 = eg.readUEG();
  11230. const bit_depth_chroma_minus8 = eg.readUEG();
  11231. const log2_max_pic_order_cnt_lsb_minus4 = eg.readUEG();
  11232. const sub_layer_ordering_info_present_flag = eg.readBoolean();
  11233. for (let i = sub_layer_ordering_info_present_flag ? 0 : max_sub_layers_minus1; i <= max_sub_layers_minus1; i++) {
  11234. eg.skipUEG();
  11235. eg.skipUEG();
  11236. eg.skipUEG();
  11237. }
  11238. eg.skipUEG();
  11239. eg.skipUEG();
  11240. eg.skipUEG();
  11241. eg.skipUEG();
  11242. eg.skipUEG();
  11243. eg.skipUEG();
  11244. const scaling_list_enabled_flag = eg.readBoolean();
  11245. if (scaling_list_enabled_flag) {
  11246. const sps_scaling_list_data_present_flag = eg.readBoolean();
  11247. if (sps_scaling_list_data_present_flag) {
  11248. for (let sizeId = 0; sizeId < 4; sizeId++) {
  11249. for (let matrixId = 0; matrixId < (sizeId === 3 ? 2 : 6); matrixId++) {
  11250. const scaling_list_pred_mode_flag = eg.readBoolean();
  11251. if (!scaling_list_pred_mode_flag) {
  11252. eg.readUEG();
  11253. } else {
  11254. const coefNum = Math.min(64, 1 << 4 + (sizeId << 1));
  11255. if (sizeId > 1) {
  11256. eg.readEG();
  11257. }
  11258. for (let i = 0; i < coefNum; i++) {
  11259. eg.readEG();
  11260. }
  11261. }
  11262. }
  11263. }
  11264. }
  11265. }
  11266. eg.readBoolean();
  11267. eg.readBoolean();
  11268. const pcm_enabled_flag = eg.readBoolean();
  11269. if (pcm_enabled_flag) {
  11270. eg.readUByte();
  11271. eg.skipUEG();
  11272. eg.skipUEG();
  11273. eg.readBoolean();
  11274. }
  11275. const num_short_term_ref_pic_sets = eg.readUEG();
  11276. let num_delta_pocs = 0;
  11277. for (let i = 0; i < num_short_term_ref_pic_sets; i++) {
  11278. let inter_ref_pic_set_prediction_flag = false;
  11279. if (i !== 0) {
  11280. inter_ref_pic_set_prediction_flag = eg.readBoolean();
  11281. }
  11282. if (inter_ref_pic_set_prediction_flag) {
  11283. if (i === num_short_term_ref_pic_sets) {
  11284. eg.readUEG();
  11285. }
  11286. eg.readBoolean();
  11287. eg.readUEG();
  11288. let next_num_delta_pocs = 0;
  11289. for (let j = 0; j <= num_delta_pocs; j++) {
  11290. const used_by_curr_pic_flag = eg.readBoolean();
  11291. let use_delta_flag = false;
  11292. if (!used_by_curr_pic_flag) {
  11293. use_delta_flag = eg.readBoolean();
  11294. }
  11295. if (used_by_curr_pic_flag || use_delta_flag) {
  11296. next_num_delta_pocs++;
  11297. }
  11298. }
  11299. num_delta_pocs = next_num_delta_pocs;
  11300. } else {
  11301. const num_negative_pics = eg.readUEG();
  11302. const num_positive_pics = eg.readUEG();
  11303. num_delta_pocs = num_negative_pics + num_positive_pics;
  11304. for (let j = 0; j < num_negative_pics; j++) {
  11305. eg.readUEG();
  11306. eg.readBoolean();
  11307. }
  11308. for (let j = 0; j < num_positive_pics; j++) {
  11309. eg.readUEG();
  11310. eg.readBoolean();
  11311. }
  11312. }
  11313. }
  11314. const long_term_ref_pics_present_flag = eg.readBoolean();
  11315. if (long_term_ref_pics_present_flag) {
  11316. const num_long_term_ref_pics_sps = eg.readUEG();
  11317. for (let i = 0; i < num_long_term_ref_pics_sps; i++) {
  11318. for (let j = 0; j < log2_max_pic_order_cnt_lsb_minus4 + 4; j++) {
  11319. eg.readBits(1);
  11320. }
  11321. eg.readBits(1);
  11322. }
  11323. }
  11324. let min_spatial_segmentation_idc = 0;
  11325. let sar_width = 1, sar_height = 1;
  11326. let fps_fixed = true, fps_den = 1, fps_num = 0;
  11327. eg.readBoolean();
  11328. eg.readBoolean();
  11329. let default_display_window_flag = false;
  11330. const vui_parameters_present_flag = eg.readBoolean();
  11331. if (vui_parameters_present_flag) {
  11332. const aspect_ratio_info_present_flag = eg.readBoolean();
  11333. if (aspect_ratio_info_present_flag) {
  11334. const aspect_ratio_idc = eg.readUByte();
  11335. const sar_width_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2];
  11336. const sar_height_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
  11337. if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) {
  11338. sar_width = sar_width_table[aspect_ratio_idc - 1];
  11339. sar_height = sar_height_table[aspect_ratio_idc - 1];
  11340. } else if (aspect_ratio_idc === 255) {
  11341. sar_width = eg.readBits(16);
  11342. sar_height = eg.readBits(16);
  11343. }
  11344. }
  11345. const overscan_info_present_flag = eg.readBoolean();
  11346. if (overscan_info_present_flag) {
  11347. eg.readBoolean();
  11348. }
  11349. const video_signal_type_present_flag = eg.readBoolean();
  11350. if (video_signal_type_present_flag) {
  11351. eg.readBits(3);
  11352. eg.readBoolean();
  11353. const colour_description_present_flag = eg.readBoolean();
  11354. if (colour_description_present_flag) {
  11355. eg.readUByte();
  11356. eg.readUByte();
  11357. eg.readUByte();
  11358. }
  11359. }
  11360. const chroma_loc_info_present_flag = eg.readBoolean();
  11361. if (chroma_loc_info_present_flag) {
  11362. eg.readUEG();
  11363. eg.readUEG();
  11364. }
  11365. eg.readBoolean();
  11366. eg.readBoolean();
  11367. eg.readBoolean();
  11368. default_display_window_flag = eg.readBoolean();
  11369. if (default_display_window_flag) {
  11370. eg.skipUEG();
  11371. eg.skipUEG();
  11372. eg.skipUEG();
  11373. eg.skipUEG();
  11374. }
  11375. const vui_timing_info_present_flag = eg.readBoolean();
  11376. if (vui_timing_info_present_flag) {
  11377. fps_den = eg.readBits(32);
  11378. fps_num = eg.readBits(32);
  11379. const vui_poc_proportional_to_timing_flag = eg.readBoolean();
  11380. if (vui_poc_proportional_to_timing_flag) {
  11381. eg.readUEG();
  11382. }
  11383. const vui_hrd_parameters_present_flag = eg.readBoolean();
  11384. if (vui_hrd_parameters_present_flag) {
  11385. const nal_hrd_parameters_present_flag = eg.readBoolean();
  11386. const vcl_hrd_parameters_present_flag = eg.readBoolean();
  11387. let sub_pic_hrd_params_present_flag = false;
  11388. if (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag) {
  11389. sub_pic_hrd_params_present_flag = eg.readBoolean();
  11390. if (sub_pic_hrd_params_present_flag) {
  11391. eg.readUByte();
  11392. eg.readBits(5);
  11393. eg.readBoolean();
  11394. eg.readBits(5);
  11395. }
  11396. eg.readBits(4);
  11397. eg.readBits(4);
  11398. if (sub_pic_hrd_params_present_flag) {
  11399. eg.readBits(4);
  11400. }
  11401. eg.readBits(5);
  11402. eg.readBits(5);
  11403. eg.readBits(5);
  11404. }
  11405. for (let i = 0; i <= max_sub_layers_minus1; i++) {
  11406. fps_fixed = eg.readBoolean();
  11407. const fixed_pic_rate_within_cvs_flag = fps_fixed || eg.readBoolean();
  11408. let low_delay_hrd_flag = false;
  11409. if (fixed_pic_rate_within_cvs_flag) {
  11410. eg.readEG();
  11411. } else {
  11412. low_delay_hrd_flag = eg.readBoolean();
  11413. }
  11414. const cpb_cnt = low_delay_hrd_flag ? 1 : eg.readUEG() + 1;
  11415. if (nal_hrd_parameters_present_flag) {
  11416. for (let j = 0; j < cpb_cnt; j++) {
  11417. eg.readUEG();
  11418. eg.readUEG();
  11419. if (sub_pic_hrd_params_present_flag) {
  11420. eg.readUEG();
  11421. eg.readUEG();
  11422. }
  11423. eg.skipBits(1);
  11424. }
  11425. }
  11426. if (vcl_hrd_parameters_present_flag) {
  11427. for (let j = 0; j < cpb_cnt; j++) {
  11428. eg.readUEG();
  11429. eg.readUEG();
  11430. if (sub_pic_hrd_params_present_flag) {
  11431. eg.readUEG();
  11432. eg.readUEG();
  11433. }
  11434. eg.skipBits(1);
  11435. }
  11436. }
  11437. }
  11438. }
  11439. }
  11440. const bitstream_restriction_flag = eg.readBoolean();
  11441. if (bitstream_restriction_flag) {
  11442. eg.readBoolean();
  11443. eg.readBoolean();
  11444. eg.readBoolean();
  11445. min_spatial_segmentation_idc = eg.readUEG();
  11446. }
  11447. }
  11448. let width = pic_width_in_luma_samples, height = pic_height_in_luma_samples;
  11449. if (conformance_window_flag) {
  11450. let chroma_scale_w = 1, chroma_scale_h = 1;
  11451. if (chroma_format_idc === 1) {
  11452. chroma_scale_w = chroma_scale_h = 2;
  11453. } else if (chroma_format_idc == 2) {
  11454. chroma_scale_w = 2;
  11455. }
  11456. width = pic_width_in_luma_samples - chroma_scale_w * pic_right_offset - chroma_scale_w * pic_left_offset;
  11457. height = pic_height_in_luma_samples - chroma_scale_h * pic_bottom_offset - chroma_scale_h * pic_top_offset;
  11458. }
  11459. const profile_space_string = general_profile_space ? ["A", "B", "C"][general_profile_space] : "";
  11460. 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;
  11461. let profile_compatibility_rev = 0;
  11462. for (let i = 0; i < 32; i++) {
  11463. profile_compatibility_rev = (profile_compatibility_rev | (profile_compatibility_buf >> i & 1) << 31 - i) >>> 0;
  11464. }
  11465. let profile_compatibility_flags_string = profile_compatibility_rev.toString(16);
  11466. if (general_profile_idc === 1 && profile_compatibility_flags_string === "2") {
  11467. profile_compatibility_flags_string = "6";
  11468. }
  11469. const tier_flag_string = general_tier_flag ? "H" : "L";
  11470. return {
  11471. codecString: `hvc1.${profile_space_string}${general_profile_idc}.${profile_compatibility_flags_string}.${tier_flag_string}${general_level_idc}.B0`,
  11472. params: {
  11473. general_tier_flag,
  11474. general_profile_idc,
  11475. general_profile_space,
  11476. general_profile_compatibility_flags: [general_profile_compatibility_flags_1, general_profile_compatibility_flags_2, general_profile_compatibility_flags_3, general_profile_compatibility_flags_4],
  11477. 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],
  11478. general_level_idc,
  11479. bit_depth: bit_depth_luma_minus8 + 8,
  11480. bit_depth_luma_minus8,
  11481. bit_depth_chroma_minus8,
  11482. min_spatial_segmentation_idc,
  11483. chroma_format_idc,
  11484. frame_rate: {
  11485. fixed: fps_fixed,
  11486. fps: fps_num / fps_den
  11487. }
  11488. },
  11489. width,
  11490. height,
  11491. pixelRatio: [sar_width, sar_height]
  11492. };
  11493. }
  11494. readPPS(pps) {
  11495. const eg = new ExpGolomb(this.ebsp2rbsp(pps));
  11496. eg.readUByte();
  11497. eg.readUByte();
  11498. eg.skipUEG();
  11499. eg.skipUEG();
  11500. eg.skipBits(2);
  11501. eg.skipBits(3);
  11502. eg.skipBits(2);
  11503. eg.skipUEG();
  11504. eg.skipUEG();
  11505. eg.skipEG();
  11506. eg.skipBits(2);
  11507. const cu_qp_delta_enabled_flag = eg.readBoolean();
  11508. if (cu_qp_delta_enabled_flag) {
  11509. eg.skipUEG();
  11510. }
  11511. eg.skipEG();
  11512. eg.skipEG();
  11513. eg.skipBits(4);
  11514. const tiles_enabled_flag = eg.readBoolean();
  11515. const entropy_coding_sync_enabled_flag = eg.readBoolean();
  11516. let parallelismType = 1;
  11517. if (entropy_coding_sync_enabled_flag && tiles_enabled_flag) {
  11518. parallelismType = 0;
  11519. } else if (entropy_coding_sync_enabled_flag) {
  11520. parallelismType = 3;
  11521. } else if (tiles_enabled_flag) {
  11522. parallelismType = 2;
  11523. }
  11524. return {
  11525. parallelismType
  11526. };
  11527. }
  11528. matchSPS(sps1, sps2) {
  11529. return String.fromCharCode.apply(null, sps1).substr(3) === String.fromCharCode.apply(null, sps2).substr(3);
  11530. }
  11531. };
  11532. var PACKET_LENGTH = 188;
  11533. var TSDemuxer = class _TSDemuxer {
  11534. constructor(observer, config, typeSupported, logger2) {
  11535. this.logger = void 0;
  11536. this.observer = void 0;
  11537. this.config = void 0;
  11538. this.typeSupported = void 0;
  11539. this.sampleAes = null;
  11540. this.pmtParsed = false;
  11541. this.audioCodec = void 0;
  11542. this.videoCodec = void 0;
  11543. this._pmtId = -1;
  11544. this._videoTrack = void 0;
  11545. this._audioTrack = void 0;
  11546. this._id3Track = void 0;
  11547. this._txtTrack = void 0;
  11548. this.aacOverFlow = null;
  11549. this.remainderData = null;
  11550. this.videoParser = void 0;
  11551. this.observer = observer;
  11552. this.config = config;
  11553. this.typeSupported = typeSupported;
  11554. this.logger = logger2;
  11555. this.videoParser = null;
  11556. }
  11557. static probe(data, logger2) {
  11558. const syncOffset = _TSDemuxer.syncOffset(data);
  11559. if (syncOffset > 0) {
  11560. logger2.warn(`MPEG2-TS detected but first sync word found @ offset ${syncOffset}`);
  11561. }
  11562. return syncOffset !== -1;
  11563. }
  11564. static syncOffset(data) {
  11565. const length = data.length;
  11566. let scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;
  11567. let i = 0;
  11568. while (i < scanwindow) {
  11569. let foundPat = false;
  11570. let packetStart = -1;
  11571. let tsPackets = 0;
  11572. for (let j = i; j < length; j += PACKET_LENGTH) {
  11573. if (data[j] === 71 && (length - j === PACKET_LENGTH || data[j + PACKET_LENGTH] === 71)) {
  11574. tsPackets++;
  11575. if (packetStart === -1) {
  11576. packetStart = j;
  11577. if (packetStart !== 0) {
  11578. scanwindow = Math.min(packetStart + PACKET_LENGTH * 99, data.length - PACKET_LENGTH) + 1;
  11579. }
  11580. }
  11581. if (!foundPat) {
  11582. foundPat = parsePID(data, j) === 0;
  11583. }
  11584. if (foundPat && tsPackets > 1 && (packetStart === 0 && tsPackets > 2 || j + PACKET_LENGTH > scanwindow)) {
  11585. return packetStart;
  11586. }
  11587. } else if (tsPackets) {
  11588. return -1;
  11589. } else {
  11590. break;
  11591. }
  11592. }
  11593. i++;
  11594. }
  11595. return -1;
  11596. }
  11597. /**
  11598. * Creates a track model internal to demuxer used to drive remuxing input
  11599. */
  11600. static createTrack(type, duration) {
  11601. return {
  11602. container: type === "video" || type === "audio" ? "video/mp2t" : void 0,
  11603. type,
  11604. id: RemuxerTrackIdConfig[type],
  11605. pid: -1,
  11606. inputTimeScale: 9e4,
  11607. sequenceNumber: 0,
  11608. samples: [],
  11609. dropped: 0,
  11610. duration: type === "audio" ? duration : void 0
  11611. };
  11612. }
  11613. /**
  11614. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  11615. * Resets all internal track instances of the demuxer.
  11616. */
  11617. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  11618. this.pmtParsed = false;
  11619. this._pmtId = -1;
  11620. this._videoTrack = _TSDemuxer.createTrack("video");
  11621. this._videoTrack.duration = trackDuration;
  11622. this._audioTrack = _TSDemuxer.createTrack("audio", trackDuration);
  11623. this._id3Track = _TSDemuxer.createTrack("id3");
  11624. this._txtTrack = _TSDemuxer.createTrack("text");
  11625. this._audioTrack.segmentCodec = "aac";
  11626. this.videoParser = null;
  11627. this.aacOverFlow = null;
  11628. this.remainderData = null;
  11629. this.audioCodec = audioCodec;
  11630. this.videoCodec = videoCodec;
  11631. }
  11632. resetTimeStamp() {
  11633. }
  11634. resetContiguity() {
  11635. const {
  11636. _audioTrack,
  11637. _videoTrack,
  11638. _id3Track
  11639. } = this;
  11640. if (_audioTrack) {
  11641. _audioTrack.pesData = null;
  11642. }
  11643. if (_videoTrack) {
  11644. _videoTrack.pesData = null;
  11645. }
  11646. if (_id3Track) {
  11647. _id3Track.pesData = null;
  11648. }
  11649. this.aacOverFlow = null;
  11650. this.remainderData = null;
  11651. }
  11652. demux(data, timeOffset, isSampleAes = false, flush = false) {
  11653. if (!isSampleAes) {
  11654. this.sampleAes = null;
  11655. }
  11656. let pes;
  11657. const videoTrack = this._videoTrack;
  11658. const audioTrack = this._audioTrack;
  11659. const id3Track = this._id3Track;
  11660. const textTrack = this._txtTrack;
  11661. let videoPid = videoTrack.pid;
  11662. let videoData = videoTrack.pesData;
  11663. let audioPid = audioTrack.pid;
  11664. let id3Pid = id3Track.pid;
  11665. let audioData = audioTrack.pesData;
  11666. let id3Data = id3Track.pesData;
  11667. let unknownPID = null;
  11668. let pmtParsed = this.pmtParsed;
  11669. let pmtId = this._pmtId;
  11670. let len = data.length;
  11671. if (this.remainderData) {
  11672. data = appendUint8Array(this.remainderData, data);
  11673. len = data.length;
  11674. this.remainderData = null;
  11675. }
  11676. if (len < PACKET_LENGTH && !flush) {
  11677. this.remainderData = data;
  11678. return {
  11679. audioTrack,
  11680. videoTrack,
  11681. id3Track,
  11682. textTrack
  11683. };
  11684. }
  11685. const syncOffset = Math.max(0, _TSDemuxer.syncOffset(data));
  11686. len -= (len - syncOffset) % PACKET_LENGTH;
  11687. if (len < data.byteLength && !flush) {
  11688. this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
  11689. }
  11690. let tsPacketErrors = 0;
  11691. for (let start = syncOffset; start < len; start += PACKET_LENGTH) {
  11692. if (data[start] === 71) {
  11693. const stt = !!(data[start + 1] & 64);
  11694. const pid = parsePID(data, start);
  11695. const atf = (data[start + 3] & 48) >> 4;
  11696. let offset;
  11697. if (atf > 1) {
  11698. offset = start + 5 + data[start + 4];
  11699. if (offset === start + PACKET_LENGTH) {
  11700. continue;
  11701. }
  11702. } else {
  11703. offset = start + 4;
  11704. }
  11705. switch (pid) {
  11706. case videoPid:
  11707. if (stt) {
  11708. if (videoData && (pes = parsePES(videoData, this.logger))) {
  11709. this.readyVideoParser(videoTrack.segmentCodec);
  11710. if (this.videoParser !== null) {
  11711. this.videoParser.parsePES(videoTrack, textTrack, pes, false);
  11712. }
  11713. }
  11714. videoData = {
  11715. data: [],
  11716. size: 0
  11717. };
  11718. }
  11719. if (videoData) {
  11720. videoData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  11721. videoData.size += start + PACKET_LENGTH - offset;
  11722. }
  11723. break;
  11724. case audioPid:
  11725. if (stt) {
  11726. if (audioData && (pes = parsePES(audioData, this.logger))) {
  11727. switch (audioTrack.segmentCodec) {
  11728. case "aac":
  11729. this.parseAACPES(audioTrack, pes);
  11730. break;
  11731. case "mp3":
  11732. this.parseMPEGPES(audioTrack, pes);
  11733. break;
  11734. case "ac3":
  11735. {
  11736. this.parseAC3PES(audioTrack, pes);
  11737. }
  11738. break;
  11739. }
  11740. }
  11741. audioData = {
  11742. data: [],
  11743. size: 0
  11744. };
  11745. }
  11746. if (audioData) {
  11747. audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  11748. audioData.size += start + PACKET_LENGTH - offset;
  11749. }
  11750. break;
  11751. case id3Pid:
  11752. if (stt) {
  11753. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  11754. this.parseID3PES(id3Track, pes);
  11755. }
  11756. id3Data = {
  11757. data: [],
  11758. size: 0
  11759. };
  11760. }
  11761. if (id3Data) {
  11762. id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));
  11763. id3Data.size += start + PACKET_LENGTH - offset;
  11764. }
  11765. break;
  11766. case 0:
  11767. if (stt) {
  11768. offset += data[offset] + 1;
  11769. }
  11770. pmtId = this._pmtId = parsePAT(data, offset);
  11771. break;
  11772. case pmtId: {
  11773. if (stt) {
  11774. offset += data[offset] + 1;
  11775. }
  11776. const parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes, this.observer, this.logger);
  11777. videoPid = parsedPIDs.videoPid;
  11778. if (videoPid > 0) {
  11779. videoTrack.pid = videoPid;
  11780. videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;
  11781. }
  11782. audioPid = parsedPIDs.audioPid;
  11783. if (audioPid > 0) {
  11784. audioTrack.pid = audioPid;
  11785. audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;
  11786. }
  11787. id3Pid = parsedPIDs.id3Pid;
  11788. if (id3Pid > 0) {
  11789. id3Track.pid = id3Pid;
  11790. }
  11791. if (unknownPID !== null && !pmtParsed) {
  11792. this.logger.warn(`MPEG-TS PMT found at ${start} after unknown PID '${unknownPID}'. Backtracking to sync byte @${syncOffset} to parse all TS packets.`);
  11793. unknownPID = null;
  11794. start = syncOffset - 188;
  11795. }
  11796. pmtParsed = this.pmtParsed = true;
  11797. break;
  11798. }
  11799. case 17:
  11800. case 8191:
  11801. break;
  11802. default:
  11803. unknownPID = pid;
  11804. break;
  11805. }
  11806. } else {
  11807. tsPacketErrors++;
  11808. }
  11809. }
  11810. if (tsPacketErrors > 0) {
  11811. emitParsingError(this.observer, new Error(`Found ${tsPacketErrors} TS packet/s that do not start with 0x47`), void 0, this.logger);
  11812. }
  11813. videoTrack.pesData = videoData;
  11814. audioTrack.pesData = audioData;
  11815. id3Track.pesData = id3Data;
  11816. const demuxResult = {
  11817. audioTrack,
  11818. videoTrack,
  11819. id3Track,
  11820. textTrack
  11821. };
  11822. if (flush) {
  11823. this.extractRemainingSamples(demuxResult);
  11824. }
  11825. return demuxResult;
  11826. }
  11827. flush() {
  11828. const {
  11829. remainderData
  11830. } = this;
  11831. this.remainderData = null;
  11832. let result;
  11833. if (remainderData) {
  11834. result = this.demux(remainderData, -1, false, true);
  11835. } else {
  11836. result = {
  11837. videoTrack: this._videoTrack,
  11838. audioTrack: this._audioTrack,
  11839. id3Track: this._id3Track,
  11840. textTrack: this._txtTrack
  11841. };
  11842. }
  11843. this.extractRemainingSamples(result);
  11844. if (this.sampleAes) {
  11845. return this.decrypt(result, this.sampleAes);
  11846. }
  11847. return result;
  11848. }
  11849. extractRemainingSamples(demuxResult) {
  11850. const {
  11851. audioTrack,
  11852. videoTrack,
  11853. id3Track,
  11854. textTrack
  11855. } = demuxResult;
  11856. const videoData = videoTrack.pesData;
  11857. const audioData = audioTrack.pesData;
  11858. const id3Data = id3Track.pesData;
  11859. let pes;
  11860. if (videoData && (pes = parsePES(videoData, this.logger))) {
  11861. this.readyVideoParser(videoTrack.segmentCodec);
  11862. if (this.videoParser !== null) {
  11863. this.videoParser.parsePES(videoTrack, textTrack, pes, true);
  11864. videoTrack.pesData = null;
  11865. }
  11866. } else {
  11867. videoTrack.pesData = videoData;
  11868. }
  11869. if (audioData && (pes = parsePES(audioData, this.logger))) {
  11870. switch (audioTrack.segmentCodec) {
  11871. case "aac":
  11872. this.parseAACPES(audioTrack, pes);
  11873. break;
  11874. case "mp3":
  11875. this.parseMPEGPES(audioTrack, pes);
  11876. break;
  11877. case "ac3":
  11878. {
  11879. this.parseAC3PES(audioTrack, pes);
  11880. }
  11881. break;
  11882. }
  11883. audioTrack.pesData = null;
  11884. } else {
  11885. if (audioData != null && audioData.size) {
  11886. this.logger.log("last AAC PES packet truncated,might overlap between fragments");
  11887. }
  11888. audioTrack.pesData = audioData;
  11889. }
  11890. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  11891. this.parseID3PES(id3Track, pes);
  11892. id3Track.pesData = null;
  11893. } else {
  11894. id3Track.pesData = id3Data;
  11895. }
  11896. }
  11897. demuxSampleAes(data, keyData, timeOffset) {
  11898. const demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
  11899. const sampleAes = this.sampleAes = new SampleAesDecrypter(this.observer, this.config, keyData);
  11900. return this.decrypt(demuxResult, sampleAes);
  11901. }
  11902. readyVideoParser(codec) {
  11903. if (this.videoParser === null) {
  11904. if (codec === "avc") {
  11905. this.videoParser = new AvcVideoParser();
  11906. } else if (codec === "hevc") {
  11907. this.videoParser = new HevcVideoParser();
  11908. }
  11909. }
  11910. }
  11911. decrypt(demuxResult, sampleAes) {
  11912. return new Promise((resolve) => {
  11913. const {
  11914. audioTrack,
  11915. videoTrack
  11916. } = demuxResult;
  11917. if (audioTrack.samples && audioTrack.segmentCodec === "aac") {
  11918. sampleAes.decryptAacSamples(audioTrack.samples, 0, () => {
  11919. if (videoTrack.samples) {
  11920. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  11921. resolve(demuxResult);
  11922. });
  11923. } else {
  11924. resolve(demuxResult);
  11925. }
  11926. });
  11927. } else if (videoTrack.samples) {
  11928. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  11929. resolve(demuxResult);
  11930. });
  11931. }
  11932. });
  11933. }
  11934. destroy() {
  11935. if (this.observer) {
  11936. this.observer.removeAllListeners();
  11937. }
  11938. this.config = this.logger = this.observer = null;
  11939. this.aacOverFlow = this.videoParser = this.remainderData = this.sampleAes = null;
  11940. this._videoTrack = this._audioTrack = this._id3Track = this._txtTrack = void 0;
  11941. }
  11942. parseAACPES(track, pes) {
  11943. let startOffset = 0;
  11944. const aacOverFlow = this.aacOverFlow;
  11945. let data = pes.data;
  11946. if (aacOverFlow) {
  11947. this.aacOverFlow = null;
  11948. const frameMissingBytes = aacOverFlow.missing;
  11949. const sampleLength = aacOverFlow.sample.unit.byteLength;
  11950. if (frameMissingBytes === -1) {
  11951. data = appendUint8Array(aacOverFlow.sample.unit, data);
  11952. } else {
  11953. const frameOverflowBytes = sampleLength - frameMissingBytes;
  11954. aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
  11955. track.samples.push(aacOverFlow.sample);
  11956. startOffset = aacOverFlow.missing;
  11957. }
  11958. }
  11959. let offset;
  11960. let len;
  11961. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  11962. if (isHeader$1(data, offset)) {
  11963. break;
  11964. }
  11965. }
  11966. if (offset !== startOffset) {
  11967. let reason;
  11968. const recoverable = offset < len - 1;
  11969. if (recoverable) {
  11970. reason = `AAC PES did not start with ADTS header,offset:${offset}`;
  11971. } else {
  11972. reason = "No ADTS header found in AAC PES";
  11973. }
  11974. emitParsingError(this.observer, new Error(reason), recoverable, this.logger);
  11975. if (!recoverable) {
  11976. return;
  11977. }
  11978. }
  11979. initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  11980. let pts;
  11981. if (pes.pts !== void 0) {
  11982. pts = pes.pts;
  11983. } else if (aacOverFlow) {
  11984. const frameDuration = getFrameDuration(track.samplerate);
  11985. pts = aacOverFlow.sample.pts + frameDuration;
  11986. } else {
  11987. this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");
  11988. return;
  11989. }
  11990. let frameIndex = 0;
  11991. let frame;
  11992. while (offset < len) {
  11993. frame = appendFrame$2(track, data, offset, pts, frameIndex);
  11994. offset += frame.length;
  11995. if (!frame.missing) {
  11996. frameIndex++;
  11997. for (; offset < len - 1; offset++) {
  11998. if (isHeader$1(data, offset)) {
  11999. break;
  12000. }
  12001. }
  12002. } else {
  12003. this.aacOverFlow = frame;
  12004. break;
  12005. }
  12006. }
  12007. }
  12008. parseMPEGPES(track, pes) {
  12009. const data = pes.data;
  12010. const length = data.length;
  12011. let frameIndex = 0;
  12012. let offset = 0;
  12013. const pts = pes.pts;
  12014. if (pts === void 0) {
  12015. this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");
  12016. return;
  12017. }
  12018. while (offset < length) {
  12019. if (isHeader(data, offset)) {
  12020. const frame = appendFrame$1(track, data, offset, pts, frameIndex);
  12021. if (frame) {
  12022. offset += frame.length;
  12023. frameIndex++;
  12024. } else {
  12025. break;
  12026. }
  12027. } else {
  12028. offset++;
  12029. }
  12030. }
  12031. }
  12032. parseAC3PES(track, pes) {
  12033. {
  12034. const data = pes.data;
  12035. const pts = pes.pts;
  12036. if (pts === void 0) {
  12037. this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");
  12038. return;
  12039. }
  12040. const length = data.length;
  12041. let frameIndex = 0;
  12042. let offset = 0;
  12043. let parsed;
  12044. while (offset < length && (parsed = appendFrame(track, data, offset, pts, frameIndex++)) > 0) {
  12045. offset += parsed;
  12046. }
  12047. }
  12048. }
  12049. parseID3PES(id3Track, pes) {
  12050. if (pes.pts === void 0) {
  12051. this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");
  12052. return;
  12053. }
  12054. const id3Sample = _extends({}, pes, {
  12055. type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,
  12056. duration: Number.POSITIVE_INFINITY
  12057. });
  12058. id3Track.samples.push(id3Sample);
  12059. }
  12060. };
  12061. function parsePID(data, offset) {
  12062. return ((data[offset + 1] & 31) << 8) + data[offset + 2];
  12063. }
  12064. function parsePAT(data, offset) {
  12065. return (data[offset + 10] & 31) << 8 | data[offset + 11];
  12066. }
  12067. function parsePMT(data, offset, typeSupported, isSampleAes, observer, logger2) {
  12068. const result = {
  12069. audioPid: -1,
  12070. videoPid: -1,
  12071. id3Pid: -1,
  12072. segmentVideoCodec: "avc",
  12073. segmentAudioCodec: "aac"
  12074. };
  12075. const sectionLength = (data[offset + 1] & 15) << 8 | data[offset + 2];
  12076. const tableEnd = offset + 3 + sectionLength - 4;
  12077. const programInfoLength = (data[offset + 10] & 15) << 8 | data[offset + 11];
  12078. offset += 12 + programInfoLength;
  12079. while (offset < tableEnd) {
  12080. const pid = parsePID(data, offset);
  12081. const esInfoLength = (data[offset + 3] & 15) << 8 | data[offset + 4];
  12082. switch (data[offset]) {
  12083. case 207:
  12084. if (!isSampleAes) {
  12085. logEncryptedSamplesFoundInUnencryptedStream("ADTS AAC", logger2);
  12086. break;
  12087. }
  12088. case 15:
  12089. if (result.audioPid === -1) {
  12090. result.audioPid = pid;
  12091. }
  12092. break;
  12093. case 21:
  12094. if (result.id3Pid === -1) {
  12095. result.id3Pid = pid;
  12096. }
  12097. break;
  12098. case 219:
  12099. if (!isSampleAes) {
  12100. logEncryptedSamplesFoundInUnencryptedStream("H.264", logger2);
  12101. break;
  12102. }
  12103. case 27:
  12104. if (result.videoPid === -1) {
  12105. result.videoPid = pid;
  12106. }
  12107. break;
  12108. case 3:
  12109. case 4:
  12110. if (!typeSupported.mpeg && !typeSupported.mp3) {
  12111. logger2.log("MPEG audio found, not supported in this browser");
  12112. } else if (result.audioPid === -1) {
  12113. result.audioPid = pid;
  12114. result.segmentAudioCodec = "mp3";
  12115. }
  12116. break;
  12117. case 193:
  12118. if (!isSampleAes) {
  12119. logEncryptedSamplesFoundInUnencryptedStream("AC-3", logger2);
  12120. break;
  12121. }
  12122. case 129:
  12123. {
  12124. if (!typeSupported.ac3) {
  12125. logger2.log("AC-3 audio found, not supported in this browser");
  12126. } else if (result.audioPid === -1) {
  12127. result.audioPid = pid;
  12128. result.segmentAudioCodec = "ac3";
  12129. }
  12130. }
  12131. break;
  12132. case 6:
  12133. if (result.audioPid === -1 && esInfoLength > 0) {
  12134. let parsePos = offset + 5;
  12135. let remaining = esInfoLength;
  12136. while (remaining > 2) {
  12137. const descriptorId = data[parsePos];
  12138. switch (descriptorId) {
  12139. case 106:
  12140. {
  12141. if (typeSupported.ac3 !== true) {
  12142. logger2.log("AC-3 audio found, not supported in this browser for now");
  12143. } else {
  12144. result.audioPid = pid;
  12145. result.segmentAudioCodec = "ac3";
  12146. }
  12147. }
  12148. break;
  12149. }
  12150. const descriptorLen = data[parsePos + 1] + 2;
  12151. parsePos += descriptorLen;
  12152. remaining -= descriptorLen;
  12153. }
  12154. }
  12155. break;
  12156. case 194:
  12157. case 135:
  12158. emitParsingError(observer, new Error("Unsupported EC-3 in M2TS found"), void 0, logger2);
  12159. return result;
  12160. case 36:
  12161. {
  12162. if (result.videoPid === -1) {
  12163. result.videoPid = pid;
  12164. result.segmentVideoCodec = "hevc";
  12165. logger2.log("HEVC in M2TS found");
  12166. }
  12167. }
  12168. break;
  12169. }
  12170. offset += esInfoLength + 5;
  12171. }
  12172. return result;
  12173. }
  12174. function emitParsingError(observer, error, levelRetry, logger2) {
  12175. logger2.warn(`parsing error: ${error.message}`);
  12176. observer.emit(Events.ERROR, Events.ERROR, {
  12177. type: ErrorTypes.MEDIA_ERROR,
  12178. details: ErrorDetails.FRAG_PARSING_ERROR,
  12179. fatal: false,
  12180. levelRetry,
  12181. error,
  12182. reason: error.message
  12183. });
  12184. }
  12185. function logEncryptedSamplesFoundInUnencryptedStream(type, logger2) {
  12186. logger2.log(`${type} with AES-128-CBC encryption found in unencrypted stream`);
  12187. }
  12188. function parsePES(stream, logger2) {
  12189. let i = 0;
  12190. let frag;
  12191. let pesLen;
  12192. let pesHdrLen;
  12193. let pesPts;
  12194. let pesDts;
  12195. const data = stream.data;
  12196. if (!stream || stream.size === 0) {
  12197. return null;
  12198. }
  12199. while (data[0].length < 19 && data.length > 1) {
  12200. data[0] = appendUint8Array(data[0], data[1]);
  12201. data.splice(1, 1);
  12202. }
  12203. frag = data[0];
  12204. const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  12205. if (pesPrefix === 1) {
  12206. pesLen = (frag[4] << 8) + frag[5];
  12207. if (pesLen && pesLen > stream.size - 6) {
  12208. return null;
  12209. }
  12210. const pesFlags = frag[7];
  12211. if (pesFlags & 192) {
  12212. pesPts = (frag[9] & 14) * 536870912 + // 1 << 29
  12213. (frag[10] & 255) * 4194304 + // 1 << 22
  12214. (frag[11] & 254) * 16384 + // 1 << 14
  12215. (frag[12] & 255) * 128 + // 1 << 7
  12216. (frag[13] & 254) / 2;
  12217. if (pesFlags & 64) {
  12218. pesDts = (frag[14] & 14) * 536870912 + // 1 << 29
  12219. (frag[15] & 255) * 4194304 + // 1 << 22
  12220. (frag[16] & 254) * 16384 + // 1 << 14
  12221. (frag[17] & 255) * 128 + // 1 << 7
  12222. (frag[18] & 254) / 2;
  12223. if (pesPts - pesDts > 60 * 9e4) {
  12224. logger2.warn(`${Math.round((pesPts - pesDts) / 9e4)}s delta between PTS and DTS, align them`);
  12225. pesPts = pesDts;
  12226. }
  12227. } else {
  12228. pesDts = pesPts;
  12229. }
  12230. }
  12231. pesHdrLen = frag[8];
  12232. let payloadStartOffset = pesHdrLen + 9;
  12233. if (stream.size <= payloadStartOffset) {
  12234. return null;
  12235. }
  12236. stream.size -= payloadStartOffset;
  12237. const pesData = new Uint8Array(stream.size);
  12238. for (let j = 0, dataLen = data.length; j < dataLen; j++) {
  12239. frag = data[j];
  12240. let len = frag.byteLength;
  12241. if (payloadStartOffset) {
  12242. if (payloadStartOffset > len) {
  12243. payloadStartOffset -= len;
  12244. continue;
  12245. } else {
  12246. frag = frag.subarray(payloadStartOffset);
  12247. len -= payloadStartOffset;
  12248. payloadStartOffset = 0;
  12249. }
  12250. }
  12251. pesData.set(frag, i);
  12252. i += len;
  12253. }
  12254. if (pesLen) {
  12255. pesLen -= pesHdrLen + 3;
  12256. }
  12257. return {
  12258. data: pesData,
  12259. pts: pesPts,
  12260. dts: pesDts,
  12261. len: pesLen
  12262. };
  12263. }
  12264. return null;
  12265. }
  12266. var AAC = class {
  12267. static getSilentFrame(codec, channelCount) {
  12268. switch (codec) {
  12269. case "mp4a.40.2":
  12270. if (channelCount === 1) {
  12271. return new Uint8Array([0, 200, 0, 128, 35, 128]);
  12272. } else if (channelCount === 2) {
  12273. return new Uint8Array([33, 0, 73, 144, 2, 25, 0, 35, 128]);
  12274. } else if (channelCount === 3) {
  12275. return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 142]);
  12276. } else if (channelCount === 4) {
  12277. return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 128, 44, 128, 8, 2, 56]);
  12278. } else if (channelCount === 5) {
  12279. return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 56]);
  12280. } else if (channelCount === 6) {
  12281. 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]);
  12282. }
  12283. break;
  12284. default:
  12285. if (channelCount === 1) {
  12286. 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]);
  12287. } else if (channelCount === 2) {
  12288. 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]);
  12289. } else if (channelCount === 3) {
  12290. 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]);
  12291. }
  12292. break;
  12293. }
  12294. return void 0;
  12295. }
  12296. };
  12297. var UINT32_MAX = Math.pow(2, 32) - 1;
  12298. var MP4 = class _MP4 {
  12299. static init() {
  12300. _MP4.types = {
  12301. avc1: [],
  12302. // codingname
  12303. avcC: [],
  12304. hvc1: [],
  12305. hvcC: [],
  12306. btrt: [],
  12307. dinf: [],
  12308. dref: [],
  12309. esds: [],
  12310. ftyp: [],
  12311. hdlr: [],
  12312. mdat: [],
  12313. mdhd: [],
  12314. mdia: [],
  12315. mfhd: [],
  12316. minf: [],
  12317. moof: [],
  12318. moov: [],
  12319. mp4a: [],
  12320. ".mp3": [],
  12321. dac3: [],
  12322. "ac-3": [],
  12323. mvex: [],
  12324. mvhd: [],
  12325. pasp: [],
  12326. sdtp: [],
  12327. stbl: [],
  12328. stco: [],
  12329. stsc: [],
  12330. stsd: [],
  12331. stsz: [],
  12332. stts: [],
  12333. tfdt: [],
  12334. tfhd: [],
  12335. traf: [],
  12336. trak: [],
  12337. trun: [],
  12338. trex: [],
  12339. tkhd: [],
  12340. vmhd: [],
  12341. smhd: []
  12342. };
  12343. let i;
  12344. for (i in _MP4.types) {
  12345. if (_MP4.types.hasOwnProperty(i)) {
  12346. _MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  12347. }
  12348. }
  12349. const videoHdlr = new Uint8Array([
  12350. 0,
  12351. // version 0
  12352. 0,
  12353. 0,
  12354. 0,
  12355. // flags
  12356. 0,
  12357. 0,
  12358. 0,
  12359. 0,
  12360. // pre_defined
  12361. 118,
  12362. 105,
  12363. 100,
  12364. 101,
  12365. // handler_type: 'vide'
  12366. 0,
  12367. 0,
  12368. 0,
  12369. 0,
  12370. // reserved
  12371. 0,
  12372. 0,
  12373. 0,
  12374. 0,
  12375. // reserved
  12376. 0,
  12377. 0,
  12378. 0,
  12379. 0,
  12380. // reserved
  12381. 86,
  12382. 105,
  12383. 100,
  12384. 101,
  12385. 111,
  12386. 72,
  12387. 97,
  12388. 110,
  12389. 100,
  12390. 108,
  12391. 101,
  12392. 114,
  12393. 0
  12394. // name: 'VideoHandler'
  12395. ]);
  12396. const audioHdlr = new Uint8Array([
  12397. 0,
  12398. // version 0
  12399. 0,
  12400. 0,
  12401. 0,
  12402. // flags
  12403. 0,
  12404. 0,
  12405. 0,
  12406. 0,
  12407. // pre_defined
  12408. 115,
  12409. 111,
  12410. 117,
  12411. 110,
  12412. // handler_type: 'soun'
  12413. 0,
  12414. 0,
  12415. 0,
  12416. 0,
  12417. // reserved
  12418. 0,
  12419. 0,
  12420. 0,
  12421. 0,
  12422. // reserved
  12423. 0,
  12424. 0,
  12425. 0,
  12426. 0,
  12427. // reserved
  12428. 83,
  12429. 111,
  12430. 117,
  12431. 110,
  12432. 100,
  12433. 72,
  12434. 97,
  12435. 110,
  12436. 100,
  12437. 108,
  12438. 101,
  12439. 114,
  12440. 0
  12441. // name: 'SoundHandler'
  12442. ]);
  12443. _MP4.HDLR_TYPES = {
  12444. video: videoHdlr,
  12445. audio: audioHdlr
  12446. };
  12447. const dref = new Uint8Array([
  12448. 0,
  12449. // version 0
  12450. 0,
  12451. 0,
  12452. 0,
  12453. // flags
  12454. 0,
  12455. 0,
  12456. 0,
  12457. 1,
  12458. // entry_count
  12459. 0,
  12460. 0,
  12461. 0,
  12462. 12,
  12463. // entry_size
  12464. 117,
  12465. 114,
  12466. 108,
  12467. 32,
  12468. // 'url' type
  12469. 0,
  12470. // version 0
  12471. 0,
  12472. 0,
  12473. 1
  12474. // entry_flags
  12475. ]);
  12476. const stco = new Uint8Array([
  12477. 0,
  12478. // version
  12479. 0,
  12480. 0,
  12481. 0,
  12482. // flags
  12483. 0,
  12484. 0,
  12485. 0,
  12486. 0
  12487. // entry_count
  12488. ]);
  12489. _MP4.STTS = _MP4.STSC = _MP4.STCO = stco;
  12490. _MP4.STSZ = new Uint8Array([
  12491. 0,
  12492. // version
  12493. 0,
  12494. 0,
  12495. 0,
  12496. // flags
  12497. 0,
  12498. 0,
  12499. 0,
  12500. 0,
  12501. // sample_size
  12502. 0,
  12503. 0,
  12504. 0,
  12505. 0
  12506. // sample_count
  12507. ]);
  12508. _MP4.VMHD = new Uint8Array([
  12509. 0,
  12510. // version
  12511. 0,
  12512. 0,
  12513. 1,
  12514. // flags
  12515. 0,
  12516. 0,
  12517. // graphicsmode
  12518. 0,
  12519. 0,
  12520. 0,
  12521. 0,
  12522. 0,
  12523. 0
  12524. // opcolor
  12525. ]);
  12526. _MP4.SMHD = new Uint8Array([
  12527. 0,
  12528. // version
  12529. 0,
  12530. 0,
  12531. 0,
  12532. // flags
  12533. 0,
  12534. 0,
  12535. // balance
  12536. 0,
  12537. 0
  12538. // reserved
  12539. ]);
  12540. _MP4.STSD = new Uint8Array([
  12541. 0,
  12542. // version 0
  12543. 0,
  12544. 0,
  12545. 0,
  12546. // flags
  12547. 0,
  12548. 0,
  12549. 0,
  12550. 1
  12551. ]);
  12552. const majorBrand = new Uint8Array([105, 115, 111, 109]);
  12553. const avc1Brand = new Uint8Array([97, 118, 99, 49]);
  12554. const minorVersion = new Uint8Array([0, 0, 0, 1]);
  12555. _MP4.FTYP = _MP4.box(_MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  12556. _MP4.DINF = _MP4.box(_MP4.types.dinf, _MP4.box(_MP4.types.dref, dref));
  12557. }
  12558. static box(type, ...payload) {
  12559. let size = 8;
  12560. let i = payload.length;
  12561. const len = i;
  12562. while (i--) {
  12563. size += payload[i].byteLength;
  12564. }
  12565. const result = new Uint8Array(size);
  12566. result[0] = size >> 24 & 255;
  12567. result[1] = size >> 16 & 255;
  12568. result[2] = size >> 8 & 255;
  12569. result[3] = size & 255;
  12570. result.set(type, 4);
  12571. for (i = 0, size = 8; i < len; i++) {
  12572. result.set(payload[i], size);
  12573. size += payload[i].byteLength;
  12574. }
  12575. return result;
  12576. }
  12577. static hdlr(type) {
  12578. return _MP4.box(_MP4.types.hdlr, _MP4.HDLR_TYPES[type]);
  12579. }
  12580. static mdat(data) {
  12581. return _MP4.box(_MP4.types.mdat, data);
  12582. }
  12583. static mdhd(timescale, duration) {
  12584. duration *= timescale;
  12585. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  12586. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  12587. return _MP4.box(_MP4.types.mdhd, new Uint8Array([
  12588. 1,
  12589. // version 1
  12590. 0,
  12591. 0,
  12592. 0,
  12593. // flags
  12594. 0,
  12595. 0,
  12596. 0,
  12597. 0,
  12598. 0,
  12599. 0,
  12600. 0,
  12601. 2,
  12602. // creation_time
  12603. 0,
  12604. 0,
  12605. 0,
  12606. 0,
  12607. 0,
  12608. 0,
  12609. 0,
  12610. 3,
  12611. // modification_time
  12612. timescale >> 24 & 255,
  12613. timescale >> 16 & 255,
  12614. timescale >> 8 & 255,
  12615. timescale & 255,
  12616. // timescale
  12617. upperWordDuration >> 24,
  12618. upperWordDuration >> 16 & 255,
  12619. upperWordDuration >> 8 & 255,
  12620. upperWordDuration & 255,
  12621. lowerWordDuration >> 24,
  12622. lowerWordDuration >> 16 & 255,
  12623. lowerWordDuration >> 8 & 255,
  12624. lowerWordDuration & 255,
  12625. 85,
  12626. 196,
  12627. // 'und' language (undetermined)
  12628. 0,
  12629. 0
  12630. ]));
  12631. }
  12632. static mdia(track) {
  12633. return _MP4.box(_MP4.types.mdia, _MP4.mdhd(track.timescale || 0, track.duration || 0), _MP4.hdlr(track.type), _MP4.minf(track));
  12634. }
  12635. static mfhd(sequenceNumber) {
  12636. return _MP4.box(_MP4.types.mfhd, new Uint8Array([
  12637. 0,
  12638. 0,
  12639. 0,
  12640. 0,
  12641. // flags
  12642. sequenceNumber >> 24,
  12643. sequenceNumber >> 16 & 255,
  12644. sequenceNumber >> 8 & 255,
  12645. sequenceNumber & 255
  12646. // sequence_number
  12647. ]));
  12648. }
  12649. static minf(track) {
  12650. if (track.type === "audio") {
  12651. return _MP4.box(_MP4.types.minf, _MP4.box(_MP4.types.smhd, _MP4.SMHD), _MP4.DINF, _MP4.stbl(track));
  12652. } else {
  12653. return _MP4.box(_MP4.types.minf, _MP4.box(_MP4.types.vmhd, _MP4.VMHD), _MP4.DINF, _MP4.stbl(track));
  12654. }
  12655. }
  12656. static moof(sn, baseMediaDecodeTime, track) {
  12657. return _MP4.box(_MP4.types.moof, _MP4.mfhd(sn), _MP4.traf(track, baseMediaDecodeTime));
  12658. }
  12659. static moov(tracks) {
  12660. let i = tracks.length;
  12661. const boxes = [];
  12662. while (i--) {
  12663. boxes[i] = _MP4.trak(tracks[i]);
  12664. }
  12665. return _MP4.box.apply(null, [_MP4.types.moov, _MP4.mvhd(tracks[0].timescale || 0, tracks[0].duration || 0)].concat(boxes).concat(_MP4.mvex(tracks)));
  12666. }
  12667. static mvex(tracks) {
  12668. let i = tracks.length;
  12669. const boxes = [];
  12670. while (i--) {
  12671. boxes[i] = _MP4.trex(tracks[i]);
  12672. }
  12673. return _MP4.box.apply(null, [_MP4.types.mvex, ...boxes]);
  12674. }
  12675. static mvhd(timescale, duration) {
  12676. duration *= timescale;
  12677. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  12678. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  12679. const bytes = new Uint8Array([
  12680. 1,
  12681. // version 1
  12682. 0,
  12683. 0,
  12684. 0,
  12685. // flags
  12686. 0,
  12687. 0,
  12688. 0,
  12689. 0,
  12690. 0,
  12691. 0,
  12692. 0,
  12693. 2,
  12694. // creation_time
  12695. 0,
  12696. 0,
  12697. 0,
  12698. 0,
  12699. 0,
  12700. 0,
  12701. 0,
  12702. 3,
  12703. // modification_time
  12704. timescale >> 24 & 255,
  12705. timescale >> 16 & 255,
  12706. timescale >> 8 & 255,
  12707. timescale & 255,
  12708. // timescale
  12709. upperWordDuration >> 24,
  12710. upperWordDuration >> 16 & 255,
  12711. upperWordDuration >> 8 & 255,
  12712. upperWordDuration & 255,
  12713. lowerWordDuration >> 24,
  12714. lowerWordDuration >> 16 & 255,
  12715. lowerWordDuration >> 8 & 255,
  12716. lowerWordDuration & 255,
  12717. 0,
  12718. 1,
  12719. 0,
  12720. 0,
  12721. // 1.0 rate
  12722. 1,
  12723. 0,
  12724. // 1.0 volume
  12725. 0,
  12726. 0,
  12727. // reserved
  12728. 0,
  12729. 0,
  12730. 0,
  12731. 0,
  12732. // reserved
  12733. 0,
  12734. 0,
  12735. 0,
  12736. 0,
  12737. // reserved
  12738. 0,
  12739. 1,
  12740. 0,
  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. 1,
  12756. 0,
  12757. 0,
  12758. 0,
  12759. 0,
  12760. 0,
  12761. 0,
  12762. 0,
  12763. 0,
  12764. 0,
  12765. 0,
  12766. 0,
  12767. 0,
  12768. 0,
  12769. 0,
  12770. 64,
  12771. 0,
  12772. 0,
  12773. 0,
  12774. // transformation: unity matrix
  12775. 0,
  12776. 0,
  12777. 0,
  12778. 0,
  12779. 0,
  12780. 0,
  12781. 0,
  12782. 0,
  12783. 0,
  12784. 0,
  12785. 0,
  12786. 0,
  12787. 0,
  12788. 0,
  12789. 0,
  12790. 0,
  12791. 0,
  12792. 0,
  12793. 0,
  12794. 0,
  12795. 0,
  12796. 0,
  12797. 0,
  12798. 0,
  12799. // pre_defined
  12800. 255,
  12801. 255,
  12802. 255,
  12803. 255
  12804. // next_track_ID
  12805. ]);
  12806. return _MP4.box(_MP4.types.mvhd, bytes);
  12807. }
  12808. static sdtp(track) {
  12809. const samples = track.samples || [];
  12810. const bytes = new Uint8Array(4 + samples.length);
  12811. let i;
  12812. let flags;
  12813. for (i = 0; i < samples.length; i++) {
  12814. flags = samples[i].flags;
  12815. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  12816. }
  12817. return _MP4.box(_MP4.types.sdtp, bytes);
  12818. }
  12819. static stbl(track) {
  12820. 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));
  12821. }
  12822. static avc1(track) {
  12823. let sps = [];
  12824. let pps = [];
  12825. let i;
  12826. let data;
  12827. let len;
  12828. for (i = 0; i < track.sps.length; i++) {
  12829. data = track.sps[i];
  12830. len = data.byteLength;
  12831. sps.push(len >>> 8 & 255);
  12832. sps.push(len & 255);
  12833. sps = sps.concat(Array.prototype.slice.call(data));
  12834. }
  12835. for (i = 0; i < track.pps.length; i++) {
  12836. data = track.pps[i];
  12837. len = data.byteLength;
  12838. pps.push(len >>> 8 & 255);
  12839. pps.push(len & 255);
  12840. pps = pps.concat(Array.prototype.slice.call(data));
  12841. }
  12842. const avcc = _MP4.box(_MP4.types.avcC, new Uint8Array([
  12843. 1,
  12844. // version
  12845. sps[3],
  12846. // profile
  12847. sps[4],
  12848. // profile compat
  12849. sps[5],
  12850. // level
  12851. 252 | 3,
  12852. // lengthSizeMinusOne, hard-coded to 4 bytes
  12853. 224 | track.sps.length
  12854. // 3bit reserved (111) + numOfSequenceParameterSets
  12855. ].concat(sps).concat([
  12856. track.pps.length
  12857. // numOfPictureParameterSets
  12858. ]).concat(pps)));
  12859. const width = track.width;
  12860. const height = track.height;
  12861. const hSpacing = track.pixelRatio[0];
  12862. const vSpacing = track.pixelRatio[1];
  12863. return _MP4.box(
  12864. _MP4.types.avc1,
  12865. new Uint8Array([
  12866. 0,
  12867. 0,
  12868. 0,
  12869. // reserved
  12870. 0,
  12871. 0,
  12872. 0,
  12873. // reserved
  12874. 0,
  12875. 1,
  12876. // data_reference_index
  12877. 0,
  12878. 0,
  12879. // pre_defined
  12880. 0,
  12881. 0,
  12882. // reserved
  12883. 0,
  12884. 0,
  12885. 0,
  12886. 0,
  12887. 0,
  12888. 0,
  12889. 0,
  12890. 0,
  12891. 0,
  12892. 0,
  12893. 0,
  12894. 0,
  12895. // pre_defined
  12896. width >> 8 & 255,
  12897. width & 255,
  12898. // width
  12899. height >> 8 & 255,
  12900. height & 255,
  12901. // height
  12902. 0,
  12903. 72,
  12904. 0,
  12905. 0,
  12906. // horizresolution
  12907. 0,
  12908. 72,
  12909. 0,
  12910. 0,
  12911. // vertresolution
  12912. 0,
  12913. 0,
  12914. 0,
  12915. 0,
  12916. // reserved
  12917. 0,
  12918. 1,
  12919. // frame_count
  12920. 18,
  12921. 100,
  12922. 97,
  12923. 105,
  12924. 108,
  12925. // dailymotion/hls.js
  12926. 121,
  12927. 109,
  12928. 111,
  12929. 116,
  12930. 105,
  12931. 111,
  12932. 110,
  12933. 47,
  12934. 104,
  12935. 108,
  12936. 115,
  12937. 46,
  12938. 106,
  12939. 115,
  12940. 0,
  12941. 0,
  12942. 0,
  12943. 0,
  12944. 0,
  12945. 0,
  12946. 0,
  12947. 0,
  12948. 0,
  12949. 0,
  12950. 0,
  12951. 0,
  12952. 0,
  12953. // compressorname
  12954. 0,
  12955. 24,
  12956. // depth = 24
  12957. 17,
  12958. 17
  12959. ]),
  12960. // pre_defined = -1
  12961. avcc,
  12962. _MP4.box(_MP4.types.btrt, new Uint8Array([
  12963. 0,
  12964. 28,
  12965. 156,
  12966. 128,
  12967. // bufferSizeDB
  12968. 0,
  12969. 45,
  12970. 198,
  12971. 192,
  12972. // maxBitrate
  12973. 0,
  12974. 45,
  12975. 198,
  12976. 192
  12977. ])),
  12978. // avgBitrate
  12979. _MP4.box(_MP4.types.pasp, new Uint8Array([
  12980. hSpacing >> 24,
  12981. // hSpacing
  12982. hSpacing >> 16 & 255,
  12983. hSpacing >> 8 & 255,
  12984. hSpacing & 255,
  12985. vSpacing >> 24,
  12986. // vSpacing
  12987. vSpacing >> 16 & 255,
  12988. vSpacing >> 8 & 255,
  12989. vSpacing & 255
  12990. ]))
  12991. );
  12992. }
  12993. static esds(track) {
  12994. const config = track.config;
  12995. return new Uint8Array([
  12996. 0,
  12997. // version 0
  12998. 0,
  12999. 0,
  13000. 0,
  13001. // flags
  13002. 3,
  13003. // descriptor_type
  13004. 25,
  13005. // length
  13006. 0,
  13007. 1,
  13008. // es_id
  13009. 0,
  13010. // stream_priority
  13011. 4,
  13012. // descriptor_type
  13013. 17,
  13014. // length
  13015. 64,
  13016. // codec : mpeg4_audio
  13017. 21,
  13018. // stream_type
  13019. 0,
  13020. 0,
  13021. 0,
  13022. // buffer_size
  13023. 0,
  13024. 0,
  13025. 0,
  13026. 0,
  13027. // maxBitrate
  13028. 0,
  13029. 0,
  13030. 0,
  13031. 0,
  13032. // avgBitrate
  13033. 5,
  13034. // descriptor_type
  13035. 2,
  13036. // length
  13037. ...config,
  13038. 6,
  13039. 1,
  13040. 2
  13041. // GASpecificConfig)); // length + audio config descriptor
  13042. ]);
  13043. }
  13044. static audioStsd(track) {
  13045. const samplerate = track.samplerate || 0;
  13046. return new Uint8Array([
  13047. 0,
  13048. 0,
  13049. 0,
  13050. // reserved
  13051. 0,
  13052. 0,
  13053. 0,
  13054. // reserved
  13055. 0,
  13056. 1,
  13057. // data_reference_index
  13058. 0,
  13059. 0,
  13060. 0,
  13061. 0,
  13062. 0,
  13063. 0,
  13064. 0,
  13065. 0,
  13066. // reserved
  13067. 0,
  13068. track.channelCount || 0,
  13069. // channelcount
  13070. 0,
  13071. 16,
  13072. // sampleSize:16bits
  13073. 0,
  13074. 0,
  13075. 0,
  13076. 0,
  13077. // reserved2
  13078. samplerate >> 8 & 255,
  13079. samplerate & 255,
  13080. //
  13081. 0,
  13082. 0
  13083. ]);
  13084. }
  13085. static mp4a(track) {
  13086. return _MP4.box(_MP4.types.mp4a, _MP4.audioStsd(track), _MP4.box(_MP4.types.esds, _MP4.esds(track)));
  13087. }
  13088. static mp3(track) {
  13089. return _MP4.box(_MP4.types[".mp3"], _MP4.audioStsd(track));
  13090. }
  13091. static ac3(track) {
  13092. return _MP4.box(_MP4.types["ac-3"], _MP4.audioStsd(track), _MP4.box(_MP4.types.dac3, track.config));
  13093. }
  13094. static stsd(track) {
  13095. const {
  13096. segmentCodec
  13097. } = track;
  13098. if (track.type === "audio") {
  13099. if (segmentCodec === "aac") {
  13100. return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.mp4a(track));
  13101. }
  13102. if (segmentCodec === "ac3" && track.config) {
  13103. return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.ac3(track));
  13104. }
  13105. if (segmentCodec === "mp3" && track.codec === "mp3") {
  13106. return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.mp3(track));
  13107. }
  13108. } else {
  13109. if (track.pps && track.sps) {
  13110. if (segmentCodec === "avc") {
  13111. return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.avc1(track));
  13112. }
  13113. if (segmentCodec === "hevc" && track.vps) {
  13114. return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.hvc1(track));
  13115. }
  13116. } else {
  13117. throw new Error(`video track missing pps or sps`);
  13118. }
  13119. }
  13120. throw new Error(`unsupported ${track.type} segment codec (${segmentCodec}/${track.codec})`);
  13121. }
  13122. static tkhd(track) {
  13123. const id = track.id;
  13124. const duration = (track.duration || 0) * (track.timescale || 0);
  13125. const width = track.width || 0;
  13126. const height = track.height || 0;
  13127. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  13128. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  13129. return _MP4.box(_MP4.types.tkhd, new Uint8Array([
  13130. 1,
  13131. // version 1
  13132. 0,
  13133. 0,
  13134. 7,
  13135. // flags
  13136. 0,
  13137. 0,
  13138. 0,
  13139. 0,
  13140. 0,
  13141. 0,
  13142. 0,
  13143. 2,
  13144. // creation_time
  13145. 0,
  13146. 0,
  13147. 0,
  13148. 0,
  13149. 0,
  13150. 0,
  13151. 0,
  13152. 3,
  13153. // modification_time
  13154. id >> 24 & 255,
  13155. id >> 16 & 255,
  13156. id >> 8 & 255,
  13157. id & 255,
  13158. // track_ID
  13159. 0,
  13160. 0,
  13161. 0,
  13162. 0,
  13163. // reserved
  13164. upperWordDuration >> 24,
  13165. upperWordDuration >> 16 & 255,
  13166. upperWordDuration >> 8 & 255,
  13167. upperWordDuration & 255,
  13168. lowerWordDuration >> 24,
  13169. lowerWordDuration >> 16 & 255,
  13170. lowerWordDuration >> 8 & 255,
  13171. lowerWordDuration & 255,
  13172. 0,
  13173. 0,
  13174. 0,
  13175. 0,
  13176. 0,
  13177. 0,
  13178. 0,
  13179. 0,
  13180. // reserved
  13181. 0,
  13182. 0,
  13183. // layer
  13184. 0,
  13185. 0,
  13186. // alternate_group
  13187. 0,
  13188. 0,
  13189. // non-audio track volume
  13190. 0,
  13191. 0,
  13192. // reserved
  13193. 0,
  13194. 1,
  13195. 0,
  13196. 0,
  13197. 0,
  13198. 0,
  13199. 0,
  13200. 0,
  13201. 0,
  13202. 0,
  13203. 0,
  13204. 0,
  13205. 0,
  13206. 0,
  13207. 0,
  13208. 0,
  13209. 0,
  13210. 1,
  13211. 0,
  13212. 0,
  13213. 0,
  13214. 0,
  13215. 0,
  13216. 0,
  13217. 0,
  13218. 0,
  13219. 0,
  13220. 0,
  13221. 0,
  13222. 0,
  13223. 0,
  13224. 0,
  13225. 64,
  13226. 0,
  13227. 0,
  13228. 0,
  13229. // transformation: unity matrix
  13230. width >> 8 & 255,
  13231. width & 255,
  13232. 0,
  13233. 0,
  13234. // width
  13235. height >> 8 & 255,
  13236. height & 255,
  13237. 0,
  13238. 0
  13239. // height
  13240. ]));
  13241. }
  13242. static traf(track, baseMediaDecodeTime) {
  13243. const sampleDependencyTable = _MP4.sdtp(track);
  13244. const id = track.id;
  13245. const upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  13246. const lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  13247. return _MP4.box(
  13248. _MP4.types.traf,
  13249. _MP4.box(_MP4.types.tfhd, new Uint8Array([
  13250. 0,
  13251. // version 0
  13252. 0,
  13253. 0,
  13254. 0,
  13255. // flags
  13256. id >> 24,
  13257. id >> 16 & 255,
  13258. id >> 8 & 255,
  13259. id & 255
  13260. // track_ID
  13261. ])),
  13262. _MP4.box(_MP4.types.tfdt, new Uint8Array([
  13263. 1,
  13264. // version 1
  13265. 0,
  13266. 0,
  13267. 0,
  13268. // flags
  13269. upperWordBaseMediaDecodeTime >> 24,
  13270. upperWordBaseMediaDecodeTime >> 16 & 255,
  13271. upperWordBaseMediaDecodeTime >> 8 & 255,
  13272. upperWordBaseMediaDecodeTime & 255,
  13273. lowerWordBaseMediaDecodeTime >> 24,
  13274. lowerWordBaseMediaDecodeTime >> 16 & 255,
  13275. lowerWordBaseMediaDecodeTime >> 8 & 255,
  13276. lowerWordBaseMediaDecodeTime & 255
  13277. ])),
  13278. _MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd
  13279. 20 + // tfdt
  13280. 8 + // traf header
  13281. 16 + // mfhd
  13282. 8 + // moof header
  13283. 8),
  13284. // mdat header
  13285. sampleDependencyTable
  13286. );
  13287. }
  13288. /**
  13289. * Generate a track box.
  13290. * @param track a track definition
  13291. */
  13292. static trak(track) {
  13293. track.duration = track.duration || 4294967295;
  13294. return _MP4.box(_MP4.types.trak, _MP4.tkhd(track), _MP4.mdia(track));
  13295. }
  13296. static trex(track) {
  13297. const id = track.id;
  13298. return _MP4.box(_MP4.types.trex, new Uint8Array([
  13299. 0,
  13300. // version 0
  13301. 0,
  13302. 0,
  13303. 0,
  13304. // flags
  13305. id >> 24,
  13306. id >> 16 & 255,
  13307. id >> 8 & 255,
  13308. id & 255,
  13309. // track_ID
  13310. 0,
  13311. 0,
  13312. 0,
  13313. 1,
  13314. // default_sample_description_index
  13315. 0,
  13316. 0,
  13317. 0,
  13318. 0,
  13319. // default_sample_duration
  13320. 0,
  13321. 0,
  13322. 0,
  13323. 0,
  13324. // default_sample_size
  13325. 0,
  13326. 1,
  13327. 0,
  13328. 1
  13329. // default_sample_flags
  13330. ]));
  13331. }
  13332. static trun(track, offset) {
  13333. const samples = track.samples || [];
  13334. const len = samples.length;
  13335. const arraylen = 12 + 16 * len;
  13336. const array = new Uint8Array(arraylen);
  13337. let i;
  13338. let sample;
  13339. let duration;
  13340. let size;
  13341. let flags;
  13342. let cts;
  13343. offset += 8 + arraylen;
  13344. array.set([
  13345. track.type === "video" ? 1 : 0,
  13346. // version 1 for video with signed-int sample_composition_time_offset
  13347. 0,
  13348. 15,
  13349. 1,
  13350. // flags
  13351. len >>> 24 & 255,
  13352. len >>> 16 & 255,
  13353. len >>> 8 & 255,
  13354. len & 255,
  13355. // sample_count
  13356. offset >>> 24 & 255,
  13357. offset >>> 16 & 255,
  13358. offset >>> 8 & 255,
  13359. offset & 255
  13360. // data_offset
  13361. ], 0);
  13362. for (i = 0; i < len; i++) {
  13363. sample = samples[i];
  13364. duration = sample.duration;
  13365. size = sample.size;
  13366. flags = sample.flags;
  13367. cts = sample.cts;
  13368. array.set([
  13369. duration >>> 24 & 255,
  13370. duration >>> 16 & 255,
  13371. duration >>> 8 & 255,
  13372. duration & 255,
  13373. // sample_duration
  13374. size >>> 24 & 255,
  13375. size >>> 16 & 255,
  13376. size >>> 8 & 255,
  13377. size & 255,
  13378. // sample_size
  13379. flags.isLeading << 2 | flags.dependsOn,
  13380. flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync,
  13381. flags.degradPrio & 240 << 8,
  13382. flags.degradPrio & 15,
  13383. // sample_flags
  13384. cts >>> 24 & 255,
  13385. cts >>> 16 & 255,
  13386. cts >>> 8 & 255,
  13387. cts & 255
  13388. // sample_composition_time_offset
  13389. ], 12 + 16 * i);
  13390. }
  13391. return _MP4.box(_MP4.types.trun, array);
  13392. }
  13393. static initSegment(tracks) {
  13394. if (!_MP4.types) {
  13395. _MP4.init();
  13396. }
  13397. const movie = _MP4.moov(tracks);
  13398. const result = appendUint8Array(_MP4.FTYP, movie);
  13399. return result;
  13400. }
  13401. static hvc1(track) {
  13402. const ps = track.params;
  13403. const units = [track.vps, track.sps, track.pps];
  13404. const NALuLengthSize = 4;
  13405. 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]);
  13406. let length = config.length;
  13407. for (let i = 0; i < units.length; i += 1) {
  13408. length += 3;
  13409. for (let j = 0; j < units[i].length; j += 1) {
  13410. length += 2 + units[i][j].length;
  13411. }
  13412. }
  13413. const hvcC = new Uint8Array(length);
  13414. hvcC.set(config, 0);
  13415. length = config.length;
  13416. const iMax = units.length - 1;
  13417. for (let i = 0; i < units.length; i += 1) {
  13418. hvcC.set(new Uint8Array([32 + i | (i === iMax ? 128 : 0), 0, units[i].length]), length);
  13419. length += 3;
  13420. for (let j = 0; j < units[i].length; j += 1) {
  13421. hvcC.set(new Uint8Array([units[i][j].length >> 8, units[i][j].length & 255]), length);
  13422. length += 2;
  13423. hvcC.set(units[i][j], length);
  13424. length += units[i][j].length;
  13425. }
  13426. }
  13427. const hvcc = _MP4.box(_MP4.types.hvcC, hvcC);
  13428. const width = track.width;
  13429. const height = track.height;
  13430. const hSpacing = track.pixelRatio[0];
  13431. const vSpacing = track.pixelRatio[1];
  13432. return _MP4.box(
  13433. _MP4.types.hvc1,
  13434. new Uint8Array([
  13435. 0,
  13436. 0,
  13437. 0,
  13438. // reserved
  13439. 0,
  13440. 0,
  13441. 0,
  13442. // reserved
  13443. 0,
  13444. 1,
  13445. // data_reference_index
  13446. 0,
  13447. 0,
  13448. // pre_defined
  13449. 0,
  13450. 0,
  13451. // reserved
  13452. 0,
  13453. 0,
  13454. 0,
  13455. 0,
  13456. 0,
  13457. 0,
  13458. 0,
  13459. 0,
  13460. 0,
  13461. 0,
  13462. 0,
  13463. 0,
  13464. // pre_defined
  13465. width >> 8 & 255,
  13466. width & 255,
  13467. // width
  13468. height >> 8 & 255,
  13469. height & 255,
  13470. // height
  13471. 0,
  13472. 72,
  13473. 0,
  13474. 0,
  13475. // horizresolution
  13476. 0,
  13477. 72,
  13478. 0,
  13479. 0,
  13480. // vertresolution
  13481. 0,
  13482. 0,
  13483. 0,
  13484. 0,
  13485. // reserved
  13486. 0,
  13487. 1,
  13488. // frame_count
  13489. 18,
  13490. 100,
  13491. 97,
  13492. 105,
  13493. 108,
  13494. // dailymotion/hls.js
  13495. 121,
  13496. 109,
  13497. 111,
  13498. 116,
  13499. 105,
  13500. 111,
  13501. 110,
  13502. 47,
  13503. 104,
  13504. 108,
  13505. 115,
  13506. 46,
  13507. 106,
  13508. 115,
  13509. 0,
  13510. 0,
  13511. 0,
  13512. 0,
  13513. 0,
  13514. 0,
  13515. 0,
  13516. 0,
  13517. 0,
  13518. 0,
  13519. 0,
  13520. 0,
  13521. 0,
  13522. // compressorname
  13523. 0,
  13524. 24,
  13525. // depth = 24
  13526. 17,
  13527. 17
  13528. ]),
  13529. // pre_defined = -1
  13530. hvcc,
  13531. _MP4.box(_MP4.types.btrt, new Uint8Array([
  13532. 0,
  13533. 28,
  13534. 156,
  13535. 128,
  13536. // bufferSizeDB
  13537. 0,
  13538. 45,
  13539. 198,
  13540. 192,
  13541. // maxBitrate
  13542. 0,
  13543. 45,
  13544. 198,
  13545. 192
  13546. ])),
  13547. // avgBitrate
  13548. _MP4.box(_MP4.types.pasp, new Uint8Array([
  13549. hSpacing >> 24,
  13550. // hSpacing
  13551. hSpacing >> 16 & 255,
  13552. hSpacing >> 8 & 255,
  13553. hSpacing & 255,
  13554. vSpacing >> 24,
  13555. // vSpacing
  13556. vSpacing >> 16 & 255,
  13557. vSpacing >> 8 & 255,
  13558. vSpacing & 255
  13559. ]))
  13560. );
  13561. }
  13562. };
  13563. MP4.types = void 0;
  13564. MP4.HDLR_TYPES = void 0;
  13565. MP4.STTS = void 0;
  13566. MP4.STSC = void 0;
  13567. MP4.STCO = void 0;
  13568. MP4.STSZ = void 0;
  13569. MP4.VMHD = void 0;
  13570. MP4.SMHD = void 0;
  13571. MP4.STSD = void 0;
  13572. MP4.FTYP = void 0;
  13573. MP4.DINF = void 0;
  13574. var MPEG_TS_CLOCK_FREQ_HZ = 9e4;
  13575. function toTimescaleFromBase(baseTime, destScale, srcBase = 1, round = false) {
  13576. const result = baseTime * destScale * srcBase;
  13577. return round ? Math.round(result) : result;
  13578. }
  13579. function toTimescaleFromScale(baseTime, destScale, srcScale = 1, round = false) {
  13580. return toTimescaleFromBase(baseTime, destScale, 1 / srcScale, round);
  13581. }
  13582. function toMsFromMpegTsClock(baseTime, round = false) {
  13583. return toTimescaleFromBase(baseTime, 1e3, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
  13584. }
  13585. function toMpegTsClockFromTimescale(baseTime, srcScale = 1) {
  13586. return toTimescaleFromBase(baseTime, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
  13587. }
  13588. function timestampToString(timestamp) {
  13589. const {
  13590. baseTime,
  13591. timescale,
  13592. trackId
  13593. } = timestamp;
  13594. return `${baseTime / timescale} (${baseTime}/${timescale}) trackId: ${trackId}`;
  13595. }
  13596. var MAX_SILENT_FRAME_DURATION = 10 * 1e3;
  13597. var AAC_SAMPLES_PER_FRAME = 1024;
  13598. var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
  13599. var AC3_SAMPLES_PER_FRAME = 1536;
  13600. var chromeVersion = null;
  13601. var safariWebkitVersion = null;
  13602. function createMp4Sample(isKeyframe, duration, size, cts) {
  13603. return {
  13604. duration,
  13605. size,
  13606. cts,
  13607. flags: {
  13608. isLeading: 0,
  13609. isDependedOn: 0,
  13610. hasRedundancy: 0,
  13611. degradPrio: 0,
  13612. dependsOn: isKeyframe ? 2 : 1,
  13613. isNonSync: isKeyframe ? 0 : 1
  13614. }
  13615. };
  13616. }
  13617. var MP4Remuxer = class extends Logger {
  13618. constructor(observer, config, typeSupported, logger2) {
  13619. super("mp4-remuxer", logger2);
  13620. this.observer = void 0;
  13621. this.config = void 0;
  13622. this.typeSupported = void 0;
  13623. this.ISGenerated = false;
  13624. this._initPTS = null;
  13625. this._initDTS = null;
  13626. this.nextVideoTs = null;
  13627. this.nextAudioTs = null;
  13628. this.videoSampleDuration = null;
  13629. this.isAudioContiguous = false;
  13630. this.isVideoContiguous = false;
  13631. this.videoTrackConfig = void 0;
  13632. this.observer = observer;
  13633. this.config = config;
  13634. this.typeSupported = typeSupported;
  13635. this.ISGenerated = false;
  13636. if (chromeVersion === null) {
  13637. const userAgent = navigator.userAgent || "";
  13638. const result = userAgent.match(/Chrome\/(\d+)/i);
  13639. chromeVersion = result ? parseInt(result[1]) : 0;
  13640. }
  13641. if (safariWebkitVersion === null) {
  13642. const result = navigator.userAgent.match(/Safari\/(\d+)/i);
  13643. safariWebkitVersion = result ? parseInt(result[1]) : 0;
  13644. }
  13645. }
  13646. destroy() {
  13647. this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;
  13648. }
  13649. resetTimeStamp(defaultTimeStamp) {
  13650. const initPTS = this._initPTS;
  13651. if (!initPTS || !defaultTimeStamp || defaultTimeStamp.trackId !== initPTS.trackId || defaultTimeStamp.baseTime !== initPTS.baseTime || defaultTimeStamp.timescale !== initPTS.timescale) {
  13652. this.log(`Reset initPTS: ${initPTS ? timestampToString(initPTS) : initPTS} > ${defaultTimeStamp ? timestampToString(defaultTimeStamp) : defaultTimeStamp}`);
  13653. }
  13654. this._initPTS = this._initDTS = defaultTimeStamp;
  13655. }
  13656. resetNextTimestamp() {
  13657. this.log("reset next timestamp");
  13658. this.isVideoContiguous = false;
  13659. this.isAudioContiguous = false;
  13660. }
  13661. resetInitSegment() {
  13662. this.log("ISGenerated flag reset");
  13663. this.ISGenerated = false;
  13664. this.videoTrackConfig = void 0;
  13665. }
  13666. getVideoStartPts(videoSamples) {
  13667. let rolloverDetected = false;
  13668. const firstPts = videoSamples[0].pts;
  13669. const startPTS = videoSamples.reduce((minPTS, sample) => {
  13670. let pts = sample.pts;
  13671. let delta = pts - minPTS;
  13672. if (delta < -4294967296) {
  13673. rolloverDetected = true;
  13674. pts = normalizePts(pts, firstPts);
  13675. delta = pts - minPTS;
  13676. }
  13677. if (delta > 0) {
  13678. return minPTS;
  13679. }
  13680. return pts;
  13681. }, firstPts);
  13682. if (rolloverDetected) {
  13683. this.debug("PTS rollover detected");
  13684. }
  13685. return startPTS;
  13686. }
  13687. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
  13688. let video;
  13689. let audio;
  13690. let initSegment;
  13691. let text;
  13692. let id3;
  13693. let independent;
  13694. let audioTimeOffset = timeOffset;
  13695. let videoTimeOffset = timeOffset;
  13696. const hasAudio = audioTrack.pid > -1;
  13697. const hasVideo = videoTrack.pid > -1;
  13698. const length = videoTrack.samples.length;
  13699. const enoughAudioSamples = audioTrack.samples.length > 0;
  13700. const enoughVideoSamples = flush && length > 0 || length > 1;
  13701. const canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
  13702. if (canRemuxAvc) {
  13703. if (this.ISGenerated) {
  13704. var _videoTrack$pixelRati, _config$pixelRatio, _videoTrack$pixelRati2, _config$pixelRatio2;
  13705. const config = this.videoTrackConfig;
  13706. 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) {
  13707. this.resetInitSegment();
  13708. }
  13709. }
  13710. if (!this.ISGenerated) {
  13711. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  13712. }
  13713. const isVideoContiguous = this.isVideoContiguous;
  13714. let firstKeyFrameIndex = -1;
  13715. let firstKeyFramePTS;
  13716. if (enoughVideoSamples) {
  13717. firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
  13718. if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
  13719. independent = true;
  13720. if (firstKeyFrameIndex > 0) {
  13721. this.warn(`Dropped ${firstKeyFrameIndex} out of ${length} video samples due to a missing keyframe`);
  13722. const startPTS = this.getVideoStartPts(videoTrack.samples);
  13723. videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
  13724. videoTrack.dropped += firstKeyFrameIndex;
  13725. videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale;
  13726. firstKeyFramePTS = videoTimeOffset;
  13727. } else if (firstKeyFrameIndex === -1) {
  13728. this.warn(`No keyframe found out of ${length} video samples`);
  13729. independent = false;
  13730. }
  13731. }
  13732. }
  13733. if (this.ISGenerated) {
  13734. if (enoughAudioSamples && enoughVideoSamples) {
  13735. const startPTS = this.getVideoStartPts(videoTrack.samples);
  13736. const tsDelta = normalizePts(audioTrack.samples[0].pts, startPTS) - startPTS;
  13737. const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
  13738. audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
  13739. videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
  13740. }
  13741. if (enoughAudioSamples) {
  13742. if (!audioTrack.samplerate) {
  13743. this.warn("regenerate InitSegment as audio detected");
  13744. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  13745. }
  13746. audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : void 0);
  13747. if (enoughVideoSamples) {
  13748. const audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;
  13749. if (!videoTrack.inputTimeScale) {
  13750. this.warn("regenerate InitSegment as video detected");
  13751. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  13752. }
  13753. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
  13754. }
  13755. } else if (enoughVideoSamples) {
  13756. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
  13757. }
  13758. if (video) {
  13759. video.firstKeyFrame = firstKeyFrameIndex;
  13760. video.independent = firstKeyFrameIndex !== -1;
  13761. video.firstKeyFramePTS = firstKeyFramePTS;
  13762. }
  13763. }
  13764. }
  13765. if (this.ISGenerated && this._initPTS && this._initDTS) {
  13766. if (id3Track.samples.length) {
  13767. id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS);
  13768. }
  13769. if (textTrack.samples.length) {
  13770. text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS);
  13771. }
  13772. }
  13773. return {
  13774. audio,
  13775. video,
  13776. initSegment,
  13777. independent,
  13778. text,
  13779. id3
  13780. };
  13781. }
  13782. computeInitPts(basetime, timescale, presentationTime, type) {
  13783. const offset = Math.round(presentationTime * timescale);
  13784. let timestamp = normalizePts(basetime, offset);
  13785. if (timestamp < offset + timescale) {
  13786. this.log(`Adjusting PTS for rollover in timeline near ${(offset - timestamp) / timescale} ${type}`);
  13787. while (timestamp < offset + timescale) {
  13788. timestamp += 8589934592;
  13789. }
  13790. }
  13791. return timestamp - offset;
  13792. }
  13793. generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset) {
  13794. const audioSamples = audioTrack.samples;
  13795. const videoSamples = videoTrack.samples;
  13796. const typeSupported = this.typeSupported;
  13797. const tracks = {};
  13798. const _initPTS = this._initPTS;
  13799. let computePTSDTS = !_initPTS || accurateTimeOffset;
  13800. let container = "audio/mp4";
  13801. let initPTS;
  13802. let initDTS;
  13803. let timescale;
  13804. let trackId = -1;
  13805. if (computePTSDTS) {
  13806. initPTS = initDTS = Infinity;
  13807. }
  13808. if (audioTrack.config && audioSamples.length) {
  13809. audioTrack.timescale = audioTrack.samplerate;
  13810. switch (audioTrack.segmentCodec) {
  13811. case "mp3":
  13812. if (typeSupported.mpeg) {
  13813. container = "audio/mpeg";
  13814. audioTrack.codec = "";
  13815. } else if (typeSupported.mp3) {
  13816. audioTrack.codec = "mp3";
  13817. }
  13818. break;
  13819. case "ac3":
  13820. audioTrack.codec = "ac-3";
  13821. break;
  13822. }
  13823. tracks.audio = {
  13824. id: "audio",
  13825. container,
  13826. codec: audioTrack.codec,
  13827. initSegment: audioTrack.segmentCodec === "mp3" && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]),
  13828. metadata: {
  13829. channelCount: audioTrack.channelCount
  13830. }
  13831. };
  13832. if (computePTSDTS) {
  13833. trackId = audioTrack.id;
  13834. timescale = audioTrack.inputTimeScale;
  13835. if (!_initPTS || timescale !== _initPTS.timescale) {
  13836. initPTS = initDTS = this.computeInitPts(audioSamples[0].pts, timescale, timeOffset, "audio");
  13837. } else {
  13838. computePTSDTS = false;
  13839. }
  13840. }
  13841. }
  13842. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  13843. videoTrack.timescale = videoTrack.inputTimeScale;
  13844. tracks.video = {
  13845. id: "main",
  13846. container: "video/mp4",
  13847. codec: videoTrack.codec,
  13848. initSegment: MP4.initSegment([videoTrack]),
  13849. metadata: {
  13850. width: videoTrack.width,
  13851. height: videoTrack.height
  13852. }
  13853. };
  13854. if (computePTSDTS) {
  13855. trackId = videoTrack.id;
  13856. timescale = videoTrack.inputTimeScale;
  13857. if (!_initPTS || timescale !== _initPTS.timescale) {
  13858. const basePTS = this.getVideoStartPts(videoSamples);
  13859. const baseDTS = normalizePts(videoSamples[0].dts, basePTS);
  13860. const videoInitDTS = this.computeInitPts(baseDTS, timescale, timeOffset, "video");
  13861. const videoInitPTS = this.computeInitPts(basePTS, timescale, timeOffset, "video");
  13862. initDTS = Math.min(initDTS, videoInitDTS);
  13863. initPTS = Math.min(initPTS, videoInitPTS);
  13864. } else {
  13865. computePTSDTS = false;
  13866. }
  13867. }
  13868. this.videoTrackConfig = {
  13869. width: videoTrack.width,
  13870. height: videoTrack.height,
  13871. pixelRatio: videoTrack.pixelRatio
  13872. };
  13873. }
  13874. if (Object.keys(tracks).length) {
  13875. this.ISGenerated = true;
  13876. if (computePTSDTS) {
  13877. if (_initPTS) {
  13878. this.warn(`Timestamps at playlist time: ${accurateTimeOffset ? "" : "~"}${timeOffset} ${initPTS / timescale} != initPTS: ${_initPTS.baseTime / _initPTS.timescale} (${_initPTS.baseTime}/${_initPTS.timescale}) trackId: ${_initPTS.trackId}`);
  13879. }
  13880. this.log(`Found initPTS at playlist time: ${timeOffset} offset: ${initPTS / timescale} (${initPTS}/${timescale}) trackId: ${trackId}`);
  13881. this._initPTS = {
  13882. baseTime: initPTS,
  13883. timescale,
  13884. trackId
  13885. };
  13886. this._initDTS = {
  13887. baseTime: initDTS,
  13888. timescale,
  13889. trackId
  13890. };
  13891. } else {
  13892. initPTS = timescale = void 0;
  13893. }
  13894. return {
  13895. tracks,
  13896. initPTS,
  13897. timescale,
  13898. trackId
  13899. };
  13900. }
  13901. }
  13902. remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
  13903. const timeScale = track.inputTimeScale;
  13904. const inputSamples = track.samples;
  13905. const outputSamples = [];
  13906. const nbSamples = inputSamples.length;
  13907. const initPTS = this._initPTS;
  13908. const initTime = initPTS.baseTime * timeScale / initPTS.timescale;
  13909. let nextVideoTs = this.nextVideoTs;
  13910. let offset = 8;
  13911. let mp4SampleDuration = this.videoSampleDuration;
  13912. let firstDTS;
  13913. let lastDTS;
  13914. let minPTS = Number.POSITIVE_INFINITY;
  13915. let maxPTS = Number.NEGATIVE_INFINITY;
  13916. let sortSamples = false;
  13917. if (!contiguous || nextVideoTs === null) {
  13918. const pts = initTime + timeOffset * timeScale;
  13919. const cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts);
  13920. if (chromeVersion && nextVideoTs !== null && Math.abs(pts - cts - (nextVideoTs + initTime)) < 15e3) {
  13921. contiguous = true;
  13922. } else {
  13923. nextVideoTs = pts - cts - initTime;
  13924. }
  13925. }
  13926. const nextVideoPts = nextVideoTs + initTime;
  13927. for (let i = 0; i < nbSamples; i++) {
  13928. const sample = inputSamples[i];
  13929. sample.pts = normalizePts(sample.pts, nextVideoPts);
  13930. sample.dts = normalizePts(sample.dts, nextVideoPts);
  13931. if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
  13932. sortSamples = true;
  13933. }
  13934. }
  13935. if (sortSamples) {
  13936. inputSamples.sort(function(a, b) {
  13937. const deltadts = a.dts - b.dts;
  13938. const deltapts = a.pts - b.pts;
  13939. return deltadts || deltapts;
  13940. });
  13941. }
  13942. firstDTS = inputSamples[0].dts;
  13943. lastDTS = inputSamples[inputSamples.length - 1].dts;
  13944. const inputDuration = lastDTS - firstDTS;
  13945. const averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track.inputTimeScale / 30;
  13946. if (contiguous) {
  13947. const delta = firstDTS - nextVideoPts;
  13948. const foundHole = delta > averageSampleDuration;
  13949. const foundOverlap = delta < -1;
  13950. if (foundHole || foundOverlap) {
  13951. if (foundHole) {
  13952. this.warn(`${(track.segmentCodec || "").toUpperCase()}: ${toMsFromMpegTsClock(delta, true)} ms (${delta}dts) hole between fragments detected at ${timeOffset.toFixed(3)}`);
  13953. } else {
  13954. this.warn(`${(track.segmentCodec || "").toUpperCase()}: ${toMsFromMpegTsClock(-delta, true)} ms (${delta}dts) overlapping between fragments detected at ${timeOffset.toFixed(3)}`);
  13955. }
  13956. if (!foundOverlap || nextVideoPts >= inputSamples[0].pts || chromeVersion) {
  13957. firstDTS = nextVideoPts;
  13958. const firstPTS = inputSamples[0].pts - delta;
  13959. if (foundHole) {
  13960. inputSamples[0].dts = firstDTS;
  13961. inputSamples[0].pts = firstPTS;
  13962. } else {
  13963. let isPTSOrderRetained = true;
  13964. for (let i = 0; i < inputSamples.length; i++) {
  13965. if (inputSamples[i].dts > firstPTS && isPTSOrderRetained) {
  13966. break;
  13967. }
  13968. const prevPTS = inputSamples[i].pts;
  13969. inputSamples[i].dts -= delta;
  13970. inputSamples[i].pts -= delta;
  13971. if (i < inputSamples.length - 1) {
  13972. const nextSamplePTS = inputSamples[i + 1].pts;
  13973. const currentSamplePTS = inputSamples[i].pts;
  13974. const currentOrder = nextSamplePTS <= currentSamplePTS;
  13975. const prevOrder = nextSamplePTS <= prevPTS;
  13976. isPTSOrderRetained = currentOrder == prevOrder;
  13977. }
  13978. }
  13979. }
  13980. this.log(`Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(firstPTS, true)}/${toMsFromMpegTsClock(firstDTS, true)}, delta: ${toMsFromMpegTsClock(delta, true)} ms`);
  13981. }
  13982. }
  13983. }
  13984. firstDTS = Math.max(0, firstDTS);
  13985. let nbNalu = 0;
  13986. let naluLen = 0;
  13987. let dtsStep = firstDTS;
  13988. for (let i = 0; i < nbSamples; i++) {
  13989. const sample = inputSamples[i];
  13990. const units = sample.units;
  13991. const nbUnits = units.length;
  13992. let sampleLen = 0;
  13993. for (let j = 0; j < nbUnits; j++) {
  13994. sampleLen += units[j].data.length;
  13995. }
  13996. naluLen += sampleLen;
  13997. nbNalu += nbUnits;
  13998. sample.length = sampleLen;
  13999. if (sample.dts < dtsStep) {
  14000. sample.dts = dtsStep;
  14001. dtsStep += averageSampleDuration / 4 | 0 || 1;
  14002. } else {
  14003. dtsStep = sample.dts;
  14004. }
  14005. minPTS = Math.min(sample.pts, minPTS);
  14006. maxPTS = Math.max(sample.pts, maxPTS);
  14007. }
  14008. lastDTS = inputSamples[nbSamples - 1].dts;
  14009. const mdatSize = naluLen + 4 * nbNalu + 8;
  14010. let mdat;
  14011. try {
  14012. mdat = new Uint8Array(mdatSize);
  14013. } catch (err) {
  14014. this.observer.emit(Events.ERROR, Events.ERROR, {
  14015. type: ErrorTypes.MUX_ERROR,
  14016. details: ErrorDetails.REMUX_ALLOC_ERROR,
  14017. fatal: false,
  14018. error: err,
  14019. bytes: mdatSize,
  14020. reason: `fail allocating video mdat ${mdatSize}`
  14021. });
  14022. return;
  14023. }
  14024. const view2 = new DataView(mdat.buffer);
  14025. view2.setUint32(0, mdatSize);
  14026. mdat.set(MP4.types.mdat, 4);
  14027. let stretchedLastFrame = false;
  14028. let minDtsDelta = Number.POSITIVE_INFINITY;
  14029. let minPtsDelta = Number.POSITIVE_INFINITY;
  14030. let maxDtsDelta = Number.NEGATIVE_INFINITY;
  14031. let maxPtsDelta = Number.NEGATIVE_INFINITY;
  14032. for (let i = 0; i < nbSamples; i++) {
  14033. const VideoSample = inputSamples[i];
  14034. const VideoSampleUnits = VideoSample.units;
  14035. let mp4SampleLength = 0;
  14036. for (let j = 0, nbUnits = VideoSampleUnits.length; j < nbUnits; j++) {
  14037. const unit = VideoSampleUnits[j];
  14038. const unitData = unit.data;
  14039. const unitDataLen = unit.data.byteLength;
  14040. view2.setUint32(offset, unitDataLen);
  14041. offset += 4;
  14042. mdat.set(unitData, offset);
  14043. offset += unitDataLen;
  14044. mp4SampleLength += 4 + unitDataLen;
  14045. }
  14046. let ptsDelta;
  14047. if (i < nbSamples - 1) {
  14048. mp4SampleDuration = inputSamples[i + 1].dts - VideoSample.dts;
  14049. ptsDelta = inputSamples[i + 1].pts - VideoSample.pts;
  14050. } else {
  14051. const config = this.config;
  14052. const lastFrameDuration = i > 0 ? VideoSample.dts - inputSamples[i - 1].dts : averageSampleDuration;
  14053. ptsDelta = i > 0 ? VideoSample.pts - inputSamples[i - 1].pts : averageSampleDuration;
  14054. if (config.stretchShortVideoTrack && this.nextAudioTs !== null) {
  14055. const gapTolerance = Math.floor(config.maxBufferHole * timeScale);
  14056. const deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioTs + initTime) - VideoSample.pts;
  14057. if (deltaToFrameEnd > gapTolerance) {
  14058. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  14059. if (mp4SampleDuration < 0) {
  14060. mp4SampleDuration = lastFrameDuration;
  14061. } else {
  14062. stretchedLastFrame = true;
  14063. }
  14064. this.log(`It is approximately ${deltaToFrameEnd / 90} ms to the next segment; using duration ${mp4SampleDuration / 90} ms for the last video frame.`);
  14065. } else {
  14066. mp4SampleDuration = lastFrameDuration;
  14067. }
  14068. } else {
  14069. mp4SampleDuration = lastFrameDuration;
  14070. }
  14071. }
  14072. const compositionTimeOffset = Math.round(VideoSample.pts - VideoSample.dts);
  14073. minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);
  14074. maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);
  14075. minPtsDelta = Math.min(minPtsDelta, ptsDelta);
  14076. maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);
  14077. outputSamples.push(createMp4Sample(VideoSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
  14078. }
  14079. if (outputSamples.length) {
  14080. if (chromeVersion) {
  14081. if (chromeVersion < 70) {
  14082. const flags = outputSamples[0].flags;
  14083. flags.dependsOn = 2;
  14084. flags.isNonSync = 0;
  14085. }
  14086. } else if (safariWebkitVersion) {
  14087. if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) {
  14088. this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");
  14089. let dts = firstDTS;
  14090. for (let i = 0, len = outputSamples.length; i < len; i++) {
  14091. const nextDts = dts + outputSamples[i].duration;
  14092. const pts = dts + outputSamples[i].cts;
  14093. if (i < len - 1) {
  14094. const nextPts = nextDts + outputSamples[i + 1].cts;
  14095. outputSamples[i].duration = nextPts - pts;
  14096. } else {
  14097. outputSamples[i].duration = i ? outputSamples[i - 1].duration : averageSampleDuration;
  14098. }
  14099. outputSamples[i].cts = 0;
  14100. dts = nextDts;
  14101. }
  14102. }
  14103. }
  14104. }
  14105. mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration;
  14106. const endDTS = lastDTS + mp4SampleDuration;
  14107. this.nextVideoTs = nextVideoTs = endDTS - initTime;
  14108. this.videoSampleDuration = mp4SampleDuration;
  14109. this.isVideoContiguous = true;
  14110. const moof = MP4.moof(track.sequenceNumber++, firstDTS, _extends(track, {
  14111. samples: outputSamples
  14112. }));
  14113. const type = "video";
  14114. const data = {
  14115. data1: moof,
  14116. data2: mdat,
  14117. startPTS: (minPTS - initTime) / timeScale,
  14118. endPTS: (maxPTS + mp4SampleDuration - initTime) / timeScale,
  14119. startDTS: (firstDTS - initTime) / timeScale,
  14120. endDTS: nextVideoTs / timeScale,
  14121. type,
  14122. hasAudio: false,
  14123. hasVideo: true,
  14124. nb: outputSamples.length,
  14125. dropped: track.dropped
  14126. };
  14127. track.samples = [];
  14128. track.dropped = 0;
  14129. return data;
  14130. }
  14131. getSamplesPerFrame(track) {
  14132. switch (track.segmentCodec) {
  14133. case "mp3":
  14134. return MPEG_AUDIO_SAMPLE_PER_FRAME;
  14135. case "ac3":
  14136. return AC3_SAMPLES_PER_FRAME;
  14137. default:
  14138. return AAC_SAMPLES_PER_FRAME;
  14139. }
  14140. }
  14141. remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
  14142. const inputTimeScale = track.inputTimeScale;
  14143. const mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  14144. const scaleFactor = inputTimeScale / mp4timeScale;
  14145. const mp4SampleDuration = this.getSamplesPerFrame(track);
  14146. const inputSampleDuration = mp4SampleDuration * scaleFactor;
  14147. const initPTS = this._initPTS;
  14148. const rawMPEG = track.segmentCodec === "mp3" && this.typeSupported.mpeg;
  14149. const outputSamples = [];
  14150. const alignedWithVideo = videoTimeOffset !== void 0;
  14151. let inputSamples = track.samples;
  14152. let offset = rawMPEG ? 0 : 8;
  14153. let nextAudioTs = this.nextAudioTs || -1;
  14154. const initTime = initPTS.baseTime * inputTimeScale / initPTS.timescale;
  14155. const timeOffsetMpegTS = initTime + timeOffset * inputTimeScale;
  14156. 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);
  14157. inputSamples.forEach(function(sample) {
  14158. sample.pts = normalizePts(sample.pts, timeOffsetMpegTS);
  14159. });
  14160. if (!contiguous || nextAudioTs < 0) {
  14161. const sampleCount = inputSamples.length;
  14162. inputSamples = inputSamples.filter((sample) => sample.pts >= 0);
  14163. if (sampleCount !== inputSamples.length) {
  14164. this.warn(`Removed ${inputSamples.length - sampleCount} of ${sampleCount} samples (initPTS ${initTime} / ${inputTimeScale})`);
  14165. }
  14166. if (!inputSamples.length) {
  14167. return;
  14168. }
  14169. if (videoTimeOffset === 0) {
  14170. nextAudioTs = 0;
  14171. } else if (accurateTimeOffset && !alignedWithVideo) {
  14172. nextAudioTs = Math.max(0, timeOffsetMpegTS - initTime);
  14173. } else {
  14174. nextAudioTs = inputSamples[0].pts - initTime;
  14175. }
  14176. }
  14177. if (track.segmentCodec === "aac") {
  14178. const maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  14179. for (let i = 0, nextPts = nextAudioTs + initTime; i < inputSamples.length; i++) {
  14180. const sample = inputSamples[i];
  14181. const pts = sample.pts;
  14182. const delta = pts - nextPts;
  14183. const duration = Math.abs(1e3 * delta / inputTimeScale);
  14184. if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
  14185. if (i === 0) {
  14186. this.warn(`Audio frame @ ${(pts / inputTimeScale).toFixed(3)}s overlaps marker by ${Math.round(1e3 * delta / inputTimeScale)} ms.`);
  14187. this.nextAudioTs = nextAudioTs = pts - initTime;
  14188. nextPts = pts;
  14189. }
  14190. } else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
  14191. let missing = Math.round(delta / inputSampleDuration);
  14192. nextPts = pts - missing * inputSampleDuration;
  14193. while (nextPts < 0 && missing && inputSampleDuration) {
  14194. missing--;
  14195. nextPts += inputSampleDuration;
  14196. }
  14197. if (i === 0) {
  14198. this.nextAudioTs = nextAudioTs = nextPts - initTime;
  14199. }
  14200. this.warn(`Injecting ${missing} audio frames @ ${((nextPts - initTime) / inputTimeScale).toFixed(3)}s due to ${Math.round(1e3 * delta / inputTimeScale)} ms gap.`);
  14201. for (let j = 0; j < missing; j++) {
  14202. let fillFrame = AAC.getSilentFrame(track.parsedCodec || track.manifestCodec || track.codec, track.channelCount);
  14203. if (!fillFrame) {
  14204. this.log("Unable to get silent frame for given audio codec; duplicating last frame instead.");
  14205. fillFrame = sample.unit.subarray();
  14206. }
  14207. inputSamples.splice(i, 0, {
  14208. unit: fillFrame,
  14209. pts: nextPts
  14210. });
  14211. nextPts += inputSampleDuration;
  14212. i++;
  14213. }
  14214. }
  14215. sample.pts = nextPts;
  14216. nextPts += inputSampleDuration;
  14217. }
  14218. }
  14219. let firstPTS = null;
  14220. let lastPTS = null;
  14221. let mdat;
  14222. let mdatSize = 0;
  14223. let sampleLength = inputSamples.length;
  14224. while (sampleLength--) {
  14225. mdatSize += inputSamples[sampleLength].unit.byteLength;
  14226. }
  14227. for (let j = 0, _nbSamples = inputSamples.length; j < _nbSamples; j++) {
  14228. const audioSample = inputSamples[j];
  14229. const unit = audioSample.unit;
  14230. let pts = audioSample.pts;
  14231. if (lastPTS !== null) {
  14232. const prevSample = outputSamples[j - 1];
  14233. prevSample.duration = Math.round((pts - lastPTS) / scaleFactor);
  14234. } else {
  14235. if (contiguous && track.segmentCodec === "aac") {
  14236. pts = nextAudioTs + initTime;
  14237. }
  14238. firstPTS = pts;
  14239. if (mdatSize > 0) {
  14240. mdatSize += offset;
  14241. try {
  14242. mdat = new Uint8Array(mdatSize);
  14243. } catch (err) {
  14244. this.observer.emit(Events.ERROR, Events.ERROR, {
  14245. type: ErrorTypes.MUX_ERROR,
  14246. details: ErrorDetails.REMUX_ALLOC_ERROR,
  14247. fatal: false,
  14248. error: err,
  14249. bytes: mdatSize,
  14250. reason: `fail allocating audio mdat ${mdatSize}`
  14251. });
  14252. return;
  14253. }
  14254. if (!rawMPEG) {
  14255. const view2 = new DataView(mdat.buffer);
  14256. view2.setUint32(0, mdatSize);
  14257. mdat.set(MP4.types.mdat, 4);
  14258. }
  14259. } else {
  14260. return;
  14261. }
  14262. }
  14263. mdat.set(unit, offset);
  14264. const unitLen = unit.byteLength;
  14265. offset += unitLen;
  14266. outputSamples.push(createMp4Sample(true, mp4SampleDuration, unitLen, 0));
  14267. lastPTS = pts;
  14268. }
  14269. const nbSamples = outputSamples.length;
  14270. if (!nbSamples) {
  14271. return;
  14272. }
  14273. const lastSample = outputSamples[outputSamples.length - 1];
  14274. nextAudioTs = lastPTS - initTime;
  14275. this.nextAudioTs = nextAudioTs + scaleFactor * lastSample.duration;
  14276. const moof = rawMPEG ? new Uint8Array(0) : MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
  14277. samples: outputSamples
  14278. }));
  14279. track.samples = [];
  14280. const start = (firstPTS - initTime) / inputTimeScale;
  14281. const end = nextAudioTs / inputTimeScale;
  14282. const type = "audio";
  14283. const audioData = {
  14284. data1: moof,
  14285. data2: mdat,
  14286. startPTS: start,
  14287. endPTS: end,
  14288. startDTS: start,
  14289. endDTS: end,
  14290. type,
  14291. hasAudio: true,
  14292. hasVideo: false,
  14293. nb: nbSamples
  14294. };
  14295. this.isAudioContiguous = true;
  14296. return audioData;
  14297. }
  14298. };
  14299. function normalizePts(value, reference) {
  14300. let offset;
  14301. if (reference === null) {
  14302. return value;
  14303. }
  14304. if (reference < value) {
  14305. offset = -8589934592;
  14306. } else {
  14307. offset = 8589934592;
  14308. }
  14309. while (Math.abs(value - reference) > 4294967296) {
  14310. value += offset;
  14311. }
  14312. return value;
  14313. }
  14314. function findKeyframeIndex(samples) {
  14315. for (let i = 0; i < samples.length; i++) {
  14316. if (samples[i].key) {
  14317. return i;
  14318. }
  14319. }
  14320. return -1;
  14321. }
  14322. function flushTextTrackMetadataCueSamples(track, timeOffset, initPTS, initDTS) {
  14323. const length = track.samples.length;
  14324. if (!length) {
  14325. return;
  14326. }
  14327. const inputTimeScale = track.inputTimeScale;
  14328. for (let index = 0; index < length; index++) {
  14329. const sample = track.samples[index];
  14330. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  14331. sample.dts = normalizePts(sample.dts - initDTS.baseTime * inputTimeScale / initDTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  14332. }
  14333. const samples = track.samples;
  14334. track.samples = [];
  14335. return {
  14336. samples
  14337. };
  14338. }
  14339. function flushTextTrackUserdataCueSamples(track, timeOffset, initPTS) {
  14340. const length = track.samples.length;
  14341. if (!length) {
  14342. return;
  14343. }
  14344. const inputTimeScale = track.inputTimeScale;
  14345. for (let index = 0; index < length; index++) {
  14346. const sample = track.samples[index];
  14347. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  14348. }
  14349. track.samples.sort((a, b) => a.pts - b.pts);
  14350. const samples = track.samples;
  14351. track.samples = [];
  14352. return {
  14353. samples
  14354. };
  14355. }
  14356. var PassThroughRemuxer = class extends Logger {
  14357. constructor(observer, config, typeSupported, logger2) {
  14358. super("passthrough-remuxer", logger2);
  14359. this.emitInitSegment = false;
  14360. this.audioCodec = void 0;
  14361. this.videoCodec = void 0;
  14362. this.initData = void 0;
  14363. this.initPTS = null;
  14364. this.initTracks = void 0;
  14365. this.lastEndTime = null;
  14366. this.isVideoContiguous = false;
  14367. }
  14368. destroy() {
  14369. }
  14370. resetTimeStamp(defaultInitPTS) {
  14371. this.lastEndTime = null;
  14372. const initPTS = this.initPTS;
  14373. if (initPTS && defaultInitPTS) {
  14374. if (initPTS.baseTime === defaultInitPTS.baseTime && initPTS.timescale === defaultInitPTS.timescale) {
  14375. return;
  14376. }
  14377. }
  14378. this.initPTS = defaultInitPTS;
  14379. }
  14380. resetNextTimestamp() {
  14381. this.isVideoContiguous = false;
  14382. this.lastEndTime = null;
  14383. }
  14384. resetInitSegment(initSegment, audioCodec, videoCodec, decryptdata) {
  14385. this.audioCodec = audioCodec;
  14386. this.videoCodec = videoCodec;
  14387. this.generateInitSegment(initSegment, decryptdata);
  14388. this.emitInitSegment = true;
  14389. }
  14390. generateInitSegment(initSegment, decryptdata) {
  14391. let {
  14392. audioCodec,
  14393. videoCodec
  14394. } = this;
  14395. if (!(initSegment != null && initSegment.byteLength)) {
  14396. this.initTracks = void 0;
  14397. this.initData = void 0;
  14398. return;
  14399. }
  14400. const {
  14401. audio,
  14402. video
  14403. } = this.initData = parseInitSegment(initSegment);
  14404. if (decryptdata) {
  14405. patchEncyptionData(initSegment, decryptdata);
  14406. } else {
  14407. const eitherTrack = audio || video;
  14408. if (eitherTrack != null && eitherTrack.encrypted) {
  14409. this.warn(`Init segment with encrypted track with has no key ("${eitherTrack.codec}")!`);
  14410. }
  14411. }
  14412. if (audio) {
  14413. audioCodec = getParsedTrackCodec(audio, ElementaryStreamTypes.AUDIO, this);
  14414. }
  14415. if (video) {
  14416. videoCodec = getParsedTrackCodec(video, ElementaryStreamTypes.VIDEO, this);
  14417. }
  14418. const tracks = {};
  14419. if (audio && video) {
  14420. tracks.audiovideo = {
  14421. container: "video/mp4",
  14422. codec: audioCodec + "," + videoCodec,
  14423. supplemental: video.supplemental,
  14424. encrypted: video.encrypted,
  14425. initSegment,
  14426. id: "main"
  14427. };
  14428. } else if (audio) {
  14429. tracks.audio = {
  14430. container: "audio/mp4",
  14431. codec: audioCodec,
  14432. encrypted: audio.encrypted,
  14433. initSegment,
  14434. id: "audio"
  14435. };
  14436. } else if (video) {
  14437. tracks.video = {
  14438. container: "video/mp4",
  14439. codec: videoCodec,
  14440. supplemental: video.supplemental,
  14441. encrypted: video.encrypted,
  14442. initSegment,
  14443. id: "main"
  14444. };
  14445. } else {
  14446. this.warn("initSegment does not contain moov or trak boxes.");
  14447. }
  14448. this.initTracks = tracks;
  14449. }
  14450. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset) {
  14451. var _initData, _initData2;
  14452. let {
  14453. initPTS,
  14454. lastEndTime
  14455. } = this;
  14456. const result = {
  14457. audio: void 0,
  14458. video: void 0,
  14459. text: textTrack,
  14460. id3: id3Track,
  14461. initSegment: void 0
  14462. };
  14463. if (!isFiniteNumber(lastEndTime)) {
  14464. lastEndTime = this.lastEndTime = timeOffset || 0;
  14465. }
  14466. const data = videoTrack.samples;
  14467. if (!data.length) {
  14468. return result;
  14469. }
  14470. const initSegment = {
  14471. initPTS: void 0,
  14472. timescale: void 0,
  14473. trackId: void 0
  14474. };
  14475. let initData = this.initData;
  14476. if (!((_initData = initData) != null && _initData.length)) {
  14477. this.generateInitSegment(data);
  14478. initData = this.initData;
  14479. }
  14480. if (!((_initData2 = initData) != null && _initData2.length)) {
  14481. this.warn("Failed to generate initSegment.");
  14482. return result;
  14483. }
  14484. if (this.emitInitSegment) {
  14485. initSegment.tracks = this.initTracks;
  14486. this.emitInitSegment = false;
  14487. }
  14488. const trackSampleData = getSampleData(data, initData, this);
  14489. const audioSampleTimestamps = initData.audio ? trackSampleData[initData.audio.id] : null;
  14490. const videoSampleTimestamps = initData.video ? trackSampleData[initData.video.id] : null;
  14491. const videoStartTime = toStartEndOrDefault(videoSampleTimestamps, Infinity);
  14492. const audioStartTime = toStartEndOrDefault(audioSampleTimestamps, Infinity);
  14493. const videoEndTime = toStartEndOrDefault(videoSampleTimestamps, 0, true);
  14494. const audioEndTime = toStartEndOrDefault(audioSampleTimestamps, 0, true);
  14495. let decodeTime = timeOffset;
  14496. let duration = 0;
  14497. const syncOnAudio = audioSampleTimestamps && (!videoSampleTimestamps || !initPTS && audioStartTime < videoStartTime || initPTS && initPTS.trackId === initData.audio.id);
  14498. const baseOffsetSamples = syncOnAudio ? audioSampleTimestamps : videoSampleTimestamps;
  14499. if (baseOffsetSamples) {
  14500. const timescale = baseOffsetSamples.timescale;
  14501. const baseTime = baseOffsetSamples.start - timeOffset * timescale;
  14502. const trackId = syncOnAudio ? initData.audio.id : initData.video.id;
  14503. decodeTime = baseOffsetSamples.start / timescale;
  14504. duration = syncOnAudio ? audioEndTime - audioStartTime : videoEndTime - videoStartTime;
  14505. if ((accurateTimeOffset || !initPTS) && (isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) || timescale !== initPTS.timescale)) {
  14506. if (initPTS) {
  14507. this.warn(`Timestamps at playlist time: ${accurateTimeOffset ? "" : "~"}${timeOffset} ${baseTime / timescale} != initPTS: ${initPTS.baseTime / initPTS.timescale} (${initPTS.baseTime}/${initPTS.timescale}) trackId: ${initPTS.trackId}`);
  14508. }
  14509. this.log(`Found initPTS at playlist time: ${timeOffset} offset: ${decodeTime - timeOffset} (${baseTime}/${timescale}) trackId: ${trackId}`);
  14510. initPTS = null;
  14511. initSegment.initPTS = baseTime;
  14512. initSegment.timescale = timescale;
  14513. initSegment.trackId = trackId;
  14514. }
  14515. } else {
  14516. this.warn(`No audio or video samples found for initPTS at playlist time: ${timeOffset}`);
  14517. }
  14518. if (!initPTS) {
  14519. if (!initSegment.timescale || initSegment.trackId === void 0 || initSegment.initPTS === void 0) {
  14520. this.warn("Could not set initPTS");
  14521. initSegment.initPTS = decodeTime;
  14522. initSegment.timescale = 1;
  14523. initSegment.trackId = -1;
  14524. }
  14525. this.initPTS = initPTS = {
  14526. baseTime: initSegment.initPTS,
  14527. timescale: initSegment.timescale,
  14528. trackId: initSegment.trackId
  14529. };
  14530. } else {
  14531. initSegment.initPTS = initPTS.baseTime;
  14532. initSegment.timescale = initPTS.timescale;
  14533. initSegment.trackId = initPTS.trackId;
  14534. }
  14535. const startTime = decodeTime - initPTS.baseTime / initPTS.timescale;
  14536. const endTime = startTime + duration;
  14537. if (duration > 0) {
  14538. this.lastEndTime = endTime;
  14539. } else {
  14540. this.warn("Duration parsed from mp4 should be greater than zero");
  14541. this.resetNextTimestamp();
  14542. }
  14543. const hasAudio = !!initData.audio;
  14544. const hasVideo = !!initData.video;
  14545. let type = "";
  14546. if (hasAudio) {
  14547. type += "audio";
  14548. }
  14549. if (hasVideo) {
  14550. type += "video";
  14551. }
  14552. const encrypted = (initData.audio ? initData.audio.encrypted : false) || (initData.video ? initData.video.encrypted : false);
  14553. const track = {
  14554. data1: data,
  14555. startPTS: startTime,
  14556. startDTS: startTime,
  14557. endPTS: endTime,
  14558. endDTS: endTime,
  14559. type,
  14560. hasAudio,
  14561. hasVideo,
  14562. nb: 1,
  14563. dropped: 0,
  14564. encrypted
  14565. };
  14566. result.audio = hasAudio && !hasVideo ? track : void 0;
  14567. result.video = hasVideo ? track : void 0;
  14568. const videoSampleCount = videoSampleTimestamps == null ? void 0 : videoSampleTimestamps.sampleCount;
  14569. if (videoSampleCount) {
  14570. const firstKeyFrame = videoSampleTimestamps.keyFrameIndex;
  14571. const independent = firstKeyFrame !== -1;
  14572. track.nb = videoSampleCount;
  14573. track.dropped = firstKeyFrame === 0 || this.isVideoContiguous ? 0 : independent ? firstKeyFrame : videoSampleCount;
  14574. track.independent = independent;
  14575. track.firstKeyFrame = firstKeyFrame;
  14576. if (independent && videoSampleTimestamps.keyFrameStart) {
  14577. track.firstKeyFramePTS = (videoSampleTimestamps.keyFrameStart - initPTS.baseTime) / initPTS.timescale;
  14578. }
  14579. if (!this.isVideoContiguous) {
  14580. result.independent = independent;
  14581. }
  14582. this.isVideoContiguous || (this.isVideoContiguous = independent);
  14583. if (track.dropped) {
  14584. this.warn(`fmp4 does not start with IDR: firstIDR ${firstKeyFrame}/${videoSampleCount} dropped: ${track.dropped} start: ${track.firstKeyFramePTS || "NA"}`);
  14585. }
  14586. }
  14587. result.initSegment = initSegment;
  14588. result.id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, initPTS, initPTS);
  14589. if (textTrack.samples.length) {
  14590. result.text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, initPTS);
  14591. }
  14592. return result;
  14593. }
  14594. };
  14595. function toStartEndOrDefault(trackTimes, defaultValue, end = false) {
  14596. return (trackTimes == null ? void 0 : trackTimes.start) !== void 0 ? (trackTimes.start + (end ? trackTimes.duration : 0)) / trackTimes.timescale : defaultValue;
  14597. }
  14598. function isInvalidInitPts(initPTS, startDTS, timeOffset, duration) {
  14599. if (initPTS === null) {
  14600. return true;
  14601. }
  14602. const minDuration = Math.max(duration, 1);
  14603. const startTime = startDTS - initPTS.baseTime / initPTS.timescale;
  14604. return Math.abs(startTime - timeOffset) > minDuration;
  14605. }
  14606. function getParsedTrackCodec(track, type, logger2) {
  14607. const parsedCodec = track.codec;
  14608. if (parsedCodec && parsedCodec.length > 4) {
  14609. return parsedCodec;
  14610. }
  14611. if (type === ElementaryStreamTypes.AUDIO) {
  14612. if (parsedCodec === "ec-3" || parsedCodec === "ac-3" || parsedCodec === "alac") {
  14613. return parsedCodec;
  14614. }
  14615. if (parsedCodec === "fLaC" || parsedCodec === "Opus") {
  14616. const preferManagedMediaSource = false;
  14617. return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);
  14618. }
  14619. logger2.warn(`Unhandled audio codec "${parsedCodec}" in mp4 MAP`);
  14620. return parsedCodec || "mp4a";
  14621. }
  14622. logger2.warn(`Unhandled video codec "${parsedCodec}" in mp4 MAP`);
  14623. return parsedCodec || "avc1";
  14624. }
  14625. var now;
  14626. try {
  14627. now = self.performance.now.bind(self.performance);
  14628. } catch (err) {
  14629. now = Date.now;
  14630. }
  14631. var muxConfig = [{
  14632. demux: MP4Demuxer,
  14633. remux: PassThroughRemuxer
  14634. }, {
  14635. demux: TSDemuxer,
  14636. remux: MP4Remuxer
  14637. }, {
  14638. demux: AACDemuxer,
  14639. remux: MP4Remuxer
  14640. }, {
  14641. demux: MP3Demuxer,
  14642. remux: MP4Remuxer
  14643. }];
  14644. {
  14645. muxConfig.splice(2, 0, {
  14646. demux: AC3Demuxer,
  14647. remux: MP4Remuxer
  14648. });
  14649. }
  14650. var Transmuxer = class {
  14651. constructor(observer, typeSupported, config, vendor, id, logger2) {
  14652. this.asyncResult = false;
  14653. this.logger = void 0;
  14654. this.observer = void 0;
  14655. this.typeSupported = void 0;
  14656. this.config = void 0;
  14657. this.id = void 0;
  14658. this.demuxer = void 0;
  14659. this.remuxer = void 0;
  14660. this.decrypter = void 0;
  14661. this.probe = void 0;
  14662. this.decryptionPromise = null;
  14663. this.transmuxConfig = void 0;
  14664. this.currentTransmuxState = void 0;
  14665. this.observer = observer;
  14666. this.typeSupported = typeSupported;
  14667. this.config = config;
  14668. this.id = id;
  14669. this.logger = logger2;
  14670. }
  14671. configure(transmuxConfig) {
  14672. this.transmuxConfig = transmuxConfig;
  14673. if (this.decrypter) {
  14674. this.decrypter.reset();
  14675. }
  14676. }
  14677. push(data, decryptdata, chunkMeta, state) {
  14678. const stats = chunkMeta.transmuxing;
  14679. stats.executeStart = now();
  14680. let uintData = new Uint8Array(data);
  14681. const {
  14682. currentTransmuxState,
  14683. transmuxConfig
  14684. } = this;
  14685. if (state) {
  14686. this.currentTransmuxState = state;
  14687. }
  14688. const {
  14689. contiguous,
  14690. discontinuity,
  14691. trackSwitch,
  14692. accurateTimeOffset,
  14693. timeOffset,
  14694. initSegmentChange
  14695. } = state || currentTransmuxState;
  14696. const {
  14697. audioCodec,
  14698. videoCodec,
  14699. defaultInitPts,
  14700. duration,
  14701. initSegmentData
  14702. } = transmuxConfig;
  14703. const keyData = getEncryptionType(uintData, decryptdata);
  14704. if (keyData && isFullSegmentEncryption(keyData.method)) {
  14705. const decrypter = this.getDecrypter();
  14706. const aesMode = getAesModeFromFullSegmentMethod(keyData.method);
  14707. if (decrypter.isSync()) {
  14708. let decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode);
  14709. const loadingParts = chunkMeta.part > -1;
  14710. if (loadingParts) {
  14711. const _data = decrypter.flush();
  14712. decryptedData = _data ? _data.buffer : _data;
  14713. }
  14714. if (!decryptedData) {
  14715. stats.executeEnd = now();
  14716. return emptyResult(chunkMeta);
  14717. }
  14718. uintData = new Uint8Array(decryptedData);
  14719. } else {
  14720. this.asyncResult = true;
  14721. this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode).then((decryptedData) => {
  14722. const result2 = this.push(decryptedData, null, chunkMeta);
  14723. this.decryptionPromise = null;
  14724. return result2;
  14725. });
  14726. return this.decryptionPromise;
  14727. }
  14728. }
  14729. const resetMuxers = this.needsProbing(discontinuity, trackSwitch);
  14730. if (resetMuxers) {
  14731. const error = this.configureTransmuxer(uintData);
  14732. if (error) {
  14733. this.logger.warn(`[transmuxer] ${error.message}`);
  14734. this.observer.emit(Events.ERROR, Events.ERROR, {
  14735. type: ErrorTypes.MEDIA_ERROR,
  14736. details: ErrorDetails.FRAG_PARSING_ERROR,
  14737. fatal: false,
  14738. error,
  14739. reason: error.message
  14740. });
  14741. stats.executeEnd = now();
  14742. return emptyResult(chunkMeta);
  14743. }
  14744. }
  14745. if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {
  14746. this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration, decryptdata);
  14747. }
  14748. if (discontinuity || initSegmentChange || resetMuxers) {
  14749. this.resetInitialTimestamp(defaultInitPts);
  14750. }
  14751. if (!contiguous) {
  14752. this.resetContiguity();
  14753. }
  14754. const result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  14755. this.asyncResult = isPromise(result);
  14756. const currentState = this.currentTransmuxState;
  14757. currentState.contiguous = true;
  14758. currentState.discontinuity = false;
  14759. currentState.trackSwitch = false;
  14760. stats.executeEnd = now();
  14761. return result;
  14762. }
  14763. // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
  14764. flush(chunkMeta) {
  14765. const stats = chunkMeta.transmuxing;
  14766. stats.executeStart = now();
  14767. const {
  14768. decrypter,
  14769. currentTransmuxState,
  14770. decryptionPromise
  14771. } = this;
  14772. if (decryptionPromise) {
  14773. this.asyncResult = true;
  14774. return decryptionPromise.then(() => {
  14775. return this.flush(chunkMeta);
  14776. });
  14777. }
  14778. const transmuxResults = [];
  14779. const {
  14780. timeOffset
  14781. } = currentTransmuxState;
  14782. if (decrypter) {
  14783. const decryptedData = decrypter.flush();
  14784. if (decryptedData) {
  14785. transmuxResults.push(this.push(decryptedData.buffer, null, chunkMeta));
  14786. }
  14787. }
  14788. const {
  14789. demuxer,
  14790. remuxer
  14791. } = this;
  14792. if (!demuxer || !remuxer) {
  14793. stats.executeEnd = now();
  14794. const emptyResults = [emptyResult(chunkMeta)];
  14795. if (this.asyncResult) {
  14796. return Promise.resolve(emptyResults);
  14797. }
  14798. return emptyResults;
  14799. }
  14800. const demuxResultOrPromise = demuxer.flush(timeOffset);
  14801. if (isPromise(demuxResultOrPromise)) {
  14802. this.asyncResult = true;
  14803. return demuxResultOrPromise.then((demuxResult) => {
  14804. this.flushRemux(transmuxResults, demuxResult, chunkMeta);
  14805. return transmuxResults;
  14806. });
  14807. }
  14808. this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
  14809. if (this.asyncResult) {
  14810. return Promise.resolve(transmuxResults);
  14811. }
  14812. return transmuxResults;
  14813. }
  14814. flushRemux(transmuxResults, demuxResult, chunkMeta) {
  14815. const {
  14816. audioTrack,
  14817. videoTrack,
  14818. id3Track,
  14819. textTrack
  14820. } = demuxResult;
  14821. const {
  14822. accurateTimeOffset,
  14823. timeOffset
  14824. } = this.currentTransmuxState;
  14825. 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}`);
  14826. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
  14827. transmuxResults.push({
  14828. remuxResult,
  14829. chunkMeta
  14830. });
  14831. chunkMeta.transmuxing.executeEnd = now();
  14832. }
  14833. resetInitialTimestamp(defaultInitPts) {
  14834. const {
  14835. demuxer,
  14836. remuxer
  14837. } = this;
  14838. if (!demuxer || !remuxer) {
  14839. return;
  14840. }
  14841. demuxer.resetTimeStamp(defaultInitPts);
  14842. remuxer.resetTimeStamp(defaultInitPts);
  14843. }
  14844. resetContiguity() {
  14845. const {
  14846. demuxer,
  14847. remuxer
  14848. } = this;
  14849. if (!demuxer || !remuxer) {
  14850. return;
  14851. }
  14852. demuxer.resetContiguity();
  14853. remuxer.resetNextTimestamp();
  14854. }
  14855. resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration, decryptdata) {
  14856. const {
  14857. demuxer,
  14858. remuxer
  14859. } = this;
  14860. if (!demuxer || !remuxer) {
  14861. return;
  14862. }
  14863. demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration);
  14864. remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, decryptdata);
  14865. }
  14866. destroy() {
  14867. if (this.demuxer) {
  14868. this.demuxer.destroy();
  14869. this.demuxer = void 0;
  14870. }
  14871. if (this.remuxer) {
  14872. this.remuxer.destroy();
  14873. this.remuxer = void 0;
  14874. }
  14875. }
  14876. transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
  14877. let result;
  14878. if (keyData && keyData.method === "SAMPLE-AES") {
  14879. result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  14880. } else {
  14881. result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
  14882. }
  14883. return result;
  14884. }
  14885. transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
  14886. const {
  14887. audioTrack,
  14888. videoTrack,
  14889. id3Track,
  14890. textTrack
  14891. } = this.demuxer.demux(data, timeOffset, false, !this.config.progressive);
  14892. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
  14893. return {
  14894. remuxResult,
  14895. chunkMeta
  14896. };
  14897. }
  14898. transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
  14899. return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then((demuxResult) => {
  14900. const remuxResult = this.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, this.id);
  14901. return {
  14902. remuxResult,
  14903. chunkMeta
  14904. };
  14905. });
  14906. }
  14907. configureTransmuxer(data) {
  14908. const {
  14909. config,
  14910. observer,
  14911. typeSupported
  14912. } = this;
  14913. let mux;
  14914. for (let i = 0, len = muxConfig.length; i < len; i++) {
  14915. var _muxConfig$i$demux;
  14916. if ((_muxConfig$i$demux = muxConfig[i].demux) != null && _muxConfig$i$demux.probe(data, this.logger)) {
  14917. mux = muxConfig[i];
  14918. break;
  14919. }
  14920. }
  14921. if (!mux) {
  14922. return new Error("Failed to find demuxer by probing fragment data");
  14923. }
  14924. const demuxer = this.demuxer;
  14925. const remuxer = this.remuxer;
  14926. const Remuxer = mux.remux;
  14927. const Demuxer = mux.demux;
  14928. if (!remuxer || !(remuxer instanceof Remuxer)) {
  14929. this.remuxer = new Remuxer(observer, config, typeSupported, this.logger);
  14930. }
  14931. if (!demuxer || !(demuxer instanceof Demuxer)) {
  14932. this.demuxer = new Demuxer(observer, config, typeSupported, this.logger);
  14933. this.probe = Demuxer.probe;
  14934. }
  14935. }
  14936. needsProbing(discontinuity, trackSwitch) {
  14937. return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
  14938. }
  14939. getDecrypter() {
  14940. let decrypter = this.decrypter;
  14941. if (!decrypter) {
  14942. decrypter = this.decrypter = new Decrypter(this.config);
  14943. }
  14944. return decrypter;
  14945. }
  14946. };
  14947. function getEncryptionType(data, decryptData) {
  14948. let encryptionType = null;
  14949. if (data.byteLength > 0 && (decryptData == null ? void 0 : decryptData.key) != null && decryptData.iv !== null && decryptData.method != null) {
  14950. encryptionType = decryptData;
  14951. }
  14952. return encryptionType;
  14953. }
  14954. var emptyResult = (chunkMeta) => ({
  14955. remuxResult: {},
  14956. chunkMeta
  14957. });
  14958. function isPromise(p) {
  14959. return "then" in p && p.then instanceof Function;
  14960. }
  14961. var TransmuxConfig = class {
  14962. constructor(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
  14963. this.audioCodec = void 0;
  14964. this.videoCodec = void 0;
  14965. this.initSegmentData = void 0;
  14966. this.duration = void 0;
  14967. this.defaultInitPts = void 0;
  14968. this.audioCodec = audioCodec;
  14969. this.videoCodec = videoCodec;
  14970. this.initSegmentData = initSegmentData;
  14971. this.duration = duration;
  14972. this.defaultInitPts = defaultInitPts || null;
  14973. }
  14974. };
  14975. var TransmuxState = class {
  14976. constructor(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) {
  14977. this.discontinuity = void 0;
  14978. this.contiguous = void 0;
  14979. this.accurateTimeOffset = void 0;
  14980. this.trackSwitch = void 0;
  14981. this.timeOffset = void 0;
  14982. this.initSegmentChange = void 0;
  14983. this.discontinuity = discontinuity;
  14984. this.contiguous = contiguous;
  14985. this.accurateTimeOffset = accurateTimeOffset;
  14986. this.trackSwitch = trackSwitch;
  14987. this.timeOffset = timeOffset;
  14988. this.initSegmentChange = initSegmentChange;
  14989. }
  14990. };
  14991. var transmuxerInstanceCount = 0;
  14992. var TransmuxerInterface = class {
  14993. constructor(_hls, id, onTransmuxComplete, onFlush) {
  14994. this.error = null;
  14995. this.hls = void 0;
  14996. this.id = void 0;
  14997. this.instanceNo = transmuxerInstanceCount++;
  14998. this.observer = void 0;
  14999. this.frag = null;
  15000. this.part = null;
  15001. this.useWorker = void 0;
  15002. this.workerContext = null;
  15003. this.transmuxer = null;
  15004. this.onTransmuxComplete = void 0;
  15005. this.onFlush = void 0;
  15006. this.onWorkerMessage = (event) => {
  15007. const data = event.data;
  15008. const hls = this.hls;
  15009. if (!hls || !(data != null && data.event) || data.instanceNo !== this.instanceNo) {
  15010. return;
  15011. }
  15012. switch (data.event) {
  15013. case "init": {
  15014. var _this$workerContext;
  15015. const objectURL = (_this$workerContext = this.workerContext) == null ? void 0 : _this$workerContext.objectURL;
  15016. if (objectURL) {
  15017. self.URL.revokeObjectURL(objectURL);
  15018. }
  15019. break;
  15020. }
  15021. case "transmuxComplete": {
  15022. this.handleTransmuxComplete(data.data);
  15023. break;
  15024. }
  15025. case "flush": {
  15026. this.onFlush(data.data);
  15027. break;
  15028. }
  15029. case "workerLog": {
  15030. if (hls.logger[data.data.logType]) {
  15031. hls.logger[data.data.logType](data.data.message);
  15032. }
  15033. break;
  15034. }
  15035. default: {
  15036. data.data = data.data || {};
  15037. data.data.frag = this.frag;
  15038. data.data.part = this.part;
  15039. data.data.id = this.id;
  15040. hls.trigger(data.event, data.data);
  15041. break;
  15042. }
  15043. }
  15044. };
  15045. this.onWorkerError = (event) => {
  15046. if (!this.hls) {
  15047. return;
  15048. }
  15049. const error = new Error(`${event.message} (${event.filename}:${event.lineno})`);
  15050. this.hls.config.enableWorker = false;
  15051. this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`);
  15052. this.hls.trigger(Events.ERROR, {
  15053. type: ErrorTypes.OTHER_ERROR,
  15054. details: ErrorDetails.INTERNAL_EXCEPTION,
  15055. fatal: false,
  15056. event: "demuxerWorker",
  15057. error
  15058. });
  15059. };
  15060. const config = _hls.config;
  15061. this.hls = _hls;
  15062. this.id = id;
  15063. this.useWorker = !!config.enableWorker;
  15064. this.onTransmuxComplete = onTransmuxComplete;
  15065. this.onFlush = onFlush;
  15066. const forwardMessage = (ev, data) => {
  15067. data = data || {};
  15068. data.frag = this.frag || void 0;
  15069. if (ev === Events.ERROR) {
  15070. data = data;
  15071. data.parent = this.id;
  15072. data.part = this.part;
  15073. this.error = data.error;
  15074. }
  15075. this.hls.trigger(ev, data);
  15076. };
  15077. this.observer = new EventEmitter();
  15078. this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  15079. this.observer.on(Events.ERROR, forwardMessage);
  15080. const m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
  15081. if (this.useWorker && typeof Worker !== "undefined") {
  15082. const logger2 = this.hls.logger;
  15083. const canCreateWorker = config.workerPath || hasUMDWorker();
  15084. if (canCreateWorker) {
  15085. try {
  15086. if (config.workerPath) {
  15087. logger2.log(`loading Web Worker ${config.workerPath} for "${id}"`);
  15088. this.workerContext = loadWorker(config.workerPath);
  15089. } else {
  15090. logger2.log(`injecting Web Worker for "${id}"`);
  15091. this.workerContext = injectWorker();
  15092. }
  15093. const {
  15094. worker
  15095. } = this.workerContext;
  15096. worker.addEventListener("message", this.onWorkerMessage);
  15097. worker.addEventListener("error", this.onWorkerError);
  15098. worker.postMessage({
  15099. instanceNo: this.instanceNo,
  15100. cmd: "init",
  15101. typeSupported: m2tsTypeSupported,
  15102. id,
  15103. config: stringify(config)
  15104. });
  15105. } catch (err) {
  15106. logger2.warn(`Error setting up "${id}" Web Worker, fallback to inline`, err);
  15107. this.terminateWorker();
  15108. this.error = null;
  15109. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, "", id, _hls.logger);
  15110. }
  15111. return;
  15112. }
  15113. }
  15114. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, "", id, _hls.logger);
  15115. }
  15116. reset() {
  15117. this.frag = null;
  15118. this.part = null;
  15119. if (this.workerContext) {
  15120. const instanceNo = this.instanceNo;
  15121. this.instanceNo = transmuxerInstanceCount++;
  15122. const config = this.hls.config;
  15123. const m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
  15124. this.workerContext.worker.postMessage({
  15125. instanceNo: this.instanceNo,
  15126. cmd: "reset",
  15127. resetNo: instanceNo,
  15128. typeSupported: m2tsTypeSupported,
  15129. id: this.id,
  15130. config: stringify(config)
  15131. });
  15132. }
  15133. }
  15134. terminateWorker() {
  15135. if (this.workerContext) {
  15136. const {
  15137. worker
  15138. } = this.workerContext;
  15139. this.workerContext = null;
  15140. worker.removeEventListener("message", this.onWorkerMessage);
  15141. worker.removeEventListener("error", this.onWorkerError);
  15142. removeWorkerFromStore(this.hls.config.workerPath);
  15143. }
  15144. }
  15145. destroy() {
  15146. if (this.workerContext) {
  15147. this.terminateWorker();
  15148. this.onWorkerMessage = this.onWorkerError = null;
  15149. } else {
  15150. const transmuxer = this.transmuxer;
  15151. if (transmuxer) {
  15152. transmuxer.destroy();
  15153. this.transmuxer = null;
  15154. }
  15155. }
  15156. const observer = this.observer;
  15157. if (observer) {
  15158. observer.removeAllListeners();
  15159. }
  15160. this.frag = null;
  15161. this.part = null;
  15162. this.observer = null;
  15163. this.hls = null;
  15164. }
  15165. push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
  15166. var _frag$initSegment, _lastFrag$initSegment;
  15167. chunkMeta.transmuxing.start = self.performance.now();
  15168. const {
  15169. instanceNo,
  15170. transmuxer
  15171. } = this;
  15172. const timeOffset = part ? part.start : frag.start;
  15173. const decryptdata = frag.decryptdata;
  15174. const lastFrag = this.frag;
  15175. const discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  15176. const trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
  15177. const snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
  15178. const partDiff = this.part ? chunkMeta.part - this.part.index : -1;
  15179. const progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag == null ? void 0 : lastFrag.stats.chunkCount);
  15180. const contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0));
  15181. const now2 = self.performance.now();
  15182. if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
  15183. frag.stats.parsing.start = now2;
  15184. }
  15185. if (part && (partDiff || !contiguous)) {
  15186. part.stats.parsing.start = now2;
  15187. }
  15188. const initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) == null ? void 0 : _lastFrag$initSegment.url));
  15189. const state = new TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange);
  15190. if (!contiguous || discontinuity || initSegmentChange) {
  15191. 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}
  15192. discontinuity: ${discontinuity}
  15193. trackSwitch: ${trackSwitch}
  15194. contiguous: ${contiguous}
  15195. accurateTimeOffset: ${accurateTimeOffset}
  15196. timeOffset: ${timeOffset}
  15197. initSegmentChange: ${initSegmentChange}`);
  15198. const config = new TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
  15199. this.configureTransmuxer(config);
  15200. }
  15201. this.frag = frag;
  15202. this.part = part;
  15203. if (this.workerContext) {
  15204. this.workerContext.worker.postMessage({
  15205. instanceNo,
  15206. cmd: "demux",
  15207. data,
  15208. decryptdata,
  15209. chunkMeta,
  15210. state
  15211. }, data instanceof ArrayBuffer ? [data] : []);
  15212. } else if (transmuxer) {
  15213. const transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
  15214. if (isPromise(transmuxResult)) {
  15215. transmuxResult.then((data2) => {
  15216. this.handleTransmuxComplete(data2);
  15217. }).catch((error) => {
  15218. this.transmuxerError(error, chunkMeta, "transmuxer-interface push error");
  15219. });
  15220. } else {
  15221. this.handleTransmuxComplete(transmuxResult);
  15222. }
  15223. }
  15224. }
  15225. flush(chunkMeta) {
  15226. chunkMeta.transmuxing.start = self.performance.now();
  15227. const {
  15228. instanceNo,
  15229. transmuxer
  15230. } = this;
  15231. if (this.workerContext) {
  15232. this.workerContext.worker.postMessage({
  15233. instanceNo,
  15234. cmd: "flush",
  15235. chunkMeta
  15236. });
  15237. } else if (transmuxer) {
  15238. const transmuxResult = transmuxer.flush(chunkMeta);
  15239. if (isPromise(transmuxResult)) {
  15240. transmuxResult.then((data) => {
  15241. this.handleFlushResult(data, chunkMeta);
  15242. }).catch((error) => {
  15243. this.transmuxerError(error, chunkMeta, "transmuxer-interface flush error");
  15244. });
  15245. } else {
  15246. this.handleFlushResult(transmuxResult, chunkMeta);
  15247. }
  15248. }
  15249. }
  15250. transmuxerError(error, chunkMeta, reason) {
  15251. if (!this.hls) {
  15252. return;
  15253. }
  15254. this.error = error;
  15255. this.hls.trigger(Events.ERROR, {
  15256. type: ErrorTypes.MEDIA_ERROR,
  15257. details: ErrorDetails.FRAG_PARSING_ERROR,
  15258. chunkMeta,
  15259. frag: this.frag || void 0,
  15260. part: this.part || void 0,
  15261. fatal: false,
  15262. error,
  15263. err: error,
  15264. reason
  15265. });
  15266. }
  15267. handleFlushResult(results, chunkMeta) {
  15268. results.forEach((result) => {
  15269. this.handleTransmuxComplete(result);
  15270. });
  15271. this.onFlush(chunkMeta);
  15272. }
  15273. configureTransmuxer(config) {
  15274. const {
  15275. instanceNo,
  15276. transmuxer
  15277. } = this;
  15278. if (this.workerContext) {
  15279. this.workerContext.worker.postMessage({
  15280. instanceNo,
  15281. cmd: "configure",
  15282. config
  15283. });
  15284. } else if (transmuxer) {
  15285. transmuxer.configure(config);
  15286. }
  15287. }
  15288. handleTransmuxComplete(result) {
  15289. result.chunkMeta.transmuxing.end = self.performance.now();
  15290. this.onTransmuxComplete(result);
  15291. }
  15292. };
  15293. var TICK_INTERVAL$3 = 100;
  15294. var AudioStreamController = class extends BaseStreamController {
  15295. constructor(hls, fragmentTracker, keyLoader) {
  15296. super(hls, fragmentTracker, keyLoader, "audio-stream-controller", PlaylistLevelType.AUDIO);
  15297. this.mainAnchor = null;
  15298. this.mainFragLoading = null;
  15299. this.audioOnly = false;
  15300. this.bufferedTrack = null;
  15301. this.switchingTrack = null;
  15302. this.trackId = -1;
  15303. this.waitingData = null;
  15304. this.mainDetails = null;
  15305. this.flushing = false;
  15306. this.bufferFlushed = false;
  15307. this.cachedTrackLoadedData = null;
  15308. this.registerListeners();
  15309. }
  15310. onHandlerDestroying() {
  15311. this.unregisterListeners();
  15312. super.onHandlerDestroying();
  15313. this.resetItem();
  15314. }
  15315. resetItem() {
  15316. this.mainDetails = this.mainAnchor = this.mainFragLoading = this.bufferedTrack = this.switchingTrack = this.waitingData = this.cachedTrackLoadedData = null;
  15317. }
  15318. registerListeners() {
  15319. super.registerListeners();
  15320. const {
  15321. hls
  15322. } = this;
  15323. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  15324. hls.on(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  15325. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  15326. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  15327. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  15328. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  15329. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  15330. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  15331. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  15332. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  15333. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  15334. }
  15335. unregisterListeners() {
  15336. const {
  15337. hls
  15338. } = this;
  15339. if (!hls) {
  15340. return;
  15341. }
  15342. super.unregisterListeners();
  15343. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  15344. hls.off(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  15345. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  15346. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  15347. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  15348. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  15349. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  15350. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  15351. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  15352. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  15353. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  15354. }
  15355. // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value
  15356. onInitPtsFound(event, {
  15357. frag,
  15358. id,
  15359. initPTS,
  15360. timescale,
  15361. trackId
  15362. }) {
  15363. if (id === PlaylistLevelType.MAIN) {
  15364. const cc = frag.cc;
  15365. const inFlightFrag = this.fragCurrent;
  15366. this.initPTS[cc] = {
  15367. baseTime: initPTS,
  15368. timescale,
  15369. trackId
  15370. };
  15371. this.log(`InitPTS for cc: ${cc} found from main: ${initPTS / timescale} (${initPTS}/${timescale}) trackId: ${trackId}`);
  15372. this.mainAnchor = frag;
  15373. if (this.state === State.WAITING_INIT_PTS) {
  15374. const waitingData = this.waitingData;
  15375. if (!waitingData && !this.loadingParts || waitingData && waitingData.frag.cc !== cc) {
  15376. this.syncWithAnchor(frag, waitingData == null ? void 0 : waitingData.frag);
  15377. }
  15378. } else if (!this.hls.hasEnoughToStart && inFlightFrag && inFlightFrag.cc !== cc) {
  15379. inFlightFrag.abortRequests();
  15380. this.syncWithAnchor(frag, inFlightFrag);
  15381. } else if (this.state === State.IDLE) {
  15382. this.tick();
  15383. }
  15384. }
  15385. }
  15386. getLoadPosition() {
  15387. if (!this.startFragRequested && this.nextLoadPosition >= 0) {
  15388. return this.nextLoadPosition;
  15389. }
  15390. return super.getLoadPosition();
  15391. }
  15392. syncWithAnchor(mainAnchor, waitingToAppend) {
  15393. var _this$mainFragLoading;
  15394. const mainFragLoading = ((_this$mainFragLoading = this.mainFragLoading) == null ? void 0 : _this$mainFragLoading.frag) || null;
  15395. if (waitingToAppend) {
  15396. if ((mainFragLoading == null ? void 0 : mainFragLoading.cc) === waitingToAppend.cc) {
  15397. return;
  15398. }
  15399. }
  15400. const targetDiscontinuity = (mainFragLoading || mainAnchor).cc;
  15401. const trackDetails = this.getLevelDetails();
  15402. const pos = this.getLoadPosition();
  15403. const syncFrag = findNearestWithCC(trackDetails, targetDiscontinuity, pos);
  15404. if (syncFrag) {
  15405. this.log(`Syncing with main frag at ${syncFrag.start} cc ${syncFrag.cc}`);
  15406. this.startFragRequested = false;
  15407. this.nextLoadPosition = syncFrag.start;
  15408. this.resetLoadingState();
  15409. if (this.state === State.IDLE) {
  15410. this.doTickIdle();
  15411. }
  15412. }
  15413. }
  15414. startLoad(startPosition, skipSeekToStartPosition) {
  15415. if (!this.levels) {
  15416. this.startPosition = startPosition;
  15417. this.state = State.STOPPED;
  15418. return;
  15419. }
  15420. const lastCurrentTime = this.lastCurrentTime;
  15421. this.stopLoad();
  15422. this.setInterval(TICK_INTERVAL$3);
  15423. if (lastCurrentTime > 0 && startPosition === -1) {
  15424. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  15425. startPosition = lastCurrentTime;
  15426. this.state = State.IDLE;
  15427. } else {
  15428. this.state = State.WAITING_TRACK;
  15429. }
  15430. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  15431. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  15432. this.tick();
  15433. }
  15434. doTick() {
  15435. switch (this.state) {
  15436. case State.IDLE:
  15437. this.doTickIdle();
  15438. break;
  15439. case State.WAITING_TRACK: {
  15440. const {
  15441. levels,
  15442. trackId
  15443. } = this;
  15444. const currenTrack = levels == null ? void 0 : levels[trackId];
  15445. const details = currenTrack == null ? void 0 : currenTrack.details;
  15446. if (details && !this.waitForLive(currenTrack)) {
  15447. if (this.waitForCdnTuneIn(details)) {
  15448. break;
  15449. }
  15450. this.state = State.WAITING_INIT_PTS;
  15451. }
  15452. break;
  15453. }
  15454. case State.FRAG_LOADING_WAITING_RETRY: {
  15455. this.checkRetryDate();
  15456. break;
  15457. }
  15458. case State.WAITING_INIT_PTS: {
  15459. const waitingData = this.waitingData;
  15460. if (waitingData) {
  15461. const {
  15462. frag,
  15463. part,
  15464. cache,
  15465. complete
  15466. } = waitingData;
  15467. const mainAnchor = this.mainAnchor;
  15468. if (this.initPTS[frag.cc] !== void 0) {
  15469. this.waitingData = null;
  15470. this.state = State.FRAG_LOADING;
  15471. const payload = cache.flush().buffer;
  15472. const data = {
  15473. frag,
  15474. part,
  15475. payload,
  15476. networkDetails: null
  15477. };
  15478. this._handleFragmentLoadProgress(data);
  15479. if (complete) {
  15480. super._handleFragmentLoadComplete(data);
  15481. }
  15482. } else if (mainAnchor && mainAnchor.cc !== waitingData.frag.cc) {
  15483. this.syncWithAnchor(mainAnchor, waitingData.frag);
  15484. }
  15485. } else {
  15486. this.state = State.IDLE;
  15487. }
  15488. }
  15489. }
  15490. this.onTickEnd();
  15491. }
  15492. resetLoadingState() {
  15493. const waitingData = this.waitingData;
  15494. if (waitingData) {
  15495. this.fragmentTracker.removeFragment(waitingData.frag);
  15496. this.waitingData = null;
  15497. }
  15498. super.resetLoadingState();
  15499. }
  15500. onTickEnd() {
  15501. const {
  15502. media
  15503. } = this;
  15504. if (!(media != null && media.readyState)) {
  15505. return;
  15506. }
  15507. this.lastCurrentTime = media.currentTime;
  15508. }
  15509. doTickIdle() {
  15510. var _this$mainFragLoading2;
  15511. const {
  15512. hls,
  15513. levels,
  15514. media,
  15515. trackId
  15516. } = this;
  15517. const config = hls.config;
  15518. if (!this.buffering || !media && !this.primaryPrefetch && (this.startFragRequested || !config.startFragPrefetch) || !(levels != null && levels[trackId])) {
  15519. return;
  15520. }
  15521. const levelInfo = levels[trackId];
  15522. const trackDetails = levelInfo.details;
  15523. if (!trackDetails || this.waitForLive(levelInfo) || this.waitForCdnTuneIn(trackDetails)) {
  15524. this.state = State.WAITING_TRACK;
  15525. this.startFragRequested = false;
  15526. return;
  15527. }
  15528. const bufferable = this.mediaBuffer ? this.mediaBuffer : this.media;
  15529. if (this.bufferFlushed && bufferable) {
  15530. this.bufferFlushed = false;
  15531. this.afterBufferFlushed(bufferable, ElementaryStreamTypes.AUDIO, PlaylistLevelType.AUDIO);
  15532. }
  15533. const bufferInfo = this.getFwdBufferInfo(bufferable, PlaylistLevelType.AUDIO);
  15534. if (bufferInfo === null) {
  15535. return;
  15536. }
  15537. if (!this.switchingTrack && this._streamEnded(bufferInfo, trackDetails)) {
  15538. hls.trigger(Events.BUFFER_EOS, {
  15539. type: "audio"
  15540. });
  15541. this.state = State.ENDED;
  15542. return;
  15543. }
  15544. const bufferLen = bufferInfo.len;
  15545. const maxBufLen = hls.maxBufferLength;
  15546. const fragments = trackDetails.fragments;
  15547. const start = fragments[0].start;
  15548. const loadPosition = this.getLoadPosition();
  15549. const targetBufferTime = this.flushing ? loadPosition : bufferInfo.end;
  15550. if (this.switchingTrack && media) {
  15551. const pos = loadPosition;
  15552. if (trackDetails.PTSKnown && pos < start) {
  15553. if (bufferInfo.end > start || bufferInfo.nextStart) {
  15554. this.log("Alt audio track ahead of main track, seek to start of alt audio track");
  15555. media.currentTime = start + 0.05;
  15556. }
  15557. }
  15558. }
  15559. if (bufferLen >= maxBufLen && !this.switchingTrack && targetBufferTime < fragments[fragments.length - 1].start) {
  15560. return;
  15561. }
  15562. let frag = this.getNextFragment(targetBufferTime, trackDetails);
  15563. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  15564. frag = this.getNextFragmentLoopLoading(frag, trackDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  15565. }
  15566. if (!frag) {
  15567. this.bufferFlushed = true;
  15568. return;
  15569. }
  15570. let mainFragLoading = ((_this$mainFragLoading2 = this.mainFragLoading) == null ? void 0 : _this$mainFragLoading2.frag) || null;
  15571. if (!this.audioOnly && this.startFragRequested && mainFragLoading && isMediaFragment(frag) && !frag.endList && (!trackDetails.live || !this.loadingParts && targetBufferTime < this.hls.liveSyncPosition)) {
  15572. if (this.fragmentTracker.getState(mainFragLoading) === FragmentState.OK) {
  15573. this.mainFragLoading = mainFragLoading = null;
  15574. }
  15575. if (mainFragLoading && isMediaFragment(mainFragLoading)) {
  15576. if (frag.start > mainFragLoading.end) {
  15577. const mainFragAtPos = this.fragmentTracker.getFragAtPos(targetBufferTime, PlaylistLevelType.MAIN);
  15578. if (mainFragAtPos && mainFragAtPos.end > mainFragLoading.end) {
  15579. mainFragLoading = mainFragAtPos;
  15580. this.mainFragLoading = {
  15581. frag: mainFragAtPos,
  15582. targetBufferTime: null
  15583. };
  15584. }
  15585. }
  15586. const atBufferSyncLimit = frag.start > mainFragLoading.end;
  15587. if (atBufferSyncLimit) {
  15588. return;
  15589. }
  15590. }
  15591. }
  15592. this.loadFragment(frag, levelInfo, targetBufferTime);
  15593. }
  15594. onMediaDetaching(event, data) {
  15595. this.bufferFlushed = this.flushing = false;
  15596. super.onMediaDetaching(event, data);
  15597. }
  15598. onAudioTracksUpdated(event, {
  15599. audioTracks
  15600. }) {
  15601. this.resetTransmuxer();
  15602. this.levels = audioTracks.map((mediaPlaylist) => new Level(mediaPlaylist));
  15603. }
  15604. onAudioTrackSwitching(event, data) {
  15605. const altAudio = !!data.url;
  15606. this.trackId = data.id;
  15607. const {
  15608. fragCurrent
  15609. } = this;
  15610. if (fragCurrent) {
  15611. fragCurrent.abortRequests();
  15612. this.removeUnbufferedFrags(fragCurrent.start);
  15613. }
  15614. this.resetLoadingState();
  15615. if (altAudio) {
  15616. this.switchingTrack = data;
  15617. this.flushAudioIfNeeded(data);
  15618. if (this.state !== State.STOPPED) {
  15619. this.setInterval(TICK_INTERVAL$3);
  15620. this.state = State.IDLE;
  15621. this.tick();
  15622. }
  15623. } else {
  15624. this.resetTransmuxer();
  15625. this.switchingTrack = null;
  15626. this.bufferedTrack = data;
  15627. this.clearInterval();
  15628. }
  15629. }
  15630. onManifestLoading() {
  15631. super.onManifestLoading();
  15632. this.bufferFlushed = this.flushing = this.audioOnly = false;
  15633. this.resetItem();
  15634. this.trackId = -1;
  15635. }
  15636. onLevelLoaded(event, data) {
  15637. this.mainDetails = data.details;
  15638. const cachedTrackLoadedData = this.cachedTrackLoadedData;
  15639. if (cachedTrackLoadedData) {
  15640. this.cachedTrackLoadedData = null;
  15641. this.onAudioTrackLoaded(Events.AUDIO_TRACK_LOADED, cachedTrackLoadedData);
  15642. }
  15643. }
  15644. onAudioTrackLoaded(event, data) {
  15645. var _trackLevel$details;
  15646. const {
  15647. levels
  15648. } = this;
  15649. const {
  15650. details: newDetails,
  15651. id: trackId,
  15652. groupId,
  15653. track
  15654. } = data;
  15655. if (!levels) {
  15656. this.warn(`Audio tracks reset while loading track ${trackId} "${track.name}" of "${groupId}"`);
  15657. return;
  15658. }
  15659. const mainDetails = this.mainDetails;
  15660. if (!mainDetails || newDetails.endCC > mainDetails.endCC || mainDetails.expired) {
  15661. this.cachedTrackLoadedData = data;
  15662. if (this.state !== State.STOPPED) {
  15663. this.state = State.WAITING_TRACK;
  15664. }
  15665. return;
  15666. }
  15667. this.cachedTrackLoadedData = null;
  15668. this.log(`Audio track ${trackId} "${track.name}" of "${groupId}" loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""},duration:${newDetails.totalduration}`);
  15669. const trackLevel = levels[trackId];
  15670. let sliding = 0;
  15671. if (newDetails.live || (_trackLevel$details = trackLevel.details) != null && _trackLevel$details.live) {
  15672. this.checkLiveUpdate(newDetails);
  15673. if (newDetails.deltaUpdateFailed) {
  15674. return;
  15675. }
  15676. if (trackLevel.details) {
  15677. var _this$levelLastLoaded;
  15678. sliding = this.alignPlaylists(newDetails, trackLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  15679. }
  15680. if (!newDetails.alignedSliding) {
  15681. alignDiscontinuities(newDetails, mainDetails);
  15682. if (!newDetails.alignedSliding) {
  15683. alignMediaPlaylistByPDT(newDetails, mainDetails);
  15684. }
  15685. sliding = newDetails.fragmentStart;
  15686. }
  15687. }
  15688. trackLevel.details = newDetails;
  15689. this.levelLastLoaded = trackLevel;
  15690. if (!this.startFragRequested) {
  15691. this.setStartPosition(mainDetails, sliding);
  15692. }
  15693. this.hls.trigger(Events.AUDIO_TRACK_UPDATED, {
  15694. details: newDetails,
  15695. id: trackId,
  15696. groupId: data.groupId
  15697. });
  15698. if (this.state === State.WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) {
  15699. this.state = State.IDLE;
  15700. }
  15701. this.tick();
  15702. }
  15703. _handleFragmentLoadProgress(data) {
  15704. var _frag$initSegment;
  15705. const frag = data.frag;
  15706. const {
  15707. part,
  15708. payload
  15709. } = data;
  15710. const {
  15711. config,
  15712. trackId,
  15713. levels
  15714. } = this;
  15715. if (!levels) {
  15716. this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  15717. return;
  15718. }
  15719. const track = levels[trackId];
  15720. if (!track) {
  15721. this.warn("Audio track is undefined on fragment load progress");
  15722. return;
  15723. }
  15724. const details = track.details;
  15725. if (!details) {
  15726. this.warn("Audio track details undefined on fragment load progress");
  15727. this.removeUnbufferedFrags(frag.start);
  15728. return;
  15729. }
  15730. const audioCodec = config.defaultAudioCodec || track.audioCodec || "mp4a.40.2";
  15731. let transmuxer = this.transmuxer;
  15732. if (!transmuxer) {
  15733. transmuxer = this.transmuxer = new TransmuxerInterface(this.hls, PlaylistLevelType.AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  15734. }
  15735. const initPTS = this.initPTS[frag.cc];
  15736. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  15737. if (initPTS !== void 0) {
  15738. const accurateTimeOffset = false;
  15739. const partIndex = part ? part.index : -1;
  15740. const partial = partIndex !== -1;
  15741. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  15742. transmuxer.push(payload, initSegmentData, audioCodec, "", frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  15743. } else {
  15744. 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}`);
  15745. const {
  15746. cache
  15747. } = this.waitingData = this.waitingData || {
  15748. frag,
  15749. part,
  15750. cache: new ChunkCache(),
  15751. complete: false
  15752. };
  15753. cache.push(new Uint8Array(payload));
  15754. if (this.state !== State.STOPPED) {
  15755. this.state = State.WAITING_INIT_PTS;
  15756. }
  15757. }
  15758. }
  15759. _handleFragmentLoadComplete(fragLoadedData) {
  15760. if (this.waitingData) {
  15761. this.waitingData.complete = true;
  15762. return;
  15763. }
  15764. super._handleFragmentLoadComplete(fragLoadedData);
  15765. }
  15766. onBufferReset() {
  15767. this.mediaBuffer = null;
  15768. }
  15769. onBufferCreated(event, data) {
  15770. this.bufferFlushed = this.flushing = false;
  15771. const audioTrack = data.tracks.audio;
  15772. if (audioTrack) {
  15773. this.mediaBuffer = audioTrack.buffer || null;
  15774. }
  15775. }
  15776. onFragLoading(event, data) {
  15777. if (!this.audioOnly && data.frag.type === PlaylistLevelType.MAIN && isMediaFragment(data.frag)) {
  15778. this.mainFragLoading = data;
  15779. if (this.state === State.IDLE) {
  15780. this.tick();
  15781. }
  15782. }
  15783. }
  15784. onFragBuffered(event, data) {
  15785. const {
  15786. frag,
  15787. part
  15788. } = data;
  15789. if (frag.type !== PlaylistLevelType.AUDIO) {
  15790. if (!this.audioOnly && frag.type === PlaylistLevelType.MAIN && !frag.elementaryStreams.video && !frag.elementaryStreams.audiovideo) {
  15791. this.audioOnly = true;
  15792. this.mainFragLoading = null;
  15793. }
  15794. return;
  15795. }
  15796. if (this.fragContextChanged(frag)) {
  15797. 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"}`);
  15798. return;
  15799. }
  15800. if (isMediaFragment(frag)) {
  15801. this.fragPrevious = frag;
  15802. const track = this.switchingTrack;
  15803. if (track) {
  15804. this.bufferedTrack = track;
  15805. this.switchingTrack = null;
  15806. this.hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, track));
  15807. }
  15808. }
  15809. this.fragBufferedComplete(frag, part);
  15810. if (this.media) {
  15811. this.tick();
  15812. }
  15813. }
  15814. onError(event, data) {
  15815. var _data$context;
  15816. if (data.fatal) {
  15817. this.state = State.ERROR;
  15818. return;
  15819. }
  15820. switch (data.details) {
  15821. case ErrorDetails.FRAG_GAP:
  15822. case ErrorDetails.FRAG_PARSING_ERROR:
  15823. case ErrorDetails.FRAG_DECRYPT_ERROR:
  15824. case ErrorDetails.FRAG_LOAD_ERROR:
  15825. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  15826. case ErrorDetails.KEY_LOAD_ERROR:
  15827. case ErrorDetails.KEY_LOAD_TIMEOUT:
  15828. this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO, data);
  15829. break;
  15830. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  15831. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  15832. case ErrorDetails.LEVEL_PARSING_ERROR:
  15833. if (!data.levelRetry && this.state === State.WAITING_TRACK && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.AUDIO_TRACK) {
  15834. this.state = State.IDLE;
  15835. }
  15836. break;
  15837. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  15838. case ErrorDetails.BUFFER_APPEND_ERROR:
  15839. if (data.parent !== "audio") {
  15840. return;
  15841. }
  15842. if (!this.reduceLengthAndFlushBuffer(data)) {
  15843. this.resetLoadingState();
  15844. }
  15845. break;
  15846. case ErrorDetails.BUFFER_FULL_ERROR:
  15847. if (data.parent !== "audio") {
  15848. return;
  15849. }
  15850. if (this.reduceLengthAndFlushBuffer(data)) {
  15851. this.bufferedTrack = null;
  15852. super.flushMainBuffer(0, Number.POSITIVE_INFINITY, "audio");
  15853. }
  15854. break;
  15855. case ErrorDetails.INTERNAL_EXCEPTION:
  15856. this.recoverWorkerError(data);
  15857. break;
  15858. }
  15859. }
  15860. onBufferFlushing(event, {
  15861. type
  15862. }) {
  15863. if (type !== ElementaryStreamTypes.VIDEO) {
  15864. this.flushing = true;
  15865. }
  15866. }
  15867. onBufferFlushed(event, {
  15868. type
  15869. }) {
  15870. if (type !== ElementaryStreamTypes.VIDEO) {
  15871. this.flushing = false;
  15872. this.bufferFlushed = true;
  15873. if (this.state === State.ENDED) {
  15874. this.state = State.IDLE;
  15875. }
  15876. const mediaBuffer = this.mediaBuffer || this.media;
  15877. if (mediaBuffer) {
  15878. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.AUDIO);
  15879. this.tick();
  15880. }
  15881. }
  15882. }
  15883. _handleTransmuxComplete(transmuxResult) {
  15884. var _id3$samples;
  15885. const id = "audio";
  15886. const {
  15887. hls
  15888. } = this;
  15889. const {
  15890. remuxResult,
  15891. chunkMeta
  15892. } = transmuxResult;
  15893. const context = this.getCurrentContext(chunkMeta);
  15894. if (!context) {
  15895. this.resetWhenMissingContext(chunkMeta);
  15896. return;
  15897. }
  15898. const {
  15899. frag,
  15900. part,
  15901. level
  15902. } = context;
  15903. const {
  15904. details
  15905. } = level;
  15906. const {
  15907. audio,
  15908. text,
  15909. id3,
  15910. initSegment
  15911. } = remuxResult;
  15912. if (this.fragContextChanged(frag) || !details) {
  15913. this.fragmentTracker.removeFragment(frag);
  15914. return;
  15915. }
  15916. this.state = State.PARSING;
  15917. if (this.switchingTrack && audio) {
  15918. this.completeAudioSwitch(this.switchingTrack);
  15919. }
  15920. if (initSegment != null && initSegment.tracks) {
  15921. const mapFragment = frag.initSegment || frag;
  15922. if (this.unhandledEncryptionError(initSegment, frag)) {
  15923. return;
  15924. }
  15925. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  15926. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  15927. frag: mapFragment,
  15928. id,
  15929. tracks: initSegment.tracks
  15930. });
  15931. }
  15932. if (audio) {
  15933. const {
  15934. startPTS,
  15935. endPTS,
  15936. startDTS,
  15937. endDTS
  15938. } = audio;
  15939. if (part) {
  15940. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  15941. startPTS,
  15942. endPTS,
  15943. startDTS,
  15944. endDTS
  15945. };
  15946. }
  15947. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  15948. this.bufferFragmentData(audio, frag, part, chunkMeta);
  15949. }
  15950. if (id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  15951. const emittedID3 = _extends({
  15952. id,
  15953. frag,
  15954. details
  15955. }, id3);
  15956. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  15957. }
  15958. if (text) {
  15959. const emittedText = _extends({
  15960. id,
  15961. frag,
  15962. details
  15963. }, text);
  15964. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  15965. }
  15966. }
  15967. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  15968. if (this.state !== State.PARSING) {
  15969. return;
  15970. }
  15971. if (tracks.video) {
  15972. delete tracks.video;
  15973. }
  15974. if (tracks.audiovideo) {
  15975. delete tracks.audiovideo;
  15976. }
  15977. if (!tracks.audio) {
  15978. return;
  15979. }
  15980. const track = tracks.audio;
  15981. track.id = PlaylistLevelType.AUDIO;
  15982. const variantAudioCodecs = currentLevel.audioCodec;
  15983. this.log(`Init audio buffer, container:${track.container}, codecs[level/parsed]=[${variantAudioCodecs}/${track.codec}]`);
  15984. if (variantAudioCodecs && variantAudioCodecs.split(",").length === 1) {
  15985. track.levelCodec = variantAudioCodecs;
  15986. }
  15987. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  15988. const initSegment = track.initSegment;
  15989. if (initSegment != null && initSegment.byteLength) {
  15990. const segment = {
  15991. type: "audio",
  15992. frag,
  15993. part: null,
  15994. chunkMeta,
  15995. parent: frag.type,
  15996. data: initSegment
  15997. };
  15998. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  15999. }
  16000. this.tickImmediate();
  16001. }
  16002. loadFragment(frag, track, targetBufferTime) {
  16003. const fragState = this.fragmentTracker.getState(frag);
  16004. if (this.switchingTrack || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  16005. var _track$details;
  16006. if (!isMediaFragment(frag)) {
  16007. this._loadInitSegment(frag, track);
  16008. } else if ((_track$details = track.details) != null && _track$details.live && !this.initPTS[frag.cc]) {
  16009. this.log(`Waiting for video PTS in continuity counter ${frag.cc} of live stream before loading audio fragment ${frag.sn} of level ${this.trackId}`);
  16010. this.state = State.WAITING_INIT_PTS;
  16011. const mainDetails = this.mainDetails;
  16012. if (mainDetails && mainDetails.fragmentStart !== track.details.fragmentStart) {
  16013. alignMediaPlaylistByPDT(track.details, mainDetails);
  16014. }
  16015. } else {
  16016. super.loadFragment(frag, track, targetBufferTime);
  16017. }
  16018. } else {
  16019. this.clearTrackerIfNeeded(frag);
  16020. }
  16021. }
  16022. flushAudioIfNeeded(switchingTrack) {
  16023. if (this.media && this.bufferedTrack) {
  16024. const {
  16025. name,
  16026. lang,
  16027. assocLang,
  16028. characteristics,
  16029. audioCodec,
  16030. channels
  16031. } = this.bufferedTrack;
  16032. if (!matchesOption({
  16033. name,
  16034. lang,
  16035. assocLang,
  16036. characteristics,
  16037. audioCodec,
  16038. channels
  16039. }, switchingTrack, audioMatchPredicate)) {
  16040. if (useAlternateAudio(switchingTrack.url, this.hls)) {
  16041. this.log("Switching audio track : flushing all audio");
  16042. super.flushMainBuffer(0, Number.POSITIVE_INFINITY, "audio");
  16043. this.bufferedTrack = null;
  16044. } else {
  16045. this.bufferedTrack = switchingTrack;
  16046. }
  16047. }
  16048. }
  16049. }
  16050. completeAudioSwitch(switchingTrack) {
  16051. const {
  16052. hls
  16053. } = this;
  16054. this.flushAudioIfNeeded(switchingTrack);
  16055. this.bufferedTrack = switchingTrack;
  16056. this.switchingTrack = null;
  16057. hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, switchingTrack));
  16058. }
  16059. };
  16060. var BasePlaylistController = class extends Logger {
  16061. constructor(hls, logPrefix) {
  16062. super(logPrefix, hls.logger);
  16063. this.hls = void 0;
  16064. this.canLoad = false;
  16065. this.timer = -1;
  16066. this.hls = hls;
  16067. }
  16068. destroy() {
  16069. this.clearTimer();
  16070. this.hls = this.log = this.warn = null;
  16071. }
  16072. clearTimer() {
  16073. if (this.timer !== -1) {
  16074. self.clearTimeout(this.timer);
  16075. this.timer = -1;
  16076. }
  16077. }
  16078. startLoad() {
  16079. this.canLoad = true;
  16080. this.loadPlaylist();
  16081. }
  16082. stopLoad() {
  16083. this.canLoad = false;
  16084. this.clearTimer();
  16085. }
  16086. switchParams(playlistUri, previous, current) {
  16087. const renditionReports = previous == null ? void 0 : previous.renditionReports;
  16088. if (renditionReports) {
  16089. let foundIndex = -1;
  16090. for (let i = 0; i < renditionReports.length; i++) {
  16091. const attr = renditionReports[i];
  16092. let uri;
  16093. try {
  16094. uri = new self.URL(attr.URI, previous.url).href;
  16095. } catch (error) {
  16096. this.warn(`Could not construct new URL for Rendition Report: ${error}`);
  16097. uri = attr.URI || "";
  16098. }
  16099. if (uri === playlistUri) {
  16100. foundIndex = i;
  16101. break;
  16102. } else if (uri === playlistUri.substring(0, uri.length)) {
  16103. foundIndex = i;
  16104. }
  16105. }
  16106. if (foundIndex !== -1) {
  16107. const attr = renditionReports[foundIndex];
  16108. const msn = parseInt(attr["LAST-MSN"]) || previous.lastPartSn;
  16109. let part = parseInt(attr["LAST-PART"]) || previous.lastPartIndex;
  16110. if (this.hls.config.lowLatencyMode) {
  16111. const currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
  16112. if (part >= 0 && currentGoal > previous.partTarget) {
  16113. part += 1;
  16114. }
  16115. }
  16116. const skip = current && getSkipValue(current);
  16117. return new HlsUrlParameters(msn, part >= 0 ? part : void 0, skip);
  16118. }
  16119. }
  16120. }
  16121. loadPlaylist(hlsUrlParameters) {
  16122. this.clearTimer();
  16123. }
  16124. loadingPlaylist(playlist, hlsUrlParameters) {
  16125. this.clearTimer();
  16126. }
  16127. shouldLoadPlaylist(playlist) {
  16128. return this.canLoad && !!playlist && !!playlist.url && (!playlist.details || playlist.details.live);
  16129. }
  16130. getUrlWithDirectives(uri, hlsUrlParameters) {
  16131. if (hlsUrlParameters) {
  16132. try {
  16133. return hlsUrlParameters.addDirectives(uri);
  16134. } catch (error) {
  16135. this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`);
  16136. }
  16137. }
  16138. return uri;
  16139. }
  16140. playlistLoaded(index, data, previousDetails) {
  16141. const {
  16142. details,
  16143. stats
  16144. } = data;
  16145. const now2 = self.performance.now();
  16146. const elapsed = stats.loading.first ? Math.max(0, now2 - stats.loading.first) : 0;
  16147. details.advancedDateTime = Date.now() - elapsed;
  16148. const timelineOffset = this.hls.config.timelineOffset;
  16149. if (timelineOffset !== details.appliedTimelineOffset) {
  16150. const offset = Math.max(timelineOffset || 0, 0);
  16151. details.appliedTimelineOffset = offset;
  16152. details.fragments.forEach((frag) => {
  16153. frag.setStart(frag.playlistOffset + offset);
  16154. });
  16155. }
  16156. if (details.live || previousDetails != null && previousDetails.live) {
  16157. const levelOrTrack = "levelInfo" in data ? data.levelInfo : data.track;
  16158. details.reloaded(previousDetails);
  16159. if (previousDetails && details.fragments.length > 0) {
  16160. mergeDetails(previousDetails, details, this);
  16161. const error = details.playlistParsingError;
  16162. if (error) {
  16163. this.warn(error);
  16164. const hls = this.hls;
  16165. if (!hls.config.ignorePlaylistParsingErrors) {
  16166. var _details$fragments$;
  16167. const {
  16168. networkDetails
  16169. } = data;
  16170. hls.trigger(Events.ERROR, {
  16171. type: ErrorTypes.NETWORK_ERROR,
  16172. details: ErrorDetails.LEVEL_PARSING_ERROR,
  16173. fatal: false,
  16174. url: details.url,
  16175. error,
  16176. reason: error.message,
  16177. level: data.level || void 0,
  16178. parent: (_details$fragments$ = details.fragments[0]) == null ? void 0 : _details$fragments$.type,
  16179. networkDetails,
  16180. stats
  16181. });
  16182. return;
  16183. }
  16184. details.playlistParsingError = null;
  16185. }
  16186. }
  16187. if (details.requestScheduled === -1) {
  16188. details.requestScheduled = stats.loading.start;
  16189. }
  16190. const bufferInfo = this.hls.mainForwardBufferInfo;
  16191. const position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;
  16192. const distanceToLiveEdgeMs = (details.edge - position) * 1e3;
  16193. const reloadInterval = computeReloadInterval(details, distanceToLiveEdgeMs);
  16194. if (details.requestScheduled + reloadInterval < now2) {
  16195. details.requestScheduled = now2;
  16196. } else {
  16197. details.requestScheduled += reloadInterval;
  16198. }
  16199. this.log(`live playlist ${index} ${details.advanced ? "REFRESHED " + details.lastPartSn + "-" + details.lastPartIndex : details.updated ? "UPDATED" : "MISSED"}`);
  16200. if (!this.canLoad || !details.live) {
  16201. return;
  16202. }
  16203. let deliveryDirectives;
  16204. let msn = void 0;
  16205. let part = void 0;
  16206. if (details.canBlockReload && details.endSN && details.advanced) {
  16207. const lowLatencyMode = this.hls.config.lowLatencyMode;
  16208. const lastPartSn = details.lastPartSn;
  16209. const endSn = details.endSN;
  16210. const lastPartIndex = details.lastPartIndex;
  16211. const hasParts = lastPartIndex !== -1;
  16212. const atLastPartOfSegment = lastPartSn === endSn;
  16213. if (hasParts) {
  16214. if (atLastPartOfSegment) {
  16215. msn = endSn + 1;
  16216. part = lowLatencyMode ? 0 : lastPartIndex;
  16217. } else {
  16218. msn = lastPartSn;
  16219. part = lowLatencyMode ? lastPartIndex + 1 : details.maxPartIndex;
  16220. }
  16221. } else {
  16222. msn = endSn + 1;
  16223. }
  16224. const lastAdvanced = details.age;
  16225. const cdnAge = lastAdvanced + details.ageHeader;
  16226. let currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
  16227. if (currentGoal > 0) {
  16228. if (cdnAge > details.targetduration * 3) {
  16229. this.log(`Playlist last advanced ${lastAdvanced.toFixed(2)}s ago. Omitting segment and part directives.`);
  16230. msn = void 0;
  16231. part = void 0;
  16232. } else if (previousDetails != null && previousDetails.tuneInGoal && cdnAge - details.partTarget > previousDetails.tuneInGoal) {
  16233. this.warn(`CDN Tune-in goal increased from: ${previousDetails.tuneInGoal} to: ${currentGoal} with playlist age: ${details.age}`);
  16234. currentGoal = 0;
  16235. } else {
  16236. const segments = Math.floor(currentGoal / details.targetduration);
  16237. msn += segments;
  16238. if (part !== void 0) {
  16239. const parts = Math.round(currentGoal % details.targetduration / details.partTarget);
  16240. part += parts;
  16241. }
  16242. this.log(`CDN Tune-in age: ${details.ageHeader}s last advanced ${lastAdvanced.toFixed(2)}s goal: ${currentGoal} skip sn ${segments} to part ${part}`);
  16243. }
  16244. details.tuneInGoal = currentGoal;
  16245. }
  16246. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  16247. if (lowLatencyMode || !atLastPartOfSegment) {
  16248. details.requestScheduled = now2;
  16249. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  16250. return;
  16251. }
  16252. } else if (details.canBlockReload || details.canSkipUntil) {
  16253. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  16254. }
  16255. if (deliveryDirectives && msn !== void 0 && details.canBlockReload) {
  16256. details.requestScheduled = stats.loading.first + Math.max(reloadInterval - elapsed * 2, reloadInterval / 2);
  16257. }
  16258. this.scheduleLoading(levelOrTrack, deliveryDirectives, details);
  16259. } else {
  16260. this.clearTimer();
  16261. }
  16262. }
  16263. scheduleLoading(levelOrTrack, deliveryDirectives, updatedDetails) {
  16264. const details = updatedDetails || levelOrTrack.details;
  16265. if (!details) {
  16266. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  16267. return;
  16268. }
  16269. const now2 = self.performance.now();
  16270. const requestScheduled = details.requestScheduled;
  16271. if (now2 >= requestScheduled) {
  16272. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  16273. return;
  16274. }
  16275. const estimatedTimeUntilUpdate = requestScheduled - now2;
  16276. this.log(`reload live playlist ${levelOrTrack.name || levelOrTrack.bitrate + "bps"} in ${Math.round(estimatedTimeUntilUpdate)} ms`);
  16277. this.clearTimer();
  16278. this.timer = self.setTimeout(() => this.loadingPlaylist(levelOrTrack, deliveryDirectives), estimatedTimeUntilUpdate);
  16279. }
  16280. getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
  16281. let skip = getSkipValue(details);
  16282. if (previousDeliveryDirectives != null && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
  16283. msn = previousDeliveryDirectives.msn;
  16284. part = previousDeliveryDirectives.part;
  16285. skip = HlsSkip.No;
  16286. }
  16287. return new HlsUrlParameters(msn, part, skip);
  16288. }
  16289. checkRetry(errorEvent) {
  16290. const errorDetails = errorEvent.details;
  16291. const isTimeout = isTimeoutError(errorEvent);
  16292. const errorAction = errorEvent.errorAction;
  16293. const {
  16294. action,
  16295. retryCount = 0,
  16296. retryConfig
  16297. } = errorAction || {};
  16298. const retry = !!errorAction && !!retryConfig && (action === NetworkErrorAction.RetryRequest || !errorAction.resolved && action === NetworkErrorAction.SendAlternateToPenaltyBox);
  16299. if (retry) {
  16300. var _errorEvent$context;
  16301. if (retryCount >= retryConfig.maxNumRetry) {
  16302. return false;
  16303. }
  16304. if (isTimeout && (_errorEvent$context = errorEvent.context) != null && _errorEvent$context.deliveryDirectives) {
  16305. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" without delivery-directives`);
  16306. this.loadPlaylist();
  16307. } else {
  16308. const delay = getRetryDelay(retryConfig, retryCount);
  16309. this.clearTimer();
  16310. this.timer = self.setTimeout(() => this.loadPlaylist(), delay);
  16311. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" in ${delay}ms`);
  16312. }
  16313. errorEvent.levelRetry = true;
  16314. errorAction.resolved = true;
  16315. }
  16316. return retry;
  16317. }
  16318. };
  16319. function subtitleOptionsIdentical(trackList1, trackList2) {
  16320. if (trackList1.length !== trackList2.length) {
  16321. return false;
  16322. }
  16323. for (let i = 0; i < trackList1.length; i++) {
  16324. if (!mediaAttributesIdentical(trackList1[i].attrs, trackList2[i].attrs)) {
  16325. return false;
  16326. }
  16327. }
  16328. return true;
  16329. }
  16330. function mediaAttributesIdentical(attrs1, attrs2, customAttributes) {
  16331. const stableRenditionId = attrs1["STABLE-RENDITION-ID"];
  16332. if (stableRenditionId && !customAttributes) {
  16333. return stableRenditionId === attrs2["STABLE-RENDITION-ID"];
  16334. }
  16335. return !(customAttributes || ["LANGUAGE", "NAME", "CHARACTERISTICS", "AUTOSELECT", "DEFAULT", "FORCED", "ASSOC-LANGUAGE"]).some((subtitleAttribute) => attrs1[subtitleAttribute] !== attrs2[subtitleAttribute]);
  16336. }
  16337. function subtitleTrackMatchesTextTrack(subtitleTrack, textTrack) {
  16338. return textTrack.label.toLowerCase() === subtitleTrack.name.toLowerCase() && (!textTrack.language || textTrack.language.toLowerCase() === (subtitleTrack.lang || "").toLowerCase());
  16339. }
  16340. var AudioTrackController = class extends BasePlaylistController {
  16341. constructor(hls) {
  16342. super(hls, "audio-track-controller");
  16343. this.tracks = [];
  16344. this.groupIds = null;
  16345. this.tracksInGroup = [];
  16346. this.trackId = -1;
  16347. this.currentTrack = null;
  16348. this.selectDefaultTrack = true;
  16349. this.registerListeners();
  16350. }
  16351. registerListeners() {
  16352. const {
  16353. hls
  16354. } = this;
  16355. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16356. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  16357. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  16358. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  16359. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  16360. hls.on(Events.ERROR, this.onError, this);
  16361. }
  16362. unregisterListeners() {
  16363. const {
  16364. hls
  16365. } = this;
  16366. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16367. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  16368. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  16369. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  16370. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  16371. hls.off(Events.ERROR, this.onError, this);
  16372. }
  16373. destroy() {
  16374. this.unregisterListeners();
  16375. this.tracks.length = 0;
  16376. this.tracksInGroup.length = 0;
  16377. this.currentTrack = null;
  16378. super.destroy();
  16379. }
  16380. onManifestLoading() {
  16381. this.tracks = [];
  16382. this.tracksInGroup = [];
  16383. this.groupIds = null;
  16384. this.currentTrack = null;
  16385. this.trackId = -1;
  16386. this.selectDefaultTrack = true;
  16387. }
  16388. onManifestParsed(event, data) {
  16389. this.tracks = data.audioTracks || [];
  16390. }
  16391. onAudioTrackLoaded(event, data) {
  16392. const {
  16393. id,
  16394. groupId,
  16395. details
  16396. } = data;
  16397. const trackInActiveGroup = this.tracksInGroup[id];
  16398. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  16399. this.warn(`Audio track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
  16400. return;
  16401. }
  16402. const curDetails = trackInActiveGroup.details;
  16403. trackInActiveGroup.details = data.details;
  16404. this.log(`Audio track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
  16405. if (id === this.trackId) {
  16406. this.playlistLoaded(id, data, curDetails);
  16407. }
  16408. }
  16409. onLevelLoading(event, data) {
  16410. this.switchLevel(data.level);
  16411. }
  16412. onLevelSwitching(event, data) {
  16413. this.switchLevel(data.level);
  16414. }
  16415. switchLevel(levelIndex) {
  16416. const levelInfo = this.hls.levels[levelIndex];
  16417. if (!levelInfo) {
  16418. return;
  16419. }
  16420. const audioGroups = levelInfo.audioGroups || null;
  16421. const currentGroups = this.groupIds;
  16422. let currentTrack = this.currentTrack;
  16423. 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)) {
  16424. this.groupIds = audioGroups;
  16425. this.trackId = -1;
  16426. this.currentTrack = null;
  16427. const audioTracks = this.tracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  16428. if (audioTracks.length) {
  16429. if (this.selectDefaultTrack && !audioTracks.some((track) => track.default)) {
  16430. this.selectDefaultTrack = false;
  16431. }
  16432. audioTracks.forEach((track, i) => {
  16433. track.id = i;
  16434. });
  16435. } else if (!currentTrack && !this.tracksInGroup.length) {
  16436. return;
  16437. }
  16438. this.tracksInGroup = audioTracks;
  16439. const audioPreference = this.hls.config.audioPreference;
  16440. if (!currentTrack && audioPreference) {
  16441. const groupIndex = findMatchingOption(audioPreference, audioTracks, audioMatchPredicate);
  16442. if (groupIndex > -1) {
  16443. currentTrack = audioTracks[groupIndex];
  16444. } else {
  16445. const allIndex = findMatchingOption(audioPreference, this.tracks);
  16446. currentTrack = this.tracks[allIndex];
  16447. }
  16448. }
  16449. let trackId = this.findTrackId(currentTrack);
  16450. if (trackId === -1 && currentTrack) {
  16451. trackId = this.findTrackId(null);
  16452. }
  16453. const audioTracksUpdated = {
  16454. audioTracks
  16455. };
  16456. this.log(`Updating audio tracks, ${audioTracks.length} track(s) found in group(s): ${audioGroups == null ? void 0 : audioGroups.join(",")}`);
  16457. this.hls.trigger(Events.AUDIO_TRACKS_UPDATED, audioTracksUpdated);
  16458. const selectedTrackId = this.trackId;
  16459. if (trackId !== -1 && selectedTrackId === -1) {
  16460. this.setAudioTrack(trackId);
  16461. } else if (audioTracks.length && selectedTrackId === -1) {
  16462. var _this$groupIds;
  16463. 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}`);
  16464. this.warn(error.message);
  16465. this.hls.trigger(Events.ERROR, {
  16466. type: ErrorTypes.MEDIA_ERROR,
  16467. details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,
  16468. fatal: true,
  16469. error
  16470. });
  16471. }
  16472. }
  16473. }
  16474. onError(event, data) {
  16475. if (data.fatal || !data.context) {
  16476. return;
  16477. }
  16478. if (data.context.type === PlaylistContextType.AUDIO_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  16479. this.checkRetry(data);
  16480. }
  16481. }
  16482. get allAudioTracks() {
  16483. return this.tracks;
  16484. }
  16485. get audioTracks() {
  16486. return this.tracksInGroup;
  16487. }
  16488. get audioTrack() {
  16489. return this.trackId;
  16490. }
  16491. set audioTrack(newId) {
  16492. this.selectDefaultTrack = false;
  16493. this.setAudioTrack(newId);
  16494. }
  16495. setAudioOption(audioOption) {
  16496. const hls = this.hls;
  16497. hls.config.audioPreference = audioOption;
  16498. if (audioOption) {
  16499. const allAudioTracks = this.allAudioTracks;
  16500. this.selectDefaultTrack = false;
  16501. if (allAudioTracks.length) {
  16502. const currentTrack = this.currentTrack;
  16503. if (currentTrack && matchesOption(audioOption, currentTrack, audioMatchPredicate)) {
  16504. return currentTrack;
  16505. }
  16506. const groupIndex = findMatchingOption(audioOption, this.tracksInGroup, audioMatchPredicate);
  16507. if (groupIndex > -1) {
  16508. const track = this.tracksInGroup[groupIndex];
  16509. this.setAudioTrack(groupIndex);
  16510. return track;
  16511. } else if (currentTrack) {
  16512. let searchIndex = hls.loadLevel;
  16513. if (searchIndex === -1) {
  16514. searchIndex = hls.firstAutoLevel;
  16515. }
  16516. const switchIndex = findClosestLevelWithAudioGroup(audioOption, hls.levels, allAudioTracks, searchIndex, audioMatchPredicate);
  16517. if (switchIndex === -1) {
  16518. return null;
  16519. }
  16520. hls.nextLoadLevel = switchIndex;
  16521. }
  16522. if (audioOption.channels || audioOption.audioCodec) {
  16523. const withoutCodecAndChannelsMatch = findMatchingOption(audioOption, allAudioTracks);
  16524. if (withoutCodecAndChannelsMatch > -1) {
  16525. return allAudioTracks[withoutCodecAndChannelsMatch];
  16526. }
  16527. }
  16528. }
  16529. }
  16530. return null;
  16531. }
  16532. setAudioTrack(newId) {
  16533. const tracks = this.tracksInGroup;
  16534. if (newId < 0 || newId >= tracks.length) {
  16535. this.warn(`Invalid audio track id: ${newId}`);
  16536. return;
  16537. }
  16538. this.selectDefaultTrack = false;
  16539. const lastTrack = this.currentTrack;
  16540. const track = tracks[newId];
  16541. const trackLoaded = track.details && !track.details.live;
  16542. if (newId === this.trackId && track === lastTrack && trackLoaded) {
  16543. return;
  16544. }
  16545. this.log(`Switching to audio-track ${newId} "${track.name}" lang:${track.lang} group:${track.groupId} channels:${track.channels}`);
  16546. this.trackId = newId;
  16547. this.currentTrack = track;
  16548. this.hls.trigger(Events.AUDIO_TRACK_SWITCHING, _objectSpread2({}, track));
  16549. if (trackLoaded) {
  16550. return;
  16551. }
  16552. const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
  16553. this.loadPlaylist(hlsUrlParameters);
  16554. }
  16555. findTrackId(currentTrack) {
  16556. const audioTracks = this.tracksInGroup;
  16557. for (let i = 0; i < audioTracks.length; i++) {
  16558. const track = audioTracks[i];
  16559. if (this.selectDefaultTrack && !track.default) {
  16560. continue;
  16561. }
  16562. if (!currentTrack || matchesOption(currentTrack, track, audioMatchPredicate)) {
  16563. return i;
  16564. }
  16565. }
  16566. if (currentTrack) {
  16567. const {
  16568. name,
  16569. lang,
  16570. assocLang,
  16571. characteristics,
  16572. audioCodec,
  16573. channels
  16574. } = currentTrack;
  16575. for (let i = 0; i < audioTracks.length; i++) {
  16576. const track = audioTracks[i];
  16577. if (matchesOption({
  16578. name,
  16579. lang,
  16580. assocLang,
  16581. characteristics,
  16582. audioCodec,
  16583. channels
  16584. }, track, audioMatchPredicate)) {
  16585. return i;
  16586. }
  16587. }
  16588. for (let i = 0; i < audioTracks.length; i++) {
  16589. const track = audioTracks[i];
  16590. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE", "ASSOC-LANGUAGE", "CHARACTERISTICS"])) {
  16591. return i;
  16592. }
  16593. }
  16594. for (let i = 0; i < audioTracks.length; i++) {
  16595. const track = audioTracks[i];
  16596. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE"])) {
  16597. return i;
  16598. }
  16599. }
  16600. }
  16601. return -1;
  16602. }
  16603. loadPlaylist(hlsUrlParameters) {
  16604. super.loadPlaylist();
  16605. const audioTrack = this.currentTrack;
  16606. if (!this.shouldLoadPlaylist(audioTrack)) {
  16607. return;
  16608. }
  16609. if (useAlternateAudio(audioTrack.url, this.hls)) {
  16610. this.scheduleLoading(audioTrack, hlsUrlParameters);
  16611. }
  16612. }
  16613. loadingPlaylist(audioTrack, hlsUrlParameters) {
  16614. super.loadingPlaylist(audioTrack, hlsUrlParameters);
  16615. const id = audioTrack.id;
  16616. const groupId = audioTrack.groupId;
  16617. const url = this.getUrlWithDirectives(audioTrack.url, hlsUrlParameters);
  16618. const details = audioTrack.details;
  16619. const age = details == null ? void 0 : details.age;
  16620. 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}`);
  16621. this.hls.trigger(Events.AUDIO_TRACK_LOADING, {
  16622. url,
  16623. id,
  16624. groupId,
  16625. deliveryDirectives: hlsUrlParameters || null,
  16626. track: audioTrack
  16627. });
  16628. }
  16629. };
  16630. var BufferOperationQueue = class {
  16631. constructor(sourceBufferReference) {
  16632. this.tracks = void 0;
  16633. this.queues = {
  16634. video: [],
  16635. audio: [],
  16636. audiovideo: []
  16637. };
  16638. this.tracks = sourceBufferReference;
  16639. }
  16640. destroy() {
  16641. this.tracks = this.queues = null;
  16642. }
  16643. append(operation, type, pending) {
  16644. if (this.queues === null || this.tracks === null) {
  16645. return;
  16646. }
  16647. const queue = this.queues[type];
  16648. queue.push(operation);
  16649. if (queue.length === 1 && !pending) {
  16650. this.executeNext(type);
  16651. }
  16652. }
  16653. appendBlocker(type) {
  16654. return new Promise((resolve) => {
  16655. const operation = {
  16656. label: "async-blocker",
  16657. execute: resolve,
  16658. onStart: () => {
  16659. },
  16660. onComplete: () => {
  16661. },
  16662. onError: () => {
  16663. }
  16664. };
  16665. this.append(operation, type);
  16666. });
  16667. }
  16668. prependBlocker(type) {
  16669. return new Promise((resolve) => {
  16670. if (this.queues) {
  16671. const operation = {
  16672. label: "async-blocker-prepend",
  16673. execute: resolve,
  16674. onStart: () => {
  16675. },
  16676. onComplete: () => {
  16677. },
  16678. onError: () => {
  16679. }
  16680. };
  16681. this.queues[type].unshift(operation);
  16682. }
  16683. });
  16684. }
  16685. removeBlockers() {
  16686. if (this.queues === null) {
  16687. return;
  16688. }
  16689. [this.queues.video, this.queues.audio, this.queues.audiovideo].forEach((queue) => {
  16690. var _queue$;
  16691. const label = (_queue$ = queue[0]) == null ? void 0 : _queue$.label;
  16692. if (label === "async-blocker" || label === "async-blocker-prepend") {
  16693. queue[0].execute();
  16694. queue.splice(0, 1);
  16695. }
  16696. });
  16697. }
  16698. unblockAudio(op) {
  16699. if (this.queues === null) {
  16700. return;
  16701. }
  16702. const queue = this.queues.audio;
  16703. if (queue[0] === op) {
  16704. this.shiftAndExecuteNext("audio");
  16705. }
  16706. }
  16707. executeNext(type) {
  16708. if (this.queues === null || this.tracks === null) {
  16709. return;
  16710. }
  16711. const queue = this.queues[type];
  16712. if (queue.length) {
  16713. const operation = queue[0];
  16714. try {
  16715. operation.execute();
  16716. } catch (error) {
  16717. var _this$tracks$type;
  16718. operation.onError(error);
  16719. if (this.queues === null || this.tracks === null) {
  16720. return;
  16721. }
  16722. const sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  16723. if (!(sb != null && sb.updating)) {
  16724. this.shiftAndExecuteNext(type);
  16725. }
  16726. }
  16727. }
  16728. }
  16729. shiftAndExecuteNext(type) {
  16730. if (this.queues === null) {
  16731. return;
  16732. }
  16733. this.queues[type].shift();
  16734. this.executeNext(type);
  16735. }
  16736. current(type) {
  16737. var _this$queues;
  16738. return ((_this$queues = this.queues) == null ? void 0 : _this$queues[type][0]) || null;
  16739. }
  16740. toString() {
  16741. const {
  16742. queues,
  16743. tracks
  16744. } = this;
  16745. if (queues === null || tracks === null) {
  16746. return `<destroyed>`;
  16747. }
  16748. return `
  16749. ${this.list("video")}
  16750. ${this.list("audio")}
  16751. ${this.list("audiovideo")}}`;
  16752. }
  16753. list(type) {
  16754. var _this$queues2, _this$tracks;
  16755. return (_this$queues2 = this.queues) != null && _this$queues2[type] || (_this$tracks = this.tracks) != null && _this$tracks[type] ? `${type}: (${this.listSbInfo(type)}) ${this.listOps(type)}` : "";
  16756. }
  16757. listSbInfo(type) {
  16758. var _this$tracks2;
  16759. const track = (_this$tracks2 = this.tracks) == null ? void 0 : _this$tracks2[type];
  16760. const sb = track == null ? void 0 : track.buffer;
  16761. if (!sb) {
  16762. return "none";
  16763. }
  16764. return `SourceBuffer${sb.updating ? " updating" : ""}${track.ended ? " ended" : ""}${track.ending ? " ending" : ""}`;
  16765. }
  16766. listOps(type) {
  16767. var _this$queues3;
  16768. return ((_this$queues3 = this.queues) == null ? void 0 : _this$queues3[type].map((op) => op.label).join(", ")) || "";
  16769. }
  16770. };
  16771. var VIDEO_CODEC_PROFILE_REPLACE = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;
  16772. var TRACK_REMOVED_ERROR_NAME = "HlsJsTrackRemovedError";
  16773. var HlsJsTrackRemovedError = class extends Error {
  16774. constructor(message) {
  16775. super(message);
  16776. this.name = TRACK_REMOVED_ERROR_NAME;
  16777. }
  16778. };
  16779. var BufferController = class extends Logger {
  16780. constructor(hls, fragmentTracker) {
  16781. super("buffer-controller", hls.logger);
  16782. this.hls = void 0;
  16783. this.fragmentTracker = void 0;
  16784. this.details = null;
  16785. this._objectUrl = null;
  16786. this.operationQueue = null;
  16787. this.bufferCodecEventsTotal = 0;
  16788. this.media = null;
  16789. this.mediaSource = null;
  16790. this.lastMpegAudioChunk = null;
  16791. this.blockedAudioAppend = null;
  16792. this.lastVideoAppendEnd = 0;
  16793. this.appendSource = void 0;
  16794. this.transferData = void 0;
  16795. this.overrides = void 0;
  16796. this.appendErrors = {
  16797. audio: 0,
  16798. video: 0,
  16799. audiovideo: 0
  16800. };
  16801. this.tracks = {};
  16802. this.sourceBuffers = [[null, null], [null, null]];
  16803. this._onEndStreaming = (event) => {
  16804. var _this$mediaSource;
  16805. if (!this.hls) {
  16806. return;
  16807. }
  16808. if (((_this$mediaSource = this.mediaSource) == null ? void 0 : _this$mediaSource.readyState) !== "open") {
  16809. return;
  16810. }
  16811. this.hls.pauseBuffering();
  16812. };
  16813. this._onStartStreaming = (event) => {
  16814. if (!this.hls) {
  16815. return;
  16816. }
  16817. this.hls.resumeBuffering();
  16818. };
  16819. this._onMediaSourceOpen = (e) => {
  16820. const {
  16821. media,
  16822. mediaSource
  16823. } = this;
  16824. if (e) {
  16825. this.log("Media source opened");
  16826. }
  16827. if (!media || !mediaSource) {
  16828. return;
  16829. }
  16830. mediaSource.removeEventListener("sourceopen", this._onMediaSourceOpen);
  16831. media.removeEventListener("emptied", this._onMediaEmptied);
  16832. this.updateDuration();
  16833. this.hls.trigger(Events.MEDIA_ATTACHED, {
  16834. media,
  16835. mediaSource
  16836. });
  16837. if (this.mediaSource !== null) {
  16838. this.checkPendingTracks();
  16839. }
  16840. };
  16841. this._onMediaSourceClose = () => {
  16842. this.log("Media source closed");
  16843. };
  16844. this._onMediaSourceEnded = () => {
  16845. this.log("Media source ended");
  16846. };
  16847. this._onMediaEmptied = () => {
  16848. const {
  16849. mediaSrc,
  16850. _objectUrl
  16851. } = this;
  16852. if (mediaSrc !== _objectUrl) {
  16853. this.error(`Media element src was set while attaching MediaSource (${_objectUrl} > ${mediaSrc})`);
  16854. }
  16855. };
  16856. this.hls = hls;
  16857. this.fragmentTracker = fragmentTracker;
  16858. this.appendSource = isManagedMediaSource(getMediaSource(hls.config.preferManagedMediaSource));
  16859. this.initTracks();
  16860. this.registerListeners();
  16861. }
  16862. hasSourceTypes() {
  16863. return Object.keys(this.tracks).length > 0;
  16864. }
  16865. destroy() {
  16866. this.unregisterListeners();
  16867. this.details = null;
  16868. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  16869. this.transferData = this.overrides = void 0;
  16870. if (this.operationQueue) {
  16871. this.operationQueue.destroy();
  16872. this.operationQueue = null;
  16873. }
  16874. this.hls = this.fragmentTracker = null;
  16875. this._onMediaSourceOpen = this._onMediaSourceClose = null;
  16876. this._onMediaSourceEnded = null;
  16877. this._onStartStreaming = this._onEndStreaming = null;
  16878. }
  16879. registerListeners() {
  16880. const {
  16881. hls
  16882. } = this;
  16883. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  16884. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  16885. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16886. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  16887. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  16888. hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  16889. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  16890. hls.on(Events.BUFFER_EOS, this.onBufferEos, this);
  16891. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  16892. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  16893. hls.on(Events.FRAG_PARSED, this.onFragParsed, this);
  16894. hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);
  16895. hls.on(Events.ERROR, this.onError, this);
  16896. }
  16897. unregisterListeners() {
  16898. const {
  16899. hls
  16900. } = this;
  16901. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  16902. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  16903. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16904. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  16905. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  16906. hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  16907. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  16908. hls.off(Events.BUFFER_EOS, this.onBufferEos, this);
  16909. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  16910. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  16911. hls.off(Events.FRAG_PARSED, this.onFragParsed, this);
  16912. hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);
  16913. hls.off(Events.ERROR, this.onError, this);
  16914. }
  16915. transferMedia() {
  16916. const {
  16917. media,
  16918. mediaSource
  16919. } = this;
  16920. if (!media) {
  16921. return null;
  16922. }
  16923. const tracks = {};
  16924. if (this.operationQueue) {
  16925. const updating = this.isUpdating();
  16926. if (!updating) {
  16927. this.operationQueue.removeBlockers();
  16928. }
  16929. const queued = this.isQueued();
  16930. if (updating || queued) {
  16931. this.warn(`Transfering MediaSource with${queued ? " operations in queue" : ""}${updating ? " updating SourceBuffer(s)" : ""} ${this.operationQueue}`);
  16932. }
  16933. this.operationQueue.destroy();
  16934. }
  16935. const transferData = this.transferData;
  16936. if (!this.sourceBufferCount && transferData && transferData.mediaSource === mediaSource) {
  16937. _extends(tracks, transferData.tracks);
  16938. } else {
  16939. this.sourceBuffers.forEach((tuple) => {
  16940. const [type] = tuple;
  16941. if (type) {
  16942. tracks[type] = _extends({}, this.tracks[type]);
  16943. this.removeBuffer(type);
  16944. }
  16945. tuple[0] = tuple[1] = null;
  16946. });
  16947. }
  16948. return {
  16949. media,
  16950. mediaSource,
  16951. tracks
  16952. };
  16953. }
  16954. initTracks() {
  16955. const tracks = {};
  16956. this.sourceBuffers = [[null, null], [null, null]];
  16957. this.tracks = tracks;
  16958. this.resetQueue();
  16959. this.resetAppendErrors();
  16960. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  16961. this.lastVideoAppendEnd = 0;
  16962. }
  16963. onManifestLoading() {
  16964. this.bufferCodecEventsTotal = 0;
  16965. this.details = null;
  16966. }
  16967. onManifestParsed(event, data) {
  16968. var _this$transferData;
  16969. let codecEvents = 2;
  16970. if (data.audio && !data.video || !data.altAudio) {
  16971. codecEvents = 1;
  16972. }
  16973. this.bufferCodecEventsTotal = codecEvents;
  16974. this.log(`${codecEvents} bufferCodec event(s) expected.`);
  16975. if ((_this$transferData = this.transferData) != null && _this$transferData.mediaSource && this.sourceBufferCount && codecEvents) {
  16976. this.bufferCreated();
  16977. }
  16978. }
  16979. onMediaAttaching(event, data) {
  16980. const media = this.media = data.media;
  16981. this.transferData = this.overrides = void 0;
  16982. const MediaSource = getMediaSource(this.appendSource);
  16983. if (MediaSource) {
  16984. const transferringMedia = !!data.mediaSource;
  16985. if (transferringMedia || data.overrides) {
  16986. this.transferData = data;
  16987. this.overrides = data.overrides;
  16988. }
  16989. const ms = this.mediaSource = data.mediaSource || new MediaSource();
  16990. this.assignMediaSource(ms);
  16991. if (transferringMedia) {
  16992. this._objectUrl = media.src;
  16993. this.attachTransferred();
  16994. } else {
  16995. const objectUrl = this._objectUrl = self.URL.createObjectURL(ms);
  16996. if (this.appendSource) {
  16997. try {
  16998. media.removeAttribute("src");
  16999. const MMS = self.ManagedMediaSource;
  17000. media.disableRemotePlayback = media.disableRemotePlayback || MMS && ms instanceof MMS;
  17001. removeSourceChildren(media);
  17002. addSource(media, objectUrl);
  17003. media.load();
  17004. } catch (error) {
  17005. media.src = objectUrl;
  17006. }
  17007. } else {
  17008. media.src = objectUrl;
  17009. }
  17010. }
  17011. media.addEventListener("emptied", this._onMediaEmptied);
  17012. }
  17013. }
  17014. assignMediaSource(ms) {
  17015. var _this$transferData2, _ms$constructor;
  17016. 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}`);
  17017. ms.addEventListener("sourceopen", this._onMediaSourceOpen);
  17018. ms.addEventListener("sourceended", this._onMediaSourceEnded);
  17019. ms.addEventListener("sourceclose", this._onMediaSourceClose);
  17020. if (this.appendSource) {
  17021. ms.addEventListener("startstreaming", this._onStartStreaming);
  17022. ms.addEventListener("endstreaming", this._onEndStreaming);
  17023. }
  17024. }
  17025. attachTransferred() {
  17026. const media = this.media;
  17027. const data = this.transferData;
  17028. if (!data || !media) {
  17029. return;
  17030. }
  17031. const requiredTracks = this.tracks;
  17032. const transferredTracks = data.tracks;
  17033. const trackNames = transferredTracks ? Object.keys(transferredTracks) : null;
  17034. const trackCount = trackNames ? trackNames.length : 0;
  17035. const mediaSourceOpenCallback = () => {
  17036. Promise.resolve().then(() => {
  17037. if (this.media && this.mediaSourceOpenOrEnded) {
  17038. this._onMediaSourceOpen();
  17039. }
  17040. });
  17041. };
  17042. if (transferredTracks && trackNames && trackCount) {
  17043. if (!this.tracksReady) {
  17044. this.hls.config.startFragPrefetch = true;
  17045. this.log(`attachTransferred: waiting for SourceBuffer track info`);
  17046. return;
  17047. }
  17048. this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
  17049. required tracks: ${stringify(requiredTracks, (key, value) => key === "initSegment" ? void 0 : value)};
  17050. transfer tracks: ${stringify(transferredTracks, (key, value) => key === "initSegment" ? void 0 : value)}}`);
  17051. if (!isCompatibleTrackChange(transferredTracks, requiredTracks)) {
  17052. data.mediaSource = null;
  17053. data.tracks = void 0;
  17054. const currentTime = media.currentTime;
  17055. const details = this.details;
  17056. const startTime = Math.max(currentTime, (details == null ? void 0 : details.fragments[0].start) || 0);
  17057. if (startTime - currentTime > 1) {
  17058. this.log(`attachTransferred: waiting for playback to reach new tracks start time ${currentTime} -> ${startTime}`);
  17059. return;
  17060. }
  17061. this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(transferredTracks)}"->"${Object.keys(requiredTracks)}") start time: ${startTime} currentTime: ${currentTime}`);
  17062. this.onMediaDetaching(Events.MEDIA_DETACHING, {});
  17063. this.onMediaAttaching(Events.MEDIA_ATTACHING, data);
  17064. media.currentTime = startTime;
  17065. return;
  17066. }
  17067. this.transferData = void 0;
  17068. trackNames.forEach((trackName) => {
  17069. const type = trackName;
  17070. const track = transferredTracks[type];
  17071. if (track) {
  17072. const sb = track.buffer;
  17073. if (sb) {
  17074. const fragmentTracker = this.fragmentTracker;
  17075. const playlistType = track.id;
  17076. if (fragmentTracker.hasFragments(playlistType) || fragmentTracker.hasParts(playlistType)) {
  17077. const bufferedTimeRanges = BufferHelper.getBuffered(sb);
  17078. fragmentTracker.detectEvictedFragments(type, bufferedTimeRanges, playlistType, null, true);
  17079. }
  17080. const sbIndex = sourceBufferNameToIndex(type);
  17081. const sbTuple = [type, sb];
  17082. this.sourceBuffers[sbIndex] = sbTuple;
  17083. if (sb.updating && this.operationQueue) {
  17084. this.operationQueue.prependBlocker(type);
  17085. }
  17086. this.trackSourceBuffer(type, track);
  17087. }
  17088. }
  17089. });
  17090. mediaSourceOpenCallback();
  17091. this.bufferCreated();
  17092. } else {
  17093. this.log(`attachTransferred: MediaSource w/o SourceBuffers`);
  17094. mediaSourceOpenCallback();
  17095. }
  17096. }
  17097. get mediaSourceOpenOrEnded() {
  17098. var _this$mediaSource2;
  17099. const readyState = (_this$mediaSource2 = this.mediaSource) == null ? void 0 : _this$mediaSource2.readyState;
  17100. return readyState === "open" || readyState === "ended";
  17101. }
  17102. onMediaDetaching(event, data) {
  17103. const transferringMedia = !!data.transferMedia;
  17104. this.transferData = this.overrides = void 0;
  17105. const {
  17106. media,
  17107. mediaSource,
  17108. _objectUrl
  17109. } = this;
  17110. if (mediaSource) {
  17111. this.log(`media source ${transferringMedia ? "transferring" : "detaching"}`);
  17112. if (transferringMedia) {
  17113. this.sourceBuffers.forEach(([type]) => {
  17114. if (type) {
  17115. this.removeBuffer(type);
  17116. }
  17117. });
  17118. this.resetQueue();
  17119. } else {
  17120. if (this.mediaSourceOpenOrEnded) {
  17121. const open = mediaSource.readyState === "open";
  17122. try {
  17123. const sourceBuffers = mediaSource.sourceBuffers;
  17124. for (let i = sourceBuffers.length; i--; ) {
  17125. if (open) {
  17126. sourceBuffers[i].abort();
  17127. }
  17128. mediaSource.removeSourceBuffer(sourceBuffers[i]);
  17129. }
  17130. if (open) {
  17131. mediaSource.endOfStream();
  17132. }
  17133. } catch (err) {
  17134. this.warn(`onMediaDetaching: ${err.message} while calling endOfStream`);
  17135. }
  17136. }
  17137. if (this.sourceBufferCount) {
  17138. this.onBufferReset();
  17139. }
  17140. }
  17141. mediaSource.removeEventListener("sourceopen", this._onMediaSourceOpen);
  17142. mediaSource.removeEventListener("sourceended", this._onMediaSourceEnded);
  17143. mediaSource.removeEventListener("sourceclose", this._onMediaSourceClose);
  17144. if (this.appendSource) {
  17145. mediaSource.removeEventListener("startstreaming", this._onStartStreaming);
  17146. mediaSource.removeEventListener("endstreaming", this._onEndStreaming);
  17147. }
  17148. this.mediaSource = null;
  17149. this._objectUrl = null;
  17150. }
  17151. if (media) {
  17152. media.removeEventListener("emptied", this._onMediaEmptied);
  17153. if (!transferringMedia) {
  17154. if (_objectUrl) {
  17155. self.URL.revokeObjectURL(_objectUrl);
  17156. }
  17157. if (this.mediaSrc === _objectUrl) {
  17158. media.removeAttribute("src");
  17159. if (this.appendSource) {
  17160. removeSourceChildren(media);
  17161. }
  17162. media.load();
  17163. } else {
  17164. this.warn("media|source.src was changed by a third party - skip cleanup");
  17165. }
  17166. }
  17167. this.media = null;
  17168. }
  17169. this.hls.trigger(Events.MEDIA_DETACHED, data);
  17170. }
  17171. onBufferReset() {
  17172. this.sourceBuffers.forEach(([type]) => {
  17173. if (type) {
  17174. this.resetBuffer(type);
  17175. }
  17176. });
  17177. this.initTracks();
  17178. }
  17179. resetBuffer(type) {
  17180. var _this$tracks$type;
  17181. const sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  17182. this.removeBuffer(type);
  17183. if (sb) {
  17184. try {
  17185. var _this$mediaSource3;
  17186. if ((_this$mediaSource3 = this.mediaSource) != null && _this$mediaSource3.sourceBuffers.length) {
  17187. this.mediaSource.removeSourceBuffer(sb);
  17188. }
  17189. } catch (err) {
  17190. this.warn(`onBufferReset ${type}`, err);
  17191. }
  17192. }
  17193. delete this.tracks[type];
  17194. }
  17195. removeBuffer(type) {
  17196. this.removeBufferListeners(type);
  17197. this.sourceBuffers[sourceBufferNameToIndex(type)] = [null, null];
  17198. const track = this.tracks[type];
  17199. if (track) {
  17200. track.buffer = void 0;
  17201. }
  17202. }
  17203. resetQueue() {
  17204. if (this.operationQueue) {
  17205. this.operationQueue.destroy();
  17206. }
  17207. this.operationQueue = new BufferOperationQueue(this.tracks);
  17208. }
  17209. onBufferCodecs(event, data) {
  17210. var _data$audio;
  17211. const tracks = this.tracks;
  17212. const trackNames = Object.keys(data);
  17213. this.log(`BUFFER_CODECS: "${trackNames}" (current SB count ${this.sourceBufferCount})`);
  17214. const unmuxedToMuxed = "audiovideo" in data && (tracks.audio || tracks.video) || tracks.audiovideo && ("audio" in data || "video" in data);
  17215. const muxedToUnmuxed = !unmuxedToMuxed && this.sourceBufferCount && this.media && trackNames.some((sbName) => !tracks[sbName]);
  17216. if (unmuxedToMuxed || muxedToUnmuxed) {
  17217. this.warn(`Unsupported transition between "${Object.keys(tracks)}" and "${trackNames}" SourceBuffers`);
  17218. return;
  17219. }
  17220. trackNames.forEach((trackName) => {
  17221. var _this$transferData3, _trackCodec;
  17222. const parsedTrack = data[trackName];
  17223. const {
  17224. id,
  17225. codec,
  17226. levelCodec,
  17227. container,
  17228. metadata,
  17229. supplemental
  17230. } = parsedTrack;
  17231. let track = tracks[trackName];
  17232. const transferredTrack = (_this$transferData3 = this.transferData) == null || (_this$transferData3 = _this$transferData3.tracks) == null ? void 0 : _this$transferData3[trackName];
  17233. const sbTrack = transferredTrack != null && transferredTrack.buffer ? transferredTrack : track;
  17234. const sbCodec = (sbTrack == null ? void 0 : sbTrack.pendingCodec) || (sbTrack == null ? void 0 : sbTrack.codec);
  17235. const trackLevelCodec = sbTrack == null ? void 0 : sbTrack.levelCodec;
  17236. if (!track) {
  17237. track = tracks[trackName] = {
  17238. buffer: void 0,
  17239. listeners: [],
  17240. codec,
  17241. supplemental,
  17242. container,
  17243. levelCodec,
  17244. metadata,
  17245. id
  17246. };
  17247. }
  17248. const currentCodecFull = pickMostCompleteCodecName(sbCodec, trackLevelCodec);
  17249. const currentCodec = currentCodecFull == null ? void 0 : currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE, "$1");
  17250. let trackCodec = pickMostCompleteCodecName(codec, levelCodec);
  17251. const nextCodec = (_trackCodec = trackCodec) == null ? void 0 : _trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE, "$1");
  17252. if (trackCodec && currentCodecFull && currentCodec !== nextCodec) {
  17253. if (trackName.slice(0, 5) === "audio") {
  17254. trackCodec = getCodecCompatibleName(trackCodec, this.appendSource);
  17255. }
  17256. this.log(`switching codec ${sbCodec} to ${trackCodec}`);
  17257. if (trackCodec !== (track.pendingCodec || track.codec)) {
  17258. track.pendingCodec = trackCodec;
  17259. }
  17260. track.container = container;
  17261. this.appendChangeType(trackName, container, trackCodec);
  17262. }
  17263. });
  17264. if (this.tracksReady || this.sourceBufferCount) {
  17265. data.tracks = this.sourceBufferTracks;
  17266. }
  17267. if (this.sourceBufferCount) {
  17268. return;
  17269. }
  17270. if (this.bufferCodecEventsTotal > 1 && !this.tracks.video && !data.video && ((_data$audio = data.audio) == null ? void 0 : _data$audio.id) === "main") {
  17271. this.log(`Main audio-only`);
  17272. this.bufferCodecEventsTotal = 1;
  17273. }
  17274. if (this.mediaSourceOpenOrEnded) {
  17275. this.checkPendingTracks();
  17276. }
  17277. }
  17278. get sourceBufferTracks() {
  17279. return Object.keys(this.tracks).reduce((baseTracks, type) => {
  17280. const track = this.tracks[type];
  17281. baseTracks[type] = {
  17282. id: track.id,
  17283. container: track.container,
  17284. codec: track.codec,
  17285. levelCodec: track.levelCodec
  17286. };
  17287. return baseTracks;
  17288. }, {});
  17289. }
  17290. appendChangeType(type, container, codec) {
  17291. const mimeType = `${container};codecs=${codec}`;
  17292. const operation = {
  17293. label: `change-type=${mimeType}`,
  17294. execute: () => {
  17295. const track = this.tracks[type];
  17296. if (track) {
  17297. const sb = track.buffer;
  17298. if (sb != null && sb.changeType) {
  17299. this.log(`changing ${type} sourceBuffer type to ${mimeType}`);
  17300. sb.changeType(mimeType);
  17301. track.codec = codec;
  17302. track.container = container;
  17303. }
  17304. }
  17305. this.shiftAndExecuteNext(type);
  17306. },
  17307. onStart: () => {
  17308. },
  17309. onComplete: () => {
  17310. },
  17311. onError: (error) => {
  17312. this.warn(`Failed to change ${type} SourceBuffer type`, error);
  17313. }
  17314. };
  17315. this.append(operation, type, this.isPending(this.tracks[type]));
  17316. }
  17317. blockAudio(partOrFrag) {
  17318. var _this$fragmentTracker;
  17319. const pStart = partOrFrag.start;
  17320. const pTime = pStart + partOrFrag.duration * 0.05;
  17321. const atGap = ((_this$fragmentTracker = this.fragmentTracker.getAppendedFrag(pStart, PlaylistLevelType.MAIN)) == null ? void 0 : _this$fragmentTracker.gap) === true;
  17322. if (atGap) {
  17323. return;
  17324. }
  17325. const op = {
  17326. label: "block-audio",
  17327. execute: () => {
  17328. var _this$fragmentTracker2;
  17329. const videoTrack = this.tracks.video;
  17330. 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) {
  17331. this.blockedAudioAppend = null;
  17332. this.shiftAndExecuteNext("audio");
  17333. }
  17334. },
  17335. onStart: () => {
  17336. },
  17337. onComplete: () => {
  17338. },
  17339. onError: (error) => {
  17340. this.warn("Error executing block-audio operation", error);
  17341. }
  17342. };
  17343. this.blockedAudioAppend = {
  17344. op,
  17345. frag: partOrFrag
  17346. };
  17347. this.append(op, "audio", true);
  17348. }
  17349. unblockAudio() {
  17350. const {
  17351. blockedAudioAppend,
  17352. operationQueue
  17353. } = this;
  17354. if (blockedAudioAppend && operationQueue) {
  17355. this.blockedAudioAppend = null;
  17356. operationQueue.unblockAudio(blockedAudioAppend.op);
  17357. }
  17358. }
  17359. onBufferAppending(event, eventData) {
  17360. const {
  17361. tracks
  17362. } = this;
  17363. const {
  17364. data,
  17365. type,
  17366. parent,
  17367. frag,
  17368. part,
  17369. chunkMeta,
  17370. offset
  17371. } = eventData;
  17372. const chunkStats = chunkMeta.buffering[type];
  17373. const {
  17374. sn,
  17375. cc
  17376. } = frag;
  17377. const bufferAppendingStart = self.performance.now();
  17378. chunkStats.start = bufferAppendingStart;
  17379. const fragBuffering = frag.stats.buffering;
  17380. const partBuffering = part ? part.stats.buffering : null;
  17381. if (fragBuffering.start === 0) {
  17382. fragBuffering.start = bufferAppendingStart;
  17383. }
  17384. if (partBuffering && partBuffering.start === 0) {
  17385. partBuffering.start = bufferAppendingStart;
  17386. }
  17387. const audioTrack = tracks.audio;
  17388. let checkTimestampOffset = false;
  17389. if (type === "audio" && (audioTrack == null ? void 0 : audioTrack.container) === "audio/mpeg") {
  17390. checkTimestampOffset = !this.lastMpegAudioChunk || chunkMeta.id === 1 || this.lastMpegAudioChunk.sn !== chunkMeta.sn;
  17391. this.lastMpegAudioChunk = chunkMeta;
  17392. }
  17393. const videoTrack = tracks.video;
  17394. const videoSb = videoTrack == null ? void 0 : videoTrack.buffer;
  17395. if (videoSb && sn !== "initSegment") {
  17396. const partOrFrag = part || frag;
  17397. const blockedAudioAppend = this.blockedAudioAppend;
  17398. if (type === "audio" && parent !== "main" && !this.blockedAudioAppend && !(videoTrack.ending || videoTrack.ended)) {
  17399. const pStart = partOrFrag.start;
  17400. const pTime = pStart + partOrFrag.duration * 0.05;
  17401. const vbuffered = videoSb.buffered;
  17402. const vappending = this.currentOp("video");
  17403. if (!vbuffered.length && !vappending) {
  17404. this.blockAudio(partOrFrag);
  17405. } else if (!vappending && !BufferHelper.isBuffered(videoSb, pTime) && this.lastVideoAppendEnd < pTime) {
  17406. this.blockAudio(partOrFrag);
  17407. }
  17408. } else if (type === "video") {
  17409. const videoAppendEnd = partOrFrag.end;
  17410. if (blockedAudioAppend) {
  17411. const audioStart = blockedAudioAppend.frag.start;
  17412. if (videoAppendEnd > audioStart || videoAppendEnd < this.lastVideoAppendEnd || BufferHelper.isBuffered(videoSb, audioStart)) {
  17413. this.unblockAudio();
  17414. }
  17415. }
  17416. this.lastVideoAppendEnd = videoAppendEnd;
  17417. }
  17418. }
  17419. const fragStart = (part || frag).start;
  17420. const operation = {
  17421. label: `append-${type}`,
  17422. execute: () => {
  17423. var _this$tracks$type2;
  17424. chunkStats.executeStart = self.performance.now();
  17425. const sb = (_this$tracks$type2 = this.tracks[type]) == null ? void 0 : _this$tracks$type2.buffer;
  17426. if (sb) {
  17427. if (checkTimestampOffset) {
  17428. this.updateTimestampOffset(sb, fragStart, 0.1, type, sn, cc);
  17429. } else if (offset !== void 0 && isFiniteNumber(offset)) {
  17430. this.updateTimestampOffset(sb, offset, 1e-6, type, sn, cc);
  17431. }
  17432. }
  17433. this.appendExecutor(data, type);
  17434. },
  17435. onStart: () => {
  17436. },
  17437. onComplete: () => {
  17438. const end = self.performance.now();
  17439. chunkStats.executeEnd = chunkStats.end = end;
  17440. if (fragBuffering.first === 0) {
  17441. fragBuffering.first = end;
  17442. }
  17443. if (partBuffering && partBuffering.first === 0) {
  17444. partBuffering.first = end;
  17445. }
  17446. const timeRanges = {};
  17447. this.sourceBuffers.forEach(([type2, sb]) => {
  17448. if (type2) {
  17449. timeRanges[type2] = BufferHelper.getBuffered(sb);
  17450. }
  17451. });
  17452. this.appendErrors[type] = 0;
  17453. if (type === "audio" || type === "video") {
  17454. this.appendErrors.audiovideo = 0;
  17455. } else {
  17456. this.appendErrors.audio = 0;
  17457. this.appendErrors.video = 0;
  17458. }
  17459. this.hls.trigger(Events.BUFFER_APPENDED, {
  17460. type,
  17461. frag,
  17462. part,
  17463. chunkMeta,
  17464. parent: frag.type,
  17465. timeRanges
  17466. });
  17467. },
  17468. onError: (error) => {
  17469. var _this$media;
  17470. const event2 = {
  17471. type: ErrorTypes.MEDIA_ERROR,
  17472. parent: frag.type,
  17473. details: ErrorDetails.BUFFER_APPEND_ERROR,
  17474. sourceBufferName: type,
  17475. frag,
  17476. part,
  17477. chunkMeta,
  17478. error,
  17479. err: error,
  17480. fatal: false
  17481. };
  17482. const mediaError = (_this$media = this.media) == null ? void 0 : _this$media.error;
  17483. if (error.code === DOMException.QUOTA_EXCEEDED_ERR || error.name == "QuotaExceededError" || `quota` in error) {
  17484. event2.details = ErrorDetails.BUFFER_FULL_ERROR;
  17485. } else if (error.code === DOMException.INVALID_STATE_ERR && this.mediaSourceOpenOrEnded && !mediaError) {
  17486. event2.errorAction = createDoNothingErrorAction(true);
  17487. } else if (error.name === TRACK_REMOVED_ERROR_NAME && this.sourceBufferCount === 0) {
  17488. event2.errorAction = createDoNothingErrorAction(true);
  17489. } else {
  17490. const appendErrorCount = ++this.appendErrors[type];
  17491. this.warn(`Failed ${appendErrorCount}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${type}" sourceBuffer (${mediaError ? mediaError : "no media error"})`);
  17492. if (appendErrorCount >= this.hls.config.appendErrorMaxRetry || !!mediaError) {
  17493. event2.fatal = true;
  17494. }
  17495. }
  17496. this.hls.trigger(Events.ERROR, event2);
  17497. }
  17498. };
  17499. this.log(`queuing "${type}" append sn: ${sn}${part ? " p: " + part.index : ""} of ${frag.type === PlaylistLevelType.MAIN ? "level" : "track"} ${frag.level} cc: ${cc}`);
  17500. this.append(operation, type, this.isPending(this.tracks[type]));
  17501. }
  17502. getFlushOp(type, start, end) {
  17503. this.log(`queuing "${type}" remove ${start}-${end}`);
  17504. return {
  17505. label: "remove",
  17506. execute: () => {
  17507. this.removeExecutor(type, start, end);
  17508. },
  17509. onStart: () => {
  17510. },
  17511. onComplete: () => {
  17512. this.hls.trigger(Events.BUFFER_FLUSHED, {
  17513. type
  17514. });
  17515. },
  17516. onError: (error) => {
  17517. this.warn(`Failed to remove ${start}-${end} from "${type}" SourceBuffer`, error);
  17518. }
  17519. };
  17520. }
  17521. onBufferFlushing(event, data) {
  17522. const {
  17523. type,
  17524. startOffset,
  17525. endOffset
  17526. } = data;
  17527. if (type) {
  17528. this.append(this.getFlushOp(type, startOffset, endOffset), type);
  17529. } else {
  17530. this.sourceBuffers.forEach(([type2]) => {
  17531. if (type2) {
  17532. this.append(this.getFlushOp(type2, startOffset, endOffset), type2);
  17533. }
  17534. });
  17535. }
  17536. }
  17537. onFragParsed(event, data) {
  17538. const {
  17539. frag,
  17540. part
  17541. } = data;
  17542. const buffersAppendedTo = [];
  17543. const elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
  17544. if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {
  17545. buffersAppendedTo.push("audiovideo");
  17546. } else {
  17547. if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {
  17548. buffersAppendedTo.push("audio");
  17549. }
  17550. if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {
  17551. buffersAppendedTo.push("video");
  17552. }
  17553. }
  17554. const onUnblocked = () => {
  17555. const now2 = self.performance.now();
  17556. frag.stats.buffering.end = now2;
  17557. if (part) {
  17558. part.stats.buffering.end = now2;
  17559. }
  17560. const stats = part ? part.stats : frag.stats;
  17561. this.hls.trigger(Events.FRAG_BUFFERED, {
  17562. frag,
  17563. part,
  17564. stats,
  17565. id: frag.type
  17566. });
  17567. };
  17568. if (buffersAppendedTo.length === 0) {
  17569. this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${frag.type} level: ${frag.level} sn: ${frag.sn}`);
  17570. }
  17571. this.blockBuffers(onUnblocked, buffersAppendedTo).catch((error) => {
  17572. this.warn(`Fragment buffered callback ${error}`);
  17573. this.stepOperationQueue(this.sourceBufferTypes);
  17574. });
  17575. }
  17576. onFragChanged(event, data) {
  17577. this.trimBuffers();
  17578. }
  17579. get bufferedToEnd() {
  17580. return this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type]) => {
  17581. if (type) {
  17582. const track = this.tracks[type];
  17583. if (track) {
  17584. return !track.ended || track.ending;
  17585. }
  17586. }
  17587. return false;
  17588. });
  17589. }
  17590. // on BUFFER_EOS mark matching sourcebuffer(s) as "ending" and "ended" and queue endOfStream after remaining operations(s)
  17591. // an undefined data.type will mark all buffers as EOS.
  17592. onBufferEos(event, data) {
  17593. var _this$overrides;
  17594. this.sourceBuffers.forEach(([type]) => {
  17595. if (type) {
  17596. const track = this.tracks[type];
  17597. if (!data.type || data.type === type) {
  17598. track.ending = true;
  17599. if (!track.ended) {
  17600. track.ended = true;
  17601. this.log(`${type} buffer reached EOS`);
  17602. }
  17603. }
  17604. }
  17605. });
  17606. const allowEndOfStream = ((_this$overrides = this.overrides) == null ? void 0 : _this$overrides.endOfStream) !== false;
  17607. const allTracksEnding = this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type]) => {
  17608. var _this$tracks$type3;
  17609. return type && !((_this$tracks$type3 = this.tracks[type]) != null && _this$tracks$type3.ended);
  17610. });
  17611. if (allTracksEnding) {
  17612. if (allowEndOfStream) {
  17613. this.log(`Queueing EOS`);
  17614. this.blockUntilOpen(() => {
  17615. this.tracksEnded();
  17616. const {
  17617. mediaSource
  17618. } = this;
  17619. if (!mediaSource || mediaSource.readyState !== "open") {
  17620. if (mediaSource) {
  17621. this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${mediaSource.readyState}`);
  17622. }
  17623. return;
  17624. }
  17625. this.log(`Calling mediaSource.endOfStream()`);
  17626. mediaSource.endOfStream();
  17627. this.hls.trigger(Events.BUFFERED_TO_END, void 0);
  17628. });
  17629. } else {
  17630. this.tracksEnded();
  17631. this.hls.trigger(Events.BUFFERED_TO_END, void 0);
  17632. }
  17633. } else if (data.type === "video") {
  17634. this.unblockAudio();
  17635. }
  17636. }
  17637. tracksEnded() {
  17638. this.sourceBuffers.forEach(([type]) => {
  17639. if (type !== null) {
  17640. const track = this.tracks[type];
  17641. if (track) {
  17642. track.ending = false;
  17643. }
  17644. }
  17645. });
  17646. }
  17647. onLevelUpdated(event, {
  17648. details
  17649. }) {
  17650. if (!details.fragments.length) {
  17651. return;
  17652. }
  17653. this.details = details;
  17654. this.updateDuration();
  17655. }
  17656. updateDuration() {
  17657. this.blockUntilOpen(() => {
  17658. const durationAndRange = this.getDurationAndRange();
  17659. if (!durationAndRange) {
  17660. return;
  17661. }
  17662. this.updateMediaSource(durationAndRange);
  17663. });
  17664. }
  17665. onError(event, data) {
  17666. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && data.frag) {
  17667. var _data$errorAction;
  17668. const nextAutoLevel = (_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.nextAutoLevel;
  17669. if (isFiniteNumber(nextAutoLevel) && nextAutoLevel !== data.frag.level) {
  17670. this.resetAppendErrors();
  17671. }
  17672. }
  17673. }
  17674. resetAppendErrors() {
  17675. this.appendErrors = {
  17676. audio: 0,
  17677. video: 0,
  17678. audiovideo: 0
  17679. };
  17680. }
  17681. trimBuffers() {
  17682. const {
  17683. hls,
  17684. details,
  17685. media
  17686. } = this;
  17687. if (!media || details === null) {
  17688. return;
  17689. }
  17690. if (!this.sourceBufferCount) {
  17691. return;
  17692. }
  17693. const config = hls.config;
  17694. const currentTime = media.currentTime;
  17695. const targetDuration = details.levelTargetDuration;
  17696. const backBufferLength = details.live && config.liveBackBufferLength !== null ? config.liveBackBufferLength : config.backBufferLength;
  17697. if (isFiniteNumber(backBufferLength) && backBufferLength >= 0) {
  17698. const maxBackBufferLength = Math.max(backBufferLength, targetDuration);
  17699. const targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
  17700. this.flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition);
  17701. }
  17702. const frontBufferFlushThreshold = config.frontBufferFlushThreshold;
  17703. if (isFiniteNumber(frontBufferFlushThreshold) && frontBufferFlushThreshold > 0) {
  17704. const frontBufferLength = Math.max(config.maxBufferLength, frontBufferFlushThreshold);
  17705. const maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);
  17706. const targetFrontBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration + maxFrontBufferLength;
  17707. this.flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition);
  17708. }
  17709. }
  17710. flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition) {
  17711. this.sourceBuffers.forEach(([type, sb]) => {
  17712. if (sb) {
  17713. const buffered = BufferHelper.getBuffered(sb);
  17714. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  17715. var _this$details;
  17716. this.hls.trigger(Events.BACK_BUFFER_REACHED, {
  17717. bufferEnd: targetBackBufferPosition
  17718. });
  17719. const track = this.tracks[type];
  17720. if ((_this$details = this.details) != null && _this$details.live) {
  17721. this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {
  17722. bufferEnd: targetBackBufferPosition
  17723. });
  17724. } else if (track != null && track.ended) {
  17725. this.log(`Cannot flush ${type} back buffer while SourceBuffer is in ended state`);
  17726. return;
  17727. }
  17728. this.hls.trigger(Events.BUFFER_FLUSHING, {
  17729. startOffset: 0,
  17730. endOffset: targetBackBufferPosition,
  17731. type
  17732. });
  17733. }
  17734. }
  17735. });
  17736. }
  17737. flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition) {
  17738. this.sourceBuffers.forEach(([type, sb]) => {
  17739. if (sb) {
  17740. const buffered = BufferHelper.getBuffered(sb);
  17741. const numBufferedRanges = buffered.length;
  17742. if (numBufferedRanges < 2) {
  17743. return;
  17744. }
  17745. const bufferStart = buffered.start(numBufferedRanges - 1);
  17746. const bufferEnd = buffered.end(numBufferedRanges - 1);
  17747. if (targetFrontBufferPosition > bufferStart || currentTime >= bufferStart && currentTime <= bufferEnd) {
  17748. return;
  17749. }
  17750. this.hls.trigger(Events.BUFFER_FLUSHING, {
  17751. startOffset: bufferStart,
  17752. endOffset: Infinity,
  17753. type
  17754. });
  17755. }
  17756. });
  17757. }
  17758. /**
  17759. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  17760. * 'liveDurationInfinity` is set to `true`
  17761. * More details: https://github.com/video-dev/hls.js/issues/355
  17762. */
  17763. getDurationAndRange() {
  17764. var _this$overrides2;
  17765. const {
  17766. details,
  17767. mediaSource
  17768. } = this;
  17769. if (!details || !this.media || (mediaSource == null ? void 0 : mediaSource.readyState) !== "open") {
  17770. return null;
  17771. }
  17772. const playlistEnd = details.edge;
  17773. if (details.live && this.hls.config.liveDurationInfinity) {
  17774. const len = details.fragments.length;
  17775. if (len && !!mediaSource.setLiveSeekableRange) {
  17776. const start = Math.max(0, details.fragmentStart);
  17777. const end = Math.max(start, playlistEnd);
  17778. return {
  17779. duration: Infinity,
  17780. start,
  17781. end
  17782. };
  17783. }
  17784. return {
  17785. duration: Infinity
  17786. };
  17787. }
  17788. const overrideDuration = (_this$overrides2 = this.overrides) == null ? void 0 : _this$overrides2.duration;
  17789. if (overrideDuration) {
  17790. if (!isFiniteNumber(overrideDuration)) {
  17791. return null;
  17792. }
  17793. return {
  17794. duration: overrideDuration
  17795. };
  17796. }
  17797. const mediaDuration = this.media.duration;
  17798. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : 0;
  17799. if (playlistEnd > msDuration && playlistEnd > mediaDuration || !isFiniteNumber(mediaDuration)) {
  17800. return {
  17801. duration: playlistEnd
  17802. };
  17803. }
  17804. return null;
  17805. }
  17806. updateMediaSource({
  17807. duration,
  17808. start,
  17809. end
  17810. }) {
  17811. const mediaSource = this.mediaSource;
  17812. if (!this.media || !mediaSource || mediaSource.readyState !== "open") {
  17813. return;
  17814. }
  17815. if (mediaSource.duration !== duration) {
  17816. if (isFiniteNumber(duration)) {
  17817. this.log(`Updating MediaSource duration to ${duration.toFixed(3)}`);
  17818. }
  17819. mediaSource.duration = duration;
  17820. }
  17821. if (start !== void 0 && end !== void 0) {
  17822. this.log(`MediaSource duration is set to ${mediaSource.duration}. Setting seekable range to ${start}-${end}.`);
  17823. mediaSource.setLiveSeekableRange(start, end);
  17824. }
  17825. }
  17826. get tracksReady() {
  17827. const pendingTrackCount = this.pendingTrackCount;
  17828. return pendingTrackCount > 0 && (pendingTrackCount >= this.bufferCodecEventsTotal || this.isPending(this.tracks.audiovideo));
  17829. }
  17830. checkPendingTracks() {
  17831. const {
  17832. bufferCodecEventsTotal,
  17833. pendingTrackCount,
  17834. tracks
  17835. } = this;
  17836. this.log(`checkPendingTracks (pending: ${pendingTrackCount} codec events expected: ${bufferCodecEventsTotal}) ${stringify(tracks)}`);
  17837. if (this.tracksReady) {
  17838. var _this$transferData4;
  17839. const transferredTracks = (_this$transferData4 = this.transferData) == null ? void 0 : _this$transferData4.tracks;
  17840. if (transferredTracks && Object.keys(transferredTracks).length) {
  17841. this.attachTransferred();
  17842. } else {
  17843. this.createSourceBuffers();
  17844. }
  17845. }
  17846. }
  17847. bufferCreated() {
  17848. if (this.sourceBufferCount) {
  17849. const tracks = {};
  17850. this.sourceBuffers.forEach(([type, buffer]) => {
  17851. if (type) {
  17852. const track = this.tracks[type];
  17853. tracks[type] = {
  17854. buffer,
  17855. container: track.container,
  17856. codec: track.codec,
  17857. supplemental: track.supplemental,
  17858. levelCodec: track.levelCodec,
  17859. id: track.id,
  17860. metadata: track.metadata
  17861. };
  17862. }
  17863. });
  17864. this.hls.trigger(Events.BUFFER_CREATED, {
  17865. tracks
  17866. });
  17867. this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`);
  17868. this.sourceBuffers.forEach(([type]) => {
  17869. this.executeNext(type);
  17870. });
  17871. } else {
  17872. const error = new Error("could not create source buffer for media codec(s)");
  17873. this.hls.trigger(Events.ERROR, {
  17874. type: ErrorTypes.MEDIA_ERROR,
  17875. details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,
  17876. fatal: true,
  17877. error,
  17878. reason: error.message
  17879. });
  17880. }
  17881. }
  17882. createSourceBuffers() {
  17883. const {
  17884. tracks,
  17885. sourceBuffers,
  17886. mediaSource
  17887. } = this;
  17888. if (!mediaSource) {
  17889. throw new Error("createSourceBuffers called when mediaSource was null");
  17890. }
  17891. for (const trackName in tracks) {
  17892. const type = trackName;
  17893. const track = tracks[type];
  17894. if (this.isPending(track)) {
  17895. const codec = this.getTrackCodec(track, type);
  17896. const mimeType = `${track.container};codecs=${codec}`;
  17897. track.codec = codec;
  17898. this.log(`creating sourceBuffer(${mimeType})${this.currentOp(type) ? " Queued" : ""} ${stringify(track)}`);
  17899. try {
  17900. const sb = mediaSource.addSourceBuffer(mimeType);
  17901. const sbIndex = sourceBufferNameToIndex(type);
  17902. const sbTuple = [type, sb];
  17903. sourceBuffers[sbIndex] = sbTuple;
  17904. track.buffer = sb;
  17905. } catch (error) {
  17906. var _this$operationQueue;
  17907. this.error(`error while trying to add sourceBuffer: ${error.message}`);
  17908. this.shiftAndExecuteNext(type);
  17909. (_this$operationQueue = this.operationQueue) == null || _this$operationQueue.removeBlockers();
  17910. delete this.tracks[type];
  17911. this.hls.trigger(Events.ERROR, {
  17912. type: ErrorTypes.MEDIA_ERROR,
  17913. details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,
  17914. fatal: false,
  17915. error,
  17916. sourceBufferName: type,
  17917. mimeType,
  17918. parent: track.id
  17919. });
  17920. return;
  17921. }
  17922. this.trackSourceBuffer(type, track);
  17923. }
  17924. }
  17925. this.bufferCreated();
  17926. }
  17927. getTrackCodec(track, trackName) {
  17928. const supplementalCodec = track.supplemental;
  17929. let trackCodec = track.codec;
  17930. if (supplementalCodec && (trackName === "video" || trackName === "audiovideo") && areCodecsMediaSourceSupported(supplementalCodec, "video")) {
  17931. trackCodec = replaceVideoCodec(trackCodec, supplementalCodec);
  17932. }
  17933. const codec = pickMostCompleteCodecName(trackCodec, track.levelCodec);
  17934. if (codec) {
  17935. if (trackName.slice(0, 5) === "audio") {
  17936. return getCodecCompatibleName(codec, this.appendSource);
  17937. }
  17938. return codec;
  17939. }
  17940. return "";
  17941. }
  17942. trackSourceBuffer(type, track) {
  17943. const buffer = track.buffer;
  17944. if (!buffer) {
  17945. return;
  17946. }
  17947. const codec = this.getTrackCodec(track, type);
  17948. this.tracks[type] = {
  17949. buffer,
  17950. codec,
  17951. container: track.container,
  17952. levelCodec: track.levelCodec,
  17953. supplemental: track.supplemental,
  17954. metadata: track.metadata,
  17955. id: track.id,
  17956. listeners: []
  17957. };
  17958. this.removeBufferListeners(type);
  17959. this.addBufferListener(type, "updatestart", this.onSBUpdateStart);
  17960. this.addBufferListener(type, "updateend", this.onSBUpdateEnd);
  17961. this.addBufferListener(type, "error", this.onSBUpdateError);
  17962. if (this.appendSource) {
  17963. this.addBufferListener(type, "bufferedchange", (type2, event) => {
  17964. const removedRanges = event.removedRanges;
  17965. if (removedRanges != null && removedRanges.length) {
  17966. this.hls.trigger(Events.BUFFER_FLUSHED, {
  17967. type: type2
  17968. });
  17969. }
  17970. });
  17971. }
  17972. }
  17973. get mediaSrc() {
  17974. var _this$media2, _this$media2$querySel;
  17975. const media = ((_this$media2 = this.media) == null || (_this$media2$querySel = _this$media2.querySelector) == null ? void 0 : _this$media2$querySel.call(_this$media2, "source")) || this.media;
  17976. return media == null ? void 0 : media.src;
  17977. }
  17978. onSBUpdateStart(type) {
  17979. const operation = this.currentOp(type);
  17980. if (!operation) {
  17981. return;
  17982. }
  17983. operation.onStart();
  17984. }
  17985. onSBUpdateEnd(type) {
  17986. var _this$mediaSource4;
  17987. if (((_this$mediaSource4 = this.mediaSource) == null ? void 0 : _this$mediaSource4.readyState) === "closed") {
  17988. this.resetBuffer(type);
  17989. return;
  17990. }
  17991. const operation = this.currentOp(type);
  17992. if (!operation) {
  17993. return;
  17994. }
  17995. operation.onComplete();
  17996. this.shiftAndExecuteNext(type);
  17997. }
  17998. onSBUpdateError(type, event) {
  17999. var _this$mediaSource5;
  18000. const error = new Error(`${type} SourceBuffer error. MediaSource readyState: ${(_this$mediaSource5 = this.mediaSource) == null ? void 0 : _this$mediaSource5.readyState}`);
  18001. this.error(`${error}`, event);
  18002. this.hls.trigger(Events.ERROR, {
  18003. type: ErrorTypes.MEDIA_ERROR,
  18004. details: ErrorDetails.BUFFER_APPENDING_ERROR,
  18005. sourceBufferName: type,
  18006. error,
  18007. fatal: false
  18008. });
  18009. const operation = this.currentOp(type);
  18010. if (operation) {
  18011. operation.onError(error);
  18012. }
  18013. }
  18014. updateTimestampOffset(sb, timestampOffset, tolerance, type, sn, cc) {
  18015. const delta = timestampOffset - sb.timestampOffset;
  18016. if (Math.abs(delta) >= tolerance) {
  18017. this.log(`Updating ${type} SourceBuffer timestampOffset to ${timestampOffset} (sn: ${sn} cc: ${cc})`);
  18018. sb.timestampOffset = timestampOffset;
  18019. }
  18020. }
  18021. // This method must result in an updateend event; if remove is not called, onSBUpdateEnd must be called manually
  18022. removeExecutor(type, startOffset, endOffset) {
  18023. const {
  18024. media,
  18025. mediaSource
  18026. } = this;
  18027. const track = this.tracks[type];
  18028. const sb = track == null ? void 0 : track.buffer;
  18029. if (!media || !mediaSource || !sb) {
  18030. this.warn(`Attempting to remove from the ${type} SourceBuffer, but it does not exist`);
  18031. this.shiftAndExecuteNext(type);
  18032. return;
  18033. }
  18034. const mediaDuration = isFiniteNumber(media.duration) ? media.duration : Infinity;
  18035. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : Infinity;
  18036. const removeStart = Math.max(0, startOffset);
  18037. const removeEnd = Math.min(endOffset, mediaDuration, msDuration);
  18038. if (removeEnd > removeStart && (!track.ending || track.ended)) {
  18039. track.ended = false;
  18040. this.log(`Removing [${removeStart},${removeEnd}] from the ${type} SourceBuffer`);
  18041. sb.remove(removeStart, removeEnd);
  18042. } else {
  18043. this.shiftAndExecuteNext(type);
  18044. }
  18045. }
  18046. // This method must result in an updateend event; if append is not called, onSBUpdateEnd must be called manually
  18047. appendExecutor(data, type) {
  18048. const track = this.tracks[type];
  18049. const sb = track == null ? void 0 : track.buffer;
  18050. if (!sb) {
  18051. throw new HlsJsTrackRemovedError(`Attempting to append to the ${type} SourceBuffer, but it does not exist`);
  18052. }
  18053. track.ending = false;
  18054. track.ended = false;
  18055. sb.appendBuffer(data);
  18056. }
  18057. blockUntilOpen(callback) {
  18058. if (this.isUpdating() || this.isQueued()) {
  18059. this.blockBuffers(callback).catch((error) => {
  18060. this.warn(`SourceBuffer blocked callback ${error}`);
  18061. this.stepOperationQueue(this.sourceBufferTypes);
  18062. });
  18063. } else {
  18064. try {
  18065. callback();
  18066. } catch (error) {
  18067. this.warn(`Callback run without blocking ${this.operationQueue} ${error}`);
  18068. }
  18069. }
  18070. }
  18071. isUpdating() {
  18072. return this.sourceBuffers.some(([type, sb]) => type && sb.updating);
  18073. }
  18074. isQueued() {
  18075. return this.sourceBuffers.some(([type]) => type && !!this.currentOp(type));
  18076. }
  18077. isPending(track) {
  18078. return !!track && !track.buffer;
  18079. }
  18080. // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
  18081. // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
  18082. // upon completion, since we already do it here
  18083. blockBuffers(onUnblocked, bufferNames = this.sourceBufferTypes) {
  18084. if (!bufferNames.length) {
  18085. this.log("Blocking operation requested, but no SourceBuffers exist");
  18086. return Promise.resolve().then(onUnblocked);
  18087. }
  18088. const {
  18089. operationQueue
  18090. } = this;
  18091. const blockingOperations = bufferNames.map((type) => this.appendBlocker(type));
  18092. const audioBlocked = bufferNames.length > 1 && !!this.blockedAudioAppend;
  18093. if (audioBlocked) {
  18094. this.unblockAudio();
  18095. }
  18096. return Promise.all(blockingOperations).then((result) => {
  18097. if (operationQueue !== this.operationQueue) {
  18098. return;
  18099. }
  18100. onUnblocked();
  18101. this.stepOperationQueue(this.sourceBufferTypes);
  18102. });
  18103. }
  18104. stepOperationQueue(bufferNames) {
  18105. bufferNames.forEach((type) => {
  18106. var _this$tracks$type4;
  18107. const sb = (_this$tracks$type4 = this.tracks[type]) == null ? void 0 : _this$tracks$type4.buffer;
  18108. if (!sb || sb.updating) {
  18109. return;
  18110. }
  18111. this.shiftAndExecuteNext(type);
  18112. });
  18113. }
  18114. append(operation, type, pending) {
  18115. if (this.operationQueue) {
  18116. this.operationQueue.append(operation, type, pending);
  18117. }
  18118. }
  18119. appendBlocker(type) {
  18120. if (this.operationQueue) {
  18121. return this.operationQueue.appendBlocker(type);
  18122. }
  18123. }
  18124. currentOp(type) {
  18125. if (this.operationQueue) {
  18126. return this.operationQueue.current(type);
  18127. }
  18128. return null;
  18129. }
  18130. executeNext(type) {
  18131. if (type && this.operationQueue) {
  18132. this.operationQueue.executeNext(type);
  18133. }
  18134. }
  18135. shiftAndExecuteNext(type) {
  18136. if (this.operationQueue) {
  18137. this.operationQueue.shiftAndExecuteNext(type);
  18138. }
  18139. }
  18140. get pendingTrackCount() {
  18141. return Object.keys(this.tracks).reduce((acc, type) => acc + (this.isPending(this.tracks[type]) ? 1 : 0), 0);
  18142. }
  18143. get sourceBufferCount() {
  18144. return this.sourceBuffers.reduce((acc, [type]) => acc + (type ? 1 : 0), 0);
  18145. }
  18146. get sourceBufferTypes() {
  18147. return this.sourceBuffers.map(([type]) => type).filter((type) => !!type);
  18148. }
  18149. addBufferListener(type, event, fn) {
  18150. const track = this.tracks[type];
  18151. if (!track) {
  18152. return;
  18153. }
  18154. const buffer = track.buffer;
  18155. if (!buffer) {
  18156. return;
  18157. }
  18158. const listener = fn.bind(this, type);
  18159. track.listeners.push({
  18160. event,
  18161. listener
  18162. });
  18163. buffer.addEventListener(event, listener);
  18164. }
  18165. removeBufferListeners(type) {
  18166. const track = this.tracks[type];
  18167. if (!track) {
  18168. return;
  18169. }
  18170. const buffer = track.buffer;
  18171. if (!buffer) {
  18172. return;
  18173. }
  18174. track.listeners.forEach((l) => {
  18175. buffer.removeEventListener(l.event, l.listener);
  18176. });
  18177. track.listeners.length = 0;
  18178. }
  18179. };
  18180. function removeSourceChildren(node) {
  18181. const sourceChildren = node.querySelectorAll("source");
  18182. [].slice.call(sourceChildren).forEach((source) => {
  18183. node.removeChild(source);
  18184. });
  18185. }
  18186. function addSource(media, url) {
  18187. const source = self.document.createElement("source");
  18188. source.type = "video/mp4";
  18189. source.src = url;
  18190. media.appendChild(source);
  18191. }
  18192. function sourceBufferNameToIndex(type) {
  18193. return type === "audio" ? 1 : 0;
  18194. }
  18195. var CapLevelController = class _CapLevelController {
  18196. constructor(hls) {
  18197. this.hls = void 0;
  18198. this.autoLevelCapping = void 0;
  18199. this.firstLevel = void 0;
  18200. this.media = void 0;
  18201. this.restrictedLevels = void 0;
  18202. this.timer = void 0;
  18203. this.clientRect = void 0;
  18204. this.streamController = void 0;
  18205. this.hls = hls;
  18206. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  18207. this.firstLevel = -1;
  18208. this.media = null;
  18209. this.restrictedLevels = [];
  18210. this.timer = void 0;
  18211. this.clientRect = null;
  18212. this.registerListeners();
  18213. }
  18214. setStreamController(streamController) {
  18215. this.streamController = streamController;
  18216. }
  18217. destroy() {
  18218. if (this.hls) {
  18219. this.unregisterListener();
  18220. }
  18221. if (this.timer) {
  18222. this.stopCapping();
  18223. }
  18224. this.media = null;
  18225. this.clientRect = null;
  18226. this.hls = this.streamController = null;
  18227. }
  18228. registerListeners() {
  18229. const {
  18230. hls
  18231. } = this;
  18232. hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  18233. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  18234. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  18235. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  18236. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  18237. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18238. }
  18239. unregisterListener() {
  18240. const {
  18241. hls
  18242. } = this;
  18243. hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  18244. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  18245. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  18246. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  18247. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  18248. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18249. }
  18250. onFpsDropLevelCapping(event, data) {
  18251. const level = this.hls.levels[data.droppedLevel];
  18252. if (this.isLevelAllowed(level)) {
  18253. this.restrictedLevels.push({
  18254. bitrate: level.bitrate,
  18255. height: level.height,
  18256. width: level.width
  18257. });
  18258. }
  18259. }
  18260. onMediaAttaching(event, data) {
  18261. this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  18262. this.clientRect = null;
  18263. if (this.timer && this.hls.levels.length) {
  18264. this.detectPlayerSize();
  18265. }
  18266. }
  18267. onManifestParsed(event, data) {
  18268. const hls = this.hls;
  18269. this.restrictedLevels = [];
  18270. this.firstLevel = data.firstLevel;
  18271. if (hls.config.capLevelToPlayerSize && data.video) {
  18272. this.startCapping();
  18273. }
  18274. }
  18275. onLevelsUpdated(event, data) {
  18276. if (this.timer && isFiniteNumber(this.autoLevelCapping)) {
  18277. this.detectPlayerSize();
  18278. }
  18279. }
  18280. // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  18281. // to the first level
  18282. onBufferCodecs(event, data) {
  18283. const hls = this.hls;
  18284. if (hls.config.capLevelToPlayerSize && data.video) {
  18285. this.startCapping();
  18286. }
  18287. }
  18288. onMediaDetaching() {
  18289. this.stopCapping();
  18290. this.media = null;
  18291. }
  18292. detectPlayerSize() {
  18293. if (this.media) {
  18294. if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {
  18295. this.clientRect = null;
  18296. return;
  18297. }
  18298. const levels = this.hls.levels;
  18299. if (levels.length) {
  18300. const hls = this.hls;
  18301. const maxLevel = this.getMaxLevel(levels.length - 1);
  18302. if (maxLevel !== this.autoLevelCapping) {
  18303. hls.logger.log(`Setting autoLevelCapping to ${maxLevel}: ${levels[maxLevel].height}p@${levels[maxLevel].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`);
  18304. }
  18305. hls.autoLevelCapping = maxLevel;
  18306. if (hls.autoLevelEnabled && hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
  18307. this.streamController.nextLevelSwitch();
  18308. }
  18309. this.autoLevelCapping = hls.autoLevelCapping;
  18310. }
  18311. }
  18312. }
  18313. /*
  18314. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  18315. */
  18316. getMaxLevel(capLevelIndex) {
  18317. const levels = this.hls.levels;
  18318. if (!levels.length) {
  18319. return -1;
  18320. }
  18321. const validLevels = levels.filter((level, index) => this.isLevelAllowed(level) && index <= capLevelIndex);
  18322. this.clientRect = null;
  18323. return _CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  18324. }
  18325. startCapping() {
  18326. if (this.timer) {
  18327. return;
  18328. }
  18329. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  18330. self.clearInterval(this.timer);
  18331. this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1e3);
  18332. this.detectPlayerSize();
  18333. }
  18334. stopCapping() {
  18335. this.restrictedLevels = [];
  18336. this.firstLevel = -1;
  18337. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  18338. if (this.timer) {
  18339. self.clearInterval(this.timer);
  18340. this.timer = void 0;
  18341. }
  18342. }
  18343. getDimensions() {
  18344. if (this.clientRect) {
  18345. return this.clientRect;
  18346. }
  18347. const media = this.media;
  18348. const boundsRect = {
  18349. width: 0,
  18350. height: 0
  18351. };
  18352. if (media) {
  18353. const clientRect = media.getBoundingClientRect();
  18354. boundsRect.width = clientRect.width;
  18355. boundsRect.height = clientRect.height;
  18356. if (!boundsRect.width && !boundsRect.height) {
  18357. boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
  18358. boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
  18359. }
  18360. }
  18361. this.clientRect = boundsRect;
  18362. return boundsRect;
  18363. }
  18364. get mediaWidth() {
  18365. return this.getDimensions().width * this.contentScaleFactor;
  18366. }
  18367. get mediaHeight() {
  18368. return this.getDimensions().height * this.contentScaleFactor;
  18369. }
  18370. get contentScaleFactor() {
  18371. let pixelRatio = 1;
  18372. if (!this.hls.config.ignoreDevicePixelRatio) {
  18373. try {
  18374. pixelRatio = self.devicePixelRatio;
  18375. } catch (e) {
  18376. }
  18377. }
  18378. return Math.min(pixelRatio, this.hls.config.maxDevicePixelRatio);
  18379. }
  18380. isLevelAllowed(level) {
  18381. const restrictedLevels = this.restrictedLevels;
  18382. return !restrictedLevels.some((restrictedLevel) => {
  18383. return level.bitrate === restrictedLevel.bitrate && level.width === restrictedLevel.width && level.height === restrictedLevel.height;
  18384. });
  18385. }
  18386. static getMaxLevelByMediaSize(levels, width, height) {
  18387. if (!(levels != null && levels.length)) {
  18388. return -1;
  18389. }
  18390. const atGreatestBandwidth = (curLevel, nextLevel) => {
  18391. if (!nextLevel) {
  18392. return true;
  18393. }
  18394. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  18395. };
  18396. let maxLevelIndex = levels.length - 1;
  18397. const squareSize = Math.max(width, height);
  18398. for (let i = 0; i < levels.length; i += 1) {
  18399. const level = levels[i];
  18400. if ((level.width >= squareSize || level.height >= squareSize) && atGreatestBandwidth(level, levels[i + 1])) {
  18401. maxLevelIndex = i;
  18402. break;
  18403. }
  18404. }
  18405. return maxLevelIndex;
  18406. }
  18407. };
  18408. var CmObjectType = {
  18409. /**
  18410. * text file, such as a manifest or playlist
  18411. */
  18412. MANIFEST: "m",
  18413. /**
  18414. * audio only
  18415. */
  18416. AUDIO: "a",
  18417. /**
  18418. * video only
  18419. */
  18420. VIDEO: "v",
  18421. /**
  18422. * muxed audio and video
  18423. */
  18424. MUXED: "av",
  18425. /**
  18426. * init segment
  18427. */
  18428. INIT: "i",
  18429. /**
  18430. * caption or subtitle
  18431. */
  18432. CAPTION: "c",
  18433. /**
  18434. * ISOBMFF timed text track
  18435. */
  18436. TIMED_TEXT: "tt",
  18437. /**
  18438. * cryptographic key, license or certificate.
  18439. */
  18440. KEY: "k",
  18441. /**
  18442. * other
  18443. */
  18444. OTHER: "o"
  18445. };
  18446. var CmcdObjectType = CmObjectType;
  18447. var CmStreamingFormat = {
  18448. /**
  18449. * HTTP Live Streaming (HLS)
  18450. */
  18451. HLS: "h"
  18452. };
  18453. var CmcdStreamingFormat = CmStreamingFormat;
  18454. var SfItem = class _SfItem {
  18455. constructor(value, params) {
  18456. if (Array.isArray(value)) {
  18457. value = value.map((v) => v instanceof _SfItem ? v : new _SfItem(v));
  18458. }
  18459. this.value = value;
  18460. this.params = params;
  18461. }
  18462. };
  18463. var DICT = "Dict";
  18464. function format(value) {
  18465. if (Array.isArray(value)) {
  18466. return JSON.stringify(value);
  18467. }
  18468. if (value instanceof Map) {
  18469. return "Map{}";
  18470. }
  18471. if (value instanceof Set) {
  18472. return "Set{}";
  18473. }
  18474. if (typeof value === "object") {
  18475. return JSON.stringify(value);
  18476. }
  18477. return String(value);
  18478. }
  18479. function throwError(action, src, type, cause) {
  18480. return new Error(`failed to ${action} "${format(src)}" as ${type}`, {
  18481. cause
  18482. });
  18483. }
  18484. function serializeError(src, type, cause) {
  18485. return throwError("serialize", src, type, cause);
  18486. }
  18487. var SfToken = class {
  18488. constructor(description) {
  18489. this.description = description;
  18490. }
  18491. };
  18492. var BARE_ITEM = "Bare Item";
  18493. var BOOLEAN = "Boolean";
  18494. function serializeBoolean(value) {
  18495. if (typeof value !== "boolean") {
  18496. throw serializeError(value, BOOLEAN);
  18497. }
  18498. return value ? "?1" : "?0";
  18499. }
  18500. function encodeBase64(binary) {
  18501. return btoa(String.fromCharCode(...binary));
  18502. }
  18503. var BYTES = "Byte Sequence";
  18504. function serializeByteSequence(value) {
  18505. if (ArrayBuffer.isView(value) === false) {
  18506. throw serializeError(value, BYTES);
  18507. }
  18508. return `:${encodeBase64(value)}:`;
  18509. }
  18510. var INTEGER = "Integer";
  18511. function isInvalidInt(value) {
  18512. return value < -999999999999999 || 999999999999999 < value;
  18513. }
  18514. function serializeInteger(value) {
  18515. if (isInvalidInt(value)) {
  18516. throw serializeError(value, INTEGER);
  18517. }
  18518. return value.toString();
  18519. }
  18520. function serializeDate(value) {
  18521. return `@${serializeInteger(value.getTime() / 1e3)}`;
  18522. }
  18523. function roundToEven(value, precision) {
  18524. if (value < 0) {
  18525. return -roundToEven(-value, precision);
  18526. }
  18527. const decimalShift = Math.pow(10, precision);
  18528. const isEquidistant = Math.abs(value * decimalShift % 1 - 0.5) < Number.EPSILON;
  18529. if (isEquidistant) {
  18530. const flooredValue = Math.floor(value * decimalShift);
  18531. return (flooredValue % 2 === 0 ? flooredValue : flooredValue + 1) / decimalShift;
  18532. } else {
  18533. return Math.round(value * decimalShift) / decimalShift;
  18534. }
  18535. }
  18536. var DECIMAL = "Decimal";
  18537. function serializeDecimal(value) {
  18538. const roundedValue = roundToEven(value, 3);
  18539. if (Math.floor(Math.abs(roundedValue)).toString().length > 12) {
  18540. throw serializeError(value, DECIMAL);
  18541. }
  18542. const stringValue = roundedValue.toString();
  18543. return stringValue.includes(".") ? stringValue : `${stringValue}.0`;
  18544. }
  18545. var STRING = "String";
  18546. var STRING_REGEX = /[\x00-\x1f\x7f]+/;
  18547. function serializeString(value) {
  18548. if (STRING_REGEX.test(value)) {
  18549. throw serializeError(value, STRING);
  18550. }
  18551. return `"${value.replace(/\\/g, `\\\\`).replace(/"/g, `\\"`)}"`;
  18552. }
  18553. function symbolToStr(symbol) {
  18554. return symbol.description || symbol.toString().slice(7, -1);
  18555. }
  18556. var TOKEN = "Token";
  18557. function serializeToken(token) {
  18558. const value = symbolToStr(token);
  18559. if (/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(value) === false) {
  18560. throw serializeError(value, TOKEN);
  18561. }
  18562. return value;
  18563. }
  18564. function serializeBareItem(value) {
  18565. switch (typeof value) {
  18566. case "number":
  18567. if (!isFiniteNumber(value)) {
  18568. throw serializeError(value, BARE_ITEM);
  18569. }
  18570. if (Number.isInteger(value)) {
  18571. return serializeInteger(value);
  18572. }
  18573. return serializeDecimal(value);
  18574. case "string":
  18575. return serializeString(value);
  18576. case "symbol":
  18577. return serializeToken(value);
  18578. case "boolean":
  18579. return serializeBoolean(value);
  18580. case "object":
  18581. if (value instanceof Date) {
  18582. return serializeDate(value);
  18583. }
  18584. if (value instanceof Uint8Array) {
  18585. return serializeByteSequence(value);
  18586. }
  18587. if (value instanceof SfToken) {
  18588. return serializeToken(value);
  18589. }
  18590. default:
  18591. throw serializeError(value, BARE_ITEM);
  18592. }
  18593. }
  18594. var KEY = "Key";
  18595. function serializeKey(value) {
  18596. if (/^[a-z*][a-z0-9\-_.*]*$/.test(value) === false) {
  18597. throw serializeError(value, KEY);
  18598. }
  18599. return value;
  18600. }
  18601. function serializeParams(params) {
  18602. if (params == null) {
  18603. return "";
  18604. }
  18605. return Object.entries(params).map(([key, value]) => {
  18606. if (value === true) {
  18607. return `;${serializeKey(key)}`;
  18608. }
  18609. return `;${serializeKey(key)}=${serializeBareItem(value)}`;
  18610. }).join("");
  18611. }
  18612. function serializeItem(value) {
  18613. if (value instanceof SfItem) {
  18614. return `${serializeBareItem(value.value)}${serializeParams(value.params)}`;
  18615. } else {
  18616. return serializeBareItem(value);
  18617. }
  18618. }
  18619. function serializeInnerList(value) {
  18620. return `(${value.value.map(serializeItem).join(" ")})${serializeParams(value.params)}`;
  18621. }
  18622. function serializeDict(dict, options = {
  18623. whitespace: true
  18624. }) {
  18625. if (typeof dict !== "object" || dict == null) {
  18626. throw serializeError(dict, DICT);
  18627. }
  18628. const entries = dict instanceof Map ? dict.entries() : Object.entries(dict);
  18629. const optionalWhiteSpace = (options === null || options === void 0 ? void 0 : options.whitespace) ? " " : "";
  18630. return Array.from(entries).map(([key, item]) => {
  18631. if (item instanceof SfItem === false) {
  18632. item = new SfItem(item);
  18633. }
  18634. let output = serializeKey(key);
  18635. if (item.value === true) {
  18636. output += serializeParams(item.params);
  18637. } else {
  18638. output += "=";
  18639. if (Array.isArray(item.value)) {
  18640. output += serializeInnerList(item);
  18641. } else {
  18642. output += serializeItem(item);
  18643. }
  18644. }
  18645. return output;
  18646. }).join(`,${optionalWhiteSpace}`);
  18647. }
  18648. function encodeSfDict(value, options) {
  18649. return serializeDict(value, options);
  18650. }
  18651. var CMCD_OBJECT = "CMCD-Object";
  18652. var CMCD_REQUEST = "CMCD-Request";
  18653. var CMCD_SESSION = "CMCD-Session";
  18654. var CMCD_STATUS = "CMCD-Status";
  18655. var CMCD_HEADER_MAP = {
  18656. // Object
  18657. br: CMCD_OBJECT,
  18658. ab: CMCD_OBJECT,
  18659. d: CMCD_OBJECT,
  18660. ot: CMCD_OBJECT,
  18661. tb: CMCD_OBJECT,
  18662. tpb: CMCD_OBJECT,
  18663. lb: CMCD_OBJECT,
  18664. tab: CMCD_OBJECT,
  18665. lab: CMCD_OBJECT,
  18666. url: CMCD_OBJECT,
  18667. // Request
  18668. pb: CMCD_REQUEST,
  18669. bl: CMCD_REQUEST,
  18670. tbl: CMCD_REQUEST,
  18671. dl: CMCD_REQUEST,
  18672. ltc: CMCD_REQUEST,
  18673. mtp: CMCD_REQUEST,
  18674. nor: CMCD_REQUEST,
  18675. nrr: CMCD_REQUEST,
  18676. rc: CMCD_REQUEST,
  18677. sn: CMCD_REQUEST,
  18678. sta: CMCD_REQUEST,
  18679. su: CMCD_REQUEST,
  18680. ttfb: CMCD_REQUEST,
  18681. ttfbb: CMCD_REQUEST,
  18682. ttlb: CMCD_REQUEST,
  18683. cmsdd: CMCD_REQUEST,
  18684. cmsds: CMCD_REQUEST,
  18685. smrt: CMCD_REQUEST,
  18686. df: CMCD_REQUEST,
  18687. cs: CMCD_REQUEST,
  18688. // TODO: Which header to put the `ts` field is not defined yet.
  18689. ts: CMCD_REQUEST,
  18690. // Session
  18691. cid: CMCD_SESSION,
  18692. pr: CMCD_SESSION,
  18693. sf: CMCD_SESSION,
  18694. sid: CMCD_SESSION,
  18695. st: CMCD_SESSION,
  18696. v: CMCD_SESSION,
  18697. msd: CMCD_SESSION,
  18698. // Status
  18699. bs: CMCD_STATUS,
  18700. bsd: CMCD_STATUS,
  18701. cdn: CMCD_STATUS,
  18702. rtp: CMCD_STATUS,
  18703. bg: CMCD_STATUS,
  18704. pt: CMCD_STATUS,
  18705. ec: CMCD_STATUS,
  18706. e: CMCD_STATUS
  18707. };
  18708. var CmcdHeaderField = {
  18709. /**
  18710. * keys whose values vary with each request.
  18711. */
  18712. REQUEST: CMCD_REQUEST
  18713. };
  18714. function createHeaderMap(headerMap) {
  18715. return Object.keys(headerMap).reduce((acc, field) => {
  18716. var _a;
  18717. (_a = headerMap[field]) === null || _a === void 0 ? void 0 : _a.forEach((key) => acc[key] = field);
  18718. return acc;
  18719. }, {});
  18720. }
  18721. function groupCmcdHeaders(cmcd, customHeaderMap) {
  18722. const result = {};
  18723. if (!cmcd) {
  18724. return result;
  18725. }
  18726. const keys = Object.keys(cmcd);
  18727. const custom = customHeaderMap ? createHeaderMap(customHeaderMap) : {};
  18728. return keys.reduce((acc, key) => {
  18729. var _a;
  18730. const field = CMCD_HEADER_MAP[key] || custom[key] || CmcdHeaderField.REQUEST;
  18731. const data = (_a = acc[field]) !== null && _a !== void 0 ? _a : acc[field] = {};
  18732. data[key] = cmcd[key];
  18733. return acc;
  18734. }, result);
  18735. }
  18736. function isTokenField(key) {
  18737. return ["ot", "sf", "st", "e", "sta"].includes(key);
  18738. }
  18739. function isValid(value) {
  18740. if (typeof value === "number") {
  18741. return isFiniteNumber(value);
  18742. }
  18743. return value != null && value !== "" && value !== false;
  18744. }
  18745. var CMCD_EVENT_MODE = "event";
  18746. function urlToRelativePath(url, base) {
  18747. const to = new URL(url);
  18748. const from = new URL(base);
  18749. if (to.origin !== from.origin) {
  18750. return url;
  18751. }
  18752. const toPath = to.pathname.split("/").slice(1);
  18753. const fromPath = from.pathname.split("/").slice(1, -1);
  18754. while (toPath[0] === fromPath[0]) {
  18755. toPath.shift();
  18756. fromPath.shift();
  18757. }
  18758. while (fromPath.length) {
  18759. fromPath.shift();
  18760. toPath.unshift("..");
  18761. }
  18762. const relativePath = toPath.join("/");
  18763. return relativePath + to.search + to.hash;
  18764. }
  18765. var toRounded = (value) => Math.round(value);
  18766. var toUrlSafe = (value, options) => {
  18767. if (Array.isArray(value)) {
  18768. return value.map((item) => toUrlSafe(item, options));
  18769. }
  18770. if (value instanceof SfItem && typeof value.value === "string") {
  18771. return new SfItem(toUrlSafe(value.value, options), value.params);
  18772. } else {
  18773. if (options.baseUrl) {
  18774. value = urlToRelativePath(value, options.baseUrl);
  18775. }
  18776. return options.version === 1 ? encodeURIComponent(value) : value;
  18777. }
  18778. };
  18779. var toHundred = (value) => toRounded(value / 100) * 100;
  18780. var nor = (value, options) => {
  18781. let norValue = value;
  18782. if (options.version >= 2) {
  18783. if (value instanceof SfItem && typeof value.value === "string") {
  18784. norValue = new SfItem([value]);
  18785. } else if (typeof value === "string") {
  18786. norValue = [value];
  18787. }
  18788. }
  18789. return toUrlSafe(norValue, options);
  18790. };
  18791. var CMCD_FORMATTER_MAP = {
  18792. /**
  18793. * Bitrate (kbps) rounded integer
  18794. */
  18795. br: toRounded,
  18796. /**
  18797. * Duration (milliseconds) rounded integer
  18798. */
  18799. d: toRounded,
  18800. /**
  18801. * Buffer Length (milliseconds) rounded nearest 100ms
  18802. */
  18803. bl: toHundred,
  18804. /**
  18805. * Deadline (milliseconds) rounded nearest 100ms
  18806. */
  18807. dl: toHundred,
  18808. /**
  18809. * Measured Throughput (kbps) rounded nearest 100kbps
  18810. */
  18811. mtp: toHundred,
  18812. /**
  18813. * Next Object Request URL encoded
  18814. */
  18815. nor,
  18816. /**
  18817. * Requested maximum throughput (kbps) rounded nearest 100kbps
  18818. */
  18819. rtp: toHundred,
  18820. /**
  18821. * Top Bitrate (kbps) rounded integer
  18822. */
  18823. tb: toRounded
  18824. };
  18825. var CMCD_REQUEST_MODE = "request";
  18826. var CMCD_RESPONSE_MODE = "response";
  18827. var CMCD_COMMON_KEYS = ["ab", "bg", "bl", "br", "bs", "bsd", "cdn", "cid", "cs", "df", "ec", "lab", "lb", "ltc", "msd", "mtp", "pb", "pr", "pt", "sf", "sid", "sn", "st", "sta", "tab", "tb", "tbl", "tpb", "ts", "v"];
  18828. var CMCD_EVENT_KEYS = ["e"];
  18829. var CUSTOM_KEY_REGEX = /^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;
  18830. function isCmcdCustomKey(key) {
  18831. return CUSTOM_KEY_REGEX.test(key);
  18832. }
  18833. function isCmcdEventKey(key) {
  18834. return CMCD_COMMON_KEYS.includes(key) || CMCD_EVENT_KEYS.includes(key) || isCmcdCustomKey(key);
  18835. }
  18836. var CMCD_REQUEST_KEYS = ["d", "dl", "nor", "ot", "rtp", "su"];
  18837. function isCmcdRequestKey(key) {
  18838. return CMCD_COMMON_KEYS.includes(key) || CMCD_REQUEST_KEYS.includes(key) || isCmcdCustomKey(key);
  18839. }
  18840. var CMCD_RESPONSE_KEYS = ["cmsdd", "cmsds", "rc", "smrt", "ttfb", "ttfbb", "ttlb", "url"];
  18841. function isCmcdResponseKey(key) {
  18842. return CMCD_COMMON_KEYS.includes(key) || CMCD_REQUEST_KEYS.includes(key) || CMCD_RESPONSE_KEYS.includes(key) || isCmcdCustomKey(key);
  18843. }
  18844. var CMCD_V1_KEYS = ["bl", "br", "bs", "cid", "d", "dl", "mtp", "nor", "nrr", "ot", "pr", "rtp", "sf", "sid", "st", "su", "tb", "v"];
  18845. function isCmcdV1Key(key) {
  18846. return CMCD_V1_KEYS.includes(key) || isCmcdCustomKey(key);
  18847. }
  18848. var filterMap = {
  18849. [CMCD_RESPONSE_MODE]: isCmcdResponseKey,
  18850. [CMCD_EVENT_MODE]: isCmcdEventKey,
  18851. [CMCD_REQUEST_MODE]: isCmcdRequestKey
  18852. };
  18853. function prepareCmcdData(obj, options = {}) {
  18854. const results = {};
  18855. if (obj == null || typeof obj !== "object") {
  18856. return results;
  18857. }
  18858. const version2 = options.version || obj["v"] || 1;
  18859. const reportingMode = options.reportingMode || CMCD_REQUEST_MODE;
  18860. const keyFilter = version2 === 1 ? isCmcdV1Key : filterMap[reportingMode];
  18861. let keys = Object.keys(obj).filter(keyFilter);
  18862. const filter = options.filter;
  18863. if (typeof filter === "function") {
  18864. keys = keys.filter(filter);
  18865. }
  18866. const needsTimestamp = reportingMode === CMCD_RESPONSE_MODE || reportingMode === CMCD_EVENT_MODE;
  18867. if (needsTimestamp && !keys.includes("ts")) {
  18868. keys.push("ts");
  18869. }
  18870. if (version2 > 1 && !keys.includes("v")) {
  18871. keys.push("v");
  18872. }
  18873. const formatters = _extends({}, CMCD_FORMATTER_MAP, options.formatters);
  18874. const formatterOptions = {
  18875. version: version2,
  18876. reportingMode,
  18877. baseUrl: options.baseUrl
  18878. };
  18879. keys.sort().forEach((key) => {
  18880. let value = obj[key];
  18881. const formatter = formatters[key];
  18882. if (typeof formatter === "function") {
  18883. value = formatter(value, formatterOptions);
  18884. }
  18885. if (key === "v") {
  18886. if (version2 === 1) {
  18887. return;
  18888. } else {
  18889. value = version2;
  18890. }
  18891. }
  18892. if (key == "pr" && value === 1) {
  18893. return;
  18894. }
  18895. if (needsTimestamp && key === "ts" && !isFiniteNumber(value)) {
  18896. value = Date.now();
  18897. }
  18898. if (!isValid(value)) {
  18899. return;
  18900. }
  18901. if (isTokenField(key) && typeof value === "string") {
  18902. value = new SfToken(value);
  18903. }
  18904. results[key] = value;
  18905. });
  18906. return results;
  18907. }
  18908. function toCmcdHeaders(cmcd, options = {}) {
  18909. const result = {};
  18910. if (!cmcd) {
  18911. return result;
  18912. }
  18913. const data = prepareCmcdData(cmcd, options);
  18914. const shards = groupCmcdHeaders(data, options === null || options === void 0 ? void 0 : options.customHeaderMap);
  18915. return Object.entries(shards).reduce((acc, [field, value]) => {
  18916. const shard = encodeSfDict(value, {
  18917. whitespace: false
  18918. });
  18919. if (shard) {
  18920. acc[field] = shard;
  18921. }
  18922. return acc;
  18923. }, result);
  18924. }
  18925. function appendCmcdHeaders(headers, cmcd, options) {
  18926. return _extends(headers, toCmcdHeaders(cmcd, options));
  18927. }
  18928. var CMCD_PARAM = "CMCD";
  18929. function encodeCmcd(cmcd, options = {}) {
  18930. if (!cmcd) {
  18931. return "";
  18932. }
  18933. return encodeSfDict(prepareCmcdData(cmcd, options), {
  18934. whitespace: false
  18935. });
  18936. }
  18937. function toCmcdUrl(cmcd, options = {}) {
  18938. if (!cmcd) {
  18939. return "";
  18940. }
  18941. const params = encodeCmcd(cmcd, options);
  18942. return encodeURIComponent(params);
  18943. }
  18944. function toCmcdQuery(cmcd, options = {}) {
  18945. if (!cmcd) {
  18946. return "";
  18947. }
  18948. const value = toCmcdUrl(cmcd, options);
  18949. return `${CMCD_PARAM}=${value}`;
  18950. }
  18951. var REGEX = /CMCD=[^&#]+/;
  18952. function appendCmcdQuery(url, cmcd, options) {
  18953. const query = toCmcdQuery(cmcd, options);
  18954. if (!query) {
  18955. return url;
  18956. }
  18957. if (REGEX.test(url)) {
  18958. return url.replace(REGEX, query);
  18959. }
  18960. const separator = url.includes("?") ? "&" : "?";
  18961. return `${url}${separator}${query}`;
  18962. }
  18963. var CMCDController = class {
  18964. constructor(hls) {
  18965. this.hls = void 0;
  18966. this.config = void 0;
  18967. this.media = void 0;
  18968. this.sid = void 0;
  18969. this.cid = void 0;
  18970. this.useHeaders = false;
  18971. this.includeKeys = void 0;
  18972. this.initialized = false;
  18973. this.starved = false;
  18974. this.buffering = true;
  18975. this.audioBuffer = void 0;
  18976. this.videoBuffer = void 0;
  18977. this.onWaiting = () => {
  18978. if (this.initialized) {
  18979. this.starved = true;
  18980. }
  18981. this.buffering = true;
  18982. };
  18983. this.onPlaying = () => {
  18984. if (!this.initialized) {
  18985. this.initialized = true;
  18986. }
  18987. this.buffering = false;
  18988. };
  18989. this.applyPlaylistData = (context) => {
  18990. try {
  18991. this.apply(context, {
  18992. ot: CmcdObjectType.MANIFEST,
  18993. su: !this.initialized
  18994. });
  18995. } catch (error) {
  18996. this.hls.logger.warn("Could not generate manifest CMCD data.", error);
  18997. }
  18998. };
  18999. this.applyFragmentData = (context) => {
  19000. try {
  19001. const {
  19002. frag,
  19003. part
  19004. } = context;
  19005. const level = this.hls.levels[frag.level];
  19006. const ot = this.getObjectType(frag);
  19007. const data = {
  19008. d: (part || frag).duration * 1e3,
  19009. ot
  19010. };
  19011. if (ot === CmcdObjectType.VIDEO || ot === CmcdObjectType.AUDIO || ot == CmcdObjectType.MUXED) {
  19012. data.br = level.bitrate / 1e3;
  19013. data.tb = this.getTopBandwidth(ot) / 1e3;
  19014. data.bl = this.getBufferLength(ot);
  19015. }
  19016. const next = part ? this.getNextPart(part) : this.getNextFrag(frag);
  19017. if (next != null && next.url && next.url !== frag.url) {
  19018. data.nor = next.url;
  19019. }
  19020. this.apply(context, data);
  19021. } catch (error) {
  19022. this.hls.logger.warn("Could not generate segment CMCD data.", error);
  19023. }
  19024. };
  19025. this.hls = hls;
  19026. const config = this.config = hls.config;
  19027. const {
  19028. cmcd
  19029. } = config;
  19030. if (cmcd != null) {
  19031. config.pLoader = this.createPlaylistLoader();
  19032. config.fLoader = this.createFragmentLoader();
  19033. this.sid = cmcd.sessionId || hls.sessionId;
  19034. this.cid = cmcd.contentId;
  19035. this.useHeaders = cmcd.useHeaders === true;
  19036. this.includeKeys = cmcd.includeKeys;
  19037. this.registerListeners();
  19038. }
  19039. }
  19040. registerListeners() {
  19041. const hls = this.hls;
  19042. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  19043. hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  19044. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  19045. }
  19046. unregisterListeners() {
  19047. const hls = this.hls;
  19048. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  19049. hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  19050. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  19051. }
  19052. destroy() {
  19053. this.unregisterListeners();
  19054. this.onMediaDetached();
  19055. this.hls = this.config = this.audioBuffer = this.videoBuffer = null;
  19056. this.onWaiting = this.onPlaying = this.media = null;
  19057. }
  19058. onMediaAttached(event, data) {
  19059. this.media = data.media;
  19060. this.media.addEventListener("waiting", this.onWaiting);
  19061. this.media.addEventListener("playing", this.onPlaying);
  19062. }
  19063. onMediaDetached() {
  19064. if (!this.media) {
  19065. return;
  19066. }
  19067. this.media.removeEventListener("waiting", this.onWaiting);
  19068. this.media.removeEventListener("playing", this.onPlaying);
  19069. this.media = null;
  19070. }
  19071. onBufferCreated(event, data) {
  19072. var _data$tracks$audio, _data$tracks$video;
  19073. this.audioBuffer = (_data$tracks$audio = data.tracks.audio) == null ? void 0 : _data$tracks$audio.buffer;
  19074. this.videoBuffer = (_data$tracks$video = data.tracks.video) == null ? void 0 : _data$tracks$video.buffer;
  19075. }
  19076. /**
  19077. * Create baseline CMCD data
  19078. */
  19079. createData() {
  19080. var _this$media;
  19081. return {
  19082. v: 1,
  19083. sf: CmcdStreamingFormat.HLS,
  19084. sid: this.sid,
  19085. cid: this.cid,
  19086. pr: (_this$media = this.media) == null ? void 0 : _this$media.playbackRate,
  19087. mtp: this.hls.bandwidthEstimate / 1e3
  19088. };
  19089. }
  19090. /**
  19091. * Apply CMCD data to a request.
  19092. */
  19093. apply(context, data = {}) {
  19094. _extends(data, this.createData());
  19095. const isVideo = data.ot === CmcdObjectType.INIT || data.ot === CmcdObjectType.VIDEO || data.ot === CmcdObjectType.MUXED;
  19096. if (this.starved && isVideo) {
  19097. data.bs = true;
  19098. data.su = true;
  19099. this.starved = false;
  19100. }
  19101. if (data.su == null) {
  19102. data.su = this.buffering;
  19103. }
  19104. const {
  19105. includeKeys
  19106. } = this;
  19107. if (includeKeys) {
  19108. data = Object.keys(data).reduce((acc, key) => {
  19109. includeKeys.includes(key) && (acc[key] = data[key]);
  19110. return acc;
  19111. }, {});
  19112. }
  19113. const options = {
  19114. baseUrl: context.url
  19115. };
  19116. if (this.useHeaders) {
  19117. if (!context.headers) {
  19118. context.headers = {};
  19119. }
  19120. appendCmcdHeaders(context.headers, data, options);
  19121. } else {
  19122. context.url = appendCmcdQuery(context.url, data, options);
  19123. }
  19124. }
  19125. getNextFrag(fragment) {
  19126. var _this$hls$levels$frag;
  19127. const levelDetails = (_this$hls$levels$frag = this.hls.levels[fragment.level]) == null ? void 0 : _this$hls$levels$frag.details;
  19128. if (levelDetails) {
  19129. const index = fragment.sn - levelDetails.startSN;
  19130. return levelDetails.fragments[index + 1];
  19131. }
  19132. return void 0;
  19133. }
  19134. getNextPart(part) {
  19135. var _this$hls$levels$frag2;
  19136. const {
  19137. index,
  19138. fragment
  19139. } = part;
  19140. const partList = (_this$hls$levels$frag2 = this.hls.levels[fragment.level]) == null || (_this$hls$levels$frag2 = _this$hls$levels$frag2.details) == null ? void 0 : _this$hls$levels$frag2.partList;
  19141. if (partList) {
  19142. const {
  19143. sn
  19144. } = fragment;
  19145. for (let i = partList.length - 1; i >= 0; i--) {
  19146. const p = partList[i];
  19147. if (p.index === index && p.fragment.sn === sn) {
  19148. return partList[i + 1];
  19149. }
  19150. }
  19151. }
  19152. return void 0;
  19153. }
  19154. /**
  19155. * The CMCD object type.
  19156. */
  19157. getObjectType(fragment) {
  19158. const {
  19159. type
  19160. } = fragment;
  19161. if (type === "subtitle") {
  19162. return CmcdObjectType.TIMED_TEXT;
  19163. }
  19164. if (fragment.sn === "initSegment") {
  19165. return CmcdObjectType.INIT;
  19166. }
  19167. if (type === "audio") {
  19168. return CmcdObjectType.AUDIO;
  19169. }
  19170. if (type === "main") {
  19171. if (!this.hls.audioTracks.length) {
  19172. return CmcdObjectType.MUXED;
  19173. }
  19174. return CmcdObjectType.VIDEO;
  19175. }
  19176. return void 0;
  19177. }
  19178. /**
  19179. * Get the highest bitrate.
  19180. */
  19181. getTopBandwidth(type) {
  19182. let bitrate = 0;
  19183. let levels;
  19184. const hls = this.hls;
  19185. if (type === CmcdObjectType.AUDIO) {
  19186. levels = hls.audioTracks;
  19187. } else {
  19188. const max = hls.maxAutoLevel;
  19189. const len = max > -1 ? max + 1 : hls.levels.length;
  19190. levels = hls.levels.slice(0, len);
  19191. }
  19192. levels.forEach((level) => {
  19193. if (level.bitrate > bitrate) {
  19194. bitrate = level.bitrate;
  19195. }
  19196. });
  19197. return bitrate > 0 ? bitrate : NaN;
  19198. }
  19199. /**
  19200. * Get the buffer length for a media type in milliseconds
  19201. */
  19202. getBufferLength(type) {
  19203. const media = this.media;
  19204. const buffer = type === CmcdObjectType.AUDIO ? this.audioBuffer : this.videoBuffer;
  19205. if (!buffer || !media) {
  19206. return NaN;
  19207. }
  19208. const info = BufferHelper.bufferInfo(buffer, media.currentTime, this.config.maxBufferHole);
  19209. return info.len * 1e3;
  19210. }
  19211. /**
  19212. * Create a playlist loader
  19213. */
  19214. createPlaylistLoader() {
  19215. const {
  19216. pLoader
  19217. } = this.config;
  19218. const apply = this.applyPlaylistData;
  19219. const Ctor = pLoader || this.config.loader;
  19220. return class CmcdPlaylistLoader {
  19221. constructor(config) {
  19222. this.loader = void 0;
  19223. this.loader = new Ctor(config);
  19224. }
  19225. get stats() {
  19226. return this.loader.stats;
  19227. }
  19228. get context() {
  19229. return this.loader.context;
  19230. }
  19231. destroy() {
  19232. this.loader.destroy();
  19233. }
  19234. abort() {
  19235. this.loader.abort();
  19236. }
  19237. load(context, config, callbacks) {
  19238. apply(context);
  19239. this.loader.load(context, config, callbacks);
  19240. }
  19241. };
  19242. }
  19243. /**
  19244. * Create a playlist loader
  19245. */
  19246. createFragmentLoader() {
  19247. const {
  19248. fLoader
  19249. } = this.config;
  19250. const apply = this.applyFragmentData;
  19251. const Ctor = fLoader || this.config.loader;
  19252. return class CmcdFragmentLoader {
  19253. constructor(config) {
  19254. this.loader = void 0;
  19255. this.loader = new Ctor(config);
  19256. }
  19257. get stats() {
  19258. return this.loader.stats;
  19259. }
  19260. get context() {
  19261. return this.loader.context;
  19262. }
  19263. destroy() {
  19264. this.loader.destroy();
  19265. }
  19266. abort() {
  19267. this.loader.abort();
  19268. }
  19269. load(context, config, callbacks) {
  19270. apply(context);
  19271. this.loader.load(context, config, callbacks);
  19272. }
  19273. };
  19274. }
  19275. };
  19276. var PATHWAY_PENALTY_DURATION_MS = 3e5;
  19277. var ContentSteeringController = class extends Logger {
  19278. constructor(hls) {
  19279. super("content-steering", hls.logger);
  19280. this.hls = void 0;
  19281. this.loader = null;
  19282. this.uri = null;
  19283. this.pathwayId = ".";
  19284. this._pathwayPriority = null;
  19285. this.timeToLoad = 300;
  19286. this.reloadTimer = -1;
  19287. this.updated = 0;
  19288. this.started = false;
  19289. this.enabled = true;
  19290. this.levels = null;
  19291. this.audioTracks = null;
  19292. this.subtitleTracks = null;
  19293. this.penalizedPathways = {};
  19294. this.hls = hls;
  19295. this.registerListeners();
  19296. }
  19297. registerListeners() {
  19298. const hls = this.hls;
  19299. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  19300. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  19301. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  19302. hls.on(Events.ERROR, this.onError, this);
  19303. }
  19304. unregisterListeners() {
  19305. const hls = this.hls;
  19306. if (!hls) {
  19307. return;
  19308. }
  19309. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  19310. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  19311. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  19312. hls.off(Events.ERROR, this.onError, this);
  19313. }
  19314. pathways() {
  19315. return (this.levels || []).reduce((pathways, level) => {
  19316. if (pathways.indexOf(level.pathwayId) === -1) {
  19317. pathways.push(level.pathwayId);
  19318. }
  19319. return pathways;
  19320. }, []);
  19321. }
  19322. get pathwayPriority() {
  19323. return this._pathwayPriority;
  19324. }
  19325. set pathwayPriority(pathwayPriority) {
  19326. this.updatePathwayPriority(pathwayPriority);
  19327. }
  19328. startLoad() {
  19329. this.started = true;
  19330. this.clearTimeout();
  19331. if (this.enabled && this.uri) {
  19332. if (this.updated) {
  19333. const ttl = this.timeToLoad * 1e3 - (performance.now() - this.updated);
  19334. if (ttl > 0) {
  19335. this.scheduleRefresh(this.uri, ttl);
  19336. return;
  19337. }
  19338. }
  19339. this.loadSteeringManifest(this.uri);
  19340. }
  19341. }
  19342. stopLoad() {
  19343. this.started = false;
  19344. if (this.loader) {
  19345. this.loader.destroy();
  19346. this.loader = null;
  19347. }
  19348. this.clearTimeout();
  19349. }
  19350. clearTimeout() {
  19351. if (this.reloadTimer !== -1) {
  19352. self.clearTimeout(this.reloadTimer);
  19353. this.reloadTimer = -1;
  19354. }
  19355. }
  19356. destroy() {
  19357. this.unregisterListeners();
  19358. this.stopLoad();
  19359. this.hls = null;
  19360. this.levels = this.audioTracks = this.subtitleTracks = null;
  19361. }
  19362. removeLevel(levelToRemove) {
  19363. const levels = this.levels;
  19364. if (levels) {
  19365. this.levels = levels.filter((level) => level !== levelToRemove);
  19366. }
  19367. }
  19368. onManifestLoading() {
  19369. this.stopLoad();
  19370. this.enabled = true;
  19371. this.timeToLoad = 300;
  19372. this.updated = 0;
  19373. this.uri = null;
  19374. this.pathwayId = ".";
  19375. this.levels = this.audioTracks = this.subtitleTracks = null;
  19376. }
  19377. onManifestLoaded(event, data) {
  19378. const {
  19379. contentSteering
  19380. } = data;
  19381. if (contentSteering === null) {
  19382. return;
  19383. }
  19384. this.pathwayId = contentSteering.pathwayId;
  19385. this.uri = contentSteering.uri;
  19386. if (this.started) {
  19387. this.startLoad();
  19388. }
  19389. }
  19390. onManifestParsed(event, data) {
  19391. this.audioTracks = data.audioTracks;
  19392. this.subtitleTracks = data.subtitleTracks;
  19393. }
  19394. onError(event, data) {
  19395. const {
  19396. errorAction
  19397. } = data;
  19398. if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox && errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost) {
  19399. const levels = this.levels;
  19400. let pathwayPriority = this._pathwayPriority;
  19401. let errorPathway = this.pathwayId;
  19402. if (data.context) {
  19403. const {
  19404. groupId,
  19405. pathwayId,
  19406. type
  19407. } = data.context;
  19408. if (groupId && levels) {
  19409. errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway);
  19410. } else if (pathwayId) {
  19411. errorPathway = pathwayId;
  19412. }
  19413. }
  19414. if (!(errorPathway in this.penalizedPathways)) {
  19415. this.penalizedPathways[errorPathway] = performance.now();
  19416. }
  19417. if (!pathwayPriority && levels) {
  19418. pathwayPriority = this.pathways();
  19419. }
  19420. if (pathwayPriority && pathwayPriority.length > 1) {
  19421. this.updatePathwayPriority(pathwayPriority);
  19422. errorAction.resolved = this.pathwayId !== errorPathway;
  19423. }
  19424. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && !data.fatal) {
  19425. errorAction.resolved = true;
  19426. } else if (!errorAction.resolved) {
  19427. 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)}`);
  19428. }
  19429. }
  19430. }
  19431. filterParsedLevels(levels) {
  19432. this.levels = levels;
  19433. let pathwayLevels = this.getLevelsForPathway(this.pathwayId);
  19434. if (pathwayLevels.length === 0) {
  19435. const pathwayId = levels[0].pathwayId;
  19436. this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${pathwayId}"`);
  19437. pathwayLevels = this.getLevelsForPathway(pathwayId);
  19438. this.pathwayId = pathwayId;
  19439. }
  19440. if (pathwayLevels.length !== levels.length) {
  19441. this.log(`Found ${pathwayLevels.length}/${levels.length} levels in Pathway "${this.pathwayId}"`);
  19442. }
  19443. return pathwayLevels;
  19444. }
  19445. getLevelsForPathway(pathwayId) {
  19446. if (this.levels === null) {
  19447. return [];
  19448. }
  19449. return this.levels.filter((level) => pathwayId === level.pathwayId);
  19450. }
  19451. updatePathwayPriority(pathwayPriority) {
  19452. this._pathwayPriority = pathwayPriority;
  19453. let levels;
  19454. const penalizedPathways = this.penalizedPathways;
  19455. const now2 = performance.now();
  19456. Object.keys(penalizedPathways).forEach((pathwayId) => {
  19457. if (now2 - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {
  19458. delete penalizedPathways[pathwayId];
  19459. }
  19460. });
  19461. for (let i = 0; i < pathwayPriority.length; i++) {
  19462. const pathwayId = pathwayPriority[i];
  19463. if (pathwayId in penalizedPathways) {
  19464. continue;
  19465. }
  19466. if (pathwayId === this.pathwayId) {
  19467. return;
  19468. }
  19469. const selectedIndex = this.hls.nextLoadLevel;
  19470. const selectedLevel = this.hls.levels[selectedIndex];
  19471. levels = this.getLevelsForPathway(pathwayId);
  19472. if (levels.length > 0) {
  19473. this.log(`Setting Pathway to "${pathwayId}"`);
  19474. this.pathwayId = pathwayId;
  19475. reassignFragmentLevelIndexes(levels);
  19476. this.hls.trigger(Events.LEVELS_UPDATED, {
  19477. levels
  19478. });
  19479. const levelAfterChange = this.hls.levels[selectedIndex];
  19480. if (selectedLevel && levelAfterChange && this.levels) {
  19481. if (levelAfterChange.attrs["STABLE-VARIANT-ID"] !== selectedLevel.attrs["STABLE-VARIANT-ID"] && levelAfterChange.bitrate !== selectedLevel.bitrate) {
  19482. this.log(`Unstable Pathways change from bitrate ${selectedLevel.bitrate} to ${levelAfterChange.bitrate}`);
  19483. }
  19484. this.hls.nextLoadLevel = selectedIndex;
  19485. }
  19486. break;
  19487. }
  19488. }
  19489. }
  19490. getPathwayForGroupId(groupId, type, defaultPathway) {
  19491. const levels = this.getLevelsForPathway(defaultPathway).concat(this.levels || []);
  19492. for (let i = 0; i < levels.length; i++) {
  19493. if (type === PlaylistContextType.AUDIO_TRACK && levels[i].hasAudioGroup(groupId) || type === PlaylistContextType.SUBTITLE_TRACK && levels[i].hasSubtitleGroup(groupId)) {
  19494. return levels[i].pathwayId;
  19495. }
  19496. }
  19497. return defaultPathway;
  19498. }
  19499. clonePathways(pathwayClones) {
  19500. const levels = this.levels;
  19501. if (!levels) {
  19502. return;
  19503. }
  19504. const audioGroupCloneMap = {};
  19505. const subtitleGroupCloneMap = {};
  19506. pathwayClones.forEach((pathwayClone) => {
  19507. const {
  19508. ID: cloneId,
  19509. "BASE-ID": baseId,
  19510. "URI-REPLACEMENT": uriReplacement
  19511. } = pathwayClone;
  19512. if (levels.some((level) => level.pathwayId === cloneId)) {
  19513. return;
  19514. }
  19515. const clonedVariants = this.getLevelsForPathway(baseId).map((baseLevel) => {
  19516. const attributes = new AttrList(baseLevel.attrs);
  19517. attributes["PATHWAY-ID"] = cloneId;
  19518. const clonedAudioGroupId = attributes.AUDIO && `${attributes.AUDIO}_clone_${cloneId}`;
  19519. const clonedSubtitleGroupId = attributes.SUBTITLES && `${attributes.SUBTITLES}_clone_${cloneId}`;
  19520. if (clonedAudioGroupId) {
  19521. audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;
  19522. attributes.AUDIO = clonedAudioGroupId;
  19523. }
  19524. if (clonedSubtitleGroupId) {
  19525. subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;
  19526. attributes.SUBTITLES = clonedSubtitleGroupId;
  19527. }
  19528. const url = performUriReplacement(baseLevel.uri, attributes["STABLE-VARIANT-ID"], "PER-VARIANT-URIS", uriReplacement);
  19529. const clonedLevel = new Level({
  19530. attrs: attributes,
  19531. audioCodec: baseLevel.audioCodec,
  19532. bitrate: baseLevel.bitrate,
  19533. height: baseLevel.height,
  19534. name: baseLevel.name,
  19535. url,
  19536. videoCodec: baseLevel.videoCodec,
  19537. width: baseLevel.width
  19538. });
  19539. if (baseLevel.audioGroups) {
  19540. for (let i = 1; i < baseLevel.audioGroups.length; i++) {
  19541. clonedLevel.addGroupId("audio", `${baseLevel.audioGroups[i]}_clone_${cloneId}`);
  19542. }
  19543. }
  19544. if (baseLevel.subtitleGroups) {
  19545. for (let i = 1; i < baseLevel.subtitleGroups.length; i++) {
  19546. clonedLevel.addGroupId("text", `${baseLevel.subtitleGroups[i]}_clone_${cloneId}`);
  19547. }
  19548. }
  19549. return clonedLevel;
  19550. });
  19551. levels.push(...clonedVariants);
  19552. cloneRenditionGroups(this.audioTracks, audioGroupCloneMap, uriReplacement, cloneId);
  19553. cloneRenditionGroups(this.subtitleTracks, subtitleGroupCloneMap, uriReplacement, cloneId);
  19554. });
  19555. }
  19556. loadSteeringManifest(uri) {
  19557. const config = this.hls.config;
  19558. const Loader = config.loader;
  19559. if (this.loader) {
  19560. this.loader.destroy();
  19561. }
  19562. this.loader = new Loader(config);
  19563. let url;
  19564. try {
  19565. url = new self.URL(uri);
  19566. } catch (error) {
  19567. this.enabled = false;
  19568. this.log(`Failed to parse Steering Manifest URI: ${uri}`);
  19569. return;
  19570. }
  19571. if (url.protocol !== "data:") {
  19572. const throughput = (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;
  19573. url.searchParams.set("_HLS_pathway", this.pathwayId);
  19574. url.searchParams.set("_HLS_throughput", "" + throughput);
  19575. }
  19576. const context = {
  19577. responseType: "json",
  19578. url: url.href
  19579. };
  19580. const loadPolicy = config.steeringManifestLoadPolicy.default;
  19581. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  19582. const loaderConfig = {
  19583. loadPolicy,
  19584. timeout: loadPolicy.maxLoadTimeMs,
  19585. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  19586. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  19587. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  19588. };
  19589. const callbacks = {
  19590. onSuccess: (response, stats, context2, networkDetails) => {
  19591. this.log(`Loaded steering manifest: "${url}"`);
  19592. const steeringData = response.data;
  19593. if ((steeringData == null ? void 0 : steeringData.VERSION) !== 1) {
  19594. this.log(`Steering VERSION ${steeringData.VERSION} not supported!`);
  19595. return;
  19596. }
  19597. this.updated = performance.now();
  19598. this.timeToLoad = steeringData.TTL;
  19599. const {
  19600. "RELOAD-URI": reloadUri,
  19601. "PATHWAY-CLONES": pathwayClones,
  19602. "PATHWAY-PRIORITY": pathwayPriority
  19603. } = steeringData;
  19604. if (reloadUri) {
  19605. try {
  19606. this.uri = new self.URL(reloadUri, url).href;
  19607. } catch (error) {
  19608. this.enabled = false;
  19609. this.log(`Failed to parse Steering Manifest RELOAD-URI: ${reloadUri}`);
  19610. return;
  19611. }
  19612. }
  19613. this.scheduleRefresh(this.uri || context2.url);
  19614. if (pathwayClones) {
  19615. this.clonePathways(pathwayClones);
  19616. }
  19617. const loadedSteeringData = {
  19618. steeringManifest: steeringData,
  19619. url: url.toString()
  19620. };
  19621. this.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);
  19622. if (pathwayPriority) {
  19623. this.updatePathwayPriority(pathwayPriority);
  19624. }
  19625. },
  19626. onError: (error, context2, networkDetails, stats) => {
  19627. this.log(`Error loading steering manifest: ${error.code} ${error.text} (${context2.url})`);
  19628. this.stopLoad();
  19629. if (error.code === 410) {
  19630. this.enabled = false;
  19631. this.log(`Steering manifest ${context2.url} no longer available`);
  19632. return;
  19633. }
  19634. let ttl = this.timeToLoad * 1e3;
  19635. if (error.code === 429) {
  19636. const loader = this.loader;
  19637. if (typeof (loader == null ? void 0 : loader.getResponseHeader) === "function") {
  19638. const retryAfter = loader.getResponseHeader("Retry-After");
  19639. if (retryAfter) {
  19640. ttl = parseFloat(retryAfter) * 1e3;
  19641. }
  19642. }
  19643. this.log(`Steering manifest ${context2.url} rate limited`);
  19644. return;
  19645. }
  19646. this.scheduleRefresh(this.uri || context2.url, ttl);
  19647. },
  19648. onTimeout: (stats, context2, networkDetails) => {
  19649. this.log(`Timeout loading steering manifest (${context2.url})`);
  19650. this.scheduleRefresh(this.uri || context2.url);
  19651. }
  19652. };
  19653. this.log(`Requesting steering manifest: ${url}`);
  19654. this.loader.load(context, loaderConfig, callbacks);
  19655. }
  19656. scheduleRefresh(uri, ttlMs = this.timeToLoad * 1e3) {
  19657. this.clearTimeout();
  19658. this.reloadTimer = self.setTimeout(() => {
  19659. var _this$hls;
  19660. const media = (_this$hls = this.hls) == null ? void 0 : _this$hls.media;
  19661. if (media && !media.ended) {
  19662. this.loadSteeringManifest(uri);
  19663. return;
  19664. }
  19665. this.scheduleRefresh(uri, this.timeToLoad * 1e3);
  19666. }, ttlMs);
  19667. }
  19668. };
  19669. function cloneRenditionGroups(tracks, groupCloneMap, uriReplacement, cloneId) {
  19670. if (!tracks) {
  19671. return;
  19672. }
  19673. Object.keys(groupCloneMap).forEach((audioGroupId) => {
  19674. const clonedTracks = tracks.filter((track) => track.groupId === audioGroupId).map((track) => {
  19675. const clonedTrack = _extends({}, track);
  19676. clonedTrack.details = void 0;
  19677. clonedTrack.attrs = new AttrList(clonedTrack.attrs);
  19678. clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(track.url, track.attrs["STABLE-RENDITION-ID"], "PER-RENDITION-URIS", uriReplacement);
  19679. clonedTrack.groupId = clonedTrack.attrs["GROUP-ID"] = groupCloneMap[audioGroupId];
  19680. clonedTrack.attrs["PATHWAY-ID"] = cloneId;
  19681. return clonedTrack;
  19682. });
  19683. tracks.push(...clonedTracks);
  19684. });
  19685. }
  19686. function performUriReplacement(uri, stableId, perOptionKey, uriReplacement) {
  19687. const {
  19688. HOST: host,
  19689. PARAMS: params,
  19690. [perOptionKey]: perOptionUris
  19691. } = uriReplacement;
  19692. let perVariantUri;
  19693. if (stableId) {
  19694. perVariantUri = perOptionUris == null ? void 0 : perOptionUris[stableId];
  19695. if (perVariantUri) {
  19696. uri = perVariantUri;
  19697. }
  19698. }
  19699. const url = new self.URL(uri);
  19700. if (host && !perVariantUri) {
  19701. url.host = host;
  19702. }
  19703. if (params) {
  19704. Object.keys(params).sort().forEach((key) => {
  19705. if (key) {
  19706. url.searchParams.set(key, params[key]);
  19707. }
  19708. });
  19709. }
  19710. return url.href;
  19711. }
  19712. var EMEController = class _EMEController extends Logger {
  19713. constructor(hls) {
  19714. super("eme", hls.logger);
  19715. this.hls = void 0;
  19716. this.config = void 0;
  19717. this.media = null;
  19718. this.keyFormatPromise = null;
  19719. this.keySystemAccessPromises = {};
  19720. this._requestLicenseFailureCount = 0;
  19721. this.mediaKeySessions = [];
  19722. this.keyIdToKeySessionPromise = {};
  19723. this.mediaKeys = null;
  19724. this.setMediaKeysQueue = _EMEController.CDMCleanupPromise ? [_EMEController.CDMCleanupPromise] : [];
  19725. this.bannedKeyIds = {};
  19726. this.onMediaEncrypted = (event) => {
  19727. const {
  19728. initDataType,
  19729. initData
  19730. } = event;
  19731. const logMessage = `"${event.type}" event: init data type: "${initDataType}"`;
  19732. this.debug(logMessage);
  19733. if (initData === null) {
  19734. return;
  19735. }
  19736. if (!this.keyFormatPromise) {
  19737. let keySystems = Object.keys(this.keySystemAccessPromises);
  19738. if (!keySystems.length) {
  19739. keySystems = getKeySystemsForConfig(this.config);
  19740. }
  19741. const keyFormats = keySystems.map(keySystemDomainToKeySystemFormat).filter((k) => !!k);
  19742. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  19743. }
  19744. this.keyFormatPromise.then((keySystemFormat) => {
  19745. const keySystem = keySystemFormatToKeySystemDomain(keySystemFormat);
  19746. if (initDataType !== "sinf" || keySystem !== KeySystems.FAIRPLAY) {
  19747. this.log(`Ignoring "${event.type}" event with init data type: "${initDataType}" for selected key-system ${keySystem}`);
  19748. return;
  19749. }
  19750. let keyId;
  19751. try {
  19752. const json = bin2str(new Uint8Array(initData));
  19753. const sinf = base64Decode(JSON.parse(json).sinf);
  19754. const tenc = parseSinf(sinf);
  19755. if (!tenc) {
  19756. throw new Error(`'schm' box missing or not cbcs/cenc with schi > tenc`);
  19757. }
  19758. keyId = new Uint8Array(tenc.subarray(8, 24));
  19759. } catch (error) {
  19760. this.warn(`${logMessage} Failed to parse sinf: ${error}`);
  19761. return;
  19762. }
  19763. const keyIdHex = arrayToHex(keyId);
  19764. const {
  19765. keyIdToKeySessionPromise,
  19766. mediaKeySessions
  19767. } = this;
  19768. let keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex];
  19769. for (let i = 0; i < mediaKeySessions.length; i++) {
  19770. const keyContext = mediaKeySessions[i];
  19771. const decryptdata = keyContext.decryptdata;
  19772. if (!decryptdata.keyId) {
  19773. continue;
  19774. }
  19775. const oldKeyIdHex = arrayToHex(decryptdata.keyId);
  19776. if (arrayValuesMatch(keyId, decryptdata.keyId) || decryptdata.uri.replace(/-/g, "").indexOf(keyIdHex) !== -1) {
  19777. keySessionContextPromise = keyIdToKeySessionPromise[oldKeyIdHex];
  19778. if (!keySessionContextPromise) {
  19779. continue;
  19780. }
  19781. if (decryptdata.pssh) {
  19782. break;
  19783. }
  19784. delete keyIdToKeySessionPromise[oldKeyIdHex];
  19785. decryptdata.pssh = new Uint8Array(initData);
  19786. decryptdata.keyId = keyId;
  19787. keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex] = keySessionContextPromise.then(() => {
  19788. return this.generateRequestWithPreferredKeySession(keyContext, initDataType, initData, "encrypted-event-key-match");
  19789. });
  19790. keySessionContextPromise.catch((error) => this.handleError(error));
  19791. break;
  19792. }
  19793. }
  19794. if (!keySessionContextPromise) {
  19795. this.handleError(new Error(`Key ID ${keyIdHex} not encountered in playlist. Key-system sessions ${mediaKeySessions.length}.`));
  19796. }
  19797. }).catch((error) => this.handleError(error));
  19798. };
  19799. this.onWaitingForKey = (event) => {
  19800. this.log(`"${event.type}" event`);
  19801. };
  19802. this.hls = hls;
  19803. this.config = hls.config;
  19804. this.registerListeners();
  19805. }
  19806. destroy() {
  19807. this.onDestroying();
  19808. this.onMediaDetached();
  19809. const config = this.config;
  19810. config.requestMediaKeySystemAccessFunc = null;
  19811. config.licenseXhrSetup = config.licenseResponseCallback = void 0;
  19812. config.drmSystems = config.drmSystemOptions = {};
  19813. this.hls = this.config = this.keyIdToKeySessionPromise = null;
  19814. this.onMediaEncrypted = this.onWaitingForKey = null;
  19815. }
  19816. registerListeners() {
  19817. this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  19818. this.hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  19819. this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  19820. this.hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  19821. this.hls.on(Events.DESTROYING, this.onDestroying, this);
  19822. }
  19823. unregisterListeners() {
  19824. this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  19825. this.hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  19826. this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  19827. this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  19828. this.hls.off(Events.DESTROYING, this.onDestroying, this);
  19829. }
  19830. getLicenseServerUrl(keySystem) {
  19831. const {
  19832. drmSystems,
  19833. widevineLicenseUrl
  19834. } = this.config;
  19835. const keySystemConfiguration = drmSystems == null ? void 0 : drmSystems[keySystem];
  19836. if (keySystemConfiguration) {
  19837. return keySystemConfiguration.licenseUrl;
  19838. }
  19839. if (keySystem === KeySystems.WIDEVINE && widevineLicenseUrl) {
  19840. return widevineLicenseUrl;
  19841. }
  19842. }
  19843. getLicenseServerUrlOrThrow(keySystem) {
  19844. const url = this.getLicenseServerUrl(keySystem);
  19845. if (url === void 0) {
  19846. throw new Error(`no license server URL configured for key-system "${keySystem}"`);
  19847. }
  19848. return url;
  19849. }
  19850. getServerCertificateUrl(keySystem) {
  19851. const {
  19852. drmSystems
  19853. } = this.config;
  19854. const keySystemConfiguration = drmSystems == null ? void 0 : drmSystems[keySystem];
  19855. if (keySystemConfiguration) {
  19856. return keySystemConfiguration.serverCertificateUrl;
  19857. } else {
  19858. this.log(`No Server Certificate in config.drmSystems["${keySystem}"]`);
  19859. }
  19860. }
  19861. attemptKeySystemAccess(keySystemsToAttempt) {
  19862. const levels = this.hls.levels;
  19863. const uniqueCodec = (value, i, a) => !!value && a.indexOf(value) === i;
  19864. const audioCodecs = levels.map((level) => level.audioCodec).filter(uniqueCodec);
  19865. const videoCodecs = levels.map((level) => level.videoCodec).filter(uniqueCodec);
  19866. if (audioCodecs.length + videoCodecs.length === 0) {
  19867. videoCodecs.push("avc1.42e01e");
  19868. }
  19869. return new Promise((resolve, reject) => {
  19870. const attempt = (keySystems) => {
  19871. const keySystem = keySystems.shift();
  19872. this.getMediaKeysPromise(keySystem, audioCodecs, videoCodecs).then((mediaKeys) => resolve({
  19873. keySystem,
  19874. mediaKeys
  19875. })).catch((error) => {
  19876. if (keySystems.length) {
  19877. attempt(keySystems);
  19878. } else if (error instanceof EMEKeyError) {
  19879. reject(error);
  19880. } else {
  19881. reject(new EMEKeyError({
  19882. type: ErrorTypes.KEY_SYSTEM_ERROR,
  19883. details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,
  19884. error,
  19885. fatal: true
  19886. }, error.message));
  19887. }
  19888. });
  19889. };
  19890. attempt(keySystemsToAttempt);
  19891. });
  19892. }
  19893. requestMediaKeySystemAccess(keySystem, supportedConfigurations) {
  19894. const {
  19895. requestMediaKeySystemAccessFunc
  19896. } = this.config;
  19897. if (!(typeof requestMediaKeySystemAccessFunc === "function")) {
  19898. let errMessage = `Configured requestMediaKeySystemAccess is not a function ${requestMediaKeySystemAccessFunc}`;
  19899. if (requestMediaKeySystemAccess === null && self.location.protocol === "http:") {
  19900. errMessage = `navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`;
  19901. }
  19902. return Promise.reject(new Error(errMessage));
  19903. }
  19904. return requestMediaKeySystemAccessFunc(keySystem, supportedConfigurations);
  19905. }
  19906. getMediaKeysPromise(keySystem, audioCodecs, videoCodecs) {
  19907. var _keySystemAccessPromi;
  19908. const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this.config.drmSystemOptions || {});
  19909. let keySystemAccessPromises = this.keySystemAccessPromises[keySystem];
  19910. let keySystemAccess = (_keySystemAccessPromi = keySystemAccessPromises) == null ? void 0 : _keySystemAccessPromi.keySystemAccess;
  19911. if (!keySystemAccess) {
  19912. this.log(`Requesting encrypted media "${keySystem}" key-system access with config: ${stringify(mediaKeySystemConfigs)}`);
  19913. keySystemAccess = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);
  19914. const keySystemAccessPromisesNew = keySystemAccessPromises = this.keySystemAccessPromises[keySystem] = {
  19915. keySystemAccess
  19916. };
  19917. keySystemAccess.catch((error) => {
  19918. this.log(`Failed to obtain access to key-system "${keySystem}": ${error}`);
  19919. });
  19920. return keySystemAccess.then((mediaKeySystemAccess) => {
  19921. this.log(`Access for key-system "${mediaKeySystemAccess.keySystem}" obtained`);
  19922. const certificateRequest = this.fetchServerCertificate(keySystem);
  19923. this.log(`Create media-keys for "${keySystem}"`);
  19924. const mediaKeys = keySystemAccessPromisesNew.mediaKeys = mediaKeySystemAccess.createMediaKeys().then((mediaKeys2) => {
  19925. this.log(`Media-keys created for "${keySystem}"`);
  19926. keySystemAccessPromisesNew.hasMediaKeys = true;
  19927. return certificateRequest.then((certificate) => {
  19928. if (certificate) {
  19929. return this.setMediaKeysServerCertificate(mediaKeys2, keySystem, certificate);
  19930. }
  19931. return mediaKeys2;
  19932. });
  19933. });
  19934. mediaKeys.catch((error) => {
  19935. this.error(`Failed to create media-keys for "${keySystem}"}: ${error}`);
  19936. });
  19937. return mediaKeys;
  19938. });
  19939. }
  19940. return keySystemAccess.then(() => keySystemAccessPromises.mediaKeys);
  19941. }
  19942. createMediaKeySessionContext({
  19943. decryptdata,
  19944. keySystem,
  19945. mediaKeys
  19946. }) {
  19947. this.log(`Creating key-system session "${keySystem}" keyId: ${arrayToHex(decryptdata.keyId || [])} keyUri: ${decryptdata.uri}`);
  19948. const mediaKeysSession = mediaKeys.createSession();
  19949. const mediaKeySessionContext = {
  19950. decryptdata,
  19951. keySystem,
  19952. mediaKeys,
  19953. mediaKeysSession,
  19954. keyStatus: "status-pending"
  19955. };
  19956. this.mediaKeySessions.push(mediaKeySessionContext);
  19957. return mediaKeySessionContext;
  19958. }
  19959. renewKeySession(mediaKeySessionContext) {
  19960. const decryptdata = mediaKeySessionContext.decryptdata;
  19961. if (decryptdata.pssh) {
  19962. const keySessionContext = this.createMediaKeySessionContext(mediaKeySessionContext);
  19963. const keyId = getKeyIdString(decryptdata);
  19964. const scheme = "cenc";
  19965. this.keyIdToKeySessionPromise[keyId] = this.generateRequestWithPreferredKeySession(keySessionContext, scheme, decryptdata.pssh.buffer, "expired");
  19966. } else {
  19967. this.warn(`Could not renew expired session. Missing pssh initData.`);
  19968. }
  19969. this.removeSession(mediaKeySessionContext);
  19970. }
  19971. updateKeySession(mediaKeySessionContext, data) {
  19972. const keySession = mediaKeySessionContext.mediaKeysSession;
  19973. this.log(`Updating key-session "${keySession.sessionId}" for keyId ${arrayToHex(mediaKeySessionContext.decryptdata.keyId || [])}
  19974. } (data length: ${data.byteLength})`);
  19975. return keySession.update(data);
  19976. }
  19977. getSelectedKeySystemFormats() {
  19978. return Object.keys(this.keySystemAccessPromises).map((keySystem) => ({
  19979. keySystem,
  19980. hasMediaKeys: this.keySystemAccessPromises[keySystem].hasMediaKeys
  19981. })).filter(({
  19982. hasMediaKeys
  19983. }) => !!hasMediaKeys).map(({
  19984. keySystem
  19985. }) => keySystemDomainToKeySystemFormat(keySystem)).filter((keySystem) => !!keySystem);
  19986. }
  19987. getKeySystemAccess(keySystemsToAttempt) {
  19988. return this.getKeySystemSelectionPromise(keySystemsToAttempt).then(({
  19989. keySystem,
  19990. mediaKeys
  19991. }) => {
  19992. return this.attemptSetMediaKeys(keySystem, mediaKeys);
  19993. });
  19994. }
  19995. selectKeySystem(keySystemsToAttempt) {
  19996. return new Promise((resolve, reject) => {
  19997. this.getKeySystemSelectionPromise(keySystemsToAttempt).then(({
  19998. keySystem
  19999. }) => {
  20000. const keySystemFormat = keySystemDomainToKeySystemFormat(keySystem);
  20001. if (keySystemFormat) {
  20002. resolve(keySystemFormat);
  20003. } else {
  20004. reject(new Error(`Unable to find format for key-system "${keySystem}"`));
  20005. }
  20006. }).catch(reject);
  20007. });
  20008. }
  20009. selectKeySystemFormat(frag) {
  20010. const keyFormats = Object.keys(frag.levelkeys || {});
  20011. if (!this.keyFormatPromise) {
  20012. this.log(`Selecting key-system from fragment (sn: ${frag.sn} ${frag.type}: ${frag.level}) key formats ${keyFormats.join(", ")}`);
  20013. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  20014. }
  20015. return this.keyFormatPromise;
  20016. }
  20017. getKeyFormatPromise(keyFormats) {
  20018. const keySystemsInConfig = getKeySystemsForConfig(this.config);
  20019. const keySystemsToAttempt = keyFormats.map(keySystemFormatToKeySystemDomain).filter((value) => !!value && keySystemsInConfig.indexOf(value) !== -1);
  20020. return this.selectKeySystem(keySystemsToAttempt);
  20021. }
  20022. getKeyStatus(decryptdata) {
  20023. const {
  20024. mediaKeySessions
  20025. } = this;
  20026. for (let i = 0; i < mediaKeySessions.length; i++) {
  20027. const status2 = getKeyStatus(decryptdata, mediaKeySessions[i]);
  20028. if (status2) {
  20029. return status2;
  20030. }
  20031. }
  20032. return void 0;
  20033. }
  20034. loadKey(data) {
  20035. const decryptdata = data.keyInfo.decryptdata;
  20036. const keyId = getKeyIdString(decryptdata);
  20037. const badStatus = this.bannedKeyIds[keyId];
  20038. if (badStatus || this.getKeyStatus(decryptdata) === "internal-error") {
  20039. const error = getKeyStatusError(badStatus || "internal-error", decryptdata);
  20040. this.handleError(error, data.frag);
  20041. return Promise.reject(error);
  20042. }
  20043. const keyDetails = `(keyId: ${keyId} format: "${decryptdata.keyFormat}" method: ${decryptdata.method} uri: ${decryptdata.uri})`;
  20044. this.log(`Starting session for key ${keyDetails}`);
  20045. const keyContextPromise = this.keyIdToKeySessionPromise[keyId];
  20046. if (!keyContextPromise) {
  20047. const keySessionContextPromise = this.getKeySystemForKeyPromise(decryptdata).then(({
  20048. keySystem,
  20049. mediaKeys
  20050. }) => {
  20051. this.throwIfDestroyed();
  20052. this.log(`Handle encrypted media sn: ${data.frag.sn} ${data.frag.type}: ${data.frag.level} using key ${keyDetails}`);
  20053. return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => {
  20054. this.throwIfDestroyed();
  20055. return this.createMediaKeySessionContext({
  20056. keySystem,
  20057. mediaKeys,
  20058. decryptdata
  20059. });
  20060. });
  20061. }).then((keySessionContext) => {
  20062. const scheme = "cenc";
  20063. const initData = decryptdata.pssh ? decryptdata.pssh.buffer : null;
  20064. return this.generateRequestWithPreferredKeySession(keySessionContext, scheme, initData, "playlist-key");
  20065. });
  20066. keySessionContextPromise.catch((error) => this.handleError(error, data.frag));
  20067. this.keyIdToKeySessionPromise[keyId] = keySessionContextPromise;
  20068. return keySessionContextPromise;
  20069. }
  20070. keyContextPromise.catch((error) => {
  20071. if (error instanceof EMEKeyError) {
  20072. const errorData = _objectSpread2({}, error.data);
  20073. if (this.getKeyStatus(decryptdata) === "internal-error") {
  20074. errorData.decryptdata = decryptdata;
  20075. }
  20076. const clonedError = new EMEKeyError(errorData, error.message);
  20077. this.handleError(clonedError, data.frag);
  20078. }
  20079. });
  20080. return keyContextPromise;
  20081. }
  20082. throwIfDestroyed(message = "Invalid state") {
  20083. if (!this.hls) {
  20084. throw new Error("invalid state");
  20085. }
  20086. }
  20087. handleError(error, frag) {
  20088. if (!this.hls) {
  20089. return;
  20090. }
  20091. if (error instanceof EMEKeyError) {
  20092. if (frag) {
  20093. error.data.frag = frag;
  20094. }
  20095. const levelKey = error.data.decryptdata;
  20096. this.error(`${error.message}${levelKey ? ` (${arrayToHex(levelKey.keyId || [])})` : ""}`);
  20097. this.hls.trigger(Events.ERROR, error.data);
  20098. } else {
  20099. this.error(error.message);
  20100. this.hls.trigger(Events.ERROR, {
  20101. type: ErrorTypes.KEY_SYSTEM_ERROR,
  20102. details: ErrorDetails.KEY_SYSTEM_NO_KEYS,
  20103. error,
  20104. fatal: true
  20105. });
  20106. }
  20107. }
  20108. getKeySystemForKeyPromise(decryptdata) {
  20109. const keyId = getKeyIdString(decryptdata);
  20110. const mediaKeySessionContext = this.keyIdToKeySessionPromise[keyId];
  20111. if (!mediaKeySessionContext) {
  20112. const keySystem = keySystemFormatToKeySystemDomain(decryptdata.keyFormat);
  20113. const keySystemsToAttempt = keySystem ? [keySystem] : getKeySystemsForConfig(this.config);
  20114. return this.attemptKeySystemAccess(keySystemsToAttempt);
  20115. }
  20116. return mediaKeySessionContext;
  20117. }
  20118. getKeySystemSelectionPromise(keySystemsToAttempt) {
  20119. if (!keySystemsToAttempt.length) {
  20120. keySystemsToAttempt = getKeySystemsForConfig(this.config);
  20121. }
  20122. if (keySystemsToAttempt.length === 0) {
  20123. throw new EMEKeyError({
  20124. type: ErrorTypes.KEY_SYSTEM_ERROR,
  20125. details: ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,
  20126. fatal: true
  20127. }, `Missing key-system license configuration options ${stringify({
  20128. drmSystems: this.config.drmSystems
  20129. })}`);
  20130. }
  20131. return this.attemptKeySystemAccess(keySystemsToAttempt);
  20132. }
  20133. attemptSetMediaKeys(keySystem, mediaKeys) {
  20134. if (this.mediaKeys === mediaKeys) {
  20135. return Promise.resolve();
  20136. }
  20137. const queue = this.setMediaKeysQueue.slice();
  20138. this.log(`Setting media-keys for "${keySystem}"`);
  20139. const setMediaKeysPromise = Promise.all(queue).then(() => {
  20140. if (!this.media) {
  20141. this.mediaKeys = null;
  20142. throw new Error("Attempted to set mediaKeys without media element attached");
  20143. }
  20144. return this.media.setMediaKeys(mediaKeys);
  20145. });
  20146. this.mediaKeys = mediaKeys;
  20147. this.setMediaKeysQueue.push(setMediaKeysPromise);
  20148. return setMediaKeysPromise.then(() => {
  20149. this.log(`Media-keys set for "${keySystem}"`);
  20150. queue.push(setMediaKeysPromise);
  20151. this.setMediaKeysQueue = this.setMediaKeysQueue.filter((p) => queue.indexOf(p) === -1);
  20152. });
  20153. }
  20154. generateRequestWithPreferredKeySession(context, initDataType, initData, reason) {
  20155. var _this$config$drmSyste;
  20156. const generateRequestFilter = (_this$config$drmSyste = this.config.drmSystems) == null || (_this$config$drmSyste = _this$config$drmSyste[context.keySystem]) == null ? void 0 : _this$config$drmSyste.generateRequest;
  20157. if (generateRequestFilter) {
  20158. try {
  20159. const mappedInitData = generateRequestFilter.call(this.hls, initDataType, initData, context);
  20160. if (!mappedInitData) {
  20161. throw new Error("Invalid response from configured generateRequest filter");
  20162. }
  20163. initDataType = mappedInitData.initDataType;
  20164. initData = mappedInitData.initData ? mappedInitData.initData : null;
  20165. context.decryptdata.pssh = initData ? new Uint8Array(initData) : null;
  20166. } catch (error) {
  20167. this.warn(error.message);
  20168. if (this.hls && this.hls.config.debug) {
  20169. throw error;
  20170. }
  20171. }
  20172. }
  20173. if (initData === null) {
  20174. this.log(`Skipping key-session request for "${reason}" (no initData)`);
  20175. return Promise.resolve(context);
  20176. }
  20177. const keyId = getKeyIdString(context.decryptdata);
  20178. const keyUri = context.decryptdata.uri;
  20179. this.log(`Generating key-session request for "${reason}" keyId: ${keyId} URI: ${keyUri} (init data type: ${initDataType} length: ${initData.byteLength})`);
  20180. const licenseStatus = new EventEmitter();
  20181. const onmessage = context._onmessage = (event) => {
  20182. const keySession = context.mediaKeysSession;
  20183. if (!keySession) {
  20184. licenseStatus.emit("error", new Error("invalid state"));
  20185. return;
  20186. }
  20187. const {
  20188. messageType,
  20189. message
  20190. } = event;
  20191. this.log(`"${messageType}" message event for session "${keySession.sessionId}" message size: ${message.byteLength}`);
  20192. if (messageType === "license-request" || messageType === "license-renewal") {
  20193. this.renewLicense(context, message).catch((error) => {
  20194. if (licenseStatus.eventNames().length) {
  20195. licenseStatus.emit("error", error);
  20196. } else {
  20197. this.handleError(error);
  20198. }
  20199. });
  20200. } else if (messageType === "license-release") {
  20201. if (context.keySystem === KeySystems.FAIRPLAY) {
  20202. this.updateKeySession(context, strToUtf8array("acknowledged")).then(() => this.removeSession(context)).catch((error) => this.handleError(error));
  20203. }
  20204. } else {
  20205. this.warn(`unhandled media key message type "${messageType}"`);
  20206. }
  20207. };
  20208. const handleKeyStatus = (keyStatus, context2) => {
  20209. context2.keyStatus = keyStatus;
  20210. let keyError;
  20211. if (keyStatus.startsWith("usable")) {
  20212. licenseStatus.emit("resolved");
  20213. } else if (keyStatus === "internal-error" || keyStatus === "output-restricted" || keyStatus === "output-downscaled") {
  20214. keyError = getKeyStatusError(keyStatus, context2.decryptdata);
  20215. } else if (keyStatus === "expired") {
  20216. keyError = new Error(`key expired (keyId: ${keyId})`);
  20217. } else if (keyStatus === "released") {
  20218. keyError = new Error(`key released`);
  20219. } else if (keyStatus === "status-pending")
  20220. ;
  20221. else {
  20222. this.warn(`unhandled key status change "${keyStatus}" (keyId: ${keyId})`);
  20223. }
  20224. if (keyError) {
  20225. if (licenseStatus.eventNames().length) {
  20226. licenseStatus.emit("error", keyError);
  20227. } else {
  20228. this.handleError(keyError);
  20229. }
  20230. }
  20231. };
  20232. const onkeystatuseschange = context._onkeystatuseschange = (event) => {
  20233. const keySession = context.mediaKeysSession;
  20234. if (!keySession) {
  20235. licenseStatus.emit("error", new Error("invalid state"));
  20236. return;
  20237. }
  20238. const keyStatuses = this.getKeyStatuses(context);
  20239. const keyIds = Object.keys(keyStatuses);
  20240. if (!keyIds.some((id) => keyStatuses[id] !== "status-pending")) {
  20241. return;
  20242. }
  20243. if (keyStatuses[keyId] === "expired") {
  20244. this.log(`Expired key ${stringify(keyStatuses)} in key-session "${context.mediaKeysSession.sessionId}"`);
  20245. this.renewKeySession(context);
  20246. return;
  20247. }
  20248. let keyStatus = keyStatuses[keyId];
  20249. if (keyStatus) {
  20250. handleKeyStatus(keyStatus, context);
  20251. } else {
  20252. var _context$keyStatusTim;
  20253. const timeout = 1e3;
  20254. context.keyStatusTimeouts || (context.keyStatusTimeouts = {});
  20255. (_context$keyStatusTim = context.keyStatusTimeouts)[keyId] || (_context$keyStatusTim[keyId] = self.setTimeout(() => {
  20256. if (!context.mediaKeysSession || !this.mediaKeys) {
  20257. return;
  20258. }
  20259. const sessionKeyStatus = this.getKeyStatus(context.decryptdata);
  20260. if (sessionKeyStatus && sessionKeyStatus !== "status-pending") {
  20261. this.log(`No status for keyId ${keyId} in key-session "${context.mediaKeysSession.sessionId}". Using session key-status ${sessionKeyStatus} from other session.`);
  20262. return handleKeyStatus(sessionKeyStatus, context);
  20263. }
  20264. this.log(`key status for ${keyId} in key-session "${context.mediaKeysSession.sessionId}" timed out after ${timeout}ms`);
  20265. keyStatus = "internal-error";
  20266. handleKeyStatus(keyStatus, context);
  20267. }, timeout));
  20268. this.log(`No status for keyId ${keyId} (${stringify(keyStatuses)}).`);
  20269. }
  20270. };
  20271. addEventListener(context.mediaKeysSession, "message", onmessage);
  20272. addEventListener(context.mediaKeysSession, "keystatuseschange", onkeystatuseschange);
  20273. const keyUsablePromise = new Promise((resolve, reject) => {
  20274. licenseStatus.on("error", reject);
  20275. licenseStatus.on("resolved", resolve);
  20276. });
  20277. return context.mediaKeysSession.generateRequest(initDataType, initData).then(() => {
  20278. this.log(`Request generated for key-session "${context.mediaKeysSession.sessionId}" keyId: ${keyId} URI: ${keyUri}`);
  20279. }).catch((error) => {
  20280. throw new EMEKeyError({
  20281. type: ErrorTypes.KEY_SYSTEM_ERROR,
  20282. details: ErrorDetails.KEY_SYSTEM_NO_SESSION,
  20283. error,
  20284. decryptdata: context.decryptdata,
  20285. fatal: false
  20286. }, `Error generating key-session request: ${error}`);
  20287. }).then(() => keyUsablePromise).catch((error) => {
  20288. licenseStatus.removeAllListeners();
  20289. return this.removeSession(context).then(() => {
  20290. throw error;
  20291. });
  20292. }).then(() => {
  20293. licenseStatus.removeAllListeners();
  20294. return context;
  20295. });
  20296. }
  20297. getKeyStatuses(mediaKeySessionContext) {
  20298. const keyStatuses = {};
  20299. mediaKeySessionContext.mediaKeysSession.keyStatuses.forEach((status2, keyId) => {
  20300. if (typeof keyId === "string" && typeof status2 === "object") {
  20301. const temp = keyId;
  20302. keyId = status2;
  20303. status2 = temp;
  20304. }
  20305. const keyIdArray = "buffer" in keyId ? new Uint8Array(keyId.buffer, keyId.byteOffset, keyId.byteLength) : new Uint8Array(keyId);
  20306. if (mediaKeySessionContext.keySystem === KeySystems.PLAYREADY && keyIdArray.length === 16) {
  20307. changeEndianness(keyIdArray);
  20308. }
  20309. const keyIdWithStatusChange = arrayToHex(keyIdArray);
  20310. if (status2 === "internal-error") {
  20311. this.bannedKeyIds[keyIdWithStatusChange] = status2;
  20312. }
  20313. this.log(`key status change "${status2}" for keyStatuses keyId: ${keyIdWithStatusChange} key-session "${mediaKeySessionContext.mediaKeysSession.sessionId}"`);
  20314. keyStatuses[keyIdWithStatusChange] = status2;
  20315. });
  20316. return keyStatuses;
  20317. }
  20318. fetchServerCertificate(keySystem) {
  20319. const config = this.config;
  20320. const Loader = config.loader;
  20321. const certLoader = new Loader(config);
  20322. const url = this.getServerCertificateUrl(keySystem);
  20323. if (!url) {
  20324. return Promise.resolve();
  20325. }
  20326. this.log(`Fetching server certificate for "${keySystem}"`);
  20327. return new Promise((resolve, reject) => {
  20328. const loaderContext = {
  20329. responseType: "arraybuffer",
  20330. url
  20331. };
  20332. const loadPolicy = config.certLoadPolicy.default;
  20333. const loaderConfig = {
  20334. loadPolicy,
  20335. timeout: loadPolicy.maxLoadTimeMs,
  20336. maxRetry: 0,
  20337. retryDelay: 0,
  20338. maxRetryDelay: 0
  20339. };
  20340. const loaderCallbacks = {
  20341. onSuccess: (response, stats, context, networkDetails) => {
  20342. resolve(response.data);
  20343. },
  20344. onError: (response, contex, networkDetails, stats) => {
  20345. reject(new EMEKeyError({
  20346. type: ErrorTypes.KEY_SYSTEM_ERROR,
  20347. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  20348. fatal: true,
  20349. networkDetails,
  20350. response: _objectSpread2({
  20351. url: loaderContext.url,
  20352. data: void 0
  20353. }, response)
  20354. }, `"${keySystem}" certificate request failed (${url}). Status: ${response.code} (${response.text})`));
  20355. },
  20356. onTimeout: (stats, context, networkDetails) => {
  20357. reject(new EMEKeyError({
  20358. type: ErrorTypes.KEY_SYSTEM_ERROR,
  20359. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  20360. fatal: true,
  20361. networkDetails,
  20362. response: {
  20363. url: loaderContext.url,
  20364. data: void 0
  20365. }
  20366. }, `"${keySystem}" certificate request timed out (${url})`));
  20367. },
  20368. onAbort: (stats, context, networkDetails) => {
  20369. reject(new Error("aborted"));
  20370. }
  20371. };
  20372. certLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  20373. });
  20374. }
  20375. setMediaKeysServerCertificate(mediaKeys, keySystem, cert) {
  20376. return new Promise((resolve, reject) => {
  20377. mediaKeys.setServerCertificate(cert).then((success) => {
  20378. this.log(`setServerCertificate ${success ? "success" : "not supported by CDM"} (${cert.byteLength}) on "${keySystem}"`);
  20379. resolve(mediaKeys);
  20380. }).catch((error) => {
  20381. reject(new EMEKeyError({
  20382. type: ErrorTypes.KEY_SYSTEM_ERROR,
  20383. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,
  20384. error,
  20385. fatal: true
  20386. }, error.message));
  20387. });
  20388. });
  20389. }
  20390. renewLicense(context, keyMessage) {
  20391. return this.requestLicense(context, new Uint8Array(keyMessage)).then((data) => {
  20392. return this.updateKeySession(context, new Uint8Array(data)).catch((error) => {
  20393. throw new EMEKeyError({
  20394. type: ErrorTypes.KEY_SYSTEM_ERROR,
  20395. details: ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,
  20396. decryptdata: context.decryptdata,
  20397. error,
  20398. fatal: false
  20399. }, error.message);
  20400. });
  20401. });
  20402. }
  20403. unpackPlayReadyKeyMessage(xhr, licenseChallenge) {
  20404. const xmlString = String.fromCharCode.apply(null, new Uint16Array(licenseChallenge.buffer));
  20405. if (!xmlString.includes("PlayReadyKeyMessage")) {
  20406. xhr.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  20407. return licenseChallenge;
  20408. }
  20409. const keyMessageXml = new DOMParser().parseFromString(xmlString, "application/xml");
  20410. const headers = keyMessageXml.querySelectorAll("HttpHeader");
  20411. if (headers.length > 0) {
  20412. let header;
  20413. for (let i = 0, len = headers.length; i < len; i++) {
  20414. var _header$querySelector, _header$querySelector2;
  20415. header = headers[i];
  20416. const name = (_header$querySelector = header.querySelector("name")) == null ? void 0 : _header$querySelector.textContent;
  20417. const value = (_header$querySelector2 = header.querySelector("value")) == null ? void 0 : _header$querySelector2.textContent;
  20418. if (name && value) {
  20419. xhr.setRequestHeader(name, value);
  20420. }
  20421. }
  20422. }
  20423. const challengeElement = keyMessageXml.querySelector("Challenge");
  20424. const challengeText = challengeElement == null ? void 0 : challengeElement.textContent;
  20425. if (!challengeText) {
  20426. throw new Error(`Cannot find <Challenge> in key message`);
  20427. }
  20428. return strToUtf8array(atob(challengeText));
  20429. }
  20430. setupLicenseXHR(xhr, url, keysListItem, licenseChallenge) {
  20431. const licenseXhrSetup = this.config.licenseXhrSetup;
  20432. if (!licenseXhrSetup) {
  20433. xhr.open("POST", url, true);
  20434. return Promise.resolve({
  20435. xhr,
  20436. licenseChallenge
  20437. });
  20438. }
  20439. return Promise.resolve().then(() => {
  20440. if (!keysListItem.decryptdata) {
  20441. throw new Error("Key removed");
  20442. }
  20443. return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);
  20444. }).catch((error) => {
  20445. if (!keysListItem.decryptdata) {
  20446. throw error;
  20447. }
  20448. xhr.open("POST", url, true);
  20449. return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);
  20450. }).then((licenseXhrSetupResult) => {
  20451. if (!xhr.readyState) {
  20452. xhr.open("POST", url, true);
  20453. }
  20454. const finalLicenseChallenge = licenseXhrSetupResult ? licenseXhrSetupResult : licenseChallenge;
  20455. return {
  20456. xhr,
  20457. licenseChallenge: finalLicenseChallenge
  20458. };
  20459. });
  20460. }
  20461. requestLicense(keySessionContext, licenseChallenge) {
  20462. const keyLoadPolicy = this.config.keyLoadPolicy.default;
  20463. return new Promise((resolve, reject) => {
  20464. const url = this.getLicenseServerUrlOrThrow(keySessionContext.keySystem);
  20465. this.log(`Sending license request to URL: ${url}`);
  20466. const xhr = new XMLHttpRequest();
  20467. xhr.responseType = "arraybuffer";
  20468. xhr.onreadystatechange = () => {
  20469. if (!this.hls || !keySessionContext.mediaKeysSession) {
  20470. return reject(new Error("invalid state"));
  20471. }
  20472. if (xhr.readyState === 4) {
  20473. if (xhr.status === 200) {
  20474. this._requestLicenseFailureCount = 0;
  20475. let data = xhr.response;
  20476. this.log(`License received ${data instanceof ArrayBuffer ? data.byteLength : data}`);
  20477. const licenseResponseCallback = this.config.licenseResponseCallback;
  20478. if (licenseResponseCallback) {
  20479. try {
  20480. data = licenseResponseCallback.call(this.hls, xhr, url, keySessionContext);
  20481. } catch (error) {
  20482. this.error(error);
  20483. }
  20484. }
  20485. resolve(data);
  20486. } else {
  20487. const retryConfig = keyLoadPolicy.errorRetry;
  20488. const maxNumRetry = retryConfig ? retryConfig.maxNumRetry : 0;
  20489. this._requestLicenseFailureCount++;
  20490. if (this._requestLicenseFailureCount > maxNumRetry || xhr.status >= 400 && xhr.status < 500) {
  20491. reject(new EMEKeyError({
  20492. type: ErrorTypes.KEY_SYSTEM_ERROR,
  20493. details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  20494. decryptdata: keySessionContext.decryptdata,
  20495. fatal: true,
  20496. networkDetails: xhr,
  20497. response: {
  20498. url,
  20499. data: void 0,
  20500. code: xhr.status,
  20501. text: xhr.statusText
  20502. }
  20503. }, `License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`));
  20504. } else {
  20505. const attemptsLeft = maxNumRetry - this._requestLicenseFailureCount + 1;
  20506. this.warn(`Retrying license request, ${attemptsLeft} attempts left`);
  20507. this.requestLicense(keySessionContext, licenseChallenge).then(resolve, reject);
  20508. }
  20509. }
  20510. }
  20511. };
  20512. if (keySessionContext.licenseXhr && keySessionContext.licenseXhr.readyState !== XMLHttpRequest.DONE) {
  20513. keySessionContext.licenseXhr.abort();
  20514. }
  20515. keySessionContext.licenseXhr = xhr;
  20516. this.setupLicenseXHR(xhr, url, keySessionContext, licenseChallenge).then(({
  20517. xhr: xhr2,
  20518. licenseChallenge: licenseChallenge2
  20519. }) => {
  20520. if (keySessionContext.keySystem == KeySystems.PLAYREADY) {
  20521. licenseChallenge2 = this.unpackPlayReadyKeyMessage(xhr2, licenseChallenge2);
  20522. }
  20523. xhr2.send(licenseChallenge2);
  20524. }).catch(reject);
  20525. });
  20526. }
  20527. onDestroying() {
  20528. this.unregisterListeners();
  20529. this._clear();
  20530. }
  20531. onMediaAttached(event, data) {
  20532. if (!this.config.emeEnabled) {
  20533. return;
  20534. }
  20535. const media = data.media;
  20536. this.media = media;
  20537. addEventListener(media, "encrypted", this.onMediaEncrypted);
  20538. addEventListener(media, "waitingforkey", this.onWaitingForKey);
  20539. }
  20540. onMediaDetached() {
  20541. const media = this.media;
  20542. if (media) {
  20543. removeEventListener(media, "encrypted", this.onMediaEncrypted);
  20544. removeEventListener(media, "waitingforkey", this.onWaitingForKey);
  20545. this.media = null;
  20546. this.mediaKeys = null;
  20547. }
  20548. }
  20549. _clear() {
  20550. var _media$setMediaKeys;
  20551. this._requestLicenseFailureCount = 0;
  20552. this.keyIdToKeySessionPromise = {};
  20553. this.bannedKeyIds = {};
  20554. if (!this.mediaKeys && !this.mediaKeySessions.length) {
  20555. return;
  20556. }
  20557. const media = this.media;
  20558. const mediaKeysList = this.mediaKeySessions.slice();
  20559. this.mediaKeySessions = [];
  20560. this.mediaKeys = null;
  20561. LevelKey.clearKeyUriToKeyIdMap();
  20562. const keySessionCount = mediaKeysList.length;
  20563. _EMEController.CDMCleanupPromise = Promise.all(mediaKeysList.map((mediaKeySessionContext) => this.removeSession(mediaKeySessionContext)).concat((media == null || (_media$setMediaKeys = media.setMediaKeys(null)) == null ? void 0 : _media$setMediaKeys.catch((error) => {
  20564. this.log(`Could not clear media keys: ${error}`);
  20565. if (!this.hls)
  20566. return;
  20567. this.hls.trigger(Events.ERROR, {
  20568. type: ErrorTypes.OTHER_ERROR,
  20569. details: ErrorDetails.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,
  20570. fatal: false,
  20571. error: new Error(`Could not clear media keys: ${error}`)
  20572. });
  20573. })) || Promise.resolve())).catch((error) => {
  20574. this.log(`Could not close sessions and clear media keys: ${error}`);
  20575. if (!this.hls)
  20576. return;
  20577. this.hls.trigger(Events.ERROR, {
  20578. type: ErrorTypes.OTHER_ERROR,
  20579. details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
  20580. fatal: false,
  20581. error: new Error(`Could not close sessions and clear media keys: ${error}`)
  20582. });
  20583. }).then(() => {
  20584. if (keySessionCount) {
  20585. this.log("finished closing key sessions and clearing media keys");
  20586. }
  20587. });
  20588. }
  20589. onManifestLoading() {
  20590. this.keyFormatPromise = null;
  20591. this.bannedKeyIds = {};
  20592. }
  20593. onManifestLoaded(event, {
  20594. sessionKeys
  20595. }) {
  20596. if (!sessionKeys || !this.config.emeEnabled) {
  20597. return;
  20598. }
  20599. if (!this.keyFormatPromise) {
  20600. const keyFormats = sessionKeys.reduce((formats, sessionKey) => {
  20601. if (formats.indexOf(sessionKey.keyFormat) === -1) {
  20602. formats.push(sessionKey.keyFormat);
  20603. }
  20604. return formats;
  20605. }, []);
  20606. this.log(`Selecting key-system from session-keys ${keyFormats.join(", ")}`);
  20607. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  20608. }
  20609. }
  20610. removeSession(mediaKeySessionContext) {
  20611. const {
  20612. mediaKeysSession,
  20613. licenseXhr,
  20614. decryptdata
  20615. } = mediaKeySessionContext;
  20616. if (mediaKeysSession) {
  20617. this.log(`Remove licenses and keys and close session "${mediaKeysSession.sessionId}" keyId: ${arrayToHex((decryptdata == null ? void 0 : decryptdata.keyId) || [])}`);
  20618. if (mediaKeySessionContext._onmessage) {
  20619. mediaKeysSession.removeEventListener("message", mediaKeySessionContext._onmessage);
  20620. mediaKeySessionContext._onmessage = void 0;
  20621. }
  20622. if (mediaKeySessionContext._onkeystatuseschange) {
  20623. mediaKeysSession.removeEventListener("keystatuseschange", mediaKeySessionContext._onkeystatuseschange);
  20624. mediaKeySessionContext._onkeystatuseschange = void 0;
  20625. }
  20626. if (licenseXhr && licenseXhr.readyState !== XMLHttpRequest.DONE) {
  20627. licenseXhr.abort();
  20628. }
  20629. mediaKeySessionContext.mediaKeysSession = mediaKeySessionContext.decryptdata = mediaKeySessionContext.licenseXhr = void 0;
  20630. const index = this.mediaKeySessions.indexOf(mediaKeySessionContext);
  20631. if (index > -1) {
  20632. this.mediaKeySessions.splice(index, 1);
  20633. }
  20634. const {
  20635. keyStatusTimeouts
  20636. } = mediaKeySessionContext;
  20637. if (keyStatusTimeouts) {
  20638. Object.keys(keyStatusTimeouts).forEach((keyId) => self.clearTimeout(keyStatusTimeouts[keyId]));
  20639. }
  20640. const {
  20641. drmSystemOptions
  20642. } = this.config;
  20643. const removePromise = isPersistentSessionType(drmSystemOptions) ? new Promise((resolve, reject) => {
  20644. self.setTimeout(() => reject(new Error(`MediaKeySession.remove() timeout`)), 8e3);
  20645. mediaKeysSession.remove().then(resolve).catch(reject);
  20646. }) : Promise.resolve();
  20647. return removePromise.catch((error) => {
  20648. this.log(`Could not remove session: ${error}`);
  20649. if (!this.hls)
  20650. return;
  20651. this.hls.trigger(Events.ERROR, {
  20652. type: ErrorTypes.OTHER_ERROR,
  20653. details: ErrorDetails.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,
  20654. fatal: false,
  20655. error: new Error(`Could not remove session: ${error}`)
  20656. });
  20657. }).then(() => {
  20658. return mediaKeysSession.close();
  20659. }).catch((error) => {
  20660. this.log(`Could not close session: ${error}`);
  20661. if (!this.hls)
  20662. return;
  20663. this.hls.trigger(Events.ERROR, {
  20664. type: ErrorTypes.OTHER_ERROR,
  20665. details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
  20666. fatal: false,
  20667. error: new Error(`Could not close session: ${error}`)
  20668. });
  20669. });
  20670. }
  20671. return Promise.resolve();
  20672. }
  20673. };
  20674. EMEController.CDMCleanupPromise = void 0;
  20675. function getKeyIdString(decryptdata) {
  20676. if (!decryptdata) {
  20677. throw new Error("Could not read keyId of undefined decryptdata");
  20678. }
  20679. if (decryptdata.keyId === null) {
  20680. throw new Error("keyId is null");
  20681. }
  20682. return arrayToHex(decryptdata.keyId);
  20683. }
  20684. function getKeyStatus(decryptdata, keyContext) {
  20685. if (decryptdata.keyId && keyContext.mediaKeysSession.keyStatuses.has(decryptdata.keyId)) {
  20686. return keyContext.mediaKeysSession.keyStatuses.get(decryptdata.keyId);
  20687. }
  20688. if (decryptdata.matches(keyContext.decryptdata)) {
  20689. return keyContext.keyStatus;
  20690. }
  20691. return void 0;
  20692. }
  20693. var EMEKeyError = class extends Error {
  20694. constructor(data, message) {
  20695. super(message);
  20696. this.data = void 0;
  20697. data.error || (data.error = new Error(message));
  20698. this.data = data;
  20699. data.err = data.error;
  20700. }
  20701. };
  20702. function getKeyStatusError(keyStatus, decryptdata) {
  20703. const outputRestricted = keyStatus === "output-restricted";
  20704. const details = outputRestricted ? ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED : ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR;
  20705. return new EMEKeyError({
  20706. type: ErrorTypes.KEY_SYSTEM_ERROR,
  20707. details,
  20708. fatal: false,
  20709. decryptdata
  20710. }, outputRestricted ? "HDCP level output restricted" : `key status changed to "${keyStatus}"`);
  20711. }
  20712. var FPSController = class {
  20713. constructor(hls) {
  20714. this.hls = void 0;
  20715. this.isVideoPlaybackQualityAvailable = false;
  20716. this.timer = void 0;
  20717. this.media = null;
  20718. this.lastTime = void 0;
  20719. this.lastDroppedFrames = 0;
  20720. this.lastDecodedFrames = 0;
  20721. this.streamController = void 0;
  20722. this.hls = hls;
  20723. this.registerListeners();
  20724. }
  20725. setStreamController(streamController) {
  20726. this.streamController = streamController;
  20727. }
  20728. registerListeners() {
  20729. this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  20730. this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  20731. }
  20732. unregisterListeners() {
  20733. this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  20734. this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  20735. }
  20736. destroy() {
  20737. if (this.timer) {
  20738. clearInterval(this.timer);
  20739. }
  20740. this.unregisterListeners();
  20741. this.isVideoPlaybackQualityAvailable = false;
  20742. this.media = null;
  20743. }
  20744. onMediaAttaching(event, data) {
  20745. const config = this.hls.config;
  20746. if (config.capLevelOnFPSDrop) {
  20747. const media = data.media instanceof self.HTMLVideoElement ? data.media : null;
  20748. this.media = media;
  20749. if (media && typeof media.getVideoPlaybackQuality === "function") {
  20750. this.isVideoPlaybackQualityAvailable = true;
  20751. }
  20752. self.clearInterval(this.timer);
  20753. this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  20754. }
  20755. }
  20756. onMediaDetaching() {
  20757. this.media = null;
  20758. }
  20759. checkFPS(video, decodedFrames, droppedFrames) {
  20760. const currentTime = performance.now();
  20761. if (decodedFrames) {
  20762. if (this.lastTime) {
  20763. const currentPeriod = currentTime - this.lastTime;
  20764. const currentDropped = droppedFrames - this.lastDroppedFrames;
  20765. const currentDecoded = decodedFrames - this.lastDecodedFrames;
  20766. const droppedFPS = 1e3 * currentDropped / currentPeriod;
  20767. const hls = this.hls;
  20768. hls.trigger(Events.FPS_DROP, {
  20769. currentDropped,
  20770. currentDecoded,
  20771. totalDroppedFrames: droppedFrames
  20772. });
  20773. if (droppedFPS > 0) {
  20774. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  20775. let currentLevel = hls.currentLevel;
  20776. hls.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: " + currentLevel);
  20777. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  20778. currentLevel = currentLevel - 1;
  20779. hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {
  20780. level: currentLevel,
  20781. droppedLevel: hls.currentLevel
  20782. });
  20783. hls.autoLevelCapping = currentLevel;
  20784. this.streamController.nextLevelSwitch();
  20785. }
  20786. }
  20787. }
  20788. }
  20789. this.lastTime = currentTime;
  20790. this.lastDroppedFrames = droppedFrames;
  20791. this.lastDecodedFrames = decodedFrames;
  20792. }
  20793. }
  20794. checkFPSInterval() {
  20795. const video = this.media;
  20796. if (video) {
  20797. if (this.isVideoPlaybackQualityAvailable) {
  20798. const videoPlaybackQuality = video.getVideoPlaybackQuality();
  20799. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  20800. } else {
  20801. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  20802. }
  20803. }
  20804. }
  20805. };
  20806. function sendAddTrackEvent(track, videoEl) {
  20807. let event;
  20808. try {
  20809. event = new Event("addtrack");
  20810. } catch (err) {
  20811. event = document.createEvent("Event");
  20812. event.initEvent("addtrack", false, false);
  20813. }
  20814. event.track = track;
  20815. videoEl.dispatchEvent(event);
  20816. }
  20817. function addCueToTrack(track, cue) {
  20818. const mode = track.mode;
  20819. if (mode === "disabled") {
  20820. track.mode = "hidden";
  20821. }
  20822. if (track.cues && !track.cues.getCueById(cue.id)) {
  20823. try {
  20824. track.addCue(cue);
  20825. if (!track.cues.getCueById(cue.id)) {
  20826. throw new Error(`addCue is failed for: ${cue}`);
  20827. }
  20828. } catch (err) {
  20829. logger.debug(`[texttrack-utils]: ${err}`);
  20830. try {
  20831. const textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);
  20832. textTrackCue.id = cue.id;
  20833. track.addCue(textTrackCue);
  20834. } catch (err2) {
  20835. logger.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${err2}`);
  20836. }
  20837. }
  20838. }
  20839. if (mode === "disabled") {
  20840. track.mode = mode;
  20841. }
  20842. }
  20843. function clearCurrentCues(track, enterHandler) {
  20844. const mode = track.mode;
  20845. if (mode === "disabled") {
  20846. track.mode = "hidden";
  20847. }
  20848. if (track.cues) {
  20849. for (let i = track.cues.length; i--; ) {
  20850. if (enterHandler) {
  20851. track.cues[i].removeEventListener("enter", enterHandler);
  20852. }
  20853. track.removeCue(track.cues[i]);
  20854. }
  20855. }
  20856. if (mode === "disabled") {
  20857. track.mode = mode;
  20858. }
  20859. }
  20860. function removeCuesInRange(track, start, end, predicate) {
  20861. const mode = track.mode;
  20862. if (mode === "disabled") {
  20863. track.mode = "hidden";
  20864. }
  20865. if (track.cues && track.cues.length > 0) {
  20866. const cues = getCuesInRange(track.cues, start, end);
  20867. for (let i = 0; i < cues.length; i++) {
  20868. if (!predicate || predicate(cues[i])) {
  20869. track.removeCue(cues[i]);
  20870. }
  20871. }
  20872. }
  20873. if (mode === "disabled") {
  20874. track.mode = mode;
  20875. }
  20876. }
  20877. function getFirstCueIndexFromTime(cues, time) {
  20878. if (time <= cues[0].startTime) {
  20879. return 0;
  20880. }
  20881. const len = cues.length - 1;
  20882. if (time > cues[len].endTime) {
  20883. return -1;
  20884. }
  20885. let left = 0;
  20886. let right = len;
  20887. let mid;
  20888. while (left <= right) {
  20889. mid = Math.floor((right + left) / 2);
  20890. if (time < cues[mid].startTime) {
  20891. right = mid - 1;
  20892. } else if (time > cues[mid].startTime && left < len) {
  20893. left = mid + 1;
  20894. } else {
  20895. return mid;
  20896. }
  20897. }
  20898. return cues[left].startTime - time < time - cues[right].startTime ? left : right;
  20899. }
  20900. function getCuesInRange(cues, start, end) {
  20901. const cuesFound = [];
  20902. const firstCueInRange = getFirstCueIndexFromTime(cues, start);
  20903. if (firstCueInRange > -1) {
  20904. for (let i = firstCueInRange, len = cues.length; i < len; i++) {
  20905. const cue = cues[i];
  20906. if (cue.startTime >= start && cue.endTime <= end) {
  20907. cuesFound.push(cue);
  20908. } else if (cue.startTime > end) {
  20909. return cuesFound;
  20910. }
  20911. }
  20912. }
  20913. return cuesFound;
  20914. }
  20915. function filterSubtitleTracks(textTrackList) {
  20916. const tracks = [];
  20917. for (let i = 0; i < textTrackList.length; i++) {
  20918. const track = textTrackList[i];
  20919. if ((track.kind === "subtitles" || track.kind === "captions") && track.label) {
  20920. tracks.push(textTrackList[i]);
  20921. }
  20922. }
  20923. return tracks;
  20924. }
  20925. var SubtitleTrackController = class extends BasePlaylistController {
  20926. constructor(hls) {
  20927. super(hls, "subtitle-track-controller");
  20928. this.media = null;
  20929. this.tracks = [];
  20930. this.groupIds = null;
  20931. this.tracksInGroup = [];
  20932. this.trackId = -1;
  20933. this.currentTrack = null;
  20934. this.selectDefaultTrack = true;
  20935. this.queuedDefaultTrack = -1;
  20936. this.useTextTrackPolling = false;
  20937. this.subtitlePollingInterval = -1;
  20938. this._subtitleDisplay = true;
  20939. this.asyncPollTrackChange = () => this.pollTrackChange(0);
  20940. this.onTextTracksChanged = () => {
  20941. if (!this.useTextTrackPolling) {
  20942. self.clearInterval(this.subtitlePollingInterval);
  20943. }
  20944. if (!this.media || !this.hls.config.renderTextTracksNatively) {
  20945. return;
  20946. }
  20947. let textTrack = null;
  20948. const tracks = filterSubtitleTracks(this.media.textTracks);
  20949. for (let i = 0; i < tracks.length; i++) {
  20950. if (tracks[i].mode === "hidden") {
  20951. textTrack = tracks[i];
  20952. } else if (tracks[i].mode === "showing") {
  20953. textTrack = tracks[i];
  20954. break;
  20955. }
  20956. }
  20957. const trackId = this.findTrackForTextTrack(textTrack);
  20958. if (this.subtitleTrack !== trackId) {
  20959. this.setSubtitleTrack(trackId);
  20960. }
  20961. };
  20962. this.registerListeners();
  20963. }
  20964. destroy() {
  20965. this.unregisterListeners();
  20966. this.tracks.length = 0;
  20967. this.tracksInGroup.length = 0;
  20968. this.currentTrack = null;
  20969. this.onTextTracksChanged = this.asyncPollTrackChange = null;
  20970. super.destroy();
  20971. }
  20972. get subtitleDisplay() {
  20973. return this._subtitleDisplay;
  20974. }
  20975. set subtitleDisplay(value) {
  20976. this._subtitleDisplay = value;
  20977. if (this.trackId > -1) {
  20978. this.toggleTrackModes();
  20979. }
  20980. }
  20981. registerListeners() {
  20982. const {
  20983. hls
  20984. } = this;
  20985. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  20986. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  20987. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  20988. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  20989. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  20990. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  20991. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  20992. hls.on(Events.ERROR, this.onError, this);
  20993. }
  20994. unregisterListeners() {
  20995. const {
  20996. hls
  20997. } = this;
  20998. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  20999. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  21000. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21001. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  21002. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  21003. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  21004. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  21005. hls.off(Events.ERROR, this.onError, this);
  21006. }
  21007. // Listen for subtitle track change, then extract the current track ID.
  21008. onMediaAttached(event, data) {
  21009. this.media = data.media;
  21010. if (!this.media) {
  21011. return;
  21012. }
  21013. if (this.queuedDefaultTrack > -1) {
  21014. this.subtitleTrack = this.queuedDefaultTrack;
  21015. this.queuedDefaultTrack = -1;
  21016. }
  21017. this.useTextTrackPolling = !(this.media.textTracks && "onchange" in this.media.textTracks);
  21018. if (this.useTextTrackPolling) {
  21019. this.pollTrackChange(500);
  21020. } else {
  21021. this.media.textTracks.addEventListener("change", this.asyncPollTrackChange);
  21022. }
  21023. }
  21024. pollTrackChange(timeout) {
  21025. self.clearInterval(this.subtitlePollingInterval);
  21026. this.subtitlePollingInterval = self.setInterval(this.onTextTracksChanged, timeout);
  21027. }
  21028. onMediaDetaching(event, data) {
  21029. const media = this.media;
  21030. if (!media) {
  21031. return;
  21032. }
  21033. const transferringMedia = !!data.transferMedia;
  21034. self.clearInterval(this.subtitlePollingInterval);
  21035. if (!this.useTextTrackPolling) {
  21036. media.textTracks.removeEventListener("change", this.asyncPollTrackChange);
  21037. }
  21038. if (this.trackId > -1) {
  21039. this.queuedDefaultTrack = this.trackId;
  21040. }
  21041. this.subtitleTrack = -1;
  21042. this.media = null;
  21043. if (transferringMedia) {
  21044. return;
  21045. }
  21046. const textTracks = filterSubtitleTracks(media.textTracks);
  21047. textTracks.forEach((track) => {
  21048. clearCurrentCues(track);
  21049. });
  21050. }
  21051. onManifestLoading() {
  21052. this.tracks = [];
  21053. this.groupIds = null;
  21054. this.tracksInGroup = [];
  21055. this.trackId = -1;
  21056. this.currentTrack = null;
  21057. this.selectDefaultTrack = true;
  21058. }
  21059. // Fired whenever a new manifest is loaded.
  21060. onManifestParsed(event, data) {
  21061. this.tracks = data.subtitleTracks;
  21062. }
  21063. onSubtitleTrackLoaded(event, data) {
  21064. const {
  21065. id,
  21066. groupId,
  21067. details
  21068. } = data;
  21069. const trackInActiveGroup = this.tracksInGroup[id];
  21070. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  21071. this.warn(`Subtitle track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
  21072. return;
  21073. }
  21074. const curDetails = trackInActiveGroup.details;
  21075. trackInActiveGroup.details = data.details;
  21076. this.log(`Subtitle track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
  21077. if (id === this.trackId) {
  21078. this.playlistLoaded(id, data, curDetails);
  21079. }
  21080. }
  21081. onLevelLoading(event, data) {
  21082. this.switchLevel(data.level);
  21083. }
  21084. onLevelSwitching(event, data) {
  21085. this.switchLevel(data.level);
  21086. }
  21087. switchLevel(levelIndex) {
  21088. const levelInfo = this.hls.levels[levelIndex];
  21089. if (!levelInfo) {
  21090. return;
  21091. }
  21092. const subtitleGroups = levelInfo.subtitleGroups || null;
  21093. const currentGroups = this.groupIds;
  21094. let currentTrack = this.currentTrack;
  21095. 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)) {
  21096. this.groupIds = subtitleGroups;
  21097. this.trackId = -1;
  21098. this.currentTrack = null;
  21099. const subtitleTracks = this.tracks.filter((track) => !subtitleGroups || subtitleGroups.indexOf(track.groupId) !== -1);
  21100. if (subtitleTracks.length) {
  21101. if (this.selectDefaultTrack && !subtitleTracks.some((track) => track.default)) {
  21102. this.selectDefaultTrack = false;
  21103. }
  21104. subtitleTracks.forEach((track, i) => {
  21105. track.id = i;
  21106. });
  21107. } else if (!currentTrack && !this.tracksInGroup.length) {
  21108. return;
  21109. }
  21110. this.tracksInGroup = subtitleTracks;
  21111. const subtitlePreference = this.hls.config.subtitlePreference;
  21112. if (!currentTrack && subtitlePreference) {
  21113. this.selectDefaultTrack = false;
  21114. const groupIndex = findMatchingOption(subtitlePreference, subtitleTracks);
  21115. if (groupIndex > -1) {
  21116. currentTrack = subtitleTracks[groupIndex];
  21117. } else {
  21118. const allIndex = findMatchingOption(subtitlePreference, this.tracks);
  21119. currentTrack = this.tracks[allIndex];
  21120. }
  21121. }
  21122. let trackId = this.findTrackId(currentTrack);
  21123. if (trackId === -1 && currentTrack) {
  21124. trackId = this.findTrackId(null);
  21125. }
  21126. const subtitleTracksUpdated = {
  21127. subtitleTracks
  21128. };
  21129. this.log(`Updating subtitle tracks, ${subtitleTracks.length} track(s) found in "${subtitleGroups == null ? void 0 : subtitleGroups.join(",")}" group-id`);
  21130. this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);
  21131. if (trackId !== -1 && this.trackId === -1) {
  21132. this.setSubtitleTrack(trackId);
  21133. }
  21134. }
  21135. }
  21136. findTrackId(currentTrack) {
  21137. const tracks = this.tracksInGroup;
  21138. const selectDefault = this.selectDefaultTrack;
  21139. for (let i = 0; i < tracks.length; i++) {
  21140. const track = tracks[i];
  21141. if (selectDefault && !track.default || !selectDefault && !currentTrack) {
  21142. continue;
  21143. }
  21144. if (!currentTrack || matchesOption(track, currentTrack)) {
  21145. return i;
  21146. }
  21147. }
  21148. if (currentTrack) {
  21149. for (let i = 0; i < tracks.length; i++) {
  21150. const track = tracks[i];
  21151. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE", "ASSOC-LANGUAGE", "CHARACTERISTICS"])) {
  21152. return i;
  21153. }
  21154. }
  21155. for (let i = 0; i < tracks.length; i++) {
  21156. const track = tracks[i];
  21157. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE"])) {
  21158. return i;
  21159. }
  21160. }
  21161. }
  21162. return -1;
  21163. }
  21164. findTrackForTextTrack(textTrack) {
  21165. if (textTrack) {
  21166. const tracks = this.tracksInGroup;
  21167. for (let i = 0; i < tracks.length; i++) {
  21168. const track = tracks[i];
  21169. if (subtitleTrackMatchesTextTrack(track, textTrack)) {
  21170. return i;
  21171. }
  21172. }
  21173. }
  21174. return -1;
  21175. }
  21176. onError(event, data) {
  21177. if (data.fatal || !data.context) {
  21178. return;
  21179. }
  21180. if (data.context.type === PlaylistContextType.SUBTITLE_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  21181. this.checkRetry(data);
  21182. }
  21183. }
  21184. get allSubtitleTracks() {
  21185. return this.tracks;
  21186. }
  21187. /** get alternate subtitle tracks list from playlist **/
  21188. get subtitleTracks() {
  21189. return this.tracksInGroup;
  21190. }
  21191. /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/
  21192. get subtitleTrack() {
  21193. return this.trackId;
  21194. }
  21195. set subtitleTrack(newId) {
  21196. this.selectDefaultTrack = false;
  21197. this.setSubtitleTrack(newId);
  21198. }
  21199. setSubtitleOption(subtitleOption) {
  21200. this.hls.config.subtitlePreference = subtitleOption;
  21201. if (subtitleOption) {
  21202. if (subtitleOption.id === -1) {
  21203. this.setSubtitleTrack(-1);
  21204. return null;
  21205. }
  21206. const allSubtitleTracks = this.allSubtitleTracks;
  21207. this.selectDefaultTrack = false;
  21208. if (allSubtitleTracks.length) {
  21209. const currentTrack = this.currentTrack;
  21210. if (currentTrack && matchesOption(subtitleOption, currentTrack)) {
  21211. return currentTrack;
  21212. }
  21213. const groupIndex = findMatchingOption(subtitleOption, this.tracksInGroup);
  21214. if (groupIndex > -1) {
  21215. const track = this.tracksInGroup[groupIndex];
  21216. this.setSubtitleTrack(groupIndex);
  21217. return track;
  21218. } else if (currentTrack) {
  21219. return null;
  21220. } else {
  21221. const allIndex = findMatchingOption(subtitleOption, allSubtitleTracks);
  21222. if (allIndex > -1) {
  21223. return allSubtitleTracks[allIndex];
  21224. }
  21225. }
  21226. }
  21227. }
  21228. return null;
  21229. }
  21230. loadPlaylist(hlsUrlParameters) {
  21231. super.loadPlaylist();
  21232. if (this.shouldLoadPlaylist(this.currentTrack)) {
  21233. this.scheduleLoading(this.currentTrack, hlsUrlParameters);
  21234. }
  21235. }
  21236. loadingPlaylist(currentTrack, hlsUrlParameters) {
  21237. super.loadingPlaylist(currentTrack, hlsUrlParameters);
  21238. const id = currentTrack.id;
  21239. const groupId = currentTrack.groupId;
  21240. const url = this.getUrlWithDirectives(currentTrack.url, hlsUrlParameters);
  21241. const details = currentTrack.details;
  21242. const age = details == null ? void 0 : details.age;
  21243. 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}`);
  21244. this.hls.trigger(Events.SUBTITLE_TRACK_LOADING, {
  21245. url,
  21246. id,
  21247. groupId,
  21248. deliveryDirectives: hlsUrlParameters || null,
  21249. track: currentTrack
  21250. });
  21251. }
  21252. /**
  21253. * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
  21254. * This operates on the DOM textTracks.
  21255. * A value of -1 will disable all subtitle tracks.
  21256. */
  21257. toggleTrackModes() {
  21258. const {
  21259. media
  21260. } = this;
  21261. if (!media) {
  21262. return;
  21263. }
  21264. const textTracks = filterSubtitleTracks(media.textTracks);
  21265. const currentTrack = this.currentTrack;
  21266. let nextTrack;
  21267. if (currentTrack) {
  21268. nextTrack = textTracks.filter((textTrack) => subtitleTrackMatchesTextTrack(currentTrack, textTrack))[0];
  21269. if (!nextTrack) {
  21270. this.warn(`Unable to find subtitle TextTrack with name "${currentTrack.name}" and language "${currentTrack.lang}"`);
  21271. }
  21272. }
  21273. [].slice.call(textTracks).forEach((track) => {
  21274. if (track.mode !== "disabled" && track !== nextTrack) {
  21275. track.mode = "disabled";
  21276. }
  21277. });
  21278. if (nextTrack) {
  21279. const mode = this.subtitleDisplay ? "showing" : "hidden";
  21280. if (nextTrack.mode !== mode) {
  21281. nextTrack.mode = mode;
  21282. }
  21283. }
  21284. }
  21285. /**
  21286. * This method is responsible for validating the subtitle index and periodically reloading if live.
  21287. * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
  21288. */
  21289. setSubtitleTrack(newId) {
  21290. const tracks = this.tracksInGroup;
  21291. if (!this.media) {
  21292. this.queuedDefaultTrack = newId;
  21293. return;
  21294. }
  21295. if (newId < -1 || newId >= tracks.length || !isFiniteNumber(newId)) {
  21296. this.warn(`Invalid subtitle track id: ${newId}`);
  21297. return;
  21298. }
  21299. this.selectDefaultTrack = false;
  21300. const lastTrack = this.currentTrack;
  21301. const track = tracks[newId] || null;
  21302. this.trackId = newId;
  21303. this.currentTrack = track;
  21304. this.toggleTrackModes();
  21305. if (!track) {
  21306. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  21307. id: newId
  21308. });
  21309. return;
  21310. }
  21311. const trackLoaded = !!track.details && !track.details.live;
  21312. if (newId === this.trackId && track === lastTrack && trackLoaded) {
  21313. return;
  21314. }
  21315. this.log(`Switching to subtitle-track ${newId}` + (track ? ` "${track.name}" lang:${track.lang} group:${track.groupId}` : ""));
  21316. const {
  21317. id,
  21318. groupId = "",
  21319. name,
  21320. type,
  21321. url
  21322. } = track;
  21323. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  21324. id,
  21325. groupId,
  21326. name,
  21327. type,
  21328. url
  21329. });
  21330. const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
  21331. this.loadPlaylist(hlsUrlParameters);
  21332. }
  21333. };
  21334. function uuid() {
  21335. try {
  21336. return crypto.randomUUID();
  21337. } catch (error) {
  21338. try {
  21339. const url = URL.createObjectURL(new Blob());
  21340. const uuid2 = url.toString();
  21341. URL.revokeObjectURL(url);
  21342. return uuid2.slice(uuid2.lastIndexOf("/") + 1);
  21343. } catch (error2) {
  21344. let dt = (/* @__PURE__ */ new Date()).getTime();
  21345. const uuid2 = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
  21346. const r = (dt + Math.random() * 16) % 16 | 0;
  21347. dt = Math.floor(dt / 16);
  21348. return (c == "x" ? r : r & 3 | 8).toString(16);
  21349. });
  21350. return uuid2;
  21351. }
  21352. }
  21353. }
  21354. function hash(text) {
  21355. let hash2 = 5381;
  21356. let i = text.length;
  21357. while (i) {
  21358. hash2 = hash2 * 33 ^ text.charCodeAt(--i);
  21359. }
  21360. return (hash2 >>> 0).toString();
  21361. }
  21362. var ALIGNED_END_THRESHOLD_SECONDS = 0.025;
  21363. var TimelineOccupancy = function(TimelineOccupancy2) {
  21364. TimelineOccupancy2[TimelineOccupancy2["Point"] = 0] = "Point";
  21365. TimelineOccupancy2[TimelineOccupancy2["Range"] = 1] = "Range";
  21366. return TimelineOccupancy2;
  21367. }({});
  21368. function generateAssetIdentifier(interstitial, uri, assetListIndex) {
  21369. return `${interstitial.identifier}-${assetListIndex + 1}-${hash(uri)}`;
  21370. }
  21371. var InterstitialEvent = class {
  21372. constructor(dateRange, base) {
  21373. this.base = void 0;
  21374. this._duration = null;
  21375. this._timelineStart = null;
  21376. this.appendInPlaceDisabled = void 0;
  21377. this.appendInPlaceStarted = void 0;
  21378. this.dateRange = void 0;
  21379. this.hasPlayed = false;
  21380. this.cumulativeDuration = 0;
  21381. this.resumeOffset = NaN;
  21382. this.playoutLimit = NaN;
  21383. this.restrictions = {
  21384. skip: false,
  21385. jump: false
  21386. };
  21387. this.snapOptions = {
  21388. out: false,
  21389. in: false
  21390. };
  21391. this.assetList = [];
  21392. this.assetListLoader = void 0;
  21393. this.assetListResponse = null;
  21394. this.resumeAnchor = void 0;
  21395. this.error = void 0;
  21396. this.resetOnResume = void 0;
  21397. this.base = base;
  21398. this.dateRange = dateRange;
  21399. this.setDateRange(dateRange);
  21400. }
  21401. setDateRange(dateRange) {
  21402. this.dateRange = dateRange;
  21403. this.resumeOffset = dateRange.attr.optionalFloat("X-RESUME-OFFSET", this.resumeOffset);
  21404. this.playoutLimit = dateRange.attr.optionalFloat("X-PLAYOUT-LIMIT", this.playoutLimit);
  21405. this.restrictions = dateRange.attr.enumeratedStringList("X-RESTRICT", this.restrictions);
  21406. this.snapOptions = dateRange.attr.enumeratedStringList("X-SNAP", this.snapOptions);
  21407. }
  21408. reset() {
  21409. var _this$assetListLoader;
  21410. this.appendInPlaceStarted = false;
  21411. (_this$assetListLoader = this.assetListLoader) == null || _this$assetListLoader.destroy();
  21412. this.assetListLoader = void 0;
  21413. if (!this.supplementsPrimary) {
  21414. this.assetListResponse = null;
  21415. this.assetList = [];
  21416. this._duration = null;
  21417. }
  21418. }
  21419. isAssetPastPlayoutLimit(assetIndex) {
  21420. var _this$assetList$asset;
  21421. if (assetIndex > 0 && assetIndex >= this.assetList.length) {
  21422. return true;
  21423. }
  21424. const playoutLimit = this.playoutLimit;
  21425. if (assetIndex <= 0 || isNaN(playoutLimit)) {
  21426. return false;
  21427. }
  21428. if (playoutLimit === 0) {
  21429. return true;
  21430. }
  21431. const assetOffset = ((_this$assetList$asset = this.assetList[assetIndex]) == null ? void 0 : _this$assetList$asset.startOffset) || 0;
  21432. return assetOffset > playoutLimit;
  21433. }
  21434. findAssetIndex(asset) {
  21435. const index = this.assetList.indexOf(asset);
  21436. return index;
  21437. }
  21438. get identifier() {
  21439. return this.dateRange.id;
  21440. }
  21441. get startDate() {
  21442. return this.dateRange.startDate;
  21443. }
  21444. get startTime() {
  21445. const startTime = this.dateRange.startTime;
  21446. if (this.snapOptions.out) {
  21447. const frag = this.dateRange.tagAnchor;
  21448. if (frag) {
  21449. return getSnapToFragmentTime(startTime, frag);
  21450. }
  21451. }
  21452. return startTime;
  21453. }
  21454. get startOffset() {
  21455. return this.cue.pre ? 0 : this.startTime;
  21456. }
  21457. get startIsAligned() {
  21458. if (this.startTime === 0 || this.snapOptions.out) {
  21459. return true;
  21460. }
  21461. const frag = this.dateRange.tagAnchor;
  21462. if (frag) {
  21463. const startTime = this.dateRange.startTime;
  21464. const snappedStart = getSnapToFragmentTime(startTime, frag);
  21465. return startTime - snappedStart < 0.1;
  21466. }
  21467. return false;
  21468. }
  21469. get resumptionOffset() {
  21470. const resumeOffset = this.resumeOffset;
  21471. const offset = isFiniteNumber(resumeOffset) ? resumeOffset : this.duration;
  21472. return this.cumulativeDuration + offset;
  21473. }
  21474. get resumeTime() {
  21475. const resumeTime = this.startOffset + this.resumptionOffset;
  21476. if (this.snapOptions.in) {
  21477. const frag = this.resumeAnchor;
  21478. if (frag) {
  21479. return getSnapToFragmentTime(resumeTime, frag);
  21480. }
  21481. }
  21482. return resumeTime;
  21483. }
  21484. get appendInPlace() {
  21485. if (this.appendInPlaceStarted) {
  21486. return true;
  21487. }
  21488. if (this.appendInPlaceDisabled) {
  21489. return false;
  21490. }
  21491. if (!this.cue.once && !this.cue.pre && // preroll starts at startPosition before startPosition is known (live)
  21492. this.startIsAligned && (isNaN(this.playoutLimit) && isNaN(this.resumeOffset) || this.resumeOffset && this.duration && Math.abs(this.resumeOffset - this.duration) < ALIGNED_END_THRESHOLD_SECONDS)) {
  21493. return true;
  21494. }
  21495. return false;
  21496. }
  21497. set appendInPlace(value) {
  21498. if (this.appendInPlaceStarted) {
  21499. this.resetOnResume = !value;
  21500. return;
  21501. }
  21502. this.appendInPlaceDisabled = !value;
  21503. }
  21504. // Extended timeline start time
  21505. get timelineStart() {
  21506. if (this._timelineStart !== null) {
  21507. return this._timelineStart;
  21508. }
  21509. return this.startTime;
  21510. }
  21511. set timelineStart(value) {
  21512. this._timelineStart = value;
  21513. }
  21514. get duration() {
  21515. const playoutLimit = this.playoutLimit;
  21516. let duration;
  21517. if (this._duration !== null) {
  21518. duration = this._duration;
  21519. } else if (this.dateRange.duration) {
  21520. duration = this.dateRange.duration;
  21521. } else {
  21522. duration = this.dateRange.plannedDuration || 0;
  21523. }
  21524. if (!isNaN(playoutLimit) && playoutLimit < duration) {
  21525. duration = playoutLimit;
  21526. }
  21527. return duration;
  21528. }
  21529. set duration(value) {
  21530. this._duration = value;
  21531. }
  21532. get cue() {
  21533. return this.dateRange.cue;
  21534. }
  21535. get timelineOccupancy() {
  21536. if (this.dateRange.attr["X-TIMELINE-OCCUPIES"] === "RANGE") {
  21537. return TimelineOccupancy.Range;
  21538. }
  21539. return TimelineOccupancy.Point;
  21540. }
  21541. get supplementsPrimary() {
  21542. return this.dateRange.attr["X-TIMELINE-STYLE"] === "PRIMARY";
  21543. }
  21544. get contentMayVary() {
  21545. return this.dateRange.attr["X-CONTENT-MAY-VARY"] !== "NO";
  21546. }
  21547. get assetUrl() {
  21548. return this.dateRange.attr["X-ASSET-URI"];
  21549. }
  21550. get assetListUrl() {
  21551. return this.dateRange.attr["X-ASSET-LIST"];
  21552. }
  21553. get baseUrl() {
  21554. return this.base.url;
  21555. }
  21556. get assetListLoaded() {
  21557. return this.assetList.length > 0 || this.assetListResponse !== null;
  21558. }
  21559. toString() {
  21560. return eventToString(this);
  21561. }
  21562. };
  21563. function getSnapToFragmentTime(time, frag) {
  21564. return time - frag.start < frag.duration / 2 && !(Math.abs(time - (frag.start + frag.duration)) < ALIGNED_END_THRESHOLD_SECONDS) ? frag.start : frag.start + frag.duration;
  21565. }
  21566. function getInterstitialUrl(uri, sessionId, baseUrl) {
  21567. const url = new self.URL(uri, baseUrl);
  21568. if (url.protocol !== "data:") {
  21569. url.searchParams.set("_HLS_primary_id", sessionId);
  21570. }
  21571. return url;
  21572. }
  21573. function getNextAssetIndex(interstitial, assetListIndex) {
  21574. while ((_interstitial$assetLi = interstitial.assetList[++assetListIndex]) != null && _interstitial$assetLi.error) {
  21575. var _interstitial$assetLi;
  21576. }
  21577. return assetListIndex;
  21578. }
  21579. function eventToString(interstitial) {
  21580. return `["${interstitial.identifier}" ${interstitial.cue.pre ? "<pre>" : interstitial.cue.post ? "<post>" : ""}${interstitial.timelineStart.toFixed(2)}-${interstitial.resumeTime.toFixed(2)}]`;
  21581. }
  21582. function eventAssetToString(asset) {
  21583. const start = asset.timelineStart;
  21584. const duration = asset.duration || 0;
  21585. return `["${asset.identifier}" ${start.toFixed(2)}-${(start + duration).toFixed(2)}]`;
  21586. }
  21587. var HlsAssetPlayer = class {
  21588. constructor(HlsPlayerClass, userConfig, interstitial, assetItem) {
  21589. this.hls = void 0;
  21590. this.interstitial = void 0;
  21591. this.assetItem = void 0;
  21592. this.tracks = null;
  21593. this.hasDetails = false;
  21594. this.mediaAttached = null;
  21595. this._currentTime = void 0;
  21596. this._bufferedEosTime = void 0;
  21597. this.checkPlayout = () => {
  21598. if (this.reachedPlayout(this.currentTime) && this.hls) {
  21599. this.hls.trigger(Events.PLAYOUT_LIMIT_REACHED, {});
  21600. }
  21601. };
  21602. const hls = this.hls = new HlsPlayerClass(userConfig);
  21603. this.interstitial = interstitial;
  21604. this.assetItem = assetItem;
  21605. const detailsLoaded = () => {
  21606. this.hasDetails = true;
  21607. };
  21608. hls.once(Events.LEVEL_LOADED, detailsLoaded);
  21609. hls.once(Events.AUDIO_TRACK_LOADED, detailsLoaded);
  21610. hls.once(Events.SUBTITLE_TRACK_LOADED, detailsLoaded);
  21611. hls.on(Events.MEDIA_ATTACHING, (name, {
  21612. media
  21613. }) => {
  21614. this.removeMediaListeners();
  21615. this.mediaAttached = media;
  21616. const event = this.interstitial;
  21617. if (event.playoutLimit) {
  21618. media.addEventListener("timeupdate", this.checkPlayout);
  21619. if (this.appendInPlace) {
  21620. hls.on(Events.BUFFER_APPENDED, () => {
  21621. const bufferedEnd = this.bufferedEnd;
  21622. if (this.reachedPlayout(bufferedEnd)) {
  21623. this._bufferedEosTime = bufferedEnd;
  21624. hls.trigger(Events.BUFFERED_TO_END, void 0);
  21625. }
  21626. });
  21627. }
  21628. }
  21629. });
  21630. }
  21631. get appendInPlace() {
  21632. return this.interstitial.appendInPlace;
  21633. }
  21634. loadSource() {
  21635. const hls = this.hls;
  21636. if (!hls) {
  21637. return;
  21638. }
  21639. if (!hls.url) {
  21640. let uri = this.assetItem.uri;
  21641. try {
  21642. uri = getInterstitialUrl(uri, hls.config.primarySessionId || "").href;
  21643. } catch (error) {
  21644. }
  21645. hls.loadSource(uri);
  21646. } else if (hls.levels.length && !hls.started) {
  21647. hls.startLoad(-1, true);
  21648. }
  21649. }
  21650. bufferedInPlaceToEnd(media) {
  21651. var _this$hls;
  21652. if (!this.appendInPlace) {
  21653. return false;
  21654. }
  21655. if ((_this$hls = this.hls) != null && _this$hls.bufferedToEnd) {
  21656. return true;
  21657. }
  21658. if (!media) {
  21659. return false;
  21660. }
  21661. const duration = Math.min(this._bufferedEosTime || Infinity, this.duration);
  21662. const start = this.timelineOffset;
  21663. const bufferInfo = BufferHelper.bufferInfo(media, start, 0);
  21664. const bufferedEnd = this.getAssetTime(bufferInfo.end);
  21665. return bufferedEnd >= duration - 0.02;
  21666. }
  21667. reachedPlayout(time) {
  21668. const interstitial = this.interstitial;
  21669. const playoutLimit = interstitial.playoutLimit;
  21670. return this.startOffset + time >= playoutLimit;
  21671. }
  21672. get destroyed() {
  21673. var _this$hls2;
  21674. return !((_this$hls2 = this.hls) != null && _this$hls2.userConfig);
  21675. }
  21676. get assetId() {
  21677. return this.assetItem.identifier;
  21678. }
  21679. get interstitialId() {
  21680. return this.assetItem.parentIdentifier;
  21681. }
  21682. get media() {
  21683. var _this$hls3;
  21684. return ((_this$hls3 = this.hls) == null ? void 0 : _this$hls3.media) || null;
  21685. }
  21686. get bufferedEnd() {
  21687. const media = this.media || this.mediaAttached;
  21688. if (!media) {
  21689. if (this._bufferedEosTime) {
  21690. return this._bufferedEosTime;
  21691. }
  21692. return this.currentTime;
  21693. }
  21694. const bufferInfo = BufferHelper.bufferInfo(media, media.currentTime, 1e-3);
  21695. return this.getAssetTime(bufferInfo.end);
  21696. }
  21697. get currentTime() {
  21698. const media = this.media || this.mediaAttached;
  21699. if (!media) {
  21700. return this._currentTime || 0;
  21701. }
  21702. return this.getAssetTime(media.currentTime);
  21703. }
  21704. get duration() {
  21705. const duration = this.assetItem.duration;
  21706. if (!duration) {
  21707. return 0;
  21708. }
  21709. const playoutLimit = this.interstitial.playoutLimit;
  21710. if (playoutLimit) {
  21711. const assetPlayout = playoutLimit - this.startOffset;
  21712. if (assetPlayout > 0 && assetPlayout < duration) {
  21713. return assetPlayout;
  21714. }
  21715. }
  21716. return duration;
  21717. }
  21718. get remaining() {
  21719. const duration = this.duration;
  21720. if (!duration) {
  21721. return 0;
  21722. }
  21723. return Math.max(0, duration - this.currentTime);
  21724. }
  21725. get startOffset() {
  21726. return this.assetItem.startOffset;
  21727. }
  21728. get timelineOffset() {
  21729. var _this$hls4;
  21730. return ((_this$hls4 = this.hls) == null ? void 0 : _this$hls4.config.timelineOffset) || 0;
  21731. }
  21732. set timelineOffset(value) {
  21733. const timelineOffset = this.timelineOffset;
  21734. if (value !== timelineOffset) {
  21735. const diff = value - timelineOffset;
  21736. if (Math.abs(diff) > 1 / 9e4 && this.hls) {
  21737. if (this.hasDetails) {
  21738. throw new Error(`Cannot set timelineOffset after playlists are loaded`);
  21739. }
  21740. this.hls.config.timelineOffset = value;
  21741. }
  21742. }
  21743. }
  21744. getAssetTime(time) {
  21745. const timelineOffset = this.timelineOffset;
  21746. const duration = this.duration;
  21747. return Math.min(Math.max(0, time - timelineOffset), duration);
  21748. }
  21749. removeMediaListeners() {
  21750. const media = this.mediaAttached;
  21751. if (media) {
  21752. this._currentTime = media.currentTime;
  21753. this.bufferSnapShot();
  21754. media.removeEventListener("timeupdate", this.checkPlayout);
  21755. }
  21756. }
  21757. bufferSnapShot() {
  21758. if (this.mediaAttached) {
  21759. var _this$hls5;
  21760. if ((_this$hls5 = this.hls) != null && _this$hls5.bufferedToEnd) {
  21761. this._bufferedEosTime = this.bufferedEnd;
  21762. }
  21763. }
  21764. }
  21765. destroy() {
  21766. this.removeMediaListeners();
  21767. if (this.hls) {
  21768. this.hls.destroy();
  21769. }
  21770. this.hls = null;
  21771. this.tracks = this.mediaAttached = this.checkPlayout = null;
  21772. }
  21773. attachMedia(data) {
  21774. var _this$hls6;
  21775. this.loadSource();
  21776. (_this$hls6 = this.hls) == null || _this$hls6.attachMedia(data);
  21777. }
  21778. detachMedia() {
  21779. var _this$hls7;
  21780. this.removeMediaListeners();
  21781. this.mediaAttached = null;
  21782. (_this$hls7 = this.hls) == null || _this$hls7.detachMedia();
  21783. }
  21784. resumeBuffering() {
  21785. var _this$hls8;
  21786. (_this$hls8 = this.hls) == null || _this$hls8.resumeBuffering();
  21787. }
  21788. pauseBuffering() {
  21789. var _this$hls9;
  21790. (_this$hls9 = this.hls) == null || _this$hls9.pauseBuffering();
  21791. }
  21792. transferMedia() {
  21793. var _this$hls0;
  21794. this.bufferSnapShot();
  21795. return ((_this$hls0 = this.hls) == null ? void 0 : _this$hls0.transferMedia()) || null;
  21796. }
  21797. resetDetails() {
  21798. const hls = this.hls;
  21799. if (hls && this.hasDetails) {
  21800. hls.stopLoad();
  21801. const deleteDetails = (obj) => delete obj.details;
  21802. hls.levels.forEach(deleteDetails);
  21803. hls.allAudioTracks.forEach(deleteDetails);
  21804. hls.allSubtitleTracks.forEach(deleteDetails);
  21805. this.hasDetails = false;
  21806. }
  21807. }
  21808. on(event, listener, context) {
  21809. var _this$hls1;
  21810. (_this$hls1 = this.hls) == null || _this$hls1.on(event, listener);
  21811. }
  21812. once(event, listener, context) {
  21813. var _this$hls10;
  21814. (_this$hls10 = this.hls) == null || _this$hls10.once(event, listener);
  21815. }
  21816. off(event, listener, context) {
  21817. var _this$hls11;
  21818. (_this$hls11 = this.hls) == null || _this$hls11.off(event, listener);
  21819. }
  21820. toString() {
  21821. var _this$hls12;
  21822. return `HlsAssetPlayer: ${eventAssetToString(this.assetItem)} ${(_this$hls12 = this.hls) == null ? void 0 : _this$hls12.sessionId} ${this.appendInPlace ? "append-in-place" : ""}`;
  21823. }
  21824. };
  21825. var ABUTTING_THRESHOLD_SECONDS = 0.033;
  21826. var InterstitialsSchedule = class extends Logger {
  21827. constructor(onScheduleUpdate, logger2) {
  21828. super("interstitials-sched", logger2);
  21829. this.onScheduleUpdate = void 0;
  21830. this.eventMap = {};
  21831. this.events = null;
  21832. this.items = null;
  21833. this.durations = {
  21834. primary: 0,
  21835. playout: 0,
  21836. integrated: 0
  21837. };
  21838. this.onScheduleUpdate = onScheduleUpdate;
  21839. }
  21840. destroy() {
  21841. this.reset();
  21842. this.onScheduleUpdate = null;
  21843. }
  21844. reset() {
  21845. this.eventMap = {};
  21846. this.setDurations(0, 0, 0);
  21847. if (this.events) {
  21848. this.events.forEach((interstitial) => interstitial.reset());
  21849. }
  21850. this.events = this.items = null;
  21851. }
  21852. resetErrorsInRange(start, end) {
  21853. if (this.events) {
  21854. return this.events.reduce((count, interstitial) => {
  21855. if (start <= interstitial.startOffset && end > interstitial.startOffset) {
  21856. delete interstitial.error;
  21857. return count + 1;
  21858. }
  21859. return count;
  21860. }, 0);
  21861. }
  21862. return 0;
  21863. }
  21864. get duration() {
  21865. const items = this.items;
  21866. return items ? items[items.length - 1].end : 0;
  21867. }
  21868. get length() {
  21869. return this.items ? this.items.length : 0;
  21870. }
  21871. getEvent(identifier) {
  21872. return identifier ? this.eventMap[identifier] || null : null;
  21873. }
  21874. hasEvent(identifier) {
  21875. return identifier in this.eventMap;
  21876. }
  21877. findItemIndex(item, time) {
  21878. if (item.event) {
  21879. return this.findEventIndex(item.event.identifier);
  21880. }
  21881. let index = -1;
  21882. if (item.nextEvent) {
  21883. index = this.findEventIndex(item.nextEvent.identifier) - 1;
  21884. } else if (item.previousEvent) {
  21885. index = this.findEventIndex(item.previousEvent.identifier) + 1;
  21886. }
  21887. const items = this.items;
  21888. if (items) {
  21889. if (!items[index]) {
  21890. if (time === void 0) {
  21891. time = item.start;
  21892. }
  21893. index = this.findItemIndexAtTime(time);
  21894. }
  21895. while (index >= 0 && (_items$index = items[index]) != null && _items$index.event) {
  21896. var _items$index;
  21897. index--;
  21898. }
  21899. }
  21900. return index;
  21901. }
  21902. findItemIndexAtTime(timelinePos, timelineType) {
  21903. const items = this.items;
  21904. if (items) {
  21905. for (let i = 0; i < items.length; i++) {
  21906. let timeRange = items[i];
  21907. if (timelineType && timelineType !== "primary") {
  21908. timeRange = timeRange[timelineType];
  21909. }
  21910. if (timelinePos === timeRange.start || timelinePos > timeRange.start && timelinePos < timeRange.end) {
  21911. return i;
  21912. }
  21913. }
  21914. }
  21915. return -1;
  21916. }
  21917. findJumpRestrictedIndex(startIndex, endIndex) {
  21918. const items = this.items;
  21919. if (items) {
  21920. for (let i = startIndex; i <= endIndex; i++) {
  21921. if (!items[i]) {
  21922. break;
  21923. }
  21924. const event = items[i].event;
  21925. if (event != null && event.restrictions.jump && !event.appendInPlace) {
  21926. return i;
  21927. }
  21928. }
  21929. }
  21930. return -1;
  21931. }
  21932. findEventIndex(identifier) {
  21933. const items = this.items;
  21934. if (items) {
  21935. for (let i = items.length; i--; ) {
  21936. var _items$i$event;
  21937. if (((_items$i$event = items[i].event) == null ? void 0 : _items$i$event.identifier) === identifier) {
  21938. return i;
  21939. }
  21940. }
  21941. }
  21942. return -1;
  21943. }
  21944. findAssetIndex(event, timelinePos) {
  21945. const assetList = event.assetList;
  21946. const length = assetList.length;
  21947. if (length > 1) {
  21948. for (let i = 0; i < length; i++) {
  21949. const asset = assetList[i];
  21950. if (!asset.error) {
  21951. const timelineStart = asset.timelineStart;
  21952. if (timelinePos === timelineStart || timelinePos > timelineStart && (timelinePos < timelineStart + (asset.duration || 0) || i === length - 1)) {
  21953. return i;
  21954. }
  21955. }
  21956. }
  21957. }
  21958. return 0;
  21959. }
  21960. get assetIdAtEnd() {
  21961. var _this$items;
  21962. const interstitialAtEnd = (_this$items = this.items) == null || (_this$items = _this$items[this.length - 1]) == null ? void 0 : _this$items.event;
  21963. if (interstitialAtEnd) {
  21964. const assetList = interstitialAtEnd.assetList;
  21965. const assetAtEnd = assetList[assetList.length - 1];
  21966. if (assetAtEnd) {
  21967. return assetAtEnd.identifier;
  21968. }
  21969. }
  21970. return null;
  21971. }
  21972. parseInterstitialDateRanges(mediaSelection, enableAppendInPlace) {
  21973. const details = mediaSelection.main.details;
  21974. const {
  21975. dateRanges
  21976. } = details;
  21977. const previousInterstitialEvents = this.events;
  21978. const interstitialEvents = this.parseDateRanges(dateRanges, {
  21979. url: details.url
  21980. }, enableAppendInPlace);
  21981. const ids = Object.keys(dateRanges);
  21982. const removedInterstitials = previousInterstitialEvents ? previousInterstitialEvents.filter((event) => !ids.includes(event.identifier)) : [];
  21983. if (interstitialEvents.length) {
  21984. interstitialEvents.sort((a, b) => {
  21985. const aPre = a.cue.pre;
  21986. const aPost = a.cue.post;
  21987. const bPre = b.cue.pre;
  21988. const bPost = b.cue.post;
  21989. if (aPre && !bPre) {
  21990. return -1;
  21991. }
  21992. if (bPre && !aPre) {
  21993. return 1;
  21994. }
  21995. if (aPost && !bPost) {
  21996. return 1;
  21997. }
  21998. if (bPost && !aPost) {
  21999. return -1;
  22000. }
  22001. if (!aPre && !bPre && !aPost && !bPost) {
  22002. const startA = a.startTime;
  22003. const startB = b.startTime;
  22004. if (startA !== startB) {
  22005. return startA - startB;
  22006. }
  22007. }
  22008. return a.dateRange.tagOrder - b.dateRange.tagOrder;
  22009. });
  22010. }
  22011. this.events = interstitialEvents;
  22012. removedInterstitials.forEach((interstitial) => {
  22013. this.removeEvent(interstitial);
  22014. });
  22015. this.updateSchedule(mediaSelection, removedInterstitials);
  22016. }
  22017. updateSchedule(mediaSelection, removedInterstitials = [], forceUpdate = false) {
  22018. const events = this.events || [];
  22019. if (events.length || removedInterstitials.length || this.length < 2) {
  22020. const currentItems = this.items;
  22021. const updatedItems = this.parseSchedule(events, mediaSelection);
  22022. const updated = forceUpdate || removedInterstitials.length || (currentItems == null ? void 0 : currentItems.length) !== updatedItems.length || updatedItems.some((item, i) => {
  22023. return Math.abs(item.playout.start - currentItems[i].playout.start) > 5e-3 || Math.abs(item.playout.end - currentItems[i].playout.end) > 5e-3;
  22024. });
  22025. if (updated) {
  22026. this.items = updatedItems;
  22027. this.onScheduleUpdate(removedInterstitials, currentItems);
  22028. }
  22029. }
  22030. }
  22031. parseDateRanges(dateRanges, baseData, enableAppendInPlace) {
  22032. const interstitialEvents = [];
  22033. const ids = Object.keys(dateRanges);
  22034. for (let i = 0; i < ids.length; i++) {
  22035. const id = ids[i];
  22036. const dateRange = dateRanges[id];
  22037. if (dateRange.isInterstitial) {
  22038. let interstitial = this.eventMap[id];
  22039. if (interstitial) {
  22040. interstitial.setDateRange(dateRange);
  22041. } else {
  22042. interstitial = new InterstitialEvent(dateRange, baseData);
  22043. this.eventMap[id] = interstitial;
  22044. if (enableAppendInPlace === false) {
  22045. interstitial.appendInPlace = enableAppendInPlace;
  22046. }
  22047. }
  22048. interstitialEvents.push(interstitial);
  22049. }
  22050. }
  22051. return interstitialEvents;
  22052. }
  22053. parseSchedule(interstitialEvents, mediaSelection) {
  22054. const schedule = [];
  22055. const details = mediaSelection.main.details;
  22056. const primaryDuration = details.live ? Infinity : details.edge;
  22057. let playoutDuration = 0;
  22058. interstitialEvents = interstitialEvents.filter((event) => !event.error && !(event.cue.once && event.hasPlayed));
  22059. if (interstitialEvents.length) {
  22060. this.resolveOffsets(interstitialEvents, mediaSelection);
  22061. let primaryPosition = 0;
  22062. let integratedTime = 0;
  22063. interstitialEvents.forEach((interstitial, i) => {
  22064. const preroll = interstitial.cue.pre;
  22065. const postroll = interstitial.cue.post;
  22066. const previousEvent = interstitialEvents[i - 1] || null;
  22067. const appendInPlace = interstitial.appendInPlace;
  22068. const eventStart = postroll ? primaryDuration : interstitial.startOffset;
  22069. const interstitialDuration = interstitial.duration;
  22070. const timelineDuration = interstitial.timelineOccupancy === TimelineOccupancy.Range ? interstitialDuration : 0;
  22071. const resumptionOffset = interstitial.resumptionOffset;
  22072. const inSameStartTimeSequence = (previousEvent == null ? void 0 : previousEvent.startTime) === eventStart;
  22073. const start = eventStart + interstitial.cumulativeDuration;
  22074. let end = appendInPlace ? start + interstitialDuration : eventStart + resumptionOffset;
  22075. if (preroll || !postroll && eventStart <= 0) {
  22076. const integratedStart = integratedTime;
  22077. integratedTime += timelineDuration;
  22078. interstitial.timelineStart = start;
  22079. const playoutStart = playoutDuration;
  22080. playoutDuration += interstitialDuration;
  22081. schedule.push({
  22082. event: interstitial,
  22083. start,
  22084. end,
  22085. playout: {
  22086. start: playoutStart,
  22087. end: playoutDuration
  22088. },
  22089. integrated: {
  22090. start: integratedStart,
  22091. end: integratedTime
  22092. }
  22093. });
  22094. } else if (eventStart <= primaryDuration) {
  22095. if (!inSameStartTimeSequence) {
  22096. const segmentDuration = eventStart - primaryPosition;
  22097. if (segmentDuration > ABUTTING_THRESHOLD_SECONDS) {
  22098. const timelineStart = primaryPosition;
  22099. const _integratedStart = integratedTime;
  22100. integratedTime += segmentDuration;
  22101. const _playoutStart = playoutDuration;
  22102. playoutDuration += segmentDuration;
  22103. const primarySegment = {
  22104. previousEvent: interstitialEvents[i - 1] || null,
  22105. nextEvent: interstitial,
  22106. start: timelineStart,
  22107. end: timelineStart + segmentDuration,
  22108. playout: {
  22109. start: _playoutStart,
  22110. end: playoutDuration
  22111. },
  22112. integrated: {
  22113. start: _integratedStart,
  22114. end: integratedTime
  22115. }
  22116. };
  22117. schedule.push(primarySegment);
  22118. } else if (segmentDuration > 0 && previousEvent) {
  22119. previousEvent.cumulativeDuration += segmentDuration;
  22120. schedule[schedule.length - 1].end = eventStart;
  22121. }
  22122. }
  22123. if (postroll) {
  22124. end = start;
  22125. }
  22126. interstitial.timelineStart = start;
  22127. const integratedStart = integratedTime;
  22128. integratedTime += timelineDuration;
  22129. const playoutStart = playoutDuration;
  22130. playoutDuration += interstitialDuration;
  22131. schedule.push({
  22132. event: interstitial,
  22133. start,
  22134. end,
  22135. playout: {
  22136. start: playoutStart,
  22137. end: playoutDuration
  22138. },
  22139. integrated: {
  22140. start: integratedStart,
  22141. end: integratedTime
  22142. }
  22143. });
  22144. } else {
  22145. return;
  22146. }
  22147. const resumeTime = interstitial.resumeTime;
  22148. if (postroll || resumeTime > primaryDuration) {
  22149. primaryPosition = primaryDuration;
  22150. } else {
  22151. primaryPosition = resumeTime;
  22152. }
  22153. });
  22154. if (primaryPosition < primaryDuration) {
  22155. var _schedule;
  22156. const timelineStart = primaryPosition;
  22157. const integratedStart = integratedTime;
  22158. const segmentDuration = primaryDuration - primaryPosition;
  22159. integratedTime += segmentDuration;
  22160. const playoutStart = playoutDuration;
  22161. playoutDuration += segmentDuration;
  22162. schedule.push({
  22163. previousEvent: ((_schedule = schedule[schedule.length - 1]) == null ? void 0 : _schedule.event) || null,
  22164. nextEvent: null,
  22165. start: primaryPosition,
  22166. end: timelineStart + segmentDuration,
  22167. playout: {
  22168. start: playoutStart,
  22169. end: playoutDuration
  22170. },
  22171. integrated: {
  22172. start: integratedStart,
  22173. end: integratedTime
  22174. }
  22175. });
  22176. }
  22177. this.setDurations(primaryDuration, playoutDuration, integratedTime);
  22178. } else {
  22179. const start = 0;
  22180. schedule.push({
  22181. previousEvent: null,
  22182. nextEvent: null,
  22183. start,
  22184. end: primaryDuration,
  22185. playout: {
  22186. start,
  22187. end: primaryDuration
  22188. },
  22189. integrated: {
  22190. start,
  22191. end: primaryDuration
  22192. }
  22193. });
  22194. this.setDurations(primaryDuration, primaryDuration, primaryDuration);
  22195. }
  22196. return schedule;
  22197. }
  22198. setDurations(primary, playout, integrated) {
  22199. this.durations = {
  22200. primary,
  22201. playout,
  22202. integrated
  22203. };
  22204. }
  22205. resolveOffsets(interstitialEvents, mediaSelection) {
  22206. const details = mediaSelection.main.details;
  22207. const primaryDuration = details.live ? Infinity : details.edge;
  22208. let cumulativeDuration = 0;
  22209. let lastScheduledStart = -1;
  22210. interstitialEvents.forEach((interstitial, i) => {
  22211. const preroll = interstitial.cue.pre;
  22212. const postroll = interstitial.cue.post;
  22213. const eventStart = preroll ? 0 : postroll ? primaryDuration : interstitial.startTime;
  22214. this.updateAssetDurations(interstitial);
  22215. const inSameStartTimeSequence = lastScheduledStart === eventStart;
  22216. if (inSameStartTimeSequence) {
  22217. interstitial.cumulativeDuration = cumulativeDuration;
  22218. } else {
  22219. cumulativeDuration = 0;
  22220. lastScheduledStart = eventStart;
  22221. }
  22222. if (!postroll && interstitial.snapOptions.in) {
  22223. interstitial.resumeAnchor = findFragmentByPTS(null, details.fragments, interstitial.startOffset + interstitial.resumptionOffset, 0, 0) || void 0;
  22224. }
  22225. if (interstitial.appendInPlace && !interstitial.appendInPlaceStarted) {
  22226. const alignedSegmentStart = this.primaryCanResumeInPlaceAt(interstitial, mediaSelection);
  22227. if (!alignedSegmentStart) {
  22228. interstitial.appendInPlace = false;
  22229. }
  22230. }
  22231. if (!interstitial.appendInPlace && i + 1 < interstitialEvents.length) {
  22232. const timeBetween = interstitialEvents[i + 1].startTime - interstitialEvents[i].resumeTime;
  22233. if (timeBetween < ABUTTING_THRESHOLD_SECONDS) {
  22234. interstitialEvents[i + 1].appendInPlace = false;
  22235. if (interstitialEvents[i + 1].appendInPlace) {
  22236. this.warn(`Could not change append strategy for abutting event ${interstitial}`);
  22237. }
  22238. }
  22239. }
  22240. const resumeOffset = isFiniteNumber(interstitial.resumeOffset) ? interstitial.resumeOffset : interstitial.duration;
  22241. cumulativeDuration += resumeOffset;
  22242. });
  22243. }
  22244. primaryCanResumeInPlaceAt(interstitial, mediaSelection) {
  22245. const resumeTime = interstitial.resumeTime;
  22246. const resumesInPlaceAt = interstitial.startTime + interstitial.resumptionOffset;
  22247. if (Math.abs(resumeTime - resumesInPlaceAt) > ALIGNED_END_THRESHOLD_SECONDS) {
  22248. this.log(`"${interstitial.identifier}" resumption ${resumeTime} not aligned with estimated timeline end ${resumesInPlaceAt}`);
  22249. return false;
  22250. }
  22251. const playlists = Object.keys(mediaSelection);
  22252. return !playlists.some((playlistType) => {
  22253. const details = mediaSelection[playlistType].details;
  22254. const playlistEnd = details.edge;
  22255. if (resumeTime >= playlistEnd) {
  22256. this.log(`"${interstitial.identifier}" resumption ${resumeTime} past ${playlistType} playlist end ${playlistEnd}`);
  22257. return false;
  22258. }
  22259. const startFragment = findFragmentByPTS(null, details.fragments, resumeTime);
  22260. if (!startFragment) {
  22261. this.log(`"${interstitial.identifier}" resumption ${resumeTime} does not align with any fragments in ${playlistType} playlist (${details.fragStart}-${details.fragmentEnd})`);
  22262. return true;
  22263. }
  22264. const allowance = playlistType === "audio" ? 0.175 : 0;
  22265. const alignedWithSegment = Math.abs(startFragment.start - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance || Math.abs(startFragment.end - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance;
  22266. if (!alignedWithSegment) {
  22267. this.log(`"${interstitial.identifier}" resumption ${resumeTime} not aligned with ${playlistType} fragment bounds (${startFragment.start}-${startFragment.end} sn: ${startFragment.sn} cc: ${startFragment.cc})`);
  22268. return true;
  22269. }
  22270. return false;
  22271. });
  22272. }
  22273. updateAssetDurations(interstitial) {
  22274. if (!interstitial.assetListLoaded) {
  22275. return;
  22276. }
  22277. const eventStart = interstitial.timelineStart;
  22278. let sumDuration = 0;
  22279. let hasUnknownDuration = false;
  22280. let hasErrors = false;
  22281. for (let i = 0; i < interstitial.assetList.length; i++) {
  22282. const asset = interstitial.assetList[i];
  22283. const timelineStart = eventStart + sumDuration;
  22284. asset.startOffset = sumDuration;
  22285. asset.timelineStart = timelineStart;
  22286. hasUnknownDuration || (hasUnknownDuration = asset.duration === null);
  22287. hasErrors || (hasErrors = !!asset.error);
  22288. const duration = asset.error ? 0 : asset.duration || 0;
  22289. sumDuration += duration;
  22290. }
  22291. if (hasUnknownDuration && !hasErrors) {
  22292. interstitial.duration = Math.max(sumDuration, interstitial.duration);
  22293. } else {
  22294. interstitial.duration = sumDuration;
  22295. }
  22296. }
  22297. removeEvent(interstitial) {
  22298. interstitial.reset();
  22299. delete this.eventMap[interstitial.identifier];
  22300. }
  22301. };
  22302. function segmentToString(segment) {
  22303. return `[${segment.event ? '"' + segment.event.identifier + '"' : "primary"}: ${segment.start.toFixed(2)}-${segment.end.toFixed(2)}]`;
  22304. }
  22305. var AssetListLoader = class {
  22306. constructor(hls) {
  22307. this.hls = void 0;
  22308. this.hls = hls;
  22309. }
  22310. destroy() {
  22311. this.hls = null;
  22312. }
  22313. loadAssetList(interstitial, hlsStartOffset) {
  22314. const assetListUrl = interstitial.assetListUrl;
  22315. let url;
  22316. try {
  22317. url = getInterstitialUrl(assetListUrl, this.hls.sessionId, interstitial.baseUrl);
  22318. } catch (error) {
  22319. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_ERROR, error, assetListUrl);
  22320. this.hls.trigger(Events.ERROR, errorData);
  22321. return;
  22322. }
  22323. if (hlsStartOffset && url.protocol !== "data:") {
  22324. url.searchParams.set("_HLS_start_offset", "" + hlsStartOffset);
  22325. }
  22326. const config = this.hls.config;
  22327. const Loader = config.loader;
  22328. const loader = new Loader(config);
  22329. const context = {
  22330. responseType: "json",
  22331. url: url.href
  22332. };
  22333. const loadPolicy = config.interstitialAssetListLoadPolicy.default;
  22334. const loaderConfig = {
  22335. loadPolicy,
  22336. timeout: loadPolicy.maxLoadTimeMs,
  22337. maxRetry: 0,
  22338. retryDelay: 0,
  22339. maxRetryDelay: 0
  22340. };
  22341. const callbacks = {
  22342. onSuccess: (response, stats, context2, networkDetails) => {
  22343. const assetListResponse = response.data;
  22344. const assets = assetListResponse == null ? void 0 : assetListResponse.ASSETS;
  22345. if (!Array.isArray(assets)) {
  22346. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_PARSING_ERROR, new Error(`Invalid interstitial asset list`), context2.url, stats, networkDetails);
  22347. this.hls.trigger(Events.ERROR, errorData);
  22348. return;
  22349. }
  22350. interstitial.assetListResponse = assetListResponse;
  22351. this.hls.trigger(Events.ASSET_LIST_LOADED, {
  22352. event: interstitial,
  22353. assetListResponse,
  22354. networkDetails
  22355. });
  22356. },
  22357. onError: (error, context2, networkDetails, stats) => {
  22358. 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);
  22359. this.hls.trigger(Events.ERROR, errorData);
  22360. },
  22361. onTimeout: (stats, context2, networkDetails) => {
  22362. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_TIMEOUT, new Error(`Timeout loading X-ASSET-LIST (${context2.url})`), context2.url, stats, networkDetails);
  22363. this.hls.trigger(Events.ERROR, errorData);
  22364. }
  22365. };
  22366. loader.load(context, loaderConfig, callbacks);
  22367. this.hls.trigger(Events.ASSET_LIST_LOADING, {
  22368. event: interstitial
  22369. });
  22370. return loader;
  22371. }
  22372. assignAssetListError(interstitial, details, error, url, stats, networkDetails) {
  22373. interstitial.error = error;
  22374. return {
  22375. type: ErrorTypes.NETWORK_ERROR,
  22376. details,
  22377. fatal: false,
  22378. interstitial,
  22379. url,
  22380. error,
  22381. networkDetails,
  22382. stats
  22383. };
  22384. }
  22385. };
  22386. function playWithCatch(media) {
  22387. media == null || media.play().catch(() => {
  22388. });
  22389. }
  22390. function timelineMessage(label, time) {
  22391. return `[${label}] Advancing timeline position to ${time}`;
  22392. }
  22393. var InterstitialsController = class extends Logger {
  22394. constructor(hls, HlsPlayerClass) {
  22395. super("interstitials", hls.logger);
  22396. this.HlsPlayerClass = void 0;
  22397. this.hls = void 0;
  22398. this.assetListLoader = void 0;
  22399. this.mediaSelection = null;
  22400. this.altSelection = null;
  22401. this.media = null;
  22402. this.detachedData = null;
  22403. this.requiredTracks = null;
  22404. this.manager = null;
  22405. this.playerQueue = [];
  22406. this.bufferedPos = -1;
  22407. this.timelinePos = -1;
  22408. this.schedule = void 0;
  22409. this.playingItem = null;
  22410. this.bufferingItem = null;
  22411. this.waitingItem = null;
  22412. this.endedItem = null;
  22413. this.playingAsset = null;
  22414. this.endedAsset = null;
  22415. this.bufferingAsset = null;
  22416. this.shouldPlay = false;
  22417. this.onPlay = () => {
  22418. this.shouldPlay = true;
  22419. };
  22420. this.onPause = () => {
  22421. this.shouldPlay = false;
  22422. };
  22423. this.onSeeking = () => {
  22424. const currentTime = this.currentTime;
  22425. if (currentTime === void 0 || this.playbackDisabled || !this.schedule) {
  22426. return;
  22427. }
  22428. const diff = currentTime - this.timelinePos;
  22429. const roundingError = Math.abs(diff) < 1 / 7056e5;
  22430. if (roundingError) {
  22431. return;
  22432. }
  22433. const backwardSeek = diff <= -0.01;
  22434. this.timelinePos = currentTime;
  22435. this.bufferedPos = currentTime;
  22436. const playingItem = this.playingItem;
  22437. if (!playingItem) {
  22438. this.checkBuffer();
  22439. return;
  22440. }
  22441. if (backwardSeek) {
  22442. const resetCount = this.schedule.resetErrorsInRange(currentTime, currentTime - diff);
  22443. if (resetCount) {
  22444. this.updateSchedule(true);
  22445. }
  22446. }
  22447. this.checkBuffer();
  22448. if (backwardSeek && currentTime < playingItem.start || currentTime >= playingItem.end) {
  22449. var _this$media;
  22450. const playingIndex = this.findItemIndex(playingItem);
  22451. let scheduleIndex = this.schedule.findItemIndexAtTime(currentTime);
  22452. if (scheduleIndex === -1) {
  22453. scheduleIndex = playingIndex + (backwardSeek ? -1 : 1);
  22454. this.log(`seeked ${backwardSeek ? "back " : ""}to position not covered by schedule ${currentTime} (resolving from ${playingIndex} to ${scheduleIndex})`);
  22455. }
  22456. if (!this.isInterstitial(playingItem) && (_this$media = this.media) != null && _this$media.paused) {
  22457. this.shouldPlay = false;
  22458. }
  22459. if (!backwardSeek) {
  22460. if (scheduleIndex > playingIndex) {
  22461. const jumpIndex = this.schedule.findJumpRestrictedIndex(playingIndex + 1, scheduleIndex);
  22462. if (jumpIndex > playingIndex) {
  22463. this.setSchedulePosition(jumpIndex);
  22464. return;
  22465. }
  22466. }
  22467. }
  22468. this.setSchedulePosition(scheduleIndex);
  22469. return;
  22470. }
  22471. const playingAsset = this.playingAsset;
  22472. if (!playingAsset) {
  22473. if (this.playingLastItem && this.isInterstitial(playingItem)) {
  22474. const restartAsset = playingItem.event.assetList[0];
  22475. if (restartAsset) {
  22476. this.endedItem = this.playingItem;
  22477. this.playingItem = null;
  22478. this.setScheduleToAssetAtTime(currentTime, restartAsset);
  22479. }
  22480. }
  22481. return;
  22482. }
  22483. const start = playingAsset.timelineStart;
  22484. const duration = playingAsset.duration || 0;
  22485. if (backwardSeek && currentTime < start || currentTime >= start + duration) {
  22486. var _playingItem$event;
  22487. if ((_playingItem$event = playingItem.event) != null && _playingItem$event.appendInPlace) {
  22488. this.clearInterstitial(playingItem.event, playingItem);
  22489. this.flushFrontBuffer(currentTime);
  22490. }
  22491. this.setScheduleToAssetAtTime(currentTime, playingAsset);
  22492. }
  22493. };
  22494. this.onTimeupdate = () => {
  22495. const currentTime = this.currentTime;
  22496. if (currentTime === void 0 || this.playbackDisabled) {
  22497. return;
  22498. }
  22499. if (currentTime > this.timelinePos) {
  22500. this.timelinePos = currentTime;
  22501. if (currentTime > this.bufferedPos) {
  22502. this.checkBuffer();
  22503. }
  22504. } else {
  22505. return;
  22506. }
  22507. const playingItem = this.playingItem;
  22508. if (!playingItem || this.playingLastItem) {
  22509. return;
  22510. }
  22511. if (currentTime >= playingItem.end) {
  22512. this.timelinePos = playingItem.end;
  22513. const playingIndex = this.findItemIndex(playingItem);
  22514. this.setSchedulePosition(playingIndex + 1);
  22515. }
  22516. const playingAsset = this.playingAsset;
  22517. if (!playingAsset) {
  22518. return;
  22519. }
  22520. const end = playingAsset.timelineStart + (playingAsset.duration || 0);
  22521. if (currentTime >= end) {
  22522. this.setScheduleToAssetAtTime(currentTime, playingAsset);
  22523. }
  22524. };
  22525. this.onScheduleUpdate = (removedInterstitials, previousItems) => {
  22526. const schedule = this.schedule;
  22527. if (!schedule) {
  22528. return;
  22529. }
  22530. const playingItem = this.playingItem;
  22531. const interstitialEvents = schedule.events || [];
  22532. const scheduleItems = schedule.items || [];
  22533. const durations = schedule.durations;
  22534. const removedIds = removedInterstitials.map((interstitial) => interstitial.identifier);
  22535. const interstitialsUpdated = !!(interstitialEvents.length || removedIds.length);
  22536. if (interstitialsUpdated || previousItems) {
  22537. this.log(`INTERSTITIALS_UPDATED (${interstitialEvents.length}): ${interstitialEvents}
  22538. Schedule: ${scheduleItems.map((seg) => segmentToString(seg))} pos: ${this.timelinePos}`);
  22539. }
  22540. if (removedIds.length) {
  22541. this.log(`Removed events ${removedIds}`);
  22542. }
  22543. let updatedPlayingItem = null;
  22544. let updatedBufferingItem = null;
  22545. if (playingItem) {
  22546. updatedPlayingItem = this.updateItem(playingItem, this.timelinePos);
  22547. if (this.itemsMatch(playingItem, updatedPlayingItem)) {
  22548. this.playingItem = updatedPlayingItem;
  22549. } else {
  22550. this.waitingItem = this.endedItem = null;
  22551. }
  22552. }
  22553. this.waitingItem = this.updateItem(this.waitingItem);
  22554. this.endedItem = this.updateItem(this.endedItem);
  22555. const bufferingItem = this.bufferingItem;
  22556. if (bufferingItem) {
  22557. updatedBufferingItem = this.updateItem(bufferingItem, this.bufferedPos);
  22558. if (this.itemsMatch(bufferingItem, updatedBufferingItem)) {
  22559. this.bufferingItem = updatedBufferingItem;
  22560. } else if (bufferingItem.event) {
  22561. this.bufferingItem = this.playingItem;
  22562. this.clearInterstitial(bufferingItem.event, null);
  22563. }
  22564. }
  22565. removedInterstitials.forEach((interstitial) => {
  22566. interstitial.assetList.forEach((asset) => {
  22567. this.clearAssetPlayer(asset.identifier, null);
  22568. });
  22569. });
  22570. this.playerQueue.forEach((player) => {
  22571. if (player.interstitial.appendInPlace) {
  22572. const timelineStart = player.assetItem.timelineStart;
  22573. const diff = player.timelineOffset - timelineStart;
  22574. if (diff) {
  22575. try {
  22576. player.timelineOffset = timelineStart;
  22577. } catch (e) {
  22578. if (Math.abs(diff) > ALIGNED_END_THRESHOLD_SECONDS) {
  22579. this.warn(`${e} ("${player.assetId}" ${player.timelineOffset}->${timelineStart})`);
  22580. }
  22581. }
  22582. }
  22583. }
  22584. });
  22585. if (interstitialsUpdated || previousItems) {
  22586. this.hls.trigger(Events.INTERSTITIALS_UPDATED, {
  22587. events: interstitialEvents.slice(0),
  22588. schedule: scheduleItems.slice(0),
  22589. durations,
  22590. removedIds
  22591. });
  22592. if (this.isInterstitial(playingItem) && removedIds.includes(playingItem.event.identifier)) {
  22593. this.warn(`Interstitial "${playingItem.event.identifier}" removed while playing`);
  22594. this.primaryFallback(playingItem.event);
  22595. return;
  22596. }
  22597. if (playingItem) {
  22598. this.trimInPlace(updatedPlayingItem, playingItem);
  22599. }
  22600. if (bufferingItem && updatedBufferingItem !== updatedPlayingItem) {
  22601. this.trimInPlace(updatedBufferingItem, bufferingItem);
  22602. }
  22603. this.checkBuffer();
  22604. }
  22605. };
  22606. this.hls = hls;
  22607. this.HlsPlayerClass = HlsPlayerClass;
  22608. this.assetListLoader = new AssetListLoader(hls);
  22609. this.schedule = new InterstitialsSchedule(this.onScheduleUpdate, hls.logger);
  22610. this.registerListeners();
  22611. }
  22612. registerListeners() {
  22613. const hls = this.hls;
  22614. if (hls) {
  22615. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  22616. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  22617. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  22618. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  22619. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  22620. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  22621. hls.on(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);
  22622. hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  22623. hls.on(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);
  22624. hls.on(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);
  22625. hls.on(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);
  22626. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  22627. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  22628. hls.on(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);
  22629. hls.on(Events.MEDIA_ENDED, this.onMediaEnded, this);
  22630. hls.on(Events.ERROR, this.onError, this);
  22631. hls.on(Events.DESTROYING, this.onDestroying, this);
  22632. }
  22633. }
  22634. unregisterListeners() {
  22635. const hls = this.hls;
  22636. if (hls) {
  22637. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  22638. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  22639. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  22640. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  22641. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  22642. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  22643. hls.off(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);
  22644. hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  22645. hls.off(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);
  22646. hls.off(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);
  22647. hls.off(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);
  22648. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  22649. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  22650. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  22651. hls.off(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);
  22652. hls.off(Events.MEDIA_ENDED, this.onMediaEnded, this);
  22653. hls.off(Events.ERROR, this.onError, this);
  22654. hls.off(Events.DESTROYING, this.onDestroying, this);
  22655. }
  22656. }
  22657. startLoad() {
  22658. this.resumeBuffering();
  22659. }
  22660. stopLoad() {
  22661. this.pauseBuffering();
  22662. }
  22663. resumeBuffering() {
  22664. var _this$getBufferingPla;
  22665. (_this$getBufferingPla = this.getBufferingPlayer()) == null || _this$getBufferingPla.resumeBuffering();
  22666. }
  22667. pauseBuffering() {
  22668. var _this$getBufferingPla2;
  22669. (_this$getBufferingPla2 = this.getBufferingPlayer()) == null || _this$getBufferingPla2.pauseBuffering();
  22670. }
  22671. destroy() {
  22672. this.unregisterListeners();
  22673. this.stopLoad();
  22674. if (this.assetListLoader) {
  22675. this.assetListLoader.destroy();
  22676. }
  22677. this.emptyPlayerQueue();
  22678. this.clearScheduleState();
  22679. if (this.schedule) {
  22680. this.schedule.destroy();
  22681. }
  22682. this.media = this.detachedData = this.mediaSelection = this.requiredTracks = this.altSelection = this.schedule = this.manager = null;
  22683. this.hls = this.HlsPlayerClass = this.log = null;
  22684. this.assetListLoader = null;
  22685. this.onPlay = this.onPause = this.onSeeking = this.onTimeupdate = null;
  22686. this.onScheduleUpdate = null;
  22687. }
  22688. onDestroying() {
  22689. const media = this.primaryMedia || this.media;
  22690. if (media) {
  22691. this.removeMediaListeners(media);
  22692. }
  22693. }
  22694. removeMediaListeners(media) {
  22695. removeEventListener(media, "play", this.onPlay);
  22696. removeEventListener(media, "pause", this.onPause);
  22697. removeEventListener(media, "seeking", this.onSeeking);
  22698. removeEventListener(media, "timeupdate", this.onTimeupdate);
  22699. }
  22700. onMediaAttaching(event, data) {
  22701. const media = this.media = data.media;
  22702. addEventListener(media, "seeking", this.onSeeking);
  22703. addEventListener(media, "timeupdate", this.onTimeupdate);
  22704. addEventListener(media, "play", this.onPlay);
  22705. addEventListener(media, "pause", this.onPause);
  22706. }
  22707. onMediaAttached(event, data) {
  22708. const playingItem = this.effectivePlayingItem;
  22709. const detachedMedia = this.detachedData;
  22710. this.detachedData = null;
  22711. if (playingItem === null) {
  22712. this.checkStart();
  22713. } else if (!detachedMedia) {
  22714. this.clearScheduleState();
  22715. const playingIndex = this.findItemIndex(playingItem);
  22716. this.setSchedulePosition(playingIndex);
  22717. }
  22718. }
  22719. clearScheduleState() {
  22720. this.log(`clear schedule state`);
  22721. this.playingItem = this.bufferingItem = this.waitingItem = this.endedItem = this.playingAsset = this.endedAsset = this.bufferingAsset = null;
  22722. }
  22723. onMediaDetaching(event, data) {
  22724. const transferringMedia = !!data.transferMedia;
  22725. const media = this.media;
  22726. this.media = null;
  22727. if (transferringMedia) {
  22728. return;
  22729. }
  22730. if (media) {
  22731. this.removeMediaListeners(media);
  22732. }
  22733. if (this.detachedData) {
  22734. const player = this.getBufferingPlayer();
  22735. if (player) {
  22736. this.log(`Removing schedule state for detachedData and ${player}`);
  22737. this.playingAsset = this.endedAsset = this.bufferingAsset = this.bufferingItem = this.waitingItem = this.detachedData = null;
  22738. player.detachMedia();
  22739. }
  22740. this.shouldPlay = false;
  22741. }
  22742. }
  22743. get interstitialsManager() {
  22744. if (!this.hls) {
  22745. return null;
  22746. }
  22747. if (this.manager) {
  22748. return this.manager;
  22749. }
  22750. const c = this;
  22751. const effectiveBufferingItem = () => c.bufferingItem || c.waitingItem;
  22752. const getAssetPlayer = (asset) => asset ? c.getAssetPlayer(asset.identifier) : asset;
  22753. const getMappedTime = (item, timelineType, asset, controllerField, assetPlayerField) => {
  22754. if (item) {
  22755. let time = item[timelineType].start;
  22756. const interstitial = item.event;
  22757. if (interstitial) {
  22758. if (timelineType === "playout" || interstitial.timelineOccupancy !== TimelineOccupancy.Point) {
  22759. const assetPlayer = getAssetPlayer(asset);
  22760. if ((assetPlayer == null ? void 0 : assetPlayer.interstitial) === interstitial) {
  22761. time += assetPlayer.assetItem.startOffset + assetPlayer[assetPlayerField];
  22762. }
  22763. }
  22764. } else {
  22765. const value = controllerField === "bufferedPos" ? getBufferedEnd() : c[controllerField];
  22766. time += value - item.start;
  22767. }
  22768. return time;
  22769. }
  22770. return 0;
  22771. };
  22772. const findMappedTime = (primaryTime, timelineType) => {
  22773. var _c$schedule;
  22774. if (primaryTime !== 0 && timelineType !== "primary" && (_c$schedule = c.schedule) != null && _c$schedule.length) {
  22775. var _c$schedule$items;
  22776. const index = c.schedule.findItemIndexAtTime(primaryTime);
  22777. const item = (_c$schedule$items = c.schedule.items) == null ? void 0 : _c$schedule$items[index];
  22778. if (item) {
  22779. const diff = item[timelineType].start - item.start;
  22780. return primaryTime + diff;
  22781. }
  22782. }
  22783. return primaryTime;
  22784. };
  22785. const getBufferedEnd = () => {
  22786. const value = c.bufferedPos;
  22787. if (value === Number.MAX_VALUE) {
  22788. return getMappedDuration("primary");
  22789. }
  22790. return Math.max(value, 0);
  22791. };
  22792. const getMappedDuration = (timelineType) => {
  22793. var _c$primaryDetails, _c$schedule2;
  22794. if ((_c$primaryDetails = c.primaryDetails) != null && _c$primaryDetails.live) {
  22795. return c.primaryDetails.edge;
  22796. }
  22797. return ((_c$schedule2 = c.schedule) == null ? void 0 : _c$schedule2.durations[timelineType]) || 0;
  22798. };
  22799. const seekTo = (time, timelineType) => {
  22800. var _item$event, _c$schedule$items2;
  22801. const item = c.effectivePlayingItem;
  22802. if (item != null && (_item$event = item.event) != null && _item$event.restrictions.skip || !c.schedule) {
  22803. return;
  22804. }
  22805. c.log(`seek to ${time} "${timelineType}"`);
  22806. const playingItem = c.effectivePlayingItem;
  22807. const targetIndex = c.schedule.findItemIndexAtTime(time, timelineType);
  22808. const targetItem = (_c$schedule$items2 = c.schedule.items) == null ? void 0 : _c$schedule$items2[targetIndex];
  22809. const bufferingPlayer = c.getBufferingPlayer();
  22810. const bufferingInterstitial = bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial;
  22811. const appendInPlace = bufferingInterstitial == null ? void 0 : bufferingInterstitial.appendInPlace;
  22812. const seekInItem = playingItem && c.itemsMatch(playingItem, targetItem);
  22813. if (playingItem && (appendInPlace || seekInItem)) {
  22814. const assetPlayer = getAssetPlayer(c.playingAsset);
  22815. const media = (assetPlayer == null ? void 0 : assetPlayer.media) || c.primaryMedia;
  22816. if (media) {
  22817. const currentTime = timelineType === "primary" ? media.currentTime : getMappedTime(playingItem, timelineType, c.playingAsset, "timelinePos", "currentTime");
  22818. const diff = time - currentTime;
  22819. const seekToTime = (appendInPlace ? currentTime : media.currentTime) + diff;
  22820. if (seekToTime >= 0 && (!assetPlayer || appendInPlace || seekToTime <= assetPlayer.duration)) {
  22821. media.currentTime = seekToTime;
  22822. return;
  22823. }
  22824. }
  22825. }
  22826. if (targetItem) {
  22827. let seekToTime = time;
  22828. if (timelineType !== "primary") {
  22829. const primarySegmentStart = targetItem[timelineType].start;
  22830. const diff = time - primarySegmentStart;
  22831. seekToTime = targetItem.start + diff;
  22832. }
  22833. const targetIsPrimary = !c.isInterstitial(targetItem);
  22834. if ((!c.isInterstitial(playingItem) || playingItem.event.appendInPlace) && (targetIsPrimary || targetItem.event.appendInPlace)) {
  22835. const media = c.media || (appendInPlace ? bufferingPlayer == null ? void 0 : bufferingPlayer.media : null);
  22836. if (media) {
  22837. media.currentTime = seekToTime;
  22838. }
  22839. } else if (playingItem) {
  22840. const playingIndex = c.findItemIndex(playingItem);
  22841. if (targetIndex > playingIndex) {
  22842. const jumpIndex = c.schedule.findJumpRestrictedIndex(playingIndex + 1, targetIndex);
  22843. if (jumpIndex > playingIndex) {
  22844. c.setSchedulePosition(jumpIndex);
  22845. return;
  22846. }
  22847. }
  22848. let assetIndex = 0;
  22849. if (targetIsPrimary) {
  22850. c.timelinePos = seekToTime;
  22851. c.checkBuffer();
  22852. } else {
  22853. const assetList = targetItem.event.assetList;
  22854. const eventTime = time - (targetItem[timelineType] || targetItem).start;
  22855. for (let i = assetList.length; i--; ) {
  22856. const asset = assetList[i];
  22857. if (asset.duration && eventTime >= asset.startOffset && eventTime < asset.startOffset + asset.duration) {
  22858. assetIndex = i;
  22859. break;
  22860. }
  22861. }
  22862. }
  22863. c.setSchedulePosition(targetIndex, assetIndex);
  22864. }
  22865. }
  22866. };
  22867. const getActiveInterstitial = () => {
  22868. const playingItem = c.effectivePlayingItem;
  22869. if (c.isInterstitial(playingItem)) {
  22870. return playingItem;
  22871. }
  22872. const bufferingItem = effectiveBufferingItem();
  22873. if (c.isInterstitial(bufferingItem)) {
  22874. return bufferingItem;
  22875. }
  22876. return null;
  22877. };
  22878. const interstitialPlayer = {
  22879. get bufferedEnd() {
  22880. const interstitialItem = effectiveBufferingItem();
  22881. const bufferingItem = c.bufferingItem;
  22882. if (bufferingItem && bufferingItem === interstitialItem) {
  22883. var _c$bufferingAsset;
  22884. return getMappedTime(bufferingItem, "playout", c.bufferingAsset, "bufferedPos", "bufferedEnd") - bufferingItem.playout.start || ((_c$bufferingAsset = c.bufferingAsset) == null ? void 0 : _c$bufferingAsset.startOffset) || 0;
  22885. }
  22886. return 0;
  22887. },
  22888. get currentTime() {
  22889. const interstitialItem = getActiveInterstitial();
  22890. const playingItem = c.effectivePlayingItem;
  22891. if (playingItem && playingItem === interstitialItem) {
  22892. return getMappedTime(playingItem, "playout", c.effectivePlayingAsset, "timelinePos", "currentTime") - playingItem.playout.start;
  22893. }
  22894. return 0;
  22895. },
  22896. set currentTime(time) {
  22897. const interstitialItem = getActiveInterstitial();
  22898. const playingItem = c.effectivePlayingItem;
  22899. if (playingItem && playingItem === interstitialItem) {
  22900. seekTo(time + playingItem.playout.start, "playout");
  22901. }
  22902. },
  22903. get duration() {
  22904. const interstitialItem = getActiveInterstitial();
  22905. if (interstitialItem) {
  22906. return interstitialItem.playout.end - interstitialItem.playout.start;
  22907. }
  22908. return 0;
  22909. },
  22910. get assetPlayers() {
  22911. var _getActiveInterstitia;
  22912. const assetList = (_getActiveInterstitia = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia.event.assetList;
  22913. if (assetList) {
  22914. return assetList.map((asset) => c.getAssetPlayer(asset.identifier));
  22915. }
  22916. return [];
  22917. },
  22918. get playingIndex() {
  22919. var _getActiveInterstitia2;
  22920. const interstitial = (_getActiveInterstitia2 = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia2.event;
  22921. if (interstitial && c.effectivePlayingAsset) {
  22922. return interstitial.findAssetIndex(c.effectivePlayingAsset);
  22923. }
  22924. return -1;
  22925. },
  22926. get scheduleItem() {
  22927. return getActiveInterstitial();
  22928. }
  22929. };
  22930. return this.manager = {
  22931. get events() {
  22932. var _c$schedule3;
  22933. return ((_c$schedule3 = c.schedule) == null || (_c$schedule3 = _c$schedule3.events) == null ? void 0 : _c$schedule3.slice(0)) || [];
  22934. },
  22935. get schedule() {
  22936. var _c$schedule4;
  22937. return ((_c$schedule4 = c.schedule) == null || (_c$schedule4 = _c$schedule4.items) == null ? void 0 : _c$schedule4.slice(0)) || [];
  22938. },
  22939. get interstitialPlayer() {
  22940. if (getActiveInterstitial()) {
  22941. return interstitialPlayer;
  22942. }
  22943. return null;
  22944. },
  22945. get playerQueue() {
  22946. return c.playerQueue.slice(0);
  22947. },
  22948. get bufferingAsset() {
  22949. return c.bufferingAsset;
  22950. },
  22951. get bufferingItem() {
  22952. return effectiveBufferingItem();
  22953. },
  22954. get bufferingIndex() {
  22955. const item = effectiveBufferingItem();
  22956. return c.findItemIndex(item);
  22957. },
  22958. get playingAsset() {
  22959. return c.effectivePlayingAsset;
  22960. },
  22961. get playingItem() {
  22962. return c.effectivePlayingItem;
  22963. },
  22964. get playingIndex() {
  22965. const item = c.effectivePlayingItem;
  22966. return c.findItemIndex(item);
  22967. },
  22968. primary: {
  22969. get bufferedEnd() {
  22970. return getBufferedEnd();
  22971. },
  22972. get currentTime() {
  22973. const timelinePos = c.timelinePos;
  22974. return timelinePos > 0 ? timelinePos : 0;
  22975. },
  22976. set currentTime(time) {
  22977. seekTo(time, "primary");
  22978. },
  22979. get duration() {
  22980. return getMappedDuration("primary");
  22981. },
  22982. get seekableStart() {
  22983. var _c$primaryDetails2;
  22984. return ((_c$primaryDetails2 = c.primaryDetails) == null ? void 0 : _c$primaryDetails2.fragmentStart) || 0;
  22985. }
  22986. },
  22987. integrated: {
  22988. get bufferedEnd() {
  22989. return getMappedTime(effectiveBufferingItem(), "integrated", c.bufferingAsset, "bufferedPos", "bufferedEnd");
  22990. },
  22991. get currentTime() {
  22992. return getMappedTime(c.effectivePlayingItem, "integrated", c.effectivePlayingAsset, "timelinePos", "currentTime");
  22993. },
  22994. set currentTime(time) {
  22995. seekTo(time, "integrated");
  22996. },
  22997. get duration() {
  22998. return getMappedDuration("integrated");
  22999. },
  23000. get seekableStart() {
  23001. var _c$primaryDetails3;
  23002. return findMappedTime(((_c$primaryDetails3 = c.primaryDetails) == null ? void 0 : _c$primaryDetails3.fragmentStart) || 0, "integrated");
  23003. }
  23004. },
  23005. skip: () => {
  23006. const item = c.effectivePlayingItem;
  23007. const event = item == null ? void 0 : item.event;
  23008. if (event && !event.restrictions.skip) {
  23009. const index = c.findItemIndex(item);
  23010. if (event.appendInPlace) {
  23011. const time = item.playout.start + item.event.duration;
  23012. seekTo(time + 1e-3, "playout");
  23013. } else {
  23014. c.advanceAfterAssetEnded(event, index, Infinity);
  23015. }
  23016. }
  23017. }
  23018. };
  23019. }
  23020. // Schedule getters
  23021. get effectivePlayingItem() {
  23022. return this.waitingItem || this.playingItem || this.endedItem;
  23023. }
  23024. get effectivePlayingAsset() {
  23025. return this.playingAsset || this.endedAsset;
  23026. }
  23027. get playingLastItem() {
  23028. var _this$schedule;
  23029. const playingItem = this.playingItem;
  23030. const items = (_this$schedule = this.schedule) == null ? void 0 : _this$schedule.items;
  23031. if (!this.playbackStarted || !playingItem || !items) {
  23032. return false;
  23033. }
  23034. return this.findItemIndex(playingItem) === items.length - 1;
  23035. }
  23036. get playbackStarted() {
  23037. return this.effectivePlayingItem !== null;
  23038. }
  23039. // Media getters and event callbacks
  23040. get currentTime() {
  23041. var _this$bufferingItem, _media;
  23042. if (this.mediaSelection === null) {
  23043. return void 0;
  23044. }
  23045. const queuedForPlayback = this.waitingItem || this.playingItem;
  23046. if (this.isInterstitial(queuedForPlayback) && !queuedForPlayback.event.appendInPlace) {
  23047. return void 0;
  23048. }
  23049. let media = this.media;
  23050. if (!media && (_this$bufferingItem = this.bufferingItem) != null && (_this$bufferingItem = _this$bufferingItem.event) != null && _this$bufferingItem.appendInPlace) {
  23051. media = this.primaryMedia;
  23052. }
  23053. const currentTime = (_media = media) == null ? void 0 : _media.currentTime;
  23054. if (currentTime === void 0 || !isFiniteNumber(currentTime)) {
  23055. return void 0;
  23056. }
  23057. return currentTime;
  23058. }
  23059. get primaryMedia() {
  23060. var _this$detachedData;
  23061. return this.media || ((_this$detachedData = this.detachedData) == null ? void 0 : _this$detachedData.media) || null;
  23062. }
  23063. isInterstitial(item) {
  23064. return !!(item != null && item.event);
  23065. }
  23066. retreiveMediaSource(assetId, toSegment) {
  23067. const player = this.getAssetPlayer(assetId);
  23068. if (player) {
  23069. this.transferMediaFromPlayer(player, toSegment);
  23070. }
  23071. }
  23072. transferMediaFromPlayer(player, toSegment) {
  23073. const appendInPlace = player.interstitial.appendInPlace;
  23074. const playerMedia = player.media;
  23075. if (appendInPlace && playerMedia === this.primaryMedia) {
  23076. this.bufferingAsset = null;
  23077. if (!toSegment || this.isInterstitial(toSegment) && !toSegment.event.appendInPlace) {
  23078. if (toSegment && playerMedia) {
  23079. this.detachedData = {
  23080. media: playerMedia
  23081. };
  23082. return;
  23083. }
  23084. }
  23085. const attachMediaSourceData = player.transferMedia();
  23086. this.log(`transfer MediaSource from ${player} ${stringify(attachMediaSourceData)}`);
  23087. this.detachedData = attachMediaSourceData;
  23088. } else if (toSegment && playerMedia) {
  23089. this.shouldPlay || (this.shouldPlay = !playerMedia.paused);
  23090. }
  23091. }
  23092. transferMediaTo(player, media) {
  23093. var _this$detachedData2, _attachMediaSourceDat;
  23094. if (player.media === media) {
  23095. return;
  23096. }
  23097. let attachMediaSourceData = null;
  23098. const primaryPlayer = this.hls;
  23099. const isAssetPlayer = player !== primaryPlayer;
  23100. const appendInPlace = isAssetPlayer && player.interstitial.appendInPlace;
  23101. const detachedMediaSource = (_this$detachedData2 = this.detachedData) == null ? void 0 : _this$detachedData2.mediaSource;
  23102. let logFromSource;
  23103. if (primaryPlayer.media) {
  23104. if (appendInPlace) {
  23105. attachMediaSourceData = primaryPlayer.transferMedia();
  23106. this.detachedData = attachMediaSourceData;
  23107. }
  23108. logFromSource = `Primary`;
  23109. } else if (detachedMediaSource) {
  23110. const bufferingPlayer = this.getBufferingPlayer();
  23111. if (bufferingPlayer) {
  23112. attachMediaSourceData = bufferingPlayer.transferMedia();
  23113. logFromSource = `${bufferingPlayer}`;
  23114. } else {
  23115. logFromSource = `detached MediaSource`;
  23116. }
  23117. } else {
  23118. logFromSource = `detached media`;
  23119. }
  23120. if (!attachMediaSourceData) {
  23121. if (detachedMediaSource) {
  23122. attachMediaSourceData = this.detachedData;
  23123. this.log(`using detachedData: MediaSource ${stringify(attachMediaSourceData)}`);
  23124. } else if (!this.detachedData || primaryPlayer.media === media) {
  23125. const playerQueue = this.playerQueue;
  23126. if (playerQueue.length > 1) {
  23127. playerQueue.forEach((queuedPlayer) => {
  23128. if (isAssetPlayer && queuedPlayer.interstitial.appendInPlace !== appendInPlace) {
  23129. const interstitial = queuedPlayer.interstitial;
  23130. this.clearInterstitial(queuedPlayer.interstitial, null);
  23131. interstitial.appendInPlace = false;
  23132. if (interstitial.appendInPlace) {
  23133. this.warn(`Could not change append strategy for queued assets ${interstitial}`);
  23134. }
  23135. }
  23136. });
  23137. }
  23138. this.hls.detachMedia();
  23139. this.detachedData = {
  23140. media
  23141. };
  23142. }
  23143. }
  23144. const transferring = attachMediaSourceData && "mediaSource" in attachMediaSourceData && ((_attachMediaSourceDat = attachMediaSourceData.mediaSource) == null ? void 0 : _attachMediaSourceDat.readyState) !== "closed";
  23145. const dataToAttach = transferring && attachMediaSourceData ? attachMediaSourceData : media;
  23146. this.log(`${transferring ? "transfering MediaSource" : "attaching media"} to ${isAssetPlayer ? player : "Primary"} from ${logFromSource} (media.currentTime: ${media.currentTime})`);
  23147. const schedule = this.schedule;
  23148. if (dataToAttach === attachMediaSourceData && schedule) {
  23149. const isAssetAtEndOfSchedule = isAssetPlayer && player.assetId === schedule.assetIdAtEnd;
  23150. dataToAttach.overrides = {
  23151. duration: schedule.duration,
  23152. endOfStream: !isAssetPlayer || isAssetAtEndOfSchedule,
  23153. cueRemoval: !isAssetPlayer
  23154. };
  23155. }
  23156. player.attachMedia(dataToAttach);
  23157. }
  23158. onInterstitialCueEnter() {
  23159. this.onTimeupdate();
  23160. }
  23161. // Scheduling methods
  23162. checkStart() {
  23163. const schedule = this.schedule;
  23164. const interstitialEvents = schedule == null ? void 0 : schedule.events;
  23165. if (!interstitialEvents || this.playbackDisabled || !this.media) {
  23166. return;
  23167. }
  23168. if (this.bufferedPos === -1) {
  23169. this.bufferedPos = 0;
  23170. }
  23171. const timelinePos = this.timelinePos;
  23172. const effectivePlayingItem = this.effectivePlayingItem;
  23173. if (timelinePos === -1) {
  23174. const startPosition = this.hls.startPosition;
  23175. this.log(timelineMessage("checkStart", startPosition));
  23176. this.timelinePos = startPosition;
  23177. if (interstitialEvents.length && interstitialEvents[0].cue.pre) {
  23178. const index = schedule.findEventIndex(interstitialEvents[0].identifier);
  23179. this.setSchedulePosition(index);
  23180. } else if (startPosition >= 0 || !this.primaryLive) {
  23181. const start = this.timelinePos = startPosition > 0 ? startPosition : 0;
  23182. const index = schedule.findItemIndexAtTime(start);
  23183. this.setSchedulePosition(index);
  23184. }
  23185. } else if (effectivePlayingItem && !this.playingItem) {
  23186. const index = schedule.findItemIndex(effectivePlayingItem);
  23187. this.setSchedulePosition(index);
  23188. }
  23189. }
  23190. advanceAssetBuffering(item, assetItem) {
  23191. const interstitial = item.event;
  23192. const assetListIndex = interstitial.findAssetIndex(assetItem);
  23193. const nextAssetIndex = getNextAssetIndex(interstitial, assetListIndex);
  23194. if (!interstitial.isAssetPastPlayoutLimit(nextAssetIndex)) {
  23195. this.bufferedToEvent(item, nextAssetIndex);
  23196. } else if (this.schedule) {
  23197. var _this$schedule$items;
  23198. const nextItem = (_this$schedule$items = this.schedule.items) == null ? void 0 : _this$schedule$items[this.findItemIndex(item) + 1];
  23199. if (nextItem) {
  23200. this.bufferedToItem(nextItem);
  23201. }
  23202. }
  23203. }
  23204. advanceAfterAssetEnded(interstitial, index, assetListIndex) {
  23205. const nextAssetIndex = getNextAssetIndex(interstitial, assetListIndex);
  23206. if (!interstitial.isAssetPastPlayoutLimit(nextAssetIndex)) {
  23207. if (interstitial.appendInPlace) {
  23208. const assetItem = interstitial.assetList[nextAssetIndex];
  23209. if (assetItem) {
  23210. this.advanceInPlace(assetItem.timelineStart);
  23211. }
  23212. }
  23213. this.setSchedulePosition(index, nextAssetIndex);
  23214. } else if (this.schedule) {
  23215. const scheduleItems = this.schedule.items;
  23216. if (scheduleItems) {
  23217. const nextIndex = index + 1;
  23218. const scheduleLength = scheduleItems.length;
  23219. if (nextIndex >= scheduleLength) {
  23220. this.setSchedulePosition(-1);
  23221. return;
  23222. }
  23223. const resumptionTime = interstitial.resumeTime;
  23224. if (this.timelinePos < resumptionTime) {
  23225. this.log(timelineMessage("advanceAfterAssetEnded", resumptionTime));
  23226. this.timelinePos = resumptionTime;
  23227. if (interstitial.appendInPlace) {
  23228. this.advanceInPlace(resumptionTime);
  23229. }
  23230. this.checkBuffer(this.bufferedPos < resumptionTime);
  23231. }
  23232. this.setSchedulePosition(nextIndex);
  23233. }
  23234. }
  23235. }
  23236. setScheduleToAssetAtTime(time, playingAsset) {
  23237. const schedule = this.schedule;
  23238. if (!schedule) {
  23239. return;
  23240. }
  23241. const parentIdentifier = playingAsset.parentIdentifier;
  23242. const interstitial = schedule.getEvent(parentIdentifier);
  23243. if (interstitial) {
  23244. const itemIndex = schedule.findEventIndex(parentIdentifier);
  23245. const assetListIndex = schedule.findAssetIndex(interstitial, time);
  23246. this.advanceAfterAssetEnded(interstitial, itemIndex, assetListIndex - 1);
  23247. }
  23248. }
  23249. setSchedulePosition(index, assetListIndex) {
  23250. var _this$schedule2;
  23251. const scheduleItems = (_this$schedule2 = this.schedule) == null ? void 0 : _this$schedule2.items;
  23252. if (!scheduleItems || this.playbackDisabled) {
  23253. return;
  23254. }
  23255. const scheduledItem = index >= 0 ? scheduleItems[index] : null;
  23256. this.log(`setSchedulePosition ${index}, ${assetListIndex} (${scheduledItem ? segmentToString(scheduledItem) : scheduledItem}) pos: ${this.timelinePos}`);
  23257. const currentItem = this.waitingItem || this.playingItem;
  23258. const playingLastItem = this.playingLastItem;
  23259. if (this.isInterstitial(currentItem)) {
  23260. const interstitial = currentItem.event;
  23261. const playingAsset = this.playingAsset;
  23262. const assetId = playingAsset == null ? void 0 : playingAsset.identifier;
  23263. const player = assetId ? this.getAssetPlayer(assetId) : null;
  23264. if (player && assetId && (!this.eventItemsMatch(currentItem, scheduledItem) || assetListIndex !== void 0 && assetId !== interstitial.assetList[assetListIndex].identifier)) {
  23265. var _this$detachedData3;
  23266. const playingAssetListIndex = interstitial.findAssetIndex(playingAsset);
  23267. this.log(`INTERSTITIAL_ASSET_ENDED ${playingAssetListIndex + 1}/${interstitial.assetList.length} ${eventAssetToString(playingAsset)}`);
  23268. this.endedAsset = playingAsset;
  23269. this.playingAsset = null;
  23270. this.hls.trigger(Events.INTERSTITIAL_ASSET_ENDED, {
  23271. asset: playingAsset,
  23272. assetListIndex: playingAssetListIndex,
  23273. event: interstitial,
  23274. schedule: scheduleItems.slice(0),
  23275. scheduleIndex: index,
  23276. player
  23277. });
  23278. if (currentItem !== this.playingItem) {
  23279. if (this.itemsMatch(currentItem, this.playingItem) && // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
  23280. !this.playingAsset) {
  23281. this.advanceAfterAssetEnded(interstitial, this.findItemIndex(this.playingItem), playingAssetListIndex);
  23282. }
  23283. return;
  23284. }
  23285. this.retreiveMediaSource(assetId, scheduledItem);
  23286. if (player.media && !((_this$detachedData3 = this.detachedData) != null && _this$detachedData3.mediaSource)) {
  23287. player.detachMedia();
  23288. }
  23289. }
  23290. if (!this.eventItemsMatch(currentItem, scheduledItem)) {
  23291. this.endedItem = currentItem;
  23292. this.playingItem = null;
  23293. this.log(`INTERSTITIAL_ENDED ${interstitial} ${segmentToString(currentItem)}`);
  23294. interstitial.hasPlayed = true;
  23295. this.hls.trigger(Events.INTERSTITIAL_ENDED, {
  23296. event: interstitial,
  23297. schedule: scheduleItems.slice(0),
  23298. scheduleIndex: index
  23299. });
  23300. if (interstitial.cue.once) {
  23301. var _this$schedule3;
  23302. this.updateSchedule();
  23303. const updatedScheduleItems = (_this$schedule3 = this.schedule) == null ? void 0 : _this$schedule3.items;
  23304. if (scheduledItem && updatedScheduleItems) {
  23305. const updatedIndex = this.findItemIndex(scheduledItem);
  23306. this.advanceSchedule(updatedIndex, updatedScheduleItems, assetListIndex, currentItem, playingLastItem);
  23307. }
  23308. return;
  23309. }
  23310. }
  23311. }
  23312. this.advanceSchedule(index, scheduleItems, assetListIndex, currentItem, playingLastItem);
  23313. }
  23314. advanceSchedule(index, scheduleItems, assetListIndex, currentItem, playedLastItem) {
  23315. const schedule = this.schedule;
  23316. if (!schedule) {
  23317. return;
  23318. }
  23319. const scheduledItem = scheduleItems[index] || null;
  23320. const media = this.primaryMedia;
  23321. const playerQueue = this.playerQueue;
  23322. if (playerQueue.length) {
  23323. playerQueue.forEach((player) => {
  23324. const interstitial = player.interstitial;
  23325. const queuedIndex = schedule.findEventIndex(interstitial.identifier);
  23326. if (queuedIndex < index || queuedIndex > index + 1) {
  23327. this.clearInterstitial(interstitial, scheduledItem);
  23328. }
  23329. });
  23330. }
  23331. if (this.isInterstitial(scheduledItem)) {
  23332. this.timelinePos = Math.min(Math.max(this.timelinePos, scheduledItem.start), scheduledItem.end);
  23333. const interstitial = scheduledItem.event;
  23334. if (assetListIndex === void 0) {
  23335. assetListIndex = schedule.findAssetIndex(interstitial, this.timelinePos);
  23336. const assetIndexCandidate = getNextAssetIndex(interstitial, assetListIndex - 1);
  23337. if (interstitial.isAssetPastPlayoutLimit(assetIndexCandidate) || interstitial.appendInPlace && this.timelinePos === scheduledItem.end) {
  23338. this.advanceAfterAssetEnded(interstitial, index, assetListIndex);
  23339. return;
  23340. }
  23341. assetListIndex = assetIndexCandidate;
  23342. }
  23343. const waitingItem = this.waitingItem;
  23344. if (!this.assetsBuffered(scheduledItem, media)) {
  23345. this.setBufferingItem(scheduledItem);
  23346. }
  23347. let player = this.preloadAssets(interstitial, assetListIndex);
  23348. if (!this.eventItemsMatch(scheduledItem, waitingItem || currentItem)) {
  23349. this.waitingItem = scheduledItem;
  23350. this.log(`INTERSTITIAL_STARTED ${segmentToString(scheduledItem)} ${interstitial.appendInPlace ? "append in place" : ""}`);
  23351. this.hls.trigger(Events.INTERSTITIAL_STARTED, {
  23352. event: interstitial,
  23353. schedule: scheduleItems.slice(0),
  23354. scheduleIndex: index
  23355. });
  23356. }
  23357. if (!interstitial.assetListLoaded) {
  23358. this.log(`Waiting for ASSET-LIST to complete loading ${interstitial}`);
  23359. return;
  23360. }
  23361. if (interstitial.assetListLoader) {
  23362. interstitial.assetListLoader.destroy();
  23363. interstitial.assetListLoader = void 0;
  23364. }
  23365. if (!media) {
  23366. this.log(`Waiting for attachMedia to start Interstitial ${interstitial}`);
  23367. return;
  23368. }
  23369. this.waitingItem = this.endedItem = null;
  23370. this.playingItem = scheduledItem;
  23371. const assetItem = interstitial.assetList[assetListIndex];
  23372. if (!assetItem) {
  23373. this.advanceAfterAssetEnded(interstitial, index, assetListIndex || 0);
  23374. return;
  23375. }
  23376. if (!player) {
  23377. player = this.getAssetPlayer(assetItem.identifier);
  23378. }
  23379. if (player === null || player.destroyed) {
  23380. const assetListLength = interstitial.assetList.length;
  23381. this.warn(`asset ${assetListIndex + 1}/${assetListLength} player destroyed ${interstitial}`);
  23382. player = this.createAssetPlayer(interstitial, assetItem, assetListIndex);
  23383. player.loadSource();
  23384. }
  23385. if (!this.eventItemsMatch(scheduledItem, this.bufferingItem)) {
  23386. if (interstitial.appendInPlace && this.isAssetBuffered(assetItem)) {
  23387. return;
  23388. }
  23389. }
  23390. this.startAssetPlayer(player, assetListIndex, scheduleItems, index, media);
  23391. if (this.shouldPlay) {
  23392. playWithCatch(player.media);
  23393. }
  23394. } else if (scheduledItem) {
  23395. this.resumePrimary(scheduledItem, index, currentItem);
  23396. if (this.shouldPlay) {
  23397. playWithCatch(this.hls.media);
  23398. }
  23399. } else if (playedLastItem && this.isInterstitial(currentItem)) {
  23400. this.endedItem = null;
  23401. this.playingItem = currentItem;
  23402. if (!currentItem.event.appendInPlace) {
  23403. this.attachPrimary(schedule.durations.primary, null);
  23404. }
  23405. }
  23406. }
  23407. get playbackDisabled() {
  23408. return this.hls.config.enableInterstitialPlayback === false;
  23409. }
  23410. get primaryDetails() {
  23411. var _this$mediaSelection;
  23412. return (_this$mediaSelection = this.mediaSelection) == null ? void 0 : _this$mediaSelection.main.details;
  23413. }
  23414. get primaryLive() {
  23415. var _this$primaryDetails;
  23416. return !!((_this$primaryDetails = this.primaryDetails) != null && _this$primaryDetails.live);
  23417. }
  23418. resumePrimary(scheduledItem, index, fromItem) {
  23419. var _this$detachedData4, _this$schedule4;
  23420. this.playingItem = scheduledItem;
  23421. this.playingAsset = this.endedAsset = null;
  23422. this.waitingItem = this.endedItem = null;
  23423. this.bufferedToItem(scheduledItem);
  23424. this.log(`resuming ${segmentToString(scheduledItem)}`);
  23425. if (!((_this$detachedData4 = this.detachedData) != null && _this$detachedData4.mediaSource)) {
  23426. let timelinePos = this.timelinePos;
  23427. if (timelinePos < scheduledItem.start || timelinePos >= scheduledItem.end) {
  23428. timelinePos = this.getPrimaryResumption(scheduledItem, index);
  23429. this.log(timelineMessage("resumePrimary", timelinePos));
  23430. this.timelinePos = timelinePos;
  23431. }
  23432. this.attachPrimary(timelinePos, scheduledItem);
  23433. }
  23434. if (!fromItem) {
  23435. return;
  23436. }
  23437. const scheduleItems = (_this$schedule4 = this.schedule) == null ? void 0 : _this$schedule4.items;
  23438. if (!scheduleItems) {
  23439. return;
  23440. }
  23441. this.log(`INTERSTITIALS_PRIMARY_RESUMED ${segmentToString(scheduledItem)}`);
  23442. this.hls.trigger(Events.INTERSTITIALS_PRIMARY_RESUMED, {
  23443. schedule: scheduleItems.slice(0),
  23444. scheduleIndex: index
  23445. });
  23446. this.checkBuffer();
  23447. }
  23448. getPrimaryResumption(scheduledItem, index) {
  23449. const itemStart = scheduledItem.start;
  23450. if (this.primaryLive) {
  23451. const details = this.primaryDetails;
  23452. if (index === 0) {
  23453. return this.hls.startPosition;
  23454. } else if (details && (itemStart < details.fragmentStart || itemStart > details.edge)) {
  23455. return this.hls.liveSyncPosition || -1;
  23456. }
  23457. }
  23458. return itemStart;
  23459. }
  23460. isAssetBuffered(asset) {
  23461. const player = this.getAssetPlayer(asset.identifier);
  23462. if (player != null && player.hls) {
  23463. return player.hls.bufferedToEnd;
  23464. }
  23465. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);
  23466. return bufferInfo.end + 1 >= asset.timelineStart + (asset.duration || 0);
  23467. }
  23468. attachPrimary(timelinePos, item, skipSeekToStartPosition) {
  23469. if (item) {
  23470. this.setBufferingItem(item);
  23471. } else {
  23472. this.bufferingItem = this.playingItem;
  23473. }
  23474. this.bufferingAsset = null;
  23475. const media = this.primaryMedia;
  23476. if (!media) {
  23477. return;
  23478. }
  23479. const hls = this.hls;
  23480. if (hls.media) {
  23481. this.checkBuffer();
  23482. } else {
  23483. this.transferMediaTo(hls, media);
  23484. if (skipSeekToStartPosition) {
  23485. this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);
  23486. }
  23487. }
  23488. if (!skipSeekToStartPosition) {
  23489. this.log(timelineMessage("attachPrimary", timelinePos));
  23490. this.timelinePos = timelinePos;
  23491. this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);
  23492. }
  23493. }
  23494. startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition) {
  23495. var _hls$mainForwardBuffe;
  23496. const hls = this.hls;
  23497. if (!hls.loadingEnabled || !hls.media || Math.abs((((_hls$mainForwardBuffe = hls.mainForwardBufferInfo) == null ? void 0 : _hls$mainForwardBuffe.start) || hls.media.currentTime) - timelinePos) > 0.5) {
  23498. hls.startLoad(timelinePos, skipSeekToStartPosition);
  23499. } else if (!hls.bufferingEnabled) {
  23500. hls.resumeBuffering();
  23501. }
  23502. }
  23503. // HLS.js event callbacks
  23504. onManifestLoading() {
  23505. var _this$schedule5;
  23506. this.stopLoad();
  23507. (_this$schedule5 = this.schedule) == null || _this$schedule5.reset();
  23508. this.emptyPlayerQueue();
  23509. this.clearScheduleState();
  23510. this.shouldPlay = false;
  23511. this.bufferedPos = this.timelinePos = -1;
  23512. this.mediaSelection = this.altSelection = this.manager = this.requiredTracks = null;
  23513. this.hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  23514. this.hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  23515. }
  23516. onLevelUpdated(event, data) {
  23517. if (data.level === -1 || !this.schedule) {
  23518. return;
  23519. }
  23520. const main = this.hls.levels[data.level];
  23521. if (!main.details) {
  23522. return;
  23523. }
  23524. const currentSelection = _objectSpread2(_objectSpread2({}, this.mediaSelection || this.altSelection), {}, {
  23525. main
  23526. });
  23527. this.mediaSelection = currentSelection;
  23528. this.schedule.parseInterstitialDateRanges(currentSelection, this.hls.config.interstitialAppendInPlace);
  23529. if (!this.effectivePlayingItem && this.schedule.items) {
  23530. this.checkStart();
  23531. }
  23532. }
  23533. onAudioTrackUpdated(event, data) {
  23534. const audio = this.hls.audioTracks[data.id];
  23535. const previousSelection = this.mediaSelection;
  23536. if (!previousSelection) {
  23537. this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {
  23538. audio
  23539. });
  23540. return;
  23541. }
  23542. const currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {
  23543. audio
  23544. });
  23545. this.mediaSelection = currentSelection;
  23546. }
  23547. onSubtitleTrackUpdated(event, data) {
  23548. const subtitles = this.hls.subtitleTracks[data.id];
  23549. const previousSelection = this.mediaSelection;
  23550. if (!previousSelection) {
  23551. this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {
  23552. subtitles
  23553. });
  23554. return;
  23555. }
  23556. const currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {
  23557. subtitles
  23558. });
  23559. this.mediaSelection = currentSelection;
  23560. }
  23561. onAudioTrackSwitching(event, data) {
  23562. const audioOption = getBasicSelectionOption(data);
  23563. this.playerQueue.forEach(({
  23564. hls
  23565. }) => hls && (hls.setAudioOption(data) || hls.setAudioOption(audioOption)));
  23566. }
  23567. onSubtitleTrackSwitch(event, data) {
  23568. const subtitleOption = getBasicSelectionOption(data);
  23569. this.playerQueue.forEach(({
  23570. hls
  23571. }) => hls && (hls.setSubtitleOption(data) || data.id !== -1 && hls.setSubtitleOption(subtitleOption)));
  23572. }
  23573. onBufferCodecs(event, data) {
  23574. const requiredTracks = data.tracks;
  23575. if (requiredTracks) {
  23576. this.requiredTracks = requiredTracks;
  23577. }
  23578. }
  23579. onBufferAppended(event, data) {
  23580. this.checkBuffer();
  23581. }
  23582. onBufferFlushed(event, data) {
  23583. const playingItem = this.playingItem;
  23584. if (playingItem && !this.itemsMatch(playingItem, this.bufferingItem) && !this.isInterstitial(playingItem)) {
  23585. const timelinePos = this.timelinePos;
  23586. this.bufferedPos = timelinePos;
  23587. this.checkBuffer();
  23588. }
  23589. }
  23590. onBufferedToEnd(event) {
  23591. if (!this.schedule) {
  23592. return;
  23593. }
  23594. const interstitialEvents = this.schedule.events;
  23595. if (this.bufferedPos < Number.MAX_VALUE && interstitialEvents) {
  23596. for (let i = 0; i < interstitialEvents.length; i++) {
  23597. const interstitial = interstitialEvents[i];
  23598. if (interstitial.cue.post) {
  23599. var _this$schedule$items2;
  23600. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  23601. const item = (_this$schedule$items2 = this.schedule.items) == null ? void 0 : _this$schedule$items2[scheduleIndex];
  23602. if (this.isInterstitial(item) && this.eventItemsMatch(item, this.bufferingItem)) {
  23603. this.bufferedToItem(item, 0);
  23604. }
  23605. break;
  23606. }
  23607. }
  23608. this.bufferedPos = Number.MAX_VALUE;
  23609. }
  23610. }
  23611. onMediaEnded(event) {
  23612. const playingItem = this.playingItem;
  23613. if (!this.playingLastItem && playingItem) {
  23614. const playingIndex = this.findItemIndex(playingItem);
  23615. this.setSchedulePosition(playingIndex + 1);
  23616. } else {
  23617. this.shouldPlay = false;
  23618. }
  23619. }
  23620. updateItem(previousItem, time) {
  23621. var _this$schedule6;
  23622. const items = (_this$schedule6 = this.schedule) == null ? void 0 : _this$schedule6.items;
  23623. if (previousItem && items) {
  23624. const index = this.findItemIndex(previousItem, time);
  23625. return items[index] || null;
  23626. }
  23627. return null;
  23628. }
  23629. trimInPlace(updatedItem, itemBeforeUpdate) {
  23630. if (this.isInterstitial(updatedItem) && updatedItem.event.appendInPlace && itemBeforeUpdate.end - updatedItem.end > 0.25) {
  23631. updatedItem.event.assetList.forEach((asset, index) => {
  23632. if (updatedItem.event.isAssetPastPlayoutLimit(index)) {
  23633. this.clearAssetPlayer(asset.identifier, null);
  23634. }
  23635. });
  23636. const flushStart = updatedItem.end + 0.25;
  23637. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, flushStart, 0);
  23638. if (bufferInfo.end > flushStart || (bufferInfo.nextStart || 0) > flushStart) {
  23639. this.log(`trim buffered interstitial ${segmentToString(updatedItem)} (was ${segmentToString(itemBeforeUpdate)})`);
  23640. const skipSeekToStartPosition = true;
  23641. this.attachPrimary(flushStart, null, skipSeekToStartPosition);
  23642. this.flushFrontBuffer(flushStart);
  23643. }
  23644. }
  23645. }
  23646. itemsMatch(a, b) {
  23647. return !!b && (a === b || a.event && b.event && this.eventItemsMatch(a, b) || !a.event && !b.event && this.findItemIndex(a) === this.findItemIndex(b));
  23648. }
  23649. eventItemsMatch(a, b) {
  23650. var _b$event;
  23651. return !!b && (a === b || a.event.identifier === ((_b$event = b.event) == null ? void 0 : _b$event.identifier));
  23652. }
  23653. findItemIndex(item, time) {
  23654. return item && this.schedule ? this.schedule.findItemIndex(item, time) : -1;
  23655. }
  23656. updateSchedule(forceUpdate = false) {
  23657. var _this$schedule7;
  23658. const mediaSelection = this.mediaSelection;
  23659. if (!mediaSelection) {
  23660. return;
  23661. }
  23662. (_this$schedule7 = this.schedule) == null || _this$schedule7.updateSchedule(mediaSelection, [], forceUpdate);
  23663. }
  23664. // Schedule buffer control
  23665. checkBuffer(starved) {
  23666. var _this$schedule8;
  23667. const items = (_this$schedule8 = this.schedule) == null ? void 0 : _this$schedule8.items;
  23668. if (!items) {
  23669. return;
  23670. }
  23671. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);
  23672. if (starved) {
  23673. this.bufferedPos = this.timelinePos;
  23674. }
  23675. starved || (starved = bufferInfo.len < 1);
  23676. this.updateBufferedPos(bufferInfo.end, items, starved);
  23677. }
  23678. updateBufferedPos(bufferEnd, items, bufferIsEmpty) {
  23679. const schedule = this.schedule;
  23680. const bufferingItem = this.bufferingItem;
  23681. if (this.bufferedPos > bufferEnd || !schedule) {
  23682. return;
  23683. }
  23684. if (items.length === 1 && this.itemsMatch(items[0], bufferingItem)) {
  23685. this.bufferedPos = bufferEnd;
  23686. return;
  23687. }
  23688. const playingItem = this.playingItem;
  23689. const playingIndex = this.findItemIndex(playingItem);
  23690. let bufferEndIndex = schedule.findItemIndexAtTime(bufferEnd);
  23691. if (this.bufferedPos < bufferEnd) {
  23692. var _nextItemToBuffer$eve;
  23693. const bufferingIndex = this.findItemIndex(bufferingItem);
  23694. const nextToBufferIndex = Math.min(bufferingIndex + 1, items.length - 1);
  23695. const nextItemToBuffer = items[nextToBufferIndex];
  23696. if (bufferEndIndex === -1 && bufferingItem && bufferEnd >= bufferingItem.end || (_nextItemToBuffer$eve = nextItemToBuffer.event) != null && _nextItemToBuffer$eve.appendInPlace && bufferEnd + 0.01 >= nextItemToBuffer.start) {
  23697. bufferEndIndex = nextToBufferIndex;
  23698. }
  23699. if (this.isInterstitial(bufferingItem)) {
  23700. const interstitial = bufferingItem.event;
  23701. if (nextToBufferIndex - playingIndex > 1 && interstitial.appendInPlace === false) {
  23702. return;
  23703. }
  23704. if (interstitial.assetList.length === 0 && interstitial.assetListLoader) {
  23705. return;
  23706. }
  23707. }
  23708. this.bufferedPos = bufferEnd;
  23709. if (bufferEndIndex > bufferingIndex && bufferEndIndex > playingIndex) {
  23710. this.bufferedToItem(nextItemToBuffer);
  23711. } else {
  23712. const details = this.primaryDetails;
  23713. if (this.primaryLive && details && bufferEnd > details.edge - details.targetduration && nextItemToBuffer.start < details.edge + this.hls.config.interstitialLiveLookAhead && this.isInterstitial(nextItemToBuffer)) {
  23714. this.preloadAssets(nextItemToBuffer.event, 0);
  23715. }
  23716. }
  23717. } else if (bufferIsEmpty && playingItem && !this.itemsMatch(playingItem, bufferingItem)) {
  23718. if (bufferEndIndex === playingIndex) {
  23719. this.bufferedToItem(playingItem);
  23720. } else if (bufferEndIndex === playingIndex + 1) {
  23721. this.bufferedToItem(items[bufferEndIndex]);
  23722. }
  23723. }
  23724. }
  23725. assetsBuffered(item, media) {
  23726. const assetList = item.event.assetList;
  23727. if (assetList.length === 0) {
  23728. return false;
  23729. }
  23730. return !item.event.assetList.some((asset) => {
  23731. const player = this.getAssetPlayer(asset.identifier);
  23732. return !(player != null && player.bufferedInPlaceToEnd(media));
  23733. });
  23734. }
  23735. setBufferingItem(item) {
  23736. const bufferingLast = this.bufferingItem;
  23737. const schedule = this.schedule;
  23738. if (!this.itemsMatch(item, bufferingLast) && schedule) {
  23739. const {
  23740. items,
  23741. events
  23742. } = schedule;
  23743. if (!items || !events) {
  23744. return bufferingLast;
  23745. }
  23746. const isInterstitial = this.isInterstitial(item);
  23747. const bufferingPlayer = this.getBufferingPlayer();
  23748. this.bufferingItem = item;
  23749. this.bufferedPos = Math.max(item.start, Math.min(item.end, this.timelinePos));
  23750. const timeRemaining = bufferingPlayer ? bufferingPlayer.remaining : bufferingLast ? bufferingLast.end - this.timelinePos : 0;
  23751. this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${segmentToString(item)}` + (bufferingLast ? ` (${timeRemaining.toFixed(2)} remaining)` : ""));
  23752. if (!this.playbackDisabled) {
  23753. if (isInterstitial) {
  23754. const bufferIndex = schedule.findAssetIndex(item.event, this.bufferedPos);
  23755. item.event.assetList.forEach((asset, i) => {
  23756. const player = this.getAssetPlayer(asset.identifier);
  23757. if (player) {
  23758. if (i === bufferIndex) {
  23759. player.loadSource();
  23760. }
  23761. player.resumeBuffering();
  23762. }
  23763. });
  23764. } else {
  23765. this.hls.resumeBuffering();
  23766. this.playerQueue.forEach((player) => player.pauseBuffering());
  23767. }
  23768. }
  23769. this.hls.trigger(Events.INTERSTITIALS_BUFFERED_TO_BOUNDARY, {
  23770. events: events.slice(0),
  23771. schedule: items.slice(0),
  23772. bufferingIndex: this.findItemIndex(item),
  23773. playingIndex: this.findItemIndex(this.playingItem)
  23774. });
  23775. } else if (this.bufferingItem !== item) {
  23776. this.bufferingItem = item;
  23777. }
  23778. return bufferingLast;
  23779. }
  23780. bufferedToItem(item, assetListIndex = 0) {
  23781. const bufferingLast = this.setBufferingItem(item);
  23782. if (this.playbackDisabled) {
  23783. return;
  23784. }
  23785. if (this.isInterstitial(item)) {
  23786. this.bufferedToEvent(item, assetListIndex);
  23787. } else if (bufferingLast !== null) {
  23788. this.bufferingAsset = null;
  23789. const detachedData = this.detachedData;
  23790. if (detachedData) {
  23791. if (detachedData.mediaSource) {
  23792. const skipSeekToStartPosition = true;
  23793. this.attachPrimary(item.start, item, skipSeekToStartPosition);
  23794. } else {
  23795. this.preloadPrimary(item);
  23796. }
  23797. } else {
  23798. this.preloadPrimary(item);
  23799. }
  23800. }
  23801. }
  23802. preloadPrimary(item) {
  23803. const index = this.findItemIndex(item);
  23804. const timelinePos = this.getPrimaryResumption(item, index);
  23805. this.startLoadingPrimaryAt(timelinePos);
  23806. }
  23807. bufferedToEvent(item, assetListIndex) {
  23808. const interstitial = item.event;
  23809. const neverLoaded = interstitial.assetList.length === 0 && !interstitial.assetListLoader;
  23810. const playOnce = interstitial.cue.once;
  23811. if (neverLoaded || !playOnce) {
  23812. const player = this.preloadAssets(interstitial, assetListIndex);
  23813. if (player != null && player.interstitial.appendInPlace) {
  23814. const media = this.primaryMedia;
  23815. if (media) {
  23816. this.bufferAssetPlayer(player, media);
  23817. }
  23818. }
  23819. }
  23820. }
  23821. preloadAssets(interstitial, assetListIndex) {
  23822. const uri = interstitial.assetUrl;
  23823. const assetListLength = interstitial.assetList.length;
  23824. const neverLoaded = assetListLength === 0 && !interstitial.assetListLoader;
  23825. const playOnce = interstitial.cue.once;
  23826. if (neverLoaded) {
  23827. const timelineStart = interstitial.timelineStart;
  23828. if (interstitial.appendInPlace) {
  23829. var _playingItem$nextEven;
  23830. const playingItem = this.playingItem;
  23831. if (!this.isInterstitial(playingItem) && (playingItem == null || (_playingItem$nextEven = playingItem.nextEvent) == null ? void 0 : _playingItem$nextEven.identifier) === interstitial.identifier) {
  23832. this.flushFrontBuffer(timelineStart + 0.25);
  23833. }
  23834. }
  23835. let hlsStartOffset;
  23836. let liveStartPosition = 0;
  23837. if (!this.playingItem && this.primaryLive) {
  23838. liveStartPosition = this.hls.startPosition;
  23839. if (liveStartPosition === -1) {
  23840. liveStartPosition = this.hls.liveSyncPosition || 0;
  23841. }
  23842. }
  23843. if (liveStartPosition && !(interstitial.cue.pre || interstitial.cue.post)) {
  23844. const startOffset = liveStartPosition - timelineStart;
  23845. if (startOffset > 0) {
  23846. hlsStartOffset = Math.round(startOffset * 1e3) / 1e3;
  23847. }
  23848. }
  23849. this.log(`Load interstitial asset ${assetListIndex + 1}/${uri ? 1 : assetListLength} ${interstitial}${hlsStartOffset ? ` live-start: ${liveStartPosition} start-offset: ${hlsStartOffset}` : ""}`);
  23850. if (uri) {
  23851. return this.createAsset(interstitial, 0, 0, timelineStart, interstitial.duration, uri);
  23852. }
  23853. const assetListLoader = this.assetListLoader.loadAssetList(interstitial, hlsStartOffset);
  23854. if (assetListLoader) {
  23855. interstitial.assetListLoader = assetListLoader;
  23856. }
  23857. } else if (!playOnce && assetListLength) {
  23858. for (let i = assetListIndex; i < assetListLength; i++) {
  23859. const _asset = interstitial.assetList[i];
  23860. const playerIndex = this.getAssetPlayerQueueIndex(_asset.identifier);
  23861. if ((playerIndex === -1 || this.playerQueue[playerIndex].destroyed) && !_asset.error) {
  23862. this.createAssetPlayer(interstitial, _asset, i);
  23863. }
  23864. }
  23865. const asset = interstitial.assetList[assetListIndex];
  23866. if (asset) {
  23867. const player = this.getAssetPlayer(asset.identifier);
  23868. if (player) {
  23869. player.loadSource();
  23870. }
  23871. return player;
  23872. }
  23873. }
  23874. return null;
  23875. }
  23876. flushFrontBuffer(startOffset) {
  23877. const requiredTracks = this.requiredTracks;
  23878. if (!requiredTracks) {
  23879. return;
  23880. }
  23881. this.log(`Removing front buffer starting at ${startOffset}`);
  23882. const sourceBufferNames = Object.keys(requiredTracks);
  23883. sourceBufferNames.forEach((type) => {
  23884. this.hls.trigger(Events.BUFFER_FLUSHING, {
  23885. startOffset,
  23886. endOffset: Infinity,
  23887. type
  23888. });
  23889. });
  23890. }
  23891. // Interstitial Asset Player control
  23892. getAssetPlayerQueueIndex(assetId) {
  23893. const playerQueue = this.playerQueue;
  23894. for (let i = 0; i < playerQueue.length; i++) {
  23895. if (assetId === playerQueue[i].assetId) {
  23896. return i;
  23897. }
  23898. }
  23899. return -1;
  23900. }
  23901. getAssetPlayer(assetId) {
  23902. const index = this.getAssetPlayerQueueIndex(assetId);
  23903. return this.playerQueue[index] || null;
  23904. }
  23905. getBufferingPlayer() {
  23906. const {
  23907. playerQueue,
  23908. primaryMedia
  23909. } = this;
  23910. if (primaryMedia) {
  23911. for (let i = 0; i < playerQueue.length; i++) {
  23912. if (playerQueue[i].media === primaryMedia) {
  23913. return playerQueue[i];
  23914. }
  23915. }
  23916. }
  23917. return null;
  23918. }
  23919. createAsset(interstitial, assetListIndex, startOffset, timelineStart, duration, uri) {
  23920. const assetItem = {
  23921. parentIdentifier: interstitial.identifier,
  23922. identifier: generateAssetIdentifier(interstitial, uri, assetListIndex),
  23923. duration,
  23924. startOffset,
  23925. timelineStart,
  23926. uri
  23927. };
  23928. return this.createAssetPlayer(interstitial, assetItem, assetListIndex);
  23929. }
  23930. createAssetPlayer(interstitial, assetItem, assetListIndex) {
  23931. const primary = this.hls;
  23932. const userConfig = primary.userConfig;
  23933. let videoPreference = userConfig.videoPreference;
  23934. const currentLevel = primary.loadLevelObj || primary.levels[primary.currentLevel];
  23935. if (videoPreference || currentLevel) {
  23936. videoPreference = _extends({}, videoPreference);
  23937. if (currentLevel.videoCodec) {
  23938. videoPreference.videoCodec = currentLevel.videoCodec;
  23939. }
  23940. if (currentLevel.videoRange) {
  23941. videoPreference.allowedVideoRanges = [currentLevel.videoRange];
  23942. }
  23943. }
  23944. const selectedAudio = primary.audioTracks[primary.audioTrack];
  23945. const selectedSubtitle = primary.subtitleTracks[primary.subtitleTrack];
  23946. let startPosition = 0;
  23947. if (this.primaryLive || interstitial.appendInPlace) {
  23948. const timePastStart = this.timelinePos - assetItem.timelineStart;
  23949. if (timePastStart > 1) {
  23950. const duration = assetItem.duration;
  23951. if (duration && timePastStart < duration) {
  23952. startPosition = timePastStart;
  23953. }
  23954. }
  23955. }
  23956. const assetId = assetItem.identifier;
  23957. const playerConfig = _objectSpread2(_objectSpread2({}, userConfig), {}, {
  23958. maxMaxBufferLength: Math.min(180, primary.config.maxMaxBufferLength),
  23959. autoStartLoad: true,
  23960. startFragPrefetch: true,
  23961. primarySessionId: primary.sessionId,
  23962. assetPlayerId: assetId,
  23963. abrEwmaDefaultEstimate: primary.bandwidthEstimate,
  23964. interstitialsController: void 0,
  23965. startPosition,
  23966. liveDurationInfinity: false,
  23967. testBandwidth: false,
  23968. videoPreference,
  23969. audioPreference: selectedAudio || userConfig.audioPreference,
  23970. subtitlePreference: selectedSubtitle || userConfig.subtitlePreference
  23971. });
  23972. if (interstitial.appendInPlace) {
  23973. interstitial.appendInPlaceStarted = true;
  23974. if (assetItem.timelineStart) {
  23975. playerConfig.timelineOffset = assetItem.timelineStart;
  23976. }
  23977. }
  23978. const cmcd = playerConfig.cmcd;
  23979. if (cmcd != null && cmcd.sessionId && cmcd.contentId) {
  23980. playerConfig.cmcd = _extends({}, cmcd, {
  23981. contentId: hash(assetItem.uri)
  23982. });
  23983. }
  23984. if (this.getAssetPlayer(assetId)) {
  23985. this.warn(`Duplicate date range identifier ${interstitial} and asset ${assetId}`);
  23986. }
  23987. const player = new HlsAssetPlayer(this.HlsPlayerClass, playerConfig, interstitial, assetItem);
  23988. this.playerQueue.push(player);
  23989. interstitial.assetList[assetListIndex] = assetItem;
  23990. let initialDuration = true;
  23991. const updateAssetPlayerDetails = (details) => {
  23992. if (details.live) {
  23993. var _this$schedule9;
  23994. const error = new Error(`Interstitials MUST be VOD assets ${interstitial}`);
  23995. const errorData = {
  23996. fatal: true,
  23997. type: ErrorTypes.OTHER_ERROR,
  23998. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  23999. error
  24000. };
  24001. const scheduleIndex = ((_this$schedule9 = this.schedule) == null ? void 0 : _this$schedule9.findEventIndex(interstitial.identifier)) || -1;
  24002. this.handleAssetItemError(errorData, interstitial, scheduleIndex, assetListIndex, error.message);
  24003. return;
  24004. }
  24005. const duration = details.edge - details.fragmentStart;
  24006. const currentAssetDuration = assetItem.duration;
  24007. if (initialDuration || currentAssetDuration === null || duration > currentAssetDuration) {
  24008. initialDuration = false;
  24009. this.log(`Interstitial asset "${assetId}" duration change ${currentAssetDuration} > ${duration}`);
  24010. assetItem.duration = duration;
  24011. this.updateSchedule();
  24012. }
  24013. };
  24014. player.on(Events.LEVEL_UPDATED, (event, {
  24015. details
  24016. }) => updateAssetPlayerDetails(details));
  24017. player.on(Events.LEVEL_PTS_UPDATED, (event, {
  24018. details
  24019. }) => updateAssetPlayerDetails(details));
  24020. player.on(Events.EVENT_CUE_ENTER, () => this.onInterstitialCueEnter());
  24021. const onBufferCodecs = (event, data) => {
  24022. const inQueuPlayer = this.getAssetPlayer(assetId);
  24023. if (inQueuPlayer && data.tracks) {
  24024. inQueuPlayer.off(Events.BUFFER_CODECS, onBufferCodecs);
  24025. inQueuPlayer.tracks = data.tracks;
  24026. const media = this.primaryMedia;
  24027. if (this.bufferingAsset === inQueuPlayer.assetItem && media && !inQueuPlayer.media) {
  24028. this.bufferAssetPlayer(inQueuPlayer, media);
  24029. }
  24030. }
  24031. };
  24032. player.on(Events.BUFFER_CODECS, onBufferCodecs);
  24033. const bufferedToEnd = () => {
  24034. var _this$schedule$items3;
  24035. const inQueuPlayer = this.getAssetPlayer(assetId);
  24036. this.log(`buffered to end of asset ${inQueuPlayer}`);
  24037. if (!inQueuPlayer || !this.schedule) {
  24038. return;
  24039. }
  24040. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  24041. const item = (_this$schedule$items3 = this.schedule.items) == null ? void 0 : _this$schedule$items3[scheduleIndex];
  24042. if (this.isInterstitial(item)) {
  24043. this.advanceAssetBuffering(item, assetItem);
  24044. }
  24045. };
  24046. player.on(Events.BUFFERED_TO_END, bufferedToEnd);
  24047. const endedWithAssetIndex = (assetIndex) => {
  24048. return () => {
  24049. const inQueuPlayer = this.getAssetPlayer(assetId);
  24050. if (!inQueuPlayer || !this.schedule) {
  24051. return;
  24052. }
  24053. this.shouldPlay = true;
  24054. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  24055. this.advanceAfterAssetEnded(interstitial, scheduleIndex, assetIndex);
  24056. };
  24057. };
  24058. player.once(Events.MEDIA_ENDED, endedWithAssetIndex(assetListIndex));
  24059. player.once(Events.PLAYOUT_LIMIT_REACHED, endedWithAssetIndex(Infinity));
  24060. player.on(Events.ERROR, (event, data) => {
  24061. if (!this.schedule) {
  24062. return;
  24063. }
  24064. const inQueuPlayer = this.getAssetPlayer(assetId);
  24065. if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {
  24066. if (inQueuPlayer != null && inQueuPlayer.appendInPlace) {
  24067. this.handleInPlaceStall(interstitial);
  24068. return;
  24069. }
  24070. this.onTimeupdate();
  24071. this.checkBuffer(true);
  24072. return;
  24073. }
  24074. this.handleAssetItemError(data, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, `Asset player error ${data.error} ${interstitial}`);
  24075. });
  24076. player.on(Events.DESTROYING, () => {
  24077. const inQueuPlayer = this.getAssetPlayer(assetId);
  24078. if (!inQueuPlayer || !this.schedule) {
  24079. return;
  24080. }
  24081. const error = new Error(`Asset player destroyed unexpectedly ${assetId}`);
  24082. const errorData = {
  24083. fatal: true,
  24084. type: ErrorTypes.OTHER_ERROR,
  24085. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  24086. error
  24087. };
  24088. this.handleAssetItemError(errorData, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, error.message);
  24089. });
  24090. this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${eventAssetToString(assetItem)}`);
  24091. this.hls.trigger(Events.INTERSTITIAL_ASSET_PLAYER_CREATED, {
  24092. asset: assetItem,
  24093. assetListIndex,
  24094. event: interstitial,
  24095. player
  24096. });
  24097. return player;
  24098. }
  24099. clearInterstitial(interstitial, toSegment) {
  24100. interstitial.assetList.forEach((asset) => {
  24101. this.clearAssetPlayer(asset.identifier, toSegment);
  24102. });
  24103. interstitial.reset();
  24104. }
  24105. resetAssetPlayer(assetId) {
  24106. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  24107. if (playerIndex !== -1) {
  24108. this.log(`reset asset player "${assetId}" after error`);
  24109. const player = this.playerQueue[playerIndex];
  24110. this.transferMediaFromPlayer(player, null);
  24111. player.resetDetails();
  24112. }
  24113. }
  24114. clearAssetPlayer(assetId, toSegment) {
  24115. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  24116. if (playerIndex !== -1) {
  24117. const player = this.playerQueue[playerIndex];
  24118. this.log(`clear ${player} toSegment: ${toSegment ? segmentToString(toSegment) : toSegment}`);
  24119. this.transferMediaFromPlayer(player, toSegment);
  24120. this.playerQueue.splice(playerIndex, 1);
  24121. player.destroy();
  24122. }
  24123. }
  24124. emptyPlayerQueue() {
  24125. let player;
  24126. while (player = this.playerQueue.pop()) {
  24127. player.destroy();
  24128. }
  24129. this.playerQueue = [];
  24130. }
  24131. startAssetPlayer(player, assetListIndex, scheduleItems, scheduleIndex, media) {
  24132. const {
  24133. interstitial,
  24134. assetItem,
  24135. assetId
  24136. } = player;
  24137. const assetListLength = interstitial.assetList.length;
  24138. const playingAsset = this.playingAsset;
  24139. this.endedAsset = null;
  24140. this.playingAsset = assetItem;
  24141. if (!playingAsset || playingAsset.identifier !== assetId) {
  24142. if (playingAsset) {
  24143. this.clearAssetPlayer(playingAsset.identifier, scheduleItems[scheduleIndex]);
  24144. delete playingAsset.error;
  24145. }
  24146. this.log(`INTERSTITIAL_ASSET_STARTED ${assetListIndex + 1}/${assetListLength} ${eventAssetToString(assetItem)}`);
  24147. this.hls.trigger(Events.INTERSTITIAL_ASSET_STARTED, {
  24148. asset: assetItem,
  24149. assetListIndex,
  24150. event: interstitial,
  24151. schedule: scheduleItems.slice(0),
  24152. scheduleIndex,
  24153. player
  24154. });
  24155. }
  24156. this.bufferAssetPlayer(player, media);
  24157. }
  24158. bufferAssetPlayer(player, media) {
  24159. var _this$schedule$items4, _this$detachedData5;
  24160. if (!this.schedule) {
  24161. return;
  24162. }
  24163. const {
  24164. interstitial,
  24165. assetItem
  24166. } = player;
  24167. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  24168. const item = (_this$schedule$items4 = this.schedule.items) == null ? void 0 : _this$schedule$items4[scheduleIndex];
  24169. if (!item) {
  24170. return;
  24171. }
  24172. player.loadSource();
  24173. this.setBufferingItem(item);
  24174. this.bufferingAsset = assetItem;
  24175. const bufferingPlayer = this.getBufferingPlayer();
  24176. if (bufferingPlayer === player) {
  24177. return;
  24178. }
  24179. const appendInPlaceNext = interstitial.appendInPlace;
  24180. if (appendInPlaceNext && (bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial.appendInPlace) === false) {
  24181. return;
  24182. }
  24183. const activeTracks = (bufferingPlayer == null ? void 0 : bufferingPlayer.tracks) || ((_this$detachedData5 = this.detachedData) == null ? void 0 : _this$detachedData5.tracks) || this.requiredTracks;
  24184. if (appendInPlaceNext && assetItem !== this.playingAsset) {
  24185. if (!player.tracks) {
  24186. this.log(`Waiting for track info before buffering ${player}`);
  24187. return;
  24188. }
  24189. if (activeTracks && !isCompatibleTrackChange(activeTracks, player.tracks)) {
  24190. const error = new Error(`Asset ${eventAssetToString(assetItem)} SourceBuffer tracks ('${Object.keys(player.tracks)}') are not compatible with primary content tracks ('${Object.keys(activeTracks)}')`);
  24191. const errorData = {
  24192. fatal: true,
  24193. type: ErrorTypes.OTHER_ERROR,
  24194. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  24195. error
  24196. };
  24197. const assetListIndex = interstitial.findAssetIndex(assetItem);
  24198. this.handleAssetItemError(errorData, interstitial, scheduleIndex, assetListIndex, error.message);
  24199. return;
  24200. }
  24201. }
  24202. this.transferMediaTo(player, media);
  24203. }
  24204. handleInPlaceStall(interstitial) {
  24205. const schedule = this.schedule;
  24206. const media = this.primaryMedia;
  24207. if (!schedule || !media) {
  24208. return;
  24209. }
  24210. const currentTime = media.currentTime;
  24211. const foundAssetIndex = schedule.findAssetIndex(interstitial, currentTime);
  24212. const stallingAsset = interstitial.assetList[foundAssetIndex];
  24213. if (stallingAsset) {
  24214. const player = this.getAssetPlayer(stallingAsset.identifier);
  24215. if (player) {
  24216. const assetCurrentTime = player.currentTime || currentTime - stallingAsset.timelineStart;
  24217. const distanceFromEnd = player.duration - assetCurrentTime;
  24218. this.warn(`Stalled at ${assetCurrentTime} of ${assetCurrentTime + distanceFromEnd} in ${player} ${interstitial} (media.currentTime: ${currentTime})`);
  24219. if (assetCurrentTime && (distanceFromEnd / media.playbackRate < 0.5 || player.bufferedInPlaceToEnd(media)) && player.hls) {
  24220. const scheduleIndex = schedule.findEventIndex(interstitial.identifier);
  24221. this.advanceAfterAssetEnded(interstitial, scheduleIndex, foundAssetIndex);
  24222. }
  24223. }
  24224. }
  24225. }
  24226. advanceInPlace(time) {
  24227. const media = this.primaryMedia;
  24228. if (media && media.currentTime < time) {
  24229. media.currentTime = time;
  24230. }
  24231. }
  24232. handleAssetItemError(data, interstitial, scheduleIndex, assetListIndex, errorMessage) {
  24233. if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {
  24234. return;
  24235. }
  24236. const assetItem = interstitial.assetList[assetListIndex] || null;
  24237. this.warn(`INTERSTITIAL_ASSET_ERROR ${assetItem ? eventAssetToString(assetItem) : assetItem} ${data.error}`);
  24238. if (!this.schedule) {
  24239. return;
  24240. }
  24241. const assetId = (assetItem == null ? void 0 : assetItem.identifier) || "";
  24242. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  24243. const player = this.playerQueue[playerIndex] || null;
  24244. const items = this.schedule.items;
  24245. const interstitialAssetError = _extends({}, data, {
  24246. fatal: false,
  24247. errorAction: createDoNothingErrorAction(true),
  24248. asset: assetItem,
  24249. assetListIndex,
  24250. event: interstitial,
  24251. schedule: items,
  24252. scheduleIndex,
  24253. player
  24254. });
  24255. this.hls.trigger(Events.INTERSTITIAL_ASSET_ERROR, interstitialAssetError);
  24256. if (!data.fatal) {
  24257. return;
  24258. }
  24259. const playingAsset = this.playingAsset;
  24260. const bufferingAsset = this.bufferingAsset;
  24261. const error = new Error(errorMessage);
  24262. if (assetItem) {
  24263. this.clearAssetPlayer(assetId, null);
  24264. assetItem.error = error;
  24265. }
  24266. if (!interstitial.assetList.some((asset) => !asset.error)) {
  24267. interstitial.error = error;
  24268. } else {
  24269. for (let i = assetListIndex; i < interstitial.assetList.length; i++) {
  24270. this.resetAssetPlayer(interstitial.assetList[i].identifier);
  24271. }
  24272. }
  24273. this.updateSchedule(true);
  24274. if (interstitial.error) {
  24275. this.primaryFallback(interstitial);
  24276. } else if (playingAsset && playingAsset.identifier === assetId) {
  24277. this.advanceAfterAssetEnded(interstitial, scheduleIndex, assetListIndex);
  24278. } else if (bufferingAsset && bufferingAsset.identifier === assetId && this.isInterstitial(this.bufferingItem)) {
  24279. this.advanceAssetBuffering(this.bufferingItem, bufferingAsset);
  24280. }
  24281. }
  24282. primaryFallback(interstitial) {
  24283. const flushStart = interstitial.timelineStart;
  24284. const playingItem = this.effectivePlayingItem;
  24285. if (playingItem) {
  24286. this.log(`Fallback to primary from event "${interstitial.identifier}" start: ${flushStart} pos: ${this.timelinePos} playing: ${segmentToString(playingItem)} error: ${interstitial.error}`);
  24287. let timelinePos = this.timelinePos;
  24288. if (timelinePos === -1) {
  24289. timelinePos = this.hls.startPosition;
  24290. }
  24291. const newPlayingItem = this.updateItem(playingItem, timelinePos);
  24292. if (this.itemsMatch(playingItem, newPlayingItem)) {
  24293. this.clearInterstitial(interstitial, null);
  24294. }
  24295. if (interstitial.appendInPlace) {
  24296. this.attachPrimary(flushStart, null);
  24297. this.flushFrontBuffer(flushStart);
  24298. }
  24299. if (!this.schedule) {
  24300. return;
  24301. }
  24302. const scheduleIndex = this.schedule.findItemIndexAtTime(timelinePos);
  24303. this.setSchedulePosition(scheduleIndex);
  24304. } else {
  24305. this.checkStart();
  24306. }
  24307. }
  24308. // Asset List loading
  24309. onAssetListLoaded(event, data) {
  24310. var _this$schedule0, _this$bufferingItem2;
  24311. const interstitial = data.event;
  24312. const interstitialId = interstitial.identifier;
  24313. const assets = data.assetListResponse.ASSETS;
  24314. if (!((_this$schedule0 = this.schedule) != null && _this$schedule0.hasEvent(interstitialId))) {
  24315. return;
  24316. }
  24317. const eventStart = interstitial.timelineStart;
  24318. const previousDuration = interstitial.duration;
  24319. let sumDuration = 0;
  24320. assets.forEach((asset, assetListIndex) => {
  24321. const duration = parseFloat(asset.DURATION);
  24322. this.createAsset(interstitial, assetListIndex, sumDuration, eventStart + sumDuration, duration, asset.URI);
  24323. sumDuration += duration;
  24324. });
  24325. interstitial.duration = sumDuration;
  24326. this.log(`Loaded asset-list with duration: ${sumDuration} (was: ${previousDuration}) ${interstitial}`);
  24327. const waitingItem = this.waitingItem;
  24328. const waitingForItem = (waitingItem == null ? void 0 : waitingItem.event.identifier) === interstitialId;
  24329. this.updateSchedule();
  24330. const bufferingEvent = (_this$bufferingItem2 = this.bufferingItem) == null ? void 0 : _this$bufferingItem2.event;
  24331. if (waitingForItem) {
  24332. var _this$schedule$items5;
  24333. const scheduleIndex = this.schedule.findEventIndex(interstitialId);
  24334. const item = (_this$schedule$items5 = this.schedule.items) == null ? void 0 : _this$schedule$items5[scheduleIndex];
  24335. if (item) {
  24336. if (!this.playingItem && this.timelinePos > item.end) {
  24337. const index = this.schedule.findItemIndexAtTime(this.timelinePos);
  24338. if (index !== scheduleIndex) {
  24339. interstitial.error = new Error(`Interstitial no longer within playback range ${this.timelinePos} ${interstitial}`);
  24340. this.updateSchedule(true);
  24341. this.primaryFallback(interstitial);
  24342. return;
  24343. }
  24344. }
  24345. this.setBufferingItem(item);
  24346. }
  24347. this.setSchedulePosition(scheduleIndex);
  24348. } else if ((bufferingEvent == null ? void 0 : bufferingEvent.identifier) === interstitialId) {
  24349. const assetItem = interstitial.assetList[0];
  24350. if (assetItem) {
  24351. const player = this.getAssetPlayer(assetItem.identifier);
  24352. if (bufferingEvent.appendInPlace) {
  24353. const media = this.primaryMedia;
  24354. if (player && media) {
  24355. this.bufferAssetPlayer(player, media);
  24356. }
  24357. } else if (player) {
  24358. player.loadSource();
  24359. }
  24360. }
  24361. }
  24362. }
  24363. onError(event, data) {
  24364. if (!this.schedule) {
  24365. return;
  24366. }
  24367. switch (data.details) {
  24368. case ErrorDetails.ASSET_LIST_PARSING_ERROR:
  24369. case ErrorDetails.ASSET_LIST_LOAD_ERROR:
  24370. case ErrorDetails.ASSET_LIST_LOAD_TIMEOUT: {
  24371. const interstitial = data.interstitial;
  24372. if (interstitial) {
  24373. this.updateSchedule(true);
  24374. this.primaryFallback(interstitial);
  24375. }
  24376. break;
  24377. }
  24378. case ErrorDetails.BUFFER_STALLED_ERROR: {
  24379. const stallingItem = this.endedItem || this.waitingItem || this.playingItem;
  24380. if (this.isInterstitial(stallingItem) && stallingItem.event.appendInPlace) {
  24381. this.handleInPlaceStall(stallingItem.event);
  24382. return;
  24383. }
  24384. this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`);
  24385. this.onTimeupdate();
  24386. this.checkBuffer(true);
  24387. break;
  24388. }
  24389. }
  24390. }
  24391. };
  24392. var TICK_INTERVAL$2 = 500;
  24393. var SubtitleStreamController = class extends BaseStreamController {
  24394. constructor(hls, fragmentTracker, keyLoader) {
  24395. super(hls, fragmentTracker, keyLoader, "subtitle-stream-controller", PlaylistLevelType.SUBTITLE);
  24396. this.currentTrackId = -1;
  24397. this.tracksBuffered = [];
  24398. this.mainDetails = null;
  24399. this.registerListeners();
  24400. }
  24401. onHandlerDestroying() {
  24402. this.unregisterListeners();
  24403. super.onHandlerDestroying();
  24404. this.mainDetails = null;
  24405. }
  24406. registerListeners() {
  24407. super.registerListeners();
  24408. const {
  24409. hls
  24410. } = this;
  24411. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  24412. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  24413. hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  24414. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  24415. hls.on(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  24416. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  24417. }
  24418. unregisterListeners() {
  24419. super.unregisterListeners();
  24420. const {
  24421. hls
  24422. } = this;
  24423. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  24424. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  24425. hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  24426. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  24427. hls.off(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  24428. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  24429. }
  24430. startLoad(startPosition, skipSeekToStartPosition) {
  24431. this.stopLoad();
  24432. this.state = State.IDLE;
  24433. this.setInterval(TICK_INTERVAL$2);
  24434. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  24435. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  24436. this.tick();
  24437. }
  24438. onManifestLoading() {
  24439. super.onManifestLoading();
  24440. this.mainDetails = null;
  24441. }
  24442. onMediaDetaching(event, data) {
  24443. this.tracksBuffered = [];
  24444. super.onMediaDetaching(event, data);
  24445. }
  24446. onLevelLoaded(event, data) {
  24447. this.mainDetails = data.details;
  24448. }
  24449. onSubtitleFragProcessed(event, data) {
  24450. const {
  24451. frag,
  24452. success
  24453. } = data;
  24454. if (!this.fragContextChanged(frag)) {
  24455. if (isMediaFragment(frag)) {
  24456. this.fragPrevious = frag;
  24457. }
  24458. this.state = State.IDLE;
  24459. }
  24460. if (!success) {
  24461. return;
  24462. }
  24463. const buffered = this.tracksBuffered[this.currentTrackId];
  24464. if (!buffered) {
  24465. return;
  24466. }
  24467. let timeRange;
  24468. const fragStart = frag.start;
  24469. for (let i = 0; i < buffered.length; i++) {
  24470. if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
  24471. timeRange = buffered[i];
  24472. break;
  24473. }
  24474. }
  24475. const fragEnd = frag.start + frag.duration;
  24476. if (timeRange) {
  24477. timeRange.end = fragEnd;
  24478. } else {
  24479. timeRange = {
  24480. start: fragStart,
  24481. end: fragEnd
  24482. };
  24483. buffered.push(timeRange);
  24484. }
  24485. this.fragmentTracker.fragBuffered(frag);
  24486. this.fragBufferedComplete(frag, null);
  24487. if (this.media) {
  24488. this.tick();
  24489. }
  24490. }
  24491. onBufferFlushing(event, data) {
  24492. const {
  24493. startOffset,
  24494. endOffset
  24495. } = data;
  24496. if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) {
  24497. const endOffsetSubtitles = endOffset - 1;
  24498. if (endOffsetSubtitles <= 0) {
  24499. return;
  24500. }
  24501. data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles);
  24502. this.tracksBuffered.forEach((buffered) => {
  24503. for (let i = 0; i < buffered.length; ) {
  24504. if (buffered[i].end <= endOffsetSubtitles) {
  24505. buffered.shift();
  24506. continue;
  24507. } else if (buffered[i].start < endOffsetSubtitles) {
  24508. buffered[i].start = endOffsetSubtitles;
  24509. } else {
  24510. break;
  24511. }
  24512. i++;
  24513. }
  24514. });
  24515. this.fragmentTracker.removeFragmentsInRange(startOffset, endOffsetSubtitles, PlaylistLevelType.SUBTITLE);
  24516. }
  24517. }
  24518. // If something goes wrong, proceed to next frag, if we were processing one.
  24519. onError(event, data) {
  24520. const frag = data.frag;
  24521. if ((frag == null ? void 0 : frag.type) === PlaylistLevelType.SUBTITLE) {
  24522. if (data.details === ErrorDetails.FRAG_GAP) {
  24523. this.fragmentTracker.fragBuffered(frag, true);
  24524. }
  24525. if (this.fragCurrent) {
  24526. this.fragCurrent.abortRequests();
  24527. }
  24528. if (this.state !== State.STOPPED) {
  24529. this.state = State.IDLE;
  24530. }
  24531. }
  24532. }
  24533. // Got all new subtitle levels.
  24534. onSubtitleTracksUpdated(event, {
  24535. subtitleTracks
  24536. }) {
  24537. if (this.levels && subtitleOptionsIdentical(this.levels, subtitleTracks)) {
  24538. this.levels = subtitleTracks.map((mediaPlaylist) => new Level(mediaPlaylist));
  24539. return;
  24540. }
  24541. this.tracksBuffered = [];
  24542. this.levels = subtitleTracks.map((mediaPlaylist) => {
  24543. const level = new Level(mediaPlaylist);
  24544. this.tracksBuffered[level.id] = [];
  24545. return level;
  24546. });
  24547. this.fragmentTracker.removeFragmentsInRange(0, Number.POSITIVE_INFINITY, PlaylistLevelType.SUBTITLE);
  24548. this.fragPrevious = null;
  24549. this.mediaBuffer = null;
  24550. }
  24551. onSubtitleTrackSwitch(event, data) {
  24552. var _this$levels;
  24553. this.currentTrackId = data.id;
  24554. if (!((_this$levels = this.levels) != null && _this$levels.length) || this.currentTrackId === -1) {
  24555. this.clearInterval();
  24556. return;
  24557. }
  24558. const currentTrack = this.levels[this.currentTrackId];
  24559. if (currentTrack != null && currentTrack.details) {
  24560. this.mediaBuffer = this.mediaBufferTimeRanges;
  24561. } else {
  24562. this.mediaBuffer = null;
  24563. }
  24564. if (currentTrack && this.state !== State.STOPPED) {
  24565. this.setInterval(TICK_INTERVAL$2);
  24566. }
  24567. }
  24568. // Got a new set of subtitle fragments.
  24569. onSubtitleTrackLoaded(event, data) {
  24570. var _track$details;
  24571. const {
  24572. currentTrackId,
  24573. levels
  24574. } = this;
  24575. const {
  24576. details: newDetails,
  24577. id: trackId
  24578. } = data;
  24579. if (!levels) {
  24580. this.warn(`Subtitle tracks were reset while loading level ${trackId}`);
  24581. return;
  24582. }
  24583. const track = levels[trackId];
  24584. if (trackId >= levels.length || !track) {
  24585. return;
  24586. }
  24587. this.log(`Subtitle track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""},duration:${newDetails.totalduration}`);
  24588. this.mediaBuffer = this.mediaBufferTimeRanges;
  24589. let sliding = 0;
  24590. if (newDetails.live || (_track$details = track.details) != null && _track$details.live) {
  24591. if (newDetails.deltaUpdateFailed) {
  24592. return;
  24593. }
  24594. const mainDetails = this.mainDetails;
  24595. if (!mainDetails) {
  24596. this.startFragRequested = false;
  24597. return;
  24598. }
  24599. const mainSlidingStartFragment = mainDetails.fragments[0];
  24600. if (!track.details) {
  24601. if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {
  24602. alignMediaPlaylistByPDT(newDetails, mainDetails);
  24603. sliding = newDetails.fragmentStart;
  24604. } else if (mainSlidingStartFragment) {
  24605. sliding = mainSlidingStartFragment.start;
  24606. addSliding(newDetails, sliding);
  24607. }
  24608. } else {
  24609. var _this$levelLastLoaded;
  24610. sliding = this.alignPlaylists(newDetails, track.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  24611. if (sliding === 0 && mainSlidingStartFragment) {
  24612. sliding = mainSlidingStartFragment.start;
  24613. addSliding(newDetails, sliding);
  24614. }
  24615. }
  24616. if (mainDetails && !this.startFragRequested) {
  24617. this.setStartPosition(mainDetails, sliding);
  24618. }
  24619. }
  24620. track.details = newDetails;
  24621. this.levelLastLoaded = track;
  24622. if (trackId !== currentTrackId) {
  24623. return;
  24624. }
  24625. this.hls.trigger(Events.SUBTITLE_TRACK_UPDATED, {
  24626. details: newDetails,
  24627. id: trackId,
  24628. groupId: data.groupId
  24629. });
  24630. this.tick();
  24631. if (newDetails.live && !this.fragCurrent && this.media && this.state === State.IDLE) {
  24632. const foundFrag = findFragmentByPTS(null, newDetails.fragments, this.media.currentTime, 0);
  24633. if (!foundFrag) {
  24634. this.warn("Subtitle playlist not aligned with playback");
  24635. track.details = void 0;
  24636. }
  24637. }
  24638. }
  24639. _handleFragmentLoadComplete(fragLoadedData) {
  24640. const {
  24641. frag,
  24642. payload
  24643. } = fragLoadedData;
  24644. const decryptData = frag.decryptdata;
  24645. const hls = this.hls;
  24646. if (this.fragContextChanged(frag)) {
  24647. return;
  24648. }
  24649. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
  24650. const startTime = performance.now();
  24651. this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch((err) => {
  24652. hls.trigger(Events.ERROR, {
  24653. type: ErrorTypes.MEDIA_ERROR,
  24654. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  24655. fatal: false,
  24656. error: err,
  24657. reason: err.message,
  24658. frag
  24659. });
  24660. throw err;
  24661. }).then((decryptedData) => {
  24662. const endTime = performance.now();
  24663. hls.trigger(Events.FRAG_DECRYPTED, {
  24664. frag,
  24665. payload: decryptedData,
  24666. stats: {
  24667. tstart: startTime,
  24668. tdecrypt: endTime
  24669. }
  24670. });
  24671. }).catch((err) => {
  24672. this.warn(`${err.name}: ${err.message}`);
  24673. this.state = State.IDLE;
  24674. });
  24675. }
  24676. }
  24677. doTick() {
  24678. if (!this.media) {
  24679. this.state = State.IDLE;
  24680. return;
  24681. }
  24682. if (this.state === State.IDLE) {
  24683. const {
  24684. currentTrackId,
  24685. levels
  24686. } = this;
  24687. const track = levels == null ? void 0 : levels[currentTrackId];
  24688. if (!track || !levels.length || !track.details) {
  24689. return;
  24690. }
  24691. if (this.waitForLive(track)) {
  24692. return;
  24693. }
  24694. const {
  24695. config
  24696. } = this;
  24697. const currentTime = this.getLoadPosition();
  24698. const bufferedInfo = BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId] || [], currentTime, config.maxBufferHole);
  24699. const {
  24700. end: targetBufferTime,
  24701. len: bufferLen
  24702. } = bufferedInfo;
  24703. const trackDetails = track.details;
  24704. const maxBufLen = this.hls.maxBufferLength + trackDetails.levelTargetDuration;
  24705. if (bufferLen > maxBufLen) {
  24706. return;
  24707. }
  24708. const fragments = trackDetails.fragments;
  24709. const fragLen = fragments.length;
  24710. const end = trackDetails.edge;
  24711. let foundFrag = null;
  24712. const fragPrevious = this.fragPrevious;
  24713. if (targetBufferTime < end) {
  24714. const tolerance = config.maxFragLookUpTolerance;
  24715. const lookupTolerance = targetBufferTime > end - tolerance ? 0 : tolerance;
  24716. foundFrag = findFragmentByPTS(fragPrevious, fragments, Math.max(fragments[0].start, targetBufferTime), lookupTolerance);
  24717. if (!foundFrag && fragPrevious && fragPrevious.start < fragments[0].start) {
  24718. foundFrag = fragments[0];
  24719. }
  24720. } else {
  24721. foundFrag = fragments[fragLen - 1];
  24722. }
  24723. foundFrag = this.filterReplacedPrimary(foundFrag, track.details);
  24724. if (!foundFrag) {
  24725. return;
  24726. }
  24727. const curSNIdx = foundFrag.sn - trackDetails.startSN;
  24728. const prevFrag = fragments[curSNIdx - 1];
  24729. if (prevFrag && prevFrag.cc === foundFrag.cc && this.fragmentTracker.getState(prevFrag) === FragmentState.NOT_LOADED) {
  24730. foundFrag = prevFrag;
  24731. }
  24732. if (this.fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) {
  24733. const fragToLoad = this.mapToInitFragWhenRequired(foundFrag);
  24734. if (fragToLoad) {
  24735. this.loadFragment(fragToLoad, track, targetBufferTime);
  24736. }
  24737. }
  24738. }
  24739. }
  24740. loadFragment(frag, level, targetBufferTime) {
  24741. if (!isMediaFragment(frag)) {
  24742. this._loadInitSegment(frag, level);
  24743. } else {
  24744. super.loadFragment(frag, level, targetBufferTime);
  24745. }
  24746. }
  24747. get mediaBufferTimeRanges() {
  24748. return new BufferableInstance(this.tracksBuffered[this.currentTrackId] || []);
  24749. }
  24750. };
  24751. var BufferableInstance = class {
  24752. constructor(timeranges) {
  24753. this.buffered = void 0;
  24754. const getRange = (name, index, length) => {
  24755. index = index >>> 0;
  24756. if (index > length - 1) {
  24757. throw new DOMException(`Failed to execute '${name}' on 'TimeRanges': The index provided (${index}) is greater than the maximum bound (${length})`);
  24758. }
  24759. return timeranges[index][name];
  24760. };
  24761. this.buffered = {
  24762. get length() {
  24763. return timeranges.length;
  24764. },
  24765. end(index) {
  24766. return getRange("end", index, timeranges.length);
  24767. },
  24768. start(index) {
  24769. return getRange("start", index, timeranges.length);
  24770. }
  24771. };
  24772. }
  24773. };
  24774. var specialCea608CharsCodes = {
  24775. 42: 225,
  24776. // lowercase a, acute accent
  24777. 92: 233,
  24778. // lowercase e, acute accent
  24779. 94: 237,
  24780. // lowercase i, acute accent
  24781. 95: 243,
  24782. // lowercase o, acute accent
  24783. 96: 250,
  24784. // lowercase u, acute accent
  24785. 123: 231,
  24786. // lowercase c with cedilla
  24787. 124: 247,
  24788. // division symbol
  24789. 125: 209,
  24790. // uppercase N tilde
  24791. 126: 241,
  24792. // lowercase n tilde
  24793. 127: 9608,
  24794. // Full block
  24795. // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  24796. // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
  24797. // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
  24798. 128: 174,
  24799. // Registered symbol (R)
  24800. 129: 176,
  24801. // degree sign
  24802. 130: 189,
  24803. // 1/2 symbol
  24804. 131: 191,
  24805. // Inverted (open) question mark
  24806. 132: 8482,
  24807. // Trademark symbol (TM)
  24808. 133: 162,
  24809. // Cents symbol
  24810. 134: 163,
  24811. // Pounds sterling
  24812. 135: 9834,
  24813. // Music 8'th note
  24814. 136: 224,
  24815. // lowercase a, grave accent
  24816. 137: 32,
  24817. // transparent space (regular)
  24818. 138: 232,
  24819. // lowercase e, grave accent
  24820. 139: 226,
  24821. // lowercase a, circumflex accent
  24822. 140: 234,
  24823. // lowercase e, circumflex accent
  24824. 141: 238,
  24825. // lowercase i, circumflex accent
  24826. 142: 244,
  24827. // lowercase o, circumflex accent
  24828. 143: 251,
  24829. // lowercase u, circumflex accent
  24830. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  24831. // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
  24832. 144: 193,
  24833. // capital letter A with acute
  24834. 145: 201,
  24835. // capital letter E with acute
  24836. 146: 211,
  24837. // capital letter O with acute
  24838. 147: 218,
  24839. // capital letter U with acute
  24840. 148: 220,
  24841. // capital letter U with diaresis
  24842. 149: 252,
  24843. // lowercase letter U with diaeresis
  24844. 150: 8216,
  24845. // opening single quote
  24846. 151: 161,
  24847. // inverted exclamation mark
  24848. 152: 42,
  24849. // asterisk
  24850. 153: 8217,
  24851. // closing single quote
  24852. 154: 9473,
  24853. // box drawings heavy horizontal
  24854. 155: 169,
  24855. // copyright sign
  24856. 156: 8480,
  24857. // Service mark
  24858. 157: 8226,
  24859. // (round) bullet
  24860. 158: 8220,
  24861. // Left double quotation mark
  24862. 159: 8221,
  24863. // Right double quotation mark
  24864. 160: 192,
  24865. // uppercase A, grave accent
  24866. 161: 194,
  24867. // uppercase A, circumflex
  24868. 162: 199,
  24869. // uppercase C with cedilla
  24870. 163: 200,
  24871. // uppercase E, grave accent
  24872. 164: 202,
  24873. // uppercase E, circumflex
  24874. 165: 203,
  24875. // capital letter E with diaresis
  24876. 166: 235,
  24877. // lowercase letter e with diaresis
  24878. 167: 206,
  24879. // uppercase I, circumflex
  24880. 168: 207,
  24881. // uppercase I, with diaresis
  24882. 169: 239,
  24883. // lowercase i, with diaresis
  24884. 170: 212,
  24885. // uppercase O, circumflex
  24886. 171: 217,
  24887. // uppercase U, grave accent
  24888. 172: 249,
  24889. // lowercase u, grave accent
  24890. 173: 219,
  24891. // uppercase U, circumflex
  24892. 174: 171,
  24893. // left-pointing double angle quotation mark
  24894. 175: 187,
  24895. // right-pointing double angle quotation mark
  24896. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  24897. // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
  24898. 176: 195,
  24899. // Uppercase A, tilde
  24900. 177: 227,
  24901. // Lowercase a, tilde
  24902. 178: 205,
  24903. // Uppercase I, acute accent
  24904. 179: 204,
  24905. // Uppercase I, grave accent
  24906. 180: 236,
  24907. // Lowercase i, grave accent
  24908. 181: 210,
  24909. // Uppercase O, grave accent
  24910. 182: 242,
  24911. // Lowercase o, grave accent
  24912. 183: 213,
  24913. // Uppercase O, tilde
  24914. 184: 245,
  24915. // Lowercase o, tilde
  24916. 185: 123,
  24917. // Open curly brace
  24918. 186: 125,
  24919. // Closing curly brace
  24920. 187: 92,
  24921. // Backslash
  24922. 188: 94,
  24923. // Caret
  24924. 189: 95,
  24925. // Underscore
  24926. 190: 124,
  24927. // Pipe (vertical line)
  24928. 191: 8764,
  24929. // Tilde operator
  24930. 192: 196,
  24931. // Uppercase A, umlaut
  24932. 193: 228,
  24933. // Lowercase A, umlaut
  24934. 194: 214,
  24935. // Uppercase O, umlaut
  24936. 195: 246,
  24937. // Lowercase o, umlaut
  24938. 196: 223,
  24939. // Esszett (sharp S)
  24940. 197: 165,
  24941. // Yen symbol
  24942. 198: 164,
  24943. // Generic currency sign
  24944. 199: 9475,
  24945. // Box drawings heavy vertical
  24946. 200: 197,
  24947. // Uppercase A, ring
  24948. 201: 229,
  24949. // Lowercase A, ring
  24950. 202: 216,
  24951. // Uppercase O, stroke
  24952. 203: 248,
  24953. // Lowercase o, strok
  24954. 204: 9487,
  24955. // Box drawings heavy down and right
  24956. 205: 9491,
  24957. // Box drawings heavy down and left
  24958. 206: 9495,
  24959. // Box drawings heavy up and right
  24960. 207: 9499
  24961. // Box drawings heavy up and left
  24962. };
  24963. var getCharForByte = (byte) => String.fromCharCode(specialCea608CharsCodes[byte] || byte);
  24964. var NR_ROWS = 15;
  24965. var NR_COLS = 100;
  24966. var rowsLowCh1 = {
  24967. 17: 1,
  24968. 18: 3,
  24969. 21: 5,
  24970. 22: 7,
  24971. 23: 9,
  24972. 16: 11,
  24973. 19: 12,
  24974. 20: 14
  24975. };
  24976. var rowsHighCh1 = {
  24977. 17: 2,
  24978. 18: 4,
  24979. 21: 6,
  24980. 22: 8,
  24981. 23: 10,
  24982. 19: 13,
  24983. 20: 15
  24984. };
  24985. var rowsLowCh2 = {
  24986. 25: 1,
  24987. 26: 3,
  24988. 29: 5,
  24989. 30: 7,
  24990. 31: 9,
  24991. 24: 11,
  24992. 27: 12,
  24993. 28: 14
  24994. };
  24995. var rowsHighCh2 = {
  24996. 25: 2,
  24997. 26: 4,
  24998. 29: 6,
  24999. 30: 8,
  25000. 31: 10,
  25001. 27: 13,
  25002. 28: 15
  25003. };
  25004. var backgroundColors = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "black", "transparent"];
  25005. var CaptionsLogger = class {
  25006. constructor() {
  25007. this.time = null;
  25008. this.verboseLevel = 0;
  25009. }
  25010. log(severity, msg) {
  25011. if (this.verboseLevel >= severity) {
  25012. const m = typeof msg === "function" ? msg() : msg;
  25013. logger.log(`${this.time} [${severity}] ${m}`);
  25014. }
  25015. }
  25016. };
  25017. var numArrayToHexArray = function numArrayToHexArray2(numArray) {
  25018. const hexArray = [];
  25019. for (let j = 0; j < numArray.length; j++) {
  25020. hexArray.push(numArray[j].toString(16));
  25021. }
  25022. return hexArray;
  25023. };
  25024. var PenState = class {
  25025. constructor() {
  25026. this.foreground = "white";
  25027. this.underline = false;
  25028. this.italics = false;
  25029. this.background = "black";
  25030. this.flash = false;
  25031. }
  25032. reset() {
  25033. this.foreground = "white";
  25034. this.underline = false;
  25035. this.italics = false;
  25036. this.background = "black";
  25037. this.flash = false;
  25038. }
  25039. setStyles(styles) {
  25040. const attribs = ["foreground", "underline", "italics", "background", "flash"];
  25041. for (let i = 0; i < attribs.length; i++) {
  25042. const style = attribs[i];
  25043. if (styles.hasOwnProperty(style)) {
  25044. this[style] = styles[style];
  25045. }
  25046. }
  25047. }
  25048. isDefault() {
  25049. return this.foreground === "white" && !this.underline && !this.italics && this.background === "black" && !this.flash;
  25050. }
  25051. equals(other) {
  25052. return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
  25053. }
  25054. copy(newPenState) {
  25055. this.foreground = newPenState.foreground;
  25056. this.underline = newPenState.underline;
  25057. this.italics = newPenState.italics;
  25058. this.background = newPenState.background;
  25059. this.flash = newPenState.flash;
  25060. }
  25061. toString() {
  25062. return "color=" + this.foreground + ", underline=" + this.underline + ", italics=" + this.italics + ", background=" + this.background + ", flash=" + this.flash;
  25063. }
  25064. };
  25065. var StyledUnicodeChar = class {
  25066. constructor() {
  25067. this.uchar = " ";
  25068. this.penState = new PenState();
  25069. }
  25070. reset() {
  25071. this.uchar = " ";
  25072. this.penState.reset();
  25073. }
  25074. setChar(uchar, newPenState) {
  25075. this.uchar = uchar;
  25076. this.penState.copy(newPenState);
  25077. }
  25078. setPenState(newPenState) {
  25079. this.penState.copy(newPenState);
  25080. }
  25081. equals(other) {
  25082. return this.uchar === other.uchar && this.penState.equals(other.penState);
  25083. }
  25084. copy(newChar) {
  25085. this.uchar = newChar.uchar;
  25086. this.penState.copy(newChar.penState);
  25087. }
  25088. isEmpty() {
  25089. return this.uchar === " " && this.penState.isDefault();
  25090. }
  25091. };
  25092. var Row = class {
  25093. constructor(logger2) {
  25094. this.chars = [];
  25095. this.pos = 0;
  25096. this.currPenState = new PenState();
  25097. this.cueStartTime = null;
  25098. this.logger = void 0;
  25099. for (let i = 0; i < NR_COLS; i++) {
  25100. this.chars.push(new StyledUnicodeChar());
  25101. }
  25102. this.logger = logger2;
  25103. }
  25104. equals(other) {
  25105. for (let i = 0; i < NR_COLS; i++) {
  25106. if (!this.chars[i].equals(other.chars[i])) {
  25107. return false;
  25108. }
  25109. }
  25110. return true;
  25111. }
  25112. copy(other) {
  25113. for (let i = 0; i < NR_COLS; i++) {
  25114. this.chars[i].copy(other.chars[i]);
  25115. }
  25116. }
  25117. isEmpty() {
  25118. let empty = true;
  25119. for (let i = 0; i < NR_COLS; i++) {
  25120. if (!this.chars[i].isEmpty()) {
  25121. empty = false;
  25122. break;
  25123. }
  25124. }
  25125. return empty;
  25126. }
  25127. /**
  25128. * Set the cursor to a valid column.
  25129. */
  25130. setCursor(absPos) {
  25131. if (this.pos !== absPos) {
  25132. this.pos = absPos;
  25133. }
  25134. if (this.pos < 0) {
  25135. this.logger.log(3, "Negative cursor position " + this.pos);
  25136. this.pos = 0;
  25137. } else if (this.pos > NR_COLS) {
  25138. this.logger.log(3, "Too large cursor position " + this.pos);
  25139. this.pos = NR_COLS;
  25140. }
  25141. }
  25142. /**
  25143. * Move the cursor relative to current position.
  25144. */
  25145. moveCursor(relPos) {
  25146. const newPos = this.pos + relPos;
  25147. if (relPos > 1) {
  25148. for (let i = this.pos + 1; i < newPos + 1; i++) {
  25149. this.chars[i].setPenState(this.currPenState);
  25150. }
  25151. }
  25152. this.setCursor(newPos);
  25153. }
  25154. /**
  25155. * Backspace, move one step back and clear character.
  25156. */
  25157. backSpace() {
  25158. this.moveCursor(-1);
  25159. this.chars[this.pos].setChar(" ", this.currPenState);
  25160. }
  25161. insertChar(byte) {
  25162. if (byte >= 144) {
  25163. this.backSpace();
  25164. }
  25165. const char = getCharForByte(byte);
  25166. if (this.pos >= NR_COLS) {
  25167. this.logger.log(0, () => "Cannot insert " + byte.toString(16) + " (" + char + ") at position " + this.pos + ". Skipping it!");
  25168. return;
  25169. }
  25170. this.chars[this.pos].setChar(char, this.currPenState);
  25171. this.moveCursor(1);
  25172. }
  25173. clearFromPos(startPos) {
  25174. let i;
  25175. for (i = startPos; i < NR_COLS; i++) {
  25176. this.chars[i].reset();
  25177. }
  25178. }
  25179. clear() {
  25180. this.clearFromPos(0);
  25181. this.pos = 0;
  25182. this.currPenState.reset();
  25183. }
  25184. clearToEndOfRow() {
  25185. this.clearFromPos(this.pos);
  25186. }
  25187. getTextString() {
  25188. const chars = [];
  25189. let empty = true;
  25190. for (let i = 0; i < NR_COLS; i++) {
  25191. const char = this.chars[i].uchar;
  25192. if (char !== " ") {
  25193. empty = false;
  25194. }
  25195. chars.push(char);
  25196. }
  25197. if (empty) {
  25198. return "";
  25199. } else {
  25200. return chars.join("");
  25201. }
  25202. }
  25203. setPenStyles(styles) {
  25204. this.currPenState.setStyles(styles);
  25205. const currChar = this.chars[this.pos];
  25206. currChar.setPenState(this.currPenState);
  25207. }
  25208. };
  25209. var CaptionScreen = class {
  25210. constructor(logger2) {
  25211. this.rows = [];
  25212. this.currRow = NR_ROWS - 1;
  25213. this.nrRollUpRows = null;
  25214. this.lastOutputScreen = null;
  25215. this.logger = void 0;
  25216. for (let i = 0; i < NR_ROWS; i++) {
  25217. this.rows.push(new Row(logger2));
  25218. }
  25219. this.logger = logger2;
  25220. }
  25221. reset() {
  25222. for (let i = 0; i < NR_ROWS; i++) {
  25223. this.rows[i].clear();
  25224. }
  25225. this.currRow = NR_ROWS - 1;
  25226. }
  25227. equals(other) {
  25228. let equal = true;
  25229. for (let i = 0; i < NR_ROWS; i++) {
  25230. if (!this.rows[i].equals(other.rows[i])) {
  25231. equal = false;
  25232. break;
  25233. }
  25234. }
  25235. return equal;
  25236. }
  25237. copy(other) {
  25238. for (let i = 0; i < NR_ROWS; i++) {
  25239. this.rows[i].copy(other.rows[i]);
  25240. }
  25241. }
  25242. isEmpty() {
  25243. let empty = true;
  25244. for (let i = 0; i < NR_ROWS; i++) {
  25245. if (!this.rows[i].isEmpty()) {
  25246. empty = false;
  25247. break;
  25248. }
  25249. }
  25250. return empty;
  25251. }
  25252. backSpace() {
  25253. const row = this.rows[this.currRow];
  25254. row.backSpace();
  25255. }
  25256. clearToEndOfRow() {
  25257. const row = this.rows[this.currRow];
  25258. row.clearToEndOfRow();
  25259. }
  25260. /**
  25261. * Insert a character (without styling) in the current row.
  25262. */
  25263. insertChar(char) {
  25264. const row = this.rows[this.currRow];
  25265. row.insertChar(char);
  25266. }
  25267. setPen(styles) {
  25268. const row = this.rows[this.currRow];
  25269. row.setPenStyles(styles);
  25270. }
  25271. moveCursor(relPos) {
  25272. const row = this.rows[this.currRow];
  25273. row.moveCursor(relPos);
  25274. }
  25275. setCursor(absPos) {
  25276. this.logger.log(2, "setCursor: " + absPos);
  25277. const row = this.rows[this.currRow];
  25278. row.setCursor(absPos);
  25279. }
  25280. setPAC(pacData) {
  25281. this.logger.log(2, () => "pacData = " + stringify(pacData));
  25282. let newRow = pacData.row - 1;
  25283. if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
  25284. newRow = this.nrRollUpRows - 1;
  25285. }
  25286. if (this.nrRollUpRows && this.currRow !== newRow) {
  25287. for (let i = 0; i < NR_ROWS; i++) {
  25288. this.rows[i].clear();
  25289. }
  25290. const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  25291. const lastOutputScreen = this.lastOutputScreen;
  25292. if (lastOutputScreen) {
  25293. const prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
  25294. const time = this.logger.time;
  25295. if (prevLineTime !== null && time !== null && prevLineTime < time) {
  25296. for (let i = 0; i < this.nrRollUpRows; i++) {
  25297. this.rows[newRow - this.nrRollUpRows + i + 1].copy(lastOutputScreen.rows[topRowIndex + i]);
  25298. }
  25299. }
  25300. }
  25301. }
  25302. this.currRow = newRow;
  25303. const row = this.rows[this.currRow];
  25304. if (pacData.indent !== null) {
  25305. const indent = pacData.indent;
  25306. const prevPos = Math.max(indent - 1, 0);
  25307. row.setCursor(pacData.indent);
  25308. pacData.color = row.chars[prevPos].penState.foreground;
  25309. }
  25310. const styles = {
  25311. foreground: pacData.color,
  25312. underline: pacData.underline,
  25313. italics: pacData.italics,
  25314. background: "black",
  25315. flash: false
  25316. };
  25317. this.setPen(styles);
  25318. }
  25319. /**
  25320. * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
  25321. */
  25322. setBkgData(bkgData) {
  25323. this.logger.log(2, () => "bkgData = " + stringify(bkgData));
  25324. this.backSpace();
  25325. this.setPen(bkgData);
  25326. this.insertChar(32);
  25327. }
  25328. setRollUpRows(nrRows) {
  25329. this.nrRollUpRows = nrRows;
  25330. }
  25331. rollUp() {
  25332. if (this.nrRollUpRows === null) {
  25333. this.logger.log(3, "roll_up but nrRollUpRows not set yet");
  25334. return;
  25335. }
  25336. this.logger.log(1, () => this.getDisplayText());
  25337. const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  25338. const topRow = this.rows.splice(topRowIndex, 1)[0];
  25339. topRow.clear();
  25340. this.rows.splice(this.currRow, 0, topRow);
  25341. this.logger.log(2, "Rolling up");
  25342. }
  25343. /**
  25344. * Get all non-empty rows with as unicode text.
  25345. */
  25346. getDisplayText(asOneRow) {
  25347. asOneRow = asOneRow || false;
  25348. const displayText = [];
  25349. let text = "";
  25350. let rowNr = -1;
  25351. for (let i = 0; i < NR_ROWS; i++) {
  25352. const rowText = this.rows[i].getTextString();
  25353. if (rowText) {
  25354. rowNr = i + 1;
  25355. if (asOneRow) {
  25356. displayText.push("Row " + rowNr + ": '" + rowText + "'");
  25357. } else {
  25358. displayText.push(rowText.trim());
  25359. }
  25360. }
  25361. }
  25362. if (displayText.length > 0) {
  25363. if (asOneRow) {
  25364. text = "[" + displayText.join(" | ") + "]";
  25365. } else {
  25366. text = displayText.join("\n");
  25367. }
  25368. }
  25369. return text;
  25370. }
  25371. getTextAndFormat() {
  25372. return this.rows;
  25373. }
  25374. };
  25375. var Cea608Channel = class {
  25376. constructor(channelNumber, outputFilter, logger2) {
  25377. this.chNr = void 0;
  25378. this.outputFilter = void 0;
  25379. this.mode = void 0;
  25380. this.verbose = void 0;
  25381. this.displayedMemory = void 0;
  25382. this.nonDisplayedMemory = void 0;
  25383. this.lastOutputScreen = void 0;
  25384. this.currRollUpRow = void 0;
  25385. this.writeScreen = void 0;
  25386. this.cueStartTime = void 0;
  25387. this.logger = void 0;
  25388. this.chNr = channelNumber;
  25389. this.outputFilter = outputFilter;
  25390. this.mode = null;
  25391. this.verbose = 0;
  25392. this.displayedMemory = new CaptionScreen(logger2);
  25393. this.nonDisplayedMemory = new CaptionScreen(logger2);
  25394. this.lastOutputScreen = new CaptionScreen(logger2);
  25395. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  25396. this.writeScreen = this.displayedMemory;
  25397. this.mode = null;
  25398. this.cueStartTime = null;
  25399. this.logger = logger2;
  25400. }
  25401. reset() {
  25402. this.mode = null;
  25403. this.displayedMemory.reset();
  25404. this.nonDisplayedMemory.reset();
  25405. this.lastOutputScreen.reset();
  25406. this.outputFilter.reset();
  25407. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  25408. this.writeScreen = this.displayedMemory;
  25409. this.mode = null;
  25410. this.cueStartTime = null;
  25411. }
  25412. getHandler() {
  25413. return this.outputFilter;
  25414. }
  25415. setHandler(newHandler) {
  25416. this.outputFilter = newHandler;
  25417. }
  25418. setPAC(pacData) {
  25419. this.writeScreen.setPAC(pacData);
  25420. }
  25421. setBkgData(bkgData) {
  25422. this.writeScreen.setBkgData(bkgData);
  25423. }
  25424. setMode(newMode) {
  25425. if (newMode === this.mode) {
  25426. return;
  25427. }
  25428. this.mode = newMode;
  25429. this.logger.log(2, () => "MODE=" + newMode);
  25430. if (this.mode === "MODE_POP-ON") {
  25431. this.writeScreen = this.nonDisplayedMemory;
  25432. } else {
  25433. this.writeScreen = this.displayedMemory;
  25434. this.writeScreen.reset();
  25435. }
  25436. if (this.mode !== "MODE_ROLL-UP") {
  25437. this.displayedMemory.nrRollUpRows = null;
  25438. this.nonDisplayedMemory.nrRollUpRows = null;
  25439. }
  25440. this.mode = newMode;
  25441. }
  25442. insertChars(chars) {
  25443. for (let i = 0; i < chars.length; i++) {
  25444. this.writeScreen.insertChar(chars[i]);
  25445. }
  25446. const screen = this.writeScreen === this.displayedMemory ? "DISP" : "NON_DISP";
  25447. this.logger.log(2, () => screen + ": " + this.writeScreen.getDisplayText(true));
  25448. if (this.mode === "MODE_PAINT-ON" || this.mode === "MODE_ROLL-UP") {
  25449. this.logger.log(1, () => "DISPLAYED: " + this.displayedMemory.getDisplayText(true));
  25450. this.outputDataUpdate();
  25451. }
  25452. }
  25453. ccRCL() {
  25454. this.logger.log(2, "RCL - Resume Caption Loading");
  25455. this.setMode("MODE_POP-ON");
  25456. }
  25457. ccBS() {
  25458. this.logger.log(2, "BS - BackSpace");
  25459. if (this.mode === "MODE_TEXT") {
  25460. return;
  25461. }
  25462. this.writeScreen.backSpace();
  25463. if (this.writeScreen === this.displayedMemory) {
  25464. this.outputDataUpdate();
  25465. }
  25466. }
  25467. ccAOF() {
  25468. }
  25469. ccAON() {
  25470. }
  25471. ccDER() {
  25472. this.logger.log(2, "DER- Delete to End of Row");
  25473. this.writeScreen.clearToEndOfRow();
  25474. this.outputDataUpdate();
  25475. }
  25476. ccRU(nrRows) {
  25477. this.logger.log(2, "RU(" + nrRows + ") - Roll Up");
  25478. this.writeScreen = this.displayedMemory;
  25479. this.setMode("MODE_ROLL-UP");
  25480. this.writeScreen.setRollUpRows(nrRows);
  25481. }
  25482. ccFON() {
  25483. this.logger.log(2, "FON - Flash On");
  25484. this.writeScreen.setPen({
  25485. flash: true
  25486. });
  25487. }
  25488. ccRDC() {
  25489. this.logger.log(2, "RDC - Resume Direct Captioning");
  25490. this.setMode("MODE_PAINT-ON");
  25491. }
  25492. ccTR() {
  25493. this.logger.log(2, "TR");
  25494. this.setMode("MODE_TEXT");
  25495. }
  25496. ccRTD() {
  25497. this.logger.log(2, "RTD");
  25498. this.setMode("MODE_TEXT");
  25499. }
  25500. ccEDM() {
  25501. this.logger.log(2, "EDM - Erase Displayed Memory");
  25502. this.displayedMemory.reset();
  25503. this.outputDataUpdate(true);
  25504. }
  25505. ccCR() {
  25506. this.logger.log(2, "CR - Carriage Return");
  25507. this.writeScreen.rollUp();
  25508. this.outputDataUpdate(true);
  25509. }
  25510. ccENM() {
  25511. this.logger.log(2, "ENM - Erase Non-displayed Memory");
  25512. this.nonDisplayedMemory.reset();
  25513. }
  25514. ccEOC() {
  25515. this.logger.log(2, "EOC - End Of Caption");
  25516. if (this.mode === "MODE_POP-ON") {
  25517. const tmp = this.displayedMemory;
  25518. this.displayedMemory = this.nonDisplayedMemory;
  25519. this.nonDisplayedMemory = tmp;
  25520. this.writeScreen = this.nonDisplayedMemory;
  25521. this.logger.log(1, () => "DISP: " + this.displayedMemory.getDisplayText());
  25522. }
  25523. this.outputDataUpdate(true);
  25524. }
  25525. ccTO(nrCols) {
  25526. this.logger.log(2, "TO(" + nrCols + ") - Tab Offset");
  25527. this.writeScreen.moveCursor(nrCols);
  25528. }
  25529. ccMIDROW(secondByte) {
  25530. const styles = {
  25531. flash: false
  25532. };
  25533. styles.underline = secondByte % 2 === 1;
  25534. styles.italics = secondByte >= 46;
  25535. if (!styles.italics) {
  25536. const colorIndex = Math.floor(secondByte / 2) - 16;
  25537. const colors = ["white", "green", "blue", "cyan", "red", "yellow", "magenta"];
  25538. styles.foreground = colors[colorIndex];
  25539. } else {
  25540. styles.foreground = "white";
  25541. }
  25542. this.logger.log(2, "MIDROW: " + stringify(styles));
  25543. this.writeScreen.setPen(styles);
  25544. }
  25545. outputDataUpdate(dispatch = false) {
  25546. const time = this.logger.time;
  25547. if (time === null) {
  25548. return;
  25549. }
  25550. if (this.outputFilter) {
  25551. if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
  25552. this.cueStartTime = time;
  25553. } else {
  25554. if (!this.displayedMemory.equals(this.lastOutputScreen)) {
  25555. this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);
  25556. if (dispatch && this.outputFilter.dispatchCue) {
  25557. this.outputFilter.dispatchCue();
  25558. }
  25559. this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;
  25560. }
  25561. }
  25562. this.lastOutputScreen.copy(this.displayedMemory);
  25563. }
  25564. }
  25565. cueSplitAtTime(t) {
  25566. if (this.outputFilter) {
  25567. if (!this.displayedMemory.isEmpty()) {
  25568. if (this.outputFilter.newCue) {
  25569. this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
  25570. }
  25571. this.cueStartTime = t;
  25572. }
  25573. }
  25574. }
  25575. };
  25576. var Cea608Parser = class {
  25577. constructor(field, out1, out2) {
  25578. this.channels = void 0;
  25579. this.currentChannel = 0;
  25580. this.cmdHistory = createCmdHistory();
  25581. this.logger = void 0;
  25582. const logger2 = this.logger = new CaptionsLogger();
  25583. this.channels = [null, new Cea608Channel(field, out1, logger2), new Cea608Channel(field + 1, out2, logger2)];
  25584. }
  25585. getHandler(channel) {
  25586. return this.channels[channel].getHandler();
  25587. }
  25588. setHandler(channel, newHandler) {
  25589. this.channels[channel].setHandler(newHandler);
  25590. }
  25591. /**
  25592. * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
  25593. */
  25594. addData(time, byteList) {
  25595. this.logger.time = time;
  25596. for (let i = 0; i < byteList.length; i += 2) {
  25597. const a = byteList[i] & 127;
  25598. const b = byteList[i + 1] & 127;
  25599. let cmdFound = false;
  25600. let charsFound = null;
  25601. if (a === 0 && b === 0) {
  25602. continue;
  25603. } else {
  25604. this.logger.log(3, () => "[" + numArrayToHexArray([byteList[i], byteList[i + 1]]) + "] -> (" + numArrayToHexArray([a, b]) + ")");
  25605. }
  25606. const cmdHistory = this.cmdHistory;
  25607. const isControlCode = a >= 16 && a <= 31;
  25608. if (isControlCode) {
  25609. if (hasCmdRepeated(a, b, cmdHistory)) {
  25610. setLastCmd(null, null, cmdHistory);
  25611. this.logger.log(3, () => "Repeated command (" + numArrayToHexArray([a, b]) + ") is dropped");
  25612. continue;
  25613. }
  25614. setLastCmd(a, b, this.cmdHistory);
  25615. cmdFound = this.parseCmd(a, b);
  25616. if (!cmdFound) {
  25617. cmdFound = this.parseMidrow(a, b);
  25618. }
  25619. if (!cmdFound) {
  25620. cmdFound = this.parsePAC(a, b);
  25621. }
  25622. if (!cmdFound) {
  25623. cmdFound = this.parseBackgroundAttributes(a, b);
  25624. }
  25625. } else {
  25626. setLastCmd(null, null, cmdHistory);
  25627. }
  25628. if (!cmdFound) {
  25629. charsFound = this.parseChars(a, b);
  25630. if (charsFound) {
  25631. const currChNr = this.currentChannel;
  25632. if (currChNr && currChNr > 0) {
  25633. const channel = this.channels[currChNr];
  25634. channel.insertChars(charsFound);
  25635. } else {
  25636. this.logger.log(2, "No channel found yet. TEXT-MODE?");
  25637. }
  25638. }
  25639. }
  25640. if (!cmdFound && !charsFound) {
  25641. this.logger.log(2, () => "Couldn't parse cleaned data " + numArrayToHexArray([a, b]) + " orig: " + numArrayToHexArray([byteList[i], byteList[i + 1]]));
  25642. }
  25643. }
  25644. }
  25645. /**
  25646. * Parse Command.
  25647. * @returns True if a command was found
  25648. */
  25649. parseCmd(a, b) {
  25650. const cond1 = (a === 20 || a === 28 || a === 21 || a === 29) && b >= 32 && b <= 47;
  25651. const cond2 = (a === 23 || a === 31) && b >= 33 && b <= 35;
  25652. if (!(cond1 || cond2)) {
  25653. return false;
  25654. }
  25655. const chNr = a === 20 || a === 21 || a === 23 ? 1 : 2;
  25656. const channel = this.channels[chNr];
  25657. if (a === 20 || a === 21 || a === 28 || a === 29) {
  25658. if (b === 32) {
  25659. channel.ccRCL();
  25660. } else if (b === 33) {
  25661. channel.ccBS();
  25662. } else if (b === 34) {
  25663. channel.ccAOF();
  25664. } else if (b === 35) {
  25665. channel.ccAON();
  25666. } else if (b === 36) {
  25667. channel.ccDER();
  25668. } else if (b === 37) {
  25669. channel.ccRU(2);
  25670. } else if (b === 38) {
  25671. channel.ccRU(3);
  25672. } else if (b === 39) {
  25673. channel.ccRU(4);
  25674. } else if (b === 40) {
  25675. channel.ccFON();
  25676. } else if (b === 41) {
  25677. channel.ccRDC();
  25678. } else if (b === 42) {
  25679. channel.ccTR();
  25680. } else if (b === 43) {
  25681. channel.ccRTD();
  25682. } else if (b === 44) {
  25683. channel.ccEDM();
  25684. } else if (b === 45) {
  25685. channel.ccCR();
  25686. } else if (b === 46) {
  25687. channel.ccENM();
  25688. } else if (b === 47) {
  25689. channel.ccEOC();
  25690. }
  25691. } else {
  25692. channel.ccTO(b - 32);
  25693. }
  25694. this.currentChannel = chNr;
  25695. return true;
  25696. }
  25697. /**
  25698. * Parse midrow styling command
  25699. */
  25700. parseMidrow(a, b) {
  25701. let chNr = 0;
  25702. if ((a === 17 || a === 25) && b >= 32 && b <= 47) {
  25703. if (a === 17) {
  25704. chNr = 1;
  25705. } else {
  25706. chNr = 2;
  25707. }
  25708. if (chNr !== this.currentChannel) {
  25709. this.logger.log(0, "Mismatch channel in midrow parsing");
  25710. return false;
  25711. }
  25712. const channel = this.channels[chNr];
  25713. if (!channel) {
  25714. return false;
  25715. }
  25716. channel.ccMIDROW(b);
  25717. this.logger.log(3, () => "MIDROW (" + numArrayToHexArray([a, b]) + ")");
  25718. return true;
  25719. }
  25720. return false;
  25721. }
  25722. /**
  25723. * Parse Preable Access Codes (Table 53).
  25724. * @returns {Boolean} Tells if PAC found
  25725. */
  25726. parsePAC(a, b) {
  25727. let row;
  25728. const case1 = (a >= 17 && a <= 23 || a >= 25 && a <= 31) && b >= 64 && b <= 127;
  25729. const case2 = (a === 16 || a === 24) && b >= 64 && b <= 95;
  25730. if (!(case1 || case2)) {
  25731. return false;
  25732. }
  25733. const chNr = a <= 23 ? 1 : 2;
  25734. if (b >= 64 && b <= 95) {
  25735. row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
  25736. } else {
  25737. row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
  25738. }
  25739. const channel = this.channels[chNr];
  25740. if (!channel) {
  25741. return false;
  25742. }
  25743. channel.setPAC(this.interpretPAC(row, b));
  25744. this.currentChannel = chNr;
  25745. return true;
  25746. }
  25747. /**
  25748. * Interpret the second byte of the pac, and return the information.
  25749. * @returns pacData with style parameters
  25750. */
  25751. interpretPAC(row, byte) {
  25752. let pacIndex;
  25753. const pacData = {
  25754. color: null,
  25755. italics: false,
  25756. indent: null,
  25757. underline: false,
  25758. row
  25759. };
  25760. if (byte > 95) {
  25761. pacIndex = byte - 96;
  25762. } else {
  25763. pacIndex = byte - 64;
  25764. }
  25765. pacData.underline = (pacIndex & 1) === 1;
  25766. if (pacIndex <= 13) {
  25767. pacData.color = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "white"][Math.floor(pacIndex / 2)];
  25768. } else if (pacIndex <= 15) {
  25769. pacData.italics = true;
  25770. pacData.color = "white";
  25771. } else {
  25772. pacData.indent = Math.floor((pacIndex - 16) / 2) * 4;
  25773. }
  25774. return pacData;
  25775. }
  25776. /**
  25777. * Parse characters.
  25778. * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
  25779. */
  25780. parseChars(a, b) {
  25781. let channelNr;
  25782. let charCodes = null;
  25783. let charCode1 = null;
  25784. if (a >= 25) {
  25785. channelNr = 2;
  25786. charCode1 = a - 8;
  25787. } else {
  25788. channelNr = 1;
  25789. charCode1 = a;
  25790. }
  25791. if (charCode1 >= 17 && charCode1 <= 19) {
  25792. let oneCode;
  25793. if (charCode1 === 17) {
  25794. oneCode = b + 80;
  25795. } else if (charCode1 === 18) {
  25796. oneCode = b + 112;
  25797. } else {
  25798. oneCode = b + 144;
  25799. }
  25800. this.logger.log(2, () => "Special char '" + getCharForByte(oneCode) + "' in channel " + channelNr);
  25801. charCodes = [oneCode];
  25802. } else if (a >= 32 && a <= 127) {
  25803. charCodes = b === 0 ? [a] : [a, b];
  25804. }
  25805. if (charCodes) {
  25806. this.logger.log(3, () => "Char codes = " + numArrayToHexArray(charCodes).join(","));
  25807. }
  25808. return charCodes;
  25809. }
  25810. /**
  25811. * Parse extended background attributes as well as new foreground color black.
  25812. * @returns True if background attributes are found
  25813. */
  25814. parseBackgroundAttributes(a, b) {
  25815. const case1 = (a === 16 || a === 24) && b >= 32 && b <= 47;
  25816. const case2 = (a === 23 || a === 31) && b >= 45 && b <= 47;
  25817. if (!(case1 || case2)) {
  25818. return false;
  25819. }
  25820. let index;
  25821. const bkgData = {};
  25822. if (a === 16 || a === 24) {
  25823. index = Math.floor((b - 32) / 2);
  25824. bkgData.background = backgroundColors[index];
  25825. if (b % 2 === 1) {
  25826. bkgData.background = bkgData.background + "_semi";
  25827. }
  25828. } else if (b === 45) {
  25829. bkgData.background = "transparent";
  25830. } else {
  25831. bkgData.foreground = "black";
  25832. if (b === 47) {
  25833. bkgData.underline = true;
  25834. }
  25835. }
  25836. const chNr = a <= 23 ? 1 : 2;
  25837. const channel = this.channels[chNr];
  25838. channel.setBkgData(bkgData);
  25839. return true;
  25840. }
  25841. /**
  25842. * Reset state of parser and its channels.
  25843. */
  25844. reset() {
  25845. for (let i = 0; i < Object.keys(this.channels).length; i++) {
  25846. const channel = this.channels[i];
  25847. if (channel) {
  25848. channel.reset();
  25849. }
  25850. }
  25851. setLastCmd(null, null, this.cmdHistory);
  25852. }
  25853. /**
  25854. * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
  25855. */
  25856. cueSplitAtTime(t) {
  25857. for (let i = 0; i < this.channels.length; i++) {
  25858. const channel = this.channels[i];
  25859. if (channel) {
  25860. channel.cueSplitAtTime(t);
  25861. }
  25862. }
  25863. }
  25864. };
  25865. function setLastCmd(a, b, cmdHistory) {
  25866. cmdHistory.a = a;
  25867. cmdHistory.b = b;
  25868. }
  25869. function hasCmdRepeated(a, b, cmdHistory) {
  25870. return cmdHistory.a === a && cmdHistory.b === b;
  25871. }
  25872. function createCmdHistory() {
  25873. return {
  25874. a: null,
  25875. b: null
  25876. };
  25877. }
  25878. var VTTCue = function() {
  25879. if (optionalSelf != null && optionalSelf.VTTCue) {
  25880. return self.VTTCue;
  25881. }
  25882. const AllowedDirections = ["", "lr", "rl"];
  25883. const AllowedAlignments = ["start", "middle", "end", "left", "right"];
  25884. function isAllowedValue(allowed, value) {
  25885. if (typeof value !== "string") {
  25886. return false;
  25887. }
  25888. if (!Array.isArray(allowed)) {
  25889. return false;
  25890. }
  25891. const lcValue = value.toLowerCase();
  25892. if (~allowed.indexOf(lcValue)) {
  25893. return lcValue;
  25894. }
  25895. return false;
  25896. }
  25897. function findDirectionSetting(value) {
  25898. return isAllowedValue(AllowedDirections, value);
  25899. }
  25900. function findAlignSetting(value) {
  25901. return isAllowedValue(AllowedAlignments, value);
  25902. }
  25903. function extend(obj, ...rest) {
  25904. let i = 1;
  25905. for (; i < arguments.length; i++) {
  25906. const cobj = arguments[i];
  25907. for (const p in cobj) {
  25908. obj[p] = cobj[p];
  25909. }
  25910. }
  25911. return obj;
  25912. }
  25913. function VTTCue2(startTime, endTime, text) {
  25914. const cue = this;
  25915. const baseObj = {
  25916. enumerable: true
  25917. };
  25918. cue.hasBeenReset = false;
  25919. let _id = "";
  25920. let _pauseOnExit = false;
  25921. let _startTime = startTime;
  25922. let _endTime = endTime;
  25923. let _text = text;
  25924. let _region = null;
  25925. let _vertical = "";
  25926. let _snapToLines = true;
  25927. let _line = "auto";
  25928. let _lineAlign = "start";
  25929. let _position = 50;
  25930. let _positionAlign = "middle";
  25931. let _size = 50;
  25932. let _align = "middle";
  25933. Object.defineProperty(cue, "id", extend({}, baseObj, {
  25934. get: function() {
  25935. return _id;
  25936. },
  25937. set: function(value) {
  25938. _id = "" + value;
  25939. }
  25940. }));
  25941. Object.defineProperty(cue, "pauseOnExit", extend({}, baseObj, {
  25942. get: function() {
  25943. return _pauseOnExit;
  25944. },
  25945. set: function(value) {
  25946. _pauseOnExit = !!value;
  25947. }
  25948. }));
  25949. Object.defineProperty(cue, "startTime", extend({}, baseObj, {
  25950. get: function() {
  25951. return _startTime;
  25952. },
  25953. set: function(value) {
  25954. if (typeof value !== "number") {
  25955. throw new TypeError("Start time must be set to a number.");
  25956. }
  25957. _startTime = value;
  25958. this.hasBeenReset = true;
  25959. }
  25960. }));
  25961. Object.defineProperty(cue, "endTime", extend({}, baseObj, {
  25962. get: function() {
  25963. return _endTime;
  25964. },
  25965. set: function(value) {
  25966. if (typeof value !== "number") {
  25967. throw new TypeError("End time must be set to a number.");
  25968. }
  25969. _endTime = value;
  25970. this.hasBeenReset = true;
  25971. }
  25972. }));
  25973. Object.defineProperty(cue, "text", extend({}, baseObj, {
  25974. get: function() {
  25975. return _text;
  25976. },
  25977. set: function(value) {
  25978. _text = "" + value;
  25979. this.hasBeenReset = true;
  25980. }
  25981. }));
  25982. Object.defineProperty(cue, "region", extend({}, baseObj, {
  25983. get: function() {
  25984. return _region;
  25985. },
  25986. set: function(value) {
  25987. _region = value;
  25988. this.hasBeenReset = true;
  25989. }
  25990. }));
  25991. Object.defineProperty(cue, "vertical", extend({}, baseObj, {
  25992. get: function() {
  25993. return _vertical;
  25994. },
  25995. set: function(value) {
  25996. const setting = findDirectionSetting(value);
  25997. if (setting === false) {
  25998. throw new SyntaxError("An invalid or illegal string was specified.");
  25999. }
  26000. _vertical = setting;
  26001. this.hasBeenReset = true;
  26002. }
  26003. }));
  26004. Object.defineProperty(cue, "snapToLines", extend({}, baseObj, {
  26005. get: function() {
  26006. return _snapToLines;
  26007. },
  26008. set: function(value) {
  26009. _snapToLines = !!value;
  26010. this.hasBeenReset = true;
  26011. }
  26012. }));
  26013. Object.defineProperty(cue, "line", extend({}, baseObj, {
  26014. get: function() {
  26015. return _line;
  26016. },
  26017. set: function(value) {
  26018. if (typeof value !== "number" && value !== "auto") {
  26019. throw new SyntaxError("An invalid number or illegal string was specified.");
  26020. }
  26021. _line = value;
  26022. this.hasBeenReset = true;
  26023. }
  26024. }));
  26025. Object.defineProperty(cue, "lineAlign", extend({}, baseObj, {
  26026. get: function() {
  26027. return _lineAlign;
  26028. },
  26029. set: function(value) {
  26030. const setting = findAlignSetting(value);
  26031. if (!setting) {
  26032. throw new SyntaxError("An invalid or illegal string was specified.");
  26033. }
  26034. _lineAlign = setting;
  26035. this.hasBeenReset = true;
  26036. }
  26037. }));
  26038. Object.defineProperty(cue, "position", extend({}, baseObj, {
  26039. get: function() {
  26040. return _position;
  26041. },
  26042. set: function(value) {
  26043. if (value < 0 || value > 100) {
  26044. throw new Error("Position must be between 0 and 100.");
  26045. }
  26046. _position = value;
  26047. this.hasBeenReset = true;
  26048. }
  26049. }));
  26050. Object.defineProperty(cue, "positionAlign", extend({}, baseObj, {
  26051. get: function() {
  26052. return _positionAlign;
  26053. },
  26054. set: function(value) {
  26055. const setting = findAlignSetting(value);
  26056. if (!setting) {
  26057. throw new SyntaxError("An invalid or illegal string was specified.");
  26058. }
  26059. _positionAlign = setting;
  26060. this.hasBeenReset = true;
  26061. }
  26062. }));
  26063. Object.defineProperty(cue, "size", extend({}, baseObj, {
  26064. get: function() {
  26065. return _size;
  26066. },
  26067. set: function(value) {
  26068. if (value < 0 || value > 100) {
  26069. throw new Error("Size must be between 0 and 100.");
  26070. }
  26071. _size = value;
  26072. this.hasBeenReset = true;
  26073. }
  26074. }));
  26075. Object.defineProperty(cue, "align", extend({}, baseObj, {
  26076. get: function() {
  26077. return _align;
  26078. },
  26079. set: function(value) {
  26080. const setting = findAlignSetting(value);
  26081. if (!setting) {
  26082. throw new SyntaxError("An invalid or illegal string was specified.");
  26083. }
  26084. _align = setting;
  26085. this.hasBeenReset = true;
  26086. }
  26087. }));
  26088. cue.displayState = void 0;
  26089. }
  26090. VTTCue2.prototype.getCueAsHTML = function() {
  26091. const WebVTT = self.WebVTT;
  26092. return WebVTT.convertCueToDOMTree(self, this.text);
  26093. };
  26094. return VTTCue2;
  26095. }();
  26096. var StringDecoder = class {
  26097. decode(data, options) {
  26098. if (!data) {
  26099. return "";
  26100. }
  26101. if (typeof data !== "string") {
  26102. throw new Error("Error - expected string data.");
  26103. }
  26104. return decodeURIComponent(encodeURIComponent(data));
  26105. }
  26106. };
  26107. function parseTimeStamp(input) {
  26108. function computeSeconds(h, m2, s, f) {
  26109. return (h | 0) * 3600 + (m2 | 0) * 60 + (s | 0) + parseFloat(f || 0);
  26110. }
  26111. const m = input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);
  26112. if (!m) {
  26113. return null;
  26114. }
  26115. if (parseFloat(m[2]) > 59) {
  26116. return computeSeconds(m[2], m[3], 0, m[4]);
  26117. }
  26118. return computeSeconds(m[1], m[2], m[3], m[4]);
  26119. }
  26120. var Settings = class {
  26121. constructor() {
  26122. this.values = /* @__PURE__ */ Object.create(null);
  26123. }
  26124. // Only accept the first assignment to any key.
  26125. set(k, v) {
  26126. if (!this.get(k) && v !== "") {
  26127. this.values[k] = v;
  26128. }
  26129. }
  26130. // Return the value for a key, or a default value.
  26131. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  26132. // a number of possible default values as properties where 'defaultKey' is
  26133. // the key of the property that will be chosen; otherwise it's assumed to be
  26134. // a single value.
  26135. get(k, dflt, defaultKey) {
  26136. if (defaultKey) {
  26137. return this.has(k) ? this.values[k] : dflt[defaultKey];
  26138. }
  26139. return this.has(k) ? this.values[k] : dflt;
  26140. }
  26141. // Check whether we have a value for a key.
  26142. has(k) {
  26143. return k in this.values;
  26144. }
  26145. // Accept a setting if its one of the given alternatives.
  26146. alt(k, v, a) {
  26147. for (let n = 0; n < a.length; ++n) {
  26148. if (v === a[n]) {
  26149. this.set(k, v);
  26150. break;
  26151. }
  26152. }
  26153. }
  26154. // Accept a setting if its a valid (signed) integer.
  26155. integer(k, v) {
  26156. if (/^-?\d+$/.test(v)) {
  26157. this.set(k, parseInt(v, 10));
  26158. }
  26159. }
  26160. // Accept a setting if its a valid percentage.
  26161. percent(k, v) {
  26162. if (/^([\d]{1,3})(\.[\d]*)?%$/.test(v)) {
  26163. const percent = parseFloat(v);
  26164. if (percent >= 0 && percent <= 100) {
  26165. this.set(k, percent);
  26166. return true;
  26167. }
  26168. }
  26169. return false;
  26170. }
  26171. };
  26172. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  26173. const groups = groupDelim ? input.split(groupDelim) : [input];
  26174. for (const i in groups) {
  26175. if (typeof groups[i] !== "string") {
  26176. continue;
  26177. }
  26178. const kv = groups[i].split(keyValueDelim);
  26179. if (kv.length !== 2) {
  26180. continue;
  26181. }
  26182. const k = kv[0];
  26183. const v = kv[1];
  26184. callback(k, v);
  26185. }
  26186. }
  26187. var defaults = new VTTCue(0, 0, "");
  26188. var center = defaults.align === "middle" ? "middle" : "center";
  26189. function parseCue(input, cue, regionList) {
  26190. const oInput = input;
  26191. function consumeTimeStamp() {
  26192. const ts = parseTimeStamp(input);
  26193. if (ts === null) {
  26194. throw new Error("Malformed timestamp: " + oInput);
  26195. }
  26196. input = input.replace(/^[^\sa-zA-Z-]+/, "");
  26197. return ts;
  26198. }
  26199. function consumeCueSettings(input2, cue2) {
  26200. const settings = new Settings();
  26201. parseOptions(input2, function(k, v) {
  26202. let vals;
  26203. switch (k) {
  26204. case "region":
  26205. for (let i = regionList.length - 1; i >= 0; i--) {
  26206. if (regionList[i].id === v) {
  26207. settings.set(k, regionList[i].region);
  26208. break;
  26209. }
  26210. }
  26211. break;
  26212. case "vertical":
  26213. settings.alt(k, v, ["rl", "lr"]);
  26214. break;
  26215. case "line":
  26216. vals = v.split(",");
  26217. settings.integer(k, vals[0]);
  26218. if (settings.percent(k, vals[0])) {
  26219. settings.set("snapToLines", false);
  26220. }
  26221. settings.alt(k, vals[0], ["auto"]);
  26222. if (vals.length === 2) {
  26223. settings.alt("lineAlign", vals[1], ["start", center, "end"]);
  26224. }
  26225. break;
  26226. case "position":
  26227. vals = v.split(",");
  26228. settings.percent(k, vals[0]);
  26229. if (vals.length === 2) {
  26230. settings.alt("positionAlign", vals[1], ["start", center, "end", "line-left", "line-right", "auto"]);
  26231. }
  26232. break;
  26233. case "size":
  26234. settings.percent(k, v);
  26235. break;
  26236. case "align":
  26237. settings.alt(k, v, ["start", center, "end", "left", "right"]);
  26238. break;
  26239. }
  26240. }, /:/, /\s/);
  26241. cue2.region = settings.get("region", null);
  26242. cue2.vertical = settings.get("vertical", "");
  26243. let line = settings.get("line", "auto");
  26244. if (line === "auto" && defaults.line === -1) {
  26245. line = -1;
  26246. }
  26247. cue2.line = line;
  26248. cue2.lineAlign = settings.get("lineAlign", "start");
  26249. cue2.snapToLines = settings.get("snapToLines", true);
  26250. cue2.size = settings.get("size", 100);
  26251. cue2.align = settings.get("align", center);
  26252. let position = settings.get("position", "auto");
  26253. if (position === "auto" && defaults.position === 50) {
  26254. position = cue2.align === "start" || cue2.align === "left" ? 0 : cue2.align === "end" || cue2.align === "right" ? 100 : 50;
  26255. }
  26256. cue2.position = position;
  26257. }
  26258. function skipWhitespace() {
  26259. input = input.replace(/^\s+/, "");
  26260. }
  26261. skipWhitespace();
  26262. cue.startTime = consumeTimeStamp();
  26263. skipWhitespace();
  26264. if (input.slice(0, 3) !== "-->") {
  26265. throw new Error("Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
  26266. }
  26267. input = input.slice(3);
  26268. skipWhitespace();
  26269. cue.endTime = consumeTimeStamp();
  26270. skipWhitespace();
  26271. consumeCueSettings(input, cue);
  26272. }
  26273. function fixLineBreaks(input) {
  26274. return input.replace(/<br(?: \/)?>/gi, "\n");
  26275. }
  26276. var VTTParser = class {
  26277. constructor() {
  26278. this.state = "INITIAL";
  26279. this.buffer = "";
  26280. this.decoder = new StringDecoder();
  26281. this.regionList = [];
  26282. this.cue = null;
  26283. this.oncue = void 0;
  26284. this.onparsingerror = void 0;
  26285. this.onflush = void 0;
  26286. }
  26287. parse(data) {
  26288. const _this = this;
  26289. if (data) {
  26290. _this.buffer += _this.decoder.decode(data, {
  26291. stream: true
  26292. });
  26293. }
  26294. function collectNextLine() {
  26295. let buffer = _this.buffer;
  26296. let pos = 0;
  26297. buffer = fixLineBreaks(buffer);
  26298. while (pos < buffer.length && buffer[pos] !== "\r" && buffer[pos] !== "\n") {
  26299. ++pos;
  26300. }
  26301. const line = buffer.slice(0, pos);
  26302. if (buffer[pos] === "\r") {
  26303. ++pos;
  26304. }
  26305. if (buffer[pos] === "\n") {
  26306. ++pos;
  26307. }
  26308. _this.buffer = buffer.slice(pos);
  26309. return line;
  26310. }
  26311. function parseHeader2(input) {
  26312. parseOptions(input, function(k, v) {
  26313. }, /:/);
  26314. }
  26315. try {
  26316. let line = "";
  26317. if (_this.state === "INITIAL") {
  26318. if (!/\r\n|\n/.test(_this.buffer)) {
  26319. return this;
  26320. }
  26321. line = collectNextLine();
  26322. const m = line.match(/^()?WEBVTT([ \t].*)?$/);
  26323. if (!(m != null && m[0])) {
  26324. throw new Error("Malformed WebVTT signature.");
  26325. }
  26326. _this.state = "HEADER";
  26327. }
  26328. let alreadyCollectedLine = false;
  26329. while (_this.buffer) {
  26330. if (!/\r\n|\n/.test(_this.buffer)) {
  26331. return this;
  26332. }
  26333. if (!alreadyCollectedLine) {
  26334. line = collectNextLine();
  26335. } else {
  26336. alreadyCollectedLine = false;
  26337. }
  26338. switch (_this.state) {
  26339. case "HEADER":
  26340. if (/:/.test(line)) {
  26341. parseHeader2(line);
  26342. } else if (!line) {
  26343. _this.state = "ID";
  26344. }
  26345. continue;
  26346. case "NOTE":
  26347. if (!line) {
  26348. _this.state = "ID";
  26349. }
  26350. continue;
  26351. case "ID":
  26352. if (/^NOTE($|[ \t])/.test(line)) {
  26353. _this.state = "NOTE";
  26354. break;
  26355. }
  26356. if (!line) {
  26357. continue;
  26358. }
  26359. _this.cue = new VTTCue(0, 0, "");
  26360. _this.state = "CUE";
  26361. if (line.indexOf("-->") === -1) {
  26362. _this.cue.id = line;
  26363. continue;
  26364. }
  26365. case "CUE":
  26366. if (!_this.cue) {
  26367. _this.state = "BADCUE";
  26368. continue;
  26369. }
  26370. try {
  26371. parseCue(line, _this.cue, _this.regionList);
  26372. } catch (e) {
  26373. _this.cue = null;
  26374. _this.state = "BADCUE";
  26375. continue;
  26376. }
  26377. _this.state = "CUETEXT";
  26378. continue;
  26379. case "CUETEXT":
  26380. {
  26381. const hasSubstring = line.indexOf("-->") !== -1;
  26382. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  26383. if (_this.oncue && _this.cue) {
  26384. _this.oncue(_this.cue);
  26385. }
  26386. _this.cue = null;
  26387. _this.state = "ID";
  26388. continue;
  26389. }
  26390. if (_this.cue === null) {
  26391. continue;
  26392. }
  26393. if (_this.cue.text) {
  26394. _this.cue.text += "\n";
  26395. }
  26396. _this.cue.text += line;
  26397. }
  26398. continue;
  26399. case "BADCUE":
  26400. if (!line) {
  26401. _this.state = "ID";
  26402. }
  26403. }
  26404. }
  26405. } catch (e) {
  26406. if (_this.state === "CUETEXT" && _this.cue && _this.oncue) {
  26407. _this.oncue(_this.cue);
  26408. }
  26409. _this.cue = null;
  26410. _this.state = _this.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
  26411. }
  26412. return this;
  26413. }
  26414. flush() {
  26415. const _this = this;
  26416. try {
  26417. if (_this.cue || _this.state === "HEADER") {
  26418. _this.buffer += "\n\n";
  26419. _this.parse();
  26420. }
  26421. if (_this.state === "INITIAL" || _this.state === "BADWEBVTT") {
  26422. throw new Error("Malformed WebVTT signature.");
  26423. }
  26424. } catch (e) {
  26425. if (_this.onparsingerror) {
  26426. _this.onparsingerror(e);
  26427. }
  26428. }
  26429. if (_this.onflush) {
  26430. _this.onflush();
  26431. }
  26432. return this;
  26433. }
  26434. };
  26435. var LINEBREAKS = /\r\n|\n\r|\n|\r/g;
  26436. var startsWith = function startsWith2(inputString, searchString, position = 0) {
  26437. return inputString.slice(position, position + searchString.length) === searchString;
  26438. };
  26439. var cueString2millis = function cueString2millis2(timeString) {
  26440. let ts = parseInt(timeString.slice(-3));
  26441. const secs = parseInt(timeString.slice(-6, -4));
  26442. const mins = parseInt(timeString.slice(-9, -7));
  26443. const hours = timeString.length > 9 ? parseInt(timeString.substring(0, timeString.indexOf(":"))) : 0;
  26444. if (!isFiniteNumber(ts) || !isFiniteNumber(secs) || !isFiniteNumber(mins) || !isFiniteNumber(hours)) {
  26445. throw Error(`Malformed X-TIMESTAMP-MAP: Local:${timeString}`);
  26446. }
  26447. ts += 1e3 * secs;
  26448. ts += 60 * 1e3 * mins;
  26449. ts += 60 * 60 * 1e3 * hours;
  26450. return ts;
  26451. };
  26452. function generateCueId(startTime, endTime, text) {
  26453. return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);
  26454. }
  26455. var calculateOffset = function calculateOffset2(vttCCs, cc, presentationTime) {
  26456. let currCC = vttCCs[cc];
  26457. let prevCC = vttCCs[currCC.prevCC];
  26458. if (!prevCC || !prevCC.new && currCC.new) {
  26459. vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
  26460. currCC.new = false;
  26461. return;
  26462. }
  26463. while ((_prevCC = prevCC) != null && _prevCC.new) {
  26464. var _prevCC;
  26465. vttCCs.ccOffset += currCC.start - prevCC.start;
  26466. currCC.new = false;
  26467. currCC = prevCC;
  26468. prevCC = vttCCs[currCC.prevCC];
  26469. }
  26470. vttCCs.presentationOffset = presentationTime;
  26471. };
  26472. function parseWebVTT(vttByteArray, initPTS, vttCCs, cc, timeOffset, callBack, errorCallBack) {
  26473. const parser = new VTTParser();
  26474. const vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, "\n").split("\n");
  26475. const cues = [];
  26476. const init90kHz = initPTS ? toMpegTsClockFromTimescale(initPTS.baseTime, initPTS.timescale) : 0;
  26477. let cueTime = "00:00.000";
  26478. let timestampMapMPEGTS = 0;
  26479. let timestampMapLOCAL = 0;
  26480. let parsingError;
  26481. let inHeader = true;
  26482. parser.oncue = function(cue) {
  26483. const currCC = vttCCs[cc];
  26484. let cueOffset = vttCCs.ccOffset;
  26485. const webVttMpegTsMapOffset = (timestampMapMPEGTS - init90kHz) / 9e4;
  26486. if (currCC != null && currCC.new) {
  26487. if (timestampMapLOCAL !== void 0) {
  26488. cueOffset = vttCCs.ccOffset = currCC.start;
  26489. } else {
  26490. calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);
  26491. }
  26492. }
  26493. if (webVttMpegTsMapOffset) {
  26494. if (!initPTS) {
  26495. parsingError = new Error("Missing initPTS for VTT MPEGTS");
  26496. return;
  26497. }
  26498. cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;
  26499. }
  26500. const duration = cue.endTime - cue.startTime;
  26501. const startTime = normalizePts((cue.startTime + cueOffset - timestampMapLOCAL) * 9e4, timeOffset * 9e4) / 9e4;
  26502. cue.startTime = Math.max(startTime, 0);
  26503. cue.endTime = Math.max(startTime + duration, 0);
  26504. const text = cue.text.trim();
  26505. cue.text = decodeURIComponent(encodeURIComponent(text));
  26506. if (!cue.id) {
  26507. cue.id = generateCueId(cue.startTime, cue.endTime, text);
  26508. }
  26509. if (cue.endTime > 0) {
  26510. cues.push(cue);
  26511. }
  26512. };
  26513. parser.onparsingerror = function(error) {
  26514. parsingError = error;
  26515. };
  26516. parser.onflush = function() {
  26517. if (parsingError) {
  26518. errorCallBack(parsingError);
  26519. return;
  26520. }
  26521. callBack(cues);
  26522. };
  26523. vttLines.forEach((line) => {
  26524. if (inHeader) {
  26525. if (startsWith(line, "X-TIMESTAMP-MAP=")) {
  26526. inHeader = false;
  26527. line.slice(16).split(",").forEach((timestamp) => {
  26528. if (startsWith(timestamp, "LOCAL:")) {
  26529. cueTime = timestamp.slice(6);
  26530. } else if (startsWith(timestamp, "MPEGTS:")) {
  26531. timestampMapMPEGTS = parseInt(timestamp.slice(7));
  26532. }
  26533. });
  26534. try {
  26535. timestampMapLOCAL = cueString2millis(cueTime) / 1e3;
  26536. } catch (error) {
  26537. parsingError = error;
  26538. }
  26539. return;
  26540. } else if (line === "") {
  26541. inHeader = false;
  26542. }
  26543. }
  26544. parser.parse(line + "\n");
  26545. });
  26546. parser.flush();
  26547. }
  26548. var IMSC1_CODEC = "stpp.ttml.im1t";
  26549. var HMSF_REGEX = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/;
  26550. var TIME_UNIT_REGEX = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/;
  26551. var textAlignToLineAlign = {
  26552. left: "start",
  26553. center: "center",
  26554. right: "end",
  26555. start: "start",
  26556. end: "end"
  26557. };
  26558. function parseIMSC1(payload, initPTS, callBack, errorCallBack) {
  26559. const results = findBox(new Uint8Array(payload), ["mdat"]);
  26560. if (results.length === 0) {
  26561. errorCallBack(new Error("Could not parse IMSC1 mdat"));
  26562. return;
  26563. }
  26564. const ttmlList = results.map((mdat) => utf8ArrayToStr(mdat));
  26565. const syncTime = toTimescaleFromScale(initPTS.baseTime, 1, initPTS.timescale);
  26566. try {
  26567. ttmlList.forEach((ttml) => callBack(parseTTML(ttml, syncTime)));
  26568. } catch (error) {
  26569. errorCallBack(error);
  26570. }
  26571. }
  26572. function parseTTML(ttml, syncTime) {
  26573. const parser = new DOMParser();
  26574. const xmlDoc = parser.parseFromString(ttml, "text/xml");
  26575. const tt = xmlDoc.getElementsByTagName("tt")[0];
  26576. if (!tt) {
  26577. throw new Error("Invalid ttml");
  26578. }
  26579. const defaultRateInfo = {
  26580. frameRate: 30,
  26581. subFrameRate: 1,
  26582. frameRateMultiplier: 0,
  26583. tickRate: 0
  26584. };
  26585. const rateInfo = Object.keys(defaultRateInfo).reduce((result, key) => {
  26586. result[key] = tt.getAttribute(`ttp:${key}`) || defaultRateInfo[key];
  26587. return result;
  26588. }, {});
  26589. const trim = tt.getAttribute("xml:space") !== "preserve";
  26590. const styleElements = collectionToDictionary(getElementCollection(tt, "styling", "style"));
  26591. const regionElements = collectionToDictionary(getElementCollection(tt, "layout", "region"));
  26592. const cueElements = getElementCollection(tt, "body", "[begin]");
  26593. return [].map.call(cueElements, (cueElement) => {
  26594. const cueText = getTextContent(cueElement, trim);
  26595. if (!cueText || !cueElement.hasAttribute("begin")) {
  26596. return null;
  26597. }
  26598. const startTime = parseTtmlTime(cueElement.getAttribute("begin"), rateInfo);
  26599. const duration = parseTtmlTime(cueElement.getAttribute("dur"), rateInfo);
  26600. let endTime = parseTtmlTime(cueElement.getAttribute("end"), rateInfo);
  26601. if (startTime === null) {
  26602. throw timestampParsingError(cueElement);
  26603. }
  26604. if (endTime === null) {
  26605. if (duration === null) {
  26606. throw timestampParsingError(cueElement);
  26607. }
  26608. endTime = startTime + duration;
  26609. }
  26610. const cue = new VTTCue(startTime - syncTime, endTime - syncTime, cueText);
  26611. cue.id = generateCueId(cue.startTime, cue.endTime, cue.text);
  26612. const region = regionElements[cueElement.getAttribute("region")];
  26613. const style = styleElements[cueElement.getAttribute("style")];
  26614. const styles = getTtmlStyles(region, style, styleElements);
  26615. const {
  26616. textAlign
  26617. } = styles;
  26618. if (textAlign) {
  26619. const lineAlign = textAlignToLineAlign[textAlign];
  26620. if (lineAlign) {
  26621. cue.lineAlign = lineAlign;
  26622. }
  26623. cue.align = textAlign;
  26624. }
  26625. _extends(cue, styles);
  26626. return cue;
  26627. }).filter((cue) => cue !== null);
  26628. }
  26629. function getElementCollection(fromElement, parentName, childName) {
  26630. const parent = fromElement.getElementsByTagName(parentName)[0];
  26631. if (parent) {
  26632. return [].slice.call(parent.querySelectorAll(childName));
  26633. }
  26634. return [];
  26635. }
  26636. function collectionToDictionary(elementsWithId) {
  26637. return elementsWithId.reduce((dict, element) => {
  26638. const id = element.getAttribute("xml:id");
  26639. if (id) {
  26640. dict[id] = element;
  26641. }
  26642. return dict;
  26643. }, {});
  26644. }
  26645. function getTextContent(element, trim) {
  26646. return [].slice.call(element.childNodes).reduce((str, node, i) => {
  26647. var _node$childNodes;
  26648. if (node.nodeName === "br" && i) {
  26649. return str + "\n";
  26650. }
  26651. if ((_node$childNodes = node.childNodes) != null && _node$childNodes.length) {
  26652. return getTextContent(node, trim);
  26653. } else if (trim) {
  26654. return str + node.textContent.trim().replace(/\s+/g, " ");
  26655. }
  26656. return str + node.textContent;
  26657. }, "");
  26658. }
  26659. function getTtmlStyles(region, style, styleElements) {
  26660. const ttsNs = "http://www.w3.org/ns/ttml#styling";
  26661. let regionStyle = null;
  26662. const styleAttributes = [
  26663. "displayAlign",
  26664. "textAlign",
  26665. "color",
  26666. "backgroundColor",
  26667. "fontSize",
  26668. "fontFamily"
  26669. // 'fontWeight',
  26670. // 'lineHeight',
  26671. // 'wrapOption',
  26672. // 'fontStyle',
  26673. // 'direction',
  26674. // 'writingMode'
  26675. ];
  26676. const regionStyleName = region != null && region.hasAttribute("style") ? region.getAttribute("style") : null;
  26677. if (regionStyleName && styleElements.hasOwnProperty(regionStyleName)) {
  26678. regionStyle = styleElements[regionStyleName];
  26679. }
  26680. return styleAttributes.reduce((styles, name) => {
  26681. const value = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name) || getAttributeNS(regionStyle, ttsNs, name);
  26682. if (value) {
  26683. styles[name] = value;
  26684. }
  26685. return styles;
  26686. }, {});
  26687. }
  26688. function getAttributeNS(element, ns, name) {
  26689. if (!element) {
  26690. return null;
  26691. }
  26692. return element.hasAttributeNS(ns, name) ? element.getAttributeNS(ns, name) : null;
  26693. }
  26694. function timestampParsingError(node) {
  26695. return new Error(`Could not parse ttml timestamp ${node}`);
  26696. }
  26697. function parseTtmlTime(timeAttributeValue, rateInfo) {
  26698. if (!timeAttributeValue) {
  26699. return null;
  26700. }
  26701. let seconds = parseTimeStamp(timeAttributeValue);
  26702. if (seconds === null) {
  26703. if (HMSF_REGEX.test(timeAttributeValue)) {
  26704. seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);
  26705. } else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {
  26706. seconds = parseTimeUnits(timeAttributeValue, rateInfo);
  26707. }
  26708. }
  26709. return seconds;
  26710. }
  26711. function parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) {
  26712. const m = HMSF_REGEX.exec(timeAttributeValue);
  26713. const frames = (m[4] | 0) + (m[5] | 0) / rateInfo.subFrameRate;
  26714. return (m[1] | 0) * 3600 + (m[2] | 0) * 60 + (m[3] | 0) + frames / rateInfo.frameRate;
  26715. }
  26716. function parseTimeUnits(timeAttributeValue, rateInfo) {
  26717. const m = TIME_UNIT_REGEX.exec(timeAttributeValue);
  26718. const value = Number(m[1]);
  26719. const unit = m[2];
  26720. switch (unit) {
  26721. case "h":
  26722. return value * 3600;
  26723. case "m":
  26724. return value * 60;
  26725. case "ms":
  26726. return value * 1e3;
  26727. case "f":
  26728. return value / rateInfo.frameRate;
  26729. case "t":
  26730. return value / rateInfo.tickRate;
  26731. }
  26732. return value;
  26733. }
  26734. var OutputFilter = class {
  26735. constructor(timelineController, trackName) {
  26736. this.timelineController = void 0;
  26737. this.cueRanges = [];
  26738. this.trackName = void 0;
  26739. this.startTime = null;
  26740. this.endTime = null;
  26741. this.screen = null;
  26742. this.timelineController = timelineController;
  26743. this.trackName = trackName;
  26744. }
  26745. dispatchCue() {
  26746. if (this.startTime === null) {
  26747. return;
  26748. }
  26749. this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);
  26750. this.startTime = null;
  26751. }
  26752. newCue(startTime, endTime, screen) {
  26753. if (this.startTime === null || this.startTime > startTime) {
  26754. this.startTime = startTime;
  26755. }
  26756. this.endTime = endTime;
  26757. this.screen = screen;
  26758. this.timelineController.createCaptionsTrack(this.trackName);
  26759. }
  26760. reset() {
  26761. this.cueRanges = [];
  26762. this.startTime = null;
  26763. }
  26764. };
  26765. var TimelineController = class {
  26766. constructor(hls) {
  26767. this.hls = void 0;
  26768. this.media = null;
  26769. this.config = void 0;
  26770. this.enabled = true;
  26771. this.Cues = void 0;
  26772. this.textTracks = [];
  26773. this.tracks = [];
  26774. this.initPTS = [];
  26775. this.unparsedVttFrags = [];
  26776. this.captionsTracks = {};
  26777. this.nonNativeCaptionsTracks = {};
  26778. this.cea608Parser1 = void 0;
  26779. this.cea608Parser2 = void 0;
  26780. this.lastCc = -1;
  26781. this.lastSn = -1;
  26782. this.lastPartIndex = -1;
  26783. this.prevCC = -1;
  26784. this.vttCCs = newVTTCCs();
  26785. this.captionsProperties = void 0;
  26786. this.hls = hls;
  26787. this.config = hls.config;
  26788. this.Cues = hls.config.cueHandler;
  26789. this.captionsProperties = {
  26790. textTrack1: {
  26791. label: this.config.captionsTextTrack1Label,
  26792. languageCode: this.config.captionsTextTrack1LanguageCode
  26793. },
  26794. textTrack2: {
  26795. label: this.config.captionsTextTrack2Label,
  26796. languageCode: this.config.captionsTextTrack2LanguageCode
  26797. },
  26798. textTrack3: {
  26799. label: this.config.captionsTextTrack3Label,
  26800. languageCode: this.config.captionsTextTrack3LanguageCode
  26801. },
  26802. textTrack4: {
  26803. label: this.config.captionsTextTrack4Label,
  26804. languageCode: this.config.captionsTextTrack4LanguageCode
  26805. }
  26806. };
  26807. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  26808. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  26809. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  26810. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  26811. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  26812. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  26813. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  26814. hls.on(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  26815. hls.on(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  26816. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  26817. hls.on(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  26818. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  26819. }
  26820. destroy() {
  26821. const {
  26822. hls
  26823. } = this;
  26824. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  26825. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  26826. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  26827. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  26828. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  26829. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  26830. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  26831. hls.off(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  26832. hls.off(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  26833. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  26834. hls.off(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  26835. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  26836. this.hls = this.config = this.media = null;
  26837. this.cea608Parser1 = this.cea608Parser2 = void 0;
  26838. }
  26839. initCea608Parsers() {
  26840. const channel1 = new OutputFilter(this, "textTrack1");
  26841. const channel2 = new OutputFilter(this, "textTrack2");
  26842. const channel3 = new OutputFilter(this, "textTrack3");
  26843. const channel4 = new OutputFilter(this, "textTrack4");
  26844. this.cea608Parser1 = new Cea608Parser(1, channel1, channel2);
  26845. this.cea608Parser2 = new Cea608Parser(3, channel3, channel4);
  26846. }
  26847. addCues(trackName, startTime, endTime, screen, cueRanges) {
  26848. let merged = false;
  26849. for (let i = cueRanges.length; i--; ) {
  26850. const cueRange = cueRanges[i];
  26851. const overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
  26852. if (overlap >= 0) {
  26853. cueRange[0] = Math.min(cueRange[0], startTime);
  26854. cueRange[1] = Math.max(cueRange[1], endTime);
  26855. merged = true;
  26856. if (overlap / (endTime - startTime) > 0.5) {
  26857. return;
  26858. }
  26859. }
  26860. }
  26861. if (!merged) {
  26862. cueRanges.push([startTime, endTime]);
  26863. }
  26864. if (this.config.renderTextTracksNatively) {
  26865. const track = this.captionsTracks[trackName];
  26866. this.Cues.newCue(track, startTime, endTime, screen);
  26867. } else {
  26868. const cues = this.Cues.newCue(null, startTime, endTime, screen);
  26869. this.hls.trigger(Events.CUES_PARSED, {
  26870. type: "captions",
  26871. cues,
  26872. track: trackName
  26873. });
  26874. }
  26875. }
  26876. // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
  26877. onInitPtsFound(event, {
  26878. frag,
  26879. id,
  26880. initPTS,
  26881. timescale,
  26882. trackId
  26883. }) {
  26884. const {
  26885. unparsedVttFrags
  26886. } = this;
  26887. if (id === PlaylistLevelType.MAIN) {
  26888. this.initPTS[frag.cc] = {
  26889. baseTime: initPTS,
  26890. timescale,
  26891. trackId
  26892. };
  26893. }
  26894. if (unparsedVttFrags.length) {
  26895. this.unparsedVttFrags = [];
  26896. unparsedVttFrags.forEach((data) => {
  26897. if (this.initPTS[data.frag.cc]) {
  26898. this.onFragLoaded(Events.FRAG_LOADED, data);
  26899. } else {
  26900. this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  26901. success: false,
  26902. frag: data.frag,
  26903. error: new Error("Subtitle discontinuity domain does not match main")
  26904. });
  26905. }
  26906. });
  26907. }
  26908. }
  26909. getExistingTrack(label, language) {
  26910. const {
  26911. media
  26912. } = this;
  26913. if (media) {
  26914. for (let i = 0; i < media.textTracks.length; i++) {
  26915. const textTrack = media.textTracks[i];
  26916. if (canReuseVttTextTrack(textTrack, {
  26917. name: label,
  26918. lang: language,
  26919. characteristics: "transcribes-spoken-dialog,describes-music-and-sound"
  26920. })) {
  26921. return textTrack;
  26922. }
  26923. }
  26924. }
  26925. return null;
  26926. }
  26927. createCaptionsTrack(trackName) {
  26928. if (this.config.renderTextTracksNatively) {
  26929. this.createNativeTrack(trackName);
  26930. } else {
  26931. this.createNonNativeTrack(trackName);
  26932. }
  26933. }
  26934. createNativeTrack(trackName) {
  26935. if (this.captionsTracks[trackName]) {
  26936. return;
  26937. }
  26938. const {
  26939. captionsProperties,
  26940. captionsTracks,
  26941. media
  26942. } = this;
  26943. const {
  26944. label,
  26945. languageCode
  26946. } = captionsProperties[trackName];
  26947. const existingTrack = this.getExistingTrack(label, languageCode);
  26948. if (!existingTrack) {
  26949. const textTrack = this.createTextTrack("captions", label, languageCode);
  26950. if (textTrack) {
  26951. textTrack[trackName] = true;
  26952. captionsTracks[trackName] = textTrack;
  26953. }
  26954. } else {
  26955. captionsTracks[trackName] = existingTrack;
  26956. clearCurrentCues(captionsTracks[trackName]);
  26957. sendAddTrackEvent(captionsTracks[trackName], media);
  26958. }
  26959. }
  26960. createNonNativeTrack(trackName) {
  26961. if (this.nonNativeCaptionsTracks[trackName]) {
  26962. return;
  26963. }
  26964. const trackProperties = this.captionsProperties[trackName];
  26965. if (!trackProperties) {
  26966. return;
  26967. }
  26968. const label = trackProperties.label;
  26969. const track = {
  26970. _id: trackName,
  26971. label,
  26972. kind: "captions",
  26973. default: trackProperties.media ? !!trackProperties.media.default : false,
  26974. closedCaptions: trackProperties.media
  26975. };
  26976. this.nonNativeCaptionsTracks[trackName] = track;
  26977. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  26978. tracks: [track]
  26979. });
  26980. }
  26981. createTextTrack(kind, label, lang) {
  26982. const media = this.media;
  26983. if (!media) {
  26984. return;
  26985. }
  26986. return media.addTextTrack(kind, label, lang);
  26987. }
  26988. onMediaAttaching(event, data) {
  26989. this.media = data.media;
  26990. if (!data.mediaSource) {
  26991. this._cleanTracks();
  26992. }
  26993. }
  26994. onMediaDetaching(event, data) {
  26995. const transferringMedia = !!data.transferMedia;
  26996. this.media = null;
  26997. if (transferringMedia) {
  26998. return;
  26999. }
  27000. const {
  27001. captionsTracks
  27002. } = this;
  27003. Object.keys(captionsTracks).forEach((trackName) => {
  27004. clearCurrentCues(captionsTracks[trackName]);
  27005. delete captionsTracks[trackName];
  27006. });
  27007. this.nonNativeCaptionsTracks = {};
  27008. }
  27009. onManifestLoading() {
  27010. this.lastCc = -1;
  27011. this.lastSn = -1;
  27012. this.lastPartIndex = -1;
  27013. this.prevCC = -1;
  27014. this.vttCCs = newVTTCCs();
  27015. this._cleanTracks();
  27016. this.tracks = [];
  27017. this.captionsTracks = {};
  27018. this.nonNativeCaptionsTracks = {};
  27019. this.textTracks = [];
  27020. this.unparsedVttFrags = [];
  27021. this.initPTS = [];
  27022. if (this.cea608Parser1 && this.cea608Parser2) {
  27023. this.cea608Parser1.reset();
  27024. this.cea608Parser2.reset();
  27025. }
  27026. }
  27027. _cleanTracks() {
  27028. const {
  27029. media
  27030. } = this;
  27031. if (!media) {
  27032. return;
  27033. }
  27034. const textTracks = media.textTracks;
  27035. if (textTracks) {
  27036. for (let i = 0; i < textTracks.length; i++) {
  27037. clearCurrentCues(textTracks[i]);
  27038. }
  27039. }
  27040. }
  27041. onSubtitleTracksUpdated(event, data) {
  27042. const tracks = data.subtitleTracks || [];
  27043. const hasIMSC1 = tracks.some((track) => track.textCodec === IMSC1_CODEC);
  27044. if (this.config.enableWebVTT || hasIMSC1 && this.config.enableIMSC1) {
  27045. const listIsIdentical = subtitleOptionsIdentical(this.tracks, tracks);
  27046. if (listIsIdentical) {
  27047. this.tracks = tracks;
  27048. return;
  27049. }
  27050. this.textTracks = [];
  27051. this.tracks = tracks;
  27052. if (this.config.renderTextTracksNatively) {
  27053. const media = this.media;
  27054. const inUseTracks = media ? filterSubtitleTracks(media.textTracks) : null;
  27055. this.tracks.forEach((track, index) => {
  27056. let textTrack;
  27057. if (inUseTracks) {
  27058. let inUseTrack = null;
  27059. for (let i = 0; i < inUseTracks.length; i++) {
  27060. if (inUseTracks[i] && canReuseVttTextTrack(inUseTracks[i], track)) {
  27061. inUseTrack = inUseTracks[i];
  27062. inUseTracks[i] = null;
  27063. break;
  27064. }
  27065. }
  27066. if (inUseTrack) {
  27067. textTrack = inUseTrack;
  27068. }
  27069. }
  27070. if (textTrack) {
  27071. clearCurrentCues(textTrack);
  27072. } else {
  27073. const textTrackKind = captionsOrSubtitlesFromCharacteristics(track);
  27074. textTrack = this.createTextTrack(textTrackKind, track.name, track.lang);
  27075. if (textTrack) {
  27076. textTrack.mode = "disabled";
  27077. }
  27078. }
  27079. if (textTrack) {
  27080. this.textTracks.push(textTrack);
  27081. }
  27082. });
  27083. if (inUseTracks != null && inUseTracks.length) {
  27084. const unusedTextTracks = inUseTracks.filter((t) => t !== null).map((t) => t.label);
  27085. if (unusedTextTracks.length) {
  27086. this.hls.logger.warn(`Media element contains unused subtitle tracks: ${unusedTextTracks.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`);
  27087. }
  27088. }
  27089. } else if (this.tracks.length) {
  27090. const tracksList = this.tracks.map((track) => {
  27091. return {
  27092. label: track.name,
  27093. kind: track.type.toLowerCase(),
  27094. default: track.default,
  27095. subtitleTrack: track
  27096. };
  27097. });
  27098. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  27099. tracks: tracksList
  27100. });
  27101. }
  27102. }
  27103. }
  27104. onManifestLoaded(event, data) {
  27105. if (this.config.enableCEA708Captions && data.captions) {
  27106. data.captions.forEach((captionsTrack) => {
  27107. const instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);
  27108. if (!instreamIdMatch) {
  27109. return;
  27110. }
  27111. const trackName = `textTrack${instreamIdMatch[1]}`;
  27112. const trackProperties = this.captionsProperties[trackName];
  27113. if (!trackProperties) {
  27114. return;
  27115. }
  27116. trackProperties.label = captionsTrack.name;
  27117. if (captionsTrack.lang) {
  27118. trackProperties.languageCode = captionsTrack.lang;
  27119. }
  27120. trackProperties.media = captionsTrack;
  27121. });
  27122. }
  27123. }
  27124. closedCaptionsForLevel(frag) {
  27125. const level = this.hls.levels[frag.level];
  27126. return level == null ? void 0 : level.attrs["CLOSED-CAPTIONS"];
  27127. }
  27128. onFragLoading(event, data) {
  27129. if (this.enabled && data.frag.type === PlaylistLevelType.MAIN) {
  27130. var _data$part$index, _data$part;
  27131. const {
  27132. cea608Parser1,
  27133. cea608Parser2,
  27134. lastSn
  27135. } = this;
  27136. const {
  27137. cc,
  27138. sn
  27139. } = data.frag;
  27140. const partIndex = (_data$part$index = (_data$part = data.part) == null ? void 0 : _data$part.index) != null ? _data$part$index : -1;
  27141. if (cea608Parser1 && cea608Parser2) {
  27142. if (sn !== lastSn + 1 || sn === lastSn && partIndex !== this.lastPartIndex + 1 || cc !== this.lastCc) {
  27143. cea608Parser1.reset();
  27144. cea608Parser2.reset();
  27145. }
  27146. }
  27147. this.lastCc = cc;
  27148. this.lastSn = sn;
  27149. this.lastPartIndex = partIndex;
  27150. }
  27151. }
  27152. onFragLoaded(event, data) {
  27153. const {
  27154. frag,
  27155. payload
  27156. } = data;
  27157. if (frag.type === PlaylistLevelType.SUBTITLE) {
  27158. if (payload.byteLength) {
  27159. const decryptData = frag.decryptdata;
  27160. const decrypted = "stats" in data;
  27161. if (decryptData == null || !decryptData.encrypted || decrypted) {
  27162. const trackPlaylistMedia = this.tracks[frag.level];
  27163. const vttCCs = this.vttCCs;
  27164. if (!vttCCs[frag.cc]) {
  27165. vttCCs[frag.cc] = {
  27166. start: frag.start,
  27167. prevCC: this.prevCC,
  27168. new: true
  27169. };
  27170. this.prevCC = frag.cc;
  27171. }
  27172. if (trackPlaylistMedia && trackPlaylistMedia.textCodec === IMSC1_CODEC) {
  27173. this._parseIMSC1(frag, payload);
  27174. } else {
  27175. this._parseVTTs(data);
  27176. }
  27177. }
  27178. } else {
  27179. this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  27180. success: false,
  27181. frag,
  27182. error: new Error("Empty subtitle payload")
  27183. });
  27184. }
  27185. }
  27186. }
  27187. _parseIMSC1(frag, payload) {
  27188. const hls = this.hls;
  27189. parseIMSC1(payload, this.initPTS[frag.cc], (cues) => {
  27190. this._appendCues(cues, frag.level);
  27191. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  27192. success: true,
  27193. frag
  27194. });
  27195. }, (error) => {
  27196. hls.logger.log(`Failed to parse IMSC1: ${error}`);
  27197. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  27198. success: false,
  27199. frag,
  27200. error
  27201. });
  27202. });
  27203. }
  27204. _parseVTTs(data) {
  27205. var _frag$initSegment;
  27206. const {
  27207. frag,
  27208. payload
  27209. } = data;
  27210. const {
  27211. initPTS,
  27212. unparsedVttFrags
  27213. } = this;
  27214. const maxAvCC = initPTS.length - 1;
  27215. if (!initPTS[frag.cc] && maxAvCC === -1) {
  27216. unparsedVttFrags.push(data);
  27217. return;
  27218. }
  27219. const hls = this.hls;
  27220. const payloadWebVTT = (_frag$initSegment = frag.initSegment) != null && _frag$initSegment.data ? appendUint8Array(frag.initSegment.data, new Uint8Array(payload)).buffer : payload;
  27221. parseWebVTT(payloadWebVTT, this.initPTS[frag.cc], this.vttCCs, frag.cc, frag.start, (cues) => {
  27222. this._appendCues(cues, frag.level);
  27223. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  27224. success: true,
  27225. frag
  27226. });
  27227. }, (error) => {
  27228. const missingInitPTS = error.message === "Missing initPTS for VTT MPEGTS";
  27229. if (missingInitPTS) {
  27230. unparsedVttFrags.push(data);
  27231. } else {
  27232. this._fallbackToIMSC1(frag, payload);
  27233. }
  27234. hls.logger.log(`Failed to parse VTT cue: ${error}`);
  27235. if (missingInitPTS && maxAvCC > frag.cc) {
  27236. return;
  27237. }
  27238. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  27239. success: false,
  27240. frag,
  27241. error
  27242. });
  27243. });
  27244. }
  27245. _fallbackToIMSC1(frag, payload) {
  27246. const trackPlaylistMedia = this.tracks[frag.level];
  27247. if (!trackPlaylistMedia.textCodec) {
  27248. parseIMSC1(payload, this.initPTS[frag.cc], () => {
  27249. trackPlaylistMedia.textCodec = IMSC1_CODEC;
  27250. this._parseIMSC1(frag, payload);
  27251. }, () => {
  27252. trackPlaylistMedia.textCodec = "wvtt";
  27253. });
  27254. }
  27255. }
  27256. _appendCues(cues, fragLevel) {
  27257. const hls = this.hls;
  27258. if (this.config.renderTextTracksNatively) {
  27259. const textTrack = this.textTracks[fragLevel];
  27260. if (!textTrack || textTrack.mode === "disabled") {
  27261. return;
  27262. }
  27263. cues.forEach((cue) => addCueToTrack(textTrack, cue));
  27264. } else {
  27265. const currentTrack = this.tracks[fragLevel];
  27266. if (!currentTrack) {
  27267. return;
  27268. }
  27269. const track = currentTrack.default ? "default" : "subtitles" + fragLevel;
  27270. hls.trigger(Events.CUES_PARSED, {
  27271. type: "subtitles",
  27272. cues,
  27273. track
  27274. });
  27275. }
  27276. }
  27277. onFragDecrypted(event, data) {
  27278. const {
  27279. frag
  27280. } = data;
  27281. if (frag.type === PlaylistLevelType.SUBTITLE) {
  27282. this.onFragLoaded(Events.FRAG_LOADED, data);
  27283. }
  27284. }
  27285. onSubtitleTracksCleared() {
  27286. this.tracks = [];
  27287. this.captionsTracks = {};
  27288. }
  27289. onFragParsingUserdata(event, data) {
  27290. if (!this.enabled || !this.config.enableCEA708Captions) {
  27291. return;
  27292. }
  27293. const {
  27294. frag,
  27295. samples
  27296. } = data;
  27297. if (frag.type === PlaylistLevelType.MAIN && this.closedCaptionsForLevel(frag) === "NONE") {
  27298. return;
  27299. }
  27300. for (let i = 0; i < samples.length; i++) {
  27301. const ccBytes = samples[i].bytes;
  27302. if (ccBytes) {
  27303. if (!this.cea608Parser1) {
  27304. this.initCea608Parsers();
  27305. }
  27306. const ccdatas = this.extractCea608Data(ccBytes);
  27307. this.cea608Parser1.addData(samples[i].pts, ccdatas[0]);
  27308. this.cea608Parser2.addData(samples[i].pts, ccdatas[1]);
  27309. }
  27310. }
  27311. }
  27312. onBufferFlushing(event, {
  27313. startOffset,
  27314. endOffset,
  27315. endOffsetSubtitles,
  27316. type
  27317. }) {
  27318. const {
  27319. media
  27320. } = this;
  27321. if (!media || media.currentTime < endOffset) {
  27322. return;
  27323. }
  27324. if (!type || type === "video") {
  27325. const {
  27326. captionsTracks
  27327. } = this;
  27328. Object.keys(captionsTracks).forEach((trackName) => removeCuesInRange(captionsTracks[trackName], startOffset, endOffset));
  27329. }
  27330. if (this.config.renderTextTracksNatively) {
  27331. if (startOffset === 0 && endOffsetSubtitles !== void 0) {
  27332. const {
  27333. textTracks
  27334. } = this;
  27335. Object.keys(textTracks).forEach((trackName) => removeCuesInRange(textTracks[trackName], startOffset, endOffsetSubtitles));
  27336. }
  27337. }
  27338. }
  27339. extractCea608Data(byteArray) {
  27340. const actualCCBytes = [[], []];
  27341. const count = byteArray[0] & 31;
  27342. let position = 2;
  27343. for (let j = 0; j < count; j++) {
  27344. const tmpByte = byteArray[position++];
  27345. const ccbyte1 = 127 & byteArray[position++];
  27346. const ccbyte2 = 127 & byteArray[position++];
  27347. if (ccbyte1 === 0 && ccbyte2 === 0) {
  27348. continue;
  27349. }
  27350. const ccValid = (4 & tmpByte) !== 0;
  27351. if (ccValid) {
  27352. const ccType = 3 & tmpByte;
  27353. if (0 === ccType || 1 === ccType) {
  27354. actualCCBytes[ccType].push(ccbyte1);
  27355. actualCCBytes[ccType].push(ccbyte2);
  27356. }
  27357. }
  27358. }
  27359. return actualCCBytes;
  27360. }
  27361. };
  27362. function captionsOrSubtitlesFromCharacteristics(track) {
  27363. if (track.characteristics) {
  27364. if (/transcribes-spoken-dialog/gi.test(track.characteristics) && /describes-music-and-sound/gi.test(track.characteristics)) {
  27365. return "captions";
  27366. }
  27367. }
  27368. return "subtitles";
  27369. }
  27370. function canReuseVttTextTrack(inUseTrack, manifestTrack) {
  27371. return !!inUseTrack && inUseTrack.kind === captionsOrSubtitlesFromCharacteristics(manifestTrack) && subtitleTrackMatchesTextTrack(manifestTrack, inUseTrack);
  27372. }
  27373. function intersection(x1, x2, y1, y2) {
  27374. return Math.min(x2, y2) - Math.max(x1, y1);
  27375. }
  27376. function newVTTCCs() {
  27377. return {
  27378. ccOffset: 0,
  27379. presentationOffset: 0,
  27380. 0: {
  27381. start: 0,
  27382. prevCC: -1,
  27383. new: true
  27384. }
  27385. };
  27386. }
  27387. var WHITESPACE_CHAR = /\s/;
  27388. var Cues = {
  27389. newCue(track, startTime, endTime, captionScreen) {
  27390. const result = [];
  27391. let row;
  27392. let cue;
  27393. let indenting;
  27394. let indent;
  27395. let text;
  27396. const Cue = self.VTTCue || self.TextTrackCue;
  27397. for (let r = 0; r < captionScreen.rows.length; r++) {
  27398. row = captionScreen.rows[r];
  27399. indenting = true;
  27400. indent = 0;
  27401. text = "";
  27402. if (!row.isEmpty()) {
  27403. var _track$cues;
  27404. for (let c = 0; c < row.chars.length; c++) {
  27405. if (WHITESPACE_CHAR.test(row.chars[c].uchar) && indenting) {
  27406. indent++;
  27407. } else {
  27408. text += row.chars[c].uchar;
  27409. indenting = false;
  27410. }
  27411. }
  27412. row.cueStartTime = startTime;
  27413. if (startTime === endTime) {
  27414. endTime += 1e-4;
  27415. }
  27416. if (indent >= 16) {
  27417. indent--;
  27418. } else {
  27419. indent++;
  27420. }
  27421. const cueText = fixLineBreaks(text.trim());
  27422. const id = generateCueId(startTime, endTime, cueText);
  27423. if (!(track != null && (_track$cues = track.cues) != null && _track$cues.getCueById(id))) {
  27424. cue = new Cue(startTime, endTime, cueText);
  27425. cue.id = id;
  27426. cue.line = r + 1;
  27427. cue.align = "left";
  27428. cue.position = 10 + Math.min(80, Math.floor(indent * 8 / 32) * 10);
  27429. result.push(cue);
  27430. }
  27431. }
  27432. }
  27433. if (track && result.length) {
  27434. result.sort((cueA, cueB) => {
  27435. if (cueA.line === "auto" || cueB.line === "auto") {
  27436. return 0;
  27437. }
  27438. if (cueA.line > 8 && cueB.line > 8) {
  27439. return cueB.line - cueA.line;
  27440. }
  27441. return cueA.line - cueB.line;
  27442. });
  27443. result.forEach((cue2) => addCueToTrack(track, cue2));
  27444. }
  27445. return result;
  27446. }
  27447. };
  27448. function fetchSupported() {
  27449. if (
  27450. // @ts-ignore
  27451. self.fetch && self.AbortController && self.ReadableStream && self.Request
  27452. ) {
  27453. try {
  27454. new self.ReadableStream({});
  27455. return true;
  27456. } catch (e) {
  27457. }
  27458. }
  27459. return false;
  27460. }
  27461. var BYTERANGE = /(\d+)-(\d+)\/(\d+)/;
  27462. var FetchLoader = class {
  27463. constructor(config) {
  27464. this.fetchSetup = void 0;
  27465. this.requestTimeout = void 0;
  27466. this.request = null;
  27467. this.response = null;
  27468. this.controller = void 0;
  27469. this.context = null;
  27470. this.config = null;
  27471. this.callbacks = null;
  27472. this.stats = void 0;
  27473. this.loader = null;
  27474. this.fetchSetup = config.fetchSetup || getRequest;
  27475. this.controller = new self.AbortController();
  27476. this.stats = new LoadStats();
  27477. }
  27478. destroy() {
  27479. this.loader = this.callbacks = this.context = this.config = this.request = null;
  27480. this.abortInternal();
  27481. this.response = null;
  27482. this.fetchSetup = this.controller = this.stats = null;
  27483. }
  27484. abortInternal() {
  27485. if (this.controller && !this.stats.loading.end) {
  27486. this.stats.aborted = true;
  27487. this.controller.abort();
  27488. }
  27489. }
  27490. abort() {
  27491. var _this$callbacks;
  27492. this.abortInternal();
  27493. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  27494. this.callbacks.onAbort(this.stats, this.context, this.response);
  27495. }
  27496. }
  27497. load(context, config, callbacks) {
  27498. const stats = this.stats;
  27499. if (stats.loading.start) {
  27500. throw new Error("Loader can only be used once.");
  27501. }
  27502. stats.loading.start = self.performance.now();
  27503. const initParams = getRequestParameters(context, this.controller.signal);
  27504. const isArrayBuffer = context.responseType === "arraybuffer";
  27505. const LENGTH = isArrayBuffer ? "byteLength" : "length";
  27506. const {
  27507. maxTimeToFirstByteMs,
  27508. maxLoadTimeMs
  27509. } = config.loadPolicy;
  27510. this.context = context;
  27511. this.config = config;
  27512. this.callbacks = callbacks;
  27513. this.request = this.fetchSetup(context, initParams);
  27514. self.clearTimeout(this.requestTimeout);
  27515. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  27516. this.requestTimeout = self.setTimeout(() => {
  27517. if (this.callbacks) {
  27518. this.abortInternal();
  27519. this.callbacks.onTimeout(stats, context, this.response);
  27520. }
  27521. }, config.timeout);
  27522. const fetchPromise = isPromise(this.request) ? this.request.then(self.fetch) : self.fetch(this.request);
  27523. fetchPromise.then((response) => {
  27524. var _this$callbacks2;
  27525. this.response = this.loader = response;
  27526. const first = Math.max(self.performance.now(), stats.loading.start);
  27527. self.clearTimeout(this.requestTimeout);
  27528. config.timeout = maxLoadTimeMs;
  27529. this.requestTimeout = self.setTimeout(() => {
  27530. if (this.callbacks) {
  27531. this.abortInternal();
  27532. this.callbacks.onTimeout(stats, context, this.response);
  27533. }
  27534. }, maxLoadTimeMs - (first - stats.loading.start));
  27535. if (!response.ok) {
  27536. const {
  27537. status: status2,
  27538. statusText
  27539. } = response;
  27540. throw new FetchError(statusText || "fetch, bad network response", status2, response);
  27541. }
  27542. stats.loading.first = first;
  27543. stats.total = getContentLength(response.headers) || stats.total;
  27544. const onProgress = (_this$callbacks2 = this.callbacks) == null ? void 0 : _this$callbacks2.onProgress;
  27545. if (onProgress && isFiniteNumber(config.highWaterMark)) {
  27546. return this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
  27547. }
  27548. if (isArrayBuffer) {
  27549. return response.arrayBuffer();
  27550. }
  27551. if (context.responseType === "json") {
  27552. return response.json();
  27553. }
  27554. return response.text();
  27555. }).then((responseData) => {
  27556. var _this$callbacks3, _this$callbacks4;
  27557. const response = this.response;
  27558. if (!response) {
  27559. throw new Error("loader destroyed");
  27560. }
  27561. self.clearTimeout(this.requestTimeout);
  27562. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  27563. const total = responseData[LENGTH];
  27564. if (total) {
  27565. stats.loaded = stats.total = total;
  27566. }
  27567. const loaderResponse = {
  27568. url: response.url,
  27569. data: responseData,
  27570. code: response.status
  27571. };
  27572. const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  27573. if (onProgress && !isFiniteNumber(config.highWaterMark)) {
  27574. onProgress(stats, context, responseData, response);
  27575. }
  27576. (_this$callbacks4 = this.callbacks) == null || _this$callbacks4.onSuccess(loaderResponse, stats, context, response);
  27577. }).catch((error) => {
  27578. var _this$callbacks5;
  27579. self.clearTimeout(this.requestTimeout);
  27580. if (stats.aborted) {
  27581. return;
  27582. }
  27583. const code = !error ? 0 : error.code || 0;
  27584. const text = !error ? null : error.message;
  27585. (_this$callbacks5 = this.callbacks) == null || _this$callbacks5.onError({
  27586. code,
  27587. text
  27588. }, context, error ? error.details : null, stats);
  27589. });
  27590. }
  27591. getCacheAge() {
  27592. let result = null;
  27593. if (this.response) {
  27594. const ageHeader = this.response.headers.get("age");
  27595. result = ageHeader ? parseFloat(ageHeader) : null;
  27596. }
  27597. return result;
  27598. }
  27599. getResponseHeader(name) {
  27600. return this.response ? this.response.headers.get(name) : null;
  27601. }
  27602. loadProgressively(response, stats, context, highWaterMark = 0, onProgress) {
  27603. const chunkCache = new ChunkCache();
  27604. const reader = response.body.getReader();
  27605. const pump = () => {
  27606. return reader.read().then((data) => {
  27607. if (data.done) {
  27608. if (chunkCache.dataLength) {
  27609. onProgress(stats, context, chunkCache.flush().buffer, response);
  27610. }
  27611. return Promise.resolve(new ArrayBuffer(0));
  27612. }
  27613. const chunk = data.value;
  27614. const len = chunk.length;
  27615. stats.loaded += len;
  27616. if (len < highWaterMark || chunkCache.dataLength) {
  27617. chunkCache.push(chunk);
  27618. if (chunkCache.dataLength >= highWaterMark) {
  27619. onProgress(stats, context, chunkCache.flush().buffer, response);
  27620. }
  27621. } else {
  27622. onProgress(stats, context, chunk.buffer, response);
  27623. }
  27624. return pump();
  27625. }).catch(() => {
  27626. return Promise.reject();
  27627. });
  27628. };
  27629. return pump();
  27630. }
  27631. };
  27632. function getRequestParameters(context, signal) {
  27633. const initParams = {
  27634. method: "GET",
  27635. mode: "cors",
  27636. credentials: "same-origin",
  27637. signal,
  27638. headers: new self.Headers(_extends({}, context.headers))
  27639. };
  27640. if (context.rangeEnd) {
  27641. initParams.headers.set("Range", "bytes=" + context.rangeStart + "-" + String(context.rangeEnd - 1));
  27642. }
  27643. return initParams;
  27644. }
  27645. function getByteRangeLength(byteRangeHeader) {
  27646. const result = BYTERANGE.exec(byteRangeHeader);
  27647. if (result) {
  27648. return parseInt(result[2]) - parseInt(result[1]) + 1;
  27649. }
  27650. }
  27651. function getContentLength(headers) {
  27652. const contentRange = headers.get("Content-Range");
  27653. if (contentRange) {
  27654. const byteRangeLength = getByteRangeLength(contentRange);
  27655. if (isFiniteNumber(byteRangeLength)) {
  27656. return byteRangeLength;
  27657. }
  27658. }
  27659. const contentLength = headers.get("Content-Length");
  27660. if (contentLength) {
  27661. return parseInt(contentLength);
  27662. }
  27663. }
  27664. function getRequest(context, initParams) {
  27665. return new self.Request(context.url, initParams);
  27666. }
  27667. var FetchError = class extends Error {
  27668. constructor(message, code, details) {
  27669. super(message);
  27670. this.code = void 0;
  27671. this.details = void 0;
  27672. this.code = code;
  27673. this.details = details;
  27674. }
  27675. };
  27676. var AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/im;
  27677. var XhrLoader = class {
  27678. constructor(config) {
  27679. this.xhrSetup = void 0;
  27680. this.requestTimeout = void 0;
  27681. this.retryTimeout = void 0;
  27682. this.retryDelay = void 0;
  27683. this.config = null;
  27684. this.callbacks = null;
  27685. this.context = null;
  27686. this.loader = null;
  27687. this.stats = void 0;
  27688. this.xhrSetup = config ? config.xhrSetup || null : null;
  27689. this.stats = new LoadStats();
  27690. this.retryDelay = 0;
  27691. }
  27692. destroy() {
  27693. this.callbacks = null;
  27694. this.abortInternal();
  27695. this.loader = null;
  27696. this.config = null;
  27697. this.context = null;
  27698. this.xhrSetup = null;
  27699. }
  27700. abortInternal() {
  27701. const loader = this.loader;
  27702. self.clearTimeout(this.requestTimeout);
  27703. self.clearTimeout(this.retryTimeout);
  27704. if (loader) {
  27705. loader.onreadystatechange = null;
  27706. loader.onprogress = null;
  27707. if (loader.readyState !== 4) {
  27708. this.stats.aborted = true;
  27709. loader.abort();
  27710. }
  27711. }
  27712. }
  27713. abort() {
  27714. var _this$callbacks;
  27715. this.abortInternal();
  27716. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  27717. this.callbacks.onAbort(this.stats, this.context, this.loader);
  27718. }
  27719. }
  27720. load(context, config, callbacks) {
  27721. if (this.stats.loading.start) {
  27722. throw new Error("Loader can only be used once.");
  27723. }
  27724. this.stats.loading.start = self.performance.now();
  27725. this.context = context;
  27726. this.config = config;
  27727. this.callbacks = callbacks;
  27728. this.loadInternal();
  27729. }
  27730. loadInternal() {
  27731. const {
  27732. config,
  27733. context
  27734. } = this;
  27735. if (!config || !context) {
  27736. return;
  27737. }
  27738. const xhr = this.loader = new self.XMLHttpRequest();
  27739. const stats = this.stats;
  27740. stats.loading.first = 0;
  27741. stats.loaded = 0;
  27742. stats.aborted = false;
  27743. const xhrSetup = this.xhrSetup;
  27744. if (xhrSetup) {
  27745. Promise.resolve().then(() => {
  27746. if (this.loader !== xhr || this.stats.aborted)
  27747. return;
  27748. return xhrSetup(xhr, context.url);
  27749. }).catch((error) => {
  27750. if (this.loader !== xhr || this.stats.aborted)
  27751. return;
  27752. xhr.open("GET", context.url, true);
  27753. return xhrSetup(xhr, context.url);
  27754. }).then(() => {
  27755. if (this.loader !== xhr || this.stats.aborted)
  27756. return;
  27757. this.openAndSendXhr(xhr, context, config);
  27758. }).catch((error) => {
  27759. var _this$callbacks2;
  27760. (_this$callbacks2 = this.callbacks) == null || _this$callbacks2.onError({
  27761. code: xhr.status,
  27762. text: error.message
  27763. }, context, xhr, stats);
  27764. return;
  27765. });
  27766. } else {
  27767. this.openAndSendXhr(xhr, context, config);
  27768. }
  27769. }
  27770. openAndSendXhr(xhr, context, config) {
  27771. if (!xhr.readyState) {
  27772. xhr.open("GET", context.url, true);
  27773. }
  27774. const headers = context.headers;
  27775. const {
  27776. maxTimeToFirstByteMs,
  27777. maxLoadTimeMs
  27778. } = config.loadPolicy;
  27779. if (headers) {
  27780. for (const header in headers) {
  27781. xhr.setRequestHeader(header, headers[header]);
  27782. }
  27783. }
  27784. if (context.rangeEnd) {
  27785. xhr.setRequestHeader("Range", "bytes=" + context.rangeStart + "-" + (context.rangeEnd - 1));
  27786. }
  27787. xhr.onreadystatechange = this.readystatechange.bind(this);
  27788. xhr.onprogress = this.loadprogress.bind(this);
  27789. xhr.responseType = context.responseType;
  27790. self.clearTimeout(this.requestTimeout);
  27791. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  27792. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
  27793. xhr.send();
  27794. }
  27795. readystatechange() {
  27796. const {
  27797. context,
  27798. loader: xhr,
  27799. stats
  27800. } = this;
  27801. if (!context || !xhr) {
  27802. return;
  27803. }
  27804. const readyState = xhr.readyState;
  27805. const config = this.config;
  27806. if (stats.aborted) {
  27807. return;
  27808. }
  27809. if (readyState >= 2) {
  27810. if (stats.loading.first === 0) {
  27811. stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
  27812. if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {
  27813. self.clearTimeout(this.requestTimeout);
  27814. config.timeout = config.loadPolicy.maxLoadTimeMs;
  27815. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.loadPolicy.maxLoadTimeMs - (stats.loading.first - stats.loading.start));
  27816. }
  27817. }
  27818. if (readyState === 4) {
  27819. self.clearTimeout(this.requestTimeout);
  27820. xhr.onreadystatechange = null;
  27821. xhr.onprogress = null;
  27822. const status2 = xhr.status;
  27823. const useResponseText = xhr.responseType === "text" ? xhr.responseText : null;
  27824. if (status2 >= 200 && status2 < 300) {
  27825. const data = useResponseText != null ? useResponseText : xhr.response;
  27826. if (data != null) {
  27827. var _this$callbacks3, _this$callbacks4;
  27828. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  27829. const len = xhr.responseType === "arraybuffer" ? data.byteLength : data.length;
  27830. stats.loaded = stats.total = len;
  27831. stats.bwEstimate = stats.total * 8e3 / (stats.loading.end - stats.loading.first);
  27832. const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  27833. if (onProgress) {
  27834. onProgress(stats, context, data, xhr);
  27835. }
  27836. const _response = {
  27837. url: xhr.responseURL,
  27838. data,
  27839. code: status2
  27840. };
  27841. (_this$callbacks4 = this.callbacks) == null || _this$callbacks4.onSuccess(_response, stats, context, xhr);
  27842. return;
  27843. }
  27844. }
  27845. const retryConfig = config.loadPolicy.errorRetry;
  27846. const retryCount = stats.retry;
  27847. const response = {
  27848. url: context.url,
  27849. data: void 0,
  27850. code: status2
  27851. };
  27852. if (shouldRetry(retryConfig, retryCount, false, response)) {
  27853. this.retry(retryConfig);
  27854. } else {
  27855. var _this$callbacks5;
  27856. logger.error(`${status2} while loading ${context.url}`);
  27857. (_this$callbacks5 = this.callbacks) == null || _this$callbacks5.onError({
  27858. code: status2,
  27859. text: xhr.statusText
  27860. }, context, xhr, stats);
  27861. }
  27862. }
  27863. }
  27864. }
  27865. loadtimeout() {
  27866. if (!this.config)
  27867. return;
  27868. const retryConfig = this.config.loadPolicy.timeoutRetry;
  27869. const retryCount = this.stats.retry;
  27870. if (shouldRetry(retryConfig, retryCount, true)) {
  27871. this.retry(retryConfig);
  27872. } else {
  27873. var _this$context;
  27874. logger.warn(`timeout while loading ${(_this$context = this.context) == null ? void 0 : _this$context.url}`);
  27875. const callbacks = this.callbacks;
  27876. if (callbacks) {
  27877. this.abortInternal();
  27878. callbacks.onTimeout(this.stats, this.context, this.loader);
  27879. }
  27880. }
  27881. }
  27882. retry(retryConfig) {
  27883. const {
  27884. context,
  27885. stats
  27886. } = this;
  27887. this.retryDelay = getRetryDelay(retryConfig, stats.retry);
  27888. stats.retry++;
  27889. logger.warn(`${status ? "HTTP Status " + status : "Timeout"} while loading ${context == null ? void 0 : context.url}, retrying ${stats.retry}/${retryConfig.maxNumRetry} in ${this.retryDelay}ms`);
  27890. this.abortInternal();
  27891. this.loader = null;
  27892. self.clearTimeout(this.retryTimeout);
  27893. this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  27894. }
  27895. loadprogress(event) {
  27896. const stats = this.stats;
  27897. stats.loaded = event.loaded;
  27898. if (event.lengthComputable) {
  27899. stats.total = event.total;
  27900. }
  27901. }
  27902. getCacheAge() {
  27903. let result = null;
  27904. if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
  27905. const ageHeader = this.loader.getResponseHeader("age");
  27906. result = ageHeader ? parseFloat(ageHeader) : null;
  27907. }
  27908. return result;
  27909. }
  27910. getResponseHeader(name) {
  27911. if (this.loader && new RegExp(`^${name}:\\s*[\\d.]+\\s*$`, "im").test(this.loader.getAllResponseHeaders())) {
  27912. return this.loader.getResponseHeader(name);
  27913. }
  27914. return null;
  27915. }
  27916. };
  27917. var defaultLoadPolicy = {
  27918. maxTimeToFirstByteMs: 8e3,
  27919. maxLoadTimeMs: 2e4,
  27920. timeoutRetry: null,
  27921. errorRetry: null
  27922. };
  27923. var hlsDefaultConfig = _objectSpread2(_objectSpread2({
  27924. autoStartLoad: true,
  27925. // used by stream-controller
  27926. startPosition: -1,
  27927. // used by stream-controller
  27928. defaultAudioCodec: void 0,
  27929. // used by stream-controller
  27930. debug: false,
  27931. // used by logger
  27932. capLevelOnFPSDrop: false,
  27933. // used by fps-controller
  27934. capLevelToPlayerSize: false,
  27935. // used by cap-level-controller
  27936. ignoreDevicePixelRatio: false,
  27937. // used by cap-level-controller
  27938. maxDevicePixelRatio: Number.POSITIVE_INFINITY,
  27939. // used by cap-level-controller
  27940. preferManagedMediaSource: true,
  27941. initialLiveManifestSize: 1,
  27942. // used by stream-controller
  27943. maxBufferLength: 30,
  27944. // used by stream-controller
  27945. backBufferLength: Infinity,
  27946. // used by buffer-controller
  27947. frontBufferFlushThreshold: Infinity,
  27948. startOnSegmentBoundary: false,
  27949. // used by stream-controller
  27950. maxBufferSize: 60 * 1e3 * 1e3,
  27951. // used by stream-controller
  27952. maxFragLookUpTolerance: 0.25,
  27953. // used by stream-controller
  27954. maxBufferHole: 0.1,
  27955. // used by stream-controller and gap-controller
  27956. detectStallWithCurrentTimeMs: 1250,
  27957. // used by gap-controller
  27958. highBufferWatchdogPeriod: 2,
  27959. // used by gap-controller
  27960. nudgeOffset: 0.1,
  27961. // used by gap-controller
  27962. nudgeMaxRetry: 3,
  27963. // used by gap-controller
  27964. nudgeOnVideoHole: true,
  27965. // used by gap-controller
  27966. liveSyncMode: "edge",
  27967. // used by stream-controller
  27968. liveSyncDurationCount: 3,
  27969. // used by latency-controller
  27970. liveSyncOnStallIncrease: 1,
  27971. // used by latency-controller
  27972. liveMaxLatencyDurationCount: Infinity,
  27973. // used by latency-controller
  27974. liveSyncDuration: void 0,
  27975. // used by latency-controller
  27976. liveMaxLatencyDuration: void 0,
  27977. // used by latency-controller
  27978. maxLiveSyncPlaybackRate: 1,
  27979. // used by latency-controller
  27980. liveDurationInfinity: false,
  27981. // used by buffer-controller
  27982. /**
  27983. * @deprecated use backBufferLength
  27984. */
  27985. liveBackBufferLength: null,
  27986. // used by buffer-controller
  27987. maxMaxBufferLength: 600,
  27988. // used by stream-controller
  27989. enableWorker: true,
  27990. // used by transmuxer
  27991. workerPath: null,
  27992. // used by transmuxer
  27993. enableSoftwareAES: true,
  27994. // used by decrypter
  27995. startLevel: void 0,
  27996. // used by level-controller
  27997. startFragPrefetch: false,
  27998. // used by stream-controller
  27999. fpsDroppedMonitoringPeriod: 5e3,
  28000. // used by fps-controller
  28001. fpsDroppedMonitoringThreshold: 0.2,
  28002. // used by fps-controller
  28003. appendErrorMaxRetry: 3,
  28004. // used by buffer-controller
  28005. ignorePlaylistParsingErrors: false,
  28006. loader: XhrLoader,
  28007. // loader: FetchLoader,
  28008. fLoader: void 0,
  28009. // used by fragment-loader
  28010. pLoader: void 0,
  28011. // used by playlist-loader
  28012. xhrSetup: void 0,
  28013. // used by xhr-loader
  28014. licenseXhrSetup: void 0,
  28015. // used by eme-controller
  28016. licenseResponseCallback: void 0,
  28017. // used by eme-controller
  28018. abrController: AbrController,
  28019. bufferController: BufferController,
  28020. capLevelController: CapLevelController,
  28021. errorController: ErrorController,
  28022. fpsController: FPSController,
  28023. stretchShortVideoTrack: false,
  28024. // used by mp4-remuxer
  28025. maxAudioFramesDrift: 1,
  28026. // used by mp4-remuxer
  28027. forceKeyFrameOnDiscontinuity: true,
  28028. // used by ts-demuxer
  28029. abrEwmaFastLive: 3,
  28030. // used by abr-controller
  28031. abrEwmaSlowLive: 9,
  28032. // used by abr-controller
  28033. abrEwmaFastVoD: 3,
  28034. // used by abr-controller
  28035. abrEwmaSlowVoD: 9,
  28036. // used by abr-controller
  28037. abrEwmaDefaultEstimate: 5e5,
  28038. // 500 kbps // used by abr-controller
  28039. abrEwmaDefaultEstimateMax: 5e6,
  28040. // 5 mbps
  28041. abrBandWidthFactor: 0.95,
  28042. // used by abr-controller
  28043. abrBandWidthUpFactor: 0.7,
  28044. // used by abr-controller
  28045. abrMaxWithRealBitrate: false,
  28046. // used by abr-controller
  28047. maxStarvationDelay: 4,
  28048. // used by abr-controller
  28049. maxLoadingDelay: 4,
  28050. // used by abr-controller
  28051. minAutoBitrate: 0,
  28052. // used by hls
  28053. emeEnabled: false,
  28054. // used by eme-controller
  28055. widevineLicenseUrl: void 0,
  28056. // used by eme-controller
  28057. drmSystems: {},
  28058. // used by eme-controller
  28059. drmSystemOptions: {},
  28060. // used by eme-controller
  28061. requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess,
  28062. // used by eme-controller
  28063. requireKeySystemAccessOnStart: false,
  28064. // used by eme-controller
  28065. testBandwidth: true,
  28066. progressive: false,
  28067. lowLatencyMode: true,
  28068. cmcd: void 0,
  28069. enableDateRangeMetadataCues: true,
  28070. enableEmsgMetadataCues: true,
  28071. enableEmsgKLVMetadata: false,
  28072. enableID3MetadataCues: true,
  28073. enableInterstitialPlayback: true,
  28074. interstitialAppendInPlace: true,
  28075. interstitialLiveLookAhead: 10,
  28076. useMediaCapabilities: true,
  28077. preserveManualLevelOnError: false,
  28078. certLoadPolicy: {
  28079. default: defaultLoadPolicy
  28080. },
  28081. keyLoadPolicy: {
  28082. default: {
  28083. maxTimeToFirstByteMs: 8e3,
  28084. maxLoadTimeMs: 2e4,
  28085. timeoutRetry: {
  28086. maxNumRetry: 1,
  28087. retryDelayMs: 1e3,
  28088. maxRetryDelayMs: 2e4,
  28089. backoff: "linear"
  28090. },
  28091. errorRetry: {
  28092. maxNumRetry: 8,
  28093. retryDelayMs: 1e3,
  28094. maxRetryDelayMs: 2e4,
  28095. backoff: "linear"
  28096. }
  28097. }
  28098. },
  28099. manifestLoadPolicy: {
  28100. default: {
  28101. maxTimeToFirstByteMs: Infinity,
  28102. maxLoadTimeMs: 2e4,
  28103. timeoutRetry: {
  28104. maxNumRetry: 2,
  28105. retryDelayMs: 0,
  28106. maxRetryDelayMs: 0
  28107. },
  28108. errorRetry: {
  28109. maxNumRetry: 1,
  28110. retryDelayMs: 1e3,
  28111. maxRetryDelayMs: 8e3
  28112. }
  28113. }
  28114. },
  28115. playlistLoadPolicy: {
  28116. default: {
  28117. maxTimeToFirstByteMs: 1e4,
  28118. maxLoadTimeMs: 2e4,
  28119. timeoutRetry: {
  28120. maxNumRetry: 2,
  28121. retryDelayMs: 0,
  28122. maxRetryDelayMs: 0
  28123. },
  28124. errorRetry: {
  28125. maxNumRetry: 2,
  28126. retryDelayMs: 1e3,
  28127. maxRetryDelayMs: 8e3
  28128. }
  28129. }
  28130. },
  28131. fragLoadPolicy: {
  28132. default: {
  28133. maxTimeToFirstByteMs: 1e4,
  28134. maxLoadTimeMs: 12e4,
  28135. timeoutRetry: {
  28136. maxNumRetry: 4,
  28137. retryDelayMs: 0,
  28138. maxRetryDelayMs: 0
  28139. },
  28140. errorRetry: {
  28141. maxNumRetry: 6,
  28142. retryDelayMs: 1e3,
  28143. maxRetryDelayMs: 8e3
  28144. }
  28145. }
  28146. },
  28147. steeringManifestLoadPolicy: {
  28148. default: {
  28149. maxTimeToFirstByteMs: 1e4,
  28150. maxLoadTimeMs: 2e4,
  28151. timeoutRetry: {
  28152. maxNumRetry: 2,
  28153. retryDelayMs: 0,
  28154. maxRetryDelayMs: 0
  28155. },
  28156. errorRetry: {
  28157. maxNumRetry: 1,
  28158. retryDelayMs: 1e3,
  28159. maxRetryDelayMs: 8e3
  28160. }
  28161. }
  28162. },
  28163. interstitialAssetListLoadPolicy: {
  28164. default: {
  28165. maxTimeToFirstByteMs: 1e4,
  28166. maxLoadTimeMs: 3e4,
  28167. timeoutRetry: {
  28168. maxNumRetry: 0,
  28169. retryDelayMs: 0,
  28170. maxRetryDelayMs: 0
  28171. },
  28172. errorRetry: {
  28173. maxNumRetry: 0,
  28174. retryDelayMs: 1e3,
  28175. maxRetryDelayMs: 8e3
  28176. }
  28177. }
  28178. },
  28179. // These default settings are deprecated in favor of the above policies
  28180. // and are maintained for backwards compatibility
  28181. manifestLoadingTimeOut: 1e4,
  28182. manifestLoadingMaxRetry: 1,
  28183. manifestLoadingRetryDelay: 1e3,
  28184. manifestLoadingMaxRetryTimeout: 64e3,
  28185. levelLoadingTimeOut: 1e4,
  28186. levelLoadingMaxRetry: 4,
  28187. levelLoadingRetryDelay: 1e3,
  28188. levelLoadingMaxRetryTimeout: 64e3,
  28189. fragLoadingTimeOut: 2e4,
  28190. fragLoadingMaxRetry: 6,
  28191. fragLoadingRetryDelay: 1e3,
  28192. fragLoadingMaxRetryTimeout: 64e3
  28193. }, timelineConfig()), {}, {
  28194. subtitleStreamController: SubtitleStreamController,
  28195. subtitleTrackController: SubtitleTrackController,
  28196. timelineController: TimelineController,
  28197. audioStreamController: AudioStreamController,
  28198. audioTrackController: AudioTrackController,
  28199. emeController: EMEController,
  28200. cmcdController: CMCDController,
  28201. contentSteeringController: ContentSteeringController,
  28202. interstitialsController: InterstitialsController
  28203. });
  28204. function timelineConfig() {
  28205. return {
  28206. cueHandler: Cues,
  28207. // used by timeline-controller
  28208. enableWebVTT: true,
  28209. // used by timeline-controller
  28210. enableIMSC1: true,
  28211. // used by timeline-controller
  28212. enableCEA708Captions: true,
  28213. // used by timeline-controller
  28214. captionsTextTrack1Label: "English",
  28215. // used by timeline-controller
  28216. captionsTextTrack1LanguageCode: "en",
  28217. // used by timeline-controller
  28218. captionsTextTrack2Label: "Spanish",
  28219. // used by timeline-controller
  28220. captionsTextTrack2LanguageCode: "es",
  28221. // used by timeline-controller
  28222. captionsTextTrack3Label: "Unknown CC",
  28223. // used by timeline-controller
  28224. captionsTextTrack3LanguageCode: "",
  28225. // used by timeline-controller
  28226. captionsTextTrack4Label: "Unknown CC",
  28227. // used by timeline-controller
  28228. captionsTextTrack4LanguageCode: "",
  28229. // used by timeline-controller
  28230. renderTextTracksNatively: true
  28231. };
  28232. }
  28233. function mergeConfig(defaultConfig, userConfig, logger2) {
  28234. if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
  28235. throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  28236. }
  28237. if (userConfig.liveMaxLatencyDurationCount !== void 0 && (userConfig.liveSyncDurationCount === void 0 || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
  28238. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  28239. }
  28240. if (userConfig.liveMaxLatencyDuration !== void 0 && (userConfig.liveSyncDuration === void 0 || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
  28241. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  28242. }
  28243. const defaultsCopy = deepCpy(defaultConfig);
  28244. const deprecatedSettingTypes = ["manifest", "level", "frag"];
  28245. const deprecatedSettings = ["TimeOut", "MaxRetry", "RetryDelay", "MaxRetryTimeout"];
  28246. deprecatedSettingTypes.forEach((type) => {
  28247. const policyName = `${type === "level" ? "playlist" : type}LoadPolicy`;
  28248. const policyNotSet = userConfig[policyName] === void 0;
  28249. const report = [];
  28250. deprecatedSettings.forEach((setting) => {
  28251. const deprecatedSetting = `${type}Loading${setting}`;
  28252. const value = userConfig[deprecatedSetting];
  28253. if (value !== void 0 && policyNotSet) {
  28254. report.push(deprecatedSetting);
  28255. const settings = defaultsCopy[policyName].default;
  28256. userConfig[policyName] = {
  28257. default: settings
  28258. };
  28259. switch (setting) {
  28260. case "TimeOut":
  28261. settings.maxLoadTimeMs = value;
  28262. settings.maxTimeToFirstByteMs = value;
  28263. break;
  28264. case "MaxRetry":
  28265. settings.errorRetry.maxNumRetry = value;
  28266. settings.timeoutRetry.maxNumRetry = value;
  28267. break;
  28268. case "RetryDelay":
  28269. settings.errorRetry.retryDelayMs = value;
  28270. settings.timeoutRetry.retryDelayMs = value;
  28271. break;
  28272. case "MaxRetryTimeout":
  28273. settings.errorRetry.maxRetryDelayMs = value;
  28274. settings.timeoutRetry.maxRetryDelayMs = value;
  28275. break;
  28276. }
  28277. }
  28278. });
  28279. if (report.length) {
  28280. logger2.warn(`hls.js config: "${report.join('", "')}" setting(s) are deprecated, use "${policyName}": ${stringify(userConfig[policyName])}`);
  28281. }
  28282. });
  28283. return _objectSpread2(_objectSpread2({}, defaultsCopy), userConfig);
  28284. }
  28285. function deepCpy(obj) {
  28286. if (obj && typeof obj === "object") {
  28287. if (Array.isArray(obj)) {
  28288. return obj.map(deepCpy);
  28289. }
  28290. return Object.keys(obj).reduce((result, key) => {
  28291. result[key] = deepCpy(obj[key]);
  28292. return result;
  28293. }, {});
  28294. }
  28295. return obj;
  28296. }
  28297. function enableStreamingMode(config, logger2) {
  28298. const currentLoader = config.loader;
  28299. if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {
  28300. logger2.log("[config]: Custom loader detected, cannot enable progressive streaming");
  28301. config.progressive = false;
  28302. } else {
  28303. const canStreamProgressively = fetchSupported();
  28304. if (canStreamProgressively) {
  28305. config.loader = FetchLoader;
  28306. config.progressive = true;
  28307. config.enableSoftwareAES = true;
  28308. logger2.log("[config]: Progressive streaming enabled, using FetchLoader");
  28309. }
  28310. }
  28311. }
  28312. var MAX_START_GAP_JUMP = 2;
  28313. var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
  28314. var SKIP_BUFFER_RANGE_START = 0.05;
  28315. var TICK_INTERVAL$1 = 100;
  28316. var GapController = class extends TaskLoop {
  28317. constructor(hls, fragmentTracker) {
  28318. super("gap-controller", hls.logger);
  28319. this.hls = void 0;
  28320. this.fragmentTracker = void 0;
  28321. this.media = null;
  28322. this.mediaSource = void 0;
  28323. this.nudgeRetry = 0;
  28324. this.stallReported = false;
  28325. this.stalled = null;
  28326. this.moved = false;
  28327. this.seeking = false;
  28328. this.buffered = {};
  28329. this.lastCurrentTime = 0;
  28330. this.ended = 0;
  28331. this.waiting = 0;
  28332. this.onMediaPlaying = () => {
  28333. this.ended = 0;
  28334. this.waiting = 0;
  28335. };
  28336. this.onMediaWaiting = () => {
  28337. var _this$media;
  28338. if ((_this$media = this.media) != null && _this$media.seeking) {
  28339. return;
  28340. }
  28341. this.waiting = self.performance.now();
  28342. this.tick();
  28343. };
  28344. this.onMediaEnded = () => {
  28345. if (this.hls) {
  28346. var _this$media2;
  28347. this.ended = ((_this$media2 = this.media) == null ? void 0 : _this$media2.currentTime) || 1;
  28348. this.hls.trigger(Events.MEDIA_ENDED, {
  28349. stalled: false
  28350. });
  28351. }
  28352. };
  28353. this.hls = hls;
  28354. this.fragmentTracker = fragmentTracker;
  28355. this.registerListeners();
  28356. }
  28357. registerListeners() {
  28358. const {
  28359. hls
  28360. } = this;
  28361. if (hls) {
  28362. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  28363. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  28364. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  28365. }
  28366. }
  28367. unregisterListeners() {
  28368. const {
  28369. hls
  28370. } = this;
  28371. if (hls) {
  28372. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  28373. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  28374. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  28375. }
  28376. }
  28377. destroy() {
  28378. super.destroy();
  28379. this.unregisterListeners();
  28380. this.media = this.hls = this.fragmentTracker = null;
  28381. this.mediaSource = void 0;
  28382. }
  28383. onMediaAttached(event, data) {
  28384. this.setInterval(TICK_INTERVAL$1);
  28385. this.mediaSource = data.mediaSource;
  28386. const media = this.media = data.media;
  28387. addEventListener(media, "playing", this.onMediaPlaying);
  28388. addEventListener(media, "waiting", this.onMediaWaiting);
  28389. addEventListener(media, "ended", this.onMediaEnded);
  28390. }
  28391. onMediaDetaching(event, data) {
  28392. this.clearInterval();
  28393. const {
  28394. media
  28395. } = this;
  28396. if (media) {
  28397. removeEventListener(media, "playing", this.onMediaPlaying);
  28398. removeEventListener(media, "waiting", this.onMediaWaiting);
  28399. removeEventListener(media, "ended", this.onMediaEnded);
  28400. this.media = null;
  28401. }
  28402. this.mediaSource = void 0;
  28403. }
  28404. onBufferAppended(event, data) {
  28405. this.buffered = data.timeRanges;
  28406. }
  28407. get hasBuffered() {
  28408. return Object.keys(this.buffered).length > 0;
  28409. }
  28410. tick() {
  28411. var _this$media3;
  28412. if (!((_this$media3 = this.media) != null && _this$media3.readyState) || !this.hasBuffered) {
  28413. return;
  28414. }
  28415. const currentTime = this.media.currentTime;
  28416. this.poll(currentTime, this.lastCurrentTime);
  28417. this.lastCurrentTime = currentTime;
  28418. }
  28419. /**
  28420. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  28421. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  28422. *
  28423. * @param lastCurrentTime - Previously read playhead position
  28424. */
  28425. poll(currentTime, lastCurrentTime) {
  28426. var _this$hls, _this$hls2;
  28427. const config = (_this$hls = this.hls) == null ? void 0 : _this$hls.config;
  28428. if (!config) {
  28429. return;
  28430. }
  28431. const media = this.media;
  28432. if (!media) {
  28433. return;
  28434. }
  28435. const {
  28436. seeking
  28437. } = media;
  28438. const seeked = this.seeking && !seeking;
  28439. const beginSeek = !this.seeking && seeking;
  28440. const pausedEndedOrHalted = media.paused && !seeking || media.ended || media.playbackRate === 0;
  28441. this.seeking = seeking;
  28442. if (currentTime !== lastCurrentTime) {
  28443. if (lastCurrentTime) {
  28444. this.ended = 0;
  28445. }
  28446. this.moved = true;
  28447. if (!seeking) {
  28448. this.nudgeRetry = 0;
  28449. if (config.nudgeOnVideoHole && !pausedEndedOrHalted && currentTime > lastCurrentTime) {
  28450. this.nudgeOnVideoHole(currentTime, lastCurrentTime);
  28451. }
  28452. }
  28453. if (this.waiting === 0) {
  28454. this.stallResolved(currentTime);
  28455. }
  28456. return;
  28457. }
  28458. if (beginSeek || seeked) {
  28459. if (seeked) {
  28460. this.stallResolved(currentTime);
  28461. }
  28462. return;
  28463. }
  28464. if (pausedEndedOrHalted) {
  28465. this.nudgeRetry = 0;
  28466. this.stallResolved(currentTime);
  28467. if (!this.ended && media.ended && this.hls) {
  28468. this.ended = currentTime || 1;
  28469. this.hls.trigger(Events.MEDIA_ENDED, {
  28470. stalled: false
  28471. });
  28472. }
  28473. return;
  28474. }
  28475. if (!BufferHelper.getBuffered(media).length) {
  28476. this.nudgeRetry = 0;
  28477. return;
  28478. }
  28479. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  28480. const nextStart = bufferInfo.nextStart || 0;
  28481. const fragmentTracker = this.fragmentTracker;
  28482. if (seeking && fragmentTracker && this.hls) {
  28483. const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, currentTime);
  28484. const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;
  28485. const noBufferHole = !nextStart || inFlightDependency || nextStart - currentTime > MAX_START_GAP_JUMP && !fragmentTracker.getPartialFragment(currentTime);
  28486. if (hasEnoughBuffer || noBufferHole) {
  28487. return;
  28488. }
  28489. this.moved = false;
  28490. }
  28491. const levelDetails = (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.latestLevelDetails;
  28492. if (!this.moved && this.stalled !== null && fragmentTracker) {
  28493. const isBuffered = bufferInfo.len > 0;
  28494. if (!isBuffered && !nextStart) {
  28495. return;
  28496. }
  28497. const startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
  28498. const isLive = !!(levelDetails != null && levelDetails.live);
  28499. const maxStartGapJump = isLive ? levelDetails.targetduration * 2 : MAX_START_GAP_JUMP;
  28500. const appended = appendedFragAtPosition(currentTime, fragmentTracker);
  28501. if (startJump > 0 && (startJump <= maxStartGapJump || appended)) {
  28502. if (!media.paused) {
  28503. this._trySkipBufferHole(appended);
  28504. }
  28505. return;
  28506. }
  28507. }
  28508. const detectStallWithCurrentTimeMs = config.detectStallWithCurrentTimeMs;
  28509. const tnow = self.performance.now();
  28510. const tWaiting = this.waiting;
  28511. let stalled = this.stalled;
  28512. if (stalled === null) {
  28513. if (tWaiting > 0 && tnow - tWaiting < detectStallWithCurrentTimeMs) {
  28514. stalled = this.stalled = tWaiting;
  28515. } else {
  28516. this.stalled = tnow;
  28517. return;
  28518. }
  28519. }
  28520. const stalledDuration = tnow - stalled;
  28521. if (!seeking && (stalledDuration >= detectStallWithCurrentTimeMs || tWaiting) && this.hls) {
  28522. var _this$mediaSource;
  28523. 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) {
  28524. if (this.ended) {
  28525. return;
  28526. }
  28527. this.ended = currentTime || 1;
  28528. this.hls.trigger(Events.MEDIA_ENDED, {
  28529. stalled: true
  28530. });
  28531. return;
  28532. }
  28533. this._reportStall(bufferInfo);
  28534. if (!this.media || !this.hls) {
  28535. return;
  28536. }
  28537. }
  28538. const bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  28539. this._tryFixBufferStall(bufferedWithHoles, stalledDuration, currentTime);
  28540. }
  28541. stallResolved(currentTime) {
  28542. const stalled = this.stalled;
  28543. if (stalled && this.hls) {
  28544. this.stalled = null;
  28545. if (this.stallReported) {
  28546. const stalledDuration = self.performance.now() - stalled;
  28547. this.log(`playback not stuck anymore @${currentTime}, after ${Math.round(stalledDuration)}ms`);
  28548. this.stallReported = false;
  28549. this.waiting = 0;
  28550. this.hls.trigger(Events.STALL_RESOLVED, {});
  28551. }
  28552. }
  28553. }
  28554. nudgeOnVideoHole(currentTime, lastCurrentTime) {
  28555. var _this$buffered$audio;
  28556. const videoSourceBuffered = this.buffered.video;
  28557. 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)) {
  28558. const audioBufferInfo = BufferHelper.bufferedInfo(BufferHelper.timeRangesToArray(this.buffered.audio), currentTime, 0);
  28559. if (audioBufferInfo.len > 1 && lastCurrentTime >= audioBufferInfo.start) {
  28560. const videoTimes = BufferHelper.timeRangesToArray(videoSourceBuffered);
  28561. const lastBufferedIndex = BufferHelper.bufferedInfo(videoTimes, lastCurrentTime, 0).bufferedIndex;
  28562. if (lastBufferedIndex > -1 && lastBufferedIndex < videoTimes.length - 1) {
  28563. const bufferedIndex = BufferHelper.bufferedInfo(videoTimes, currentTime, 0).bufferedIndex;
  28564. const holeStart = videoTimes[lastBufferedIndex].end;
  28565. const holeEnd = videoTimes[lastBufferedIndex + 1].start;
  28566. if ((bufferedIndex === -1 || bufferedIndex > lastBufferedIndex) && holeEnd - holeStart < 1 && // `maxBufferHole` may be too small and setting it to 0 should not disable this feature
  28567. currentTime - holeStart < 2) {
  28568. const error = new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${currentTime} hole: ${holeStart} -> ${holeEnd} buffered index: ${bufferedIndex}`);
  28569. this.warn(error.message);
  28570. this.media.currentTime += 1e-6;
  28571. let frag = appendedFragAtPosition(currentTime, this.fragmentTracker);
  28572. if (frag && "fragment" in frag) {
  28573. frag = frag.fragment;
  28574. } else if (!frag) {
  28575. frag = void 0;
  28576. }
  28577. const bufferInfo = BufferHelper.bufferInfo(this.media, currentTime, 0);
  28578. this.hls.trigger(Events.ERROR, {
  28579. type: ErrorTypes.MEDIA_ERROR,
  28580. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  28581. fatal: false,
  28582. error,
  28583. reason: error.message,
  28584. frag,
  28585. buffer: bufferInfo.len,
  28586. bufferInfo
  28587. });
  28588. }
  28589. }
  28590. }
  28591. }
  28592. }
  28593. /**
  28594. * Detects and attempts to fix known buffer stalling issues.
  28595. * @param bufferInfo - The properties of the current buffer.
  28596. * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
  28597. * @private
  28598. */
  28599. _tryFixBufferStall(bufferInfo, stalledDurationMs, currentTime) {
  28600. var _this$hls3, _this$hls4;
  28601. const {
  28602. fragmentTracker,
  28603. media
  28604. } = this;
  28605. const config = (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.config;
  28606. if (!media || !fragmentTracker || !config) {
  28607. return;
  28608. }
  28609. const levelDetails = (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.latestLevelDetails;
  28610. const appended = appendedFragAtPosition(currentTime, fragmentTracker);
  28611. if (appended || levelDetails != null && levelDetails.live && currentTime < levelDetails.fragmentStart) {
  28612. const targetTime = this._trySkipBufferHole(appended);
  28613. if (targetTime || !this.media) {
  28614. return;
  28615. }
  28616. }
  28617. const bufferedRanges = bufferInfo.buffered;
  28618. const adjacentTraversal = this.adjacentTraversal(bufferInfo, currentTime);
  28619. if ((bufferedRanges && bufferedRanges.length > 1 && bufferInfo.len > config.maxBufferHole || bufferInfo.nextStart && (bufferInfo.nextStart - currentTime < config.maxBufferHole || adjacentTraversal)) && (stalledDurationMs > config.highBufferWatchdogPeriod * 1e3 || this.waiting)) {
  28620. this.warn("Trying to nudge playhead over buffer-hole");
  28621. this._tryNudgeBuffer(bufferInfo);
  28622. }
  28623. }
  28624. adjacentTraversal(bufferInfo, currentTime) {
  28625. const fragmentTracker = this.fragmentTracker;
  28626. const nextStart = bufferInfo.nextStart;
  28627. if (fragmentTracker && nextStart) {
  28628. const current = fragmentTracker.getFragAtPos(currentTime, PlaylistLevelType.MAIN);
  28629. const next = fragmentTracker.getFragAtPos(nextStart, PlaylistLevelType.MAIN);
  28630. if (current && next) {
  28631. return next.sn - current.sn < 2;
  28632. }
  28633. }
  28634. return false;
  28635. }
  28636. /**
  28637. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  28638. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  28639. * @private
  28640. */
  28641. _reportStall(bufferInfo) {
  28642. const {
  28643. hls,
  28644. media,
  28645. stallReported,
  28646. stalled
  28647. } = this;
  28648. if (!stallReported && stalled !== null && media && hls) {
  28649. this.stallReported = true;
  28650. const error = new Error(`Playback stalling at @${media.currentTime} due to low buffer (${stringify(bufferInfo)})`);
  28651. this.warn(error.message);
  28652. hls.trigger(Events.ERROR, {
  28653. type: ErrorTypes.MEDIA_ERROR,
  28654. details: ErrorDetails.BUFFER_STALLED_ERROR,
  28655. fatal: false,
  28656. error,
  28657. buffer: bufferInfo.len,
  28658. bufferInfo,
  28659. stalled: {
  28660. start: stalled
  28661. }
  28662. });
  28663. }
  28664. }
  28665. /**
  28666. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  28667. * @param appended - The fragment or part found at the current time (where playback is stalling).
  28668. * @private
  28669. */
  28670. _trySkipBufferHole(appended) {
  28671. var _this$hls5;
  28672. const {
  28673. fragmentTracker,
  28674. media
  28675. } = this;
  28676. const config = (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.config;
  28677. if (!media || !fragmentTracker || !config) {
  28678. return 0;
  28679. }
  28680. const currentTime = media.currentTime;
  28681. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  28682. const startTime = currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;
  28683. if (startTime && this.hls) {
  28684. const bufferStarved = bufferInfo.len <= config.maxBufferHole;
  28685. const waiting = bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;
  28686. const gapLength = startTime - currentTime;
  28687. if (gapLength > 0 && (bufferStarved || waiting)) {
  28688. if (gapLength > config.maxBufferHole) {
  28689. let startGap = false;
  28690. if (currentTime === 0) {
  28691. const startFrag = fragmentTracker.getAppendedFrag(0, PlaylistLevelType.MAIN);
  28692. if (startFrag && startTime < startFrag.end) {
  28693. startGap = true;
  28694. }
  28695. }
  28696. if (!startGap && appended) {
  28697. var _this$hls$loadLevelOb;
  28698. if (!((_this$hls$loadLevelOb = this.hls.loadLevelObj) != null && _this$hls$loadLevelOb.details)) {
  28699. return 0;
  28700. }
  28701. const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, startTime);
  28702. if (inFlightDependency) {
  28703. return 0;
  28704. }
  28705. let moreToLoad = false;
  28706. let pos = appended.end;
  28707. while (pos < startTime) {
  28708. const provisioned = appendedFragAtPosition(pos, fragmentTracker);
  28709. if (provisioned) {
  28710. pos += provisioned.duration;
  28711. } else {
  28712. moreToLoad = true;
  28713. break;
  28714. }
  28715. }
  28716. if (moreToLoad) {
  28717. return 0;
  28718. }
  28719. }
  28720. }
  28721. const targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
  28722. this.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`);
  28723. this.moved = true;
  28724. media.currentTime = targetTime;
  28725. if (!(appended != null && appended.gap)) {
  28726. const error = new Error(`fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`);
  28727. const errorData = {
  28728. type: ErrorTypes.MEDIA_ERROR,
  28729. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  28730. fatal: false,
  28731. error,
  28732. reason: error.message,
  28733. buffer: bufferInfo.len,
  28734. bufferInfo
  28735. };
  28736. if (appended) {
  28737. if ("fragment" in appended) {
  28738. errorData.part = appended;
  28739. } else {
  28740. errorData.frag = appended;
  28741. }
  28742. }
  28743. this.hls.trigger(Events.ERROR, errorData);
  28744. }
  28745. return targetTime;
  28746. }
  28747. }
  28748. return 0;
  28749. }
  28750. /**
  28751. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  28752. * @private
  28753. */
  28754. _tryNudgeBuffer(bufferInfo) {
  28755. const {
  28756. hls,
  28757. media,
  28758. nudgeRetry
  28759. } = this;
  28760. const config = hls == null ? void 0 : hls.config;
  28761. if (!media || !config) {
  28762. return 0;
  28763. }
  28764. const currentTime = media.currentTime;
  28765. this.nudgeRetry++;
  28766. if (nudgeRetry < config.nudgeMaxRetry) {
  28767. const targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;
  28768. const error = new Error(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`);
  28769. this.warn(error.message);
  28770. media.currentTime = targetTime;
  28771. hls.trigger(Events.ERROR, {
  28772. type: ErrorTypes.MEDIA_ERROR,
  28773. details: ErrorDetails.BUFFER_NUDGE_ON_STALL,
  28774. error,
  28775. fatal: false,
  28776. buffer: bufferInfo.len,
  28777. bufferInfo
  28778. });
  28779. } else {
  28780. const error = new Error(`Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`);
  28781. this.error(error.message);
  28782. hls.trigger(Events.ERROR, {
  28783. type: ErrorTypes.MEDIA_ERROR,
  28784. details: ErrorDetails.BUFFER_STALLED_ERROR,
  28785. error,
  28786. fatal: true,
  28787. buffer: bufferInfo.len,
  28788. bufferInfo
  28789. });
  28790. }
  28791. }
  28792. };
  28793. function getInFlightDependency(inFlightFragments, currentTime) {
  28794. const main = inFlight(inFlightFragments.main);
  28795. if (main && main.start <= currentTime) {
  28796. return main;
  28797. }
  28798. const audio = inFlight(inFlightFragments.audio);
  28799. if (audio && audio.start <= currentTime) {
  28800. return audio;
  28801. }
  28802. return null;
  28803. }
  28804. function inFlight(inFlightData) {
  28805. if (!inFlightData) {
  28806. return null;
  28807. }
  28808. switch (inFlightData.state) {
  28809. case State.IDLE:
  28810. case State.STOPPED:
  28811. case State.ENDED:
  28812. case State.ERROR:
  28813. return null;
  28814. }
  28815. return inFlightData.frag;
  28816. }
  28817. function appendedFragAtPosition(pos, fragmentTracker) {
  28818. return fragmentTracker.getAppendedFrag(pos, PlaylistLevelType.MAIN) || fragmentTracker.getPartialFragment(pos);
  28819. }
  28820. var MIN_CUE_DURATION = 0.25;
  28821. function getCueClass() {
  28822. if (typeof self === "undefined")
  28823. return void 0;
  28824. return self.VTTCue || self.TextTrackCue;
  28825. }
  28826. function createCueWithDataFields(Cue, startTime, endTime, data, type) {
  28827. let cue = new Cue(startTime, endTime, "");
  28828. try {
  28829. cue.value = data;
  28830. if (type) {
  28831. cue.type = type;
  28832. }
  28833. } catch (e) {
  28834. cue = new Cue(startTime, endTime, stringify(type ? _objectSpread2({
  28835. type
  28836. }, data) : data));
  28837. }
  28838. return cue;
  28839. }
  28840. var MAX_CUE_ENDTIME = (() => {
  28841. const Cue = getCueClass();
  28842. try {
  28843. Cue && new Cue(0, Number.POSITIVE_INFINITY, "");
  28844. } catch (e) {
  28845. return Number.MAX_VALUE;
  28846. }
  28847. return Number.POSITIVE_INFINITY;
  28848. })();
  28849. var ID3TrackController = class {
  28850. constructor(hls) {
  28851. this.hls = void 0;
  28852. this.id3Track = null;
  28853. this.media = null;
  28854. this.dateRangeCuesAppended = {};
  28855. this.removeCues = true;
  28856. this.assetCue = void 0;
  28857. this.onEventCueEnter = () => {
  28858. if (!this.hls) {
  28859. return;
  28860. }
  28861. this.hls.trigger(Events.EVENT_CUE_ENTER, {});
  28862. };
  28863. this.hls = hls;
  28864. this._registerListeners();
  28865. }
  28866. destroy() {
  28867. this._unregisterListeners();
  28868. this.id3Track = null;
  28869. this.media = null;
  28870. this.dateRangeCuesAppended = {};
  28871. this.hls = this.onEventCueEnter = null;
  28872. }
  28873. _registerListeners() {
  28874. const {
  28875. hls
  28876. } = this;
  28877. if (hls) {
  28878. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  28879. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  28880. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  28881. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  28882. hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  28883. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  28884. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  28885. hls.on(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  28886. }
  28887. }
  28888. _unregisterListeners() {
  28889. const {
  28890. hls
  28891. } = this;
  28892. if (hls) {
  28893. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  28894. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  28895. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  28896. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  28897. hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  28898. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  28899. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  28900. hls.off(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  28901. }
  28902. }
  28903. // Add ID3 metatadata text track.
  28904. onMediaAttaching(event, data) {
  28905. var _data$overrides;
  28906. this.media = data.media;
  28907. if (((_data$overrides = data.overrides) == null ? void 0 : _data$overrides.cueRemoval) === false) {
  28908. this.removeCues = false;
  28909. }
  28910. }
  28911. onMediaAttached() {
  28912. var _this$hls;
  28913. const details = (_this$hls = this.hls) == null ? void 0 : _this$hls.latestLevelDetails;
  28914. if (details) {
  28915. this.updateDateRangeCues(details);
  28916. }
  28917. }
  28918. onMediaDetaching(event, data) {
  28919. this.media = null;
  28920. const transferringMedia = !!data.transferMedia;
  28921. if (transferringMedia) {
  28922. return;
  28923. }
  28924. if (this.id3Track) {
  28925. if (this.removeCues) {
  28926. clearCurrentCues(this.id3Track, this.onEventCueEnter);
  28927. }
  28928. this.id3Track = null;
  28929. }
  28930. this.dateRangeCuesAppended = {};
  28931. }
  28932. onManifestLoading() {
  28933. this.dateRangeCuesAppended = {};
  28934. }
  28935. createTrack(media) {
  28936. const track = this.getID3Track(media.textTracks);
  28937. track.mode = "hidden";
  28938. return track;
  28939. }
  28940. getID3Track(textTracks) {
  28941. if (!this.media) {
  28942. return;
  28943. }
  28944. for (let i = 0; i < textTracks.length; i++) {
  28945. const textTrack = textTracks[i];
  28946. if (textTrack.kind === "metadata" && textTrack.label === "id3") {
  28947. sendAddTrackEvent(textTrack, this.media);
  28948. return textTrack;
  28949. }
  28950. }
  28951. return this.media.addTextTrack("metadata", "id3");
  28952. }
  28953. onFragParsingMetadata(event, data) {
  28954. if (!this.media || !this.hls) {
  28955. return;
  28956. }
  28957. const {
  28958. enableEmsgMetadataCues,
  28959. enableID3MetadataCues
  28960. } = this.hls.config;
  28961. if (!enableEmsgMetadataCues && !enableID3MetadataCues) {
  28962. return;
  28963. }
  28964. const {
  28965. samples
  28966. } = data;
  28967. if (!this.id3Track) {
  28968. this.id3Track = this.createTrack(this.media);
  28969. }
  28970. const Cue = getCueClass();
  28971. if (!Cue) {
  28972. return;
  28973. }
  28974. for (let i = 0; i < samples.length; i++) {
  28975. const type = samples[i].type;
  28976. if (type === MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) {
  28977. continue;
  28978. }
  28979. const frames = getId3Frames(samples[i].data);
  28980. const startTime = samples[i].pts;
  28981. let endTime = startTime + samples[i].duration;
  28982. if (endTime > MAX_CUE_ENDTIME) {
  28983. endTime = MAX_CUE_ENDTIME;
  28984. }
  28985. const timeDiff = endTime - startTime;
  28986. if (timeDiff <= 0) {
  28987. endTime = startTime + MIN_CUE_DURATION;
  28988. }
  28989. for (let j = 0; j < frames.length; j++) {
  28990. const frame = frames[j];
  28991. if (!isId3TimestampFrame(frame)) {
  28992. this.updateId3CueEnds(startTime, type);
  28993. const cue = createCueWithDataFields(Cue, startTime, endTime, frame, type);
  28994. if (cue) {
  28995. this.id3Track.addCue(cue);
  28996. }
  28997. }
  28998. }
  28999. }
  29000. }
  29001. updateId3CueEnds(startTime, type) {
  29002. var _this$id3Track;
  29003. const cues = (_this$id3Track = this.id3Track) == null ? void 0 : _this$id3Track.cues;
  29004. if (cues) {
  29005. for (let i = cues.length; i--; ) {
  29006. const cue = cues[i];
  29007. if (cue.type === type && cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {
  29008. cue.endTime = startTime;
  29009. }
  29010. }
  29011. }
  29012. }
  29013. onBufferFlushing(event, {
  29014. startOffset,
  29015. endOffset,
  29016. type
  29017. }) {
  29018. const {
  29019. id3Track,
  29020. hls
  29021. } = this;
  29022. if (!hls) {
  29023. return;
  29024. }
  29025. const {
  29026. config: {
  29027. enableEmsgMetadataCues,
  29028. enableID3MetadataCues
  29029. }
  29030. } = hls;
  29031. if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {
  29032. let predicate;
  29033. if (type === "audio") {
  29034. predicate = (cue) => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues;
  29035. } else if (type === "video") {
  29036. predicate = (cue) => cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  29037. } else {
  29038. predicate = (cue) => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  29039. }
  29040. removeCuesInRange(id3Track, startOffset, endOffset, predicate);
  29041. }
  29042. }
  29043. onLevelUpdated(event, {
  29044. details
  29045. }) {
  29046. this.updateDateRangeCues(details, true);
  29047. }
  29048. onLevelPtsUpdated(event, data) {
  29049. if (Math.abs(data.drift) > 0.01) {
  29050. this.updateDateRangeCues(data.details);
  29051. }
  29052. }
  29053. updateDateRangeCues(details, removeOldCues) {
  29054. if (!this.hls || !this.media) {
  29055. return;
  29056. }
  29057. const {
  29058. assetPlayerId,
  29059. timelineOffset,
  29060. enableDateRangeMetadataCues,
  29061. interstitialsController
  29062. } = this.hls.config;
  29063. if (!enableDateRangeMetadataCues) {
  29064. return;
  29065. }
  29066. const Cue = getCueClass();
  29067. if (assetPlayerId && timelineOffset && !interstitialsController) {
  29068. const {
  29069. fragmentStart,
  29070. fragmentEnd
  29071. } = details;
  29072. let cue = this.assetCue;
  29073. if (cue) {
  29074. cue.startTime = fragmentStart;
  29075. cue.endTime = fragmentEnd;
  29076. } else if (Cue) {
  29077. cue = this.assetCue = createCueWithDataFields(Cue, fragmentStart, fragmentEnd, {
  29078. assetPlayerId: this.hls.config.assetPlayerId
  29079. }, "hlsjs.interstitial.asset");
  29080. if (cue) {
  29081. cue.id = assetPlayerId;
  29082. this.id3Track || (this.id3Track = this.createTrack(this.media));
  29083. this.id3Track.addCue(cue);
  29084. cue.addEventListener("enter", this.onEventCueEnter);
  29085. }
  29086. }
  29087. }
  29088. if (!details.hasProgramDateTime) {
  29089. return;
  29090. }
  29091. const {
  29092. id3Track
  29093. } = this;
  29094. const {
  29095. dateRanges
  29096. } = details;
  29097. const ids = Object.keys(dateRanges);
  29098. let dateRangeCuesAppended = this.dateRangeCuesAppended;
  29099. if (id3Track && removeOldCues) {
  29100. var _id3Track$cues;
  29101. if ((_id3Track$cues = id3Track.cues) != null && _id3Track$cues.length) {
  29102. const idsToRemove = Object.keys(dateRangeCuesAppended).filter((id) => !ids.includes(id));
  29103. for (let i = idsToRemove.length; i--; ) {
  29104. var _dateRangeCuesAppende;
  29105. const id = idsToRemove[i];
  29106. const cues = (_dateRangeCuesAppende = dateRangeCuesAppended[id]) == null ? void 0 : _dateRangeCuesAppende.cues;
  29107. delete dateRangeCuesAppended[id];
  29108. if (cues) {
  29109. Object.keys(cues).forEach((key) => {
  29110. const cue = cues[key];
  29111. if (cue) {
  29112. cue.removeEventListener("enter", this.onEventCueEnter);
  29113. try {
  29114. id3Track.removeCue(cue);
  29115. } catch (e) {
  29116. }
  29117. }
  29118. });
  29119. }
  29120. }
  29121. } else {
  29122. dateRangeCuesAppended = this.dateRangeCuesAppended = {};
  29123. }
  29124. }
  29125. const lastFragment = details.fragments[details.fragments.length - 1];
  29126. if (ids.length === 0 || !isFiniteNumber(lastFragment == null ? void 0 : lastFragment.programDateTime)) {
  29127. return;
  29128. }
  29129. this.id3Track || (this.id3Track = this.createTrack(this.media));
  29130. for (let i = 0; i < ids.length; i++) {
  29131. const id = ids[i];
  29132. const dateRange = dateRanges[id];
  29133. const startTime = dateRange.startTime;
  29134. const appendedDateRangeCues = dateRangeCuesAppended[id];
  29135. const cues = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.cues) || {};
  29136. let durationKnown = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.durationKnown) || false;
  29137. let endTime = MAX_CUE_ENDTIME;
  29138. const {
  29139. duration,
  29140. endDate
  29141. } = dateRange;
  29142. if (endDate && duration !== null) {
  29143. endTime = startTime + duration;
  29144. durationKnown = true;
  29145. } else if (dateRange.endOnNext && !durationKnown) {
  29146. const nextDateRangeWithSameClass = ids.reduce((candidateDateRange, id2) => {
  29147. if (id2 !== dateRange.id) {
  29148. const otherDateRange = dateRanges[id2];
  29149. if (otherDateRange.class === dateRange.class && otherDateRange.startDate > dateRange.startDate && (!candidateDateRange || dateRange.startDate < candidateDateRange.startDate)) {
  29150. return otherDateRange;
  29151. }
  29152. }
  29153. return candidateDateRange;
  29154. }, null);
  29155. if (nextDateRangeWithSameClass) {
  29156. endTime = nextDateRangeWithSameClass.startTime;
  29157. durationKnown = true;
  29158. }
  29159. }
  29160. const attributes = Object.keys(dateRange.attr);
  29161. for (let j = 0; j < attributes.length; j++) {
  29162. const key = attributes[j];
  29163. if (!isDateRangeCueAttribute(key)) {
  29164. continue;
  29165. }
  29166. const cue = cues[key];
  29167. if (cue) {
  29168. if (durationKnown && !(appendedDateRangeCues != null && appendedDateRangeCues.durationKnown)) {
  29169. cue.endTime = endTime;
  29170. } else if (Math.abs(cue.startTime - startTime) > 0.01) {
  29171. cue.startTime = startTime;
  29172. cue.endTime = endTime;
  29173. }
  29174. } else if (Cue) {
  29175. let data = dateRange.attr[key];
  29176. if (isSCTE35Attribute(key)) {
  29177. data = hexToArrayBuffer(data);
  29178. }
  29179. const payload = {
  29180. key,
  29181. data
  29182. };
  29183. const _cue = createCueWithDataFields(Cue, startTime, endTime, payload, MetadataSchema.dateRange);
  29184. if (_cue) {
  29185. _cue.id = id;
  29186. this.id3Track.addCue(_cue);
  29187. cues[key] = _cue;
  29188. if (interstitialsController) {
  29189. if (key === "X-ASSET-LIST" || key === "X-ASSET-URL") {
  29190. _cue.addEventListener("enter", this.onEventCueEnter);
  29191. }
  29192. }
  29193. }
  29194. }
  29195. }
  29196. dateRangeCuesAppended[id] = {
  29197. cues,
  29198. dateRange,
  29199. durationKnown
  29200. };
  29201. }
  29202. }
  29203. };
  29204. var LatencyController = class {
  29205. constructor(hls) {
  29206. this.hls = void 0;
  29207. this.config = void 0;
  29208. this.media = null;
  29209. this.currentTime = 0;
  29210. this.stallCount = 0;
  29211. this._latency = null;
  29212. this._targetLatencyUpdated = false;
  29213. this.onTimeupdate = () => {
  29214. const {
  29215. media
  29216. } = this;
  29217. const levelDetails = this.levelDetails;
  29218. if (!media || !levelDetails) {
  29219. return;
  29220. }
  29221. this.currentTime = media.currentTime;
  29222. const latency = this.computeLatency();
  29223. if (latency === null) {
  29224. return;
  29225. }
  29226. this._latency = latency;
  29227. const {
  29228. lowLatencyMode,
  29229. maxLiveSyncPlaybackRate
  29230. } = this.config;
  29231. if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1 || !levelDetails.live) {
  29232. return;
  29233. }
  29234. const targetLatency = this.targetLatency;
  29235. if (targetLatency === null) {
  29236. return;
  29237. }
  29238. const distanceFromTarget = latency - targetLatency;
  29239. const liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
  29240. const inLiveRange = distanceFromTarget < liveMinLatencyDuration;
  29241. if (inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
  29242. const max = Math.min(2, Math.max(1, maxLiveSyncPlaybackRate));
  29243. const rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
  29244. const playbackRate = Math.min(max, Math.max(1, rate));
  29245. this.changeMediaPlaybackRate(media, playbackRate);
  29246. } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
  29247. this.changeMediaPlaybackRate(media, 1);
  29248. }
  29249. };
  29250. this.hls = hls;
  29251. this.config = hls.config;
  29252. this.registerListeners();
  29253. }
  29254. get levelDetails() {
  29255. var _this$hls;
  29256. return ((_this$hls = this.hls) == null ? void 0 : _this$hls.latestLevelDetails) || null;
  29257. }
  29258. get latency() {
  29259. return this._latency || 0;
  29260. }
  29261. get maxLatency() {
  29262. const {
  29263. config
  29264. } = this;
  29265. if (config.liveMaxLatencyDuration !== void 0) {
  29266. return config.liveMaxLatencyDuration;
  29267. }
  29268. const levelDetails = this.levelDetails;
  29269. return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
  29270. }
  29271. get targetLatency() {
  29272. const levelDetails = this.levelDetails;
  29273. if (levelDetails === null || this.hls === null) {
  29274. return null;
  29275. }
  29276. const {
  29277. holdBack,
  29278. partHoldBack,
  29279. targetduration
  29280. } = levelDetails;
  29281. const {
  29282. liveSyncDuration,
  29283. liveSyncDurationCount,
  29284. lowLatencyMode
  29285. } = this.config;
  29286. const userConfig = this.hls.userConfig;
  29287. let targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
  29288. if (this._targetLatencyUpdated || userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
  29289. targetLatency = liveSyncDuration !== void 0 ? liveSyncDuration : liveSyncDurationCount * targetduration;
  29290. }
  29291. const maxLiveSyncOnStallIncrease = targetduration;
  29292. return targetLatency + Math.min(this.stallCount * this.config.liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
  29293. }
  29294. set targetLatency(latency) {
  29295. this.stallCount = 0;
  29296. this.config.liveSyncDuration = latency;
  29297. this._targetLatencyUpdated = true;
  29298. }
  29299. get liveSyncPosition() {
  29300. const liveEdge = this.estimateLiveEdge();
  29301. const targetLatency = this.targetLatency;
  29302. if (liveEdge === null || targetLatency === null) {
  29303. return null;
  29304. }
  29305. const levelDetails = this.levelDetails;
  29306. if (levelDetails === null) {
  29307. return null;
  29308. }
  29309. const edge = levelDetails.edge;
  29310. const syncPosition = liveEdge - targetLatency - this.edgeStalled;
  29311. const min = edge - levelDetails.totalduration;
  29312. const max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
  29313. return Math.min(Math.max(min, syncPosition), max);
  29314. }
  29315. get drift() {
  29316. const levelDetails = this.levelDetails;
  29317. if (levelDetails === null) {
  29318. return 1;
  29319. }
  29320. return levelDetails.drift;
  29321. }
  29322. get edgeStalled() {
  29323. const levelDetails = this.levelDetails;
  29324. if (levelDetails === null) {
  29325. return 0;
  29326. }
  29327. const maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
  29328. return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
  29329. }
  29330. get forwardBufferLength() {
  29331. const {
  29332. media
  29333. } = this;
  29334. const levelDetails = this.levelDetails;
  29335. if (!media || !levelDetails) {
  29336. return 0;
  29337. }
  29338. const bufferedRanges = media.buffered.length;
  29339. return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime;
  29340. }
  29341. destroy() {
  29342. this.unregisterListeners();
  29343. this.onMediaDetaching();
  29344. this.hls = null;
  29345. }
  29346. registerListeners() {
  29347. const {
  29348. hls
  29349. } = this;
  29350. if (!hls) {
  29351. return;
  29352. }
  29353. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  29354. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  29355. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  29356. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  29357. hls.on(Events.ERROR, this.onError, this);
  29358. }
  29359. unregisterListeners() {
  29360. const {
  29361. hls
  29362. } = this;
  29363. if (!hls) {
  29364. return;
  29365. }
  29366. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  29367. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  29368. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  29369. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  29370. hls.off(Events.ERROR, this.onError, this);
  29371. }
  29372. onMediaAttached(event, data) {
  29373. this.media = data.media;
  29374. this.media.addEventListener("timeupdate", this.onTimeupdate);
  29375. }
  29376. onMediaDetaching() {
  29377. if (this.media) {
  29378. this.media.removeEventListener("timeupdate", this.onTimeupdate);
  29379. this.media = null;
  29380. }
  29381. }
  29382. onManifestLoading() {
  29383. this._latency = null;
  29384. this.stallCount = 0;
  29385. }
  29386. onLevelUpdated(event, {
  29387. details
  29388. }) {
  29389. if (details.advanced) {
  29390. this.onTimeupdate();
  29391. }
  29392. if (!details.live && this.media) {
  29393. this.media.removeEventListener("timeupdate", this.onTimeupdate);
  29394. }
  29395. }
  29396. onError(event, data) {
  29397. var _this$levelDetails;
  29398. if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {
  29399. return;
  29400. }
  29401. this.stallCount++;
  29402. if (this.hls && (_this$levelDetails = this.levelDetails) != null && _this$levelDetails.live) {
  29403. this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency");
  29404. }
  29405. }
  29406. changeMediaPlaybackRate(media, playbackRate) {
  29407. var _this$hls2, _this$targetLatency;
  29408. if (media.playbackRate === playbackRate) {
  29409. return;
  29410. }
  29411. (_this$hls2 = this.hls) == null || _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}`);
  29412. media.playbackRate = playbackRate;
  29413. }
  29414. estimateLiveEdge() {
  29415. const levelDetails = this.levelDetails;
  29416. if (levelDetails === null) {
  29417. return null;
  29418. }
  29419. return levelDetails.edge + levelDetails.age;
  29420. }
  29421. computeLatency() {
  29422. const liveEdge = this.estimateLiveEdge();
  29423. if (liveEdge === null) {
  29424. return null;
  29425. }
  29426. return liveEdge - this.currentTime;
  29427. }
  29428. };
  29429. var LevelController = class extends BasePlaylistController {
  29430. constructor(hls, contentSteeringController) {
  29431. super(hls, "level-controller");
  29432. this._levels = [];
  29433. this._firstLevel = -1;
  29434. this._maxAutoLevel = -1;
  29435. this._startLevel = void 0;
  29436. this.currentLevel = null;
  29437. this.currentLevelIndex = -1;
  29438. this.manualLevelIndex = -1;
  29439. this.steering = void 0;
  29440. this.onParsedComplete = void 0;
  29441. this.steering = contentSteeringController;
  29442. this._registerListeners();
  29443. }
  29444. _registerListeners() {
  29445. const {
  29446. hls
  29447. } = this;
  29448. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  29449. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  29450. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  29451. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  29452. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  29453. hls.on(Events.ERROR, this.onError, this);
  29454. }
  29455. _unregisterListeners() {
  29456. const {
  29457. hls
  29458. } = this;
  29459. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  29460. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  29461. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  29462. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  29463. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  29464. hls.off(Events.ERROR, this.onError, this);
  29465. }
  29466. destroy() {
  29467. this._unregisterListeners();
  29468. this.steering = null;
  29469. this.resetLevels();
  29470. super.destroy();
  29471. }
  29472. stopLoad() {
  29473. const levels = this._levels;
  29474. levels.forEach((level) => {
  29475. level.loadError = 0;
  29476. level.fragmentError = 0;
  29477. });
  29478. super.stopLoad();
  29479. }
  29480. resetLevels() {
  29481. this._startLevel = void 0;
  29482. this.manualLevelIndex = -1;
  29483. this.currentLevelIndex = -1;
  29484. this.currentLevel = null;
  29485. this._levels = [];
  29486. this._maxAutoLevel = -1;
  29487. }
  29488. onManifestLoading(event, data) {
  29489. this.resetLevels();
  29490. }
  29491. onManifestLoaded(event, data) {
  29492. const preferManagedMediaSource = this.hls.config.preferManagedMediaSource;
  29493. const levels = [];
  29494. const redundantSet = {};
  29495. const generatePathwaySet = {};
  29496. let resolutionFound = false;
  29497. let videoCodecFound = false;
  29498. let audioCodecFound = false;
  29499. data.levels.forEach((levelParsed) => {
  29500. const attributes = levelParsed.attrs;
  29501. let {
  29502. audioCodec,
  29503. videoCodec
  29504. } = levelParsed;
  29505. if (audioCodec) {
  29506. levelParsed.audioCodec = audioCodec = getCodecCompatibleName(audioCodec, preferManagedMediaSource) || void 0;
  29507. }
  29508. if (videoCodec) {
  29509. videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);
  29510. }
  29511. const {
  29512. width,
  29513. height,
  29514. unknownCodecs
  29515. } = levelParsed;
  29516. const unknownUnsupportedCodecCount = (unknownCodecs == null ? void 0 : unknownCodecs.length) || 0;
  29517. resolutionFound || (resolutionFound = !!(width && height));
  29518. videoCodecFound || (videoCodecFound = !!videoCodec);
  29519. audioCodecFound || (audioCodecFound = !!audioCodec);
  29520. if (unknownUnsupportedCodecCount || audioCodec && !this.isAudioSupported(audioCodec) || videoCodec && !this.isVideoSupported(videoCodec)) {
  29521. this.log(`Some or all CODECS not supported "${attributes.CODECS}"`);
  29522. return;
  29523. }
  29524. const {
  29525. CODECS,
  29526. "FRAME-RATE": FRAMERATE,
  29527. "HDCP-LEVEL": HDCP,
  29528. "PATHWAY-ID": PATHWAY,
  29529. RESOLUTION,
  29530. "VIDEO-RANGE": VIDEO_RANGE
  29531. } = attributes;
  29532. const contentSteeringPrefix = `${PATHWAY || "."}-`;
  29533. const levelKey = `${contentSteeringPrefix}${levelParsed.bitrate}-${RESOLUTION}-${FRAMERATE}-${CODECS}-${VIDEO_RANGE}-${HDCP}`;
  29534. if (!redundantSet[levelKey]) {
  29535. const level = this.createLevel(levelParsed);
  29536. redundantSet[levelKey] = level;
  29537. generatePathwaySet[levelKey] = 1;
  29538. levels.push(level);
  29539. } else if (redundantSet[levelKey].uri !== levelParsed.url && !levelParsed.attrs["PATHWAY-ID"]) {
  29540. const pathwayCount = generatePathwaySet[levelKey] += 1;
  29541. levelParsed.attrs["PATHWAY-ID"] = new Array(pathwayCount + 1).join(".");
  29542. const level = this.createLevel(levelParsed);
  29543. redundantSet[levelKey] = level;
  29544. levels.push(level);
  29545. } else {
  29546. redundantSet[levelKey].addGroupId("audio", attributes.AUDIO);
  29547. redundantSet[levelKey].addGroupId("text", attributes.SUBTITLES);
  29548. }
  29549. });
  29550. this.filterAndSortMediaOptions(levels, data, resolutionFound, videoCodecFound, audioCodecFound);
  29551. }
  29552. createLevel(levelParsed) {
  29553. const level = new Level(levelParsed);
  29554. const supplemental = levelParsed.supplemental;
  29555. if (supplemental != null && supplemental.videoCodec && !this.isVideoSupported(supplemental.videoCodec)) {
  29556. const error = new Error(`SUPPLEMENTAL-CODECS not supported "${supplemental.videoCodec}"`);
  29557. this.log(error.message);
  29558. level.supportedResult = getUnsupportedResult(error, []);
  29559. }
  29560. return level;
  29561. }
  29562. isAudioSupported(codec) {
  29563. return areCodecsMediaSourceSupported(codec, "audio", this.hls.config.preferManagedMediaSource);
  29564. }
  29565. isVideoSupported(codec) {
  29566. return areCodecsMediaSourceSupported(codec, "video", this.hls.config.preferManagedMediaSource);
  29567. }
  29568. filterAndSortMediaOptions(filteredLevels, data, resolutionFound, videoCodecFound, audioCodecFound) {
  29569. var _data$stats;
  29570. let audioTracks = [];
  29571. let subtitleTracks = [];
  29572. let levels = filteredLevels;
  29573. const statsParsing = ((_data$stats = data.stats) == null ? void 0 : _data$stats.parsing) || {};
  29574. if ((resolutionFound || videoCodecFound) && audioCodecFound) {
  29575. levels = levels.filter(({
  29576. videoCodec,
  29577. videoRange,
  29578. width,
  29579. height
  29580. }) => (!!videoCodec || !!(width && height)) && isVideoRange(videoRange));
  29581. }
  29582. if (levels.length === 0) {
  29583. Promise.resolve().then(() => {
  29584. if (this.hls) {
  29585. let message = "no level with compatible codecs found in manifest";
  29586. let reason = message;
  29587. if (data.levels.length) {
  29588. 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))}`;
  29589. this.warn(reason);
  29590. message += ` (${reason})`;
  29591. }
  29592. const error = new Error(message);
  29593. this.hls.trigger(Events.ERROR, {
  29594. type: ErrorTypes.MEDIA_ERROR,
  29595. details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  29596. fatal: true,
  29597. url: data.url,
  29598. error,
  29599. reason
  29600. });
  29601. }
  29602. });
  29603. statsParsing.end = performance.now();
  29604. return;
  29605. }
  29606. if (data.audioTracks) {
  29607. audioTracks = data.audioTracks.filter((track) => !track.audioCodec || this.isAudioSupported(track.audioCodec));
  29608. assignTrackIdsByGroup(audioTracks);
  29609. }
  29610. if (data.subtitles) {
  29611. subtitleTracks = data.subtitles;
  29612. assignTrackIdsByGroup(subtitleTracks);
  29613. }
  29614. const unsortedLevels = levels.slice(0);
  29615. levels.sort((a, b) => {
  29616. if (a.attrs["HDCP-LEVEL"] !== b.attrs["HDCP-LEVEL"]) {
  29617. return (a.attrs["HDCP-LEVEL"] || "") > (b.attrs["HDCP-LEVEL"] || "") ? 1 : -1;
  29618. }
  29619. if (resolutionFound && a.height !== b.height) {
  29620. return a.height - b.height;
  29621. }
  29622. if (a.frameRate !== b.frameRate) {
  29623. return a.frameRate - b.frameRate;
  29624. }
  29625. if (a.videoRange !== b.videoRange) {
  29626. return VideoRangeValues.indexOf(a.videoRange) - VideoRangeValues.indexOf(b.videoRange);
  29627. }
  29628. if (a.videoCodec !== b.videoCodec) {
  29629. const valueA = videoCodecPreferenceValue(a.videoCodec);
  29630. const valueB = videoCodecPreferenceValue(b.videoCodec);
  29631. if (valueA !== valueB) {
  29632. return valueB - valueA;
  29633. }
  29634. }
  29635. if (a.uri === b.uri && a.codecSet !== b.codecSet) {
  29636. const valueA = codecsSetSelectionPreferenceValue(a.codecSet);
  29637. const valueB = codecsSetSelectionPreferenceValue(b.codecSet);
  29638. if (valueA !== valueB) {
  29639. return valueB - valueA;
  29640. }
  29641. }
  29642. if (a.averageBitrate !== b.averageBitrate) {
  29643. return a.averageBitrate - b.averageBitrate;
  29644. }
  29645. return 0;
  29646. });
  29647. let firstLevelInPlaylist = unsortedLevels[0];
  29648. if (this.steering) {
  29649. levels = this.steering.filterParsedLevels(levels);
  29650. if (levels.length !== unsortedLevels.length) {
  29651. for (let i = 0; i < unsortedLevels.length; i++) {
  29652. if (unsortedLevels[i].pathwayId === levels[0].pathwayId) {
  29653. firstLevelInPlaylist = unsortedLevels[i];
  29654. break;
  29655. }
  29656. }
  29657. }
  29658. }
  29659. this._levels = levels;
  29660. for (let i = 0; i < levels.length; i++) {
  29661. if (levels[i] === firstLevelInPlaylist) {
  29662. var _this$hls$userConfig;
  29663. this._firstLevel = i;
  29664. const firstLevelBitrate = firstLevelInPlaylist.bitrate;
  29665. const bandwidthEstimate = this.hls.bandwidthEstimate;
  29666. this.log(`manifest loaded, ${levels.length} level(s) found, first bitrate: ${firstLevelBitrate}`);
  29667. if (((_this$hls$userConfig = this.hls.userConfig) == null ? void 0 : _this$hls$userConfig.abrEwmaDefaultEstimate) === void 0) {
  29668. const startingBwEstimate = Math.min(firstLevelBitrate, this.hls.config.abrEwmaDefaultEstimateMax);
  29669. if (startingBwEstimate > bandwidthEstimate && bandwidthEstimate === this.hls.abrEwmaDefaultEstimate) {
  29670. this.hls.bandwidthEstimate = startingBwEstimate;
  29671. }
  29672. }
  29673. break;
  29674. }
  29675. }
  29676. const audioOnly = audioCodecFound && !videoCodecFound;
  29677. const config = this.hls.config;
  29678. const altAudioEnabled = !!(config.audioStreamController && config.audioTrackController);
  29679. const edata = {
  29680. levels,
  29681. audioTracks,
  29682. subtitleTracks,
  29683. sessionData: data.sessionData,
  29684. sessionKeys: data.sessionKeys,
  29685. firstLevel: this._firstLevel,
  29686. stats: data.stats,
  29687. audio: audioCodecFound,
  29688. video: videoCodecFound,
  29689. altAudio: altAudioEnabled && !audioOnly && audioTracks.some((t) => !!t.url)
  29690. };
  29691. statsParsing.end = performance.now();
  29692. this.hls.trigger(Events.MANIFEST_PARSED, edata);
  29693. }
  29694. get levels() {
  29695. if (this._levels.length === 0) {
  29696. return null;
  29697. }
  29698. return this._levels;
  29699. }
  29700. get loadLevelObj() {
  29701. return this.currentLevel;
  29702. }
  29703. get level() {
  29704. return this.currentLevelIndex;
  29705. }
  29706. set level(newLevel) {
  29707. const levels = this._levels;
  29708. if (levels.length === 0) {
  29709. return;
  29710. }
  29711. if (newLevel < 0 || newLevel >= levels.length) {
  29712. const error = new Error("invalid level idx");
  29713. const fatal = newLevel < 0;
  29714. this.hls.trigger(Events.ERROR, {
  29715. type: ErrorTypes.OTHER_ERROR,
  29716. details: ErrorDetails.LEVEL_SWITCH_ERROR,
  29717. level: newLevel,
  29718. fatal,
  29719. error,
  29720. reason: error.message
  29721. });
  29722. if (fatal) {
  29723. return;
  29724. }
  29725. newLevel = Math.min(newLevel, levels.length - 1);
  29726. }
  29727. const lastLevelIndex = this.currentLevelIndex;
  29728. const lastLevel = this.currentLevel;
  29729. const lastPathwayId = lastLevel ? lastLevel.attrs["PATHWAY-ID"] : void 0;
  29730. const level = levels[newLevel];
  29731. const pathwayId = level.attrs["PATHWAY-ID"];
  29732. this.currentLevelIndex = newLevel;
  29733. this.currentLevel = level;
  29734. if (lastLevelIndex === newLevel && lastLevel && lastPathwayId === pathwayId) {
  29735. return;
  29736. }
  29737. 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 : ""}`);
  29738. const levelSwitchingData = {
  29739. level: newLevel,
  29740. attrs: level.attrs,
  29741. details: level.details,
  29742. bitrate: level.bitrate,
  29743. averageBitrate: level.averageBitrate,
  29744. maxBitrate: level.maxBitrate,
  29745. realBitrate: level.realBitrate,
  29746. width: level.width,
  29747. height: level.height,
  29748. codecSet: level.codecSet,
  29749. audioCodec: level.audioCodec,
  29750. videoCodec: level.videoCodec,
  29751. audioGroups: level.audioGroups,
  29752. subtitleGroups: level.subtitleGroups,
  29753. loaded: level.loaded,
  29754. loadError: level.loadError,
  29755. fragmentError: level.fragmentError,
  29756. name: level.name,
  29757. id: level.id,
  29758. uri: level.uri,
  29759. url: level.url,
  29760. urlId: 0,
  29761. audioGroupIds: level.audioGroupIds,
  29762. textGroupIds: level.textGroupIds
  29763. };
  29764. this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);
  29765. const levelDetails = level.details;
  29766. if (!levelDetails || levelDetails.live) {
  29767. const hlsUrlParameters = this.switchParams(level.uri, lastLevel == null ? void 0 : lastLevel.details, levelDetails);
  29768. this.loadPlaylist(hlsUrlParameters);
  29769. }
  29770. }
  29771. get manualLevel() {
  29772. return this.manualLevelIndex;
  29773. }
  29774. set manualLevel(newLevel) {
  29775. this.manualLevelIndex = newLevel;
  29776. if (this._startLevel === void 0) {
  29777. this._startLevel = newLevel;
  29778. }
  29779. if (newLevel !== -1) {
  29780. this.level = newLevel;
  29781. }
  29782. }
  29783. get firstLevel() {
  29784. return this._firstLevel;
  29785. }
  29786. set firstLevel(newLevel) {
  29787. this._firstLevel = newLevel;
  29788. }
  29789. get startLevel() {
  29790. if (this._startLevel === void 0) {
  29791. const configStartLevel = this.hls.config.startLevel;
  29792. if (configStartLevel !== void 0) {
  29793. return configStartLevel;
  29794. }
  29795. return this.hls.firstAutoLevel;
  29796. }
  29797. return this._startLevel;
  29798. }
  29799. set startLevel(newLevel) {
  29800. this._startLevel = newLevel;
  29801. }
  29802. get pathways() {
  29803. if (this.steering) {
  29804. return this.steering.pathways();
  29805. }
  29806. return [];
  29807. }
  29808. get pathwayPriority() {
  29809. if (this.steering) {
  29810. return this.steering.pathwayPriority;
  29811. }
  29812. return null;
  29813. }
  29814. set pathwayPriority(pathwayPriority) {
  29815. if (this.steering) {
  29816. const pathwaysList = this.steering.pathways();
  29817. const filteredPathwayPriority = pathwayPriority.filter((pathwayId) => {
  29818. return pathwaysList.indexOf(pathwayId) !== -1;
  29819. });
  29820. if (pathwayPriority.length < 1) {
  29821. this.warn(`pathwayPriority ${pathwayPriority} should contain at least one pathway from list: ${pathwaysList}`);
  29822. return;
  29823. }
  29824. this.steering.pathwayPriority = filteredPathwayPriority;
  29825. }
  29826. }
  29827. onError(event, data) {
  29828. if (data.fatal || !data.context) {
  29829. return;
  29830. }
  29831. if (data.context.type === PlaylistContextType.LEVEL && data.context.level === this.level) {
  29832. this.checkRetry(data);
  29833. }
  29834. }
  29835. // reset errors on the successful load of a fragment
  29836. onFragBuffered(event, {
  29837. frag
  29838. }) {
  29839. if (frag !== void 0 && frag.type === PlaylistLevelType.MAIN) {
  29840. const el = frag.elementaryStreams;
  29841. if (!Object.keys(el).some((type) => !!el[type])) {
  29842. return;
  29843. }
  29844. const level = this._levels[frag.level];
  29845. if (level != null && level.loadError) {
  29846. this.log(`Resetting level error count of ${level.loadError} on frag buffered`);
  29847. level.loadError = 0;
  29848. }
  29849. }
  29850. }
  29851. onLevelLoaded(event, data) {
  29852. var _data$deliveryDirecti2;
  29853. const {
  29854. level,
  29855. details
  29856. } = data;
  29857. const curLevel = data.levelInfo;
  29858. if (!curLevel) {
  29859. var _data$deliveryDirecti;
  29860. this.warn(`Invalid level index ${level}`);
  29861. if ((_data$deliveryDirecti = data.deliveryDirectives) != null && _data$deliveryDirecti.skip) {
  29862. details.deltaUpdateFailed = true;
  29863. }
  29864. return;
  29865. }
  29866. if (curLevel === this.currentLevel || data.withoutMultiVariant) {
  29867. if (curLevel.fragmentError === 0) {
  29868. curLevel.loadError = 0;
  29869. }
  29870. let previousDetails = curLevel.details;
  29871. if (previousDetails === data.details && previousDetails.advanced) {
  29872. previousDetails = void 0;
  29873. }
  29874. this.playlistLoaded(level, data, previousDetails);
  29875. } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) != null && _data$deliveryDirecti2.skip) {
  29876. details.deltaUpdateFailed = true;
  29877. }
  29878. }
  29879. loadPlaylist(hlsUrlParameters) {
  29880. super.loadPlaylist();
  29881. if (this.shouldLoadPlaylist(this.currentLevel)) {
  29882. this.scheduleLoading(this.currentLevel, hlsUrlParameters);
  29883. }
  29884. }
  29885. loadingPlaylist(currentLevel, hlsUrlParameters) {
  29886. super.loadingPlaylist(currentLevel, hlsUrlParameters);
  29887. const url = this.getUrlWithDirectives(currentLevel.uri, hlsUrlParameters);
  29888. const currentLevelIndex = this.currentLevelIndex;
  29889. const pathwayId = currentLevel.attrs["PATHWAY-ID"];
  29890. const details = currentLevel.details;
  29891. const age = details == null ? void 0 : details.age;
  29892. 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}`);
  29893. this.hls.trigger(Events.LEVEL_LOADING, {
  29894. url,
  29895. level: currentLevelIndex,
  29896. levelInfo: currentLevel,
  29897. pathwayId: currentLevel.attrs["PATHWAY-ID"],
  29898. id: 0,
  29899. // Deprecated Level urlId
  29900. deliveryDirectives: hlsUrlParameters || null
  29901. });
  29902. }
  29903. get nextLoadLevel() {
  29904. if (this.manualLevelIndex !== -1) {
  29905. return this.manualLevelIndex;
  29906. } else {
  29907. return this.hls.nextAutoLevel;
  29908. }
  29909. }
  29910. set nextLoadLevel(nextLevel) {
  29911. this.level = nextLevel;
  29912. if (this.manualLevelIndex === -1) {
  29913. this.hls.nextAutoLevel = nextLevel;
  29914. }
  29915. }
  29916. removeLevel(levelIndex) {
  29917. var _this$currentLevel;
  29918. if (this._levels.length === 1) {
  29919. return;
  29920. }
  29921. const levels = this._levels.filter((level, index) => {
  29922. if (index !== levelIndex) {
  29923. return true;
  29924. }
  29925. if (this.steering) {
  29926. this.steering.removeLevel(level);
  29927. }
  29928. if (level === this.currentLevel) {
  29929. this.currentLevel = null;
  29930. this.currentLevelIndex = -1;
  29931. if (level.details) {
  29932. level.details.fragments.forEach((f) => f.level = -1);
  29933. }
  29934. }
  29935. return false;
  29936. });
  29937. reassignFragmentLevelIndexes(levels);
  29938. this._levels = levels;
  29939. if (this.currentLevelIndex > -1 && (_this$currentLevel = this.currentLevel) != null && _this$currentLevel.details) {
  29940. this.currentLevelIndex = this.currentLevel.details.fragments[0].level;
  29941. }
  29942. if (this.manualLevelIndex > -1) {
  29943. this.manualLevelIndex = this.currentLevelIndex;
  29944. }
  29945. const maxLevel = levels.length - 1;
  29946. this._firstLevel = Math.min(this._firstLevel, maxLevel);
  29947. if (this._startLevel) {
  29948. this._startLevel = Math.min(this._startLevel, maxLevel);
  29949. }
  29950. this.hls.trigger(Events.LEVELS_UPDATED, {
  29951. levels
  29952. });
  29953. }
  29954. onLevelsUpdated(event, {
  29955. levels
  29956. }) {
  29957. this._levels = levels;
  29958. }
  29959. checkMaxAutoUpdated() {
  29960. const {
  29961. autoLevelCapping,
  29962. maxAutoLevel,
  29963. maxHdcpLevel
  29964. } = this.hls;
  29965. if (this._maxAutoLevel !== maxAutoLevel) {
  29966. this._maxAutoLevel = maxAutoLevel;
  29967. this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {
  29968. autoLevelCapping,
  29969. levels: this.levels,
  29970. maxAutoLevel,
  29971. minAutoLevel: this.hls.minAutoLevel,
  29972. maxHdcpLevel
  29973. });
  29974. }
  29975. }
  29976. };
  29977. function assignTrackIdsByGroup(tracks) {
  29978. const groups = {};
  29979. tracks.forEach((track) => {
  29980. const groupId = track.groupId || "";
  29981. track.id = groups[groupId] = groups[groupId] || 0;
  29982. groups[groupId]++;
  29983. });
  29984. }
  29985. function getSourceBuffer() {
  29986. return self.SourceBuffer || self.WebKitSourceBuffer;
  29987. }
  29988. function isMSESupported() {
  29989. const mediaSource = getMediaSource();
  29990. if (!mediaSource) {
  29991. return false;
  29992. }
  29993. const sourceBuffer = getSourceBuffer();
  29994. return !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === "function" && typeof sourceBuffer.prototype.remove === "function";
  29995. }
  29996. function isSupported() {
  29997. if (!isMSESupported()) {
  29998. return false;
  29999. }
  30000. const mediaSource = getMediaSource();
  30001. 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"))));
  30002. }
  30003. function changeTypeSupported() {
  30004. var _sourceBuffer$prototy;
  30005. const sourceBuffer = getSourceBuffer();
  30006. return typeof (sourceBuffer == null || (_sourceBuffer$prototy = sourceBuffer.prototype) == null ? void 0 : _sourceBuffer$prototy.changeType) === "function";
  30007. }
  30008. var TICK_INTERVAL = 100;
  30009. var StreamController = class extends BaseStreamController {
  30010. constructor(hls, fragmentTracker, keyLoader) {
  30011. super(hls, fragmentTracker, keyLoader, "stream-controller", PlaylistLevelType.MAIN);
  30012. this.audioCodecSwap = false;
  30013. this.level = -1;
  30014. this._forceStartLoad = false;
  30015. this._hasEnoughToStart = false;
  30016. this.altAudio = 0;
  30017. this.audioOnly = false;
  30018. this.fragPlaying = null;
  30019. this.fragLastKbps = 0;
  30020. this.couldBacktrack = false;
  30021. this.backtrackFragment = null;
  30022. this.audioCodecSwitch = false;
  30023. this.videoBuffer = null;
  30024. this.onMediaPlaying = () => {
  30025. this.tick();
  30026. };
  30027. this.onMediaSeeked = () => {
  30028. const media = this.media;
  30029. const currentTime = media ? media.currentTime : null;
  30030. if (currentTime === null || !isFiniteNumber(currentTime)) {
  30031. return;
  30032. }
  30033. this.log(`Media seeked to ${currentTime.toFixed(3)}`);
  30034. if (!this.getBufferedFrag(currentTime)) {
  30035. return;
  30036. }
  30037. const bufferInfo = this.getFwdBufferInfoAtPos(media, currentTime, PlaylistLevelType.MAIN, 0);
  30038. if (bufferInfo === null || bufferInfo.len === 0) {
  30039. this.warn(`Main forward buffer length at ${currentTime} on "seeked" event ${bufferInfo ? bufferInfo.len : "empty"})`);
  30040. return;
  30041. }
  30042. this.tick();
  30043. };
  30044. this.registerListeners();
  30045. }
  30046. registerListeners() {
  30047. super.registerListeners();
  30048. const {
  30049. hls
  30050. } = this;
  30051. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  30052. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  30053. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  30054. hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  30055. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  30056. hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  30057. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  30058. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  30059. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  30060. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  30061. }
  30062. unregisterListeners() {
  30063. super.unregisterListeners();
  30064. const {
  30065. hls
  30066. } = this;
  30067. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  30068. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  30069. hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  30070. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  30071. hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  30072. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  30073. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  30074. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  30075. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  30076. }
  30077. onHandlerDestroying() {
  30078. this.onMediaPlaying = this.onMediaSeeked = null;
  30079. this.unregisterListeners();
  30080. super.onHandlerDestroying();
  30081. }
  30082. startLoad(startPosition, skipSeekToStartPosition) {
  30083. if (this.levels) {
  30084. const {
  30085. lastCurrentTime,
  30086. hls
  30087. } = this;
  30088. this.stopLoad();
  30089. this.setInterval(TICK_INTERVAL);
  30090. this.level = -1;
  30091. if (!this.startFragRequested) {
  30092. let startLevel = hls.startLevel;
  30093. if (startLevel === -1) {
  30094. if (hls.config.testBandwidth && this.levels.length > 1) {
  30095. startLevel = 0;
  30096. this.bitrateTest = true;
  30097. } else {
  30098. startLevel = hls.firstAutoLevel;
  30099. }
  30100. }
  30101. hls.nextLoadLevel = startLevel;
  30102. this.level = hls.loadLevel;
  30103. this._hasEnoughToStart = !!skipSeekToStartPosition;
  30104. }
  30105. if (lastCurrentTime > 0 && startPosition === -1 && !skipSeekToStartPosition) {
  30106. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  30107. startPosition = lastCurrentTime;
  30108. }
  30109. this.state = State.IDLE;
  30110. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  30111. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  30112. this.tick();
  30113. } else {
  30114. this._forceStartLoad = true;
  30115. this.state = State.STOPPED;
  30116. }
  30117. }
  30118. stopLoad() {
  30119. this._forceStartLoad = false;
  30120. super.stopLoad();
  30121. }
  30122. doTick() {
  30123. switch (this.state) {
  30124. case State.WAITING_LEVEL: {
  30125. const {
  30126. levels,
  30127. level
  30128. } = this;
  30129. const currentLevel = levels == null ? void 0 : levels[level];
  30130. const details = currentLevel == null ? void 0 : currentLevel.details;
  30131. if (details && (!details.live || this.levelLastLoaded === currentLevel && !this.waitForLive(currentLevel))) {
  30132. if (this.waitForCdnTuneIn(details)) {
  30133. break;
  30134. }
  30135. this.state = State.IDLE;
  30136. break;
  30137. } else if (this.hls.nextLoadLevel !== this.level) {
  30138. this.state = State.IDLE;
  30139. break;
  30140. }
  30141. break;
  30142. }
  30143. case State.FRAG_LOADING_WAITING_RETRY:
  30144. this.checkRetryDate();
  30145. break;
  30146. }
  30147. if (this.state === State.IDLE) {
  30148. this.doTickIdle();
  30149. }
  30150. this.onTickEnd();
  30151. }
  30152. onTickEnd() {
  30153. var _this$media;
  30154. super.onTickEnd();
  30155. if ((_this$media = this.media) != null && _this$media.readyState && this.media.seeking === false) {
  30156. this.lastCurrentTime = this.media.currentTime;
  30157. }
  30158. this.checkFragmentChanged();
  30159. }
  30160. doTickIdle() {
  30161. const {
  30162. hls,
  30163. levelLastLoaded,
  30164. levels,
  30165. media
  30166. } = this;
  30167. if (levelLastLoaded === null || !media && !this.primaryPrefetch && (this.startFragRequested || !hls.config.startFragPrefetch)) {
  30168. return;
  30169. }
  30170. if (this.altAudio && this.audioOnly) {
  30171. return;
  30172. }
  30173. const level = this.buffering ? hls.nextLoadLevel : hls.loadLevel;
  30174. if (!(levels != null && levels[level])) {
  30175. return;
  30176. }
  30177. const levelInfo = levels[level];
  30178. const bufferInfo = this.getMainFwdBufferInfo();
  30179. if (bufferInfo === null) {
  30180. return;
  30181. }
  30182. const lastDetails = this.getLevelDetails();
  30183. if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {
  30184. const data = {};
  30185. if (this.altAudio === 2) {
  30186. data.type = "video";
  30187. }
  30188. this.hls.trigger(Events.BUFFER_EOS, data);
  30189. this.state = State.ENDED;
  30190. return;
  30191. }
  30192. if (!this.buffering) {
  30193. return;
  30194. }
  30195. if (hls.loadLevel !== level && hls.manualLevel === -1) {
  30196. this.log(`Adapting to level ${level} from level ${this.level}`);
  30197. }
  30198. this.level = hls.nextLoadLevel = level;
  30199. const levelDetails = levelInfo.details;
  30200. if (!levelDetails || this.state === State.WAITING_LEVEL || this.waitForLive(levelInfo)) {
  30201. this.level = level;
  30202. this.state = State.WAITING_LEVEL;
  30203. this.startFragRequested = false;
  30204. return;
  30205. }
  30206. const bufferLen = bufferInfo.len;
  30207. const maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);
  30208. if (bufferLen >= maxBufLen) {
  30209. return;
  30210. }
  30211. if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) {
  30212. this.backtrackFragment = null;
  30213. }
  30214. const targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end;
  30215. let frag = this.getNextFragment(targetBufferTime, levelDetails);
  30216. if (this.couldBacktrack && !this.fragPrevious && frag && isMediaFragment(frag) && this.fragmentTracker.getState(frag) !== FragmentState.OK) {
  30217. var _this$backtrackFragme;
  30218. const backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn;
  30219. const fragIdx = backtrackSn - levelDetails.startSN;
  30220. const backtrackFrag = levelDetails.fragments[fragIdx - 1];
  30221. if (backtrackFrag && frag.cc === backtrackFrag.cc) {
  30222. frag = backtrackFrag;
  30223. this.fragmentTracker.removeFragment(backtrackFrag);
  30224. }
  30225. } else if (this.backtrackFragment && bufferInfo.len) {
  30226. this.backtrackFragment = null;
  30227. }
  30228. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  30229. const gapStart = frag.gap;
  30230. if (!gapStart) {
  30231. const type = this.audioOnly && !this.altAudio ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
  30232. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  30233. if (mediaBuffer) {
  30234. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  30235. }
  30236. }
  30237. frag = this.getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  30238. }
  30239. if (!frag) {
  30240. return;
  30241. }
  30242. if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
  30243. frag = frag.initSegment;
  30244. }
  30245. this.loadFragment(frag, levelInfo, targetBufferTime);
  30246. }
  30247. loadFragment(frag, level, targetBufferTime) {
  30248. const fragState = this.fragmentTracker.getState(frag);
  30249. if (fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  30250. if (!isMediaFragment(frag)) {
  30251. this._loadInitSegment(frag, level);
  30252. } else if (this.bitrateTest) {
  30253. this.log(`Fragment ${frag.sn} of level ${frag.level} is being downloaded to test bitrate and will not be buffered`);
  30254. this._loadBitrateTestFrag(frag, level);
  30255. } else {
  30256. super.loadFragment(frag, level, targetBufferTime);
  30257. }
  30258. } else {
  30259. this.clearTrackerIfNeeded(frag);
  30260. }
  30261. }
  30262. getBufferedFrag(position) {
  30263. return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
  30264. }
  30265. followingBufferedFrag(frag) {
  30266. if (frag) {
  30267. return this.getBufferedFrag(frag.end + 0.5);
  30268. }
  30269. return null;
  30270. }
  30271. /*
  30272. on immediate level switch :
  30273. - pause playback if playing
  30274. - cancel any pending load request
  30275. - and trigger a buffer flush
  30276. */
  30277. immediateLevelSwitch() {
  30278. this.abortCurrentFrag();
  30279. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  30280. }
  30281. /**
  30282. * try to switch ASAP without breaking video playback:
  30283. * in order to ensure smooth but quick level switching,
  30284. * we need to find the next flushable buffer range
  30285. * we should take into account new segment fetch time
  30286. */
  30287. nextLevelSwitch() {
  30288. const {
  30289. levels,
  30290. media
  30291. } = this;
  30292. if (media != null && media.readyState) {
  30293. let fetchdelay;
  30294. const fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
  30295. if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
  30296. this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
  30297. }
  30298. const levelDetails = this.getLevelDetails();
  30299. if (levelDetails != null && levelDetails.live) {
  30300. const bufferInfo = this.getMainFwdBufferInfo();
  30301. if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {
  30302. return;
  30303. }
  30304. }
  30305. if (!media.paused && levels) {
  30306. const nextLevelId = this.hls.nextLoadLevel;
  30307. const nextLevel = levels[nextLevelId];
  30308. const fragLastKbps = this.fragLastKbps;
  30309. if (fragLastKbps && this.fragCurrent) {
  30310. fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1e3 * fragLastKbps) + 1;
  30311. } else {
  30312. fetchdelay = 0;
  30313. }
  30314. } else {
  30315. fetchdelay = 0;
  30316. }
  30317. const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  30318. if (bufferedFrag) {
  30319. const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
  30320. if (nextBufferedFrag) {
  30321. this.abortCurrentFrag();
  30322. const maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
  30323. const fragDuration = nextBufferedFrag.duration;
  30324. 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)));
  30325. this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
  30326. }
  30327. }
  30328. }
  30329. }
  30330. abortCurrentFrag() {
  30331. const fragCurrent = this.fragCurrent;
  30332. this.fragCurrent = null;
  30333. this.backtrackFragment = null;
  30334. if (fragCurrent) {
  30335. fragCurrent.abortRequests();
  30336. this.fragmentTracker.removeFragment(fragCurrent);
  30337. }
  30338. switch (this.state) {
  30339. case State.KEY_LOADING:
  30340. case State.FRAG_LOADING:
  30341. case State.FRAG_LOADING_WAITING_RETRY:
  30342. case State.PARSING:
  30343. case State.PARSED:
  30344. this.state = State.IDLE;
  30345. break;
  30346. }
  30347. this.nextLoadPosition = this.getLoadPosition();
  30348. }
  30349. flushMainBuffer(startOffset, endOffset) {
  30350. super.flushMainBuffer(startOffset, endOffset, this.altAudio === 2 ? "video" : null);
  30351. }
  30352. onMediaAttached(event, data) {
  30353. super.onMediaAttached(event, data);
  30354. const media = data.media;
  30355. addEventListener(media, "playing", this.onMediaPlaying);
  30356. addEventListener(media, "seeked", this.onMediaSeeked);
  30357. }
  30358. onMediaDetaching(event, data) {
  30359. const {
  30360. media
  30361. } = this;
  30362. if (media) {
  30363. removeEventListener(media, "playing", this.onMediaPlaying);
  30364. removeEventListener(media, "seeked", this.onMediaSeeked);
  30365. }
  30366. this.videoBuffer = null;
  30367. this.fragPlaying = null;
  30368. super.onMediaDetaching(event, data);
  30369. const transferringMedia = !!data.transferMedia;
  30370. if (transferringMedia) {
  30371. return;
  30372. }
  30373. this._hasEnoughToStart = false;
  30374. }
  30375. onManifestLoading() {
  30376. super.onManifestLoading();
  30377. this.log("Trigger BUFFER_RESET");
  30378. this.hls.trigger(Events.BUFFER_RESET, void 0);
  30379. this.couldBacktrack = false;
  30380. this.fragLastKbps = 0;
  30381. this.fragPlaying = this.backtrackFragment = null;
  30382. this.altAudio = 0;
  30383. this.audioOnly = false;
  30384. }
  30385. onManifestParsed(event, data) {
  30386. let aac = false;
  30387. let heaac = false;
  30388. for (let i = 0; i < data.levels.length; i++) {
  30389. const codec = data.levels[i].audioCodec;
  30390. if (codec) {
  30391. aac = aac || codec.indexOf("mp4a.40.2") !== -1;
  30392. heaac = heaac || codec.indexOf("mp4a.40.5") !== -1;
  30393. }
  30394. }
  30395. this.audioCodecSwitch = aac && heaac && !changeTypeSupported();
  30396. if (this.audioCodecSwitch) {
  30397. this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC");
  30398. }
  30399. this.levels = data.levels;
  30400. this.startFragRequested = false;
  30401. }
  30402. onLevelLoading(event, data) {
  30403. const {
  30404. levels
  30405. } = this;
  30406. if (!levels || this.state !== State.IDLE) {
  30407. return;
  30408. }
  30409. const level = data.levelInfo;
  30410. if (!level.details || level.details.live && (this.levelLastLoaded !== level || level.details.expired) || this.waitForCdnTuneIn(level.details)) {
  30411. this.state = State.WAITING_LEVEL;
  30412. }
  30413. }
  30414. onLevelLoaded(event, data) {
  30415. var _curLevel$details;
  30416. const {
  30417. levels,
  30418. startFragRequested
  30419. } = this;
  30420. const newLevelId = data.level;
  30421. const newDetails = data.details;
  30422. const duration = newDetails.totalduration;
  30423. if (!levels) {
  30424. this.warn(`Levels were reset while loading level ${newLevelId}`);
  30425. return;
  30426. }
  30427. this.log(`Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""}, cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration}`);
  30428. const curLevel = data.levelInfo;
  30429. const fragCurrent = this.fragCurrent;
  30430. if (fragCurrent && (this.state === State.FRAG_LOADING || this.state === State.FRAG_LOADING_WAITING_RETRY)) {
  30431. if (fragCurrent.level !== data.level && fragCurrent.loader) {
  30432. this.abortCurrentFrag();
  30433. }
  30434. }
  30435. let sliding = 0;
  30436. if (newDetails.live || (_curLevel$details = curLevel.details) != null && _curLevel$details.live) {
  30437. var _this$levelLastLoaded;
  30438. this.checkLiveUpdate(newDetails);
  30439. if (newDetails.deltaUpdateFailed) {
  30440. return;
  30441. }
  30442. sliding = this.alignPlaylists(newDetails, curLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  30443. }
  30444. curLevel.details = newDetails;
  30445. this.levelLastLoaded = curLevel;
  30446. if (!startFragRequested) {
  30447. this.setStartPosition(newDetails, sliding);
  30448. }
  30449. this.hls.trigger(Events.LEVEL_UPDATED, {
  30450. details: newDetails,
  30451. level: newLevelId
  30452. });
  30453. if (this.state === State.WAITING_LEVEL) {
  30454. if (this.waitForCdnTuneIn(newDetails)) {
  30455. return;
  30456. }
  30457. this.state = State.IDLE;
  30458. }
  30459. if (startFragRequested && newDetails.live) {
  30460. this.synchronizeToLiveEdge(newDetails);
  30461. }
  30462. this.tick();
  30463. }
  30464. synchronizeToLiveEdge(levelDetails) {
  30465. const {
  30466. config,
  30467. media
  30468. } = this;
  30469. if (!media) {
  30470. return;
  30471. }
  30472. const liveSyncPosition = this.hls.liveSyncPosition;
  30473. const currentTime = this.getLoadPosition();
  30474. const start = levelDetails.fragmentStart;
  30475. const end = levelDetails.edge;
  30476. const withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end;
  30477. if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
  30478. const maxLatency = config.liveMaxLatencyDuration !== void 0 ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  30479. if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
  30480. if (!this._hasEnoughToStart) {
  30481. this.nextLoadPosition = liveSyncPosition;
  30482. }
  30483. if (media.readyState) {
  30484. this.warn(`Playback: ${currentTime.toFixed(3)} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);
  30485. if (this.config.liveSyncMode === "buffered") {
  30486. var _bufferInfo$buffered;
  30487. const bufferInfo = BufferHelper.bufferInfo(media, liveSyncPosition, 0);
  30488. if (!((_bufferInfo$buffered = bufferInfo.buffered) != null && _bufferInfo$buffered.length)) {
  30489. media.currentTime = liveSyncPosition;
  30490. return;
  30491. }
  30492. const isLiveSyncInBuffer = bufferInfo.start <= currentTime;
  30493. if (isLiveSyncInBuffer) {
  30494. media.currentTime = liveSyncPosition;
  30495. return;
  30496. }
  30497. const {
  30498. nextStart
  30499. } = BufferHelper.bufferedInfo(bufferInfo.buffered, currentTime, 0);
  30500. if (nextStart) {
  30501. media.currentTime = nextStart;
  30502. }
  30503. } else {
  30504. media.currentTime = liveSyncPosition;
  30505. }
  30506. }
  30507. }
  30508. }
  30509. }
  30510. _handleFragmentLoadProgress(data) {
  30511. var _frag$initSegment;
  30512. const frag = data.frag;
  30513. const {
  30514. part,
  30515. payload
  30516. } = data;
  30517. const {
  30518. levels
  30519. } = this;
  30520. if (!levels) {
  30521. this.warn(`Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  30522. return;
  30523. }
  30524. const currentLevel = levels[frag.level];
  30525. if (!currentLevel) {
  30526. this.warn(`Level ${frag.level} not found on progress`);
  30527. return;
  30528. }
  30529. const details = currentLevel.details;
  30530. if (!details) {
  30531. this.warn(`Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`);
  30532. this.fragmentTracker.removeFragment(frag);
  30533. return;
  30534. }
  30535. const videoCodec = currentLevel.videoCodec;
  30536. const accurateTimeOffset = details.PTSKnown || !details.live;
  30537. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  30538. const audioCodec = this._getAudioCodec(currentLevel);
  30539. const transmuxer = this.transmuxer = this.transmuxer || new TransmuxerInterface(this.hls, PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  30540. const partIndex = part ? part.index : -1;
  30541. const partial = partIndex !== -1;
  30542. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  30543. const initPTS = this.initPTS[frag.cc];
  30544. transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  30545. }
  30546. onAudioTrackSwitching(event, data) {
  30547. const hls = this.hls;
  30548. const fromAltAudio = this.altAudio === 2;
  30549. const altAudio = useAlternateAudio(data.url, hls);
  30550. if (!altAudio) {
  30551. if (this.mediaBuffer !== this.media) {
  30552. this.log("Switching on main audio, use media.buffered to schedule main fragment loading");
  30553. this.mediaBuffer = this.media;
  30554. const fragCurrent = this.fragCurrent;
  30555. if (fragCurrent) {
  30556. this.log("Switching to main audio track, cancel main fragment load");
  30557. fragCurrent.abortRequests();
  30558. this.fragmentTracker.removeFragment(fragCurrent);
  30559. }
  30560. this.resetTransmuxer();
  30561. this.resetLoadingState();
  30562. } else if (this.audioOnly) {
  30563. this.resetTransmuxer();
  30564. }
  30565. if (fromAltAudio) {
  30566. this.fragmentTracker.removeAllFragments();
  30567. hls.once(Events.BUFFER_FLUSHED, () => {
  30568. if (!this.hls) {
  30569. return;
  30570. }
  30571. this.hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  30572. });
  30573. hls.trigger(Events.BUFFER_FLUSHING, {
  30574. startOffset: 0,
  30575. endOffset: Number.POSITIVE_INFINITY,
  30576. type: null
  30577. });
  30578. return;
  30579. }
  30580. hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  30581. } else {
  30582. this.altAudio = 1;
  30583. }
  30584. }
  30585. onAudioTrackSwitched(event, data) {
  30586. const altAudio = useAlternateAudio(data.url, this.hls);
  30587. if (altAudio) {
  30588. const videoBuffer = this.videoBuffer;
  30589. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  30590. this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading");
  30591. this.mediaBuffer = videoBuffer;
  30592. }
  30593. }
  30594. this.altAudio = altAudio ? 2 : 0;
  30595. this.tick();
  30596. }
  30597. onBufferCreated(event, data) {
  30598. const tracks = data.tracks;
  30599. let mediaTrack;
  30600. let name;
  30601. let alternate = false;
  30602. for (const type in tracks) {
  30603. const track = tracks[type];
  30604. if (track.id === "main") {
  30605. name = type;
  30606. mediaTrack = track;
  30607. if (type === "video") {
  30608. const videoTrack = tracks[type];
  30609. if (videoTrack) {
  30610. this.videoBuffer = videoTrack.buffer;
  30611. }
  30612. }
  30613. } else {
  30614. alternate = true;
  30615. }
  30616. }
  30617. if (alternate && mediaTrack) {
  30618. this.log(`Alternate track found, use ${name}.buffered to schedule main fragment loading`);
  30619. this.mediaBuffer = mediaTrack.buffer;
  30620. } else {
  30621. this.mediaBuffer = this.media;
  30622. }
  30623. }
  30624. onFragBuffered(event, data) {
  30625. const {
  30626. frag,
  30627. part
  30628. } = data;
  30629. const bufferedMainFragment = frag.type === PlaylistLevelType.MAIN;
  30630. if (bufferedMainFragment) {
  30631. if (this.fragContextChanged(frag)) {
  30632. this.warn(`Fragment ${frag.sn}${part ? " p: " + part.index : ""} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}`);
  30633. if (this.state === State.PARSED) {
  30634. this.state = State.IDLE;
  30635. }
  30636. return;
  30637. }
  30638. const stats = part ? part.stats : frag.stats;
  30639. this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
  30640. if (isMediaFragment(frag)) {
  30641. this.fragPrevious = frag;
  30642. }
  30643. this.fragBufferedComplete(frag, part);
  30644. }
  30645. const media = this.media;
  30646. if (!media) {
  30647. return;
  30648. }
  30649. if (!this._hasEnoughToStart && BufferHelper.getBuffered(media).length) {
  30650. this._hasEnoughToStart = true;
  30651. this.seekToStartPos();
  30652. }
  30653. if (bufferedMainFragment) {
  30654. this.tick();
  30655. }
  30656. }
  30657. get hasEnoughToStart() {
  30658. return this._hasEnoughToStart;
  30659. }
  30660. onError(event, data) {
  30661. var _data$context;
  30662. if (data.fatal) {
  30663. this.state = State.ERROR;
  30664. return;
  30665. }
  30666. switch (data.details) {
  30667. case ErrorDetails.FRAG_GAP:
  30668. case ErrorDetails.FRAG_PARSING_ERROR:
  30669. case ErrorDetails.FRAG_DECRYPT_ERROR:
  30670. case ErrorDetails.FRAG_LOAD_ERROR:
  30671. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  30672. case ErrorDetails.KEY_LOAD_ERROR:
  30673. case ErrorDetails.KEY_LOAD_TIMEOUT:
  30674. this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);
  30675. break;
  30676. case ErrorDetails.LEVEL_LOAD_ERROR:
  30677. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  30678. case ErrorDetails.LEVEL_PARSING_ERROR:
  30679. if (!data.levelRetry && this.state === State.WAITING_LEVEL && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.LEVEL) {
  30680. this.state = State.IDLE;
  30681. }
  30682. break;
  30683. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  30684. case ErrorDetails.BUFFER_APPEND_ERROR:
  30685. if (data.parent !== "main") {
  30686. return;
  30687. }
  30688. if (this.reduceLengthAndFlushBuffer(data)) {
  30689. this.resetLoadingState();
  30690. }
  30691. break;
  30692. case ErrorDetails.BUFFER_FULL_ERROR:
  30693. if (data.parent !== "main") {
  30694. return;
  30695. }
  30696. if (this.reduceLengthAndFlushBuffer(data)) {
  30697. const isAssetPlayer = !this.config.interstitialsController && this.config.assetPlayerId;
  30698. if (isAssetPlayer) {
  30699. this._hasEnoughToStart = true;
  30700. } else {
  30701. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  30702. }
  30703. }
  30704. break;
  30705. case ErrorDetails.INTERNAL_EXCEPTION:
  30706. this.recoverWorkerError(data);
  30707. break;
  30708. }
  30709. }
  30710. onFragLoadEmergencyAborted() {
  30711. this.state = State.IDLE;
  30712. if (!this._hasEnoughToStart) {
  30713. this.startFragRequested = false;
  30714. this.nextLoadPosition = this.lastCurrentTime;
  30715. }
  30716. this.tickImmediate();
  30717. }
  30718. onBufferFlushed(event, {
  30719. type
  30720. }) {
  30721. if (type !== ElementaryStreamTypes.AUDIO || !this.altAudio) {
  30722. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  30723. if (mediaBuffer) {
  30724. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  30725. this.tick();
  30726. }
  30727. }
  30728. }
  30729. onLevelsUpdated(event, data) {
  30730. if (this.level > -1 && this.fragCurrent) {
  30731. this.level = this.fragCurrent.level;
  30732. if (this.level === -1) {
  30733. this.resetWhenMissingContext(this.fragCurrent);
  30734. }
  30735. }
  30736. this.levels = data.levels;
  30737. }
  30738. swapAudioCodec() {
  30739. this.audioCodecSwap = !this.audioCodecSwap;
  30740. }
  30741. /**
  30742. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  30743. */
  30744. seekToStartPos() {
  30745. const {
  30746. media
  30747. } = this;
  30748. if (!media) {
  30749. return;
  30750. }
  30751. const currentTime = media.currentTime;
  30752. let startPosition = this.startPosition;
  30753. if (startPosition >= 0 && currentTime < startPosition) {
  30754. if (media.seeking) {
  30755. this.log(`could not seek to ${startPosition}, already seeking at ${currentTime}`);
  30756. return;
  30757. }
  30758. const timelineOffset = this.timelineOffset;
  30759. if (timelineOffset && startPosition) {
  30760. startPosition += timelineOffset;
  30761. }
  30762. const details = this.getLevelDetails();
  30763. const buffered = BufferHelper.getBuffered(media);
  30764. const bufferStart = buffered.length ? buffered.start(0) : 0;
  30765. const delta = bufferStart - startPosition;
  30766. const skipTolerance = Math.max(this.config.maxBufferHole, this.config.maxFragLookUpTolerance);
  30767. if (this.config.startOnSegmentBoundary || delta > 0 && (delta < skipTolerance || this.loadingParts && delta < 2 * ((details == null ? void 0 : details.partTarget) || 0))) {
  30768. this.log(`adjusting start position by ${delta} to match buffer start`);
  30769. startPosition += delta;
  30770. this.startPosition = startPosition;
  30771. }
  30772. if (currentTime < startPosition) {
  30773. this.log(`seek to target start position ${startPosition} from current time ${currentTime} buffer start ${bufferStart}`);
  30774. media.currentTime = startPosition;
  30775. }
  30776. }
  30777. }
  30778. _getAudioCodec(currentLevel) {
  30779. let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  30780. if (this.audioCodecSwap && audioCodec) {
  30781. this.log("Swapping audio codec");
  30782. if (audioCodec.indexOf("mp4a.40.5") !== -1) {
  30783. audioCodec = "mp4a.40.2";
  30784. } else {
  30785. audioCodec = "mp4a.40.5";
  30786. }
  30787. }
  30788. return audioCodec;
  30789. }
  30790. _loadBitrateTestFrag(fragment, level) {
  30791. fragment.bitrateTest = true;
  30792. this._doFragLoad(fragment, level).then((data) => {
  30793. const {
  30794. hls
  30795. } = this;
  30796. const frag = data == null ? void 0 : data.frag;
  30797. if (!frag || this.fragContextChanged(frag)) {
  30798. return;
  30799. }
  30800. level.fragmentError = 0;
  30801. this.state = State.IDLE;
  30802. this.startFragRequested = false;
  30803. this.bitrateTest = false;
  30804. const stats = frag.stats;
  30805. stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
  30806. hls.trigger(Events.FRAG_LOADED, data);
  30807. frag.bitrateTest = false;
  30808. }).catch((reason) => {
  30809. if (this.state === State.STOPPED || this.state === State.ERROR) {
  30810. return;
  30811. }
  30812. this.warn(reason);
  30813. this.resetFragmentLoading(fragment);
  30814. });
  30815. }
  30816. _handleTransmuxComplete(transmuxResult) {
  30817. const id = this.playlistType;
  30818. const {
  30819. hls
  30820. } = this;
  30821. const {
  30822. remuxResult,
  30823. chunkMeta
  30824. } = transmuxResult;
  30825. const context = this.getCurrentContext(chunkMeta);
  30826. if (!context) {
  30827. this.resetWhenMissingContext(chunkMeta);
  30828. return;
  30829. }
  30830. const {
  30831. frag,
  30832. part,
  30833. level
  30834. } = context;
  30835. const {
  30836. video,
  30837. text,
  30838. id3,
  30839. initSegment
  30840. } = remuxResult;
  30841. const {
  30842. details
  30843. } = level;
  30844. const audio = this.altAudio ? void 0 : remuxResult.audio;
  30845. if (this.fragContextChanged(frag)) {
  30846. this.fragmentTracker.removeFragment(frag);
  30847. return;
  30848. }
  30849. this.state = State.PARSING;
  30850. if (initSegment) {
  30851. const tracks = initSegment.tracks;
  30852. if (tracks) {
  30853. const mapFragment = frag.initSegment || frag;
  30854. if (this.unhandledEncryptionError(initSegment, frag)) {
  30855. return;
  30856. }
  30857. this._bufferInitSegment(level, tracks, mapFragment, chunkMeta);
  30858. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  30859. frag: mapFragment,
  30860. id,
  30861. tracks
  30862. });
  30863. }
  30864. const baseTime = initSegment.initPTS;
  30865. const timescale = initSegment.timescale;
  30866. const initPTS = this.initPTS[frag.cc];
  30867. if (isFiniteNumber(baseTime) && (!initPTS || initPTS.baseTime !== baseTime || initPTS.timescale !== timescale)) {
  30868. const trackId = initSegment.trackId;
  30869. this.initPTS[frag.cc] = {
  30870. baseTime,
  30871. timescale,
  30872. trackId
  30873. };
  30874. hls.trigger(Events.INIT_PTS_FOUND, {
  30875. frag,
  30876. id,
  30877. initPTS: baseTime,
  30878. timescale,
  30879. trackId
  30880. });
  30881. }
  30882. }
  30883. if (video && details) {
  30884. if (audio && video.type === "audiovideo") {
  30885. this.logMuxedErr(frag);
  30886. }
  30887. const prevFrag = details.fragments[frag.sn - 1 - details.startSN];
  30888. const isFirstFragment = frag.sn === details.startSN;
  30889. const isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;
  30890. if (remuxResult.independent !== false) {
  30891. const {
  30892. startPTS,
  30893. endPTS,
  30894. startDTS,
  30895. endDTS
  30896. } = video;
  30897. if (part) {
  30898. part.elementaryStreams[video.type] = {
  30899. startPTS,
  30900. endPTS,
  30901. startDTS,
  30902. endDTS
  30903. };
  30904. } else {
  30905. if (video.firstKeyFrame && video.independent && chunkMeta.id === 1 && !isFirstInDiscontinuity) {
  30906. this.couldBacktrack = true;
  30907. }
  30908. if (video.dropped && video.independent) {
  30909. const bufferInfo = this.getMainFwdBufferInfo();
  30910. const targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole;
  30911. const startTime = video.firstKeyFramePTS ? video.firstKeyFramePTS : startPTS;
  30912. if (!isFirstFragment && targetBufferTime < startTime - this.config.maxBufferHole && !isFirstInDiscontinuity) {
  30913. this.backtrack(frag);
  30914. return;
  30915. } else if (isFirstInDiscontinuity) {
  30916. frag.gap = true;
  30917. }
  30918. frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
  30919. } else if (isFirstFragment && startPTS - (details.appliedTimelineOffset || 0) > MAX_START_GAP_JUMP) {
  30920. frag.gap = true;
  30921. }
  30922. }
  30923. frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
  30924. if (this.backtrackFragment) {
  30925. this.backtrackFragment = frag;
  30926. }
  30927. this.bufferFragmentData(video, frag, part, chunkMeta, isFirstFragment || isFirstInDiscontinuity);
  30928. } else if (isFirstFragment || isFirstInDiscontinuity) {
  30929. frag.gap = true;
  30930. } else {
  30931. this.backtrack(frag);
  30932. return;
  30933. }
  30934. }
  30935. if (audio) {
  30936. const {
  30937. startPTS,
  30938. endPTS,
  30939. startDTS,
  30940. endDTS
  30941. } = audio;
  30942. if (part) {
  30943. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  30944. startPTS,
  30945. endPTS,
  30946. startDTS,
  30947. endDTS
  30948. };
  30949. }
  30950. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  30951. this.bufferFragmentData(audio, frag, part, chunkMeta);
  30952. }
  30953. if (details && id3 != null && id3.samples.length) {
  30954. const emittedID3 = {
  30955. id,
  30956. frag,
  30957. details,
  30958. samples: id3.samples
  30959. };
  30960. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  30961. }
  30962. if (details && text) {
  30963. const emittedText = {
  30964. id,
  30965. frag,
  30966. details,
  30967. samples: text.samples
  30968. };
  30969. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  30970. }
  30971. }
  30972. logMuxedErr(frag) {
  30973. this.warn(`${isMediaFragment(frag) ? "Media" : "Init"} segment with muxed audiovideo where only video expected: ${frag.url}`);
  30974. }
  30975. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  30976. if (this.state !== State.PARSING) {
  30977. return;
  30978. }
  30979. this.audioOnly = !!tracks.audio && !tracks.video;
  30980. if (this.altAudio && !this.audioOnly) {
  30981. delete tracks.audio;
  30982. if (tracks.audiovideo) {
  30983. this.logMuxedErr(frag);
  30984. }
  30985. }
  30986. const {
  30987. audio,
  30988. video,
  30989. audiovideo
  30990. } = tracks;
  30991. if (audio) {
  30992. const levelCodec = currentLevel.audioCodec;
  30993. let audioCodec = pickMostCompleteCodecName(audio.codec, levelCodec);
  30994. if (audioCodec === "mp4a") {
  30995. audioCodec = "mp4a.40.5";
  30996. }
  30997. const ua = navigator.userAgent.toLowerCase();
  30998. if (this.audioCodecSwitch) {
  30999. if (audioCodec) {
  31000. if (audioCodec.indexOf("mp4a.40.5") !== -1) {
  31001. audioCodec = "mp4a.40.2";
  31002. } else {
  31003. audioCodec = "mp4a.40.5";
  31004. }
  31005. }
  31006. const audioMetadata = audio.metadata;
  31007. if (audioMetadata && "channelCount" in audioMetadata && (audioMetadata.channelCount || 1) !== 1 && ua.indexOf("firefox") === -1) {
  31008. audioCodec = "mp4a.40.5";
  31009. }
  31010. }
  31011. if (audioCodec && audioCodec.indexOf("mp4a.40.5") !== -1 && ua.indexOf("android") !== -1 && audio.container !== "audio/mpeg") {
  31012. audioCodec = "mp4a.40.2";
  31013. this.log(`Android: force audio codec to ${audioCodec}`);
  31014. }
  31015. if (levelCodec && levelCodec !== audioCodec) {
  31016. this.log(`Swapping manifest audio codec "${levelCodec}" for "${audioCodec}"`);
  31017. }
  31018. audio.levelCodec = audioCodec;
  31019. audio.id = PlaylistLevelType.MAIN;
  31020. this.log(`Init audio buffer, container:${audio.container}, codecs[selected/level/parsed]=[${audioCodec || ""}/${levelCodec || ""}/${audio.codec}]`);
  31021. delete tracks.audiovideo;
  31022. }
  31023. if (video) {
  31024. video.levelCodec = currentLevel.videoCodec;
  31025. video.id = PlaylistLevelType.MAIN;
  31026. const parsedVideoCodec = video.codec;
  31027. if ((parsedVideoCodec == null ? void 0 : parsedVideoCodec.length) === 4) {
  31028. switch (parsedVideoCodec) {
  31029. case "hvc1":
  31030. case "hev1":
  31031. video.codec = "hvc1.1.6.L120.90";
  31032. break;
  31033. case "av01":
  31034. video.codec = "av01.0.04M.08";
  31035. break;
  31036. case "avc1":
  31037. video.codec = "avc1.42e01e";
  31038. break;
  31039. }
  31040. }
  31041. 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 : ""}`);
  31042. delete tracks.audiovideo;
  31043. }
  31044. if (audiovideo) {
  31045. this.log(`Init audiovideo buffer, container:${audiovideo.container}, codecs[level/parsed]=[${currentLevel.codecs}/${audiovideo.codec}]`);
  31046. delete tracks.video;
  31047. delete tracks.audio;
  31048. }
  31049. const trackTypes = Object.keys(tracks);
  31050. if (trackTypes.length) {
  31051. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  31052. if (!this.hls) {
  31053. return;
  31054. }
  31055. trackTypes.forEach((trackName) => {
  31056. const track = tracks[trackName];
  31057. const initSegment = track.initSegment;
  31058. if (initSegment != null && initSegment.byteLength) {
  31059. this.hls.trigger(Events.BUFFER_APPENDING, {
  31060. type: trackName,
  31061. data: initSegment,
  31062. frag,
  31063. part: null,
  31064. chunkMeta,
  31065. parent: frag.type
  31066. });
  31067. }
  31068. });
  31069. }
  31070. this.tickImmediate();
  31071. }
  31072. getMainFwdBufferInfo() {
  31073. const bufferOutput = this.mediaBuffer && this.altAudio === 2 ? this.mediaBuffer : this.media;
  31074. return this.getFwdBufferInfo(bufferOutput, PlaylistLevelType.MAIN);
  31075. }
  31076. get maxBufferLength() {
  31077. const {
  31078. levels,
  31079. level
  31080. } = this;
  31081. const levelInfo = levels == null ? void 0 : levels[level];
  31082. if (!levelInfo) {
  31083. return this.config.maxBufferLength;
  31084. }
  31085. return this.getMaxBufferLength(levelInfo.maxBitrate);
  31086. }
  31087. backtrack(frag) {
  31088. this.couldBacktrack = true;
  31089. this.backtrackFragment = frag;
  31090. this.resetTransmuxer();
  31091. this.flushBufferGap(frag);
  31092. this.fragmentTracker.removeFragment(frag);
  31093. this.fragPrevious = null;
  31094. this.nextLoadPosition = frag.start;
  31095. this.state = State.IDLE;
  31096. }
  31097. checkFragmentChanged() {
  31098. const video = this.media;
  31099. let fragPlayingCurrent = null;
  31100. if (video && video.readyState > 1 && video.seeking === false) {
  31101. const currentTime = video.currentTime;
  31102. if (BufferHelper.isBuffered(video, currentTime)) {
  31103. fragPlayingCurrent = this.getAppendedFrag(currentTime);
  31104. } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
  31105. fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
  31106. }
  31107. if (fragPlayingCurrent) {
  31108. this.backtrackFragment = null;
  31109. const fragPlaying = this.fragPlaying;
  31110. const fragCurrentLevel = fragPlayingCurrent.level;
  31111. if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel) {
  31112. this.fragPlaying = fragPlayingCurrent;
  31113. this.hls.trigger(Events.FRAG_CHANGED, {
  31114. frag: fragPlayingCurrent
  31115. });
  31116. if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
  31117. this.hls.trigger(Events.LEVEL_SWITCHED, {
  31118. level: fragCurrentLevel
  31119. });
  31120. }
  31121. }
  31122. }
  31123. }
  31124. }
  31125. get nextLevel() {
  31126. const frag = this.nextBufferedFrag;
  31127. if (frag) {
  31128. return frag.level;
  31129. }
  31130. return -1;
  31131. }
  31132. get currentFrag() {
  31133. var _this$media2;
  31134. if (this.fragPlaying) {
  31135. return this.fragPlaying;
  31136. }
  31137. const currentTime = ((_this$media2 = this.media) == null ? void 0 : _this$media2.currentTime) || this.lastCurrentTime;
  31138. if (isFiniteNumber(currentTime)) {
  31139. return this.getAppendedFrag(currentTime);
  31140. }
  31141. return null;
  31142. }
  31143. get currentProgramDateTime() {
  31144. var _this$media3;
  31145. const currentTime = ((_this$media3 = this.media) == null ? void 0 : _this$media3.currentTime) || this.lastCurrentTime;
  31146. if (isFiniteNumber(currentTime)) {
  31147. const details = this.getLevelDetails();
  31148. const frag = this.currentFrag || (details ? findFragmentByPTS(null, details.fragments, currentTime) : null);
  31149. if (frag) {
  31150. const programDateTime = frag.programDateTime;
  31151. if (programDateTime !== null) {
  31152. const epocMs = programDateTime + (currentTime - frag.start) * 1e3;
  31153. return new Date(epocMs);
  31154. }
  31155. }
  31156. }
  31157. return null;
  31158. }
  31159. get currentLevel() {
  31160. const frag = this.currentFrag;
  31161. if (frag) {
  31162. return frag.level;
  31163. }
  31164. return -1;
  31165. }
  31166. get nextBufferedFrag() {
  31167. const frag = this.currentFrag;
  31168. if (frag) {
  31169. return this.followingBufferedFrag(frag);
  31170. }
  31171. return null;
  31172. }
  31173. get forceStartLoad() {
  31174. return this._forceStartLoad;
  31175. }
  31176. };
  31177. var KeyLoader = class extends Logger {
  31178. constructor(config, logger2) {
  31179. super("key-loader", logger2);
  31180. this.config = void 0;
  31181. this.keyIdToKeyInfo = {};
  31182. this.emeController = null;
  31183. this.config = config;
  31184. }
  31185. abort(type) {
  31186. for (const id in this.keyIdToKeyInfo) {
  31187. const loader = this.keyIdToKeyInfo[id].loader;
  31188. if (loader) {
  31189. var _loader$context;
  31190. if (type && type !== ((_loader$context = loader.context) == null ? void 0 : _loader$context.frag.type)) {
  31191. return;
  31192. }
  31193. loader.abort();
  31194. }
  31195. }
  31196. }
  31197. detach() {
  31198. for (const id in this.keyIdToKeyInfo) {
  31199. const keyInfo = this.keyIdToKeyInfo[id];
  31200. if (keyInfo.mediaKeySessionContext || keyInfo.decryptdata.isCommonEncryption) {
  31201. delete this.keyIdToKeyInfo[id];
  31202. }
  31203. }
  31204. }
  31205. destroy() {
  31206. this.detach();
  31207. for (const id in this.keyIdToKeyInfo) {
  31208. const loader = this.keyIdToKeyInfo[id].loader;
  31209. if (loader) {
  31210. loader.destroy();
  31211. }
  31212. }
  31213. this.keyIdToKeyInfo = {};
  31214. }
  31215. createKeyLoadError(frag, details = ErrorDetails.KEY_LOAD_ERROR, error, networkDetails, response) {
  31216. return new LoadError({
  31217. type: ErrorTypes.NETWORK_ERROR,
  31218. details,
  31219. fatal: false,
  31220. frag,
  31221. response,
  31222. error,
  31223. networkDetails
  31224. });
  31225. }
  31226. loadClear(loadingFrag, encryptedFragments, startFragRequested) {
  31227. if (this.emeController && this.config.emeEnabled && !this.emeController.getSelectedKeySystemFormats().length) {
  31228. if (encryptedFragments.length) {
  31229. for (let i = 0, l = encryptedFragments.length; i < l; i++) {
  31230. const frag = encryptedFragments[i];
  31231. if (loadingFrag.cc <= frag.cc && (!isMediaFragment(loadingFrag) || !isMediaFragment(frag) || loadingFrag.sn < frag.sn) || !startFragRequested && i == l - 1) {
  31232. return this.emeController.selectKeySystemFormat(frag).then((keySystemFormat) => {
  31233. if (!this.emeController) {
  31234. return;
  31235. }
  31236. frag.setKeyFormat(keySystemFormat);
  31237. const keySystem = keySystemFormatToKeySystemDomain(keySystemFormat);
  31238. if (keySystem) {
  31239. return this.emeController.getKeySystemAccess([keySystem]);
  31240. }
  31241. });
  31242. }
  31243. }
  31244. }
  31245. if (this.config.requireKeySystemAccessOnStart) {
  31246. const keySystemsInConfig = getKeySystemsForConfig(this.config);
  31247. if (keySystemsInConfig.length) {
  31248. return this.emeController.getKeySystemAccess(keySystemsInConfig);
  31249. }
  31250. }
  31251. }
  31252. return null;
  31253. }
  31254. load(frag) {
  31255. if (!frag.decryptdata && frag.encrypted && this.emeController && this.config.emeEnabled) {
  31256. return this.emeController.selectKeySystemFormat(frag).then((keySystemFormat) => {
  31257. return this.loadInternal(frag, keySystemFormat);
  31258. });
  31259. }
  31260. return this.loadInternal(frag);
  31261. }
  31262. loadInternal(frag, keySystemFormat) {
  31263. var _keyInfo, _keyInfo2;
  31264. if (keySystemFormat) {
  31265. frag.setKeyFormat(keySystemFormat);
  31266. }
  31267. const decryptdata = frag.decryptdata;
  31268. if (!decryptdata) {
  31269. const error = new Error(keySystemFormat ? `Expected frag.decryptdata to be defined after setting format ${keySystemFormat}` : `Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController && this.config.emeEnabled})`);
  31270. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error));
  31271. }
  31272. const uri = decryptdata.uri;
  31273. if (!uri) {
  31274. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Invalid key URI: "${uri}"`)));
  31275. }
  31276. const id = getKeyId(decryptdata);
  31277. let keyInfo = this.keyIdToKeyInfo[id];
  31278. if ((_keyInfo = keyInfo) != null && _keyInfo.decryptdata.key) {
  31279. decryptdata.key = keyInfo.decryptdata.key;
  31280. return Promise.resolve({
  31281. frag,
  31282. keyInfo
  31283. });
  31284. }
  31285. if (this.emeController && (_keyInfo2 = keyInfo) != null && _keyInfo2.keyLoadPromise) {
  31286. const keyStatus = this.emeController.getKeyStatus(keyInfo.decryptdata);
  31287. switch (keyStatus) {
  31288. case "usable":
  31289. case "usable-in-future":
  31290. return keyInfo.keyLoadPromise.then((keyLoadedData) => {
  31291. const {
  31292. keyInfo: keyInfo2
  31293. } = keyLoadedData;
  31294. decryptdata.key = keyInfo2.decryptdata.key;
  31295. return {
  31296. frag,
  31297. keyInfo: keyInfo2
  31298. };
  31299. });
  31300. }
  31301. }
  31302. this.log(`${this.keyIdToKeyInfo[id] ? "Rel" : "L"}oading${decryptdata.keyId ? " keyId: " + arrayToHex(decryptdata.keyId) : ""} URI: ${decryptdata.uri} from ${frag.type} ${frag.level}`);
  31303. keyInfo = this.keyIdToKeyInfo[id] = {
  31304. decryptdata,
  31305. keyLoadPromise: null,
  31306. loader: null,
  31307. mediaKeySessionContext: null
  31308. };
  31309. switch (decryptdata.method) {
  31310. case "SAMPLE-AES":
  31311. case "SAMPLE-AES-CENC":
  31312. case "SAMPLE-AES-CTR":
  31313. if (decryptdata.keyFormat === "identity") {
  31314. return this.loadKeyHTTP(keyInfo, frag);
  31315. }
  31316. return this.loadKeyEME(keyInfo, frag);
  31317. case "AES-128":
  31318. case "AES-256":
  31319. case "AES-256-CTR":
  31320. return this.loadKeyHTTP(keyInfo, frag);
  31321. default:
  31322. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Key supplied with unsupported METHOD: "${decryptdata.method}"`)));
  31323. }
  31324. }
  31325. loadKeyEME(keyInfo, frag) {
  31326. const keyLoadedData = {
  31327. frag,
  31328. keyInfo
  31329. };
  31330. if (this.emeController && this.config.emeEnabled) {
  31331. var _frag$initSegment;
  31332. if (!keyInfo.decryptdata.keyId && (_frag$initSegment = frag.initSegment) != null && _frag$initSegment.data) {
  31333. const keyIds = parseKeyIdsFromTenc(frag.initSegment.data);
  31334. if (keyIds.length) {
  31335. const keyId = keyIds[0];
  31336. if (keyId.some((b) => b !== 0)) {
  31337. this.log(`Using keyId found in init segment ${arrayToHex(keyId)}`);
  31338. keyInfo.decryptdata.keyId = keyId;
  31339. LevelKey.setKeyIdForUri(keyInfo.decryptdata.uri, keyId);
  31340. }
  31341. }
  31342. }
  31343. const keySessionContextPromise = this.emeController.loadKey(keyLoadedData);
  31344. return (keyInfo.keyLoadPromise = keySessionContextPromise.then((keySessionContext) => {
  31345. keyInfo.mediaKeySessionContext = keySessionContext;
  31346. return keyLoadedData;
  31347. })).catch((error) => {
  31348. keyInfo.keyLoadPromise = null;
  31349. if ("data" in error) {
  31350. error.data.frag = frag;
  31351. }
  31352. throw error;
  31353. });
  31354. }
  31355. return Promise.resolve(keyLoadedData);
  31356. }
  31357. loadKeyHTTP(keyInfo, frag) {
  31358. const config = this.config;
  31359. const Loader = config.loader;
  31360. const keyLoader = new Loader(config);
  31361. frag.keyLoader = keyInfo.loader = keyLoader;
  31362. return keyInfo.keyLoadPromise = new Promise((resolve, reject) => {
  31363. const loaderContext = {
  31364. keyInfo,
  31365. frag,
  31366. responseType: "arraybuffer",
  31367. url: keyInfo.decryptdata.uri
  31368. };
  31369. const loadPolicy = config.keyLoadPolicy.default;
  31370. const loaderConfig = {
  31371. loadPolicy,
  31372. timeout: loadPolicy.maxLoadTimeMs,
  31373. maxRetry: 0,
  31374. retryDelay: 0,
  31375. maxRetryDelay: 0
  31376. };
  31377. const loaderCallbacks = {
  31378. onSuccess: (response, stats, context, networkDetails) => {
  31379. const {
  31380. frag: frag2,
  31381. keyInfo: keyInfo2
  31382. } = context;
  31383. const id = getKeyId(keyInfo2.decryptdata);
  31384. if (!frag2.decryptdata || keyInfo2 !== this.keyIdToKeyInfo[id]) {
  31385. return reject(this.createKeyLoadError(frag2, ErrorDetails.KEY_LOAD_ERROR, new Error("after key load, decryptdata unset or changed"), networkDetails));
  31386. }
  31387. keyInfo2.decryptdata.key = frag2.decryptdata.key = new Uint8Array(response.data);
  31388. frag2.keyLoader = null;
  31389. keyInfo2.loader = null;
  31390. resolve({
  31391. frag: frag2,
  31392. keyInfo: keyInfo2
  31393. });
  31394. },
  31395. onError: (response, context, networkDetails, stats) => {
  31396. this.resetLoader(context);
  31397. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`HTTP Error ${response.code} loading key ${response.text}`), networkDetails, _objectSpread2({
  31398. url: loaderContext.url,
  31399. data: void 0
  31400. }, response)));
  31401. },
  31402. onTimeout: (stats, context, networkDetails) => {
  31403. this.resetLoader(context);
  31404. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_TIMEOUT, new Error("key loading timed out"), networkDetails));
  31405. },
  31406. onAbort: (stats, context, networkDetails) => {
  31407. this.resetLoader(context);
  31408. reject(this.createKeyLoadError(frag, ErrorDetails.INTERNAL_ABORTED, new Error("key loading aborted"), networkDetails));
  31409. }
  31410. };
  31411. keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  31412. });
  31413. }
  31414. resetLoader(context) {
  31415. const {
  31416. frag,
  31417. keyInfo,
  31418. url: uri
  31419. } = context;
  31420. const loader = keyInfo.loader;
  31421. if (frag.keyLoader === loader) {
  31422. frag.keyLoader = null;
  31423. keyInfo.loader = null;
  31424. }
  31425. const id = getKeyId(keyInfo.decryptdata) || uri;
  31426. delete this.keyIdToKeyInfo[id];
  31427. if (loader) {
  31428. loader.destroy();
  31429. }
  31430. }
  31431. };
  31432. function getKeyId(decryptdata) {
  31433. if (decryptdata.keyFormat !== KeySystemFormats.FAIRPLAY) {
  31434. const keyId = decryptdata.keyId;
  31435. if (keyId) {
  31436. return arrayToHex(keyId);
  31437. }
  31438. }
  31439. return decryptdata.uri;
  31440. }
  31441. function mapContextToLevelType(context) {
  31442. const {
  31443. type
  31444. } = context;
  31445. switch (type) {
  31446. case PlaylistContextType.AUDIO_TRACK:
  31447. return PlaylistLevelType.AUDIO;
  31448. case PlaylistContextType.SUBTITLE_TRACK:
  31449. return PlaylistLevelType.SUBTITLE;
  31450. default:
  31451. return PlaylistLevelType.MAIN;
  31452. }
  31453. }
  31454. function getResponseUrl(response, context) {
  31455. let url = response.url;
  31456. if (url === void 0 || url.indexOf("data:") === 0) {
  31457. url = context.url;
  31458. }
  31459. return url;
  31460. }
  31461. var PlaylistLoader = class {
  31462. constructor(hls) {
  31463. this.hls = void 0;
  31464. this.loaders = /* @__PURE__ */ Object.create(null);
  31465. this.variableList = null;
  31466. this.onManifestLoaded = this.checkAutostartLoad;
  31467. this.hls = hls;
  31468. this.registerListeners();
  31469. }
  31470. startLoad(startPosition) {
  31471. }
  31472. stopLoad() {
  31473. this.destroyInternalLoaders();
  31474. }
  31475. registerListeners() {
  31476. const {
  31477. hls
  31478. } = this;
  31479. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  31480. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  31481. hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  31482. hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  31483. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  31484. }
  31485. unregisterListeners() {
  31486. const {
  31487. hls
  31488. } = this;
  31489. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  31490. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  31491. hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  31492. hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  31493. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  31494. }
  31495. /**
  31496. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  31497. */
  31498. createInternalLoader(context) {
  31499. const config = this.hls.config;
  31500. const PLoader = config.pLoader;
  31501. const Loader = config.loader;
  31502. const InternalLoader = PLoader || Loader;
  31503. const loader = new InternalLoader(config);
  31504. this.loaders[context.type] = loader;
  31505. return loader;
  31506. }
  31507. getInternalLoader(context) {
  31508. return this.loaders[context.type];
  31509. }
  31510. resetInternalLoader(contextType) {
  31511. if (this.loaders[contextType]) {
  31512. delete this.loaders[contextType];
  31513. }
  31514. }
  31515. /**
  31516. * Call `destroy` on all internal loader instances mapped (one per context type)
  31517. */
  31518. destroyInternalLoaders() {
  31519. for (const contextType in this.loaders) {
  31520. const loader = this.loaders[contextType];
  31521. if (loader) {
  31522. loader.destroy();
  31523. }
  31524. this.resetInternalLoader(contextType);
  31525. }
  31526. }
  31527. destroy() {
  31528. this.variableList = null;
  31529. this.unregisterListeners();
  31530. this.destroyInternalLoaders();
  31531. }
  31532. onManifestLoading(event, data) {
  31533. const {
  31534. url
  31535. } = data;
  31536. this.variableList = null;
  31537. this.load({
  31538. id: null,
  31539. level: 0,
  31540. responseType: "text",
  31541. type: PlaylistContextType.MANIFEST,
  31542. url,
  31543. deliveryDirectives: null,
  31544. levelOrTrack: null
  31545. });
  31546. }
  31547. onLevelLoading(event, data) {
  31548. const {
  31549. id,
  31550. level,
  31551. pathwayId,
  31552. url,
  31553. deliveryDirectives,
  31554. levelInfo
  31555. } = data;
  31556. this.load({
  31557. id,
  31558. level,
  31559. pathwayId,
  31560. responseType: "text",
  31561. type: PlaylistContextType.LEVEL,
  31562. url,
  31563. deliveryDirectives,
  31564. levelOrTrack: levelInfo
  31565. });
  31566. }
  31567. onAudioTrackLoading(event, data) {
  31568. const {
  31569. id,
  31570. groupId,
  31571. url,
  31572. deliveryDirectives,
  31573. track
  31574. } = data;
  31575. this.load({
  31576. id,
  31577. groupId,
  31578. level: null,
  31579. responseType: "text",
  31580. type: PlaylistContextType.AUDIO_TRACK,
  31581. url,
  31582. deliveryDirectives,
  31583. levelOrTrack: track
  31584. });
  31585. }
  31586. onSubtitleTrackLoading(event, data) {
  31587. const {
  31588. id,
  31589. groupId,
  31590. url,
  31591. deliveryDirectives,
  31592. track
  31593. } = data;
  31594. this.load({
  31595. id,
  31596. groupId,
  31597. level: null,
  31598. responseType: "text",
  31599. type: PlaylistContextType.SUBTITLE_TRACK,
  31600. url,
  31601. deliveryDirectives,
  31602. levelOrTrack: track
  31603. });
  31604. }
  31605. onLevelsUpdated(event, data) {
  31606. const loader = this.loaders[PlaylistContextType.LEVEL];
  31607. if (loader) {
  31608. const context = loader.context;
  31609. if (context && !data.levels.some((lvl) => lvl === context.levelOrTrack)) {
  31610. loader.abort();
  31611. delete this.loaders[PlaylistContextType.LEVEL];
  31612. }
  31613. }
  31614. }
  31615. load(context) {
  31616. var _context$deliveryDire;
  31617. const config = this.hls.config;
  31618. let loader = this.getInternalLoader(context);
  31619. if (loader) {
  31620. const logger2 = this.hls.logger;
  31621. const loaderContext = loader.context;
  31622. if (loaderContext && loaderContext.levelOrTrack === context.levelOrTrack && (loaderContext.url === context.url || loaderContext.deliveryDirectives && !context.deliveryDirectives)) {
  31623. if (loaderContext.url === context.url) {
  31624. logger2.log(`[playlist-loader]: ignore ${context.url} ongoing request`);
  31625. } else {
  31626. logger2.log(`[playlist-loader]: ignore ${context.url} in favor of ${loaderContext.url}`);
  31627. }
  31628. return;
  31629. }
  31630. logger2.log(`[playlist-loader]: aborting previous loader for type: ${context.type}`);
  31631. loader.abort();
  31632. }
  31633. let loadPolicy;
  31634. if (context.type === PlaylistContextType.MANIFEST) {
  31635. loadPolicy = config.manifestLoadPolicy.default;
  31636. } else {
  31637. loadPolicy = _extends({}, config.playlistLoadPolicy.default, {
  31638. timeoutRetry: null,
  31639. errorRetry: null
  31640. });
  31641. }
  31642. loader = this.createInternalLoader(context);
  31643. if (isFiniteNumber((_context$deliveryDire = context.deliveryDirectives) == null ? void 0 : _context$deliveryDire.part)) {
  31644. let levelDetails;
  31645. if (context.type === PlaylistContextType.LEVEL && context.level !== null) {
  31646. levelDetails = this.hls.levels[context.level].details;
  31647. } else if (context.type === PlaylistContextType.AUDIO_TRACK && context.id !== null) {
  31648. levelDetails = this.hls.audioTracks[context.id].details;
  31649. } else if (context.type === PlaylistContextType.SUBTITLE_TRACK && context.id !== null) {
  31650. levelDetails = this.hls.subtitleTracks[context.id].details;
  31651. }
  31652. if (levelDetails) {
  31653. const partTarget = levelDetails.partTarget;
  31654. const targetDuration = levelDetails.targetduration;
  31655. if (partTarget && targetDuration) {
  31656. const maxLowLatencyPlaylistRefresh = Math.max(partTarget * 3, targetDuration * 0.8) * 1e3;
  31657. loadPolicy = _extends({}, loadPolicy, {
  31658. maxTimeToFirstByteMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs),
  31659. maxLoadTimeMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs)
  31660. });
  31661. }
  31662. }
  31663. }
  31664. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  31665. const loaderConfig = {
  31666. loadPolicy,
  31667. timeout: loadPolicy.maxLoadTimeMs,
  31668. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  31669. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  31670. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  31671. };
  31672. const loaderCallbacks = {
  31673. onSuccess: (response, stats, context2, networkDetails) => {
  31674. const loader2 = this.getInternalLoader(context2);
  31675. this.resetInternalLoader(context2.type);
  31676. const string = response.data;
  31677. stats.parsing.start = performance.now();
  31678. if (M3U8Parser.isMediaPlaylist(string) || context2.type !== PlaylistContextType.MANIFEST) {
  31679. this.handleTrackOrLevelPlaylist(response, stats, context2, networkDetails || null, loader2);
  31680. } else {
  31681. this.handleMasterPlaylist(response, stats, context2, networkDetails);
  31682. }
  31683. },
  31684. onError: (response, context2, networkDetails, stats) => {
  31685. this.handleNetworkError(context2, networkDetails, false, response, stats);
  31686. },
  31687. onTimeout: (stats, context2, networkDetails) => {
  31688. this.handleNetworkError(context2, networkDetails, true, void 0, stats);
  31689. }
  31690. };
  31691. loader.load(context, loaderConfig, loaderCallbacks);
  31692. }
  31693. checkAutostartLoad() {
  31694. if (!this.hls) {
  31695. return;
  31696. }
  31697. const {
  31698. config: {
  31699. autoStartLoad,
  31700. startPosition
  31701. },
  31702. forceStartLoad
  31703. } = this.hls;
  31704. if (autoStartLoad || forceStartLoad) {
  31705. this.hls.logger.log(`${autoStartLoad ? "auto" : "force"} startLoad with configured startPosition ${startPosition}`);
  31706. this.hls.startLoad(startPosition);
  31707. }
  31708. }
  31709. handleMasterPlaylist(response, stats, context, networkDetails) {
  31710. const hls = this.hls;
  31711. const string = response.data;
  31712. const url = getResponseUrl(response, context);
  31713. const parsedResult = M3U8Parser.parseMasterPlaylist(string, url);
  31714. if (parsedResult.playlistParsingError) {
  31715. stats.parsing.end = performance.now();
  31716. this.handleManifestParsingError(response, context, parsedResult.playlistParsingError, networkDetails, stats);
  31717. return;
  31718. }
  31719. const {
  31720. contentSteering,
  31721. levels,
  31722. sessionData,
  31723. sessionKeys,
  31724. startTimeOffset,
  31725. variableList
  31726. } = parsedResult;
  31727. this.variableList = variableList;
  31728. levels.forEach((levelParsed) => {
  31729. const {
  31730. unknownCodecs
  31731. } = levelParsed;
  31732. if (unknownCodecs) {
  31733. const {
  31734. preferManagedMediaSource
  31735. } = this.hls.config;
  31736. let {
  31737. audioCodec,
  31738. videoCodec
  31739. } = levelParsed;
  31740. for (let i = unknownCodecs.length; i--; ) {
  31741. const unknownCodec = unknownCodecs[i];
  31742. if (areCodecsMediaSourceSupported(unknownCodec, "audio", preferManagedMediaSource)) {
  31743. levelParsed.audioCodec = audioCodec = audioCodec ? `${audioCodec},${unknownCodec}` : unknownCodec;
  31744. sampleEntryCodesISO.audio[audioCodec.substring(0, 4)] = 2;
  31745. unknownCodecs.splice(i, 1);
  31746. } else if (areCodecsMediaSourceSupported(unknownCodec, "video", preferManagedMediaSource)) {
  31747. levelParsed.videoCodec = videoCodec = videoCodec ? `${videoCodec},${unknownCodec}` : unknownCodec;
  31748. sampleEntryCodesISO.video[videoCodec.substring(0, 4)] = 2;
  31749. unknownCodecs.splice(i, 1);
  31750. }
  31751. }
  31752. }
  31753. });
  31754. const {
  31755. AUDIO: audioTracks = [],
  31756. SUBTITLES: subtitles,
  31757. "CLOSED-CAPTIONS": captions
  31758. } = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult);
  31759. if (audioTracks.length) {
  31760. const embeddedAudioFound = audioTracks.some((audioTrack) => !audioTrack.url);
  31761. if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  31762. this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one");
  31763. audioTracks.unshift({
  31764. type: "main",
  31765. name: "main",
  31766. groupId: "main",
  31767. default: false,
  31768. autoselect: false,
  31769. forced: false,
  31770. id: -1,
  31771. attrs: new AttrList({}),
  31772. bitrate: 0,
  31773. url: ""
  31774. });
  31775. }
  31776. }
  31777. hls.trigger(Events.MANIFEST_LOADED, {
  31778. levels,
  31779. audioTracks,
  31780. subtitles,
  31781. captions,
  31782. contentSteering,
  31783. url,
  31784. stats,
  31785. networkDetails,
  31786. sessionData,
  31787. sessionKeys,
  31788. startTimeOffset,
  31789. variableList
  31790. });
  31791. }
  31792. handleTrackOrLevelPlaylist(response, stats, context, networkDetails, loader) {
  31793. const hls = this.hls;
  31794. const {
  31795. id,
  31796. level,
  31797. type
  31798. } = context;
  31799. const url = getResponseUrl(response, context);
  31800. const levelId = isFiniteNumber(level) ? level : isFiniteNumber(id) ? id : 0;
  31801. const levelType = mapContextToLevelType(context);
  31802. const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, 0, this.variableList);
  31803. if (type === PlaylistContextType.MANIFEST) {
  31804. const singleLevel = {
  31805. attrs: new AttrList({}),
  31806. bitrate: 0,
  31807. details: levelDetails,
  31808. name: "",
  31809. url
  31810. };
  31811. levelDetails.requestScheduled = stats.loading.start + computeReloadInterval(levelDetails, 0);
  31812. hls.trigger(Events.MANIFEST_LOADED, {
  31813. levels: [singleLevel],
  31814. audioTracks: [],
  31815. url,
  31816. stats,
  31817. networkDetails,
  31818. sessionData: null,
  31819. sessionKeys: null,
  31820. contentSteering: null,
  31821. startTimeOffset: null,
  31822. variableList: null
  31823. });
  31824. }
  31825. stats.parsing.end = performance.now();
  31826. context.levelDetails = levelDetails;
  31827. this.handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader);
  31828. }
  31829. handleManifestParsingError(response, context, error, networkDetails, stats) {
  31830. this.hls.trigger(Events.ERROR, {
  31831. type: ErrorTypes.NETWORK_ERROR,
  31832. details: ErrorDetails.MANIFEST_PARSING_ERROR,
  31833. fatal: context.type === PlaylistContextType.MANIFEST,
  31834. url: response.url,
  31835. err: error,
  31836. error,
  31837. reason: error.message,
  31838. response,
  31839. context,
  31840. networkDetails,
  31841. stats
  31842. });
  31843. }
  31844. handleNetworkError(context, networkDetails, timeout = false, response, stats) {
  31845. let message = `A network ${timeout ? "timeout" : "error" + (response ? " (status " + response.code + ")" : "")} occurred while loading ${context.type}`;
  31846. if (context.type === PlaylistContextType.LEVEL) {
  31847. message += `: ${context.level} id: ${context.id}`;
  31848. } else if (context.type === PlaylistContextType.AUDIO_TRACK || context.type === PlaylistContextType.SUBTITLE_TRACK) {
  31849. message += ` id: ${context.id} group-id: "${context.groupId}"`;
  31850. }
  31851. const error = new Error(message);
  31852. this.hls.logger.warn(`[playlist-loader]: ${message}`);
  31853. let details = ErrorDetails.UNKNOWN;
  31854. let fatal = false;
  31855. const loader = this.getInternalLoader(context);
  31856. switch (context.type) {
  31857. case PlaylistContextType.MANIFEST:
  31858. details = timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR;
  31859. fatal = true;
  31860. break;
  31861. case PlaylistContextType.LEVEL:
  31862. details = timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR;
  31863. fatal = false;
  31864. break;
  31865. case PlaylistContextType.AUDIO_TRACK:
  31866. details = timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  31867. fatal = false;
  31868. break;
  31869. case PlaylistContextType.SUBTITLE_TRACK:
  31870. details = timeout ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_LOAD_ERROR;
  31871. fatal = false;
  31872. break;
  31873. }
  31874. if (loader) {
  31875. this.resetInternalLoader(context.type);
  31876. }
  31877. const errorData = {
  31878. type: ErrorTypes.NETWORK_ERROR,
  31879. details,
  31880. fatal,
  31881. url: context.url,
  31882. loader,
  31883. context,
  31884. error,
  31885. networkDetails,
  31886. stats
  31887. };
  31888. if (response) {
  31889. const url = (networkDetails == null ? void 0 : networkDetails.url) || context.url;
  31890. errorData.response = _objectSpread2({
  31891. url,
  31892. data: void 0
  31893. }, response);
  31894. }
  31895. this.hls.trigger(Events.ERROR, errorData);
  31896. }
  31897. handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader) {
  31898. const hls = this.hls;
  31899. const {
  31900. type,
  31901. level,
  31902. levelOrTrack,
  31903. id,
  31904. groupId,
  31905. deliveryDirectives
  31906. } = context;
  31907. const url = getResponseUrl(response, context);
  31908. const parent = mapContextToLevelType(context);
  31909. let levelIndex = typeof context.level === "number" && parent === PlaylistLevelType.MAIN ? level : void 0;
  31910. const error = levelDetails.playlistParsingError;
  31911. if (error) {
  31912. this.hls.logger.warn(`${error} ${levelDetails.url}`);
  31913. if (!hls.config.ignorePlaylistParsingErrors) {
  31914. hls.trigger(Events.ERROR, {
  31915. type: ErrorTypes.NETWORK_ERROR,
  31916. details: ErrorDetails.LEVEL_PARSING_ERROR,
  31917. fatal: false,
  31918. url,
  31919. error,
  31920. reason: error.message,
  31921. response,
  31922. context,
  31923. level: levelIndex,
  31924. parent,
  31925. networkDetails,
  31926. stats
  31927. });
  31928. return;
  31929. }
  31930. levelDetails.playlistParsingError = null;
  31931. }
  31932. if (!levelDetails.fragments.length) {
  31933. const _error = levelDetails.playlistParsingError = new Error("No Segments found in Playlist");
  31934. hls.trigger(Events.ERROR, {
  31935. type: ErrorTypes.NETWORK_ERROR,
  31936. details: ErrorDetails.LEVEL_EMPTY_ERROR,
  31937. fatal: false,
  31938. url,
  31939. error: _error,
  31940. reason: _error.message,
  31941. response,
  31942. context,
  31943. level: levelIndex,
  31944. parent,
  31945. networkDetails,
  31946. stats
  31947. });
  31948. return;
  31949. }
  31950. if (levelDetails.live && loader) {
  31951. if (loader.getCacheAge) {
  31952. levelDetails.ageHeader = loader.getCacheAge() || 0;
  31953. }
  31954. if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
  31955. levelDetails.ageHeader = 0;
  31956. }
  31957. }
  31958. switch (type) {
  31959. case PlaylistContextType.MANIFEST:
  31960. case PlaylistContextType.LEVEL:
  31961. if (levelIndex) {
  31962. if (!levelOrTrack) {
  31963. levelIndex = 0;
  31964. } else {
  31965. if (levelOrTrack !== hls.levels[levelIndex]) {
  31966. const updatedIndex = hls.levels.indexOf(levelOrTrack);
  31967. if (updatedIndex > -1) {
  31968. levelIndex = updatedIndex;
  31969. }
  31970. }
  31971. }
  31972. }
  31973. hls.trigger(Events.LEVEL_LOADED, {
  31974. details: levelDetails,
  31975. levelInfo: levelOrTrack || hls.levels[0],
  31976. level: levelIndex || 0,
  31977. id: id || 0,
  31978. stats,
  31979. networkDetails,
  31980. deliveryDirectives,
  31981. withoutMultiVariant: type === PlaylistContextType.MANIFEST
  31982. });
  31983. break;
  31984. case PlaylistContextType.AUDIO_TRACK:
  31985. hls.trigger(Events.AUDIO_TRACK_LOADED, {
  31986. details: levelDetails,
  31987. track: levelOrTrack,
  31988. id: id || 0,
  31989. groupId: groupId || "",
  31990. stats,
  31991. networkDetails,
  31992. deliveryDirectives
  31993. });
  31994. break;
  31995. case PlaylistContextType.SUBTITLE_TRACK:
  31996. hls.trigger(Events.SUBTITLE_TRACK_LOADED, {
  31997. details: levelDetails,
  31998. track: levelOrTrack,
  31999. id: id || 0,
  32000. groupId: groupId || "",
  32001. stats,
  32002. networkDetails,
  32003. deliveryDirectives
  32004. });
  32005. break;
  32006. }
  32007. }
  32008. };
  32009. var Hls = class _Hls {
  32010. /**
  32011. * Get the video-dev/hls.js package version.
  32012. */
  32013. static get version() {
  32014. return version;
  32015. }
  32016. /**
  32017. * Check if the required MediaSource Extensions are available.
  32018. */
  32019. static isMSESupported() {
  32020. return isMSESupported();
  32021. }
  32022. /**
  32023. * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.
  32024. */
  32025. static isSupported() {
  32026. return isSupported();
  32027. }
  32028. /**
  32029. * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).
  32030. */
  32031. static getMediaSource() {
  32032. return getMediaSource();
  32033. }
  32034. static get Events() {
  32035. return Events;
  32036. }
  32037. static get MetadataSchema() {
  32038. return MetadataSchema;
  32039. }
  32040. static get ErrorTypes() {
  32041. return ErrorTypes;
  32042. }
  32043. static get ErrorDetails() {
  32044. return ErrorDetails;
  32045. }
  32046. /**
  32047. * Get the default configuration applied to new instances.
  32048. */
  32049. static get DefaultConfig() {
  32050. if (!_Hls.defaultConfig) {
  32051. return hlsDefaultConfig;
  32052. }
  32053. return _Hls.defaultConfig;
  32054. }
  32055. /**
  32056. * Replace the default configuration applied to new instances.
  32057. */
  32058. static set DefaultConfig(defaultConfig) {
  32059. _Hls.defaultConfig = defaultConfig;
  32060. }
  32061. /**
  32062. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  32063. * @param userConfig - Configuration options applied over `Hls.DefaultConfig`
  32064. */
  32065. constructor(userConfig = {}) {
  32066. this.config = void 0;
  32067. this.userConfig = void 0;
  32068. this.logger = void 0;
  32069. this.coreComponents = void 0;
  32070. this.networkControllers = void 0;
  32071. this._emitter = new EventEmitter();
  32072. this._autoLevelCapping = -1;
  32073. this._maxHdcpLevel = null;
  32074. this.abrController = void 0;
  32075. this.bufferController = void 0;
  32076. this.capLevelController = void 0;
  32077. this.latencyController = void 0;
  32078. this.levelController = void 0;
  32079. this.streamController = void 0;
  32080. this.audioStreamController = void 0;
  32081. this.subtititleStreamController = void 0;
  32082. this.audioTrackController = void 0;
  32083. this.subtitleTrackController = void 0;
  32084. this.interstitialsController = void 0;
  32085. this.gapController = void 0;
  32086. this.emeController = void 0;
  32087. this.cmcdController = void 0;
  32088. this._media = null;
  32089. this._url = null;
  32090. this._sessionId = void 0;
  32091. this.triggeringException = void 0;
  32092. this.started = false;
  32093. const logger2 = this.logger = enableLogs(userConfig.debug || false, "Hls instance", userConfig.assetPlayerId);
  32094. const config = this.config = mergeConfig(_Hls.DefaultConfig, userConfig, logger2);
  32095. this.userConfig = userConfig;
  32096. if (config.progressive) {
  32097. enableStreamingMode(config, logger2);
  32098. }
  32099. const {
  32100. abrController: _AbrController,
  32101. bufferController: _BufferController,
  32102. capLevelController: _CapLevelController,
  32103. errorController: _ErrorController,
  32104. fpsController: _FpsController
  32105. } = config;
  32106. const errorController = new _ErrorController(this);
  32107. const abrController = this.abrController = new _AbrController(this);
  32108. const fragmentTracker = new FragmentTracker(this);
  32109. const _InterstitialsController = config.interstitialsController;
  32110. const interstitialsController = _InterstitialsController ? this.interstitialsController = new _InterstitialsController(this, _Hls) : null;
  32111. const bufferController = this.bufferController = new _BufferController(this, fragmentTracker);
  32112. const capLevelController = this.capLevelController = new _CapLevelController(this);
  32113. const fpsController = new _FpsController(this);
  32114. const playListLoader = new PlaylistLoader(this);
  32115. const _ContentSteeringController = config.contentSteeringController;
  32116. const contentSteering = _ContentSteeringController ? new _ContentSteeringController(this) : null;
  32117. const levelController = this.levelController = new LevelController(this, contentSteering);
  32118. const id3TrackController = new ID3TrackController(this);
  32119. const keyLoader = new KeyLoader(this.config, this.logger);
  32120. const streamController = this.streamController = new StreamController(this, fragmentTracker, keyLoader);
  32121. const gapController = this.gapController = new GapController(this, fragmentTracker);
  32122. capLevelController.setStreamController(streamController);
  32123. fpsController.setStreamController(streamController);
  32124. const networkControllers = [playListLoader, levelController, streamController];
  32125. if (interstitialsController) {
  32126. networkControllers.splice(1, 0, interstitialsController);
  32127. }
  32128. if (contentSteering) {
  32129. networkControllers.splice(1, 0, contentSteering);
  32130. }
  32131. this.networkControllers = networkControllers;
  32132. const coreComponents = [abrController, bufferController, gapController, capLevelController, fpsController, id3TrackController, fragmentTracker];
  32133. this.audioTrackController = this.createController(config.audioTrackController, networkControllers);
  32134. const AudioStreamControllerClass = config.audioStreamController;
  32135. if (AudioStreamControllerClass) {
  32136. networkControllers.push(this.audioStreamController = new AudioStreamControllerClass(this, fragmentTracker, keyLoader));
  32137. }
  32138. this.subtitleTrackController = this.createController(config.subtitleTrackController, networkControllers);
  32139. const SubtitleStreamControllerClass = config.subtitleStreamController;
  32140. if (SubtitleStreamControllerClass) {
  32141. networkControllers.push(this.subtititleStreamController = new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader));
  32142. }
  32143. this.createController(config.timelineController, coreComponents);
  32144. keyLoader.emeController = this.emeController = this.createController(config.emeController, coreComponents);
  32145. this.cmcdController = this.createController(config.cmcdController, coreComponents);
  32146. this.latencyController = this.createController(LatencyController, coreComponents);
  32147. this.coreComponents = coreComponents;
  32148. networkControllers.push(errorController);
  32149. const onErrorOut = errorController.onErrorOut;
  32150. if (typeof onErrorOut === "function") {
  32151. this.on(Events.ERROR, onErrorOut, errorController);
  32152. }
  32153. this.on(Events.MANIFEST_LOADED, playListLoader.onManifestLoaded, playListLoader);
  32154. }
  32155. createController(ControllerClass, components) {
  32156. if (ControllerClass) {
  32157. const controllerInstance = new ControllerClass(this);
  32158. if (components) {
  32159. components.push(controllerInstance);
  32160. }
  32161. return controllerInstance;
  32162. }
  32163. return null;
  32164. }
  32165. // Delegate the EventEmitter through the public API of Hls.js
  32166. on(event, listener, context = this) {
  32167. this._emitter.on(event, listener, context);
  32168. }
  32169. once(event, listener, context = this) {
  32170. this._emitter.once(event, listener, context);
  32171. }
  32172. removeAllListeners(event) {
  32173. this._emitter.removeAllListeners(event);
  32174. }
  32175. off(event, listener, context = this, once) {
  32176. this._emitter.off(event, listener, context, once);
  32177. }
  32178. listeners(event) {
  32179. return this._emitter.listeners(event);
  32180. }
  32181. emit(event, name, eventObject) {
  32182. return this._emitter.emit(event, name, eventObject);
  32183. }
  32184. trigger(event, eventObject) {
  32185. if (this.config.debug) {
  32186. return this.emit(event, event, eventObject);
  32187. } else {
  32188. try {
  32189. return this.emit(event, event, eventObject);
  32190. } catch (error) {
  32191. this.logger.error("An internal error happened while handling event " + event + '. Error message: "' + error.message + '". Here is a stacktrace:', error);
  32192. if (!this.triggeringException) {
  32193. this.triggeringException = true;
  32194. const fatal = event === Events.ERROR;
  32195. this.trigger(Events.ERROR, {
  32196. type: ErrorTypes.OTHER_ERROR,
  32197. details: ErrorDetails.INTERNAL_EXCEPTION,
  32198. fatal,
  32199. event,
  32200. error
  32201. });
  32202. this.triggeringException = false;
  32203. }
  32204. }
  32205. }
  32206. return false;
  32207. }
  32208. listenerCount(event) {
  32209. return this._emitter.listenerCount(event);
  32210. }
  32211. /**
  32212. * Dispose of the instance
  32213. */
  32214. destroy() {
  32215. this.logger.log("destroy");
  32216. this.trigger(Events.DESTROYING, void 0);
  32217. this.detachMedia();
  32218. this.removeAllListeners();
  32219. this._autoLevelCapping = -1;
  32220. this._url = null;
  32221. this.networkControllers.forEach((component) => component.destroy());
  32222. this.networkControllers.length = 0;
  32223. this.coreComponents.forEach((component) => component.destroy());
  32224. this.coreComponents.length = 0;
  32225. const config = this.config;
  32226. config.xhrSetup = config.fetchSetup = void 0;
  32227. this.userConfig = null;
  32228. }
  32229. /**
  32230. * Attaches Hls.js to a media element
  32231. */
  32232. attachMedia(data) {
  32233. if (!data || "media" in data && !data.media) {
  32234. const error = new Error(`attachMedia failed: invalid argument (${data})`);
  32235. this.trigger(Events.ERROR, {
  32236. type: ErrorTypes.OTHER_ERROR,
  32237. details: ErrorDetails.ATTACH_MEDIA_ERROR,
  32238. fatal: true,
  32239. error
  32240. });
  32241. return;
  32242. }
  32243. this.logger.log(`attachMedia`);
  32244. if (this._media) {
  32245. this.logger.warn(`media must be detached before attaching`);
  32246. this.detachMedia();
  32247. }
  32248. const attachMediaSource = "media" in data;
  32249. const media = attachMediaSource ? data.media : data;
  32250. const attachingData = attachMediaSource ? data : {
  32251. media
  32252. };
  32253. this._media = media;
  32254. this.trigger(Events.MEDIA_ATTACHING, attachingData);
  32255. }
  32256. /**
  32257. * Detach Hls.js from the media
  32258. */
  32259. detachMedia() {
  32260. this.logger.log("detachMedia");
  32261. this.trigger(Events.MEDIA_DETACHING, {});
  32262. this._media = null;
  32263. }
  32264. /**
  32265. * Detach HTMLMediaElement, MediaSource, and SourceBuffers without reset, for attaching to another instance
  32266. */
  32267. transferMedia() {
  32268. this._media = null;
  32269. const transferMedia = this.bufferController.transferMedia();
  32270. this.trigger(Events.MEDIA_DETACHING, {
  32271. transferMedia
  32272. });
  32273. return transferMedia;
  32274. }
  32275. /**
  32276. * Set the source URL. Can be relative or absolute.
  32277. */
  32278. loadSource(url) {
  32279. this.stopLoad();
  32280. const media = this.media;
  32281. const loadedSource = this._url;
  32282. const loadingSource = this._url = urlToolkitExports.buildAbsoluteURL(self.location.href, url, {
  32283. alwaysNormalize: true
  32284. });
  32285. this._autoLevelCapping = -1;
  32286. this._maxHdcpLevel = null;
  32287. this.logger.log(`loadSource:${loadingSource}`);
  32288. if (media && loadedSource && (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())) {
  32289. this.detachMedia();
  32290. this.attachMedia(media);
  32291. }
  32292. this.trigger(Events.MANIFEST_LOADING, {
  32293. url
  32294. });
  32295. }
  32296. /**
  32297. * Gets the currently loaded URL
  32298. */
  32299. get url() {
  32300. return this._url;
  32301. }
  32302. /**
  32303. * Whether or not enough has been buffered to seek to start position or use `media.currentTime` to determine next load position
  32304. */
  32305. get hasEnoughToStart() {
  32306. return this.streamController.hasEnoughToStart;
  32307. }
  32308. /**
  32309. * Get the startPosition set on startLoad(position) or on autostart with config.startPosition
  32310. */
  32311. get startPosition() {
  32312. return this.streamController.startPositionValue;
  32313. }
  32314. /**
  32315. * Start loading data from the stream source.
  32316. * Depending on default config, client starts loading automatically when a source is set.
  32317. *
  32318. * @param startPosition - Set the start position to stream from.
  32319. * Defaults to -1 (None: starts from earliest point)
  32320. */
  32321. startLoad(startPosition = -1, skipSeekToStartPosition) {
  32322. this.logger.log(`startLoad(${startPosition + (skipSeekToStartPosition ? ", <skip seek to start>" : "")})`);
  32323. this.started = true;
  32324. this.resumeBuffering();
  32325. for (let i = 0; i < this.networkControllers.length; i++) {
  32326. this.networkControllers[i].startLoad(startPosition, skipSeekToStartPosition);
  32327. if (!this.started || !this.networkControllers) {
  32328. break;
  32329. }
  32330. }
  32331. }
  32332. /**
  32333. * Stop loading of any stream data.
  32334. */
  32335. stopLoad() {
  32336. this.logger.log("stopLoad");
  32337. this.started = false;
  32338. for (let i = 0; i < this.networkControllers.length; i++) {
  32339. this.networkControllers[i].stopLoad();
  32340. if (this.started || !this.networkControllers) {
  32341. break;
  32342. }
  32343. }
  32344. }
  32345. /**
  32346. * Returns whether loading, toggled with `startLoad()` and `stopLoad()`, is active or not`.
  32347. */
  32348. get loadingEnabled() {
  32349. return this.started;
  32350. }
  32351. /**
  32352. * Returns state of fragment loading toggled by calling `pauseBuffering()` and `resumeBuffering()`.
  32353. */
  32354. get bufferingEnabled() {
  32355. return this.streamController.bufferingEnabled;
  32356. }
  32357. /**
  32358. * Resumes stream controller segment loading after `pauseBuffering` has been called.
  32359. */
  32360. resumeBuffering() {
  32361. if (!this.bufferingEnabled) {
  32362. this.logger.log(`resume buffering`);
  32363. this.networkControllers.forEach((controller) => {
  32364. if (controller.resumeBuffering) {
  32365. controller.resumeBuffering();
  32366. }
  32367. });
  32368. }
  32369. }
  32370. /**
  32371. * Prevents stream controller from loading new segments until `resumeBuffering` is called.
  32372. * This allows for media buffering to be paused without interupting playlist loading.
  32373. */
  32374. pauseBuffering() {
  32375. if (this.bufferingEnabled) {
  32376. this.logger.log(`pause buffering`);
  32377. this.networkControllers.forEach((controller) => {
  32378. if (controller.pauseBuffering) {
  32379. controller.pauseBuffering();
  32380. }
  32381. });
  32382. }
  32383. }
  32384. get inFlightFragments() {
  32385. const inFlightData = {
  32386. [PlaylistLevelType.MAIN]: this.streamController.inFlightFrag
  32387. };
  32388. if (this.audioStreamController) {
  32389. inFlightData[PlaylistLevelType.AUDIO] = this.audioStreamController.inFlightFrag;
  32390. }
  32391. if (this.subtititleStreamController) {
  32392. inFlightData[PlaylistLevelType.SUBTITLE] = this.subtititleStreamController.inFlightFrag;
  32393. }
  32394. return inFlightData;
  32395. }
  32396. /**
  32397. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  32398. */
  32399. swapAudioCodec() {
  32400. this.logger.log("swapAudioCodec");
  32401. this.streamController.swapAudioCodec();
  32402. }
  32403. /**
  32404. * When the media-element fails, this allows to detach and then re-attach it
  32405. * as one call (convenience method).
  32406. *
  32407. * Automatic recovery of media-errors by this process is configurable.
  32408. */
  32409. recoverMediaError() {
  32410. this.logger.log("recoverMediaError");
  32411. const media = this._media;
  32412. const time = media == null ? void 0 : media.currentTime;
  32413. this.detachMedia();
  32414. if (media) {
  32415. this.attachMedia(media);
  32416. if (time) {
  32417. this.startLoad(time);
  32418. }
  32419. }
  32420. }
  32421. removeLevel(levelIndex) {
  32422. this.levelController.removeLevel(levelIndex);
  32423. }
  32424. /**
  32425. * @returns a UUID for this player instance
  32426. */
  32427. get sessionId() {
  32428. let _sessionId = this._sessionId;
  32429. if (!_sessionId) {
  32430. _sessionId = this._sessionId = uuid();
  32431. }
  32432. return _sessionId;
  32433. }
  32434. /**
  32435. * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH
  32436. */
  32437. get levels() {
  32438. const levels = this.levelController.levels;
  32439. return levels ? levels : [];
  32440. }
  32441. /**
  32442. * @returns LevelDetails of last loaded level (variant) or `null` prior to loading a media playlist.
  32443. */
  32444. get latestLevelDetails() {
  32445. return this.streamController.getLevelDetails() || null;
  32446. }
  32447. /**
  32448. * @returns Level object of selected level (variant) or `null` prior to selecting a level or once the level is removed.
  32449. */
  32450. get loadLevelObj() {
  32451. return this.levelController.loadLevelObj;
  32452. }
  32453. /**
  32454. * Index of quality level (variant) currently played
  32455. */
  32456. get currentLevel() {
  32457. return this.streamController.currentLevel;
  32458. }
  32459. /**
  32460. * Set quality level index immediately. This will flush the current buffer to replace the quality asap. That means playback will interrupt at least shortly to re-buffer and re-sync eventually. Set to -1 for automatic level selection.
  32461. */
  32462. set currentLevel(newLevel) {
  32463. this.logger.log(`set currentLevel:${newLevel}`);
  32464. this.levelController.manualLevel = newLevel;
  32465. this.streamController.immediateLevelSwitch();
  32466. }
  32467. /**
  32468. * Index of next quality level loaded as scheduled by stream controller.
  32469. */
  32470. get nextLevel() {
  32471. return this.streamController.nextLevel;
  32472. }
  32473. /**
  32474. * Set quality level index for next loaded data.
  32475. * This will switch the video quality asap, without interrupting playback.
  32476. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  32477. * @param newLevel - Pass -1 for automatic level selection
  32478. */
  32479. set nextLevel(newLevel) {
  32480. this.logger.log(`set nextLevel:${newLevel}`);
  32481. this.levelController.manualLevel = newLevel;
  32482. this.streamController.nextLevelSwitch();
  32483. }
  32484. /**
  32485. * Return the quality level of the currently or last (of none is loaded currently) segment
  32486. */
  32487. get loadLevel() {
  32488. return this.levelController.level;
  32489. }
  32490. /**
  32491. * Set quality level index for next loaded data in a conservative way.
  32492. * This will switch the quality without flushing, but interrupt current loading.
  32493. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  32494. * @param newLevel - Pass -1 for automatic level selection
  32495. */
  32496. set loadLevel(newLevel) {
  32497. this.logger.log(`set loadLevel:${newLevel}`);
  32498. this.levelController.manualLevel = newLevel;
  32499. }
  32500. /**
  32501. * get next quality level loaded
  32502. */
  32503. get nextLoadLevel() {
  32504. return this.levelController.nextLoadLevel;
  32505. }
  32506. /**
  32507. * Set quality level of next loaded segment in a fully "non-destructive" way.
  32508. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  32509. */
  32510. set nextLoadLevel(level) {
  32511. this.levelController.nextLoadLevel = level;
  32512. }
  32513. /**
  32514. * Return "first level": like a default level, if not set,
  32515. * falls back to index of first level referenced in manifest
  32516. */
  32517. get firstLevel() {
  32518. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  32519. }
  32520. /**
  32521. * Sets "first-level", see getter.
  32522. */
  32523. set firstLevel(newLevel) {
  32524. this.logger.log(`set firstLevel:${newLevel}`);
  32525. this.levelController.firstLevel = newLevel;
  32526. }
  32527. /**
  32528. * Return the desired start level for the first fragment that will be loaded.
  32529. * The default value of -1 indicates automatic start level selection.
  32530. * Setting hls.nextAutoLevel without setting a startLevel will result in
  32531. * the nextAutoLevel value being used for one fragment load.
  32532. */
  32533. get startLevel() {
  32534. const startLevel = this.levelController.startLevel;
  32535. if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {
  32536. return this.abrController.forcedAutoLevel;
  32537. }
  32538. return startLevel;
  32539. }
  32540. /**
  32541. * set start level (level of first fragment that will be played back)
  32542. * if not overrided by user, first level appearing in manifest will be used as start level
  32543. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  32544. * (determined from download of first segment)
  32545. */
  32546. set startLevel(newLevel) {
  32547. this.logger.log(`set startLevel:${newLevel}`);
  32548. if (newLevel !== -1) {
  32549. newLevel = Math.max(newLevel, this.minAutoLevel);
  32550. }
  32551. this.levelController.startLevel = newLevel;
  32552. }
  32553. /**
  32554. * Whether level capping is enabled.
  32555. * Default value is set via `config.capLevelToPlayerSize`.
  32556. */
  32557. get capLevelToPlayerSize() {
  32558. return this.config.capLevelToPlayerSize;
  32559. }
  32560. /**
  32561. * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.
  32562. */
  32563. set capLevelToPlayerSize(shouldStartCapping) {
  32564. const newCapLevelToPlayerSize = !!shouldStartCapping;
  32565. if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
  32566. if (newCapLevelToPlayerSize) {
  32567. this.capLevelController.startCapping();
  32568. } else {
  32569. this.capLevelController.stopCapping();
  32570. this.autoLevelCapping = -1;
  32571. this.streamController.nextLevelSwitch();
  32572. }
  32573. this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
  32574. }
  32575. }
  32576. /**
  32577. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  32578. */
  32579. get autoLevelCapping() {
  32580. return this._autoLevelCapping;
  32581. }
  32582. /**
  32583. * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.
  32584. */
  32585. get bandwidthEstimate() {
  32586. const {
  32587. bwEstimator
  32588. } = this.abrController;
  32589. if (!bwEstimator) {
  32590. return NaN;
  32591. }
  32592. return bwEstimator.getEstimate();
  32593. }
  32594. set bandwidthEstimate(abrEwmaDefaultEstimate) {
  32595. this.abrController.resetEstimator(abrEwmaDefaultEstimate);
  32596. }
  32597. get abrEwmaDefaultEstimate() {
  32598. const {
  32599. bwEstimator
  32600. } = this.abrController;
  32601. if (!bwEstimator) {
  32602. return NaN;
  32603. }
  32604. return bwEstimator.defaultEstimate;
  32605. }
  32606. /**
  32607. * get time to first byte estimate
  32608. * @type {number}
  32609. */
  32610. get ttfbEstimate() {
  32611. const {
  32612. bwEstimator
  32613. } = this.abrController;
  32614. if (!bwEstimator) {
  32615. return NaN;
  32616. }
  32617. return bwEstimator.getEstimateTTFB();
  32618. }
  32619. /**
  32620. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  32621. */
  32622. set autoLevelCapping(newLevel) {
  32623. if (this._autoLevelCapping !== newLevel) {
  32624. this.logger.log(`set autoLevelCapping:${newLevel}`);
  32625. this._autoLevelCapping = newLevel;
  32626. this.levelController.checkMaxAutoUpdated();
  32627. }
  32628. }
  32629. get maxHdcpLevel() {
  32630. return this._maxHdcpLevel;
  32631. }
  32632. set maxHdcpLevel(value) {
  32633. if (isHdcpLevel(value) && this._maxHdcpLevel !== value) {
  32634. this._maxHdcpLevel = value;
  32635. this.levelController.checkMaxAutoUpdated();
  32636. }
  32637. }
  32638. /**
  32639. * True when automatic level selection enabled
  32640. */
  32641. get autoLevelEnabled() {
  32642. return this.levelController.manualLevel === -1;
  32643. }
  32644. /**
  32645. * Level set manually (if any)
  32646. */
  32647. get manualLevel() {
  32648. return this.levelController.manualLevel;
  32649. }
  32650. /**
  32651. * min level selectable in auto mode according to config.minAutoBitrate
  32652. */
  32653. get minAutoLevel() {
  32654. const {
  32655. levels,
  32656. config: {
  32657. minAutoBitrate
  32658. }
  32659. } = this;
  32660. if (!levels)
  32661. return 0;
  32662. const len = levels.length;
  32663. for (let i = 0; i < len; i++) {
  32664. if (levels[i].maxBitrate >= minAutoBitrate) {
  32665. return i;
  32666. }
  32667. }
  32668. return 0;
  32669. }
  32670. /**
  32671. * max level selectable in auto mode according to autoLevelCapping
  32672. */
  32673. get maxAutoLevel() {
  32674. const {
  32675. levels,
  32676. autoLevelCapping,
  32677. maxHdcpLevel
  32678. } = this;
  32679. let maxAutoLevel;
  32680. if (autoLevelCapping === -1 && levels != null && levels.length) {
  32681. maxAutoLevel = levels.length - 1;
  32682. } else {
  32683. maxAutoLevel = autoLevelCapping;
  32684. }
  32685. if (maxHdcpLevel) {
  32686. for (let i = maxAutoLevel; i--; ) {
  32687. const hdcpLevel = levels[i].attrs["HDCP-LEVEL"];
  32688. if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {
  32689. return i;
  32690. }
  32691. }
  32692. }
  32693. return maxAutoLevel;
  32694. }
  32695. get firstAutoLevel() {
  32696. return this.abrController.firstAutoLevel;
  32697. }
  32698. /**
  32699. * next automatically selected quality level
  32700. */
  32701. get nextAutoLevel() {
  32702. return this.abrController.nextAutoLevel;
  32703. }
  32704. /**
  32705. * this setter is used to force next auto level.
  32706. * this is useful to force a switch down in auto mode:
  32707. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  32708. * forced value is valid for one fragment. upon successful frag loading at forced level,
  32709. * this value will be resetted to -1 by ABR controller.
  32710. */
  32711. set nextAutoLevel(nextLevel) {
  32712. this.abrController.nextAutoLevel = nextLevel;
  32713. }
  32714. /**
  32715. * get the datetime value relative to media.currentTime for the active level Program Date Time if present
  32716. */
  32717. get playingDate() {
  32718. return this.streamController.currentProgramDateTime;
  32719. }
  32720. get mainForwardBufferInfo() {
  32721. return this.streamController.getMainFwdBufferInfo();
  32722. }
  32723. get maxBufferLength() {
  32724. return this.streamController.maxBufferLength;
  32725. }
  32726. /**
  32727. * Find and select the best matching audio track, making a level switch when a Group change is necessary.
  32728. * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found.
  32729. */
  32730. setAudioOption(audioOption) {
  32731. var _this$audioTrackContr;
  32732. return ((_this$audioTrackContr = this.audioTrackController) == null ? void 0 : _this$audioTrackContr.setAudioOption(audioOption)) || null;
  32733. }
  32734. /**
  32735. * Find and select the best matching subtitle track, making a level switch when a Group change is necessary.
  32736. * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found.
  32737. */
  32738. setSubtitleOption(subtitleOption) {
  32739. var _this$subtitleTrackCo;
  32740. return ((_this$subtitleTrackCo = this.subtitleTrackController) == null ? void 0 : _this$subtitleTrackCo.setSubtitleOption(subtitleOption)) || null;
  32741. }
  32742. /**
  32743. * Get the complete list of audio tracks across all media groups
  32744. */
  32745. get allAudioTracks() {
  32746. const audioTrackController = this.audioTrackController;
  32747. return audioTrackController ? audioTrackController.allAudioTracks : [];
  32748. }
  32749. /**
  32750. * Get the list of selectable audio tracks
  32751. */
  32752. get audioTracks() {
  32753. const audioTrackController = this.audioTrackController;
  32754. return audioTrackController ? audioTrackController.audioTracks : [];
  32755. }
  32756. /**
  32757. * index of the selected audio track (index in audio track lists)
  32758. */
  32759. get audioTrack() {
  32760. const audioTrackController = this.audioTrackController;
  32761. return audioTrackController ? audioTrackController.audioTrack : -1;
  32762. }
  32763. /**
  32764. * selects an audio track, based on its index in audio track lists
  32765. */
  32766. set audioTrack(audioTrackId) {
  32767. const audioTrackController = this.audioTrackController;
  32768. if (audioTrackController) {
  32769. audioTrackController.audioTrack = audioTrackId;
  32770. }
  32771. }
  32772. /**
  32773. * get the complete list of subtitle tracks across all media groups
  32774. */
  32775. get allSubtitleTracks() {
  32776. const subtitleTrackController = this.subtitleTrackController;
  32777. return subtitleTrackController ? subtitleTrackController.allSubtitleTracks : [];
  32778. }
  32779. /**
  32780. * get alternate subtitle tracks list from playlist
  32781. */
  32782. get subtitleTracks() {
  32783. const subtitleTrackController = this.subtitleTrackController;
  32784. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  32785. }
  32786. /**
  32787. * index of the selected subtitle track (index in subtitle track lists)
  32788. */
  32789. get subtitleTrack() {
  32790. const subtitleTrackController = this.subtitleTrackController;
  32791. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  32792. }
  32793. get media() {
  32794. return this._media;
  32795. }
  32796. /**
  32797. * select an subtitle track, based on its index in subtitle track lists
  32798. */
  32799. set subtitleTrack(subtitleTrackId) {
  32800. const subtitleTrackController = this.subtitleTrackController;
  32801. if (subtitleTrackController) {
  32802. subtitleTrackController.subtitleTrack = subtitleTrackId;
  32803. }
  32804. }
  32805. /**
  32806. * Whether subtitle display is enabled or not
  32807. */
  32808. get subtitleDisplay() {
  32809. const subtitleTrackController = this.subtitleTrackController;
  32810. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  32811. }
  32812. /**
  32813. * Enable/disable subtitle display rendering
  32814. */
  32815. set subtitleDisplay(value) {
  32816. const subtitleTrackController = this.subtitleTrackController;
  32817. if (subtitleTrackController) {
  32818. subtitleTrackController.subtitleDisplay = value;
  32819. }
  32820. }
  32821. /**
  32822. * get mode for Low-Latency HLS loading
  32823. */
  32824. get lowLatencyMode() {
  32825. return this.config.lowLatencyMode;
  32826. }
  32827. /**
  32828. * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
  32829. */
  32830. set lowLatencyMode(mode) {
  32831. this.config.lowLatencyMode = mode;
  32832. }
  32833. /**
  32834. * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
  32835. * @returns null prior to loading live Playlist
  32836. */
  32837. get liveSyncPosition() {
  32838. return this.latencyController.liveSyncPosition;
  32839. }
  32840. /**
  32841. * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
  32842. * @returns 0 before first playlist is loaded
  32843. */
  32844. get latency() {
  32845. return this.latencyController.latency;
  32846. }
  32847. /**
  32848. * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
  32849. * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
  32850. * @returns 0 before first playlist is loaded
  32851. */
  32852. get maxLatency() {
  32853. return this.latencyController.maxLatency;
  32854. }
  32855. /**
  32856. * target distance from the edge as calculated by the latency controller
  32857. */
  32858. get targetLatency() {
  32859. return this.latencyController.targetLatency;
  32860. }
  32861. set targetLatency(latency) {
  32862. this.latencyController.targetLatency = latency;
  32863. }
  32864. /**
  32865. * the rate at which the edge of the current live playlist is advancing or 1 if there is none
  32866. */
  32867. get drift() {
  32868. return this.latencyController.drift;
  32869. }
  32870. /**
  32871. * set to true when startLoad is called before MANIFEST_PARSED event
  32872. */
  32873. get forceStartLoad() {
  32874. return this.streamController.forceStartLoad;
  32875. }
  32876. /**
  32877. * ContentSteering pathways getter
  32878. */
  32879. get pathways() {
  32880. return this.levelController.pathways;
  32881. }
  32882. /**
  32883. * ContentSteering pathwayPriority getter/setter
  32884. */
  32885. get pathwayPriority() {
  32886. return this.levelController.pathwayPriority;
  32887. }
  32888. set pathwayPriority(pathwayPriority) {
  32889. this.levelController.pathwayPriority = pathwayPriority;
  32890. }
  32891. /**
  32892. * returns true when all SourceBuffers are buffered to the end
  32893. */
  32894. get bufferedToEnd() {
  32895. var _this$bufferControlle;
  32896. return !!((_this$bufferControlle = this.bufferController) != null && _this$bufferControlle.bufferedToEnd);
  32897. }
  32898. /**
  32899. * returns Interstitials Program Manager
  32900. */
  32901. get interstitialsManager() {
  32902. var _this$interstitialsCo;
  32903. return ((_this$interstitialsCo = this.interstitialsController) == null ? void 0 : _this$interstitialsCo.interstitialsManager) || null;
  32904. }
  32905. /**
  32906. * returns mediaCapabilities.decodingInfo for a variant/rendition
  32907. */
  32908. getMediaDecodingInfo(level, audioTracks = this.allAudioTracks) {
  32909. const audioTracksByGroup = getAudioTracksByGroup(audioTracks);
  32910. return getMediaDecodingInfoPromise(level, audioTracksByGroup, navigator.mediaCapabilities);
  32911. }
  32912. };
  32913. Hls.defaultConfig = void 0;
  32914. export {
  32915. AbrController,
  32916. AttrList,
  32917. AudioStreamController,
  32918. AudioTrackController,
  32919. BasePlaylistController,
  32920. BaseSegment,
  32921. BaseStreamController,
  32922. BufferController,
  32923. CMCDController,
  32924. CapLevelController,
  32925. ChunkMetadata,
  32926. ContentSteeringController,
  32927. Cues,
  32928. DateRange,
  32929. EMEController,
  32930. ErrorActionFlags,
  32931. ErrorController,
  32932. ErrorDetails,
  32933. ErrorTypes,
  32934. Events,
  32935. FPSController,
  32936. FetchLoader,
  32937. Fragment,
  32938. Hls,
  32939. HlsSkip,
  32940. HlsUrlParameters,
  32941. KeySystemFormats,
  32942. KeySystems,
  32943. Level,
  32944. LevelDetails,
  32945. LevelKey,
  32946. LoadStats,
  32947. M3U8Parser,
  32948. MetadataSchema,
  32949. NetworkErrorAction,
  32950. Part,
  32951. PlaylistLevelType,
  32952. SubtitleStreamController,
  32953. SubtitleTrackController,
  32954. TimelineController,
  32955. XhrLoader,
  32956. Hls as default,
  32957. fetchSupported,
  32958. getMediaSource,
  32959. isMSESupported,
  32960. isSupported,
  32961. requestMediaKeySystemAccess
  32962. };
  32963. //# sourceMappingURL=hls__js.js.map