hls.light.mjs 832 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613
  1. // https://caniuse.com/mdn-javascript_builtins_number_isfinite
  2. const isFiniteNumber = Number.isFinite || function (value) {
  3. return typeof value === 'number' && isFinite(value);
  4. };
  5. // https://caniuse.com/mdn-javascript_builtins_number_issafeinteger
  6. const isSafeInteger = Number.isSafeInteger || function (value) {
  7. return typeof value === 'number' && Math.abs(value) <= MAX_SAFE_INTEGER;
  8. };
  9. const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  10. let ErrorTypes = /*#__PURE__*/function (ErrorTypes) {
  11. // Identifier for a network error (loading error / timeout ...)
  12. ErrorTypes["NETWORK_ERROR"] = "networkError";
  13. // Identifier for a media Error (video/parsing/mediasource error)
  14. ErrorTypes["MEDIA_ERROR"] = "mediaError";
  15. // EME (encrypted media extensions) errors
  16. ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError";
  17. // Identifier for a mux Error (demuxing/remuxing)
  18. ErrorTypes["MUX_ERROR"] = "muxError";
  19. // Identifier for all other errors
  20. ErrorTypes["OTHER_ERROR"] = "otherError";
  21. return ErrorTypes;
  22. }({});
  23. let ErrorDetails = /*#__PURE__*/function (ErrorDetails) {
  24. ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
  25. ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
  26. ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
  27. ErrorDetails["KEY_SYSTEM_NO_CONFIGURED_LICENSE"] = "keySystemNoConfiguredLicense";
  28. ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
  29. ErrorDetails["KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED"] = "keySystemServerCertificateRequestFailed";
  30. ErrorDetails["KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED"] = "keySystemServerCertificateUpdateFailed";
  31. ErrorDetails["KEY_SYSTEM_SESSION_UPDATE_FAILED"] = "keySystemSessionUpdateFailed";
  32. ErrorDetails["KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED"] = "keySystemStatusOutputRestricted";
  33. ErrorDetails["KEY_SYSTEM_STATUS_INTERNAL_ERROR"] = "keySystemStatusInternalError";
  34. ErrorDetails["KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR"] = "keySystemDestroyMediaKeysError";
  35. ErrorDetails["KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR"] = "keySystemDestroyCloseSessionError";
  36. ErrorDetails["KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR"] = "keySystemDestroyRemoveSessionError";
  37. // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  38. ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
  39. // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  40. ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
  41. // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}
  42. ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
  43. // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}
  44. ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
  45. // Identifier for a level which contains no fragments - data: { url: faulty URL, reason: "no fragments found in level", level: index of the bad level }
  46. ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
  47. // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  48. ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError";
  49. // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  50. ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
  51. // Identifier for a level parse error - data: { url : faulty URL, error: Error, reason: error message }
  52. ErrorDetails["LEVEL_PARSING_ERROR"] = "levelParsingError";
  53. // Identifier for a level switch error - data: { level : faulty level Id, event : error description}
  54. ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
  55. // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  56. ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
  57. // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  58. ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
  59. // Identifier for a subtitle track load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  60. ErrorDetails["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
  61. // Identifier for a subtitle track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  62. ErrorDetails["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
  63. // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  64. ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError";
  65. // Identifier for fragment load timeout error - data: { frag : fragment object}
  66. ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
  67. // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }
  68. ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
  69. // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }
  70. // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release
  71. ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError";
  72. // Identifier for a fragment or part load skipped because of a GAP tag or attribute
  73. ErrorDetails["FRAG_GAP"] = "fragGap";
  74. // Identifier for a remux alloc error event - data: { id : demuxer Id, frag : fragment object, bytes : nb of bytes on which allocation failed , reason : error text }
  75. ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError";
  76. // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  77. ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError";
  78. // Identifier for decrypt key load timeout error - data: { frag : fragment object}
  79. ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
  80. // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { error : exception , mimeType : mimeType }
  81. ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
  82. // Triggered when source buffer(s) could not be created using level (manifest CODECS attribute), parsed media, or best guess codec(s) - data: { reason : error reason }
  83. ErrorDetails["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
  84. // Identifier for a buffer append error - data: append error description
  85. ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError";
  86. // Identifier for a buffer appending error event - data: appending error description
  87. ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
  88. // Identifier for a buffer stalled error event
  89. ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError";
  90. // Identifier for a buffer full event
  91. ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError";
  92. // Identifier for a buffer seek over hole event
  93. ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
  94. // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)
  95. ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
  96. // Identifier for a Interstitial Asset List load error - data: { url: faulty URL, response: { code: error code, text: error text } }
  97. ErrorDetails["ASSET_LIST_LOAD_ERROR"] = "assetListLoadError";
  98. // Identifier for a Interstitial Asset List load timeout - data: { url: faulty URL, response: { code: error code, text: error text } }
  99. ErrorDetails["ASSET_LIST_LOAD_TIMEOUT"] = "assetListLoadTimeout";
  100. // Identifier for a Interstitial Asset List parsing error - data: { url : faulty URL, reason : error reason, response : { code: error code, text: error text }}
  101. ErrorDetails["ASSET_LIST_PARSING_ERROR"] = "assetListParsingError";
  102. // Identifier for a Interstitial Asset List parsing error - data: { url : faulty URL, reason : error reason, response : { code: error code, text: error text }}
  103. ErrorDetails["INTERSTITIAL_ASSET_ITEM_ERROR"] = "interstitialAssetItemError";
  104. // Identifier for an internal exception happening inside hls.js while handling an event
  105. ErrorDetails["INTERNAL_EXCEPTION"] = "internalException";
  106. // Identifier for an internal call to abort a loader
  107. ErrorDetails["INTERNAL_ABORTED"] = "aborted";
  108. // Triggered when attachMedia fails
  109. ErrorDetails["ATTACH_MEDIA_ERROR"] = "attachMediaError";
  110. // Uncategorized error
  111. ErrorDetails["UNKNOWN"] = "unknown";
  112. return ErrorDetails;
  113. }({});
  114. let Events = /*#__PURE__*/function (Events) {
  115. // Fired before MediaSource is attaching to media element
  116. Events["MEDIA_ATTACHING"] = "hlsMediaAttaching";
  117. // Fired when MediaSource has been successfully attached to media element
  118. Events["MEDIA_ATTACHED"] = "hlsMediaAttached";
  119. // Fired before detaching MediaSource from media element
  120. Events["MEDIA_DETACHING"] = "hlsMediaDetaching";
  121. // Fired when MediaSource has been detached from media element
  122. Events["MEDIA_DETACHED"] = "hlsMediaDetached";
  123. // Fired when HTMLMediaElement dispatches "ended" event, or stalls at end of VOD program
  124. Events["MEDIA_ENDED"] = "hlsMediaEnded";
  125. // Fired after playback stall is resolved with playing, seeked, or ended event following BUFFER_STALLED_ERROR
  126. Events["STALL_RESOLVED"] = "hlsStallResolved";
  127. // Fired when the buffer is going to be reset
  128. Events["BUFFER_RESET"] = "hlsBufferReset";
  129. // Fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}
  130. Events["BUFFER_CODECS"] = "hlsBufferCodecs";
  131. // fired when sourcebuffers have been created - data: { tracks : tracks }
  132. Events["BUFFER_CREATED"] = "hlsBufferCreated";
  133. // fired when we append a segment to the buffer - data: { segment: segment object }
  134. Events["BUFFER_APPENDING"] = "hlsBufferAppending";
  135. // fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent}
  136. Events["BUFFER_APPENDED"] = "hlsBufferAppended";
  137. // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }
  138. Events["BUFFER_EOS"] = "hlsBufferEos";
  139. // fired when all buffers are full to the end of the program, after calling MediaSource.endOfStream() (unless restricted)
  140. Events["BUFFERED_TO_END"] = "hlsBufferedToEnd";
  141. // fired when the media buffer should be flushed - data { startOffset, endOffset }
  142. Events["BUFFER_FLUSHING"] = "hlsBufferFlushing";
  143. // fired when the media buffer has been flushed - data: { }
  144. Events["BUFFER_FLUSHED"] = "hlsBufferFlushed";
  145. // fired to signal that a manifest loading starts - data: { url : manifestURL}
  146. Events["MANIFEST_LOADING"] = "hlsManifestLoading";
  147. // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks ], url : manifestURL, stats : LoaderStats }
  148. Events["MANIFEST_LOADED"] = "hlsManifestLoaded";
  149. // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}
  150. Events["MANIFEST_PARSED"] = "hlsManifestParsed";
  151. // fired when a level switch is requested - data: { level : id of new level }
  152. Events["LEVEL_SWITCHING"] = "hlsLevelSwitching";
  153. // fired when a level switch is effective - data: { level : id of new level }
  154. Events["LEVEL_SWITCHED"] = "hlsLevelSwitched";
  155. // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}
  156. Events["LEVEL_LOADING"] = "hlsLevelLoading";
  157. // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : LoaderStats }
  158. Events["LEVEL_LOADED"] = "hlsLevelLoaded";
  159. // fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level }
  160. Events["LEVEL_UPDATED"] = "hlsLevelUpdated";
  161. // fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }
  162. Events["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
  163. // fired to notify that levels have changed after removing a level - data: { levels : [available quality levels] }
  164. Events["LEVELS_UPDATED"] = "hlsLevelsUpdated";
  165. // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }
  166. Events["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
  167. // fired when an audio track switching is requested - data: { id : audio track id }
  168. Events["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
  169. // fired when an audio track switch actually occurs - data: { id : audio track id }
  170. Events["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
  171. // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }
  172. Events["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
  173. // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : LoaderStats }
  174. Events["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
  175. // fired when an audio tracks's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, id : track id }
  176. Events["AUDIO_TRACK_UPDATED"] = "hlsAudioTrackUpdated";
  177. // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }
  178. Events["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
  179. // fired to notify that subtitle tracks were cleared as a result of stopping the media
  180. Events["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
  181. // fired when an subtitle track switch occurs - data: { id : subtitle track id }
  182. Events["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
  183. // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }
  184. Events["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
  185. // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : LoaderStats }
  186. Events["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
  187. // fired when a subtitle racks's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, id : track id }
  188. Events["SUBTITLE_TRACK_UPDATED"] = "hlsSubtitleTrackUpdated";
  189. // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }
  190. Events["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
  191. // fired when a set of VTTCues to be managed externally has been parsed - data: { type: string, track: string, cues: [ VTTCue ] }
  192. Events["CUES_PARSED"] = "hlsCuesParsed";
  193. // fired when a text track to be managed externally is found - data: { tracks: [ { label: string, kind: string, default: boolean } ] }
  194. Events["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
  195. // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, timescale: timescale, frag : fragment object }
  196. Events["INIT_PTS_FOUND"] = "hlsInitPtsFound";
  197. // fired when a fragment loading starts - data: { frag : fragment object }
  198. Events["FRAG_LOADING"] = "hlsFragLoading";
  199. // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }
  200. // FRAG_LOAD_PROGRESS = 'hlsFragLoadProgress',
  201. // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }
  202. Events["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
  203. // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : LoaderStats }
  204. Events["FRAG_LOADED"] = "hlsFragLoaded";
  205. // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }
  206. Events["FRAG_DECRYPTED"] = "hlsFragDecrypted";
  207. // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }
  208. Events["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
  209. // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }
  210. Events["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
  211. // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }
  212. Events["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
  213. // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}
  214. // FRAG_PARSING_DATA = 'hlsFragParsingData',
  215. // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }
  216. Events["FRAG_PARSED"] = "hlsFragParsed";
  217. // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : LoaderStats }
  218. Events["FRAG_BUFFERED"] = "hlsFragBuffered";
  219. // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }
  220. Events["FRAG_CHANGED"] = "hlsFragChanged";
  221. // Identifier for a FPS drop event - data: { currentDropped, currentDecoded, totalDroppedFrames }
  222. Events["FPS_DROP"] = "hlsFpsDrop";
  223. // triggered when FPS drop triggers auto level capping - data: { level, droppedLevel }
  224. Events["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
  225. // triggered when maxAutoLevel changes - data { autoLevelCapping, levels, maxAutoLevel, minAutoLevel, maxHdcpLevel }
  226. Events["MAX_AUTO_LEVEL_UPDATED"] = "hlsMaxAutoLevelUpdated";
  227. // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }
  228. Events["ERROR"] = "hlsError";
  229. // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }
  230. Events["DESTROYING"] = "hlsDestroying";
  231. // fired when a decrypt key loading starts - data: { frag : fragment object }
  232. Events["KEY_LOADING"] = "hlsKeyLoading";
  233. // fired when a decrypt key loading is completed - data: { frag : fragment object, keyInfo : KeyLoaderInfo }
  234. Events["KEY_LOADED"] = "hlsKeyLoaded";
  235. // deprecated; please use BACK_BUFFER_REACHED - data : { bufferEnd: number }
  236. Events["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
  237. // fired when the back buffer is reached as defined by the backBufferLength config option - data : { bufferEnd: number }
  238. Events["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
  239. // fired after steering manifest has been loaded - data: { steeringManifest: SteeringManifest object, url: steering manifest URL }
  240. Events["STEERING_MANIFEST_LOADED"] = "hlsSteeringManifestLoaded";
  241. // fired when asset list has begun loading
  242. Events["ASSET_LIST_LOADING"] = "hlsAssetListLoading";
  243. // fired when a valid asset list is loaded
  244. Events["ASSET_LIST_LOADED"] = "hlsAssetListLoaded";
  245. // fired when the list of Interstitial Events and Interstitial Schedule is updated
  246. Events["INTERSTITIALS_UPDATED"] = "hlsInterstitialsUpdated";
  247. // fired when the buffer reaches an Interstitial Schedule boundary (both Primary segments and Interstitial Assets)
  248. Events["INTERSTITIALS_BUFFERED_TO_BOUNDARY"] = "hlsInterstitialsBufferedToBoundary";
  249. // fired when a player instance for an Interstitial Asset has been created
  250. Events["INTERSTITIAL_ASSET_PLAYER_CREATED"] = "hlsInterstitialAssetPlayerCreated";
  251. // Interstitial playback started
  252. Events["INTERSTITIAL_STARTED"] = "hlsInterstitialStarted";
  253. // InterstitialAsset playback started
  254. Events["INTERSTITIAL_ASSET_STARTED"] = "hlsInterstitialAssetStarted";
  255. // InterstitialAsset playback ended
  256. Events["INTERSTITIAL_ASSET_ENDED"] = "hlsInterstitialAssetEnded";
  257. // InterstitialAsset playback errored
  258. Events["INTERSTITIAL_ASSET_ERROR"] = "hlsInterstitialAssetError";
  259. // Interstitial playback ended
  260. Events["INTERSTITIAL_ENDED"] = "hlsInterstitialEnded";
  261. // Interstitial schedule resumed primary playback
  262. Events["INTERSTITIALS_PRIMARY_RESUMED"] = "hlsInterstitialsPrimaryResumed";
  263. // Interstitial players dispatch this event when playout limit is reached
  264. Events["PLAYOUT_LIMIT_REACHED"] = "hlsPlayoutLimitReached";
  265. // Event DateRange cue "enter" event dispatched
  266. Events["EVENT_CUE_ENTER"] = "hlsEventCueEnter";
  267. return Events;
  268. }({});
  269. /**
  270. * Defines each Event type and payload by Event name. Used in {@link hls.js#HlsEventEmitter} to strongly type the event listener API.
  271. */
  272. var PlaylistContextType = {
  273. MANIFEST: "manifest",
  274. LEVEL: "level",
  275. AUDIO_TRACK: "audioTrack",
  276. SUBTITLE_TRACK: "subtitleTrack"
  277. };
  278. var PlaylistLevelType = {
  279. MAIN: "main",
  280. AUDIO: "audio",
  281. SUBTITLE: "subtitle"
  282. };
  283. /*
  284. * compute an Exponential Weighted moving average
  285. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  286. * - heavily inspired from shaka-player
  287. */
  288. class EWMA {
  289. // About half of the estimated value will be from the last |halfLife| samples by weight.
  290. constructor(halfLife, estimate = 0, weight = 0) {
  291. this.halfLife = void 0;
  292. this.alpha_ = void 0;
  293. this.estimate_ = void 0;
  294. this.totalWeight_ = void 0;
  295. this.halfLife = halfLife;
  296. // Larger values of alpha expire historical data more slowly.
  297. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  298. this.estimate_ = estimate;
  299. this.totalWeight_ = weight;
  300. }
  301. sample(weight, value) {
  302. const adjAlpha = Math.pow(this.alpha_, weight);
  303. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  304. this.totalWeight_ += weight;
  305. }
  306. getTotalWeight() {
  307. return this.totalWeight_;
  308. }
  309. getEstimate() {
  310. if (this.alpha_) {
  311. const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  312. if (zeroFactor) {
  313. return this.estimate_ / zeroFactor;
  314. }
  315. }
  316. return this.estimate_;
  317. }
  318. }
  319. /*
  320. * EWMA Bandwidth Estimator
  321. * - heavily inspired from shaka-player
  322. * Tracks bandwidth samples and estimates available bandwidth.
  323. * Based on the minimum of two exponentially-weighted moving averages with
  324. * different half-lives.
  325. */
  326. class EwmaBandWidthEstimator {
  327. constructor(slow, fast, defaultEstimate, defaultTTFB = 100) {
  328. this.defaultEstimate_ = void 0;
  329. this.minWeight_ = void 0;
  330. this.minDelayMs_ = void 0;
  331. this.slow_ = void 0;
  332. this.fast_ = void 0;
  333. this.defaultTTFB_ = void 0;
  334. this.ttfb_ = void 0;
  335. this.defaultEstimate_ = defaultEstimate;
  336. this.minWeight_ = 0.001;
  337. this.minDelayMs_ = 50;
  338. this.slow_ = new EWMA(slow);
  339. this.fast_ = new EWMA(fast);
  340. this.defaultTTFB_ = defaultTTFB;
  341. this.ttfb_ = new EWMA(slow);
  342. }
  343. update(slow, fast) {
  344. const {
  345. slow_,
  346. fast_,
  347. ttfb_
  348. } = this;
  349. if (slow_.halfLife !== slow) {
  350. this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());
  351. }
  352. if (fast_.halfLife !== fast) {
  353. this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());
  354. }
  355. if (ttfb_.halfLife !== slow) {
  356. this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());
  357. }
  358. }
  359. sample(durationMs, numBytes) {
  360. durationMs = Math.max(durationMs, this.minDelayMs_);
  361. const numBits = 8 * numBytes;
  362. // weight is duration in seconds
  363. const durationS = durationMs / 1000;
  364. // value is bandwidth in bits/s
  365. const bandwidthInBps = numBits / durationS;
  366. this.fast_.sample(durationS, bandwidthInBps);
  367. this.slow_.sample(durationS, bandwidthInBps);
  368. }
  369. sampleTTFB(ttfb) {
  370. // weight is frequency curve applied to TTFB in seconds
  371. // (longer times have less weight with expected input under 1 second)
  372. const seconds = ttfb / 1000;
  373. const weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);
  374. this.ttfb_.sample(weight, Math.max(ttfb, 5));
  375. }
  376. canEstimate() {
  377. return this.fast_.getTotalWeight() >= this.minWeight_;
  378. }
  379. getEstimate() {
  380. if (this.canEstimate()) {
  381. // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
  382. // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
  383. // Take the minimum of these two estimates. This should have the effect of
  384. // adapting down quickly, but up more slowly.
  385. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  386. } else {
  387. return this.defaultEstimate_;
  388. }
  389. }
  390. getEstimateTTFB() {
  391. if (this.ttfb_.getTotalWeight() >= this.minWeight_) {
  392. return this.ttfb_.getEstimate();
  393. } else {
  394. return this.defaultTTFB_;
  395. }
  396. }
  397. get defaultEstimate() {
  398. return this.defaultEstimate_;
  399. }
  400. destroy() {}
  401. }
  402. function _defineProperty(e, r, t) {
  403. return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
  404. value: t,
  405. enumerable: true,
  406. configurable: true,
  407. writable: true
  408. }) : e[r] = t, e;
  409. }
  410. function _extends() {
  411. return _extends = Object.assign ? Object.assign.bind() : function (n) {
  412. for (var e = 1; e < arguments.length; e++) {
  413. var t = arguments[e];
  414. for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
  415. }
  416. return n;
  417. }, _extends.apply(null, arguments);
  418. }
  419. function ownKeys(e, r) {
  420. var t = Object.keys(e);
  421. if (Object.getOwnPropertySymbols) {
  422. var o = Object.getOwnPropertySymbols(e);
  423. r && (o = o.filter(function (r) {
  424. return Object.getOwnPropertyDescriptor(e, r).enumerable;
  425. })), t.push.apply(t, o);
  426. }
  427. return t;
  428. }
  429. function _objectSpread2(e) {
  430. for (var r = 1; r < arguments.length; r++) {
  431. var t = null != arguments[r] ? arguments[r] : {};
  432. r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
  433. _defineProperty(e, r, t[r]);
  434. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
  435. Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
  436. });
  437. }
  438. return e;
  439. }
  440. function _toPrimitive(t, r) {
  441. if ("object" != typeof t || !t) return t;
  442. var e = t[Symbol.toPrimitive];
  443. if (void 0 !== e) {
  444. var i = e.call(t, r);
  445. if ("object" != typeof i) return i;
  446. throw new TypeError("@@toPrimitive must return a primitive value.");
  447. }
  448. return ("string" === r ? String : Number)(t);
  449. }
  450. function _toPropertyKey(t) {
  451. var i = _toPrimitive(t, "string");
  452. return "symbol" == typeof i ? i : i + "";
  453. }
  454. class Logger {
  455. constructor(label, logger) {
  456. this.trace = void 0;
  457. this.debug = void 0;
  458. this.log = void 0;
  459. this.warn = void 0;
  460. this.info = void 0;
  461. this.error = void 0;
  462. const lb = `[${label}]:`;
  463. this.trace = noop;
  464. this.debug = logger.debug.bind(null, lb);
  465. this.log = logger.log.bind(null, lb);
  466. this.warn = logger.warn.bind(null, lb);
  467. this.info = logger.info.bind(null, lb);
  468. this.error = logger.error.bind(null, lb);
  469. }
  470. }
  471. const noop = function noop() {};
  472. const fakeLogger = {
  473. trace: noop,
  474. debug: noop,
  475. log: noop,
  476. warn: noop,
  477. info: noop,
  478. error: noop
  479. };
  480. function createLogger() {
  481. return _extends({}, fakeLogger);
  482. }
  483. // let lastCallTime;
  484. // function formatMsgWithTimeInfo(type, msg) {
  485. // const now = Date.now();
  486. // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
  487. // lastCallTime = now;
  488. // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
  489. // return msg;
  490. // }
  491. function consolePrintFn(type, id) {
  492. const func = self.console[type];
  493. return func ? func.bind(self.console, `${id ? '[' + id + '] ' : ''}[${type}] >`) : noop;
  494. }
  495. function getLoggerFn(key, debugConfig, id) {
  496. return debugConfig[key] ? debugConfig[key].bind(debugConfig) : consolePrintFn(key, id);
  497. }
  498. const exportedLogger = createLogger();
  499. function enableLogs(debugConfig, context, id) {
  500. // check that console is available
  501. const newLogger = createLogger();
  502. if (typeof console === 'object' && debugConfig === true || typeof debugConfig === 'object') {
  503. const keys = [
  504. // Remove out from list here to hard-disable a log-level
  505. // 'trace',
  506. 'debug', 'log', 'info', 'warn', 'error'];
  507. keys.forEach(key => {
  508. newLogger[key] = getLoggerFn(key, debugConfig, id);
  509. });
  510. // Some browsers don't allow to use bind on console object anyway
  511. // fallback to default if needed
  512. try {
  513. newLogger.log(`Debug logs enabled for "${context}" in hls.js version ${"1.6.7"}`);
  514. } catch (e) {
  515. /* log fn threw an exception. All logger methods are no-ops. */
  516. return createLogger();
  517. }
  518. // global exported logger uses the same functions as new logger without `id`
  519. keys.forEach(key => {
  520. exportedLogger[key] = getLoggerFn(key, debugConfig);
  521. });
  522. } else {
  523. // Reset global exported logger
  524. _extends(exportedLogger, newLogger);
  525. }
  526. return newLogger;
  527. }
  528. const logger = exportedLogger;
  529. function getDefaultExportFromCjs (x) {
  530. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  531. }
  532. var emptyEs;
  533. var hasRequiredEmptyEs;
  534. function requireEmptyEs() {
  535. if (hasRequiredEmptyEs) return emptyEs;
  536. hasRequiredEmptyEs = 1;
  537. // This file is inserted as a shim for modules which we do not want to include into the distro.
  538. // This replacement is done in the "alias" plugin of the rollup config.
  539. // Use a ES dedicated file as Rollup assigns an object in the output
  540. // For example: "var KeySystemFormats = emptyEs.KeySystemFormats;"
  541. emptyEs = {};
  542. return emptyEs;
  543. }
  544. var emptyEsExports = requireEmptyEs();
  545. var Cues = /*@__PURE__*/getDefaultExportFromCjs(emptyEsExports);
  546. function getMediaSource(preferManagedMediaSource = true) {
  547. if (typeof self === 'undefined') return undefined;
  548. const mms = (preferManagedMediaSource || !self.MediaSource) && self.ManagedMediaSource;
  549. return mms || self.MediaSource || self.WebKitMediaSource;
  550. }
  551. function isManagedMediaSource(source) {
  552. return typeof self !== 'undefined' && source === self.ManagedMediaSource;
  553. }
  554. function isCompatibleTrackChange(currentTracks, requiredTracks) {
  555. const trackNames = Object.keys(currentTracks);
  556. const requiredTrackNames = Object.keys(requiredTracks);
  557. const trackCount = trackNames.length;
  558. const requiredTrackCount = requiredTrackNames.length;
  559. return !trackCount || !requiredTrackCount || trackCount === requiredTrackCount && !trackNames.some(name => requiredTrackNames.indexOf(name) === -1);
  560. }
  561. // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
  562. // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
  563. /* utf.js - UTF-8 <=> UTF-16 convertion
  564. *
  565. * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
  566. * Version: 1.0
  567. * LastModified: Dec 25 1999
  568. * This library is free. You can redistribute it and/or modify it.
  569. */
  570. /**
  571. * Converts a UTF-8 array to a string.
  572. *
  573. * @param array - The UTF-8 array to convert
  574. *
  575. * @returns The string
  576. *
  577. * @group Utils
  578. *
  579. * @beta
  580. */
  581. function utf8ArrayToStr(array, exitOnNull = false) {
  582. if (typeof TextDecoder !== 'undefined') {
  583. const decoder = new TextDecoder('utf-8');
  584. const decoded = decoder.decode(array);
  585. if (exitOnNull) {
  586. // grab up to the first null
  587. const idx = decoded.indexOf('\0');
  588. return idx !== -1 ? decoded.substring(0, idx) : decoded;
  589. }
  590. // remove any null characters
  591. return decoded.replace(/\0/g, '');
  592. }
  593. const len = array.length;
  594. let c;
  595. let char2;
  596. let char3;
  597. let out = '';
  598. let i = 0;
  599. while (i < len) {
  600. c = array[i++];
  601. if (c === 0x00 && exitOnNull) {
  602. return out;
  603. } else if (c === 0x00 || c === 0x03) {
  604. // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
  605. continue;
  606. }
  607. switch (c >> 4) {
  608. case 0:
  609. case 1:
  610. case 2:
  611. case 3:
  612. case 4:
  613. case 5:
  614. case 6:
  615. case 7:
  616. // 0xxxxxxx
  617. out += String.fromCharCode(c);
  618. break;
  619. case 12:
  620. case 13:
  621. // 110x xxxx 10xx xxxx
  622. char2 = array[i++];
  623. out += String.fromCharCode((c & 0x1f) << 6 | char2 & 0x3f);
  624. break;
  625. case 14:
  626. // 1110 xxxx 10xx xxxx 10xx xxxx
  627. char2 = array[i++];
  628. char3 = array[i++];
  629. out += String.fromCharCode((c & 0x0f) << 12 | (char2 & 0x3f) << 6 | (char3 & 0x3f) << 0);
  630. break;
  631. }
  632. }
  633. return out;
  634. }
  635. /**
  636. * hex dump helper class
  637. */
  638. const Hex = {
  639. hexDump: function (array) {
  640. let str = '';
  641. for (let i = 0; i < array.length; i++) {
  642. let h = array[i].toString(16);
  643. if (h.length < 2) {
  644. h = '0' + h;
  645. }
  646. str += h;
  647. }
  648. return str;
  649. }
  650. };
  651. function hexToArrayBuffer(str) {
  652. return Uint8Array.from(str.replace(/^0x/, '').replace(/([\da-fA-F]{2}) ?/g, '0x$1 ').replace(/ +$/, '').split(' ')).buffer;
  653. }
  654. var urlToolkit = {exports: {}};
  655. var hasRequiredUrlToolkit;
  656. function requireUrlToolkit () {
  657. if (hasRequiredUrlToolkit) return urlToolkit.exports;
  658. hasRequiredUrlToolkit = 1;
  659. (function (module, exports) {
  660. // see https://tools.ietf.org/html/rfc1808
  661. (function (root) {
  662. var URL_REGEX =
  663. /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/;
  664. var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/;
  665. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  666. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  667. var URLToolkit = {
  668. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  669. // E.g
  670. // With opts.alwaysNormalize = false (default, spec compliant)
  671. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  672. // With opts.alwaysNormalize = true (not spec compliant)
  673. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  674. buildAbsoluteURL: function (baseURL, relativeURL, opts) {
  675. opts = opts || {};
  676. // remove any remaining space and CRLF
  677. baseURL = baseURL.trim();
  678. relativeURL = relativeURL.trim();
  679. if (!relativeURL) {
  680. // 2a) If the embedded URL is entirely empty, it inherits the
  681. // entire base URL (i.e., is set equal to the base URL)
  682. // and we are done.
  683. if (!opts.alwaysNormalize) {
  684. return baseURL;
  685. }
  686. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  687. if (!basePartsForNormalise) {
  688. throw new Error('Error trying to parse base URL.');
  689. }
  690. basePartsForNormalise.path = URLToolkit.normalizePath(
  691. basePartsForNormalise.path
  692. );
  693. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  694. }
  695. var relativeParts = URLToolkit.parseURL(relativeURL);
  696. if (!relativeParts) {
  697. throw new Error('Error trying to parse relative URL.');
  698. }
  699. if (relativeParts.scheme) {
  700. // 2b) If the embedded URL starts with a scheme name, it is
  701. // interpreted as an absolute URL and we are done.
  702. if (!opts.alwaysNormalize) {
  703. return relativeURL;
  704. }
  705. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  706. return URLToolkit.buildURLFromParts(relativeParts);
  707. }
  708. var baseParts = URLToolkit.parseURL(baseURL);
  709. if (!baseParts) {
  710. throw new Error('Error trying to parse base URL.');
  711. }
  712. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  713. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  714. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  715. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  716. baseParts.netLoc = pathParts[1];
  717. baseParts.path = pathParts[2];
  718. }
  719. if (baseParts.netLoc && !baseParts.path) {
  720. baseParts.path = '/';
  721. }
  722. var builtParts = {
  723. // 2c) Otherwise, the embedded URL inherits the scheme of
  724. // the base URL.
  725. scheme: baseParts.scheme,
  726. netLoc: relativeParts.netLoc,
  727. path: null,
  728. params: relativeParts.params,
  729. query: relativeParts.query,
  730. fragment: relativeParts.fragment,
  731. };
  732. if (!relativeParts.netLoc) {
  733. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  734. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  735. // (if any) of the base URL.
  736. builtParts.netLoc = baseParts.netLoc;
  737. // 4) If the embedded URL path is preceded by a slash "/", the
  738. // path is not relative and we skip to Step 7.
  739. if (relativeParts.path[0] !== '/') {
  740. if (!relativeParts.path) {
  741. // 5) If the embedded URL path is empty (and not preceded by a
  742. // slash), then the embedded URL inherits the base URL path
  743. builtParts.path = baseParts.path;
  744. // 5a) if the embedded URL's <params> is non-empty, we skip to
  745. // step 7; otherwise, it inherits the <params> of the base
  746. // URL (if any) and
  747. if (!relativeParts.params) {
  748. builtParts.params = baseParts.params;
  749. // 5b) if the embedded URL's <query> is non-empty, we skip to
  750. // step 7; otherwise, it inherits the <query> of the base
  751. // URL (if any) and we skip to step 7.
  752. if (!relativeParts.query) {
  753. builtParts.query = baseParts.query;
  754. }
  755. }
  756. } else {
  757. // 6) The last segment of the base URL's path (anything
  758. // following the rightmost slash "/", or the entire path if no
  759. // slash is present) is removed and the embedded URL's path is
  760. // appended in its place.
  761. var baseURLPath = baseParts.path;
  762. var newPath =
  763. baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +
  764. relativeParts.path;
  765. builtParts.path = URLToolkit.normalizePath(newPath);
  766. }
  767. }
  768. }
  769. if (builtParts.path === null) {
  770. builtParts.path = opts.alwaysNormalize
  771. ? URLToolkit.normalizePath(relativeParts.path)
  772. : relativeParts.path;
  773. }
  774. return URLToolkit.buildURLFromParts(builtParts);
  775. },
  776. parseURL: function (url) {
  777. var parts = URL_REGEX.exec(url);
  778. if (!parts) {
  779. return null;
  780. }
  781. return {
  782. scheme: parts[1] || '',
  783. netLoc: parts[2] || '',
  784. path: parts[3] || '',
  785. params: parts[4] || '',
  786. query: parts[5] || '',
  787. fragment: parts[6] || '',
  788. };
  789. },
  790. normalizePath: function (path) {
  791. // The following operations are
  792. // then applied, in order, to the new path:
  793. // 6a) All occurrences of "./", where "." is a complete path
  794. // segment, are removed.
  795. // 6b) If the path ends with "." as a complete path segment,
  796. // that "." is removed.
  797. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
  798. // 6c) All occurrences of "<segment>/../", where <segment> is a
  799. // complete path segment not equal to "..", are removed.
  800. // Removal of these path segments is performed iteratively,
  801. // removing the leftmost matching pattern on each iteration,
  802. // until no matching pattern remains.
  803. // 6d) If the path ends with "<segment>/..", where <segment> is a
  804. // complete path segment not equal to "..", that
  805. // "<segment>/.." is removed.
  806. while (
  807. path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length
  808. ) {}
  809. return path.split('').reverse().join('');
  810. },
  811. buildURLFromParts: function (parts) {
  812. return (
  813. parts.scheme +
  814. parts.netLoc +
  815. parts.path +
  816. parts.params +
  817. parts.query +
  818. parts.fragment
  819. );
  820. },
  821. };
  822. module.exports = URLToolkit;
  823. })();
  824. } (urlToolkit));
  825. return urlToolkit.exports;
  826. }
  827. var urlToolkitExports = requireUrlToolkit();
  828. class LoadStats {
  829. constructor() {
  830. this.aborted = false;
  831. this.loaded = 0;
  832. this.retry = 0;
  833. this.total = 0;
  834. this.chunkCount = 0;
  835. this.bwEstimate = 0;
  836. this.loading = {
  837. start: 0,
  838. first: 0,
  839. end: 0
  840. };
  841. this.parsing = {
  842. start: 0,
  843. end: 0
  844. };
  845. this.buffering = {
  846. start: 0,
  847. first: 0,
  848. end: 0
  849. };
  850. }
  851. }
  852. var ElementaryStreamTypes = {
  853. AUDIO: "audio",
  854. VIDEO: "video",
  855. AUDIOVIDEO: "audiovideo"
  856. };
  857. class BaseSegment {
  858. constructor(base) {
  859. this._byteRange = null;
  860. this._url = null;
  861. this._stats = null;
  862. this._streams = null;
  863. // baseurl is the URL to the playlist
  864. this.base = void 0;
  865. // relurl is the portion of the URL that comes from inside the playlist.
  866. this.relurl = void 0;
  867. if (typeof base === 'string') {
  868. base = {
  869. url: base
  870. };
  871. }
  872. this.base = base;
  873. makeEnumerable(this, 'stats');
  874. }
  875. // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
  876. setByteRange(value, previous) {
  877. const params = value.split('@', 2);
  878. let start;
  879. if (params.length === 1) {
  880. start = (previous == null ? void 0 : previous.byteRangeEndOffset) || 0;
  881. } else {
  882. start = parseInt(params[1]);
  883. }
  884. this._byteRange = [start, parseInt(params[0]) + start];
  885. }
  886. get baseurl() {
  887. return this.base.url;
  888. }
  889. get byteRange() {
  890. if (this._byteRange === null) {
  891. return [];
  892. }
  893. return this._byteRange;
  894. }
  895. get byteRangeStartOffset() {
  896. return this.byteRange[0];
  897. }
  898. get byteRangeEndOffset() {
  899. return this.byteRange[1];
  900. }
  901. get elementaryStreams() {
  902. if (this._streams === null) {
  903. this._streams = {
  904. [ElementaryStreamTypes.AUDIO]: null,
  905. [ElementaryStreamTypes.VIDEO]: null,
  906. [ElementaryStreamTypes.AUDIOVIDEO]: null
  907. };
  908. }
  909. return this._streams;
  910. }
  911. set elementaryStreams(value) {
  912. this._streams = value;
  913. }
  914. get hasStats() {
  915. return this._stats !== null;
  916. }
  917. get hasStreams() {
  918. return this._streams !== null;
  919. }
  920. get stats() {
  921. if (this._stats === null) {
  922. this._stats = new LoadStats();
  923. }
  924. return this._stats;
  925. }
  926. set stats(value) {
  927. this._stats = value;
  928. }
  929. get url() {
  930. if (!this._url && this.baseurl && this.relurl) {
  931. this._url = urlToolkitExports.buildAbsoluteURL(this.baseurl, this.relurl, {
  932. alwaysNormalize: true
  933. });
  934. }
  935. return this._url || '';
  936. }
  937. set url(value) {
  938. this._url = value;
  939. }
  940. clearElementaryStreamInfo() {
  941. const {
  942. elementaryStreams
  943. } = this;
  944. elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
  945. elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
  946. elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
  947. }
  948. }
  949. function isMediaFragment(frag) {
  950. return frag.sn !== 'initSegment';
  951. }
  952. /**
  953. * Object representing parsed data from an HLS Segment. Found in {@link hls.js#LevelDetails.fragments}.
  954. */
  955. class Fragment extends BaseSegment {
  956. constructor(type, base) {
  957. super(base);
  958. this._decryptdata = null;
  959. this._programDateTime = null;
  960. this._ref = null;
  961. // Approximate bit rate of the fragment expressed in bits per second (bps) as indicated by the last EXT-X-BITRATE (kbps) tag
  962. this._bitrate = void 0;
  963. this.rawProgramDateTime = null;
  964. this.tagList = [];
  965. // EXTINF has to be present for a m3u8 to be considered valid
  966. this.duration = 0;
  967. // sn notates the sequence number for a segment, and if set to a string can be 'initSegment'
  968. this.sn = 0;
  969. // levelkeys are the EXT-X-KEY tags that apply to this segment for decryption
  970. // core difference from the private field _decryptdata is the lack of the initialized IV
  971. // _decryptdata will set the IV for this segment based on the segment number in the fragment
  972. this.levelkeys = void 0;
  973. // A string representing the fragment type
  974. this.type = void 0;
  975. // A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading
  976. this.loader = null;
  977. // A reference to the key loader. Set while the key is loading, and removed afterwards. Used to abort key loading
  978. this.keyLoader = null;
  979. // The level/track index to which the fragment belongs
  980. this.level = -1;
  981. // The continuity counter of the fragment
  982. this.cc = 0;
  983. // The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
  984. this.startPTS = void 0;
  985. // The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
  986. this.endPTS = void 0;
  987. // The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
  988. this.startDTS = void 0;
  989. // The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
  990. this.endDTS = void 0;
  991. // The start time of the fragment, as listed in the manifest. Updated after transmux complete.
  992. this.start = 0;
  993. // The offset time (seconds) of the fragment from the start of the Playlist
  994. this.playlistOffset = 0;
  995. // Set by `updateFragPTSDTS` in level-helper
  996. this.deltaPTS = void 0;
  997. // The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
  998. this.maxStartPTS = void 0;
  999. // The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
  1000. this.minEndPTS = void 0;
  1001. // Init Segment bytes (unset for media segments)
  1002. this.data = void 0;
  1003. // A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered
  1004. this.bitrateTest = false;
  1005. // #EXTINF segment title
  1006. this.title = null;
  1007. // The Media Initialization Section for this segment
  1008. this.initSegment = null;
  1009. // Fragment is the last fragment in the media playlist
  1010. this.endList = void 0;
  1011. // Fragment is marked by an EXT-X-GAP tag indicating that it does not contain media data and should not be loaded
  1012. this.gap = void 0;
  1013. // Deprecated
  1014. this.urlId = 0;
  1015. this.type = type;
  1016. }
  1017. get byteLength() {
  1018. if (this.hasStats) {
  1019. const total = this.stats.total;
  1020. if (total) {
  1021. return total;
  1022. }
  1023. }
  1024. if (this.byteRange) {
  1025. const start = this.byteRange[0];
  1026. const end = this.byteRange[1];
  1027. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  1028. return end - start;
  1029. }
  1030. }
  1031. return null;
  1032. }
  1033. get bitrate() {
  1034. if (this.byteLength) {
  1035. return this.byteLength * 8 / this.duration;
  1036. }
  1037. if (this._bitrate) {
  1038. return this._bitrate;
  1039. }
  1040. return null;
  1041. }
  1042. set bitrate(value) {
  1043. this._bitrate = value;
  1044. }
  1045. get decryptdata() {
  1046. const {
  1047. levelkeys
  1048. } = this;
  1049. if (!levelkeys && !this._decryptdata) {
  1050. return null;
  1051. }
  1052. if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) {
  1053. const key = this.levelkeys.identity;
  1054. if (key) {
  1055. this._decryptdata = key.getDecryptData(this.sn);
  1056. } else {
  1057. const keyFormats = Object.keys(this.levelkeys);
  1058. if (keyFormats.length === 1) {
  1059. return this._decryptdata = this.levelkeys[keyFormats[0]].getDecryptData(this.sn);
  1060. }
  1061. }
  1062. }
  1063. return this._decryptdata;
  1064. }
  1065. get end() {
  1066. return this.start + this.duration;
  1067. }
  1068. get endProgramDateTime() {
  1069. if (this.programDateTime === null) {
  1070. return null;
  1071. }
  1072. const duration = !isFiniteNumber(this.duration) ? 0 : this.duration;
  1073. return this.programDateTime + duration * 1000;
  1074. }
  1075. get encrypted() {
  1076. var _this$_decryptdata;
  1077. // At the m3u8-parser level we need to add support for manifest signalled keyformats
  1078. // when we want the fragment to start reporting that it is encrypted.
  1079. // Currently, keyFormat will only be set for identity keys
  1080. if ((_this$_decryptdata = this._decryptdata) != null && _this$_decryptdata.encrypted) {
  1081. return true;
  1082. } else if (this.levelkeys) {
  1083. const keyFormats = Object.keys(this.levelkeys);
  1084. const len = keyFormats.length;
  1085. if (len > 1 || len === 1 && this.levelkeys[keyFormats[0]].encrypted) {
  1086. return true;
  1087. }
  1088. }
  1089. return false;
  1090. }
  1091. get programDateTime() {
  1092. if (this._programDateTime === null && this.rawProgramDateTime) {
  1093. this.programDateTime = Date.parse(this.rawProgramDateTime);
  1094. }
  1095. return this._programDateTime;
  1096. }
  1097. set programDateTime(value) {
  1098. if (!isFiniteNumber(value)) {
  1099. this._programDateTime = this.rawProgramDateTime = null;
  1100. return;
  1101. }
  1102. this._programDateTime = value;
  1103. }
  1104. get ref() {
  1105. if (!isMediaFragment(this)) {
  1106. return null;
  1107. }
  1108. if (!this._ref) {
  1109. this._ref = {
  1110. base: this.base,
  1111. start: this.start,
  1112. duration: this.duration,
  1113. sn: this.sn,
  1114. programDateTime: this.programDateTime
  1115. };
  1116. }
  1117. return this._ref;
  1118. }
  1119. addStart(value) {
  1120. this.setStart(this.start + value);
  1121. }
  1122. setStart(value) {
  1123. this.start = value;
  1124. if (this._ref) {
  1125. this._ref.start = value;
  1126. }
  1127. }
  1128. setDuration(value) {
  1129. this.duration = value;
  1130. if (this._ref) {
  1131. this._ref.duration = value;
  1132. }
  1133. }
  1134. setKeyFormat(keyFormat) {
  1135. if (this.levelkeys) {
  1136. const key = this.levelkeys[keyFormat];
  1137. if (key && !this._decryptdata) {
  1138. this._decryptdata = key.getDecryptData(this.sn);
  1139. }
  1140. }
  1141. }
  1142. abortRequests() {
  1143. var _this$loader, _this$keyLoader;
  1144. (_this$loader = this.loader) == null ? void 0 : _this$loader.abort();
  1145. (_this$keyLoader = this.keyLoader) == null ? void 0 : _this$keyLoader.abort();
  1146. }
  1147. setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial = false) {
  1148. const {
  1149. elementaryStreams
  1150. } = this;
  1151. const info = elementaryStreams[type];
  1152. if (!info) {
  1153. elementaryStreams[type] = {
  1154. startPTS,
  1155. endPTS,
  1156. startDTS,
  1157. endDTS,
  1158. partial
  1159. };
  1160. return;
  1161. }
  1162. info.startPTS = Math.min(info.startPTS, startPTS);
  1163. info.endPTS = Math.max(info.endPTS, endPTS);
  1164. info.startDTS = Math.min(info.startDTS, startDTS);
  1165. info.endDTS = Math.max(info.endDTS, endDTS);
  1166. }
  1167. }
  1168. /**
  1169. * Object representing parsed data from an HLS Partial Segment. Found in {@link hls.js#LevelDetails.partList}.
  1170. */
  1171. class Part extends BaseSegment {
  1172. constructor(partAttrs, frag, base, index, previous) {
  1173. super(base);
  1174. this.fragOffset = 0;
  1175. this.duration = 0;
  1176. this.gap = false;
  1177. this.independent = false;
  1178. this.relurl = void 0;
  1179. this.fragment = void 0;
  1180. this.index = void 0;
  1181. this.duration = partAttrs.decimalFloatingPoint('DURATION');
  1182. this.gap = partAttrs.bool('GAP');
  1183. this.independent = partAttrs.bool('INDEPENDENT');
  1184. this.relurl = partAttrs.enumeratedString('URI');
  1185. this.fragment = frag;
  1186. this.index = index;
  1187. const byteRange = partAttrs.enumeratedString('BYTERANGE');
  1188. if (byteRange) {
  1189. this.setByteRange(byteRange, previous);
  1190. }
  1191. if (previous) {
  1192. this.fragOffset = previous.fragOffset + previous.duration;
  1193. }
  1194. }
  1195. get start() {
  1196. return this.fragment.start + this.fragOffset;
  1197. }
  1198. get end() {
  1199. return this.start + this.duration;
  1200. }
  1201. get loaded() {
  1202. const {
  1203. elementaryStreams
  1204. } = this;
  1205. return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
  1206. }
  1207. }
  1208. function getOwnPropertyDescriptorFromPrototypeChain(object, property) {
  1209. const prototype = Object.getPrototypeOf(object);
  1210. if (prototype) {
  1211. const propertyDescriptor = Object.getOwnPropertyDescriptor(prototype, property);
  1212. if (propertyDescriptor) {
  1213. return propertyDescriptor;
  1214. }
  1215. return getOwnPropertyDescriptorFromPrototypeChain(prototype, property);
  1216. }
  1217. }
  1218. function makeEnumerable(object, property) {
  1219. const d = getOwnPropertyDescriptorFromPrototypeChain(object, property);
  1220. if (d) {
  1221. d.enumerable = true;
  1222. Object.defineProperty(object, property, d);
  1223. }
  1224. }
  1225. const UINT32_MAX$1 = Math.pow(2, 32) - 1;
  1226. const push = [].push;
  1227. // We are using fixed track IDs for driving the MP4 remuxer
  1228. // instead of following the TS PIDs.
  1229. // There is no reason not to do this and some browsers/SourceBuffer-demuxers
  1230. // may not like if there are TrackID "switches"
  1231. // See https://github.com/video-dev/hls.js/issues/1331
  1232. // Here we are mapping our internal track types to constant MP4 track IDs
  1233. // With MSE currently one can only have one track of each, and we are muxing
  1234. // whatever video/audio rendition in them.
  1235. const RemuxerTrackIdConfig = {
  1236. video: 1,
  1237. audio: 2,
  1238. id3: 3,
  1239. text: 4
  1240. };
  1241. function bin2str(data) {
  1242. return String.fromCharCode.apply(null, data);
  1243. }
  1244. function readUint16(buffer, offset) {
  1245. const val = buffer[offset] << 8 | buffer[offset + 1];
  1246. return val < 0 ? 65536 + val : val;
  1247. }
  1248. function readUint32(buffer, offset) {
  1249. const val = readSint32(buffer, offset);
  1250. return val < 0 ? 4294967296 + val : val;
  1251. }
  1252. function readUint64(buffer, offset) {
  1253. let result = readUint32(buffer, offset);
  1254. result *= Math.pow(2, 32);
  1255. result += readUint32(buffer, offset + 4);
  1256. return result;
  1257. }
  1258. function readSint32(buffer, offset) {
  1259. return buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
  1260. }
  1261. // Find "moof" box
  1262. function hasMoofData(data) {
  1263. const end = data.byteLength;
  1264. for (let i = 0; i < end;) {
  1265. const size = readUint32(data, i);
  1266. if (size > 8 && data[i + 4] === 0x6d && data[i + 5] === 0x6f && data[i + 6] === 0x6f && data[i + 7] === 0x66) {
  1267. return true;
  1268. }
  1269. i = size > 1 ? i + size : end;
  1270. }
  1271. return false;
  1272. }
  1273. // Find the data for a box specified by its path
  1274. function findBox(data, path) {
  1275. const results = [];
  1276. if (!path.length) {
  1277. // short-circuit the search for empty paths
  1278. return results;
  1279. }
  1280. const end = data.byteLength;
  1281. for (let i = 0; i < end;) {
  1282. const size = readUint32(data, i);
  1283. const type = bin2str(data.subarray(i + 4, i + 8));
  1284. const endbox = size > 1 ? i + size : end;
  1285. if (type === path[0]) {
  1286. if (path.length === 1) {
  1287. // this is the end of the path and we've found the box we were
  1288. // looking for
  1289. results.push(data.subarray(i + 8, endbox));
  1290. } else {
  1291. // recursively search for the next box along the path
  1292. const subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));
  1293. if (subresults.length) {
  1294. push.apply(results, subresults);
  1295. }
  1296. }
  1297. }
  1298. i = endbox;
  1299. }
  1300. // we've finished searching all of data
  1301. return results;
  1302. }
  1303. function parseSegmentIndex(sidx) {
  1304. const references = [];
  1305. const version = sidx[0];
  1306. // set initial offset, we skip the reference ID (not needed)
  1307. let index = 8;
  1308. const timescale = readUint32(sidx, index);
  1309. index += 4;
  1310. let earliestPresentationTime = 0;
  1311. let firstOffset = 0;
  1312. if (version === 0) {
  1313. earliestPresentationTime = readUint32(sidx, index);
  1314. firstOffset = readUint32(sidx, index + 4);
  1315. index += 8;
  1316. } else {
  1317. earliestPresentationTime = readUint64(sidx, index);
  1318. firstOffset = readUint64(sidx, index + 8);
  1319. index += 16;
  1320. }
  1321. // skip reserved
  1322. index += 2;
  1323. let startByte = sidx.length + firstOffset;
  1324. const referencesCount = readUint16(sidx, index);
  1325. index += 2;
  1326. for (let i = 0; i < referencesCount; i++) {
  1327. let referenceIndex = index;
  1328. const referenceInfo = readUint32(sidx, referenceIndex);
  1329. referenceIndex += 4;
  1330. const referenceSize = referenceInfo & 0x7fffffff;
  1331. const referenceType = (referenceInfo & 0x80000000) >>> 31;
  1332. if (referenceType === 1) {
  1333. logger.warn('SIDX has hierarchical references (not supported)');
  1334. return null;
  1335. }
  1336. const subsegmentDuration = readUint32(sidx, referenceIndex);
  1337. referenceIndex += 4;
  1338. references.push({
  1339. referenceSize,
  1340. subsegmentDuration,
  1341. // unscaled
  1342. info: {
  1343. duration: subsegmentDuration / timescale,
  1344. start: startByte,
  1345. end: startByte + referenceSize - 1
  1346. }
  1347. });
  1348. startByte += referenceSize;
  1349. // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
  1350. // for |sapDelta|.
  1351. referenceIndex += 4;
  1352. // skip to next ref
  1353. index = referenceIndex;
  1354. }
  1355. return {
  1356. earliestPresentationTime,
  1357. timescale,
  1358. version,
  1359. referencesCount,
  1360. references
  1361. };
  1362. }
  1363. /**
  1364. * Parses an MP4 initialization segment and extracts stream type and
  1365. * timescale values for any declared tracks. Timescale values indicate the
  1366. * number of clock ticks per second to assume for time-based values
  1367. * elsewhere in the MP4.
  1368. *
  1369. * To determine the start time of an MP4, you need two pieces of
  1370. * information: the timescale unit and the earliest base media decode
  1371. * time. Multiple timescales can be specified within an MP4 but the
  1372. * base media decode time is always expressed in the timescale from
  1373. * the media header box for the track:
  1374. * ```
  1375. * moov > trak > mdia > mdhd.timescale
  1376. * moov > trak > mdia > hdlr
  1377. * ```
  1378. * @param initSegment the bytes of the init segment
  1379. * @returns a hash of track type to timescale values or null if
  1380. * the init segment is malformed.
  1381. */
  1382. function parseInitSegment(initSegment) {
  1383. const result = [];
  1384. const traks = findBox(initSegment, ['moov', 'trak']);
  1385. for (let i = 0; i < traks.length; i++) {
  1386. const trak = traks[i];
  1387. const tkhd = findBox(trak, ['tkhd'])[0];
  1388. if (tkhd) {
  1389. let version = tkhd[0];
  1390. const trackId = readUint32(tkhd, version === 0 ? 12 : 20);
  1391. const mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  1392. if (mdhd) {
  1393. version = mdhd[0];
  1394. const timescale = readUint32(mdhd, version === 0 ? 12 : 20);
  1395. const hdlr = findBox(trak, ['mdia', 'hdlr'])[0];
  1396. if (hdlr) {
  1397. const hdlrType = bin2str(hdlr.subarray(8, 12));
  1398. const type = {
  1399. soun: ElementaryStreamTypes.AUDIO,
  1400. vide: ElementaryStreamTypes.VIDEO
  1401. }[hdlrType];
  1402. // Parse codec details
  1403. const stsdBox = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  1404. const stsd = parseStsd(stsdBox);
  1405. if (type) {
  1406. // Add 'audio', 'video', and 'audiovideo' track records that will map to SourceBuffers
  1407. result[trackId] = {
  1408. timescale,
  1409. type,
  1410. stsd
  1411. };
  1412. result[type] = _objectSpread2({
  1413. timescale,
  1414. id: trackId
  1415. }, stsd);
  1416. } else {
  1417. // Add 'meta' and other track records
  1418. result[trackId] = {
  1419. timescale,
  1420. type: hdlrType,
  1421. stsd
  1422. };
  1423. }
  1424. }
  1425. }
  1426. }
  1427. }
  1428. const trex = findBox(initSegment, ['moov', 'mvex', 'trex']);
  1429. trex.forEach(trex => {
  1430. const trackId = readUint32(trex, 4);
  1431. const track = result[trackId];
  1432. if (track) {
  1433. track.default = {
  1434. duration: readUint32(trex, 12),
  1435. flags: readUint32(trex, 20)
  1436. };
  1437. }
  1438. });
  1439. return result;
  1440. }
  1441. function parseStsd(stsd) {
  1442. const sampleEntries = stsd.subarray(8);
  1443. const sampleEntriesEnd = sampleEntries.subarray(8 + 78);
  1444. const fourCC = bin2str(sampleEntries.subarray(4, 8));
  1445. let codec = fourCC;
  1446. let supplemental;
  1447. const encrypted = fourCC === 'enca' || fourCC === 'encv';
  1448. if (encrypted) {
  1449. const encBox = findBox(sampleEntries, [fourCC])[0];
  1450. const encBoxChildren = encBox.subarray(fourCC === 'enca' ? 28 : 78);
  1451. const sinfs = findBox(encBoxChildren, ['sinf']);
  1452. sinfs.forEach(sinf => {
  1453. const schm = findBox(sinf, ['schm'])[0];
  1454. if (schm) {
  1455. const scheme = bin2str(schm.subarray(4, 8));
  1456. if (scheme === 'cbcs' || scheme === 'cenc') {
  1457. const frma = findBox(sinf, ['frma'])[0];
  1458. if (frma) {
  1459. // for encrypted content codec fourCC will be in frma
  1460. codec = bin2str(frma);
  1461. }
  1462. }
  1463. }
  1464. });
  1465. }
  1466. const codecFourCC = codec;
  1467. switch (codec) {
  1468. case 'avc1':
  1469. case 'avc2':
  1470. case 'avc3':
  1471. case 'avc4':
  1472. {
  1473. // extract profile + compatibility + level out of avcC box
  1474. const avcCBox = findBox(sampleEntriesEnd, ['avcC'])[0];
  1475. if (avcCBox && avcCBox.length > 3) {
  1476. codec += '.' + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]);
  1477. supplemental = parseSupplementalDoViCodec(codecFourCC === 'avc1' ? 'dva1' : 'dvav', sampleEntriesEnd);
  1478. }
  1479. break;
  1480. }
  1481. case 'mp4a':
  1482. {
  1483. const codecBox = findBox(sampleEntries, [fourCC])[0];
  1484. const esdsBox = findBox(codecBox.subarray(28), ['esds'])[0];
  1485. if (esdsBox && esdsBox.length > 7) {
  1486. let i = 4;
  1487. // ES Descriptor tag
  1488. if (esdsBox[i++] !== 0x03) {
  1489. break;
  1490. }
  1491. i = skipBERInteger(esdsBox, i);
  1492. i += 2; // skip es_id;
  1493. const flags = esdsBox[i++];
  1494. if (flags & 0x80) {
  1495. i += 2; // skip dependency es_id
  1496. }
  1497. if (flags & 0x40) {
  1498. i += esdsBox[i++]; // skip URL
  1499. }
  1500. // Decoder config descriptor
  1501. if (esdsBox[i++] !== 0x04) {
  1502. break;
  1503. }
  1504. i = skipBERInteger(esdsBox, i);
  1505. const objectType = esdsBox[i++];
  1506. if (objectType === 0x40) {
  1507. codec += '.' + toHex(objectType);
  1508. } else {
  1509. break;
  1510. }
  1511. i += 12;
  1512. // Decoder specific info
  1513. if (esdsBox[i++] !== 0x05) {
  1514. break;
  1515. }
  1516. i = skipBERInteger(esdsBox, i);
  1517. const firstByte = esdsBox[i++];
  1518. let audioObjectType = (firstByte & 0xf8) >> 3;
  1519. if (audioObjectType === 31) {
  1520. audioObjectType += 1 + ((firstByte & 0x7) << 3) + ((esdsBox[i] & 0xe0) >> 5);
  1521. }
  1522. codec += '.' + audioObjectType;
  1523. }
  1524. break;
  1525. }
  1526. case 'hvc1':
  1527. case 'hev1':
  1528. {
  1529. const hvcCBox = findBox(sampleEntriesEnd, ['hvcC'])[0];
  1530. if (hvcCBox && hvcCBox.length > 12) {
  1531. const profileByte = hvcCBox[1];
  1532. const profileSpace = ['', 'A', 'B', 'C'][profileByte >> 6];
  1533. const generalProfileIdc = profileByte & 0x1f;
  1534. const profileCompat = readUint32(hvcCBox, 2);
  1535. const tierFlag = (profileByte & 0x20) >> 5 ? 'H' : 'L';
  1536. const levelIDC = hvcCBox[12];
  1537. const constraintIndicator = hvcCBox.subarray(6, 12);
  1538. codec += '.' + profileSpace + generalProfileIdc;
  1539. codec += '.' + reverse32BitInt(profileCompat).toString(16).toUpperCase();
  1540. codec += '.' + tierFlag + levelIDC;
  1541. let constraintString = '';
  1542. for (let i = constraintIndicator.length; i--;) {
  1543. const byte = constraintIndicator[i];
  1544. if (byte || constraintString) {
  1545. const encodedByte = byte.toString(16).toUpperCase();
  1546. constraintString = '.' + encodedByte + constraintString;
  1547. }
  1548. }
  1549. codec += constraintString;
  1550. }
  1551. supplemental = parseSupplementalDoViCodec(codecFourCC == 'hev1' ? 'dvhe' : 'dvh1', sampleEntriesEnd);
  1552. break;
  1553. }
  1554. case 'dvh1':
  1555. case 'dvhe':
  1556. case 'dvav':
  1557. case 'dva1':
  1558. case 'dav1':
  1559. {
  1560. codec = parseSupplementalDoViCodec(codec, sampleEntriesEnd) || codec;
  1561. break;
  1562. }
  1563. case 'vp09':
  1564. {
  1565. const vpcCBox = findBox(sampleEntriesEnd, ['vpcC'])[0];
  1566. if (vpcCBox && vpcCBox.length > 6) {
  1567. const profile = vpcCBox[4];
  1568. const level = vpcCBox[5];
  1569. const bitDepth = vpcCBox[6] >> 4 & 0x0f;
  1570. codec += '.' + addLeadingZero(profile) + '.' + addLeadingZero(level) + '.' + addLeadingZero(bitDepth);
  1571. }
  1572. break;
  1573. }
  1574. case 'av01':
  1575. {
  1576. const av1CBox = findBox(sampleEntriesEnd, ['av1C'])[0];
  1577. if (av1CBox && av1CBox.length > 2) {
  1578. const profile = av1CBox[1] >>> 5;
  1579. const level = av1CBox[1] & 0x1f;
  1580. const tierFlag = av1CBox[2] >>> 7 ? 'H' : 'M';
  1581. const highBitDepth = (av1CBox[2] & 0x40) >> 6;
  1582. const twelveBit = (av1CBox[2] & 0x20) >> 5;
  1583. const bitDepth = profile === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8;
  1584. const monochrome = (av1CBox[2] & 0x10) >> 4;
  1585. const chromaSubsamplingX = (av1CBox[2] & 0x08) >> 3;
  1586. const chromaSubsamplingY = (av1CBox[2] & 0x04) >> 2;
  1587. const chromaSamplePosition = av1CBox[2] & 0x03;
  1588. // TODO: parse color_description_present_flag
  1589. // default it to BT.709/limited range for now
  1590. // more info https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax
  1591. const colorPrimaries = 1;
  1592. const transferCharacteristics = 1;
  1593. const matrixCoefficients = 1;
  1594. const videoFullRangeFlag = 0;
  1595. codec += '.' + profile + '.' + addLeadingZero(level) + tierFlag + '.' + addLeadingZero(bitDepth) + '.' + monochrome + '.' + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition + '.' + addLeadingZero(colorPrimaries) + '.' + addLeadingZero(transferCharacteristics) + '.' + addLeadingZero(matrixCoefficients) + '.' + videoFullRangeFlag;
  1596. supplemental = parseSupplementalDoViCodec('dav1', sampleEntriesEnd);
  1597. }
  1598. break;
  1599. }
  1600. }
  1601. return {
  1602. codec,
  1603. encrypted,
  1604. supplemental
  1605. };
  1606. }
  1607. function parseSupplementalDoViCodec(fourCC, sampleEntriesEnd) {
  1608. const dvvCResult = findBox(sampleEntriesEnd, ['dvvC']); // used by DoVi Profile 8 to 10
  1609. const dvXCBox = dvvCResult.length ? dvvCResult[0] : findBox(sampleEntriesEnd, ['dvcC'])[0]; // used by DoVi Profiles up to 7 and 20
  1610. if (dvXCBox) {
  1611. const doViProfile = dvXCBox[2] >> 1 & 0x7f;
  1612. const doViLevel = dvXCBox[2] << 5 & 0x20 | dvXCBox[3] >> 3 & 0x1f;
  1613. return fourCC + '.' + addLeadingZero(doViProfile) + '.' + addLeadingZero(doViLevel);
  1614. }
  1615. }
  1616. function reverse32BitInt(val) {
  1617. let result = 0;
  1618. for (let i = 0; i < 32; i++) {
  1619. result |= (val >> i & 1) << 32 - 1 - i;
  1620. }
  1621. return result >>> 0;
  1622. }
  1623. function skipBERInteger(bytes, i) {
  1624. const limit = i + 5;
  1625. while (bytes[i++] & 0x80 && i < limit) {
  1626. /* do nothing */
  1627. }
  1628. return i;
  1629. }
  1630. function toHex(x) {
  1631. return ('0' + x.toString(16).toUpperCase()).slice(-2);
  1632. }
  1633. function addLeadingZero(num) {
  1634. return (num < 10 ? '0' : '') + num;
  1635. }
  1636. function patchEncyptionData(initSegment, decryptdata) {
  1637. if (!initSegment || !decryptdata) {
  1638. return initSegment;
  1639. }
  1640. const keyId = decryptdata.keyId;
  1641. if (keyId && decryptdata.isCommonEncryption) {
  1642. const traks = findBox(initSegment, ['moov', 'trak']);
  1643. traks.forEach(trak => {
  1644. const stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  1645. // skip the sample entry count
  1646. const sampleEntries = stsd.subarray(8);
  1647. let encBoxes = findBox(sampleEntries, ['enca']);
  1648. const isAudio = encBoxes.length > 0;
  1649. if (!isAudio) {
  1650. encBoxes = findBox(sampleEntries, ['encv']);
  1651. }
  1652. encBoxes.forEach(enc => {
  1653. const encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);
  1654. const sinfBoxes = findBox(encBoxChildren, ['sinf']);
  1655. sinfBoxes.forEach(sinf => {
  1656. const tenc = parseSinf(sinf);
  1657. if (tenc) {
  1658. // Look for default key id (keyID offset is always 8 within the tenc box):
  1659. const tencKeyId = tenc.subarray(8, 24);
  1660. if (!tencKeyId.some(b => b !== 0)) {
  1661. logger.log(`[eme] Patching keyId in 'enc${isAudio ? 'a' : 'v'}>sinf>>tenc' box: ${Hex.hexDump(tencKeyId)} -> ${Hex.hexDump(keyId)}`);
  1662. tenc.set(keyId, 8);
  1663. }
  1664. }
  1665. });
  1666. });
  1667. });
  1668. }
  1669. return initSegment;
  1670. }
  1671. function parseSinf(sinf) {
  1672. const schm = findBox(sinf, ['schm'])[0];
  1673. if (schm) {
  1674. const scheme = bin2str(schm.subarray(4, 8));
  1675. if (scheme === 'cbcs' || scheme === 'cenc') {
  1676. return findBox(sinf, ['schi', 'tenc'])[0];
  1677. }
  1678. }
  1679. return null;
  1680. }
  1681. /*
  1682. For Reference:
  1683. aligned(8) class TrackFragmentHeaderBox
  1684. extends FullBox(‘tfhd’, 0, tf_flags){
  1685. unsigned int(32) track_ID;
  1686. // all the following are optional fields
  1687. unsigned int(64) base_data_offset;
  1688. unsigned int(32) sample_description_index;
  1689. unsigned int(32) default_sample_duration;
  1690. unsigned int(32) default_sample_size;
  1691. unsigned int(32) default_sample_flags
  1692. }
  1693. */
  1694. function getSampleData(data, initData, logger) {
  1695. const tracks = {};
  1696. const trafs = findBox(data, ['moof', 'traf']);
  1697. for (let i = 0; i < trafs.length; i++) {
  1698. const traf = trafs[i];
  1699. // There is only one tfhd & trun per traf
  1700. // This is true for CMAF style content, and we should perhaps check the ftyp
  1701. // and only look for a single trun then, but for ISOBMFF we should check
  1702. // for multiple track runs.
  1703. const tfhd = findBox(traf, ['tfhd'])[0];
  1704. // get the track id from the tfhd
  1705. const id = readUint32(tfhd, 4);
  1706. const track = initData[id];
  1707. if (!track) {
  1708. continue;
  1709. }
  1710. const trackTimes = tracks[id] || (tracks[id] = {
  1711. start: NaN,
  1712. duration: 0,
  1713. sampleCount: 0,
  1714. timescale: track.timescale,
  1715. type: track.type
  1716. });
  1717. // get start DTS
  1718. const tfdt = findBox(traf, ['tfdt'])[0];
  1719. if (tfdt) {
  1720. const version = tfdt[0];
  1721. let baseTime = readUint32(tfdt, 4);
  1722. if (version === 1) {
  1723. // If value is too large, assume signed 64-bit. Negative track fragment decode times are invalid, but they exist in the wild.
  1724. // This prevents large values from being used for initPTS, which can cause playlist sync issues.
  1725. // https://github.com/video-dev/hls.js/issues/5303
  1726. if (baseTime === UINT32_MAX$1) {
  1727. logger.warn(`[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`);
  1728. } else {
  1729. baseTime *= UINT32_MAX$1 + 1;
  1730. baseTime += readUint32(tfdt, 8);
  1731. }
  1732. }
  1733. if (isFiniteNumber(baseTime) && (!isFiniteNumber(trackTimes.start) || baseTime < trackTimes.start)) {
  1734. trackTimes.start = baseTime;
  1735. }
  1736. }
  1737. const trackDefault = track.default;
  1738. const tfhdFlags = readUint32(tfhd, 0) | (trackDefault == null ? void 0 : trackDefault.flags);
  1739. let defaultSampleDuration = (trackDefault == null ? void 0 : trackDefault.duration) || 0;
  1740. if (tfhdFlags & 0x000008) {
  1741. // 0x000008 indicates the presence of the default_sample_duration field
  1742. if (tfhdFlags & 0x000002) {
  1743. // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration
  1744. // If present, the default_sample_duration exists at byte offset 12
  1745. defaultSampleDuration = readUint32(tfhd, 12);
  1746. } else {
  1747. // Otherwise, the duration is at byte offset 8
  1748. defaultSampleDuration = readUint32(tfhd, 8);
  1749. }
  1750. }
  1751. const truns = findBox(traf, ['trun']);
  1752. let sampleDTS = trackTimes.start || 0;
  1753. let rawDuration = 0;
  1754. let sampleDuration = defaultSampleDuration;
  1755. for (let j = 0; j < truns.length; j++) {
  1756. const trun = truns[j];
  1757. const sampleCount = readUint32(trun, 4);
  1758. const sampleIndex = trackTimes.sampleCount;
  1759. trackTimes.sampleCount += sampleCount;
  1760. // Get duration from samples
  1761. const dataOffsetPresent = trun[3] & 0x01;
  1762. const firstSampleFlagsPresent = trun[3] & 0x04;
  1763. const sampleDurationPresent = trun[2] & 0x01;
  1764. const sampleSizePresent = trun[2] & 0x02;
  1765. const sampleFlagsPresent = trun[2] & 0x04;
  1766. const sampleCompositionTimeOffsetPresent = trun[2] & 0x08;
  1767. let offset = 8;
  1768. let remaining = sampleCount;
  1769. if (dataOffsetPresent) {
  1770. offset += 4;
  1771. }
  1772. if (firstSampleFlagsPresent && sampleCount) {
  1773. const isNonSyncSample = trun[offset + 1] & 0x01;
  1774. if (!isNonSyncSample && trackTimes.keyFrameIndex === undefined) {
  1775. trackTimes.keyFrameIndex = sampleIndex;
  1776. }
  1777. offset += 4;
  1778. if (sampleDurationPresent) {
  1779. sampleDuration = readUint32(trun, offset);
  1780. offset += 4;
  1781. } else {
  1782. sampleDuration = defaultSampleDuration;
  1783. }
  1784. if (sampleSizePresent) {
  1785. offset += 4;
  1786. }
  1787. if (sampleCompositionTimeOffsetPresent) {
  1788. offset += 4;
  1789. }
  1790. sampleDTS += sampleDuration;
  1791. rawDuration += sampleDuration;
  1792. remaining--;
  1793. }
  1794. while (remaining--) {
  1795. if (sampleDurationPresent) {
  1796. sampleDuration = readUint32(trun, offset);
  1797. offset += 4;
  1798. } else {
  1799. sampleDuration = defaultSampleDuration;
  1800. }
  1801. if (sampleSizePresent) {
  1802. offset += 4;
  1803. }
  1804. if (sampleFlagsPresent) {
  1805. const isNonSyncSample = trun[offset + 1] & 0x01;
  1806. if (!isNonSyncSample) {
  1807. if (trackTimes.keyFrameIndex === undefined) {
  1808. trackTimes.keyFrameIndex = trackTimes.sampleCount - (remaining + 1);
  1809. trackTimes.keyFrameStart = sampleDTS;
  1810. }
  1811. }
  1812. offset += 4;
  1813. }
  1814. if (sampleCompositionTimeOffsetPresent) {
  1815. offset += 4;
  1816. }
  1817. sampleDTS += sampleDuration;
  1818. rawDuration += sampleDuration;
  1819. }
  1820. if (!rawDuration && defaultSampleDuration) {
  1821. rawDuration += defaultSampleDuration * sampleCount;
  1822. }
  1823. }
  1824. trackTimes.duration += rawDuration;
  1825. }
  1826. if (!Object.keys(tracks).some(trackId => tracks[trackId].duration)) {
  1827. // If duration samples are not available in the traf use sidx subsegment_duration
  1828. let sidxMinStart = Infinity;
  1829. let sidxMaxEnd = 0;
  1830. const sidxs = findBox(data, ['sidx']);
  1831. for (let i = 0; i < sidxs.length; i++) {
  1832. const sidx = parseSegmentIndex(sidxs[i]);
  1833. if (sidx != null && sidx.references) {
  1834. sidxMinStart = Math.min(sidxMinStart, sidx.earliestPresentationTime / sidx.timescale);
  1835. const subSegmentDuration = sidx.references.reduce((dur, ref) => dur + ref.info.duration || 0, 0);
  1836. sidxMaxEnd = Math.max(sidxMaxEnd, subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale);
  1837. }
  1838. }
  1839. if (sidxMaxEnd && isFiniteNumber(sidxMaxEnd)) {
  1840. Object.keys(tracks).forEach(trackId => {
  1841. if (!tracks[trackId].duration) {
  1842. tracks[trackId].duration = sidxMaxEnd * tracks[trackId].timescale - tracks[trackId].start;
  1843. }
  1844. });
  1845. }
  1846. }
  1847. return tracks;
  1848. }
  1849. // TODO: Check if the last moof+mdat pair is part of the valid range
  1850. function segmentValidRange(data) {
  1851. const segmentedRange = {
  1852. valid: null,
  1853. remainder: null
  1854. };
  1855. const moofs = findBox(data, ['moof']);
  1856. if (moofs.length < 2) {
  1857. segmentedRange.remainder = data;
  1858. return segmentedRange;
  1859. }
  1860. const last = moofs[moofs.length - 1];
  1861. // Offset by 8 bytes; findBox offsets the start by as much
  1862. segmentedRange.valid = data.slice(0, last.byteOffset - 8);
  1863. segmentedRange.remainder = data.slice(last.byteOffset - 8);
  1864. return segmentedRange;
  1865. }
  1866. function appendUint8Array(data1, data2) {
  1867. const temp = new Uint8Array(data1.length + data2.length);
  1868. temp.set(data1);
  1869. temp.set(data2, data1.length);
  1870. return temp;
  1871. }
  1872. function parseSamples(timeOffset, track) {
  1873. const seiSamples = [];
  1874. const videoData = track.samples;
  1875. const timescale = track.timescale;
  1876. const trackId = track.id;
  1877. let isHEVCFlavor = false;
  1878. const moofs = findBox(videoData, ['moof']);
  1879. moofs.map(moof => {
  1880. const moofOffset = moof.byteOffset - 8;
  1881. const trafs = findBox(moof, ['traf']);
  1882. trafs.map(traf => {
  1883. // get the base media decode time from the tfdt
  1884. const baseTime = findBox(traf, ['tfdt']).map(tfdt => {
  1885. const version = tfdt[0];
  1886. let result = readUint32(tfdt, 4);
  1887. if (version === 1) {
  1888. result *= Math.pow(2, 32);
  1889. result += readUint32(tfdt, 8);
  1890. }
  1891. return result / timescale;
  1892. })[0];
  1893. if (baseTime !== undefined) {
  1894. timeOffset = baseTime;
  1895. }
  1896. return findBox(traf, ['tfhd']).map(tfhd => {
  1897. const id = readUint32(tfhd, 4);
  1898. const tfhdFlags = readUint32(tfhd, 0) & 0xffffff;
  1899. const baseDataOffsetPresent = (tfhdFlags & 0x000001) !== 0;
  1900. const sampleDescriptionIndexPresent = (tfhdFlags & 0x000002) !== 0;
  1901. const defaultSampleDurationPresent = (tfhdFlags & 0x000008) !== 0;
  1902. let defaultSampleDuration = 0;
  1903. const defaultSampleSizePresent = (tfhdFlags & 0x000010) !== 0;
  1904. let defaultSampleSize = 0;
  1905. const defaultSampleFlagsPresent = (tfhdFlags & 0x000020) !== 0;
  1906. let tfhdOffset = 8;
  1907. if (id === trackId) {
  1908. if (baseDataOffsetPresent) {
  1909. tfhdOffset += 8;
  1910. }
  1911. if (sampleDescriptionIndexPresent) {
  1912. tfhdOffset += 4;
  1913. }
  1914. if (defaultSampleDurationPresent) {
  1915. defaultSampleDuration = readUint32(tfhd, tfhdOffset);
  1916. tfhdOffset += 4;
  1917. }
  1918. if (defaultSampleSizePresent) {
  1919. defaultSampleSize = readUint32(tfhd, tfhdOffset);
  1920. tfhdOffset += 4;
  1921. }
  1922. if (defaultSampleFlagsPresent) {
  1923. tfhdOffset += 4;
  1924. }
  1925. if (track.type === 'video') {
  1926. isHEVCFlavor = isHEVC(track.codec);
  1927. }
  1928. findBox(traf, ['trun']).map(trun => {
  1929. const version = trun[0];
  1930. const flags = readUint32(trun, 0) & 0xffffff;
  1931. const dataOffsetPresent = (flags & 0x000001) !== 0;
  1932. let dataOffset = 0;
  1933. const firstSampleFlagsPresent = (flags & 0x000004) !== 0;
  1934. const sampleDurationPresent = (flags & 0x000100) !== 0;
  1935. let sampleDuration = 0;
  1936. const sampleSizePresent = (flags & 0x000200) !== 0;
  1937. let sampleSize = 0;
  1938. const sampleFlagsPresent = (flags & 0x000400) !== 0;
  1939. const sampleCompositionOffsetsPresent = (flags & 0x000800) !== 0;
  1940. let compositionOffset = 0;
  1941. const sampleCount = readUint32(trun, 4);
  1942. let trunOffset = 8; // past version, flags, and sample count
  1943. if (dataOffsetPresent) {
  1944. dataOffset = readUint32(trun, trunOffset);
  1945. trunOffset += 4;
  1946. }
  1947. if (firstSampleFlagsPresent) {
  1948. trunOffset += 4;
  1949. }
  1950. let sampleOffset = dataOffset + moofOffset;
  1951. for (let ix = 0; ix < sampleCount; ix++) {
  1952. if (sampleDurationPresent) {
  1953. sampleDuration = readUint32(trun, trunOffset);
  1954. trunOffset += 4;
  1955. } else {
  1956. sampleDuration = defaultSampleDuration;
  1957. }
  1958. if (sampleSizePresent) {
  1959. sampleSize = readUint32(trun, trunOffset);
  1960. trunOffset += 4;
  1961. } else {
  1962. sampleSize = defaultSampleSize;
  1963. }
  1964. if (sampleFlagsPresent) {
  1965. trunOffset += 4;
  1966. }
  1967. if (sampleCompositionOffsetsPresent) {
  1968. if (version === 0) {
  1969. compositionOffset = readUint32(trun, trunOffset);
  1970. } else {
  1971. compositionOffset = readSint32(trun, trunOffset);
  1972. }
  1973. trunOffset += 4;
  1974. }
  1975. if (track.type === ElementaryStreamTypes.VIDEO) {
  1976. let naluTotalSize = 0;
  1977. while (naluTotalSize < sampleSize) {
  1978. const naluSize = readUint32(videoData, sampleOffset);
  1979. sampleOffset += 4;
  1980. if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {
  1981. const data = videoData.subarray(sampleOffset, sampleOffset + naluSize);
  1982. parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale, seiSamples);
  1983. }
  1984. sampleOffset += naluSize;
  1985. naluTotalSize += naluSize + 4;
  1986. }
  1987. }
  1988. timeOffset += sampleDuration / timescale;
  1989. }
  1990. });
  1991. }
  1992. });
  1993. });
  1994. });
  1995. return seiSamples;
  1996. }
  1997. function isHEVC(codec) {
  1998. if (!codec) {
  1999. return false;
  2000. }
  2001. const baseCodec = codec.substring(0, 4);
  2002. return baseCodec === 'hvc1' || baseCodec === 'hev1' ||
  2003. // Dolby Vision
  2004. baseCodec === 'dvh1' || baseCodec === 'dvhe';
  2005. }
  2006. function isSEIMessage(isHEVCFlavor, naluHeader) {
  2007. if (isHEVCFlavor) {
  2008. const naluType = naluHeader >> 1 & 0x3f;
  2009. return naluType === 39 || naluType === 40;
  2010. } else {
  2011. const naluType = naluHeader & 0x1f;
  2012. return naluType === 6;
  2013. }
  2014. }
  2015. function parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) {
  2016. const data = discardEPB(unescapedData);
  2017. let seiPtr = 0;
  2018. // skip nal header
  2019. seiPtr += headerSize;
  2020. let payloadType = 0;
  2021. let payloadSize = 0;
  2022. let b = 0;
  2023. while (seiPtr < data.length) {
  2024. payloadType = 0;
  2025. do {
  2026. if (seiPtr >= data.length) {
  2027. break;
  2028. }
  2029. b = data[seiPtr++];
  2030. payloadType += b;
  2031. } while (b === 0xff);
  2032. // Parse payload size.
  2033. payloadSize = 0;
  2034. do {
  2035. if (seiPtr >= data.length) {
  2036. break;
  2037. }
  2038. b = data[seiPtr++];
  2039. payloadSize += b;
  2040. } while (b === 0xff);
  2041. const leftOver = data.length - seiPtr;
  2042. // Create a variable to process the payload
  2043. let payPtr = seiPtr;
  2044. // Increment the seiPtr to the end of the payload
  2045. if (payloadSize < leftOver) {
  2046. seiPtr += payloadSize;
  2047. } else if (payloadSize > leftOver) {
  2048. // Some type of corruption has happened?
  2049. logger.error(`Malformed SEI payload. ${payloadSize} is too small, only ${leftOver} bytes left to parse.`);
  2050. // We might be able to parse some data, but let's be safe and ignore it.
  2051. break;
  2052. }
  2053. if (payloadType === 4) {
  2054. const countryCode = data[payPtr++];
  2055. if (countryCode === 181) {
  2056. const providerCode = readUint16(data, payPtr);
  2057. payPtr += 2;
  2058. if (providerCode === 49) {
  2059. const userStructure = readUint32(data, payPtr);
  2060. payPtr += 4;
  2061. if (userStructure === 0x47413934) {
  2062. const userDataType = data[payPtr++];
  2063. // Raw CEA-608 bytes wrapped in CEA-708 packet
  2064. if (userDataType === 3) {
  2065. const firstByte = data[payPtr++];
  2066. const totalCCs = 0x1f & firstByte;
  2067. const enabled = 0x40 & firstByte;
  2068. const totalBytes = enabled ? 2 + totalCCs * 3 : 0;
  2069. const byteArray = new Uint8Array(totalBytes);
  2070. if (enabled) {
  2071. byteArray[0] = firstByte;
  2072. for (let i = 1; i < totalBytes; i++) {
  2073. byteArray[i] = data[payPtr++];
  2074. }
  2075. }
  2076. samples.push({
  2077. type: userDataType,
  2078. payloadType,
  2079. pts,
  2080. bytes: byteArray
  2081. });
  2082. }
  2083. }
  2084. }
  2085. }
  2086. } else if (payloadType === 5) {
  2087. if (payloadSize > 16) {
  2088. const uuidStrArray = [];
  2089. for (let i = 0; i < 16; i++) {
  2090. const _b = data[payPtr++].toString(16);
  2091. uuidStrArray.push(_b.length == 1 ? '0' + _b : _b);
  2092. if (i === 3 || i === 5 || i === 7 || i === 9) {
  2093. uuidStrArray.push('-');
  2094. }
  2095. }
  2096. const length = payloadSize - 16;
  2097. const userDataBytes = new Uint8Array(length);
  2098. for (let i = 0; i < length; i++) {
  2099. userDataBytes[i] = data[payPtr++];
  2100. }
  2101. samples.push({
  2102. payloadType,
  2103. pts,
  2104. uuid: uuidStrArray.join(''),
  2105. userData: utf8ArrayToStr(userDataBytes),
  2106. userDataBytes
  2107. });
  2108. }
  2109. }
  2110. }
  2111. }
  2112. /**
  2113. * remove Emulation Prevention bytes from a RBSP
  2114. */
  2115. function discardEPB(data) {
  2116. const length = data.byteLength;
  2117. const EPBPositions = [];
  2118. let i = 1;
  2119. // Find all `Emulation Prevention Bytes`
  2120. while (i < length - 2) {
  2121. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  2122. EPBPositions.push(i + 2);
  2123. i += 2;
  2124. } else {
  2125. i++;
  2126. }
  2127. }
  2128. // If no Emulation Prevention Bytes were found just return the original
  2129. // array
  2130. if (EPBPositions.length === 0) {
  2131. return data;
  2132. }
  2133. // Create a new array to hold the NAL unit data
  2134. const newLength = length - EPBPositions.length;
  2135. const newData = new Uint8Array(newLength);
  2136. let sourceIndex = 0;
  2137. for (i = 0; i < newLength; sourceIndex++, i++) {
  2138. if (sourceIndex === EPBPositions[0]) {
  2139. // Skip this byte
  2140. sourceIndex++;
  2141. // Remove this position index
  2142. EPBPositions.shift();
  2143. }
  2144. newData[i] = data[sourceIndex];
  2145. }
  2146. return newData;
  2147. }
  2148. function parseEmsg(data) {
  2149. const version = data[0];
  2150. let schemeIdUri = '';
  2151. let value = '';
  2152. let timeScale = 0;
  2153. let presentationTimeDelta = 0;
  2154. let presentationTime = 0;
  2155. let eventDuration = 0;
  2156. let id = 0;
  2157. let offset = 0;
  2158. if (version === 0) {
  2159. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2160. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2161. offset += 1;
  2162. }
  2163. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2164. offset += 1;
  2165. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2166. value += bin2str(data.subarray(offset, offset + 1));
  2167. offset += 1;
  2168. }
  2169. value += bin2str(data.subarray(offset, offset + 1));
  2170. offset += 1;
  2171. timeScale = readUint32(data, 12);
  2172. presentationTimeDelta = readUint32(data, 16);
  2173. eventDuration = readUint32(data, 20);
  2174. id = readUint32(data, 24);
  2175. offset = 28;
  2176. } else if (version === 1) {
  2177. offset += 4;
  2178. timeScale = readUint32(data, offset);
  2179. offset += 4;
  2180. const leftPresentationTime = readUint32(data, offset);
  2181. offset += 4;
  2182. const rightPresentationTime = readUint32(data, offset);
  2183. offset += 4;
  2184. presentationTime = 2 ** 32 * leftPresentationTime + rightPresentationTime;
  2185. if (!isSafeInteger(presentationTime)) {
  2186. presentationTime = Number.MAX_SAFE_INTEGER;
  2187. logger.warn('Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box');
  2188. }
  2189. eventDuration = readUint32(data, offset);
  2190. offset += 4;
  2191. id = readUint32(data, offset);
  2192. offset += 4;
  2193. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2194. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2195. offset += 1;
  2196. }
  2197. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2198. offset += 1;
  2199. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2200. value += bin2str(data.subarray(offset, offset + 1));
  2201. offset += 1;
  2202. }
  2203. value += bin2str(data.subarray(offset, offset + 1));
  2204. offset += 1;
  2205. }
  2206. const payload = data.subarray(offset, data.byteLength);
  2207. return {
  2208. schemeIdUri,
  2209. value,
  2210. timeScale,
  2211. presentationTime,
  2212. presentationTimeDelta,
  2213. eventDuration,
  2214. id,
  2215. payload
  2216. };
  2217. }
  2218. const userAgentHevcSupportIsInaccurate = () => {
  2219. return /\(Windows.+Firefox\//i.test(navigator.userAgent);
  2220. };
  2221. // from http://mp4ra.org/codecs.html
  2222. // values indicate codec selection preference (lower is higher priority)
  2223. const sampleEntryCodesISO = {
  2224. audio: {
  2225. a3ds: 1,
  2226. 'ac-3': 0.95,
  2227. 'ac-4': 1,
  2228. alac: 0.9,
  2229. alaw: 1,
  2230. dra1: 1,
  2231. 'dts+': 1,
  2232. 'dts-': 1,
  2233. dtsc: 1,
  2234. dtse: 1,
  2235. dtsh: 1,
  2236. 'ec-3': 0.9,
  2237. enca: 1,
  2238. fLaC: 0.9,
  2239. // MP4-RA listed codec entry for FLAC
  2240. flac: 0.9,
  2241. // legacy browser codec name for FLAC
  2242. FLAC: 0.9,
  2243. // some manifests may list "FLAC" with Apple's tools
  2244. g719: 1,
  2245. g726: 1,
  2246. m4ae: 1,
  2247. mha1: 1,
  2248. mha2: 1,
  2249. mhm1: 1,
  2250. mhm2: 1,
  2251. mlpa: 1,
  2252. mp4a: 1,
  2253. 'raw ': 1,
  2254. Opus: 1,
  2255. opus: 1,
  2256. // browsers expect this to be lowercase despite MP4RA says 'Opus'
  2257. samr: 1,
  2258. sawb: 1,
  2259. sawp: 1,
  2260. sevc: 1,
  2261. sqcp: 1,
  2262. ssmv: 1,
  2263. twos: 1,
  2264. ulaw: 1
  2265. },
  2266. video: {
  2267. avc1: 1,
  2268. avc2: 1,
  2269. avc3: 1,
  2270. avc4: 1,
  2271. avcp: 1,
  2272. av01: 0.8,
  2273. dav1: 0.8,
  2274. drac: 1,
  2275. dva1: 1,
  2276. dvav: 1,
  2277. dvh1: 0.7,
  2278. dvhe: 0.7,
  2279. encv: 1,
  2280. hev1: 0.75,
  2281. hvc1: 0.75,
  2282. mjp2: 1,
  2283. mp4v: 1,
  2284. mvc1: 1,
  2285. mvc2: 1,
  2286. mvc3: 1,
  2287. mvc4: 1,
  2288. resv: 1,
  2289. rv60: 1,
  2290. s263: 1,
  2291. svc1: 1,
  2292. svc2: 1,
  2293. 'vc-1': 1,
  2294. vp08: 1,
  2295. vp09: 0.9
  2296. },
  2297. text: {
  2298. stpp: 1,
  2299. wvtt: 1
  2300. }
  2301. };
  2302. function isCodecType(codec, type) {
  2303. const typeCodes = sampleEntryCodesISO[type];
  2304. return !!typeCodes && !!typeCodes[codec.slice(0, 4)];
  2305. }
  2306. function areCodecsMediaSourceSupported(codecs, type, preferManagedMediaSource = true) {
  2307. return !codecs.split(',').some(codec => !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource));
  2308. }
  2309. function isCodecMediaSourceSupported(codec, type, preferManagedMediaSource = true) {
  2310. var _MediaSource$isTypeSu;
  2311. const MediaSource = getMediaSource(preferManagedMediaSource);
  2312. return (_MediaSource$isTypeSu = MediaSource == null ? void 0 : MediaSource.isTypeSupported(mimeTypeForCodec(codec, type))) != null ? _MediaSource$isTypeSu : false;
  2313. }
  2314. function mimeTypeForCodec(codec, type) {
  2315. return `${type}/mp4;codecs=${codec}`;
  2316. }
  2317. function videoCodecPreferenceValue(videoCodec) {
  2318. if (videoCodec) {
  2319. const fourCC = videoCodec.substring(0, 4);
  2320. return sampleEntryCodesISO.video[fourCC];
  2321. }
  2322. return 2;
  2323. }
  2324. function codecsSetSelectionPreferenceValue(codecSet) {
  2325. const limitedHevcSupport = userAgentHevcSupportIsInaccurate();
  2326. return codecSet.split(',').reduce((num, fourCC) => {
  2327. const lowerPriority = limitedHevcSupport && isHEVC(fourCC);
  2328. const preferenceValue = lowerPriority ? 9 : sampleEntryCodesISO.video[fourCC];
  2329. if (preferenceValue) {
  2330. return (preferenceValue * 2 + num) / (num ? 3 : 2);
  2331. }
  2332. return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);
  2333. }, 0);
  2334. }
  2335. const CODEC_COMPATIBLE_NAMES = {};
  2336. function getCodecCompatibleNameLower(lowerCaseCodec, preferManagedMediaSource = true) {
  2337. if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {
  2338. return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];
  2339. }
  2340. const codecsToCheck = {
  2341. // Idealy fLaC and Opus would be first (spec-compliant) but
  2342. // some browsers will report that fLaC is supported then fail.
  2343. // see: https://bugs.chromium.org/p/chromium/issues/detail?id=1422728
  2344. flac: ['flac', 'fLaC', 'FLAC'],
  2345. opus: ['opus', 'Opus'],
  2346. // Replace audio codec info if browser does not support mp4a.40.34,
  2347. // and demuxer can fallback to 'audio/mpeg' or 'audio/mp4;codecs="mp3"'
  2348. 'mp4a.40.34': ['mp3']
  2349. }[lowerCaseCodec];
  2350. for (let i = 0; i < codecsToCheck.length; i++) {
  2351. var _getMediaSource;
  2352. if (isCodecMediaSourceSupported(codecsToCheck[i], 'audio', preferManagedMediaSource)) {
  2353. CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i];
  2354. return codecsToCheck[i];
  2355. } else if (codecsToCheck[i] === 'mp3' && (_getMediaSource = getMediaSource(preferManagedMediaSource)) != null && _getMediaSource.isTypeSupported('audio/mpeg')) {
  2356. return '';
  2357. }
  2358. }
  2359. return lowerCaseCodec;
  2360. }
  2361. const AUDIO_CODEC_REGEXP = /flac|opus|mp4a\.40\.34/i;
  2362. function getCodecCompatibleName(codec, preferManagedMediaSource = true) {
  2363. return codec.replace(AUDIO_CODEC_REGEXP, m => getCodecCompatibleNameLower(m.toLowerCase(), preferManagedMediaSource));
  2364. }
  2365. function replaceVideoCodec(originalCodecs, newVideoCodec) {
  2366. const codecs = [];
  2367. if (originalCodecs) {
  2368. const allCodecs = originalCodecs.split(',');
  2369. for (let i = 0; i < allCodecs.length; i++) {
  2370. if (!isCodecType(allCodecs[i], 'video')) {
  2371. codecs.push(allCodecs[i]);
  2372. }
  2373. }
  2374. }
  2375. if (newVideoCodec) {
  2376. codecs.push(newVideoCodec);
  2377. }
  2378. return codecs.join(',');
  2379. }
  2380. function pickMostCompleteCodecName(parsedCodec, levelCodec) {
  2381. // Parsing of mp4a codecs strings in mp4-tools from media is incomplete as of d8c6c7a
  2382. // so use level codec is parsed codec is unavailable or incomplete
  2383. if (parsedCodec && (parsedCodec.length > 4 || ['ac-3', 'ec-3', 'alac', 'fLaC', 'Opus'].indexOf(parsedCodec) !== -1)) {
  2384. if (isCodecSupportedAsType(parsedCodec, 'audio') || isCodecSupportedAsType(parsedCodec, 'video')) {
  2385. return parsedCodec;
  2386. }
  2387. }
  2388. if (levelCodec) {
  2389. const levelCodecs = levelCodec.split(',');
  2390. if (levelCodecs.length > 1) {
  2391. if (parsedCodec) {
  2392. for (let i = levelCodecs.length; i--;) {
  2393. if (levelCodecs[i].substring(0, 4) === parsedCodec.substring(0, 4)) {
  2394. return levelCodecs[i];
  2395. }
  2396. }
  2397. }
  2398. return levelCodecs[0];
  2399. }
  2400. }
  2401. return levelCodec || parsedCodec;
  2402. }
  2403. function isCodecSupportedAsType(codec, type) {
  2404. return isCodecType(codec, type) && isCodecMediaSourceSupported(codec, type);
  2405. }
  2406. function convertAVC1ToAVCOTI(videoCodecs) {
  2407. // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported
  2408. // Examples: avc1.66.30 to avc1.42001e and avc1.77.30,avc1.66.30 to avc1.4d001e,avc1.42001e.
  2409. const codecs = videoCodecs.split(',');
  2410. for (let i = 0; i < codecs.length; i++) {
  2411. const avcdata = codecs[i].split('.');
  2412. // only convert codec strings starting with avc1 (Examples: avc1.64001f,dvh1.05.07)
  2413. if (avcdata.length > 2 && avcdata[0] === 'avc1') {
  2414. codecs[i] = `avc1.${parseInt(avcdata[1]).toString(16)}${('000' + parseInt(avcdata[2]).toString(16)).slice(-4)}`;
  2415. }
  2416. }
  2417. return codecs.join(',');
  2418. }
  2419. function fillInMissingAV01Params(videoCodec) {
  2420. // Used to fill in incomplete AV1 playlist CODECS strings for mediaCapabilities.decodingInfo queries
  2421. if (videoCodec.startsWith('av01.')) {
  2422. const av1params = videoCodec.split('.');
  2423. const placeholders = ['0', '111', '01', '01', '01', '0'];
  2424. for (let i = av1params.length; i > 4 && i < 10; i++) {
  2425. av1params[i] = placeholders[i - 4];
  2426. }
  2427. return av1params.join('.');
  2428. }
  2429. return videoCodec;
  2430. }
  2431. function getM2TSSupportedAudioTypes(preferManagedMediaSource) {
  2432. const MediaSource = getMediaSource(preferManagedMediaSource) || {
  2433. isTypeSupported: () => false
  2434. };
  2435. return {
  2436. mpeg: MediaSource.isTypeSupported('audio/mpeg'),
  2437. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"'),
  2438. ac3: false
  2439. };
  2440. }
  2441. function getCodecsForMimeType(mimeType) {
  2442. return mimeType.replace(/^.+codecs=["']?([^"']+).*$/, '$1');
  2443. }
  2444. const HdcpLevels = ['NONE', 'TYPE-0', 'TYPE-1', null];
  2445. function isHdcpLevel(value) {
  2446. return HdcpLevels.indexOf(value) > -1;
  2447. }
  2448. const VideoRangeValues = ['SDR', 'PQ', 'HLG'];
  2449. function isVideoRange(value) {
  2450. return !!value && VideoRangeValues.indexOf(value) > -1;
  2451. }
  2452. var HlsSkip = {
  2453. No: "",
  2454. Yes: "YES",
  2455. v2: "v2"
  2456. };
  2457. function getSkipValue(details) {
  2458. const {
  2459. canSkipUntil,
  2460. canSkipDateRanges,
  2461. age
  2462. } = details;
  2463. // A Client SHOULD NOT request a Playlist Delta Update unless it already
  2464. // has a version of the Playlist that is no older than one-half of the Skip Boundary.
  2465. // @see: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis#section-6.3.7
  2466. const playlistRecentEnough = age < canSkipUntil / 2;
  2467. if (canSkipUntil && playlistRecentEnough) {
  2468. if (canSkipDateRanges) {
  2469. return HlsSkip.v2;
  2470. }
  2471. return HlsSkip.Yes;
  2472. }
  2473. return HlsSkip.No;
  2474. }
  2475. class HlsUrlParameters {
  2476. constructor(msn, part, skip) {
  2477. this.msn = void 0;
  2478. this.part = void 0;
  2479. this.skip = void 0;
  2480. this.msn = msn;
  2481. this.part = part;
  2482. this.skip = skip;
  2483. }
  2484. addDirectives(uri) {
  2485. const url = new self.URL(uri);
  2486. if (this.msn !== undefined) {
  2487. url.searchParams.set('_HLS_msn', this.msn.toString());
  2488. }
  2489. if (this.part !== undefined) {
  2490. url.searchParams.set('_HLS_part', this.part.toString());
  2491. }
  2492. if (this.skip) {
  2493. url.searchParams.set('_HLS_skip', this.skip);
  2494. }
  2495. return url.href;
  2496. }
  2497. }
  2498. class Level {
  2499. constructor(data) {
  2500. this._attrs = void 0;
  2501. this.audioCodec = void 0;
  2502. this.bitrate = void 0;
  2503. this.codecSet = void 0;
  2504. this.url = void 0;
  2505. this.frameRate = void 0;
  2506. this.height = void 0;
  2507. this.id = void 0;
  2508. this.name = void 0;
  2509. this.supplemental = void 0;
  2510. this.videoCodec = void 0;
  2511. this.width = void 0;
  2512. this.details = void 0;
  2513. this.fragmentError = 0;
  2514. this.loadError = 0;
  2515. this.loaded = void 0;
  2516. this.realBitrate = 0;
  2517. this.supportedPromise = void 0;
  2518. this.supportedResult = void 0;
  2519. this._avgBitrate = 0;
  2520. this._audioGroups = void 0;
  2521. this._subtitleGroups = void 0;
  2522. // Deprecated (retained for backwards compatibility)
  2523. this._urlId = 0;
  2524. this.url = [data.url];
  2525. this._attrs = [data.attrs];
  2526. this.bitrate = data.bitrate;
  2527. if (data.details) {
  2528. this.details = data.details;
  2529. }
  2530. this.id = data.id || 0;
  2531. this.name = data.name;
  2532. this.width = data.width || 0;
  2533. this.height = data.height || 0;
  2534. this.frameRate = data.attrs.optionalFloat('FRAME-RATE', 0);
  2535. this._avgBitrate = data.attrs.decimalInteger('AVERAGE-BANDWIDTH');
  2536. this.audioCodec = data.audioCodec;
  2537. this.videoCodec = data.videoCodec;
  2538. this.codecSet = [data.videoCodec, data.audioCodec].filter(c => !!c).map(s => s.substring(0, 4)).join(',');
  2539. if ('supplemental' in data) {
  2540. var _data$supplemental;
  2541. this.supplemental = data.supplemental;
  2542. const supplementalVideo = (_data$supplemental = data.supplemental) == null ? void 0 : _data$supplemental.videoCodec;
  2543. if (supplementalVideo && supplementalVideo !== data.videoCodec) {
  2544. this.codecSet += `,${supplementalVideo.substring(0, 4)}`;
  2545. }
  2546. }
  2547. this.addGroupId('audio', data.attrs.AUDIO);
  2548. this.addGroupId('text', data.attrs.SUBTITLES);
  2549. }
  2550. get maxBitrate() {
  2551. return Math.max(this.realBitrate, this.bitrate);
  2552. }
  2553. get averageBitrate() {
  2554. return this._avgBitrate || this.realBitrate || this.bitrate;
  2555. }
  2556. get attrs() {
  2557. return this._attrs[0];
  2558. }
  2559. get codecs() {
  2560. return this.attrs.CODECS || '';
  2561. }
  2562. get pathwayId() {
  2563. return this.attrs['PATHWAY-ID'] || '.';
  2564. }
  2565. get videoRange() {
  2566. return this.attrs['VIDEO-RANGE'] || 'SDR';
  2567. }
  2568. get score() {
  2569. return this.attrs.optionalFloat('SCORE', 0);
  2570. }
  2571. get uri() {
  2572. return this.url[0] || '';
  2573. }
  2574. hasAudioGroup(groupId) {
  2575. return hasGroup(this._audioGroups, groupId);
  2576. }
  2577. hasSubtitleGroup(groupId) {
  2578. return hasGroup(this._subtitleGroups, groupId);
  2579. }
  2580. get audioGroups() {
  2581. return this._audioGroups;
  2582. }
  2583. get subtitleGroups() {
  2584. return this._subtitleGroups;
  2585. }
  2586. addGroupId(type, groupId) {
  2587. if (!groupId) {
  2588. return;
  2589. }
  2590. if (type === 'audio') {
  2591. let audioGroups = this._audioGroups;
  2592. if (!audioGroups) {
  2593. audioGroups = this._audioGroups = [];
  2594. }
  2595. if (audioGroups.indexOf(groupId) === -1) {
  2596. audioGroups.push(groupId);
  2597. }
  2598. } else if (type === 'text') {
  2599. let subtitleGroups = this._subtitleGroups;
  2600. if (!subtitleGroups) {
  2601. subtitleGroups = this._subtitleGroups = [];
  2602. }
  2603. if (subtitleGroups.indexOf(groupId) === -1) {
  2604. subtitleGroups.push(groupId);
  2605. }
  2606. }
  2607. }
  2608. // Deprecated methods (retained for backwards compatibility)
  2609. get urlId() {
  2610. return 0;
  2611. }
  2612. set urlId(value) {}
  2613. get audioGroupIds() {
  2614. return this.audioGroups ? [this.audioGroupId] : undefined;
  2615. }
  2616. get textGroupIds() {
  2617. return this.subtitleGroups ? [this.textGroupId] : undefined;
  2618. }
  2619. get audioGroupId() {
  2620. var _this$audioGroups;
  2621. return (_this$audioGroups = this.audioGroups) == null ? void 0 : _this$audioGroups[0];
  2622. }
  2623. get textGroupId() {
  2624. var _this$subtitleGroups;
  2625. return (_this$subtitleGroups = this.subtitleGroups) == null ? void 0 : _this$subtitleGroups[0];
  2626. }
  2627. addFallback() {}
  2628. }
  2629. function hasGroup(groups, groupId) {
  2630. if (!groupId || !groups) {
  2631. return false;
  2632. }
  2633. return groups.indexOf(groupId) !== -1;
  2634. }
  2635. /**
  2636. * @returns Whether we can detect and validate HDR capability within the window context
  2637. */
  2638. function isHdrSupported() {
  2639. if (typeof matchMedia === 'function') {
  2640. const mediaQueryList = matchMedia('(dynamic-range: high)');
  2641. const badQuery = matchMedia('bad query');
  2642. if (mediaQueryList.media !== badQuery.media) {
  2643. return mediaQueryList.matches === true;
  2644. }
  2645. }
  2646. return false;
  2647. }
  2648. /**
  2649. * Sanitizes inputs to return the active video selection options for HDR/SDR.
  2650. * When both inputs are null:
  2651. *
  2652. * `{ preferHDR: false, allowedVideoRanges: [] }`
  2653. *
  2654. * When `currentVideoRange` non-null, maintain the active range:
  2655. *
  2656. * `{ preferHDR: currentVideoRange !== 'SDR', allowedVideoRanges: [currentVideoRange] }`
  2657. *
  2658. * When VideoSelectionOption non-null:
  2659. *
  2660. * - Allow all video ranges if `allowedVideoRanges` unspecified.
  2661. * - If `preferHDR` is non-null use the value to filter `allowedVideoRanges`.
  2662. * - Else check window for HDR support and set `preferHDR` to the result.
  2663. *
  2664. * @param currentVideoRange
  2665. * @param videoPreference
  2666. */
  2667. function getVideoSelectionOptions(currentVideoRange, videoPreference) {
  2668. let preferHDR = false;
  2669. let allowedVideoRanges = [];
  2670. if (currentVideoRange) {
  2671. preferHDR = currentVideoRange !== 'SDR';
  2672. allowedVideoRanges = [currentVideoRange];
  2673. }
  2674. if (videoPreference) {
  2675. allowedVideoRanges = videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);
  2676. const allowAutoPreferHDR = allowedVideoRanges.join('') !== 'SDR' && !videoPreference.videoCodec;
  2677. preferHDR = videoPreference.preferHDR !== undefined ? videoPreference.preferHDR : allowAutoPreferHDR && isHdrSupported();
  2678. if (!preferHDR) {
  2679. allowedVideoRanges = ['SDR'];
  2680. }
  2681. }
  2682. return {
  2683. preferHDR,
  2684. allowedVideoRanges
  2685. };
  2686. }
  2687. const omitCircularRefsReplacer = replacer => {
  2688. const known = new WeakSet();
  2689. return (_, value) => {
  2690. if (replacer) {
  2691. value = replacer(_, value);
  2692. }
  2693. if (typeof value === 'object' && value !== null) {
  2694. if (known.has(value)) {
  2695. return;
  2696. }
  2697. known.add(value);
  2698. }
  2699. return value;
  2700. };
  2701. };
  2702. const stringify = (object, replacer) => JSON.stringify(object, omitCircularRefsReplacer(replacer));
  2703. function getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference) {
  2704. const codecSets = Object.keys(codecTiers);
  2705. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  2706. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  2707. const videoCodecPreference = videoPreference == null ? void 0 : videoPreference.videoCodec;
  2708. const preferStereo = channelsPreference && parseInt(channelsPreference) === 2;
  2709. // Use first level set to determine stereo, and minimum resolution and framerate
  2710. let hasStereo = false;
  2711. let hasCurrentVideoRange = false;
  2712. let minHeight = Infinity;
  2713. let minFramerate = Infinity;
  2714. let minBitrate = Infinity;
  2715. let minIndex = Infinity;
  2716. let selectedScore = 0;
  2717. let videoRanges = [];
  2718. const {
  2719. preferHDR,
  2720. allowedVideoRanges
  2721. } = getVideoSelectionOptions(currentVideoRange, videoPreference);
  2722. for (let i = codecSets.length; i--;) {
  2723. const tier = codecTiers[codecSets[i]];
  2724. hasStereo || (hasStereo = tier.channels[2] > 0);
  2725. minHeight = Math.min(minHeight, tier.minHeight);
  2726. minFramerate = Math.min(minFramerate, tier.minFramerate);
  2727. minBitrate = Math.min(minBitrate, tier.minBitrate);
  2728. const matchingVideoRanges = allowedVideoRanges.filter(range => tier.videoRanges[range] > 0);
  2729. if (matchingVideoRanges.length > 0) {
  2730. hasCurrentVideoRange = true;
  2731. }
  2732. }
  2733. minHeight = isFiniteNumber(minHeight) ? minHeight : 0;
  2734. minFramerate = isFiniteNumber(minFramerate) ? minFramerate : 0;
  2735. const maxHeight = Math.max(1080, minHeight);
  2736. const maxFramerate = Math.max(30, minFramerate);
  2737. minBitrate = isFiniteNumber(minBitrate) ? minBitrate : currentBw;
  2738. currentBw = Math.max(minBitrate, currentBw);
  2739. // If there are no variants with matching preference, set currentVideoRange to undefined
  2740. if (!hasCurrentVideoRange) {
  2741. currentVideoRange = undefined;
  2742. }
  2743. const hasMultipleSets = codecSets.length > 1;
  2744. const codecSet = codecSets.reduce((selected, candidate) => {
  2745. // Remove candiates which do not meet bitrate, default audio, stereo or channels preference, 1080p or lower, 30fps or lower, or SDR/HDR selection if present
  2746. const candidateTier = codecTiers[candidate];
  2747. if (candidate === selected) {
  2748. return selected;
  2749. }
  2750. videoRanges = hasCurrentVideoRange ? allowedVideoRanges.filter(range => candidateTier.videoRanges[range] > 0) : [];
  2751. if (hasMultipleSets) {
  2752. if (candidateTier.minBitrate > currentBw) {
  2753. logStartCodecCandidateIgnored(candidate, `min bitrate of ${candidateTier.minBitrate} > current estimate of ${currentBw}`);
  2754. return selected;
  2755. }
  2756. if (!candidateTier.hasDefaultAudio) {
  2757. logStartCodecCandidateIgnored(candidate, `no renditions with default or auto-select sound found`);
  2758. return selected;
  2759. }
  2760. if (audioCodecPreference && candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0) {
  2761. logStartCodecCandidateIgnored(candidate, `audio codec preference "${audioCodecPreference}" not found`);
  2762. return selected;
  2763. }
  2764. if (channelsPreference && !preferStereo) {
  2765. if (!candidateTier.channels[channelsPreference]) {
  2766. logStartCodecCandidateIgnored(candidate, `no renditions with ${channelsPreference} channel sound found (channels options: ${Object.keys(candidateTier.channels)})`);
  2767. return selected;
  2768. }
  2769. } else if ((!audioCodecPreference || preferStereo) && hasStereo && candidateTier.channels['2'] === 0) {
  2770. logStartCodecCandidateIgnored(candidate, `no renditions with stereo sound found`);
  2771. return selected;
  2772. }
  2773. if (candidateTier.minHeight > maxHeight) {
  2774. logStartCodecCandidateIgnored(candidate, `min resolution of ${candidateTier.minHeight} > maximum of ${maxHeight}`);
  2775. return selected;
  2776. }
  2777. if (candidateTier.minFramerate > maxFramerate) {
  2778. logStartCodecCandidateIgnored(candidate, `min framerate of ${candidateTier.minFramerate} > maximum of ${maxFramerate}`);
  2779. return selected;
  2780. }
  2781. if (!videoRanges.some(range => candidateTier.videoRanges[range] > 0)) {
  2782. logStartCodecCandidateIgnored(candidate, `no variants with VIDEO-RANGE of ${stringify(videoRanges)} found`);
  2783. return selected;
  2784. }
  2785. if (videoCodecPreference && candidate.indexOf(videoCodecPreference.substring(0, 4)) % 5 !== 0) {
  2786. logStartCodecCandidateIgnored(candidate, `video codec preference "${videoCodecPreference}" not found`);
  2787. return selected;
  2788. }
  2789. if (candidateTier.maxScore < selectedScore) {
  2790. logStartCodecCandidateIgnored(candidate, `max score of ${candidateTier.maxScore} < selected max of ${selectedScore}`);
  2791. return selected;
  2792. }
  2793. }
  2794. // Remove candiates with less preferred codecs or more errors
  2795. if (selected && (codecsSetSelectionPreferenceValue(candidate) >= codecsSetSelectionPreferenceValue(selected) || candidateTier.fragmentError > codecTiers[selected].fragmentError)) {
  2796. return selected;
  2797. }
  2798. minIndex = candidateTier.minIndex;
  2799. selectedScore = candidateTier.maxScore;
  2800. return candidate;
  2801. }, undefined);
  2802. return {
  2803. codecSet,
  2804. videoRanges,
  2805. preferHDR,
  2806. minFramerate,
  2807. minBitrate,
  2808. minIndex
  2809. };
  2810. }
  2811. function logStartCodecCandidateIgnored(codeSet, reason) {
  2812. logger.log(`[abr] start candidates with "${codeSet}" ignored because ${reason}`);
  2813. }
  2814. function getAudioTracksByGroup(allAudioTracks) {
  2815. return allAudioTracks.reduce((audioTracksByGroup, track) => {
  2816. let trackGroup = audioTracksByGroup.groups[track.groupId];
  2817. if (!trackGroup) {
  2818. trackGroup = audioTracksByGroup.groups[track.groupId] = {
  2819. tracks: [],
  2820. channels: {
  2821. 2: 0
  2822. },
  2823. hasDefault: false,
  2824. hasAutoSelect: false
  2825. };
  2826. }
  2827. trackGroup.tracks.push(track);
  2828. const channelsKey = track.channels || '2';
  2829. trackGroup.channels[channelsKey] = (trackGroup.channels[channelsKey] || 0) + 1;
  2830. trackGroup.hasDefault = trackGroup.hasDefault || track.default;
  2831. trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;
  2832. if (trackGroup.hasDefault) {
  2833. audioTracksByGroup.hasDefaultAudio = true;
  2834. }
  2835. if (trackGroup.hasAutoSelect) {
  2836. audioTracksByGroup.hasAutoSelectAudio = true;
  2837. }
  2838. return audioTracksByGroup;
  2839. }, {
  2840. hasDefaultAudio: false,
  2841. hasAutoSelectAudio: false,
  2842. groups: {}
  2843. });
  2844. }
  2845. function getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel) {
  2846. return levels.slice(minAutoLevel, maxAutoLevel + 1).reduce((tiers, level, index) => {
  2847. if (!level.codecSet) {
  2848. return tiers;
  2849. }
  2850. const audioGroups = level.audioGroups;
  2851. let tier = tiers[level.codecSet];
  2852. if (!tier) {
  2853. tiers[level.codecSet] = tier = {
  2854. minBitrate: Infinity,
  2855. minHeight: Infinity,
  2856. minFramerate: Infinity,
  2857. minIndex: index,
  2858. maxScore: 0,
  2859. videoRanges: {
  2860. SDR: 0
  2861. },
  2862. channels: {
  2863. '2': 0
  2864. },
  2865. hasDefaultAudio: !audioGroups,
  2866. fragmentError: 0
  2867. };
  2868. }
  2869. tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);
  2870. const lesserWidthOrHeight = Math.min(level.height, level.width);
  2871. tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);
  2872. tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);
  2873. tier.minIndex = Math.min(tier.minIndex, index);
  2874. tier.maxScore = Math.max(tier.maxScore, level.score);
  2875. tier.fragmentError += level.fragmentError;
  2876. tier.videoRanges[level.videoRange] = (tier.videoRanges[level.videoRange] || 0) + 1;
  2877. return tiers;
  2878. }, {});
  2879. }
  2880. function useAlternateAudio(audioTrackUrl, hls) {
  2881. var _hls$loadLevelObj;
  2882. return !!audioTrackUrl && audioTrackUrl !== ((_hls$loadLevelObj = hls.loadLevelObj) == null ? void 0 : _hls$loadLevelObj.uri);
  2883. }
  2884. class AbrController extends Logger {
  2885. constructor(_hls) {
  2886. super('abr', _hls.logger);
  2887. this.hls = void 0;
  2888. this.lastLevelLoadSec = 0;
  2889. this.lastLoadedFragLevel = -1;
  2890. this.firstSelection = -1;
  2891. this._nextAutoLevel = -1;
  2892. this.nextAutoLevelKey = '';
  2893. this.audioTracksByGroup = null;
  2894. this.codecTiers = null;
  2895. this.timer = -1;
  2896. this.fragCurrent = null;
  2897. this.partCurrent = null;
  2898. this.bitrateTestDelay = 0;
  2899. this.rebufferNotice = -1;
  2900. this.supportedCache = {};
  2901. this.bwEstimator = void 0;
  2902. /*
  2903. This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load
  2904. quickly enough to prevent underbuffering
  2905. */
  2906. this._abandonRulesCheck = levelLoaded => {
  2907. var _ref;
  2908. const {
  2909. fragCurrent: frag,
  2910. partCurrent: part,
  2911. hls
  2912. } = this;
  2913. const {
  2914. autoLevelEnabled,
  2915. media
  2916. } = hls;
  2917. if (!frag || !media) {
  2918. return;
  2919. }
  2920. const now = performance.now();
  2921. const stats = part ? part.stats : frag.stats;
  2922. const duration = part ? part.duration : frag.duration;
  2923. const timeLoading = now - stats.loading.start;
  2924. const minAutoLevel = hls.minAutoLevel;
  2925. const loadingFragForLevel = frag.level;
  2926. const currentAutoLevel = this._nextAutoLevel;
  2927. // If frag loading is aborted, complete, or from lowest level, stop timer and return
  2928. if (stats.aborted || stats.loaded && stats.loaded === stats.total || loadingFragForLevel <= minAutoLevel) {
  2929. this.clearTimer();
  2930. // reset forced auto level value so that next level will be selected
  2931. this._nextAutoLevel = -1;
  2932. return;
  2933. }
  2934. // This check only runs if we're in ABR mode
  2935. if (!autoLevelEnabled) {
  2936. return;
  2937. }
  2938. // Must be loading/loaded a new level or be in a playing state
  2939. const fragBlockingSwitch = currentAutoLevel > -1 && currentAutoLevel !== loadingFragForLevel;
  2940. const levelChange = !!levelLoaded || fragBlockingSwitch;
  2941. if (!levelChange && (media.paused || !media.playbackRate || !media.readyState)) {
  2942. return;
  2943. }
  2944. const bufferInfo = hls.mainForwardBufferInfo;
  2945. if (!levelChange && bufferInfo === null) {
  2946. return;
  2947. }
  2948. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  2949. const playbackRate = Math.abs(media.playbackRate);
  2950. // To maintain stable adaptive playback, only begin monitoring frag loading after half or more of its playback duration has passed
  2951. if (timeLoading <= Math.max(ttfbEstimate, 1000 * (duration / (playbackRate * 2)))) {
  2952. return;
  2953. }
  2954. // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer
  2955. const bufferStarvationDelay = bufferInfo ? bufferInfo.len / playbackRate : 0;
  2956. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  2957. const loadedFirstByte = stats.loaded && ttfb > -1;
  2958. const bwEstimate = this.getBwEstimate();
  2959. const levels = hls.levels;
  2960. const level = levels[loadingFragForLevel];
  2961. const expectedLen = Math.max(stats.loaded, Math.round(duration * (frag.bitrate || level.averageBitrate) / 8));
  2962. let timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;
  2963. if (timeStreaming < 1 && loadedFirstByte) {
  2964. timeStreaming = Math.min(timeLoading, stats.loaded * 8 / bwEstimate);
  2965. }
  2966. const loadRate = loadedFirstByte ? stats.loaded * 1000 / timeStreaming : 0;
  2967. // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the remainder of the fragment
  2968. const ttfbSeconds = ttfbEstimate / 1000;
  2969. const fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate + ttfbSeconds;
  2970. // Only downswitch if the time to finish loading the current fragment is greater than the amount of buffer left
  2971. if (fragLoadedDelay <= bufferStarvationDelay) {
  2972. return;
  2973. }
  2974. const bwe = loadRate ? loadRate * 8 : bwEstimate;
  2975. const live = ((_ref = (levelLoaded == null ? void 0 : levelLoaded.details) || this.hls.latestLevelDetails) == null ? void 0 : _ref.live) === true;
  2976. const abrBandWidthUpFactor = this.hls.config.abrBandWidthUpFactor;
  2977. let fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
  2978. let nextLoadLevel;
  2979. // Iterate through lower level and try to find the largest one that avoids rebuffering
  2980. for (nextLoadLevel = loadingFragForLevel - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  2981. // compute time to load next fragment at lower level
  2982. // 8 = bits per byte (bps/Bps)
  2983. const levelNextBitrate = levels[nextLoadLevel].maxBitrate;
  2984. const requiresLevelLoad = !levels[nextLoadLevel].details || live;
  2985. fragLevelNextLoadedDelay = this.getTimeToLoadFrag(ttfbSeconds, bwe, duration * levelNextBitrate, requiresLevelLoad);
  2986. if (fragLevelNextLoadedDelay < Math.min(bufferStarvationDelay, duration + ttfbSeconds)) {
  2987. break;
  2988. }
  2989. }
  2990. // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing
  2991. // to load the current one
  2992. if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
  2993. return;
  2994. }
  2995. // if estimated load time of new segment is completely unreasonable, ignore and do not emergency switch down
  2996. if (fragLevelNextLoadedDelay > duration * 10) {
  2997. return;
  2998. }
  2999. if (loadedFirstByte) {
  3000. // If there has been loading progress, sample bandwidth using loading time offset by minimum TTFB time
  3001. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  3002. } else {
  3003. // If there has been no loading progress, sample TTFB
  3004. this.bwEstimator.sampleTTFB(timeLoading);
  3005. }
  3006. const nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;
  3007. if (this.getBwEstimate() * abrBandWidthUpFactor > nextLoadLevelBitrate) {
  3008. this.resetEstimator(nextLoadLevelBitrate);
  3009. }
  3010. const bestSwitchLevel = this.findBestLevel(nextLoadLevelBitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay, 1, 1);
  3011. if (bestSwitchLevel > -1) {
  3012. nextLoadLevel = bestSwitchLevel;
  3013. }
  3014. this.warn(`Fragment ${frag.sn}${part ? ' part ' + part.index : ''} of level ${loadingFragForLevel} is loading too slowly;
  3015. Fragment duration: ${frag.duration.toFixed(3)}
  3016. Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s
  3017. Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s
  3018. Estimated load time for down switch fragment: ${fragLevelNextLoadedDelay.toFixed(3)} s
  3019. TTFB estimate: ${ttfb | 0} ms
  3020. Current BW estimate: ${isFiniteNumber(bwEstimate) ? bwEstimate | 0 : 'Unknown'} bps
  3021. New BW estimate: ${this.getBwEstimate() | 0} bps
  3022. Switching to level ${nextLoadLevel} @ ${nextLoadLevelBitrate | 0} bps`);
  3023. hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;
  3024. this.clearTimer();
  3025. const abortAndSwitch = () => {
  3026. // Are nextLoadLevel details available or is stream-controller still in "WAITING_LEVEL" state?
  3027. this.clearTimer();
  3028. if (this.fragCurrent === frag && this.hls.loadLevel === nextLoadLevel && nextLoadLevel > 0) {
  3029. const bufferStarvationDelay = this.getStarvationDelay();
  3030. this.warn(`Aborting inflight request ${nextLoadLevel > 0 ? 'and switching down' : ''}
  3031. Fragment duration: ${frag.duration.toFixed(3)} s
  3032. Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s`);
  3033. frag.abortRequests();
  3034. this.fragCurrent = this.partCurrent = null;
  3035. if (nextLoadLevel > minAutoLevel) {
  3036. let lowestSwitchLevel = this.findBestLevel(this.hls.levels[minAutoLevel].bitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay, 1, 1);
  3037. if (lowestSwitchLevel === -1) {
  3038. lowestSwitchLevel = minAutoLevel;
  3039. }
  3040. this.hls.nextLoadLevel = this.hls.nextAutoLevel = lowestSwitchLevel;
  3041. this.resetEstimator(this.hls.levels[lowestSwitchLevel].bitrate);
  3042. }
  3043. }
  3044. };
  3045. if (fragBlockingSwitch || fragLoadedDelay > fragLevelNextLoadedDelay * 2) {
  3046. abortAndSwitch();
  3047. } else {
  3048. this.timer = self.setInterval(abortAndSwitch, fragLevelNextLoadedDelay * 1000);
  3049. }
  3050. hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, {
  3051. frag,
  3052. part,
  3053. stats
  3054. });
  3055. };
  3056. this.hls = _hls;
  3057. this.bwEstimator = this.initEstimator();
  3058. this.registerListeners();
  3059. }
  3060. resetEstimator(abrEwmaDefaultEstimate) {
  3061. if (abrEwmaDefaultEstimate) {
  3062. this.log(`setting initial bwe to ${abrEwmaDefaultEstimate}`);
  3063. this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;
  3064. }
  3065. this.firstSelection = -1;
  3066. this.bwEstimator = this.initEstimator();
  3067. }
  3068. initEstimator() {
  3069. const config = this.hls.config;
  3070. return new EwmaBandWidthEstimator(config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
  3071. }
  3072. registerListeners() {
  3073. const {
  3074. hls
  3075. } = this;
  3076. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3077. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  3078. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  3079. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  3080. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  3081. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  3082. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  3083. hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  3084. hls.on(Events.ERROR, this.onError, this);
  3085. }
  3086. unregisterListeners() {
  3087. const {
  3088. hls
  3089. } = this;
  3090. if (!hls) {
  3091. return;
  3092. }
  3093. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3094. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  3095. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  3096. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  3097. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  3098. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  3099. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  3100. hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  3101. hls.off(Events.ERROR, this.onError, this);
  3102. }
  3103. destroy() {
  3104. this.unregisterListeners();
  3105. this.clearTimer();
  3106. // @ts-ignore
  3107. this.hls = this._abandonRulesCheck = this.supportedCache = null;
  3108. this.fragCurrent = this.partCurrent = null;
  3109. }
  3110. onManifestLoading(event, data) {
  3111. this.lastLoadedFragLevel = -1;
  3112. this.firstSelection = -1;
  3113. this.lastLevelLoadSec = 0;
  3114. this.supportedCache = {};
  3115. this.fragCurrent = this.partCurrent = null;
  3116. this.onLevelsUpdated();
  3117. this.clearTimer();
  3118. }
  3119. onLevelsUpdated() {
  3120. if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {
  3121. this.lastLoadedFragLevel = this.fragCurrent.level;
  3122. }
  3123. this._nextAutoLevel = -1;
  3124. this.onMaxAutoLevelUpdated();
  3125. this.codecTiers = null;
  3126. this.audioTracksByGroup = null;
  3127. }
  3128. onMaxAutoLevelUpdated() {
  3129. this.firstSelection = -1;
  3130. this.nextAutoLevelKey = '';
  3131. }
  3132. onFragLoading(event, data) {
  3133. const frag = data.frag;
  3134. if (this.ignoreFragment(frag)) {
  3135. return;
  3136. }
  3137. if (!frag.bitrateTest) {
  3138. var _data$part;
  3139. this.fragCurrent = frag;
  3140. this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
  3141. }
  3142. this.clearTimer();
  3143. this.timer = self.setInterval(this._abandonRulesCheck, 100);
  3144. }
  3145. onLevelSwitching(event, data) {
  3146. this.clearTimer();
  3147. }
  3148. onError(event, data) {
  3149. if (data.fatal) {
  3150. return;
  3151. }
  3152. switch (data.details) {
  3153. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  3154. case ErrorDetails.BUFFER_APPEND_ERROR:
  3155. // Reset last loaded level so that a new selection can be made after calling recoverMediaError
  3156. this.lastLoadedFragLevel = -1;
  3157. this.firstSelection = -1;
  3158. break;
  3159. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  3160. {
  3161. const frag = data.frag;
  3162. const {
  3163. fragCurrent,
  3164. partCurrent: part
  3165. } = this;
  3166. if (frag && fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level) {
  3167. const now = performance.now();
  3168. const stats = part ? part.stats : frag.stats;
  3169. const timeLoading = now - stats.loading.start;
  3170. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  3171. const loadedFirstByte = stats.loaded && ttfb > -1;
  3172. if (loadedFirstByte) {
  3173. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  3174. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  3175. } else {
  3176. this.bwEstimator.sampleTTFB(timeLoading);
  3177. }
  3178. }
  3179. break;
  3180. }
  3181. }
  3182. }
  3183. getTimeToLoadFrag(timeToFirstByteSec, bandwidth, fragSizeBits, isSwitch) {
  3184. const fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;
  3185. const playlistLoadSec = isSwitch ? timeToFirstByteSec + this.lastLevelLoadSec : 0;
  3186. return fragLoadSec + playlistLoadSec;
  3187. }
  3188. onLevelLoaded(event, data) {
  3189. const config = this.hls.config;
  3190. const {
  3191. loading
  3192. } = data.stats;
  3193. const timeLoadingMs = loading.end - loading.first;
  3194. if (isFiniteNumber(timeLoadingMs)) {
  3195. this.lastLevelLoadSec = timeLoadingMs / 1000;
  3196. }
  3197. if (data.details.live) {
  3198. this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
  3199. } else {
  3200. this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
  3201. }
  3202. if (this.timer > -1) {
  3203. this._abandonRulesCheck(data.levelInfo);
  3204. }
  3205. }
  3206. onFragLoaded(event, {
  3207. frag,
  3208. part
  3209. }) {
  3210. const stats = part ? part.stats : frag.stats;
  3211. if (frag.type === PlaylistLevelType.MAIN) {
  3212. this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);
  3213. }
  3214. if (this.ignoreFragment(frag)) {
  3215. return;
  3216. }
  3217. // stop monitoring bw once frag loaded
  3218. this.clearTimer();
  3219. // reset forced auto level value so that next level will be selected
  3220. if (frag.level === this._nextAutoLevel) {
  3221. this._nextAutoLevel = -1;
  3222. }
  3223. this.firstSelection = -1;
  3224. // compute level average bitrate
  3225. if (this.hls.config.abrMaxWithRealBitrate) {
  3226. const duration = part ? part.duration : frag.duration;
  3227. const level = this.hls.levels[frag.level];
  3228. const loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
  3229. const loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
  3230. level.loaded = {
  3231. bytes: loadedBytes,
  3232. duration: loadedDuration
  3233. };
  3234. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  3235. }
  3236. if (frag.bitrateTest) {
  3237. const fragBufferedData = {
  3238. stats,
  3239. frag,
  3240. part,
  3241. id: frag.type
  3242. };
  3243. this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);
  3244. frag.bitrateTest = false;
  3245. } else {
  3246. // store level id after successful fragment load for playback
  3247. this.lastLoadedFragLevel = frag.level;
  3248. }
  3249. }
  3250. onFragBuffered(event, data) {
  3251. const {
  3252. frag,
  3253. part
  3254. } = data;
  3255. const stats = part != null && part.stats.loaded ? part.stats : frag.stats;
  3256. if (stats.aborted) {
  3257. return;
  3258. }
  3259. if (this.ignoreFragment(frag)) {
  3260. return;
  3261. }
  3262. // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;
  3263. // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch
  3264. // is used. If we used buffering in that case, our BW estimate sample will be very large.
  3265. const processingMs = stats.parsing.end - stats.loading.start - Math.min(stats.loading.first - stats.loading.start, this.bwEstimator.getEstimateTTFB());
  3266. this.bwEstimator.sample(processingMs, stats.loaded);
  3267. stats.bwEstimate = this.getBwEstimate();
  3268. if (frag.bitrateTest) {
  3269. this.bitrateTestDelay = processingMs / 1000;
  3270. } else {
  3271. this.bitrateTestDelay = 0;
  3272. }
  3273. }
  3274. ignoreFragment(frag) {
  3275. // Only count non-alt-audio frags which were actually buffered in our BW calculations
  3276. return frag.type !== PlaylistLevelType.MAIN || frag.sn === 'initSegment';
  3277. }
  3278. clearTimer() {
  3279. if (this.timer > -1) {
  3280. self.clearInterval(this.timer);
  3281. this.timer = -1;
  3282. }
  3283. }
  3284. get firstAutoLevel() {
  3285. const {
  3286. maxAutoLevel,
  3287. minAutoLevel
  3288. } = this.hls;
  3289. const bwEstimate = this.getBwEstimate();
  3290. const maxStartDelay = this.hls.config.maxStarvationDelay;
  3291. const abrAutoLevel = this.findBestLevel(bwEstimate, minAutoLevel, maxAutoLevel, 0, maxStartDelay, 1, 1);
  3292. if (abrAutoLevel > -1) {
  3293. return abrAutoLevel;
  3294. }
  3295. const firstLevel = this.hls.firstLevel;
  3296. const clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);
  3297. this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${firstLevel} clamped to ${clamped}`);
  3298. return clamped;
  3299. }
  3300. get forcedAutoLevel() {
  3301. if (this.nextAutoLevelKey) {
  3302. return -1;
  3303. }
  3304. return this._nextAutoLevel;
  3305. }
  3306. // return next auto level
  3307. get nextAutoLevel() {
  3308. const forcedAutoLevel = this.forcedAutoLevel;
  3309. const bwEstimator = this.bwEstimator;
  3310. const useEstimate = bwEstimator.canEstimate();
  3311. const loadedFirstFrag = this.lastLoadedFragLevel > -1;
  3312. // in case next auto level has been forced, and bw not available or not reliable, return forced value
  3313. if (forcedAutoLevel !== -1 && (!useEstimate || !loadedFirstFrag || this.nextAutoLevelKey === this.getAutoLevelKey())) {
  3314. return forcedAutoLevel;
  3315. }
  3316. // compute next level using ABR logic
  3317. const nextABRAutoLevel = useEstimate && loadedFirstFrag ? this.getNextABRAutoLevel() : this.firstAutoLevel;
  3318. // use forced auto level while it hasn't errored more than ABR selection
  3319. if (forcedAutoLevel !== -1) {
  3320. const levels = this.hls.levels;
  3321. if (levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) && levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError) {
  3322. return forcedAutoLevel;
  3323. }
  3324. }
  3325. // save result until state has changed
  3326. this._nextAutoLevel = nextABRAutoLevel;
  3327. this.nextAutoLevelKey = this.getAutoLevelKey();
  3328. return nextABRAutoLevel;
  3329. }
  3330. getAutoLevelKey() {
  3331. return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`;
  3332. }
  3333. getNextABRAutoLevel() {
  3334. const {
  3335. fragCurrent,
  3336. partCurrent,
  3337. hls
  3338. } = this;
  3339. if (hls.levels.length <= 1) {
  3340. return hls.loadLevel;
  3341. }
  3342. const {
  3343. maxAutoLevel,
  3344. config,
  3345. minAutoLevel
  3346. } = hls;
  3347. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  3348. const avgbw = this.getBwEstimate();
  3349. // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
  3350. const bufferStarvationDelay = this.getStarvationDelay();
  3351. let bwFactor = config.abrBandWidthFactor;
  3352. let bwUpFactor = config.abrBandWidthUpFactor;
  3353. // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
  3354. if (bufferStarvationDelay) {
  3355. const _bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, 0, bwFactor, bwUpFactor);
  3356. if (_bestLevel >= 0) {
  3357. this.rebufferNotice = -1;
  3358. return _bestLevel;
  3359. }
  3360. }
  3361. // not possible to get rid of rebuffering... try to find level that will guarantee less than maxStarvationDelay of rebuffering
  3362. let maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
  3363. if (!bufferStarvationDelay) {
  3364. // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
  3365. const bitrateTestDelay = this.bitrateTestDelay;
  3366. if (bitrateTestDelay) {
  3367. // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
  3368. // max video loading delay used in automatic start level selection :
  3369. // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
  3370. // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
  3371. // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
  3372. const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  3373. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  3374. this.info(`bitrate test took ${Math.round(1000 * bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1000 * maxStarvationDelay)} ms`);
  3375. // don't use conservative factor on bitrate test
  3376. bwFactor = bwUpFactor = 1;
  3377. }
  3378. }
  3379. const bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor);
  3380. if (this.rebufferNotice !== bestLevel) {
  3381. this.rebufferNotice = bestLevel;
  3382. this.info(`${bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty'}, optimal quality level ${bestLevel}`);
  3383. }
  3384. if (bestLevel > -1) {
  3385. return bestLevel;
  3386. }
  3387. // If no matching level found, see if min auto level would be a better option
  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. // or if bitrate is not lower, continue to use loadLevel
  3394. return hls.loadLevel;
  3395. }
  3396. getStarvationDelay() {
  3397. const hls = this.hls;
  3398. const media = hls.media;
  3399. if (!media) {
  3400. return Infinity;
  3401. }
  3402. // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as
  3403. // if we're playing back at the normal rate.
  3404. const playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;
  3405. const bufferInfo = hls.mainForwardBufferInfo;
  3406. return (bufferInfo ? bufferInfo.len : 0) / playbackRate;
  3407. }
  3408. getBwEstimate() {
  3409. return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;
  3410. }
  3411. findBestLevel(currentBw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor) {
  3412. var _this$hls$latestLevel;
  3413. const maxFetchDuration = bufferStarvationDelay + maxStarvationDelay;
  3414. const lastLoadedFragLevel = this.lastLoadedFragLevel;
  3415. const selectionBaseLevel = lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;
  3416. const {
  3417. fragCurrent,
  3418. partCurrent
  3419. } = this;
  3420. const {
  3421. levels,
  3422. allAudioTracks,
  3423. loadLevel,
  3424. config
  3425. } = this.hls;
  3426. if (levels.length === 1) {
  3427. return 0;
  3428. }
  3429. const level = levels[selectionBaseLevel];
  3430. const live = !!((_this$hls$latestLevel = this.hls.latestLevelDetails) != null && _this$hls$latestLevel.live);
  3431. const firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;
  3432. let currentCodecSet;
  3433. let currentVideoRange = 'SDR';
  3434. let currentFrameRate = (level == null ? void 0 : level.frameRate) || 0;
  3435. const {
  3436. audioPreference,
  3437. videoPreference
  3438. } = config;
  3439. const audioTracksByGroup = this.audioTracksByGroup || (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));
  3440. let minStartIndex = -1;
  3441. if (firstSelection) {
  3442. if (this.firstSelection !== -1) {
  3443. return this.firstSelection;
  3444. }
  3445. const codecTiers = this.codecTiers || (this.codecTiers = getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel));
  3446. const startTier = getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference);
  3447. const {
  3448. codecSet,
  3449. videoRanges,
  3450. minFramerate,
  3451. minBitrate,
  3452. minIndex,
  3453. preferHDR
  3454. } = startTier;
  3455. minStartIndex = minIndex;
  3456. currentCodecSet = codecSet;
  3457. currentVideoRange = preferHDR ? videoRanges[videoRanges.length - 1] : videoRanges[0];
  3458. currentFrameRate = minFramerate;
  3459. currentBw = Math.max(currentBw, minBitrate);
  3460. this.log(`picked start tier ${stringify(startTier)}`);
  3461. } else {
  3462. currentCodecSet = level == null ? void 0 : level.codecSet;
  3463. currentVideoRange = level == null ? void 0 : level.videoRange;
  3464. }
  3465. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  3466. const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1000;
  3467. const levelsSkipped = [];
  3468. for (let i = maxAutoLevel; i >= minAutoLevel; i--) {
  3469. var _levelInfo$supportedR, _levelInfo$supportedR2;
  3470. const levelInfo = levels[i];
  3471. const upSwitch = i > selectionBaseLevel;
  3472. if (!levelInfo) {
  3473. continue;
  3474. }
  3475. // skip candidates which change codec-family or video-range,
  3476. // and which decrease or increase frame-rate for up and down-switch respectfully
  3477. if (currentCodecSet && levelInfo.codecSet !== currentCodecSet || currentVideoRange && levelInfo.videoRange !== currentVideoRange || upSwitch && currentFrameRate > levelInfo.frameRate || !upSwitch && currentFrameRate > 0 && currentFrameRate < levelInfo.frameRate || (_levelInfo$supportedR = levelInfo.supportedResult) != null && (_levelInfo$supportedR2 = _levelInfo$supportedR.decodingInfoResults) != null && _levelInfo$supportedR2.some(info => info.smooth === false)) {
  3478. if (!firstSelection || i !== minStartIndex) {
  3479. levelsSkipped.push(i);
  3480. continue;
  3481. }
  3482. }
  3483. const levelDetails = levelInfo.details;
  3484. const avgDuration = (partCurrent ? levelDetails == null ? void 0 : levelDetails.partTarget : levelDetails == null ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
  3485. let adjustedbw;
  3486. // follow algorithm captured from stagefright :
  3487. // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
  3488. // Pick the highest bandwidth stream below or equal to estimated bandwidth.
  3489. // consider only 80% of the available bandwidth, but if we are switching up,
  3490. // be even more conservative (70%) to avoid overestimating and immediately
  3491. // switching back.
  3492. if (!upSwitch) {
  3493. adjustedbw = bwFactor * currentBw;
  3494. } else {
  3495. adjustedbw = bwUpFactor * currentBw;
  3496. }
  3497. // Use average bitrate when starvation delay (buffer length) is gt or eq two segment durations and rebuffering is not expected (maxStarvationDelay > 0)
  3498. const bitrate = currentFragDuration && bufferStarvationDelay >= currentFragDuration * 2 && maxStarvationDelay === 0 ? levelInfo.averageBitrate : levelInfo.maxBitrate;
  3499. const fetchDuration = this.getTimeToLoadFrag(ttfbEstimateSec, adjustedbw, bitrate * avgDuration, levelDetails === undefined);
  3500. const canSwitchWithinTolerance =
  3501. // if adjusted bw is greater than level bitrate AND
  3502. adjustedbw >= bitrate && (
  3503. // no level change, or new level has no error history
  3504. i === lastLoadedFragLevel || levelInfo.loadError === 0 && levelInfo.fragmentError === 0) && (
  3505. // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  3506. // 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 ...
  3507. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
  3508. fetchDuration <= ttfbEstimateSec || !isFiniteNumber(fetchDuration) || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration);
  3509. if (canSwitchWithinTolerance) {
  3510. const forcedAutoLevel = this.forcedAutoLevel;
  3511. if (i !== loadLevel && (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)) {
  3512. if (levelsSkipped.length) {
  3513. 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}`);
  3514. }
  3515. 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}`);
  3516. }
  3517. if (firstSelection) {
  3518. this.firstSelection = i;
  3519. }
  3520. // as we are looping from highest to lowest, this will return the best achievable quality level
  3521. return i;
  3522. }
  3523. }
  3524. // not enough time budget even with quality level 0 ... rebuffering might happen
  3525. return -1;
  3526. }
  3527. set nextAutoLevel(nextLevel) {
  3528. const value = this.deriveNextAutoLevel(nextLevel);
  3529. if (this._nextAutoLevel !== value) {
  3530. this.nextAutoLevelKey = '';
  3531. this._nextAutoLevel = value;
  3532. }
  3533. }
  3534. deriveNextAutoLevel(nextLevel) {
  3535. const {
  3536. maxAutoLevel,
  3537. minAutoLevel
  3538. } = this.hls;
  3539. return Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);
  3540. }
  3541. }
  3542. const BinarySearch = {
  3543. /**
  3544. * Searches for an item in an array which matches a certain condition.
  3545. * This requires the condition to only match one item in the array,
  3546. * and for the array to be ordered.
  3547. *
  3548. * @param list The array to search.
  3549. * @param comparisonFn
  3550. * Called and provided a candidate item as the first argument.
  3551. * Should return:
  3552. * > -1 if the item should be located at a lower index than the provided item.
  3553. * > 1 if the item should be located at a higher index than the provided item.
  3554. * > 0 if the item is the item you're looking for.
  3555. *
  3556. * @returns the object if found, otherwise returns null
  3557. */
  3558. search: function (list, comparisonFn) {
  3559. let minIndex = 0;
  3560. let maxIndex = list.length - 1;
  3561. let currentIndex = null;
  3562. let currentElement = null;
  3563. while (minIndex <= maxIndex) {
  3564. currentIndex = (minIndex + maxIndex) / 2 | 0;
  3565. currentElement = list[currentIndex];
  3566. const comparisonResult = comparisonFn(currentElement);
  3567. if (comparisonResult > 0) {
  3568. minIndex = currentIndex + 1;
  3569. } else if (comparisonResult < 0) {
  3570. maxIndex = currentIndex - 1;
  3571. } else {
  3572. return currentElement;
  3573. }
  3574. }
  3575. return null;
  3576. }
  3577. };
  3578. /**
  3579. * Returns first fragment whose endPdt value exceeds the given PDT, or null.
  3580. * @param fragments - The array of candidate fragments
  3581. * @param PDTValue - The PDT value which must be exceeded
  3582. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  3583. */
  3584. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  3585. if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !isFiniteNumber(PDTValue)) {
  3586. return null;
  3587. }
  3588. // if less than start
  3589. const startPDT = fragments[0].programDateTime;
  3590. if (PDTValue < (startPDT || 0)) {
  3591. return null;
  3592. }
  3593. const endPDT = fragments[fragments.length - 1].endProgramDateTime;
  3594. if (PDTValue >= (endPDT || 0)) {
  3595. return null;
  3596. }
  3597. for (let seg = 0; seg < fragments.length; ++seg) {
  3598. const frag = fragments[seg];
  3599. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  3600. return frag;
  3601. }
  3602. }
  3603. return null;
  3604. }
  3605. /**
  3606. * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
  3607. * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
  3608. * breaking any traps which would cause the same fragment to be continuously selected within a small range.
  3609. * @param fragPrevious - The last frag successfully appended
  3610. * @param fragments - The array of candidate fragments
  3611. * @param bufferEnd - The end of the contiguous buffered range the playhead is currently within
  3612. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  3613. * @returns a matching fragment or null
  3614. */
  3615. function findFragmentByPTS(fragPrevious, fragments, bufferEnd = 0, maxFragLookUpTolerance = 0, nextFragLookupTolerance = 0.005) {
  3616. let fragNext = null;
  3617. if (fragPrevious) {
  3618. fragNext = fragments[1 + fragPrevious.sn - fragments[0].sn] || null;
  3619. // check for buffer-end rounding error
  3620. const bufferEdgeError = fragPrevious.endDTS - bufferEnd;
  3621. if (bufferEdgeError > 0 && bufferEdgeError < 0.0000015) {
  3622. bufferEnd += 0.0000015;
  3623. }
  3624. if (fragNext && fragPrevious.level !== fragNext.level && fragNext.end <= fragPrevious.end) {
  3625. fragNext = fragments[2 + fragPrevious.sn - fragments[0].sn] || null;
  3626. }
  3627. } else if (bufferEnd === 0 && fragments[0].start === 0) {
  3628. fragNext = fragments[0];
  3629. }
  3630. // Prefer the next fragment if it's within tolerance
  3631. if (fragNext && ((!fragPrevious || fragPrevious.level === fragNext.level) && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0 || fragmentWithinFastStartSwitch(fragNext, fragPrevious, Math.min(nextFragLookupTolerance, maxFragLookUpTolerance)))) {
  3632. return fragNext;
  3633. }
  3634. // We might be seeking past the tolerance so find the best match
  3635. const foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  3636. if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {
  3637. return foundFragment;
  3638. }
  3639. // If no match was found return the next fragment after fragPrevious, or null
  3640. return fragNext;
  3641. }
  3642. function fragmentWithinFastStartSwitch(fragNext, fragPrevious, nextFragLookupTolerance) {
  3643. if (fragPrevious && fragPrevious.start === 0 && fragPrevious.level < fragNext.level && (fragPrevious.endPTS || 0) > 0) {
  3644. const firstDuration = fragPrevious.tagList.reduce((duration, tag) => {
  3645. if (tag[0] === 'INF') {
  3646. duration += parseFloat(tag[1]);
  3647. }
  3648. return duration;
  3649. }, nextFragLookupTolerance);
  3650. return fragNext.start <= firstDuration;
  3651. }
  3652. return false;
  3653. }
  3654. /**
  3655. * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
  3656. * @param candidate - The fragment to test
  3657. * @param bufferEnd - The end of the current buffered range the playhead is currently within
  3658. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  3659. * @returns 0 if it matches, 1 if too low, -1 if too high
  3660. */
  3661. function fragmentWithinToleranceTest(bufferEnd = 0, maxFragLookUpTolerance = 0, candidate) {
  3662. // eagerly accept an accurate match (no tolerance)
  3663. if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) {
  3664. return 0;
  3665. }
  3666. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  3667. // this is to cope with situations like
  3668. // bufferEnd = 9.991
  3669. // frag[Ø] : [0,10]
  3670. // frag[1] : [10,20]
  3671. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  3672. // frag start frag start+duration
  3673. // |-----------------------------|
  3674. // <---> <--->
  3675. // ...--------><-----------------------------><---------....
  3676. // previous frag matching fragment next frag
  3677. // return -1 return 0 return 1
  3678. // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  3679. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  3680. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  3681. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  3682. return 1;
  3683. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  3684. // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  3685. return -1;
  3686. }
  3687. return 0;
  3688. }
  3689. /**
  3690. * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
  3691. * This function tests the candidate's program date time values, as represented in Unix time
  3692. * @param candidate - The fragment to test
  3693. * @param pdtBufferEnd - The Unix time representing the end of the current buffered range
  3694. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  3695. * @returns true if contiguous, false otherwise
  3696. */
  3697. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  3698. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;
  3699. // endProgramDateTime can be null, default to zero
  3700. const endProgramDateTime = candidate.endProgramDateTime || 0;
  3701. return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  3702. }
  3703. function findNearestWithCC(details, cc, pos) {
  3704. if (details) {
  3705. if (details.startCC <= cc && details.endCC >= cc) {
  3706. let fragments = details.fragments;
  3707. const {
  3708. fragmentHint
  3709. } = details;
  3710. if (fragmentHint) {
  3711. fragments = fragments.concat(fragmentHint);
  3712. }
  3713. let closest;
  3714. BinarySearch.search(fragments, candidate => {
  3715. if (candidate.cc < cc) {
  3716. return 1;
  3717. }
  3718. if (candidate.cc > cc) {
  3719. return -1;
  3720. }
  3721. closest = candidate;
  3722. if (candidate.end <= pos) {
  3723. return 1;
  3724. }
  3725. if (candidate.start > pos) {
  3726. return -1;
  3727. }
  3728. return 0;
  3729. });
  3730. return closest || null;
  3731. }
  3732. }
  3733. return null;
  3734. }
  3735. function isTimeoutError(error) {
  3736. switch (error.details) {
  3737. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  3738. case ErrorDetails.KEY_LOAD_TIMEOUT:
  3739. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  3740. case ErrorDetails.MANIFEST_LOAD_TIMEOUT:
  3741. return true;
  3742. }
  3743. return false;
  3744. }
  3745. function getRetryConfig(loadPolicy, error) {
  3746. const isTimeout = isTimeoutError(error);
  3747. return loadPolicy.default[`${isTimeout ? 'timeout' : 'error'}Retry`];
  3748. }
  3749. function getRetryDelay(retryConfig, retryCount) {
  3750. // exponential backoff capped to max retry delay
  3751. const backoffFactor = retryConfig.backoff === 'linear' ? 1 : Math.pow(2, retryCount);
  3752. return Math.min(backoffFactor * retryConfig.retryDelayMs, retryConfig.maxRetryDelayMs);
  3753. }
  3754. function getLoaderConfigWithoutReties(loderConfig) {
  3755. return _objectSpread2(_objectSpread2({}, loderConfig), {
  3756. errorRetry: null,
  3757. timeoutRetry: null
  3758. });
  3759. }
  3760. function shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse) {
  3761. if (!retryConfig) {
  3762. return false;
  3763. }
  3764. const httpStatus = loaderResponse == null ? void 0 : loaderResponse.code;
  3765. const retry = retryCount < retryConfig.maxNumRetry && (retryForHttpStatus(httpStatus) || !!isTimeout);
  3766. return retryConfig.shouldRetry ? retryConfig.shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse, retry) : retry;
  3767. }
  3768. function retryForHttpStatus(httpStatus) {
  3769. // Do not retry on status 4xx, status 0 (CORS error), or undefined (decrypt/gap/parse error)
  3770. return httpStatus === 0 && navigator.onLine === false || !!httpStatus && (httpStatus < 400 || httpStatus > 499);
  3771. }
  3772. var NetworkErrorAction = {
  3773. DoNothing: 0,
  3774. SendEndCallback: 1,
  3775. SendAlternateToPenaltyBox: 2,
  3776. RemoveAlternatePermanently: 3,
  3777. InsertDiscontinuity: 4,
  3778. RetryRequest: 5
  3779. };
  3780. var ErrorActionFlags = {
  3781. None: 0,
  3782. MoveAllAlternatesMatchingHost: 1,
  3783. MoveAllAlternatesMatchingHDCP: 2,
  3784. SwitchToSDR: 4
  3785. };
  3786. class ErrorController extends Logger {
  3787. constructor(hls) {
  3788. super('error-controller', hls.logger);
  3789. this.hls = void 0;
  3790. this.playlistError = 0;
  3791. this.penalizedRenditions = {};
  3792. this.hls = hls;
  3793. this.registerListeners();
  3794. }
  3795. registerListeners() {
  3796. const hls = this.hls;
  3797. hls.on(Events.ERROR, this.onError, this);
  3798. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3799. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  3800. }
  3801. unregisterListeners() {
  3802. const hls = this.hls;
  3803. if (!hls) {
  3804. return;
  3805. }
  3806. hls.off(Events.ERROR, this.onError, this);
  3807. hls.off(Events.ERROR, this.onErrorOut, this);
  3808. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3809. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  3810. }
  3811. destroy() {
  3812. this.unregisterListeners();
  3813. // @ts-ignore
  3814. this.hls = null;
  3815. this.penalizedRenditions = {};
  3816. }
  3817. startLoad(startPosition) {}
  3818. stopLoad() {
  3819. this.playlistError = 0;
  3820. }
  3821. getVariantLevelIndex(frag) {
  3822. return (frag == null ? void 0 : frag.type) === PlaylistLevelType.MAIN ? frag.level : this.hls.loadLevel;
  3823. }
  3824. onManifestLoading() {
  3825. this.playlistError = 0;
  3826. this.penalizedRenditions = {};
  3827. }
  3828. onLevelUpdated() {
  3829. this.playlistError = 0;
  3830. }
  3831. onError(event, data) {
  3832. var _data$frag;
  3833. if (data.fatal) {
  3834. return;
  3835. }
  3836. const hls = this.hls;
  3837. const context = data.context;
  3838. switch (data.details) {
  3839. case ErrorDetails.FRAG_LOAD_ERROR:
  3840. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  3841. case ErrorDetails.KEY_LOAD_ERROR:
  3842. case ErrorDetails.KEY_LOAD_TIMEOUT:
  3843. data.errorAction = this.getFragRetryOrSwitchAction(data);
  3844. return;
  3845. case ErrorDetails.FRAG_PARSING_ERROR:
  3846. // ignore empty segment errors marked as gap
  3847. if ((_data$frag = data.frag) != null && _data$frag.gap) {
  3848. data.errorAction = createDoNothingErrorAction();
  3849. return;
  3850. }
  3851. // falls through
  3852. case ErrorDetails.FRAG_GAP:
  3853. case ErrorDetails.FRAG_DECRYPT_ERROR:
  3854. {
  3855. // Switch level if possible, otherwise allow retry count to reach max error retries
  3856. data.errorAction = this.getFragRetryOrSwitchAction(data);
  3857. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  3858. return;
  3859. }
  3860. case ErrorDetails.LEVEL_EMPTY_ERROR:
  3861. case ErrorDetails.LEVEL_PARSING_ERROR:
  3862. {
  3863. var _data$context, _data$context$levelDe;
  3864. // Only retry when empty and live
  3865. const levelIndex = data.parent === PlaylistLevelType.MAIN ? data.level : hls.loadLevel;
  3866. if (data.details === ErrorDetails.LEVEL_EMPTY_ERROR && !!((_data$context = data.context) != null && (_data$context$levelDe = _data$context.levelDetails) != null && _data$context$levelDe.live)) {
  3867. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, levelIndex);
  3868. } else {
  3869. // Escalate to fatal if not retrying or switching
  3870. data.levelRetry = false;
  3871. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  3872. }
  3873. }
  3874. return;
  3875. case ErrorDetails.LEVEL_LOAD_ERROR:
  3876. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  3877. if (typeof (context == null ? void 0 : context.level) === 'number') {
  3878. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, context.level);
  3879. }
  3880. return;
  3881. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  3882. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  3883. case ErrorDetails.SUBTITLE_LOAD_ERROR:
  3884. case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:
  3885. if (context) {
  3886. const level = hls.loadLevelObj;
  3887. if (level && (context.type === PlaylistContextType.AUDIO_TRACK && level.hasAudioGroup(context.groupId) || context.type === PlaylistContextType.SUBTITLE_TRACK && level.hasSubtitleGroup(context.groupId))) {
  3888. // Perform Pathway switch or Redundant failover if possible for fastest recovery
  3889. // otherwise allow playlist retry count to reach max error retries
  3890. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, hls.loadLevel);
  3891. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  3892. data.errorAction.flags = ErrorActionFlags.MoveAllAlternatesMatchingHost;
  3893. return;
  3894. }
  3895. }
  3896. return;
  3897. case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:
  3898. {
  3899. const level = hls.loadLevelObj;
  3900. const restrictedHdcpLevel = level == null ? void 0 : level.attrs['HDCP-LEVEL'];
  3901. if (restrictedHdcpLevel) {
  3902. data.errorAction = {
  3903. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  3904. flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,
  3905. hdcpLevel: restrictedHdcpLevel
  3906. };
  3907. } else {
  3908. this.keySystemError(data);
  3909. }
  3910. }
  3911. return;
  3912. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  3913. case ErrorDetails.REMUX_ALLOC_ERROR:
  3914. case ErrorDetails.BUFFER_APPEND_ERROR:
  3915. // Buffer-controller can set errorAction when append errors can be ignored or resolved locally
  3916. if (!data.errorAction) {
  3917. var _data$level;
  3918. data.errorAction = this.getLevelSwitchAction(data, (_data$level = data.level) != null ? _data$level : hls.loadLevel);
  3919. }
  3920. return;
  3921. case ErrorDetails.INTERNAL_EXCEPTION:
  3922. case ErrorDetails.BUFFER_APPENDING_ERROR:
  3923. case ErrorDetails.BUFFER_FULL_ERROR:
  3924. case ErrorDetails.LEVEL_SWITCH_ERROR:
  3925. case ErrorDetails.BUFFER_STALLED_ERROR:
  3926. case ErrorDetails.BUFFER_SEEK_OVER_HOLE:
  3927. case ErrorDetails.BUFFER_NUDGE_ON_STALL:
  3928. data.errorAction = createDoNothingErrorAction();
  3929. return;
  3930. }
  3931. if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {
  3932. this.keySystemError(data);
  3933. }
  3934. }
  3935. keySystemError(data) {
  3936. const levelIndex = this.getVariantLevelIndex(data.frag);
  3937. // Do not retry level. Escalate to fatal if switching levels fails.
  3938. data.levelRetry = false;
  3939. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  3940. }
  3941. getPlaylistRetryOrSwitchAction(data, levelIndex) {
  3942. const hls = this.hls;
  3943. const retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);
  3944. const retryCount = this.playlistError++;
  3945. const retry = shouldRetry(retryConfig, retryCount, isTimeoutError(data), data.response);
  3946. if (retry) {
  3947. return {
  3948. action: NetworkErrorAction.RetryRequest,
  3949. flags: ErrorActionFlags.None,
  3950. retryConfig,
  3951. retryCount
  3952. };
  3953. }
  3954. const errorAction = this.getLevelSwitchAction(data, levelIndex);
  3955. if (retryConfig) {
  3956. errorAction.retryConfig = retryConfig;
  3957. errorAction.retryCount = retryCount;
  3958. }
  3959. return errorAction;
  3960. }
  3961. getFragRetryOrSwitchAction(data) {
  3962. const hls = this.hls;
  3963. // Share fragment error count accross media options (main, audio, subs)
  3964. // This allows for level based rendition switching when media option assets fail
  3965. const variantLevelIndex = this.getVariantLevelIndex(data.frag);
  3966. const level = hls.levels[variantLevelIndex];
  3967. const {
  3968. fragLoadPolicy,
  3969. keyLoadPolicy
  3970. } = hls.config;
  3971. const retryConfig = getRetryConfig(data.details.startsWith('key') ? keyLoadPolicy : fragLoadPolicy, data);
  3972. const fragmentErrors = hls.levels.reduce((acc, level) => acc + level.fragmentError, 0);
  3973. // Switch levels when out of retried or level index out of bounds
  3974. if (level) {
  3975. if (data.details !== ErrorDetails.FRAG_GAP) {
  3976. level.fragmentError++;
  3977. }
  3978. const retry = shouldRetry(retryConfig, fragmentErrors, isTimeoutError(data), data.response);
  3979. if (retry) {
  3980. return {
  3981. action: NetworkErrorAction.RetryRequest,
  3982. flags: ErrorActionFlags.None,
  3983. retryConfig,
  3984. retryCount: fragmentErrors
  3985. };
  3986. }
  3987. }
  3988. // Reach max retry count, or Missing level reference
  3989. // Switch to valid index
  3990. const errorAction = this.getLevelSwitchAction(data, variantLevelIndex);
  3991. // Add retry details to allow skipping of FRAG_PARSING_ERROR
  3992. if (retryConfig) {
  3993. errorAction.retryConfig = retryConfig;
  3994. errorAction.retryCount = fragmentErrors;
  3995. }
  3996. return errorAction;
  3997. }
  3998. getLevelSwitchAction(data, levelIndex) {
  3999. const hls = this.hls;
  4000. if (levelIndex === null || levelIndex === undefined) {
  4001. levelIndex = hls.loadLevel;
  4002. }
  4003. const level = this.hls.levels[levelIndex];
  4004. if (level) {
  4005. var _data$frag2, _data$context2;
  4006. const errorDetails = data.details;
  4007. level.loadError++;
  4008. if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {
  4009. level.fragmentError++;
  4010. }
  4011. // Search for next level to retry
  4012. let nextLevel = -1;
  4013. const {
  4014. levels,
  4015. loadLevel,
  4016. minAutoLevel,
  4017. maxAutoLevel
  4018. } = hls;
  4019. if (!hls.autoLevelEnabled && !hls.config.preserveManualLevelOnError) {
  4020. hls.loadLevel = -1;
  4021. }
  4022. const fragErrorType = (_data$frag2 = data.frag) == null ? void 0 : _data$frag2.type;
  4023. // Find alternate audio codec if available on audio codec error
  4024. const isAudioCodecError = fragErrorType === PlaylistLevelType.AUDIO && errorDetails === ErrorDetails.FRAG_PARSING_ERROR || data.sourceBufferName === 'audio' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  4025. const findAudioCodecAlternate = isAudioCodecError && levels.some(({
  4026. audioCodec
  4027. }) => level.audioCodec !== audioCodec);
  4028. // Find alternate video codec if available on video codec error
  4029. const isVideoCodecError = data.sourceBufferName === 'video' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  4030. const findVideoCodecAlternate = isVideoCodecError && levels.some(({
  4031. codecSet,
  4032. audioCodec
  4033. }) => level.codecSet !== codecSet && level.audioCodec === audioCodec);
  4034. const {
  4035. type: playlistErrorType,
  4036. groupId: playlistErrorGroupId
  4037. } = (_data$context2 = data.context) != null ? _data$context2 : {};
  4038. for (let i = levels.length; i--;) {
  4039. const candidate = (i + loadLevel) % levels.length;
  4040. if (candidate !== loadLevel && candidate >= minAutoLevel && candidate <= maxAutoLevel && levels[candidate].loadError === 0) {
  4041. var _level$audioGroups, _level$subtitleGroups;
  4042. const levelCandidate = levels[candidate];
  4043. // Skip level switch if GAP tag is found in next level at same position
  4044. if (errorDetails === ErrorDetails.FRAG_GAP && fragErrorType === PlaylistLevelType.MAIN && data.frag) {
  4045. const levelDetails = levels[candidate].details;
  4046. if (levelDetails) {
  4047. const fragCandidate = findFragmentByPTS(data.frag, levelDetails.fragments, data.frag.start);
  4048. if (fragCandidate != null && fragCandidate.gap) {
  4049. continue;
  4050. }
  4051. }
  4052. } else if (playlistErrorType === PlaylistContextType.AUDIO_TRACK && levelCandidate.hasAudioGroup(playlistErrorGroupId) || playlistErrorType === PlaylistContextType.SUBTITLE_TRACK && levelCandidate.hasSubtitleGroup(playlistErrorGroupId)) {
  4053. // For audio/subs playlist errors find another group ID or fallthrough to redundant fail-over
  4054. continue;
  4055. } else if (fragErrorType === PlaylistLevelType.AUDIO && (_level$audioGroups = level.audioGroups) != null && _level$audioGroups.some(groupId => levelCandidate.hasAudioGroup(groupId)) || fragErrorType === PlaylistLevelType.SUBTITLE && (_level$subtitleGroups = level.subtitleGroups) != null && _level$subtitleGroups.some(groupId => levelCandidate.hasSubtitleGroup(groupId)) || findAudioCodecAlternate && level.audioCodec === levelCandidate.audioCodec || !findAudioCodecAlternate && level.audioCodec !== levelCandidate.audioCodec || findVideoCodecAlternate && level.codecSet === levelCandidate.codecSet) {
  4056. // For video/audio/subs frag errors find another group ID or fallthrough to redundant fail-over
  4057. continue;
  4058. }
  4059. nextLevel = candidate;
  4060. break;
  4061. }
  4062. }
  4063. if (nextLevel > -1 && hls.loadLevel !== nextLevel) {
  4064. data.levelRetry = true;
  4065. this.playlistError = 0;
  4066. return {
  4067. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  4068. flags: ErrorActionFlags.None,
  4069. nextAutoLevel: nextLevel
  4070. };
  4071. }
  4072. }
  4073. // No levels to switch / Manual level selection / Level not found
  4074. // Resolve with Pathway switch, Redundant fail-over, or stay on lowest Level
  4075. return {
  4076. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  4077. flags: ErrorActionFlags.MoveAllAlternatesMatchingHost
  4078. };
  4079. }
  4080. onErrorOut(event, data) {
  4081. var _data$errorAction;
  4082. switch ((_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.action) {
  4083. case NetworkErrorAction.DoNothing:
  4084. break;
  4085. case NetworkErrorAction.SendAlternateToPenaltyBox:
  4086. this.sendAlternateToPenaltyBox(data);
  4087. if (!data.errorAction.resolved && data.details !== ErrorDetails.FRAG_GAP) {
  4088. data.fatal = true;
  4089. } else if (/MediaSource readyState: ended/.test(data.error.message)) {
  4090. this.warn(`MediaSource ended after "${data.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`);
  4091. this.hls.recoverMediaError();
  4092. }
  4093. break;
  4094. case NetworkErrorAction.RetryRequest:
  4095. // handled by stream and playlist/level controllers
  4096. break;
  4097. }
  4098. if (data.fatal) {
  4099. this.hls.stopLoad();
  4100. return;
  4101. }
  4102. }
  4103. sendAlternateToPenaltyBox(data) {
  4104. const hls = this.hls;
  4105. const errorAction = data.errorAction;
  4106. if (!errorAction) {
  4107. return;
  4108. }
  4109. const {
  4110. flags,
  4111. hdcpLevel,
  4112. nextAutoLevel
  4113. } = errorAction;
  4114. switch (flags) {
  4115. case ErrorActionFlags.None:
  4116. this.switchLevel(data, nextAutoLevel);
  4117. break;
  4118. case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:
  4119. if (hdcpLevel) {
  4120. hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];
  4121. errorAction.resolved = true;
  4122. }
  4123. this.warn(`Restricting playback to HDCP-LEVEL of "${hls.maxHdcpLevel}" or lower`);
  4124. break;
  4125. }
  4126. // If not resolved by previous actions try to switch to next level
  4127. if (!errorAction.resolved) {
  4128. this.switchLevel(data, nextAutoLevel);
  4129. }
  4130. }
  4131. switchLevel(data, levelIndex) {
  4132. if (levelIndex !== undefined && data.errorAction) {
  4133. this.warn(`switching to level ${levelIndex} after ${data.details}`);
  4134. this.hls.nextAutoLevel = levelIndex;
  4135. data.errorAction.resolved = true;
  4136. // Stream controller is responsible for this but won't switch on false start
  4137. this.hls.nextLoadLevel = this.hls.nextAutoLevel;
  4138. if (data.details === ErrorDetails.BUFFER_ADD_CODEC_ERROR && data.mimeType && data.sourceBufferName !== 'audiovideo') {
  4139. const codec = getCodecsForMimeType(data.mimeType);
  4140. const levels = this.hls.levels;
  4141. for (let i = levels.length; i--;) {
  4142. if (levels[i][`${data.sourceBufferName}Codec`] === codec) {
  4143. this.hls.removeLevel(i);
  4144. }
  4145. }
  4146. }
  4147. }
  4148. }
  4149. }
  4150. function createDoNothingErrorAction(resolved) {
  4151. const errorAction = {
  4152. action: NetworkErrorAction.DoNothing,
  4153. flags: ErrorActionFlags.None
  4154. };
  4155. if (resolved) {
  4156. errorAction.resolved = true;
  4157. }
  4158. return errorAction;
  4159. }
  4160. const DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/;
  4161. const ATTR_LIST_REGEX = /(.+?)=(".*?"|.*?)(?:,|$)/g;
  4162. // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
  4163. class AttrList {
  4164. constructor(attrs, parsed) {
  4165. if (typeof attrs === 'string') {
  4166. attrs = AttrList.parseAttrList(attrs, parsed);
  4167. }
  4168. _extends(this, attrs);
  4169. }
  4170. get clientAttrs() {
  4171. return Object.keys(this).filter(attr => attr.substring(0, 2) === 'X-');
  4172. }
  4173. decimalInteger(attrName) {
  4174. const intValue = parseInt(this[attrName], 10);
  4175. if (intValue > Number.MAX_SAFE_INTEGER) {
  4176. return Infinity;
  4177. }
  4178. return intValue;
  4179. }
  4180. hexadecimalInteger(attrName) {
  4181. if (this[attrName]) {
  4182. let stringValue = (this[attrName] || '0x').slice(2);
  4183. stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
  4184. const value = new Uint8Array(stringValue.length / 2);
  4185. for (let i = 0; i < stringValue.length / 2; i++) {
  4186. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  4187. }
  4188. return value;
  4189. }
  4190. return null;
  4191. }
  4192. hexadecimalIntegerAsNumber(attrName) {
  4193. const intValue = parseInt(this[attrName], 16);
  4194. if (intValue > Number.MAX_SAFE_INTEGER) {
  4195. return Infinity;
  4196. }
  4197. return intValue;
  4198. }
  4199. decimalFloatingPoint(attrName) {
  4200. return parseFloat(this[attrName]);
  4201. }
  4202. optionalFloat(attrName, defaultValue) {
  4203. const value = this[attrName];
  4204. return value ? parseFloat(value) : defaultValue;
  4205. }
  4206. enumeratedString(attrName) {
  4207. return this[attrName];
  4208. }
  4209. enumeratedStringList(attrName, dict) {
  4210. const attrValue = this[attrName];
  4211. return (attrValue ? attrValue.split(/[ ,]+/) : []).reduce((result, identifier) => {
  4212. result[identifier.toLowerCase()] = true;
  4213. return result;
  4214. }, dict);
  4215. }
  4216. bool(attrName) {
  4217. return this[attrName] === 'YES';
  4218. }
  4219. decimalResolution(attrName) {
  4220. const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  4221. if (res === null) {
  4222. return undefined;
  4223. }
  4224. return {
  4225. width: parseInt(res[1], 10),
  4226. height: parseInt(res[2], 10)
  4227. };
  4228. }
  4229. static parseAttrList(input, parsed) {
  4230. let match;
  4231. const attrs = {};
  4232. const quote = '"';
  4233. ATTR_LIST_REGEX.lastIndex = 0;
  4234. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  4235. const name = match[1].trim();
  4236. let value = match[2];
  4237. const quotedString = value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1;
  4238. let hexadecimalSequence = false;
  4239. if (quotedString) {
  4240. value = value.slice(1, -1);
  4241. } else {
  4242. switch (name) {
  4243. case 'IV':
  4244. case 'SCTE35-CMD':
  4245. case 'SCTE35-IN':
  4246. case 'SCTE35-OUT':
  4247. hexadecimalSequence = true;
  4248. }
  4249. }
  4250. if (parsed && (quotedString || hexadecimalSequence)) ; else if (!hexadecimalSequence && !quotedString) {
  4251. switch (name) {
  4252. case 'CLOSED-CAPTIONS':
  4253. if (value === 'NONE') {
  4254. break;
  4255. }
  4256. // falls through
  4257. case 'ALLOWED-CPC':
  4258. case 'CLASS':
  4259. case 'ASSOC-LANGUAGE':
  4260. case 'AUDIO':
  4261. case 'BYTERANGE':
  4262. case 'CHANNELS':
  4263. case 'CHARACTERISTICS':
  4264. case 'CODECS':
  4265. case 'DATA-ID':
  4266. case 'END-DATE':
  4267. case 'GROUP-ID':
  4268. case 'ID':
  4269. case 'IMPORT':
  4270. case 'INSTREAM-ID':
  4271. case 'KEYFORMAT':
  4272. case 'KEYFORMATVERSIONS':
  4273. case 'LANGUAGE':
  4274. case 'NAME':
  4275. case 'PATHWAY-ID':
  4276. case 'QUERYPARAM':
  4277. case 'RECENTLY-REMOVED-DATERANGES':
  4278. case 'SERVER-URI':
  4279. case 'STABLE-RENDITION-ID':
  4280. case 'STABLE-VARIANT-ID':
  4281. case 'START-DATE':
  4282. case 'SUBTITLES':
  4283. case 'SUPPLEMENTAL-CODECS':
  4284. case 'URI':
  4285. case 'VALUE':
  4286. case 'VIDEO':
  4287. case 'X-ASSET-LIST':
  4288. case 'X-ASSET-URI':
  4289. // Since we are not checking tag:attribute combination, just warn rather than ignoring attribute
  4290. logger.warn(`${input}: attribute ${name} is missing quotes`);
  4291. // continue;
  4292. }
  4293. }
  4294. attrs[name] = value;
  4295. }
  4296. return attrs;
  4297. }
  4298. }
  4299. // Avoid exporting const enum so that these values can be inlined
  4300. const CLASS_INTERSTITIAL = 'com.apple.hls.interstitial';
  4301. function isDateRangeCueAttribute(attrName) {
  4302. return attrName !== "ID" && attrName !== "CLASS" && attrName !== "CUE" && attrName !== "START-DATE" && attrName !== "DURATION" && attrName !== "END-DATE" && attrName !== "END-ON-NEXT";
  4303. }
  4304. function isSCTE35Attribute(attrName) {
  4305. return attrName === "SCTE35-OUT" || attrName === "SCTE35-IN" || attrName === "SCTE35-CMD";
  4306. }
  4307. class DateRange {
  4308. constructor(dateRangeAttr, dateRangeWithSameId, tagCount = 0) {
  4309. var _dateRangeWithSameId$;
  4310. this.attr = void 0;
  4311. this.tagAnchor = void 0;
  4312. this.tagOrder = void 0;
  4313. this._startDate = void 0;
  4314. this._endDate = void 0;
  4315. this._dateAtEnd = void 0;
  4316. this._cue = void 0;
  4317. this._badValueForSameId = void 0;
  4318. this.tagAnchor = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagAnchor) || null;
  4319. this.tagOrder = (_dateRangeWithSameId$ = dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagOrder) != null ? _dateRangeWithSameId$ : tagCount;
  4320. if (dateRangeWithSameId) {
  4321. const previousAttr = dateRangeWithSameId.attr;
  4322. for (const key in previousAttr) {
  4323. if (Object.prototype.hasOwnProperty.call(dateRangeAttr, key) && dateRangeAttr[key] !== previousAttr[key]) {
  4324. logger.warn(`DATERANGE tag attribute: "${key}" does not match for tags with ID: "${dateRangeAttr.ID}"`);
  4325. this._badValueForSameId = key;
  4326. break;
  4327. }
  4328. }
  4329. // Merge DateRange tags with the same ID
  4330. dateRangeAttr = _extends(new AttrList({}), previousAttr, dateRangeAttr);
  4331. }
  4332. this.attr = dateRangeAttr;
  4333. if (dateRangeWithSameId) {
  4334. this._startDate = dateRangeWithSameId._startDate;
  4335. this._cue = dateRangeWithSameId._cue;
  4336. this._endDate = dateRangeWithSameId._endDate;
  4337. this._dateAtEnd = dateRangeWithSameId._dateAtEnd;
  4338. } else {
  4339. this._startDate = new Date(dateRangeAttr["START-DATE"]);
  4340. }
  4341. if ("END-DATE" in this.attr) {
  4342. const endDate = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.endDate) || new Date(this.attr["END-DATE"]);
  4343. if (isFiniteNumber(endDate.getTime())) {
  4344. this._endDate = endDate;
  4345. }
  4346. }
  4347. }
  4348. get id() {
  4349. return this.attr.ID;
  4350. }
  4351. get class() {
  4352. return this.attr.CLASS;
  4353. }
  4354. get cue() {
  4355. const _cue = this._cue;
  4356. if (_cue === undefined) {
  4357. return this._cue = this.attr.enumeratedStringList(this.attr.CUE ? 'CUE' : 'X-CUE', {
  4358. pre: false,
  4359. post: false,
  4360. once: false
  4361. });
  4362. }
  4363. return _cue;
  4364. }
  4365. get startTime() {
  4366. const {
  4367. tagAnchor
  4368. } = this;
  4369. // eslint-disable-next-line @typescript-eslint/prefer-optional-chain
  4370. if (tagAnchor === null || tagAnchor.programDateTime === null) {
  4371. logger.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${tagAnchor}`);
  4372. return NaN;
  4373. }
  4374. return tagAnchor.start + (this.startDate.getTime() - tagAnchor.programDateTime) / 1000;
  4375. }
  4376. get startDate() {
  4377. return this._startDate;
  4378. }
  4379. get endDate() {
  4380. const dateAtEnd = this._endDate || this._dateAtEnd;
  4381. if (dateAtEnd) {
  4382. return dateAtEnd;
  4383. }
  4384. const duration = this.duration;
  4385. if (duration !== null) {
  4386. return this._dateAtEnd = new Date(this._startDate.getTime() + duration * 1000);
  4387. }
  4388. return null;
  4389. }
  4390. get duration() {
  4391. if ("DURATION" in this.attr) {
  4392. const duration = this.attr.decimalFloatingPoint("DURATION");
  4393. if (isFiniteNumber(duration)) {
  4394. return duration;
  4395. }
  4396. } else if (this._endDate) {
  4397. return (this._endDate.getTime() - this._startDate.getTime()) / 1000;
  4398. }
  4399. return null;
  4400. }
  4401. get plannedDuration() {
  4402. if ("PLANNED-DURATION" in this.attr) {
  4403. return this.attr.decimalFloatingPoint("PLANNED-DURATION");
  4404. }
  4405. return null;
  4406. }
  4407. get endOnNext() {
  4408. return this.attr.bool("END-ON-NEXT");
  4409. }
  4410. get isInterstitial() {
  4411. return this.class === CLASS_INTERSTITIAL;
  4412. }
  4413. get isValid() {
  4414. 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);
  4415. }
  4416. }
  4417. const DEFAULT_TARGET_DURATION = 10;
  4418. /**
  4419. * Object representing parsed data from an HLS Media Playlist. Found in {@link hls.js#Level.details}.
  4420. */
  4421. class LevelDetails {
  4422. constructor(baseUrl) {
  4423. this.PTSKnown = false;
  4424. this.alignedSliding = false;
  4425. this.averagetargetduration = void 0;
  4426. this.endCC = 0;
  4427. this.endSN = 0;
  4428. this.fragments = void 0;
  4429. this.fragmentHint = void 0;
  4430. this.partList = null;
  4431. this.dateRanges = void 0;
  4432. this.dateRangeTagCount = 0;
  4433. this.live = true;
  4434. this.requestScheduled = -1;
  4435. this.ageHeader = 0;
  4436. this.advancedDateTime = void 0;
  4437. this.updated = true;
  4438. this.advanced = true;
  4439. this.misses = 0;
  4440. this.startCC = 0;
  4441. this.startSN = 0;
  4442. this.startTimeOffset = null;
  4443. this.targetduration = 0;
  4444. this.totalduration = 0;
  4445. this.type = null;
  4446. this.url = void 0;
  4447. this.m3u8 = '';
  4448. this.version = null;
  4449. this.canBlockReload = false;
  4450. this.canSkipUntil = 0;
  4451. this.canSkipDateRanges = false;
  4452. this.skippedSegments = 0;
  4453. this.recentlyRemovedDateranges = void 0;
  4454. this.partHoldBack = 0;
  4455. this.holdBack = 0;
  4456. this.partTarget = 0;
  4457. this.preloadHint = void 0;
  4458. this.renditionReports = void 0;
  4459. this.tuneInGoal = 0;
  4460. this.deltaUpdateFailed = void 0;
  4461. this.driftStartTime = 0;
  4462. this.driftEndTime = 0;
  4463. this.driftStart = 0;
  4464. this.driftEnd = 0;
  4465. this.encryptedFragments = void 0;
  4466. this.playlistParsingError = null;
  4467. this.variableList = null;
  4468. this.hasVariableRefs = false;
  4469. this.appliedTimelineOffset = void 0;
  4470. this.fragments = [];
  4471. this.encryptedFragments = [];
  4472. this.dateRanges = {};
  4473. this.url = baseUrl;
  4474. }
  4475. reloaded(previous) {
  4476. if (!previous) {
  4477. this.advanced = true;
  4478. this.updated = true;
  4479. return;
  4480. }
  4481. const partSnDiff = this.lastPartSn - previous.lastPartSn;
  4482. const partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
  4483. this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff || !this.live;
  4484. this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
  4485. if (this.updated || this.advanced) {
  4486. this.misses = Math.floor(previous.misses * 0.6);
  4487. } else {
  4488. this.misses = previous.misses + 1;
  4489. }
  4490. }
  4491. get hasProgramDateTime() {
  4492. if (this.fragments.length) {
  4493. return isFiniteNumber(this.fragments[this.fragments.length - 1].programDateTime);
  4494. }
  4495. return false;
  4496. }
  4497. get levelTargetDuration() {
  4498. return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
  4499. }
  4500. get drift() {
  4501. const runTime = this.driftEndTime - this.driftStartTime;
  4502. if (runTime > 0) {
  4503. const runDuration = this.driftEnd - this.driftStart;
  4504. return runDuration * 1000 / runTime;
  4505. }
  4506. return 1;
  4507. }
  4508. get edge() {
  4509. return this.partEnd || this.fragmentEnd;
  4510. }
  4511. get partEnd() {
  4512. var _this$partList;
  4513. if ((_this$partList = this.partList) != null && _this$partList.length) {
  4514. return this.partList[this.partList.length - 1].end;
  4515. }
  4516. return this.fragmentEnd;
  4517. }
  4518. get fragmentEnd() {
  4519. var _this$fragments;
  4520. if ((_this$fragments = this.fragments) != null && _this$fragments.length) {
  4521. return this.fragments[this.fragments.length - 1].end;
  4522. }
  4523. return 0;
  4524. }
  4525. get fragmentStart() {
  4526. var _this$fragments2;
  4527. if ((_this$fragments2 = this.fragments) != null && _this$fragments2.length) {
  4528. return this.fragments[0].start;
  4529. }
  4530. return 0;
  4531. }
  4532. get age() {
  4533. if (this.advancedDateTime) {
  4534. return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;
  4535. }
  4536. return 0;
  4537. }
  4538. get lastPartIndex() {
  4539. var _this$partList2;
  4540. if ((_this$partList2 = this.partList) != null && _this$partList2.length) {
  4541. return this.partList[this.partList.length - 1].index;
  4542. }
  4543. return -1;
  4544. }
  4545. get maxPartIndex() {
  4546. const partList = this.partList;
  4547. if (partList) {
  4548. const lastIndex = this.lastPartIndex;
  4549. if (lastIndex !== -1) {
  4550. for (let i = partList.length; i--;) {
  4551. if (partList[i].index > lastIndex) {
  4552. return partList[i].index;
  4553. }
  4554. }
  4555. return lastIndex;
  4556. }
  4557. }
  4558. return 0;
  4559. }
  4560. get lastPartSn() {
  4561. var _this$partList3;
  4562. if ((_this$partList3 = this.partList) != null && _this$partList3.length) {
  4563. return this.partList[this.partList.length - 1].fragment.sn;
  4564. }
  4565. return this.endSN;
  4566. }
  4567. get expired() {
  4568. if (this.live && this.age && this.misses < 3) {
  4569. const playlistWindowDuration = this.partEnd - this.fragmentStart;
  4570. return this.age > Math.max(playlistWindowDuration, this.totalduration) + this.levelTargetDuration;
  4571. }
  4572. return false;
  4573. }
  4574. }
  4575. var DecrypterAesMode = {
  4576. cbc: 0,
  4577. ctr: 1
  4578. };
  4579. function isFullSegmentEncryption(method) {
  4580. return method === 'AES-128' || method === 'AES-256' || method === 'AES-256-CTR';
  4581. }
  4582. function getAesModeFromFullSegmentMethod(method) {
  4583. switch (method) {
  4584. case 'AES-128':
  4585. case 'AES-256':
  4586. return DecrypterAesMode.cbc;
  4587. case 'AES-256-CTR':
  4588. return DecrypterAesMode.ctr;
  4589. default:
  4590. throw new Error(`invalid full segment method ${method}`);
  4591. }
  4592. }
  4593. class LevelKey {
  4594. static clearKeyUriToKeyIdMap() {
  4595. }
  4596. constructor(method, uri, format, formatversions = [1], iv = null, keyId) {
  4597. this.uri = void 0;
  4598. this.method = void 0;
  4599. this.keyFormat = void 0;
  4600. this.keyFormatVersions = void 0;
  4601. this.encrypted = void 0;
  4602. this.isCommonEncryption = void 0;
  4603. this.iv = null;
  4604. this.key = null;
  4605. this.keyId = null;
  4606. this.pssh = null;
  4607. this.method = method;
  4608. this.uri = uri;
  4609. this.keyFormat = format;
  4610. this.keyFormatVersions = formatversions;
  4611. this.iv = iv;
  4612. this.encrypted = method ? method !== 'NONE' : false;
  4613. this.isCommonEncryption = this.encrypted && !isFullSegmentEncryption(method);
  4614. if (keyId != null && keyId.startsWith('0x')) {
  4615. this.keyId = new Uint8Array(hexToArrayBuffer(keyId));
  4616. }
  4617. }
  4618. matches(key) {
  4619. var _key$iv, _this$iv;
  4620. return key.uri === this.uri && key.method === this.method && key.encrypted === this.encrypted && key.keyFormat === this.keyFormat && key.keyFormatVersions.join(',') === this.keyFormatVersions.join(',') && ((_key$iv = key.iv) == null ? void 0 : _key$iv.join(',')) === ((_this$iv = this.iv) == null ? void 0 : _this$iv.join(','));
  4621. }
  4622. isSupported() {
  4623. // If it's Segment encryption or No encryption, just select that key system
  4624. if (this.method) {
  4625. if (isFullSegmentEncryption(this.method) || this.method === 'NONE') {
  4626. return true;
  4627. }
  4628. if (this.keyFormat === 'identity') {
  4629. // Maintain support for clear SAMPLE-AES with MPEG-3 TS
  4630. return this.method === 'SAMPLE-AES';
  4631. }
  4632. }
  4633. return false;
  4634. }
  4635. getDecryptData(sn) {
  4636. if (!this.encrypted || !this.uri) {
  4637. return null;
  4638. }
  4639. if (isFullSegmentEncryption(this.method) && this.uri && !this.iv) {
  4640. if (typeof sn !== 'number') {
  4641. // We are fetching decryption data for a initialization segment
  4642. // If the segment was encrypted with AES-128/256
  4643. // It must have an IV defined. We cannot substitute the Segment Number in.
  4644. logger.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`);
  4645. // Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
  4646. sn = 0;
  4647. }
  4648. const iv = createInitializationVector(sn);
  4649. const decryptdata = new LevelKey(this.method, this.uri, 'identity', this.keyFormatVersions, iv);
  4650. return decryptdata;
  4651. }
  4652. {
  4653. return this;
  4654. }
  4655. }
  4656. }
  4657. function createInitializationVector(segmentNumber) {
  4658. const uint8View = new Uint8Array(16);
  4659. for (let i = 12; i < 16; i++) {
  4660. uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
  4661. }
  4662. return uint8View;
  4663. }
  4664. const 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;
  4665. const MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  4666. const IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m; // Handle empty Media Playlist (first EXTINF not signaled, but TARGETDURATION present)
  4667. const LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,
  4668. // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  4669. /(?!#) *(\S[^\r\n]*)/.source,
  4670. // segment URI, group 3 => the URI (note newline is not eaten)
  4671. /#.*/.source // All other non-segment oriented tags will match with all groups empty
  4672. ].join('|'), 'g');
  4673. const 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('|'));
  4674. class M3U8Parser {
  4675. static findGroup(groups, mediaGroupId) {
  4676. for (let i = 0; i < groups.length; i++) {
  4677. const group = groups[i];
  4678. if (group.id === mediaGroupId) {
  4679. return group;
  4680. }
  4681. }
  4682. }
  4683. static resolve(url, baseUrl) {
  4684. return urlToolkitExports.buildAbsoluteURL(baseUrl, url, {
  4685. alwaysNormalize: true
  4686. });
  4687. }
  4688. static isMediaPlaylist(str) {
  4689. return IS_MEDIA_PLAYLIST.test(str);
  4690. }
  4691. static parseMasterPlaylist(string, baseurl) {
  4692. const hasVariableRefs = false;
  4693. const parsed = {
  4694. contentSteering: null,
  4695. levels: [],
  4696. playlistParsingError: null,
  4697. sessionData: null,
  4698. sessionKeys: null,
  4699. startTimeOffset: null,
  4700. variableList: null,
  4701. hasVariableRefs
  4702. };
  4703. const levelsWithKnownCodecs = [];
  4704. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  4705. let result;
  4706. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  4707. if (result[1]) {
  4708. var _level$unknownCodecs;
  4709. // '#EXT-X-STREAM-INF' is found, parse level tag in group 1
  4710. const attrs = new AttrList(result[1], parsed);
  4711. const uri = result[2];
  4712. const level = {
  4713. attrs,
  4714. bitrate: attrs.decimalInteger('BANDWIDTH') || attrs.decimalInteger('AVERAGE-BANDWIDTH'),
  4715. name: attrs.NAME,
  4716. url: M3U8Parser.resolve(uri, baseurl)
  4717. };
  4718. const resolution = attrs.decimalResolution('RESOLUTION');
  4719. if (resolution) {
  4720. level.width = resolution.width;
  4721. level.height = resolution.height;
  4722. }
  4723. setCodecs(attrs.CODECS, level);
  4724. const supplementalCodecs = attrs['SUPPLEMENTAL-CODECS'];
  4725. if (supplementalCodecs) {
  4726. level.supplemental = {};
  4727. setCodecs(supplementalCodecs, level.supplemental);
  4728. }
  4729. if (!((_level$unknownCodecs = level.unknownCodecs) != null && _level$unknownCodecs.length)) {
  4730. levelsWithKnownCodecs.push(level);
  4731. }
  4732. parsed.levels.push(level);
  4733. } else if (result[3]) {
  4734. const tag = result[3];
  4735. const attributes = result[4];
  4736. switch (tag) {
  4737. case 'SESSION-DATA':
  4738. {
  4739. // #EXT-X-SESSION-DATA
  4740. const sessionAttrs = new AttrList(attributes, parsed);
  4741. const dataId = sessionAttrs['DATA-ID'];
  4742. if (dataId) {
  4743. if (parsed.sessionData === null) {
  4744. parsed.sessionData = {};
  4745. }
  4746. parsed.sessionData[dataId] = sessionAttrs;
  4747. }
  4748. break;
  4749. }
  4750. case 'SESSION-KEY':
  4751. {
  4752. // #EXT-X-SESSION-KEY
  4753. const sessionKey = parseKey(attributes, baseurl, parsed);
  4754. if (sessionKey.encrypted && sessionKey.isSupported()) {
  4755. if (parsed.sessionKeys === null) {
  4756. parsed.sessionKeys = [];
  4757. }
  4758. parsed.sessionKeys.push(sessionKey);
  4759. } else {
  4760. logger.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${attributes}"`);
  4761. }
  4762. break;
  4763. }
  4764. case 'DEFINE':
  4765. {
  4766. break;
  4767. }
  4768. case 'CONTENT-STEERING':
  4769. {
  4770. // #EXT-X-CONTENT-STEERING
  4771. const contentSteeringAttributes = new AttrList(attributes, parsed);
  4772. parsed.contentSteering = {
  4773. uri: M3U8Parser.resolve(contentSteeringAttributes['SERVER-URI'], baseurl),
  4774. pathwayId: contentSteeringAttributes['PATHWAY-ID'] || '.'
  4775. };
  4776. break;
  4777. }
  4778. case 'START':
  4779. {
  4780. // #EXT-X-START
  4781. parsed.startTimeOffset = parseStartTimeOffset(attributes);
  4782. break;
  4783. }
  4784. }
  4785. }
  4786. }
  4787. // Filter out levels with unknown codecs if it does not remove all levels
  4788. const stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < parsed.levels.length;
  4789. parsed.levels = stripUnknownCodecLevels ? levelsWithKnownCodecs : parsed.levels;
  4790. if (parsed.levels.length === 0) {
  4791. parsed.playlistParsingError = new Error('no levels found in manifest');
  4792. }
  4793. return parsed;
  4794. }
  4795. static parseMasterPlaylistMedia(string, baseurl, parsed) {
  4796. let result;
  4797. const results = {};
  4798. const levels = parsed.levels;
  4799. const groupsByType = {
  4800. AUDIO: levels.map(level => ({
  4801. id: level.attrs.AUDIO,
  4802. audioCodec: level.audioCodec
  4803. })),
  4804. SUBTITLES: levels.map(level => ({
  4805. id: level.attrs.SUBTITLES,
  4806. textCodec: level.textCodec
  4807. })),
  4808. 'CLOSED-CAPTIONS': []
  4809. };
  4810. let id = 0;
  4811. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  4812. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  4813. const attrs = new AttrList(result[1], parsed);
  4814. const type = attrs.TYPE;
  4815. if (type) {
  4816. const groups = groupsByType[type];
  4817. const medias = results[type] || [];
  4818. results[type] = medias;
  4819. const lang = attrs.LANGUAGE;
  4820. const assocLang = attrs['ASSOC-LANGUAGE'];
  4821. const channels = attrs.CHANNELS;
  4822. const characteristics = attrs.CHARACTERISTICS;
  4823. const instreamId = attrs['INSTREAM-ID'];
  4824. const media = {
  4825. attrs,
  4826. bitrate: 0,
  4827. id: id++,
  4828. groupId: attrs['GROUP-ID'] || '',
  4829. name: attrs.NAME || lang || '',
  4830. type,
  4831. default: attrs.bool('DEFAULT'),
  4832. autoselect: attrs.bool('AUTOSELECT'),
  4833. forced: attrs.bool('FORCED'),
  4834. lang,
  4835. url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ''
  4836. };
  4837. if (assocLang) {
  4838. media.assocLang = assocLang;
  4839. }
  4840. if (channels) {
  4841. media.channels = channels;
  4842. }
  4843. if (characteristics) {
  4844. media.characteristics = characteristics;
  4845. }
  4846. if (instreamId) {
  4847. media.instreamId = instreamId;
  4848. }
  4849. if (groups != null && groups.length) {
  4850. // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track
  4851. // If we don't find the track signalled, lets use the first audio groups codec we have
  4852. // Acting as a best guess
  4853. const groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
  4854. assignCodec(media, groupCodec, 'audioCodec');
  4855. assignCodec(media, groupCodec, 'textCodec');
  4856. }
  4857. medias.push(media);
  4858. }
  4859. }
  4860. return results;
  4861. }
  4862. static parseLevelPlaylist(string, baseurl, id, type, levelUrlId, multivariantVariableList) {
  4863. var _LEVEL_PLAYLIST_REGEX;
  4864. const base = {
  4865. url: baseurl
  4866. };
  4867. const level = new LevelDetails(baseurl);
  4868. const fragments = level.fragments;
  4869. const programDateTimes = [];
  4870. // The most recent init segment seen (applies to all subsequent segments)
  4871. let currentInitSegment = null;
  4872. let currentSN = 0;
  4873. let currentPart = 0;
  4874. let totalduration = 0;
  4875. let discontinuityCounter = 0;
  4876. let currentBitrate = 0;
  4877. let prevFrag = null;
  4878. let frag = new Fragment(type, base);
  4879. let result;
  4880. let i;
  4881. let levelkeys;
  4882. let firstPdtIndex = -1;
  4883. let createNextFrag = false;
  4884. let nextByteRange = null;
  4885. let serverControlAttrs;
  4886. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  4887. level.m3u8 = string;
  4888. level.hasVariableRefs = false;
  4889. if (((_LEVEL_PLAYLIST_REGEX = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) == null ? void 0 : _LEVEL_PLAYLIST_REGEX[0]) !== '#EXTM3U') {
  4890. level.playlistParsingError = new Error('Missing format identifier #EXTM3U');
  4891. return level;
  4892. }
  4893. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  4894. if (createNextFrag) {
  4895. createNextFrag = false;
  4896. frag = new Fragment(type, base);
  4897. // setup the next fragment for part loading
  4898. frag.playlistOffset = totalduration;
  4899. frag.start = totalduration;
  4900. frag.sn = currentSN;
  4901. frag.cc = discontinuityCounter;
  4902. if (currentBitrate) {
  4903. frag.bitrate = currentBitrate;
  4904. }
  4905. frag.level = id;
  4906. if (currentInitSegment) {
  4907. frag.initSegment = currentInitSegment;
  4908. if (currentInitSegment.rawProgramDateTime) {
  4909. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  4910. currentInitSegment.rawProgramDateTime = null;
  4911. }
  4912. if (nextByteRange) {
  4913. frag.setByteRange(nextByteRange);
  4914. nextByteRange = null;
  4915. }
  4916. }
  4917. }
  4918. const duration = result[1];
  4919. if (duration) {
  4920. // INF
  4921. frag.duration = parseFloat(duration);
  4922. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  4923. const title = (' ' + result[2]).slice(1);
  4924. frag.title = title || null;
  4925. frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
  4926. } else if (result[3]) {
  4927. // url
  4928. if (isFiniteNumber(frag.duration)) {
  4929. frag.playlistOffset = totalduration;
  4930. frag.start = totalduration;
  4931. if (levelkeys) {
  4932. setFragLevelKeys(frag, levelkeys, level);
  4933. }
  4934. frag.sn = currentSN;
  4935. frag.level = id;
  4936. frag.cc = discontinuityCounter;
  4937. fragments.push(frag);
  4938. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  4939. const uri = (' ' + result[3]).slice(1);
  4940. frag.relurl = uri;
  4941. assignProgramDateTime(frag, prevFrag, programDateTimes);
  4942. prevFrag = frag;
  4943. totalduration += frag.duration;
  4944. currentSN++;
  4945. currentPart = 0;
  4946. createNextFrag = true;
  4947. }
  4948. } else {
  4949. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  4950. if (!result) {
  4951. logger.warn('No matches on slow regex match for level playlist!');
  4952. continue;
  4953. }
  4954. for (i = 1; i < result.length; i++) {
  4955. if (result[i] !== undefined) {
  4956. break;
  4957. }
  4958. }
  4959. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  4960. const tag = (' ' + result[i]).slice(1);
  4961. const value1 = (' ' + result[i + 1]).slice(1);
  4962. const value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : null;
  4963. switch (tag) {
  4964. case 'BYTERANGE':
  4965. if (prevFrag) {
  4966. frag.setByteRange(value1, prevFrag);
  4967. } else {
  4968. frag.setByteRange(value1);
  4969. }
  4970. break;
  4971. case 'PROGRAM-DATE-TIME':
  4972. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  4973. frag.rawProgramDateTime = value1;
  4974. frag.tagList.push(['PROGRAM-DATE-TIME', value1]);
  4975. if (firstPdtIndex === -1) {
  4976. firstPdtIndex = fragments.length;
  4977. }
  4978. break;
  4979. case 'PLAYLIST-TYPE':
  4980. if (level.type) {
  4981. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  4982. }
  4983. level.type = value1.toUpperCase();
  4984. break;
  4985. case 'MEDIA-SEQUENCE':
  4986. if (level.startSN !== 0) {
  4987. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  4988. } else if (fragments.length > 0) {
  4989. assignMustAppearBeforeSegmentsError(level, tag, result);
  4990. }
  4991. currentSN = level.startSN = parseInt(value1);
  4992. break;
  4993. case 'SKIP':
  4994. {
  4995. if (level.skippedSegments) {
  4996. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  4997. }
  4998. const skipAttrs = new AttrList(value1, level);
  4999. const skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS');
  5000. if (isFiniteNumber(skippedSegments)) {
  5001. level.skippedSegments += skippedSegments;
  5002. // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`
  5003. for (let _i = skippedSegments; _i--;) {
  5004. fragments.push(null);
  5005. }
  5006. currentSN += skippedSegments;
  5007. }
  5008. const recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES');
  5009. if (recentlyRemovedDateranges) {
  5010. level.recentlyRemovedDateranges = (level.recentlyRemovedDateranges || []).concat(recentlyRemovedDateranges.split('\t'));
  5011. }
  5012. break;
  5013. }
  5014. case 'TARGETDURATION':
  5015. if (level.targetduration !== 0) {
  5016. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  5017. }
  5018. level.targetduration = Math.max(parseInt(value1), 1);
  5019. break;
  5020. case 'VERSION':
  5021. if (level.version !== null) {
  5022. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  5023. }
  5024. level.version = parseInt(value1);
  5025. break;
  5026. case 'INDEPENDENT-SEGMENTS':
  5027. break;
  5028. case 'ENDLIST':
  5029. if (!level.live) {
  5030. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  5031. }
  5032. level.live = false;
  5033. break;
  5034. case '#':
  5035. if (value1 || value2) {
  5036. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  5037. }
  5038. break;
  5039. case 'DISCONTINUITY':
  5040. discontinuityCounter++;
  5041. frag.tagList.push(['DIS']);
  5042. break;
  5043. case 'GAP':
  5044. frag.gap = true;
  5045. frag.tagList.push([tag]);
  5046. break;
  5047. case 'BITRATE':
  5048. frag.tagList.push([tag, value1]);
  5049. currentBitrate = parseInt(value1) * 1000;
  5050. if (isFiniteNumber(currentBitrate)) {
  5051. frag.bitrate = currentBitrate;
  5052. } else {
  5053. currentBitrate = 0;
  5054. }
  5055. break;
  5056. case 'DATERANGE':
  5057. {
  5058. const dateRangeAttr = new AttrList(value1, level);
  5059. const dateRange = new DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID], level.dateRangeTagCount);
  5060. level.dateRangeTagCount++;
  5061. if (dateRange.isValid || level.skippedSegments) {
  5062. level.dateRanges[dateRange.id] = dateRange;
  5063. } else {
  5064. logger.warn(`Ignoring invalid DATERANGE tag: "${value1}"`);
  5065. }
  5066. // Add to fragment tag list for backwards compatibility (< v1.2.0)
  5067. frag.tagList.push(['EXT-X-DATERANGE', value1]);
  5068. break;
  5069. }
  5070. case 'DEFINE':
  5071. {
  5072. break;
  5073. }
  5074. case 'DISCONTINUITY-SEQUENCE':
  5075. if (level.startCC !== 0) {
  5076. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  5077. } else if (fragments.length > 0) {
  5078. assignMustAppearBeforeSegmentsError(level, tag, result);
  5079. }
  5080. level.startCC = discontinuityCounter = parseInt(value1);
  5081. break;
  5082. case 'KEY':
  5083. {
  5084. const levelKey = parseKey(value1, baseurl, level);
  5085. if (levelKey.isSupported()) {
  5086. if (levelKey.method === 'NONE') {
  5087. levelkeys = undefined;
  5088. break;
  5089. }
  5090. if (!levelkeys) {
  5091. levelkeys = {};
  5092. }
  5093. const currentKey = levelkeys[levelKey.keyFormat];
  5094. // Ignore duplicate playlist KEY tags
  5095. if (!(currentKey != null && currentKey.matches(levelKey))) {
  5096. if (currentKey) {
  5097. levelkeys = _extends({}, levelkeys);
  5098. }
  5099. levelkeys[levelKey.keyFormat] = levelKey;
  5100. }
  5101. } else {
  5102. logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${value1}"`);
  5103. }
  5104. break;
  5105. }
  5106. case 'START':
  5107. level.startTimeOffset = parseStartTimeOffset(value1);
  5108. break;
  5109. case 'MAP':
  5110. {
  5111. const mapAttrs = new AttrList(value1, level);
  5112. if (frag.duration) {
  5113. // Initial segment tag is after segment duration tag.
  5114. // #EXTINF: 6.0
  5115. // #EXT-X-MAP:URI="init.mp4
  5116. const init = new Fragment(type, base);
  5117. setInitSegment(init, mapAttrs, id, levelkeys);
  5118. currentInitSegment = init;
  5119. frag.initSegment = currentInitSegment;
  5120. if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) {
  5121. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  5122. }
  5123. } else {
  5124. // Initial segment tag is before segment duration tag
  5125. // Handle case where EXT-X-MAP is declared after EXT-X-BYTERANGE
  5126. const end = frag.byteRangeEndOffset;
  5127. if (end) {
  5128. const start = frag.byteRangeStartOffset;
  5129. nextByteRange = `${end - start}@${start}`;
  5130. } else {
  5131. nextByteRange = null;
  5132. }
  5133. setInitSegment(frag, mapAttrs, id, levelkeys);
  5134. currentInitSegment = frag;
  5135. createNextFrag = true;
  5136. }
  5137. currentInitSegment.cc = discontinuityCounter;
  5138. break;
  5139. }
  5140. case 'SERVER-CONTROL':
  5141. {
  5142. if (serverControlAttrs) {
  5143. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  5144. }
  5145. serverControlAttrs = new AttrList(value1);
  5146. level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');
  5147. level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0);
  5148. level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES');
  5149. level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0);
  5150. level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);
  5151. break;
  5152. }
  5153. case 'PART-INF':
  5154. {
  5155. if (level.partTarget) {
  5156. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  5157. }
  5158. const partInfAttrs = new AttrList(value1);
  5159. level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');
  5160. break;
  5161. }
  5162. case 'PART':
  5163. {
  5164. let partList = level.partList;
  5165. if (!partList) {
  5166. partList = level.partList = [];
  5167. }
  5168. const previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined;
  5169. const index = currentPart++;
  5170. const partAttrs = new AttrList(value1, level);
  5171. const part = new Part(partAttrs, frag, base, index, previousFragmentPart);
  5172. partList.push(part);
  5173. frag.duration += part.duration;
  5174. break;
  5175. }
  5176. case 'PRELOAD-HINT':
  5177. {
  5178. const preloadHintAttrs = new AttrList(value1, level);
  5179. level.preloadHint = preloadHintAttrs;
  5180. break;
  5181. }
  5182. case 'RENDITION-REPORT':
  5183. {
  5184. const renditionReportAttrs = new AttrList(value1, level);
  5185. level.renditionReports = level.renditionReports || [];
  5186. level.renditionReports.push(renditionReportAttrs);
  5187. break;
  5188. }
  5189. default:
  5190. logger.warn(`line parsed but not handled: ${result}`);
  5191. break;
  5192. }
  5193. }
  5194. }
  5195. if (prevFrag && !prevFrag.relurl) {
  5196. fragments.pop();
  5197. totalduration -= prevFrag.duration;
  5198. if (level.partList) {
  5199. level.fragmentHint = prevFrag;
  5200. }
  5201. } else if (level.partList) {
  5202. assignProgramDateTime(frag, prevFrag, programDateTimes);
  5203. frag.cc = discontinuityCounter;
  5204. level.fragmentHint = frag;
  5205. if (levelkeys) {
  5206. setFragLevelKeys(frag, levelkeys, level);
  5207. }
  5208. }
  5209. if (!level.targetduration) {
  5210. level.playlistParsingError = new Error(`#EXT-X-TARGETDURATION is required`);
  5211. }
  5212. const fragmentLength = fragments.length;
  5213. const firstFragment = fragments[0];
  5214. const lastFragment = fragments[fragmentLength - 1];
  5215. totalduration += level.skippedSegments * level.targetduration;
  5216. if (totalduration > 0 && fragmentLength && lastFragment) {
  5217. level.averagetargetduration = totalduration / fragmentLength;
  5218. const lastSn = lastFragment.sn;
  5219. level.endSN = lastSn !== 'initSegment' ? lastSn : 0;
  5220. if (!level.live) {
  5221. lastFragment.endList = true;
  5222. }
  5223. if (firstFragment && level.startCC === undefined) {
  5224. level.startCC = firstFragment.cc;
  5225. }
  5226. /**
  5227. * Backfill any missing PDT values
  5228. * "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
  5229. * one or more Media Segment URIs, the client SHOULD extrapolate
  5230. * backward from that tag (using EXTINF durations and/or media
  5231. * timestamps) to associate dates with those segments."
  5232. * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
  5233. * computed.
  5234. */
  5235. if (firstPdtIndex > 0) {
  5236. backfillProgramDateTimes(fragments, firstPdtIndex);
  5237. if (firstFragment) {
  5238. programDateTimes.unshift(firstFragment);
  5239. }
  5240. }
  5241. } else {
  5242. level.endSN = 0;
  5243. level.startCC = 0;
  5244. }
  5245. if (level.fragmentHint) {
  5246. totalduration += level.fragmentHint.duration;
  5247. }
  5248. level.totalduration = totalduration;
  5249. if (programDateTimes.length && level.dateRangeTagCount && firstFragment) {
  5250. mapDateRanges(programDateTimes, level);
  5251. }
  5252. level.endCC = discontinuityCounter;
  5253. return level;
  5254. }
  5255. }
  5256. function mapDateRanges(programDateTimes, details) {
  5257. // Make sure DateRanges are mapped to a ProgramDateTime tag that applies a date to a segment that overlaps with its start date
  5258. const programDateTimeCount = programDateTimes.length;
  5259. if (!programDateTimeCount) {
  5260. return;
  5261. }
  5262. const lastProgramDateTime = programDateTimes[programDateTimeCount - 1];
  5263. const playlistEnd = details.live ? Infinity : details.totalduration;
  5264. const dateRangeIds = Object.keys(details.dateRanges);
  5265. for (let i = dateRangeIds.length; i--;) {
  5266. const dateRange = details.dateRanges[dateRangeIds[i]];
  5267. const startDateTime = dateRange.startDate.getTime();
  5268. dateRange.tagAnchor = lastProgramDateTime.ref;
  5269. for (let j = programDateTimeCount; j--;) {
  5270. const fragIndex = findFragmentWithStartDate(details, startDateTime, programDateTimes, j, playlistEnd);
  5271. if (fragIndex !== -1) {
  5272. dateRange.tagAnchor = details.fragments[fragIndex].ref;
  5273. break;
  5274. }
  5275. }
  5276. }
  5277. }
  5278. function findFragmentWithStartDate(details, startDateTime, programDateTimes, index, endTime) {
  5279. const pdtFragment = programDateTimes[index];
  5280. if (pdtFragment) {
  5281. // find matching range between PDT tags
  5282. const pdtStart = pdtFragment.programDateTime;
  5283. if (startDateTime >= pdtStart || index === 0) {
  5284. var _programDateTimes;
  5285. const durationBetweenPdt = (((_programDateTimes = programDateTimes[index + 1]) == null ? void 0 : _programDateTimes.start) || endTime) - pdtFragment.start;
  5286. if (startDateTime <= pdtStart + durationBetweenPdt * 1000) {
  5287. // map to fragment with date-time range
  5288. const startIndex = programDateTimes[index].sn - details.startSN;
  5289. const fragments = details.fragments;
  5290. if (fragments.length > programDateTimes.length) {
  5291. const endSegment = programDateTimes[index + 1] || fragments[fragments.length - 1];
  5292. const endIndex = endSegment.sn - details.startSN;
  5293. for (let i = endIndex; i > startIndex; i--) {
  5294. const fragStartDateTime = fragments[i].programDateTime;
  5295. if (startDateTime >= fragStartDateTime && startDateTime < fragStartDateTime + fragments[i].duration * 1000) {
  5296. return i;
  5297. }
  5298. }
  5299. }
  5300. return startIndex;
  5301. }
  5302. }
  5303. }
  5304. return -1;
  5305. }
  5306. function parseKey(keyTagAttributes, baseurl, parsed) {
  5307. var _keyAttrs$METHOD, _keyAttrs$KEYFORMAT;
  5308. // https://tools.ietf.org/html/rfc8216#section-4.3.2.4
  5309. const keyAttrs = new AttrList(keyTagAttributes, parsed);
  5310. const decryptmethod = (_keyAttrs$METHOD = keyAttrs.METHOD) != null ? _keyAttrs$METHOD : '';
  5311. const decrypturi = keyAttrs.URI;
  5312. const decryptiv = keyAttrs.hexadecimalInteger('IV');
  5313. const decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;
  5314. // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
  5315. const decryptkeyformat = (_keyAttrs$KEYFORMAT = keyAttrs.KEYFORMAT) != null ? _keyAttrs$KEYFORMAT : 'identity';
  5316. if (decrypturi && keyAttrs.IV && !decryptiv) {
  5317. logger.error(`Invalid IV: ${keyAttrs.IV}`);
  5318. }
  5319. // If decrypturi is a URI with a scheme, then baseurl will be ignored
  5320. // No uri is allowed when METHOD is NONE
  5321. const resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : '';
  5322. const keyFormatVersions = (decryptkeyformatversions ? decryptkeyformatversions : '1').split('/').map(Number).filter(Number.isFinite);
  5323. return new LevelKey(decryptmethod, resolvedUri, decryptkeyformat, keyFormatVersions, decryptiv, keyAttrs.KEYID);
  5324. }
  5325. function parseStartTimeOffset(startAttributes) {
  5326. const startAttrs = new AttrList(startAttributes);
  5327. const startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
  5328. if (isFiniteNumber(startTimeOffset)) {
  5329. return startTimeOffset;
  5330. }
  5331. return null;
  5332. }
  5333. function setCodecs(codecsAttributeValue, level) {
  5334. let codecs = (codecsAttributeValue || '').split(/[ ,]+/).filter(c => c);
  5335. ['video', 'audio', 'text'].forEach(type => {
  5336. const filtered = codecs.filter(codec => isCodecType(codec, type));
  5337. if (filtered.length) {
  5338. // Comma separated list of all codecs for type
  5339. level[`${type}Codec`] = filtered.map(c => c.split('/')[0]).join(',');
  5340. // Remove known codecs so that only unknownCodecs are left after iterating through each type
  5341. codecs = codecs.filter(codec => filtered.indexOf(codec) === -1);
  5342. }
  5343. });
  5344. level.unknownCodecs = codecs;
  5345. }
  5346. function assignCodec(media, groupItem, codecProperty) {
  5347. const codecValue = groupItem[codecProperty];
  5348. if (codecValue) {
  5349. media[codecProperty] = codecValue;
  5350. }
  5351. }
  5352. function backfillProgramDateTimes(fragments, firstPdtIndex) {
  5353. let fragPrev = fragments[firstPdtIndex];
  5354. for (let i = firstPdtIndex; i--;) {
  5355. const frag = fragments[i];
  5356. // Exit on delta-playlist skipped segments
  5357. if (!frag) {
  5358. return;
  5359. }
  5360. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
  5361. fragPrev = frag;
  5362. }
  5363. }
  5364. function assignProgramDateTime(frag, prevFrag, programDateTimes) {
  5365. if (frag.rawProgramDateTime) {
  5366. programDateTimes.push(frag);
  5367. } else if (prevFrag != null && prevFrag.programDateTime) {
  5368. frag.programDateTime = prevFrag.endProgramDateTime;
  5369. }
  5370. }
  5371. function setInitSegment(frag, mapAttrs, id, levelkeys) {
  5372. frag.relurl = mapAttrs.URI;
  5373. if (mapAttrs.BYTERANGE) {
  5374. frag.setByteRange(mapAttrs.BYTERANGE);
  5375. }
  5376. frag.level = id;
  5377. frag.sn = 'initSegment';
  5378. if (levelkeys) {
  5379. frag.levelkeys = levelkeys;
  5380. }
  5381. frag.initSegment = null;
  5382. }
  5383. function setFragLevelKeys(frag, levelkeys, level) {
  5384. frag.levelkeys = levelkeys;
  5385. const {
  5386. encryptedFragments
  5387. } = level;
  5388. if ((!encryptedFragments.length || encryptedFragments[encryptedFragments.length - 1].levelkeys !== levelkeys) && Object.keys(levelkeys).some(format => levelkeys[format].isCommonEncryption)) {
  5389. encryptedFragments.push(frag);
  5390. }
  5391. }
  5392. function assignMultipleMediaPlaylistTagOccuranceError(level, tag, result) {
  5393. level.playlistParsingError = new Error(`#EXT-X-${tag} must not appear more than once (${result[0]})`);
  5394. }
  5395. function assignMustAppearBeforeSegmentsError(level, tag, result) {
  5396. level.playlistParsingError = new Error(`#EXT-X-${tag} must appear before the first Media Segment (${result[0]})`);
  5397. }
  5398. function updateFromToPTS(fragFrom, fragTo) {
  5399. const fragToPTS = fragTo.startPTS;
  5400. // if we know startPTS[toIdx]
  5401. if (isFiniteNumber(fragToPTS)) {
  5402. // update fragment duration.
  5403. // it helps to fix drifts between playlist reported duration and fragment real duration
  5404. let duration = 0;
  5405. let frag;
  5406. if (fragTo.sn > fragFrom.sn) {
  5407. duration = fragToPTS - fragFrom.start;
  5408. frag = fragFrom;
  5409. } else {
  5410. duration = fragFrom.start - fragToPTS;
  5411. frag = fragTo;
  5412. }
  5413. if (frag.duration !== duration) {
  5414. frag.setDuration(duration);
  5415. }
  5416. // we dont know startPTS[toIdx]
  5417. } else if (fragTo.sn > fragFrom.sn) {
  5418. const contiguous = fragFrom.cc === fragTo.cc;
  5419. // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS
  5420. if (contiguous && fragFrom.minEndPTS) {
  5421. fragTo.setStart(fragFrom.start + (fragFrom.minEndPTS - fragFrom.start));
  5422. } else {
  5423. fragTo.setStart(fragFrom.start + fragFrom.duration);
  5424. }
  5425. } else {
  5426. fragTo.setStart(Math.max(fragFrom.start - fragTo.duration, 0));
  5427. }
  5428. }
  5429. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  5430. const parsedMediaDuration = endPTS - startPTS;
  5431. if (parsedMediaDuration <= 0) {
  5432. logger.warn('Fragment should have a positive duration', frag);
  5433. endPTS = startPTS + frag.duration;
  5434. endDTS = startDTS + frag.duration;
  5435. }
  5436. let maxStartPTS = startPTS;
  5437. let minEndPTS = endPTS;
  5438. const fragStartPts = frag.startPTS;
  5439. const fragEndPts = frag.endPTS;
  5440. if (isFiniteNumber(fragStartPts)) {
  5441. // delta PTS between audio and video
  5442. const deltaPTS = Math.abs(fragStartPts - startPTS);
  5443. if (!isFiniteNumber(frag.deltaPTS)) {
  5444. frag.deltaPTS = deltaPTS;
  5445. } else {
  5446. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  5447. }
  5448. maxStartPTS = Math.max(startPTS, fragStartPts);
  5449. startPTS = Math.min(startPTS, fragStartPts);
  5450. startDTS = Math.min(startDTS, frag.startDTS);
  5451. minEndPTS = Math.min(endPTS, fragEndPts);
  5452. endPTS = Math.max(endPTS, fragEndPts);
  5453. endDTS = Math.max(endDTS, frag.endDTS);
  5454. }
  5455. const drift = startPTS - frag.start;
  5456. if (frag.start !== 0) {
  5457. frag.setStart(startPTS);
  5458. }
  5459. frag.setDuration(endPTS - frag.start);
  5460. frag.startPTS = startPTS;
  5461. frag.maxStartPTS = maxStartPTS;
  5462. frag.startDTS = startDTS;
  5463. frag.endPTS = endPTS;
  5464. frag.minEndPTS = minEndPTS;
  5465. frag.endDTS = endDTS;
  5466. const sn = frag.sn;
  5467. // exit if sn out of range
  5468. if (!details || sn < details.startSN || sn > details.endSN) {
  5469. return 0;
  5470. }
  5471. let i;
  5472. const fragIdx = sn - details.startSN;
  5473. const fragments = details.fragments;
  5474. // update frag reference in fragments array
  5475. // rationale is that fragments array might not contain this frag object.
  5476. // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
  5477. // if we don't update frag, we won't be able to propagate PTS info on the playlist
  5478. // resulting in invalid sliding computation
  5479. fragments[fragIdx] = frag;
  5480. // adjust fragment PTS/duration from seqnum-1 to frag 0
  5481. for (i = fragIdx; i > 0; i--) {
  5482. updateFromToPTS(fragments[i], fragments[i - 1]);
  5483. }
  5484. // adjust fragment PTS/duration from seqnum to last frag
  5485. for (i = fragIdx; i < fragments.length - 1; i++) {
  5486. updateFromToPTS(fragments[i], fragments[i + 1]);
  5487. }
  5488. if (details.fragmentHint) {
  5489. updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
  5490. }
  5491. details.PTSKnown = details.alignedSliding = true;
  5492. return drift;
  5493. }
  5494. function mergeDetails(oldDetails, newDetails) {
  5495. if (oldDetails === newDetails) {
  5496. return;
  5497. }
  5498. // Track the last initSegment processed. Initialize it to the last one on the timeline.
  5499. let currentInitSegment = null;
  5500. const oldFragments = oldDetails.fragments;
  5501. for (let i = oldFragments.length - 1; i >= 0; i--) {
  5502. const oldInit = oldFragments[i].initSegment;
  5503. if (oldInit) {
  5504. currentInitSegment = oldInit;
  5505. break;
  5506. }
  5507. }
  5508. if (oldDetails.fragmentHint) {
  5509. // prevent PTS and duration from being adjusted on the next hint
  5510. delete oldDetails.fragmentHint.endPTS;
  5511. }
  5512. // check if old/new playlists have fragments in common
  5513. // loop through overlapping SN and update startPTS, cc, and duration if any found
  5514. let PTSFrag;
  5515. mapFragmentIntersection(oldDetails, newDetails, (oldFrag, newFrag, newFragIndex, newFragments) => {
  5516. if ((!newDetails.startCC || newDetails.skippedSegments) && newFrag.cc !== oldFrag.cc) {
  5517. const ccOffset = oldFrag.cc - newFrag.cc;
  5518. for (let i = newFragIndex; i < newFragments.length; i++) {
  5519. newFragments[i].cc += ccOffset;
  5520. }
  5521. newDetails.endCC = newFragments[newFragments.length - 1].cc;
  5522. }
  5523. if (isFiniteNumber(oldFrag.startPTS) && isFiniteNumber(oldFrag.endPTS)) {
  5524. newFrag.setStart(newFrag.startPTS = oldFrag.startPTS);
  5525. newFrag.startDTS = oldFrag.startDTS;
  5526. newFrag.maxStartPTS = oldFrag.maxStartPTS;
  5527. newFrag.endPTS = oldFrag.endPTS;
  5528. newFrag.endDTS = oldFrag.endDTS;
  5529. newFrag.minEndPTS = oldFrag.minEndPTS;
  5530. newFrag.setDuration(oldFrag.endPTS - oldFrag.startPTS);
  5531. if (newFrag.duration) {
  5532. PTSFrag = newFrag;
  5533. }
  5534. // PTS is known when any segment has startPTS and endPTS
  5535. newDetails.PTSKnown = newDetails.alignedSliding = true;
  5536. }
  5537. if (oldFrag.hasStreams) {
  5538. newFrag.elementaryStreams = oldFrag.elementaryStreams;
  5539. }
  5540. newFrag.loader = oldFrag.loader;
  5541. if (oldFrag.hasStats) {
  5542. newFrag.stats = oldFrag.stats;
  5543. }
  5544. if (oldFrag.initSegment) {
  5545. newFrag.initSegment = oldFrag.initSegment;
  5546. currentInitSegment = oldFrag.initSegment;
  5547. }
  5548. });
  5549. const newFragments = newDetails.fragments;
  5550. const fragmentsToCheck = newDetails.fragmentHint ? newFragments.concat(newDetails.fragmentHint) : newFragments;
  5551. if (currentInitSegment) {
  5552. fragmentsToCheck.forEach(frag => {
  5553. var _currentInitSegment;
  5554. if (frag && (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) == null ? void 0 : _currentInitSegment.relurl))) {
  5555. frag.initSegment = currentInitSegment;
  5556. }
  5557. });
  5558. }
  5559. if (newDetails.skippedSegments) {
  5560. newDetails.deltaUpdateFailed = newFragments.some(frag => !frag);
  5561. if (newDetails.deltaUpdateFailed) {
  5562. logger.warn('[level-helper] Previous playlist missing segments skipped in delta playlist');
  5563. for (let i = newDetails.skippedSegments; i--;) {
  5564. newFragments.shift();
  5565. }
  5566. newDetails.startSN = newFragments[0].sn;
  5567. } else {
  5568. if (newDetails.canSkipDateRanges) {
  5569. newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails);
  5570. }
  5571. const programDateTimes = oldDetails.fragments.filter(frag => frag.rawProgramDateTime);
  5572. if (oldDetails.hasProgramDateTime && !newDetails.hasProgramDateTime) {
  5573. for (let i = 1; i < fragmentsToCheck.length; i++) {
  5574. if (fragmentsToCheck[i].programDateTime === null) {
  5575. assignProgramDateTime(fragmentsToCheck[i], fragmentsToCheck[i - 1], programDateTimes);
  5576. }
  5577. }
  5578. }
  5579. mapDateRanges(programDateTimes, newDetails);
  5580. }
  5581. newDetails.endCC = newFragments[newFragments.length - 1].cc;
  5582. }
  5583. if (!newDetails.startCC) {
  5584. var _fragPriorToNewStart$;
  5585. const fragPriorToNewStart = getFragmentWithSN(oldDetails, newDetails.startSN - 1);
  5586. newDetails.startCC = (_fragPriorToNewStart$ = fragPriorToNewStart == null ? void 0 : fragPriorToNewStart.cc) != null ? _fragPriorToNewStart$ : newFragments[0].cc;
  5587. }
  5588. // Merge parts
  5589. mapPartIntersection(oldDetails.partList, newDetails.partList, (oldPart, newPart) => {
  5590. newPart.elementaryStreams = oldPart.elementaryStreams;
  5591. newPart.stats = oldPart.stats;
  5592. });
  5593. // if at least one fragment contains PTS info, recompute PTS information for all fragments
  5594. if (PTSFrag) {
  5595. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  5596. } else {
  5597. // ensure that delta is within oldFragments range
  5598. // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
  5599. // in that case we also need to adjust start offset of all fragments
  5600. adjustSliding(oldDetails, newDetails);
  5601. }
  5602. if (newFragments.length) {
  5603. newDetails.totalduration = newDetails.edge - newFragments[0].start;
  5604. }
  5605. newDetails.driftStartTime = oldDetails.driftStartTime;
  5606. newDetails.driftStart = oldDetails.driftStart;
  5607. const advancedDateTime = newDetails.advancedDateTime;
  5608. if (newDetails.advanced && advancedDateTime) {
  5609. const edge = newDetails.edge;
  5610. if (!newDetails.driftStart) {
  5611. newDetails.driftStartTime = advancedDateTime;
  5612. newDetails.driftStart = edge;
  5613. }
  5614. newDetails.driftEndTime = advancedDateTime;
  5615. newDetails.driftEnd = edge;
  5616. } else {
  5617. newDetails.driftEndTime = oldDetails.driftEndTime;
  5618. newDetails.driftEnd = oldDetails.driftEnd;
  5619. newDetails.advancedDateTime = oldDetails.advancedDateTime;
  5620. }
  5621. if (newDetails.requestScheduled === -1) {
  5622. newDetails.requestScheduled = oldDetails.requestScheduled;
  5623. }
  5624. }
  5625. function mergeDateRanges(oldDateRanges, newDetails) {
  5626. const {
  5627. dateRanges: deltaDateRanges,
  5628. recentlyRemovedDateranges
  5629. } = newDetails;
  5630. const dateRanges = _extends({}, oldDateRanges);
  5631. if (recentlyRemovedDateranges) {
  5632. recentlyRemovedDateranges.forEach(id => {
  5633. delete dateRanges[id];
  5634. });
  5635. }
  5636. const mergeIds = Object.keys(dateRanges);
  5637. const mergeCount = mergeIds.length;
  5638. if (mergeCount) {
  5639. Object.keys(deltaDateRanges).forEach(id => {
  5640. const mergedDateRange = dateRanges[id];
  5641. const dateRange = new DateRange(deltaDateRanges[id].attr, mergedDateRange);
  5642. if (dateRange.isValid) {
  5643. dateRanges[id] = dateRange;
  5644. if (!mergedDateRange) {
  5645. dateRange.tagOrder += mergeCount;
  5646. }
  5647. } else {
  5648. logger.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${stringify(deltaDateRanges[id].attr)}"`);
  5649. }
  5650. });
  5651. }
  5652. return dateRanges;
  5653. }
  5654. function mapPartIntersection(oldParts, newParts, intersectionFn) {
  5655. if (oldParts && newParts) {
  5656. let delta = 0;
  5657. for (let i = 0, len = oldParts.length; i <= len; i++) {
  5658. const oldPart = oldParts[i];
  5659. const newPart = newParts[i + delta];
  5660. if (oldPart && newPart && oldPart.index === newPart.index && oldPart.fragment.sn === newPart.fragment.sn) {
  5661. intersectionFn(oldPart, newPart);
  5662. } else {
  5663. delta--;
  5664. }
  5665. }
  5666. }
  5667. }
  5668. function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
  5669. const skippedSegments = newDetails.skippedSegments;
  5670. const start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
  5671. const end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
  5672. const delta = newDetails.startSN - oldDetails.startSN;
  5673. const newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  5674. const oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
  5675. for (let i = start; i <= end; i++) {
  5676. const oldFrag = oldFrags[delta + i];
  5677. let newFrag = newFrags[i];
  5678. if (skippedSegments && !newFrag && oldFrag) {
  5679. // Fill in skipped segments in delta playlist
  5680. newFrag = newDetails.fragments[i] = oldFrag;
  5681. }
  5682. if (oldFrag && newFrag) {
  5683. intersectionFn(oldFrag, newFrag, i, newFrags);
  5684. if (oldFrag.url && oldFrag.url !== newFrag.url) {
  5685. newDetails.playlistParsingError = getSequenceError(`media sequence mismatch ${newFrag.sn}:`, oldDetails, newDetails, oldFrag, newFrag);
  5686. return;
  5687. } else if (oldFrag.cc !== newFrag.cc) {
  5688. newDetails.playlistParsingError = getSequenceError(`discontinuity sequence mismatch (${oldFrag.cc}!=${newFrag.cc})`, oldDetails, newDetails, oldFrag, newFrag);
  5689. return;
  5690. }
  5691. }
  5692. }
  5693. }
  5694. function getSequenceError(message, oldDetails, newDetails, oldFrag, newFrag) {
  5695. return new Error(`${message} ${newFrag.url}
  5696. Playlist starting @${oldDetails.startSN}
  5697. ${oldDetails.m3u8}
  5698. Playlist starting @${newDetails.startSN}
  5699. ${newDetails.m3u8}`);
  5700. }
  5701. function adjustSliding(oldDetails, newDetails, matchingStableVariantOrRendition = true) {
  5702. const delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
  5703. const oldFragments = oldDetails.fragments;
  5704. const advancedOrStable = delta >= 0;
  5705. let sliding = 0;
  5706. if (advancedOrStable && delta < oldFragments.length) {
  5707. sliding = oldFragments[delta].start;
  5708. } else if (advancedOrStable && newDetails.startSN === oldDetails.endSN + 1) {
  5709. sliding = oldDetails.fragmentEnd;
  5710. } else if (advancedOrStable && matchingStableVariantOrRendition) {
  5711. // align with expected position (updated playlist start sequence is past end sequence of last update)
  5712. sliding = oldDetails.fragmentStart + delta * newDetails.levelTargetDuration;
  5713. } else if (!newDetails.skippedSegments && newDetails.fragmentStart === 0) {
  5714. // align new start with old (playlist switch has a sequence with no overlap and should not be used for alignment)
  5715. sliding = oldDetails.fragmentStart;
  5716. } else {
  5717. // new details already has a sliding offset or has skipped segments
  5718. return;
  5719. }
  5720. addSliding(newDetails, sliding);
  5721. }
  5722. function addSliding(details, sliding) {
  5723. if (sliding) {
  5724. const fragments = details.fragments;
  5725. for (let i = details.skippedSegments; i < fragments.length; i++) {
  5726. fragments[i].addStart(sliding);
  5727. }
  5728. if (details.fragmentHint) {
  5729. details.fragmentHint.addStart(sliding);
  5730. }
  5731. }
  5732. }
  5733. function computeReloadInterval(newDetails, distanceToLiveEdgeMs = Infinity) {
  5734. let reloadInterval = 1000 * newDetails.targetduration;
  5735. if (newDetails.updated) {
  5736. // Use last segment duration when shorter than target duration and near live edge
  5737. const fragments = newDetails.fragments;
  5738. const liveEdgeMaxTargetDurations = 4;
  5739. if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) {
  5740. const lastSegmentDuration = fragments[fragments.length - 1].duration * 1000;
  5741. if (lastSegmentDuration < reloadInterval) {
  5742. reloadInterval = lastSegmentDuration;
  5743. }
  5744. }
  5745. } else {
  5746. // estimate = 'miss half average';
  5747. // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
  5748. // changed then it MUST wait for a period of one-half the target
  5749. // duration before retrying.
  5750. reloadInterval /= 2;
  5751. }
  5752. return Math.round(reloadInterval);
  5753. }
  5754. function getFragmentWithSN(details, sn, fragCurrent) {
  5755. if (!details) {
  5756. return null;
  5757. }
  5758. let fragment = details.fragments[sn - details.startSN];
  5759. if (fragment) {
  5760. return fragment;
  5761. }
  5762. fragment = details.fragmentHint;
  5763. if (fragment && fragment.sn === sn) {
  5764. return fragment;
  5765. }
  5766. if (sn < details.startSN && fragCurrent && fragCurrent.sn === sn) {
  5767. return fragCurrent;
  5768. }
  5769. return null;
  5770. }
  5771. function getPartWith(details, sn, partIndex) {
  5772. if (!details) {
  5773. return null;
  5774. }
  5775. return findPart(details.partList, sn, partIndex);
  5776. }
  5777. function findPart(partList, sn, partIndex) {
  5778. if (partList) {
  5779. for (let i = partList.length; i--;) {
  5780. const part = partList[i];
  5781. if (part.index === partIndex && part.fragment.sn === sn) {
  5782. return part;
  5783. }
  5784. }
  5785. }
  5786. return null;
  5787. }
  5788. function reassignFragmentLevelIndexes(levels) {
  5789. levels.forEach((level, index) => {
  5790. var _level$details;
  5791. (_level$details = level.details) == null ? void 0 : _level$details.fragments.forEach(fragment => {
  5792. fragment.level = index;
  5793. if (fragment.initSegment) {
  5794. fragment.initSegment.level = index;
  5795. }
  5796. });
  5797. });
  5798. }
  5799. class BasePlaylistController extends Logger {
  5800. constructor(hls, logPrefix) {
  5801. super(logPrefix, hls.logger);
  5802. this.hls = void 0;
  5803. this.canLoad = false;
  5804. this.timer = -1;
  5805. this.hls = hls;
  5806. }
  5807. destroy() {
  5808. this.clearTimer();
  5809. // @ts-ignore
  5810. this.hls = this.log = this.warn = null;
  5811. }
  5812. clearTimer() {
  5813. if (this.timer !== -1) {
  5814. self.clearTimeout(this.timer);
  5815. this.timer = -1;
  5816. }
  5817. }
  5818. startLoad() {
  5819. this.canLoad = true;
  5820. this.loadPlaylist();
  5821. }
  5822. stopLoad() {
  5823. this.canLoad = false;
  5824. this.clearTimer();
  5825. }
  5826. switchParams(playlistUri, previous, current) {
  5827. const renditionReports = previous == null ? void 0 : previous.renditionReports;
  5828. if (renditionReports) {
  5829. let foundIndex = -1;
  5830. for (let i = 0; i < renditionReports.length; i++) {
  5831. const attr = renditionReports[i];
  5832. let uri;
  5833. try {
  5834. uri = new self.URL(attr.URI, previous.url).href;
  5835. } catch (error) {
  5836. this.warn(`Could not construct new URL for Rendition Report: ${error}`);
  5837. uri = attr.URI || '';
  5838. }
  5839. // Use exact match. Otherwise, the last partial match, if any, will be used
  5840. // (Playlist URI includes a query string that the Rendition Report does not)
  5841. if (uri === playlistUri) {
  5842. foundIndex = i;
  5843. break;
  5844. } else if (uri === playlistUri.substring(0, uri.length)) {
  5845. foundIndex = i;
  5846. }
  5847. }
  5848. if (foundIndex !== -1) {
  5849. const attr = renditionReports[foundIndex];
  5850. const msn = parseInt(attr['LAST-MSN']) || (previous == null ? void 0 : previous.lastPartSn);
  5851. let part = parseInt(attr['LAST-PART']) || (previous == null ? void 0 : previous.lastPartIndex);
  5852. if (this.hls.config.lowLatencyMode) {
  5853. const currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
  5854. if (part >= 0 && currentGoal > previous.partTarget) {
  5855. part += 1;
  5856. }
  5857. }
  5858. const skip = current && getSkipValue(current);
  5859. return new HlsUrlParameters(msn, part >= 0 ? part : undefined, skip);
  5860. }
  5861. }
  5862. }
  5863. loadPlaylist(hlsUrlParameters) {
  5864. // Loading is handled by the subclasses
  5865. this.clearTimer();
  5866. }
  5867. loadingPlaylist(playlist, hlsUrlParameters) {
  5868. // Loading is handled by the subclasses
  5869. this.clearTimer();
  5870. }
  5871. shouldLoadPlaylist(playlist) {
  5872. return this.canLoad && !!playlist && !!playlist.url && (!playlist.details || playlist.details.live);
  5873. }
  5874. getUrlWithDirectives(uri, hlsUrlParameters) {
  5875. if (hlsUrlParameters) {
  5876. try {
  5877. return hlsUrlParameters.addDirectives(uri);
  5878. } catch (error) {
  5879. this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`);
  5880. }
  5881. }
  5882. return uri;
  5883. }
  5884. playlistLoaded(index, data, previousDetails) {
  5885. const {
  5886. details,
  5887. stats
  5888. } = data;
  5889. // Set last updated date-time
  5890. const now = self.performance.now();
  5891. const elapsed = stats.loading.first ? Math.max(0, now - stats.loading.first) : 0;
  5892. details.advancedDateTime = Date.now() - elapsed;
  5893. // shift fragment starts with timelineOffset
  5894. const timelineOffset = this.hls.config.timelineOffset;
  5895. if (timelineOffset !== details.appliedTimelineOffset) {
  5896. const offset = Math.max(timelineOffset || 0, 0);
  5897. details.appliedTimelineOffset = offset;
  5898. details.fragments.forEach(frag => {
  5899. frag.start = frag.playlistOffset + offset;
  5900. });
  5901. }
  5902. // if current playlist is a live playlist, arm a timer to reload it
  5903. if (details.live || previousDetails != null && previousDetails.live) {
  5904. const levelOrTrack = 'levelInfo' in data ? data.levelInfo : data.track;
  5905. details.reloaded(previousDetails);
  5906. // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments
  5907. if (previousDetails && details.fragments.length > 0) {
  5908. mergeDetails(previousDetails, details);
  5909. const error = details.playlistParsingError;
  5910. if (error) {
  5911. this.warn(error);
  5912. const hls = this.hls;
  5913. if (!hls.config.ignorePlaylistParsingErrors) {
  5914. var _details$fragments$;
  5915. const {
  5916. networkDetails
  5917. } = data;
  5918. hls.trigger(Events.ERROR, {
  5919. type: ErrorTypes.NETWORK_ERROR,
  5920. details: ErrorDetails.LEVEL_PARSING_ERROR,
  5921. fatal: false,
  5922. url: details.url,
  5923. error,
  5924. reason: error.message,
  5925. level: data.level || undefined,
  5926. parent: (_details$fragments$ = details.fragments[0]) == null ? void 0 : _details$fragments$.type,
  5927. networkDetails,
  5928. stats
  5929. });
  5930. return;
  5931. }
  5932. details.playlistParsingError = null;
  5933. }
  5934. }
  5935. if (details.requestScheduled === -1) {
  5936. details.requestScheduled = stats.loading.start;
  5937. }
  5938. const bufferInfo = this.hls.mainForwardBufferInfo;
  5939. const position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;
  5940. const distanceToLiveEdgeMs = (details.edge - position) * 1000;
  5941. const reloadInterval = computeReloadInterval(details, distanceToLiveEdgeMs);
  5942. if (details.requestScheduled + reloadInterval < now) {
  5943. details.requestScheduled = now;
  5944. } else {
  5945. details.requestScheduled += reloadInterval;
  5946. }
  5947. this.log(`live playlist ${index} ${details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : details.updated ? 'UPDATED' : 'MISSED'}`);
  5948. if (!this.canLoad || !details.live) {
  5949. return;
  5950. }
  5951. let deliveryDirectives;
  5952. let msn = undefined;
  5953. let part = undefined;
  5954. if (details.canBlockReload && details.endSN && details.advanced) {
  5955. // Load level with LL-HLS delivery directives
  5956. const lowLatencyMode = this.hls.config.lowLatencyMode;
  5957. const lastPartSn = details.lastPartSn;
  5958. const endSn = details.endSN;
  5959. const lastPartIndex = details.lastPartIndex;
  5960. const hasParts = lastPartIndex !== -1;
  5961. const atLastPartOfSegment = lastPartSn === endSn;
  5962. if (hasParts) {
  5963. // When low latency mode is disabled, request the last part of the next segment
  5964. if (atLastPartOfSegment) {
  5965. msn = endSn + 1;
  5966. part = lowLatencyMode ? 0 : lastPartIndex;
  5967. } else {
  5968. msn = lastPartSn;
  5969. part = lowLatencyMode ? lastPartIndex + 1 : details.maxPartIndex;
  5970. }
  5971. } else {
  5972. msn = endSn + 1;
  5973. }
  5974. // Low-Latency CDN Tune-in: "age" header and time since load indicates we're behind by more than one part
  5975. // Update directives to obtain the Playlist that has the estimated additional duration of media
  5976. const lastAdvanced = details.age;
  5977. const cdnAge = lastAdvanced + details.ageHeader;
  5978. let currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
  5979. if (currentGoal > 0) {
  5980. if (cdnAge > details.targetduration * 3) {
  5981. // Omit segment and part directives when the last response was more than 3 target durations ago,
  5982. this.log(`Playlist last advanced ${lastAdvanced.toFixed(2)}s ago. Omitting segment and part directives.`);
  5983. msn = undefined;
  5984. part = undefined;
  5985. } else if (previousDetails != null && previousDetails.tuneInGoal && cdnAge - details.partTarget > previousDetails.tuneInGoal) {
  5986. // If we attempted to get the next or latest playlist update, but currentGoal increased,
  5987. // then we either can't catchup, or the "age" header cannot be trusted.
  5988. this.warn(`CDN Tune-in goal increased from: ${previousDetails.tuneInGoal} to: ${currentGoal} with playlist age: ${details.age}`);
  5989. currentGoal = 0;
  5990. } else {
  5991. const segments = Math.floor(currentGoal / details.targetduration);
  5992. msn += segments;
  5993. if (part !== undefined) {
  5994. const parts = Math.round(currentGoal % details.targetduration / details.partTarget);
  5995. part += parts;
  5996. }
  5997. this.log(`CDN Tune-in age: ${details.ageHeader}s last advanced ${lastAdvanced.toFixed(2)}s goal: ${currentGoal} skip sn ${segments} to part ${part}`);
  5998. }
  5999. details.tuneInGoal = currentGoal;
  6000. }
  6001. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  6002. if (lowLatencyMode || !atLastPartOfSegment) {
  6003. details.requestScheduled = now;
  6004. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  6005. return;
  6006. }
  6007. } else if (details.canBlockReload || details.canSkipUntil) {
  6008. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  6009. }
  6010. if (deliveryDirectives && msn !== undefined && details.canBlockReload) {
  6011. details.requestScheduled = stats.loading.first + Math.max(reloadInterval - elapsed * 2, reloadInterval / 2);
  6012. }
  6013. this.scheduleLoading(levelOrTrack, deliveryDirectives, details);
  6014. } else {
  6015. this.clearTimer();
  6016. }
  6017. }
  6018. scheduleLoading(levelOrTrack, deliveryDirectives, updatedDetails) {
  6019. const details = updatedDetails || levelOrTrack.details;
  6020. if (!details) {
  6021. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  6022. return;
  6023. }
  6024. const now = self.performance.now();
  6025. const requestScheduled = details.requestScheduled;
  6026. if (now >= requestScheduled) {
  6027. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  6028. return;
  6029. }
  6030. const estimatedTimeUntilUpdate = requestScheduled - now;
  6031. this.log(`reload live playlist ${levelOrTrack.name || levelOrTrack.bitrate + 'bps'} in ${Math.round(estimatedTimeUntilUpdate)} ms`);
  6032. this.clearTimer();
  6033. this.timer = self.setTimeout(() => this.loadingPlaylist(levelOrTrack, deliveryDirectives), estimatedTimeUntilUpdate);
  6034. }
  6035. getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
  6036. let skip = getSkipValue(details);
  6037. if (previousDeliveryDirectives != null && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
  6038. msn = previousDeliveryDirectives.msn;
  6039. part = previousDeliveryDirectives.part;
  6040. skip = HlsSkip.No;
  6041. }
  6042. return new HlsUrlParameters(msn, part, skip);
  6043. }
  6044. checkRetry(errorEvent) {
  6045. const errorDetails = errorEvent.details;
  6046. const isTimeout = isTimeoutError(errorEvent);
  6047. const errorAction = errorEvent.errorAction;
  6048. const {
  6049. action,
  6050. retryCount = 0,
  6051. retryConfig
  6052. } = errorAction || {};
  6053. const retry = !!errorAction && !!retryConfig && (action === NetworkErrorAction.RetryRequest || !errorAction.resolved && action === NetworkErrorAction.SendAlternateToPenaltyBox);
  6054. if (retry) {
  6055. var _errorEvent$context;
  6056. if (retryCount >= retryConfig.maxNumRetry) {
  6057. return false;
  6058. }
  6059. if (isTimeout && (_errorEvent$context = errorEvent.context) != null && _errorEvent$context.deliveryDirectives) {
  6060. // The LL-HLS request already timed out so retry immediately
  6061. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" without delivery-directives`);
  6062. this.loadPlaylist();
  6063. } else {
  6064. const delay = getRetryDelay(retryConfig, retryCount);
  6065. // Schedule level/track reload
  6066. this.clearTimer();
  6067. this.timer = self.setTimeout(() => this.loadPlaylist(), delay);
  6068. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" in ${delay}ms`);
  6069. }
  6070. // `levelRetry = true` used to inform other controllers that a retry is happening
  6071. errorEvent.levelRetry = true;
  6072. errorAction.resolved = true;
  6073. }
  6074. return retry;
  6075. }
  6076. }
  6077. var FragmentState = {
  6078. NOT_LOADED: "NOT_LOADED",
  6079. APPENDING: "APPENDING",
  6080. PARTIAL: "PARTIAL",
  6081. OK: "OK"
  6082. };
  6083. class FragmentTracker {
  6084. constructor(hls) {
  6085. this.activePartLists = Object.create(null);
  6086. this.endListFragments = Object.create(null);
  6087. this.fragments = Object.create(null);
  6088. this.timeRanges = Object.create(null);
  6089. this.bufferPadding = 0.2;
  6090. this.hls = void 0;
  6091. this.hasGaps = false;
  6092. this.hls = hls;
  6093. this._registerListeners();
  6094. }
  6095. _registerListeners() {
  6096. const {
  6097. hls
  6098. } = this;
  6099. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  6100. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  6101. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  6102. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  6103. }
  6104. _unregisterListeners() {
  6105. const {
  6106. hls
  6107. } = this;
  6108. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  6109. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  6110. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  6111. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  6112. }
  6113. destroy() {
  6114. this._unregisterListeners();
  6115. // @ts-ignore
  6116. this.fragments =
  6117. // @ts-ignore
  6118. this.activePartLists =
  6119. // @ts-ignore
  6120. this.endListFragments = this.timeRanges = null;
  6121. }
  6122. /**
  6123. * Return a Fragment or Part with an appended range that matches the position and levelType
  6124. * Otherwise, return null
  6125. */
  6126. getAppendedFrag(position, levelType) {
  6127. const activeParts = this.activePartLists[levelType];
  6128. if (activeParts) {
  6129. for (let i = activeParts.length; i--;) {
  6130. const activePart = activeParts[i];
  6131. if (!activePart) {
  6132. break;
  6133. }
  6134. const appendedPTS = activePart.end;
  6135. if (activePart.start <= position && appendedPTS !== null && position <= appendedPTS) {
  6136. return activePart;
  6137. }
  6138. }
  6139. }
  6140. return this.getBufferedFrag(position, levelType);
  6141. }
  6142. /**
  6143. * Return a buffered Fragment that matches the position and levelType.
  6144. * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
  6145. * If not found any Fragment, return null
  6146. */
  6147. getBufferedFrag(position, levelType) {
  6148. return this.getFragAtPos(position, levelType, true);
  6149. }
  6150. getFragAtPos(position, levelType, buffered) {
  6151. const {
  6152. fragments
  6153. } = this;
  6154. const keys = Object.keys(fragments);
  6155. for (let i = keys.length; i--;) {
  6156. const fragmentEntity = fragments[keys[i]];
  6157. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === levelType && (!buffered || fragmentEntity.buffered)) {
  6158. const frag = fragmentEntity.body;
  6159. if (frag.start <= position && position <= frag.end) {
  6160. return frag;
  6161. }
  6162. }
  6163. }
  6164. return null;
  6165. }
  6166. /**
  6167. * Partial fragments effected by coded frame eviction will be removed
  6168. * The browser will unload parts of the buffer to free up memory for new buffer data
  6169. * 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)
  6170. */
  6171. detectEvictedFragments(elementaryStream, timeRange, playlistType, appendedPart, removeAppending) {
  6172. if (this.timeRanges) {
  6173. this.timeRanges[elementaryStream] = timeRange;
  6174. }
  6175. // Check if any flagged fragments have been unloaded
  6176. // excluding anything newer than appendedPartSn
  6177. const appendedPartSn = (appendedPart == null ? void 0 : appendedPart.fragment.sn) || -1;
  6178. Object.keys(this.fragments).forEach(key => {
  6179. const fragmentEntity = this.fragments[key];
  6180. if (!fragmentEntity) {
  6181. return;
  6182. }
  6183. if (appendedPartSn >= fragmentEntity.body.sn) {
  6184. return;
  6185. }
  6186. if (!fragmentEntity.buffered && (!fragmentEntity.loaded || removeAppending)) {
  6187. if (fragmentEntity.body.type === playlistType) {
  6188. this.removeFragment(fragmentEntity.body);
  6189. }
  6190. return;
  6191. }
  6192. const esData = fragmentEntity.range[elementaryStream];
  6193. if (!esData) {
  6194. return;
  6195. }
  6196. if (esData.time.length === 0) {
  6197. this.removeFragment(fragmentEntity.body);
  6198. return;
  6199. }
  6200. esData.time.some(time => {
  6201. const isNotBuffered = !this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
  6202. if (isNotBuffered) {
  6203. // Unregister partial fragment as it needs to load again to be reused
  6204. this.removeFragment(fragmentEntity.body);
  6205. }
  6206. return isNotBuffered;
  6207. });
  6208. });
  6209. }
  6210. /**
  6211. * Checks if the fragment passed in is loaded in the buffer properly
  6212. * Partially loaded fragments will be registered as a partial fragment
  6213. */
  6214. detectPartialFragments(data) {
  6215. const timeRanges = this.timeRanges;
  6216. if (!timeRanges || data.frag.sn === 'initSegment') {
  6217. return;
  6218. }
  6219. const frag = data.frag;
  6220. const fragKey = getFragmentKey(frag);
  6221. const fragmentEntity = this.fragments[fragKey];
  6222. if (!fragmentEntity || fragmentEntity.buffered && frag.gap) {
  6223. return;
  6224. }
  6225. const isFragHint = !frag.relurl;
  6226. Object.keys(timeRanges).forEach(elementaryStream => {
  6227. const streamInfo = frag.elementaryStreams[elementaryStream];
  6228. if (!streamInfo) {
  6229. return;
  6230. }
  6231. const timeRange = timeRanges[elementaryStream];
  6232. const partial = isFragHint || streamInfo.partial === true;
  6233. fragmentEntity.range[elementaryStream] = this.getBufferedTimes(frag, data.part, partial, timeRange);
  6234. });
  6235. fragmentEntity.loaded = null;
  6236. if (Object.keys(fragmentEntity.range).length) {
  6237. fragmentEntity.buffered = true;
  6238. const endList = fragmentEntity.body.endList = frag.endList || fragmentEntity.body.endList;
  6239. if (endList) {
  6240. this.endListFragments[fragmentEntity.body.type] = fragmentEntity;
  6241. }
  6242. if (!isPartial(fragmentEntity)) {
  6243. // Remove older fragment parts from lookup after frag is tracked as buffered
  6244. this.removeParts(frag.sn - 1, frag.type);
  6245. }
  6246. } else {
  6247. // remove fragment if nothing was appended
  6248. this.removeFragment(fragmentEntity.body);
  6249. }
  6250. }
  6251. removeParts(snToKeep, levelType) {
  6252. const activeParts = this.activePartLists[levelType];
  6253. if (!activeParts) {
  6254. return;
  6255. }
  6256. this.activePartLists[levelType] = filterParts(activeParts, part => part.fragment.sn >= snToKeep);
  6257. }
  6258. fragBuffered(frag, force) {
  6259. const fragKey = getFragmentKey(frag);
  6260. let fragmentEntity = this.fragments[fragKey];
  6261. if (!fragmentEntity && force) {
  6262. fragmentEntity = this.fragments[fragKey] = {
  6263. body: frag,
  6264. appendedPTS: null,
  6265. loaded: null,
  6266. buffered: false,
  6267. range: Object.create(null)
  6268. };
  6269. if (frag.gap) {
  6270. this.hasGaps = true;
  6271. }
  6272. }
  6273. if (fragmentEntity) {
  6274. fragmentEntity.loaded = null;
  6275. fragmentEntity.buffered = true;
  6276. }
  6277. }
  6278. getBufferedTimes(fragment, part, partial, timeRange) {
  6279. const buffered = {
  6280. time: [],
  6281. partial
  6282. };
  6283. const startPTS = fragment.start;
  6284. const endPTS = fragment.end;
  6285. const minEndPTS = fragment.minEndPTS || endPTS;
  6286. const maxStartPTS = fragment.maxStartPTS || startPTS;
  6287. for (let i = 0; i < timeRange.length; i++) {
  6288. const startTime = timeRange.start(i) - this.bufferPadding;
  6289. const endTime = timeRange.end(i) + this.bufferPadding;
  6290. if (maxStartPTS >= startTime && minEndPTS <= endTime) {
  6291. // Fragment is entirely contained in buffer
  6292. // No need to check the other timeRange times since it's completely playable
  6293. buffered.time.push({
  6294. startPTS: Math.max(startPTS, timeRange.start(i)),
  6295. endPTS: Math.min(endPTS, timeRange.end(i))
  6296. });
  6297. break;
  6298. } else if (startPTS < endTime && endPTS > startTime) {
  6299. const start = Math.max(startPTS, timeRange.start(i));
  6300. const end = Math.min(endPTS, timeRange.end(i));
  6301. if (end > start) {
  6302. buffered.partial = true;
  6303. // Check for intersection with buffer
  6304. // Get playable sections of the fragment
  6305. buffered.time.push({
  6306. startPTS: start,
  6307. endPTS: end
  6308. });
  6309. }
  6310. } else if (endPTS <= startTime) {
  6311. // No need to check the rest of the timeRange as it is in order
  6312. break;
  6313. }
  6314. }
  6315. return buffered;
  6316. }
  6317. /**
  6318. * Gets the partial fragment for a certain time
  6319. */
  6320. getPartialFragment(time) {
  6321. let bestFragment = null;
  6322. let timePadding;
  6323. let startTime;
  6324. let endTime;
  6325. let bestOverlap = 0;
  6326. const {
  6327. bufferPadding,
  6328. fragments
  6329. } = this;
  6330. Object.keys(fragments).forEach(key => {
  6331. const fragmentEntity = fragments[key];
  6332. if (!fragmentEntity) {
  6333. return;
  6334. }
  6335. if (isPartial(fragmentEntity)) {
  6336. startTime = fragmentEntity.body.start - bufferPadding;
  6337. endTime = fragmentEntity.body.end + bufferPadding;
  6338. if (time >= startTime && time <= endTime) {
  6339. // Use the fragment that has the most padding from start and end time
  6340. timePadding = Math.min(time - startTime, endTime - time);
  6341. if (bestOverlap <= timePadding) {
  6342. bestFragment = fragmentEntity.body;
  6343. bestOverlap = timePadding;
  6344. }
  6345. }
  6346. }
  6347. });
  6348. return bestFragment;
  6349. }
  6350. isEndListAppended(type) {
  6351. const lastFragmentEntity = this.endListFragments[type];
  6352. return lastFragmentEntity !== undefined && (lastFragmentEntity.buffered || isPartial(lastFragmentEntity));
  6353. }
  6354. getState(fragment) {
  6355. const fragKey = getFragmentKey(fragment);
  6356. const fragmentEntity = this.fragments[fragKey];
  6357. if (fragmentEntity) {
  6358. if (!fragmentEntity.buffered) {
  6359. return FragmentState.APPENDING;
  6360. } else if (isPartial(fragmentEntity)) {
  6361. return FragmentState.PARTIAL;
  6362. } else {
  6363. return FragmentState.OK;
  6364. }
  6365. }
  6366. return FragmentState.NOT_LOADED;
  6367. }
  6368. isTimeBuffered(startPTS, endPTS, timeRange) {
  6369. let startTime;
  6370. let endTime;
  6371. for (let i = 0; i < timeRange.length; i++) {
  6372. startTime = timeRange.start(i) - this.bufferPadding;
  6373. endTime = timeRange.end(i) + this.bufferPadding;
  6374. if (startPTS >= startTime && endPTS <= endTime) {
  6375. return true;
  6376. }
  6377. if (endPTS <= startTime) {
  6378. // No need to check the rest of the timeRange as it is in order
  6379. return false;
  6380. }
  6381. }
  6382. return false;
  6383. }
  6384. onManifestLoading() {
  6385. this.removeAllFragments();
  6386. }
  6387. onFragLoaded(event, data) {
  6388. // don't track initsegment (for which sn is not a number)
  6389. // don't track frags used for bitrateTest, they're irrelevant.
  6390. if (data.frag.sn === 'initSegment' || data.frag.bitrateTest) {
  6391. return;
  6392. }
  6393. const frag = data.frag;
  6394. // Fragment entity `loaded` FragLoadedData is null when loading parts
  6395. const loaded = data.part ? null : data;
  6396. const fragKey = getFragmentKey(frag);
  6397. this.fragments[fragKey] = {
  6398. body: frag,
  6399. appendedPTS: null,
  6400. loaded,
  6401. buffered: false,
  6402. range: Object.create(null)
  6403. };
  6404. }
  6405. onBufferAppended(event, data) {
  6406. const {
  6407. frag,
  6408. part,
  6409. timeRanges,
  6410. type
  6411. } = data;
  6412. if (frag.sn === 'initSegment') {
  6413. return;
  6414. }
  6415. const playlistType = frag.type;
  6416. if (part) {
  6417. let activeParts = this.activePartLists[playlistType];
  6418. if (!activeParts) {
  6419. this.activePartLists[playlistType] = activeParts = [];
  6420. }
  6421. activeParts.push(part);
  6422. }
  6423. // Store the latest timeRanges loaded in the buffer
  6424. this.timeRanges = timeRanges;
  6425. const timeRange = timeRanges[type];
  6426. this.detectEvictedFragments(type, timeRange, playlistType, part);
  6427. }
  6428. onFragBuffered(event, data) {
  6429. this.detectPartialFragments(data);
  6430. }
  6431. hasFragment(fragment) {
  6432. const fragKey = getFragmentKey(fragment);
  6433. return !!this.fragments[fragKey];
  6434. }
  6435. hasFragments(type) {
  6436. const {
  6437. fragments
  6438. } = this;
  6439. const keys = Object.keys(fragments);
  6440. if (!type) {
  6441. return keys.length > 0;
  6442. }
  6443. for (let i = keys.length; i--;) {
  6444. const fragmentEntity = fragments[keys[i]];
  6445. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === type) {
  6446. return true;
  6447. }
  6448. }
  6449. return false;
  6450. }
  6451. hasParts(type) {
  6452. var _this$activePartLists;
  6453. return !!((_this$activePartLists = this.activePartLists[type]) != null && _this$activePartLists.length);
  6454. }
  6455. removeFragmentsInRange(start, end, playlistType, withGapOnly, unbufferedOnly) {
  6456. if (withGapOnly && !this.hasGaps) {
  6457. return;
  6458. }
  6459. Object.keys(this.fragments).forEach(key => {
  6460. const fragmentEntity = this.fragments[key];
  6461. if (!fragmentEntity) {
  6462. return;
  6463. }
  6464. const frag = fragmentEntity.body;
  6465. if (frag.type !== playlistType || withGapOnly && !frag.gap) {
  6466. return;
  6467. }
  6468. if (frag.start < end && frag.end > start && (fragmentEntity.buffered || unbufferedOnly)) {
  6469. this.removeFragment(frag);
  6470. }
  6471. });
  6472. }
  6473. removeFragment(fragment) {
  6474. const fragKey = getFragmentKey(fragment);
  6475. fragment.clearElementaryStreamInfo();
  6476. const activeParts = this.activePartLists[fragment.type];
  6477. if (activeParts) {
  6478. const snToRemove = fragment.sn;
  6479. this.activePartLists[fragment.type] = filterParts(activeParts, part => part.fragment.sn !== snToRemove);
  6480. }
  6481. delete this.fragments[fragKey];
  6482. if (fragment.endList) {
  6483. delete this.endListFragments[fragment.type];
  6484. }
  6485. }
  6486. removeAllFragments() {
  6487. var _this$hls, _this$hls$latestLevel;
  6488. this.fragments = Object.create(null);
  6489. this.endListFragments = Object.create(null);
  6490. this.activePartLists = Object.create(null);
  6491. this.hasGaps = false;
  6492. const partlist = (_this$hls = this.hls) == null ? void 0 : (_this$hls$latestLevel = _this$hls.latestLevelDetails) == null ? void 0 : _this$hls$latestLevel.partList;
  6493. if (partlist) {
  6494. partlist.forEach(part => part.clearElementaryStreamInfo());
  6495. }
  6496. }
  6497. }
  6498. function isPartial(fragmentEntity) {
  6499. var _fragmentEntity$range, _fragmentEntity$range2, _fragmentEntity$range3;
  6500. return fragmentEntity.buffered && (fragmentEntity.body.gap || ((_fragmentEntity$range = fragmentEntity.range.video) == null ? void 0 : _fragmentEntity$range.partial) || ((_fragmentEntity$range2 = fragmentEntity.range.audio) == null ? void 0 : _fragmentEntity$range2.partial) || ((_fragmentEntity$range3 = fragmentEntity.range.audiovideo) == null ? void 0 : _fragmentEntity$range3.partial));
  6501. }
  6502. function getFragmentKey(fragment) {
  6503. return `${fragment.type}_${fragment.level}_${fragment.sn}`;
  6504. }
  6505. function filterParts(partList, predicate) {
  6506. return partList.filter(part => {
  6507. const keep = predicate(part);
  6508. if (!keep) {
  6509. part.clearElementaryStreamInfo();
  6510. }
  6511. return keep;
  6512. });
  6513. }
  6514. class AESCrypto {
  6515. constructor(subtle, iv, aesMode) {
  6516. this.subtle = void 0;
  6517. this.aesIV = void 0;
  6518. this.aesMode = void 0;
  6519. this.subtle = subtle;
  6520. this.aesIV = iv;
  6521. this.aesMode = aesMode;
  6522. }
  6523. decrypt(data, key) {
  6524. switch (this.aesMode) {
  6525. case DecrypterAesMode.cbc:
  6526. return this.subtle.decrypt({
  6527. name: 'AES-CBC',
  6528. iv: this.aesIV
  6529. }, key, data);
  6530. case DecrypterAesMode.ctr:
  6531. return this.subtle.decrypt({
  6532. name: 'AES-CTR',
  6533. counter: this.aesIV,
  6534. length: 64
  6535. },
  6536. //64 : NIST SP800-38A standard suggests that the counter should occupy half of the counter block
  6537. key, data);
  6538. default:
  6539. throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`);
  6540. }
  6541. }
  6542. }
  6543. // PKCS7
  6544. function removePadding(array) {
  6545. const outputBytes = array.byteLength;
  6546. const paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
  6547. if (paddingBytes) {
  6548. return array.slice(0, outputBytes - paddingBytes);
  6549. }
  6550. return array;
  6551. }
  6552. class AESDecryptor {
  6553. constructor() {
  6554. this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  6555. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  6556. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  6557. this.sBox = new Uint32Array(256);
  6558. this.invSBox = new Uint32Array(256);
  6559. this.key = new Uint32Array(0);
  6560. this.ksRows = 0;
  6561. this.keySize = 0;
  6562. this.keySchedule = void 0;
  6563. this.invKeySchedule = void 0;
  6564. this.initTable();
  6565. }
  6566. // Using view.getUint32() also swaps the byte order.
  6567. uint8ArrayToUint32Array_(arrayBuffer) {
  6568. const view = new DataView(arrayBuffer);
  6569. const newArray = new Uint32Array(4);
  6570. for (let i = 0; i < 4; i++) {
  6571. newArray[i] = view.getUint32(i * 4);
  6572. }
  6573. return newArray;
  6574. }
  6575. initTable() {
  6576. const sBox = this.sBox;
  6577. const invSBox = this.invSBox;
  6578. const subMix = this.subMix;
  6579. const subMix0 = subMix[0];
  6580. const subMix1 = subMix[1];
  6581. const subMix2 = subMix[2];
  6582. const subMix3 = subMix[3];
  6583. const invSubMix = this.invSubMix;
  6584. const invSubMix0 = invSubMix[0];
  6585. const invSubMix1 = invSubMix[1];
  6586. const invSubMix2 = invSubMix[2];
  6587. const invSubMix3 = invSubMix[3];
  6588. const d = new Uint32Array(256);
  6589. let x = 0;
  6590. let xi = 0;
  6591. let i = 0;
  6592. for (i = 0; i < 256; i++) {
  6593. if (i < 128) {
  6594. d[i] = i << 1;
  6595. } else {
  6596. d[i] = i << 1 ^ 0x11b;
  6597. }
  6598. }
  6599. for (i = 0; i < 256; i++) {
  6600. let sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  6601. sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
  6602. sBox[x] = sx;
  6603. invSBox[sx] = x;
  6604. // Compute multiplication
  6605. const x2 = d[x];
  6606. const x4 = d[x2];
  6607. const x8 = d[x4];
  6608. // Compute sub/invSub bytes, mix columns tables
  6609. let t = d[sx] * 0x101 ^ sx * 0x1010100;
  6610. subMix0[x] = t << 24 | t >>> 8;
  6611. subMix1[x] = t << 16 | t >>> 16;
  6612. subMix2[x] = t << 8 | t >>> 24;
  6613. subMix3[x] = t;
  6614. // Compute inv sub bytes, inv mix columns tables
  6615. t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  6616. invSubMix0[sx] = t << 24 | t >>> 8;
  6617. invSubMix1[sx] = t << 16 | t >>> 16;
  6618. invSubMix2[sx] = t << 8 | t >>> 24;
  6619. invSubMix3[sx] = t;
  6620. // Compute next counter
  6621. if (!x) {
  6622. x = xi = 1;
  6623. } else {
  6624. x = x2 ^ d[d[d[x8 ^ x2]]];
  6625. xi ^= d[d[xi]];
  6626. }
  6627. }
  6628. }
  6629. expandKey(keyBuffer) {
  6630. // convert keyBuffer to Uint32Array
  6631. const key = this.uint8ArrayToUint32Array_(keyBuffer);
  6632. let sameKey = true;
  6633. let offset = 0;
  6634. while (offset < key.length && sameKey) {
  6635. sameKey = key[offset] === this.key[offset];
  6636. offset++;
  6637. }
  6638. if (sameKey) {
  6639. return;
  6640. }
  6641. this.key = key;
  6642. const keySize = this.keySize = key.length;
  6643. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  6644. throw new Error('Invalid aes key size=' + keySize);
  6645. }
  6646. const ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  6647. let ksRow;
  6648. let invKsRow;
  6649. const keySchedule = this.keySchedule = new Uint32Array(ksRows);
  6650. const invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  6651. const sbox = this.sBox;
  6652. const rcon = this.rcon;
  6653. const invSubMix = this.invSubMix;
  6654. const invSubMix0 = invSubMix[0];
  6655. const invSubMix1 = invSubMix[1];
  6656. const invSubMix2 = invSubMix[2];
  6657. const invSubMix3 = invSubMix[3];
  6658. let prev;
  6659. let t;
  6660. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  6661. if (ksRow < keySize) {
  6662. prev = keySchedule[ksRow] = key[ksRow];
  6663. continue;
  6664. }
  6665. t = prev;
  6666. if (ksRow % keySize === 0) {
  6667. // Rot word
  6668. t = t << 8 | t >>> 24;
  6669. // Sub word
  6670. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  6671. // Mix Rcon
  6672. t ^= rcon[ksRow / keySize | 0] << 24;
  6673. } else if (keySize > 6 && ksRow % keySize === 4) {
  6674. // Sub word
  6675. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  6676. }
  6677. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  6678. }
  6679. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  6680. ksRow = ksRows - invKsRow;
  6681. if (invKsRow & 3) {
  6682. t = keySchedule[ksRow];
  6683. } else {
  6684. t = keySchedule[ksRow - 4];
  6685. }
  6686. if (invKsRow < 4 || ksRow <= 4) {
  6687. invKeySchedule[invKsRow] = t;
  6688. } else {
  6689. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
  6690. }
  6691. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  6692. }
  6693. }
  6694. // Adding this as a method greatly improves performance.
  6695. networkToHostOrderSwap(word) {
  6696. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  6697. }
  6698. decrypt(inputArrayBuffer, offset, aesIV) {
  6699. const nRounds = this.keySize + 6;
  6700. const invKeySchedule = this.invKeySchedule;
  6701. const invSBOX = this.invSBox;
  6702. const invSubMix = this.invSubMix;
  6703. const invSubMix0 = invSubMix[0];
  6704. const invSubMix1 = invSubMix[1];
  6705. const invSubMix2 = invSubMix[2];
  6706. const invSubMix3 = invSubMix[3];
  6707. const initVector = this.uint8ArrayToUint32Array_(aesIV);
  6708. let initVector0 = initVector[0];
  6709. let initVector1 = initVector[1];
  6710. let initVector2 = initVector[2];
  6711. let initVector3 = initVector[3];
  6712. const inputInt32 = new Int32Array(inputArrayBuffer);
  6713. const outputInt32 = new Int32Array(inputInt32.length);
  6714. let t0, t1, t2, t3;
  6715. let s0, s1, s2, s3;
  6716. let inputWords0, inputWords1, inputWords2, inputWords3;
  6717. let ksRow, i;
  6718. const swapWord = this.networkToHostOrderSwap;
  6719. while (offset < inputInt32.length) {
  6720. inputWords0 = swapWord(inputInt32[offset]);
  6721. inputWords1 = swapWord(inputInt32[offset + 1]);
  6722. inputWords2 = swapWord(inputInt32[offset + 2]);
  6723. inputWords3 = swapWord(inputInt32[offset + 3]);
  6724. s0 = inputWords0 ^ invKeySchedule[0];
  6725. s1 = inputWords3 ^ invKeySchedule[1];
  6726. s2 = inputWords2 ^ invKeySchedule[2];
  6727. s3 = inputWords1 ^ invKeySchedule[3];
  6728. ksRow = 4;
  6729. // Iterate through the rounds of decryption
  6730. for (i = 1; i < nRounds; i++) {
  6731. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
  6732. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  6733. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  6734. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  6735. // Update state
  6736. s0 = t0;
  6737. s1 = t1;
  6738. s2 = t2;
  6739. s3 = t3;
  6740. ksRow = ksRow + 4;
  6741. }
  6742. // Shift rows, sub bytes, add round key
  6743. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
  6744. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  6745. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  6746. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  6747. // Write
  6748. outputInt32[offset] = swapWord(t0 ^ initVector0);
  6749. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  6750. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  6751. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  6752. // reset initVector to last 4 unsigned int
  6753. initVector0 = inputWords0;
  6754. initVector1 = inputWords1;
  6755. initVector2 = inputWords2;
  6756. initVector3 = inputWords3;
  6757. offset = offset + 4;
  6758. }
  6759. return outputInt32.buffer;
  6760. }
  6761. }
  6762. class FastAESKey {
  6763. constructor(subtle, key, aesMode) {
  6764. this.subtle = void 0;
  6765. this.key = void 0;
  6766. this.aesMode = void 0;
  6767. this.subtle = subtle;
  6768. this.key = key;
  6769. this.aesMode = aesMode;
  6770. }
  6771. expandKey() {
  6772. const subtleAlgoName = getSubtleAlgoName(this.aesMode);
  6773. return this.subtle.importKey('raw', this.key, {
  6774. name: subtleAlgoName
  6775. }, false, ['encrypt', 'decrypt']);
  6776. }
  6777. }
  6778. function getSubtleAlgoName(aesMode) {
  6779. switch (aesMode) {
  6780. case DecrypterAesMode.cbc:
  6781. return 'AES-CBC';
  6782. case DecrypterAesMode.ctr:
  6783. return 'AES-CTR';
  6784. default:
  6785. throw new Error(`[FastAESKey] invalid aes mode ${aesMode}`);
  6786. }
  6787. }
  6788. const CHUNK_SIZE = 16; // 16 bytes, 128 bits
  6789. class Decrypter {
  6790. constructor(config, {
  6791. removePKCS7Padding = true
  6792. } = {}) {
  6793. this.logEnabled = true;
  6794. this.removePKCS7Padding = void 0;
  6795. this.subtle = null;
  6796. this.softwareDecrypter = null;
  6797. this.key = null;
  6798. this.fastAesKey = null;
  6799. this.remainderData = null;
  6800. this.currentIV = null;
  6801. this.currentResult = null;
  6802. this.useSoftware = void 0;
  6803. this.enableSoftwareAES = void 0;
  6804. this.enableSoftwareAES = config.enableSoftwareAES;
  6805. this.removePKCS7Padding = removePKCS7Padding;
  6806. // built in decryptor expects PKCS7 padding
  6807. if (removePKCS7Padding) {
  6808. try {
  6809. const browserCrypto = self.crypto;
  6810. if (browserCrypto) {
  6811. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  6812. }
  6813. } catch (e) {
  6814. /* no-op */
  6815. }
  6816. }
  6817. this.useSoftware = !this.subtle;
  6818. }
  6819. destroy() {
  6820. this.subtle = null;
  6821. this.softwareDecrypter = null;
  6822. this.key = null;
  6823. this.fastAesKey = null;
  6824. this.remainderData = null;
  6825. this.currentIV = null;
  6826. this.currentResult = null;
  6827. }
  6828. isSync() {
  6829. return this.useSoftware;
  6830. }
  6831. flush() {
  6832. const {
  6833. currentResult,
  6834. remainderData
  6835. } = this;
  6836. if (!currentResult || remainderData) {
  6837. this.reset();
  6838. return null;
  6839. }
  6840. const data = new Uint8Array(currentResult);
  6841. this.reset();
  6842. if (this.removePKCS7Padding) {
  6843. return removePadding(data);
  6844. }
  6845. return data;
  6846. }
  6847. reset() {
  6848. this.currentResult = null;
  6849. this.currentIV = null;
  6850. this.remainderData = null;
  6851. if (this.softwareDecrypter) {
  6852. this.softwareDecrypter = null;
  6853. }
  6854. }
  6855. decrypt(data, key, iv, aesMode) {
  6856. if (this.useSoftware) {
  6857. return new Promise((resolve, reject) => {
  6858. const dataView = ArrayBuffer.isView(data) ? data : new Uint8Array(data);
  6859. this.softwareDecrypt(dataView, key, iv, aesMode);
  6860. const decryptResult = this.flush();
  6861. if (decryptResult) {
  6862. resolve(decryptResult.buffer);
  6863. } else {
  6864. reject(new Error('[softwareDecrypt] Failed to decrypt data'));
  6865. }
  6866. });
  6867. }
  6868. return this.webCryptoDecrypt(new Uint8Array(data), key, iv, aesMode);
  6869. }
  6870. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  6871. // data is handled in the flush() call
  6872. softwareDecrypt(data, key, iv, aesMode) {
  6873. const {
  6874. currentIV,
  6875. currentResult,
  6876. remainderData
  6877. } = this;
  6878. if (aesMode !== DecrypterAesMode.cbc || key.byteLength !== 16) {
  6879. logger.warn('SoftwareDecrypt: can only handle AES-128-CBC');
  6880. return null;
  6881. }
  6882. this.logOnce('JS AES decrypt');
  6883. // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call
  6884. // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached
  6885. // the end on flush(), but by that time we have already received all bytes for the segment.
  6886. // Progressive decryption does not work with WebCrypto
  6887. if (remainderData) {
  6888. data = appendUint8Array(remainderData, data);
  6889. this.remainderData = null;
  6890. }
  6891. // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)
  6892. const currentChunk = this.getValidChunk(data);
  6893. if (!currentChunk.length) {
  6894. return null;
  6895. }
  6896. if (currentIV) {
  6897. iv = currentIV;
  6898. }
  6899. let softwareDecrypter = this.softwareDecrypter;
  6900. if (!softwareDecrypter) {
  6901. softwareDecrypter = this.softwareDecrypter = new AESDecryptor();
  6902. }
  6903. softwareDecrypter.expandKey(key);
  6904. const result = currentResult;
  6905. this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
  6906. this.currentIV = currentChunk.slice(-16).buffer;
  6907. if (!result) {
  6908. return null;
  6909. }
  6910. return result;
  6911. }
  6912. webCryptoDecrypt(data, key, iv, aesMode) {
  6913. if (this.key !== key || !this.fastAesKey) {
  6914. if (!this.subtle) {
  6915. return Promise.resolve(this.onWebCryptoError(data, key, iv, aesMode));
  6916. }
  6917. this.key = key;
  6918. this.fastAesKey = new FastAESKey(this.subtle, key, aesMode);
  6919. }
  6920. return this.fastAesKey.expandKey().then(aesKey => {
  6921. // decrypt using web crypto
  6922. if (!this.subtle) {
  6923. return Promise.reject(new Error('web crypto not initialized'));
  6924. }
  6925. this.logOnce('WebCrypto AES decrypt');
  6926. const crypto = new AESCrypto(this.subtle, new Uint8Array(iv), aesMode);
  6927. return crypto.decrypt(data.buffer, aesKey);
  6928. }).catch(err => {
  6929. logger.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${err.name}: ${err.message}`);
  6930. return this.onWebCryptoError(data, key, iv, aesMode);
  6931. });
  6932. }
  6933. onWebCryptoError(data, key, iv, aesMode) {
  6934. const enableSoftwareAES = this.enableSoftwareAES;
  6935. if (enableSoftwareAES) {
  6936. this.useSoftware = true;
  6937. this.logEnabled = true;
  6938. this.softwareDecrypt(data, key, iv, aesMode);
  6939. const decryptResult = this.flush();
  6940. if (decryptResult) {
  6941. return decryptResult.buffer;
  6942. }
  6943. }
  6944. throw new Error('WebCrypto' + (enableSoftwareAES ? ' and softwareDecrypt' : '') + ': failed to decrypt data');
  6945. }
  6946. getValidChunk(data) {
  6947. let currentChunk = data;
  6948. const splitPoint = data.length - data.length % CHUNK_SIZE;
  6949. if (splitPoint !== data.length) {
  6950. currentChunk = data.slice(0, splitPoint);
  6951. this.remainderData = data.slice(splitPoint);
  6952. }
  6953. return currentChunk;
  6954. }
  6955. logOnce(msg) {
  6956. if (!this.logEnabled) {
  6957. return;
  6958. }
  6959. logger.log(`[decrypter]: ${msg}`);
  6960. this.logEnabled = false;
  6961. }
  6962. }
  6963. const MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb
  6964. class FragmentLoader {
  6965. constructor(config) {
  6966. this.config = void 0;
  6967. this.loader = null;
  6968. this.partLoadTimeout = -1;
  6969. this.config = config;
  6970. }
  6971. destroy() {
  6972. if (this.loader) {
  6973. this.loader.destroy();
  6974. this.loader = null;
  6975. }
  6976. }
  6977. abort() {
  6978. if (this.loader) {
  6979. // Abort the loader for current fragment. Only one may load at any given time
  6980. this.loader.abort();
  6981. }
  6982. }
  6983. load(frag, onProgress) {
  6984. const url = frag.url;
  6985. if (!url) {
  6986. return Promise.reject(new LoadError({
  6987. type: ErrorTypes.NETWORK_ERROR,
  6988. details: ErrorDetails.FRAG_LOAD_ERROR,
  6989. fatal: false,
  6990. frag,
  6991. error: new Error(`Fragment does not have a ${url ? 'part list' : 'url'}`),
  6992. networkDetails: null
  6993. }));
  6994. }
  6995. this.abort();
  6996. const config = this.config;
  6997. const FragmentILoader = config.fLoader;
  6998. const DefaultILoader = config.loader;
  6999. return new Promise((resolve, reject) => {
  7000. if (this.loader) {
  7001. this.loader.destroy();
  7002. }
  7003. if (frag.gap) {
  7004. if (frag.tagList.some(tags => tags[0] === 'GAP')) {
  7005. reject(createGapLoadError(frag));
  7006. return;
  7007. } else {
  7008. // Reset temporary treatment as GAP tag
  7009. frag.gap = false;
  7010. }
  7011. }
  7012. const loader = this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  7013. const loaderContext = createLoaderContext(frag);
  7014. frag.loader = loader;
  7015. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  7016. const loaderConfig = {
  7017. loadPolicy,
  7018. timeout: loadPolicy.maxLoadTimeMs,
  7019. maxRetry: 0,
  7020. retryDelay: 0,
  7021. maxRetryDelay: 0,
  7022. highWaterMark: frag.sn === 'initSegment' ? Infinity : MIN_CHUNK_SIZE
  7023. };
  7024. // Assign frag stats to the loader's stats reference
  7025. frag.stats = loader.stats;
  7026. const callbacks = {
  7027. onSuccess: (response, stats, context, networkDetails) => {
  7028. this.resetLoader(frag, loader);
  7029. let payload = response.data;
  7030. if (context.resetIV && frag.decryptdata) {
  7031. frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));
  7032. payload = payload.slice(16);
  7033. }
  7034. resolve({
  7035. frag,
  7036. part: null,
  7037. payload,
  7038. networkDetails
  7039. });
  7040. },
  7041. onError: (response, context, networkDetails, stats) => {
  7042. this.resetLoader(frag, loader);
  7043. reject(new LoadError({
  7044. type: ErrorTypes.NETWORK_ERROR,
  7045. details: ErrorDetails.FRAG_LOAD_ERROR,
  7046. fatal: false,
  7047. frag,
  7048. response: _objectSpread2({
  7049. url,
  7050. data: undefined
  7051. }, response),
  7052. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  7053. networkDetails,
  7054. stats
  7055. }));
  7056. },
  7057. onAbort: (stats, context, networkDetails) => {
  7058. this.resetLoader(frag, loader);
  7059. reject(new LoadError({
  7060. type: ErrorTypes.NETWORK_ERROR,
  7061. details: ErrorDetails.INTERNAL_ABORTED,
  7062. fatal: false,
  7063. frag,
  7064. error: new Error('Aborted'),
  7065. networkDetails,
  7066. stats
  7067. }));
  7068. },
  7069. onTimeout: (stats, context, networkDetails) => {
  7070. this.resetLoader(frag, loader);
  7071. reject(new LoadError({
  7072. type: ErrorTypes.NETWORK_ERROR,
  7073. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  7074. fatal: false,
  7075. frag,
  7076. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  7077. networkDetails,
  7078. stats
  7079. }));
  7080. }
  7081. };
  7082. if (onProgress) {
  7083. callbacks.onProgress = (stats, context, data, networkDetails) => onProgress({
  7084. frag,
  7085. part: null,
  7086. payload: data,
  7087. networkDetails
  7088. });
  7089. }
  7090. loader.load(loaderContext, loaderConfig, callbacks);
  7091. });
  7092. }
  7093. loadPart(frag, part, onProgress) {
  7094. this.abort();
  7095. const config = this.config;
  7096. const FragmentILoader = config.fLoader;
  7097. const DefaultILoader = config.loader;
  7098. return new Promise((resolve, reject) => {
  7099. if (this.loader) {
  7100. this.loader.destroy();
  7101. }
  7102. if (frag.gap || part.gap) {
  7103. reject(createGapLoadError(frag, part));
  7104. return;
  7105. }
  7106. const loader = this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  7107. const loaderContext = createLoaderContext(frag, part);
  7108. frag.loader = loader;
  7109. // Should we define another load policy for parts?
  7110. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  7111. const loaderConfig = {
  7112. loadPolicy,
  7113. timeout: loadPolicy.maxLoadTimeMs,
  7114. maxRetry: 0,
  7115. retryDelay: 0,
  7116. maxRetryDelay: 0,
  7117. highWaterMark: MIN_CHUNK_SIZE
  7118. };
  7119. // Assign part stats to the loader's stats reference
  7120. part.stats = loader.stats;
  7121. loader.load(loaderContext, loaderConfig, {
  7122. onSuccess: (response, stats, context, networkDetails) => {
  7123. this.resetLoader(frag, loader);
  7124. this.updateStatsFromPart(frag, part);
  7125. const partLoadedData = {
  7126. frag,
  7127. part,
  7128. payload: response.data,
  7129. networkDetails
  7130. };
  7131. onProgress(partLoadedData);
  7132. resolve(partLoadedData);
  7133. },
  7134. onError: (response, context, networkDetails, stats) => {
  7135. this.resetLoader(frag, loader);
  7136. reject(new LoadError({
  7137. type: ErrorTypes.NETWORK_ERROR,
  7138. details: ErrorDetails.FRAG_LOAD_ERROR,
  7139. fatal: false,
  7140. frag,
  7141. part,
  7142. response: _objectSpread2({
  7143. url: loaderContext.url,
  7144. data: undefined
  7145. }, response),
  7146. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  7147. networkDetails,
  7148. stats
  7149. }));
  7150. },
  7151. onAbort: (stats, context, networkDetails) => {
  7152. frag.stats.aborted = part.stats.aborted;
  7153. this.resetLoader(frag, loader);
  7154. reject(new LoadError({
  7155. type: ErrorTypes.NETWORK_ERROR,
  7156. details: ErrorDetails.INTERNAL_ABORTED,
  7157. fatal: false,
  7158. frag,
  7159. part,
  7160. error: new Error('Aborted'),
  7161. networkDetails,
  7162. stats
  7163. }));
  7164. },
  7165. onTimeout: (stats, context, networkDetails) => {
  7166. this.resetLoader(frag, loader);
  7167. reject(new LoadError({
  7168. type: ErrorTypes.NETWORK_ERROR,
  7169. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  7170. fatal: false,
  7171. frag,
  7172. part,
  7173. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  7174. networkDetails,
  7175. stats
  7176. }));
  7177. }
  7178. });
  7179. });
  7180. }
  7181. updateStatsFromPart(frag, part) {
  7182. const fragStats = frag.stats;
  7183. const partStats = part.stats;
  7184. const partTotal = partStats.total;
  7185. fragStats.loaded += partStats.loaded;
  7186. if (partTotal) {
  7187. const estTotalParts = Math.round(frag.duration / part.duration);
  7188. const estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
  7189. const estRemainingParts = estTotalParts - estLoadedParts;
  7190. const estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
  7191. fragStats.total = fragStats.loaded + estRemainingBytes;
  7192. } else {
  7193. fragStats.total = Math.max(fragStats.loaded, fragStats.total);
  7194. }
  7195. const fragLoading = fragStats.loading;
  7196. const partLoading = partStats.loading;
  7197. if (fragLoading.start) {
  7198. // add to fragment loader latency
  7199. fragLoading.first += partLoading.first - partLoading.start;
  7200. } else {
  7201. fragLoading.start = partLoading.start;
  7202. fragLoading.first = partLoading.first;
  7203. }
  7204. fragLoading.end = partLoading.end;
  7205. }
  7206. resetLoader(frag, loader) {
  7207. frag.loader = null;
  7208. if (this.loader === loader) {
  7209. self.clearTimeout(this.partLoadTimeout);
  7210. this.loader = null;
  7211. }
  7212. loader.destroy();
  7213. }
  7214. }
  7215. function createLoaderContext(frag, part = null) {
  7216. const segment = part || frag;
  7217. const loaderContext = {
  7218. frag,
  7219. part,
  7220. responseType: 'arraybuffer',
  7221. url: segment.url,
  7222. headers: {},
  7223. rangeStart: 0,
  7224. rangeEnd: 0
  7225. };
  7226. const start = segment.byteRangeStartOffset;
  7227. const end = segment.byteRangeEndOffset;
  7228. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  7229. var _frag$decryptdata;
  7230. let byteRangeStart = start;
  7231. let byteRangeEnd = end;
  7232. if (frag.sn === 'initSegment' && isMethodFullSegmentAesCbc((_frag$decryptdata = frag.decryptdata) == null ? void 0 : _frag$decryptdata.method)) {
  7233. // MAP segment encrypted with method 'AES-128' or 'AES-256' (cbc), when served with HTTP Range,
  7234. // has the unencrypted size specified in the range.
  7235. // Ref: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6
  7236. const fragmentLen = end - start;
  7237. if (fragmentLen % 16) {
  7238. byteRangeEnd = end + (16 - fragmentLen % 16);
  7239. }
  7240. if (start !== 0) {
  7241. loaderContext.resetIV = true;
  7242. byteRangeStart = start - 16;
  7243. }
  7244. }
  7245. loaderContext.rangeStart = byteRangeStart;
  7246. loaderContext.rangeEnd = byteRangeEnd;
  7247. }
  7248. return loaderContext;
  7249. }
  7250. function createGapLoadError(frag, part) {
  7251. const error = new Error(`GAP ${frag.gap ? 'tag' : 'attribute'} found`);
  7252. const errorData = {
  7253. type: ErrorTypes.MEDIA_ERROR,
  7254. details: ErrorDetails.FRAG_GAP,
  7255. fatal: false,
  7256. frag,
  7257. error,
  7258. networkDetails: null
  7259. };
  7260. if (part) {
  7261. errorData.part = part;
  7262. }
  7263. (part ? part : frag).stats.aborted = true;
  7264. return new LoadError(errorData);
  7265. }
  7266. function isMethodFullSegmentAesCbc(method) {
  7267. return method === 'AES-128' || method === 'AES-256';
  7268. }
  7269. class LoadError extends Error {
  7270. constructor(data) {
  7271. super(data.error.message);
  7272. this.data = void 0;
  7273. this.data = data;
  7274. }
  7275. }
  7276. /**
  7277. * @ignore
  7278. * Sub-class specialization of EventHandler base class.
  7279. *
  7280. * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
  7281. * scheduled asynchroneously, avoiding recursive calls in the same tick.
  7282. *
  7283. * The task itself is implemented in `doTick`. It can be requested and called for single execution
  7284. * using the `tick` method.
  7285. *
  7286. * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
  7287. * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
  7288. *
  7289. * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
  7290. * and cancelled with `clearNextTick`.
  7291. *
  7292. * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
  7293. *
  7294. * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
  7295. *
  7296. * Further explanations:
  7297. *
  7298. * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
  7299. * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
  7300. *
  7301. * When the task execution (`tick` method) is called in re-entrant way this is detected and
  7302. * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
  7303. * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
  7304. */
  7305. class TaskLoop extends Logger {
  7306. constructor(label, logger) {
  7307. super(label, logger);
  7308. this._boundTick = void 0;
  7309. this._tickTimer = null;
  7310. this._tickInterval = null;
  7311. this._tickCallCount = 0;
  7312. this._boundTick = this.tick.bind(this);
  7313. }
  7314. destroy() {
  7315. this.onHandlerDestroying();
  7316. this.onHandlerDestroyed();
  7317. }
  7318. onHandlerDestroying() {
  7319. // clear all timers before unregistering from event bus
  7320. this.clearNextTick();
  7321. this.clearInterval();
  7322. }
  7323. onHandlerDestroyed() {}
  7324. hasInterval() {
  7325. return !!this._tickInterval;
  7326. }
  7327. hasNextTick() {
  7328. return !!this._tickTimer;
  7329. }
  7330. /**
  7331. * @param millis - Interval time (ms)
  7332. * @eturns True when interval has been scheduled, false when already scheduled (no effect)
  7333. */
  7334. setInterval(millis) {
  7335. if (!this._tickInterval) {
  7336. this._tickCallCount = 0;
  7337. this._tickInterval = self.setInterval(this._boundTick, millis);
  7338. return true;
  7339. }
  7340. return false;
  7341. }
  7342. /**
  7343. * @returns True when interval was cleared, false when none was set (no effect)
  7344. */
  7345. clearInterval() {
  7346. if (this._tickInterval) {
  7347. self.clearInterval(this._tickInterval);
  7348. this._tickInterval = null;
  7349. return true;
  7350. }
  7351. return false;
  7352. }
  7353. /**
  7354. * @returns True when timeout was cleared, false when none was set (no effect)
  7355. */
  7356. clearNextTick() {
  7357. if (this._tickTimer) {
  7358. self.clearTimeout(this._tickTimer);
  7359. this._tickTimer = null;
  7360. return true;
  7361. }
  7362. return false;
  7363. }
  7364. /**
  7365. * Will call the subclass doTick implementation in this main loop tick
  7366. * or in the next one (via setTimeout(,0)) in case it has already been called
  7367. * in this tick (in case this is a re-entrant call).
  7368. */
  7369. tick() {
  7370. this._tickCallCount++;
  7371. if (this._tickCallCount === 1) {
  7372. this.doTick();
  7373. // re-entrant call to tick from previous doTick call stack
  7374. // -> schedule a call on the next main loop iteration to process this task processing request
  7375. if (this._tickCallCount > 1) {
  7376. // make sure only one timer exists at any time at max
  7377. this.tickImmediate();
  7378. }
  7379. this._tickCallCount = 0;
  7380. }
  7381. }
  7382. tickImmediate() {
  7383. this.clearNextTick();
  7384. this._tickTimer = self.setTimeout(this._boundTick, 0);
  7385. }
  7386. /**
  7387. * For subclass to implement task logic
  7388. * @abstract
  7389. */
  7390. doTick() {}
  7391. }
  7392. class ChunkMetadata {
  7393. constructor(level, sn, id, size = 0, part = -1, partial = false) {
  7394. this.level = void 0;
  7395. this.sn = void 0;
  7396. this.part = void 0;
  7397. this.id = void 0;
  7398. this.size = void 0;
  7399. this.partial = void 0;
  7400. this.transmuxing = getNewPerformanceTiming();
  7401. this.buffering = {
  7402. audio: getNewPerformanceTiming(),
  7403. video: getNewPerformanceTiming(),
  7404. audiovideo: getNewPerformanceTiming()
  7405. };
  7406. this.level = level;
  7407. this.sn = sn;
  7408. this.id = id;
  7409. this.size = size;
  7410. this.part = part;
  7411. this.partial = partial;
  7412. }
  7413. }
  7414. function getNewPerformanceTiming() {
  7415. return {
  7416. start: 0,
  7417. executeStart: 0,
  7418. executeEnd: 0,
  7419. end: 0
  7420. };
  7421. }
  7422. /**
  7423. * Provides methods dealing with buffer length retrieval for example.
  7424. *
  7425. * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
  7426. *
  7427. * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
  7428. */
  7429. const noopBuffered = {
  7430. length: 0,
  7431. start: () => 0,
  7432. end: () => 0
  7433. };
  7434. class BufferHelper {
  7435. /**
  7436. * Return true if `media`'s buffered include `position`
  7437. */
  7438. static isBuffered(media, position) {
  7439. if (media) {
  7440. const buffered = BufferHelper.getBuffered(media);
  7441. for (let i = buffered.length; i--;) {
  7442. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  7443. return true;
  7444. }
  7445. }
  7446. }
  7447. return false;
  7448. }
  7449. static bufferedRanges(media) {
  7450. if (media) {
  7451. const timeRanges = BufferHelper.getBuffered(media);
  7452. return BufferHelper.timeRangesToArray(timeRanges);
  7453. }
  7454. return [];
  7455. }
  7456. static timeRangesToArray(timeRanges) {
  7457. const buffered = [];
  7458. for (let i = 0; i < timeRanges.length; i++) {
  7459. buffered.push({
  7460. start: timeRanges.start(i),
  7461. end: timeRanges.end(i)
  7462. });
  7463. }
  7464. return buffered;
  7465. }
  7466. static bufferInfo(media, pos, maxHoleDuration) {
  7467. if (media) {
  7468. const buffered = BufferHelper.bufferedRanges(media);
  7469. if (buffered.length) {
  7470. return BufferHelper.bufferedInfo(buffered, pos, maxHoleDuration);
  7471. }
  7472. }
  7473. return {
  7474. len: 0,
  7475. start: pos,
  7476. end: pos,
  7477. bufferedIndex: -1
  7478. };
  7479. }
  7480. static bufferedInfo(buffered, pos, maxHoleDuration) {
  7481. pos = Math.max(0, pos);
  7482. // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
  7483. if (buffered.length > 1) {
  7484. buffered.sort((a, b) => a.start - b.start || b.end - a.end);
  7485. }
  7486. let bufferedIndex = -1;
  7487. let buffered2 = [];
  7488. if (maxHoleDuration) {
  7489. // there might be some small holes between buffer time range
  7490. // consider that holes smaller than maxHoleDuration are irrelevant and build another
  7491. // buffer time range representations that discards those holes
  7492. for (let i = 0; i < buffered.length; i++) {
  7493. if (pos >= buffered[i].start && pos <= buffered[i].end) {
  7494. bufferedIndex = i;
  7495. }
  7496. const buf2len = buffered2.length;
  7497. if (buf2len) {
  7498. const buf2end = buffered2[buf2len - 1].end;
  7499. // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
  7500. if (buffered[i].start - buf2end < maxHoleDuration) {
  7501. // merge overlapping time ranges
  7502. // update lastRange.end only if smaller than item.end
  7503. // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
  7504. // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
  7505. if (buffered[i].end > buf2end) {
  7506. buffered2[buf2len - 1].end = buffered[i].end;
  7507. }
  7508. } else {
  7509. // big hole
  7510. buffered2.push(buffered[i]);
  7511. }
  7512. } else {
  7513. // first value
  7514. buffered2.push(buffered[i]);
  7515. }
  7516. }
  7517. } else {
  7518. buffered2 = buffered;
  7519. }
  7520. let bufferLen = 0;
  7521. let nextStart;
  7522. // bufferStart and bufferEnd are buffer boundaries around current playback position (pos)
  7523. let bufferStart = pos;
  7524. let bufferEnd = pos;
  7525. for (let i = 0; i < buffered2.length; i++) {
  7526. const start = buffered2[i].start;
  7527. const end = buffered2[i].end;
  7528. // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
  7529. if (bufferedIndex === -1 && pos >= start && pos <= end) {
  7530. bufferedIndex = i;
  7531. }
  7532. if (pos + maxHoleDuration >= start && pos < end) {
  7533. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  7534. bufferStart = start;
  7535. bufferEnd = end;
  7536. bufferLen = bufferEnd - pos;
  7537. } else if (pos + maxHoleDuration < start) {
  7538. nextStart = start;
  7539. break;
  7540. }
  7541. }
  7542. return {
  7543. len: bufferLen,
  7544. start: bufferStart || 0,
  7545. end: bufferEnd || 0,
  7546. nextStart,
  7547. buffered,
  7548. bufferedIndex
  7549. };
  7550. }
  7551. /**
  7552. * Safe method to get buffered property.
  7553. * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
  7554. */
  7555. static getBuffered(media) {
  7556. try {
  7557. return media.buffered || noopBuffered;
  7558. } catch (e) {
  7559. logger.log('failed to get media.buffered', e);
  7560. return noopBuffered;
  7561. }
  7562. }
  7563. }
  7564. function findFirstFragWithCC(fragments, cc) {
  7565. for (let i = 0, len = fragments.length; i < len; i++) {
  7566. var _fragments$i;
  7567. if (((_fragments$i = fragments[i]) == null ? void 0 : _fragments$i.cc) === cc) {
  7568. return fragments[i];
  7569. }
  7570. }
  7571. return null;
  7572. }
  7573. function shouldAlignOnDiscontinuities(refDetails, details) {
  7574. if (refDetails) {
  7575. if (details.startCC < refDetails.endCC && details.endCC > refDetails.startCC) {
  7576. return true;
  7577. }
  7578. }
  7579. return false;
  7580. }
  7581. function adjustFragmentStart(frag, sliding) {
  7582. if (frag) {
  7583. const start = frag.start + sliding;
  7584. frag.start = frag.startPTS = start;
  7585. frag.endPTS = start + frag.duration;
  7586. }
  7587. }
  7588. function adjustSlidingStart(sliding, details) {
  7589. // Update segments
  7590. const fragments = details.fragments;
  7591. for (let i = 0, len = fragments.length; i < len; i++) {
  7592. adjustFragmentStart(fragments[i], sliding);
  7593. }
  7594. // Update LL-HLS parts at the end of the playlist
  7595. if (details.fragmentHint) {
  7596. adjustFragmentStart(details.fragmentHint, sliding);
  7597. }
  7598. details.alignedSliding = true;
  7599. }
  7600. /**
  7601. * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
  7602. * contiguous stream with the last fragments.
  7603. * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
  7604. * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
  7605. * and an extra download.
  7606. * @param lastLevel
  7607. * @param details
  7608. */
  7609. function alignStream(switchDetails, details) {
  7610. if (!switchDetails) {
  7611. return;
  7612. }
  7613. alignDiscontinuities(details, switchDetails);
  7614. if (!details.alignedSliding && switchDetails) {
  7615. // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
  7616. // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
  7617. // discontinuity sequence.
  7618. alignMediaPlaylistByPDT(details, switchDetails);
  7619. }
  7620. if (!details.alignedSliding && switchDetails && !details.skippedSegments) {
  7621. // Try to align on sn so that we pick a better start fragment.
  7622. // Do not perform this on playlists with delta updates as this is only to align levels on switch
  7623. // and adjustSliding only adjusts fragments after skippedSegments.
  7624. adjustSliding(switchDetails, details, false);
  7625. }
  7626. }
  7627. /**
  7628. * Ajust the start of fragments in `details` by the difference in time between fragments of the latest
  7629. * shared discontinuity sequence change.
  7630. * @param lastLevel - The details of the last loaded level
  7631. * @param details - The details of the new level
  7632. */
  7633. function alignDiscontinuities(details, refDetails) {
  7634. if (!shouldAlignOnDiscontinuities(refDetails, details)) {
  7635. return;
  7636. }
  7637. const targetCC = Math.min(refDetails.endCC, details.endCC);
  7638. const refFrag = findFirstFragWithCC(refDetails.fragments, targetCC);
  7639. const frag = findFirstFragWithCC(details.fragments, targetCC);
  7640. if (!refFrag || !frag) {
  7641. return;
  7642. }
  7643. logger.log(`Aligning playlist at start of dicontinuity sequence ${targetCC}`);
  7644. const delta = refFrag.start - frag.start;
  7645. adjustSlidingStart(delta, details);
  7646. }
  7647. /**
  7648. * Ensures appropriate time-alignment between renditions based on PDT.
  7649. * This function assumes the timelines represented in `refDetails` are accurate, including the PDTs
  7650. * for the last discontinuity sequence number shared by both playlists when present,
  7651. * and uses the "wallclock"/PDT timeline as a cross-reference to `details`, adjusting the presentation
  7652. * times/timelines of `details` accordingly.
  7653. * Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,
  7654. * the primary purpose of this function is to ensure the "local timelines" of audio/subtitle tracks
  7655. * are aligned to the main/video timeline, using PDT as the cross-reference/"anchor" that should
  7656. * be consistent across playlists, per the HLS spec.
  7657. * @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).
  7658. * @param refDetails - The details of the reference rendition with start and PDT times for alignment.
  7659. */
  7660. function alignMediaPlaylistByPDT(details, refDetails) {
  7661. if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
  7662. return;
  7663. }
  7664. const fragments = details.fragments;
  7665. const refFragments = refDetails.fragments;
  7666. if (!fragments.length || !refFragments.length) {
  7667. return;
  7668. }
  7669. // Calculate a delta to apply to all fragments according to the delta in PDT times and start times
  7670. // of a fragment in the reference details, and a fragment in the target details of the same discontinuity.
  7671. // If a fragment of the same discontinuity was not found use the middle fragment of both.
  7672. let refFrag;
  7673. let frag;
  7674. const targetCC = Math.min(refDetails.endCC, details.endCC);
  7675. if (refDetails.startCC < targetCC && details.startCC < targetCC) {
  7676. refFrag = findFirstFragWithCC(refFragments, targetCC);
  7677. frag = findFirstFragWithCC(fragments, targetCC);
  7678. }
  7679. if (!refFrag || !frag) {
  7680. refFrag = refFragments[Math.floor(refFragments.length / 2)];
  7681. frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.floor(fragments.length / 2)];
  7682. }
  7683. const refPDT = refFrag.programDateTime;
  7684. const targetPDT = frag.programDateTime;
  7685. if (!refPDT || !targetPDT) {
  7686. return;
  7687. }
  7688. const delta = (targetPDT - refPDT) / 1000 - (frag.start - refFrag.start);
  7689. adjustSlidingStart(delta, details);
  7690. }
  7691. /**
  7692. * TimeRanges to string helper
  7693. */
  7694. const TimeRanges = {
  7695. toString: function (r) {
  7696. let log = '';
  7697. const len = r.length;
  7698. for (let i = 0; i < len; i++) {
  7699. log += `[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;
  7700. }
  7701. return log;
  7702. }
  7703. };
  7704. const State = {
  7705. STOPPED: 'STOPPED',
  7706. IDLE: 'IDLE',
  7707. KEY_LOADING: 'KEY_LOADING',
  7708. FRAG_LOADING: 'FRAG_LOADING',
  7709. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  7710. PARSING: 'PARSING',
  7711. PARSED: 'PARSED',
  7712. ENDED: 'ENDED',
  7713. ERROR: 'ERROR',
  7714. WAITING_LEVEL: 'WAITING_LEVEL'
  7715. };
  7716. class BaseStreamController extends TaskLoop {
  7717. constructor(hls, fragmentTracker, keyLoader, logPrefix, playlistType) {
  7718. super(logPrefix, hls.logger);
  7719. this.hls = void 0;
  7720. this.fragPrevious = null;
  7721. this.fragCurrent = null;
  7722. this.fragmentTracker = void 0;
  7723. this.transmuxer = null;
  7724. this._state = State.STOPPED;
  7725. this.playlistType = void 0;
  7726. this.media = null;
  7727. this.mediaBuffer = null;
  7728. this.config = void 0;
  7729. this.bitrateTest = false;
  7730. this.lastCurrentTime = 0;
  7731. this.nextLoadPosition = 0;
  7732. this.startPosition = 0;
  7733. this.startTimeOffset = null;
  7734. this.retryDate = 0;
  7735. this.levels = null;
  7736. this.fragmentLoader = void 0;
  7737. this.keyLoader = void 0;
  7738. this.levelLastLoaded = null;
  7739. this.startFragRequested = false;
  7740. this.decrypter = void 0;
  7741. this.initPTS = [];
  7742. this.buffering = true;
  7743. this.loadingParts = false;
  7744. this.loopSn = void 0;
  7745. this.onMediaSeeking = () => {
  7746. const {
  7747. config,
  7748. fragCurrent,
  7749. media,
  7750. mediaBuffer,
  7751. state
  7752. } = this;
  7753. const currentTime = media ? media.currentTime : 0;
  7754. const bufferInfo = BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config.maxBufferHole);
  7755. const noFowardBuffer = !bufferInfo.len;
  7756. this.log(`Media seeking to ${isFiniteNumber(currentTime) ? currentTime.toFixed(3) : currentTime}, state: ${state}, ${noFowardBuffer ? 'out of' : 'in'} buffer`);
  7757. if (this.state === State.ENDED) {
  7758. this.resetLoadingState();
  7759. } else if (fragCurrent) {
  7760. // Seeking while frag load is in progress
  7761. const tolerance = config.maxFragLookUpTolerance;
  7762. const fragStartOffset = fragCurrent.start - tolerance;
  7763. const fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  7764. // if seeking out of buffered range or into new one
  7765. if (noFowardBuffer || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) {
  7766. const pastFragment = currentTime > fragEndOffset;
  7767. // if the seek position is outside the current fragment range
  7768. if (currentTime < fragStartOffset || pastFragment) {
  7769. if (pastFragment && fragCurrent.loader) {
  7770. this.log(`Cancelling fragment load for seek (sn: ${fragCurrent.sn})`);
  7771. fragCurrent.abortRequests();
  7772. this.resetLoadingState();
  7773. }
  7774. this.fragPrevious = null;
  7775. }
  7776. }
  7777. }
  7778. if (media) {
  7779. // Remove gap fragments
  7780. this.fragmentTracker.removeFragmentsInRange(currentTime, Infinity, this.playlistType, true);
  7781. // Don't set lastCurrentTime with backward seeks (allows for frag selection with strict tolerances)
  7782. const lastCurrentTime = this.lastCurrentTime;
  7783. if (currentTime > lastCurrentTime) {
  7784. this.lastCurrentTime = currentTime;
  7785. }
  7786. if (!this.loadingParts) {
  7787. const bufferEnd = Math.max(bufferInfo.end, currentTime);
  7788. const shouldLoadParts = this.shouldLoadParts(this.getLevelDetails(), bufferEnd);
  7789. if (shouldLoadParts) {
  7790. this.log(`LL-Part loading ON after seeking to ${currentTime.toFixed(2)} with buffer @${bufferEnd.toFixed(2)}`);
  7791. this.loadingParts = shouldLoadParts;
  7792. }
  7793. }
  7794. }
  7795. // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
  7796. if (!this.hls.hasEnoughToStart) {
  7797. this.log(`Setting ${noFowardBuffer ? 'startPosition' : 'nextLoadPosition'} to ${currentTime} for seek without enough to start`);
  7798. this.nextLoadPosition = currentTime;
  7799. if (noFowardBuffer) {
  7800. this.startPosition = currentTime;
  7801. }
  7802. }
  7803. // Async tick to speed up processing
  7804. this.tickImmediate();
  7805. };
  7806. this.onMediaEnded = () => {
  7807. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  7808. this.log(`setting startPosition to 0 because media ended`);
  7809. this.startPosition = this.lastCurrentTime = 0;
  7810. };
  7811. this.playlistType = playlistType;
  7812. this.hls = hls;
  7813. this.fragmentLoader = new FragmentLoader(hls.config);
  7814. this.keyLoader = keyLoader;
  7815. this.fragmentTracker = fragmentTracker;
  7816. this.config = hls.config;
  7817. this.decrypter = new Decrypter(hls.config);
  7818. }
  7819. registerListeners() {
  7820. const {
  7821. hls
  7822. } = this;
  7823. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  7824. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  7825. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  7826. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  7827. hls.on(Events.ERROR, this.onError, this);
  7828. }
  7829. unregisterListeners() {
  7830. const {
  7831. hls
  7832. } = this;
  7833. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  7834. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  7835. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  7836. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  7837. hls.off(Events.ERROR, this.onError, this);
  7838. }
  7839. doTick() {
  7840. this.onTickEnd();
  7841. }
  7842. onTickEnd() {}
  7843. startLoad(startPosition) {}
  7844. stopLoad() {
  7845. if (this.state === State.STOPPED) {
  7846. return;
  7847. }
  7848. this.fragmentLoader.abort();
  7849. this.keyLoader.abort(this.playlistType);
  7850. const frag = this.fragCurrent;
  7851. if (frag != null && frag.loader) {
  7852. frag.abortRequests();
  7853. this.fragmentTracker.removeFragment(frag);
  7854. }
  7855. this.resetTransmuxer();
  7856. this.fragCurrent = null;
  7857. this.fragPrevious = null;
  7858. this.clearInterval();
  7859. this.clearNextTick();
  7860. this.state = State.STOPPED;
  7861. }
  7862. get startPositionValue() {
  7863. const {
  7864. nextLoadPosition,
  7865. startPosition
  7866. } = this;
  7867. if (startPosition === -1 && nextLoadPosition) {
  7868. return nextLoadPosition;
  7869. }
  7870. return startPosition;
  7871. }
  7872. get bufferingEnabled() {
  7873. return this.buffering;
  7874. }
  7875. pauseBuffering() {
  7876. this.buffering = false;
  7877. }
  7878. resumeBuffering() {
  7879. this.buffering = true;
  7880. }
  7881. get inFlightFrag() {
  7882. return {
  7883. frag: this.fragCurrent,
  7884. state: this.state
  7885. };
  7886. }
  7887. _streamEnded(bufferInfo, levelDetails) {
  7888. // Stream is never "ended" when playlist is live or media is detached
  7889. if (levelDetails.live || !this.media) {
  7890. return false;
  7891. }
  7892. // Stream is not "ended" when nothing is buffered past the start
  7893. const bufferEnd = bufferInfo.end || 0;
  7894. const timelineStart = this.config.timelineOffset || 0;
  7895. if (bufferEnd <= timelineStart) {
  7896. return false;
  7897. }
  7898. // Stream is not "ended" when there is a second buffered range starting before the end of the playlist
  7899. const bufferedRanges = bufferInfo.buffered;
  7900. if (this.config.maxBufferHole && bufferedRanges && bufferedRanges.length > 1) {
  7901. // make sure bufferInfo accounts for any gaps
  7902. bufferInfo = BufferHelper.bufferedInfo(bufferedRanges, bufferInfo.start, 0);
  7903. }
  7904. const nextStart = bufferInfo.nextStart;
  7905. const hasSecondBufferedRange = nextStart && nextStart > timelineStart && nextStart < levelDetails.edge;
  7906. if (hasSecondBufferedRange) {
  7907. return false;
  7908. }
  7909. // Playhead is in unbuffered region. Marking EoS now could result in Safari failing to dispatch "ended" event following seek on start.
  7910. if (this.media.currentTime < bufferInfo.start) {
  7911. return false;
  7912. }
  7913. const partList = levelDetails.partList;
  7914. // Since the last part isn't guaranteed to correspond to the last playlist segment for Low-Latency HLS,
  7915. // check instead if the last part is buffered.
  7916. if (partList != null && partList.length) {
  7917. const lastPart = partList[partList.length - 1];
  7918. // Checking the midpoint of the part for potential margin of error and related issues.
  7919. // NOTE: Technically I believe parts could yield content that is < the computed duration (including potential a duration of 0)
  7920. // and still be spec-compliant, so there may still be edge cases here. Likewise, there could be issues in end of stream
  7921. // part mismatches for independent audio and video playlists/segments.
  7922. const lastPartBuffered = BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2);
  7923. return lastPartBuffered;
  7924. }
  7925. const playlistType = levelDetails.fragments[levelDetails.fragments.length - 1].type;
  7926. return this.fragmentTracker.isEndListAppended(playlistType);
  7927. }
  7928. getLevelDetails() {
  7929. if (this.levels && this.levelLastLoaded !== null) {
  7930. var _this$levelLastLoaded;
  7931. return (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details;
  7932. }
  7933. }
  7934. get timelineOffset() {
  7935. const configuredTimelineOffset = this.config.timelineOffset;
  7936. if (configuredTimelineOffset) {
  7937. var _this$getLevelDetails;
  7938. return ((_this$getLevelDetails = this.getLevelDetails()) == null ? void 0 : _this$getLevelDetails.appliedTimelineOffset) || configuredTimelineOffset;
  7939. }
  7940. return 0;
  7941. }
  7942. onMediaAttached(event, data) {
  7943. const media = this.media = this.mediaBuffer = data.media;
  7944. media.removeEventListener('seeking', this.onMediaSeeking);
  7945. media.removeEventListener('ended', this.onMediaEnded);
  7946. media.addEventListener('seeking', this.onMediaSeeking);
  7947. media.addEventListener('ended', this.onMediaEnded);
  7948. const config = this.config;
  7949. if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
  7950. this.startLoad(config.startPosition);
  7951. }
  7952. }
  7953. onMediaDetaching(event, data) {
  7954. const transferringMedia = !!data.transferMedia;
  7955. const media = this.media;
  7956. if (media === null) {
  7957. return;
  7958. }
  7959. if (media.ended) {
  7960. this.log('MSE detaching and video ended, reset startPosition');
  7961. this.startPosition = this.lastCurrentTime = 0;
  7962. }
  7963. // remove video listeners
  7964. media.removeEventListener('seeking', this.onMediaSeeking);
  7965. media.removeEventListener('ended', this.onMediaEnded);
  7966. if (this.keyLoader && !transferringMedia) {
  7967. this.keyLoader.detach();
  7968. }
  7969. this.media = this.mediaBuffer = null;
  7970. this.loopSn = undefined;
  7971. if (transferringMedia) {
  7972. this.resetLoadingState();
  7973. this.resetTransmuxer();
  7974. return;
  7975. }
  7976. this.loadingParts = false;
  7977. this.fragmentTracker.removeAllFragments();
  7978. this.stopLoad();
  7979. }
  7980. onManifestLoading() {
  7981. this.initPTS = [];
  7982. this.levels = this.levelLastLoaded = this.fragCurrent = null;
  7983. this.lastCurrentTime = this.startPosition = 0;
  7984. this.startFragRequested = false;
  7985. }
  7986. onError(event, data) {}
  7987. onManifestLoaded(event, data) {
  7988. this.startTimeOffset = data.startTimeOffset;
  7989. }
  7990. onHandlerDestroying() {
  7991. this.stopLoad();
  7992. if (this.transmuxer) {
  7993. this.transmuxer.destroy();
  7994. this.transmuxer = null;
  7995. }
  7996. super.onHandlerDestroying();
  7997. // @ts-ignore
  7998. this.hls = this.onMediaSeeking = this.onMediaEnded = null;
  7999. }
  8000. onHandlerDestroyed() {
  8001. this.state = State.STOPPED;
  8002. if (this.fragmentLoader) {
  8003. this.fragmentLoader.destroy();
  8004. }
  8005. if (this.keyLoader) {
  8006. this.keyLoader.destroy();
  8007. }
  8008. if (this.decrypter) {
  8009. this.decrypter.destroy();
  8010. }
  8011. this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null;
  8012. super.onHandlerDestroyed();
  8013. }
  8014. loadFragment(frag, level, targetBufferTime) {
  8015. this.startFragRequested = true;
  8016. this._loadFragForPlayback(frag, level, targetBufferTime);
  8017. }
  8018. _loadFragForPlayback(fragment, level, targetBufferTime) {
  8019. const progressCallback = data => {
  8020. const frag = data.frag;
  8021. if (this.fragContextChanged(frag)) {
  8022. this.warn(`${frag.type} sn: ${frag.sn}${data.part ? ' part: ' + data.part.index : ''} of ${this.fragInfo(frag, false, data.part)}) was dropped during download.`);
  8023. this.fragmentTracker.removeFragment(frag);
  8024. return;
  8025. }
  8026. frag.stats.chunkCount++;
  8027. this._handleFragmentLoadProgress(data);
  8028. };
  8029. this._doFragLoad(fragment, level, targetBufferTime, progressCallback).then(data => {
  8030. if (!data) {
  8031. // if we're here we probably needed to backtrack or are waiting for more parts
  8032. return;
  8033. }
  8034. const state = this.state;
  8035. const frag = data.frag;
  8036. if (this.fragContextChanged(frag)) {
  8037. if (state === State.FRAG_LOADING || !this.fragCurrent && state === State.PARSING) {
  8038. this.fragmentTracker.removeFragment(frag);
  8039. this.state = State.IDLE;
  8040. }
  8041. return;
  8042. }
  8043. if ('payload' in data) {
  8044. this.log(`Loaded ${frag.type} sn: ${frag.sn} of ${this.playlistLabel()} ${frag.level}`);
  8045. this.hls.trigger(Events.FRAG_LOADED, data);
  8046. }
  8047. // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback
  8048. this._handleFragmentLoadComplete(data);
  8049. }).catch(reason => {
  8050. if (this.state === State.STOPPED || this.state === State.ERROR) {
  8051. return;
  8052. }
  8053. this.warn(`Frag error: ${(reason == null ? void 0 : reason.message) || reason}`);
  8054. this.resetFragmentLoading(fragment);
  8055. });
  8056. }
  8057. clearTrackerIfNeeded(frag) {
  8058. var _this$mediaBuffer;
  8059. const {
  8060. fragmentTracker
  8061. } = this;
  8062. const fragState = fragmentTracker.getState(frag);
  8063. if (fragState === FragmentState.APPENDING) {
  8064. // Lower the max buffer length and try again
  8065. const playlistType = frag.type;
  8066. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  8067. const minForwardBufferLength = Math.max(frag.duration, bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength);
  8068. // If backtracking, always remove from the tracker without reducing max buffer length
  8069. const backtrackFragment = this.backtrackFragment;
  8070. const backtracked = backtrackFragment ? frag.sn - backtrackFragment.sn : 0;
  8071. if (backtracked === 1 || this.reduceMaxBufferLength(minForwardBufferLength, frag.duration)) {
  8072. fragmentTracker.removeFragment(frag);
  8073. }
  8074. } else if (((_this$mediaBuffer = this.mediaBuffer) == null ? void 0 : _this$mediaBuffer.buffered.length) === 0) {
  8075. // Stop gap for bad tracker / buffer flush behavior
  8076. fragmentTracker.removeAllFragments();
  8077. } else if (fragmentTracker.hasParts(frag.type)) {
  8078. // In low latency mode, remove fragments for which only some parts were buffered
  8079. fragmentTracker.detectPartialFragments({
  8080. frag,
  8081. part: null,
  8082. stats: frag.stats,
  8083. id: frag.type
  8084. });
  8085. if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {
  8086. fragmentTracker.removeFragment(frag);
  8087. }
  8088. }
  8089. }
  8090. checkLiveUpdate(details) {
  8091. if (details.updated && !details.live) {
  8092. // Live stream ended, update fragment tracker
  8093. const lastFragment = details.fragments[details.fragments.length - 1];
  8094. this.fragmentTracker.detectPartialFragments({
  8095. frag: lastFragment,
  8096. part: null,
  8097. stats: lastFragment.stats,
  8098. id: lastFragment.type
  8099. });
  8100. }
  8101. if (!details.fragments[0]) {
  8102. details.deltaUpdateFailed = true;
  8103. }
  8104. }
  8105. waitForLive(levelInfo) {
  8106. const details = levelInfo.details;
  8107. return (details == null ? void 0 : details.live) && details.type !== 'EVENT' && (this.levelLastLoaded !== levelInfo || details.expired);
  8108. }
  8109. flushMainBuffer(startOffset, endOffset, type = null) {
  8110. if (!(startOffset - endOffset)) {
  8111. return;
  8112. }
  8113. // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,
  8114. // passing a null type flushes both buffers
  8115. const flushScope = {
  8116. startOffset,
  8117. endOffset,
  8118. type
  8119. };
  8120. this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);
  8121. }
  8122. _loadInitSegment(fragment, level) {
  8123. this._doFragLoad(fragment, level).then(data => {
  8124. const frag = data == null ? void 0 : data.frag;
  8125. if (!frag || this.fragContextChanged(frag) || !this.levels) {
  8126. throw new Error('init load aborted');
  8127. }
  8128. return data;
  8129. }).then(data => {
  8130. const {
  8131. hls
  8132. } = this;
  8133. const {
  8134. frag,
  8135. payload
  8136. } = data;
  8137. const decryptData = frag.decryptdata;
  8138. // check to see if the payload needs to be decrypted
  8139. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
  8140. const startTime = self.performance.now();
  8141. // decrypt init segment data
  8142. return this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch(err => {
  8143. hls.trigger(Events.ERROR, {
  8144. type: ErrorTypes.MEDIA_ERROR,
  8145. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  8146. fatal: false,
  8147. error: err,
  8148. reason: err.message,
  8149. frag
  8150. });
  8151. throw err;
  8152. }).then(decryptedData => {
  8153. const endTime = self.performance.now();
  8154. hls.trigger(Events.FRAG_DECRYPTED, {
  8155. frag,
  8156. payload: decryptedData,
  8157. stats: {
  8158. tstart: startTime,
  8159. tdecrypt: endTime
  8160. }
  8161. });
  8162. data.payload = decryptedData;
  8163. return this.completeInitSegmentLoad(data);
  8164. });
  8165. }
  8166. return this.completeInitSegmentLoad(data);
  8167. }).catch(reason => {
  8168. if (this.state === State.STOPPED || this.state === State.ERROR) {
  8169. return;
  8170. }
  8171. this.warn(reason);
  8172. this.resetFragmentLoading(fragment);
  8173. });
  8174. }
  8175. completeInitSegmentLoad(data) {
  8176. const {
  8177. levels
  8178. } = this;
  8179. if (!levels) {
  8180. throw new Error('init load aborted, missing levels');
  8181. }
  8182. const stats = data.frag.stats;
  8183. if (this.state !== State.STOPPED) {
  8184. this.state = State.IDLE;
  8185. }
  8186. data.frag.data = new Uint8Array(data.payload);
  8187. stats.parsing.start = stats.buffering.start = self.performance.now();
  8188. stats.parsing.end = stats.buffering.end = self.performance.now();
  8189. this.tick();
  8190. }
  8191. fragContextChanged(frag) {
  8192. const {
  8193. fragCurrent
  8194. } = this;
  8195. return !frag || !fragCurrent || frag.sn !== fragCurrent.sn || frag.level !== fragCurrent.level;
  8196. }
  8197. fragBufferedComplete(frag, part) {
  8198. const media = this.mediaBuffer ? this.mediaBuffer : this.media;
  8199. 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)'})`);
  8200. if (isMediaFragment(frag)) {
  8201. var _this$levels;
  8202. if (frag.type !== PlaylistLevelType.SUBTITLE) {
  8203. const el = frag.elementaryStreams;
  8204. if (!Object.keys(el).some(type => !!el[type])) {
  8205. // empty segment
  8206. this.state = State.IDLE;
  8207. return;
  8208. }
  8209. }
  8210. const level = (_this$levels = this.levels) == null ? void 0 : _this$levels[frag.level];
  8211. if (level != null && level.fragmentError) {
  8212. this.log(`Resetting level fragment error count of ${level.fragmentError} on frag buffered`);
  8213. level.fragmentError = 0;
  8214. }
  8215. }
  8216. this.state = State.IDLE;
  8217. }
  8218. _handleFragmentLoadComplete(fragLoadedEndData) {
  8219. const {
  8220. transmuxer
  8221. } = this;
  8222. if (!transmuxer) {
  8223. return;
  8224. }
  8225. const {
  8226. frag,
  8227. part,
  8228. partsLoaded
  8229. } = fragLoadedEndData;
  8230. // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data
  8231. const complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(fragLoaded => !fragLoaded);
  8232. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
  8233. transmuxer.flush(chunkMeta);
  8234. }
  8235. _handleFragmentLoadProgress(frag) {}
  8236. _doFragLoad(frag, level, targetBufferTime = null, progressCallback) {
  8237. var _frag$decryptdata;
  8238. this.fragCurrent = frag;
  8239. const details = level == null ? void 0 : level.details;
  8240. if (!this.levels || !details) {
  8241. throw new Error(`frag load aborted, missing level${details ? '' : ' detail'}s`);
  8242. }
  8243. let keyLoadingPromise = null;
  8244. if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) != null && _frag$decryptdata.key)) {
  8245. this.log(`Loading key for ${frag.sn} of [${details.startSN}-${details.endSN}], ${this.playlistLabel()} ${frag.level}`);
  8246. this.state = State.KEY_LOADING;
  8247. this.fragCurrent = frag;
  8248. keyLoadingPromise = this.keyLoader.load(frag).then(keyLoadedData => {
  8249. if (!this.fragContextChanged(keyLoadedData.frag)) {
  8250. this.hls.trigger(Events.KEY_LOADED, keyLoadedData);
  8251. if (this.state === State.KEY_LOADING) {
  8252. this.state = State.IDLE;
  8253. }
  8254. return keyLoadedData;
  8255. }
  8256. });
  8257. this.hls.trigger(Events.KEY_LOADING, {
  8258. frag
  8259. });
  8260. if (this.fragCurrent === null) {
  8261. keyLoadingPromise = Promise.reject(new Error(`frag load aborted, context changed in KEY_LOADING`));
  8262. }
  8263. } else if (!frag.encrypted) {
  8264. keyLoadingPromise = this.keyLoader.loadClear(frag, details.encryptedFragments, this.startFragRequested);
  8265. if (keyLoadingPromise) {
  8266. this.log(`[eme] blocking frag load until media-keys acquired`);
  8267. }
  8268. }
  8269. const fragPrevious = this.fragPrevious;
  8270. if (isMediaFragment(frag) && (!fragPrevious || frag.sn !== fragPrevious.sn)) {
  8271. const shouldLoadParts = this.shouldLoadParts(level.details, frag.end);
  8272. if (shouldLoadParts !== this.loadingParts) {
  8273. this.log(`LL-Part loading ${shouldLoadParts ? 'ON' : 'OFF'} loading sn ${fragPrevious == null ? void 0 : fragPrevious.sn}->${frag.sn}`);
  8274. this.loadingParts = shouldLoadParts;
  8275. }
  8276. }
  8277. targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
  8278. if (this.loadingParts && isMediaFragment(frag)) {
  8279. const partList = details.partList;
  8280. if (partList && progressCallback) {
  8281. if (targetBufferTime > frag.end && details.fragmentHint) {
  8282. frag = details.fragmentHint;
  8283. }
  8284. const partIndex = this.getNextPart(partList, frag, targetBufferTime);
  8285. if (partIndex > -1) {
  8286. const part = partList[partIndex];
  8287. frag = this.fragCurrent = part.fragment;
  8288. 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))}`);
  8289. this.nextLoadPosition = part.start + part.duration;
  8290. this.state = State.FRAG_LOADING;
  8291. let _result;
  8292. if (keyLoadingPromise) {
  8293. _result = keyLoadingPromise.then(keyLoadedData => {
  8294. if (!keyLoadedData || this.fragContextChanged(keyLoadedData.frag)) {
  8295. return null;
  8296. }
  8297. return this.doFragPartsLoad(frag, part, level, progressCallback);
  8298. }).catch(error => this.handleFragLoadError(error));
  8299. } else {
  8300. _result = this.doFragPartsLoad(frag, part, level, progressCallback).catch(error => this.handleFragLoadError(error));
  8301. }
  8302. this.hls.trigger(Events.FRAG_LOADING, {
  8303. frag,
  8304. part,
  8305. targetBufferTime
  8306. });
  8307. if (this.fragCurrent === null) {
  8308. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING parts`));
  8309. }
  8310. return _result;
  8311. } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
  8312. // Fragment hint has no parts
  8313. return Promise.resolve(null);
  8314. }
  8315. }
  8316. }
  8317. if (isMediaFragment(frag) && this.loadingParts) {
  8318. this.log(`LL-Part loading OFF after next part miss @${targetBufferTime.toFixed(2)}`);
  8319. this.loadingParts = false;
  8320. } else if (!frag.url) {
  8321. // Selected fragment hint for part but not loading parts
  8322. return Promise.resolve(null);
  8323. }
  8324. this.log(`Loading ${frag.type} sn: ${frag.sn} of ${this.fragInfo(frag, false)}) cc: ${frag.cc} ${details ? '[' + details.startSN + '-' + details.endSN + ']' : ''}, target: ${parseFloat(targetBufferTime.toFixed(3))}`);
  8325. // Don't update nextLoadPosition for fragments which are not buffered
  8326. if (isFiniteNumber(frag.sn) && !this.bitrateTest) {
  8327. this.nextLoadPosition = frag.start + frag.duration;
  8328. }
  8329. this.state = State.FRAG_LOADING;
  8330. // Load key before streaming fragment data
  8331. const dataOnProgress = this.config.progressive;
  8332. let result;
  8333. if (dataOnProgress && keyLoadingPromise) {
  8334. result = keyLoadingPromise.then(keyLoadedData => {
  8335. if (!keyLoadedData || this.fragContextChanged(keyLoadedData == null ? void 0 : keyLoadedData.frag)) {
  8336. return null;
  8337. }
  8338. return this.fragmentLoader.load(frag, progressCallback);
  8339. }).catch(error => this.handleFragLoadError(error));
  8340. } else {
  8341. // load unencrypted fragment data with progress event,
  8342. // or handle fragment result after key and fragment are finished loading
  8343. result = Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : undefined), keyLoadingPromise]).then(([fragLoadedData]) => {
  8344. if (!dataOnProgress && fragLoadedData && progressCallback) {
  8345. progressCallback(fragLoadedData);
  8346. }
  8347. return fragLoadedData;
  8348. }).catch(error => this.handleFragLoadError(error));
  8349. }
  8350. this.hls.trigger(Events.FRAG_LOADING, {
  8351. frag,
  8352. targetBufferTime
  8353. });
  8354. if (this.fragCurrent === null) {
  8355. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING`));
  8356. }
  8357. return result;
  8358. }
  8359. doFragPartsLoad(frag, fromPart, level, progressCallback) {
  8360. return new Promise((resolve, reject) => {
  8361. var _level$details;
  8362. const partsLoaded = [];
  8363. const initialPartList = (_level$details = level.details) == null ? void 0 : _level$details.partList;
  8364. const loadPart = part => {
  8365. this.fragmentLoader.loadPart(frag, part, progressCallback).then(partLoadedData => {
  8366. partsLoaded[part.index] = partLoadedData;
  8367. const loadedPart = partLoadedData.part;
  8368. this.hls.trigger(Events.FRAG_LOADED, partLoadedData);
  8369. const nextPart = getPartWith(level.details, frag.sn, part.index + 1) || findPart(initialPartList, frag.sn, part.index + 1);
  8370. if (nextPart) {
  8371. loadPart(nextPart);
  8372. } else {
  8373. return resolve({
  8374. frag,
  8375. part: loadedPart,
  8376. partsLoaded
  8377. });
  8378. }
  8379. }).catch(reject);
  8380. };
  8381. loadPart(fromPart);
  8382. });
  8383. }
  8384. handleFragLoadError(error) {
  8385. if ('data' in error) {
  8386. const data = error.data;
  8387. if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) {
  8388. this.handleFragLoadAborted(data.frag, data.part);
  8389. } else {
  8390. this.hls.trigger(Events.ERROR, data);
  8391. }
  8392. } else {
  8393. this.hls.trigger(Events.ERROR, {
  8394. type: ErrorTypes.OTHER_ERROR,
  8395. details: ErrorDetails.INTERNAL_EXCEPTION,
  8396. err: error,
  8397. error,
  8398. fatal: true
  8399. });
  8400. }
  8401. return null;
  8402. }
  8403. _handleTransmuxerFlush(chunkMeta) {
  8404. const context = this.getCurrentContext(chunkMeta);
  8405. if (!context || this.state !== State.PARSING) {
  8406. if (!this.fragCurrent && this.state !== State.STOPPED && this.state !== State.ERROR) {
  8407. this.state = State.IDLE;
  8408. }
  8409. return;
  8410. }
  8411. const {
  8412. frag,
  8413. part,
  8414. level
  8415. } = context;
  8416. const now = self.performance.now();
  8417. frag.stats.parsing.end = now;
  8418. if (part) {
  8419. part.stats.parsing.end = now;
  8420. }
  8421. // See if part loading should be disabled/enabled based on buffer and playback position.
  8422. const levelDetails = this.getLevelDetails();
  8423. const loadingPartsAtEdge = levelDetails && frag.sn > levelDetails.endSN;
  8424. const shouldLoadParts = loadingPartsAtEdge || this.shouldLoadParts(levelDetails, frag.end);
  8425. if (shouldLoadParts !== this.loadingParts) {
  8426. this.log(`LL-Part loading ${shouldLoadParts ? 'ON' : 'OFF'} after parsing segment ending @${frag.end.toFixed(2)}`);
  8427. this.loadingParts = shouldLoadParts;
  8428. }
  8429. this.updateLevelTiming(frag, part, level, chunkMeta.partial);
  8430. }
  8431. shouldLoadParts(details, bufferEnd) {
  8432. if (this.config.lowLatencyMode) {
  8433. if (!details) {
  8434. return this.loadingParts;
  8435. }
  8436. if (details != null && details.partList) {
  8437. var _details$fragmentHint;
  8438. // Buffer must be ahead of first part + duration of parts after last segment
  8439. // and playback must be at or past segment adjacent to part list
  8440. const firstPart = details.partList[0];
  8441. const safePartStart = firstPart.end + (((_details$fragmentHint = details.fragmentHint) == null ? void 0 : _details$fragmentHint.duration) || 0);
  8442. if (bufferEnd >= safePartStart) {
  8443. var _this$media;
  8444. const playhead = this.hls.hasEnoughToStart ? ((_this$media = this.media) == null ? void 0 : _this$media.currentTime) || this.lastCurrentTime : this.getLoadPosition();
  8445. if (playhead > firstPart.start - firstPart.fragment.duration) {
  8446. return true;
  8447. }
  8448. }
  8449. }
  8450. }
  8451. return false;
  8452. }
  8453. getCurrentContext(chunkMeta) {
  8454. const {
  8455. levels,
  8456. fragCurrent
  8457. } = this;
  8458. const {
  8459. level: levelIndex,
  8460. sn,
  8461. part: partIndex
  8462. } = chunkMeta;
  8463. if (!(levels != null && levels[levelIndex])) {
  8464. this.warn(`Levels object was unset while buffering fragment ${sn} of ${this.playlistLabel()} ${levelIndex}. The current chunk will not be buffered.`);
  8465. return null;
  8466. }
  8467. const level = levels[levelIndex];
  8468. const levelDetails = level.details;
  8469. const part = partIndex > -1 ? getPartWith(levelDetails, sn, partIndex) : null;
  8470. const frag = part ? part.fragment : getFragmentWithSN(levelDetails, sn, fragCurrent);
  8471. if (!frag) {
  8472. return null;
  8473. }
  8474. if (fragCurrent && fragCurrent !== frag) {
  8475. frag.stats = fragCurrent.stats;
  8476. }
  8477. return {
  8478. frag,
  8479. part,
  8480. level
  8481. };
  8482. }
  8483. bufferFragmentData(data, frag, part, chunkMeta, noBacktracking) {
  8484. var _buffer;
  8485. if (!data || this.state !== State.PARSING) {
  8486. return;
  8487. }
  8488. const {
  8489. data1,
  8490. data2
  8491. } = data;
  8492. let buffer = data1;
  8493. if (data1 && data2) {
  8494. // Combine the moof + mdat so that we buffer with a single append
  8495. buffer = appendUint8Array(data1, data2);
  8496. }
  8497. if (!((_buffer = buffer) != null && _buffer.length)) {
  8498. return;
  8499. }
  8500. const offsetTimestamp = this.initPTS[frag.cc];
  8501. const offset = offsetTimestamp ? -offsetTimestamp.baseTime / offsetTimestamp.timescale : undefined;
  8502. const segment = {
  8503. type: data.type,
  8504. frag,
  8505. part,
  8506. chunkMeta,
  8507. offset,
  8508. parent: frag.type,
  8509. data: buffer
  8510. };
  8511. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  8512. if (data.dropped && data.independent && !part) {
  8513. if (noBacktracking) {
  8514. return;
  8515. }
  8516. // Clear buffer so that we reload previous segments sequentially if required
  8517. this.flushBufferGap(frag);
  8518. }
  8519. }
  8520. flushBufferGap(frag) {
  8521. const media = this.media;
  8522. if (!media) {
  8523. return;
  8524. }
  8525. // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed
  8526. if (!BufferHelper.isBuffered(media, media.currentTime)) {
  8527. this.flushMainBuffer(0, frag.start);
  8528. return;
  8529. }
  8530. // Remove back-buffer without interrupting playback to allow back tracking
  8531. const currentTime = media.currentTime;
  8532. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  8533. const fragDuration = frag.duration;
  8534. const segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
  8535. const start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
  8536. if (frag.start - start > segmentFraction) {
  8537. this.flushMainBuffer(start, frag.start);
  8538. }
  8539. }
  8540. getFwdBufferInfo(bufferable, type) {
  8541. var _this$media2;
  8542. const pos = this.getLoadPosition();
  8543. if (!isFiniteNumber(pos)) {
  8544. return null;
  8545. }
  8546. const backwardSeek = this.lastCurrentTime > pos;
  8547. const maxBufferHole = backwardSeek || (_this$media2 = this.media) != null && _this$media2.paused ? 0 : this.config.maxBufferHole;
  8548. return this.getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole);
  8549. }
  8550. getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole) {
  8551. const bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);
  8552. // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos
  8553. if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {
  8554. const bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
  8555. if (bufferedFragAtPos && (bufferInfo.nextStart <= bufferedFragAtPos.end || bufferedFragAtPos.gap)) {
  8556. const gapDuration = Math.max(Math.min(bufferInfo.nextStart, bufferedFragAtPos.end) - pos, maxBufferHole);
  8557. return BufferHelper.bufferInfo(bufferable, pos, gapDuration);
  8558. }
  8559. }
  8560. return bufferInfo;
  8561. }
  8562. getMaxBufferLength(levelBitrate) {
  8563. const {
  8564. config
  8565. } = this;
  8566. let maxBufLen;
  8567. if (levelBitrate) {
  8568. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  8569. } else {
  8570. maxBufLen = config.maxBufferLength;
  8571. }
  8572. return Math.min(maxBufLen, config.maxMaxBufferLength);
  8573. }
  8574. reduceMaxBufferLength(threshold, fragDuration) {
  8575. const config = this.config;
  8576. const minLength = Math.max(Math.min(threshold - fragDuration, config.maxBufferLength), fragDuration);
  8577. const reducedLength = Math.max(threshold - fragDuration * 3, config.maxMaxBufferLength / 2, minLength);
  8578. if (reducedLength >= minLength) {
  8579. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  8580. config.maxMaxBufferLength = reducedLength;
  8581. this.warn(`Reduce max buffer length to ${reducedLength}s`);
  8582. return true;
  8583. }
  8584. return false;
  8585. }
  8586. getAppendedFrag(position, playlistType = PlaylistLevelType.MAIN) {
  8587. var _this$fragmentTracker;
  8588. const fragOrPart = (_this$fragmentTracker = this.fragmentTracker) == null ? void 0 : _this$fragmentTracker.getAppendedFrag(position, playlistType);
  8589. if (fragOrPart && 'fragment' in fragOrPart) {
  8590. return fragOrPart.fragment;
  8591. }
  8592. return fragOrPart;
  8593. }
  8594. getNextFragment(pos, levelDetails) {
  8595. const fragments = levelDetails.fragments;
  8596. const fragLen = fragments.length;
  8597. if (!fragLen) {
  8598. return null;
  8599. }
  8600. // find fragment index, contiguous with end of buffer position
  8601. const {
  8602. config
  8603. } = this;
  8604. const start = fragments[0].start;
  8605. const canLoadParts = config.lowLatencyMode && !!levelDetails.partList;
  8606. let frag = null;
  8607. if (levelDetails.live) {
  8608. const initialLiveManifestSize = config.initialLiveManifestSize;
  8609. if (fragLen < initialLiveManifestSize) {
  8610. this.warn(`Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`);
  8611. return null;
  8612. }
  8613. // The real fragment start times for a live stream are only known after the PTS range for that level is known.
  8614. // In order to discover the range, we load the best matching fragment for that level and demux it.
  8615. // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that
  8616. // we get the fragment matching that start time
  8617. if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1 || pos < start) {
  8618. var _frag;
  8619. if (canLoadParts && !this.loadingParts) {
  8620. this.log(`LL-Part loading ON for initial live fragment`);
  8621. this.loadingParts = true;
  8622. }
  8623. frag = this.getInitialLiveFragment(levelDetails);
  8624. const mainStart = this.hls.startPosition;
  8625. const liveSyncPosition = this.hls.liveSyncPosition;
  8626. const startPosition = frag ? (mainStart !== -1 && mainStart >= start ? mainStart : liveSyncPosition) || frag.start : pos;
  8627. 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}`);
  8628. this.startPosition = this.nextLoadPosition = startPosition;
  8629. }
  8630. } else if (pos <= start) {
  8631. // VoD playlist: if loadPosition before start of playlist, load first fragment
  8632. frag = fragments[0];
  8633. }
  8634. // If we haven't run into any special cases already, just load the fragment most closely matching the requested position
  8635. if (!frag) {
  8636. const end = this.loadingParts ? levelDetails.partEnd : levelDetails.fragmentEnd;
  8637. frag = this.getFragmentAtPosition(pos, end, levelDetails);
  8638. }
  8639. let programFrag = this.filterReplacedPrimary(frag, levelDetails);
  8640. if (!programFrag && frag) {
  8641. const curSNIdx = frag.sn - levelDetails.startSN;
  8642. programFrag = this.filterReplacedPrimary(fragments[curSNIdx + 1] || null, levelDetails);
  8643. }
  8644. return this.mapToInitFragWhenRequired(programFrag);
  8645. }
  8646. isLoopLoading(frag, targetBufferTime) {
  8647. const trackerState = this.fragmentTracker.getState(frag);
  8648. return (trackerState === FragmentState.OK || trackerState === FragmentState.PARTIAL && !!frag.gap) && this.nextLoadPosition > targetBufferTime;
  8649. }
  8650. getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, playlistType, maxBufLen) {
  8651. let nextFragment = null;
  8652. if (frag.gap) {
  8653. nextFragment = this.getNextFragment(this.nextLoadPosition, levelDetails);
  8654. if (nextFragment && !nextFragment.gap && bufferInfo.nextStart) {
  8655. // Media buffered after GAP tags should not make the next buffer timerange exceed forward buffer length
  8656. const nextbufferInfo = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, bufferInfo.nextStart, playlistType, 0);
  8657. if (nextbufferInfo !== null && bufferInfo.len + nextbufferInfo.len >= maxBufLen) {
  8658. // Returning here might result in not finding an audio and video candiate to skip to
  8659. const sn = nextFragment.sn;
  8660. if (this.loopSn !== sn) {
  8661. this.log(`buffer full after gaps in "${playlistType}" playlist starting at sn: ${sn}`);
  8662. this.loopSn = sn;
  8663. }
  8664. return null;
  8665. }
  8666. }
  8667. }
  8668. this.loopSn = undefined;
  8669. return nextFragment;
  8670. }
  8671. get primaryPrefetch() {
  8672. if (interstitialsEnabled(this.hls.config)) ;
  8673. return false;
  8674. }
  8675. filterReplacedPrimary(frag, details) {
  8676. if (!frag) {
  8677. return frag;
  8678. }
  8679. if (interstitialsEnabled(this.hls.config)) ;
  8680. return frag;
  8681. }
  8682. mapToInitFragWhenRequired(frag) {
  8683. // If an initSegment is present, it must be buffered first
  8684. if (frag != null && frag.initSegment && !(frag != null && frag.initSegment.data) && !this.bitrateTest) {
  8685. return frag.initSegment;
  8686. }
  8687. return frag;
  8688. }
  8689. getNextPart(partList, frag, targetBufferTime) {
  8690. let nextPart = -1;
  8691. let contiguous = false;
  8692. let independentAttrOmitted = true;
  8693. for (let i = 0, len = partList.length; i < len; i++) {
  8694. const part = partList[i];
  8695. independentAttrOmitted = independentAttrOmitted && !part.independent;
  8696. if (nextPart > -1 && targetBufferTime < part.start) {
  8697. break;
  8698. }
  8699. const loaded = part.loaded;
  8700. if (loaded) {
  8701. nextPart = -1;
  8702. } else if ((contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
  8703. nextPart = i;
  8704. }
  8705. contiguous = loaded;
  8706. }
  8707. return nextPart;
  8708. }
  8709. loadedEndOfParts(partList, targetBufferTime) {
  8710. const lastPart = partList[partList.length - 1];
  8711. return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
  8712. }
  8713. /*
  8714. This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
  8715. "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
  8716. start and end times for each fragment in the playlist (after which this method will not need to be called).
  8717. */
  8718. getInitialLiveFragment(levelDetails) {
  8719. const fragments = levelDetails.fragments;
  8720. const fragPrevious = this.fragPrevious;
  8721. let frag = null;
  8722. if (fragPrevious) {
  8723. if (levelDetails.hasProgramDateTime) {
  8724. // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding
  8725. this.log(`Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`);
  8726. frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
  8727. }
  8728. if (!frag) {
  8729. // SN does not need to be accurate between renditions, but depending on the packaging it may be so.
  8730. const targetSN = fragPrevious.sn + 1;
  8731. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  8732. const fragNext = fragments[targetSN - levelDetails.startSN];
  8733. // Ensure that we're staying within the continuity range, since PTS resets upon a new range
  8734. if (fragPrevious.cc === fragNext.cc) {
  8735. frag = fragNext;
  8736. this.log(`Live playlist, switching playlist, load frag with next SN: ${frag.sn}`);
  8737. }
  8738. }
  8739. // It's important to stay within the continuity range if available; otherwise the fragments in the playlist
  8740. // will have the wrong start times
  8741. if (!frag) {
  8742. frag = findNearestWithCC(levelDetails, fragPrevious.cc, fragPrevious.end);
  8743. if (frag) {
  8744. this.log(`Live playlist, switching playlist, load frag with same CC: ${frag.sn}`);
  8745. }
  8746. }
  8747. }
  8748. } else {
  8749. // Find a new start fragment when fragPrevious is null
  8750. const liveStart = this.hls.liveSyncPosition;
  8751. if (liveStart !== null) {
  8752. frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
  8753. }
  8754. }
  8755. return frag;
  8756. }
  8757. /*
  8758. This method finds the best matching fragment given the provided position.
  8759. */
  8760. getFragmentAtPosition(bufferEnd, end, levelDetails) {
  8761. const {
  8762. config
  8763. } = this;
  8764. let {
  8765. fragPrevious
  8766. } = this;
  8767. let {
  8768. fragments,
  8769. endSN
  8770. } = levelDetails;
  8771. const {
  8772. fragmentHint
  8773. } = levelDetails;
  8774. const {
  8775. maxFragLookUpTolerance
  8776. } = config;
  8777. const partList = levelDetails.partList;
  8778. const loadingParts = !!(this.loadingParts && partList != null && partList.length && fragmentHint);
  8779. if (loadingParts && fragmentHint && !this.bitrateTest && partList[partList.length - 1].fragment.sn === fragmentHint.sn) {
  8780. // Include incomplete fragment with parts at end
  8781. fragments = fragments.concat(fragmentHint);
  8782. endSN = fragmentHint.sn;
  8783. }
  8784. let frag;
  8785. if (bufferEnd < end) {
  8786. var _this$media3;
  8787. const backwardSeek = bufferEnd < this.lastCurrentTime;
  8788. const lookupTolerance = backwardSeek || bufferEnd > end - maxFragLookUpTolerance || (_this$media3 = this.media) != null && _this$media3.paused || !this.startFragRequested ? 0 : maxFragLookUpTolerance;
  8789. // Remove the tolerance if it would put the bufferEnd past the actual end of stream
  8790. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  8791. frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);
  8792. } else {
  8793. // reach end of playlist
  8794. frag = fragments[fragments.length - 1];
  8795. }
  8796. if (frag) {
  8797. const curSNIdx = frag.sn - levelDetails.startSN;
  8798. // Move fragPrevious forward to support forcing the next fragment to load
  8799. // when the buffer catches up to a previously buffered range.
  8800. const fragState = this.fragmentTracker.getState(frag);
  8801. if (fragState === FragmentState.OK || fragState === FragmentState.PARTIAL && frag.gap) {
  8802. fragPrevious = frag;
  8803. }
  8804. if (fragPrevious && frag.sn === fragPrevious.sn && (!loadingParts || partList[0].fragment.sn > frag.sn || !levelDetails.live && !loadingParts)) {
  8805. // Force the next fragment to load if the previous one was already selected. This can occasionally happen with
  8806. // non-uniform fragment durations
  8807. const sameLevel = fragPrevious && frag.level === fragPrevious.level;
  8808. if (sameLevel) {
  8809. const nextFrag = fragments[curSNIdx + 1];
  8810. if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== FragmentState.OK) {
  8811. frag = nextFrag;
  8812. } else {
  8813. frag = null;
  8814. }
  8815. }
  8816. }
  8817. }
  8818. return frag;
  8819. }
  8820. alignPlaylists(details, previousDetails, switchDetails) {
  8821. // TODO: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,
  8822. // this could all go in level-helper mergeDetails()
  8823. const length = details.fragments.length;
  8824. if (!length) {
  8825. this.warn(`No fragments in live playlist`);
  8826. return 0;
  8827. }
  8828. const slidingStart = details.fragmentStart;
  8829. const firstLevelLoad = !previousDetails;
  8830. const aligned = details.alignedSliding && isFiniteNumber(slidingStart);
  8831. if (firstLevelLoad || !aligned && !slidingStart) {
  8832. alignStream(switchDetails, details);
  8833. const alignedSlidingStart = details.fragmentStart;
  8834. this.log(`Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${previousDetails ? previousDetails.startSN : 'na'}->${details.startSN} fragments: ${length}`);
  8835. return alignedSlidingStart;
  8836. }
  8837. return slidingStart;
  8838. }
  8839. waitForCdnTuneIn(details) {
  8840. // Wait for Low-Latency CDN Tune-in to get an updated playlist
  8841. const advancePartLimit = 3;
  8842. return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
  8843. }
  8844. setStartPosition(details, sliding) {
  8845. // compute start position if set to -1. use it straight away if value is defined
  8846. let startPosition = this.startPosition;
  8847. if (startPosition < sliding) {
  8848. startPosition = -1;
  8849. }
  8850. const timelineOffset = this.timelineOffset;
  8851. if (startPosition === -1) {
  8852. // Use Playlist EXT-X-START:TIME-OFFSET when set
  8853. // Prioritize Multivariant Playlist offset so that main, audio, and subtitle stream-controller start times match
  8854. const offsetInMultivariantPlaylist = this.startTimeOffset !== null;
  8855. const startTimeOffset = offsetInMultivariantPlaylist ? this.startTimeOffset : details.startTimeOffset;
  8856. if (startTimeOffset !== null && isFiniteNumber(startTimeOffset)) {
  8857. startPosition = sliding + startTimeOffset;
  8858. if (startTimeOffset < 0) {
  8859. startPosition += details.edge;
  8860. }
  8861. startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
  8862. this.log(`Setting startPosition to ${startPosition} for start time offset ${startTimeOffset} found in ${offsetInMultivariantPlaylist ? 'multivariant' : 'media'} playlist`);
  8863. this.startPosition = startPosition;
  8864. } else if (details.live) {
  8865. // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has
  8866. // not been specified via the config or an as an argument to startLoad (#3736).
  8867. startPosition = this.hls.liveSyncPosition || sliding;
  8868. this.log(`Setting startPosition to -1 to start at live edge ${startPosition}`);
  8869. this.startPosition = -1;
  8870. } else {
  8871. this.log(`setting startPosition to 0 by default`);
  8872. this.startPosition = startPosition = 0;
  8873. }
  8874. this.lastCurrentTime = startPosition + timelineOffset;
  8875. }
  8876. this.nextLoadPosition = startPosition + timelineOffset;
  8877. }
  8878. getLoadPosition() {
  8879. var _this$hls;
  8880. const {
  8881. media
  8882. } = this;
  8883. // if we have not yet loaded any fragment, start loading from start position
  8884. let pos = 0;
  8885. if ((_this$hls = this.hls) != null && _this$hls.hasEnoughToStart && media) {
  8886. pos = media.currentTime;
  8887. } else if (this.nextLoadPosition >= 0) {
  8888. pos = this.nextLoadPosition;
  8889. }
  8890. return pos;
  8891. }
  8892. handleFragLoadAborted(frag, part) {
  8893. if (this.transmuxer && frag.type === this.playlistType && isMediaFragment(frag) && frag.stats.aborted) {
  8894. this.log(`Fragment ${frag.sn}${part ? ' part ' + part.index : ''} of ${this.playlistLabel()} ${frag.level} was aborted`);
  8895. this.resetFragmentLoading(frag);
  8896. }
  8897. }
  8898. resetFragmentLoading(frag) {
  8899. if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) {
  8900. this.state = State.IDLE;
  8901. }
  8902. }
  8903. onFragmentOrKeyLoadError(filterType, data) {
  8904. if (data.chunkMeta && !data.frag) {
  8905. const context = this.getCurrentContext(data.chunkMeta);
  8906. if (context) {
  8907. data.frag = context.frag;
  8908. }
  8909. }
  8910. const frag = data.frag;
  8911. // Handle frag error related to caller's filterType
  8912. if (!frag || frag.type !== filterType || !this.levels) {
  8913. return;
  8914. }
  8915. if (this.fragContextChanged(frag)) {
  8916. var _this$fragCurrent;
  8917. this.warn(`Frag load error must match current frag to retry ${frag.url} > ${(_this$fragCurrent = this.fragCurrent) == null ? void 0 : _this$fragCurrent.url}`);
  8918. return;
  8919. }
  8920. const gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;
  8921. if (gapTagEncountered) {
  8922. this.fragmentTracker.fragBuffered(frag, true);
  8923. }
  8924. // keep retrying until the limit will be reached
  8925. const errorAction = data.errorAction;
  8926. const {
  8927. action,
  8928. flags,
  8929. retryCount = 0,
  8930. retryConfig
  8931. } = errorAction || {};
  8932. const couldRetry = !!errorAction && !!retryConfig;
  8933. const retry = couldRetry && action === NetworkErrorAction.RetryRequest;
  8934. const noAlternate = couldRetry && !errorAction.resolved && flags === ErrorActionFlags.MoveAllAlternatesMatchingHost;
  8935. if (!retry && noAlternate && isMediaFragment(frag) && !frag.endList) {
  8936. this.resetFragmentErrors(filterType);
  8937. this.treatAsGap(frag);
  8938. errorAction.resolved = true;
  8939. } else if ((retry || noAlternate) && retryCount < retryConfig.maxNumRetry) {
  8940. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  8941. const delay = getRetryDelay(retryConfig, retryCount);
  8942. this.warn(`Fragment ${frag.sn} of ${filterType} ${frag.level} errored with ${data.details}, retrying loading ${retryCount + 1}/${retryConfig.maxNumRetry} in ${delay}ms`);
  8943. errorAction.resolved = true;
  8944. this.retryDate = self.performance.now() + delay;
  8945. this.state = State.FRAG_LOADING_WAITING_RETRY;
  8946. } else if (retryConfig && errorAction) {
  8947. this.resetFragmentErrors(filterType);
  8948. if (retryCount < retryConfig.maxNumRetry) {
  8949. // Network retry is skipped when level switch is preferred
  8950. if (!gapTagEncountered && action !== NetworkErrorAction.RemoveAlternatePermanently) {
  8951. errorAction.resolved = true;
  8952. }
  8953. } else {
  8954. this.warn(`${data.details} reached or exceeded max retry (${retryCount})`);
  8955. return;
  8956. }
  8957. } else if (action === NetworkErrorAction.SendAlternateToPenaltyBox) {
  8958. this.state = State.WAITING_LEVEL;
  8959. } else {
  8960. this.state = State.ERROR;
  8961. }
  8962. // Perform next async tick sooner to speed up error action resolution
  8963. this.tickImmediate();
  8964. }
  8965. reduceLengthAndFlushBuffer(data) {
  8966. // if in appending state
  8967. if (this.state === State.PARSING || this.state === State.PARSED) {
  8968. const frag = data.frag;
  8969. const playlistType = data.parent;
  8970. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  8971. // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  8972. // reduce max buf len if current position is buffered
  8973. const buffered = bufferedInfo && bufferedInfo.len > 0.5;
  8974. if (buffered) {
  8975. this.reduceMaxBufferLength(bufferedInfo.len, (frag == null ? void 0 : frag.duration) || 10);
  8976. }
  8977. const flushBuffer = !buffered;
  8978. if (flushBuffer) {
  8979. // current position is not buffered, but browser is still complaining about buffer full error
  8980. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  8981. // in that case flush the whole audio buffer to recover
  8982. this.warn(`Buffer full error while media.currentTime is not buffered, flush ${playlistType} buffer`);
  8983. }
  8984. if (frag) {
  8985. this.fragmentTracker.removeFragment(frag);
  8986. this.nextLoadPosition = frag.start;
  8987. }
  8988. this.resetLoadingState();
  8989. return flushBuffer;
  8990. }
  8991. return false;
  8992. }
  8993. resetFragmentErrors(filterType) {
  8994. if (filterType === PlaylistLevelType.AUDIO) {
  8995. // Reset current fragment since audio track audio is essential and may not have a fail-over track
  8996. this.fragCurrent = null;
  8997. }
  8998. // Fragment errors that result in a level switch or redundant fail-over
  8999. // should reset the stream controller state to idle
  9000. if (!this.hls.hasEnoughToStart) {
  9001. this.startFragRequested = false;
  9002. }
  9003. if (this.state !== State.STOPPED) {
  9004. this.state = State.IDLE;
  9005. }
  9006. }
  9007. afterBufferFlushed(media, bufferType, playlistType) {
  9008. if (!media) {
  9009. return;
  9010. }
  9011. // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media
  9012. // (so that we will check against video.buffered ranges in case of alt audio track)
  9013. const bufferedTimeRanges = BufferHelper.getBuffered(media);
  9014. this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
  9015. if (this.state === State.ENDED) {
  9016. this.resetLoadingState();
  9017. }
  9018. }
  9019. resetLoadingState() {
  9020. this.log('Reset loading state');
  9021. this.fragCurrent = null;
  9022. this.fragPrevious = null;
  9023. if (this.state !== State.STOPPED) {
  9024. this.state = State.IDLE;
  9025. }
  9026. }
  9027. resetStartWhenNotLoaded(level) {
  9028. // if loadedmetadata is not set, it means that first frag request failed
  9029. // in that case, reset startFragRequested flag
  9030. if (!this.hls.hasEnoughToStart) {
  9031. this.startFragRequested = false;
  9032. const details = level ? level.details : null;
  9033. if (details != null && details.live) {
  9034. // Update the start position and return to IDLE to recover live start
  9035. this.log(`resetting startPosition for live start`);
  9036. this.startPosition = -1;
  9037. this.setStartPosition(details, details.fragmentStart);
  9038. this.resetLoadingState();
  9039. } else {
  9040. this.nextLoadPosition = this.startPosition;
  9041. }
  9042. }
  9043. }
  9044. resetWhenMissingContext(chunkMeta) {
  9045. this.warn(`The loading context changed while buffering fragment ${chunkMeta.sn} of ${this.playlistLabel()} ${chunkMeta.level}. This chunk will not be buffered.`);
  9046. this.removeUnbufferedFrags();
  9047. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  9048. this.resetLoadingState();
  9049. }
  9050. removeUnbufferedFrags(start = 0) {
  9051. this.fragmentTracker.removeFragmentsInRange(start, Infinity, this.playlistType, false, true);
  9052. }
  9053. updateLevelTiming(frag, part, level, partial) {
  9054. const details = level.details;
  9055. if (!details) {
  9056. this.warn('level.details undefined');
  9057. return;
  9058. }
  9059. const parsed = Object.keys(frag.elementaryStreams).reduce((result, type) => {
  9060. const info = frag.elementaryStreams[type];
  9061. if (info) {
  9062. const parsedDuration = info.endPTS - info.startPTS;
  9063. if (parsedDuration <= 0) {
  9064. // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.
  9065. // The new transmuxer will be configured with a time offset matching the next fragment start,
  9066. // preventing the timeline from shifting.
  9067. this.warn(`Could not parse fragment ${frag.sn} ${type} duration reliably (${parsedDuration})`);
  9068. return result || false;
  9069. }
  9070. const drift = partial ? 0 : updateFragPTSDTS(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
  9071. this.hls.trigger(Events.LEVEL_PTS_UPDATED, {
  9072. details,
  9073. level,
  9074. drift,
  9075. type,
  9076. frag,
  9077. start: info.startPTS,
  9078. end: info.endPTS
  9079. });
  9080. return true;
  9081. }
  9082. return result;
  9083. }, false);
  9084. if (!parsed) {
  9085. var _this$transmuxer;
  9086. if (level.fragmentError === 0) {
  9087. // Mark and track the odd empty segment as a gap to avoid reloading
  9088. this.treatAsGap(frag, level);
  9089. }
  9090. if (((_this$transmuxer = this.transmuxer) == null ? void 0 : _this$transmuxer.error) === null) {
  9091. const error = new Error(`Found no media in fragment ${frag.sn} of ${this.playlistLabel()} ${frag.level} resetting transmuxer to fallback to playlist timing`);
  9092. this.warn(error.message);
  9093. this.hls.trigger(Events.ERROR, {
  9094. type: ErrorTypes.MEDIA_ERROR,
  9095. details: ErrorDetails.FRAG_PARSING_ERROR,
  9096. fatal: false,
  9097. error,
  9098. frag,
  9099. reason: `Found no media in msn ${frag.sn} of ${this.playlistLabel()} "${level.url}"`
  9100. });
  9101. if (!this.hls) {
  9102. return;
  9103. }
  9104. this.resetTransmuxer();
  9105. }
  9106. // For this error fallthrough. Marking parsed will allow advancing to next fragment.
  9107. }
  9108. this.state = State.PARSED;
  9109. this.log(`Parsed ${frag.type} sn: ${frag.sn}${part ? ' part: ' + part.index : ''} of ${this.fragInfo(frag, false, part)})`);
  9110. this.hls.trigger(Events.FRAG_PARSED, {
  9111. frag,
  9112. part
  9113. });
  9114. }
  9115. playlistLabel() {
  9116. return this.playlistType === PlaylistLevelType.MAIN ? 'level' : 'track';
  9117. }
  9118. fragInfo(frag, pts = true, part) {
  9119. var _ref, _ref2;
  9120. 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') : ''}`;
  9121. }
  9122. treatAsGap(frag, level) {
  9123. if (level) {
  9124. level.fragmentError++;
  9125. }
  9126. frag.gap = true;
  9127. this.fragmentTracker.removeFragment(frag);
  9128. this.fragmentTracker.fragBuffered(frag, true);
  9129. }
  9130. resetTransmuxer() {
  9131. var _this$transmuxer2;
  9132. (_this$transmuxer2 = this.transmuxer) == null ? void 0 : _this$transmuxer2.reset();
  9133. }
  9134. recoverWorkerError(data) {
  9135. if (data.event === 'demuxerWorker') {
  9136. this.fragmentTracker.removeAllFragments();
  9137. if (this.transmuxer) {
  9138. this.transmuxer.destroy();
  9139. this.transmuxer = null;
  9140. }
  9141. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  9142. this.resetLoadingState();
  9143. }
  9144. }
  9145. set state(nextState) {
  9146. const previousState = this._state;
  9147. if (previousState !== nextState) {
  9148. this._state = nextState;
  9149. this.log(`${previousState}->${nextState}`);
  9150. }
  9151. }
  9152. get state() {
  9153. return this._state;
  9154. }
  9155. }
  9156. function interstitialsEnabled(config) {
  9157. return false;
  9158. }
  9159. class BufferOperationQueue {
  9160. constructor(sourceBufferReference) {
  9161. this.tracks = void 0;
  9162. this.queues = {
  9163. video: [],
  9164. audio: [],
  9165. audiovideo: []
  9166. };
  9167. this.tracks = sourceBufferReference;
  9168. }
  9169. destroy() {
  9170. this.tracks = this.queues = null;
  9171. }
  9172. append(operation, type, pending) {
  9173. if (this.queues === null || this.tracks === null) {
  9174. return;
  9175. }
  9176. const queue = this.queues[type];
  9177. queue.push(operation);
  9178. if (queue.length === 1 && !pending) {
  9179. this.executeNext(type);
  9180. }
  9181. }
  9182. appendBlocker(type) {
  9183. return new Promise(resolve => {
  9184. const operation = {
  9185. label: 'async-blocker',
  9186. execute: resolve,
  9187. onStart: () => {},
  9188. onComplete: () => {},
  9189. onError: () => {}
  9190. };
  9191. this.append(operation, type);
  9192. });
  9193. }
  9194. prependBlocker(type) {
  9195. return new Promise(resolve => {
  9196. if (this.queues) {
  9197. const operation = {
  9198. label: 'async-blocker-prepend',
  9199. execute: resolve,
  9200. onStart: () => {},
  9201. onComplete: () => {},
  9202. onError: () => {}
  9203. };
  9204. this.queues[type].unshift(operation);
  9205. }
  9206. });
  9207. }
  9208. removeBlockers() {
  9209. if (this.queues === null) {
  9210. return;
  9211. }
  9212. [this.queues.video, this.queues.audio, this.queues.audiovideo].forEach(queue => {
  9213. var _queue$;
  9214. const label = (_queue$ = queue[0]) == null ? void 0 : _queue$.label;
  9215. if (label === 'async-blocker' || label === 'async-blocker-prepend') {
  9216. queue[0].execute();
  9217. queue.splice(0, 1);
  9218. }
  9219. });
  9220. }
  9221. unblockAudio(op) {
  9222. if (this.queues === null) {
  9223. return;
  9224. }
  9225. const queue = this.queues.audio;
  9226. if (queue[0] === op) {
  9227. this.shiftAndExecuteNext('audio');
  9228. }
  9229. }
  9230. executeNext(type) {
  9231. if (this.queues === null || this.tracks === null) {
  9232. return;
  9233. }
  9234. const queue = this.queues[type];
  9235. if (queue.length) {
  9236. const operation = queue[0];
  9237. try {
  9238. // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations
  9239. // which do not end with this event must call _onSBUpdateEnd manually
  9240. operation.execute();
  9241. } catch (error) {
  9242. var _this$tracks$type;
  9243. operation.onError(error);
  9244. if (this.queues === null || this.tracks === null) {
  9245. return;
  9246. }
  9247. // Only shift the current operation off, otherwise the updateend handler will do this for us
  9248. const sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  9249. if (!(sb != null && sb.updating)) {
  9250. this.shiftAndExecuteNext(type);
  9251. }
  9252. }
  9253. }
  9254. }
  9255. shiftAndExecuteNext(type) {
  9256. if (this.queues === null) {
  9257. return;
  9258. }
  9259. this.queues[type].shift();
  9260. this.executeNext(type);
  9261. }
  9262. current(type) {
  9263. var _this$queues;
  9264. return ((_this$queues = this.queues) == null ? void 0 : _this$queues[type][0]) || null;
  9265. }
  9266. toString() {
  9267. const {
  9268. queues,
  9269. tracks
  9270. } = this;
  9271. if (queues === null || tracks === null) {
  9272. return `<destroyed>`;
  9273. }
  9274. return `
  9275. ${this.list('video')}
  9276. ${this.list('audio')}
  9277. ${this.list('audiovideo')}}`;
  9278. }
  9279. list(type) {
  9280. var _this$queues2, _this$tracks;
  9281. return (_this$queues2 = this.queues) != null && _this$queues2[type] || (_this$tracks = this.tracks) != null && _this$tracks[type] ? `${type}: (${this.listSbInfo(type)}) ${this.listOps(type)}` : '';
  9282. }
  9283. listSbInfo(type) {
  9284. var _this$tracks2;
  9285. const track = (_this$tracks2 = this.tracks) == null ? void 0 : _this$tracks2[type];
  9286. const sb = track == null ? void 0 : track.buffer;
  9287. if (!sb) {
  9288. return 'none';
  9289. }
  9290. return `SourceBuffer${sb.updating ? ' updating' : ''}${track.ended ? ' ended' : ''}${track.ending ? ' ending' : ''}`;
  9291. }
  9292. listOps(type) {
  9293. var _this$queues3;
  9294. return ((_this$queues3 = this.queues) == null ? void 0 : _this$queues3[type].map(op => op.label).join(', ')) || '';
  9295. }
  9296. }
  9297. const VIDEO_CODEC_PROFILE_REPLACE = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;
  9298. const TRACK_REMOVED_ERROR_NAME = 'HlsJsTrackRemovedError';
  9299. class HlsJsTrackRemovedError extends Error {
  9300. constructor(message) {
  9301. super(message);
  9302. this.name = TRACK_REMOVED_ERROR_NAME;
  9303. }
  9304. }
  9305. class BufferController extends Logger {
  9306. constructor(hls, fragmentTracker) {
  9307. super('buffer-controller', hls.logger);
  9308. this.hls = void 0;
  9309. this.fragmentTracker = void 0;
  9310. // The level details used to determine duration, target-duration and live
  9311. this.details = null;
  9312. // cache the self generated object url to detect hijack of video tag
  9313. this._objectUrl = null;
  9314. // A queue of buffer operations which require the SourceBuffer to not be updating upon execution
  9315. this.operationQueue = null;
  9316. // The total number track codecs expected before any sourceBuffers are created (2: audio and video or 1: audiovideo | audio | video)
  9317. this.bufferCodecEventsTotal = 0;
  9318. // A reference to the attached media element
  9319. this.media = null;
  9320. // A reference to the active media source
  9321. this.mediaSource = null;
  9322. // Last MP3 audio chunk appended
  9323. this.lastMpegAudioChunk = null;
  9324. // Audio fragment blocked from appending until corresponding video appends or context changes
  9325. this.blockedAudioAppend = null;
  9326. // Keep track of video append position for unblocking audio
  9327. this.lastVideoAppendEnd = 0;
  9328. // Whether or not to use ManagedMediaSource API and append source element to media element.
  9329. this.appendSource = void 0;
  9330. // Transferred MediaSource information used to detmerine if duration end endstream may be appended
  9331. this.transferData = void 0;
  9332. // Directives used to override default MediaSource handling
  9333. this.overrides = void 0;
  9334. // Error counters
  9335. this.appendErrors = {
  9336. audio: 0,
  9337. video: 0,
  9338. audiovideo: 0
  9339. };
  9340. // Record of required or created buffers by type. SourceBuffer is stored in Track.buffer once created.
  9341. this.tracks = {};
  9342. // Array of SourceBuffer type and SourceBuffer (or null). One entry per TrackSet in this.tracks.
  9343. this.sourceBuffers = [[null, null], [null, null]];
  9344. this._onEndStreaming = event => {
  9345. var _this$mediaSource;
  9346. if (!this.hls) {
  9347. return;
  9348. }
  9349. if (((_this$mediaSource = this.mediaSource) == null ? void 0 : _this$mediaSource.readyState) !== 'open') {
  9350. return;
  9351. }
  9352. this.hls.pauseBuffering();
  9353. };
  9354. this._onStartStreaming = event => {
  9355. if (!this.hls) {
  9356. return;
  9357. }
  9358. this.hls.resumeBuffering();
  9359. };
  9360. // Keep as arrow functions so that we can directly reference these functions directly as event listeners
  9361. this._onMediaSourceOpen = e => {
  9362. const {
  9363. media,
  9364. mediaSource
  9365. } = this;
  9366. if (e) {
  9367. this.log('Media source opened');
  9368. }
  9369. if (!media || !mediaSource) {
  9370. return;
  9371. }
  9372. // once received, don't listen anymore to sourceopen event
  9373. mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
  9374. media.removeEventListener('emptied', this._onMediaEmptied);
  9375. this.updateDuration();
  9376. this.hls.trigger(Events.MEDIA_ATTACHED, {
  9377. media,
  9378. mediaSource: mediaSource
  9379. });
  9380. if (this.mediaSource !== null) {
  9381. this.checkPendingTracks();
  9382. }
  9383. };
  9384. this._onMediaSourceClose = () => {
  9385. this.log('Media source closed');
  9386. };
  9387. this._onMediaSourceEnded = () => {
  9388. this.log('Media source ended');
  9389. };
  9390. this._onMediaEmptied = () => {
  9391. const {
  9392. mediaSrc,
  9393. _objectUrl
  9394. } = this;
  9395. if (mediaSrc !== _objectUrl) {
  9396. this.error(`Media element src was set while attaching MediaSource (${_objectUrl} > ${mediaSrc})`);
  9397. }
  9398. };
  9399. this.hls = hls;
  9400. this.fragmentTracker = fragmentTracker;
  9401. this.appendSource = isManagedMediaSource(getMediaSource(hls.config.preferManagedMediaSource));
  9402. this.initTracks();
  9403. this.registerListeners();
  9404. }
  9405. hasSourceTypes() {
  9406. return Object.keys(this.tracks).length > 0;
  9407. }
  9408. destroy() {
  9409. this.unregisterListeners();
  9410. this.details = null;
  9411. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  9412. this.transferData = this.overrides = undefined;
  9413. if (this.operationQueue) {
  9414. this.operationQueue.destroy();
  9415. this.operationQueue = null;
  9416. }
  9417. // @ts-ignore
  9418. this.hls = this.fragmentTracker = null;
  9419. // @ts-ignore
  9420. this._onMediaSourceOpen = this._onMediaSourceClose = null;
  9421. // @ts-ignore
  9422. this._onMediaSourceEnded = null;
  9423. // @ts-ignore
  9424. this._onStartStreaming = this._onEndStreaming = null;
  9425. }
  9426. registerListeners() {
  9427. const {
  9428. hls
  9429. } = this;
  9430. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  9431. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  9432. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  9433. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  9434. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  9435. hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  9436. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  9437. hls.on(Events.BUFFER_EOS, this.onBufferEos, this);
  9438. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  9439. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  9440. hls.on(Events.FRAG_PARSED, this.onFragParsed, this);
  9441. hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);
  9442. hls.on(Events.ERROR, this.onError, this);
  9443. }
  9444. unregisterListeners() {
  9445. const {
  9446. hls
  9447. } = this;
  9448. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  9449. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  9450. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  9451. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  9452. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  9453. hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  9454. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  9455. hls.off(Events.BUFFER_EOS, this.onBufferEos, this);
  9456. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  9457. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  9458. hls.off(Events.FRAG_PARSED, this.onFragParsed, this);
  9459. hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);
  9460. hls.off(Events.ERROR, this.onError, this);
  9461. }
  9462. transferMedia() {
  9463. const {
  9464. media,
  9465. mediaSource
  9466. } = this;
  9467. if (!media) {
  9468. return null;
  9469. }
  9470. const tracks = {};
  9471. if (this.operationQueue) {
  9472. const updating = this.isUpdating();
  9473. if (!updating) {
  9474. this.operationQueue.removeBlockers();
  9475. }
  9476. const queued = this.isQueued();
  9477. if (updating || queued) {
  9478. this.warn(`Transfering MediaSource with${queued ? ' operations in queue' : ''}${updating ? ' updating SourceBuffer(s)' : ''} ${this.operationQueue}`);
  9479. }
  9480. this.operationQueue.destroy();
  9481. }
  9482. const transferData = this.transferData;
  9483. if (!this.sourceBufferCount && transferData && transferData.mediaSource === mediaSource) {
  9484. _extends(tracks, transferData.tracks);
  9485. } else {
  9486. this.sourceBuffers.forEach(tuple => {
  9487. const [type] = tuple;
  9488. if (type) {
  9489. tracks[type] = _extends({}, this.tracks[type]);
  9490. this.removeBuffer(type);
  9491. }
  9492. tuple[0] = tuple[1] = null;
  9493. });
  9494. }
  9495. return {
  9496. media,
  9497. mediaSource,
  9498. tracks
  9499. };
  9500. }
  9501. initTracks() {
  9502. const tracks = {};
  9503. this.sourceBuffers = [[null, null], [null, null]];
  9504. this.tracks = tracks;
  9505. this.resetQueue();
  9506. this.resetAppendErrors();
  9507. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  9508. this.lastVideoAppendEnd = 0;
  9509. }
  9510. onManifestLoading() {
  9511. this.bufferCodecEventsTotal = 0;
  9512. this.details = null;
  9513. }
  9514. onManifestParsed(event, data) {
  9515. var _this$transferData;
  9516. // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
  9517. // sourcebuffers will be created all at once when the expected nb of tracks will be reached
  9518. // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
  9519. // it will contain the expected nb of source buffers, no need to compute it
  9520. let codecEvents = 2;
  9521. if (data.audio && !data.video || !data.altAudio) {
  9522. codecEvents = 1;
  9523. }
  9524. this.bufferCodecEventsTotal = codecEvents;
  9525. this.log(`${codecEvents} bufferCodec event(s) expected.`);
  9526. if ((_this$transferData = this.transferData) != null && _this$transferData.mediaSource && this.sourceBufferCount && codecEvents) {
  9527. this.bufferCreated();
  9528. }
  9529. }
  9530. onMediaAttaching(event, data) {
  9531. const media = this.media = data.media;
  9532. const MediaSource = getMediaSource(this.appendSource);
  9533. this.transferData = this.overrides = undefined;
  9534. if (media && MediaSource) {
  9535. const transferringMedia = !!data.mediaSource;
  9536. if (transferringMedia || data.overrides) {
  9537. this.transferData = data;
  9538. this.overrides = data.overrides;
  9539. }
  9540. const ms = this.mediaSource = data.mediaSource || new MediaSource();
  9541. this.assignMediaSource(ms);
  9542. if (transferringMedia) {
  9543. this._objectUrl = media.src;
  9544. this.attachTransferred();
  9545. } else {
  9546. // cache the locally generated object url
  9547. const objectUrl = this._objectUrl = self.URL.createObjectURL(ms);
  9548. // link video and media Source
  9549. if (this.appendSource) {
  9550. try {
  9551. media.removeAttribute('src');
  9552. // ManagedMediaSource will not open without disableRemotePlayback set to false or source alternatives
  9553. const MMS = self.ManagedMediaSource;
  9554. media.disableRemotePlayback = media.disableRemotePlayback || MMS && ms instanceof MMS;
  9555. removeSourceChildren(media);
  9556. addSource(media, objectUrl);
  9557. media.load();
  9558. } catch (error) {
  9559. media.src = objectUrl;
  9560. }
  9561. } else {
  9562. media.src = objectUrl;
  9563. }
  9564. }
  9565. media.addEventListener('emptied', this._onMediaEmptied);
  9566. }
  9567. }
  9568. assignMediaSource(ms) {
  9569. var _this$transferData2, _ms$constructor;
  9570. 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}`);
  9571. // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound
  9572. ms.addEventListener('sourceopen', this._onMediaSourceOpen);
  9573. ms.addEventListener('sourceended', this._onMediaSourceEnded);
  9574. ms.addEventListener('sourceclose', this._onMediaSourceClose);
  9575. if (this.appendSource) {
  9576. ms.addEventListener('startstreaming', this._onStartStreaming);
  9577. ms.addEventListener('endstreaming', this._onEndStreaming);
  9578. }
  9579. }
  9580. attachTransferred() {
  9581. const media = this.media;
  9582. const data = this.transferData;
  9583. if (!data || !media) {
  9584. return;
  9585. }
  9586. const requiredTracks = this.tracks;
  9587. const transferredTracks = data.tracks;
  9588. const trackNames = transferredTracks ? Object.keys(transferredTracks) : null;
  9589. const trackCount = trackNames ? trackNames.length : 0;
  9590. const mediaSourceOpenCallback = () => {
  9591. if (this.media && this.mediaSourceOpenOrEnded) {
  9592. this._onMediaSourceOpen();
  9593. }
  9594. };
  9595. if (transferredTracks && trackNames && trackCount) {
  9596. if (!this.tracksReady) {
  9597. // Wait for CODECS event(s)
  9598. this.hls.config.startFragPrefetch = true;
  9599. this.log(`attachTransferred: waiting for SourceBuffer track info`);
  9600. return;
  9601. }
  9602. this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
  9603. required tracks: ${stringify(requiredTracks, (key, value) => key === 'initSegment' ? undefined : value)};
  9604. transfer tracks: ${stringify(transferredTracks, (key, value) => key === 'initSegment' ? undefined : value)}}`);
  9605. if (!isCompatibleTrackChange(transferredTracks, requiredTracks)) {
  9606. // destroy attaching media source
  9607. data.mediaSource = null;
  9608. data.tracks = undefined;
  9609. const currentTime = media.currentTime;
  9610. const details = this.details;
  9611. const startTime = Math.max(currentTime, (details == null ? void 0 : details.fragments[0].start) || 0);
  9612. if (startTime - currentTime > 1) {
  9613. this.log(`attachTransferred: waiting for playback to reach new tracks start time ${currentTime} -> ${startTime}`);
  9614. return;
  9615. }
  9616. this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(transferredTracks)}"->"${Object.keys(requiredTracks)}") start time: ${startTime} currentTime: ${currentTime}`);
  9617. this.onMediaDetaching(Events.MEDIA_DETACHING, {});
  9618. this.onMediaAttaching(Events.MEDIA_ATTACHING, data);
  9619. media.currentTime = startTime;
  9620. return;
  9621. }
  9622. this.transferData = undefined;
  9623. trackNames.forEach(trackName => {
  9624. const type = trackName;
  9625. const track = transferredTracks[type];
  9626. if (track) {
  9627. const sb = track.buffer;
  9628. if (sb) {
  9629. // Purge fragment tracker of ejected segments for existing buffer
  9630. const fragmentTracker = this.fragmentTracker;
  9631. const playlistType = track.id;
  9632. if (fragmentTracker.hasFragments(playlistType) || fragmentTracker.hasParts(playlistType)) {
  9633. const bufferedTimeRanges = BufferHelper.getBuffered(sb);
  9634. fragmentTracker.detectEvictedFragments(type, bufferedTimeRanges, playlistType, null, true);
  9635. }
  9636. // Transfer SourceBuffer
  9637. const sbIndex = sourceBufferNameToIndex(type);
  9638. const sbTuple = [type, sb];
  9639. this.sourceBuffers[sbIndex] = sbTuple;
  9640. if (sb.updating && this.operationQueue) {
  9641. this.operationQueue.prependBlocker(type);
  9642. }
  9643. this.trackSourceBuffer(type, track);
  9644. }
  9645. }
  9646. });
  9647. mediaSourceOpenCallback();
  9648. this.bufferCreated();
  9649. } else {
  9650. this.log(`attachTransferred: MediaSource w/o SourceBuffers`);
  9651. mediaSourceOpenCallback();
  9652. }
  9653. }
  9654. get mediaSourceOpenOrEnded() {
  9655. var _this$mediaSource2;
  9656. const readyState = (_this$mediaSource2 = this.mediaSource) == null ? void 0 : _this$mediaSource2.readyState;
  9657. return readyState === 'open' || readyState === 'ended';
  9658. }
  9659. onMediaDetaching(event, data) {
  9660. const transferringMedia = !!data.transferMedia;
  9661. this.transferData = this.overrides = undefined;
  9662. const {
  9663. media,
  9664. mediaSource,
  9665. _objectUrl
  9666. } = this;
  9667. if (mediaSource) {
  9668. this.log(`media source ${transferringMedia ? 'transferring' : 'detaching'}`);
  9669. if (transferringMedia) {
  9670. // Detach SourceBuffers without removing from MediaSource
  9671. // and leave `tracks` (required SourceBuffers configuration)
  9672. this.sourceBuffers.forEach(([type]) => {
  9673. if (type) {
  9674. this.removeBuffer(type);
  9675. }
  9676. });
  9677. this.resetQueue();
  9678. } else {
  9679. if (this.mediaSourceOpenOrEnded) {
  9680. const open = mediaSource.readyState === 'open';
  9681. try {
  9682. const sourceBuffers = mediaSource.sourceBuffers;
  9683. for (let i = sourceBuffers.length; i--;) {
  9684. if (open) {
  9685. sourceBuffers[i].abort();
  9686. }
  9687. mediaSource.removeSourceBuffer(sourceBuffers[i]);
  9688. }
  9689. if (open) {
  9690. // endOfStream could trigger exception if any sourcebuffer is in updating state
  9691. // we don't really care about checking sourcebuffer state here,
  9692. // as we are anyway detaching the MediaSource
  9693. // let's just avoid this exception to propagate
  9694. mediaSource.endOfStream();
  9695. }
  9696. } catch (err) {
  9697. this.warn(`onMediaDetaching: ${err.message} while calling endOfStream`);
  9698. }
  9699. }
  9700. // Clean up the SourceBuffers by invoking onBufferReset
  9701. if (this.sourceBufferCount) {
  9702. this.onBufferReset();
  9703. }
  9704. }
  9705. mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
  9706. mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);
  9707. mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose);
  9708. if (this.appendSource) {
  9709. mediaSource.removeEventListener('startstreaming', this._onStartStreaming);
  9710. mediaSource.removeEventListener('endstreaming', this._onEndStreaming);
  9711. }
  9712. this.mediaSource = null;
  9713. this._objectUrl = null;
  9714. }
  9715. // Detach properly the MediaSource from the HTMLMediaElement as
  9716. // suggested in https://github.com/w3c/media-source/issues/53.
  9717. if (media) {
  9718. media.removeEventListener('emptied', this._onMediaEmptied);
  9719. if (!transferringMedia) {
  9720. if (_objectUrl) {
  9721. self.URL.revokeObjectURL(_objectUrl);
  9722. }
  9723. // clean up video tag src only if it's our own url. some external libraries might
  9724. // hijack the video tag and change its 'src' without destroying the Hls instance first
  9725. if (this.mediaSrc === _objectUrl) {
  9726. media.removeAttribute('src');
  9727. if (this.appendSource) {
  9728. removeSourceChildren(media);
  9729. }
  9730. media.load();
  9731. } else {
  9732. this.warn('media|source.src was changed by a third party - skip cleanup');
  9733. }
  9734. }
  9735. this.media = null;
  9736. }
  9737. this.hls.trigger(Events.MEDIA_DETACHED, data);
  9738. }
  9739. onBufferReset() {
  9740. this.sourceBuffers.forEach(([type]) => {
  9741. if (type) {
  9742. this.resetBuffer(type);
  9743. }
  9744. });
  9745. this.initTracks();
  9746. }
  9747. resetBuffer(type) {
  9748. var _this$tracks$type;
  9749. const sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  9750. this.removeBuffer(type);
  9751. if (sb) {
  9752. try {
  9753. var _this$mediaSource3;
  9754. if ((_this$mediaSource3 = this.mediaSource) != null && _this$mediaSource3.sourceBuffers.length) {
  9755. this.mediaSource.removeSourceBuffer(sb);
  9756. }
  9757. } catch (err) {
  9758. this.warn(`onBufferReset ${type}`, err);
  9759. }
  9760. }
  9761. delete this.tracks[type];
  9762. }
  9763. removeBuffer(type) {
  9764. this.removeBufferListeners(type);
  9765. this.sourceBuffers[sourceBufferNameToIndex(type)] = [null, null];
  9766. const track = this.tracks[type];
  9767. if (track) {
  9768. track.buffer = undefined;
  9769. }
  9770. }
  9771. resetQueue() {
  9772. if (this.operationQueue) {
  9773. this.operationQueue.destroy();
  9774. }
  9775. this.operationQueue = new BufferOperationQueue(this.tracks);
  9776. }
  9777. onBufferCodecs(event, data) {
  9778. const tracks = this.tracks;
  9779. const trackNames = Object.keys(data);
  9780. this.log(`BUFFER_CODECS: "${trackNames}" (current SB count ${this.sourceBufferCount})`);
  9781. const unmuxedToMuxed = 'audiovideo' in data && (tracks.audio || tracks.video) || tracks.audiovideo && ('audio' in data || 'video' in data);
  9782. const muxedToUnmuxed = !unmuxedToMuxed && this.sourceBufferCount && this.media && trackNames.some(sbName => !tracks[sbName]);
  9783. if (unmuxedToMuxed || muxedToUnmuxed) {
  9784. this.warn(`Unsupported transition between "${Object.keys(tracks)}" and "${trackNames}" SourceBuffers`);
  9785. // Do not add incompatible track ('audiovideo' <-> 'video'/'audio').
  9786. // Allow following onBufferAppending handle to trigger BUFFER_APPEND_ERROR.
  9787. // This will either be resolved by level switch or could be handled with recoverMediaError().
  9788. return;
  9789. }
  9790. trackNames.forEach(trackName => {
  9791. var _this$transferData3, _this$transferData3$t, _trackCodec;
  9792. const parsedTrack = data[trackName];
  9793. const {
  9794. id,
  9795. codec,
  9796. levelCodec,
  9797. container,
  9798. metadata,
  9799. supplemental
  9800. } = parsedTrack;
  9801. let track = tracks[trackName];
  9802. const transferredTrack = (_this$transferData3 = this.transferData) == null ? void 0 : (_this$transferData3$t = _this$transferData3.tracks) == null ? void 0 : _this$transferData3$t[trackName];
  9803. const sbTrack = transferredTrack != null && transferredTrack.buffer ? transferredTrack : track;
  9804. const sbCodec = (sbTrack == null ? void 0 : sbTrack.pendingCodec) || (sbTrack == null ? void 0 : sbTrack.codec);
  9805. const trackLevelCodec = sbTrack == null ? void 0 : sbTrack.levelCodec;
  9806. if (!track) {
  9807. track = tracks[trackName] = {
  9808. buffer: undefined,
  9809. listeners: [],
  9810. codec,
  9811. supplemental,
  9812. container,
  9813. levelCodec,
  9814. metadata,
  9815. id
  9816. };
  9817. }
  9818. // check if SourceBuffer codec needs to change
  9819. const currentCodecFull = pickMostCompleteCodecName(sbCodec, trackLevelCodec);
  9820. const currentCodec = currentCodecFull == null ? void 0 : currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  9821. let trackCodec = pickMostCompleteCodecName(codec, levelCodec);
  9822. const nextCodec = (_trackCodec = trackCodec) == null ? void 0 : _trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  9823. if (trackCodec && currentCodecFull && currentCodec !== nextCodec) {
  9824. if (trackName.slice(0, 5) === 'audio') {
  9825. trackCodec = getCodecCompatibleName(trackCodec, this.appendSource);
  9826. }
  9827. this.log(`switching codec ${sbCodec} to ${trackCodec}`);
  9828. if (trackCodec !== (track.pendingCodec || track.codec)) {
  9829. track.pendingCodec = trackCodec;
  9830. }
  9831. track.container = container;
  9832. this.appendChangeType(trackName, container, trackCodec);
  9833. }
  9834. });
  9835. if (this.tracksReady || this.sourceBufferCount) {
  9836. data.tracks = this.sourceBufferTracks;
  9837. }
  9838. // if sourcebuffers already created, do nothing ...
  9839. if (this.sourceBufferCount) {
  9840. return;
  9841. }
  9842. if (this.mediaSourceOpenOrEnded) {
  9843. this.checkPendingTracks();
  9844. }
  9845. }
  9846. get sourceBufferTracks() {
  9847. return Object.keys(this.tracks).reduce((baseTracks, type) => {
  9848. const track = this.tracks[type];
  9849. baseTracks[type] = {
  9850. id: track.id,
  9851. container: track.container,
  9852. codec: track.codec,
  9853. levelCodec: track.levelCodec
  9854. };
  9855. return baseTracks;
  9856. }, {});
  9857. }
  9858. appendChangeType(type, container, codec) {
  9859. const mimeType = `${container};codecs=${codec}`;
  9860. const operation = {
  9861. label: `change-type=${mimeType}`,
  9862. execute: () => {
  9863. const track = this.tracks[type];
  9864. if (track) {
  9865. const sb = track.buffer;
  9866. if (sb != null && sb.changeType) {
  9867. this.log(`changing ${type} sourceBuffer type to ${mimeType}`);
  9868. sb.changeType(mimeType);
  9869. track.codec = codec;
  9870. track.container = container;
  9871. }
  9872. }
  9873. this.shiftAndExecuteNext(type);
  9874. },
  9875. onStart: () => {},
  9876. onComplete: () => {},
  9877. onError: error => {
  9878. this.warn(`Failed to change ${type} SourceBuffer type`, error);
  9879. }
  9880. };
  9881. this.append(operation, type, this.isPending(this.tracks[type]));
  9882. }
  9883. blockAudio(partOrFrag) {
  9884. var _this$fragmentTracker;
  9885. const pStart = partOrFrag.start;
  9886. const pTime = pStart + partOrFrag.duration * 0.05;
  9887. const atGap = ((_this$fragmentTracker = this.fragmentTracker.getAppendedFrag(pStart, PlaylistLevelType.MAIN)) == null ? void 0 : _this$fragmentTracker.gap) === true;
  9888. if (atGap) {
  9889. return;
  9890. }
  9891. const op = {
  9892. label: 'block-audio',
  9893. execute: () => {
  9894. var _this$fragmentTracker2;
  9895. const videoTrack = this.tracks.video;
  9896. 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) {
  9897. this.blockedAudioAppend = null;
  9898. this.shiftAndExecuteNext('audio');
  9899. }
  9900. },
  9901. onStart: () => {},
  9902. onComplete: () => {},
  9903. onError: error => {
  9904. this.warn('Error executing block-audio operation', error);
  9905. }
  9906. };
  9907. this.blockedAudioAppend = {
  9908. op,
  9909. frag: partOrFrag
  9910. };
  9911. this.append(op, 'audio', true);
  9912. }
  9913. unblockAudio() {
  9914. const {
  9915. blockedAudioAppend,
  9916. operationQueue
  9917. } = this;
  9918. if (blockedAudioAppend && operationQueue) {
  9919. this.blockedAudioAppend = null;
  9920. operationQueue.unblockAudio(blockedAudioAppend.op);
  9921. }
  9922. }
  9923. onBufferAppending(event, eventData) {
  9924. const {
  9925. tracks
  9926. } = this;
  9927. const {
  9928. data,
  9929. type,
  9930. parent,
  9931. frag,
  9932. part,
  9933. chunkMeta,
  9934. offset
  9935. } = eventData;
  9936. const chunkStats = chunkMeta.buffering[type];
  9937. const {
  9938. sn,
  9939. cc
  9940. } = frag;
  9941. const bufferAppendingStart = self.performance.now();
  9942. chunkStats.start = bufferAppendingStart;
  9943. const fragBuffering = frag.stats.buffering;
  9944. const partBuffering = part ? part.stats.buffering : null;
  9945. if (fragBuffering.start === 0) {
  9946. fragBuffering.start = bufferAppendingStart;
  9947. }
  9948. if (partBuffering && partBuffering.start === 0) {
  9949. partBuffering.start = bufferAppendingStart;
  9950. }
  9951. // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended
  9952. // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
  9953. // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
  9954. // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).
  9955. // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
  9956. const audioTrack = tracks.audio;
  9957. let checkTimestampOffset = false;
  9958. if (type === 'audio' && (audioTrack == null ? void 0 : audioTrack.container) === 'audio/mpeg') {
  9959. checkTimestampOffset = !this.lastMpegAudioChunk || chunkMeta.id === 1 || this.lastMpegAudioChunk.sn !== chunkMeta.sn;
  9960. this.lastMpegAudioChunk = chunkMeta;
  9961. }
  9962. // Block audio append until overlapping video append
  9963. const videoTrack = tracks.video;
  9964. const videoSb = videoTrack == null ? void 0 : videoTrack.buffer;
  9965. if (videoSb && sn !== 'initSegment') {
  9966. const partOrFrag = part || frag;
  9967. const blockedAudioAppend = this.blockedAudioAppend;
  9968. if (type === 'audio' && parent !== 'main' && !this.blockedAudioAppend) {
  9969. const pStart = partOrFrag.start;
  9970. const pTime = pStart + partOrFrag.duration * 0.05;
  9971. const vbuffered = videoSb.buffered;
  9972. const vappending = this.currentOp('video');
  9973. if (!vbuffered.length && !vappending) {
  9974. // wait for video before appending audio
  9975. this.blockAudio(partOrFrag);
  9976. } else if (!vappending && !BufferHelper.isBuffered(videoSb, pTime) && this.lastVideoAppendEnd < pTime) {
  9977. // audio is ahead of video
  9978. this.blockAudio(partOrFrag);
  9979. }
  9980. } else if (type === 'video') {
  9981. const videoAppendEnd = partOrFrag.end;
  9982. if (blockedAudioAppend) {
  9983. const audioStart = blockedAudioAppend.frag.start;
  9984. if (videoAppendEnd > audioStart || videoAppendEnd < this.lastVideoAppendEnd || BufferHelper.isBuffered(videoSb, audioStart)) {
  9985. this.unblockAudio();
  9986. }
  9987. }
  9988. this.lastVideoAppendEnd = videoAppendEnd;
  9989. }
  9990. }
  9991. const fragStart = (part || frag).start;
  9992. const operation = {
  9993. label: `append-${type}`,
  9994. execute: () => {
  9995. var _this$tracks$type2;
  9996. chunkStats.executeStart = self.performance.now();
  9997. const sb = (_this$tracks$type2 = this.tracks[type]) == null ? void 0 : _this$tracks$type2.buffer;
  9998. if (sb) {
  9999. if (checkTimestampOffset) {
  10000. this.updateTimestampOffset(sb, fragStart, 0.1, type, sn, cc);
  10001. } else if (offset !== undefined && isFiniteNumber(offset)) {
  10002. this.updateTimestampOffset(sb, offset, 0.000001, type, sn, cc);
  10003. }
  10004. }
  10005. this.appendExecutor(data, type);
  10006. },
  10007. onStart: () => {
  10008. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);
  10009. },
  10010. onComplete: () => {
  10011. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);
  10012. const end = self.performance.now();
  10013. chunkStats.executeEnd = chunkStats.end = end;
  10014. if (fragBuffering.first === 0) {
  10015. fragBuffering.first = end;
  10016. }
  10017. if (partBuffering && partBuffering.first === 0) {
  10018. partBuffering.first = end;
  10019. }
  10020. const timeRanges = {};
  10021. this.sourceBuffers.forEach(([type, sb]) => {
  10022. if (type) {
  10023. timeRanges[type] = BufferHelper.getBuffered(sb);
  10024. }
  10025. });
  10026. this.appendErrors[type] = 0;
  10027. if (type === 'audio' || type === 'video') {
  10028. this.appendErrors.audiovideo = 0;
  10029. } else {
  10030. this.appendErrors.audio = 0;
  10031. this.appendErrors.video = 0;
  10032. }
  10033. this.hls.trigger(Events.BUFFER_APPENDED, {
  10034. type,
  10035. frag,
  10036. part,
  10037. chunkMeta,
  10038. parent: frag.type,
  10039. timeRanges
  10040. });
  10041. },
  10042. onError: error => {
  10043. var _this$media;
  10044. // in case any error occured while appending, put back segment in segments table
  10045. const event = {
  10046. type: ErrorTypes.MEDIA_ERROR,
  10047. parent: frag.type,
  10048. details: ErrorDetails.BUFFER_APPEND_ERROR,
  10049. sourceBufferName: type,
  10050. frag,
  10051. part,
  10052. chunkMeta,
  10053. error,
  10054. err: error,
  10055. fatal: false
  10056. };
  10057. const mediaError = (_this$media = this.media) == null ? void 0 : _this$media.error;
  10058. if (error.code === DOMException.QUOTA_EXCEEDED_ERR || error.name == 'QuotaExceededError' || `quota` in error) {
  10059. // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
  10060. // let's stop appending any segments, and report BUFFER_FULL_ERROR error
  10061. event.details = ErrorDetails.BUFFER_FULL_ERROR;
  10062. } else if (error.code === DOMException.INVALID_STATE_ERR && this.mediaSourceOpenOrEnded && !mediaError) {
  10063. // Allow retry for "Failed to execute 'appendBuffer' on 'SourceBuffer': This SourceBuffer is still processing" errors
  10064. event.errorAction = createDoNothingErrorAction(true);
  10065. } else if (error.name === TRACK_REMOVED_ERROR_NAME && this.sourceBufferCount === 0) {
  10066. // Do nothing if sourceBuffers were removed (media is detached and append was not aborted)
  10067. event.errorAction = createDoNothingErrorAction(true);
  10068. } else {
  10069. const appendErrorCount = ++this.appendErrors[type];
  10070. /* with UHD content, we could get loop of quota exceeded error until
  10071. browser is able to evict some data from sourcebuffer. Retrying can help recover.
  10072. */
  10073. this.warn(`Failed ${appendErrorCount}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${type}" sourceBuffer (${mediaError ? mediaError : 'no media error'})`);
  10074. if (appendErrorCount >= this.hls.config.appendErrorMaxRetry || !!mediaError) {
  10075. event.fatal = true;
  10076. }
  10077. }
  10078. this.hls.trigger(Events.ERROR, event);
  10079. }
  10080. };
  10081. this.append(operation, type, this.isPending(this.tracks[type]));
  10082. }
  10083. getFlushOp(type, start, end) {
  10084. this.log(`queuing "${type}" remove ${start}-${end}`);
  10085. return {
  10086. label: 'remove',
  10087. execute: () => {
  10088. this.removeExecutor(type, start, end);
  10089. },
  10090. onStart: () => {
  10091. // logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  10092. },
  10093. onComplete: () => {
  10094. // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  10095. this.hls.trigger(Events.BUFFER_FLUSHED, {
  10096. type
  10097. });
  10098. },
  10099. onError: error => {
  10100. this.warn(`Failed to remove ${start}-${end} from "${type}" SourceBuffer`, error);
  10101. }
  10102. };
  10103. }
  10104. onBufferFlushing(event, data) {
  10105. const {
  10106. type,
  10107. startOffset,
  10108. endOffset
  10109. } = data;
  10110. if (type) {
  10111. this.append(this.getFlushOp(type, startOffset, endOffset), type);
  10112. } else {
  10113. this.sourceBuffers.forEach(([type]) => {
  10114. if (type) {
  10115. this.append(this.getFlushOp(type, startOffset, endOffset), type);
  10116. }
  10117. });
  10118. }
  10119. }
  10120. onFragParsed(event, data) {
  10121. const {
  10122. frag,
  10123. part
  10124. } = data;
  10125. const buffersAppendedTo = [];
  10126. const elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
  10127. if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {
  10128. buffersAppendedTo.push('audiovideo');
  10129. } else {
  10130. if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {
  10131. buffersAppendedTo.push('audio');
  10132. }
  10133. if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {
  10134. buffersAppendedTo.push('video');
  10135. }
  10136. }
  10137. const onUnblocked = () => {
  10138. const now = self.performance.now();
  10139. frag.stats.buffering.end = now;
  10140. if (part) {
  10141. part.stats.buffering.end = now;
  10142. }
  10143. const stats = part ? part.stats : frag.stats;
  10144. this.hls.trigger(Events.FRAG_BUFFERED, {
  10145. frag,
  10146. part,
  10147. stats,
  10148. id: frag.type
  10149. });
  10150. };
  10151. if (buffersAppendedTo.length === 0) {
  10152. this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${frag.type} level: ${frag.level} sn: ${frag.sn}`);
  10153. }
  10154. this.blockBuffers(onUnblocked, buffersAppendedTo).catch(error => {
  10155. this.warn(`Fragment buffered callback ${error}`);
  10156. this.stepOperationQueue(this.sourceBufferTypes);
  10157. });
  10158. }
  10159. onFragChanged(event, data) {
  10160. this.trimBuffers();
  10161. }
  10162. get bufferedToEnd() {
  10163. return this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type]) => {
  10164. var _this$tracks$type3, _this$tracks$type4;
  10165. return type && (!((_this$tracks$type3 = this.tracks[type]) != null && _this$tracks$type3.ended) || ((_this$tracks$type4 = this.tracks[type]) == null ? void 0 : _this$tracks$type4.ending));
  10166. });
  10167. }
  10168. // on BUFFER_EOS mark matching sourcebuffer(s) as "ending" and "ended" and queue endOfStream after remaining operations(s)
  10169. // an undefined data.type will mark all buffers as EOS.
  10170. onBufferEos(event, data) {
  10171. var _this$overrides;
  10172. this.sourceBuffers.forEach(([type]) => {
  10173. if (type) {
  10174. const track = this.tracks[type];
  10175. if (!data.type || data.type === type) {
  10176. track.ending = true;
  10177. if (!track.ended) {
  10178. track.ended = true;
  10179. this.log(`${type} buffer reached EOS`);
  10180. }
  10181. }
  10182. }
  10183. });
  10184. const allowEndOfStream = ((_this$overrides = this.overrides) == null ? void 0 : _this$overrides.endOfStream) !== false;
  10185. const allTracksEnding = this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type]) => {
  10186. var _this$tracks$type5;
  10187. return type && !((_this$tracks$type5 = this.tracks[type]) != null && _this$tracks$type5.ended);
  10188. });
  10189. if (allTracksEnding) {
  10190. if (allowEndOfStream) {
  10191. this.log(`Queueing EOS`);
  10192. this.blockUntilOpen(() => {
  10193. this.tracksEnded();
  10194. const {
  10195. mediaSource
  10196. } = this;
  10197. if (!mediaSource || mediaSource.readyState !== 'open') {
  10198. if (mediaSource) {
  10199. this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${mediaSource.readyState}`);
  10200. }
  10201. return;
  10202. }
  10203. this.log(`Calling mediaSource.endOfStream()`);
  10204. // Allow this to throw and be caught by the enqueueing function
  10205. mediaSource.endOfStream();
  10206. this.hls.trigger(Events.BUFFERED_TO_END, undefined);
  10207. });
  10208. } else {
  10209. this.tracksEnded();
  10210. this.hls.trigger(Events.BUFFERED_TO_END, undefined);
  10211. }
  10212. }
  10213. }
  10214. tracksEnded() {
  10215. this.sourceBuffers.forEach(([type]) => {
  10216. if (type !== null) {
  10217. const track = this.tracks[type];
  10218. if (track) {
  10219. track.ending = false;
  10220. }
  10221. }
  10222. });
  10223. }
  10224. onLevelUpdated(event, {
  10225. details
  10226. }) {
  10227. if (!details.fragments.length) {
  10228. return;
  10229. }
  10230. this.details = details;
  10231. this.updateDuration();
  10232. }
  10233. updateDuration() {
  10234. this.blockUntilOpen(() => {
  10235. const durationAndRange = this.getDurationAndRange();
  10236. if (!durationAndRange) {
  10237. return;
  10238. }
  10239. this.updateMediaSource(durationAndRange);
  10240. });
  10241. }
  10242. onError(event, data) {
  10243. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && data.frag) {
  10244. var _data$errorAction;
  10245. const nextAutoLevel = (_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.nextAutoLevel;
  10246. if (isFiniteNumber(nextAutoLevel) && nextAutoLevel !== data.frag.level) {
  10247. this.resetAppendErrors();
  10248. }
  10249. }
  10250. }
  10251. resetAppendErrors() {
  10252. this.appendErrors = {
  10253. audio: 0,
  10254. video: 0,
  10255. audiovideo: 0
  10256. };
  10257. }
  10258. trimBuffers() {
  10259. const {
  10260. hls,
  10261. details,
  10262. media
  10263. } = this;
  10264. if (!media || details === null) {
  10265. return;
  10266. }
  10267. if (!this.sourceBufferCount) {
  10268. return;
  10269. }
  10270. const config = hls.config;
  10271. const currentTime = media.currentTime;
  10272. const targetDuration = details.levelTargetDuration;
  10273. // Support for deprecated liveBackBufferLength
  10274. const backBufferLength = details.live && config.liveBackBufferLength !== null ? config.liveBackBufferLength : config.backBufferLength;
  10275. if (isFiniteNumber(backBufferLength) && backBufferLength >= 0) {
  10276. const maxBackBufferLength = Math.max(backBufferLength, targetDuration);
  10277. const targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
  10278. this.flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition);
  10279. }
  10280. if (isFiniteNumber(config.frontBufferFlushThreshold) && config.frontBufferFlushThreshold > 0) {
  10281. const frontBufferLength = Math.max(config.maxBufferLength, config.frontBufferFlushThreshold);
  10282. const maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);
  10283. const targetFrontBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration + maxFrontBufferLength;
  10284. this.flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition);
  10285. }
  10286. }
  10287. flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition) {
  10288. this.sourceBuffers.forEach(([type, sb]) => {
  10289. if (sb) {
  10290. const buffered = BufferHelper.getBuffered(sb);
  10291. // when target buffer start exceeds actual buffer start
  10292. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  10293. var _this$details;
  10294. this.hls.trigger(Events.BACK_BUFFER_REACHED, {
  10295. bufferEnd: targetBackBufferPosition
  10296. });
  10297. // Support for deprecated event:
  10298. const track = this.tracks[type];
  10299. if ((_this$details = this.details) != null && _this$details.live) {
  10300. this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {
  10301. bufferEnd: targetBackBufferPosition
  10302. });
  10303. } else if (track != null && track.ended) {
  10304. this.log(`Cannot flush ${type} back buffer while SourceBuffer is in ended state`);
  10305. return;
  10306. }
  10307. this.hls.trigger(Events.BUFFER_FLUSHING, {
  10308. startOffset: 0,
  10309. endOffset: targetBackBufferPosition,
  10310. type
  10311. });
  10312. }
  10313. }
  10314. });
  10315. }
  10316. flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition) {
  10317. this.sourceBuffers.forEach(([type, sb]) => {
  10318. if (sb) {
  10319. const buffered = BufferHelper.getBuffered(sb);
  10320. const numBufferedRanges = buffered.length;
  10321. // The buffer is either empty or contiguous
  10322. if (numBufferedRanges < 2) {
  10323. return;
  10324. }
  10325. const bufferStart = buffered.start(numBufferedRanges - 1);
  10326. const bufferEnd = buffered.end(numBufferedRanges - 1);
  10327. // No flush if we can tolerate the current buffer length or the current buffer range we would flush is contiguous with current position
  10328. if (targetFrontBufferPosition > bufferStart || currentTime >= bufferStart && currentTime <= bufferEnd) {
  10329. return;
  10330. }
  10331. this.hls.trigger(Events.BUFFER_FLUSHING, {
  10332. startOffset: bufferStart,
  10333. endOffset: Infinity,
  10334. type
  10335. });
  10336. }
  10337. });
  10338. }
  10339. /**
  10340. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  10341. * 'liveDurationInfinity` is set to `true`
  10342. * More details: https://github.com/video-dev/hls.js/issues/355
  10343. */
  10344. getDurationAndRange() {
  10345. var _this$overrides2;
  10346. const {
  10347. details,
  10348. mediaSource
  10349. } = this;
  10350. if (!details || !this.media || (mediaSource == null ? void 0 : mediaSource.readyState) !== 'open') {
  10351. return null;
  10352. }
  10353. const playlistEnd = details.edge;
  10354. if (details.live && this.hls.config.liveDurationInfinity) {
  10355. const len = details.fragments.length;
  10356. if (len && details.live && !!mediaSource.setLiveSeekableRange) {
  10357. const start = Math.max(0, details.fragmentStart);
  10358. const end = Math.max(start, playlistEnd);
  10359. return {
  10360. duration: Infinity,
  10361. start,
  10362. end
  10363. };
  10364. }
  10365. return {
  10366. duration: Infinity
  10367. };
  10368. }
  10369. const overrideDuration = (_this$overrides2 = this.overrides) == null ? void 0 : _this$overrides2.duration;
  10370. if (overrideDuration) {
  10371. if (!isFiniteNumber(overrideDuration)) {
  10372. return null;
  10373. }
  10374. return {
  10375. duration: overrideDuration
  10376. };
  10377. }
  10378. const mediaDuration = this.media.duration;
  10379. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : 0;
  10380. if (playlistEnd > msDuration && playlistEnd > mediaDuration || !isFiniteNumber(mediaDuration)) {
  10381. return {
  10382. duration: playlistEnd
  10383. };
  10384. }
  10385. return null;
  10386. }
  10387. updateMediaSource({
  10388. duration,
  10389. start,
  10390. end
  10391. }) {
  10392. const mediaSource = this.mediaSource;
  10393. if (!this.media || !mediaSource || mediaSource.readyState !== 'open') {
  10394. return;
  10395. }
  10396. if (mediaSource.duration !== duration) {
  10397. if (isFiniteNumber(duration)) {
  10398. this.log(`Updating MediaSource duration to ${duration.toFixed(3)}`);
  10399. }
  10400. mediaSource.duration = duration;
  10401. }
  10402. if (start !== undefined && end !== undefined) {
  10403. this.log(`MediaSource duration is set to ${mediaSource.duration}. Setting seekable range to ${start}-${end}.`);
  10404. mediaSource.setLiveSeekableRange(start, end);
  10405. }
  10406. }
  10407. get tracksReady() {
  10408. const pendingTrackCount = this.pendingTrackCount;
  10409. return pendingTrackCount > 0 && (pendingTrackCount >= this.bufferCodecEventsTotal || this.isPending(this.tracks.audiovideo));
  10410. }
  10411. checkPendingTracks() {
  10412. const {
  10413. bufferCodecEventsTotal,
  10414. pendingTrackCount,
  10415. tracks
  10416. } = this;
  10417. this.log(`checkPendingTracks (pending: ${pendingTrackCount} codec events expected: ${bufferCodecEventsTotal}) ${stringify(tracks)}`);
  10418. // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
  10419. // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
  10420. // data has been appended to existing ones.
  10421. // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
  10422. if (this.tracksReady) {
  10423. var _this$transferData4;
  10424. const transferredTracks = (_this$transferData4 = this.transferData) == null ? void 0 : _this$transferData4.tracks;
  10425. if (transferredTracks && Object.keys(transferredTracks).length) {
  10426. this.attachTransferred();
  10427. } else {
  10428. // ok, let's create them now !
  10429. this.createSourceBuffers();
  10430. }
  10431. }
  10432. }
  10433. bufferCreated() {
  10434. if (this.sourceBufferCount) {
  10435. const tracks = {};
  10436. this.sourceBuffers.forEach(([type, buffer]) => {
  10437. if (type) {
  10438. const track = this.tracks[type];
  10439. tracks[type] = {
  10440. buffer,
  10441. container: track.container,
  10442. codec: track.codec,
  10443. supplemental: track.supplemental,
  10444. levelCodec: track.levelCodec,
  10445. id: track.id,
  10446. metadata: track.metadata
  10447. };
  10448. }
  10449. });
  10450. this.hls.trigger(Events.BUFFER_CREATED, {
  10451. tracks
  10452. });
  10453. this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`);
  10454. this.sourceBuffers.forEach(([type]) => {
  10455. this.executeNext(type);
  10456. });
  10457. } else {
  10458. const error = new Error('could not create source buffer for media codec(s)');
  10459. this.hls.trigger(Events.ERROR, {
  10460. type: ErrorTypes.MEDIA_ERROR,
  10461. details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,
  10462. fatal: true,
  10463. error,
  10464. reason: error.message
  10465. });
  10466. }
  10467. }
  10468. createSourceBuffers() {
  10469. const {
  10470. tracks,
  10471. sourceBuffers,
  10472. mediaSource
  10473. } = this;
  10474. if (!mediaSource) {
  10475. throw new Error('createSourceBuffers called when mediaSource was null');
  10476. }
  10477. for (const trackName in tracks) {
  10478. const type = trackName;
  10479. const track = tracks[type];
  10480. if (this.isPending(track)) {
  10481. const codec = this.getTrackCodec(track, type);
  10482. const mimeType = `${track.container};codecs=${codec}`;
  10483. track.codec = codec;
  10484. this.log(`creating sourceBuffer(${mimeType})${this.currentOp(type) ? ' Queued' : ''} ${stringify(track)}`);
  10485. try {
  10486. const sb = mediaSource.addSourceBuffer(mimeType);
  10487. const sbIndex = sourceBufferNameToIndex(type);
  10488. const sbTuple = [type, sb];
  10489. sourceBuffers[sbIndex] = sbTuple;
  10490. track.buffer = sb;
  10491. } catch (error) {
  10492. var _this$operationQueue;
  10493. this.error(`error while trying to add sourceBuffer: ${error.message}`);
  10494. // remove init segment from queue and delete track info
  10495. this.shiftAndExecuteNext(type);
  10496. (_this$operationQueue = this.operationQueue) == null ? void 0 : _this$operationQueue.removeBlockers();
  10497. delete this.tracks[type];
  10498. this.hls.trigger(Events.ERROR, {
  10499. type: ErrorTypes.MEDIA_ERROR,
  10500. details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,
  10501. fatal: false,
  10502. error,
  10503. sourceBufferName: type,
  10504. mimeType: mimeType,
  10505. parent: track.id
  10506. });
  10507. return;
  10508. }
  10509. this.trackSourceBuffer(type, track);
  10510. }
  10511. }
  10512. this.bufferCreated();
  10513. }
  10514. getTrackCodec(track, trackName) {
  10515. // Use supplemental video codec when supported when adding SourceBuffer (#5558)
  10516. const supplementalCodec = track.supplemental;
  10517. let trackCodec = track.codec;
  10518. if (supplementalCodec && (trackName === 'video' || trackName === 'audiovideo') && areCodecsMediaSourceSupported(supplementalCodec, 'video')) {
  10519. trackCodec = replaceVideoCodec(trackCodec, supplementalCodec);
  10520. }
  10521. const codec = pickMostCompleteCodecName(trackCodec, track.levelCodec);
  10522. if (codec) {
  10523. if (trackName.slice(0, 5) === 'audio') {
  10524. return getCodecCompatibleName(codec, this.appendSource);
  10525. }
  10526. return codec;
  10527. }
  10528. return '';
  10529. }
  10530. trackSourceBuffer(type, track) {
  10531. const buffer = track.buffer;
  10532. if (!buffer) {
  10533. return;
  10534. }
  10535. const codec = this.getTrackCodec(track, type);
  10536. this.tracks[type] = {
  10537. buffer,
  10538. codec,
  10539. container: track.container,
  10540. levelCodec: track.levelCodec,
  10541. supplemental: track.supplemental,
  10542. metadata: track.metadata,
  10543. id: track.id,
  10544. listeners: []
  10545. };
  10546. this.removeBufferListeners(type);
  10547. this.addBufferListener(type, 'updatestart', this.onSBUpdateStart);
  10548. this.addBufferListener(type, 'updateend', this.onSBUpdateEnd);
  10549. this.addBufferListener(type, 'error', this.onSBUpdateError);
  10550. // ManagedSourceBuffer bufferedchange event
  10551. if (this.appendSource) {
  10552. this.addBufferListener(type, 'bufferedchange', (type, event) => {
  10553. // If media was ejected check for a change. Added ranges are redundant with changes on 'updateend' event.
  10554. const removedRanges = event.removedRanges;
  10555. if (removedRanges != null && removedRanges.length) {
  10556. this.hls.trigger(Events.BUFFER_FLUSHED, {
  10557. type: type
  10558. });
  10559. }
  10560. });
  10561. }
  10562. }
  10563. get mediaSrc() {
  10564. var _this$media2, _this$media2$querySel;
  10565. const media = ((_this$media2 = this.media) == null ? void 0 : (_this$media2$querySel = _this$media2.querySelector) == null ? void 0 : _this$media2$querySel.call(_this$media2, 'source')) || this.media;
  10566. return media == null ? void 0 : media.src;
  10567. }
  10568. onSBUpdateStart(type) {
  10569. const operation = this.currentOp(type);
  10570. if (!operation) {
  10571. return;
  10572. }
  10573. operation.onStart();
  10574. }
  10575. onSBUpdateEnd(type) {
  10576. var _this$mediaSource4;
  10577. if (((_this$mediaSource4 = this.mediaSource) == null ? void 0 : _this$mediaSource4.readyState) === 'closed') {
  10578. this.resetBuffer(type);
  10579. return;
  10580. }
  10581. const operation = this.currentOp(type);
  10582. if (!operation) {
  10583. return;
  10584. }
  10585. operation.onComplete();
  10586. this.shiftAndExecuteNext(type);
  10587. }
  10588. onSBUpdateError(type, event) {
  10589. var _this$mediaSource5;
  10590. const error = new Error(`${type} SourceBuffer error. MediaSource readyState: ${(_this$mediaSource5 = this.mediaSource) == null ? void 0 : _this$mediaSource5.readyState}`);
  10591. this.error(`${error}`, event);
  10592. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  10593. // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event
  10594. this.hls.trigger(Events.ERROR, {
  10595. type: ErrorTypes.MEDIA_ERROR,
  10596. details: ErrorDetails.BUFFER_APPENDING_ERROR,
  10597. sourceBufferName: type,
  10598. error,
  10599. fatal: false
  10600. });
  10601. // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue
  10602. const operation = this.currentOp(type);
  10603. if (operation) {
  10604. operation.onError(error);
  10605. }
  10606. }
  10607. updateTimestampOffset(sb, timestampOffset, tolerance, type, sn, cc) {
  10608. const delta = timestampOffset - sb.timestampOffset;
  10609. if (Math.abs(delta) >= tolerance) {
  10610. this.log(`Updating ${type} SourceBuffer timestampOffset to ${timestampOffset} (sn: ${sn} cc: ${cc})`);
  10611. sb.timestampOffset = timestampOffset;
  10612. }
  10613. }
  10614. // This method must result in an updateend event; if remove is not called, onSBUpdateEnd must be called manually
  10615. removeExecutor(type, startOffset, endOffset) {
  10616. const {
  10617. media,
  10618. mediaSource
  10619. } = this;
  10620. const track = this.tracks[type];
  10621. const sb = track == null ? void 0 : track.buffer;
  10622. if (!media || !mediaSource || !sb) {
  10623. this.warn(`Attempting to remove from the ${type} SourceBuffer, but it does not exist`);
  10624. this.shiftAndExecuteNext(type);
  10625. return;
  10626. }
  10627. const mediaDuration = isFiniteNumber(media.duration) ? media.duration : Infinity;
  10628. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : Infinity;
  10629. const removeStart = Math.max(0, startOffset);
  10630. const removeEnd = Math.min(endOffset, mediaDuration, msDuration);
  10631. if (removeEnd > removeStart && (!track.ending || track.ended)) {
  10632. track.ended = false;
  10633. this.log(`Removing [${removeStart},${removeEnd}] from the ${type} SourceBuffer`);
  10634. sb.remove(removeStart, removeEnd);
  10635. } else {
  10636. // Cycle the queue
  10637. this.shiftAndExecuteNext(type);
  10638. }
  10639. }
  10640. // This method must result in an updateend event; if append is not called, onSBUpdateEnd must be called manually
  10641. appendExecutor(data, type) {
  10642. const track = this.tracks[type];
  10643. const sb = track == null ? void 0 : track.buffer;
  10644. if (!sb) {
  10645. throw new HlsJsTrackRemovedError(`Attempting to append to the ${type} SourceBuffer, but it does not exist`);
  10646. }
  10647. track.ending = false;
  10648. track.ended = false;
  10649. sb.appendBuffer(data);
  10650. }
  10651. blockUntilOpen(callback) {
  10652. if (this.isUpdating() || this.isQueued()) {
  10653. this.blockBuffers(callback).catch(error => {
  10654. this.warn(`SourceBuffer blocked callback ${error}`);
  10655. this.stepOperationQueue(this.sourceBufferTypes);
  10656. });
  10657. } else {
  10658. try {
  10659. callback();
  10660. } catch (error) {
  10661. this.warn(`Callback run without blocking ${this.operationQueue} ${error}`);
  10662. }
  10663. }
  10664. }
  10665. isUpdating() {
  10666. return this.sourceBuffers.some(([type, sb]) => type && sb.updating);
  10667. }
  10668. isQueued() {
  10669. return this.sourceBuffers.some(([type]) => type && !!this.currentOp(type));
  10670. }
  10671. isPending(track) {
  10672. return !!track && !track.buffer;
  10673. }
  10674. // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
  10675. // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
  10676. // upon completion, since we already do it here
  10677. blockBuffers(onUnblocked, bufferNames = this.sourceBufferTypes) {
  10678. if (!bufferNames.length) {
  10679. this.log('Blocking operation requested, but no SourceBuffers exist');
  10680. return Promise.resolve().then(onUnblocked);
  10681. }
  10682. const {
  10683. operationQueue
  10684. } = this;
  10685. // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);
  10686. const blockingOperations = bufferNames.map(type => this.appendBlocker(type));
  10687. const audioBlocked = bufferNames.length > 1 && !!this.blockedAudioAppend;
  10688. if (audioBlocked) {
  10689. this.unblockAudio();
  10690. }
  10691. return Promise.all(blockingOperations).then(result => {
  10692. if (operationQueue !== this.operationQueue) {
  10693. return;
  10694. }
  10695. // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);
  10696. onUnblocked();
  10697. this.stepOperationQueue(this.sourceBufferTypes);
  10698. });
  10699. }
  10700. stepOperationQueue(bufferNames) {
  10701. bufferNames.forEach(type => {
  10702. var _this$tracks$type6;
  10703. const sb = (_this$tracks$type6 = this.tracks[type]) == null ? void 0 : _this$tracks$type6.buffer;
  10704. // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to
  10705. // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)
  10706. // While this is a workaround, it's probably useful to have around
  10707. if (!sb || sb.updating) {
  10708. return;
  10709. }
  10710. this.shiftAndExecuteNext(type);
  10711. });
  10712. }
  10713. append(operation, type, pending) {
  10714. if (this.operationQueue) {
  10715. this.operationQueue.append(operation, type, pending);
  10716. }
  10717. }
  10718. appendBlocker(type) {
  10719. if (this.operationQueue) {
  10720. return this.operationQueue.appendBlocker(type);
  10721. }
  10722. }
  10723. currentOp(type) {
  10724. if (this.operationQueue) {
  10725. return this.operationQueue.current(type);
  10726. }
  10727. return null;
  10728. }
  10729. executeNext(type) {
  10730. if (type && this.operationQueue) {
  10731. this.operationQueue.executeNext(type);
  10732. }
  10733. }
  10734. shiftAndExecuteNext(type) {
  10735. if (this.operationQueue) {
  10736. this.operationQueue.shiftAndExecuteNext(type);
  10737. }
  10738. }
  10739. get pendingTrackCount() {
  10740. return Object.keys(this.tracks).reduce((acc, type) => acc + (this.isPending(this.tracks[type]) ? 1 : 0), 0);
  10741. }
  10742. get sourceBufferCount() {
  10743. return this.sourceBuffers.reduce((acc, [type]) => acc + (type ? 1 : 0), 0);
  10744. }
  10745. get sourceBufferTypes() {
  10746. return this.sourceBuffers.map(([type]) => type).filter(type => !!type);
  10747. }
  10748. addBufferListener(type, event, fn) {
  10749. const track = this.tracks[type];
  10750. if (!track) {
  10751. return;
  10752. }
  10753. const buffer = track.buffer;
  10754. if (!buffer) {
  10755. return;
  10756. }
  10757. const listener = fn.bind(this, type);
  10758. track.listeners.push({
  10759. event,
  10760. listener
  10761. });
  10762. buffer.addEventListener(event, listener);
  10763. }
  10764. removeBufferListeners(type) {
  10765. const track = this.tracks[type];
  10766. if (!track) {
  10767. return;
  10768. }
  10769. const buffer = track.buffer;
  10770. if (!buffer) {
  10771. return;
  10772. }
  10773. track.listeners.forEach(l => {
  10774. buffer.removeEventListener(l.event, l.listener);
  10775. });
  10776. track.listeners.length = 0;
  10777. }
  10778. }
  10779. function removeSourceChildren(node) {
  10780. const sourceChildren = node.querySelectorAll('source');
  10781. [].slice.call(sourceChildren).forEach(source => {
  10782. node.removeChild(source);
  10783. });
  10784. }
  10785. function addSource(media, url) {
  10786. const source = self.document.createElement('source');
  10787. source.type = 'video/mp4';
  10788. source.src = url;
  10789. media.appendChild(source);
  10790. }
  10791. function sourceBufferNameToIndex(type) {
  10792. return type === 'audio' ? 1 : 0;
  10793. }
  10794. class CapLevelController {
  10795. constructor(hls) {
  10796. this.hls = void 0;
  10797. this.autoLevelCapping = void 0;
  10798. this.firstLevel = void 0;
  10799. this.media = void 0;
  10800. this.restrictedLevels = void 0;
  10801. this.timer = void 0;
  10802. this.clientRect = void 0;
  10803. this.streamController = void 0;
  10804. this.hls = hls;
  10805. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  10806. this.firstLevel = -1;
  10807. this.media = null;
  10808. this.restrictedLevels = [];
  10809. this.timer = undefined;
  10810. this.clientRect = null;
  10811. this.registerListeners();
  10812. }
  10813. setStreamController(streamController) {
  10814. this.streamController = streamController;
  10815. }
  10816. destroy() {
  10817. if (this.hls) {
  10818. this.unregisterListener();
  10819. }
  10820. if (this.timer) {
  10821. this.stopCapping();
  10822. }
  10823. this.media = null;
  10824. this.clientRect = null;
  10825. // @ts-ignore
  10826. this.hls = this.streamController = null;
  10827. }
  10828. registerListeners() {
  10829. const {
  10830. hls
  10831. } = this;
  10832. hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  10833. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  10834. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  10835. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  10836. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  10837. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  10838. }
  10839. unregisterListener() {
  10840. const {
  10841. hls
  10842. } = this;
  10843. hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  10844. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  10845. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  10846. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  10847. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  10848. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  10849. }
  10850. onFpsDropLevelCapping(event, data) {
  10851. // Don't add a restricted level more than once
  10852. const level = this.hls.levels[data.droppedLevel];
  10853. if (this.isLevelAllowed(level)) {
  10854. this.restrictedLevels.push({
  10855. bitrate: level.bitrate,
  10856. height: level.height,
  10857. width: level.width
  10858. });
  10859. }
  10860. }
  10861. onMediaAttaching(event, data) {
  10862. this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  10863. this.clientRect = null;
  10864. if (this.timer && this.hls.levels.length) {
  10865. this.detectPlayerSize();
  10866. }
  10867. }
  10868. onManifestParsed(event, data) {
  10869. const hls = this.hls;
  10870. this.restrictedLevels = [];
  10871. this.firstLevel = data.firstLevel;
  10872. if (hls.config.capLevelToPlayerSize && data.video) {
  10873. // Start capping immediately if the manifest has signaled video codecs
  10874. this.startCapping();
  10875. }
  10876. }
  10877. onLevelsUpdated(event, data) {
  10878. if (this.timer && isFiniteNumber(this.autoLevelCapping)) {
  10879. this.detectPlayerSize();
  10880. }
  10881. }
  10882. // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  10883. // to the first level
  10884. onBufferCodecs(event, data) {
  10885. const hls = this.hls;
  10886. if (hls.config.capLevelToPlayerSize && data.video) {
  10887. // If the manifest did not signal a video codec capping has been deferred until we're certain video is present
  10888. this.startCapping();
  10889. }
  10890. }
  10891. onMediaDetaching() {
  10892. this.stopCapping();
  10893. this.media = null;
  10894. }
  10895. detectPlayerSize() {
  10896. if (this.media) {
  10897. if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {
  10898. this.clientRect = null;
  10899. return;
  10900. }
  10901. const levels = this.hls.levels;
  10902. if (levels.length) {
  10903. const hls = this.hls;
  10904. const maxLevel = this.getMaxLevel(levels.length - 1);
  10905. if (maxLevel !== this.autoLevelCapping) {
  10906. hls.logger.log(`Setting autoLevelCapping to ${maxLevel}: ${levels[maxLevel].height}p@${levels[maxLevel].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`);
  10907. }
  10908. hls.autoLevelCapping = maxLevel;
  10909. if (hls.autoLevelEnabled && hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
  10910. // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
  10911. // usually happen when the user go to the fullscreen mode.
  10912. this.streamController.nextLevelSwitch();
  10913. }
  10914. this.autoLevelCapping = hls.autoLevelCapping;
  10915. }
  10916. }
  10917. }
  10918. /*
  10919. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  10920. */
  10921. getMaxLevel(capLevelIndex) {
  10922. const levels = this.hls.levels;
  10923. if (!levels.length) {
  10924. return -1;
  10925. }
  10926. const validLevels = levels.filter((level, index) => this.isLevelAllowed(level) && index <= capLevelIndex);
  10927. this.clientRect = null;
  10928. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  10929. }
  10930. startCapping() {
  10931. if (this.timer) {
  10932. // Don't reset capping if started twice; this can happen if the manifest signals a video codec
  10933. return;
  10934. }
  10935. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  10936. self.clearInterval(this.timer);
  10937. this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);
  10938. this.detectPlayerSize();
  10939. }
  10940. stopCapping() {
  10941. this.restrictedLevels = [];
  10942. this.firstLevel = -1;
  10943. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  10944. if (this.timer) {
  10945. self.clearInterval(this.timer);
  10946. this.timer = undefined;
  10947. }
  10948. }
  10949. getDimensions() {
  10950. if (this.clientRect) {
  10951. return this.clientRect;
  10952. }
  10953. const media = this.media;
  10954. const boundsRect = {
  10955. width: 0,
  10956. height: 0
  10957. };
  10958. if (media) {
  10959. const clientRect = media.getBoundingClientRect();
  10960. boundsRect.width = clientRect.width;
  10961. boundsRect.height = clientRect.height;
  10962. if (!boundsRect.width && !boundsRect.height) {
  10963. // When the media element has no width or height (equivalent to not being in the DOM),
  10964. // then use its width and height attributes (media.width, media.height)
  10965. boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
  10966. boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
  10967. }
  10968. }
  10969. this.clientRect = boundsRect;
  10970. return boundsRect;
  10971. }
  10972. get mediaWidth() {
  10973. return this.getDimensions().width * this.contentScaleFactor;
  10974. }
  10975. get mediaHeight() {
  10976. return this.getDimensions().height * this.contentScaleFactor;
  10977. }
  10978. get contentScaleFactor() {
  10979. let pixelRatio = 1;
  10980. if (!this.hls.config.ignoreDevicePixelRatio) {
  10981. try {
  10982. pixelRatio = self.devicePixelRatio;
  10983. } catch (e) {
  10984. /* no-op */
  10985. }
  10986. }
  10987. return Math.min(pixelRatio, this.hls.config.maxDevicePixelRatio);
  10988. }
  10989. isLevelAllowed(level) {
  10990. const restrictedLevels = this.restrictedLevels;
  10991. return !restrictedLevels.some(restrictedLevel => {
  10992. return level.bitrate === restrictedLevel.bitrate && level.width === restrictedLevel.width && level.height === restrictedLevel.height;
  10993. });
  10994. }
  10995. static getMaxLevelByMediaSize(levels, width, height) {
  10996. if (!(levels != null && levels.length)) {
  10997. return -1;
  10998. }
  10999. // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
  11000. // to determine whether we've chosen the greatest bandwidth for the media's dimensions
  11001. const atGreatestBandwidth = (curLevel, nextLevel) => {
  11002. if (!nextLevel) {
  11003. return true;
  11004. }
  11005. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  11006. };
  11007. // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
  11008. // the max level
  11009. let maxLevelIndex = levels.length - 1;
  11010. // Prevent changes in aspect-ratio from causing capping to toggle back and forth
  11011. const squareSize = Math.max(width, height);
  11012. for (let i = 0; i < levels.length; i += 1) {
  11013. const level = levels[i];
  11014. if ((level.width >= squareSize || level.height >= squareSize) && atGreatestBandwidth(level, levels[i + 1])) {
  11015. maxLevelIndex = i;
  11016. break;
  11017. }
  11018. }
  11019. return maxLevelIndex;
  11020. }
  11021. }
  11022. const PATHWAY_PENALTY_DURATION_MS = 300000;
  11023. class ContentSteeringController extends Logger {
  11024. constructor(hls) {
  11025. super('content-steering', hls.logger);
  11026. this.hls = void 0;
  11027. this.loader = null;
  11028. this.uri = null;
  11029. this.pathwayId = '.';
  11030. this._pathwayPriority = null;
  11031. this.timeToLoad = 300;
  11032. this.reloadTimer = -1;
  11033. this.updated = 0;
  11034. this.started = false;
  11035. this.enabled = true;
  11036. this.levels = null;
  11037. this.audioTracks = null;
  11038. this.subtitleTracks = null;
  11039. this.penalizedPathways = {};
  11040. this.hls = hls;
  11041. this.registerListeners();
  11042. }
  11043. registerListeners() {
  11044. const hls = this.hls;
  11045. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  11046. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  11047. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  11048. hls.on(Events.ERROR, this.onError, this);
  11049. }
  11050. unregisterListeners() {
  11051. const hls = this.hls;
  11052. if (!hls) {
  11053. return;
  11054. }
  11055. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  11056. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  11057. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  11058. hls.off(Events.ERROR, this.onError, this);
  11059. }
  11060. pathways() {
  11061. return (this.levels || []).reduce((pathways, level) => {
  11062. if (pathways.indexOf(level.pathwayId) === -1) {
  11063. pathways.push(level.pathwayId);
  11064. }
  11065. return pathways;
  11066. }, []);
  11067. }
  11068. get pathwayPriority() {
  11069. return this._pathwayPriority;
  11070. }
  11071. set pathwayPriority(pathwayPriority) {
  11072. this.updatePathwayPriority(pathwayPriority);
  11073. }
  11074. startLoad() {
  11075. this.started = true;
  11076. this.clearTimeout();
  11077. if (this.enabled && this.uri) {
  11078. if (this.updated) {
  11079. const ttl = this.timeToLoad * 1000 - (performance.now() - this.updated);
  11080. if (ttl > 0) {
  11081. this.scheduleRefresh(this.uri, ttl);
  11082. return;
  11083. }
  11084. }
  11085. this.loadSteeringManifest(this.uri);
  11086. }
  11087. }
  11088. stopLoad() {
  11089. this.started = false;
  11090. if (this.loader) {
  11091. this.loader.destroy();
  11092. this.loader = null;
  11093. }
  11094. this.clearTimeout();
  11095. }
  11096. clearTimeout() {
  11097. if (this.reloadTimer !== -1) {
  11098. self.clearTimeout(this.reloadTimer);
  11099. this.reloadTimer = -1;
  11100. }
  11101. }
  11102. destroy() {
  11103. this.unregisterListeners();
  11104. this.stopLoad();
  11105. // @ts-ignore
  11106. this.hls = null;
  11107. this.levels = this.audioTracks = this.subtitleTracks = null;
  11108. }
  11109. removeLevel(levelToRemove) {
  11110. const levels = this.levels;
  11111. if (levels) {
  11112. this.levels = levels.filter(level => level !== levelToRemove);
  11113. }
  11114. }
  11115. onManifestLoading() {
  11116. this.stopLoad();
  11117. this.enabled = true;
  11118. this.timeToLoad = 300;
  11119. this.updated = 0;
  11120. this.uri = null;
  11121. this.pathwayId = '.';
  11122. this.levels = this.audioTracks = this.subtitleTracks = null;
  11123. }
  11124. onManifestLoaded(event, data) {
  11125. const {
  11126. contentSteering
  11127. } = data;
  11128. if (contentSteering === null) {
  11129. return;
  11130. }
  11131. this.pathwayId = contentSteering.pathwayId;
  11132. this.uri = contentSteering.uri;
  11133. if (this.started) {
  11134. this.startLoad();
  11135. }
  11136. }
  11137. onManifestParsed(event, data) {
  11138. this.audioTracks = data.audioTracks;
  11139. this.subtitleTracks = data.subtitleTracks;
  11140. }
  11141. onError(event, data) {
  11142. const {
  11143. errorAction
  11144. } = data;
  11145. if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox && errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost) {
  11146. const levels = this.levels;
  11147. let pathwayPriority = this._pathwayPriority;
  11148. let errorPathway = this.pathwayId;
  11149. if (data.context) {
  11150. const {
  11151. groupId,
  11152. pathwayId,
  11153. type
  11154. } = data.context;
  11155. if (groupId && levels) {
  11156. errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway);
  11157. } else if (pathwayId) {
  11158. errorPathway = pathwayId;
  11159. }
  11160. }
  11161. if (!(errorPathway in this.penalizedPathways)) {
  11162. this.penalizedPathways[errorPathway] = performance.now();
  11163. }
  11164. if (!pathwayPriority && levels) {
  11165. // If PATHWAY-PRIORITY was not provided, list pathways for error handling
  11166. pathwayPriority = this.pathways();
  11167. }
  11168. if (pathwayPriority && pathwayPriority.length > 1) {
  11169. this.updatePathwayPriority(pathwayPriority);
  11170. errorAction.resolved = this.pathwayId !== errorPathway;
  11171. }
  11172. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && !data.fatal) {
  11173. // Error will become fatal in buffer-controller when reaching `appendErrorMaxRetry`
  11174. // Stream-controllers are expected to reduce buffer length even if this is not deemed a QuotaExceededError
  11175. errorAction.resolved = true;
  11176. } else if (!errorAction.resolved) {
  11177. 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)}`);
  11178. }
  11179. }
  11180. }
  11181. filterParsedLevels(levels) {
  11182. // Filter levels to only include those that are in the initial pathway
  11183. this.levels = levels;
  11184. let pathwayLevels = this.getLevelsForPathway(this.pathwayId);
  11185. if (pathwayLevels.length === 0) {
  11186. const pathwayId = levels[0].pathwayId;
  11187. this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${pathwayId}"`);
  11188. pathwayLevels = this.getLevelsForPathway(pathwayId);
  11189. this.pathwayId = pathwayId;
  11190. }
  11191. if (pathwayLevels.length !== levels.length) {
  11192. this.log(`Found ${pathwayLevels.length}/${levels.length} levels in Pathway "${this.pathwayId}"`);
  11193. }
  11194. return pathwayLevels;
  11195. }
  11196. getLevelsForPathway(pathwayId) {
  11197. if (this.levels === null) {
  11198. return [];
  11199. }
  11200. return this.levels.filter(level => pathwayId === level.pathwayId);
  11201. }
  11202. updatePathwayPriority(pathwayPriority) {
  11203. this._pathwayPriority = pathwayPriority;
  11204. let levels;
  11205. // Evaluate if we should remove the pathway from the penalized list
  11206. const penalizedPathways = this.penalizedPathways;
  11207. const now = performance.now();
  11208. Object.keys(penalizedPathways).forEach(pathwayId => {
  11209. if (now - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {
  11210. delete penalizedPathways[pathwayId];
  11211. }
  11212. });
  11213. for (let i = 0; i < pathwayPriority.length; i++) {
  11214. const pathwayId = pathwayPriority[i];
  11215. if (pathwayId in penalizedPathways) {
  11216. continue;
  11217. }
  11218. if (pathwayId === this.pathwayId) {
  11219. return;
  11220. }
  11221. const selectedIndex = this.hls.nextLoadLevel;
  11222. const selectedLevel = this.hls.levels[selectedIndex];
  11223. levels = this.getLevelsForPathway(pathwayId);
  11224. if (levels.length > 0) {
  11225. this.log(`Setting Pathway to "${pathwayId}"`);
  11226. this.pathwayId = pathwayId;
  11227. reassignFragmentLevelIndexes(levels);
  11228. this.hls.trigger(Events.LEVELS_UPDATED, {
  11229. levels
  11230. });
  11231. // Set LevelController's level to trigger LEVEL_SWITCHING which loads playlist if needed
  11232. const levelAfterChange = this.hls.levels[selectedIndex];
  11233. if (selectedLevel && levelAfterChange && this.levels) {
  11234. if (levelAfterChange.attrs['STABLE-VARIANT-ID'] !== selectedLevel.attrs['STABLE-VARIANT-ID'] && levelAfterChange.bitrate !== selectedLevel.bitrate) {
  11235. this.log(`Unstable Pathways change from bitrate ${selectedLevel.bitrate} to ${levelAfterChange.bitrate}`);
  11236. }
  11237. this.hls.nextLoadLevel = selectedIndex;
  11238. }
  11239. break;
  11240. }
  11241. }
  11242. }
  11243. getPathwayForGroupId(groupId, type, defaultPathway) {
  11244. const levels = this.getLevelsForPathway(defaultPathway).concat(this.levels || []);
  11245. for (let i = 0; i < levels.length; i++) {
  11246. if (type === PlaylistContextType.AUDIO_TRACK && levels[i].hasAudioGroup(groupId) || type === PlaylistContextType.SUBTITLE_TRACK && levels[i].hasSubtitleGroup(groupId)) {
  11247. return levels[i].pathwayId;
  11248. }
  11249. }
  11250. return defaultPathway;
  11251. }
  11252. clonePathways(pathwayClones) {
  11253. const levels = this.levels;
  11254. if (!levels) {
  11255. return;
  11256. }
  11257. const audioGroupCloneMap = {};
  11258. const subtitleGroupCloneMap = {};
  11259. pathwayClones.forEach(pathwayClone => {
  11260. const {
  11261. ID: cloneId,
  11262. 'BASE-ID': baseId,
  11263. 'URI-REPLACEMENT': uriReplacement
  11264. } = pathwayClone;
  11265. if (levels.some(level => level.pathwayId === cloneId)) {
  11266. return;
  11267. }
  11268. const clonedVariants = this.getLevelsForPathway(baseId).map(baseLevel => {
  11269. const attributes = new AttrList(baseLevel.attrs);
  11270. attributes['PATHWAY-ID'] = cloneId;
  11271. const clonedAudioGroupId = attributes.AUDIO && `${attributes.AUDIO}_clone_${cloneId}`;
  11272. const clonedSubtitleGroupId = attributes.SUBTITLES && `${attributes.SUBTITLES}_clone_${cloneId}`;
  11273. if (clonedAudioGroupId) {
  11274. audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;
  11275. attributes.AUDIO = clonedAudioGroupId;
  11276. }
  11277. if (clonedSubtitleGroupId) {
  11278. subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;
  11279. attributes.SUBTITLES = clonedSubtitleGroupId;
  11280. }
  11281. const url = performUriReplacement(baseLevel.uri, attributes['STABLE-VARIANT-ID'], 'PER-VARIANT-URIS', uriReplacement);
  11282. const clonedLevel = new Level({
  11283. attrs: attributes,
  11284. audioCodec: baseLevel.audioCodec,
  11285. bitrate: baseLevel.bitrate,
  11286. height: baseLevel.height,
  11287. name: baseLevel.name,
  11288. url,
  11289. videoCodec: baseLevel.videoCodec,
  11290. width: baseLevel.width
  11291. });
  11292. if (baseLevel.audioGroups) {
  11293. for (let i = 1; i < baseLevel.audioGroups.length; i++) {
  11294. clonedLevel.addGroupId('audio', `${baseLevel.audioGroups[i]}_clone_${cloneId}`);
  11295. }
  11296. }
  11297. if (baseLevel.subtitleGroups) {
  11298. for (let i = 1; i < baseLevel.subtitleGroups.length; i++) {
  11299. clonedLevel.addGroupId('text', `${baseLevel.subtitleGroups[i]}_clone_${cloneId}`);
  11300. }
  11301. }
  11302. return clonedLevel;
  11303. });
  11304. levels.push(...clonedVariants);
  11305. cloneRenditionGroups(this.audioTracks, audioGroupCloneMap, uriReplacement, cloneId);
  11306. cloneRenditionGroups(this.subtitleTracks, subtitleGroupCloneMap, uriReplacement, cloneId);
  11307. });
  11308. }
  11309. loadSteeringManifest(uri) {
  11310. const config = this.hls.config;
  11311. const Loader = config.loader;
  11312. if (this.loader) {
  11313. this.loader.destroy();
  11314. }
  11315. this.loader = new Loader(config);
  11316. let url;
  11317. try {
  11318. url = new self.URL(uri);
  11319. } catch (error) {
  11320. this.enabled = false;
  11321. this.log(`Failed to parse Steering Manifest URI: ${uri}`);
  11322. return;
  11323. }
  11324. if (url.protocol !== 'data:') {
  11325. const throughput = (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;
  11326. url.searchParams.set('_HLS_pathway', this.pathwayId);
  11327. url.searchParams.set('_HLS_throughput', '' + throughput);
  11328. }
  11329. const context = {
  11330. responseType: 'json',
  11331. url: url.href
  11332. };
  11333. const loadPolicy = config.steeringManifestLoadPolicy.default;
  11334. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  11335. const loaderConfig = {
  11336. loadPolicy,
  11337. timeout: loadPolicy.maxLoadTimeMs,
  11338. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  11339. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  11340. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  11341. };
  11342. const callbacks = {
  11343. onSuccess: (response, stats, context, networkDetails) => {
  11344. this.log(`Loaded steering manifest: "${url}"`);
  11345. const steeringData = response.data;
  11346. if ((steeringData == null ? void 0 : steeringData.VERSION) !== 1) {
  11347. this.log(`Steering VERSION ${steeringData.VERSION} not supported!`);
  11348. return;
  11349. }
  11350. this.updated = performance.now();
  11351. this.timeToLoad = steeringData.TTL;
  11352. const {
  11353. 'RELOAD-URI': reloadUri,
  11354. 'PATHWAY-CLONES': pathwayClones,
  11355. 'PATHWAY-PRIORITY': pathwayPriority
  11356. } = steeringData;
  11357. if (reloadUri) {
  11358. try {
  11359. this.uri = new self.URL(reloadUri, url).href;
  11360. } catch (error) {
  11361. this.enabled = false;
  11362. this.log(`Failed to parse Steering Manifest RELOAD-URI: ${reloadUri}`);
  11363. return;
  11364. }
  11365. }
  11366. this.scheduleRefresh(this.uri || context.url);
  11367. if (pathwayClones) {
  11368. this.clonePathways(pathwayClones);
  11369. }
  11370. const loadedSteeringData = {
  11371. steeringManifest: steeringData,
  11372. url: url.toString()
  11373. };
  11374. this.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);
  11375. if (pathwayPriority) {
  11376. this.updatePathwayPriority(pathwayPriority);
  11377. }
  11378. },
  11379. onError: (error, context, networkDetails, stats) => {
  11380. this.log(`Error loading steering manifest: ${error.code} ${error.text} (${context.url})`);
  11381. this.stopLoad();
  11382. if (error.code === 410) {
  11383. this.enabled = false;
  11384. this.log(`Steering manifest ${context.url} no longer available`);
  11385. return;
  11386. }
  11387. let ttl = this.timeToLoad * 1000;
  11388. if (error.code === 429) {
  11389. const loader = this.loader;
  11390. if (typeof (loader == null ? void 0 : loader.getResponseHeader) === 'function') {
  11391. const retryAfter = loader.getResponseHeader('Retry-After');
  11392. if (retryAfter) {
  11393. ttl = parseFloat(retryAfter) * 1000;
  11394. }
  11395. }
  11396. this.log(`Steering manifest ${context.url} rate limited`);
  11397. return;
  11398. }
  11399. this.scheduleRefresh(this.uri || context.url, ttl);
  11400. },
  11401. onTimeout: (stats, context, networkDetails) => {
  11402. this.log(`Timeout loading steering manifest (${context.url})`);
  11403. this.scheduleRefresh(this.uri || context.url);
  11404. }
  11405. };
  11406. this.log(`Requesting steering manifest: ${url}`);
  11407. this.loader.load(context, loaderConfig, callbacks);
  11408. }
  11409. scheduleRefresh(uri, ttlMs = this.timeToLoad * 1000) {
  11410. this.clearTimeout();
  11411. this.reloadTimer = self.setTimeout(() => {
  11412. var _this$hls;
  11413. const media = (_this$hls = this.hls) == null ? void 0 : _this$hls.media;
  11414. if (media && !media.ended) {
  11415. this.loadSteeringManifest(uri);
  11416. return;
  11417. }
  11418. this.scheduleRefresh(uri, this.timeToLoad * 1000);
  11419. }, ttlMs);
  11420. }
  11421. }
  11422. function cloneRenditionGroups(tracks, groupCloneMap, uriReplacement, cloneId) {
  11423. if (!tracks) {
  11424. return;
  11425. }
  11426. Object.keys(groupCloneMap).forEach(audioGroupId => {
  11427. const clonedTracks = tracks.filter(track => track.groupId === audioGroupId).map(track => {
  11428. const clonedTrack = _extends({}, track);
  11429. clonedTrack.details = undefined;
  11430. clonedTrack.attrs = new AttrList(clonedTrack.attrs);
  11431. clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(track.url, track.attrs['STABLE-RENDITION-ID'], 'PER-RENDITION-URIS', uriReplacement);
  11432. clonedTrack.groupId = clonedTrack.attrs['GROUP-ID'] = groupCloneMap[audioGroupId];
  11433. clonedTrack.attrs['PATHWAY-ID'] = cloneId;
  11434. return clonedTrack;
  11435. });
  11436. tracks.push(...clonedTracks);
  11437. });
  11438. }
  11439. function performUriReplacement(uri, stableId, perOptionKey, uriReplacement) {
  11440. const {
  11441. HOST: host,
  11442. PARAMS: params,
  11443. [perOptionKey]: perOptionUris
  11444. } = uriReplacement;
  11445. let perVariantUri;
  11446. if (stableId) {
  11447. perVariantUri = perOptionUris == null ? void 0 : perOptionUris[stableId];
  11448. if (perVariantUri) {
  11449. uri = perVariantUri;
  11450. }
  11451. }
  11452. const url = new self.URL(uri);
  11453. if (host && !perVariantUri) {
  11454. url.host = host;
  11455. }
  11456. if (params) {
  11457. Object.keys(params).sort().forEach(key => {
  11458. if (key) {
  11459. url.searchParams.set(key, params[key]);
  11460. }
  11461. });
  11462. }
  11463. return url.href;
  11464. }
  11465. class FPSController {
  11466. constructor(hls) {
  11467. this.hls = void 0;
  11468. this.isVideoPlaybackQualityAvailable = false;
  11469. this.timer = void 0;
  11470. this.media = null;
  11471. this.lastTime = void 0;
  11472. this.lastDroppedFrames = 0;
  11473. this.lastDecodedFrames = 0;
  11474. // stream controller must be provided as a dependency!
  11475. this.streamController = void 0;
  11476. this.hls = hls;
  11477. this.registerListeners();
  11478. }
  11479. setStreamController(streamController) {
  11480. this.streamController = streamController;
  11481. }
  11482. registerListeners() {
  11483. this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  11484. this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  11485. }
  11486. unregisterListeners() {
  11487. this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  11488. this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  11489. }
  11490. destroy() {
  11491. if (this.timer) {
  11492. clearInterval(this.timer);
  11493. }
  11494. this.unregisterListeners();
  11495. this.isVideoPlaybackQualityAvailable = false;
  11496. this.media = null;
  11497. }
  11498. onMediaAttaching(event, data) {
  11499. const config = this.hls.config;
  11500. if (config.capLevelOnFPSDrop) {
  11501. const media = data.media instanceof self.HTMLVideoElement ? data.media : null;
  11502. this.media = media;
  11503. if (media && typeof media.getVideoPlaybackQuality === 'function') {
  11504. this.isVideoPlaybackQualityAvailable = true;
  11505. }
  11506. self.clearInterval(this.timer);
  11507. this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  11508. }
  11509. }
  11510. onMediaDetaching() {
  11511. this.media = null;
  11512. }
  11513. checkFPS(video, decodedFrames, droppedFrames) {
  11514. const currentTime = performance.now();
  11515. if (decodedFrames) {
  11516. if (this.lastTime) {
  11517. const currentPeriod = currentTime - this.lastTime;
  11518. const currentDropped = droppedFrames - this.lastDroppedFrames;
  11519. const currentDecoded = decodedFrames - this.lastDecodedFrames;
  11520. const droppedFPS = 1000 * currentDropped / currentPeriod;
  11521. const hls = this.hls;
  11522. hls.trigger(Events.FPS_DROP, {
  11523. currentDropped: currentDropped,
  11524. currentDecoded: currentDecoded,
  11525. totalDroppedFrames: droppedFrames
  11526. });
  11527. if (droppedFPS > 0) {
  11528. // hls.logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
  11529. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  11530. let currentLevel = hls.currentLevel;
  11531. hls.logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
  11532. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  11533. currentLevel = currentLevel - 1;
  11534. hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {
  11535. level: currentLevel,
  11536. droppedLevel: hls.currentLevel
  11537. });
  11538. hls.autoLevelCapping = currentLevel;
  11539. this.streamController.nextLevelSwitch();
  11540. }
  11541. }
  11542. }
  11543. }
  11544. this.lastTime = currentTime;
  11545. this.lastDroppedFrames = droppedFrames;
  11546. this.lastDecodedFrames = decodedFrames;
  11547. }
  11548. }
  11549. checkFPSInterval() {
  11550. const video = this.media;
  11551. if (video) {
  11552. if (this.isVideoPlaybackQualityAvailable) {
  11553. const videoPlaybackQuality = video.getVideoPlaybackQuality();
  11554. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  11555. } else {
  11556. // HTMLVideoElement doesn't include the webkit types
  11557. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  11558. }
  11559. }
  11560. }
  11561. }
  11562. /**
  11563. * Generate a random v4 UUID
  11564. *
  11565. * @returns A random v4 UUID
  11566. *
  11567. * @group Utils
  11568. *
  11569. * @beta
  11570. */
  11571. function uuid() {
  11572. try {
  11573. return crypto.randomUUID();
  11574. } catch (error) {
  11575. try {
  11576. const url = URL.createObjectURL(new Blob());
  11577. const uuid = url.toString();
  11578. URL.revokeObjectURL(url);
  11579. return uuid.slice(uuid.lastIndexOf('/') + 1);
  11580. } catch (error) {
  11581. let dt = new Date().getTime();
  11582. const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
  11583. const r = (dt + Math.random() * 16) % 16 | 0;
  11584. dt = Math.floor(dt / 16);
  11585. return (c == 'x' ? r : r & 0x3 | 0x8).toString(16);
  11586. });
  11587. return uuid;
  11588. }
  11589. }
  11590. }
  11591. var eventemitter3 = {exports: {}};
  11592. var hasRequiredEventemitter3;
  11593. function requireEventemitter3 () {
  11594. if (hasRequiredEventemitter3) return eventemitter3.exports;
  11595. hasRequiredEventemitter3 = 1;
  11596. (function (module) {
  11597. var has = Object.prototype.hasOwnProperty
  11598. , prefix = '~';
  11599. /**
  11600. * Constructor to create a storage for our `EE` objects.
  11601. * An `Events` instance is a plain object whose properties are event names.
  11602. *
  11603. * @constructor
  11604. * @private
  11605. */
  11606. function Events() {}
  11607. //
  11608. // We try to not inherit from `Object.prototype`. In some engines creating an
  11609. // instance in this way is faster than calling `Object.create(null)` directly.
  11610. // If `Object.create(null)` is not supported we prefix the event names with a
  11611. // character to make sure that the built-in object properties are not
  11612. // overridden or used as an attack vector.
  11613. //
  11614. if (Object.create) {
  11615. Events.prototype = Object.create(null);
  11616. //
  11617. // This hack is needed because the `__proto__` property is still inherited in
  11618. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  11619. //
  11620. if (!new Events().__proto__) prefix = false;
  11621. }
  11622. /**
  11623. * Representation of a single event listener.
  11624. *
  11625. * @param {Function} fn The listener function.
  11626. * @param {*} context The context to invoke the listener with.
  11627. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  11628. * @constructor
  11629. * @private
  11630. */
  11631. function EE(fn, context, once) {
  11632. this.fn = fn;
  11633. this.context = context;
  11634. this.once = once || false;
  11635. }
  11636. /**
  11637. * Add a listener for a given event.
  11638. *
  11639. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  11640. * @param {(String|Symbol)} event The event name.
  11641. * @param {Function} fn The listener function.
  11642. * @param {*} context The context to invoke the listener with.
  11643. * @param {Boolean} once Specify if the listener is a one-time listener.
  11644. * @returns {EventEmitter}
  11645. * @private
  11646. */
  11647. function addListener(emitter, event, fn, context, once) {
  11648. if (typeof fn !== 'function') {
  11649. throw new TypeError('The listener must be a function');
  11650. }
  11651. var listener = new EE(fn, context || emitter, once)
  11652. , evt = prefix ? prefix + event : event;
  11653. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  11654. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  11655. else emitter._events[evt] = [emitter._events[evt], listener];
  11656. return emitter;
  11657. }
  11658. /**
  11659. * Clear event by name.
  11660. *
  11661. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  11662. * @param {(String|Symbol)} evt The Event name.
  11663. * @private
  11664. */
  11665. function clearEvent(emitter, evt) {
  11666. if (--emitter._eventsCount === 0) emitter._events = new Events();
  11667. else delete emitter._events[evt];
  11668. }
  11669. /**
  11670. * Minimal `EventEmitter` interface that is molded against the Node.js
  11671. * `EventEmitter` interface.
  11672. *
  11673. * @constructor
  11674. * @public
  11675. */
  11676. function EventEmitter() {
  11677. this._events = new Events();
  11678. this._eventsCount = 0;
  11679. }
  11680. /**
  11681. * Return an array listing the events for which the emitter has registered
  11682. * listeners.
  11683. *
  11684. * @returns {Array}
  11685. * @public
  11686. */
  11687. EventEmitter.prototype.eventNames = function eventNames() {
  11688. var names = []
  11689. , events
  11690. , name;
  11691. if (this._eventsCount === 0) return names;
  11692. for (name in (events = this._events)) {
  11693. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  11694. }
  11695. if (Object.getOwnPropertySymbols) {
  11696. return names.concat(Object.getOwnPropertySymbols(events));
  11697. }
  11698. return names;
  11699. };
  11700. /**
  11701. * Return the listeners registered for a given event.
  11702. *
  11703. * @param {(String|Symbol)} event The event name.
  11704. * @returns {Array} The registered listeners.
  11705. * @public
  11706. */
  11707. EventEmitter.prototype.listeners = function listeners(event) {
  11708. var evt = prefix ? prefix + event : event
  11709. , handlers = this._events[evt];
  11710. if (!handlers) return [];
  11711. if (handlers.fn) return [handlers.fn];
  11712. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  11713. ee[i] = handlers[i].fn;
  11714. }
  11715. return ee;
  11716. };
  11717. /**
  11718. * Return the number of listeners listening to a given event.
  11719. *
  11720. * @param {(String|Symbol)} event The event name.
  11721. * @returns {Number} The number of listeners.
  11722. * @public
  11723. */
  11724. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  11725. var evt = prefix ? prefix + event : event
  11726. , listeners = this._events[evt];
  11727. if (!listeners) return 0;
  11728. if (listeners.fn) return 1;
  11729. return listeners.length;
  11730. };
  11731. /**
  11732. * Calls each of the listeners registered for a given event.
  11733. *
  11734. * @param {(String|Symbol)} event The event name.
  11735. * @returns {Boolean} `true` if the event had listeners, else `false`.
  11736. * @public
  11737. */
  11738. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  11739. var evt = prefix ? prefix + event : event;
  11740. if (!this._events[evt]) return false;
  11741. var listeners = this._events[evt]
  11742. , len = arguments.length
  11743. , args
  11744. , i;
  11745. if (listeners.fn) {
  11746. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  11747. switch (len) {
  11748. case 1: return listeners.fn.call(listeners.context), true;
  11749. case 2: return listeners.fn.call(listeners.context, a1), true;
  11750. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  11751. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  11752. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  11753. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  11754. }
  11755. for (i = 1, args = new Array(len -1); i < len; i++) {
  11756. args[i - 1] = arguments[i];
  11757. }
  11758. listeners.fn.apply(listeners.context, args);
  11759. } else {
  11760. var length = listeners.length
  11761. , j;
  11762. for (i = 0; i < length; i++) {
  11763. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  11764. switch (len) {
  11765. case 1: listeners[i].fn.call(listeners[i].context); break;
  11766. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  11767. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  11768. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  11769. default:
  11770. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  11771. args[j - 1] = arguments[j];
  11772. }
  11773. listeners[i].fn.apply(listeners[i].context, args);
  11774. }
  11775. }
  11776. }
  11777. return true;
  11778. };
  11779. /**
  11780. * Add a listener for a given event.
  11781. *
  11782. * @param {(String|Symbol)} event The event name.
  11783. * @param {Function} fn The listener function.
  11784. * @param {*} [context=this] The context to invoke the listener with.
  11785. * @returns {EventEmitter} `this`.
  11786. * @public
  11787. */
  11788. EventEmitter.prototype.on = function on(event, fn, context) {
  11789. return addListener(this, event, fn, context, false);
  11790. };
  11791. /**
  11792. * Add a one-time listener for a given event.
  11793. *
  11794. * @param {(String|Symbol)} event The event name.
  11795. * @param {Function} fn The listener function.
  11796. * @param {*} [context=this] The context to invoke the listener with.
  11797. * @returns {EventEmitter} `this`.
  11798. * @public
  11799. */
  11800. EventEmitter.prototype.once = function once(event, fn, context) {
  11801. return addListener(this, event, fn, context, true);
  11802. };
  11803. /**
  11804. * Remove the listeners of a given event.
  11805. *
  11806. * @param {(String|Symbol)} event The event name.
  11807. * @param {Function} fn Only remove the listeners that match this function.
  11808. * @param {*} context Only remove the listeners that have this context.
  11809. * @param {Boolean} once Only remove one-time listeners.
  11810. * @returns {EventEmitter} `this`.
  11811. * @public
  11812. */
  11813. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  11814. var evt = prefix ? prefix + event : event;
  11815. if (!this._events[evt]) return this;
  11816. if (!fn) {
  11817. clearEvent(this, evt);
  11818. return this;
  11819. }
  11820. var listeners = this._events[evt];
  11821. if (listeners.fn) {
  11822. if (
  11823. listeners.fn === fn &&
  11824. (!once || listeners.once) &&
  11825. (!context || listeners.context === context)
  11826. ) {
  11827. clearEvent(this, evt);
  11828. }
  11829. } else {
  11830. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  11831. if (
  11832. listeners[i].fn !== fn ||
  11833. (once && !listeners[i].once) ||
  11834. (context && listeners[i].context !== context)
  11835. ) {
  11836. events.push(listeners[i]);
  11837. }
  11838. }
  11839. //
  11840. // Reset the array, or remove it completely if we have no more listeners.
  11841. //
  11842. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  11843. else clearEvent(this, evt);
  11844. }
  11845. return this;
  11846. };
  11847. /**
  11848. * Remove all listeners, or those of the specified event.
  11849. *
  11850. * @param {(String|Symbol)} [event] The event name.
  11851. * @returns {EventEmitter} `this`.
  11852. * @public
  11853. */
  11854. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  11855. var evt;
  11856. if (event) {
  11857. evt = prefix ? prefix + event : event;
  11858. if (this._events[evt]) clearEvent(this, evt);
  11859. } else {
  11860. this._events = new Events();
  11861. this._eventsCount = 0;
  11862. }
  11863. return this;
  11864. };
  11865. //
  11866. // Alias methods names because people roll like that.
  11867. //
  11868. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  11869. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  11870. //
  11871. // Expose the prefix.
  11872. //
  11873. EventEmitter.prefixed = prefix;
  11874. //
  11875. // Allow `EventEmitter` to be imported as module namespace.
  11876. //
  11877. EventEmitter.EventEmitter = EventEmitter;
  11878. //
  11879. // Expose the module.
  11880. //
  11881. {
  11882. module.exports = EventEmitter;
  11883. }
  11884. } (eventemitter3));
  11885. return eventemitter3.exports;
  11886. }
  11887. var eventemitter3Exports = requireEventemitter3();
  11888. var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventemitter3Exports);
  11889. class ChunkCache {
  11890. constructor() {
  11891. this.chunks = [];
  11892. this.dataLength = 0;
  11893. }
  11894. push(chunk) {
  11895. this.chunks.push(chunk);
  11896. this.dataLength += chunk.length;
  11897. }
  11898. flush() {
  11899. const {
  11900. chunks,
  11901. dataLength
  11902. } = this;
  11903. let result;
  11904. if (!chunks.length) {
  11905. return new Uint8Array(0);
  11906. } else if (chunks.length === 1) {
  11907. result = chunks[0];
  11908. } else {
  11909. result = concatUint8Arrays(chunks, dataLength);
  11910. }
  11911. this.reset();
  11912. return result;
  11913. }
  11914. reset() {
  11915. this.chunks.length = 0;
  11916. this.dataLength = 0;
  11917. }
  11918. }
  11919. function concatUint8Arrays(chunks, dataLength) {
  11920. const result = new Uint8Array(dataLength);
  11921. let offset = 0;
  11922. for (let i = 0; i < chunks.length; i++) {
  11923. const chunk = chunks[i];
  11924. result.set(chunk, offset);
  11925. offset += chunk.length;
  11926. }
  11927. return result;
  11928. }
  11929. /**
  11930. * Returns true if an ID3 footer can be found at offset in data
  11931. *
  11932. * @param data - The data to search in
  11933. * @param offset - The offset at which to start searching
  11934. *
  11935. * @returns `true` if an ID3 footer is found
  11936. *
  11937. * @internal
  11938. *
  11939. * @group ID3
  11940. */
  11941. function isId3Footer(data, offset) {
  11942. /*
  11943. * The footer is a copy of the header, but with a different identifier
  11944. */
  11945. if (offset + 10 <= data.length) {
  11946. // look for '3DI' identifier
  11947. if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
  11948. // check version is within range
  11949. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  11950. // check size is within range
  11951. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  11952. return true;
  11953. }
  11954. }
  11955. }
  11956. }
  11957. return false;
  11958. }
  11959. /**
  11960. * Returns true if an ID3 header can be found at offset in data
  11961. *
  11962. * @param data - The data to search in
  11963. * @param offset - The offset at which to start searching
  11964. *
  11965. * @returns `true` if an ID3 header is found
  11966. *
  11967. * @internal
  11968. *
  11969. * @group ID3
  11970. */
  11971. function isId3Header(data, offset) {
  11972. /*
  11973. * http://id3.org/id3v2.3.0
  11974. * [0] = 'I'
  11975. * [1] = 'D'
  11976. * [2] = '3'
  11977. * [3,4] = {Version}
  11978. * [5] = {Flags}
  11979. * [6-9] = {ID3 Size}
  11980. *
  11981. * An ID3v2 tag can be detected with the following pattern:
  11982. * $49 44 33 yy yy xx zz zz zz zz
  11983. * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
  11984. */
  11985. if (offset + 10 <= data.length) {
  11986. // look for 'ID3' identifier
  11987. if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
  11988. // check version is within range
  11989. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  11990. // check size is within range
  11991. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  11992. return true;
  11993. }
  11994. }
  11995. }
  11996. }
  11997. return false;
  11998. }
  11999. /**
  12000. * Read ID3 size
  12001. *
  12002. * @param data - The data to read from
  12003. * @param offset - The offset at which to start reading
  12004. *
  12005. * @returns The size
  12006. *
  12007. * @internal
  12008. *
  12009. * @group ID3
  12010. */
  12011. function readId3Size(data, offset) {
  12012. let size = 0;
  12013. size = (data[offset] & 0x7f) << 21;
  12014. size |= (data[offset + 1] & 0x7f) << 14;
  12015. size |= (data[offset + 2] & 0x7f) << 7;
  12016. size |= data[offset + 3] & 0x7f;
  12017. return size;
  12018. }
  12019. /**
  12020. * Returns any adjacent ID3 tags found in data starting at offset, as one block of data
  12021. *
  12022. * @param data - The data to search in
  12023. * @param offset - The offset at which to start searching
  12024. *
  12025. * @returns The block of data containing any ID3 tags found
  12026. * or `undefined` if no header is found at the starting offset
  12027. *
  12028. * @internal
  12029. *
  12030. * @group ID3
  12031. */
  12032. function getId3Data(data, offset) {
  12033. const front = offset;
  12034. let length = 0;
  12035. while (isId3Header(data, offset)) {
  12036. // ID3 header is 10 bytes
  12037. length += 10;
  12038. const size = readId3Size(data, offset + 6);
  12039. length += size;
  12040. if (isId3Footer(data, offset + 10)) {
  12041. // ID3 footer is 10 bytes
  12042. length += 10;
  12043. }
  12044. offset += length;
  12045. }
  12046. if (length > 0) {
  12047. return data.subarray(front, front + length);
  12048. }
  12049. return undefined;
  12050. }
  12051. function getAudioConfig(observer, data, offset, manifestCodec) {
  12052. const adtsSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  12053. const byte2 = data[offset + 2];
  12054. const adtsSamplingIndex = byte2 >> 2 & 0xf;
  12055. if (adtsSamplingIndex > 12) {
  12056. const error = new Error(`invalid ADTS sampling index:${adtsSamplingIndex}`);
  12057. observer.emit(Events.ERROR, Events.ERROR, {
  12058. type: ErrorTypes.MEDIA_ERROR,
  12059. details: ErrorDetails.FRAG_PARSING_ERROR,
  12060. fatal: true,
  12061. error,
  12062. reason: error.message
  12063. });
  12064. return;
  12065. }
  12066. // MPEG-4 Audio Object Type (profile_ObjectType+1)
  12067. const adtsObjectType = (byte2 >> 6 & 0x3) + 1;
  12068. const channelCount = data[offset + 3] >> 6 & 0x3 | (byte2 & 1) << 2;
  12069. const codec = 'mp4a.40.' + adtsObjectType;
  12070. /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  12071. ISO/IEC 14496-3 - Table 1.13 — Syntax of AudioSpecificConfig()
  12072. Audio Profile / Audio Object Type
  12073. 0: Null
  12074. 1: AAC Main
  12075. 2: AAC LC (Low Complexity)
  12076. 3: AAC SSR (Scalable Sample Rate)
  12077. 4: AAC LTP (Long Term Prediction)
  12078. 5: SBR (Spectral Band Replication)
  12079. 6: AAC Scalable
  12080. sampling freq
  12081. 0: 96000 Hz
  12082. 1: 88200 Hz
  12083. 2: 64000 Hz
  12084. 3: 48000 Hz
  12085. 4: 44100 Hz
  12086. 5: 32000 Hz
  12087. 6: 24000 Hz
  12088. 7: 22050 Hz
  12089. 8: 16000 Hz
  12090. 9: 12000 Hz
  12091. 10: 11025 Hz
  12092. 11: 8000 Hz
  12093. 12: 7350 Hz
  12094. 13: Reserved
  12095. 14: Reserved
  12096. 15: frequency is written explictly
  12097. Channel Configurations
  12098. These are the channel configurations:
  12099. 0: Defined in AOT Specifc Config
  12100. 1: 1 channel: front-center
  12101. 2: 2 channels: front-left, front-right
  12102. */
  12103. // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  12104. const samplerate = adtsSamplingRates[adtsSamplingIndex];
  12105. let aacSampleIndex = adtsSamplingIndex;
  12106. if (adtsObjectType === 5 || adtsObjectType === 29) {
  12107. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  12108. // there is a factor 2 between frame sample rate and output sample rate
  12109. // multiply frequency by 2 (see table above, equivalent to substract 3)
  12110. aacSampleIndex -= 3;
  12111. }
  12112. const config = [adtsObjectType << 3 | (aacSampleIndex & 0x0e) >> 1, (aacSampleIndex & 0x01) << 7 | channelCount << 3];
  12113. logger.log(`manifest codec:${manifestCodec}, parsed codec:${codec}, channels:${channelCount}, rate:${samplerate} (ADTS object type:${adtsObjectType} sampling index:${adtsSamplingIndex})`);
  12114. return {
  12115. config,
  12116. samplerate,
  12117. channelCount,
  12118. codec,
  12119. parsedCodec: codec,
  12120. manifestCodec
  12121. };
  12122. }
  12123. function isHeaderPattern$1(data, offset) {
  12124. return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
  12125. }
  12126. function getHeaderLength(data, offset) {
  12127. return data[offset + 1] & 0x01 ? 7 : 9;
  12128. }
  12129. function getFullFrameLength(data, offset) {
  12130. return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xe0) >>> 5;
  12131. }
  12132. function canGetFrameLength(data, offset) {
  12133. return offset + 5 < data.length;
  12134. }
  12135. function isHeader$1(data, offset) {
  12136. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  12137. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  12138. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  12139. return offset + 1 < data.length && isHeaderPattern$1(data, offset);
  12140. }
  12141. function canParse$1(data, offset) {
  12142. return canGetFrameLength(data, offset) && isHeaderPattern$1(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
  12143. }
  12144. function probe$1(data, offset) {
  12145. // same as isHeader but we also check that ADTS frame follows last ADTS frame
  12146. // or end of data is reached
  12147. if (isHeader$1(data, offset)) {
  12148. // ADTS header Length
  12149. const headerLength = getHeaderLength(data, offset);
  12150. if (offset + headerLength >= data.length) {
  12151. return false;
  12152. }
  12153. // ADTS frame Length
  12154. const frameLength = getFullFrameLength(data, offset);
  12155. if (frameLength <= headerLength) {
  12156. return false;
  12157. }
  12158. const newOffset = offset + frameLength;
  12159. return newOffset === data.length || isHeader$1(data, newOffset);
  12160. }
  12161. return false;
  12162. }
  12163. function initTrackConfig(track, observer, data, offset, audioCodec) {
  12164. if (!track.samplerate) {
  12165. const config = getAudioConfig(observer, data, offset, audioCodec);
  12166. if (!config) {
  12167. return;
  12168. }
  12169. _extends(track, config);
  12170. }
  12171. }
  12172. function getFrameDuration(samplerate) {
  12173. return 1024 * 90000 / samplerate;
  12174. }
  12175. function parseFrameHeader(data, offset) {
  12176. // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  12177. const headerLength = getHeaderLength(data, offset);
  12178. if (offset + headerLength <= data.length) {
  12179. // retrieve frame size
  12180. const frameLength = getFullFrameLength(data, offset) - headerLength;
  12181. if (frameLength > 0) {
  12182. // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}`);
  12183. return {
  12184. headerLength,
  12185. frameLength
  12186. };
  12187. }
  12188. }
  12189. }
  12190. function appendFrame$1(track, data, offset, pts, frameIndex) {
  12191. const frameDuration = getFrameDuration(track.samplerate);
  12192. const stamp = pts + frameIndex * frameDuration;
  12193. const header = parseFrameHeader(data, offset);
  12194. let unit;
  12195. if (header) {
  12196. const {
  12197. frameLength,
  12198. headerLength
  12199. } = header;
  12200. const _length = headerLength + frameLength;
  12201. const missing = Math.max(0, offset + _length - data.length);
  12202. // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);
  12203. if (missing) {
  12204. unit = new Uint8Array(_length - headerLength);
  12205. unit.set(data.subarray(offset + headerLength, data.length), 0);
  12206. } else {
  12207. unit = data.subarray(offset + headerLength, offset + _length);
  12208. }
  12209. const _sample = {
  12210. unit,
  12211. pts: stamp
  12212. };
  12213. if (!missing) {
  12214. track.samples.push(_sample);
  12215. }
  12216. return {
  12217. sample: _sample,
  12218. length: _length,
  12219. missing
  12220. };
  12221. }
  12222. // overflow incomplete header
  12223. const length = data.length - offset;
  12224. unit = new Uint8Array(length);
  12225. unit.set(data.subarray(offset, data.length), 0);
  12226. const sample = {
  12227. unit,
  12228. pts: stamp
  12229. };
  12230. return {
  12231. sample,
  12232. length,
  12233. missing: -1
  12234. };
  12235. }
  12236. /**
  12237. * Checks if the given data contains an ID3 tag.
  12238. *
  12239. * @param data - The data to check
  12240. * @param offset - The offset at which to start checking
  12241. *
  12242. * @returns `true` if an ID3 tag is found
  12243. *
  12244. * @group ID3
  12245. *
  12246. * @beta
  12247. */
  12248. function canParseId3(data, offset) {
  12249. return isId3Header(data, offset) && readId3Size(data, offset + 6) + 10 <= data.length - offset;
  12250. }
  12251. function toArrayBuffer(view) {
  12252. if (view instanceof ArrayBuffer) {
  12253. return view;
  12254. } else {
  12255. if (view.byteOffset == 0 && view.byteLength == view.buffer.byteLength) {
  12256. // This is a TypedArray over the whole buffer.
  12257. return view.buffer;
  12258. }
  12259. // This is a 'view' on the buffer. Create a new buffer that only contains
  12260. // the data. Note that since this isn't an ArrayBuffer, the 'new' call
  12261. // will allocate a new buffer to hold the copy.
  12262. return new Uint8Array(view).buffer;
  12263. }
  12264. }
  12265. function toUint8(data, offset = 0, length = Infinity) {
  12266. return view(data, offset, length, Uint8Array);
  12267. }
  12268. function view(data, offset, length, Type) {
  12269. const buffer = unsafeGetArrayBuffer(data);
  12270. let bytesPerElement = 1;
  12271. if ('BYTES_PER_ELEMENT' in Type) {
  12272. bytesPerElement = Type.BYTES_PER_ELEMENT;
  12273. }
  12274. // Absolute end of the |data| view within |buffer|.
  12275. const dataOffset = isArrayBufferView(data) ? data.byteOffset : 0;
  12276. const dataEnd = (dataOffset + data.byteLength) / bytesPerElement;
  12277. // Absolute start of the result within |buffer|.
  12278. const rawStart = (dataOffset + offset) / bytesPerElement;
  12279. const start = Math.floor(Math.max(0, Math.min(rawStart, dataEnd)));
  12280. // Absolute end of the result within |buffer|.
  12281. const end = Math.floor(Math.min(start + Math.max(length, 0), dataEnd));
  12282. return new Type(buffer, start, end - start);
  12283. }
  12284. function unsafeGetArrayBuffer(view) {
  12285. if (view instanceof ArrayBuffer) {
  12286. return view;
  12287. } else {
  12288. return view.buffer;
  12289. }
  12290. }
  12291. function isArrayBufferView(obj) {
  12292. return obj && obj.buffer instanceof ArrayBuffer && obj.byteLength !== undefined && obj.byteOffset !== undefined;
  12293. }
  12294. function decodeId3ImageFrame(frame) {
  12295. const metadataFrame = {
  12296. key: frame.type,
  12297. description: '',
  12298. data: '',
  12299. mimeType: null,
  12300. pictureType: null
  12301. };
  12302. const utf8Encoding = 0x03;
  12303. if (frame.size < 2) {
  12304. return undefined;
  12305. }
  12306. if (frame.data[0] !== utf8Encoding) {
  12307. console.log('Ignore frame with unrecognized character ' + 'encoding');
  12308. return undefined;
  12309. }
  12310. const mimeTypeEndIndex = frame.data.subarray(1).indexOf(0);
  12311. if (mimeTypeEndIndex === -1) {
  12312. return undefined;
  12313. }
  12314. const mimeType = utf8ArrayToStr(toUint8(frame.data, 1, mimeTypeEndIndex));
  12315. const pictureType = frame.data[2 + mimeTypeEndIndex];
  12316. const descriptionEndIndex = frame.data.subarray(3 + mimeTypeEndIndex).indexOf(0);
  12317. if (descriptionEndIndex === -1) {
  12318. return undefined;
  12319. }
  12320. const description = utf8ArrayToStr(toUint8(frame.data, 3 + mimeTypeEndIndex, descriptionEndIndex));
  12321. let data;
  12322. if (mimeType === '-->') {
  12323. data = utf8ArrayToStr(toUint8(frame.data, 4 + mimeTypeEndIndex + descriptionEndIndex));
  12324. } else {
  12325. data = toArrayBuffer(frame.data.subarray(4 + mimeTypeEndIndex + descriptionEndIndex));
  12326. }
  12327. metadataFrame.mimeType = mimeType;
  12328. metadataFrame.pictureType = pictureType;
  12329. metadataFrame.description = description;
  12330. metadataFrame.data = data;
  12331. return metadataFrame;
  12332. }
  12333. /**
  12334. * Decode an ID3 PRIV frame.
  12335. *
  12336. * @param frame - the ID3 PRIV frame
  12337. *
  12338. * @returns The decoded ID3 PRIV frame
  12339. *
  12340. * @internal
  12341. *
  12342. * @group ID3
  12343. */
  12344. function decodeId3PrivFrame(frame) {
  12345. /*
  12346. Format: <text string>\0<binary data>
  12347. */
  12348. if (frame.size < 2) {
  12349. return undefined;
  12350. }
  12351. const owner = utf8ArrayToStr(frame.data, true);
  12352. const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  12353. return {
  12354. key: frame.type,
  12355. info: owner,
  12356. data: privateData.buffer
  12357. };
  12358. }
  12359. /**
  12360. * Decodes an ID3 text frame
  12361. *
  12362. * @param frame - the ID3 text frame
  12363. *
  12364. * @returns The decoded ID3 text frame
  12365. *
  12366. * @internal
  12367. *
  12368. * @group ID3
  12369. */
  12370. function decodeId3TextFrame(frame) {
  12371. if (frame.size < 2) {
  12372. return undefined;
  12373. }
  12374. if (frame.type === 'TXXX') {
  12375. /*
  12376. Format:
  12377. [0] = {Text Encoding}
  12378. [1-?] = {Description}\0{Value}
  12379. */
  12380. let index = 1;
  12381. const description = utf8ArrayToStr(frame.data.subarray(index), true);
  12382. index += description.length + 1;
  12383. const value = utf8ArrayToStr(frame.data.subarray(index));
  12384. return {
  12385. key: frame.type,
  12386. info: description,
  12387. data: value
  12388. };
  12389. }
  12390. /*
  12391. Format:
  12392. [0] = {Text Encoding}
  12393. [1-?] = {Value}
  12394. */
  12395. const text = utf8ArrayToStr(frame.data.subarray(1));
  12396. return {
  12397. key: frame.type,
  12398. info: '',
  12399. data: text
  12400. };
  12401. }
  12402. /**
  12403. * Decode a URL frame
  12404. *
  12405. * @param frame - the ID3 URL frame
  12406. *
  12407. * @returns The decoded ID3 URL frame
  12408. *
  12409. * @internal
  12410. *
  12411. * @group ID3
  12412. */
  12413. function decodeId3UrlFrame(frame) {
  12414. if (frame.type === 'WXXX') {
  12415. /*
  12416. Format:
  12417. [0] = {Text Encoding}
  12418. [1-?] = {Description}\0{URL}
  12419. */
  12420. if (frame.size < 2) {
  12421. return undefined;
  12422. }
  12423. let index = 1;
  12424. const description = utf8ArrayToStr(frame.data.subarray(index), true);
  12425. index += description.length + 1;
  12426. const value = utf8ArrayToStr(frame.data.subarray(index));
  12427. return {
  12428. key: frame.type,
  12429. info: description,
  12430. data: value
  12431. };
  12432. }
  12433. /*
  12434. Format:
  12435. [0-?] = {URL}
  12436. */
  12437. const url = utf8ArrayToStr(frame.data);
  12438. return {
  12439. key: frame.type,
  12440. info: '',
  12441. data: url
  12442. };
  12443. }
  12444. /**
  12445. * Decode an ID3 frame.
  12446. *
  12447. * @param frame - the ID3 frame
  12448. *
  12449. * @returns The decoded ID3 frame
  12450. *
  12451. * @internal
  12452. *
  12453. * @group ID3
  12454. */
  12455. function decodeId3Frame(frame) {
  12456. if (frame.type === 'PRIV') {
  12457. return decodeId3PrivFrame(frame);
  12458. } else if (frame.type[0] === 'W') {
  12459. return decodeId3UrlFrame(frame);
  12460. } else if (frame.type === 'APIC') {
  12461. return decodeId3ImageFrame(frame);
  12462. }
  12463. return decodeId3TextFrame(frame);
  12464. }
  12465. /**
  12466. * Returns the data of an ID3 frame.
  12467. *
  12468. * @param data - The data to read from
  12469. *
  12470. * @returns The data of the ID3 frame
  12471. *
  12472. * @internal
  12473. *
  12474. * @group ID3
  12475. */
  12476. function getId3FrameData(data) {
  12477. /*
  12478. Frame ID $xx xx xx xx (four characters)
  12479. Size $xx xx xx xx
  12480. Flags $xx xx
  12481. */
  12482. const type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  12483. const size = readId3Size(data, 4);
  12484. // skip frame id, size, and flags
  12485. const offset = 10;
  12486. return {
  12487. type,
  12488. size,
  12489. data: data.subarray(offset, offset + size)
  12490. };
  12491. }
  12492. const HEADER_FOOTER_SIZE = 10;
  12493. const FRAME_SIZE = 10;
  12494. /**
  12495. * Returns an array of ID3 frames found in all the ID3 tags in the id3Data
  12496. *
  12497. * @param id3Data - The ID3 data containing one or more ID3 tags
  12498. *
  12499. * @returns Array of ID3 frame objects
  12500. *
  12501. * @group ID3
  12502. *
  12503. * @beta
  12504. */
  12505. function getId3Frames(id3Data) {
  12506. let offset = 0;
  12507. const frames = [];
  12508. while (isId3Header(id3Data, offset)) {
  12509. const size = readId3Size(id3Data, offset + 6);
  12510. if (id3Data[offset + 5] >> 6 & 1) {
  12511. // skip extended header
  12512. offset += HEADER_FOOTER_SIZE;
  12513. }
  12514. // skip past ID3 header
  12515. offset += HEADER_FOOTER_SIZE;
  12516. const end = offset + size;
  12517. // loop through frames in the ID3 tag
  12518. while (offset + FRAME_SIZE < end) {
  12519. const frameData = getId3FrameData(id3Data.subarray(offset));
  12520. const frame = decodeId3Frame(frameData);
  12521. if (frame) {
  12522. frames.push(frame);
  12523. }
  12524. // skip frame header and frame data
  12525. offset += frameData.size + HEADER_FOOTER_SIZE;
  12526. }
  12527. if (isId3Footer(id3Data, offset)) {
  12528. offset += HEADER_FOOTER_SIZE;
  12529. }
  12530. }
  12531. return frames;
  12532. }
  12533. /**
  12534. * Returns true if the ID3 frame is an Elementary Stream timestamp frame
  12535. *
  12536. * @param frame - the ID3 frame
  12537. *
  12538. * @returns `true` if the ID3 frame is an Elementary Stream timestamp frame
  12539. *
  12540. * @internal
  12541. *
  12542. * @group ID3
  12543. */
  12544. function isId3TimestampFrame(frame) {
  12545. return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
  12546. }
  12547. /**
  12548. * Read a 33 bit timestamp from an ID3 frame.
  12549. *
  12550. * @param timeStampFrame - the ID3 frame
  12551. *
  12552. * @returns The timestamp
  12553. *
  12554. * @internal
  12555. *
  12556. * @group ID3
  12557. */
  12558. function readId3Timestamp(timeStampFrame) {
  12559. if (timeStampFrame.data.byteLength === 8) {
  12560. const data = new Uint8Array(timeStampFrame.data);
  12561. // timestamp is 33 bit expressed as a big-endian eight-octet number,
  12562. // with the upper 31 bits set to zero.
  12563. const pts33Bit = data[3] & 0x1;
  12564. let timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  12565. timestamp /= 45;
  12566. if (pts33Bit) {
  12567. timestamp += 47721858.84;
  12568. } // 2^32 / 90
  12569. return Math.round(timestamp);
  12570. }
  12571. return undefined;
  12572. }
  12573. /**
  12574. * Searches for the Elementary Stream timestamp found in the ID3 data chunk
  12575. *
  12576. * @param data - Block of data containing one or more ID3 tags
  12577. *
  12578. * @returns The timestamp
  12579. *
  12580. * @group ID3
  12581. *
  12582. * @beta
  12583. */
  12584. function getId3Timestamp(data) {
  12585. const frames = getId3Frames(data);
  12586. for (let i = 0; i < frames.length; i++) {
  12587. const frame = frames[i];
  12588. if (isId3TimestampFrame(frame)) {
  12589. return readId3Timestamp(frame);
  12590. }
  12591. }
  12592. return undefined;
  12593. }
  12594. let MetadataSchema = /*#__PURE__*/function (MetadataSchema) {
  12595. MetadataSchema["audioId3"] = "org.id3";
  12596. MetadataSchema["dateRange"] = "com.apple.quicktime.HLS";
  12597. MetadataSchema["emsg"] = "https://aomedia.org/emsg/ID3";
  12598. MetadataSchema["misbklv"] = "urn:misb:KLV:bin:1910.1";
  12599. return MetadataSchema;
  12600. }({});
  12601. function dummyTrack(type = '', inputTimeScale = 90000) {
  12602. return {
  12603. type,
  12604. id: -1,
  12605. pid: -1,
  12606. inputTimeScale,
  12607. sequenceNumber: -1,
  12608. samples: [],
  12609. dropped: 0
  12610. };
  12611. }
  12612. class BaseAudioDemuxer {
  12613. constructor() {
  12614. this._audioTrack = void 0;
  12615. this._id3Track = void 0;
  12616. this.frameIndex = 0;
  12617. this.cachedData = null;
  12618. this.basePTS = null;
  12619. this.initPTS = null;
  12620. this.lastPTS = null;
  12621. }
  12622. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  12623. this._id3Track = {
  12624. type: 'id3',
  12625. id: 3,
  12626. pid: -1,
  12627. inputTimeScale: 90000,
  12628. sequenceNumber: 0,
  12629. samples: [],
  12630. dropped: 0
  12631. };
  12632. }
  12633. resetTimeStamp(deaultTimestamp) {
  12634. this.initPTS = deaultTimestamp;
  12635. this.resetContiguity();
  12636. }
  12637. resetContiguity() {
  12638. this.basePTS = null;
  12639. this.lastPTS = null;
  12640. this.frameIndex = 0;
  12641. }
  12642. canParse(data, offset) {
  12643. return false;
  12644. }
  12645. appendFrame(track, data, offset) {}
  12646. // feed incoming data to the front of the parsing pipeline
  12647. demux(data, timeOffset) {
  12648. if (this.cachedData) {
  12649. data = appendUint8Array(this.cachedData, data);
  12650. this.cachedData = null;
  12651. }
  12652. let id3Data = getId3Data(data, 0);
  12653. let offset = id3Data ? id3Data.length : 0;
  12654. let lastDataIndex;
  12655. const track = this._audioTrack;
  12656. const id3Track = this._id3Track;
  12657. const timestamp = id3Data ? getId3Timestamp(id3Data) : undefined;
  12658. const length = data.length;
  12659. if (this.basePTS === null || this.frameIndex === 0 && isFiniteNumber(timestamp)) {
  12660. this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);
  12661. this.lastPTS = this.basePTS;
  12662. }
  12663. if (this.lastPTS === null) {
  12664. this.lastPTS = this.basePTS;
  12665. }
  12666. // more expressive than alternative: id3Data?.length
  12667. if (id3Data && id3Data.length > 0) {
  12668. id3Track.samples.push({
  12669. pts: this.lastPTS,
  12670. dts: this.lastPTS,
  12671. data: id3Data,
  12672. type: MetadataSchema.audioId3,
  12673. duration: Number.POSITIVE_INFINITY
  12674. });
  12675. }
  12676. while (offset < length) {
  12677. if (this.canParse(data, offset)) {
  12678. const frame = this.appendFrame(track, data, offset);
  12679. if (frame) {
  12680. this.frameIndex++;
  12681. this.lastPTS = frame.sample.pts;
  12682. offset += frame.length;
  12683. lastDataIndex = offset;
  12684. } else {
  12685. offset = length;
  12686. }
  12687. } else if (canParseId3(data, offset)) {
  12688. // after a canParse, a call to getId3Data *should* always returns some data
  12689. id3Data = getId3Data(data, offset);
  12690. id3Track.samples.push({
  12691. pts: this.lastPTS,
  12692. dts: this.lastPTS,
  12693. data: id3Data,
  12694. type: MetadataSchema.audioId3,
  12695. duration: Number.POSITIVE_INFINITY
  12696. });
  12697. offset += id3Data.length;
  12698. lastDataIndex = offset;
  12699. } else {
  12700. offset++;
  12701. }
  12702. if (offset === length && lastDataIndex !== length) {
  12703. const partialData = data.slice(lastDataIndex);
  12704. if (this.cachedData) {
  12705. this.cachedData = appendUint8Array(this.cachedData, partialData);
  12706. } else {
  12707. this.cachedData = partialData;
  12708. }
  12709. }
  12710. }
  12711. return {
  12712. audioTrack: track,
  12713. videoTrack: dummyTrack(),
  12714. id3Track,
  12715. textTrack: dummyTrack()
  12716. };
  12717. }
  12718. demuxSampleAes(data, keyData, timeOffset) {
  12719. return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`));
  12720. }
  12721. flush(timeOffset) {
  12722. // Parse cache in case of remaining frames.
  12723. const cachedData = this.cachedData;
  12724. if (cachedData) {
  12725. this.cachedData = null;
  12726. this.demux(cachedData, 0);
  12727. }
  12728. return {
  12729. audioTrack: this._audioTrack,
  12730. videoTrack: dummyTrack(),
  12731. id3Track: this._id3Track,
  12732. textTrack: dummyTrack()
  12733. };
  12734. }
  12735. destroy() {
  12736. this.cachedData = null;
  12737. // @ts-ignore
  12738. this._audioTrack = this._id3Track = undefined;
  12739. }
  12740. }
  12741. /**
  12742. * Initialize PTS
  12743. * <p>
  12744. * use timestamp unless it is undefined, NaN or Infinity
  12745. * </p>
  12746. */
  12747. const initPTSFn = (timestamp, timeOffset, initPTS) => {
  12748. if (isFiniteNumber(timestamp)) {
  12749. return timestamp * 90;
  12750. }
  12751. const init90kHz = initPTS ? initPTS.baseTime * 90000 / initPTS.timescale : 0;
  12752. return timeOffset * 90000 + init90kHz;
  12753. };
  12754. /**
  12755. * MPEG parser helper
  12756. */
  12757. let chromeVersion$1 = null;
  12758. const 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];
  12759. const SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];
  12760. const SamplesCoefficients = [
  12761. // MPEG 2.5
  12762. [0,
  12763. // Reserved
  12764. 72,
  12765. // Layer3
  12766. 144,
  12767. // Layer2
  12768. 12 // Layer1
  12769. ],
  12770. // Reserved
  12771. [0,
  12772. // Reserved
  12773. 0,
  12774. // Layer3
  12775. 0,
  12776. // Layer2
  12777. 0 // Layer1
  12778. ],
  12779. // MPEG 2
  12780. [0,
  12781. // Reserved
  12782. 72,
  12783. // Layer3
  12784. 144,
  12785. // Layer2
  12786. 12 // Layer1
  12787. ],
  12788. // MPEG 1
  12789. [0,
  12790. // Reserved
  12791. 144,
  12792. // Layer3
  12793. 144,
  12794. // Layer2
  12795. 12 // Layer1
  12796. ]];
  12797. const BytesInSlot = [0,
  12798. // Reserved
  12799. 1,
  12800. // Layer3
  12801. 1,
  12802. // Layer2
  12803. 4 // Layer1
  12804. ];
  12805. function appendFrame(track, data, offset, pts, frameIndex) {
  12806. // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
  12807. if (offset + 24 > data.length) {
  12808. return;
  12809. }
  12810. const header = parseHeader(data, offset);
  12811. if (header && offset + header.frameLength <= data.length) {
  12812. const frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
  12813. const stamp = pts + frameIndex * frameDuration;
  12814. const sample = {
  12815. unit: data.subarray(offset, offset + header.frameLength),
  12816. pts: stamp,
  12817. dts: stamp
  12818. };
  12819. track.config = [];
  12820. track.channelCount = header.channelCount;
  12821. track.samplerate = header.sampleRate;
  12822. track.samples.push(sample);
  12823. return {
  12824. sample,
  12825. length: header.frameLength,
  12826. missing: 0
  12827. };
  12828. }
  12829. }
  12830. function parseHeader(data, offset) {
  12831. const mpegVersion = data[offset + 1] >> 3 & 3;
  12832. const mpegLayer = data[offset + 1] >> 1 & 3;
  12833. const bitRateIndex = data[offset + 2] >> 4 & 15;
  12834. const sampleRateIndex = data[offset + 2] >> 2 & 3;
  12835. if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
  12836. const paddingBit = data[offset + 2] >> 1 & 1;
  12837. const channelMode = data[offset + 3] >> 6;
  12838. const columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
  12839. const bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;
  12840. const columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
  12841. const sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
  12842. const channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
  12843. const sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
  12844. const bytesInSlot = BytesInSlot[mpegLayer];
  12845. const samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  12846. const frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
  12847. if (chromeVersion$1 === null) {
  12848. const userAgent = navigator.userAgent || '';
  12849. const result = userAgent.match(/Chrome\/(\d+)/i);
  12850. chromeVersion$1 = result ? parseInt(result[1]) : 0;
  12851. }
  12852. const needChromeFix = !!chromeVersion$1 && chromeVersion$1 <= 87;
  12853. if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) {
  12854. // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)
  12855. data[offset + 3] = data[offset + 3] | 0x80;
  12856. }
  12857. return {
  12858. sampleRate,
  12859. channelCount,
  12860. frameLength,
  12861. samplesPerFrame
  12862. };
  12863. }
  12864. }
  12865. function isHeaderPattern(data, offset) {
  12866. return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
  12867. }
  12868. function isHeader(data, offset) {
  12869. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  12870. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  12871. // More info http://www.mp3-tech.org/programmer/frame_header.html
  12872. return offset + 1 < data.length && isHeaderPattern(data, offset);
  12873. }
  12874. function canParse(data, offset) {
  12875. const headerSize = 4;
  12876. return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
  12877. }
  12878. function probe(data, offset) {
  12879. // same as isHeader but we also check that MPEG frame follows last MPEG frame
  12880. // or end of data is reached
  12881. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  12882. // MPEG header Length
  12883. const headerLength = 4;
  12884. // MPEG frame Length
  12885. const header = parseHeader(data, offset);
  12886. let frameLength = headerLength;
  12887. if (header != null && header.frameLength) {
  12888. frameLength = header.frameLength;
  12889. }
  12890. const newOffset = offset + frameLength;
  12891. return newOffset === data.length || isHeader(data, newOffset);
  12892. }
  12893. return false;
  12894. }
  12895. /**
  12896. * AAC demuxer
  12897. */
  12898. class AACDemuxer extends BaseAudioDemuxer {
  12899. constructor(observer, config) {
  12900. super();
  12901. this.observer = void 0;
  12902. this.config = void 0;
  12903. this.observer = observer;
  12904. this.config = config;
  12905. }
  12906. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  12907. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  12908. this._audioTrack = {
  12909. container: 'audio/adts',
  12910. type: 'audio',
  12911. id: 2,
  12912. pid: -1,
  12913. sequenceNumber: 0,
  12914. segmentCodec: 'aac',
  12915. samples: [],
  12916. manifestCodec: audioCodec,
  12917. duration: trackDuration,
  12918. inputTimeScale: 90000,
  12919. dropped: 0
  12920. };
  12921. }
  12922. // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
  12923. static probe(data, logger) {
  12924. if (!data) {
  12925. return false;
  12926. }
  12927. // Check for the ADTS sync word
  12928. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  12929. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  12930. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  12931. const id3Data = getId3Data(data, 0);
  12932. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  12933. if (probe(data, offset)) {
  12934. return false;
  12935. }
  12936. for (let length = data.length; offset < length; offset++) {
  12937. if (probe$1(data, offset)) {
  12938. logger.log('ADTS sync word found !');
  12939. return true;
  12940. }
  12941. }
  12942. return false;
  12943. }
  12944. canParse(data, offset) {
  12945. return canParse$1(data, offset);
  12946. }
  12947. appendFrame(track, data, offset) {
  12948. initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  12949. const frame = appendFrame$1(track, data, offset, this.basePTS, this.frameIndex);
  12950. if (frame && frame.missing === 0) {
  12951. return frame;
  12952. }
  12953. }
  12954. }
  12955. const getAudioBSID = (data, offset) => {
  12956. // check the bsid to confirm ac-3 | ec-3
  12957. let bsid = 0;
  12958. let numBits = 5;
  12959. offset += numBits;
  12960. const temp = new Uint32Array(1); // unsigned 32 bit for temporary storage
  12961. const mask = new Uint32Array(1); // unsigned 32 bit mask value
  12962. const byte = new Uint8Array(1); // unsigned 8 bit for temporary storage
  12963. while (numBits > 0) {
  12964. byte[0] = data[offset];
  12965. // read remaining bits, upto 8 bits at a time
  12966. const bits = Math.min(numBits, 8);
  12967. const shift = 8 - bits;
  12968. mask[0] = 0xff000000 >>> 24 + shift << shift;
  12969. temp[0] = (byte[0] & mask[0]) >> shift;
  12970. bsid = !bsid ? temp[0] : bsid << bits | temp[0];
  12971. offset += 1;
  12972. numBits -= bits;
  12973. }
  12974. return bsid;
  12975. };
  12976. /**
  12977. * MP3 demuxer
  12978. */
  12979. class MP3Demuxer extends BaseAudioDemuxer {
  12980. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  12981. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  12982. this._audioTrack = {
  12983. container: 'audio/mpeg',
  12984. type: 'audio',
  12985. id: 2,
  12986. pid: -1,
  12987. sequenceNumber: 0,
  12988. segmentCodec: 'mp3',
  12989. samples: [],
  12990. manifestCodec: audioCodec,
  12991. duration: trackDuration,
  12992. inputTimeScale: 90000,
  12993. dropped: 0
  12994. };
  12995. }
  12996. static probe(data) {
  12997. if (!data) {
  12998. return false;
  12999. }
  13000. // check if data contains ID3 timestamp and MPEG sync word
  13001. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  13002. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  13003. // More info http://www.mp3-tech.org/programmer/frame_header.html
  13004. const id3Data = getId3Data(data, 0);
  13005. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  13006. // Check for ac-3|ec-3 sync bytes and return false if present
  13007. if (id3Data && data[offset] === 0x0b && data[offset + 1] === 0x77 && getId3Timestamp(id3Data) !== undefined &&
  13008. // check the bsid to confirm ac-3 or ec-3 (not mp3)
  13009. getAudioBSID(data, offset) <= 16) {
  13010. return false;
  13011. }
  13012. for (let length = data.length; offset < length; offset++) {
  13013. if (probe(data, offset)) {
  13014. logger.log('MPEG Audio sync word found !');
  13015. return true;
  13016. }
  13017. }
  13018. return false;
  13019. }
  13020. canParse(data, offset) {
  13021. return canParse(data, offset);
  13022. }
  13023. appendFrame(track, data, offset) {
  13024. if (this.basePTS === null) {
  13025. return;
  13026. }
  13027. return appendFrame(track, data, offset, this.basePTS, this.frameIndex);
  13028. }
  13029. }
  13030. const emsgSchemePattern = /\/emsg[-/]ID3/i;
  13031. class MP4Demuxer {
  13032. constructor(observer, config) {
  13033. this.remainderData = null;
  13034. this.timeOffset = 0;
  13035. this.config = void 0;
  13036. this.videoTrack = void 0;
  13037. this.audioTrack = void 0;
  13038. this.id3Track = void 0;
  13039. this.txtTrack = void 0;
  13040. this.config = config;
  13041. }
  13042. resetTimeStamp() {}
  13043. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  13044. const videoTrack = this.videoTrack = dummyTrack('video', 1);
  13045. const audioTrack = this.audioTrack = dummyTrack('audio', 1);
  13046. const captionTrack = this.txtTrack = dummyTrack('text', 1);
  13047. this.id3Track = dummyTrack('id3', 1);
  13048. this.timeOffset = 0;
  13049. if (!(initSegment != null && initSegment.byteLength)) {
  13050. return;
  13051. }
  13052. const initData = parseInitSegment(initSegment);
  13053. if (initData.video) {
  13054. const {
  13055. id,
  13056. timescale,
  13057. codec,
  13058. supplemental
  13059. } = initData.video;
  13060. videoTrack.id = id;
  13061. videoTrack.timescale = captionTrack.timescale = timescale;
  13062. videoTrack.codec = codec;
  13063. videoTrack.supplemental = supplemental;
  13064. }
  13065. if (initData.audio) {
  13066. const {
  13067. id,
  13068. timescale,
  13069. codec
  13070. } = initData.audio;
  13071. audioTrack.id = id;
  13072. audioTrack.timescale = timescale;
  13073. audioTrack.codec = codec;
  13074. }
  13075. captionTrack.id = RemuxerTrackIdConfig.text;
  13076. videoTrack.sampleDuration = 0;
  13077. videoTrack.duration = audioTrack.duration = trackDuration;
  13078. }
  13079. resetContiguity() {
  13080. this.remainderData = null;
  13081. }
  13082. static probe(data) {
  13083. return hasMoofData(data);
  13084. }
  13085. demux(data, timeOffset) {
  13086. this.timeOffset = timeOffset;
  13087. // Load all data into the avc track. The CMAF remuxer will look for the data in the samples object; the rest of the fields do not matter
  13088. let videoSamples = data;
  13089. const videoTrack = this.videoTrack;
  13090. const textTrack = this.txtTrack;
  13091. if (this.config.progressive) {
  13092. // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.
  13093. // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee
  13094. // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.
  13095. if (this.remainderData) {
  13096. videoSamples = appendUint8Array(this.remainderData, data);
  13097. }
  13098. const segmentedData = segmentValidRange(videoSamples);
  13099. this.remainderData = segmentedData.remainder;
  13100. videoTrack.samples = segmentedData.valid || new Uint8Array();
  13101. } else {
  13102. videoTrack.samples = videoSamples;
  13103. }
  13104. const id3Track = this.extractID3Track(videoTrack, timeOffset);
  13105. textTrack.samples = parseSamples(timeOffset, videoTrack);
  13106. return {
  13107. videoTrack,
  13108. audioTrack: this.audioTrack,
  13109. id3Track,
  13110. textTrack: this.txtTrack
  13111. };
  13112. }
  13113. flush() {
  13114. const timeOffset = this.timeOffset;
  13115. const videoTrack = this.videoTrack;
  13116. const textTrack = this.txtTrack;
  13117. videoTrack.samples = this.remainderData || new Uint8Array();
  13118. this.remainderData = null;
  13119. const id3Track = this.extractID3Track(videoTrack, this.timeOffset);
  13120. textTrack.samples = parseSamples(timeOffset, videoTrack);
  13121. return {
  13122. videoTrack,
  13123. audioTrack: dummyTrack(),
  13124. id3Track,
  13125. textTrack: dummyTrack()
  13126. };
  13127. }
  13128. extractID3Track(videoTrack, timeOffset) {
  13129. const id3Track = this.id3Track;
  13130. if (videoTrack.samples.length) {
  13131. const emsgs = findBox(videoTrack.samples, ['emsg']);
  13132. if (emsgs) {
  13133. emsgs.forEach(data => {
  13134. const emsgInfo = parseEmsg(data);
  13135. if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {
  13136. const pts = getEmsgStartTime(emsgInfo, timeOffset);
  13137. let duration = emsgInfo.eventDuration === 0xffffffff ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale;
  13138. // Safari takes anything <= 0.001 seconds and maps it to Infinity
  13139. if (duration <= 0.001) {
  13140. duration = Number.POSITIVE_INFINITY;
  13141. }
  13142. const payload = emsgInfo.payload;
  13143. id3Track.samples.push({
  13144. data: payload,
  13145. len: payload.byteLength,
  13146. dts: pts,
  13147. pts: pts,
  13148. type: MetadataSchema.emsg,
  13149. duration: duration
  13150. });
  13151. } else if (this.config.enableEmsgKLVMetadata && emsgInfo.schemeIdUri.startsWith('urn:misb:KLV:bin:1910.1')) {
  13152. const pts = getEmsgStartTime(emsgInfo, timeOffset);
  13153. id3Track.samples.push({
  13154. data: emsgInfo.payload,
  13155. len: emsgInfo.payload.byteLength,
  13156. dts: pts,
  13157. pts: pts,
  13158. type: MetadataSchema.misbklv,
  13159. duration: Number.POSITIVE_INFINITY
  13160. });
  13161. }
  13162. });
  13163. }
  13164. }
  13165. return id3Track;
  13166. }
  13167. demuxSampleAes(data, keyData, timeOffset) {
  13168. return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption'));
  13169. }
  13170. destroy() {
  13171. // @ts-ignore
  13172. this.config = null;
  13173. this.remainderData = null;
  13174. this.videoTrack = this.audioTrack = this.id3Track = this.txtTrack = undefined;
  13175. }
  13176. }
  13177. function getEmsgStartTime(emsgInfo, timeOffset) {
  13178. return isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;
  13179. }
  13180. /**
  13181. * SAMPLE-AES decrypter
  13182. */
  13183. class SampleAesDecrypter {
  13184. constructor(observer, config, keyData) {
  13185. this.keyData = void 0;
  13186. this.decrypter = void 0;
  13187. this.keyData = keyData;
  13188. this.decrypter = new Decrypter(config, {
  13189. removePKCS7Padding: false
  13190. });
  13191. }
  13192. decryptBuffer(encryptedData) {
  13193. return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, DecrypterAesMode.cbc);
  13194. }
  13195. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  13196. decryptAacSample(samples, sampleIndex, callback) {
  13197. const curUnit = samples[sampleIndex].unit;
  13198. if (curUnit.length <= 16) {
  13199. // No encrypted portion in this sample (first 16 bytes is not
  13200. // encrypted, see https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HLS_Sample_Encryption/Encryption/Encryption.html),
  13201. return;
  13202. }
  13203. const encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  13204. const encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  13205. this.decryptBuffer(encryptedBuffer).then(decryptedBuffer => {
  13206. const decryptedData = new Uint8Array(decryptedBuffer);
  13207. curUnit.set(decryptedData, 16);
  13208. if (!this.decrypter.isSync()) {
  13209. this.decryptAacSamples(samples, sampleIndex + 1, callback);
  13210. }
  13211. });
  13212. }
  13213. decryptAacSamples(samples, sampleIndex, callback) {
  13214. for (;; sampleIndex++) {
  13215. if (sampleIndex >= samples.length) {
  13216. callback();
  13217. return;
  13218. }
  13219. if (samples[sampleIndex].unit.length < 32) {
  13220. continue;
  13221. }
  13222. this.decryptAacSample(samples, sampleIndex, callback);
  13223. if (!this.decrypter.isSync()) {
  13224. return;
  13225. }
  13226. }
  13227. }
  13228. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  13229. getAvcEncryptedData(decodedData) {
  13230. const encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  13231. const encryptedData = new Int8Array(encryptedDataLen);
  13232. let outputPos = 0;
  13233. for (let inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) {
  13234. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  13235. }
  13236. return encryptedData;
  13237. }
  13238. getAvcDecryptedUnit(decodedData, decryptedData) {
  13239. const uint8DecryptedData = new Uint8Array(decryptedData);
  13240. let inputPos = 0;
  13241. for (let outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) {
  13242. decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
  13243. }
  13244. return decodedData;
  13245. }
  13246. decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit) {
  13247. const decodedData = discardEPB(curUnit.data);
  13248. const encryptedData = this.getAvcEncryptedData(decodedData);
  13249. this.decryptBuffer(encryptedData.buffer).then(decryptedBuffer => {
  13250. curUnit.data = this.getAvcDecryptedUnit(decodedData, decryptedBuffer);
  13251. if (!this.decrypter.isSync()) {
  13252. this.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  13253. }
  13254. });
  13255. }
  13256. decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  13257. if (samples instanceof Uint8Array) {
  13258. throw new Error('Cannot decrypt samples of type Uint8Array');
  13259. }
  13260. for (;; sampleIndex++, unitIndex = 0) {
  13261. if (sampleIndex >= samples.length) {
  13262. callback();
  13263. return;
  13264. }
  13265. const curUnits = samples[sampleIndex].units;
  13266. for (;; unitIndex++) {
  13267. if (unitIndex >= curUnits.length) {
  13268. break;
  13269. }
  13270. const curUnit = curUnits[unitIndex];
  13271. if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  13272. continue;
  13273. }
  13274. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit);
  13275. if (!this.decrypter.isSync()) {
  13276. return;
  13277. }
  13278. }
  13279. }
  13280. }
  13281. }
  13282. class BaseVideoParser {
  13283. constructor() {
  13284. this.VideoSample = null;
  13285. }
  13286. createVideoSample(key, pts, dts) {
  13287. return {
  13288. key,
  13289. frame: false,
  13290. pts,
  13291. dts,
  13292. units: [],
  13293. length: 0
  13294. };
  13295. }
  13296. getLastNalUnit(samples) {
  13297. var _VideoSample;
  13298. let VideoSample = this.VideoSample;
  13299. let lastUnit;
  13300. // try to fallback to previous sample if current one is empty
  13301. if (!VideoSample || VideoSample.units.length === 0) {
  13302. VideoSample = samples[samples.length - 1];
  13303. }
  13304. if ((_VideoSample = VideoSample) != null && _VideoSample.units) {
  13305. const units = VideoSample.units;
  13306. lastUnit = units[units.length - 1];
  13307. }
  13308. return lastUnit;
  13309. }
  13310. pushAccessUnit(VideoSample, videoTrack) {
  13311. if (VideoSample.units.length && VideoSample.frame) {
  13312. // if sample does not have PTS/DTS, patch with last sample PTS/DTS
  13313. if (VideoSample.pts === undefined) {
  13314. const samples = videoTrack.samples;
  13315. const nbSamples = samples.length;
  13316. if (nbSamples) {
  13317. const lastSample = samples[nbSamples - 1];
  13318. VideoSample.pts = lastSample.pts;
  13319. VideoSample.dts = lastSample.dts;
  13320. } else {
  13321. // dropping samples, no timestamp found
  13322. videoTrack.dropped++;
  13323. return;
  13324. }
  13325. }
  13326. videoTrack.samples.push(VideoSample);
  13327. }
  13328. }
  13329. parseNALu(track, array, endOfSegment) {
  13330. const len = array.byteLength;
  13331. let state = track.naluState || 0;
  13332. const lastState = state;
  13333. const units = [];
  13334. let i = 0;
  13335. let value;
  13336. let overflow;
  13337. let unitType;
  13338. let lastUnitStart = -1;
  13339. let lastUnitType = 0;
  13340. // logger.log('PES:' + Hex.hexDump(array));
  13341. if (state === -1) {
  13342. // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
  13343. lastUnitStart = 0;
  13344. // NALu type is value read from offset 0
  13345. lastUnitType = this.getNALuType(array, 0);
  13346. state = 0;
  13347. i = 1;
  13348. }
  13349. while (i < len) {
  13350. value = array[i++];
  13351. // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
  13352. if (!state) {
  13353. state = value ? 0 : 1;
  13354. continue;
  13355. }
  13356. if (state === 1) {
  13357. state = value ? 0 : 2;
  13358. continue;
  13359. }
  13360. // here we have state either equal to 2 or 3
  13361. if (!value) {
  13362. state = 3;
  13363. } else if (value === 1) {
  13364. overflow = i - state - 1;
  13365. if (lastUnitStart >= 0) {
  13366. const unit = {
  13367. data: array.subarray(lastUnitStart, overflow),
  13368. type: lastUnitType
  13369. };
  13370. // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  13371. units.push(unit);
  13372. } else {
  13373. // lastUnitStart is undefined => this is the first start code found in this PES packet
  13374. // first check if start code delimiter is overlapping between 2 PES packets,
  13375. // ie it started in last packet (lastState not zero)
  13376. // and ended at the beginning of this PES packet (i <= 4 - lastState)
  13377. const lastUnit = this.getLastNalUnit(track.samples);
  13378. if (lastUnit) {
  13379. if (lastState && i <= 4 - lastState) {
  13380. // start delimiter overlapping between PES packets
  13381. // strip start delimiter bytes from the end of last NAL unit
  13382. // check if lastUnit had a state different from zero
  13383. if (lastUnit.state) {
  13384. // strip last bytes
  13385. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  13386. }
  13387. }
  13388. // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
  13389. if (overflow > 0) {
  13390. // logger.log('first NALU found with overflow:' + overflow);
  13391. lastUnit.data = appendUint8Array(lastUnit.data, array.subarray(0, overflow));
  13392. lastUnit.state = 0;
  13393. }
  13394. }
  13395. }
  13396. // check if we can read unit type
  13397. if (i < len) {
  13398. unitType = this.getNALuType(array, i);
  13399. // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
  13400. lastUnitStart = i;
  13401. lastUnitType = unitType;
  13402. state = 0;
  13403. } else {
  13404. // not enough byte to read unit type. let's read it on next PES parsing
  13405. state = -1;
  13406. }
  13407. } else {
  13408. state = 0;
  13409. }
  13410. }
  13411. if (lastUnitStart >= 0 && state >= 0) {
  13412. const unit = {
  13413. data: array.subarray(lastUnitStart, len),
  13414. type: lastUnitType,
  13415. state: state
  13416. };
  13417. units.push(unit);
  13418. // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
  13419. }
  13420. // no NALu found
  13421. if (units.length === 0) {
  13422. // append pes.data to previous NAL unit
  13423. const lastUnit = this.getLastNalUnit(track.samples);
  13424. if (lastUnit) {
  13425. lastUnit.data = appendUint8Array(lastUnit.data, array);
  13426. }
  13427. }
  13428. track.naluState = state;
  13429. return units;
  13430. }
  13431. }
  13432. /**
  13433. * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
  13434. */
  13435. class ExpGolomb {
  13436. constructor(data) {
  13437. this.data = void 0;
  13438. this.bytesAvailable = void 0;
  13439. this.word = void 0;
  13440. this.bitsAvailable = void 0;
  13441. this.data = data;
  13442. // the number of bytes left to examine in this.data
  13443. this.bytesAvailable = data.byteLength;
  13444. // the current word being examined
  13445. this.word = 0; // :uint
  13446. // the number of bits left to examine in the current word
  13447. this.bitsAvailable = 0; // :uint
  13448. }
  13449. // ():void
  13450. loadWord() {
  13451. const data = this.data;
  13452. const bytesAvailable = this.bytesAvailable;
  13453. const position = data.byteLength - bytesAvailable;
  13454. const workingBytes = new Uint8Array(4);
  13455. const availableBytes = Math.min(4, bytesAvailable);
  13456. if (availableBytes === 0) {
  13457. throw new Error('no bytes available');
  13458. }
  13459. workingBytes.set(data.subarray(position, position + availableBytes));
  13460. this.word = new DataView(workingBytes.buffer).getUint32(0);
  13461. // track the amount of this.data that has been processed
  13462. this.bitsAvailable = availableBytes * 8;
  13463. this.bytesAvailable -= availableBytes;
  13464. }
  13465. // (count:int):void
  13466. skipBits(count) {
  13467. let skipBytes; // :int
  13468. count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);
  13469. if (this.bitsAvailable > count) {
  13470. this.word <<= count;
  13471. this.bitsAvailable -= count;
  13472. } else {
  13473. count -= this.bitsAvailable;
  13474. skipBytes = count >> 3;
  13475. count -= skipBytes << 3;
  13476. this.bytesAvailable -= skipBytes;
  13477. this.loadWord();
  13478. this.word <<= count;
  13479. this.bitsAvailable -= count;
  13480. }
  13481. }
  13482. // (size:int):uint
  13483. readBits(size) {
  13484. let bits = Math.min(this.bitsAvailable, size); // :uint
  13485. const valu = this.word >>> 32 - bits; // :uint
  13486. if (size > 32) {
  13487. logger.error('Cannot read more than 32 bits at a time');
  13488. }
  13489. this.bitsAvailable -= bits;
  13490. if (this.bitsAvailable > 0) {
  13491. this.word <<= bits;
  13492. } else if (this.bytesAvailable > 0) {
  13493. this.loadWord();
  13494. } else {
  13495. throw new Error('no bits available');
  13496. }
  13497. bits = size - bits;
  13498. if (bits > 0 && this.bitsAvailable) {
  13499. return valu << bits | this.readBits(bits);
  13500. } else {
  13501. return valu;
  13502. }
  13503. }
  13504. // ():uint
  13505. skipLZ() {
  13506. let leadingZeroCount; // :uint
  13507. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  13508. if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
  13509. // the first bit of working word is 1
  13510. this.word <<= leadingZeroCount;
  13511. this.bitsAvailable -= leadingZeroCount;
  13512. return leadingZeroCount;
  13513. }
  13514. }
  13515. // we exhausted word and still have not found a 1
  13516. this.loadWord();
  13517. return leadingZeroCount + this.skipLZ();
  13518. }
  13519. // ():void
  13520. skipUEG() {
  13521. this.skipBits(1 + this.skipLZ());
  13522. }
  13523. // ():void
  13524. skipEG() {
  13525. this.skipBits(1 + this.skipLZ());
  13526. }
  13527. // ():uint
  13528. readUEG() {
  13529. const clz = this.skipLZ(); // :uint
  13530. return this.readBits(clz + 1) - 1;
  13531. }
  13532. // ():int
  13533. readEG() {
  13534. const valu = this.readUEG(); // :int
  13535. if (0x01 & valu) {
  13536. // the number is odd if the low order bit is set
  13537. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  13538. } else {
  13539. return -1 * (valu >>> 1); // divide by two then make it negative
  13540. }
  13541. }
  13542. // Some convenience functions
  13543. // :Boolean
  13544. readBoolean() {
  13545. return this.readBits(1) === 1;
  13546. }
  13547. // ():int
  13548. readUByte() {
  13549. return this.readBits(8);
  13550. }
  13551. // ():int
  13552. readUShort() {
  13553. return this.readBits(16);
  13554. }
  13555. // ():int
  13556. readUInt() {
  13557. return this.readBits(32);
  13558. }
  13559. }
  13560. class AvcVideoParser extends BaseVideoParser {
  13561. parsePES(track, textTrack, pes, endOfSegment) {
  13562. const units = this.parseNALu(track, pes.data, endOfSegment);
  13563. let VideoSample = this.VideoSample;
  13564. let push;
  13565. let spsfound = false;
  13566. // free pes.data to save up some memory
  13567. pes.data = null;
  13568. // if new NAL units found and last sample still there, let's push ...
  13569. // this helps parsing streams with missing AUD (only do this if AUD never found)
  13570. if (VideoSample && units.length && !track.audFound) {
  13571. this.pushAccessUnit(VideoSample, track);
  13572. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  13573. }
  13574. units.forEach(unit => {
  13575. var _VideoSample2, _VideoSample3;
  13576. switch (unit.type) {
  13577. // NDR
  13578. case 1:
  13579. {
  13580. let iskey = false;
  13581. push = true;
  13582. const data = unit.data;
  13583. // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
  13584. if (spsfound && data.length > 4) {
  13585. // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
  13586. const sliceType = this.readSliceType(data);
  13587. // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
  13588. // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
  13589. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
  13590. // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
  13591. // if (sliceType === 2 || sliceType === 7) {
  13592. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  13593. iskey = true;
  13594. }
  13595. }
  13596. if (iskey) {
  13597. var _VideoSample;
  13598. // if we have non-keyframe data already, that cannot belong to the same frame as a keyframe, so force a push
  13599. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  13600. this.pushAccessUnit(VideoSample, track);
  13601. VideoSample = this.VideoSample = null;
  13602. }
  13603. }
  13604. if (!VideoSample) {
  13605. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  13606. }
  13607. VideoSample.frame = true;
  13608. VideoSample.key = iskey;
  13609. break;
  13610. // IDR
  13611. }
  13612. case 5:
  13613. push = true;
  13614. // handle PES not starting with AUD
  13615. // if we have frame data already, that cannot belong to the same frame, so force a push
  13616. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  13617. this.pushAccessUnit(VideoSample, track);
  13618. VideoSample = this.VideoSample = null;
  13619. }
  13620. if (!VideoSample) {
  13621. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  13622. }
  13623. VideoSample.key = true;
  13624. VideoSample.frame = true;
  13625. break;
  13626. // SEI
  13627. case 6:
  13628. {
  13629. push = true;
  13630. parseSEIMessageFromNALu(unit.data, 1, pes.pts, textTrack.samples);
  13631. break;
  13632. // SPS
  13633. }
  13634. case 7:
  13635. {
  13636. var _track$pixelRatio, _track$pixelRatio2;
  13637. push = true;
  13638. spsfound = true;
  13639. const sps = unit.data;
  13640. const config = this.readSPS(sps);
  13641. 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]) {
  13642. track.width = config.width;
  13643. track.height = config.height;
  13644. track.pixelRatio = config.pixelRatio;
  13645. track.sps = [sps];
  13646. const codecarray = sps.subarray(1, 4);
  13647. let codecstring = 'avc1.';
  13648. for (let i = 0; i < 3; i++) {
  13649. let h = codecarray[i].toString(16);
  13650. if (h.length < 2) {
  13651. h = '0' + h;
  13652. }
  13653. codecstring += h;
  13654. }
  13655. track.codec = codecstring;
  13656. }
  13657. break;
  13658. }
  13659. // PPS
  13660. case 8:
  13661. push = true;
  13662. track.pps = [unit.data];
  13663. break;
  13664. // AUD
  13665. case 9:
  13666. push = true;
  13667. track.audFound = true;
  13668. if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
  13669. this.pushAccessUnit(VideoSample, track);
  13670. VideoSample = null;
  13671. }
  13672. if (!VideoSample) {
  13673. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  13674. }
  13675. break;
  13676. // Filler Data
  13677. case 12:
  13678. push = true;
  13679. break;
  13680. default:
  13681. push = false;
  13682. break;
  13683. }
  13684. if (VideoSample && push) {
  13685. const units = VideoSample.units;
  13686. units.push(unit);
  13687. }
  13688. });
  13689. // if last PES packet, push samples
  13690. if (endOfSegment && VideoSample) {
  13691. this.pushAccessUnit(VideoSample, track);
  13692. this.VideoSample = null;
  13693. }
  13694. }
  13695. getNALuType(data, offset) {
  13696. return data[offset] & 0x1f;
  13697. }
  13698. readSliceType(data) {
  13699. const eg = new ExpGolomb(data);
  13700. // skip NALu type
  13701. eg.readUByte();
  13702. // discard first_mb_in_slice
  13703. eg.readUEG();
  13704. // return slice_type
  13705. return eg.readUEG();
  13706. }
  13707. /**
  13708. * The scaling list is optionally transmitted as part of a sequence parameter
  13709. * set and is not relevant to transmuxing.
  13710. * @param count the number of entries in this scaling list
  13711. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  13712. */
  13713. skipScalingList(count, reader) {
  13714. let lastScale = 8;
  13715. let nextScale = 8;
  13716. let deltaScale;
  13717. for (let j = 0; j < count; j++) {
  13718. if (nextScale !== 0) {
  13719. deltaScale = reader.readEG();
  13720. nextScale = (lastScale + deltaScale + 256) % 256;
  13721. }
  13722. lastScale = nextScale === 0 ? lastScale : nextScale;
  13723. }
  13724. }
  13725. /**
  13726. * Read a sequence parameter set and return some interesting video
  13727. * properties. A sequence parameter set is the H264 metadata that
  13728. * describes the properties of upcoming video frames.
  13729. * @returns an object with configuration parsed from the
  13730. * sequence parameter set, including the dimensions of the
  13731. * associated video frames.
  13732. */
  13733. readSPS(sps) {
  13734. const eg = new ExpGolomb(sps);
  13735. let frameCropLeftOffset = 0;
  13736. let frameCropRightOffset = 0;
  13737. let frameCropTopOffset = 0;
  13738. let frameCropBottomOffset = 0;
  13739. let numRefFramesInPicOrderCntCycle;
  13740. let scalingListCount;
  13741. let i;
  13742. const readUByte = eg.readUByte.bind(eg);
  13743. const readBits = eg.readBits.bind(eg);
  13744. const readUEG = eg.readUEG.bind(eg);
  13745. const readBoolean = eg.readBoolean.bind(eg);
  13746. const skipBits = eg.skipBits.bind(eg);
  13747. const skipEG = eg.skipEG.bind(eg);
  13748. const skipUEG = eg.skipUEG.bind(eg);
  13749. const skipScalingList = this.skipScalingList.bind(this);
  13750. readUByte();
  13751. const profileIdc = readUByte(); // profile_idc
  13752. readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)
  13753. skipBits(3); // reserved_zero_3bits u(3),
  13754. readUByte(); // level_idc u(8)
  13755. skipUEG(); // seq_parameter_set_id
  13756. // some profiles have more optional data we don't need
  13757. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  13758. const chromaFormatIdc = readUEG();
  13759. if (chromaFormatIdc === 3) {
  13760. skipBits(1);
  13761. } // separate_colour_plane_flag
  13762. skipUEG(); // bit_depth_luma_minus8
  13763. skipUEG(); // bit_depth_chroma_minus8
  13764. skipBits(1); // qpprime_y_zero_transform_bypass_flag
  13765. if (readBoolean()) {
  13766. // seq_scaling_matrix_present_flag
  13767. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  13768. for (i = 0; i < scalingListCount; i++) {
  13769. if (readBoolean()) {
  13770. // seq_scaling_list_present_flag[ i ]
  13771. if (i < 6) {
  13772. skipScalingList(16, eg);
  13773. } else {
  13774. skipScalingList(64, eg);
  13775. }
  13776. }
  13777. }
  13778. }
  13779. }
  13780. skipUEG(); // log2_max_frame_num_minus4
  13781. const picOrderCntType = readUEG();
  13782. if (picOrderCntType === 0) {
  13783. readUEG(); // log2_max_pic_order_cnt_lsb_minus4
  13784. } else if (picOrderCntType === 1) {
  13785. skipBits(1); // delta_pic_order_always_zero_flag
  13786. skipEG(); // offset_for_non_ref_pic
  13787. skipEG(); // offset_for_top_to_bottom_field
  13788. numRefFramesInPicOrderCntCycle = readUEG();
  13789. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  13790. skipEG();
  13791. } // offset_for_ref_frame[ i ]
  13792. }
  13793. skipUEG(); // max_num_ref_frames
  13794. skipBits(1); // gaps_in_frame_num_value_allowed_flag
  13795. const picWidthInMbsMinus1 = readUEG();
  13796. const picHeightInMapUnitsMinus1 = readUEG();
  13797. const frameMbsOnlyFlag = readBits(1);
  13798. if (frameMbsOnlyFlag === 0) {
  13799. skipBits(1);
  13800. } // mb_adaptive_frame_field_flag
  13801. skipBits(1); // direct_8x8_inference_flag
  13802. if (readBoolean()) {
  13803. // frame_cropping_flag
  13804. frameCropLeftOffset = readUEG();
  13805. frameCropRightOffset = readUEG();
  13806. frameCropTopOffset = readUEG();
  13807. frameCropBottomOffset = readUEG();
  13808. }
  13809. let pixelRatio = [1, 1];
  13810. if (readBoolean()) {
  13811. // vui_parameters_present_flag
  13812. if (readBoolean()) {
  13813. // aspect_ratio_info_present_flag
  13814. const aspectRatioIdc = readUByte();
  13815. switch (aspectRatioIdc) {
  13816. case 1:
  13817. pixelRatio = [1, 1];
  13818. break;
  13819. case 2:
  13820. pixelRatio = [12, 11];
  13821. break;
  13822. case 3:
  13823. pixelRatio = [10, 11];
  13824. break;
  13825. case 4:
  13826. pixelRatio = [16, 11];
  13827. break;
  13828. case 5:
  13829. pixelRatio = [40, 33];
  13830. break;
  13831. case 6:
  13832. pixelRatio = [24, 11];
  13833. break;
  13834. case 7:
  13835. pixelRatio = [20, 11];
  13836. break;
  13837. case 8:
  13838. pixelRatio = [32, 11];
  13839. break;
  13840. case 9:
  13841. pixelRatio = [80, 33];
  13842. break;
  13843. case 10:
  13844. pixelRatio = [18, 11];
  13845. break;
  13846. case 11:
  13847. pixelRatio = [15, 11];
  13848. break;
  13849. case 12:
  13850. pixelRatio = [64, 33];
  13851. break;
  13852. case 13:
  13853. pixelRatio = [160, 99];
  13854. break;
  13855. case 14:
  13856. pixelRatio = [4, 3];
  13857. break;
  13858. case 15:
  13859. pixelRatio = [3, 2];
  13860. break;
  13861. case 16:
  13862. pixelRatio = [2, 1];
  13863. break;
  13864. case 255:
  13865. {
  13866. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  13867. break;
  13868. }
  13869. }
  13870. }
  13871. }
  13872. return {
  13873. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  13874. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  13875. pixelRatio: pixelRatio
  13876. };
  13877. }
  13878. }
  13879. const PACKET_LENGTH = 188;
  13880. class TSDemuxer {
  13881. constructor(observer, config, typeSupported, logger) {
  13882. this.logger = void 0;
  13883. this.observer = void 0;
  13884. this.config = void 0;
  13885. this.typeSupported = void 0;
  13886. this.sampleAes = null;
  13887. this.pmtParsed = false;
  13888. this.audioCodec = void 0;
  13889. this.videoCodec = void 0;
  13890. this._pmtId = -1;
  13891. this._videoTrack = void 0;
  13892. this._audioTrack = void 0;
  13893. this._id3Track = void 0;
  13894. this._txtTrack = void 0;
  13895. this.aacOverFlow = null;
  13896. this.remainderData = null;
  13897. this.videoParser = void 0;
  13898. this.observer = observer;
  13899. this.config = config;
  13900. this.typeSupported = typeSupported;
  13901. this.logger = logger;
  13902. this.videoParser = null;
  13903. }
  13904. static probe(data, logger) {
  13905. const syncOffset = TSDemuxer.syncOffset(data);
  13906. if (syncOffset > 0) {
  13907. logger.warn(`MPEG2-TS detected but first sync word found @ offset ${syncOffset}`);
  13908. }
  13909. return syncOffset !== -1;
  13910. }
  13911. static syncOffset(data) {
  13912. const length = data.length;
  13913. let scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;
  13914. let i = 0;
  13915. while (i < scanwindow) {
  13916. // a TS init segment should contain at least 2 TS packets: PAT and PMT, each starting with 0x47
  13917. let foundPat = false;
  13918. let packetStart = -1;
  13919. let tsPackets = 0;
  13920. for (let j = i; j < length; j += PACKET_LENGTH) {
  13921. if (data[j] === 0x47 && (length - j === PACKET_LENGTH || data[j + PACKET_LENGTH] === 0x47)) {
  13922. tsPackets++;
  13923. if (packetStart === -1) {
  13924. packetStart = j;
  13925. // First sync word found at offset, increase scan length (#5251)
  13926. if (packetStart !== 0) {
  13927. scanwindow = Math.min(packetStart + PACKET_LENGTH * 99, data.length - PACKET_LENGTH) + 1;
  13928. }
  13929. }
  13930. if (!foundPat) {
  13931. foundPat = parsePID(data, j) === 0;
  13932. }
  13933. // Sync word found at 0 with 3 packets, or found at offset least 2 packets up to scanwindow (#5501)
  13934. if (foundPat && tsPackets > 1 && (packetStart === 0 && tsPackets > 2 || j + PACKET_LENGTH > scanwindow)) {
  13935. return packetStart;
  13936. }
  13937. } else if (tsPackets) {
  13938. // Exit if sync word found, but does not contain contiguous packets
  13939. return -1;
  13940. } else {
  13941. break;
  13942. }
  13943. }
  13944. i++;
  13945. }
  13946. return -1;
  13947. }
  13948. /**
  13949. * Creates a track model internal to demuxer used to drive remuxing input
  13950. */
  13951. static createTrack(type, duration) {
  13952. return {
  13953. container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
  13954. type,
  13955. id: RemuxerTrackIdConfig[type],
  13956. pid: -1,
  13957. inputTimeScale: 90000,
  13958. sequenceNumber: 0,
  13959. samples: [],
  13960. dropped: 0,
  13961. duration: type === 'audio' ? duration : undefined
  13962. };
  13963. }
  13964. /**
  13965. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  13966. * Resets all internal track instances of the demuxer.
  13967. */
  13968. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  13969. this.pmtParsed = false;
  13970. this._pmtId = -1;
  13971. this._videoTrack = TSDemuxer.createTrack('video');
  13972. this._videoTrack.duration = trackDuration;
  13973. this._audioTrack = TSDemuxer.createTrack('audio', trackDuration);
  13974. this._id3Track = TSDemuxer.createTrack('id3');
  13975. this._txtTrack = TSDemuxer.createTrack('text');
  13976. this._audioTrack.segmentCodec = 'aac';
  13977. // flush any partial content
  13978. this.aacOverFlow = null;
  13979. this.remainderData = null;
  13980. this.audioCodec = audioCodec;
  13981. this.videoCodec = videoCodec;
  13982. }
  13983. resetTimeStamp() {}
  13984. resetContiguity() {
  13985. const {
  13986. _audioTrack,
  13987. _videoTrack,
  13988. _id3Track
  13989. } = this;
  13990. if (_audioTrack) {
  13991. _audioTrack.pesData = null;
  13992. }
  13993. if (_videoTrack) {
  13994. _videoTrack.pesData = null;
  13995. }
  13996. if (_id3Track) {
  13997. _id3Track.pesData = null;
  13998. }
  13999. this.aacOverFlow = null;
  14000. this.remainderData = null;
  14001. }
  14002. demux(data, timeOffset, isSampleAes = false, flush = false) {
  14003. if (!isSampleAes) {
  14004. this.sampleAes = null;
  14005. }
  14006. let pes;
  14007. const videoTrack = this._videoTrack;
  14008. const audioTrack = this._audioTrack;
  14009. const id3Track = this._id3Track;
  14010. const textTrack = this._txtTrack;
  14011. let videoPid = videoTrack.pid;
  14012. let videoData = videoTrack.pesData;
  14013. let audioPid = audioTrack.pid;
  14014. let id3Pid = id3Track.pid;
  14015. let audioData = audioTrack.pesData;
  14016. let id3Data = id3Track.pesData;
  14017. let unknownPID = null;
  14018. let pmtParsed = this.pmtParsed;
  14019. let pmtId = this._pmtId;
  14020. let len = data.length;
  14021. if (this.remainderData) {
  14022. data = appendUint8Array(this.remainderData, data);
  14023. len = data.length;
  14024. this.remainderData = null;
  14025. }
  14026. if (len < PACKET_LENGTH && !flush) {
  14027. this.remainderData = data;
  14028. return {
  14029. audioTrack,
  14030. videoTrack,
  14031. id3Track,
  14032. textTrack
  14033. };
  14034. }
  14035. const syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
  14036. len -= (len - syncOffset) % PACKET_LENGTH;
  14037. if (len < data.byteLength && !flush) {
  14038. this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
  14039. }
  14040. // loop through TS packets
  14041. let tsPacketErrors = 0;
  14042. for (let start = syncOffset; start < len; start += PACKET_LENGTH) {
  14043. if (data[start] === 0x47) {
  14044. const stt = !!(data[start + 1] & 0x40);
  14045. const pid = parsePID(data, start);
  14046. const atf = (data[start + 3] & 0x30) >> 4;
  14047. // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
  14048. let offset;
  14049. if (atf > 1) {
  14050. offset = start + 5 + data[start + 4];
  14051. // continue if there is only adaptation field
  14052. if (offset === start + PACKET_LENGTH) {
  14053. continue;
  14054. }
  14055. } else {
  14056. offset = start + 4;
  14057. }
  14058. switch (pid) {
  14059. case videoPid:
  14060. if (stt) {
  14061. if (videoData && (pes = parsePES(videoData, this.logger))) {
  14062. if (this.videoParser === null) {
  14063. switch (videoTrack.segmentCodec) {
  14064. case 'avc':
  14065. this.videoParser = new AvcVideoParser();
  14066. break;
  14067. }
  14068. }
  14069. if (this.videoParser !== null) {
  14070. this.videoParser.parsePES(videoTrack, textTrack, pes, false);
  14071. }
  14072. }
  14073. videoData = {
  14074. data: [],
  14075. size: 0
  14076. };
  14077. }
  14078. if (videoData) {
  14079. videoData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  14080. videoData.size += start + PACKET_LENGTH - offset;
  14081. }
  14082. break;
  14083. case audioPid:
  14084. if (stt) {
  14085. if (audioData && (pes = parsePES(audioData, this.logger))) {
  14086. switch (audioTrack.segmentCodec) {
  14087. case 'aac':
  14088. this.parseAACPES(audioTrack, pes);
  14089. break;
  14090. case 'mp3':
  14091. this.parseMPEGPES(audioTrack, pes);
  14092. break;
  14093. }
  14094. }
  14095. audioData = {
  14096. data: [],
  14097. size: 0
  14098. };
  14099. }
  14100. if (audioData) {
  14101. audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  14102. audioData.size += start + PACKET_LENGTH - offset;
  14103. }
  14104. break;
  14105. case id3Pid:
  14106. if (stt) {
  14107. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  14108. this.parseID3PES(id3Track, pes);
  14109. }
  14110. id3Data = {
  14111. data: [],
  14112. size: 0
  14113. };
  14114. }
  14115. if (id3Data) {
  14116. id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));
  14117. id3Data.size += start + PACKET_LENGTH - offset;
  14118. }
  14119. break;
  14120. case 0:
  14121. if (stt) {
  14122. offset += data[offset] + 1;
  14123. }
  14124. pmtId = this._pmtId = parsePAT(data, offset);
  14125. // this.logger.log('PMT PID:' + this._pmtId);
  14126. break;
  14127. case pmtId:
  14128. {
  14129. if (stt) {
  14130. offset += data[offset] + 1;
  14131. }
  14132. const parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes, this.observer, this.logger);
  14133. // only update track id if track PID found while parsing PMT
  14134. // this is to avoid resetting the PID to -1 in case
  14135. // track PID transiently disappears from the stream
  14136. // this could happen in case of transient missing audio samples for example
  14137. // NOTE this is only the PID of the track as found in TS,
  14138. // but we are not using this for MP4 track IDs.
  14139. videoPid = parsedPIDs.videoPid;
  14140. if (videoPid > 0) {
  14141. videoTrack.pid = videoPid;
  14142. videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;
  14143. }
  14144. audioPid = parsedPIDs.audioPid;
  14145. if (audioPid > 0) {
  14146. audioTrack.pid = audioPid;
  14147. audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;
  14148. }
  14149. id3Pid = parsedPIDs.id3Pid;
  14150. if (id3Pid > 0) {
  14151. id3Track.pid = id3Pid;
  14152. }
  14153. if (unknownPID !== null && !pmtParsed) {
  14154. this.logger.warn(`MPEG-TS PMT found at ${start} after unknown PID '${unknownPID}'. Backtracking to sync byte @${syncOffset} to parse all TS packets.`);
  14155. unknownPID = null;
  14156. // we set it to -188, the += 188 in the for loop will reset start to 0
  14157. start = syncOffset - 188;
  14158. }
  14159. pmtParsed = this.pmtParsed = true;
  14160. break;
  14161. }
  14162. case 0x11:
  14163. case 0x1fff:
  14164. break;
  14165. default:
  14166. unknownPID = pid;
  14167. break;
  14168. }
  14169. } else {
  14170. tsPacketErrors++;
  14171. }
  14172. }
  14173. if (tsPacketErrors > 0) {
  14174. emitParsingError(this.observer, new Error(`Found ${tsPacketErrors} TS packet/s that do not start with 0x47`), undefined, this.logger);
  14175. }
  14176. videoTrack.pesData = videoData;
  14177. audioTrack.pesData = audioData;
  14178. id3Track.pesData = id3Data;
  14179. const demuxResult = {
  14180. audioTrack,
  14181. videoTrack,
  14182. id3Track,
  14183. textTrack
  14184. };
  14185. if (flush) {
  14186. this.extractRemainingSamples(demuxResult);
  14187. }
  14188. return demuxResult;
  14189. }
  14190. flush() {
  14191. const {
  14192. remainderData
  14193. } = this;
  14194. this.remainderData = null;
  14195. let result;
  14196. if (remainderData) {
  14197. result = this.demux(remainderData, -1, false, true);
  14198. } else {
  14199. result = {
  14200. videoTrack: this._videoTrack,
  14201. audioTrack: this._audioTrack,
  14202. id3Track: this._id3Track,
  14203. textTrack: this._txtTrack
  14204. };
  14205. }
  14206. this.extractRemainingSamples(result);
  14207. if (this.sampleAes) {
  14208. return this.decrypt(result, this.sampleAes);
  14209. }
  14210. return result;
  14211. }
  14212. extractRemainingSamples(demuxResult) {
  14213. const {
  14214. audioTrack,
  14215. videoTrack,
  14216. id3Track,
  14217. textTrack
  14218. } = demuxResult;
  14219. const videoData = videoTrack.pesData;
  14220. const audioData = audioTrack.pesData;
  14221. const id3Data = id3Track.pesData;
  14222. // try to parse last PES packets
  14223. let pes;
  14224. if (videoData && (pes = parsePES(videoData, this.logger))) {
  14225. if (this.videoParser === null) {
  14226. switch (videoTrack.segmentCodec) {
  14227. case 'avc':
  14228. this.videoParser = new AvcVideoParser();
  14229. break;
  14230. }
  14231. }
  14232. if (this.videoParser !== null) {
  14233. this.videoParser.parsePES(videoTrack, textTrack, pes, true);
  14234. videoTrack.pesData = null;
  14235. }
  14236. } else {
  14237. // either avcData null or PES truncated, keep it for next frag parsing
  14238. videoTrack.pesData = videoData;
  14239. }
  14240. if (audioData && (pes = parsePES(audioData, this.logger))) {
  14241. switch (audioTrack.segmentCodec) {
  14242. case 'aac':
  14243. this.parseAACPES(audioTrack, pes);
  14244. break;
  14245. case 'mp3':
  14246. this.parseMPEGPES(audioTrack, pes);
  14247. break;
  14248. }
  14249. audioTrack.pesData = null;
  14250. } else {
  14251. if (audioData != null && audioData.size) {
  14252. this.logger.log('last AAC PES packet truncated,might overlap between fragments');
  14253. }
  14254. // either audioData null or PES truncated, keep it for next frag parsing
  14255. audioTrack.pesData = audioData;
  14256. }
  14257. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  14258. this.parseID3PES(id3Track, pes);
  14259. id3Track.pesData = null;
  14260. } else {
  14261. // either id3Data null or PES truncated, keep it for next frag parsing
  14262. id3Track.pesData = id3Data;
  14263. }
  14264. }
  14265. demuxSampleAes(data, keyData, timeOffset) {
  14266. const demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
  14267. const sampleAes = this.sampleAes = new SampleAesDecrypter(this.observer, this.config, keyData);
  14268. return this.decrypt(demuxResult, sampleAes);
  14269. }
  14270. decrypt(demuxResult, sampleAes) {
  14271. return new Promise(resolve => {
  14272. const {
  14273. audioTrack,
  14274. videoTrack
  14275. } = demuxResult;
  14276. if (audioTrack.samples && audioTrack.segmentCodec === 'aac') {
  14277. sampleAes.decryptAacSamples(audioTrack.samples, 0, () => {
  14278. if (videoTrack.samples) {
  14279. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  14280. resolve(demuxResult);
  14281. });
  14282. } else {
  14283. resolve(demuxResult);
  14284. }
  14285. });
  14286. } else if (videoTrack.samples) {
  14287. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  14288. resolve(demuxResult);
  14289. });
  14290. }
  14291. });
  14292. }
  14293. destroy() {
  14294. if (this.observer) {
  14295. this.observer.removeAllListeners();
  14296. }
  14297. // @ts-ignore
  14298. this.config = this.logger = this.observer = null;
  14299. this.aacOverFlow = this.videoParser = this.remainderData = this.sampleAes = null;
  14300. this._videoTrack = this._audioTrack = this._id3Track = this._txtTrack = undefined;
  14301. }
  14302. parseAACPES(track, pes) {
  14303. let startOffset = 0;
  14304. const aacOverFlow = this.aacOverFlow;
  14305. let data = pes.data;
  14306. if (aacOverFlow) {
  14307. this.aacOverFlow = null;
  14308. const frameMissingBytes = aacOverFlow.missing;
  14309. const sampleLength = aacOverFlow.sample.unit.byteLength;
  14310. // logger.log(`AAC: append overflowing ${sampleLength} bytes to beginning of new PES`);
  14311. if (frameMissingBytes === -1) {
  14312. data = appendUint8Array(aacOverFlow.sample.unit, data);
  14313. } else {
  14314. const frameOverflowBytes = sampleLength - frameMissingBytes;
  14315. aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
  14316. track.samples.push(aacOverFlow.sample);
  14317. startOffset = aacOverFlow.missing;
  14318. }
  14319. }
  14320. // look for ADTS header (0xFFFx)
  14321. let offset;
  14322. let len;
  14323. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  14324. if (isHeader$1(data, offset)) {
  14325. break;
  14326. }
  14327. }
  14328. // if ADTS header does not start straight from the beginning of the PES payload, raise an error
  14329. if (offset !== startOffset) {
  14330. let reason;
  14331. const recoverable = offset < len - 1;
  14332. if (recoverable) {
  14333. reason = `AAC PES did not start with ADTS header,offset:${offset}`;
  14334. } else {
  14335. reason = 'No ADTS header found in AAC PES';
  14336. }
  14337. emitParsingError(this.observer, new Error(reason), recoverable, this.logger);
  14338. if (!recoverable) {
  14339. return;
  14340. }
  14341. }
  14342. initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  14343. let pts;
  14344. if (pes.pts !== undefined) {
  14345. pts = pes.pts;
  14346. } else if (aacOverFlow) {
  14347. // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
  14348. // first sample PTS should be equal to last sample PTS + frameDuration
  14349. const frameDuration = getFrameDuration(track.samplerate);
  14350. pts = aacOverFlow.sample.pts + frameDuration;
  14351. } else {
  14352. this.logger.warn('[tsdemuxer]: AAC PES unknown PTS');
  14353. return;
  14354. }
  14355. // scan for aac samples
  14356. let frameIndex = 0;
  14357. let frame;
  14358. while (offset < len) {
  14359. frame = appendFrame$1(track, data, offset, pts, frameIndex);
  14360. offset += frame.length;
  14361. if (!frame.missing) {
  14362. frameIndex++;
  14363. for (; offset < len - 1; offset++) {
  14364. if (isHeader$1(data, offset)) {
  14365. break;
  14366. }
  14367. }
  14368. } else {
  14369. this.aacOverFlow = frame;
  14370. break;
  14371. }
  14372. }
  14373. }
  14374. parseMPEGPES(track, pes) {
  14375. const data = pes.data;
  14376. const length = data.length;
  14377. let frameIndex = 0;
  14378. let offset = 0;
  14379. const pts = pes.pts;
  14380. if (pts === undefined) {
  14381. this.logger.warn('[tsdemuxer]: MPEG PES unknown PTS');
  14382. return;
  14383. }
  14384. while (offset < length) {
  14385. if (isHeader(data, offset)) {
  14386. const frame = appendFrame(track, data, offset, pts, frameIndex);
  14387. if (frame) {
  14388. offset += frame.length;
  14389. frameIndex++;
  14390. } else {
  14391. // logger.log('Unable to parse Mpeg audio frame');
  14392. break;
  14393. }
  14394. } else {
  14395. // nothing found, keep looking
  14396. offset++;
  14397. }
  14398. }
  14399. }
  14400. parseAC3PES(track, pes) {
  14401. }
  14402. parseID3PES(id3Track, pes) {
  14403. if (pes.pts === undefined) {
  14404. this.logger.warn('[tsdemuxer]: ID3 PES unknown PTS');
  14405. return;
  14406. }
  14407. const id3Sample = _extends({}, pes, {
  14408. type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,
  14409. duration: Number.POSITIVE_INFINITY
  14410. });
  14411. id3Track.samples.push(id3Sample);
  14412. }
  14413. }
  14414. function parsePID(data, offset) {
  14415. // pid is a 13-bit field starting at the last bit of TS[1]
  14416. return ((data[offset + 1] & 0x1f) << 8) + data[offset + 2];
  14417. }
  14418. function parsePAT(data, offset) {
  14419. // skip the PSI header and parse the first PMT entry
  14420. return (data[offset + 10] & 0x1f) << 8 | data[offset + 11];
  14421. }
  14422. function parsePMT(data, offset, typeSupported, isSampleAes, observer, logger) {
  14423. const result = {
  14424. audioPid: -1,
  14425. videoPid: -1,
  14426. id3Pid: -1,
  14427. segmentVideoCodec: 'avc',
  14428. segmentAudioCodec: 'aac'
  14429. };
  14430. const sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
  14431. const tableEnd = offset + 3 + sectionLength - 4;
  14432. // to determine where the table is, we have to figure out how
  14433. // long the program info descriptors are
  14434. const programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
  14435. // advance the offset to the first entry in the mapping table
  14436. offset += 12 + programInfoLength;
  14437. while (offset < tableEnd) {
  14438. const pid = parsePID(data, offset);
  14439. const esInfoLength = (data[offset + 3] & 0x0f) << 8 | data[offset + 4];
  14440. switch (data[offset]) {
  14441. case 0xcf:
  14442. // SAMPLE-AES AAC
  14443. if (!isSampleAes) {
  14444. logEncryptedSamplesFoundInUnencryptedStream('ADTS AAC', logger);
  14445. break;
  14446. }
  14447. /* falls through */
  14448. case 0x0f:
  14449. // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
  14450. // logger.log('AAC PID:' + pid);
  14451. if (result.audioPid === -1) {
  14452. result.audioPid = pid;
  14453. }
  14454. break;
  14455. // Packetized metadata (ID3)
  14456. case 0x15:
  14457. // logger.log('ID3 PID:' + pid);
  14458. if (result.id3Pid === -1) {
  14459. result.id3Pid = pid;
  14460. }
  14461. break;
  14462. case 0xdb:
  14463. // SAMPLE-AES AVC
  14464. if (!isSampleAes) {
  14465. logEncryptedSamplesFoundInUnencryptedStream('H.264', logger);
  14466. break;
  14467. }
  14468. /* falls through */
  14469. case 0x1b:
  14470. // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
  14471. // logger.log('AVC PID:' + pid);
  14472. if (result.videoPid === -1) {
  14473. result.videoPid = pid;
  14474. }
  14475. break;
  14476. // ISO/IEC 11172-3 (MPEG-1 audio)
  14477. // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
  14478. case 0x03:
  14479. case 0x04:
  14480. // logger.log('MPEG PID:' + pid);
  14481. if (!typeSupported.mpeg && !typeSupported.mp3) {
  14482. logger.log('MPEG audio found, not supported in this browser');
  14483. } else if (result.audioPid === -1) {
  14484. result.audioPid = pid;
  14485. result.segmentAudioCodec = 'mp3';
  14486. }
  14487. break;
  14488. case 0xc1:
  14489. // SAMPLE-AES AC3
  14490. if (!isSampleAes) {
  14491. logEncryptedSamplesFoundInUnencryptedStream('AC-3', logger);
  14492. break;
  14493. }
  14494. /* falls through */
  14495. case 0x81:
  14496. {
  14497. logger.warn('AC-3 in M2TS support not included in build');
  14498. }
  14499. break;
  14500. case 0x06:
  14501. // stream_type 6 can mean a lot of different things in case of DVB.
  14502. // We need to look at the descriptors. Right now, we're only interested
  14503. // in AC-3 audio, so we do the descriptor parsing only when we don't have
  14504. // an audio PID yet.
  14505. if (result.audioPid === -1 && esInfoLength > 0) {
  14506. let parsePos = offset + 5;
  14507. let remaining = esInfoLength;
  14508. while (remaining > 2) {
  14509. const descriptorId = data[parsePos];
  14510. switch (descriptorId) {
  14511. case 0x6a:
  14512. // DVB Descriptor for AC-3
  14513. {
  14514. logger.warn('AC-3 in M2TS support not included in build');
  14515. }
  14516. break;
  14517. }
  14518. const descriptorLen = data[parsePos + 1] + 2;
  14519. parsePos += descriptorLen;
  14520. remaining -= descriptorLen;
  14521. }
  14522. }
  14523. break;
  14524. case 0xc2: // SAMPLE-AES EC3
  14525. /* falls through */
  14526. case 0x87:
  14527. emitParsingError(observer, new Error('Unsupported EC-3 in M2TS found'), undefined, logger);
  14528. return result;
  14529. case 0x24:
  14530. // ITU-T Rec. H.265 and ISO/IEC 23008-2 (HEVC)
  14531. {
  14532. emitParsingError(observer, new Error('Unsupported HEVC in M2TS found'), undefined, logger);
  14533. return result;
  14534. }
  14535. }
  14536. // move to the next table entry
  14537. // skip past the elementary stream descriptors, if present
  14538. offset += esInfoLength + 5;
  14539. }
  14540. return result;
  14541. }
  14542. function emitParsingError(observer, error, levelRetry, logger) {
  14543. logger.warn(`parsing error: ${error.message}`);
  14544. observer.emit(Events.ERROR, Events.ERROR, {
  14545. type: ErrorTypes.MEDIA_ERROR,
  14546. details: ErrorDetails.FRAG_PARSING_ERROR,
  14547. fatal: false,
  14548. levelRetry,
  14549. error,
  14550. reason: error.message
  14551. });
  14552. }
  14553. function logEncryptedSamplesFoundInUnencryptedStream(type, logger) {
  14554. logger.log(`${type} with AES-128-CBC encryption found in unencrypted stream`);
  14555. }
  14556. function parsePES(stream, logger) {
  14557. let i = 0;
  14558. let frag;
  14559. let pesLen;
  14560. let pesHdrLen;
  14561. let pesPts;
  14562. let pesDts;
  14563. const data = stream.data;
  14564. // safety check
  14565. if (!stream || stream.size === 0) {
  14566. return null;
  14567. }
  14568. // we might need up to 19 bytes to read PES header
  14569. // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
  14570. // usually only one merge is needed (and this is rare ...)
  14571. while (data[0].length < 19 && data.length > 1) {
  14572. data[0] = appendUint8Array(data[0], data[1]);
  14573. data.splice(1, 1);
  14574. }
  14575. // retrieve PTS/DTS from first fragment
  14576. frag = data[0];
  14577. const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  14578. if (pesPrefix === 1) {
  14579. pesLen = (frag[4] << 8) + frag[5];
  14580. // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
  14581. // minus 6 : PES header size
  14582. if (pesLen && pesLen > stream.size - 6) {
  14583. return null;
  14584. }
  14585. const pesFlags = frag[7];
  14586. if (pesFlags & 0xc0) {
  14587. /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  14588. as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
  14589. as Bitwise operators treat their operands as a sequence of 32 bits */
  14590. pesPts = (frag[9] & 0x0e) * 536870912 +
  14591. // 1 << 29
  14592. (frag[10] & 0xff) * 4194304 +
  14593. // 1 << 22
  14594. (frag[11] & 0xfe) * 16384 +
  14595. // 1 << 14
  14596. (frag[12] & 0xff) * 128 +
  14597. // 1 << 7
  14598. (frag[13] & 0xfe) / 2;
  14599. if (pesFlags & 0x40) {
  14600. pesDts = (frag[14] & 0x0e) * 536870912 +
  14601. // 1 << 29
  14602. (frag[15] & 0xff) * 4194304 +
  14603. // 1 << 22
  14604. (frag[16] & 0xfe) * 16384 +
  14605. // 1 << 14
  14606. (frag[17] & 0xff) * 128 +
  14607. // 1 << 7
  14608. (frag[18] & 0xfe) / 2;
  14609. if (pesPts - pesDts > 60 * 90000) {
  14610. logger.warn(`${Math.round((pesPts - pesDts) / 90000)}s delta between PTS and DTS, align them`);
  14611. pesPts = pesDts;
  14612. }
  14613. } else {
  14614. pesDts = pesPts;
  14615. }
  14616. }
  14617. pesHdrLen = frag[8];
  14618. // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
  14619. let payloadStartOffset = pesHdrLen + 9;
  14620. if (stream.size <= payloadStartOffset) {
  14621. return null;
  14622. }
  14623. stream.size -= payloadStartOffset;
  14624. // reassemble PES packet
  14625. const pesData = new Uint8Array(stream.size);
  14626. for (let j = 0, dataLen = data.length; j < dataLen; j++) {
  14627. frag = data[j];
  14628. let len = frag.byteLength;
  14629. if (payloadStartOffset) {
  14630. if (payloadStartOffset > len) {
  14631. // trim full frag if PES header bigger than frag
  14632. payloadStartOffset -= len;
  14633. continue;
  14634. } else {
  14635. // trim partial frag if PES header smaller than frag
  14636. frag = frag.subarray(payloadStartOffset);
  14637. len -= payloadStartOffset;
  14638. payloadStartOffset = 0;
  14639. }
  14640. }
  14641. pesData.set(frag, i);
  14642. i += len;
  14643. }
  14644. if (pesLen) {
  14645. // payload size : remove PES header + PES extension
  14646. pesLen -= pesHdrLen + 3;
  14647. }
  14648. return {
  14649. data: pesData,
  14650. pts: pesPts,
  14651. dts: pesDts,
  14652. len: pesLen
  14653. };
  14654. }
  14655. return null;
  14656. }
  14657. /**
  14658. * AAC helper
  14659. */
  14660. class AAC {
  14661. static getSilentFrame(codec, channelCount) {
  14662. switch (codec) {
  14663. case 'mp4a.40.2':
  14664. if (channelCount === 1) {
  14665. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  14666. } else if (channelCount === 2) {
  14667. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  14668. } else if (channelCount === 3) {
  14669. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  14670. } else if (channelCount === 4) {
  14671. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  14672. } else if (channelCount === 5) {
  14673. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  14674. } else if (channelCount === 6) {
  14675. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]);
  14676. }
  14677. break;
  14678. // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
  14679. default:
  14680. if (channelCount === 1) {
  14681. // ffmpeg -y -f lavfi -i "aevalsrc=0:d=0.05" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
  14682. return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
  14683. } else if (channelCount === 2) {
  14684. // ffmpeg -y -f lavfi -i "aevalsrc=0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
  14685. return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
  14686. } else if (channelCount === 3) {
  14687. // ffmpeg -y -f lavfi -i "aevalsrc=0|0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
  14688. return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
  14689. }
  14690. break;
  14691. }
  14692. return undefined;
  14693. }
  14694. }
  14695. /**
  14696. * Generate MP4 Box
  14697. */
  14698. const UINT32_MAX = Math.pow(2, 32) - 1;
  14699. class MP4 {
  14700. static init() {
  14701. MP4.types = {
  14702. avc1: [],
  14703. // codingname
  14704. avcC: [],
  14705. hvc1: [],
  14706. hvcC: [],
  14707. btrt: [],
  14708. dinf: [],
  14709. dref: [],
  14710. esds: [],
  14711. ftyp: [],
  14712. hdlr: [],
  14713. mdat: [],
  14714. mdhd: [],
  14715. mdia: [],
  14716. mfhd: [],
  14717. minf: [],
  14718. moof: [],
  14719. moov: [],
  14720. mp4a: [],
  14721. '.mp3': [],
  14722. dac3: [],
  14723. 'ac-3': [],
  14724. mvex: [],
  14725. mvhd: [],
  14726. pasp: [],
  14727. sdtp: [],
  14728. stbl: [],
  14729. stco: [],
  14730. stsc: [],
  14731. stsd: [],
  14732. stsz: [],
  14733. stts: [],
  14734. tfdt: [],
  14735. tfhd: [],
  14736. traf: [],
  14737. trak: [],
  14738. trun: [],
  14739. trex: [],
  14740. tkhd: [],
  14741. vmhd: [],
  14742. smhd: []
  14743. };
  14744. let i;
  14745. for (i in MP4.types) {
  14746. if (MP4.types.hasOwnProperty(i)) {
  14747. MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  14748. }
  14749. }
  14750. const videoHdlr = new Uint8Array([0x00,
  14751. // version 0
  14752. 0x00, 0x00, 0x00,
  14753. // flags
  14754. 0x00, 0x00, 0x00, 0x00,
  14755. // pre_defined
  14756. 0x76, 0x69, 0x64, 0x65,
  14757. // handler_type: 'vide'
  14758. 0x00, 0x00, 0x00, 0x00,
  14759. // reserved
  14760. 0x00, 0x00, 0x00, 0x00,
  14761. // reserved
  14762. 0x00, 0x00, 0x00, 0x00,
  14763. // reserved
  14764. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  14765. ]);
  14766. const audioHdlr = new Uint8Array([0x00,
  14767. // version 0
  14768. 0x00, 0x00, 0x00,
  14769. // flags
  14770. 0x00, 0x00, 0x00, 0x00,
  14771. // pre_defined
  14772. 0x73, 0x6f, 0x75, 0x6e,
  14773. // handler_type: 'soun'
  14774. 0x00, 0x00, 0x00, 0x00,
  14775. // reserved
  14776. 0x00, 0x00, 0x00, 0x00,
  14777. // reserved
  14778. 0x00, 0x00, 0x00, 0x00,
  14779. // reserved
  14780. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  14781. ]);
  14782. MP4.HDLR_TYPES = {
  14783. video: videoHdlr,
  14784. audio: audioHdlr
  14785. };
  14786. const dref = new Uint8Array([0x00,
  14787. // version 0
  14788. 0x00, 0x00, 0x00,
  14789. // flags
  14790. 0x00, 0x00, 0x00, 0x01,
  14791. // entry_count
  14792. 0x00, 0x00, 0x00, 0x0c,
  14793. // entry_size
  14794. 0x75, 0x72, 0x6c, 0x20,
  14795. // 'url' type
  14796. 0x00,
  14797. // version 0
  14798. 0x00, 0x00, 0x01 // entry_flags
  14799. ]);
  14800. const stco = new Uint8Array([0x00,
  14801. // version
  14802. 0x00, 0x00, 0x00,
  14803. // flags
  14804. 0x00, 0x00, 0x00, 0x00 // entry_count
  14805. ]);
  14806. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  14807. MP4.STSZ = new Uint8Array([0x00,
  14808. // version
  14809. 0x00, 0x00, 0x00,
  14810. // flags
  14811. 0x00, 0x00, 0x00, 0x00,
  14812. // sample_size
  14813. 0x00, 0x00, 0x00, 0x00 // sample_count
  14814. ]);
  14815. MP4.VMHD = new Uint8Array([0x00,
  14816. // version
  14817. 0x00, 0x00, 0x01,
  14818. // flags
  14819. 0x00, 0x00,
  14820. // graphicsmode
  14821. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  14822. ]);
  14823. MP4.SMHD = new Uint8Array([0x00,
  14824. // version
  14825. 0x00, 0x00, 0x00,
  14826. // flags
  14827. 0x00, 0x00,
  14828. // balance
  14829. 0x00, 0x00 // reserved
  14830. ]);
  14831. MP4.STSD = new Uint8Array([0x00,
  14832. // version 0
  14833. 0x00, 0x00, 0x00,
  14834. // flags
  14835. 0x00, 0x00, 0x00, 0x01]); // entry_count
  14836. const majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
  14837. const avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
  14838. const minorVersion = new Uint8Array([0, 0, 0, 1]);
  14839. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  14840. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  14841. }
  14842. static box(type, ...payload) {
  14843. let size = 8;
  14844. let i = payload.length;
  14845. const len = i;
  14846. // calculate the total size we need to allocate
  14847. while (i--) {
  14848. size += payload[i].byteLength;
  14849. }
  14850. const result = new Uint8Array(size);
  14851. result[0] = size >> 24 & 0xff;
  14852. result[1] = size >> 16 & 0xff;
  14853. result[2] = size >> 8 & 0xff;
  14854. result[3] = size & 0xff;
  14855. result.set(type, 4);
  14856. // copy the payload into the result
  14857. for (i = 0, size = 8; i < len; i++) {
  14858. // copy payload[i] array @ offset size
  14859. result.set(payload[i], size);
  14860. size += payload[i].byteLength;
  14861. }
  14862. return result;
  14863. }
  14864. static hdlr(type) {
  14865. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  14866. }
  14867. static mdat(data) {
  14868. return MP4.box(MP4.types.mdat, data);
  14869. }
  14870. static mdhd(timescale, duration) {
  14871. duration *= timescale;
  14872. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  14873. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  14874. return MP4.box(MP4.types.mdhd, new Uint8Array([0x01,
  14875. // version 1
  14876. 0x00, 0x00, 0x00,
  14877. // flags
  14878. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  14879. // creation_time
  14880. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  14881. // modification_time
  14882. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  14883. // timescale
  14884. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x55, 0xc4,
  14885. // 'und' language (undetermined)
  14886. 0x00, 0x00]));
  14887. }
  14888. static mdia(track) {
  14889. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale || 0, track.duration || 0), MP4.hdlr(track.type), MP4.minf(track));
  14890. }
  14891. static mfhd(sequenceNumber) {
  14892. return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00,
  14893. // flags
  14894. sequenceNumber >> 24, sequenceNumber >> 16 & 0xff, sequenceNumber >> 8 & 0xff, sequenceNumber & 0xff // sequence_number
  14895. ]));
  14896. }
  14897. static minf(track) {
  14898. if (track.type === 'audio') {
  14899. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  14900. } else {
  14901. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  14902. }
  14903. }
  14904. static moof(sn, baseMediaDecodeTime, track) {
  14905. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  14906. }
  14907. static moov(tracks) {
  14908. let i = tracks.length;
  14909. const boxes = [];
  14910. while (i--) {
  14911. boxes[i] = MP4.trak(tracks[i]);
  14912. }
  14913. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale || 0, tracks[0].duration || 0)].concat(boxes).concat(MP4.mvex(tracks)));
  14914. }
  14915. static mvex(tracks) {
  14916. let i = tracks.length;
  14917. const boxes = [];
  14918. while (i--) {
  14919. boxes[i] = MP4.trex(tracks[i]);
  14920. }
  14921. return MP4.box.apply(null, [MP4.types.mvex, ...boxes]);
  14922. }
  14923. static mvhd(timescale, duration) {
  14924. duration *= timescale;
  14925. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  14926. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  14927. const bytes = new Uint8Array([0x01,
  14928. // version 1
  14929. 0x00, 0x00, 0x00,
  14930. // flags
  14931. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  14932. // creation_time
  14933. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  14934. // modification_time
  14935. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  14936. // timescale
  14937. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x01, 0x00, 0x00,
  14938. // 1.0 rate
  14939. 0x01, 0x00,
  14940. // 1.0 volume
  14941. 0x00, 0x00,
  14942. // reserved
  14943. 0x00, 0x00, 0x00, 0x00,
  14944. // reserved
  14945. 0x00, 0x00, 0x00, 0x00,
  14946. // reserved
  14947. 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
  14948. // transformation: unity matrix
  14949. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  14950. // pre_defined
  14951. 0xff, 0xff, 0xff, 0xff // next_track_ID
  14952. ]);
  14953. return MP4.box(MP4.types.mvhd, bytes);
  14954. }
  14955. static sdtp(track) {
  14956. const samples = track.samples || [];
  14957. const bytes = new Uint8Array(4 + samples.length);
  14958. let i;
  14959. let flags;
  14960. // leave the full box header (4 bytes) all zero
  14961. // write the sample table
  14962. for (i = 0; i < samples.length; i++) {
  14963. flags = samples[i].flags;
  14964. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  14965. }
  14966. return MP4.box(MP4.types.sdtp, bytes);
  14967. }
  14968. static stbl(track) {
  14969. 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));
  14970. }
  14971. static avc1(track) {
  14972. let sps = [];
  14973. let pps = [];
  14974. let i;
  14975. let data;
  14976. let len;
  14977. // assemble the SPSs
  14978. for (i = 0; i < track.sps.length; i++) {
  14979. data = track.sps[i];
  14980. len = data.byteLength;
  14981. sps.push(len >>> 8 & 0xff);
  14982. sps.push(len & 0xff);
  14983. // SPS
  14984. sps = sps.concat(Array.prototype.slice.call(data));
  14985. }
  14986. // assemble the PPSs
  14987. for (i = 0; i < track.pps.length; i++) {
  14988. data = track.pps[i];
  14989. len = data.byteLength;
  14990. pps.push(len >>> 8 & 0xff);
  14991. pps.push(len & 0xff);
  14992. pps = pps.concat(Array.prototype.slice.call(data));
  14993. }
  14994. const avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01,
  14995. // version
  14996. sps[3],
  14997. // profile
  14998. sps[4],
  14999. // profile compat
  15000. sps[5],
  15001. // level
  15002. 0xfc | 3,
  15003. // lengthSizeMinusOne, hard-coded to 4 bytes
  15004. 0xe0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
  15005. ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
  15006. ]).concat(pps))); // "PPS"
  15007. const width = track.width;
  15008. const height = track.height;
  15009. const hSpacing = track.pixelRatio[0];
  15010. const vSpacing = track.pixelRatio[1];
  15011. return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00,
  15012. // reserved
  15013. 0x00, 0x00, 0x00,
  15014. // reserved
  15015. 0x00, 0x01,
  15016. // data_reference_index
  15017. 0x00, 0x00,
  15018. // pre_defined
  15019. 0x00, 0x00,
  15020. // reserved
  15021. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  15022. // pre_defined
  15023. width >> 8 & 0xff, width & 0xff,
  15024. // width
  15025. height >> 8 & 0xff, height & 0xff,
  15026. // height
  15027. 0x00, 0x48, 0x00, 0x00,
  15028. // horizresolution
  15029. 0x00, 0x48, 0x00, 0x00,
  15030. // vertresolution
  15031. 0x00, 0x00, 0x00, 0x00,
  15032. // reserved
  15033. 0x00, 0x01,
  15034. // frame_count
  15035. 0x12, 0x64, 0x61, 0x69, 0x6c,
  15036. // dailymotion/hls.js
  15037. 0x79, 0x6d, 0x6f, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x68, 0x6c, 0x73, 0x2e, 0x6a, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  15038. // compressorname
  15039. 0x00, 0x18,
  15040. // depth = 24
  15041. 0x11, 0x11]),
  15042. // pre_defined = -1
  15043. avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,
  15044. // bufferSizeDB
  15045. 0x00, 0x2d, 0xc6, 0xc0,
  15046. // maxBitrate
  15047. 0x00, 0x2d, 0xc6, 0xc0])),
  15048. // avgBitrate
  15049. MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24,
  15050. // hSpacing
  15051. hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24,
  15052. // vSpacing
  15053. vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));
  15054. }
  15055. static esds(track) {
  15056. const config = track.config;
  15057. return new Uint8Array([0x00,
  15058. // version 0
  15059. 0x00, 0x00, 0x00,
  15060. // flags
  15061. 0x03,
  15062. // descriptor_type
  15063. 0x19,
  15064. // length
  15065. 0x00, 0x01,
  15066. // es_id
  15067. 0x00,
  15068. // stream_priority
  15069. 0x04,
  15070. // descriptor_type
  15071. 0x11,
  15072. // length
  15073. 0x40,
  15074. // codec : mpeg4_audio
  15075. 0x15,
  15076. // stream_type
  15077. 0x00, 0x00, 0x00,
  15078. // buffer_size
  15079. 0x00, 0x00, 0x00, 0x00,
  15080. // maxBitrate
  15081. 0x00, 0x00, 0x00, 0x00,
  15082. // avgBitrate
  15083. 0x05,
  15084. // descriptor_type
  15085. 0x02,
  15086. // length
  15087. ...config, 0x06, 0x01, 0x02 // GASpecificConfig)); // length + audio config descriptor
  15088. ]);
  15089. }
  15090. static audioStsd(track) {
  15091. const samplerate = track.samplerate || 0;
  15092. return new Uint8Array([0x00, 0x00, 0x00,
  15093. // reserved
  15094. 0x00, 0x00, 0x00,
  15095. // reserved
  15096. 0x00, 0x01,
  15097. // data_reference_index
  15098. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  15099. // reserved
  15100. 0x00, track.channelCount || 0,
  15101. // channelcount
  15102. 0x00, 0x10,
  15103. // sampleSize:16bits
  15104. 0x00, 0x00, 0x00, 0x00,
  15105. // reserved2
  15106. samplerate >> 8 & 0xff, samplerate & 0xff,
  15107. //
  15108. 0x00, 0x00]);
  15109. }
  15110. static mp4a(track) {
  15111. return MP4.box(MP4.types.mp4a, MP4.audioStsd(track), MP4.box(MP4.types.esds, MP4.esds(track)));
  15112. }
  15113. static mp3(track) {
  15114. return MP4.box(MP4.types['.mp3'], MP4.audioStsd(track));
  15115. }
  15116. static ac3(track) {
  15117. return MP4.box(MP4.types['ac-3'], MP4.audioStsd(track), MP4.box(MP4.types.dac3, track.config));
  15118. }
  15119. static stsd(track) {
  15120. const {
  15121. segmentCodec
  15122. } = track;
  15123. if (track.type === 'audio') {
  15124. if (segmentCodec === 'aac') {
  15125. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  15126. }
  15127. if (segmentCodec === 'mp3' && track.codec === 'mp3') {
  15128. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  15129. }
  15130. } else {
  15131. if (track.pps && track.sps) {
  15132. if (segmentCodec === 'avc') {
  15133. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  15134. }
  15135. } else {
  15136. throw new Error(`video track missing pps or sps`);
  15137. }
  15138. }
  15139. throw new Error(`unsupported ${track.type} segment codec (${segmentCodec}/${track.codec})`);
  15140. }
  15141. static tkhd(track) {
  15142. const id = track.id;
  15143. const duration = (track.duration || 0) * (track.timescale || 0);
  15144. const width = track.width || 0;
  15145. const height = track.height || 0;
  15146. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  15147. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  15148. return MP4.box(MP4.types.tkhd, new Uint8Array([0x01,
  15149. // version 1
  15150. 0x00, 0x00, 0x07,
  15151. // flags
  15152. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  15153. // creation_time
  15154. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  15155. // modification_time
  15156. id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  15157. // track_ID
  15158. 0x00, 0x00, 0x00, 0x00,
  15159. // reserved
  15160. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  15161. // reserved
  15162. 0x00, 0x00,
  15163. // layer
  15164. 0x00, 0x00,
  15165. // alternate_group
  15166. 0x00, 0x00,
  15167. // non-audio track volume
  15168. 0x00, 0x00,
  15169. // reserved
  15170. 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
  15171. // transformation: unity matrix
  15172. width >> 8 & 0xff, width & 0xff, 0x00, 0x00,
  15173. // width
  15174. height >> 8 & 0xff, height & 0xff, 0x00, 0x00 // height
  15175. ]));
  15176. }
  15177. static traf(track, baseMediaDecodeTime) {
  15178. const sampleDependencyTable = MP4.sdtp(track);
  15179. const id = track.id;
  15180. const upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  15181. const lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  15182. return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00,
  15183. // version 0
  15184. 0x00, 0x00, 0x00,
  15185. // flags
  15186. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff // track_ID
  15187. ])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01,
  15188. // version 1
  15189. 0x00, 0x00, 0x00,
  15190. // flags
  15191. upperWordBaseMediaDecodeTime >> 24, upperWordBaseMediaDecodeTime >> 16 & 0xff, upperWordBaseMediaDecodeTime >> 8 & 0xff, upperWordBaseMediaDecodeTime & 0xff, lowerWordBaseMediaDecodeTime >> 24, lowerWordBaseMediaDecodeTime >> 16 & 0xff, lowerWordBaseMediaDecodeTime >> 8 & 0xff, lowerWordBaseMediaDecodeTime & 0xff])), MP4.trun(track, sampleDependencyTable.length + 16 +
  15192. // tfhd
  15193. 20 +
  15194. // tfdt
  15195. 8 +
  15196. // traf header
  15197. 16 +
  15198. // mfhd
  15199. 8 +
  15200. // moof header
  15201. 8),
  15202. // mdat header
  15203. sampleDependencyTable);
  15204. }
  15205. /**
  15206. * Generate a track box.
  15207. * @param track a track definition
  15208. */
  15209. static trak(track) {
  15210. track.duration = track.duration || 0xffffffff;
  15211. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  15212. }
  15213. static trex(track) {
  15214. const id = track.id;
  15215. return MP4.box(MP4.types.trex, new Uint8Array([0x00,
  15216. // version 0
  15217. 0x00, 0x00, 0x00,
  15218. // flags
  15219. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  15220. // track_ID
  15221. 0x00, 0x00, 0x00, 0x01,
  15222. // default_sample_description_index
  15223. 0x00, 0x00, 0x00, 0x00,
  15224. // default_sample_duration
  15225. 0x00, 0x00, 0x00, 0x00,
  15226. // default_sample_size
  15227. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  15228. ]));
  15229. }
  15230. static trun(track, offset) {
  15231. const samples = track.samples || [];
  15232. const len = samples.length;
  15233. const arraylen = 12 + 16 * len;
  15234. const array = new Uint8Array(arraylen);
  15235. let i;
  15236. let sample;
  15237. let duration;
  15238. let size;
  15239. let flags;
  15240. let cts;
  15241. offset += 8 + arraylen;
  15242. array.set([track.type === 'video' ? 0x01 : 0x00,
  15243. // version 1 for video with signed-int sample_composition_time_offset
  15244. 0x00, 0x0f, 0x01,
  15245. // flags
  15246. len >>> 24 & 0xff, len >>> 16 & 0xff, len >>> 8 & 0xff, len & 0xff,
  15247. // sample_count
  15248. offset >>> 24 & 0xff, offset >>> 16 & 0xff, offset >>> 8 & 0xff, offset & 0xff // data_offset
  15249. ], 0);
  15250. for (i = 0; i < len; i++) {
  15251. sample = samples[i];
  15252. duration = sample.duration;
  15253. size = sample.size;
  15254. flags = sample.flags;
  15255. cts = sample.cts;
  15256. array.set([duration >>> 24 & 0xff, duration >>> 16 & 0xff, duration >>> 8 & 0xff, duration & 0xff,
  15257. // sample_duration
  15258. size >>> 24 & 0xff, size >>> 16 & 0xff, size >>> 8 & 0xff, size & 0xff,
  15259. // sample_size
  15260. flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xf0 << 8, flags.degradPrio & 0x0f,
  15261. // sample_flags
  15262. cts >>> 24 & 0xff, cts >>> 16 & 0xff, cts >>> 8 & 0xff, cts & 0xff // sample_composition_time_offset
  15263. ], 12 + 16 * i);
  15264. }
  15265. return MP4.box(MP4.types.trun, array);
  15266. }
  15267. static initSegment(tracks) {
  15268. if (!MP4.types) {
  15269. MP4.init();
  15270. }
  15271. const movie = MP4.moov(tracks);
  15272. const result = appendUint8Array(MP4.FTYP, movie);
  15273. return result;
  15274. }
  15275. static hvc1(track) {
  15276. {
  15277. return new Uint8Array();
  15278. }
  15279. }
  15280. }
  15281. MP4.types = void 0;
  15282. MP4.HDLR_TYPES = void 0;
  15283. MP4.STTS = void 0;
  15284. MP4.STSC = void 0;
  15285. MP4.STCO = void 0;
  15286. MP4.STSZ = void 0;
  15287. MP4.VMHD = void 0;
  15288. MP4.SMHD = void 0;
  15289. MP4.STSD = void 0;
  15290. MP4.FTYP = void 0;
  15291. MP4.DINF = void 0;
  15292. const MPEG_TS_CLOCK_FREQ_HZ = 90000;
  15293. function toTimescaleFromBase(baseTime, destScale, srcBase = 1, round = false) {
  15294. const result = baseTime * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
  15295. return round ? Math.round(result) : result;
  15296. }
  15297. function toMsFromMpegTsClock(baseTime, round = false) {
  15298. return toTimescaleFromBase(baseTime, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
  15299. }
  15300. const MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds
  15301. const AAC_SAMPLES_PER_FRAME = 1024;
  15302. const MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
  15303. const AC3_SAMPLES_PER_FRAME = 1536;
  15304. let chromeVersion = null;
  15305. let safariWebkitVersion = null;
  15306. function createMp4Sample(isKeyframe, duration, size, cts) {
  15307. return {
  15308. duration,
  15309. size,
  15310. cts,
  15311. flags: {
  15312. isLeading: 0,
  15313. isDependedOn: 0,
  15314. hasRedundancy: 0,
  15315. degradPrio: 0,
  15316. dependsOn: isKeyframe ? 2 : 1,
  15317. isNonSync: isKeyframe ? 0 : 1
  15318. }
  15319. };
  15320. }
  15321. class MP4Remuxer extends Logger {
  15322. constructor(observer, config, typeSupported, logger) {
  15323. super('mp4-remuxer', logger);
  15324. this.observer = void 0;
  15325. this.config = void 0;
  15326. this.typeSupported = void 0;
  15327. this.ISGenerated = false;
  15328. this._initPTS = null;
  15329. this._initDTS = null;
  15330. this.nextVideoTs = null;
  15331. this.nextAudioTs = null;
  15332. this.videoSampleDuration = null;
  15333. this.isAudioContiguous = false;
  15334. this.isVideoContiguous = false;
  15335. this.videoTrackConfig = void 0;
  15336. this.observer = observer;
  15337. this.config = config;
  15338. this.typeSupported = typeSupported;
  15339. this.ISGenerated = false;
  15340. if (chromeVersion === null) {
  15341. const userAgent = navigator.userAgent || '';
  15342. const result = userAgent.match(/Chrome\/(\d+)/i);
  15343. chromeVersion = result ? parseInt(result[1]) : 0;
  15344. }
  15345. if (safariWebkitVersion === null) {
  15346. const result = navigator.userAgent.match(/Safari\/(\d+)/i);
  15347. safariWebkitVersion = result ? parseInt(result[1]) : 0;
  15348. }
  15349. }
  15350. destroy() {
  15351. // @ts-ignore
  15352. this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;
  15353. }
  15354. resetTimeStamp(defaultTimeStamp) {
  15355. this.log('initPTS & initDTS reset');
  15356. this._initPTS = this._initDTS = defaultTimeStamp;
  15357. }
  15358. resetNextTimestamp() {
  15359. this.log('reset next timestamp');
  15360. this.isVideoContiguous = false;
  15361. this.isAudioContiguous = false;
  15362. }
  15363. resetInitSegment() {
  15364. this.log('ISGenerated flag reset');
  15365. this.ISGenerated = false;
  15366. this.videoTrackConfig = undefined;
  15367. }
  15368. getVideoStartPts(videoSamples) {
  15369. // Get the minimum PTS value relative to the first sample's PTS, normalized for 33-bit wrapping
  15370. let rolloverDetected = false;
  15371. const firstPts = videoSamples[0].pts;
  15372. const startPTS = videoSamples.reduce((minPTS, sample) => {
  15373. let pts = sample.pts;
  15374. let delta = pts - minPTS;
  15375. if (delta < -4294967296) {
  15376. // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
  15377. rolloverDetected = true;
  15378. pts = normalizePts(pts, firstPts);
  15379. delta = pts - minPTS;
  15380. }
  15381. if (delta > 0) {
  15382. return minPTS;
  15383. }
  15384. return pts;
  15385. }, firstPts);
  15386. if (rolloverDetected) {
  15387. this.debug('PTS rollover detected');
  15388. }
  15389. return startPTS;
  15390. }
  15391. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
  15392. let video;
  15393. let audio;
  15394. let initSegment;
  15395. let text;
  15396. let id3;
  15397. let independent;
  15398. let audioTimeOffset = timeOffset;
  15399. let videoTimeOffset = timeOffset;
  15400. // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.
  15401. // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid"
  15402. // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.
  15403. // However, if the initSegment has already been generated, or we've reached the end of a segment (flush),
  15404. // then we can remux one track without waiting for the other.
  15405. const hasAudio = audioTrack.pid > -1;
  15406. const hasVideo = videoTrack.pid > -1;
  15407. const length = videoTrack.samples.length;
  15408. const enoughAudioSamples = audioTrack.samples.length > 0;
  15409. const enoughVideoSamples = flush && length > 0 || length > 1;
  15410. const canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
  15411. if (canRemuxAvc) {
  15412. if (this.ISGenerated) {
  15413. var _videoTrack$pixelRati, _config$pixelRatio, _videoTrack$pixelRati2, _config$pixelRatio2;
  15414. const config = this.videoTrackConfig;
  15415. 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) {
  15416. this.resetInitSegment();
  15417. }
  15418. }
  15419. if (!this.ISGenerated) {
  15420. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  15421. }
  15422. const isVideoContiguous = this.isVideoContiguous;
  15423. let firstKeyFrameIndex = -1;
  15424. let firstKeyFramePTS;
  15425. if (enoughVideoSamples) {
  15426. firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
  15427. if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
  15428. independent = true;
  15429. if (firstKeyFrameIndex > 0) {
  15430. this.warn(`Dropped ${firstKeyFrameIndex} out of ${length} video samples due to a missing keyframe`);
  15431. const startPTS = this.getVideoStartPts(videoTrack.samples);
  15432. videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
  15433. videoTrack.dropped += firstKeyFrameIndex;
  15434. videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale;
  15435. firstKeyFramePTS = videoTimeOffset;
  15436. } else if (firstKeyFrameIndex === -1) {
  15437. this.warn(`No keyframe found out of ${length} video samples`);
  15438. independent = false;
  15439. }
  15440. }
  15441. }
  15442. if (this.ISGenerated) {
  15443. if (enoughAudioSamples && enoughVideoSamples) {
  15444. // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
  15445. // if first audio DTS is not aligned with first video DTS then we need to take that into account
  15446. // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
  15447. // drift between audio and video streams
  15448. const startPTS = this.getVideoStartPts(videoTrack.samples);
  15449. const tsDelta = normalizePts(audioTrack.samples[0].pts, startPTS) - startPTS;
  15450. const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
  15451. audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
  15452. videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
  15453. }
  15454. // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.
  15455. if (enoughAudioSamples) {
  15456. // if initSegment was generated without audio samples, regenerate it again
  15457. if (!audioTrack.samplerate) {
  15458. this.warn('regenerate InitSegment as audio detected');
  15459. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  15460. }
  15461. audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : undefined);
  15462. if (enoughVideoSamples) {
  15463. const audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;
  15464. // if initSegment was generated without video samples, regenerate it again
  15465. if (!videoTrack.inputTimeScale) {
  15466. this.warn('regenerate InitSegment as video detected');
  15467. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  15468. }
  15469. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
  15470. }
  15471. } else if (enoughVideoSamples) {
  15472. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
  15473. }
  15474. if (video) {
  15475. video.firstKeyFrame = firstKeyFrameIndex;
  15476. video.independent = firstKeyFrameIndex !== -1;
  15477. video.firstKeyFramePTS = firstKeyFramePTS;
  15478. }
  15479. }
  15480. }
  15481. // Allow ID3 and text to remux, even if more audio/video samples are required
  15482. if (this.ISGenerated && this._initPTS && this._initDTS) {
  15483. if (id3Track.samples.length) {
  15484. id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS);
  15485. }
  15486. if (textTrack.samples.length) {
  15487. text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS);
  15488. }
  15489. }
  15490. return {
  15491. audio,
  15492. video,
  15493. initSegment,
  15494. independent,
  15495. text,
  15496. id3
  15497. };
  15498. }
  15499. generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset) {
  15500. const audioSamples = audioTrack.samples;
  15501. const videoSamples = videoTrack.samples;
  15502. const typeSupported = this.typeSupported;
  15503. const tracks = {};
  15504. const _initPTS = this._initPTS;
  15505. let computePTSDTS = !_initPTS || accurateTimeOffset;
  15506. let container = 'audio/mp4';
  15507. let initPTS;
  15508. let initDTS;
  15509. let timescale;
  15510. let trackId;
  15511. if (computePTSDTS) {
  15512. initPTS = initDTS = Infinity;
  15513. }
  15514. if (audioTrack.config && audioSamples.length) {
  15515. // let's use audio sampling rate as MP4 time scale.
  15516. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
  15517. // using audio sampling rate here helps having an integer MP4 frame duration
  15518. // this avoids potential rounding issue and AV sync issue
  15519. audioTrack.timescale = audioTrack.samplerate;
  15520. switch (audioTrack.segmentCodec) {
  15521. case 'mp3':
  15522. if (typeSupported.mpeg) {
  15523. // Chrome and Safari
  15524. container = 'audio/mpeg';
  15525. audioTrack.codec = '';
  15526. } else if (typeSupported.mp3) {
  15527. // Firefox
  15528. audioTrack.codec = 'mp3';
  15529. }
  15530. break;
  15531. case 'ac3':
  15532. audioTrack.codec = 'ac-3';
  15533. break;
  15534. }
  15535. tracks.audio = {
  15536. id: 'audio',
  15537. container: container,
  15538. codec: audioTrack.codec,
  15539. initSegment: audioTrack.segmentCodec === 'mp3' && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]),
  15540. metadata: {
  15541. channelCount: audioTrack.channelCount
  15542. }
  15543. };
  15544. if (computePTSDTS) {
  15545. trackId = audioTrack.id;
  15546. timescale = audioTrack.inputTimeScale;
  15547. if (!_initPTS || timescale !== _initPTS.timescale) {
  15548. // remember first PTS of this demuxing context. for audio, PTS = DTS
  15549. initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
  15550. } else {
  15551. computePTSDTS = false;
  15552. }
  15553. }
  15554. }
  15555. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  15556. // let's use input time scale as MP4 video timescale
  15557. // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
  15558. videoTrack.timescale = videoTrack.inputTimeScale;
  15559. tracks.video = {
  15560. id: 'main',
  15561. container: 'video/mp4',
  15562. codec: videoTrack.codec,
  15563. initSegment: MP4.initSegment([videoTrack]),
  15564. metadata: {
  15565. width: videoTrack.width,
  15566. height: videoTrack.height
  15567. }
  15568. };
  15569. if (computePTSDTS) {
  15570. trackId = videoTrack.id;
  15571. timescale = videoTrack.inputTimeScale;
  15572. if (!_initPTS || timescale !== _initPTS.timescale) {
  15573. const startPTS = this.getVideoStartPts(videoSamples);
  15574. const startOffset = Math.round(timescale * timeOffset);
  15575. initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
  15576. initPTS = Math.min(initPTS, startPTS - startOffset);
  15577. } else {
  15578. computePTSDTS = false;
  15579. }
  15580. }
  15581. this.videoTrackConfig = {
  15582. width: videoTrack.width,
  15583. height: videoTrack.height,
  15584. pixelRatio: videoTrack.pixelRatio
  15585. };
  15586. }
  15587. if (Object.keys(tracks).length) {
  15588. this.ISGenerated = true;
  15589. if (computePTSDTS) {
  15590. this._initPTS = {
  15591. baseTime: initPTS,
  15592. timescale: timescale
  15593. };
  15594. this._initDTS = {
  15595. baseTime: initDTS,
  15596. timescale: timescale
  15597. };
  15598. } else {
  15599. initPTS = timescale = undefined;
  15600. }
  15601. return {
  15602. tracks,
  15603. initPTS,
  15604. timescale,
  15605. trackId
  15606. };
  15607. }
  15608. }
  15609. remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
  15610. const timeScale = track.inputTimeScale;
  15611. const inputSamples = track.samples;
  15612. const outputSamples = [];
  15613. const nbSamples = inputSamples.length;
  15614. const initPTS = this._initPTS;
  15615. const initTime = initPTS.baseTime * timeScale / initPTS.timescale;
  15616. let nextVideoTs = this.nextVideoTs;
  15617. let offset = 8;
  15618. let mp4SampleDuration = this.videoSampleDuration;
  15619. let firstDTS;
  15620. let lastDTS;
  15621. let minPTS = Number.POSITIVE_INFINITY;
  15622. let maxPTS = Number.NEGATIVE_INFINITY;
  15623. let sortSamples = false;
  15624. // if parsed fragment is contiguous with last one, let's use last DTS value as reference
  15625. if (!contiguous || nextVideoTs === null) {
  15626. const pts = initTime + timeOffset * timeScale;
  15627. const cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts);
  15628. if (chromeVersion && nextVideoTs !== null && Math.abs(pts - cts - (nextVideoTs + initTime)) < 15000) {
  15629. // treat as contigous to adjust samples that would otherwise produce video buffer gaps in Chrome
  15630. contiguous = true;
  15631. } else {
  15632. // if not contiguous, let's use target timeOffset
  15633. nextVideoTs = pts - cts - initTime;
  15634. }
  15635. }
  15636. // PTS is coded on 33bits, and can loop from -2^32 to 2^32
  15637. // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
  15638. const nextVideoPts = nextVideoTs + initTime;
  15639. for (let i = 0; i < nbSamples; i++) {
  15640. const sample = inputSamples[i];
  15641. sample.pts = normalizePts(sample.pts, nextVideoPts);
  15642. sample.dts = normalizePts(sample.dts, nextVideoPts);
  15643. if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
  15644. sortSamples = true;
  15645. }
  15646. }
  15647. // sort video samples by DTS then PTS then demux id order
  15648. if (sortSamples) {
  15649. inputSamples.sort(function (a, b) {
  15650. const deltadts = a.dts - b.dts;
  15651. const deltapts = a.pts - b.pts;
  15652. return deltadts || deltapts;
  15653. });
  15654. }
  15655. // Get first/last DTS
  15656. firstDTS = inputSamples[0].dts;
  15657. lastDTS = inputSamples[inputSamples.length - 1].dts;
  15658. // Sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
  15659. // set this constant duration as being the avg delta between consecutive DTS.
  15660. const inputDuration = lastDTS - firstDTS;
  15661. const averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track.inputTimeScale / 30;
  15662. // if fragment are contiguous, detect hole/overlapping between fragments
  15663. if (contiguous) {
  15664. // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
  15665. const delta = firstDTS - nextVideoPts;
  15666. const foundHole = delta > averageSampleDuration;
  15667. const foundOverlap = delta < -1;
  15668. if (foundHole || foundOverlap) {
  15669. if (foundHole) {
  15670. this.warn(`${(track.segmentCodec || '').toUpperCase()}: ${toMsFromMpegTsClock(delta, true)} ms (${delta}dts) hole between fragments detected at ${timeOffset.toFixed(3)}`);
  15671. } else {
  15672. this.warn(`${(track.segmentCodec || '').toUpperCase()}: ${toMsFromMpegTsClock(-delta, true)} ms (${delta}dts) overlapping between fragments detected at ${timeOffset.toFixed(3)}`);
  15673. }
  15674. if (!foundOverlap || nextVideoPts >= inputSamples[0].pts || chromeVersion) {
  15675. firstDTS = nextVideoPts;
  15676. const firstPTS = inputSamples[0].pts - delta;
  15677. if (foundHole) {
  15678. inputSamples[0].dts = firstDTS;
  15679. inputSamples[0].pts = firstPTS;
  15680. } else {
  15681. let isPTSOrderRetained = true;
  15682. for (let i = 0; i < inputSamples.length; i++) {
  15683. if (inputSamples[i].dts > firstPTS && isPTSOrderRetained) {
  15684. break;
  15685. }
  15686. const prevPTS = inputSamples[i].pts;
  15687. inputSamples[i].dts -= delta;
  15688. inputSamples[i].pts -= delta;
  15689. // check to see if this sample's PTS order has changed
  15690. // relative to the next one
  15691. if (i < inputSamples.length - 1) {
  15692. const nextSamplePTS = inputSamples[i + 1].pts;
  15693. const currentSamplePTS = inputSamples[i].pts;
  15694. const currentOrder = nextSamplePTS <= currentSamplePTS;
  15695. const prevOrder = nextSamplePTS <= prevPTS;
  15696. isPTSOrderRetained = currentOrder == prevOrder;
  15697. }
  15698. }
  15699. }
  15700. this.log(`Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(firstPTS, true)}/${toMsFromMpegTsClock(firstDTS, true)}, delta: ${toMsFromMpegTsClock(delta, true)} ms`);
  15701. }
  15702. }
  15703. }
  15704. firstDTS = Math.max(0, firstDTS);
  15705. let nbNalu = 0;
  15706. let naluLen = 0;
  15707. let dtsStep = firstDTS;
  15708. for (let i = 0; i < nbSamples; i++) {
  15709. // compute total/avc sample length and nb of NAL units
  15710. const sample = inputSamples[i];
  15711. const units = sample.units;
  15712. const nbUnits = units.length;
  15713. let sampleLen = 0;
  15714. for (let j = 0; j < nbUnits; j++) {
  15715. sampleLen += units[j].data.length;
  15716. }
  15717. naluLen += sampleLen;
  15718. nbNalu += nbUnits;
  15719. sample.length = sampleLen;
  15720. // ensure sample monotonic DTS
  15721. if (sample.dts < dtsStep) {
  15722. sample.dts = dtsStep;
  15723. dtsStep += averageSampleDuration / 4 | 0 || 1;
  15724. } else {
  15725. dtsStep = sample.dts;
  15726. }
  15727. minPTS = Math.min(sample.pts, minPTS);
  15728. maxPTS = Math.max(sample.pts, maxPTS);
  15729. }
  15730. lastDTS = inputSamples[nbSamples - 1].dts;
  15731. /* concatenate the video data and construct the mdat in place
  15732. (need 8 more bytes to fill length and mpdat type) */
  15733. const mdatSize = naluLen + 4 * nbNalu + 8;
  15734. let mdat;
  15735. try {
  15736. mdat = new Uint8Array(mdatSize);
  15737. } catch (err) {
  15738. this.observer.emit(Events.ERROR, Events.ERROR, {
  15739. type: ErrorTypes.MUX_ERROR,
  15740. details: ErrorDetails.REMUX_ALLOC_ERROR,
  15741. fatal: false,
  15742. error: err,
  15743. bytes: mdatSize,
  15744. reason: `fail allocating video mdat ${mdatSize}`
  15745. });
  15746. return;
  15747. }
  15748. const view = new DataView(mdat.buffer);
  15749. view.setUint32(0, mdatSize);
  15750. mdat.set(MP4.types.mdat, 4);
  15751. let stretchedLastFrame = false;
  15752. let minDtsDelta = Number.POSITIVE_INFINITY;
  15753. let minPtsDelta = Number.POSITIVE_INFINITY;
  15754. let maxDtsDelta = Number.NEGATIVE_INFINITY;
  15755. let maxPtsDelta = Number.NEGATIVE_INFINITY;
  15756. for (let i = 0; i < nbSamples; i++) {
  15757. const VideoSample = inputSamples[i];
  15758. const VideoSampleUnits = VideoSample.units;
  15759. let mp4SampleLength = 0;
  15760. // convert NALU bitstream to MP4 format (prepend NALU with size field)
  15761. for (let j = 0, nbUnits = VideoSampleUnits.length; j < nbUnits; j++) {
  15762. const unit = VideoSampleUnits[j];
  15763. const unitData = unit.data;
  15764. const unitDataLen = unit.data.byteLength;
  15765. view.setUint32(offset, unitDataLen);
  15766. offset += 4;
  15767. mdat.set(unitData, offset);
  15768. offset += unitDataLen;
  15769. mp4SampleLength += 4 + unitDataLen;
  15770. }
  15771. // expected sample duration is the Decoding Timestamp diff of consecutive samples
  15772. let ptsDelta;
  15773. if (i < nbSamples - 1) {
  15774. mp4SampleDuration = inputSamples[i + 1].dts - VideoSample.dts;
  15775. ptsDelta = inputSamples[i + 1].pts - VideoSample.pts;
  15776. } else {
  15777. const config = this.config;
  15778. const lastFrameDuration = i > 0 ? VideoSample.dts - inputSamples[i - 1].dts : averageSampleDuration;
  15779. ptsDelta = i > 0 ? VideoSample.pts - inputSamples[i - 1].pts : averageSampleDuration;
  15780. if (config.stretchShortVideoTrack && this.nextAudioTs !== null) {
  15781. // In some cases, a segment's audio track duration may exceed the video track duration.
  15782. // Since we've already remuxed audio, and we know how long the audio track is, we look to
  15783. // see if the delta to the next segment is longer than maxBufferHole.
  15784. // If so, playback would potentially get stuck, so we artificially inflate
  15785. // the duration of the last frame to minimize any potential gap between segments.
  15786. const gapTolerance = Math.floor(config.maxBufferHole * timeScale);
  15787. const deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioTs + initTime) - VideoSample.pts;
  15788. if (deltaToFrameEnd > gapTolerance) {
  15789. // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
  15790. // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
  15791. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  15792. if (mp4SampleDuration < 0) {
  15793. mp4SampleDuration = lastFrameDuration;
  15794. } else {
  15795. stretchedLastFrame = true;
  15796. }
  15797. this.log(`It is approximately ${deltaToFrameEnd / 90} ms to the next segment; using duration ${mp4SampleDuration / 90} ms for the last video frame.`);
  15798. } else {
  15799. mp4SampleDuration = lastFrameDuration;
  15800. }
  15801. } else {
  15802. mp4SampleDuration = lastFrameDuration;
  15803. }
  15804. }
  15805. const compositionTimeOffset = Math.round(VideoSample.pts - VideoSample.dts);
  15806. minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);
  15807. maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);
  15808. minPtsDelta = Math.min(minPtsDelta, ptsDelta);
  15809. maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);
  15810. outputSamples.push(createMp4Sample(VideoSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
  15811. }
  15812. if (outputSamples.length) {
  15813. if (chromeVersion) {
  15814. if (chromeVersion < 70) {
  15815. // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue
  15816. // https://code.google.com/p/chromium/issues/detail?id=229412
  15817. const flags = outputSamples[0].flags;
  15818. flags.dependsOn = 2;
  15819. flags.isNonSync = 0;
  15820. }
  15821. } else if (safariWebkitVersion) {
  15822. // Fix for "CNN special report, with CC" in test-streams (Safari browser only)
  15823. // Ignore DTS when frame durations are irregular. Safari MSE does not handle this leading to gaps.
  15824. if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) {
  15825. this.warn('Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.');
  15826. let dts = firstDTS;
  15827. for (let i = 0, len = outputSamples.length; i < len; i++) {
  15828. const nextDts = dts + outputSamples[i].duration;
  15829. const pts = dts + outputSamples[i].cts;
  15830. if (i < len - 1) {
  15831. const nextPts = nextDts + outputSamples[i + 1].cts;
  15832. outputSamples[i].duration = nextPts - pts;
  15833. } else {
  15834. outputSamples[i].duration = i ? outputSamples[i - 1].duration : averageSampleDuration;
  15835. }
  15836. outputSamples[i].cts = 0;
  15837. dts = nextDts;
  15838. }
  15839. }
  15840. }
  15841. }
  15842. // next AVC/HEVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
  15843. mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration;
  15844. const endDTS = lastDTS + mp4SampleDuration;
  15845. this.nextVideoTs = nextVideoTs = endDTS - initTime;
  15846. this.videoSampleDuration = mp4SampleDuration;
  15847. this.isVideoContiguous = true;
  15848. const moof = MP4.moof(track.sequenceNumber++, firstDTS, _extends(track, {
  15849. samples: outputSamples
  15850. }));
  15851. const type = 'video';
  15852. const data = {
  15853. data1: moof,
  15854. data2: mdat,
  15855. startPTS: (minPTS - initTime) / timeScale,
  15856. endPTS: (maxPTS + mp4SampleDuration - initTime) / timeScale,
  15857. startDTS: (firstDTS - initTime) / timeScale,
  15858. endDTS: nextVideoTs / timeScale,
  15859. type,
  15860. hasAudio: false,
  15861. hasVideo: true,
  15862. nb: outputSamples.length,
  15863. dropped: track.dropped
  15864. };
  15865. track.samples = [];
  15866. track.dropped = 0;
  15867. return data;
  15868. }
  15869. getSamplesPerFrame(track) {
  15870. switch (track.segmentCodec) {
  15871. case 'mp3':
  15872. return MPEG_AUDIO_SAMPLE_PER_FRAME;
  15873. case 'ac3':
  15874. return AC3_SAMPLES_PER_FRAME;
  15875. default:
  15876. return AAC_SAMPLES_PER_FRAME;
  15877. }
  15878. }
  15879. remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
  15880. const inputTimeScale = track.inputTimeScale;
  15881. const mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  15882. const scaleFactor = inputTimeScale / mp4timeScale;
  15883. const mp4SampleDuration = this.getSamplesPerFrame(track);
  15884. const inputSampleDuration = mp4SampleDuration * scaleFactor;
  15885. const initPTS = this._initPTS;
  15886. const rawMPEG = track.segmentCodec === 'mp3' && this.typeSupported.mpeg;
  15887. const outputSamples = [];
  15888. const alignedWithVideo = videoTimeOffset !== undefined;
  15889. let inputSamples = track.samples;
  15890. let offset = rawMPEG ? 0 : 8;
  15891. let nextAudioTs = this.nextAudioTs || -1;
  15892. // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);
  15893. // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
  15894. // for sake of clarity:
  15895. // consecutive fragments are frags with
  15896. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  15897. // - less than 20 audio frames distance
  15898. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  15899. // this helps ensuring audio continuity
  15900. // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
  15901. const initTime = initPTS.baseTime * inputTimeScale / initPTS.timescale;
  15902. const timeOffsetMpegTS = initTime + timeOffset * inputTimeScale;
  15903. this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioTs > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - (nextAudioTs + initTime)) < 9000 || Math.abs(normalizePts(inputSamples[0].pts, timeOffsetMpegTS) - (nextAudioTs + initTime)) < 20 * inputSampleDuration);
  15904. // compute normalized PTS
  15905. inputSamples.forEach(function (sample) {
  15906. sample.pts = normalizePts(sample.pts, timeOffsetMpegTS);
  15907. });
  15908. if (!contiguous || nextAudioTs < 0) {
  15909. // filter out sample with negative PTS that are not playable anyway
  15910. // if we don't remove these negative samples, they will shift all audio samples forward.
  15911. // leading to audio overlap between current / next fragment
  15912. inputSamples = inputSamples.filter(sample => sample.pts >= 0);
  15913. // in case all samples have negative PTS, and have been filtered out, return now
  15914. if (!inputSamples.length) {
  15915. return;
  15916. }
  15917. if (videoTimeOffset === 0) {
  15918. // Set the start to match video so that start gaps larger than inputSampleDuration are filled with silence
  15919. nextAudioTs = 0;
  15920. } else if (accurateTimeOffset && !alignedWithVideo) {
  15921. // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS
  15922. nextAudioTs = Math.max(0, timeOffsetMpegTS - initTime);
  15923. } else {
  15924. // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
  15925. nextAudioTs = inputSamples[0].pts - initTime;
  15926. }
  15927. }
  15928. // If the audio track is missing samples, the frames seem to get "left-shifted" within the
  15929. // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
  15930. // In an effort to prevent this from happening, we inject frames here where there are gaps.
  15931. // When possible, we inject a silent frame; when that's not possible, we duplicate the last
  15932. // frame.
  15933. if (track.segmentCodec === 'aac') {
  15934. const maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  15935. for (let i = 0, nextPts = nextAudioTs + initTime; i < inputSamples.length; i++) {
  15936. // First, let's see how far off this frame is from where we expect it to be
  15937. const sample = inputSamples[i];
  15938. const pts = sample.pts;
  15939. const delta = pts - nextPts;
  15940. const duration = Math.abs(1000 * delta / inputTimeScale);
  15941. // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync
  15942. if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
  15943. if (i === 0) {
  15944. this.warn(`Audio frame @ ${(pts / inputTimeScale).toFixed(3)}s overlaps marker by ${Math.round(1000 * delta / inputTimeScale)} ms.`);
  15945. this.nextAudioTs = nextAudioTs = pts - initTime;
  15946. nextPts = pts;
  15947. }
  15948. } // eslint-disable-line brace-style
  15949. // Insert missing frames if:
  15950. // 1: We're more than maxAudioFramesDrift frame away
  15951. // 2: Not more than MAX_SILENT_FRAME_DURATION away
  15952. // 3: currentTime (aka nextPtsNorm) is not 0
  15953. // 4: remuxing with video (videoTimeOffset !== undefined)
  15954. else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
  15955. let missing = Math.round(delta / inputSampleDuration);
  15956. // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from
  15957. // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.
  15958. nextPts = pts - missing * inputSampleDuration;
  15959. while (nextPts < 0 && missing && inputSampleDuration) {
  15960. missing--;
  15961. nextPts += inputSampleDuration;
  15962. }
  15963. if (i === 0) {
  15964. this.nextAudioTs = nextAudioTs = nextPts - initTime;
  15965. }
  15966. this.warn(`Injecting ${missing} audio frames @ ${((nextPts - initTime) / inputTimeScale).toFixed(3)}s due to ${Math.round(1000 * delta / inputTimeScale)} ms gap.`);
  15967. for (let j = 0; j < missing; j++) {
  15968. let fillFrame = AAC.getSilentFrame(track.parsedCodec || track.manifestCodec || track.codec, track.channelCount);
  15969. if (!fillFrame) {
  15970. this.log('Unable to get silent frame for given audio codec; duplicating last frame instead.');
  15971. fillFrame = sample.unit.subarray();
  15972. }
  15973. inputSamples.splice(i, 0, {
  15974. unit: fillFrame,
  15975. pts: nextPts
  15976. });
  15977. nextPts += inputSampleDuration;
  15978. i++;
  15979. }
  15980. }
  15981. sample.pts = nextPts;
  15982. nextPts += inputSampleDuration;
  15983. }
  15984. }
  15985. let firstPTS = null;
  15986. let lastPTS = null;
  15987. let mdat;
  15988. let mdatSize = 0;
  15989. let sampleLength = inputSamples.length;
  15990. while (sampleLength--) {
  15991. mdatSize += inputSamples[sampleLength].unit.byteLength;
  15992. }
  15993. for (let j = 0, _nbSamples = inputSamples.length; j < _nbSamples; j++) {
  15994. const audioSample = inputSamples[j];
  15995. const unit = audioSample.unit;
  15996. let pts = audioSample.pts;
  15997. if (lastPTS !== null) {
  15998. // If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with
  15999. // the previous sample
  16000. const prevSample = outputSamples[j - 1];
  16001. prevSample.duration = Math.round((pts - lastPTS) / scaleFactor);
  16002. } else {
  16003. if (contiguous && track.segmentCodec === 'aac') {
  16004. // set PTS/DTS to expected PTS/DTS
  16005. pts = nextAudioTs + initTime;
  16006. }
  16007. // remember first PTS of our audioSamples
  16008. firstPTS = pts;
  16009. if (mdatSize > 0) {
  16010. /* concatenate the audio data and construct the mdat in place
  16011. (need 8 more bytes to fill length and mdat type) */
  16012. mdatSize += offset;
  16013. try {
  16014. mdat = new Uint8Array(mdatSize);
  16015. } catch (err) {
  16016. this.observer.emit(Events.ERROR, Events.ERROR, {
  16017. type: ErrorTypes.MUX_ERROR,
  16018. details: ErrorDetails.REMUX_ALLOC_ERROR,
  16019. fatal: false,
  16020. error: err,
  16021. bytes: mdatSize,
  16022. reason: `fail allocating audio mdat ${mdatSize}`
  16023. });
  16024. return;
  16025. }
  16026. if (!rawMPEG) {
  16027. const view = new DataView(mdat.buffer);
  16028. view.setUint32(0, mdatSize);
  16029. mdat.set(MP4.types.mdat, 4);
  16030. }
  16031. } else {
  16032. // no audio samples
  16033. return;
  16034. }
  16035. }
  16036. mdat.set(unit, offset);
  16037. const unitLen = unit.byteLength;
  16038. offset += unitLen;
  16039. // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG
  16040. // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration
  16041. // becomes the PTS diff with the previous sample
  16042. outputSamples.push(createMp4Sample(true, mp4SampleDuration, unitLen, 0));
  16043. lastPTS = pts;
  16044. }
  16045. // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones
  16046. const nbSamples = outputSamples.length;
  16047. if (!nbSamples) {
  16048. return;
  16049. }
  16050. // The next audio sample PTS should be equal to last sample PTS + duration
  16051. const lastSample = outputSamples[outputSamples.length - 1];
  16052. nextAudioTs = lastPTS - initTime;
  16053. this.nextAudioTs = nextAudioTs + scaleFactor * lastSample.duration;
  16054. // Set the track samples from inputSamples to outputSamples before remuxing
  16055. const moof = rawMPEG ? new Uint8Array(0) : MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
  16056. samples: outputSamples
  16057. }));
  16058. // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared
  16059. track.samples = [];
  16060. const start = (firstPTS - initTime) / inputTimeScale;
  16061. const end = nextAudioTs / inputTimeScale;
  16062. const type = 'audio';
  16063. const audioData = {
  16064. data1: moof,
  16065. data2: mdat,
  16066. startPTS: start,
  16067. endPTS: end,
  16068. startDTS: start,
  16069. endDTS: end,
  16070. type,
  16071. hasAudio: true,
  16072. hasVideo: false,
  16073. nb: nbSamples
  16074. };
  16075. this.isAudioContiguous = true;
  16076. return audioData;
  16077. }
  16078. }
  16079. function normalizePts(value, reference) {
  16080. let offset;
  16081. if (reference === null) {
  16082. return value;
  16083. }
  16084. if (reference < value) {
  16085. // - 2^33
  16086. offset = -8589934592;
  16087. } else {
  16088. // + 2^33
  16089. offset = 8589934592;
  16090. }
  16091. /* PTS is 33bit (from 0 to 2^33 -1)
  16092. if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
  16093. PTS looping occured. fill the gap */
  16094. while (Math.abs(value - reference) > 4294967296) {
  16095. value += offset;
  16096. }
  16097. return value;
  16098. }
  16099. function findKeyframeIndex(samples) {
  16100. for (let i = 0; i < samples.length; i++) {
  16101. if (samples[i].key) {
  16102. return i;
  16103. }
  16104. }
  16105. return -1;
  16106. }
  16107. function flushTextTrackMetadataCueSamples(track, timeOffset, initPTS, initDTS) {
  16108. const length = track.samples.length;
  16109. if (!length) {
  16110. return;
  16111. }
  16112. const inputTimeScale = track.inputTimeScale;
  16113. for (let index = 0; index < length; index++) {
  16114. const sample = track.samples[index];
  16115. // setting id3 pts, dts to relative time
  16116. // using this._initPTS and this._initDTS to calculate relative time
  16117. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  16118. sample.dts = normalizePts(sample.dts - initDTS.baseTime * inputTimeScale / initDTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  16119. }
  16120. const samples = track.samples;
  16121. track.samples = [];
  16122. return {
  16123. samples
  16124. };
  16125. }
  16126. function flushTextTrackUserdataCueSamples(track, timeOffset, initPTS) {
  16127. const length = track.samples.length;
  16128. if (!length) {
  16129. return;
  16130. }
  16131. const inputTimeScale = track.inputTimeScale;
  16132. for (let index = 0; index < length; index++) {
  16133. const sample = track.samples[index];
  16134. // setting text pts, dts to relative time
  16135. // using this._initPTS and this._initDTS to calculate relative time
  16136. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  16137. }
  16138. track.samples.sort((a, b) => a.pts - b.pts);
  16139. const samples = track.samples;
  16140. track.samples = [];
  16141. return {
  16142. samples
  16143. };
  16144. }
  16145. class PassThroughRemuxer extends Logger {
  16146. constructor(observer, config, typeSupported, logger) {
  16147. super('passthrough-remuxer', logger);
  16148. this.emitInitSegment = false;
  16149. this.audioCodec = void 0;
  16150. this.videoCodec = void 0;
  16151. this.initData = void 0;
  16152. this.initPTS = null;
  16153. this.initTracks = void 0;
  16154. this.lastEndTime = null;
  16155. this.isVideoContiguous = false;
  16156. }
  16157. destroy() {}
  16158. resetTimeStamp(defaultInitPTS) {
  16159. this.lastEndTime = null;
  16160. const initPTS = this.initPTS;
  16161. if (initPTS && defaultInitPTS) {
  16162. if (initPTS.baseTime === defaultInitPTS.baseTime && initPTS.timescale === defaultInitPTS.timescale) {
  16163. return;
  16164. }
  16165. }
  16166. this.initPTS = defaultInitPTS;
  16167. }
  16168. resetNextTimestamp() {
  16169. this.isVideoContiguous = false;
  16170. this.lastEndTime = null;
  16171. }
  16172. resetInitSegment(initSegment, audioCodec, videoCodec, decryptdata) {
  16173. this.audioCodec = audioCodec;
  16174. this.videoCodec = videoCodec;
  16175. this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));
  16176. this.emitInitSegment = true;
  16177. }
  16178. generateInitSegment(initSegment) {
  16179. let {
  16180. audioCodec,
  16181. videoCodec
  16182. } = this;
  16183. if (!(initSegment != null && initSegment.byteLength)) {
  16184. this.initTracks = undefined;
  16185. this.initData = undefined;
  16186. return;
  16187. }
  16188. const initData = this.initData = parseInitSegment(initSegment);
  16189. // Get codec from initSegment
  16190. if (initData.audio) {
  16191. audioCodec = getParsedTrackCodec(initData.audio, ElementaryStreamTypes.AUDIO, this);
  16192. }
  16193. if (initData.video) {
  16194. videoCodec = getParsedTrackCodec(initData.video, ElementaryStreamTypes.VIDEO, this);
  16195. }
  16196. const tracks = {};
  16197. if (initData.audio && initData.video) {
  16198. tracks.audiovideo = {
  16199. container: 'video/mp4',
  16200. codec: audioCodec + ',' + videoCodec,
  16201. supplemental: initData.video.supplemental,
  16202. initSegment,
  16203. id: 'main'
  16204. };
  16205. } else if (initData.audio) {
  16206. tracks.audio = {
  16207. container: 'audio/mp4',
  16208. codec: audioCodec,
  16209. initSegment,
  16210. id: 'audio'
  16211. };
  16212. } else if (initData.video) {
  16213. tracks.video = {
  16214. container: 'video/mp4',
  16215. codec: videoCodec,
  16216. supplemental: initData.video.supplemental,
  16217. initSegment,
  16218. id: 'main'
  16219. };
  16220. } else {
  16221. this.warn('initSegment does not contain moov or trak boxes.');
  16222. }
  16223. this.initTracks = tracks;
  16224. }
  16225. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset) {
  16226. var _initData, _initData2;
  16227. let {
  16228. initPTS,
  16229. lastEndTime
  16230. } = this;
  16231. const result = {
  16232. audio: undefined,
  16233. video: undefined,
  16234. text: textTrack,
  16235. id3: id3Track,
  16236. initSegment: undefined
  16237. };
  16238. // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the
  16239. // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update
  16240. // the media duration (which is what timeOffset is provided as) before we need to process the next chunk.
  16241. if (!isFiniteNumber(lastEndTime)) {
  16242. lastEndTime = this.lastEndTime = timeOffset || 0;
  16243. }
  16244. // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only
  16245. // audio or video (or both); adding it to video was an arbitrary choice.
  16246. const data = videoTrack.samples;
  16247. if (!(data != null && data.length)) {
  16248. return result;
  16249. }
  16250. const initSegment = {
  16251. initPTS: undefined,
  16252. timescale: undefined,
  16253. trackId: undefined
  16254. };
  16255. let initData = this.initData;
  16256. if (!((_initData = initData) != null && _initData.length)) {
  16257. this.generateInitSegment(data);
  16258. initData = this.initData;
  16259. }
  16260. if (!((_initData2 = initData) != null && _initData2.length)) {
  16261. // We can't remux if the initSegment could not be generated
  16262. this.warn('Failed to generate initSegment.');
  16263. return result;
  16264. }
  16265. if (this.emitInitSegment) {
  16266. initSegment.tracks = this.initTracks;
  16267. this.emitInitSegment = false;
  16268. }
  16269. const trackSampleData = getSampleData(data, initData, this);
  16270. const audioSampleTimestamps = initData.audio ? trackSampleData[initData.audio.id] : null;
  16271. const videoSampleTimestamps = initData.video ? trackSampleData[initData.video.id] : null;
  16272. const videoStartTime = toStartEndOrDefault(videoSampleTimestamps, Infinity);
  16273. const audioStartTime = toStartEndOrDefault(audioSampleTimestamps, Infinity);
  16274. const videoEndTime = toStartEndOrDefault(videoSampleTimestamps, 0, true);
  16275. const audioEndTime = toStartEndOrDefault(audioSampleTimestamps, 0, true);
  16276. let baseOffsetSamples;
  16277. let decodeTime = timeOffset;
  16278. let duration = 0;
  16279. if (audioSampleTimestamps && (!videoSampleTimestamps || !initPTS && audioStartTime < videoStartTime || initPTS && initPTS.trackId === initData.audio.id)) {
  16280. initSegment.trackId = initData.audio.id;
  16281. baseOffsetSamples = audioSampleTimestamps;
  16282. duration = audioEndTime - audioStartTime;
  16283. } else if (videoSampleTimestamps) {
  16284. initSegment.trackId = initData.video.id;
  16285. baseOffsetSamples = videoSampleTimestamps;
  16286. duration = videoEndTime - videoStartTime;
  16287. }
  16288. if (baseOffsetSamples) {
  16289. const timescale = baseOffsetSamples.timescale;
  16290. decodeTime = baseOffsetSamples.start / timescale;
  16291. initSegment.initPTS = baseOffsetSamples.start - timeOffset * timescale;
  16292. initSegment.timescale = timescale;
  16293. if (!initPTS) {
  16294. this.initPTS = initPTS = {
  16295. baseTime: initSegment.initPTS,
  16296. timescale,
  16297. trackId: initSegment.trackId
  16298. };
  16299. }
  16300. }
  16301. if ((accurateTimeOffset || !initPTS) && (isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) || initSegment.timescale !== initPTS.timescale)) {
  16302. initSegment.initPTS = decodeTime - timeOffset;
  16303. initSegment.timescale = 1;
  16304. if (initPTS && initPTS.timescale === 1) {
  16305. this.warn(`Adjusting initPTS @${timeOffset} from ${initPTS.baseTime / initPTS.timescale} to ${initSegment.initPTS}`);
  16306. }
  16307. this.initPTS = initPTS = {
  16308. baseTime: initSegment.initPTS,
  16309. timescale: 1
  16310. };
  16311. }
  16312. const startTime = audioTrack ? decodeTime - initPTS.baseTime / initPTS.timescale : lastEndTime;
  16313. const endTime = startTime + duration;
  16314. if (duration > 0) {
  16315. this.lastEndTime = endTime;
  16316. } else {
  16317. this.warn('Duration parsed from mp4 should be greater than zero');
  16318. this.resetNextTimestamp();
  16319. }
  16320. const hasAudio = !!initData.audio;
  16321. const hasVideo = !!initData.video;
  16322. let type = '';
  16323. if (hasAudio) {
  16324. type += 'audio';
  16325. }
  16326. if (hasVideo) {
  16327. type += 'video';
  16328. }
  16329. const track = {
  16330. data1: data,
  16331. startPTS: startTime,
  16332. startDTS: startTime,
  16333. endPTS: endTime,
  16334. endDTS: endTime,
  16335. type,
  16336. hasAudio,
  16337. hasVideo,
  16338. nb: 1,
  16339. dropped: 0
  16340. };
  16341. result.audio = hasAudio && !hasVideo ? track : undefined;
  16342. result.video = hasVideo ? track : undefined;
  16343. const videoSampleCount = videoSampleTimestamps == null ? void 0 : videoSampleTimestamps.sampleCount;
  16344. if (videoSampleCount) {
  16345. const firstKeyFrame = videoSampleTimestamps.keyFrameIndex;
  16346. const independent = firstKeyFrame !== -1;
  16347. track.nb = videoSampleCount;
  16348. track.dropped = firstKeyFrame === 0 || this.isVideoContiguous ? 0 : independent ? firstKeyFrame : videoSampleCount;
  16349. track.independent = independent;
  16350. track.firstKeyFrame = firstKeyFrame;
  16351. if (independent && videoSampleTimestamps.keyFrameStart) {
  16352. track.firstKeyFramePTS = (videoSampleTimestamps.keyFrameStart - initPTS.baseTime) / initPTS.timescale;
  16353. }
  16354. if (!this.isVideoContiguous) {
  16355. result.independent = independent;
  16356. }
  16357. this.isVideoContiguous || (this.isVideoContiguous = independent);
  16358. if (track.dropped) {
  16359. this.warn(`fmp4 does not start with IDR: firstIDR ${firstKeyFrame}/${videoSampleCount} dropped: ${track.dropped} start: ${track.firstKeyFramePTS || 'NA'}`);
  16360. }
  16361. }
  16362. result.initSegment = initSegment;
  16363. result.id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, initPTS, initPTS);
  16364. if (textTrack.samples.length) {
  16365. result.text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, initPTS);
  16366. }
  16367. return result;
  16368. }
  16369. }
  16370. function toStartEndOrDefault(trackTimes, defaultValue, end = false) {
  16371. return (trackTimes == null ? void 0 : trackTimes.start) !== undefined ? (trackTimes.start + (end ? trackTimes.duration : 0)) / trackTimes.timescale : defaultValue;
  16372. }
  16373. function isInvalidInitPts(initPTS, startDTS, timeOffset, duration) {
  16374. if (initPTS === null) {
  16375. return true;
  16376. }
  16377. // InitPTS is invalid when distance from program would be more than segment duration or a minimum of one second
  16378. const minDuration = Math.max(duration, 1);
  16379. const startTime = startDTS - initPTS.baseTime / initPTS.timescale;
  16380. return Math.abs(startTime - timeOffset) > minDuration;
  16381. }
  16382. function getParsedTrackCodec(track, type, logger) {
  16383. const parsedCodec = track == null ? void 0 : track.codec;
  16384. if (parsedCodec && parsedCodec.length > 4) {
  16385. return parsedCodec;
  16386. }
  16387. if (type === ElementaryStreamTypes.AUDIO) {
  16388. if (parsedCodec === 'ec-3' || parsedCodec === 'ac-3' || parsedCodec === 'alac') {
  16389. return parsedCodec;
  16390. }
  16391. if (parsedCodec === 'fLaC' || parsedCodec === 'Opus') {
  16392. // Opting not to get `preferManagedMediaSource` from player config for isSupported() check for simplicity
  16393. const preferManagedMediaSource = false;
  16394. return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);
  16395. }
  16396. logger.warn(`Unhandled audio codec "${parsedCodec}" in mp4 MAP`);
  16397. return parsedCodec || 'mp4a';
  16398. }
  16399. // Provide defaults based on codec type
  16400. // This allows for some playback of some fmp4 playlists without CODECS defined in manifest
  16401. logger.warn(`Unhandled video codec "${parsedCodec}" in mp4 MAP`);
  16402. return parsedCodec || 'avc1';
  16403. }
  16404. let now;
  16405. // performance.now() not available on WebWorker, at least on Safari Desktop
  16406. try {
  16407. now = self.performance.now.bind(self.performance);
  16408. } catch (err) {
  16409. now = Date.now;
  16410. }
  16411. const muxConfig = [{
  16412. demux: MP4Demuxer,
  16413. remux: PassThroughRemuxer
  16414. }, {
  16415. demux: TSDemuxer,
  16416. remux: MP4Remuxer
  16417. }, {
  16418. demux: AACDemuxer,
  16419. remux: MP4Remuxer
  16420. }, {
  16421. demux: MP3Demuxer,
  16422. remux: MP4Remuxer
  16423. }];
  16424. class Transmuxer {
  16425. constructor(observer, typeSupported, config, vendor, id, logger) {
  16426. this.asyncResult = false;
  16427. this.logger = void 0;
  16428. this.observer = void 0;
  16429. this.typeSupported = void 0;
  16430. this.config = void 0;
  16431. this.id = void 0;
  16432. this.demuxer = void 0;
  16433. this.remuxer = void 0;
  16434. this.decrypter = void 0;
  16435. this.probe = void 0;
  16436. this.decryptionPromise = null;
  16437. this.transmuxConfig = void 0;
  16438. this.currentTransmuxState = void 0;
  16439. this.observer = observer;
  16440. this.typeSupported = typeSupported;
  16441. this.config = config;
  16442. this.id = id;
  16443. this.logger = logger;
  16444. }
  16445. configure(transmuxConfig) {
  16446. this.transmuxConfig = transmuxConfig;
  16447. if (this.decrypter) {
  16448. this.decrypter.reset();
  16449. }
  16450. }
  16451. push(data, decryptdata, chunkMeta, state) {
  16452. const stats = chunkMeta.transmuxing;
  16453. stats.executeStart = now();
  16454. let uintData = new Uint8Array(data);
  16455. const {
  16456. currentTransmuxState,
  16457. transmuxConfig
  16458. } = this;
  16459. if (state) {
  16460. this.currentTransmuxState = state;
  16461. }
  16462. const {
  16463. contiguous,
  16464. discontinuity,
  16465. trackSwitch,
  16466. accurateTimeOffset,
  16467. timeOffset,
  16468. initSegmentChange
  16469. } = state || currentTransmuxState;
  16470. const {
  16471. audioCodec,
  16472. videoCodec,
  16473. defaultInitPts,
  16474. duration,
  16475. initSegmentData
  16476. } = transmuxConfig;
  16477. const keyData = getEncryptionType(uintData, decryptdata);
  16478. if (keyData && isFullSegmentEncryption(keyData.method)) {
  16479. const decrypter = this.getDecrypter();
  16480. const aesMode = getAesModeFromFullSegmentMethod(keyData.method);
  16481. // Software decryption is synchronous; webCrypto is not
  16482. if (decrypter.isSync()) {
  16483. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  16484. // data is handled in the flush() call
  16485. let decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode);
  16486. // For Low-Latency HLS Parts, decrypt in place, since part parsing is expected on push progress
  16487. const loadingParts = chunkMeta.part > -1;
  16488. if (loadingParts) {
  16489. const _data = decrypter.flush();
  16490. decryptedData = _data ? _data.buffer : _data;
  16491. }
  16492. if (!decryptedData) {
  16493. stats.executeEnd = now();
  16494. return emptyResult(chunkMeta);
  16495. }
  16496. uintData = new Uint8Array(decryptedData);
  16497. } else {
  16498. this.asyncResult = true;
  16499. this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode).then(decryptedData => {
  16500. // Calling push here is important; if flush() is called while this is still resolving, this ensures that
  16501. // the decrypted data has been transmuxed
  16502. const result = this.push(decryptedData, null, chunkMeta);
  16503. this.decryptionPromise = null;
  16504. return result;
  16505. });
  16506. return this.decryptionPromise;
  16507. }
  16508. }
  16509. const resetMuxers = this.needsProbing(discontinuity, trackSwitch);
  16510. if (resetMuxers) {
  16511. const error = this.configureTransmuxer(uintData);
  16512. if (error) {
  16513. this.logger.warn(`[transmuxer] ${error.message}`);
  16514. this.observer.emit(Events.ERROR, Events.ERROR, {
  16515. type: ErrorTypes.MEDIA_ERROR,
  16516. details: ErrorDetails.FRAG_PARSING_ERROR,
  16517. fatal: false,
  16518. error,
  16519. reason: error.message
  16520. });
  16521. stats.executeEnd = now();
  16522. return emptyResult(chunkMeta);
  16523. }
  16524. }
  16525. if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {
  16526. this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration, decryptdata);
  16527. }
  16528. if (discontinuity || initSegmentChange || resetMuxers) {
  16529. this.resetInitialTimestamp(defaultInitPts);
  16530. }
  16531. if (!contiguous) {
  16532. this.resetContiguity();
  16533. }
  16534. const result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  16535. this.asyncResult = isPromise(result);
  16536. const currentState = this.currentTransmuxState;
  16537. currentState.contiguous = true;
  16538. currentState.discontinuity = false;
  16539. currentState.trackSwitch = false;
  16540. stats.executeEnd = now();
  16541. return result;
  16542. }
  16543. // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
  16544. flush(chunkMeta) {
  16545. const stats = chunkMeta.transmuxing;
  16546. stats.executeStart = now();
  16547. const {
  16548. decrypter,
  16549. currentTransmuxState,
  16550. decryptionPromise
  16551. } = this;
  16552. if (decryptionPromise) {
  16553. this.asyncResult = true;
  16554. // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore
  16555. // only flushing is required for async decryption
  16556. return decryptionPromise.then(() => {
  16557. return this.flush(chunkMeta);
  16558. });
  16559. }
  16560. const transmuxResults = [];
  16561. const {
  16562. timeOffset
  16563. } = currentTransmuxState;
  16564. if (decrypter) {
  16565. // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults
  16566. // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,
  16567. // or for progressive downloads with small segments)
  16568. const decryptedData = decrypter.flush();
  16569. if (decryptedData) {
  16570. // Push always returns a TransmuxerResult if decryptdata is null
  16571. transmuxResults.push(this.push(decryptedData.buffer, null, chunkMeta));
  16572. }
  16573. }
  16574. const {
  16575. demuxer,
  16576. remuxer
  16577. } = this;
  16578. if (!demuxer || !remuxer) {
  16579. // If probing failed, then Hls.js has been given content its not able to handle
  16580. stats.executeEnd = now();
  16581. const emptyResults = [emptyResult(chunkMeta)];
  16582. if (this.asyncResult) {
  16583. return Promise.resolve(emptyResults);
  16584. }
  16585. return emptyResults;
  16586. }
  16587. const demuxResultOrPromise = demuxer.flush(timeOffset);
  16588. if (isPromise(demuxResultOrPromise)) {
  16589. this.asyncResult = true;
  16590. // Decrypt final SAMPLE-AES samples
  16591. return demuxResultOrPromise.then(demuxResult => {
  16592. this.flushRemux(transmuxResults, demuxResult, chunkMeta);
  16593. return transmuxResults;
  16594. });
  16595. }
  16596. this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
  16597. if (this.asyncResult) {
  16598. return Promise.resolve(transmuxResults);
  16599. }
  16600. return transmuxResults;
  16601. }
  16602. flushRemux(transmuxResults, demuxResult, chunkMeta) {
  16603. const {
  16604. audioTrack,
  16605. videoTrack,
  16606. id3Track,
  16607. textTrack
  16608. } = demuxResult;
  16609. const {
  16610. accurateTimeOffset,
  16611. timeOffset
  16612. } = this.currentTransmuxState;
  16613. 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}`);
  16614. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
  16615. transmuxResults.push({
  16616. remuxResult,
  16617. chunkMeta
  16618. });
  16619. chunkMeta.transmuxing.executeEnd = now();
  16620. }
  16621. resetInitialTimestamp(defaultInitPts) {
  16622. const {
  16623. demuxer,
  16624. remuxer
  16625. } = this;
  16626. if (!demuxer || !remuxer) {
  16627. return;
  16628. }
  16629. demuxer.resetTimeStamp(defaultInitPts);
  16630. remuxer.resetTimeStamp(defaultInitPts);
  16631. }
  16632. resetContiguity() {
  16633. const {
  16634. demuxer,
  16635. remuxer
  16636. } = this;
  16637. if (!demuxer || !remuxer) {
  16638. return;
  16639. }
  16640. demuxer.resetContiguity();
  16641. remuxer.resetNextTimestamp();
  16642. }
  16643. resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration, decryptdata) {
  16644. const {
  16645. demuxer,
  16646. remuxer
  16647. } = this;
  16648. if (!demuxer || !remuxer) {
  16649. return;
  16650. }
  16651. demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration);
  16652. remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, decryptdata);
  16653. }
  16654. destroy() {
  16655. if (this.demuxer) {
  16656. this.demuxer.destroy();
  16657. this.demuxer = undefined;
  16658. }
  16659. if (this.remuxer) {
  16660. this.remuxer.destroy();
  16661. this.remuxer = undefined;
  16662. }
  16663. }
  16664. transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
  16665. let result;
  16666. if (keyData && keyData.method === 'SAMPLE-AES') {
  16667. result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  16668. } else {
  16669. result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
  16670. }
  16671. return result;
  16672. }
  16673. transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
  16674. const {
  16675. audioTrack,
  16676. videoTrack,
  16677. id3Track,
  16678. textTrack
  16679. } = this.demuxer.demux(data, timeOffset, false, !this.config.progressive);
  16680. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
  16681. return {
  16682. remuxResult,
  16683. chunkMeta
  16684. };
  16685. }
  16686. transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
  16687. return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(demuxResult => {
  16688. const remuxResult = this.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, this.id);
  16689. return {
  16690. remuxResult,
  16691. chunkMeta
  16692. };
  16693. });
  16694. }
  16695. configureTransmuxer(data) {
  16696. const {
  16697. config,
  16698. observer,
  16699. typeSupported
  16700. } = this;
  16701. // probe for content type
  16702. let mux;
  16703. for (let i = 0, len = muxConfig.length; i < len; i++) {
  16704. var _muxConfig$i$demux;
  16705. if ((_muxConfig$i$demux = muxConfig[i].demux) != null && _muxConfig$i$demux.probe(data, this.logger)) {
  16706. mux = muxConfig[i];
  16707. break;
  16708. }
  16709. }
  16710. if (!mux) {
  16711. return new Error('Failed to find demuxer by probing fragment data');
  16712. }
  16713. // so let's check that current remuxer and demuxer are still valid
  16714. const demuxer = this.demuxer;
  16715. const remuxer = this.remuxer;
  16716. const Remuxer = mux.remux;
  16717. const Demuxer = mux.demux;
  16718. if (!remuxer || !(remuxer instanceof Remuxer)) {
  16719. this.remuxer = new Remuxer(observer, config, typeSupported, this.logger);
  16720. }
  16721. if (!demuxer || !(demuxer instanceof Demuxer)) {
  16722. this.demuxer = new Demuxer(observer, config, typeSupported, this.logger);
  16723. this.probe = Demuxer.probe;
  16724. }
  16725. }
  16726. needsProbing(discontinuity, trackSwitch) {
  16727. // in case of continuity change, or track switch
  16728. // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
  16729. return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
  16730. }
  16731. getDecrypter() {
  16732. let decrypter = this.decrypter;
  16733. if (!decrypter) {
  16734. decrypter = this.decrypter = new Decrypter(this.config);
  16735. }
  16736. return decrypter;
  16737. }
  16738. }
  16739. function getEncryptionType(data, decryptData) {
  16740. let encryptionType = null;
  16741. if (data.byteLength > 0 && (decryptData == null ? void 0 : decryptData.key) != null && decryptData.iv !== null && decryptData.method != null) {
  16742. encryptionType = decryptData;
  16743. }
  16744. return encryptionType;
  16745. }
  16746. const emptyResult = chunkMeta => ({
  16747. remuxResult: {},
  16748. chunkMeta
  16749. });
  16750. function isPromise(p) {
  16751. return 'then' in p && p.then instanceof Function;
  16752. }
  16753. class TransmuxConfig {
  16754. constructor(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
  16755. this.audioCodec = void 0;
  16756. this.videoCodec = void 0;
  16757. this.initSegmentData = void 0;
  16758. this.duration = void 0;
  16759. this.defaultInitPts = void 0;
  16760. this.audioCodec = audioCodec;
  16761. this.videoCodec = videoCodec;
  16762. this.initSegmentData = initSegmentData;
  16763. this.duration = duration;
  16764. this.defaultInitPts = defaultInitPts || null;
  16765. }
  16766. }
  16767. class TransmuxState {
  16768. constructor(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) {
  16769. this.discontinuity = void 0;
  16770. this.contiguous = void 0;
  16771. this.accurateTimeOffset = void 0;
  16772. this.trackSwitch = void 0;
  16773. this.timeOffset = void 0;
  16774. this.initSegmentChange = void 0;
  16775. this.discontinuity = discontinuity;
  16776. this.contiguous = contiguous;
  16777. this.accurateTimeOffset = accurateTimeOffset;
  16778. this.trackSwitch = trackSwitch;
  16779. this.timeOffset = timeOffset;
  16780. this.initSegmentChange = initSegmentChange;
  16781. }
  16782. }
  16783. function fetchSupported() {
  16784. if (
  16785. // @ts-ignore
  16786. self.fetch && self.AbortController && self.ReadableStream && self.Request) {
  16787. try {
  16788. new self.ReadableStream({}); // eslint-disable-line no-new
  16789. return true;
  16790. } catch (e) {
  16791. /* noop */
  16792. }
  16793. }
  16794. return false;
  16795. }
  16796. const BYTERANGE = /(\d+)-(\d+)\/(\d+)/;
  16797. class FetchLoader {
  16798. constructor(config) {
  16799. this.fetchSetup = void 0;
  16800. this.requestTimeout = void 0;
  16801. this.request = null;
  16802. this.response = null;
  16803. this.controller = void 0;
  16804. this.context = null;
  16805. this.config = null;
  16806. this.callbacks = null;
  16807. this.stats = void 0;
  16808. this.loader = null;
  16809. this.fetchSetup = config.fetchSetup || getRequest;
  16810. this.controller = new self.AbortController();
  16811. this.stats = new LoadStats();
  16812. }
  16813. destroy() {
  16814. this.loader = this.callbacks = this.context = this.config = this.request = null;
  16815. this.abortInternal();
  16816. this.response = null;
  16817. // @ts-ignore
  16818. this.fetchSetup = this.controller = this.stats = null;
  16819. }
  16820. abortInternal() {
  16821. if (this.controller && !this.stats.loading.end) {
  16822. this.stats.aborted = true;
  16823. this.controller.abort();
  16824. }
  16825. }
  16826. abort() {
  16827. var _this$callbacks;
  16828. this.abortInternal();
  16829. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  16830. this.callbacks.onAbort(this.stats, this.context, this.response);
  16831. }
  16832. }
  16833. load(context, config, callbacks) {
  16834. const stats = this.stats;
  16835. if (stats.loading.start) {
  16836. throw new Error('Loader can only be used once.');
  16837. }
  16838. stats.loading.start = self.performance.now();
  16839. const initParams = getRequestParameters(context, this.controller.signal);
  16840. const isArrayBuffer = context.responseType === 'arraybuffer';
  16841. const LENGTH = isArrayBuffer ? 'byteLength' : 'length';
  16842. const {
  16843. maxTimeToFirstByteMs,
  16844. maxLoadTimeMs
  16845. } = config.loadPolicy;
  16846. this.context = context;
  16847. this.config = config;
  16848. this.callbacks = callbacks;
  16849. this.request = this.fetchSetup(context, initParams);
  16850. self.clearTimeout(this.requestTimeout);
  16851. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  16852. this.requestTimeout = self.setTimeout(() => {
  16853. if (this.callbacks) {
  16854. this.abortInternal();
  16855. this.callbacks.onTimeout(stats, context, this.response);
  16856. }
  16857. }, config.timeout);
  16858. const fetchPromise = isPromise(this.request) ? this.request.then(self.fetch) : self.fetch(this.request);
  16859. fetchPromise.then(response => {
  16860. var _this$callbacks2;
  16861. this.response = this.loader = response;
  16862. const first = Math.max(self.performance.now(), stats.loading.start);
  16863. self.clearTimeout(this.requestTimeout);
  16864. config.timeout = maxLoadTimeMs;
  16865. this.requestTimeout = self.setTimeout(() => {
  16866. if (this.callbacks) {
  16867. this.abortInternal();
  16868. this.callbacks.onTimeout(stats, context, this.response);
  16869. }
  16870. }, maxLoadTimeMs - (first - stats.loading.start));
  16871. if (!response.ok) {
  16872. const {
  16873. status,
  16874. statusText
  16875. } = response;
  16876. throw new FetchError(statusText || 'fetch, bad network response', status, response);
  16877. }
  16878. stats.loading.first = first;
  16879. stats.total = getContentLength(response.headers) || stats.total;
  16880. const onProgress = (_this$callbacks2 = this.callbacks) == null ? void 0 : _this$callbacks2.onProgress;
  16881. if (onProgress && isFiniteNumber(config.highWaterMark)) {
  16882. return this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
  16883. }
  16884. if (isArrayBuffer) {
  16885. return response.arrayBuffer();
  16886. }
  16887. if (context.responseType === 'json') {
  16888. return response.json();
  16889. }
  16890. return response.text();
  16891. }).then(responseData => {
  16892. var _this$callbacks3, _this$callbacks4;
  16893. const response = this.response;
  16894. if (!response) {
  16895. throw new Error('loader destroyed');
  16896. }
  16897. self.clearTimeout(this.requestTimeout);
  16898. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  16899. const total = responseData[LENGTH];
  16900. if (total) {
  16901. stats.loaded = stats.total = total;
  16902. }
  16903. const loaderResponse = {
  16904. url: response.url,
  16905. data: responseData,
  16906. code: response.status
  16907. };
  16908. const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  16909. if (onProgress && !isFiniteNumber(config.highWaterMark)) {
  16910. onProgress(stats, context, responseData, response);
  16911. }
  16912. (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(loaderResponse, stats, context, response);
  16913. }).catch(error => {
  16914. var _this$callbacks5;
  16915. self.clearTimeout(this.requestTimeout);
  16916. if (stats.aborted) {
  16917. return;
  16918. }
  16919. // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior
  16920. // when destroying, 'error' itself can be undefined
  16921. const code = !error ? 0 : error.code || 0;
  16922. const text = !error ? null : error.message;
  16923. (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({
  16924. code,
  16925. text
  16926. }, context, error ? error.details : null, stats);
  16927. });
  16928. }
  16929. getCacheAge() {
  16930. let result = null;
  16931. if (this.response) {
  16932. const ageHeader = this.response.headers.get('age');
  16933. result = ageHeader ? parseFloat(ageHeader) : null;
  16934. }
  16935. return result;
  16936. }
  16937. getResponseHeader(name) {
  16938. return this.response ? this.response.headers.get(name) : null;
  16939. }
  16940. loadProgressively(response, stats, context, highWaterMark = 0, onProgress) {
  16941. const chunkCache = new ChunkCache();
  16942. const reader = response.body.getReader();
  16943. const pump = () => {
  16944. return reader.read().then(data => {
  16945. if (data.done) {
  16946. if (chunkCache.dataLength) {
  16947. onProgress(stats, context, chunkCache.flush().buffer, response);
  16948. }
  16949. return Promise.resolve(new ArrayBuffer(0));
  16950. }
  16951. const chunk = data.value;
  16952. const len = chunk.length;
  16953. stats.loaded += len;
  16954. if (len < highWaterMark || chunkCache.dataLength) {
  16955. // The current chunk is too small to to be emitted or the cache already has data
  16956. // Push it to the cache
  16957. chunkCache.push(chunk);
  16958. if (chunkCache.dataLength >= highWaterMark) {
  16959. // flush in order to join the typed arrays
  16960. onProgress(stats, context, chunkCache.flush().buffer, response);
  16961. }
  16962. } else {
  16963. // If there's nothing cached already, and the chache is large enough
  16964. // just emit the progress event
  16965. onProgress(stats, context, chunk.buffer, response);
  16966. }
  16967. return pump();
  16968. }).catch(() => {
  16969. /* aborted */
  16970. return Promise.reject();
  16971. });
  16972. };
  16973. return pump();
  16974. }
  16975. }
  16976. function getRequestParameters(context, signal) {
  16977. const initParams = {
  16978. method: 'GET',
  16979. mode: 'cors',
  16980. credentials: 'same-origin',
  16981. signal,
  16982. headers: new self.Headers(_extends({}, context.headers))
  16983. };
  16984. if (context.rangeEnd) {
  16985. initParams.headers.set('Range', 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1));
  16986. }
  16987. return initParams;
  16988. }
  16989. function getByteRangeLength(byteRangeHeader) {
  16990. const result = BYTERANGE.exec(byteRangeHeader);
  16991. if (result) {
  16992. return parseInt(result[2]) - parseInt(result[1]) + 1;
  16993. }
  16994. }
  16995. function getContentLength(headers) {
  16996. const contentRange = headers.get('Content-Range');
  16997. if (contentRange) {
  16998. const byteRangeLength = getByteRangeLength(contentRange);
  16999. if (isFiniteNumber(byteRangeLength)) {
  17000. return byteRangeLength;
  17001. }
  17002. }
  17003. const contentLength = headers.get('Content-Length');
  17004. if (contentLength) {
  17005. return parseInt(contentLength);
  17006. }
  17007. }
  17008. function getRequest(context, initParams) {
  17009. return new self.Request(context.url, initParams);
  17010. }
  17011. class FetchError extends Error {
  17012. constructor(message, code, details) {
  17013. super(message);
  17014. this.code = void 0;
  17015. this.details = void 0;
  17016. this.code = code;
  17017. this.details = details;
  17018. }
  17019. }
  17020. const AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/im;
  17021. class XhrLoader {
  17022. constructor(config) {
  17023. this.xhrSetup = void 0;
  17024. this.requestTimeout = void 0;
  17025. this.retryTimeout = void 0;
  17026. this.retryDelay = void 0;
  17027. this.config = null;
  17028. this.callbacks = null;
  17029. this.context = null;
  17030. this.loader = null;
  17031. this.stats = void 0;
  17032. this.xhrSetup = config ? config.xhrSetup || null : null;
  17033. this.stats = new LoadStats();
  17034. this.retryDelay = 0;
  17035. }
  17036. destroy() {
  17037. this.callbacks = null;
  17038. this.abortInternal();
  17039. this.loader = null;
  17040. this.config = null;
  17041. this.context = null;
  17042. this.xhrSetup = null;
  17043. }
  17044. abortInternal() {
  17045. const loader = this.loader;
  17046. self.clearTimeout(this.requestTimeout);
  17047. self.clearTimeout(this.retryTimeout);
  17048. if (loader) {
  17049. loader.onreadystatechange = null;
  17050. loader.onprogress = null;
  17051. if (loader.readyState !== 4) {
  17052. this.stats.aborted = true;
  17053. loader.abort();
  17054. }
  17055. }
  17056. }
  17057. abort() {
  17058. var _this$callbacks;
  17059. this.abortInternal();
  17060. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  17061. this.callbacks.onAbort(this.stats, this.context, this.loader);
  17062. }
  17063. }
  17064. load(context, config, callbacks) {
  17065. if (this.stats.loading.start) {
  17066. throw new Error('Loader can only be used once.');
  17067. }
  17068. this.stats.loading.start = self.performance.now();
  17069. this.context = context;
  17070. this.config = config;
  17071. this.callbacks = callbacks;
  17072. this.loadInternal();
  17073. }
  17074. loadInternal() {
  17075. const {
  17076. config,
  17077. context
  17078. } = this;
  17079. if (!config || !context) {
  17080. return;
  17081. }
  17082. const xhr = this.loader = new self.XMLHttpRequest();
  17083. const stats = this.stats;
  17084. stats.loading.first = 0;
  17085. stats.loaded = 0;
  17086. stats.aborted = false;
  17087. const xhrSetup = this.xhrSetup;
  17088. if (xhrSetup) {
  17089. Promise.resolve().then(() => {
  17090. if (this.loader !== xhr || this.stats.aborted) return;
  17091. return xhrSetup(xhr, context.url);
  17092. }).catch(error => {
  17093. if (this.loader !== xhr || this.stats.aborted) return;
  17094. xhr.open('GET', context.url, true);
  17095. return xhrSetup(xhr, context.url);
  17096. }).then(() => {
  17097. if (this.loader !== xhr || this.stats.aborted) return;
  17098. this.openAndSendXhr(xhr, context, config);
  17099. }).catch(error => {
  17100. var _this$callbacks2;
  17101. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  17102. (_this$callbacks2 = this.callbacks) == null ? void 0 : _this$callbacks2.onError({
  17103. code: xhr.status,
  17104. text: error.message
  17105. }, context, xhr, stats);
  17106. return;
  17107. });
  17108. } else {
  17109. this.openAndSendXhr(xhr, context, config);
  17110. }
  17111. }
  17112. openAndSendXhr(xhr, context, config) {
  17113. if (!xhr.readyState) {
  17114. xhr.open('GET', context.url, true);
  17115. }
  17116. const headers = context.headers;
  17117. const {
  17118. maxTimeToFirstByteMs,
  17119. maxLoadTimeMs
  17120. } = config.loadPolicy;
  17121. if (headers) {
  17122. for (const header in headers) {
  17123. xhr.setRequestHeader(header, headers[header]);
  17124. }
  17125. }
  17126. if (context.rangeEnd) {
  17127. xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
  17128. }
  17129. xhr.onreadystatechange = this.readystatechange.bind(this);
  17130. xhr.onprogress = this.loadprogress.bind(this);
  17131. xhr.responseType = context.responseType;
  17132. // setup timeout before we perform request
  17133. self.clearTimeout(this.requestTimeout);
  17134. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  17135. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
  17136. xhr.send();
  17137. }
  17138. readystatechange() {
  17139. const {
  17140. context,
  17141. loader: xhr,
  17142. stats
  17143. } = this;
  17144. if (!context || !xhr) {
  17145. return;
  17146. }
  17147. const readyState = xhr.readyState;
  17148. const config = this.config;
  17149. // don't proceed if xhr has been aborted
  17150. if (stats.aborted) {
  17151. return;
  17152. }
  17153. // >= HEADERS_RECEIVED
  17154. if (readyState >= 2) {
  17155. if (stats.loading.first === 0) {
  17156. stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
  17157. // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
  17158. if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {
  17159. self.clearTimeout(this.requestTimeout);
  17160. config.timeout = config.loadPolicy.maxLoadTimeMs;
  17161. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.loadPolicy.maxLoadTimeMs - (stats.loading.first - stats.loading.start));
  17162. }
  17163. }
  17164. if (readyState === 4) {
  17165. self.clearTimeout(this.requestTimeout);
  17166. xhr.onreadystatechange = null;
  17167. xhr.onprogress = null;
  17168. const status = xhr.status;
  17169. // http status between 200 to 299 are all successful
  17170. const useResponseText = xhr.responseType === 'text' ? xhr.responseText : null;
  17171. if (status >= 200 && status < 300) {
  17172. const data = useResponseText != null ? useResponseText : xhr.response;
  17173. if (data != null) {
  17174. var _this$callbacks3, _this$callbacks4;
  17175. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  17176. const len = xhr.responseType === 'arraybuffer' ? data.byteLength : data.length;
  17177. stats.loaded = stats.total = len;
  17178. stats.bwEstimate = stats.total * 8000 / (stats.loading.end - stats.loading.first);
  17179. const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  17180. if (onProgress) {
  17181. onProgress(stats, context, data, xhr);
  17182. }
  17183. const _response = {
  17184. url: xhr.responseURL,
  17185. data: data,
  17186. code: status
  17187. };
  17188. (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(_response, stats, context, xhr);
  17189. return;
  17190. }
  17191. }
  17192. // Handle bad status or nullish response
  17193. const retryConfig = config.loadPolicy.errorRetry;
  17194. const retryCount = stats.retry;
  17195. // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
  17196. const response = {
  17197. url: context.url,
  17198. data: undefined,
  17199. code: status
  17200. };
  17201. if (shouldRetry(retryConfig, retryCount, false, response)) {
  17202. this.retry(retryConfig);
  17203. } else {
  17204. var _this$callbacks5;
  17205. logger.error(`${status} while loading ${context.url}`);
  17206. (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({
  17207. code: status,
  17208. text: xhr.statusText
  17209. }, context, xhr, stats);
  17210. }
  17211. }
  17212. }
  17213. }
  17214. loadtimeout() {
  17215. if (!this.config) return;
  17216. const retryConfig = this.config.loadPolicy.timeoutRetry;
  17217. const retryCount = this.stats.retry;
  17218. if (shouldRetry(retryConfig, retryCount, true)) {
  17219. this.retry(retryConfig);
  17220. } else {
  17221. var _this$context;
  17222. logger.warn(`timeout while loading ${(_this$context = this.context) == null ? void 0 : _this$context.url}`);
  17223. const callbacks = this.callbacks;
  17224. if (callbacks) {
  17225. this.abortInternal();
  17226. callbacks.onTimeout(this.stats, this.context, this.loader);
  17227. }
  17228. }
  17229. }
  17230. retry(retryConfig) {
  17231. const {
  17232. context,
  17233. stats
  17234. } = this;
  17235. this.retryDelay = getRetryDelay(retryConfig, stats.retry);
  17236. stats.retry++;
  17237. logger.warn(`${status ? 'HTTP Status ' + status : 'Timeout'} while loading ${context == null ? void 0 : context.url}, retrying ${stats.retry}/${retryConfig.maxNumRetry} in ${this.retryDelay}ms`);
  17238. // abort and reset internal state
  17239. this.abortInternal();
  17240. this.loader = null;
  17241. // schedule retry
  17242. self.clearTimeout(this.retryTimeout);
  17243. this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  17244. }
  17245. loadprogress(event) {
  17246. const stats = this.stats;
  17247. stats.loaded = event.loaded;
  17248. if (event.lengthComputable) {
  17249. stats.total = event.total;
  17250. }
  17251. }
  17252. getCacheAge() {
  17253. let result = null;
  17254. if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
  17255. const ageHeader = this.loader.getResponseHeader('age');
  17256. result = ageHeader ? parseFloat(ageHeader) : null;
  17257. }
  17258. return result;
  17259. }
  17260. getResponseHeader(name) {
  17261. if (this.loader && new RegExp(`^${name}:\\s*[\\d.]+\\s*$`, 'im').test(this.loader.getAllResponseHeaders())) {
  17262. return this.loader.getResponseHeader(name);
  17263. }
  17264. return null;
  17265. }
  17266. }
  17267. /**
  17268. * @deprecated use fragLoadPolicy.default
  17269. */
  17270. /**
  17271. * @deprecated use manifestLoadPolicy.default and playlistLoadPolicy.default
  17272. */
  17273. const defaultLoadPolicy = {
  17274. maxTimeToFirstByteMs: 8000,
  17275. maxLoadTimeMs: 20000,
  17276. timeoutRetry: null,
  17277. errorRetry: null
  17278. };
  17279. /**
  17280. * @ignore
  17281. * If possible, keep hlsDefaultConfig shallow
  17282. * It is cloned whenever a new Hls instance is created, by keeping the config
  17283. * shallow the properties are cloned, and we don't end up manipulating the default
  17284. */
  17285. const hlsDefaultConfig = _objectSpread2(_objectSpread2({
  17286. autoStartLoad: true,
  17287. // used by stream-controller
  17288. startPosition: -1,
  17289. // used by stream-controller
  17290. defaultAudioCodec: undefined,
  17291. // used by stream-controller
  17292. debug: false,
  17293. // used by logger
  17294. capLevelOnFPSDrop: false,
  17295. // used by fps-controller
  17296. capLevelToPlayerSize: false,
  17297. // used by cap-level-controller
  17298. ignoreDevicePixelRatio: false,
  17299. // used by cap-level-controller
  17300. maxDevicePixelRatio: Number.POSITIVE_INFINITY,
  17301. // used by cap-level-controller
  17302. preferManagedMediaSource: true,
  17303. initialLiveManifestSize: 1,
  17304. // used by stream-controller
  17305. maxBufferLength: 30,
  17306. // used by stream-controller
  17307. backBufferLength: Infinity,
  17308. // used by buffer-controller
  17309. frontBufferFlushThreshold: Infinity,
  17310. startOnSegmentBoundary: false,
  17311. // used by stream-controller
  17312. maxBufferSize: 60 * 1000 * 1000,
  17313. // used by stream-controller
  17314. maxFragLookUpTolerance: 0.25,
  17315. // used by stream-controller
  17316. maxBufferHole: 0.1,
  17317. // used by stream-controller and gap-controller
  17318. detectStallWithCurrentTimeMs: 1250,
  17319. // used by gap-controller
  17320. highBufferWatchdogPeriod: 2,
  17321. // used by gap-controller
  17322. nudgeOffset: 0.1,
  17323. // used by gap-controller
  17324. nudgeMaxRetry: 3,
  17325. // used by gap-controller
  17326. nudgeOnVideoHole: true,
  17327. // used by gap-controller
  17328. liveSyncMode: 'edge',
  17329. // used by stream-controller
  17330. liveSyncDurationCount: 3,
  17331. // used by latency-controller
  17332. liveSyncOnStallIncrease: 1,
  17333. // used by latency-controller
  17334. liveMaxLatencyDurationCount: Infinity,
  17335. // used by latency-controller
  17336. liveSyncDuration: undefined,
  17337. // used by latency-controller
  17338. liveMaxLatencyDuration: undefined,
  17339. // used by latency-controller
  17340. maxLiveSyncPlaybackRate: 1,
  17341. // used by latency-controller
  17342. liveDurationInfinity: false,
  17343. // used by buffer-controller
  17344. /**
  17345. * @deprecated use backBufferLength
  17346. */
  17347. liveBackBufferLength: null,
  17348. // used by buffer-controller
  17349. maxMaxBufferLength: 600,
  17350. // used by stream-controller
  17351. enableWorker: true,
  17352. // used by transmuxer
  17353. workerPath: null,
  17354. // used by transmuxer
  17355. enableSoftwareAES: true,
  17356. // used by decrypter
  17357. startLevel: undefined,
  17358. // used by level-controller
  17359. startFragPrefetch: false,
  17360. // used by stream-controller
  17361. fpsDroppedMonitoringPeriod: 5000,
  17362. // used by fps-controller
  17363. fpsDroppedMonitoringThreshold: 0.2,
  17364. // used by fps-controller
  17365. appendErrorMaxRetry: 3,
  17366. // used by buffer-controller
  17367. ignorePlaylistParsingErrors: false,
  17368. loader: XhrLoader,
  17369. // loader: FetchLoader,
  17370. fLoader: undefined,
  17371. // used by fragment-loader
  17372. pLoader: undefined,
  17373. // used by playlist-loader
  17374. xhrSetup: undefined,
  17375. // used by xhr-loader
  17376. licenseXhrSetup: undefined,
  17377. // used by eme-controller
  17378. licenseResponseCallback: undefined,
  17379. // used by eme-controller
  17380. abrController: AbrController,
  17381. bufferController: BufferController,
  17382. capLevelController: CapLevelController,
  17383. errorController: ErrorController,
  17384. fpsController: FPSController,
  17385. stretchShortVideoTrack: false,
  17386. // used by mp4-remuxer
  17387. maxAudioFramesDrift: 1,
  17388. // used by mp4-remuxer
  17389. forceKeyFrameOnDiscontinuity: true,
  17390. // used by ts-demuxer
  17391. abrEwmaFastLive: 3,
  17392. // used by abr-controller
  17393. abrEwmaSlowLive: 9,
  17394. // used by abr-controller
  17395. abrEwmaFastVoD: 3,
  17396. // used by abr-controller
  17397. abrEwmaSlowVoD: 9,
  17398. // used by abr-controller
  17399. abrEwmaDefaultEstimate: 5e5,
  17400. // 500 kbps // used by abr-controller
  17401. abrEwmaDefaultEstimateMax: 5e6,
  17402. // 5 mbps
  17403. abrBandWidthFactor: 0.95,
  17404. // used by abr-controller
  17405. abrBandWidthUpFactor: 0.7,
  17406. // used by abr-controller
  17407. abrMaxWithRealBitrate: false,
  17408. // used by abr-controller
  17409. maxStarvationDelay: 4,
  17410. // used by abr-controller
  17411. maxLoadingDelay: 4,
  17412. // used by abr-controller
  17413. minAutoBitrate: 0,
  17414. // used by hls
  17415. emeEnabled: false,
  17416. // used by eme-controller
  17417. widevineLicenseUrl: undefined,
  17418. // used by eme-controller
  17419. drmSystems: {},
  17420. // used by eme-controller
  17421. drmSystemOptions: {},
  17422. // used by eme-controller
  17423. requestMediaKeySystemAccessFunc: null,
  17424. // used by eme-controller
  17425. requireKeySystemAccessOnStart: false,
  17426. // used by eme-controller
  17427. testBandwidth: true,
  17428. progressive: false,
  17429. lowLatencyMode: true,
  17430. cmcd: undefined,
  17431. enableDateRangeMetadataCues: true,
  17432. enableEmsgMetadataCues: true,
  17433. enableEmsgKLVMetadata: false,
  17434. enableID3MetadataCues: true,
  17435. enableInterstitialPlayback: false,
  17436. interstitialAppendInPlace: true,
  17437. interstitialLiveLookAhead: 10,
  17438. useMediaCapabilities: false,
  17439. preserveManualLevelOnError: false,
  17440. certLoadPolicy: {
  17441. default: defaultLoadPolicy
  17442. },
  17443. keyLoadPolicy: {
  17444. default: {
  17445. maxTimeToFirstByteMs: 8000,
  17446. maxLoadTimeMs: 20000,
  17447. timeoutRetry: {
  17448. maxNumRetry: 1,
  17449. retryDelayMs: 1000,
  17450. maxRetryDelayMs: 20000,
  17451. backoff: 'linear'
  17452. },
  17453. errorRetry: {
  17454. maxNumRetry: 8,
  17455. retryDelayMs: 1000,
  17456. maxRetryDelayMs: 20000,
  17457. backoff: 'linear'
  17458. }
  17459. }
  17460. },
  17461. manifestLoadPolicy: {
  17462. default: {
  17463. maxTimeToFirstByteMs: Infinity,
  17464. maxLoadTimeMs: 20000,
  17465. timeoutRetry: {
  17466. maxNumRetry: 2,
  17467. retryDelayMs: 0,
  17468. maxRetryDelayMs: 0
  17469. },
  17470. errorRetry: {
  17471. maxNumRetry: 1,
  17472. retryDelayMs: 1000,
  17473. maxRetryDelayMs: 8000
  17474. }
  17475. }
  17476. },
  17477. playlistLoadPolicy: {
  17478. default: {
  17479. maxTimeToFirstByteMs: 10000,
  17480. maxLoadTimeMs: 20000,
  17481. timeoutRetry: {
  17482. maxNumRetry: 2,
  17483. retryDelayMs: 0,
  17484. maxRetryDelayMs: 0
  17485. },
  17486. errorRetry: {
  17487. maxNumRetry: 2,
  17488. retryDelayMs: 1000,
  17489. maxRetryDelayMs: 8000
  17490. }
  17491. }
  17492. },
  17493. fragLoadPolicy: {
  17494. default: {
  17495. maxTimeToFirstByteMs: 10000,
  17496. maxLoadTimeMs: 120000,
  17497. timeoutRetry: {
  17498. maxNumRetry: 4,
  17499. retryDelayMs: 0,
  17500. maxRetryDelayMs: 0
  17501. },
  17502. errorRetry: {
  17503. maxNumRetry: 6,
  17504. retryDelayMs: 1000,
  17505. maxRetryDelayMs: 8000
  17506. }
  17507. }
  17508. },
  17509. steeringManifestLoadPolicy: {
  17510. default: {
  17511. maxTimeToFirstByteMs: 10000,
  17512. maxLoadTimeMs: 20000,
  17513. timeoutRetry: {
  17514. maxNumRetry: 2,
  17515. retryDelayMs: 0,
  17516. maxRetryDelayMs: 0
  17517. },
  17518. errorRetry: {
  17519. maxNumRetry: 1,
  17520. retryDelayMs: 1000,
  17521. maxRetryDelayMs: 8000
  17522. }
  17523. }
  17524. },
  17525. interstitialAssetListLoadPolicy: {
  17526. default: defaultLoadPolicy
  17527. },
  17528. // These default settings are deprecated in favor of the above policies
  17529. // and are maintained for backwards compatibility
  17530. manifestLoadingTimeOut: 10000,
  17531. manifestLoadingMaxRetry: 1,
  17532. manifestLoadingRetryDelay: 1000,
  17533. manifestLoadingMaxRetryTimeout: 64000,
  17534. levelLoadingTimeOut: 10000,
  17535. levelLoadingMaxRetry: 4,
  17536. levelLoadingRetryDelay: 1000,
  17537. levelLoadingMaxRetryTimeout: 64000,
  17538. fragLoadingTimeOut: 20000,
  17539. fragLoadingMaxRetry: 6,
  17540. fragLoadingRetryDelay: 1000,
  17541. fragLoadingMaxRetryTimeout: 64000
  17542. }, timelineConfig()), {}, {
  17543. subtitleStreamController: undefined,
  17544. subtitleTrackController: undefined,
  17545. timelineController: undefined,
  17546. audioStreamController: undefined,
  17547. audioTrackController: undefined,
  17548. emeController: undefined,
  17549. cmcdController: undefined,
  17550. contentSteeringController: ContentSteeringController ,
  17551. interstitialsController: undefined
  17552. });
  17553. function timelineConfig() {
  17554. return {
  17555. cueHandler: Cues,
  17556. // used by timeline-controller
  17557. enableWebVTT: false,
  17558. // used by timeline-controller
  17559. enableIMSC1: false,
  17560. // used by timeline-controller
  17561. enableCEA708Captions: false,
  17562. // used by timeline-controller
  17563. captionsTextTrack1Label: 'English',
  17564. // used by timeline-controller
  17565. captionsTextTrack1LanguageCode: 'en',
  17566. // used by timeline-controller
  17567. captionsTextTrack2Label: 'Spanish',
  17568. // used by timeline-controller
  17569. captionsTextTrack2LanguageCode: 'es',
  17570. // used by timeline-controller
  17571. captionsTextTrack3Label: 'Unknown CC',
  17572. // used by timeline-controller
  17573. captionsTextTrack3LanguageCode: '',
  17574. // used by timeline-controller
  17575. captionsTextTrack4Label: 'Unknown CC',
  17576. // used by timeline-controller
  17577. captionsTextTrack4LanguageCode: '',
  17578. // used by timeline-controller
  17579. renderTextTracksNatively: true
  17580. };
  17581. }
  17582. /**
  17583. * @ignore
  17584. */
  17585. function mergeConfig(defaultConfig, userConfig, logger) {
  17586. if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
  17587. throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  17588. }
  17589. if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
  17590. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  17591. }
  17592. if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
  17593. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  17594. }
  17595. const defaultsCopy = deepCpy(defaultConfig);
  17596. // Backwards compatibility with deprecated config values
  17597. const deprecatedSettingTypes = ['manifest', 'level', 'frag'];
  17598. const deprecatedSettings = ['TimeOut', 'MaxRetry', 'RetryDelay', 'MaxRetryTimeout'];
  17599. deprecatedSettingTypes.forEach(type => {
  17600. const policyName = `${type === 'level' ? 'playlist' : type}LoadPolicy`;
  17601. const policyNotSet = userConfig[policyName] === undefined;
  17602. const report = [];
  17603. deprecatedSettings.forEach(setting => {
  17604. const deprecatedSetting = `${type}Loading${setting}`;
  17605. const value = userConfig[deprecatedSetting];
  17606. if (value !== undefined && policyNotSet) {
  17607. report.push(deprecatedSetting);
  17608. const settings = defaultsCopy[policyName].default;
  17609. userConfig[policyName] = {
  17610. default: settings
  17611. };
  17612. switch (setting) {
  17613. case 'TimeOut':
  17614. settings.maxLoadTimeMs = value;
  17615. settings.maxTimeToFirstByteMs = value;
  17616. break;
  17617. case 'MaxRetry':
  17618. settings.errorRetry.maxNumRetry = value;
  17619. settings.timeoutRetry.maxNumRetry = value;
  17620. break;
  17621. case 'RetryDelay':
  17622. settings.errorRetry.retryDelayMs = value;
  17623. settings.timeoutRetry.retryDelayMs = value;
  17624. break;
  17625. case 'MaxRetryTimeout':
  17626. settings.errorRetry.maxRetryDelayMs = value;
  17627. settings.timeoutRetry.maxRetryDelayMs = value;
  17628. break;
  17629. }
  17630. }
  17631. });
  17632. if (report.length) {
  17633. logger.warn(`hls.js config: "${report.join('", "')}" setting(s) are deprecated, use "${policyName}": ${stringify(userConfig[policyName])}`);
  17634. }
  17635. });
  17636. return _objectSpread2(_objectSpread2({}, defaultsCopy), userConfig);
  17637. }
  17638. function deepCpy(obj) {
  17639. if (obj && typeof obj === 'object') {
  17640. if (Array.isArray(obj)) {
  17641. return obj.map(deepCpy);
  17642. }
  17643. return Object.keys(obj).reduce((result, key) => {
  17644. result[key] = deepCpy(obj[key]);
  17645. return result;
  17646. }, {});
  17647. }
  17648. return obj;
  17649. }
  17650. /**
  17651. * @ignore
  17652. */
  17653. function enableStreamingMode(config, logger) {
  17654. const currentLoader = config.loader;
  17655. if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {
  17656. // If a developer has configured their own loader, respect that choice
  17657. logger.log('[config]: Custom loader detected, cannot enable progressive streaming');
  17658. config.progressive = false;
  17659. } else {
  17660. const canStreamProgressively = fetchSupported();
  17661. if (canStreamProgressively) {
  17662. config.loader = FetchLoader;
  17663. config.progressive = true;
  17664. config.enableSoftwareAES = true;
  17665. logger.log('[config]: Progressive streaming enabled, using FetchLoader');
  17666. }
  17667. }
  17668. }
  17669. function addEventListener(el, type, listener) {
  17670. removeEventListener(el, type, listener);
  17671. el.addEventListener(type, listener);
  17672. }
  17673. function removeEventListener(el, type, listener) {
  17674. el.removeEventListener(type, listener);
  17675. }
  17676. const MAX_START_GAP_JUMP = 2.0;
  17677. const SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
  17678. const SKIP_BUFFER_RANGE_START = 0.05;
  17679. const TICK_INTERVAL$1 = 100;
  17680. class GapController extends TaskLoop {
  17681. constructor(hls, fragmentTracker) {
  17682. super('gap-controller', hls.logger);
  17683. this.hls = null;
  17684. this.fragmentTracker = null;
  17685. this.media = null;
  17686. this.mediaSource = void 0;
  17687. this.nudgeRetry = 0;
  17688. this.stallReported = false;
  17689. this.stalled = null;
  17690. this.moved = false;
  17691. this.seeking = false;
  17692. this.buffered = {};
  17693. this.lastCurrentTime = 0;
  17694. this.ended = 0;
  17695. this.waiting = 0;
  17696. this.onMediaPlaying = () => {
  17697. this.ended = 0;
  17698. this.waiting = 0;
  17699. };
  17700. this.onMediaWaiting = () => {
  17701. var _this$media;
  17702. if ((_this$media = this.media) != null && _this$media.seeking) {
  17703. return;
  17704. }
  17705. this.waiting = self.performance.now();
  17706. this.tick();
  17707. };
  17708. this.onMediaEnded = () => {
  17709. if (this.hls) {
  17710. var _this$media2;
  17711. // ended is set when triggering MEDIA_ENDED so that we do not trigger it again on stall or on tick with media.ended
  17712. this.ended = ((_this$media2 = this.media) == null ? void 0 : _this$media2.currentTime) || 1;
  17713. this.hls.trigger(Events.MEDIA_ENDED, {
  17714. stalled: false
  17715. });
  17716. }
  17717. };
  17718. this.hls = hls;
  17719. this.fragmentTracker = fragmentTracker;
  17720. this.registerListeners();
  17721. }
  17722. registerListeners() {
  17723. const {
  17724. hls
  17725. } = this;
  17726. if (hls) {
  17727. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  17728. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  17729. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  17730. }
  17731. }
  17732. unregisterListeners() {
  17733. const {
  17734. hls
  17735. } = this;
  17736. if (hls) {
  17737. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  17738. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  17739. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  17740. }
  17741. }
  17742. destroy() {
  17743. super.destroy();
  17744. this.unregisterListeners();
  17745. this.media = this.hls = this.fragmentTracker = null;
  17746. this.mediaSource = undefined;
  17747. }
  17748. onMediaAttached(event, data) {
  17749. this.setInterval(TICK_INTERVAL$1);
  17750. this.mediaSource = data.mediaSource;
  17751. const media = this.media = data.media;
  17752. addEventListener(media, 'playing', this.onMediaPlaying);
  17753. addEventListener(media, 'waiting', this.onMediaWaiting);
  17754. addEventListener(media, 'ended', this.onMediaEnded);
  17755. }
  17756. onMediaDetaching(event, data) {
  17757. this.clearInterval();
  17758. const {
  17759. media
  17760. } = this;
  17761. if (media) {
  17762. removeEventListener(media, 'playing', this.onMediaPlaying);
  17763. removeEventListener(media, 'waiting', this.onMediaWaiting);
  17764. removeEventListener(media, 'ended', this.onMediaEnded);
  17765. this.media = null;
  17766. }
  17767. this.mediaSource = undefined;
  17768. }
  17769. onBufferAppended(event, data) {
  17770. this.buffered = data.timeRanges;
  17771. }
  17772. get hasBuffered() {
  17773. return Object.keys(this.buffered).length > 0;
  17774. }
  17775. tick() {
  17776. var _this$media3;
  17777. if (!((_this$media3 = this.media) != null && _this$media3.readyState) || !this.hasBuffered) {
  17778. return;
  17779. }
  17780. const currentTime = this.media.currentTime;
  17781. this.poll(currentTime, this.lastCurrentTime);
  17782. this.lastCurrentTime = currentTime;
  17783. }
  17784. /**
  17785. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  17786. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  17787. *
  17788. * @param lastCurrentTime - Previously read playhead position
  17789. */
  17790. poll(currentTime, lastCurrentTime) {
  17791. var _this$hls, _this$hls2;
  17792. const config = (_this$hls = this.hls) == null ? void 0 : _this$hls.config;
  17793. if (!config) {
  17794. return;
  17795. }
  17796. const media = this.media;
  17797. if (!media) {
  17798. return;
  17799. }
  17800. const {
  17801. seeking
  17802. } = media;
  17803. const seeked = this.seeking && !seeking;
  17804. const beginSeek = !this.seeking && seeking;
  17805. const pausedEndedOrHalted = media.paused && !seeking || media.ended || media.playbackRate === 0;
  17806. this.seeking = seeking;
  17807. // The playhead is moving, no-op
  17808. if (currentTime !== lastCurrentTime) {
  17809. if (lastCurrentTime) {
  17810. this.ended = 0;
  17811. }
  17812. this.moved = true;
  17813. if (!seeking) {
  17814. this.nudgeRetry = 0;
  17815. // When crossing between buffered video time ranges, but not audio, flush pipeline with seek (Chrome)
  17816. if (config.nudgeOnVideoHole && !pausedEndedOrHalted && currentTime > lastCurrentTime) {
  17817. this.nudgeOnVideoHole(currentTime, lastCurrentTime);
  17818. }
  17819. }
  17820. if (this.waiting === 0) {
  17821. this.stallResolved(currentTime);
  17822. }
  17823. return;
  17824. }
  17825. // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
  17826. if (beginSeek || seeked) {
  17827. if (seeked) {
  17828. this.stallResolved(currentTime);
  17829. }
  17830. return;
  17831. }
  17832. // The playhead should not be moving
  17833. if (pausedEndedOrHalted) {
  17834. this.nudgeRetry = 0;
  17835. this.stallResolved(currentTime);
  17836. // Fire MEDIA_ENDED to workaround event not being dispatched by browser
  17837. if (!this.ended && media.ended && this.hls) {
  17838. this.ended = currentTime || 1;
  17839. this.hls.trigger(Events.MEDIA_ENDED, {
  17840. stalled: false
  17841. });
  17842. }
  17843. return;
  17844. }
  17845. if (!BufferHelper.getBuffered(media).length) {
  17846. this.nudgeRetry = 0;
  17847. return;
  17848. }
  17849. // Resolve stalls at buffer holes using the main buffer, whose ranges are the intersections of the A/V sourcebuffers
  17850. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  17851. const nextStart = bufferInfo.nextStart || 0;
  17852. const fragmentTracker = this.fragmentTracker;
  17853. if (seeking && fragmentTracker && this.hls) {
  17854. // Is there a fragment loading/parsing/appending before currentTime?
  17855. const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, currentTime);
  17856. // Waiting for seeking in a buffered range to complete
  17857. const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;
  17858. // Next buffered range is too far ahead to jump to while still seeking
  17859. const noBufferHole = !nextStart || inFlightDependency || nextStart - currentTime > MAX_START_GAP_JUMP && !fragmentTracker.getPartialFragment(currentTime);
  17860. if (hasEnoughBuffer || noBufferHole) {
  17861. return;
  17862. }
  17863. // Reset moved state when seeking to a point in or before a gap/hole
  17864. this.moved = false;
  17865. }
  17866. // Skip start gaps if we haven't played, but the last poll detected the start of a stall
  17867. // The addition poll gives the browser a chance to jump the gap for us
  17868. const levelDetails = (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.latestLevelDetails;
  17869. if (!this.moved && this.stalled !== null && fragmentTracker) {
  17870. // There is no playable buffer (seeked, waiting for buffer)
  17871. const isBuffered = bufferInfo.len > 0;
  17872. if (!isBuffered && !nextStart) {
  17873. return;
  17874. }
  17875. // Jump start gaps within jump threshold
  17876. const startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
  17877. // When joining a live stream with audio tracks, account for live playlist window sliding by allowing
  17878. // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment
  17879. // that begins over 1 target duration after the video start position.
  17880. const isLive = !!(levelDetails != null && levelDetails.live);
  17881. const maxStartGapJump = isLive ? levelDetails.targetduration * 2 : MAX_START_GAP_JUMP;
  17882. const partialOrGap = fragmentTracker.getPartialFragment(currentTime);
  17883. if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {
  17884. if (!media.paused) {
  17885. this._trySkipBufferHole(partialOrGap);
  17886. }
  17887. return;
  17888. }
  17889. }
  17890. // Start tracking stall time
  17891. const detectStallWithCurrentTimeMs = config.detectStallWithCurrentTimeMs;
  17892. const tnow = self.performance.now();
  17893. const tWaiting = this.waiting;
  17894. let stalled = this.stalled;
  17895. if (stalled === null) {
  17896. // Use time of recent "waiting" event
  17897. if (tWaiting > 0 && tnow - tWaiting < detectStallWithCurrentTimeMs) {
  17898. stalled = this.stalled = tWaiting;
  17899. } else {
  17900. this.stalled = tnow;
  17901. return;
  17902. }
  17903. }
  17904. const stalledDuration = tnow - stalled;
  17905. if (!seeking && (stalledDuration >= detectStallWithCurrentTimeMs || tWaiting) && this.hls) {
  17906. var _this$mediaSource;
  17907. // Dispatch MEDIA_ENDED when media.ended/ended event is not signalled at end of stream
  17908. 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) {
  17909. if (this.ended) {
  17910. return;
  17911. }
  17912. this.ended = currentTime || 1;
  17913. this.hls.trigger(Events.MEDIA_ENDED, {
  17914. stalled: true
  17915. });
  17916. return;
  17917. }
  17918. // Report stalling after trying to fix
  17919. this._reportStall(bufferInfo);
  17920. if (!this.media || !this.hls) {
  17921. return;
  17922. }
  17923. }
  17924. const bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  17925. this._tryFixBufferStall(bufferedWithHoles, stalledDuration, currentTime);
  17926. }
  17927. stallResolved(currentTime) {
  17928. const stalled = this.stalled;
  17929. if (stalled && this.hls) {
  17930. this.stalled = null;
  17931. // The playhead is now moving, but was previously stalled
  17932. if (this.stallReported) {
  17933. const stalledDuration = self.performance.now() - stalled;
  17934. this.log(`playback not stuck anymore @${currentTime}, after ${Math.round(stalledDuration)}ms`);
  17935. this.stallReported = false;
  17936. this.waiting = 0;
  17937. this.hls.trigger(Events.STALL_RESOLVED, {});
  17938. }
  17939. }
  17940. }
  17941. nudgeOnVideoHole(currentTime, lastCurrentTime) {
  17942. var _this$buffered$audio;
  17943. // Chrome will play one second past a hole in video buffered time ranges without rendering any video from the subsequent range and then stall as long as audio is buffered:
  17944. // https://github.com/video-dev/hls.js/issues/5631
  17945. // https://issues.chromium.org/issues/40280613#comment10
  17946. // Detect the potential for this situation and proactively seek to flush the video pipeline once the playhead passes the start of the video hole.
  17947. // When there are audio and video buffers and currentTime is past the end of the first video buffered range...
  17948. const videoSourceBuffered = this.buffered.video;
  17949. 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)) {
  17950. // and audio is buffered at the playhead
  17951. const audioBufferInfo = BufferHelper.bufferedInfo(BufferHelper.timeRangesToArray(this.buffered.audio), currentTime, 0);
  17952. if (audioBufferInfo.len > 1 && lastCurrentTime >= audioBufferInfo.start) {
  17953. const videoTimes = BufferHelper.timeRangesToArray(videoSourceBuffered);
  17954. const lastBufferedIndex = BufferHelper.bufferedInfo(videoTimes, lastCurrentTime, 0).bufferedIndex;
  17955. // nudge when crossing into another video buffered range (hole).
  17956. if (lastBufferedIndex > -1 && lastBufferedIndex < videoTimes.length - 1) {
  17957. const bufferedIndex = BufferHelper.bufferedInfo(videoTimes, currentTime, 0).bufferedIndex;
  17958. const holeStart = videoTimes[lastBufferedIndex].end;
  17959. const holeEnd = videoTimes[lastBufferedIndex + 1].start;
  17960. if ((bufferedIndex === -1 || bufferedIndex > lastBufferedIndex) && holeEnd - holeStart < 1 &&
  17961. // `maxBufferHole` may be too small and setting it to 0 should not disable this feature
  17962. currentTime - holeStart < 2) {
  17963. const error = new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${currentTime} hole: ${holeStart} -> ${holeEnd} buffered index: ${bufferedIndex}`);
  17964. this.warn(error.message);
  17965. // Magic number to flush the pipeline without interuption to audio playback:
  17966. this.media.currentTime += 0.000001;
  17967. const frag = this.fragmentTracker.getPartialFragment(currentTime) || undefined;
  17968. const bufferInfo = BufferHelper.bufferInfo(this.media, currentTime, 0);
  17969. this.hls.trigger(Events.ERROR, {
  17970. type: ErrorTypes.MEDIA_ERROR,
  17971. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  17972. fatal: false,
  17973. error,
  17974. reason: error.message,
  17975. frag,
  17976. buffer: bufferInfo.len,
  17977. bufferInfo
  17978. });
  17979. }
  17980. }
  17981. }
  17982. }
  17983. }
  17984. /**
  17985. * Detects and attempts to fix known buffer stalling issues.
  17986. * @param bufferInfo - The properties of the current buffer.
  17987. * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
  17988. * @private
  17989. */
  17990. _tryFixBufferStall(bufferInfo, stalledDurationMs, currentTime) {
  17991. var _this$hls3, _this$hls4;
  17992. const {
  17993. fragmentTracker,
  17994. media
  17995. } = this;
  17996. const config = (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.config;
  17997. if (!media || !fragmentTracker || !config) {
  17998. return;
  17999. }
  18000. const levelDetails = (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.latestLevelDetails;
  18001. const partial = fragmentTracker.getPartialFragment(currentTime);
  18002. if (partial || levelDetails != null && levelDetails.live && currentTime < levelDetails.fragmentStart) {
  18003. // Try to skip over the buffer hole caused by a partial fragment
  18004. // This method isn't limited by the size of the gap between buffered ranges
  18005. const targetTime = this._trySkipBufferHole(partial);
  18006. // we return here in this case, meaning
  18007. // the branch below only executes when we haven't seeked to a new position
  18008. if (targetTime || !this.media) {
  18009. return;
  18010. }
  18011. }
  18012. // if we haven't had to skip over a buffer hole of a partial fragment
  18013. // we may just have to "nudge" the playlist as the browser decoding/rendering engine
  18014. // needs to cross some sort of threshold covering all source-buffers content
  18015. // to start playing properly.
  18016. const bufferedRanges = bufferInfo.buffered;
  18017. const adjacentTraversal = this.adjacentTraversal(bufferInfo, currentTime);
  18018. if ((bufferedRanges && bufferedRanges.length > 1 && bufferInfo.len > config.maxBufferHole || bufferInfo.nextStart && (bufferInfo.nextStart - currentTime < config.maxBufferHole || adjacentTraversal)) && (stalledDurationMs > config.highBufferWatchdogPeriod * 1000 || this.waiting)) {
  18019. this.warn('Trying to nudge playhead over buffer-hole');
  18020. // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
  18021. // We only try to jump the hole if it's under the configured size
  18022. this._tryNudgeBuffer(bufferInfo);
  18023. }
  18024. }
  18025. adjacentTraversal(bufferInfo, currentTime) {
  18026. const fragmentTracker = this.fragmentTracker;
  18027. const nextStart = bufferInfo.nextStart;
  18028. if (fragmentTracker && nextStart) {
  18029. const current = fragmentTracker.getFragAtPos(currentTime, PlaylistLevelType.MAIN);
  18030. const next = fragmentTracker.getFragAtPos(nextStart, PlaylistLevelType.MAIN);
  18031. if (current && next) {
  18032. return next.sn - current.sn < 2;
  18033. }
  18034. }
  18035. return false;
  18036. }
  18037. /**
  18038. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  18039. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  18040. * @private
  18041. */
  18042. _reportStall(bufferInfo) {
  18043. const {
  18044. hls,
  18045. media,
  18046. stallReported,
  18047. stalled
  18048. } = this;
  18049. if (!stallReported && stalled !== null && media && hls) {
  18050. // Report stalled error once
  18051. this.stallReported = true;
  18052. const error = new Error(`Playback stalling at @${media.currentTime} due to low buffer (${stringify(bufferInfo)})`);
  18053. this.warn(error.message);
  18054. hls.trigger(Events.ERROR, {
  18055. type: ErrorTypes.MEDIA_ERROR,
  18056. details: ErrorDetails.BUFFER_STALLED_ERROR,
  18057. fatal: false,
  18058. error,
  18059. buffer: bufferInfo.len,
  18060. bufferInfo,
  18061. stalled: {
  18062. start: stalled
  18063. }
  18064. });
  18065. }
  18066. }
  18067. /**
  18068. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  18069. * @param partial - The partial fragment found at the current time (where playback is stalling).
  18070. * @private
  18071. */
  18072. _trySkipBufferHole(partial) {
  18073. var _this$hls5;
  18074. const {
  18075. fragmentTracker,
  18076. media
  18077. } = this;
  18078. const config = (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.config;
  18079. if (!media || !fragmentTracker || !config) {
  18080. return 0;
  18081. }
  18082. // Check if currentTime is between unbuffered regions of partial fragments
  18083. const currentTime = media.currentTime;
  18084. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  18085. const startTime = currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;
  18086. if (startTime && this.hls) {
  18087. const bufferStarved = bufferInfo.len <= config.maxBufferHole;
  18088. const waiting = bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;
  18089. const gapLength = startTime - currentTime;
  18090. if (gapLength > 0 && (bufferStarved || waiting)) {
  18091. // Only allow large gaps to be skipped if it is a start gap, or all fragments in skip range are partial
  18092. if (gapLength > config.maxBufferHole) {
  18093. let startGap = false;
  18094. if (currentTime === 0) {
  18095. const startFrag = fragmentTracker.getAppendedFrag(0, PlaylistLevelType.MAIN);
  18096. if (startFrag && startTime < startFrag.end) {
  18097. startGap = true;
  18098. }
  18099. }
  18100. if (!startGap) {
  18101. const startProvisioned = partial || fragmentTracker.getAppendedFrag(currentTime, PlaylistLevelType.MAIN);
  18102. if (startProvisioned) {
  18103. var _this$hls$loadLevelOb;
  18104. // Do not seek when selected variant playlist is unloaded
  18105. if (!((_this$hls$loadLevelOb = this.hls.loadLevelObj) != null && _this$hls$loadLevelOb.details)) {
  18106. return 0;
  18107. }
  18108. // Do not seek when required fragments are inflight or appending
  18109. const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, startTime);
  18110. if (inFlightDependency) {
  18111. return 0;
  18112. }
  18113. // Do not seek if we can't walk tracked fragments to end of gap
  18114. let moreToLoad = false;
  18115. let pos = startProvisioned.end;
  18116. while (pos < startTime) {
  18117. const provisioned = fragmentTracker.getAppendedFrag(pos, PlaylistLevelType.MAIN) || fragmentTracker.getPartialFragment(pos);
  18118. if (provisioned) {
  18119. pos += provisioned.duration;
  18120. } else {
  18121. moreToLoad = true;
  18122. break;
  18123. }
  18124. }
  18125. if (moreToLoad) {
  18126. return 0;
  18127. }
  18128. }
  18129. }
  18130. }
  18131. const targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
  18132. this.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`);
  18133. this.moved = true;
  18134. media.currentTime = targetTime;
  18135. if (!(partial != null && partial.gap)) {
  18136. const error = new Error(`fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`);
  18137. this.hls.trigger(Events.ERROR, {
  18138. type: ErrorTypes.MEDIA_ERROR,
  18139. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  18140. fatal: false,
  18141. error,
  18142. reason: error.message,
  18143. frag: partial || undefined,
  18144. buffer: bufferInfo.len,
  18145. bufferInfo
  18146. });
  18147. }
  18148. return targetTime;
  18149. }
  18150. }
  18151. return 0;
  18152. }
  18153. /**
  18154. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  18155. * @private
  18156. */
  18157. _tryNudgeBuffer(bufferInfo) {
  18158. const {
  18159. hls,
  18160. media,
  18161. nudgeRetry
  18162. } = this;
  18163. const config = hls == null ? void 0 : hls.config;
  18164. if (!media || !config) {
  18165. return 0;
  18166. }
  18167. const currentTime = media.currentTime;
  18168. this.nudgeRetry++;
  18169. if (nudgeRetry < config.nudgeMaxRetry) {
  18170. const targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;
  18171. // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
  18172. const error = new Error(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`);
  18173. this.warn(error.message);
  18174. media.currentTime = targetTime;
  18175. hls.trigger(Events.ERROR, {
  18176. type: ErrorTypes.MEDIA_ERROR,
  18177. details: ErrorDetails.BUFFER_NUDGE_ON_STALL,
  18178. error,
  18179. fatal: false,
  18180. buffer: bufferInfo.len,
  18181. bufferInfo
  18182. });
  18183. } else {
  18184. const error = new Error(`Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`);
  18185. this.error(error.message);
  18186. hls.trigger(Events.ERROR, {
  18187. type: ErrorTypes.MEDIA_ERROR,
  18188. details: ErrorDetails.BUFFER_STALLED_ERROR,
  18189. error,
  18190. fatal: true,
  18191. buffer: bufferInfo.len,
  18192. bufferInfo
  18193. });
  18194. }
  18195. }
  18196. }
  18197. function getInFlightDependency(inFlightFragments, currentTime) {
  18198. const main = inFlight(inFlightFragments.main);
  18199. if (main && main.start <= currentTime) {
  18200. return main;
  18201. }
  18202. const audio = inFlight(inFlightFragments.audio);
  18203. if (audio && audio.start <= currentTime) {
  18204. return audio;
  18205. }
  18206. return null;
  18207. }
  18208. function inFlight(inFlightData) {
  18209. if (!inFlightData) {
  18210. return null;
  18211. }
  18212. switch (inFlightData.state) {
  18213. case State.IDLE:
  18214. case State.STOPPED:
  18215. case State.ENDED:
  18216. case State.ERROR:
  18217. return null;
  18218. }
  18219. return inFlightData.frag;
  18220. }
  18221. function sendAddTrackEvent(track, videoEl) {
  18222. let event;
  18223. try {
  18224. event = new Event('addtrack');
  18225. } catch (err) {
  18226. // for IE11
  18227. event = document.createEvent('Event');
  18228. event.initEvent('addtrack', false, false);
  18229. }
  18230. event.track = track;
  18231. videoEl.dispatchEvent(event);
  18232. }
  18233. function clearCurrentCues(track, enterHandler) {
  18234. // When track.mode is disabled, track.cues will be null.
  18235. // To guarantee the removal of cues, we need to temporarily
  18236. // change the mode to hidden
  18237. const mode = track.mode;
  18238. if (mode === 'disabled') {
  18239. track.mode = 'hidden';
  18240. }
  18241. if (track.cues) {
  18242. for (let i = track.cues.length; i--;) {
  18243. if (enterHandler) {
  18244. track.cues[i].removeEventListener('enter', enterHandler);
  18245. }
  18246. track.removeCue(track.cues[i]);
  18247. }
  18248. }
  18249. if (mode === 'disabled') {
  18250. track.mode = mode;
  18251. }
  18252. }
  18253. function removeCuesInRange(track, start, end, predicate) {
  18254. const mode = track.mode;
  18255. if (mode === 'disabled') {
  18256. track.mode = 'hidden';
  18257. }
  18258. if (track.cues && track.cues.length > 0) {
  18259. const cues = getCuesInRange(track.cues, start, end);
  18260. for (let i = 0; i < cues.length; i++) {
  18261. if (!predicate || predicate(cues[i])) {
  18262. track.removeCue(cues[i]);
  18263. }
  18264. }
  18265. }
  18266. if (mode === 'disabled') {
  18267. track.mode = mode;
  18268. }
  18269. }
  18270. // Find first cue starting at or after given time.
  18271. // Modified version of binary search O(log(n)).
  18272. function getFirstCueIndexFromTime(cues, time) {
  18273. // If first cue starts at or after time, start there
  18274. if (time <= cues[0].startTime) {
  18275. return 0;
  18276. }
  18277. // If the last cue ends before time there is no overlap
  18278. const len = cues.length - 1;
  18279. if (time > cues[len].endTime) {
  18280. return -1;
  18281. }
  18282. let left = 0;
  18283. let right = len;
  18284. let mid;
  18285. while (left <= right) {
  18286. mid = Math.floor((right + left) / 2);
  18287. if (time < cues[mid].startTime) {
  18288. right = mid - 1;
  18289. } else if (time > cues[mid].startTime && left < len) {
  18290. left = mid + 1;
  18291. } else {
  18292. // If it's not lower or higher, it must be equal.
  18293. return mid;
  18294. }
  18295. }
  18296. // At this point, left and right have swapped.
  18297. // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
  18298. return cues[left].startTime - time < time - cues[right].startTime ? left : right;
  18299. }
  18300. function getCuesInRange(cues, start, end) {
  18301. const cuesFound = [];
  18302. const firstCueInRange = getFirstCueIndexFromTime(cues, start);
  18303. if (firstCueInRange > -1) {
  18304. for (let i = firstCueInRange, len = cues.length; i < len; i++) {
  18305. const cue = cues[i];
  18306. if (cue.startTime >= start && cue.endTime <= end) {
  18307. cuesFound.push(cue);
  18308. } else if (cue.startTime > end) {
  18309. return cuesFound;
  18310. }
  18311. }
  18312. }
  18313. return cuesFound;
  18314. }
  18315. const MIN_CUE_DURATION = 0.25;
  18316. function getCueClass() {
  18317. if (typeof self === 'undefined') return undefined;
  18318. return self.VTTCue || self.TextTrackCue;
  18319. }
  18320. function createCueWithDataFields(Cue, startTime, endTime, data, type) {
  18321. let cue = new Cue(startTime, endTime, '');
  18322. try {
  18323. cue.value = data;
  18324. if (type) {
  18325. cue.type = type;
  18326. }
  18327. } catch (e) {
  18328. cue = new Cue(startTime, endTime, stringify(type ? _objectSpread2({
  18329. type
  18330. }, data) : data));
  18331. }
  18332. return cue;
  18333. }
  18334. // VTTCue latest draft allows an infinite duration, fallback
  18335. // to MAX_VALUE if necessary
  18336. const MAX_CUE_ENDTIME = (() => {
  18337. const Cue = getCueClass();
  18338. try {
  18339. Cue && new Cue(0, Number.POSITIVE_INFINITY, '');
  18340. } catch (e) {
  18341. return Number.MAX_VALUE;
  18342. }
  18343. return Number.POSITIVE_INFINITY;
  18344. })();
  18345. class ID3TrackController {
  18346. constructor(hls) {
  18347. this.hls = void 0;
  18348. this.id3Track = null;
  18349. this.media = null;
  18350. this.dateRangeCuesAppended = {};
  18351. this.removeCues = true;
  18352. this.onEventCueEnter = () => {
  18353. if (!this.hls) {
  18354. return;
  18355. }
  18356. this.hls.trigger(Events.EVENT_CUE_ENTER, {});
  18357. };
  18358. this.hls = hls;
  18359. this._registerListeners();
  18360. }
  18361. destroy() {
  18362. this._unregisterListeners();
  18363. this.id3Track = null;
  18364. this.media = null;
  18365. this.dateRangeCuesAppended = {};
  18366. // @ts-ignore
  18367. this.hls = this.onEventCueEnter = null;
  18368. }
  18369. _registerListeners() {
  18370. const {
  18371. hls
  18372. } = this;
  18373. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  18374. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18375. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18376. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18377. hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  18378. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  18379. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  18380. hls.on(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  18381. }
  18382. _unregisterListeners() {
  18383. const {
  18384. hls
  18385. } = this;
  18386. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  18387. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18388. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18389. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18390. hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  18391. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  18392. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  18393. hls.off(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  18394. }
  18395. // Add ID3 metatadata text track.
  18396. onMediaAttaching(event, data) {
  18397. var _data$overrides;
  18398. this.media = data.media;
  18399. if (((_data$overrides = data.overrides) == null ? void 0 : _data$overrides.cueRemoval) === false) {
  18400. this.removeCues = false;
  18401. }
  18402. }
  18403. onMediaAttached() {
  18404. const details = this.hls.latestLevelDetails;
  18405. if (details) {
  18406. this.updateDateRangeCues(details);
  18407. }
  18408. }
  18409. onMediaDetaching(event, data) {
  18410. this.media = null;
  18411. const transferringMedia = !!data.transferMedia;
  18412. if (transferringMedia) {
  18413. return;
  18414. }
  18415. if (this.id3Track) {
  18416. if (this.removeCues) {
  18417. clearCurrentCues(this.id3Track, this.onEventCueEnter);
  18418. }
  18419. this.id3Track = null;
  18420. }
  18421. this.dateRangeCuesAppended = {};
  18422. }
  18423. onManifestLoading() {
  18424. this.dateRangeCuesAppended = {};
  18425. }
  18426. createTrack(media) {
  18427. const track = this.getID3Track(media.textTracks);
  18428. track.mode = 'hidden';
  18429. return track;
  18430. }
  18431. getID3Track(textTracks) {
  18432. if (!this.media) {
  18433. return;
  18434. }
  18435. for (let i = 0; i < textTracks.length; i++) {
  18436. const textTrack = textTracks[i];
  18437. if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
  18438. // send 'addtrack' when reusing the textTrack for metadata,
  18439. // same as what we do for captions
  18440. sendAddTrackEvent(textTrack, this.media);
  18441. return textTrack;
  18442. }
  18443. }
  18444. return this.media.addTextTrack('metadata', 'id3');
  18445. }
  18446. onFragParsingMetadata(event, data) {
  18447. if (!this.media) {
  18448. return;
  18449. }
  18450. const {
  18451. hls: {
  18452. config: {
  18453. enableEmsgMetadataCues,
  18454. enableID3MetadataCues
  18455. }
  18456. }
  18457. } = this;
  18458. if (!enableEmsgMetadataCues && !enableID3MetadataCues) {
  18459. return;
  18460. }
  18461. const {
  18462. samples
  18463. } = data;
  18464. // create track dynamically
  18465. if (!this.id3Track) {
  18466. this.id3Track = this.createTrack(this.media);
  18467. }
  18468. const Cue = getCueClass();
  18469. if (!Cue) {
  18470. return;
  18471. }
  18472. for (let i = 0; i < samples.length; i++) {
  18473. const type = samples[i].type;
  18474. if (type === MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) {
  18475. continue;
  18476. }
  18477. const frames = getId3Frames(samples[i].data);
  18478. if (frames) {
  18479. const startTime = samples[i].pts;
  18480. let endTime = startTime + samples[i].duration;
  18481. if (endTime > MAX_CUE_ENDTIME) {
  18482. endTime = MAX_CUE_ENDTIME;
  18483. }
  18484. const timeDiff = endTime - startTime;
  18485. if (timeDiff <= 0) {
  18486. endTime = startTime + MIN_CUE_DURATION;
  18487. }
  18488. for (let j = 0; j < frames.length; j++) {
  18489. const frame = frames[j];
  18490. // Safari doesn't put the timestamp frame in the TextTrack
  18491. if (!isId3TimestampFrame(frame)) {
  18492. // add a bounds to any unbounded cues
  18493. this.updateId3CueEnds(startTime, type);
  18494. const cue = createCueWithDataFields(Cue, startTime, endTime, frame, type);
  18495. if (cue) {
  18496. this.id3Track.addCue(cue);
  18497. }
  18498. }
  18499. }
  18500. }
  18501. }
  18502. }
  18503. updateId3CueEnds(startTime, type) {
  18504. var _this$id3Track;
  18505. const cues = (_this$id3Track = this.id3Track) == null ? void 0 : _this$id3Track.cues;
  18506. if (cues) {
  18507. for (let i = cues.length; i--;) {
  18508. const cue = cues[i];
  18509. if (cue.type === type && cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {
  18510. cue.endTime = startTime;
  18511. }
  18512. }
  18513. }
  18514. }
  18515. onBufferFlushing(event, {
  18516. startOffset,
  18517. endOffset,
  18518. type
  18519. }) {
  18520. const {
  18521. id3Track,
  18522. hls
  18523. } = this;
  18524. if (!hls) {
  18525. return;
  18526. }
  18527. const {
  18528. config: {
  18529. enableEmsgMetadataCues,
  18530. enableID3MetadataCues
  18531. }
  18532. } = hls;
  18533. if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {
  18534. let predicate;
  18535. if (type === 'audio') {
  18536. predicate = cue => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues;
  18537. } else if (type === 'video') {
  18538. predicate = cue => cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  18539. } else {
  18540. predicate = cue => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  18541. }
  18542. removeCuesInRange(id3Track, startOffset, endOffset, predicate);
  18543. }
  18544. }
  18545. onLevelUpdated(event, {
  18546. details
  18547. }) {
  18548. this.updateDateRangeCues(details, true);
  18549. }
  18550. onLevelPtsUpdated(event, data) {
  18551. if (Math.abs(data.drift) > 0.01) {
  18552. this.updateDateRangeCues(data.details);
  18553. }
  18554. }
  18555. updateDateRangeCues(details, removeOldCues) {
  18556. if (!this.media || !details.hasProgramDateTime || !this.hls.config.enableDateRangeMetadataCues) {
  18557. return;
  18558. }
  18559. const {
  18560. id3Track
  18561. } = this;
  18562. const {
  18563. dateRanges
  18564. } = details;
  18565. const ids = Object.keys(dateRanges);
  18566. let dateRangeCuesAppended = this.dateRangeCuesAppended;
  18567. // Remove cues from track not found in details.dateRanges
  18568. if (id3Track && removeOldCues) {
  18569. var _id3Track$cues;
  18570. if ((_id3Track$cues = id3Track.cues) != null && _id3Track$cues.length) {
  18571. const idsToRemove = Object.keys(dateRangeCuesAppended).filter(id => !ids.includes(id));
  18572. for (let i = idsToRemove.length; i--;) {
  18573. const id = idsToRemove[i];
  18574. const cues = dateRangeCuesAppended[id].cues;
  18575. delete dateRangeCuesAppended[id];
  18576. Object.keys(cues).forEach(key => {
  18577. try {
  18578. const cue = cues[key];
  18579. cue.removeEventListener('enter', this.onEventCueEnter);
  18580. id3Track.removeCue(cue);
  18581. } catch (e) {
  18582. /* no-op */
  18583. }
  18584. });
  18585. }
  18586. } else {
  18587. dateRangeCuesAppended = this.dateRangeCuesAppended = {};
  18588. }
  18589. }
  18590. // Exit if the playlist does not have Date Ranges or does not have Program Date Time
  18591. const lastFragment = details.fragments[details.fragments.length - 1];
  18592. if (ids.length === 0 || !isFiniteNumber(lastFragment == null ? void 0 : lastFragment.programDateTime)) {
  18593. return;
  18594. }
  18595. if (!this.id3Track) {
  18596. this.id3Track = this.createTrack(this.media);
  18597. }
  18598. const Cue = getCueClass();
  18599. for (let i = 0; i < ids.length; i++) {
  18600. const id = ids[i];
  18601. const dateRange = dateRanges[id];
  18602. const startTime = dateRange.startTime;
  18603. // Process DateRanges to determine end-time (known DURATION, END-DATE, or END-ON-NEXT)
  18604. const appendedDateRangeCues = dateRangeCuesAppended[id];
  18605. const cues = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.cues) || {};
  18606. let durationKnown = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.durationKnown) || false;
  18607. let endTime = MAX_CUE_ENDTIME;
  18608. const {
  18609. duration,
  18610. endDate
  18611. } = dateRange;
  18612. if (endDate && duration !== null) {
  18613. endTime = startTime + duration;
  18614. durationKnown = true;
  18615. } else if (dateRange.endOnNext && !durationKnown) {
  18616. const nextDateRangeWithSameClass = ids.reduce((candidateDateRange, id) => {
  18617. if (id !== dateRange.id) {
  18618. const otherDateRange = dateRanges[id];
  18619. if (otherDateRange.class === dateRange.class && otherDateRange.startDate > dateRange.startDate && (!candidateDateRange || dateRange.startDate < candidateDateRange.startDate)) {
  18620. return otherDateRange;
  18621. }
  18622. }
  18623. return candidateDateRange;
  18624. }, null);
  18625. if (nextDateRangeWithSameClass) {
  18626. endTime = nextDateRangeWithSameClass.startTime;
  18627. durationKnown = true;
  18628. }
  18629. }
  18630. // Create TextTrack Cues for each MetadataGroup Item (select DateRange attribute)
  18631. // This is to emulate Safari HLS playback handling of DateRange tags
  18632. const attributes = Object.keys(dateRange.attr);
  18633. for (let j = 0; j < attributes.length; j++) {
  18634. const key = attributes[j];
  18635. if (!isDateRangeCueAttribute(key)) {
  18636. continue;
  18637. }
  18638. const cue = cues[key];
  18639. if (cue) {
  18640. if (durationKnown && !appendedDateRangeCues.durationKnown) {
  18641. cue.endTime = endTime;
  18642. } else if (Math.abs(cue.startTime - startTime) > 0.01) {
  18643. cue.startTime = startTime;
  18644. cue.endTime = endTime;
  18645. }
  18646. } else if (Cue) {
  18647. let data = dateRange.attr[key];
  18648. if (isSCTE35Attribute(key)) {
  18649. data = hexToArrayBuffer(data);
  18650. }
  18651. const payload = {
  18652. key,
  18653. data
  18654. };
  18655. const _cue = createCueWithDataFields(Cue, startTime, endTime, payload, MetadataSchema.dateRange);
  18656. if (_cue) {
  18657. _cue.id = id;
  18658. this.id3Track.addCue(_cue);
  18659. cues[key] = _cue;
  18660. }
  18661. }
  18662. }
  18663. // Keep track of processed DateRanges by ID for updating cues with new DateRange tag attributes
  18664. dateRangeCuesAppended[id] = {
  18665. cues,
  18666. dateRange,
  18667. durationKnown
  18668. };
  18669. }
  18670. }
  18671. }
  18672. class LatencyController {
  18673. constructor(hls) {
  18674. this.hls = void 0;
  18675. this.config = void 0;
  18676. this.media = null;
  18677. this.currentTime = 0;
  18678. this.stallCount = 0;
  18679. this._latency = null;
  18680. this._targetLatencyUpdated = false;
  18681. this.onTimeupdate = () => {
  18682. const {
  18683. media
  18684. } = this;
  18685. const levelDetails = this.levelDetails;
  18686. if (!media || !levelDetails) {
  18687. return;
  18688. }
  18689. this.currentTime = media.currentTime;
  18690. const latency = this.computeLatency();
  18691. if (latency === null) {
  18692. return;
  18693. }
  18694. this._latency = latency;
  18695. // Adapt playbackRate to meet target latency in low-latency mode
  18696. const {
  18697. lowLatencyMode,
  18698. maxLiveSyncPlaybackRate
  18699. } = this.config;
  18700. if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1 || !levelDetails.live) {
  18701. return;
  18702. }
  18703. const targetLatency = this.targetLatency;
  18704. if (targetLatency === null) {
  18705. return;
  18706. }
  18707. const distanceFromTarget = latency - targetLatency;
  18708. // Only adjust playbackRate when within one target duration of targetLatency
  18709. // and more than one second from under-buffering.
  18710. // Playback further than one target duration from target can be considered DVR playback.
  18711. const liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
  18712. const inLiveRange = distanceFromTarget < liveMinLatencyDuration;
  18713. if (inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
  18714. const max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));
  18715. const rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
  18716. const playbackRate = Math.min(max, Math.max(1, rate));
  18717. this.changeMediaPlaybackRate(media, playbackRate);
  18718. } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
  18719. this.changeMediaPlaybackRate(media, 1);
  18720. }
  18721. };
  18722. this.hls = hls;
  18723. this.config = hls.config;
  18724. this.registerListeners();
  18725. }
  18726. get levelDetails() {
  18727. var _this$hls;
  18728. return ((_this$hls = this.hls) == null ? void 0 : _this$hls.latestLevelDetails) || null;
  18729. }
  18730. get latency() {
  18731. return this._latency || 0;
  18732. }
  18733. get maxLatency() {
  18734. const {
  18735. config
  18736. } = this;
  18737. if (config.liveMaxLatencyDuration !== undefined) {
  18738. return config.liveMaxLatencyDuration;
  18739. }
  18740. const levelDetails = this.levelDetails;
  18741. return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
  18742. }
  18743. get targetLatency() {
  18744. const levelDetails = this.levelDetails;
  18745. if (levelDetails === null || this.hls === null) {
  18746. return null;
  18747. }
  18748. const {
  18749. holdBack,
  18750. partHoldBack,
  18751. targetduration
  18752. } = levelDetails;
  18753. const {
  18754. liveSyncDuration,
  18755. liveSyncDurationCount,
  18756. lowLatencyMode
  18757. } = this.config;
  18758. const userConfig = this.hls.userConfig;
  18759. let targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
  18760. if (this._targetLatencyUpdated || userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
  18761. targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration;
  18762. }
  18763. const maxLiveSyncOnStallIncrease = targetduration;
  18764. return targetLatency + Math.min(this.stallCount * this.config.liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
  18765. }
  18766. set targetLatency(latency) {
  18767. this.stallCount = 0;
  18768. this.config.liveSyncDuration = latency;
  18769. this._targetLatencyUpdated = true;
  18770. }
  18771. get liveSyncPosition() {
  18772. const liveEdge = this.estimateLiveEdge();
  18773. const targetLatency = this.targetLatency;
  18774. if (liveEdge === null || targetLatency === null) {
  18775. return null;
  18776. }
  18777. const levelDetails = this.levelDetails;
  18778. if (levelDetails === null) {
  18779. return null;
  18780. }
  18781. const edge = levelDetails.edge;
  18782. const syncPosition = liveEdge - targetLatency - this.edgeStalled;
  18783. const min = edge - levelDetails.totalduration;
  18784. const max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
  18785. return Math.min(Math.max(min, syncPosition), max);
  18786. }
  18787. get drift() {
  18788. const levelDetails = this.levelDetails;
  18789. if (levelDetails === null) {
  18790. return 1;
  18791. }
  18792. return levelDetails.drift;
  18793. }
  18794. get edgeStalled() {
  18795. const levelDetails = this.levelDetails;
  18796. if (levelDetails === null) {
  18797. return 0;
  18798. }
  18799. const maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
  18800. return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
  18801. }
  18802. get forwardBufferLength() {
  18803. const {
  18804. media
  18805. } = this;
  18806. const levelDetails = this.levelDetails;
  18807. if (!media || !levelDetails) {
  18808. return 0;
  18809. }
  18810. const bufferedRanges = media.buffered.length;
  18811. return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime;
  18812. }
  18813. destroy() {
  18814. this.unregisterListeners();
  18815. this.onMediaDetaching();
  18816. this.hls = null;
  18817. }
  18818. registerListeners() {
  18819. const {
  18820. hls
  18821. } = this;
  18822. if (!hls) {
  18823. return;
  18824. }
  18825. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18826. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18827. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18828. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  18829. hls.on(Events.ERROR, this.onError, this);
  18830. }
  18831. unregisterListeners() {
  18832. const {
  18833. hls
  18834. } = this;
  18835. if (!hls) {
  18836. return;
  18837. }
  18838. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18839. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18840. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18841. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  18842. hls.off(Events.ERROR, this.onError, this);
  18843. }
  18844. onMediaAttached(event, data) {
  18845. this.media = data.media;
  18846. this.media.addEventListener('timeupdate', this.onTimeupdate);
  18847. }
  18848. onMediaDetaching() {
  18849. if (this.media) {
  18850. this.media.removeEventListener('timeupdate', this.onTimeupdate);
  18851. this.media = null;
  18852. }
  18853. }
  18854. onManifestLoading() {
  18855. this._latency = null;
  18856. this.stallCount = 0;
  18857. }
  18858. onLevelUpdated(event, {
  18859. details
  18860. }) {
  18861. if (details.advanced) {
  18862. this.onTimeupdate();
  18863. }
  18864. if (!details.live && this.media) {
  18865. this.media.removeEventListener('timeupdate', this.onTimeupdate);
  18866. }
  18867. }
  18868. onError(event, data) {
  18869. var _this$levelDetails;
  18870. if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {
  18871. return;
  18872. }
  18873. this.stallCount++;
  18874. if (this.hls && (_this$levelDetails = this.levelDetails) != null && _this$levelDetails.live) {
  18875. this.hls.logger.warn('[latency-controller]: Stall detected, adjusting target latency');
  18876. }
  18877. }
  18878. changeMediaPlaybackRate(media, playbackRate) {
  18879. var _this$hls2, _this$targetLatency;
  18880. if (media.playbackRate === playbackRate) {
  18881. return;
  18882. }
  18883. (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(_this$targetLatency = this.targetLatency) == null ? void 0 : _this$targetLatency.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${media.playbackRate} to ${playbackRate}`);
  18884. media.playbackRate = playbackRate;
  18885. }
  18886. estimateLiveEdge() {
  18887. const levelDetails = this.levelDetails;
  18888. if (levelDetails === null) {
  18889. return null;
  18890. }
  18891. return levelDetails.edge + levelDetails.age;
  18892. }
  18893. computeLatency() {
  18894. const liveEdge = this.estimateLiveEdge();
  18895. if (liveEdge === null) {
  18896. return null;
  18897. }
  18898. return liveEdge - this.currentTime;
  18899. }
  18900. }
  18901. class LevelController extends BasePlaylistController {
  18902. constructor(hls, contentSteeringController) {
  18903. super(hls, 'level-controller');
  18904. this._levels = [];
  18905. this._firstLevel = -1;
  18906. this._maxAutoLevel = -1;
  18907. this._startLevel = void 0;
  18908. this.currentLevel = null;
  18909. this.currentLevelIndex = -1;
  18910. this.manualLevelIndex = -1;
  18911. this.steering = void 0;
  18912. this.onParsedComplete = void 0;
  18913. this.steering = contentSteeringController;
  18914. this._registerListeners();
  18915. }
  18916. _registerListeners() {
  18917. const {
  18918. hls
  18919. } = this;
  18920. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18921. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  18922. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  18923. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  18924. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  18925. hls.on(Events.ERROR, this.onError, this);
  18926. }
  18927. _unregisterListeners() {
  18928. const {
  18929. hls
  18930. } = this;
  18931. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18932. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  18933. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  18934. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  18935. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  18936. hls.off(Events.ERROR, this.onError, this);
  18937. }
  18938. destroy() {
  18939. this._unregisterListeners();
  18940. this.steering = null;
  18941. this.resetLevels();
  18942. super.destroy();
  18943. }
  18944. stopLoad() {
  18945. const levels = this._levels;
  18946. // clean up live level details to force reload them, and reset load errors
  18947. levels.forEach(level => {
  18948. level.loadError = 0;
  18949. level.fragmentError = 0;
  18950. });
  18951. super.stopLoad();
  18952. }
  18953. resetLevels() {
  18954. this._startLevel = undefined;
  18955. this.manualLevelIndex = -1;
  18956. this.currentLevelIndex = -1;
  18957. this.currentLevel = null;
  18958. this._levels = [];
  18959. this._maxAutoLevel = -1;
  18960. }
  18961. onManifestLoading(event, data) {
  18962. this.resetLevels();
  18963. }
  18964. onManifestLoaded(event, data) {
  18965. const preferManagedMediaSource = this.hls.config.preferManagedMediaSource;
  18966. const levels = [];
  18967. const redundantSet = {};
  18968. const generatePathwaySet = {};
  18969. let resolutionFound = false;
  18970. let videoCodecFound = false;
  18971. let audioCodecFound = false;
  18972. data.levels.forEach(levelParsed => {
  18973. const attributes = levelParsed.attrs;
  18974. let {
  18975. audioCodec,
  18976. videoCodec
  18977. } = levelParsed;
  18978. if (audioCodec) {
  18979. // Returns empty and set to undefined for 'mp4a.40.34' with fallback to 'audio/mpeg' SourceBuffer
  18980. levelParsed.audioCodec = audioCodec = getCodecCompatibleName(audioCodec, preferManagedMediaSource) || undefined;
  18981. }
  18982. if (videoCodec) {
  18983. videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);
  18984. }
  18985. // only keep levels with supported audio/video codecs
  18986. const {
  18987. width,
  18988. height,
  18989. unknownCodecs
  18990. } = levelParsed;
  18991. let unknownUnsupportedCodecCount = unknownCodecs ? unknownCodecs.length : 0;
  18992. if (unknownCodecs) {
  18993. // Treat unknown codec as audio or video codec based on passing `isTypeSupported` check
  18994. // (allows for playback of any supported codec even if not indexed in utils/codecs)
  18995. for (let i = unknownUnsupportedCodecCount; i--;) {
  18996. const unknownCodec = unknownCodecs[i];
  18997. if (this.isAudioSupported(unknownCodec)) {
  18998. levelParsed.audioCodec = audioCodec = audioCodec ? `${audioCodec},${unknownCodec}` : unknownCodec;
  18999. unknownUnsupportedCodecCount--;
  19000. sampleEntryCodesISO.audio[audioCodec.substring(0, 4)] = 2;
  19001. } else if (this.isVideoSupported(unknownCodec)) {
  19002. levelParsed.videoCodec = videoCodec = videoCodec ? `${videoCodec},${unknownCodec}` : unknownCodec;
  19003. unknownUnsupportedCodecCount--;
  19004. sampleEntryCodesISO.video[videoCodec.substring(0, 4)] = 2;
  19005. }
  19006. }
  19007. }
  19008. resolutionFound || (resolutionFound = !!(width && height));
  19009. videoCodecFound || (videoCodecFound = !!videoCodec);
  19010. audioCodecFound || (audioCodecFound = !!audioCodec);
  19011. if (unknownUnsupportedCodecCount || audioCodec && !this.isAudioSupported(audioCodec) || videoCodec && !this.isVideoSupported(videoCodec)) {
  19012. this.log(`Some or all CODECS not supported "${attributes.CODECS}"`);
  19013. return;
  19014. }
  19015. const {
  19016. CODECS,
  19017. 'FRAME-RATE': FRAMERATE,
  19018. 'HDCP-LEVEL': HDCP,
  19019. 'PATHWAY-ID': PATHWAY,
  19020. RESOLUTION,
  19021. 'VIDEO-RANGE': VIDEO_RANGE
  19022. } = attributes;
  19023. const contentSteeringPrefix = `${PATHWAY || '.'}-`;
  19024. const levelKey = `${contentSteeringPrefix}${levelParsed.bitrate}-${RESOLUTION}-${FRAMERATE}-${CODECS}-${VIDEO_RANGE}-${HDCP}`;
  19025. if (!redundantSet[levelKey]) {
  19026. const level = this.createLevel(levelParsed);
  19027. redundantSet[levelKey] = level;
  19028. generatePathwaySet[levelKey] = 1;
  19029. levels.push(level);
  19030. } else if (redundantSet[levelKey].uri !== levelParsed.url && !levelParsed.attrs['PATHWAY-ID']) {
  19031. // Assign Pathway IDs to Redundant Streams (default Pathways is ".". Redundant Streams "..", "...", and so on.)
  19032. // Content Steering controller to handles Pathway fallback on error
  19033. const pathwayCount = generatePathwaySet[levelKey] += 1;
  19034. levelParsed.attrs['PATHWAY-ID'] = new Array(pathwayCount + 1).join('.');
  19035. const level = this.createLevel(levelParsed);
  19036. redundantSet[levelKey] = level;
  19037. levels.push(level);
  19038. } else {
  19039. redundantSet[levelKey].addGroupId('audio', attributes.AUDIO);
  19040. redundantSet[levelKey].addGroupId('text', attributes.SUBTITLES);
  19041. }
  19042. });
  19043. this.filterAndSortMediaOptions(levels, data, resolutionFound, videoCodecFound, audioCodecFound);
  19044. }
  19045. createLevel(levelParsed) {
  19046. const level = new Level(levelParsed);
  19047. const supplemental = levelParsed.supplemental;
  19048. if (supplemental != null && supplemental.videoCodec && !this.isVideoSupported(supplemental.videoCodec)) {
  19049. const error = new Error(`SUPPLEMENTAL-CODECS not supported "${supplemental.videoCodec}"`);
  19050. this.log(error.message);
  19051. level.supportedResult = emptyEsExports.getUnsupportedResult(error, []);
  19052. }
  19053. return level;
  19054. }
  19055. isAudioSupported(codec) {
  19056. return areCodecsMediaSourceSupported(codec, 'audio', this.hls.config.preferManagedMediaSource);
  19057. }
  19058. isVideoSupported(codec) {
  19059. return areCodecsMediaSourceSupported(codec, 'video', this.hls.config.preferManagedMediaSource);
  19060. }
  19061. filterAndSortMediaOptions(filteredLevels, data, resolutionFound, videoCodecFound, audioCodecFound) {
  19062. let audioTracks = [];
  19063. let subtitleTracks = [];
  19064. let levels = filteredLevels;
  19065. // remove audio-only and invalid video-range levels if we also have levels with video codecs or RESOLUTION signalled
  19066. if ((resolutionFound || videoCodecFound) && audioCodecFound) {
  19067. levels = levels.filter(({
  19068. videoCodec,
  19069. videoRange,
  19070. width,
  19071. height
  19072. }) => (!!videoCodec || !!(width && height)) && isVideoRange(videoRange));
  19073. }
  19074. if (levels.length === 0) {
  19075. // Dispatch error after MANIFEST_LOADED is done propagating
  19076. Promise.resolve().then(() => {
  19077. if (this.hls) {
  19078. let message = 'no level with compatible codecs found in manifest';
  19079. let reason = message;
  19080. if (data.levels.length) {
  19081. 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))}`;
  19082. this.warn(reason);
  19083. message += ` (${reason})`;
  19084. }
  19085. const error = new Error(message);
  19086. this.hls.trigger(Events.ERROR, {
  19087. type: ErrorTypes.MEDIA_ERROR,
  19088. details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  19089. fatal: true,
  19090. url: data.url,
  19091. error,
  19092. reason
  19093. });
  19094. }
  19095. });
  19096. return;
  19097. }
  19098. if (data.audioTracks) {
  19099. audioTracks = data.audioTracks.filter(track => !track.audioCodec || this.isAudioSupported(track.audioCodec));
  19100. // Assign ids after filtering as array indices by group-id
  19101. assignTrackIdsByGroup(audioTracks);
  19102. }
  19103. if (data.subtitles) {
  19104. subtitleTracks = data.subtitles;
  19105. assignTrackIdsByGroup(subtitleTracks);
  19106. }
  19107. // start bitrate is the first bitrate of the manifest
  19108. const unsortedLevels = levels.slice(0);
  19109. // sort levels from lowest to highest
  19110. levels.sort((a, b) => {
  19111. if (a.attrs['HDCP-LEVEL'] !== b.attrs['HDCP-LEVEL']) {
  19112. return (a.attrs['HDCP-LEVEL'] || '') > (b.attrs['HDCP-LEVEL'] || '') ? 1 : -1;
  19113. }
  19114. // sort on height before bitrate for cap-level-controller
  19115. if (resolutionFound && a.height !== b.height) {
  19116. return a.height - b.height;
  19117. }
  19118. if (a.frameRate !== b.frameRate) {
  19119. return a.frameRate - b.frameRate;
  19120. }
  19121. if (a.videoRange !== b.videoRange) {
  19122. return VideoRangeValues.indexOf(a.videoRange) - VideoRangeValues.indexOf(b.videoRange);
  19123. }
  19124. if (a.videoCodec !== b.videoCodec) {
  19125. const valueA = videoCodecPreferenceValue(a.videoCodec);
  19126. const valueB = videoCodecPreferenceValue(b.videoCodec);
  19127. if (valueA !== valueB) {
  19128. return valueB - valueA;
  19129. }
  19130. }
  19131. if (a.uri === b.uri && a.codecSet !== b.codecSet) {
  19132. const valueA = codecsSetSelectionPreferenceValue(a.codecSet);
  19133. const valueB = codecsSetSelectionPreferenceValue(b.codecSet);
  19134. if (valueA !== valueB) {
  19135. return valueB - valueA;
  19136. }
  19137. }
  19138. if (a.averageBitrate !== b.averageBitrate) {
  19139. return a.averageBitrate - b.averageBitrate;
  19140. }
  19141. return 0;
  19142. });
  19143. let firstLevelInPlaylist = unsortedLevels[0];
  19144. if (this.steering) {
  19145. levels = this.steering.filterParsedLevels(levels);
  19146. if (levels.length !== unsortedLevels.length) {
  19147. for (let i = 0; i < unsortedLevels.length; i++) {
  19148. if (unsortedLevels[i].pathwayId === levels[0].pathwayId) {
  19149. firstLevelInPlaylist = unsortedLevels[i];
  19150. break;
  19151. }
  19152. }
  19153. }
  19154. }
  19155. this._levels = levels;
  19156. // find index of first level in sorted levels
  19157. for (let i = 0; i < levels.length; i++) {
  19158. if (levels[i] === firstLevelInPlaylist) {
  19159. var _this$hls$userConfig;
  19160. this._firstLevel = i;
  19161. const firstLevelBitrate = firstLevelInPlaylist.bitrate;
  19162. const bandwidthEstimate = this.hls.bandwidthEstimate;
  19163. this.log(`manifest loaded, ${levels.length} level(s) found, first bitrate: ${firstLevelBitrate}`);
  19164. // Update default bwe to first variant bitrate as long it has not been configured or set
  19165. if (((_this$hls$userConfig = this.hls.userConfig) == null ? void 0 : _this$hls$userConfig.abrEwmaDefaultEstimate) === undefined) {
  19166. const startingBwEstimate = Math.min(firstLevelBitrate, this.hls.config.abrEwmaDefaultEstimateMax);
  19167. if (startingBwEstimate > bandwidthEstimate && bandwidthEstimate === this.hls.abrEwmaDefaultEstimate) {
  19168. this.hls.bandwidthEstimate = startingBwEstimate;
  19169. }
  19170. }
  19171. break;
  19172. }
  19173. }
  19174. // Audio is only alternate if manifest include a URI along with the audio group tag,
  19175. // and this is not an audio-only stream where levels contain audio-only
  19176. const audioOnly = audioCodecFound && !videoCodecFound;
  19177. const config = this.hls.config;
  19178. const altAudioEnabled = !!(config.audioStreamController && config.audioTrackController);
  19179. const edata = {
  19180. levels,
  19181. audioTracks,
  19182. subtitleTracks,
  19183. sessionData: data.sessionData,
  19184. sessionKeys: data.sessionKeys,
  19185. firstLevel: this._firstLevel,
  19186. stats: data.stats,
  19187. audio: audioCodecFound,
  19188. video: videoCodecFound,
  19189. altAudio: altAudioEnabled && !audioOnly && audioTracks.some(t => !!t.url)
  19190. };
  19191. this.hls.trigger(Events.MANIFEST_PARSED, edata);
  19192. }
  19193. get levels() {
  19194. if (this._levels.length === 0) {
  19195. return null;
  19196. }
  19197. return this._levels;
  19198. }
  19199. get loadLevelObj() {
  19200. return this.currentLevel;
  19201. }
  19202. get level() {
  19203. return this.currentLevelIndex;
  19204. }
  19205. set level(newLevel) {
  19206. const levels = this._levels;
  19207. if (levels.length === 0) {
  19208. return;
  19209. }
  19210. // check if level idx is valid
  19211. if (newLevel < 0 || newLevel >= levels.length) {
  19212. // invalid level id given, trigger error
  19213. const error = new Error('invalid level idx');
  19214. const fatal = newLevel < 0;
  19215. this.hls.trigger(Events.ERROR, {
  19216. type: ErrorTypes.OTHER_ERROR,
  19217. details: ErrorDetails.LEVEL_SWITCH_ERROR,
  19218. level: newLevel,
  19219. fatal,
  19220. error,
  19221. reason: error.message
  19222. });
  19223. if (fatal) {
  19224. return;
  19225. }
  19226. newLevel = Math.min(newLevel, levels.length - 1);
  19227. }
  19228. const lastLevelIndex = this.currentLevelIndex;
  19229. const lastLevel = this.currentLevel;
  19230. const lastPathwayId = lastLevel ? lastLevel.attrs['PATHWAY-ID'] : undefined;
  19231. const level = levels[newLevel];
  19232. const pathwayId = level.attrs['PATHWAY-ID'];
  19233. this.currentLevelIndex = newLevel;
  19234. this.currentLevel = level;
  19235. if (lastLevelIndex === newLevel && lastLevel && lastPathwayId === pathwayId) {
  19236. return;
  19237. }
  19238. 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 : ''}`);
  19239. const levelSwitchingData = {
  19240. level: newLevel,
  19241. attrs: level.attrs,
  19242. details: level.details,
  19243. bitrate: level.bitrate,
  19244. averageBitrate: level.averageBitrate,
  19245. maxBitrate: level.maxBitrate,
  19246. realBitrate: level.realBitrate,
  19247. width: level.width,
  19248. height: level.height,
  19249. codecSet: level.codecSet,
  19250. audioCodec: level.audioCodec,
  19251. videoCodec: level.videoCodec,
  19252. audioGroups: level.audioGroups,
  19253. subtitleGroups: level.subtitleGroups,
  19254. loaded: level.loaded,
  19255. loadError: level.loadError,
  19256. fragmentError: level.fragmentError,
  19257. name: level.name,
  19258. id: level.id,
  19259. uri: level.uri,
  19260. url: level.url,
  19261. urlId: 0,
  19262. audioGroupIds: level.audioGroupIds,
  19263. textGroupIds: level.textGroupIds
  19264. };
  19265. this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);
  19266. // check if we need to load playlist for this level
  19267. const levelDetails = level.details;
  19268. if (!levelDetails || levelDetails.live) {
  19269. // level not retrieved yet, or live playlist we need to (re)load it
  19270. const hlsUrlParameters = this.switchParams(level.uri, lastLevel == null ? void 0 : lastLevel.details, levelDetails);
  19271. this.loadPlaylist(hlsUrlParameters);
  19272. }
  19273. }
  19274. get manualLevel() {
  19275. return this.manualLevelIndex;
  19276. }
  19277. set manualLevel(newLevel) {
  19278. this.manualLevelIndex = newLevel;
  19279. if (this._startLevel === undefined) {
  19280. this._startLevel = newLevel;
  19281. }
  19282. if (newLevel !== -1) {
  19283. this.level = newLevel;
  19284. }
  19285. }
  19286. get firstLevel() {
  19287. return this._firstLevel;
  19288. }
  19289. set firstLevel(newLevel) {
  19290. this._firstLevel = newLevel;
  19291. }
  19292. get startLevel() {
  19293. // Setting hls.startLevel (this._startLevel) overrides config.startLevel
  19294. if (this._startLevel === undefined) {
  19295. const configStartLevel = this.hls.config.startLevel;
  19296. if (configStartLevel !== undefined) {
  19297. return configStartLevel;
  19298. }
  19299. return this.hls.firstAutoLevel;
  19300. }
  19301. return this._startLevel;
  19302. }
  19303. set startLevel(newLevel) {
  19304. this._startLevel = newLevel;
  19305. }
  19306. get pathways() {
  19307. if (this.steering) {
  19308. return this.steering.pathways();
  19309. }
  19310. return [];
  19311. }
  19312. get pathwayPriority() {
  19313. if (this.steering) {
  19314. return this.steering.pathwayPriority;
  19315. }
  19316. return null;
  19317. }
  19318. set pathwayPriority(pathwayPriority) {
  19319. if (this.steering) {
  19320. const pathwaysList = this.steering.pathways();
  19321. const filteredPathwayPriority = pathwayPriority.filter(pathwayId => {
  19322. return pathwaysList.indexOf(pathwayId) !== -1;
  19323. });
  19324. if (pathwayPriority.length < 1) {
  19325. this.warn(`pathwayPriority ${pathwayPriority} should contain at least one pathway from list: ${pathwaysList}`);
  19326. return;
  19327. }
  19328. this.steering.pathwayPriority = filteredPathwayPriority;
  19329. }
  19330. }
  19331. onError(event, data) {
  19332. if (data.fatal || !data.context) {
  19333. return;
  19334. }
  19335. if (data.context.type === PlaylistContextType.LEVEL && data.context.level === this.level) {
  19336. this.checkRetry(data);
  19337. }
  19338. }
  19339. // reset errors on the successful load of a fragment
  19340. onFragBuffered(event, {
  19341. frag
  19342. }) {
  19343. if (frag !== undefined && frag.type === PlaylistLevelType.MAIN) {
  19344. const el = frag.elementaryStreams;
  19345. if (!Object.keys(el).some(type => !!el[type])) {
  19346. return;
  19347. }
  19348. const level = this._levels[frag.level];
  19349. if (level != null && level.loadError) {
  19350. this.log(`Resetting level error count of ${level.loadError} on frag buffered`);
  19351. level.loadError = 0;
  19352. }
  19353. }
  19354. }
  19355. onLevelLoaded(event, data) {
  19356. var _data$deliveryDirecti2;
  19357. const {
  19358. level,
  19359. details
  19360. } = data;
  19361. const curLevel = data.levelInfo;
  19362. if (!curLevel) {
  19363. var _data$deliveryDirecti;
  19364. this.warn(`Invalid level index ${level}`);
  19365. if ((_data$deliveryDirecti = data.deliveryDirectives) != null && _data$deliveryDirecti.skip) {
  19366. details.deltaUpdateFailed = true;
  19367. }
  19368. return;
  19369. }
  19370. // only process level loaded events matching with expected level or prior to switch when media playlist is loaded directly
  19371. if (curLevel === this.currentLevel || data.withoutMultiVariant) {
  19372. // reset level load error counter on successful level loaded only if there is no issues with fragments
  19373. if (curLevel.fragmentError === 0) {
  19374. curLevel.loadError = 0;
  19375. }
  19376. // Ignore matching details populated by loading a Media Playlist directly
  19377. let previousDetails = curLevel.details;
  19378. if (previousDetails === data.details && previousDetails.advanced) {
  19379. previousDetails = undefined;
  19380. }
  19381. this.playlistLoaded(level, data, previousDetails);
  19382. } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) != null && _data$deliveryDirecti2.skip) {
  19383. // received a delta playlist update that cannot be merged
  19384. details.deltaUpdateFailed = true;
  19385. }
  19386. }
  19387. loadPlaylist(hlsUrlParameters) {
  19388. super.loadPlaylist();
  19389. if (this.shouldLoadPlaylist(this.currentLevel)) {
  19390. this.scheduleLoading(this.currentLevel, hlsUrlParameters);
  19391. }
  19392. }
  19393. loadingPlaylist(currentLevel, hlsUrlParameters) {
  19394. super.loadingPlaylist(currentLevel, hlsUrlParameters);
  19395. const url = this.getUrlWithDirectives(currentLevel.uri, hlsUrlParameters);
  19396. const currentLevelIndex = this.currentLevelIndex;
  19397. const pathwayId = currentLevel.attrs['PATHWAY-ID'];
  19398. const details = currentLevel.details;
  19399. const age = details == null ? void 0 : details.age;
  19400. this.log(`Loading level index ${currentLevelIndex}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== undefined ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : ''}${pathwayId ? ' Pathway ' + pathwayId : ''}${age && details.live ? ' age ' + age.toFixed(1) + (details.type ? ' ' + details.type || '' : '') : ''} ${url}`);
  19401. this.hls.trigger(Events.LEVEL_LOADING, {
  19402. url,
  19403. level: currentLevelIndex,
  19404. levelInfo: currentLevel,
  19405. pathwayId: currentLevel.attrs['PATHWAY-ID'],
  19406. id: 0,
  19407. // Deprecated Level urlId
  19408. deliveryDirectives: hlsUrlParameters || null
  19409. });
  19410. }
  19411. get nextLoadLevel() {
  19412. if (this.manualLevelIndex !== -1) {
  19413. return this.manualLevelIndex;
  19414. } else {
  19415. return this.hls.nextAutoLevel;
  19416. }
  19417. }
  19418. set nextLoadLevel(nextLevel) {
  19419. this.level = nextLevel;
  19420. if (this.manualLevelIndex === -1) {
  19421. this.hls.nextAutoLevel = nextLevel;
  19422. }
  19423. }
  19424. removeLevel(levelIndex) {
  19425. var _this$currentLevel;
  19426. if (this._levels.length === 1) {
  19427. return;
  19428. }
  19429. const levels = this._levels.filter((level, index) => {
  19430. if (index !== levelIndex) {
  19431. return true;
  19432. }
  19433. if (this.steering) {
  19434. this.steering.removeLevel(level);
  19435. }
  19436. if (level === this.currentLevel) {
  19437. this.currentLevel = null;
  19438. this.currentLevelIndex = -1;
  19439. if (level.details) {
  19440. level.details.fragments.forEach(f => f.level = -1);
  19441. }
  19442. }
  19443. return false;
  19444. });
  19445. reassignFragmentLevelIndexes(levels);
  19446. this._levels = levels;
  19447. if (this.currentLevelIndex > -1 && (_this$currentLevel = this.currentLevel) != null && _this$currentLevel.details) {
  19448. this.currentLevelIndex = this.currentLevel.details.fragments[0].level;
  19449. }
  19450. if (this.manualLevelIndex > -1) {
  19451. this.manualLevelIndex = this.currentLevelIndex;
  19452. }
  19453. const maxLevel = levels.length - 1;
  19454. this._firstLevel = Math.min(this._firstLevel, maxLevel);
  19455. if (this._startLevel) {
  19456. this._startLevel = Math.min(this._startLevel, maxLevel);
  19457. }
  19458. this.hls.trigger(Events.LEVELS_UPDATED, {
  19459. levels
  19460. });
  19461. }
  19462. onLevelsUpdated(event, {
  19463. levels
  19464. }) {
  19465. this._levels = levels;
  19466. }
  19467. checkMaxAutoUpdated() {
  19468. const {
  19469. autoLevelCapping,
  19470. maxAutoLevel,
  19471. maxHdcpLevel
  19472. } = this.hls;
  19473. if (this._maxAutoLevel !== maxAutoLevel) {
  19474. this._maxAutoLevel = maxAutoLevel;
  19475. this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {
  19476. autoLevelCapping,
  19477. levels: this.levels,
  19478. maxAutoLevel,
  19479. minAutoLevel: this.hls.minAutoLevel,
  19480. maxHdcpLevel
  19481. });
  19482. }
  19483. }
  19484. }
  19485. function assignTrackIdsByGroup(tracks) {
  19486. const groups = {};
  19487. tracks.forEach(track => {
  19488. const groupId = track.groupId || '';
  19489. track.id = groups[groupId] = groups[groupId] || 0;
  19490. groups[groupId]++;
  19491. });
  19492. }
  19493. const version = "1.6.7";
  19494. // ensure the worker ends up in the bundle
  19495. // If the worker should not be included this gets aliased to empty.js
  19496. const workerStore = {};
  19497. function hasUMDWorker() {
  19498. return typeof __HLS_WORKER_BUNDLE__ === 'function';
  19499. }
  19500. function injectWorker() {
  19501. const workerContext = workerStore[version];
  19502. if (workerContext) {
  19503. workerContext.clientCount++;
  19504. return workerContext;
  19505. }
  19506. const blob = new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`], {
  19507. type: 'text/javascript'
  19508. });
  19509. const objectURL = self.URL.createObjectURL(blob);
  19510. const worker = new self.Worker(objectURL);
  19511. const result = {
  19512. worker,
  19513. objectURL,
  19514. clientCount: 1
  19515. };
  19516. workerStore[version] = result;
  19517. return result;
  19518. }
  19519. function loadWorker(path) {
  19520. const workerContext = workerStore[path];
  19521. if (workerContext) {
  19522. workerContext.clientCount++;
  19523. return workerContext;
  19524. }
  19525. const scriptURL = new self.URL(path, self.location.href).href;
  19526. const worker = new self.Worker(scriptURL);
  19527. const result = {
  19528. worker,
  19529. scriptURL,
  19530. clientCount: 1
  19531. };
  19532. workerStore[path] = result;
  19533. return result;
  19534. }
  19535. function removeWorkerFromStore(path) {
  19536. const workerContext = workerStore[path || version];
  19537. if (workerContext) {
  19538. const clientCount = workerContext.clientCount--;
  19539. if (clientCount === 1) {
  19540. const {
  19541. worker,
  19542. objectURL
  19543. } = workerContext;
  19544. delete workerStore[path || version];
  19545. if (objectURL) {
  19546. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  19547. self.URL.revokeObjectURL(objectURL);
  19548. }
  19549. worker.terminate();
  19550. }
  19551. }
  19552. }
  19553. let transmuxerInstanceCount = 0;
  19554. class TransmuxerInterface {
  19555. constructor(_hls, id, onTransmuxComplete, onFlush) {
  19556. this.error = null;
  19557. this.hls = void 0;
  19558. this.id = void 0;
  19559. this.instanceNo = transmuxerInstanceCount++;
  19560. this.observer = void 0;
  19561. this.frag = null;
  19562. this.part = null;
  19563. this.useWorker = void 0;
  19564. this.workerContext = null;
  19565. this.transmuxer = null;
  19566. this.onTransmuxComplete = void 0;
  19567. this.onFlush = void 0;
  19568. this.onWorkerMessage = event => {
  19569. const data = event.data;
  19570. const hls = this.hls;
  19571. if (!hls || !(data != null && data.event) || data.instanceNo !== this.instanceNo) {
  19572. return;
  19573. }
  19574. switch (data.event) {
  19575. case 'init':
  19576. {
  19577. var _this$workerContext;
  19578. const objectURL = (_this$workerContext = this.workerContext) == null ? void 0 : _this$workerContext.objectURL;
  19579. if (objectURL) {
  19580. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  19581. self.URL.revokeObjectURL(objectURL);
  19582. }
  19583. break;
  19584. }
  19585. case 'transmuxComplete':
  19586. {
  19587. this.handleTransmuxComplete(data.data);
  19588. break;
  19589. }
  19590. case 'flush':
  19591. {
  19592. this.onFlush(data.data);
  19593. break;
  19594. }
  19595. // pass logs from the worker thread to the main logger
  19596. case 'workerLog':
  19597. {
  19598. if (hls.logger[data.data.logType]) {
  19599. hls.logger[data.data.logType](data.data.message);
  19600. }
  19601. break;
  19602. }
  19603. default:
  19604. {
  19605. data.data = data.data || {};
  19606. data.data.frag = this.frag;
  19607. data.data.part = this.part;
  19608. data.data.id = this.id;
  19609. hls.trigger(data.event, data.data);
  19610. break;
  19611. }
  19612. }
  19613. };
  19614. this.onWorkerError = event => {
  19615. if (!this.hls) {
  19616. return;
  19617. }
  19618. const error = new Error(`${event.message} (${event.filename}:${event.lineno})`);
  19619. this.hls.config.enableWorker = false;
  19620. this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`);
  19621. this.hls.trigger(Events.ERROR, {
  19622. type: ErrorTypes.OTHER_ERROR,
  19623. details: ErrorDetails.INTERNAL_EXCEPTION,
  19624. fatal: false,
  19625. event: 'demuxerWorker',
  19626. error
  19627. });
  19628. };
  19629. const config = _hls.config;
  19630. this.hls = _hls;
  19631. this.id = id;
  19632. this.useWorker = !!config.enableWorker;
  19633. this.onTransmuxComplete = onTransmuxComplete;
  19634. this.onFlush = onFlush;
  19635. const forwardMessage = (ev, data) => {
  19636. data = data || {};
  19637. data.frag = this.frag || undefined;
  19638. if (ev === Events.ERROR) {
  19639. data = data;
  19640. data.parent = this.id;
  19641. data.part = this.part;
  19642. this.error = data.error;
  19643. }
  19644. this.hls.trigger(ev, data);
  19645. };
  19646. // forward events to main thread
  19647. this.observer = new EventEmitter();
  19648. this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  19649. this.observer.on(Events.ERROR, forwardMessage);
  19650. const m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
  19651. if (this.useWorker && typeof Worker !== 'undefined') {
  19652. const logger = this.hls.logger;
  19653. const canCreateWorker = config.workerPath || hasUMDWorker();
  19654. if (canCreateWorker) {
  19655. try {
  19656. if (config.workerPath) {
  19657. logger.log(`loading Web Worker ${config.workerPath} for "${id}"`);
  19658. this.workerContext = loadWorker(config.workerPath);
  19659. } else {
  19660. logger.log(`injecting Web Worker for "${id}"`);
  19661. this.workerContext = injectWorker();
  19662. }
  19663. const {
  19664. worker
  19665. } = this.workerContext;
  19666. worker.addEventListener('message', this.onWorkerMessage);
  19667. worker.addEventListener('error', this.onWorkerError);
  19668. worker.postMessage({
  19669. instanceNo: this.instanceNo,
  19670. cmd: 'init',
  19671. typeSupported: m2tsTypeSupported,
  19672. id,
  19673. config: stringify(config)
  19674. });
  19675. } catch (err) {
  19676. logger.warn(`Error setting up "${id}" Web Worker, fallback to inline`, err);
  19677. this.terminateWorker();
  19678. this.error = null;
  19679. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id, _hls.logger);
  19680. }
  19681. return;
  19682. }
  19683. }
  19684. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id, _hls.logger);
  19685. }
  19686. reset() {
  19687. this.frag = null;
  19688. this.part = null;
  19689. if (this.workerContext) {
  19690. const instanceNo = this.instanceNo;
  19691. this.instanceNo = transmuxerInstanceCount++;
  19692. const config = this.hls.config;
  19693. const m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
  19694. this.workerContext.worker.postMessage({
  19695. instanceNo: this.instanceNo,
  19696. cmd: 'reset',
  19697. resetNo: instanceNo,
  19698. typeSupported: m2tsTypeSupported,
  19699. id: this.id,
  19700. config: stringify(config)
  19701. });
  19702. }
  19703. }
  19704. terminateWorker() {
  19705. if (this.workerContext) {
  19706. const {
  19707. worker
  19708. } = this.workerContext;
  19709. this.workerContext = null;
  19710. worker.removeEventListener('message', this.onWorkerMessage);
  19711. worker.removeEventListener('error', this.onWorkerError);
  19712. removeWorkerFromStore(this.hls.config.workerPath);
  19713. }
  19714. }
  19715. destroy() {
  19716. if (this.workerContext) {
  19717. this.terminateWorker();
  19718. // @ts-ignore
  19719. this.onWorkerMessage = this.onWorkerError = null;
  19720. } else {
  19721. const transmuxer = this.transmuxer;
  19722. if (transmuxer) {
  19723. transmuxer.destroy();
  19724. this.transmuxer = null;
  19725. }
  19726. }
  19727. const observer = this.observer;
  19728. if (observer) {
  19729. observer.removeAllListeners();
  19730. }
  19731. this.frag = null;
  19732. this.part = null;
  19733. // @ts-ignore
  19734. this.observer = null;
  19735. // @ts-ignore
  19736. this.hls = null;
  19737. }
  19738. push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
  19739. var _frag$initSegment, _lastFrag$initSegment;
  19740. chunkMeta.transmuxing.start = self.performance.now();
  19741. const {
  19742. instanceNo,
  19743. transmuxer
  19744. } = this;
  19745. const timeOffset = part ? part.start : frag.start;
  19746. // TODO: push "clear-lead" decrypt data for unencrypted fragments in streams with encrypted ones
  19747. const decryptdata = frag.decryptdata;
  19748. const lastFrag = this.frag;
  19749. const discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  19750. const trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
  19751. const snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
  19752. const partDiff = this.part ? chunkMeta.part - this.part.index : -1;
  19753. const progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag == null ? void 0 : lastFrag.stats.chunkCount);
  19754. const contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0));
  19755. const now = self.performance.now();
  19756. if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
  19757. frag.stats.parsing.start = now;
  19758. }
  19759. if (part && (partDiff || !contiguous)) {
  19760. part.stats.parsing.start = now;
  19761. }
  19762. const initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) == null ? void 0 : _lastFrag$initSegment.url));
  19763. const state = new TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange);
  19764. if (!contiguous || discontinuity || initSegmentChange) {
  19765. 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}
  19766. discontinuity: ${discontinuity}
  19767. trackSwitch: ${trackSwitch}
  19768. contiguous: ${contiguous}
  19769. accurateTimeOffset: ${accurateTimeOffset}
  19770. timeOffset: ${timeOffset}
  19771. initSegmentChange: ${initSegmentChange}`);
  19772. const config = new TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
  19773. this.configureTransmuxer(config);
  19774. }
  19775. this.frag = frag;
  19776. this.part = part;
  19777. // Frags with sn of 'initSegment' are not transmuxed
  19778. if (this.workerContext) {
  19779. // post fragment payload as transferable objects for ArrayBuffer (no copy)
  19780. this.workerContext.worker.postMessage({
  19781. instanceNo,
  19782. cmd: 'demux',
  19783. data,
  19784. decryptdata,
  19785. chunkMeta,
  19786. state
  19787. }, data instanceof ArrayBuffer ? [data] : []);
  19788. } else if (transmuxer) {
  19789. const transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
  19790. if (isPromise(transmuxResult)) {
  19791. transmuxResult.then(data => {
  19792. this.handleTransmuxComplete(data);
  19793. }).catch(error => {
  19794. this.transmuxerError(error, chunkMeta, 'transmuxer-interface push error');
  19795. });
  19796. } else {
  19797. this.handleTransmuxComplete(transmuxResult);
  19798. }
  19799. }
  19800. }
  19801. flush(chunkMeta) {
  19802. chunkMeta.transmuxing.start = self.performance.now();
  19803. const {
  19804. instanceNo,
  19805. transmuxer
  19806. } = this;
  19807. if (this.workerContext) {
  19808. this.workerContext.worker.postMessage({
  19809. instanceNo,
  19810. cmd: 'flush',
  19811. chunkMeta
  19812. });
  19813. } else if (transmuxer) {
  19814. const transmuxResult = transmuxer.flush(chunkMeta);
  19815. if (isPromise(transmuxResult)) {
  19816. transmuxResult.then(data => {
  19817. this.handleFlushResult(data, chunkMeta);
  19818. }).catch(error => {
  19819. this.transmuxerError(error, chunkMeta, 'transmuxer-interface flush error');
  19820. });
  19821. } else {
  19822. this.handleFlushResult(transmuxResult, chunkMeta);
  19823. }
  19824. }
  19825. }
  19826. transmuxerError(error, chunkMeta, reason) {
  19827. if (!this.hls) {
  19828. return;
  19829. }
  19830. this.error = error;
  19831. this.hls.trigger(Events.ERROR, {
  19832. type: ErrorTypes.MEDIA_ERROR,
  19833. details: ErrorDetails.FRAG_PARSING_ERROR,
  19834. chunkMeta,
  19835. frag: this.frag || undefined,
  19836. part: this.part || undefined,
  19837. fatal: false,
  19838. error,
  19839. err: error,
  19840. reason
  19841. });
  19842. }
  19843. handleFlushResult(results, chunkMeta) {
  19844. results.forEach(result => {
  19845. this.handleTransmuxComplete(result);
  19846. });
  19847. this.onFlush(chunkMeta);
  19848. }
  19849. configureTransmuxer(config) {
  19850. const {
  19851. instanceNo,
  19852. transmuxer
  19853. } = this;
  19854. if (this.workerContext) {
  19855. this.workerContext.worker.postMessage({
  19856. instanceNo,
  19857. cmd: 'configure',
  19858. config
  19859. });
  19860. } else if (transmuxer) {
  19861. transmuxer.configure(config);
  19862. }
  19863. }
  19864. handleTransmuxComplete(result) {
  19865. result.chunkMeta.transmuxing.end = self.performance.now();
  19866. this.onTransmuxComplete(result);
  19867. }
  19868. }
  19869. function getSourceBuffer() {
  19870. return self.SourceBuffer || self.WebKitSourceBuffer;
  19871. }
  19872. function isMSESupported() {
  19873. const mediaSource = getMediaSource();
  19874. if (!mediaSource) {
  19875. return false;
  19876. }
  19877. // if SourceBuffer is exposed ensure its API is valid
  19878. // Older browsers do not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
  19879. const sourceBuffer = getSourceBuffer();
  19880. return !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
  19881. }
  19882. function isSupported() {
  19883. if (!isMSESupported()) {
  19884. return false;
  19885. }
  19886. const mediaSource = getMediaSource();
  19887. 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'))));
  19888. }
  19889. function changeTypeSupported() {
  19890. var _sourceBuffer$prototy;
  19891. const sourceBuffer = getSourceBuffer();
  19892. return typeof (sourceBuffer == null ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) == null ? void 0 : _sourceBuffer$prototy.changeType) === 'function';
  19893. }
  19894. const TICK_INTERVAL = 100; // how often to tick in ms
  19895. class StreamController extends BaseStreamController {
  19896. constructor(hls, fragmentTracker, keyLoader) {
  19897. super(hls, fragmentTracker, keyLoader, 'stream-controller', PlaylistLevelType.MAIN);
  19898. this.audioCodecSwap = false;
  19899. this.level = -1;
  19900. this._forceStartLoad = false;
  19901. this._hasEnoughToStart = false;
  19902. this.altAudio = 0;
  19903. this.audioOnly = false;
  19904. this.fragPlaying = null;
  19905. this.fragLastKbps = 0;
  19906. this.couldBacktrack = false;
  19907. this.backtrackFragment = null;
  19908. this.audioCodecSwitch = false;
  19909. this.videoBuffer = null;
  19910. this.onMediaPlaying = () => {
  19911. // tick to speed up FRAG_CHANGED triggering
  19912. this.tick();
  19913. };
  19914. this.onMediaSeeked = () => {
  19915. const media = this.media;
  19916. const currentTime = media ? media.currentTime : null;
  19917. if (currentTime === null || !isFiniteNumber(currentTime)) {
  19918. return;
  19919. }
  19920. this.log(`Media seeked to ${currentTime.toFixed(3)}`);
  19921. // If seeked was issued before buffer was appended do not tick immediately
  19922. if (!this.getBufferedFrag(currentTime)) {
  19923. return;
  19924. }
  19925. const bufferInfo = this.getFwdBufferInfoAtPos(media, currentTime, PlaylistLevelType.MAIN, 0);
  19926. if (bufferInfo === null || bufferInfo.len === 0) {
  19927. this.warn(`Main forward buffer length at ${currentTime} on "seeked" event ${bufferInfo ? bufferInfo.len : 'empty'})`);
  19928. return;
  19929. }
  19930. // tick to speed up FRAG_CHANGED triggering
  19931. this.tick();
  19932. };
  19933. this.registerListeners();
  19934. }
  19935. registerListeners() {
  19936. super.registerListeners();
  19937. const {
  19938. hls
  19939. } = this;
  19940. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  19941. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  19942. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  19943. hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  19944. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  19945. hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  19946. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  19947. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  19948. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  19949. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  19950. }
  19951. unregisterListeners() {
  19952. super.unregisterListeners();
  19953. const {
  19954. hls
  19955. } = this;
  19956. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  19957. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  19958. hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  19959. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  19960. hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  19961. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  19962. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  19963. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  19964. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  19965. }
  19966. onHandlerDestroying() {
  19967. // @ts-ignore
  19968. this.onMediaPlaying = this.onMediaSeeked = null;
  19969. this.unregisterListeners();
  19970. super.onHandlerDestroying();
  19971. }
  19972. startLoad(startPosition, skipSeekToStartPosition) {
  19973. if (this.levels) {
  19974. const {
  19975. lastCurrentTime,
  19976. hls
  19977. } = this;
  19978. this.stopLoad();
  19979. this.setInterval(TICK_INTERVAL);
  19980. this.level = -1;
  19981. if (!this.startFragRequested) {
  19982. // determine load level
  19983. let startLevel = hls.startLevel;
  19984. if (startLevel === -1) {
  19985. if (hls.config.testBandwidth && this.levels.length > 1) {
  19986. // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  19987. startLevel = 0;
  19988. this.bitrateTest = true;
  19989. } else {
  19990. startLevel = hls.firstAutoLevel;
  19991. }
  19992. }
  19993. // set new level to playlist loader : this will trigger start level load
  19994. // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  19995. hls.nextLoadLevel = startLevel;
  19996. this.level = hls.loadLevel;
  19997. this._hasEnoughToStart = !!skipSeekToStartPosition;
  19998. }
  19999. // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
  20000. if (lastCurrentTime > 0 && startPosition === -1 && !skipSeekToStartPosition) {
  20001. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  20002. startPosition = lastCurrentTime;
  20003. }
  20004. this.state = State.IDLE;
  20005. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  20006. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  20007. this.tick();
  20008. } else {
  20009. this._forceStartLoad = true;
  20010. this.state = State.STOPPED;
  20011. }
  20012. }
  20013. stopLoad() {
  20014. this._forceStartLoad = false;
  20015. super.stopLoad();
  20016. }
  20017. doTick() {
  20018. switch (this.state) {
  20019. case State.WAITING_LEVEL:
  20020. {
  20021. const {
  20022. levels,
  20023. level
  20024. } = this;
  20025. const currentLevel = levels == null ? void 0 : levels[level];
  20026. const details = currentLevel == null ? void 0 : currentLevel.details;
  20027. if (details && (!details.live || this.levelLastLoaded === currentLevel && !this.waitForLive(currentLevel))) {
  20028. if (this.waitForCdnTuneIn(details)) {
  20029. break;
  20030. }
  20031. this.state = State.IDLE;
  20032. break;
  20033. } else if (this.hls.nextLoadLevel !== this.level) {
  20034. this.state = State.IDLE;
  20035. break;
  20036. }
  20037. break;
  20038. }
  20039. case State.FRAG_LOADING_WAITING_RETRY:
  20040. {
  20041. var _this$media;
  20042. const now = self.performance.now();
  20043. const retryDate = this.retryDate;
  20044. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  20045. if (!retryDate || now >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  20046. const {
  20047. levels,
  20048. level
  20049. } = this;
  20050. const currentLevel = levels == null ? void 0 : levels[level];
  20051. this.resetStartWhenNotLoaded(currentLevel || null);
  20052. this.state = State.IDLE;
  20053. }
  20054. }
  20055. break;
  20056. }
  20057. if (this.state === State.IDLE) {
  20058. this.doTickIdle();
  20059. }
  20060. this.onTickEnd();
  20061. }
  20062. onTickEnd() {
  20063. var _this$media2;
  20064. super.onTickEnd();
  20065. if ((_this$media2 = this.media) != null && _this$media2.readyState && this.media.seeking === false) {
  20066. this.lastCurrentTime = this.media.currentTime;
  20067. }
  20068. this.checkFragmentChanged();
  20069. }
  20070. doTickIdle() {
  20071. const {
  20072. hls,
  20073. levelLastLoaded,
  20074. levels,
  20075. media
  20076. } = this;
  20077. // if start level not parsed yet OR
  20078. // if video not attached AND start fragment already requested OR start frag prefetch not enabled
  20079. // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
  20080. if (levelLastLoaded === null || !media && !this.primaryPrefetch && (this.startFragRequested || !hls.config.startFragPrefetch)) {
  20081. return;
  20082. }
  20083. // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
  20084. if (this.altAudio && this.audioOnly) {
  20085. return;
  20086. }
  20087. const level = this.buffering ? hls.nextLoadLevel : hls.loadLevel;
  20088. if (!(levels != null && levels[level])) {
  20089. return;
  20090. }
  20091. const levelInfo = levels[level];
  20092. // if buffer length is less than maxBufLen try to load a new fragment
  20093. const bufferInfo = this.getMainFwdBufferInfo();
  20094. if (bufferInfo === null) {
  20095. return;
  20096. }
  20097. const lastDetails = this.getLevelDetails();
  20098. if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {
  20099. const data = {};
  20100. if (this.altAudio === 2) {
  20101. data.type = 'video';
  20102. }
  20103. this.hls.trigger(Events.BUFFER_EOS, data);
  20104. this.state = State.ENDED;
  20105. return;
  20106. }
  20107. if (!this.buffering) {
  20108. return;
  20109. }
  20110. // set next load level : this will trigger a playlist load if needed
  20111. if (hls.loadLevel !== level && hls.manualLevel === -1) {
  20112. this.log(`Adapting to level ${level} from level ${this.level}`);
  20113. }
  20114. this.level = hls.nextLoadLevel = level;
  20115. const levelDetails = levelInfo.details;
  20116. // if level info not retrieved yet, switch state and wait for level retrieval
  20117. // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  20118. // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  20119. if (!levelDetails || this.state === State.WAITING_LEVEL || this.waitForLive(levelInfo)) {
  20120. this.level = level;
  20121. this.state = State.WAITING_LEVEL;
  20122. this.startFragRequested = false;
  20123. return;
  20124. }
  20125. const bufferLen = bufferInfo.len;
  20126. // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s
  20127. const maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);
  20128. // Stay idle if we are still with buffer margins
  20129. if (bufferLen >= maxBufLen) {
  20130. return;
  20131. }
  20132. if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) {
  20133. this.backtrackFragment = null;
  20134. }
  20135. const targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end;
  20136. let frag = this.getNextFragment(targetBufferTime, levelDetails);
  20137. // Avoid backtracking by loading an earlier segment in streams with segments that do not start with a key frame (flagged by `couldBacktrack`)
  20138. if (this.couldBacktrack && !this.fragPrevious && frag && isMediaFragment(frag) && this.fragmentTracker.getState(frag) !== FragmentState.OK) {
  20139. var _this$backtrackFragme;
  20140. const backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn;
  20141. const fragIdx = backtrackSn - levelDetails.startSN;
  20142. const backtrackFrag = levelDetails.fragments[fragIdx - 1];
  20143. if (backtrackFrag && frag.cc === backtrackFrag.cc) {
  20144. frag = backtrackFrag;
  20145. this.fragmentTracker.removeFragment(backtrackFrag);
  20146. }
  20147. } else if (this.backtrackFragment && bufferInfo.len) {
  20148. this.backtrackFragment = null;
  20149. }
  20150. // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags
  20151. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  20152. const gapStart = frag.gap;
  20153. if (!gapStart) {
  20154. // Cleanup the fragment tracker before trying to find the next unbuffered fragment
  20155. const type = this.audioOnly && !this.altAudio ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
  20156. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  20157. if (mediaBuffer) {
  20158. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  20159. }
  20160. }
  20161. frag = this.getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  20162. }
  20163. if (!frag) {
  20164. return;
  20165. }
  20166. if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
  20167. frag = frag.initSegment;
  20168. }
  20169. this.loadFragment(frag, levelInfo, targetBufferTime);
  20170. }
  20171. loadFragment(frag, level, targetBufferTime) {
  20172. // Check if fragment is not loaded
  20173. const fragState = this.fragmentTracker.getState(frag);
  20174. if (fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  20175. if (!isMediaFragment(frag)) {
  20176. this._loadInitSegment(frag, level);
  20177. } else if (this.bitrateTest) {
  20178. this.log(`Fragment ${frag.sn} of level ${frag.level} is being downloaded to test bitrate and will not be buffered`);
  20179. this._loadBitrateTestFrag(frag, level);
  20180. } else {
  20181. super.loadFragment(frag, level, targetBufferTime);
  20182. }
  20183. } else {
  20184. this.clearTrackerIfNeeded(frag);
  20185. }
  20186. }
  20187. getBufferedFrag(position) {
  20188. return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
  20189. }
  20190. followingBufferedFrag(frag) {
  20191. if (frag) {
  20192. // try to get range of next fragment (500ms after this range)
  20193. return this.getBufferedFrag(frag.end + 0.5);
  20194. }
  20195. return null;
  20196. }
  20197. /*
  20198. on immediate level switch :
  20199. - pause playback if playing
  20200. - cancel any pending load request
  20201. - and trigger a buffer flush
  20202. */
  20203. immediateLevelSwitch() {
  20204. this.abortCurrentFrag();
  20205. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  20206. }
  20207. /**
  20208. * try to switch ASAP without breaking video playback:
  20209. * in order to ensure smooth but quick level switching,
  20210. * we need to find the next flushable buffer range
  20211. * we should take into account new segment fetch time
  20212. */
  20213. nextLevelSwitch() {
  20214. const {
  20215. levels,
  20216. media
  20217. } = this;
  20218. // ensure that media is defined and that metadata are available (to retrieve currentTime)
  20219. if (media != null && media.readyState) {
  20220. let fetchdelay;
  20221. const fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
  20222. if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
  20223. // flush buffer preceding current fragment (flush until current fragment start offset)
  20224. // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  20225. this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
  20226. }
  20227. const levelDetails = this.getLevelDetails();
  20228. if (levelDetails != null && levelDetails.live) {
  20229. const bufferInfo = this.getMainFwdBufferInfo();
  20230. // Do not flush in live stream with low buffer
  20231. if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {
  20232. return;
  20233. }
  20234. }
  20235. if (!media.paused && levels) {
  20236. // add a safety delay of 1s
  20237. const nextLevelId = this.hls.nextLoadLevel;
  20238. const nextLevel = levels[nextLevelId];
  20239. const fragLastKbps = this.fragLastKbps;
  20240. if (fragLastKbps && this.fragCurrent) {
  20241. fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1;
  20242. } else {
  20243. fetchdelay = 0;
  20244. }
  20245. } else {
  20246. fetchdelay = 0;
  20247. }
  20248. // this.log('fetchdelay:'+fetchdelay);
  20249. // find buffer range that will be reached once new fragment will be fetched
  20250. const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  20251. if (bufferedFrag) {
  20252. // we can flush buffer range following this one without stalling playback
  20253. const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
  20254. if (nextBufferedFrag) {
  20255. // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  20256. this.abortCurrentFrag();
  20257. // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.
  20258. const maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
  20259. const fragDuration = nextBufferedFrag.duration;
  20260. 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)));
  20261. this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
  20262. }
  20263. }
  20264. }
  20265. }
  20266. abortCurrentFrag() {
  20267. const fragCurrent = this.fragCurrent;
  20268. this.fragCurrent = null;
  20269. this.backtrackFragment = null;
  20270. if (fragCurrent) {
  20271. fragCurrent.abortRequests();
  20272. this.fragmentTracker.removeFragment(fragCurrent);
  20273. }
  20274. switch (this.state) {
  20275. case State.KEY_LOADING:
  20276. case State.FRAG_LOADING:
  20277. case State.FRAG_LOADING_WAITING_RETRY:
  20278. case State.PARSING:
  20279. case State.PARSED:
  20280. this.state = State.IDLE;
  20281. break;
  20282. }
  20283. this.nextLoadPosition = this.getLoadPosition();
  20284. }
  20285. flushMainBuffer(startOffset, endOffset) {
  20286. super.flushMainBuffer(startOffset, endOffset, this.altAudio === 2 ? 'video' : null);
  20287. }
  20288. onMediaAttached(event, data) {
  20289. super.onMediaAttached(event, data);
  20290. const media = data.media;
  20291. addEventListener(media, 'playing', this.onMediaPlaying);
  20292. addEventListener(media, 'seeked', this.onMediaSeeked);
  20293. }
  20294. onMediaDetaching(event, data) {
  20295. const {
  20296. media
  20297. } = this;
  20298. if (media) {
  20299. removeEventListener(media, 'playing', this.onMediaPlaying);
  20300. removeEventListener(media, 'seeked', this.onMediaSeeked);
  20301. }
  20302. this.videoBuffer = null;
  20303. this.fragPlaying = null;
  20304. super.onMediaDetaching(event, data);
  20305. const transferringMedia = !!data.transferMedia;
  20306. if (transferringMedia) {
  20307. return;
  20308. }
  20309. this._hasEnoughToStart = false;
  20310. }
  20311. onManifestLoading() {
  20312. super.onManifestLoading();
  20313. // reset buffer on manifest loading
  20314. this.log('Trigger BUFFER_RESET');
  20315. this.hls.trigger(Events.BUFFER_RESET, undefined);
  20316. this.couldBacktrack = false;
  20317. this.fragLastKbps = 0;
  20318. this.fragPlaying = this.backtrackFragment = null;
  20319. this.altAudio = 0;
  20320. this.audioOnly = false;
  20321. }
  20322. onManifestParsed(event, data) {
  20323. // detect if we have different kind of audio codecs used amongst playlists
  20324. let aac = false;
  20325. let heaac = false;
  20326. data.levels.forEach(level => {
  20327. const codec = level.audioCodec;
  20328. if (codec) {
  20329. aac = aac || codec.indexOf('mp4a.40.2') !== -1;
  20330. heaac = heaac || codec.indexOf('mp4a.40.5') !== -1;
  20331. }
  20332. });
  20333. this.audioCodecSwitch = aac && heaac && !changeTypeSupported();
  20334. if (this.audioCodecSwitch) {
  20335. this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  20336. }
  20337. this.levels = data.levels;
  20338. this.startFragRequested = false;
  20339. }
  20340. onLevelLoading(event, data) {
  20341. const {
  20342. levels
  20343. } = this;
  20344. if (!levels || this.state !== State.IDLE) {
  20345. return;
  20346. }
  20347. const level = data.levelInfo;
  20348. if (!level.details || level.details.live && (this.levelLastLoaded !== level || level.details.expired) || this.waitForCdnTuneIn(level.details)) {
  20349. this.state = State.WAITING_LEVEL;
  20350. }
  20351. }
  20352. onLevelLoaded(event, data) {
  20353. var _curLevel$details;
  20354. const {
  20355. levels,
  20356. startFragRequested
  20357. } = this;
  20358. const newLevelId = data.level;
  20359. const newDetails = data.details;
  20360. const duration = newDetails.totalduration;
  20361. if (!levels) {
  20362. this.warn(`Levels were reset while loading level ${newLevelId}`);
  20363. return;
  20364. }
  20365. this.log(`Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ''}, cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration}`);
  20366. const curLevel = data.levelInfo;
  20367. const fragCurrent = this.fragCurrent;
  20368. if (fragCurrent && (this.state === State.FRAG_LOADING || this.state === State.FRAG_LOADING_WAITING_RETRY)) {
  20369. if (fragCurrent.level !== data.level && fragCurrent.loader) {
  20370. this.abortCurrentFrag();
  20371. }
  20372. }
  20373. let sliding = 0;
  20374. if (newDetails.live || (_curLevel$details = curLevel.details) != null && _curLevel$details.live) {
  20375. var _this$levelLastLoaded;
  20376. this.checkLiveUpdate(newDetails);
  20377. if (newDetails.deltaUpdateFailed) {
  20378. return;
  20379. }
  20380. sliding = this.alignPlaylists(newDetails, curLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  20381. }
  20382. // override level info
  20383. curLevel.details = newDetails;
  20384. this.levelLastLoaded = curLevel;
  20385. if (!startFragRequested) {
  20386. this.setStartPosition(newDetails, sliding);
  20387. }
  20388. this.hls.trigger(Events.LEVEL_UPDATED, {
  20389. details: newDetails,
  20390. level: newLevelId
  20391. });
  20392. // only switch back to IDLE state if we were waiting for level to start downloading a new fragment
  20393. if (this.state === State.WAITING_LEVEL) {
  20394. if (this.waitForCdnTuneIn(newDetails)) {
  20395. // Wait for Low-Latency CDN Tune-in
  20396. return;
  20397. }
  20398. this.state = State.IDLE;
  20399. }
  20400. if (startFragRequested && newDetails.live) {
  20401. this.synchronizeToLiveEdge(newDetails);
  20402. }
  20403. // trigger handler right now
  20404. this.tick();
  20405. }
  20406. synchronizeToLiveEdge(levelDetails) {
  20407. const {
  20408. config,
  20409. media
  20410. } = this;
  20411. if (!media) {
  20412. return;
  20413. }
  20414. const liveSyncPosition = this.hls.liveSyncPosition;
  20415. const currentTime = this.getLoadPosition();
  20416. const start = levelDetails.fragmentStart;
  20417. const end = levelDetails.edge;
  20418. const withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end;
  20419. // Continue if we can seek forward to sync position or if current time is outside of sliding window
  20420. if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
  20421. // Continue if buffer is starving or if current time is behind max latency
  20422. const maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  20423. if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
  20424. if (!this._hasEnoughToStart) {
  20425. this.nextLoadPosition = liveSyncPosition;
  20426. }
  20427. // Only seek if ready and there is not a significant forward buffer available for playback
  20428. if (media.readyState) {
  20429. this.warn(`Playback: ${currentTime.toFixed(3)} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);
  20430. if (this.config.liveSyncMode === 'buffered') {
  20431. var _bufferInfo$buffered;
  20432. const bufferInfo = BufferHelper.bufferInfo(media, liveSyncPosition, 0);
  20433. if (!(bufferInfo != null && (_bufferInfo$buffered = bufferInfo.buffered) != null && _bufferInfo$buffered.length)) {
  20434. media.currentTime = liveSyncPosition;
  20435. return;
  20436. }
  20437. const isLiveSyncInBuffer = bufferInfo.start <= currentTime;
  20438. if (isLiveSyncInBuffer) {
  20439. media.currentTime = liveSyncPosition;
  20440. return;
  20441. }
  20442. const {
  20443. nextStart
  20444. } = BufferHelper.bufferedInfo(bufferInfo.buffered, currentTime, 0);
  20445. if (nextStart) {
  20446. media.currentTime = nextStart;
  20447. }
  20448. } else {
  20449. media.currentTime = liveSyncPosition;
  20450. }
  20451. }
  20452. }
  20453. }
  20454. }
  20455. _handleFragmentLoadProgress(data) {
  20456. var _frag$initSegment;
  20457. const frag = data.frag;
  20458. const {
  20459. part,
  20460. payload
  20461. } = data;
  20462. const {
  20463. levels
  20464. } = this;
  20465. if (!levels) {
  20466. this.warn(`Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  20467. return;
  20468. }
  20469. const currentLevel = levels[frag.level];
  20470. if (!currentLevel) {
  20471. this.warn(`Level ${frag.level} not found on progress`);
  20472. return;
  20473. }
  20474. const details = currentLevel.details;
  20475. if (!details) {
  20476. this.warn(`Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`);
  20477. this.fragmentTracker.removeFragment(frag);
  20478. return;
  20479. }
  20480. const videoCodec = currentLevel.videoCodec;
  20481. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  20482. const accurateTimeOffset = details.PTSKnown || !details.live;
  20483. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  20484. const audioCodec = this._getAudioCodec(currentLevel);
  20485. // transmux the MPEG-TS data to ISO-BMFF segments
  20486. // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);
  20487. const transmuxer = this.transmuxer = this.transmuxer || new TransmuxerInterface(this.hls, PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  20488. const partIndex = part ? part.index : -1;
  20489. const partial = partIndex !== -1;
  20490. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  20491. const initPTS = this.initPTS[frag.cc];
  20492. transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  20493. }
  20494. onAudioTrackSwitching(event, data) {
  20495. const hls = this.hls;
  20496. // if any URL found on new audio track, it is an alternate audio track
  20497. const fromAltAudio = this.altAudio === 2;
  20498. const altAudio = useAlternateAudio(data.url, hls);
  20499. // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
  20500. // don't do anything if we switch to alt audio: audio stream controller is handling it.
  20501. // we will just have to change buffer scheduling on audioTrackSwitched
  20502. if (!altAudio) {
  20503. if (this.mediaBuffer !== this.media) {
  20504. this.log('Switching on main audio, use media.buffered to schedule main fragment loading');
  20505. this.mediaBuffer = this.media;
  20506. const fragCurrent = this.fragCurrent;
  20507. // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
  20508. if (fragCurrent) {
  20509. this.log('Switching to main audio track, cancel main fragment load');
  20510. fragCurrent.abortRequests();
  20511. this.fragmentTracker.removeFragment(fragCurrent);
  20512. }
  20513. // destroy transmuxer to force init segment generation (following audio switch)
  20514. this.resetTransmuxer();
  20515. // switch to IDLE state to load new fragment
  20516. this.resetLoadingState();
  20517. } else if (this.audioOnly) {
  20518. // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off
  20519. this.resetTransmuxer();
  20520. }
  20521. // If switching from alt to main audio, flush all audio and trigger track switched
  20522. if (fromAltAudio) {
  20523. this.fragmentTracker.removeAllFragments();
  20524. hls.once(Events.BUFFER_FLUSHED, () => {
  20525. var _this$hls;
  20526. (_this$hls = this.hls) == null ? void 0 : _this$hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  20527. });
  20528. hls.trigger(Events.BUFFER_FLUSHING, {
  20529. startOffset: 0,
  20530. endOffset: Number.POSITIVE_INFINITY,
  20531. type: null
  20532. });
  20533. return;
  20534. }
  20535. hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  20536. } else {
  20537. this.altAudio = 1;
  20538. }
  20539. }
  20540. onAudioTrackSwitched(event, data) {
  20541. const altAudio = useAlternateAudio(data.url, this.hls);
  20542. if (altAudio) {
  20543. const videoBuffer = this.videoBuffer;
  20544. // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
  20545. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  20546. this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading');
  20547. this.mediaBuffer = videoBuffer;
  20548. }
  20549. }
  20550. this.altAudio = altAudio ? 2 : 0;
  20551. this.tick();
  20552. }
  20553. onBufferCreated(event, data) {
  20554. const tracks = data.tracks;
  20555. let mediaTrack;
  20556. let name;
  20557. let alternate = false;
  20558. for (const type in tracks) {
  20559. const track = tracks[type];
  20560. if (track.id === 'main') {
  20561. name = type;
  20562. mediaTrack = track;
  20563. // keep video source buffer reference
  20564. if (type === 'video') {
  20565. const videoTrack = tracks[type];
  20566. if (videoTrack) {
  20567. this.videoBuffer = videoTrack.buffer;
  20568. }
  20569. }
  20570. } else {
  20571. alternate = true;
  20572. }
  20573. }
  20574. if (alternate && mediaTrack) {
  20575. this.log(`Alternate track found, use ${name}.buffered to schedule main fragment loading`);
  20576. this.mediaBuffer = mediaTrack.buffer;
  20577. } else {
  20578. this.mediaBuffer = this.media;
  20579. }
  20580. }
  20581. onFragBuffered(event, data) {
  20582. const {
  20583. frag,
  20584. part
  20585. } = data;
  20586. const bufferedMainFragment = frag.type === PlaylistLevelType.MAIN;
  20587. if (bufferedMainFragment) {
  20588. if (this.fragContextChanged(frag)) {
  20589. // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
  20590. // Avoid setting state back to IDLE, since that will interfere with a level switch
  20591. this.warn(`Fragment ${frag.sn}${part ? ' p: ' + part.index : ''} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}`);
  20592. if (this.state === State.PARSED) {
  20593. this.state = State.IDLE;
  20594. }
  20595. return;
  20596. }
  20597. const stats = part ? part.stats : frag.stats;
  20598. this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
  20599. if (isMediaFragment(frag)) {
  20600. this.fragPrevious = frag;
  20601. }
  20602. this.fragBufferedComplete(frag, part);
  20603. }
  20604. const media = this.media;
  20605. if (!media) {
  20606. return;
  20607. }
  20608. if (!this._hasEnoughToStart && BufferHelper.getBuffered(media).length) {
  20609. this._hasEnoughToStart = true;
  20610. this.seekToStartPos();
  20611. }
  20612. if (bufferedMainFragment) {
  20613. this.tick();
  20614. }
  20615. }
  20616. get hasEnoughToStart() {
  20617. return this._hasEnoughToStart;
  20618. }
  20619. onError(event, data) {
  20620. var _data$context;
  20621. if (data.fatal) {
  20622. this.state = State.ERROR;
  20623. return;
  20624. }
  20625. switch (data.details) {
  20626. case ErrorDetails.FRAG_GAP:
  20627. case ErrorDetails.FRAG_PARSING_ERROR:
  20628. case ErrorDetails.FRAG_DECRYPT_ERROR:
  20629. case ErrorDetails.FRAG_LOAD_ERROR:
  20630. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  20631. case ErrorDetails.KEY_LOAD_ERROR:
  20632. case ErrorDetails.KEY_LOAD_TIMEOUT:
  20633. this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);
  20634. break;
  20635. case ErrorDetails.LEVEL_LOAD_ERROR:
  20636. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  20637. case ErrorDetails.LEVEL_PARSING_ERROR:
  20638. // in case of non fatal error while loading level, if level controller is not retrying to load level, switch back to IDLE
  20639. if (!data.levelRetry && this.state === State.WAITING_LEVEL && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.LEVEL) {
  20640. this.state = State.IDLE;
  20641. }
  20642. break;
  20643. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  20644. case ErrorDetails.BUFFER_APPEND_ERROR:
  20645. if (data.parent !== 'main') {
  20646. return;
  20647. }
  20648. if (this.reduceLengthAndFlushBuffer(data)) {
  20649. this.resetLoadingState();
  20650. }
  20651. break;
  20652. case ErrorDetails.BUFFER_FULL_ERROR:
  20653. if (data.parent !== 'main') {
  20654. return;
  20655. }
  20656. if (this.reduceLengthAndFlushBuffer(data)) {
  20657. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  20658. }
  20659. break;
  20660. case ErrorDetails.INTERNAL_EXCEPTION:
  20661. this.recoverWorkerError(data);
  20662. break;
  20663. }
  20664. }
  20665. onFragLoadEmergencyAborted() {
  20666. this.state = State.IDLE;
  20667. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  20668. // in that case, reset startFragRequested flag
  20669. if (!this._hasEnoughToStart) {
  20670. this.startFragRequested = false;
  20671. this.nextLoadPosition = this.lastCurrentTime;
  20672. }
  20673. this.tickImmediate();
  20674. }
  20675. onBufferFlushed(event, {
  20676. type
  20677. }) {
  20678. if (type !== ElementaryStreamTypes.AUDIO || !this.altAudio) {
  20679. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  20680. if (mediaBuffer) {
  20681. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  20682. this.tick();
  20683. }
  20684. }
  20685. }
  20686. onLevelsUpdated(event, data) {
  20687. if (this.level > -1 && this.fragCurrent) {
  20688. this.level = this.fragCurrent.level;
  20689. if (this.level === -1) {
  20690. this.resetWhenMissingContext(this.fragCurrent);
  20691. }
  20692. }
  20693. this.levels = data.levels;
  20694. }
  20695. swapAudioCodec() {
  20696. this.audioCodecSwap = !this.audioCodecSwap;
  20697. }
  20698. /**
  20699. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  20700. */
  20701. seekToStartPos() {
  20702. const {
  20703. media
  20704. } = this;
  20705. if (!media) {
  20706. return;
  20707. }
  20708. const currentTime = media.currentTime;
  20709. let startPosition = this.startPosition;
  20710. // only adjust currentTime if different from startPosition or if startPosition not buffered
  20711. // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
  20712. if (startPosition >= 0 && currentTime < startPosition) {
  20713. if (media.seeking) {
  20714. this.log(`could not seek to ${startPosition}, already seeking at ${currentTime}`);
  20715. return;
  20716. }
  20717. // Offset start position by timeline offset
  20718. const timelineOffset = this.timelineOffset;
  20719. if (timelineOffset && startPosition) {
  20720. startPosition += timelineOffset;
  20721. }
  20722. const details = this.getLevelDetails();
  20723. const buffered = BufferHelper.getBuffered(media);
  20724. const bufferStart = buffered.length ? buffered.start(0) : 0;
  20725. const delta = bufferStart - startPosition;
  20726. const skipTolerance = Math.max(this.config.maxBufferHole, this.config.maxFragLookUpTolerance);
  20727. if (this.config.startOnSegmentBoundary || delta > 0 && (delta < skipTolerance || this.loadingParts && delta < 2 * ((details == null ? void 0 : details.partTarget) || 0))) {
  20728. this.log(`adjusting start position by ${delta} to match buffer start`);
  20729. startPosition += delta;
  20730. this.startPosition = startPosition;
  20731. }
  20732. if (currentTime < startPosition) {
  20733. this.log(`seek to target start position ${startPosition} from current time ${currentTime} buffer start ${bufferStart}`);
  20734. media.currentTime = startPosition;
  20735. }
  20736. }
  20737. }
  20738. _getAudioCodec(currentLevel) {
  20739. let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  20740. if (this.audioCodecSwap && audioCodec) {
  20741. this.log('Swapping audio codec');
  20742. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  20743. audioCodec = 'mp4a.40.2';
  20744. } else {
  20745. audioCodec = 'mp4a.40.5';
  20746. }
  20747. }
  20748. return audioCodec;
  20749. }
  20750. _loadBitrateTestFrag(fragment, level) {
  20751. fragment.bitrateTest = true;
  20752. this._doFragLoad(fragment, level).then(data => {
  20753. const {
  20754. hls
  20755. } = this;
  20756. const frag = data == null ? void 0 : data.frag;
  20757. if (!frag || this.fragContextChanged(frag)) {
  20758. return;
  20759. }
  20760. level.fragmentError = 0;
  20761. this.state = State.IDLE;
  20762. this.startFragRequested = false;
  20763. this.bitrateTest = false;
  20764. const stats = frag.stats;
  20765. // Bitrate tests fragments are neither parsed nor buffered
  20766. stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
  20767. hls.trigger(Events.FRAG_LOADED, data);
  20768. frag.bitrateTest = false;
  20769. });
  20770. }
  20771. _handleTransmuxComplete(transmuxResult) {
  20772. var _id3$samples;
  20773. const id = this.playlistType;
  20774. const {
  20775. hls
  20776. } = this;
  20777. const {
  20778. remuxResult,
  20779. chunkMeta
  20780. } = transmuxResult;
  20781. const context = this.getCurrentContext(chunkMeta);
  20782. if (!context) {
  20783. this.resetWhenMissingContext(chunkMeta);
  20784. return;
  20785. }
  20786. const {
  20787. frag,
  20788. part,
  20789. level
  20790. } = context;
  20791. const {
  20792. video,
  20793. text,
  20794. id3,
  20795. initSegment
  20796. } = remuxResult;
  20797. const {
  20798. details
  20799. } = level;
  20800. // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track
  20801. const audio = this.altAudio ? undefined : remuxResult.audio;
  20802. // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
  20803. // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
  20804. if (this.fragContextChanged(frag)) {
  20805. this.fragmentTracker.removeFragment(frag);
  20806. return;
  20807. }
  20808. this.state = State.PARSING;
  20809. if (initSegment) {
  20810. if (initSegment != null && initSegment.tracks) {
  20811. const mapFragment = frag.initSegment || frag;
  20812. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  20813. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  20814. frag: mapFragment,
  20815. id,
  20816. tracks: initSegment.tracks
  20817. });
  20818. }
  20819. // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038
  20820. const baseTime = initSegment.initPTS;
  20821. const timescale = initSegment.timescale;
  20822. const initPTS = this.initPTS[frag.cc];
  20823. if (isFiniteNumber(baseTime) && (!initPTS || initPTS.baseTime !== baseTime || initPTS.timescale !== timescale)) {
  20824. this.initPTS[frag.cc] = {
  20825. baseTime,
  20826. timescale
  20827. };
  20828. hls.trigger(Events.INIT_PTS_FOUND, {
  20829. frag,
  20830. id,
  20831. initPTS: baseTime,
  20832. timescale
  20833. });
  20834. }
  20835. }
  20836. // Avoid buffering if backtracking this fragment
  20837. if (video && details) {
  20838. if (audio && video.type === 'audiovideo') {
  20839. this.logMuxedErr(frag);
  20840. }
  20841. const prevFrag = details.fragments[frag.sn - 1 - details.startSN];
  20842. const isFirstFragment = frag.sn === details.startSN;
  20843. const isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;
  20844. if (remuxResult.independent !== false) {
  20845. const {
  20846. startPTS,
  20847. endPTS,
  20848. startDTS,
  20849. endDTS
  20850. } = video;
  20851. if (part) {
  20852. part.elementaryStreams[video.type] = {
  20853. startPTS,
  20854. endPTS,
  20855. startDTS,
  20856. endDTS
  20857. };
  20858. } else {
  20859. if (video.firstKeyFrame && video.independent && chunkMeta.id === 1 && !isFirstInDiscontinuity) {
  20860. this.couldBacktrack = true;
  20861. }
  20862. if (video.dropped && video.independent) {
  20863. // Backtrack if dropped frames create a gap after currentTime
  20864. const bufferInfo = this.getMainFwdBufferInfo();
  20865. const targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole;
  20866. const startTime = video.firstKeyFramePTS ? video.firstKeyFramePTS : startPTS;
  20867. if (!isFirstFragment && targetBufferTime < startTime - this.config.maxBufferHole && !isFirstInDiscontinuity) {
  20868. this.backtrack(frag);
  20869. return;
  20870. } else if (isFirstInDiscontinuity) {
  20871. // Mark segment with a gap to avoid loop loading
  20872. frag.gap = true;
  20873. }
  20874. // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial
  20875. frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
  20876. } else if (isFirstFragment && startPTS - (details.appliedTimelineOffset || 0) > MAX_START_GAP_JUMP) {
  20877. // Mark segment with a gap to skip large start gap
  20878. frag.gap = true;
  20879. }
  20880. }
  20881. frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
  20882. if (this.backtrackFragment) {
  20883. this.backtrackFragment = frag;
  20884. }
  20885. this.bufferFragmentData(video, frag, part, chunkMeta, isFirstFragment || isFirstInDiscontinuity);
  20886. } else if (isFirstFragment || isFirstInDiscontinuity) {
  20887. // Mark segment with a gap to avoid loop loading
  20888. frag.gap = true;
  20889. } else {
  20890. this.backtrack(frag);
  20891. return;
  20892. }
  20893. }
  20894. if (audio) {
  20895. const {
  20896. startPTS,
  20897. endPTS,
  20898. startDTS,
  20899. endDTS
  20900. } = audio;
  20901. if (part) {
  20902. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  20903. startPTS,
  20904. endPTS,
  20905. startDTS,
  20906. endDTS
  20907. };
  20908. }
  20909. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  20910. this.bufferFragmentData(audio, frag, part, chunkMeta);
  20911. }
  20912. if (details && id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  20913. const emittedID3 = {
  20914. id,
  20915. frag,
  20916. details,
  20917. samples: id3.samples
  20918. };
  20919. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  20920. }
  20921. if (details && text) {
  20922. const emittedText = {
  20923. id,
  20924. frag,
  20925. details,
  20926. samples: text.samples
  20927. };
  20928. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  20929. }
  20930. }
  20931. logMuxedErr(frag) {
  20932. this.warn(`${isMediaFragment(frag) ? 'Media' : 'Init'} segment with muxed audiovideo where only video expected: ${frag.url}`);
  20933. }
  20934. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  20935. if (this.state !== State.PARSING) {
  20936. return;
  20937. }
  20938. this.audioOnly = !!tracks.audio && !tracks.video;
  20939. // if audio track is expected to come from audio stream controller, discard any coming from main
  20940. if (this.altAudio && !this.audioOnly) {
  20941. delete tracks.audio;
  20942. if (tracks.audiovideo) {
  20943. this.logMuxedErr(frag);
  20944. }
  20945. }
  20946. // include levelCodec in audio and video tracks
  20947. const {
  20948. audio,
  20949. video,
  20950. audiovideo
  20951. } = tracks;
  20952. if (audio) {
  20953. const levelCodec = currentLevel.audioCodec;
  20954. let audioCodec = pickMostCompleteCodecName(audio.codec, levelCodec);
  20955. // Add level and profile to make up for remuxer not being able to parse full codec
  20956. // (logger warning "Unhandled audio codec...")
  20957. if (audioCodec === 'mp4a') {
  20958. audioCodec = 'mp4a.40.5';
  20959. }
  20960. // Handle `audioCodecSwitch`
  20961. const ua = navigator.userAgent.toLowerCase();
  20962. if (this.audioCodecSwitch) {
  20963. if (audioCodec) {
  20964. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  20965. audioCodec = 'mp4a.40.2';
  20966. } else {
  20967. audioCodec = 'mp4a.40.5';
  20968. }
  20969. }
  20970. // In the case that AAC and HE-AAC audio codecs are signalled in manifest,
  20971. // force HE-AAC, as it seems that most browsers prefers it.
  20972. // don't force HE-AAC if mono stream, or in Firefox
  20973. const audioMetadata = audio.metadata;
  20974. if (audioMetadata && 'channelCount' in audioMetadata && (audioMetadata.channelCount || 1) !== 1 && ua.indexOf('firefox') === -1) {
  20975. audioCodec = 'mp4a.40.5';
  20976. }
  20977. }
  20978. // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  20979. if (audioCodec && audioCodec.indexOf('mp4a.40.5') !== -1 && ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {
  20980. // Exclude mpeg audio
  20981. audioCodec = 'mp4a.40.2';
  20982. this.log(`Android: force audio codec to ${audioCodec}`);
  20983. }
  20984. if (levelCodec && levelCodec !== audioCodec) {
  20985. this.log(`Swapping manifest audio codec "${levelCodec}" for "${audioCodec}"`);
  20986. }
  20987. audio.levelCodec = audioCodec;
  20988. audio.id = PlaylistLevelType.MAIN;
  20989. this.log(`Init audio buffer, container:${audio.container}, codecs[selected/level/parsed]=[${audioCodec || ''}/${levelCodec || ''}/${audio.codec}]`);
  20990. delete tracks.audiovideo;
  20991. }
  20992. if (video) {
  20993. video.levelCodec = currentLevel.videoCodec;
  20994. video.id = PlaylistLevelType.MAIN;
  20995. const parsedVideoCodec = video.codec;
  20996. if ((parsedVideoCodec == null ? void 0 : parsedVideoCodec.length) === 4) {
  20997. // Make up for passthrough-remuxer not being able to parse full codec
  20998. // (logger warning "Unhandled video codec...")
  20999. switch (parsedVideoCodec) {
  21000. case 'hvc1':
  21001. case 'hev1':
  21002. video.codec = 'hvc1.1.6.L120.90';
  21003. break;
  21004. case 'av01':
  21005. video.codec = 'av01.0.04M.08';
  21006. break;
  21007. case 'avc1':
  21008. video.codec = 'avc1.42e01e';
  21009. break;
  21010. }
  21011. }
  21012. 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 : ''}`);
  21013. delete tracks.audiovideo;
  21014. }
  21015. if (audiovideo) {
  21016. this.log(`Init audiovideo buffer, container:${audiovideo.container}, codecs[level/parsed]=[${currentLevel.codecs}/${audiovideo.codec}]`);
  21017. delete tracks.video;
  21018. delete tracks.audio;
  21019. }
  21020. const trackTypes = Object.keys(tracks);
  21021. if (trackTypes.length) {
  21022. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  21023. if (!this.hls) {
  21024. // Exit after fatal tracks error
  21025. return;
  21026. }
  21027. // loop through tracks that are going to be provided to bufferController
  21028. trackTypes.forEach(trackName => {
  21029. const track = tracks[trackName];
  21030. const initSegment = track.initSegment;
  21031. if (initSegment != null && initSegment.byteLength) {
  21032. this.hls.trigger(Events.BUFFER_APPENDING, {
  21033. type: trackName,
  21034. data: initSegment,
  21035. frag,
  21036. part: null,
  21037. chunkMeta,
  21038. parent: frag.type
  21039. });
  21040. }
  21041. });
  21042. }
  21043. // trigger handler right now
  21044. this.tickImmediate();
  21045. }
  21046. getMainFwdBufferInfo() {
  21047. // Observe video SourceBuffer (this.mediaBuffer) only when alt-audio is used, otherwise observe combined media buffer
  21048. const bufferOutput = this.mediaBuffer && this.altAudio === 2 ? this.mediaBuffer : this.media;
  21049. return this.getFwdBufferInfo(bufferOutput, PlaylistLevelType.MAIN);
  21050. }
  21051. get maxBufferLength() {
  21052. const {
  21053. levels,
  21054. level
  21055. } = this;
  21056. const levelInfo = levels == null ? void 0 : levels[level];
  21057. if (!levelInfo) {
  21058. return this.config.maxBufferLength;
  21059. }
  21060. return this.getMaxBufferLength(levelInfo.maxBitrate);
  21061. }
  21062. backtrack(frag) {
  21063. this.couldBacktrack = true;
  21064. // Causes findFragments to backtrack through fragments to find the keyframe
  21065. this.backtrackFragment = frag;
  21066. this.resetTransmuxer();
  21067. this.flushBufferGap(frag);
  21068. this.fragmentTracker.removeFragment(frag);
  21069. this.fragPrevious = null;
  21070. this.nextLoadPosition = frag.start;
  21071. this.state = State.IDLE;
  21072. }
  21073. checkFragmentChanged() {
  21074. const video = this.media;
  21075. let fragPlayingCurrent = null;
  21076. if (video && video.readyState > 1 && video.seeking === false) {
  21077. const currentTime = video.currentTime;
  21078. /* if video element is in seeked state, currentTime can only increase.
  21079. (assuming that playback rate is positive ...)
  21080. As sometimes currentTime jumps back to zero after a
  21081. media decode error, check this, to avoid seeking back to
  21082. wrong position after a media decode error
  21083. */
  21084. if (BufferHelper.isBuffered(video, currentTime)) {
  21085. fragPlayingCurrent = this.getAppendedFrag(currentTime);
  21086. } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
  21087. /* ensure that FRAG_CHANGED event is triggered at startup,
  21088. when first video frame is displayed and playback is paused.
  21089. add a tolerance of 100ms, in case current position is not buffered,
  21090. check if current pos+100ms is buffered and use that buffer range
  21091. for FRAG_CHANGED event reporting */
  21092. fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
  21093. }
  21094. if (fragPlayingCurrent) {
  21095. this.backtrackFragment = null;
  21096. const fragPlaying = this.fragPlaying;
  21097. const fragCurrentLevel = fragPlayingCurrent.level;
  21098. if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel) {
  21099. this.fragPlaying = fragPlayingCurrent;
  21100. this.hls.trigger(Events.FRAG_CHANGED, {
  21101. frag: fragPlayingCurrent
  21102. });
  21103. if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
  21104. this.hls.trigger(Events.LEVEL_SWITCHED, {
  21105. level: fragCurrentLevel
  21106. });
  21107. }
  21108. }
  21109. }
  21110. }
  21111. }
  21112. get nextLevel() {
  21113. const frag = this.nextBufferedFrag;
  21114. if (frag) {
  21115. return frag.level;
  21116. }
  21117. return -1;
  21118. }
  21119. get currentFrag() {
  21120. var _this$media3;
  21121. if (this.fragPlaying) {
  21122. return this.fragPlaying;
  21123. }
  21124. const currentTime = ((_this$media3 = this.media) == null ? void 0 : _this$media3.currentTime) || this.lastCurrentTime;
  21125. if (isFiniteNumber(currentTime)) {
  21126. return this.getAppendedFrag(currentTime);
  21127. }
  21128. return null;
  21129. }
  21130. get currentProgramDateTime() {
  21131. var _this$media4;
  21132. const currentTime = ((_this$media4 = this.media) == null ? void 0 : _this$media4.currentTime) || this.lastCurrentTime;
  21133. if (isFiniteNumber(currentTime)) {
  21134. const details = this.getLevelDetails();
  21135. const frag = this.currentFrag || (details ? findFragmentByPTS(null, details.fragments, currentTime) : null);
  21136. if (frag) {
  21137. const programDateTime = frag.programDateTime;
  21138. if (programDateTime !== null) {
  21139. const epocMs = programDateTime + (currentTime - frag.start) * 1000;
  21140. return new Date(epocMs);
  21141. }
  21142. }
  21143. }
  21144. return null;
  21145. }
  21146. get currentLevel() {
  21147. const frag = this.currentFrag;
  21148. if (frag) {
  21149. return frag.level;
  21150. }
  21151. return -1;
  21152. }
  21153. get nextBufferedFrag() {
  21154. const frag = this.currentFrag;
  21155. if (frag) {
  21156. return this.followingBufferedFrag(frag);
  21157. }
  21158. return null;
  21159. }
  21160. get forceStartLoad() {
  21161. return this._forceStartLoad;
  21162. }
  21163. }
  21164. class KeyLoader {
  21165. constructor(config) {
  21166. this.config = void 0;
  21167. this.keyUriToKeyInfo = {};
  21168. this.emeController = null;
  21169. this.config = config;
  21170. }
  21171. abort(type) {
  21172. for (const uri in this.keyUriToKeyInfo) {
  21173. const loader = this.keyUriToKeyInfo[uri].loader;
  21174. if (loader) {
  21175. var _loader$context;
  21176. if (type && type !== ((_loader$context = loader.context) == null ? void 0 : _loader$context.frag.type)) {
  21177. return;
  21178. }
  21179. loader.abort();
  21180. }
  21181. }
  21182. }
  21183. detach() {
  21184. for (const uri in this.keyUriToKeyInfo) {
  21185. const keyInfo = this.keyUriToKeyInfo[uri];
  21186. // Remove cached EME keys on detach
  21187. if (keyInfo.mediaKeySessionContext || keyInfo.decryptdata.isCommonEncryption) {
  21188. delete this.keyUriToKeyInfo[uri];
  21189. }
  21190. }
  21191. }
  21192. destroy() {
  21193. this.detach();
  21194. for (const uri in this.keyUriToKeyInfo) {
  21195. const loader = this.keyUriToKeyInfo[uri].loader;
  21196. if (loader) {
  21197. loader.destroy();
  21198. }
  21199. }
  21200. this.keyUriToKeyInfo = {};
  21201. }
  21202. createKeyLoadError(frag, details = ErrorDetails.KEY_LOAD_ERROR, error, networkDetails, response) {
  21203. return new LoadError({
  21204. type: ErrorTypes.NETWORK_ERROR,
  21205. details,
  21206. fatal: false,
  21207. frag,
  21208. response,
  21209. error,
  21210. networkDetails
  21211. });
  21212. }
  21213. loadClear(loadingFrag, encryptedFragments, startFragRequested) {
  21214. if (this.emeController && this.config.emeEnabled && !this.emeController.getSelectedKeySystemFormats().length) {
  21215. // Access key-system with nearest key on start (loading frag is unencrypted)
  21216. if (encryptedFragments.length) {
  21217. for (let i = 0, l = encryptedFragments.length; i < l; i++) {
  21218. const frag = encryptedFragments[i];
  21219. // Loading at or before segment with EXT-X-KEY, or first frag loading and last EXT-X-KEY
  21220. if (loadingFrag.cc <= frag.cc && (!isMediaFragment(loadingFrag) || !isMediaFragment(frag) || loadingFrag.sn < frag.sn) || !startFragRequested && i == l - 1) {
  21221. return this.emeController.selectKeySystemFormat(frag).then(keySystemFormat => {
  21222. if (!this.emeController) {
  21223. return;
  21224. }
  21225. frag.setKeyFormat(keySystemFormat);
  21226. const keySystem = emptyEsExports.keySystemFormatToKeySystemDomain(keySystemFormat);
  21227. if (keySystem) {
  21228. return this.emeController.getKeySystemAccess([keySystem]);
  21229. }
  21230. });
  21231. }
  21232. }
  21233. }
  21234. if (this.config.requireKeySystemAccessOnStart) {
  21235. const keySystemsInConfig = emptyEsExports.getKeySystemsForConfig(this.config);
  21236. if (keySystemsInConfig.length) {
  21237. return this.emeController.getKeySystemAccess(keySystemsInConfig);
  21238. }
  21239. }
  21240. }
  21241. return null;
  21242. }
  21243. load(frag) {
  21244. if (!frag.decryptdata && frag.encrypted && this.emeController && this.config.emeEnabled) {
  21245. // Multiple keys, but none selected, resolve in eme-controller
  21246. return this.emeController.selectKeySystemFormat(frag).then(keySystemFormat => {
  21247. return this.loadInternal(frag, keySystemFormat);
  21248. });
  21249. }
  21250. return this.loadInternal(frag);
  21251. }
  21252. loadInternal(frag, keySystemFormat) {
  21253. var _keyInfo, _keyInfo2;
  21254. if (keySystemFormat) {
  21255. frag.setKeyFormat(keySystemFormat);
  21256. }
  21257. const decryptdata = frag.decryptdata;
  21258. if (!decryptdata) {
  21259. const error = new Error(keySystemFormat ? `Expected frag.decryptdata to be defined after setting format ${keySystemFormat}` : 'Missing decryption data on fragment in onKeyLoading');
  21260. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error));
  21261. }
  21262. const uri = decryptdata.uri;
  21263. if (!uri) {
  21264. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Invalid key URI: "${uri}"`)));
  21265. }
  21266. let keyInfo = this.keyUriToKeyInfo[uri];
  21267. if ((_keyInfo = keyInfo) != null && _keyInfo.decryptdata.key) {
  21268. decryptdata.key = keyInfo.decryptdata.key;
  21269. return Promise.resolve({
  21270. frag,
  21271. keyInfo
  21272. });
  21273. }
  21274. // Return key load promise as long as it does not have a mediakey session with an unusable key status
  21275. if ((_keyInfo2 = keyInfo) != null && _keyInfo2.keyLoadPromise) {
  21276. var _keyInfo$mediaKeySess;
  21277. switch ((_keyInfo$mediaKeySess = keyInfo.mediaKeySessionContext) == null ? void 0 : _keyInfo$mediaKeySess.keyStatus) {
  21278. case undefined:
  21279. case 'status-pending':
  21280. case 'usable':
  21281. case 'usable-in-future':
  21282. return keyInfo.keyLoadPromise.then(keyLoadedData => {
  21283. // Return the correct fragment with updated decryptdata key and loaded keyInfo
  21284. decryptdata.key = keyLoadedData.keyInfo.decryptdata.key;
  21285. return {
  21286. frag,
  21287. keyInfo
  21288. };
  21289. });
  21290. }
  21291. // If we have a key session and status and it is not pending or usable, continue
  21292. // This will go back to the eme-controller for expired keys to get a new keyLoadPromise
  21293. }
  21294. // Load the key or return the loading promise
  21295. keyInfo = this.keyUriToKeyInfo[uri] = {
  21296. decryptdata,
  21297. keyLoadPromise: null,
  21298. loader: null,
  21299. mediaKeySessionContext: null
  21300. };
  21301. switch (decryptdata.method) {
  21302. case 'ISO-23001-7':
  21303. case 'SAMPLE-AES':
  21304. case 'SAMPLE-AES-CENC':
  21305. case 'SAMPLE-AES-CTR':
  21306. if (decryptdata.keyFormat === 'identity') {
  21307. // loadKeyHTTP handles http(s) and data URLs
  21308. return this.loadKeyHTTP(keyInfo, frag);
  21309. }
  21310. return this.loadKeyEME(keyInfo, frag);
  21311. case 'AES-128':
  21312. case 'AES-256':
  21313. case 'AES-256-CTR':
  21314. return this.loadKeyHTTP(keyInfo, frag);
  21315. default:
  21316. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Key supplied with unsupported METHOD: "${decryptdata.method}"`)));
  21317. }
  21318. }
  21319. loadKeyEME(keyInfo, frag) {
  21320. const keyLoadedData = {
  21321. frag,
  21322. keyInfo
  21323. };
  21324. if (this.emeController && this.config.emeEnabled) {
  21325. const keySessionContextPromise = this.emeController.loadKey(keyLoadedData);
  21326. if (keySessionContextPromise) {
  21327. return (keyInfo.keyLoadPromise = keySessionContextPromise.then(keySessionContext => {
  21328. keyInfo.mediaKeySessionContext = keySessionContext;
  21329. return keyLoadedData;
  21330. })).catch(error => {
  21331. // Remove promise for license renewal or retry
  21332. keyInfo.keyLoadPromise = null;
  21333. throw error;
  21334. });
  21335. }
  21336. }
  21337. return Promise.resolve(keyLoadedData);
  21338. }
  21339. loadKeyHTTP(keyInfo, frag) {
  21340. const config = this.config;
  21341. const Loader = config.loader;
  21342. const keyLoader = new Loader(config);
  21343. frag.keyLoader = keyInfo.loader = keyLoader;
  21344. return keyInfo.keyLoadPromise = new Promise((resolve, reject) => {
  21345. const loaderContext = {
  21346. keyInfo,
  21347. frag,
  21348. responseType: 'arraybuffer',
  21349. url: keyInfo.decryptdata.uri
  21350. };
  21351. // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
  21352. // key-loader will trigger an error and rely on stream-controller to handle retry logic.
  21353. // this will also align retry logic with fragment-loader
  21354. const loadPolicy = config.keyLoadPolicy.default;
  21355. const loaderConfig = {
  21356. loadPolicy,
  21357. timeout: loadPolicy.maxLoadTimeMs,
  21358. maxRetry: 0,
  21359. retryDelay: 0,
  21360. maxRetryDelay: 0
  21361. };
  21362. const loaderCallbacks = {
  21363. onSuccess: (response, stats, context, networkDetails) => {
  21364. const {
  21365. frag,
  21366. keyInfo,
  21367. url: uri
  21368. } = context;
  21369. if (!frag.decryptdata || keyInfo !== this.keyUriToKeyInfo[uri]) {
  21370. return reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error('after key load, decryptdata unset or changed'), networkDetails));
  21371. }
  21372. keyInfo.decryptdata.key = frag.decryptdata.key = new Uint8Array(response.data);
  21373. // detach fragment key loader on load success
  21374. frag.keyLoader = null;
  21375. keyInfo.loader = null;
  21376. resolve({
  21377. frag,
  21378. keyInfo
  21379. });
  21380. },
  21381. onError: (response, context, networkDetails, stats) => {
  21382. this.resetLoader(context);
  21383. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`HTTP Error ${response.code} loading key ${response.text}`), networkDetails, _objectSpread2({
  21384. url: loaderContext.url,
  21385. data: undefined
  21386. }, response)));
  21387. },
  21388. onTimeout: (stats, context, networkDetails) => {
  21389. this.resetLoader(context);
  21390. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_TIMEOUT, new Error('key loading timed out'), networkDetails));
  21391. },
  21392. onAbort: (stats, context, networkDetails) => {
  21393. this.resetLoader(context);
  21394. reject(this.createKeyLoadError(frag, ErrorDetails.INTERNAL_ABORTED, new Error('key loading aborted'), networkDetails));
  21395. }
  21396. };
  21397. keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  21398. });
  21399. }
  21400. resetLoader(context) {
  21401. const {
  21402. frag,
  21403. keyInfo,
  21404. url: uri
  21405. } = context;
  21406. const loader = keyInfo.loader;
  21407. if (frag.keyLoader === loader) {
  21408. frag.keyLoader = null;
  21409. keyInfo.loader = null;
  21410. }
  21411. delete this.keyUriToKeyInfo[uri];
  21412. if (loader) {
  21413. loader.destroy();
  21414. }
  21415. }
  21416. }
  21417. function mapContextToLevelType(context) {
  21418. const {
  21419. type
  21420. } = context;
  21421. switch (type) {
  21422. case PlaylistContextType.AUDIO_TRACK:
  21423. return PlaylistLevelType.AUDIO;
  21424. case PlaylistContextType.SUBTITLE_TRACK:
  21425. return PlaylistLevelType.SUBTITLE;
  21426. default:
  21427. return PlaylistLevelType.MAIN;
  21428. }
  21429. }
  21430. function getResponseUrl(response, context) {
  21431. let url = response.url;
  21432. // responseURL not supported on some browsers (it is used to detect URL redirection)
  21433. // data-uri mode also not supported (but no need to detect redirection)
  21434. if (url === undefined || url.indexOf('data:') === 0) {
  21435. // fallback to initial URL
  21436. url = context.url;
  21437. }
  21438. return url;
  21439. }
  21440. class PlaylistLoader {
  21441. constructor(hls) {
  21442. this.hls = void 0;
  21443. this.loaders = Object.create(null);
  21444. this.variableList = null;
  21445. this.onManifestLoaded = this.checkAutostartLoad;
  21446. this.hls = hls;
  21447. this.registerListeners();
  21448. }
  21449. startLoad(startPosition) {}
  21450. stopLoad() {
  21451. this.destroyInternalLoaders();
  21452. }
  21453. registerListeners() {
  21454. const {
  21455. hls
  21456. } = this;
  21457. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21458. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  21459. hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  21460. hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  21461. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  21462. }
  21463. unregisterListeners() {
  21464. const {
  21465. hls
  21466. } = this;
  21467. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21468. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  21469. hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  21470. hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  21471. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  21472. }
  21473. /**
  21474. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  21475. */
  21476. createInternalLoader(context) {
  21477. const config = this.hls.config;
  21478. const PLoader = config.pLoader;
  21479. const Loader = config.loader;
  21480. const InternalLoader = PLoader || Loader;
  21481. const loader = new InternalLoader(config);
  21482. this.loaders[context.type] = loader;
  21483. return loader;
  21484. }
  21485. getInternalLoader(context) {
  21486. return this.loaders[context.type];
  21487. }
  21488. resetInternalLoader(contextType) {
  21489. if (this.loaders[contextType]) {
  21490. delete this.loaders[contextType];
  21491. }
  21492. }
  21493. /**
  21494. * Call `destroy` on all internal loader instances mapped (one per context type)
  21495. */
  21496. destroyInternalLoaders() {
  21497. for (const contextType in this.loaders) {
  21498. const loader = this.loaders[contextType];
  21499. if (loader) {
  21500. loader.destroy();
  21501. }
  21502. this.resetInternalLoader(contextType);
  21503. }
  21504. }
  21505. destroy() {
  21506. this.variableList = null;
  21507. this.unregisterListeners();
  21508. this.destroyInternalLoaders();
  21509. }
  21510. onManifestLoading(event, data) {
  21511. const {
  21512. url
  21513. } = data;
  21514. this.variableList = null;
  21515. this.load({
  21516. id: null,
  21517. level: 0,
  21518. responseType: 'text',
  21519. type: PlaylistContextType.MANIFEST,
  21520. url,
  21521. deliveryDirectives: null,
  21522. levelOrTrack: null
  21523. });
  21524. }
  21525. onLevelLoading(event, data) {
  21526. const {
  21527. id,
  21528. level,
  21529. pathwayId,
  21530. url,
  21531. deliveryDirectives,
  21532. levelInfo
  21533. } = data;
  21534. this.load({
  21535. id,
  21536. level,
  21537. pathwayId,
  21538. responseType: 'text',
  21539. type: PlaylistContextType.LEVEL,
  21540. url,
  21541. deliveryDirectives,
  21542. levelOrTrack: levelInfo
  21543. });
  21544. }
  21545. onAudioTrackLoading(event, data) {
  21546. const {
  21547. id,
  21548. groupId,
  21549. url,
  21550. deliveryDirectives,
  21551. track
  21552. } = data;
  21553. this.load({
  21554. id,
  21555. groupId,
  21556. level: null,
  21557. responseType: 'text',
  21558. type: PlaylistContextType.AUDIO_TRACK,
  21559. url,
  21560. deliveryDirectives,
  21561. levelOrTrack: track
  21562. });
  21563. }
  21564. onSubtitleTrackLoading(event, data) {
  21565. const {
  21566. id,
  21567. groupId,
  21568. url,
  21569. deliveryDirectives,
  21570. track
  21571. } = data;
  21572. this.load({
  21573. id,
  21574. groupId,
  21575. level: null,
  21576. responseType: 'text',
  21577. type: PlaylistContextType.SUBTITLE_TRACK,
  21578. url,
  21579. deliveryDirectives,
  21580. levelOrTrack: track
  21581. });
  21582. }
  21583. onLevelsUpdated(event, data) {
  21584. // abort and delete loader of removed levels
  21585. const loader = this.loaders[PlaylistContextType.LEVEL];
  21586. if (loader) {
  21587. const context = loader.context;
  21588. if (context && !data.levels.some(lvl => lvl === context.levelOrTrack)) {
  21589. loader.abort();
  21590. delete this.loaders[PlaylistContextType.LEVEL];
  21591. }
  21592. }
  21593. }
  21594. load(context) {
  21595. var _context$deliveryDire;
  21596. const config = this.hls.config;
  21597. // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);
  21598. // Check if a loader for this context already exists
  21599. let loader = this.getInternalLoader(context);
  21600. if (loader) {
  21601. const logger = this.hls.logger;
  21602. const loaderContext = loader.context;
  21603. if (loaderContext && loaderContext.levelOrTrack === context.levelOrTrack && (loaderContext.url === context.url || loaderContext.deliveryDirectives && !context.deliveryDirectives)) {
  21604. // same URL can't overlap, or wait for blocking request
  21605. if (loaderContext.url === context.url) {
  21606. logger.log(`[playlist-loader]: ignore ${context.url} ongoing request`);
  21607. } else {
  21608. logger.log(`[playlist-loader]: ignore ${context.url} in favor of ${loaderContext.url}`);
  21609. }
  21610. return;
  21611. }
  21612. logger.log(`[playlist-loader]: aborting previous loader for type: ${context.type}`);
  21613. loader.abort();
  21614. }
  21615. // apply different configs for retries depending on
  21616. // context (manifest, level, audio/subs playlist)
  21617. let loadPolicy;
  21618. if (context.type === PlaylistContextType.MANIFEST) {
  21619. loadPolicy = config.manifestLoadPolicy.default;
  21620. } else {
  21621. loadPolicy = _extends({}, config.playlistLoadPolicy.default, {
  21622. timeoutRetry: null,
  21623. errorRetry: null
  21624. });
  21625. }
  21626. loader = this.createInternalLoader(context);
  21627. // Override level/track timeout for LL-HLS requests
  21628. // (the default of 10000ms is counter productive to blocking playlist reload requests)
  21629. if (isFiniteNumber((_context$deliveryDire = context.deliveryDirectives) == null ? void 0 : _context$deliveryDire.part)) {
  21630. let levelDetails;
  21631. if (context.type === PlaylistContextType.LEVEL && context.level !== null) {
  21632. levelDetails = this.hls.levels[context.level].details;
  21633. } else if (context.type === PlaylistContextType.AUDIO_TRACK && context.id !== null) {
  21634. levelDetails = this.hls.audioTracks[context.id].details;
  21635. } else if (context.type === PlaylistContextType.SUBTITLE_TRACK && context.id !== null) {
  21636. levelDetails = this.hls.subtitleTracks[context.id].details;
  21637. }
  21638. if (levelDetails) {
  21639. const partTarget = levelDetails.partTarget;
  21640. const targetDuration = levelDetails.targetduration;
  21641. if (partTarget && targetDuration) {
  21642. const maxLowLatencyPlaylistRefresh = Math.max(partTarget * 3, targetDuration * 0.8) * 1000;
  21643. loadPolicy = _extends({}, loadPolicy, {
  21644. maxTimeToFirstByteMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs),
  21645. maxLoadTimeMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs)
  21646. });
  21647. }
  21648. }
  21649. }
  21650. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  21651. const loaderConfig = {
  21652. loadPolicy,
  21653. timeout: loadPolicy.maxLoadTimeMs,
  21654. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  21655. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  21656. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  21657. };
  21658. const loaderCallbacks = {
  21659. onSuccess: (response, stats, context, networkDetails) => {
  21660. const loader = this.getInternalLoader(context);
  21661. this.resetInternalLoader(context.type);
  21662. const string = response.data;
  21663. // Validate if it is an M3U8 at all
  21664. if (string.indexOf('#EXTM3U') !== 0) {
  21665. this.handleManifestParsingError(response, context, new Error('no EXTM3U delimiter'), networkDetails || null, stats);
  21666. return;
  21667. }
  21668. stats.parsing.start = performance.now();
  21669. if (M3U8Parser.isMediaPlaylist(string) || context.type !== PlaylistContextType.MANIFEST) {
  21670. this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails || null, loader);
  21671. } else {
  21672. this.handleMasterPlaylist(response, stats, context, networkDetails);
  21673. }
  21674. },
  21675. onError: (response, context, networkDetails, stats) => {
  21676. this.handleNetworkError(context, networkDetails, false, response, stats);
  21677. },
  21678. onTimeout: (stats, context, networkDetails) => {
  21679. this.handleNetworkError(context, networkDetails, true, undefined, stats);
  21680. }
  21681. };
  21682. // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);
  21683. loader.load(context, loaderConfig, loaderCallbacks);
  21684. }
  21685. checkAutostartLoad() {
  21686. if (!this.hls) {
  21687. return;
  21688. }
  21689. const {
  21690. config: {
  21691. autoStartLoad,
  21692. startPosition
  21693. },
  21694. forceStartLoad
  21695. } = this.hls;
  21696. if (autoStartLoad || forceStartLoad) {
  21697. this.hls.logger.log(`${autoStartLoad ? 'auto' : 'force'} startLoad with configured startPosition ${startPosition}`);
  21698. this.hls.startLoad(startPosition);
  21699. }
  21700. }
  21701. handleMasterPlaylist(response, stats, context, networkDetails) {
  21702. const hls = this.hls;
  21703. const string = response.data;
  21704. const url = getResponseUrl(response, context);
  21705. const parsedResult = M3U8Parser.parseMasterPlaylist(string, url);
  21706. if (parsedResult.playlistParsingError) {
  21707. this.handleManifestParsingError(response, context, parsedResult.playlistParsingError, networkDetails, stats);
  21708. return;
  21709. }
  21710. const {
  21711. contentSteering,
  21712. levels,
  21713. sessionData,
  21714. sessionKeys,
  21715. startTimeOffset,
  21716. variableList
  21717. } = parsedResult;
  21718. this.variableList = variableList;
  21719. const {
  21720. AUDIO: audioTracks = [],
  21721. SUBTITLES: subtitles,
  21722. 'CLOSED-CAPTIONS': captions
  21723. } = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult);
  21724. if (audioTracks.length) {
  21725. // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
  21726. const embeddedAudioFound = audioTracks.some(audioTrack => !audioTrack.url);
  21727. // if no embedded audio track defined, but audio codec signaled in quality level,
  21728. // we need to signal this main audio track this could happen with playlists with
  21729. // alt audio rendition in which quality levels (main)
  21730. // contains both audio+video. but with mixed audio track not signaled
  21731. if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  21732. this.hls.logger.log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one');
  21733. audioTracks.unshift({
  21734. type: 'main',
  21735. name: 'main',
  21736. groupId: 'main',
  21737. default: false,
  21738. autoselect: false,
  21739. forced: false,
  21740. id: -1,
  21741. attrs: new AttrList({}),
  21742. bitrate: 0,
  21743. url: ''
  21744. });
  21745. }
  21746. }
  21747. hls.trigger(Events.MANIFEST_LOADED, {
  21748. levels,
  21749. audioTracks,
  21750. subtitles,
  21751. captions,
  21752. contentSteering,
  21753. url,
  21754. stats,
  21755. networkDetails,
  21756. sessionData,
  21757. sessionKeys,
  21758. startTimeOffset,
  21759. variableList
  21760. });
  21761. }
  21762. handleTrackOrLevelPlaylist(response, stats, context, networkDetails, loader) {
  21763. const hls = this.hls;
  21764. const {
  21765. id,
  21766. level,
  21767. type
  21768. } = context;
  21769. const url = getResponseUrl(response, context);
  21770. const levelId = isFiniteNumber(level) ? level : isFiniteNumber(id) ? id : 0;
  21771. const levelType = mapContextToLevelType(context);
  21772. const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, 0, this.variableList);
  21773. // We have done our first request (Manifest-type) and receive
  21774. // not a master playlist but a chunk-list (track/level)
  21775. // We fire the manifest-loaded event anyway with the parsed level-details
  21776. // by creating a single-level structure for it.
  21777. if (type === PlaylistContextType.MANIFEST) {
  21778. const singleLevel = {
  21779. attrs: new AttrList({}),
  21780. bitrate: 0,
  21781. details: levelDetails,
  21782. name: '',
  21783. url
  21784. };
  21785. levelDetails.requestScheduled = stats.loading.start + computeReloadInterval(levelDetails, 0);
  21786. hls.trigger(Events.MANIFEST_LOADED, {
  21787. levels: [singleLevel],
  21788. audioTracks: [],
  21789. url,
  21790. stats,
  21791. networkDetails,
  21792. sessionData: null,
  21793. sessionKeys: null,
  21794. contentSteering: null,
  21795. startTimeOffset: null,
  21796. variableList: null
  21797. });
  21798. }
  21799. // save parsing time
  21800. stats.parsing.end = performance.now();
  21801. // extend the context with the new levelDetails property
  21802. context.levelDetails = levelDetails;
  21803. this.handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader);
  21804. }
  21805. handleManifestParsingError(response, context, error, networkDetails, stats) {
  21806. this.hls.trigger(Events.ERROR, {
  21807. type: ErrorTypes.NETWORK_ERROR,
  21808. details: ErrorDetails.MANIFEST_PARSING_ERROR,
  21809. fatal: context.type === PlaylistContextType.MANIFEST,
  21810. url: response.url,
  21811. err: error,
  21812. error,
  21813. reason: error.message,
  21814. response,
  21815. context,
  21816. networkDetails,
  21817. stats
  21818. });
  21819. }
  21820. handleNetworkError(context, networkDetails, timeout = false, response, stats) {
  21821. let message = `A network ${timeout ? 'timeout' : 'error' + (response ? ' (status ' + response.code + ')' : '')} occurred while loading ${context.type}`;
  21822. if (context.type === PlaylistContextType.LEVEL) {
  21823. message += `: ${context.level} id: ${context.id}`;
  21824. } else if (context.type === PlaylistContextType.AUDIO_TRACK || context.type === PlaylistContextType.SUBTITLE_TRACK) {
  21825. message += ` id: ${context.id} group-id: "${context.groupId}"`;
  21826. }
  21827. const error = new Error(message);
  21828. this.hls.logger.warn(`[playlist-loader]: ${message}`);
  21829. let details = ErrorDetails.UNKNOWN;
  21830. let fatal = false;
  21831. const loader = this.getInternalLoader(context);
  21832. switch (context.type) {
  21833. case PlaylistContextType.MANIFEST:
  21834. details = timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR;
  21835. fatal = true;
  21836. break;
  21837. case PlaylistContextType.LEVEL:
  21838. details = timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR;
  21839. fatal = false;
  21840. break;
  21841. case PlaylistContextType.AUDIO_TRACK:
  21842. details = timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  21843. fatal = false;
  21844. break;
  21845. case PlaylistContextType.SUBTITLE_TRACK:
  21846. details = timeout ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_LOAD_ERROR;
  21847. fatal = false;
  21848. break;
  21849. }
  21850. if (loader) {
  21851. this.resetInternalLoader(context.type);
  21852. }
  21853. const errorData = {
  21854. type: ErrorTypes.NETWORK_ERROR,
  21855. details,
  21856. fatal,
  21857. url: context.url,
  21858. loader,
  21859. context,
  21860. error,
  21861. networkDetails,
  21862. stats
  21863. };
  21864. if (response) {
  21865. const url = (networkDetails == null ? void 0 : networkDetails.url) || context.url;
  21866. errorData.response = _objectSpread2({
  21867. url,
  21868. data: undefined
  21869. }, response);
  21870. }
  21871. this.hls.trigger(Events.ERROR, errorData);
  21872. }
  21873. handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader) {
  21874. const hls = this.hls;
  21875. const {
  21876. type,
  21877. level,
  21878. id,
  21879. groupId,
  21880. deliveryDirectives
  21881. } = context;
  21882. const url = getResponseUrl(response, context);
  21883. const parent = mapContextToLevelType(context);
  21884. const levelIndex = typeof context.level === 'number' && parent === PlaylistLevelType.MAIN ? level : undefined;
  21885. if (!levelDetails.fragments.length) {
  21886. const _error = levelDetails.playlistParsingError = new Error('No Segments found in Playlist');
  21887. hls.trigger(Events.ERROR, {
  21888. type: ErrorTypes.NETWORK_ERROR,
  21889. details: ErrorDetails.LEVEL_EMPTY_ERROR,
  21890. fatal: false,
  21891. url,
  21892. error: _error,
  21893. reason: _error.message,
  21894. response,
  21895. context,
  21896. level: levelIndex,
  21897. parent,
  21898. networkDetails,
  21899. stats
  21900. });
  21901. return;
  21902. }
  21903. if (!levelDetails.targetduration) {
  21904. levelDetails.playlistParsingError = new Error('Missing Target Duration');
  21905. }
  21906. const error = levelDetails.playlistParsingError;
  21907. if (error) {
  21908. this.hls.logger.warn(error);
  21909. if (!hls.config.ignorePlaylistParsingErrors) {
  21910. hls.trigger(Events.ERROR, {
  21911. type: ErrorTypes.NETWORK_ERROR,
  21912. details: ErrorDetails.LEVEL_PARSING_ERROR,
  21913. fatal: false,
  21914. url,
  21915. error,
  21916. reason: error.message,
  21917. response,
  21918. context,
  21919. level: levelIndex,
  21920. parent,
  21921. networkDetails,
  21922. stats
  21923. });
  21924. return;
  21925. }
  21926. levelDetails.playlistParsingError = null;
  21927. }
  21928. if (levelDetails.live && loader) {
  21929. if (loader.getCacheAge) {
  21930. levelDetails.ageHeader = loader.getCacheAge() || 0;
  21931. }
  21932. if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
  21933. levelDetails.ageHeader = 0;
  21934. }
  21935. }
  21936. switch (type) {
  21937. case PlaylistContextType.MANIFEST:
  21938. case PlaylistContextType.LEVEL:
  21939. hls.trigger(Events.LEVEL_LOADED, {
  21940. details: levelDetails,
  21941. levelInfo: context.levelOrTrack || hls.levels[0],
  21942. level: levelIndex || 0,
  21943. id: id || 0,
  21944. stats,
  21945. networkDetails,
  21946. deliveryDirectives,
  21947. withoutMultiVariant: type === PlaylistContextType.MANIFEST
  21948. });
  21949. break;
  21950. case PlaylistContextType.AUDIO_TRACK:
  21951. hls.trigger(Events.AUDIO_TRACK_LOADED, {
  21952. details: levelDetails,
  21953. track: context.levelOrTrack,
  21954. id: id || 0,
  21955. groupId: groupId || '',
  21956. stats,
  21957. networkDetails,
  21958. deliveryDirectives
  21959. });
  21960. break;
  21961. case PlaylistContextType.SUBTITLE_TRACK:
  21962. hls.trigger(Events.SUBTITLE_TRACK_LOADED, {
  21963. details: levelDetails,
  21964. track: context.levelOrTrack,
  21965. id: id || 0,
  21966. groupId: groupId || '',
  21967. stats,
  21968. networkDetails,
  21969. deliveryDirectives
  21970. });
  21971. break;
  21972. }
  21973. }
  21974. }
  21975. const SUPPORTED_INFO_DEFAULT = {
  21976. supported: true,
  21977. configurations: [],
  21978. decodingInfoResults: [{
  21979. supported: true,
  21980. powerEfficient: true,
  21981. smooth: true
  21982. }]
  21983. };
  21984. function getUnsupportedResult(error, configurations) {
  21985. return {
  21986. supported: false,
  21987. configurations,
  21988. decodingInfoResults: [{
  21989. supported: false,
  21990. smooth: false,
  21991. powerEfficient: false
  21992. }],
  21993. error
  21994. };
  21995. }
  21996. function getMediaDecodingInfoPromise(level, audioTracksByGroup, mediaCapabilities, cache = {}) {
  21997. const videoCodecs = level.videoCodec;
  21998. if (!videoCodecs && !level.audioCodec || !mediaCapabilities) {
  21999. return Promise.resolve(SUPPORTED_INFO_DEFAULT);
  22000. }
  22001. const configurations = [];
  22002. const videoDecodeList = makeVideoConfigurations(level);
  22003. const videoCount = videoDecodeList.length;
  22004. const audioDecodeList = makeAudioConfigurations(level, audioTracksByGroup, videoCount > 0);
  22005. const audioCount = audioDecodeList.length;
  22006. for (let i = videoCount || 1 * audioCount || 1; i--;) {
  22007. const configuration = {
  22008. type: 'media-source'
  22009. };
  22010. if (videoCount) {
  22011. configuration.video = videoDecodeList[i % videoCount];
  22012. }
  22013. if (audioCount) {
  22014. configuration.audio = audioDecodeList[i % audioCount];
  22015. const audioBitrate = configuration.audio.bitrate;
  22016. if (configuration.video && audioBitrate) {
  22017. configuration.video.bitrate -= audioBitrate;
  22018. }
  22019. }
  22020. configurations.push(configuration);
  22021. }
  22022. if (videoCodecs) {
  22023. // Override Windows Firefox HEVC MediaCapabilities result (https://github.com/video-dev/hls.js/issues/7046)
  22024. const ua = navigator.userAgent;
  22025. if (videoCodecs.split(',').some(videoCodec => isHEVC(videoCodec)) && userAgentHevcSupportIsInaccurate()) {
  22026. return Promise.resolve(getUnsupportedResult(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${ua})`), configurations));
  22027. }
  22028. }
  22029. return Promise.all(configurations.map(configuration => {
  22030. // Cache MediaCapabilities promises
  22031. const decodingInfoKey = getMediaDecodingInfoKey(configuration);
  22032. return cache[decodingInfoKey] || (cache[decodingInfoKey] = mediaCapabilities.decodingInfo(configuration));
  22033. })).then(decodingInfoResults => ({
  22034. supported: !decodingInfoResults.some(info => !info.supported),
  22035. configurations,
  22036. decodingInfoResults
  22037. })).catch(error => ({
  22038. supported: false,
  22039. configurations,
  22040. decodingInfoResults: [],
  22041. error
  22042. }));
  22043. }
  22044. function makeVideoConfigurations(level) {
  22045. var _level$videoCodec;
  22046. const videoCodecs = (_level$videoCodec = level.videoCodec) == null ? void 0 : _level$videoCodec.split(',');
  22047. const bitrate = getVariantDecodingBitrate(level);
  22048. const width = level.width || 640;
  22049. const height = level.height || 480;
  22050. // Assume a framerate of 30fps since MediaCapabilities will not accept Level default of 0.
  22051. const framerate = level.frameRate || 30;
  22052. const videoRange = level.videoRange.toLowerCase();
  22053. return videoCodecs ? videoCodecs.map(videoCodec => {
  22054. const videoConfiguration = {
  22055. contentType: mimeTypeForCodec(fillInMissingAV01Params(videoCodec), 'video'),
  22056. width,
  22057. height,
  22058. bitrate,
  22059. framerate
  22060. };
  22061. if (videoRange !== 'sdr') {
  22062. videoConfiguration.transferFunction = videoRange;
  22063. }
  22064. return videoConfiguration;
  22065. }) : [];
  22066. }
  22067. function makeAudioConfigurations(level, audioTracksByGroup, hasVideo) {
  22068. var _level$audioCodec;
  22069. const audioCodecs = (_level$audioCodec = level.audioCodec) == null ? void 0 : _level$audioCodec.split(',');
  22070. const combinedBitrate = getVariantDecodingBitrate(level);
  22071. if (audioCodecs && level.audioGroups) {
  22072. return level.audioGroups.reduce((configurations, audioGroupId) => {
  22073. var _audioTracksByGroup$g;
  22074. const tracks = audioGroupId ? (_audioTracksByGroup$g = audioTracksByGroup.groups[audioGroupId]) == null ? void 0 : _audioTracksByGroup$g.tracks : null;
  22075. if (tracks) {
  22076. return tracks.reduce((configs, audioTrack) => {
  22077. if (audioTrack.groupId === audioGroupId) {
  22078. const channelsNumber = parseFloat(audioTrack.channels || '');
  22079. audioCodecs.forEach(audioCodec => {
  22080. const audioConfiguration = {
  22081. contentType: mimeTypeForCodec(audioCodec, 'audio'),
  22082. bitrate: hasVideo ? estimatedAudioBitrate(audioCodec, combinedBitrate) : combinedBitrate
  22083. };
  22084. if (channelsNumber) {
  22085. audioConfiguration.channels = '' + channelsNumber;
  22086. }
  22087. configs.push(audioConfiguration);
  22088. });
  22089. }
  22090. return configs;
  22091. }, configurations);
  22092. }
  22093. return configurations;
  22094. }, []);
  22095. }
  22096. return [];
  22097. }
  22098. function estimatedAudioBitrate(audioCodec, levelBitrate) {
  22099. if (levelBitrate <= 1) {
  22100. return 1;
  22101. }
  22102. let audioBitrate = 128000;
  22103. if (audioCodec === 'ec-3') {
  22104. audioBitrate = 768000;
  22105. } else if (audioCodec === 'ac-3') {
  22106. audioBitrate = 640000;
  22107. }
  22108. return Math.min(levelBitrate / 2, audioBitrate); // Don't exceed some % of level bitrate
  22109. }
  22110. function getVariantDecodingBitrate(level) {
  22111. return Math.ceil(Math.max(level.bitrate * 0.9, level.averageBitrate) / 1000) * 1000 || 1;
  22112. }
  22113. function getMediaDecodingInfoKey(config) {
  22114. let key = '';
  22115. const {
  22116. audio,
  22117. video
  22118. } = config;
  22119. if (video) {
  22120. const codec = getCodecsForMimeType(video.contentType);
  22121. key += `${codec}_r${video.height}x${video.width}f${Math.ceil(video.framerate)}${video.transferFunction || 'sd'}_${Math.ceil(video.bitrate / 1e5)}`;
  22122. }
  22123. if (audio) {
  22124. const codec = getCodecsForMimeType(audio.contentType);
  22125. key += `${video ? '_' : ''}${codec}_c${audio.channels}`;
  22126. }
  22127. return key;
  22128. }
  22129. /**
  22130. * The `Hls` class is the core of the HLS.js library used to instantiate player instances.
  22131. * @public
  22132. */
  22133. class Hls {
  22134. /**
  22135. * Get the video-dev/hls.js package version.
  22136. */
  22137. static get version() {
  22138. return version;
  22139. }
  22140. /**
  22141. * Check if the required MediaSource Extensions are available.
  22142. */
  22143. static isMSESupported() {
  22144. return isMSESupported();
  22145. }
  22146. /**
  22147. * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.
  22148. */
  22149. static isSupported() {
  22150. return isSupported();
  22151. }
  22152. /**
  22153. * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).
  22154. */
  22155. static getMediaSource() {
  22156. return getMediaSource();
  22157. }
  22158. static get Events() {
  22159. return Events;
  22160. }
  22161. static get MetadataSchema() {
  22162. return MetadataSchema;
  22163. }
  22164. static get ErrorTypes() {
  22165. return ErrorTypes;
  22166. }
  22167. static get ErrorDetails() {
  22168. return ErrorDetails;
  22169. }
  22170. /**
  22171. * Get the default configuration applied to new instances.
  22172. */
  22173. static get DefaultConfig() {
  22174. if (!Hls.defaultConfig) {
  22175. return hlsDefaultConfig;
  22176. }
  22177. return Hls.defaultConfig;
  22178. }
  22179. /**
  22180. * Replace the default configuration applied to new instances.
  22181. */
  22182. static set DefaultConfig(defaultConfig) {
  22183. Hls.defaultConfig = defaultConfig;
  22184. }
  22185. /**
  22186. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  22187. * @param userConfig - Configuration options applied over `Hls.DefaultConfig`
  22188. */
  22189. constructor(userConfig = {}) {
  22190. /**
  22191. * The runtime configuration used by the player. At instantiation this is combination of `hls.userConfig` merged over `Hls.DefaultConfig`.
  22192. */
  22193. this.config = void 0;
  22194. /**
  22195. * The configuration object provided on player instantiation.
  22196. */
  22197. this.userConfig = void 0;
  22198. /**
  22199. * The logger functions used by this player instance, configured on player instantiation.
  22200. */
  22201. this.logger = void 0;
  22202. this.coreComponents = void 0;
  22203. this.networkControllers = void 0;
  22204. this._emitter = new EventEmitter();
  22205. this._autoLevelCapping = -1;
  22206. this._maxHdcpLevel = null;
  22207. this.abrController = void 0;
  22208. this.bufferController = void 0;
  22209. this.capLevelController = void 0;
  22210. this.latencyController = void 0;
  22211. this.levelController = void 0;
  22212. this.streamController = void 0;
  22213. this.audioStreamController = void 0;
  22214. this.subtititleStreamController = void 0;
  22215. this.audioTrackController = void 0;
  22216. this.subtitleTrackController = void 0;
  22217. this.interstitialsController = void 0;
  22218. this.gapController = void 0;
  22219. this.emeController = void 0;
  22220. this.cmcdController = void 0;
  22221. this._media = null;
  22222. this._url = null;
  22223. this._sessionId = void 0;
  22224. this.triggeringException = void 0;
  22225. this.started = false;
  22226. const logger = this.logger = enableLogs(userConfig.debug || false, 'Hls instance', userConfig.assetPlayerId);
  22227. const config = this.config = mergeConfig(Hls.DefaultConfig, userConfig, logger);
  22228. this.userConfig = userConfig;
  22229. if (config.progressive) {
  22230. enableStreamingMode(config, logger);
  22231. }
  22232. // core controllers and network loaders
  22233. const {
  22234. abrController: _AbrController,
  22235. bufferController: _BufferController,
  22236. capLevelController: _CapLevelController,
  22237. errorController: _ErrorController,
  22238. fpsController: _FpsController
  22239. } = config;
  22240. const errorController = new _ErrorController(this);
  22241. const abrController = this.abrController = new _AbrController(this);
  22242. // FragmentTracker must be defined before StreamController because the order of event handling is important
  22243. const fragmentTracker = new FragmentTracker(this);
  22244. const _InterstitialsController = config.interstitialsController;
  22245. const interstitialsController = _InterstitialsController ? this.interstitialsController = new _InterstitialsController(this, Hls) : null;
  22246. const bufferController = this.bufferController = new _BufferController(this, fragmentTracker);
  22247. const capLevelController = this.capLevelController = new _CapLevelController(this);
  22248. const fpsController = new _FpsController(this);
  22249. const playListLoader = new PlaylistLoader(this);
  22250. const _ContentSteeringController = config.contentSteeringController;
  22251. // Instantiate ConentSteeringController before LevelController to receive Multivariant Playlist events first
  22252. const contentSteering = _ContentSteeringController ? new _ContentSteeringController(this) : null;
  22253. const levelController = this.levelController = new LevelController(this, contentSteering);
  22254. const id3TrackController = new ID3TrackController(this);
  22255. const keyLoader = new KeyLoader(this.config);
  22256. const streamController = this.streamController = new StreamController(this, fragmentTracker, keyLoader);
  22257. const gapController = this.gapController = new GapController(this, fragmentTracker);
  22258. // Cap level controller uses streamController to flush the buffer
  22259. capLevelController.setStreamController(streamController);
  22260. // fpsController uses streamController to switch when frames are being dropped
  22261. fpsController.setStreamController(streamController);
  22262. const networkControllers = [playListLoader, levelController, streamController];
  22263. if (interstitialsController) {
  22264. networkControllers.splice(1, 0, interstitialsController);
  22265. }
  22266. if (contentSteering) {
  22267. networkControllers.splice(1, 0, contentSteering);
  22268. }
  22269. this.networkControllers = networkControllers;
  22270. const coreComponents = [abrController, bufferController, gapController, capLevelController, fpsController, id3TrackController, fragmentTracker];
  22271. this.audioTrackController = this.createController(config.audioTrackController, networkControllers);
  22272. const AudioStreamControllerClass = config.audioStreamController;
  22273. if (AudioStreamControllerClass) {
  22274. networkControllers.push(this.audioStreamController = new AudioStreamControllerClass(this, fragmentTracker, keyLoader));
  22275. }
  22276. // Instantiate subtitleTrackController before SubtitleStreamController to receive level events first
  22277. this.subtitleTrackController = this.createController(config.subtitleTrackController, networkControllers);
  22278. const SubtitleStreamControllerClass = config.subtitleStreamController;
  22279. if (SubtitleStreamControllerClass) {
  22280. networkControllers.push(this.subtititleStreamController = new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader));
  22281. }
  22282. this.createController(config.timelineController, coreComponents);
  22283. keyLoader.emeController = this.emeController = this.createController(config.emeController, coreComponents);
  22284. this.cmcdController = this.createController(config.cmcdController, coreComponents);
  22285. this.latencyController = this.createController(LatencyController, coreComponents);
  22286. this.coreComponents = coreComponents;
  22287. // Error controller handles errors before and after all other controllers
  22288. // This listener will be invoked after all other controllers error listeners
  22289. networkControllers.push(errorController);
  22290. const onErrorOut = errorController.onErrorOut;
  22291. if (typeof onErrorOut === 'function') {
  22292. this.on(Events.ERROR, onErrorOut, errorController);
  22293. }
  22294. // Autostart load handler
  22295. this.on(Events.MANIFEST_LOADED, playListLoader.onManifestLoaded, playListLoader);
  22296. }
  22297. createController(ControllerClass, components) {
  22298. if (ControllerClass) {
  22299. const controllerInstance = new ControllerClass(this);
  22300. if (components) {
  22301. components.push(controllerInstance);
  22302. }
  22303. return controllerInstance;
  22304. }
  22305. return null;
  22306. }
  22307. // Delegate the EventEmitter through the public API of Hls.js
  22308. on(event, listener, context = this) {
  22309. this._emitter.on(event, listener, context);
  22310. }
  22311. once(event, listener, context = this) {
  22312. this._emitter.once(event, listener, context);
  22313. }
  22314. removeAllListeners(event) {
  22315. this._emitter.removeAllListeners(event);
  22316. }
  22317. off(event, listener, context = this, once) {
  22318. this._emitter.off(event, listener, context, once);
  22319. }
  22320. listeners(event) {
  22321. return this._emitter.listeners(event);
  22322. }
  22323. emit(event, name, eventObject) {
  22324. return this._emitter.emit(event, name, eventObject);
  22325. }
  22326. trigger(event, eventObject) {
  22327. if (this.config.debug) {
  22328. return this.emit(event, event, eventObject);
  22329. } else {
  22330. try {
  22331. return this.emit(event, event, eventObject);
  22332. } catch (error) {
  22333. this.logger.error('An internal error happened while handling event ' + event + '. Error message: "' + error.message + '". Here is a stacktrace:', error);
  22334. // Prevent recursion in error event handlers that throw #5497
  22335. if (!this.triggeringException) {
  22336. this.triggeringException = true;
  22337. const fatal = event === Events.ERROR;
  22338. this.trigger(Events.ERROR, {
  22339. type: ErrorTypes.OTHER_ERROR,
  22340. details: ErrorDetails.INTERNAL_EXCEPTION,
  22341. fatal,
  22342. event,
  22343. error
  22344. });
  22345. this.triggeringException = false;
  22346. }
  22347. }
  22348. }
  22349. return false;
  22350. }
  22351. listenerCount(event) {
  22352. return this._emitter.listenerCount(event);
  22353. }
  22354. /**
  22355. * Dispose of the instance
  22356. */
  22357. destroy() {
  22358. this.logger.log('destroy');
  22359. this.trigger(Events.DESTROYING, undefined);
  22360. this.detachMedia();
  22361. this.removeAllListeners();
  22362. this._autoLevelCapping = -1;
  22363. this._url = null;
  22364. this.networkControllers.forEach(component => component.destroy());
  22365. this.networkControllers.length = 0;
  22366. this.coreComponents.forEach(component => component.destroy());
  22367. this.coreComponents.length = 0;
  22368. // Remove any references that could be held in config options or callbacks
  22369. const config = this.config;
  22370. config.xhrSetup = config.fetchSetup = undefined;
  22371. // @ts-ignore
  22372. this.userConfig = null;
  22373. }
  22374. /**
  22375. * Attaches Hls.js to a media element
  22376. */
  22377. attachMedia(data) {
  22378. if (!data || 'media' in data && !data.media) {
  22379. const error = new Error(`attachMedia failed: invalid argument (${data})`);
  22380. this.trigger(Events.ERROR, {
  22381. type: ErrorTypes.OTHER_ERROR,
  22382. details: ErrorDetails.ATTACH_MEDIA_ERROR,
  22383. fatal: true,
  22384. error
  22385. });
  22386. return;
  22387. }
  22388. this.logger.log(`attachMedia`);
  22389. if (this._media) {
  22390. this.logger.warn(`media must be detached before attaching`);
  22391. this.detachMedia();
  22392. }
  22393. const attachMediaSource = 'media' in data;
  22394. const media = attachMediaSource ? data.media : data;
  22395. const attachingData = attachMediaSource ? data : {
  22396. media
  22397. };
  22398. this._media = media;
  22399. this.trigger(Events.MEDIA_ATTACHING, attachingData);
  22400. }
  22401. /**
  22402. * Detach Hls.js from the media
  22403. */
  22404. detachMedia() {
  22405. this.logger.log('detachMedia');
  22406. this.trigger(Events.MEDIA_DETACHING, {});
  22407. this._media = null;
  22408. }
  22409. /**
  22410. * Detach HTMLMediaElement, MediaSource, and SourceBuffers without reset, for attaching to another instance
  22411. */
  22412. transferMedia() {
  22413. this._media = null;
  22414. const transferMedia = this.bufferController.transferMedia();
  22415. this.trigger(Events.MEDIA_DETACHING, {
  22416. transferMedia
  22417. });
  22418. return transferMedia;
  22419. }
  22420. /**
  22421. * Set the source URL. Can be relative or absolute.
  22422. */
  22423. loadSource(url) {
  22424. this.stopLoad();
  22425. const media = this.media;
  22426. const loadedSource = this._url;
  22427. const loadingSource = this._url = urlToolkitExports.buildAbsoluteURL(self.location.href, url, {
  22428. alwaysNormalize: true
  22429. });
  22430. this._autoLevelCapping = -1;
  22431. this._maxHdcpLevel = null;
  22432. this.logger.log(`loadSource:${loadingSource}`);
  22433. if (media && loadedSource && (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())) {
  22434. // Remove and re-create MediaSource
  22435. this.detachMedia();
  22436. this.attachMedia(media);
  22437. }
  22438. // when attaching to a source URL, trigger a playlist load
  22439. this.trigger(Events.MANIFEST_LOADING, {
  22440. url: url
  22441. });
  22442. }
  22443. /**
  22444. * Gets the currently loaded URL
  22445. */
  22446. get url() {
  22447. return this._url;
  22448. }
  22449. /**
  22450. * Whether or not enough has been buffered to seek to start position or use `media.currentTime` to determine next load position
  22451. */
  22452. get hasEnoughToStart() {
  22453. return this.streamController.hasEnoughToStart;
  22454. }
  22455. /**
  22456. * Get the startPosition set on startLoad(position) or on autostart with config.startPosition
  22457. */
  22458. get startPosition() {
  22459. return this.streamController.startPositionValue;
  22460. }
  22461. /**
  22462. * Start loading data from the stream source.
  22463. * Depending on default config, client starts loading automatically when a source is set.
  22464. *
  22465. * @param startPosition - Set the start position to stream from.
  22466. * Defaults to -1 (None: starts from earliest point)
  22467. */
  22468. startLoad(startPosition = -1, skipSeekToStartPosition) {
  22469. this.logger.log(`startLoad(${startPosition + (skipSeekToStartPosition ? ', <skip seek to start>' : '')})`);
  22470. this.started = true;
  22471. this.resumeBuffering();
  22472. for (let i = 0; i < this.networkControllers.length; i++) {
  22473. this.networkControllers[i].startLoad(startPosition, skipSeekToStartPosition);
  22474. if (!this.started || !this.networkControllers) {
  22475. break;
  22476. }
  22477. }
  22478. }
  22479. /**
  22480. * Stop loading of any stream data.
  22481. */
  22482. stopLoad() {
  22483. this.logger.log('stopLoad');
  22484. this.started = false;
  22485. for (let i = 0; i < this.networkControllers.length; i++) {
  22486. this.networkControllers[i].stopLoad();
  22487. if (this.started || !this.networkControllers) {
  22488. break;
  22489. }
  22490. }
  22491. }
  22492. /**
  22493. * Returns whether loading, toggled with `startLoad()` and `stopLoad()`, is active or not`.
  22494. */
  22495. get loadingEnabled() {
  22496. return this.started;
  22497. }
  22498. /**
  22499. * Returns state of fragment loading toggled by calling `pauseBuffering()` and `resumeBuffering()`.
  22500. */
  22501. get bufferingEnabled() {
  22502. return this.streamController.bufferingEnabled;
  22503. }
  22504. /**
  22505. * Resumes stream controller segment loading after `pauseBuffering` has been called.
  22506. */
  22507. resumeBuffering() {
  22508. if (!this.bufferingEnabled) {
  22509. this.logger.log(`resume buffering`);
  22510. this.networkControllers.forEach(controller => {
  22511. if (controller.resumeBuffering) {
  22512. controller.resumeBuffering();
  22513. }
  22514. });
  22515. }
  22516. }
  22517. /**
  22518. * Prevents stream controller from loading new segments until `resumeBuffering` is called.
  22519. * This allows for media buffering to be paused without interupting playlist loading.
  22520. */
  22521. pauseBuffering() {
  22522. if (this.bufferingEnabled) {
  22523. this.logger.log(`pause buffering`);
  22524. this.networkControllers.forEach(controller => {
  22525. if (controller.pauseBuffering) {
  22526. controller.pauseBuffering();
  22527. }
  22528. });
  22529. }
  22530. }
  22531. get inFlightFragments() {
  22532. const inFlightData = {
  22533. [PlaylistLevelType.MAIN]: this.streamController.inFlightFrag
  22534. };
  22535. if (this.audioStreamController) {
  22536. inFlightData[PlaylistLevelType.AUDIO] = this.audioStreamController.inFlightFrag;
  22537. }
  22538. if (this.subtititleStreamController) {
  22539. inFlightData[PlaylistLevelType.SUBTITLE] = this.subtititleStreamController.inFlightFrag;
  22540. }
  22541. return inFlightData;
  22542. }
  22543. /**
  22544. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  22545. */
  22546. swapAudioCodec() {
  22547. this.logger.log('swapAudioCodec');
  22548. this.streamController.swapAudioCodec();
  22549. }
  22550. /**
  22551. * When the media-element fails, this allows to detach and then re-attach it
  22552. * as one call (convenience method).
  22553. *
  22554. * Automatic recovery of media-errors by this process is configurable.
  22555. */
  22556. recoverMediaError() {
  22557. this.logger.log('recoverMediaError');
  22558. const media = this._media;
  22559. const time = media == null ? void 0 : media.currentTime;
  22560. this.detachMedia();
  22561. if (media) {
  22562. this.attachMedia(media);
  22563. if (time) {
  22564. this.startLoad(time);
  22565. }
  22566. }
  22567. }
  22568. removeLevel(levelIndex) {
  22569. this.levelController.removeLevel(levelIndex);
  22570. }
  22571. /**
  22572. * @returns a UUID for this player instance
  22573. */
  22574. get sessionId() {
  22575. let _sessionId = this._sessionId;
  22576. if (!_sessionId) {
  22577. _sessionId = this._sessionId = uuid();
  22578. }
  22579. return _sessionId;
  22580. }
  22581. /**
  22582. * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH
  22583. */
  22584. get levels() {
  22585. const levels = this.levelController.levels;
  22586. return levels ? levels : [];
  22587. }
  22588. /**
  22589. * @returns LevelDetails of last loaded level (variant) or `null` prior to loading a media playlist.
  22590. */
  22591. get latestLevelDetails() {
  22592. return this.streamController.getLevelDetails() || null;
  22593. }
  22594. /**
  22595. * @returns Level object of selected level (variant) or `null` prior to selecting a level or once the level is removed.
  22596. */
  22597. get loadLevelObj() {
  22598. return this.levelController.loadLevelObj;
  22599. }
  22600. /**
  22601. * Index of quality level (variant) currently played
  22602. */
  22603. get currentLevel() {
  22604. return this.streamController.currentLevel;
  22605. }
  22606. /**
  22607. * 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.
  22608. */
  22609. set currentLevel(newLevel) {
  22610. this.logger.log(`set currentLevel:${newLevel}`);
  22611. this.levelController.manualLevel = newLevel;
  22612. this.streamController.immediateLevelSwitch();
  22613. }
  22614. /**
  22615. * Index of next quality level loaded as scheduled by stream controller.
  22616. */
  22617. get nextLevel() {
  22618. return this.streamController.nextLevel;
  22619. }
  22620. /**
  22621. * Set quality level index for next loaded data.
  22622. * This will switch the video quality asap, without interrupting playback.
  22623. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  22624. * @param newLevel - Pass -1 for automatic level selection
  22625. */
  22626. set nextLevel(newLevel) {
  22627. this.logger.log(`set nextLevel:${newLevel}`);
  22628. this.levelController.manualLevel = newLevel;
  22629. this.streamController.nextLevelSwitch();
  22630. }
  22631. /**
  22632. * Return the quality level of the currently or last (of none is loaded currently) segment
  22633. */
  22634. get loadLevel() {
  22635. return this.levelController.level;
  22636. }
  22637. /**
  22638. * Set quality level index for next loaded data in a conservative way.
  22639. * This will switch the quality without flushing, but interrupt current loading.
  22640. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  22641. * @param newLevel - Pass -1 for automatic level selection
  22642. */
  22643. set loadLevel(newLevel) {
  22644. this.logger.log(`set loadLevel:${newLevel}`);
  22645. this.levelController.manualLevel = newLevel;
  22646. }
  22647. /**
  22648. * get next quality level loaded
  22649. */
  22650. get nextLoadLevel() {
  22651. return this.levelController.nextLoadLevel;
  22652. }
  22653. /**
  22654. * Set quality level of next loaded segment in a fully "non-destructive" way.
  22655. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  22656. */
  22657. set nextLoadLevel(level) {
  22658. this.levelController.nextLoadLevel = level;
  22659. }
  22660. /**
  22661. * Return "first level": like a default level, if not set,
  22662. * falls back to index of first level referenced in manifest
  22663. */
  22664. get firstLevel() {
  22665. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  22666. }
  22667. /**
  22668. * Sets "first-level", see getter.
  22669. */
  22670. set firstLevel(newLevel) {
  22671. this.logger.log(`set firstLevel:${newLevel}`);
  22672. this.levelController.firstLevel = newLevel;
  22673. }
  22674. /**
  22675. * Return the desired start level for the first fragment that will be loaded.
  22676. * The default value of -1 indicates automatic start level selection.
  22677. * Setting hls.nextAutoLevel without setting a startLevel will result in
  22678. * the nextAutoLevel value being used for one fragment load.
  22679. */
  22680. get startLevel() {
  22681. const startLevel = this.levelController.startLevel;
  22682. if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {
  22683. return this.abrController.forcedAutoLevel;
  22684. }
  22685. return startLevel;
  22686. }
  22687. /**
  22688. * set start level (level of first fragment that will be played back)
  22689. * if not overrided by user, first level appearing in manifest will be used as start level
  22690. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  22691. * (determined from download of first segment)
  22692. */
  22693. set startLevel(newLevel) {
  22694. this.logger.log(`set startLevel:${newLevel}`);
  22695. // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
  22696. if (newLevel !== -1) {
  22697. newLevel = Math.max(newLevel, this.minAutoLevel);
  22698. }
  22699. this.levelController.startLevel = newLevel;
  22700. }
  22701. /**
  22702. * Whether level capping is enabled.
  22703. * Default value is set via `config.capLevelToPlayerSize`.
  22704. */
  22705. get capLevelToPlayerSize() {
  22706. return this.config.capLevelToPlayerSize;
  22707. }
  22708. /**
  22709. * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.
  22710. */
  22711. set capLevelToPlayerSize(shouldStartCapping) {
  22712. const newCapLevelToPlayerSize = !!shouldStartCapping;
  22713. if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
  22714. if (newCapLevelToPlayerSize) {
  22715. this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
  22716. } else {
  22717. this.capLevelController.stopCapping();
  22718. this.autoLevelCapping = -1;
  22719. this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
  22720. }
  22721. this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
  22722. }
  22723. }
  22724. /**
  22725. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  22726. */
  22727. get autoLevelCapping() {
  22728. return this._autoLevelCapping;
  22729. }
  22730. /**
  22731. * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.
  22732. */
  22733. get bandwidthEstimate() {
  22734. const {
  22735. bwEstimator
  22736. } = this.abrController;
  22737. if (!bwEstimator) {
  22738. return NaN;
  22739. }
  22740. return bwEstimator.getEstimate();
  22741. }
  22742. set bandwidthEstimate(abrEwmaDefaultEstimate) {
  22743. this.abrController.resetEstimator(abrEwmaDefaultEstimate);
  22744. }
  22745. get abrEwmaDefaultEstimate() {
  22746. const {
  22747. bwEstimator
  22748. } = this.abrController;
  22749. if (!bwEstimator) {
  22750. return NaN;
  22751. }
  22752. return bwEstimator.defaultEstimate;
  22753. }
  22754. /**
  22755. * get time to first byte estimate
  22756. * @type {number}
  22757. */
  22758. get ttfbEstimate() {
  22759. const {
  22760. bwEstimator
  22761. } = this.abrController;
  22762. if (!bwEstimator) {
  22763. return NaN;
  22764. }
  22765. return bwEstimator.getEstimateTTFB();
  22766. }
  22767. /**
  22768. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  22769. */
  22770. set autoLevelCapping(newLevel) {
  22771. if (this._autoLevelCapping !== newLevel) {
  22772. this.logger.log(`set autoLevelCapping:${newLevel}`);
  22773. this._autoLevelCapping = newLevel;
  22774. this.levelController.checkMaxAutoUpdated();
  22775. }
  22776. }
  22777. get maxHdcpLevel() {
  22778. return this._maxHdcpLevel;
  22779. }
  22780. set maxHdcpLevel(value) {
  22781. if (isHdcpLevel(value) && this._maxHdcpLevel !== value) {
  22782. this._maxHdcpLevel = value;
  22783. this.levelController.checkMaxAutoUpdated();
  22784. }
  22785. }
  22786. /**
  22787. * True when automatic level selection enabled
  22788. */
  22789. get autoLevelEnabled() {
  22790. return this.levelController.manualLevel === -1;
  22791. }
  22792. /**
  22793. * Level set manually (if any)
  22794. */
  22795. get manualLevel() {
  22796. return this.levelController.manualLevel;
  22797. }
  22798. /**
  22799. * min level selectable in auto mode according to config.minAutoBitrate
  22800. */
  22801. get minAutoLevel() {
  22802. const {
  22803. levels,
  22804. config: {
  22805. minAutoBitrate
  22806. }
  22807. } = this;
  22808. if (!levels) return 0;
  22809. const len = levels.length;
  22810. for (let i = 0; i < len; i++) {
  22811. if (levels[i].maxBitrate >= minAutoBitrate) {
  22812. return i;
  22813. }
  22814. }
  22815. return 0;
  22816. }
  22817. /**
  22818. * max level selectable in auto mode according to autoLevelCapping
  22819. */
  22820. get maxAutoLevel() {
  22821. const {
  22822. levels,
  22823. autoLevelCapping,
  22824. maxHdcpLevel
  22825. } = this;
  22826. let maxAutoLevel;
  22827. if (autoLevelCapping === -1 && levels != null && levels.length) {
  22828. maxAutoLevel = levels.length - 1;
  22829. } else {
  22830. maxAutoLevel = autoLevelCapping;
  22831. }
  22832. if (maxHdcpLevel) {
  22833. for (let i = maxAutoLevel; i--;) {
  22834. const hdcpLevel = levels[i].attrs['HDCP-LEVEL'];
  22835. if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {
  22836. return i;
  22837. }
  22838. }
  22839. }
  22840. return maxAutoLevel;
  22841. }
  22842. get firstAutoLevel() {
  22843. return this.abrController.firstAutoLevel;
  22844. }
  22845. /**
  22846. * next automatically selected quality level
  22847. */
  22848. get nextAutoLevel() {
  22849. return this.abrController.nextAutoLevel;
  22850. }
  22851. /**
  22852. * this setter is used to force next auto level.
  22853. * this is useful to force a switch down in auto mode:
  22854. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  22855. * forced value is valid for one fragment. upon successful frag loading at forced level,
  22856. * this value will be resetted to -1 by ABR controller.
  22857. */
  22858. set nextAutoLevel(nextLevel) {
  22859. this.abrController.nextAutoLevel = nextLevel;
  22860. }
  22861. /**
  22862. * get the datetime value relative to media.currentTime for the active level Program Date Time if present
  22863. */
  22864. get playingDate() {
  22865. return this.streamController.currentProgramDateTime;
  22866. }
  22867. get mainForwardBufferInfo() {
  22868. return this.streamController.getMainFwdBufferInfo();
  22869. }
  22870. get maxBufferLength() {
  22871. return this.streamController.maxBufferLength;
  22872. }
  22873. /**
  22874. * Find and select the best matching audio track, making a level switch when a Group change is necessary.
  22875. * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found.
  22876. */
  22877. setAudioOption(audioOption) {
  22878. var _this$audioTrackContr;
  22879. return ((_this$audioTrackContr = this.audioTrackController) == null ? void 0 : _this$audioTrackContr.setAudioOption(audioOption)) || null;
  22880. }
  22881. /**
  22882. * Find and select the best matching subtitle track, making a level switch when a Group change is necessary.
  22883. * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found.
  22884. */
  22885. setSubtitleOption(subtitleOption) {
  22886. var _this$subtitleTrackCo;
  22887. return ((_this$subtitleTrackCo = this.subtitleTrackController) == null ? void 0 : _this$subtitleTrackCo.setSubtitleOption(subtitleOption)) || null;
  22888. }
  22889. /**
  22890. * Get the complete list of audio tracks across all media groups
  22891. */
  22892. get allAudioTracks() {
  22893. const audioTrackController = this.audioTrackController;
  22894. return audioTrackController ? audioTrackController.allAudioTracks : [];
  22895. }
  22896. /**
  22897. * Get the list of selectable audio tracks
  22898. */
  22899. get audioTracks() {
  22900. const audioTrackController = this.audioTrackController;
  22901. return audioTrackController ? audioTrackController.audioTracks : [];
  22902. }
  22903. /**
  22904. * index of the selected audio track (index in audio track lists)
  22905. */
  22906. get audioTrack() {
  22907. const audioTrackController = this.audioTrackController;
  22908. return audioTrackController ? audioTrackController.audioTrack : -1;
  22909. }
  22910. /**
  22911. * selects an audio track, based on its index in audio track lists
  22912. */
  22913. set audioTrack(audioTrackId) {
  22914. const audioTrackController = this.audioTrackController;
  22915. if (audioTrackController) {
  22916. audioTrackController.audioTrack = audioTrackId;
  22917. }
  22918. }
  22919. /**
  22920. * get the complete list of subtitle tracks across all media groups
  22921. */
  22922. get allSubtitleTracks() {
  22923. const subtitleTrackController = this.subtitleTrackController;
  22924. return subtitleTrackController ? subtitleTrackController.allSubtitleTracks : [];
  22925. }
  22926. /**
  22927. * get alternate subtitle tracks list from playlist
  22928. */
  22929. get subtitleTracks() {
  22930. const subtitleTrackController = this.subtitleTrackController;
  22931. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  22932. }
  22933. /**
  22934. * index of the selected subtitle track (index in subtitle track lists)
  22935. */
  22936. get subtitleTrack() {
  22937. const subtitleTrackController = this.subtitleTrackController;
  22938. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  22939. }
  22940. get media() {
  22941. return this._media;
  22942. }
  22943. /**
  22944. * select an subtitle track, based on its index in subtitle track lists
  22945. */
  22946. set subtitleTrack(subtitleTrackId) {
  22947. const subtitleTrackController = this.subtitleTrackController;
  22948. if (subtitleTrackController) {
  22949. subtitleTrackController.subtitleTrack = subtitleTrackId;
  22950. }
  22951. }
  22952. /**
  22953. * Whether subtitle display is enabled or not
  22954. */
  22955. get subtitleDisplay() {
  22956. const subtitleTrackController = this.subtitleTrackController;
  22957. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  22958. }
  22959. /**
  22960. * Enable/disable subtitle display rendering
  22961. */
  22962. set subtitleDisplay(value) {
  22963. const subtitleTrackController = this.subtitleTrackController;
  22964. if (subtitleTrackController) {
  22965. subtitleTrackController.subtitleDisplay = value;
  22966. }
  22967. }
  22968. /**
  22969. * get mode for Low-Latency HLS loading
  22970. */
  22971. get lowLatencyMode() {
  22972. return this.config.lowLatencyMode;
  22973. }
  22974. /**
  22975. * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
  22976. */
  22977. set lowLatencyMode(mode) {
  22978. this.config.lowLatencyMode = mode;
  22979. }
  22980. /**
  22981. * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
  22982. * @returns null prior to loading live Playlist
  22983. */
  22984. get liveSyncPosition() {
  22985. return this.latencyController.liveSyncPosition;
  22986. }
  22987. /**
  22988. * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
  22989. * @returns 0 before first playlist is loaded
  22990. */
  22991. get latency() {
  22992. return this.latencyController.latency;
  22993. }
  22994. /**
  22995. * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
  22996. * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
  22997. * @returns 0 before first playlist is loaded
  22998. */
  22999. get maxLatency() {
  23000. return this.latencyController.maxLatency;
  23001. }
  23002. /**
  23003. * target distance from the edge as calculated by the latency controller
  23004. */
  23005. get targetLatency() {
  23006. return this.latencyController.targetLatency;
  23007. }
  23008. set targetLatency(latency) {
  23009. this.latencyController.targetLatency = latency;
  23010. }
  23011. /**
  23012. * the rate at which the edge of the current live playlist is advancing or 1 if there is none
  23013. */
  23014. get drift() {
  23015. return this.latencyController.drift;
  23016. }
  23017. /**
  23018. * set to true when startLoad is called before MANIFEST_PARSED event
  23019. */
  23020. get forceStartLoad() {
  23021. return this.streamController.forceStartLoad;
  23022. }
  23023. /**
  23024. * ContentSteering pathways getter
  23025. */
  23026. get pathways() {
  23027. return this.levelController.pathways;
  23028. }
  23029. /**
  23030. * ContentSteering pathwayPriority getter/setter
  23031. */
  23032. get pathwayPriority() {
  23033. return this.levelController.pathwayPriority;
  23034. }
  23035. set pathwayPriority(pathwayPriority) {
  23036. this.levelController.pathwayPriority = pathwayPriority;
  23037. }
  23038. /**
  23039. * returns true when all SourceBuffers are buffered to the end
  23040. */
  23041. get bufferedToEnd() {
  23042. var _this$bufferControlle;
  23043. return !!((_this$bufferControlle = this.bufferController) != null && _this$bufferControlle.bufferedToEnd);
  23044. }
  23045. /**
  23046. * returns Interstitials Program Manager
  23047. */
  23048. get interstitialsManager() {
  23049. var _this$interstitialsCo;
  23050. return ((_this$interstitialsCo = this.interstitialsController) == null ? void 0 : _this$interstitialsCo.interstitialsManager) || null;
  23051. }
  23052. /**
  23053. * returns mediaCapabilities.decodingInfo for a variant/rendition
  23054. */
  23055. getMediaDecodingInfo(level, audioTracks = this.allAudioTracks) {
  23056. const audioTracksByGroup = getAudioTracksByGroup(audioTracks);
  23057. return getMediaDecodingInfoPromise(level, audioTracksByGroup, navigator.mediaCapabilities);
  23058. }
  23059. }
  23060. Hls.defaultConfig = void 0;
  23061. var KeySystemFormats = emptyEsExports.KeySystemFormats;
  23062. var KeySystems = emptyEsExports.KeySystems;
  23063. var SubtitleStreamController = emptyEsExports.SubtitleStreamController;
  23064. var TimelineController = emptyEsExports.TimelineController;
  23065. var requestMediaKeySystemAccess = emptyEsExports.requestMediaKeySystemAccess;
  23066. export { AbrController, AttrList, Cues as AudioStreamController, Cues as AudioTrackController, BasePlaylistController, BaseSegment, BaseStreamController, BufferController, Cues as CMCDController, CapLevelController, ChunkMetadata, ContentSteeringController, Cues, DateRange, Cues as EMEController, ErrorActionFlags, ErrorController, ErrorDetails, ErrorTypes, Events, FPSController, FetchLoader, Fragment, Hls, HlsSkip, HlsUrlParameters, KeySystemFormats, KeySystems, Level, LevelDetails, LevelKey, LoadStats, M3U8Parser, MetadataSchema, NetworkErrorAction, Part, PlaylistLevelType, SubtitleStreamController, Cues as SubtitleTrackController, TimelineController, XhrLoader, Hls as default, fetchSupported, getMediaSource, isMSESupported, isSupported, requestMediaKeySystemAccess };
  23067. //# sourceMappingURL=hls.light.mjs.map